bool Buffer::find(const QString& findText, int flags, bool forward,
                  bool wrap, bool *searchWrapped) {
    if (findText.isEmpty()) {
        return false;
    }
    if (searchWrapped) {
        *searchWrapped = false;
    }
    // Perform the search
    setSearchFlags(flags);
    setTargetStart(forward ? currentPos() : currentPos() - 1);
    setTargetEnd(forward ? length() : 0);
    QByteArray findArray = findText.toUtf8();
    int findPos = searchInTarget(findArray.length(), findArray);
    // If the search should wrap, perform the search again.
    if (findPos == -1 && wrap) {
        setTargetStart(forward ? 0 : length());
        setTargetEnd(forward ? currentPos() : currentPos() - 1);
        findPos = searchInTarget(findArray.length(), findArray);
        if (searchWrapped) {
            *searchWrapped = true;
        }
    }
    if (findPos != -1)  {
        setSel(targetStart(), targetEnd());
        scrollRange(targetStart(), targetEnd());
    }
    return findPos != -1;
}
Beispiel #2
0
	// tests if two edges cross
	bool Planarity::intersect(const edge e1, const edge e2) const
	{
		node v1s = e1->source();
		node v1t = e1->target();
		node v2s = e2->source();
		node v2t = e2->target();

		bool cross = false;
		if(v1s != v2s && v1s != v2t && v1t != v2s && v1t != v2t)
			cross = lowLevelIntersect(currentPos(v1s),currentPos(v1t),
									  currentPos(v2s),currentPos(v2t));
		return cross;
	}
Beispiel #3
0
void KWFrameGeometry::updateShape()
{
    if (m_blockSignals) return;
    KWFrame *frame = m_frame;
    if (frame == 0) {
        frame = m_state->frame();
        m_state->markFrameUsed();
    }
    Q_ASSERT(frame);
    frame->shape()->update();
    KShape *shape = frame->shape();
    QPointF currentPos(shape->absolutePosition(widget.positionSelector->position()));
    QPointF pos(widget.xPos->value(), widget.yPos->value() + m_topOfPage);
    QPointF moved = pos - currentPos;
    QPointF prev(moved);
    m_state->document()->clipToDocument(frame->shape(), moved);
    pos = currentPos + moved;

    frame->shape()->setAbsolutePosition(pos, widget.positionSelector->position());
    QSizeF size(widget.width->value(), widget.height->value());
    frame->shape()->setSize(size);

    KWTextFrame *tfs = dynamic_cast <KWTextFrame*>(frame);
    if (tfs) {
        KInsets insets(widget.topMargin->value(), widget.leftMargin->value(),
                widget.bottomMargin->value(), widget.rightMargin->value());
        tfs->setInsets(insets);
    }

    frame->shape()->update();
}
bool LocalPlanner::local_planner_one_robot(const Point_2& start, const Point_2& target, const Polygon_set_2& obstacles, double eps)
{
	double x1 = CGAL::to_double(start.x());
	double y1 = CGAL::to_double(start.y());
	double x2 = CGAL::to_double(target.x());
	double y2 = CGAL::to_double(target.y()) ;

	double distance = sqrt(pow(x1 - x2, 2) + pow(y1 - y2,2));

	double step_size = eps;

	// calculate how many steps are required
	int step_num = floor((distance - step_size) / step_size);
	double vx = x2 - x1;
	double vy = y2 - y1;

	for (int i = 1; i <= step_num; ++i)
	{
		// generate a configuration for every step
		double offset =  (i * step_size) / (distance - step_size);
		double currx = x1 + vx * offset;
		double curry = y1 + vy * offset;

		Point_2 currentPos(currx, curry);



		// If an intermidiate configuration is invalid, return false
		//if (!m_cd.one_robot_valid_conf(currentPos,obstacles)) return false;
	}

	// GREAT SUCCESS!
	return true;
}
Beispiel #5
0
void RippleSimulation::update(float dt)
{
    for (std::vector<Emitter>::iterator it=mEmitters.begin(); it !=mEmitters.end(); ++it)
    {
        if (it->mPtr == MWBase::Environment::get().getWorld ()->getPlayerPtr())
        {
            // fetch a new ptr (to handle cell change etc)
            // for non-player actors this is done in updateObjectCell
            it->mPtr = MWBase::Environment::get().getWorld ()->getPlayerPtr();
        }

        osg::Vec3f currentPos (it->mPtr.getRefData().getPosition().asVec3());

        if ( (currentPos - it->mLastEmitPosition).length() > 10
             // Only emit when close to the water surface, not above it and not too deep in the water
            && MWBase::Environment::get().getWorld ()->isUnderwater (it->mPtr.getCell(), it->mPtr.getRefData().getPosition().asVec3())
             && !MWBase::Environment::get().getWorld()->isSubmerged(it->mPtr))
        {
            it->mLastEmitPosition = currentPos;

            currentPos.z() = mParticleNode->getPosition().z();

            if (mParticleSystem->numParticles()-mParticleSystem->numDeadParticles() > 500)
                continue; // TODO: remove the oldest particle to make room?

            emitRipple(currentPos);
        }
    }
}
//----------------------------------------------------
//----------------------------------------------------
void TouchControllerComponent::OnFixedUpdate(f32 in_timeSinceLastUpdate)
{
    CSCore::Vector3 currentPos(GetEntity()->GetTransform().GetWorldPosition());
    CSCore::Vector3 direction(m_targetPos - currentPos);

    m_body->ApplyImpulse(CSCore::Vector2(0.0f, direction.y) * k_maxForce * in_timeSinceLastUpdate);
}
Beispiel #7
0
void osaOpenAL::Run(void)
{

    ALint iState = 0;

    if (SoundFile) {

        //Time =  TimeServer->GetAbsoluteTimeInSeconds() - StartTime;
        //alGetSourcef( soundSource[0], AL_SEC_OFFSET, &altime);  //nearest second is not good enough.
        ALint  currentPos(0);
        alGetSourcei (SoundSource[0], AL_SAMPLE_OFFSET, &currentPos);

        Time            = SoundSettings->StartTime + CalcStreamTime(currentPos);
        StreamVolume    = CalcStreamVolume(currentPos);
        StreamVolume.Timestamp() = Time;

        alGetSourcei(SoundSource[0], AL_SOURCE_STATE, &iState);
        if (iState != AL_PLAYING ){
            if (IsPlaying == true) {
                CMN_LOG_CLASS_RUN_VERBOSE << "Run: play stopped at: " << Time.Data << std::endl;
                IsPlaying = false;
            }
        } else {

        }
    } else  {
        IsPlaying = false;
    }
}
void Buffer::gotoBookmark(bool next) {
    // Try to find the bookmark, from the next/previous line
    int line = lineFromPosition(currentPos());
    int markerLine = -1;
    if (next) {
        line = (line == lineCount()) ? 0 : line + 1;
        markerLine = markerNext(line, 1 << Bookmark);
    } else {
        line = (line == 0 ? lineCount() : line - 1);
        markerLine = markerPrevious(line, 1 << Bookmark);
    }

     // Wrap search if a bookmark was not found.
    if (markerLine == -1) {
        if (next) {
            markerLine = markerNext(0, 1 << Buffer::Bookmark);
        } else {
            markerLine = markerPrevious(lineCount(), 1 << Buffer::Bookmark);
        }
    }

    // If the marker was found, go to the line.
    if (markerLine != -1) {
        gotoLine(markerLine);
    }
}
void Buffer::onUpdateUi() {
    if (m_braceHighlight && selectionEmpty()) {
        sptr_t position = currentPos();
        sptr_t braceStart = -1;
        // Check previous character first.
        if (position != 0 && isBrace(charAt(position - 1))) {
            braceStart = position - 1;
        } else if (isBrace(charAt(position))) { // Check next character.
            braceStart = position;
        }
        if (braceStart != -1) {
            // Brace found
            sptr_t braceEnd = braceMatch(braceStart);
            if (braceEnd > 0) {
                braceHighlight(braceStart, braceEnd);
            } else {
                // Missing matching brace.
                braceBadLight(braceStart);
            }
        } else {
            // Not a brace, clear indicators.
            braceBadLight(-1);
        }
    }
}
Beispiel #10
0
int Scrollbar::thumbPosition()
{
    if (!totalSize())
        return 0;

    int trackLen = trackLength();
    float proportion = static_cast<float>(currentPos()) / totalSize();
    return round(proportion * trackLen);
}
Beispiel #11
0
void MoveTo::innerStart() {
	// get current node position
	glm::vec2 currentPos(m_target->getPosition());
	auto translation = m_targetPos - currentPos;
	m_distanceToCover = glm::length(translation);
	if (m_distanceToCover > 0)
		m_velocity = m_speed * glm::normalize (translation);
	m_distanceCovered = 0.0;
}
Beispiel #12
0
//-----------------------------------------------------------------------------------------------
float Compute2dFractalNoise( float posX, float posY, float scale, unsigned int numOctaves, float octavePersistence, float octaveScale, bool renormalize, unsigned int seed )
{
	const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave

	float totalNoise = 0.f;
	float totalAmplitude = 0.f;
	float currentAmplitude = 1.f;
	float invScale = (1.f / scale);
	Vector2 currentPos( posX * invScale, posY * invScale );

	for( unsigned int octaveNum = 0; octaveNum < numOctaves; ++ octaveNum )
	{
		// Determine noise values at nearby integer "grid point" positions
		Vector2 cellMins( FastFloor( currentPos.x ), FastFloor( currentPos.y ) );
		int indexWestX = (int) cellMins.x;
		int indexSouthY = (int) cellMins.y;
		int indexEastX = indexWestX + 1;
		int indexNorthY = indexSouthY + 1;
		float valueSouthWest = Get2dNoiseZeroToOne( indexWestX, indexSouthY, seed );
		float valueSouthEast = Get2dNoiseZeroToOne( indexEastX, indexSouthY, seed );
		float valueNorthWest = Get2dNoiseZeroToOne( indexWestX, indexNorthY, seed );
		float valueNorthEast = Get2dNoiseZeroToOne( indexEastX, indexNorthY, seed );

		// Do a smoothed (nonlinear) weighted average of nearby grid point values
		Vector2 displacementFromMins = currentPos - cellMins;
		float weightEast  = SmoothStep( displacementFromMins.x );
		float weightNorth = SmoothStep( displacementFromMins.y );
		float weightWest  = 1.f - weightEast;
		float weightSouth = 1.f - weightNorth;

		float blendSouth = (weightEast * valueSouthEast) + (weightWest * valueSouthWest);
		float blendNorth = (weightEast * valueNorthEast) + (weightWest * valueNorthWest);
		float blendTotal = (weightSouth * blendSouth) + (weightNorth * blendNorth);
		float noiseThisOctave = 2.f * (blendTotal - 0.5f); // Map from [0,1] to [-1,1]

		// Accumulate results and prepare for next octave (if any)
		totalNoise += noiseThisOctave * currentAmplitude;
		totalAmplitude += currentAmplitude;
		currentAmplitude *= octavePersistence;
		currentPos *= octaveScale;
		currentPos.x += OCTAVE_OFFSET; // Add "irrational" offsets to noise position components
		currentPos.y += OCTAVE_OFFSET; //	at each octave to break up their grid alignment
		++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded)
	}

	// Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits
	if( renormalize && totalAmplitude > 0.f )
	{
		totalNoise /= totalAmplitude;				// Amplitude exceeds 1.0 if octaves are used
		totalNoise = (totalNoise * 0.5f) + 0.5f;	// Map to [0,1]
		totalNoise = SmoothStep( totalNoise );		// Push towards extents (octaves pull us away)
		totalNoise = (totalNoise * 2.0f) - 1.f;		// Map back to [-1,1]
	}

	return totalNoise;
}
void Buffer::toggleBookmark(int line) {
    if (line < 0) {
        line = lineFromPosition(currentPos());
    }
    if (markerGet(line) & (1 << Bookmark)) {
        markerDelete(line, Bookmark);
    } else {
        markerAdd(line, Bookmark);
    }
}
void EnergyFunction::printStatus() const{
	cout << "\nEnergy function name: " << m_name;
	cout << "\nCurrent energy: " << m_energy;
	node v;
	cout << "\nPosition of nodes in current solution:";
	NodeArray<int> num(m_G);
	int count = 1;
	forall_nodes(v,m_G) num[v] = count ++;
	forall_nodes(v,m_G) {
		cout << "\nNode: " << num[v] << " Position: " << currentPos(v);
	}
void TSAAngularResolution::computeEnergy()
{
    m_energy = 0;

    node v;
    forall_nodes(v, m_G) {
        DPoint pos = currentPos(v);
        double angRes = computeAngularResolution(v);
        m_nodeEnergy[v] = angRes;
        m_energy += angRes;
    }
QDocumentCursor CursorHistory::forward(const QDocumentCursor &currentCursor) {
	Q_UNUSED(currentCursor);
	CursorPosList::iterator next = nextValidEntry(currentEntry);
	if (currentEntry == history.end() || next == history.end()) {
		updateNavActions();
		return QDocumentCursor();
	}
	currentEntry = next;
	updateNavActions();
	return currentPos();
}
QDocumentCursor CursorHistory::back(const QDocumentCursor &currentCursor) {
	if (currentEntry == history.begin()) {
		updateNavActions();
		return QDocumentCursor();
	}

	// insert currentCursor to be able to go back
	if (currentCursor.isValid() && insertPos(currentCursor, false)) {
		currentEntry--;
	}

	CursorPosition pos(currentCursor);
	if (pos.isValid() && !pos.equals(*currentEntry)) {
		updateNavActions();
		return currentPos();
	}

	currentEntry = prevValidEntry(currentEntry);
	updateNavActions();
	return currentPos();
}
Beispiel #18
0
bool StreamReader::read(quint64 pos, int *length, char *buffer)
{
    QMutexLocker lock(&m_mutex);
    DEBUG_BLOCK;
    bool ret = true;

    if (m_unlocked) {
        return ret;
    }

    if (currentPos() != pos) {
        if (!streamSeekable()) {
            return false;
        }
        setCurrentPos(pos);
    }

    if (m_buffer.capacity() < *length) {
        m_buffer.reserve(*length);
    }

    while (currentBufferSize() < static_cast<unsigned int>(*length)) {
        quint64 oldSize = currentBufferSize();
        needData();

        m_waitingForData.wait(&m_mutex);

        if (oldSize == currentBufferSize()) {
            if (m_eos && m_buffer.isEmpty()) {
                return false;
            }
            // We didn't get any more data
            *length = static_cast<int>(oldSize);
            // If we have some data to return, why tell to reader that we failed?
            // Remember that length argument is more like maxSize not requiredSize
            ret = true;
        }
    }

    if (m_mediaObject->state() != Phonon::BufferingState &&
        m_mediaObject->state() != Phonon::LoadingState) {
        enoughData();
    }

    memcpy(buffer, m_buffer.data(), *length);
    m_pos += *length;
    // trim the buffer by the amount read
    m_buffer = m_buffer.mid(*length);

    return ret;
}
Beispiel #19
0
	// computes the energy if the node returned by testNode() is moved
	// to position testPos().
	void Planarity::compCandEnergy()
	{
		node v = testNode();
		m_candidateEnergy = energy();
		edge e;
		m_crossingChanges.clear();

		forall_adj_edges(e,v) if(!e->isSelfLoop()) {
			// first we compute the two endpoints of e if v is on its new position
			node s = e->source();
			node t = e->target();
			DPoint p1 = testPos();
			DPoint p2 = (s==v)? currentPos(t) : currentPos(s);
			int e_num = (*m_edgeNums)[e];
			edge f;
			// now we compute the crossings of all other edges with e
			ListIterator<edge> it;
			for(it = m_nonSelfLoops.begin(); it.valid(); ++it) if(*it != e) {
				f = *it;
				node s2 = f->source();
				node t2 = f->target();
				if(s2 != s && s2 != t && t2 != s && t2 != t) {
					bool cross = lowLevelIntersect(p1,p2,currentPos(s2),currentPos(t2));
					int f_num = (*m_edgeNums)[f];
					bool priorIntersect = (*m_crossingMatrix)(min(e_num,f_num),max(e_num,f_num));
					if(priorIntersect != cross) {
						if(priorIntersect) m_candidateEnergy --; // this intersection was saved
						else m_candidateEnergy ++; // produced a new intersection
						ChangedCrossing cc;
						cc.edgeNum1 = min(e_num,f_num);
						cc.edgeNum2 = max(e_num,f_num);
						cc.cross = cross;
						m_crossingChanges.pushBack(cc);
					}
				}
			}
		}
	}
Beispiel #20
0
void Window::createCurveIcons()
{
    static const char* names[]= {
        "Linear",
        "InQuad", "OutQuad", "InOutQuad", "OutInQuad",
        "InCubic", "OutCubic", "InOutCubic", "OutInCubic",
        "InQuart", "OutQuart", "InOutQuart", "OutInQuart",
        "InQuint", "OutQuint", "InOutQuint", "OutInQuint",
        "InSine", "OutSine", "InOutSine", "OutInSine",
        "InExpo", "OutExpo", "InOutExpo", "OutInExpo",
        "InCirc", "OutCirc", "InOutCirc", "OutInCirc",
        "InElastic", "OutElastic", "InOutElastic", "OutInElastic",
        "InBack", "OutBack", "InOutBack", "OutInBack",
        "InBounce", "OutBounce", "InOutBounce", "OutInBounce",
        "InCurve", "OutCurve", "SineCurve", "CosineCurve"
        };

    QPixmap pix(m_iconSize);
    QPainter painter(&pix);
    QLinearGradient gradient(0,0, 0, m_iconSize.height());
    gradient.setColorAt(0.0, QColor(240, 240, 240));
    gradient.setColorAt(1.0, QColor(224, 224, 224));
    QBrush brush(gradient);
    for (int i = QtEasingCurve::Linear; i <= QtEasingCurve::CosineCurve; ++i) {
        painter.fillRect(QRect(QPoint(0, 0), m_iconSize), brush);
        QtEasingCurve curve((QtEasingCurve::Type)i);
        painter.setPen(QColor(0, 0, 255, 64));
        qreal xAxis = m_iconSize.height()/1.5;
        qreal yAxis = m_iconSize.width()/3;
        painter.drawLine(0, xAxis, m_iconSize.width(),  xAxis);
        painter.drawLine(yAxis, 0, yAxis, m_iconSize.height());
        painter.setPen(Qt::black);
        
        qreal curveScale = m_iconSize.height()/2;
        QPoint currentPos(yAxis, xAxis);
        
        for (qreal t = 0; t < 1.0; t+=1.0/curveScale) {
            QPoint to;
            to.setX(yAxis + curveScale * t);
            to.setY(xAxis - curveScale * curve.valueForStep(t));
            painter.drawLine(currentPos, to);
            currentPos = to;
        }
        QListWidgetItem *item = new QListWidgetItem();
        item->setIcon(QIcon(pix));
        item->setText(QLatin1String(names[i]));
        m_listWidget->addItem(item);
    }
}
Beispiel #21
0
/*main function to run the filter wheel from the command line */
int main(int argc, char *argv[])
{
    memset(out,0,64);
    memset(in,0,64);

    int c;

    setup(); //start the communications

    while ((c = getopt (argc, argv, "pmftoiczh")) != -1)
        switch (c)
	    {
	    if(argc==1){
	        case 'p':
		    currentPos();
		    break;
	        case 't':
		    printf("test\n");
	  	    break;
		case 'o':
		    motorOff();
		    break;
		case 'z':
		    zero();
		    break;
		case '?':
         	    if (isprint (optopt))
           	        fprintf (stderr, "Unknown option `-%c'.\n", optopt);
         	    else
           		fprintf (stderr,
                        "Unknown option character `\\x%x'.\n",
                        optopt);
			return 1;
       			default:
         		abort ();
	    }
	    if(argc==2){
		case 'm':
                    printf("%s\n", argv[2]);
                    moveMotor(argv[2]);
                    break;
		case 'f':
                    printf("%s\n", argv[2]);
                    moveToFilter(atoi(argv[2]), atoi(argv[3]));
                    break;
		}
       	     }
	return 1;
}
Beispiel #22
0
              HRESULT read(LONGLONG pos, LONG length, BYTE *buffer, LONG *actual)
              {
                  QMutexLocker locker(&m_mutexRead);

                  if (m_mediaGraph->isStopping()) {
                      return VFW_E_WRONG_STATE;
                  }

                  if(streamSize() != 1 && pos + length > streamSize()) {
                      //it tries to read outside of the boundaries
                      return E_FAIL;
                  }

                  if (currentPos() - currentBufferSize() != pos) {
                      if (!streamSeekable()) {
                          return S_FALSE;
                      }
                      setCurrentPos(pos);
                  }

                  int oldSize = currentBufferSize();
                  while (currentBufferSize() < int(length)) {
                      needData();
                      if (m_mediaGraph->isStopping()) {
                          return VFW_E_WRONG_STATE;
                      }

                      if (oldSize == currentBufferSize()) {
                          break; //we didn't get any data
                      }
                      oldSize = currentBufferSize();
                  }

                  DWORD bytesRead = qMin(currentBufferSize(), int(length));
                  {
                      QWriteLocker locker(&m_lock);
                      qMemCopy(buffer, m_buffer.data(), bytesRead);
                      //truncate the buffer
                      m_buffer = m_buffer.mid(bytesRead);
                  }

                  if (actual) {
                      *actual = bytesRead; //initialization
                  }

                  return bytesRead == length ? S_OK : S_FALSE;
              }
Beispiel #23
0
void MouseMove(int x, int y)
{
    Math::Point currentPos(static_cast<float>(x), static_cast<float>(y));

    static bool first = true;
    if (first || (x < 10) || (y < 10) || (x > 790) || (y > 590))
    {
        SDL_WarpMouse(400, 300);
        MOUSE_POS_BASE.x = 400;
        MOUSE_POS_BASE.y = 300;
        ROTATION_BASE = ROTATION;
        first = false;
        return;
    }

    ROTATION.y = ROTATION_BASE.y + (static_cast<float> (x - MOUSE_POS_BASE.x) / 800.0f) * Math::PI;
    ROTATION.x = ROTATION_BASE.x + (static_cast<float> (y - MOUSE_POS_BASE.y) / 600.0f) * Math::PI;
}
Beispiel #24
0
void MainWindow::timeout()
{
    unsigned char r, g, b;
    psmove_tracker_get_color(m_tracker, m_move, &r, &g, &b);
    psmove_set_leds(m_move, r, g, b);
    psmove_update_leds(m_move);

    psmove_tracker_update_image(m_tracker);
    psmove_tracker_update(m_tracker, m_move);

    float x, y;
    if (psmove_tracker_get_position(m_tracker, m_move, &x, &y, NULL)) {
        QPointF currentPos(x, y);
        unsigned int buttons = 0;
        while (psmove_poll(m_move)) {
            unsigned int pressed;
            psmove_get_button_events(m_move, &pressed, NULL);
            if (pressed & Btn_MOVE) {
                m_points[m_pointsOffset] = currentPos;
                m_pointsOffset = (m_pointsOffset + 1) % 4;
                m_mapping.set(m_points);
            }
            if (pressed & Btn_T) {
                m_path.moveTo(m_mapping.map(currentPos));
            }
            if (pressed & Btn_CIRCLE) {
                m_path = QPainterPath();
            }
            if (pressed & Btn_PS) {
                QApplication::quit();
            }
            buttons = psmove_get_buttons(m_move);
        }
        if (buttons & Btn_T) {
            m_path.lineTo(m_mapping.map(currentPos));
        }

        m_mousePos = QPointF(x, y);

        update();
    }

}
Beispiel #25
0
int Map::getFirstVisibleFloor()
{
    int firstFloor = 0;
    for(int ix = -1; ix <= 1 && firstFloor < m_centralPosition.z; ++ix) {
        for(int iy = -1; iy <= 1 && firstFloor < m_centralPosition.z; ++iy) {
            Position currentPos(m_centralPosition.x + ix, m_centralPosition.y + iy, m_centralPosition.z);
            if((ix == 0 && iy == 0) || isLookPossible(currentPos)) {
                Position upperPos = currentPos;
                Position perspectivePos = currentPos;
                perspectivePos.perspectiveUp();
                upperPos.up();
                while(upperPos.z >= firstFloor) {
                    if(TilePtr tile = m_tiles[upperPos]) {
                        if(ThingPtr firstThing = tile->getThing(0)) {
                            ThingType *type = firstThing->getType();
                            if((type->properties[ThingType::IsGround] || type->properties[ThingType::IsOnBottom]) && !type->properties[ThingType::DontHide]) {
                                firstFloor = upperPos.z + 1;
                                break;
                            }
                        }
                    }
                    if(TilePtr tile = m_tiles[perspectivePos]) {
                        if(ThingPtr firstThing = tile->getThing(0)) {
                            ThingType *type = firstThing->getType();
                            if((type->properties[ThingType::IsGround] || type->properties[ThingType::IsOnBottom]) && !type->properties[ThingType::DontHide]) {
                                firstFloor = perspectivePos.z + 1;
                                break;
                            }
                        }
                    }
                    perspectivePos.perspectiveUp();
                    upperPos.up();
                }
            }
        }
    }
    return firstFloor;
}
void BurstShot::setTrail(){
    hitBox.setCoords(getX()-5, getY()-5,getX()+5,getY()+5);

    Point currentPos(getX(),getY());
    if(currentPos.distanceTo( trail.first()) > 3){
        trail.prepend(currentPos);
    }

    while (trail.size() > 15) {
       trail.pop_back();
    }
    if(hit){
        trail.pop_back();
    }

    if(getX() < -100 || getX() > game->width()+100 || getY() < -100 || getY() > game->height()+100){
        hit = true;
    }
    if(trail.isEmpty()){
        removeThis = true;

    }
}
Beispiel #27
0
int zero(){
        /* return current position as determined by the motor encoder */
        strcpy(out, "PX=0");
        if(!fnPerformaxComSendRecv(Handle, out, 64,64, in))
        {
                printf("Could not send\n");
                return 1;
        }
	printf("Step Value Set to 0\n");


	strcpy(out, "EX=0");
        if(!fnPerformaxComSendRecv(Handle, out, 64,64, in))
        {
                printf("Could not send\n");
                return 1;
        }
        printf("Encoder Value Set to 0\n");

	
	currentPos();

        return 1;
}
void ScreenshotEditWidget::mouseMoveEvent(QMouseEvent* event) {
    if (_toolActive) {
        QPoint currentPos(event->x() - ui->screenshotDisplayWidget->x(),
                          event->y() - ui->screenshotDisplayWidget->y());

        switch (_selectedTool) {
        case ST_CustomDraw: {
            QPainter painter(&_newPixmap);
            QPen pen;
            pen.setColor(_color);
            pen.setWidth(3);
            painter.setPen(pen);
            painter.drawLine(_lastToolPosition, currentPos);
            break;
        }
        default:
            // to suppress warnings
            break;
        }

        _lastToolPosition = currentPos;
        update();
    }
}
Beispiel #29
0
bool GalTextItem::processText()
{
  if(m_textIt != m_text.end())
//  if (m_iIndex < m_text.count())
  {
    // 发送当前位置信号
    emit currentPos(m_iIndex);
    // 处理效果
    processEffect();
    // 添加下一个字
//    m_pTextCursor->insertText(m_text.at(m_iIndex++));
    m_pTextCursor->insertText(*m_textIt);
    // 判断当前是否超过最大高度
    if(document()->size().height() >= m_dMaxHeight)
    {
      m_pTextCursor->movePosition(QTextCursor::Start);
      m_pTextCursor->movePosition(QTextCursor::Down, QTextCursor::KeepAnchor);
      m_pTextCursor->removeSelectedText();
      m_pTextCursor->movePosition(QTextCursor::End);

      m_pTextCursor->setCharFormat(m_textCharFormat);
      m_pTextCursor->setBlockFormat(m_textBlockFormat);
    }
    // 下一个字符
    m_textIt++;
    // 当前位置+1
    m_iIndex++;
    return false;
  }
  else
  {
    m_iState = -1;
    emit finished();
    return true;
  }
}
//===============================================================================
//Execute the skill.  This is the main part of the skill, where you tell the
//robot how to perform the skill.
void JamAndShootSkill::execute()
{  
  ///If not active, dont do anything!
	if(!initialized)
	{
		return;  
  }

  //aggresive mode
  if(sp->strategy2002.JAM_AND_SHOOT_MODE == 1)
  {
    skillSet->getSkill(AggressiveJamAndShootSkill::skillNum)->run();
    return;
  }
  //stupid mode
  else if(sp->strategy2002.JAM_AND_SHOOT_MODE == 2)
  {
    skillSet->getSkill(StupidJamAndShootSkill::skillNum)->run();
    return;
  }
  
  
  
  //else normal mode
    //decrease the shoot threshold linearly as the skill runs.
  shoot_threshold = sp->strategy2002.SHOOT_LANE_THRESH;// *
                    //(WAIT_TIME - (float)timer->currentTime()) / WAIT_TIME;
                   
  
  Pair currentPos(getLocation(robotID,*currentVisionData,*sp));
  float currentRot = getRotation(robotID,*currentVisionData,*sp);
  float good_shoot_thresh=shoot_threshold;
  if(kicked) good_shoot_thresh*=1.5f;
  else if(aimed) good_shoot_thresh=.05f;
  //finished waiting.  Shoot!
  //note, we only shoot if we're facing in the direction of the goal.
  kickFrames--;
  if(
      !gaveup  && 
      towardGoal(currentPos,
                 currentRot,sp->field.THEIR_GOAL_LINE,
                 sp->field.LEFT_GOAL_POST,
                 sp->field.RIGHT_GOAL_POST) &&
      (timer->currentTime() > WAIT_TIME || 
       goodImmediateShot(sp->general.TEAM,robotID,sp->strategy2002.KICK_VELOCITY,
                        *currentVisionData,*sp,good_shoot_thresh)
      //goodCurrentShot(currentPos,currentRot,*currentVisionData,*sp,good_shoot_thresh)
      )
    )
  {
    gaveup=true;
    if(driftdir != 0){
      kickFrames = PAUSE_FRAMES + 2*rand()*PAUSE_RANDOM/RAND_MAX - PAUSE_RANDOM;
      char msg[80];
      sprintf(msg,"Jam and Shoot pausing for %d frames",kickFrames);
      GUI_Record.debuggingInfo.addDebugMessage(msg);
    }
    kicked=false;
    timer->resetTimer();
  }


  if (gaveup && kickFrames <= 0){
    //we're out of time or have a good current shot, so just kick.
    SimpleKickSkill * kickSkill=(SimpleKickSkill *) skillSet->getSkill(SimpleKickSkill::skillNum);
    if(!kickSkill->isInitialized()){
      kickSkill->initialize(KICK_SHOT);
    }
    kickSkill->run();
    strategy->getCurrentFrame()->setMessage(robotID,"No Turn and Kick. Just Shooting.");
  }else if(skillSet->getSkill(PullBallOffWallSkill::skillNum)->isValid()){
    //deal with the ball in the corner or on the wall
    if(!skillSet->getSkill(PullBallOffWallSkill::skillNum)->isInitialized()){
      skillSet->getSkill(PullBallOffWallSkill::skillNum)->initialize();
    }
    skillSet->getSkill(PullBallOffWallSkill::skillNum)->run();
    
  }else if(kicked) {
    //We have a shot, let's aim and kick.
    TurnAndKickSkill *kicker=(TurnAndKickSkill *)skillSet->getSkill(TurnAndKickSkill::skillNum);
    kicker->run();
    //strategy->getCurrentFrame()->setMessage(robotID,"Have Shot - taking it");    
  }else{
	  
    bool isShot;
    //find best shot (if we're already drifting, use a larger threshold)
    if(aimed)isShot=calcShot(robotID,sp->field.THEIR_GOAL_LINE,sp->strategy2002.SHOOT_LANE_THRESH+2*sp->general.PLAYER_RADIUS,
      sp->field.RIGHT_GOAL_POST,sp->field.LEFT_GOAL_POST,NO_ROBOT,*currentVisionData,*sp,&target);
    else isShot=calcShot(robotID,sp->field.THEIR_GOAL_LINE,sp->strategy2002.SHOOT_LANE_THRESH,
      sp->field.RIGHT_GOAL_POST,sp->field.LEFT_GOAL_POST,NO_ROBOT,*currentVisionData,*sp,&target);

    if(isShot && driftdir==0)
    {
      //take the shot
      TurnAndKickSkill *kicker=(TurnAndKickSkill *)skillSet->getSkill(TurnAndKickSkill::skillNum);
      kicker->initialize(target,KICK_SHOT,true);
      kicker->run();
      kicked=true;
      strategy->getCurrentFrame()->setMessage(robotID,"Have a shot!");   
      kickFrames=0;
    }else{
      target.set(sp->field.THEIR_GOAL_LINE,sp->field.SPLIT_LINE);
      //if no shot, start to wait, dodge if possible
      GUI_Record.debuggingInfo.setDebugPoint(robotID,4,upperbound,testline);
      GUI_Record.debuggingInfo.setDebugPoint(robotID,5,lowerbound,testline);

      if (driftdir==0){
        //Calculate which direction to drift

        //first, see if we can shoot by shifting to the near post.
        //if not, drift across the field.

        //Default to drift across.
        float goalPost;
        if(currentPos.getY()>sp->field.SPLIT_LINE){
          driftdir = 1;
          goalPost=sp->field.LEFT_GOAL_POST;
        }else{
          driftdir = -1;
          goalPost=sp->field.RIGHT_GOAL_POST;
        }
        upperbound=sp->field.THEIR_GOAL_LINE;
        lowerbound=sp->field.KILL_ZONE_LINE;
        testline=sp->field.SPLIT_LINE + driftdir*(SIDE_DIST);

        Pair loc;

        //check near-side shot.
        if(currentPos.getY() * driftdir >= goalPost*driftdir &&
           calcYShot(Pair(sp->field.THEIR_GOAL_LINE,sp->field.SPLIT_LINE),
                     testline,
                     sp->strategy2002.SHOOT_LANE_THRESH*SIDE_LANE_FACTOR,
                     upperbound,
                     lowerbound,NO_ROBOT,
                     *currentVisionData,
                     *sp, 
                     &loc)){
          driftdir=-driftdir;
        }
      }
      //  printf("%f\n",ABS(angleDifference(angleBetween(currentPos,target),currentRot)));

      if(ABS(angleDifference(angleBetween(currentPos,target),currentRot)) < AIM_ANGLE  || aimed){
        aimed=true;
        //if(target.getX() != sp->field.THEIR_GOAL_LINE) target.setX(sp->field.THEIR_GOAL_LINE);
        //drift to the side to see if we have a shot.
        //calculate the direction to drift
        
        
        Pair dest;
        float changeAngle;
        //switch directions if we've gone too far.
        if(angleBetween(currentPos,target)*driftdir > BOUNCE_ANGLE ){
          driftdir=-driftdir;
        }
        target.setY(target.getY() - AIM_DISTANCE*driftdir);
        changeAngle= DRIFT_ANGLE*driftdir;

        char msg[80];
        sprintf(msg, "No Shot - drifting %s",( driftdir > 0 ? "right" : "left"));
        strategy->getCurrentFrame()->setMessage(robotID,msg);
         //drift around goal 
        //See if we can push forward:
        rotateAboutPoint(frontOfRobot(robotID,*currentVisionData,*sp), target,changeAngle, dest);

   //DUE TO J&S BACKING UP TOO MUCH, I'M GETTING RID OF THIS NEXT PART
        
        if(!isLane(currentPos,dest,sp->general.PLAYER_RADIUS,*currentVisionData,*sp,true)){
          //we can't.  :(  drift sideways.
          rotateAboutPoint(currentPos, target,changeAngle, dest);
        }
        
        
        //see if one of their robots is in the way, and back up if they are.
        if(!isLane(currentPos,dest,sp->general.PLAYER_RADIUS,*currentVisionData,*sp,true)){
          //move destination back
          extendPoint(target,dest,sp->general.PLAYER_RADIUS,dest);
        }
        
        command->setPos(dest);
        //Adjust angle to fast the direction we're drifting a bit.
        command->setRotation(angleBetween(currentPos,target) - driftdir*DRIFT_ADJUST_ANGLE);
        command->setDribble(DRIBBLE_DEFAULT);
        command->setVerticalDribble(V_DRIBBLE_DEFAULT);
        command->setSpeed(BALL_POSSESSION_SPEED);
      }else{
        strategy->getCurrentFrame()->setMessage(robotID,"No Shot - turning to goal");
        //turn to face goal
        SpinAroundBallSkill *spin=(SpinAroundBallSkill *)strategy->getSkillSet(robotID)->getSkill(SpinAroundBallSkill::skillNum);
        spin->initialize(target);
        spin->run();
      }
    }
  }
  RobotIndex goalie;
  if(getLocation(robotID,*currentVisionData,*sp).getX() > sp->field.HALF_LINE){
    if(getTheirGoalie(*currentVisionData,*sp,&goalie)){
      if(getLocation(sp->general.OTHER_TEAM,goalie,*currentVisionData).distanceTo(getLocation(robotID,*currentVisionData,*sp)) >= 
          ENTERBOX_CAUTION_DIST+sp->general.PLAYER_RADIUS + sp->general.OPPONENT_RADIUS){
        command->setControl(OMNI_FAST_ENTERBOX);
      }
    }else{
      //if no goalie, enter the box
      command->setControl(OMNI_FAST_ENTERBOX);
    }
  }


  GUI_Record.debuggingInfo.setDebugPoint(robotID,0,target);
  //command->setControl(OMNI_NORMAL_ENTERBOX);
  command->setRotation(angleBetween(currentPos,target));
}