Пример #1
0
int ALIGN_DISTRIBUTE_TOOL::selectTarget( ALIGNMENT_RECTS& aItems, ALIGNMENT_RECTS& aLocked, T aGetValue )
{
    wxPoint curPos( getViewControls()->GetCursorPosition().x,  getViewControls()->GetCursorPosition().y );

    // after sorting, the fist item acts as the target for all others
    // unless we have a locked item, in which case we use that for the target
    int target = !aLocked.size() ? aGetValue( aItems.front() ): aGetValue( aLocked.front() );

    // Iterate through both lists to find if we are mouse-over on one of the items.
    for( auto sel = aLocked.begin(); sel != aItems.end(); sel++ )
    {
        // If there are locked items, prefer aligning to them over
        // aligning to the cursor as they do not move
        if( sel == aLocked.end() )
        {
            if( aLocked.size() == 0 )
            {
                sel = aItems.begin();
                continue;
            }

            break;
        }

        // We take the first target that overlaps our cursor.
        // This is deterministic because we assume sorted arrays
        if( sel->second.Contains( curPos ) )
        {
            target = aGetValue( *sel );
            break;
        }
    }

    return target;
}
Пример #2
0
 SimpleAutomatonTokenizer::Token SimpleAutomatonTokenizer::emitToken() {
     while (!eof()) {
         size_t startLine = line();
         size_t startColumn = column();
         const char* c = curPos();
         
         switch (*c) {
             case '{':
                 discardUntil("}");
                 break;
             case ',':
                 advance();
                 return Token(SimpleAutomatonToken::Comma, c, c+1, offset(c), startLine, startColumn);
             case ';':
                 advance();
                 return Token(SimpleAutomatonToken::Semicolon, c, c+1, offset(c), startLine, startColumn);
             case ' ':
             case '\t':
             case '\n':
             case '\r':
                 discardWhile(Whitespace);
                 break;
             default: {
                 const char* e = readString(Whitespace + ";,:");
                 if (e == NULL)
                     throw ParserException(startLine, startColumn, "Unexpected character: " + String(c, 1));
                 return Token(detectType(c, e), c, e, offset(c), startLine, startColumn);
             }
         }
     }
     return Token(SimpleAutomatonToken::Eof, NULL, NULL, length(), line(), column());
 }
Пример #3
0
bool SceneLoader::doG(istream &str, string &name)
{
    name = getString(str);
    if (name.empty()) {
        *err << "Couldn't read group name at ";
        errLine(str.tellg());
        return false;
    }

    if (groups[name] != NULL)
    {
        *err << "Illegal re-use of group name \"" << name << "\" at ";
        curPos(*err,str.tellg());
        *err << endl;
        return false;
    }

    SceneGroup *n = new SceneGroup();
    groups[name] = n;
    n->_name = name;

    do {
        int state = findOpenOrClosedParen(str);
        if (state == ERROR)
            return false;
        else if (state == CLOSED)
            return true;
        else if (state == OPEN)
        {
            string cmd;
            if (readCommand(str, cmd)) {
                if (cmd != "I")
                {
                    *err << "Command other than I from G at ";
                    curPos(*err,str.tellg());
                    *err << endl;
                }
                string iname;
                SceneInstance *newNode;
                if ((newNode = doI(str,iname)) != NULL) {
                    n->_children.push_back( newNode );
                }
                findCloseParen(str);
            }
        }
    } while (true);
}
Пример #4
0
bool SceneLoader::readCommand(istream &str, string &name) {
  name = getString(str);
  if (name.empty()) {
    *err << "error: expected command but did not find one at ";
    curPos(*err, str.tellg());
    *err << endl;
    return false;
  }
  return true;
}
Пример #5
0
string SceneLoader::getQuoted(istream &str) {
  string ret;
  char temp;
  str >> temp;
  if (temp != '"') {
    *err << "expected opening \" at ";
    curPos(*err, str.tellg());
    *err << endl;
  }
  getline(str, ret, '"');
  return ret;
}
Пример #6
0
void SummaryWidget::paintEvent(QPaintEvent *) {
    QPainter painter(this);

    QRect rect = painter.viewport();
    painter.setBrush(QBrush(Qt::gray));
    painter.drawRect(rect);

    QPointF curPos(5,5);

    QFont serifFont("Times", 9);
    QFontMetricsF fm(serifFont);
    int fontPixHeight = fm.height();

    // box at the right edge of widget, labeled with week number
    painter.save();
    QRect weekOfYearRect(width()-fontPixHeight-4, 0, fontPixHeight+4, height());
    painter.setBrush(QBrush(Qt::black));
    painter.drawRect(weekOfYearRect);
    painter.rotate(90);
    painter.setPen(Qt::white);
    painter.setRenderHint(QPainter::Antialiasing, true);
    QString sideLabel = QString("WEEK %1").arg(week.week());
    int sideLabelLen = fm.width(sideLabel);
    painter.drawText(0, -width(),height(), fontPixHeight+8,  Qt::AlignCenter, sideLabel);
    painter.restore();

//    QFont serifFont("Times", 10);
//    QFontMetricsF fm(serifFont);
//    int fontPixHeight = fm.height();

    for (int i=0; i<summary->getSessions().length(); i++) {
        curPos = summary->getSessions().value(i)->paint(*spainter, curPos, painter);
    }
    // no session this week => print "recomp"
    if (summary->getSessions().length() == 0) {
        QFont serifFont("Times", 14, QFont::Bold);
        QFontMetricsF fm(serifFont);
        fontPixHeight = fm.height();
        painter.setFont(serifFont);
        painter.setPen(QPen(Qt::red));

        curPos += QPointF(0, fontPixHeight);
        painter.drawText(curPos, "recomp");
        int space = sideLabelLen - curPos.y() + 20;

        curPos += QPointF(0, space);
    }

    plotHeight = curPos.y();

    emit plotHeightChanged(week);
}
Пример #7
0
bool SceneLoader::doRender(istream &str, string &name)
{
    name = getString(str);
    if (name.empty())
    {
        *err << "Trying to render group without specifying a name at ";
        curPos(*err,str.tellg());
        *err << endl;
        return false;
    }

    if (groups[name] == NULL)
    {
        *err << "Trying to render group not found \"" << name << "\" at ";
        curPos(*err,str.tellg());
        *err << endl;
        return false;
    }

    root->_child = groups[name];

    return true;
}
Пример #8
0
bool QQuickCustomAffector::affectParticle(QQuickParticleData *d, qreal dt)
{
    //This does the property based affecting, called by superclass if signal isn't hooked up.
    bool changed = false;
    QPointF curPos(d->curX(), d->curY());

    if (m_acceleration != &m_nullVector){
        QPointF pos = m_acceleration->sample(curPos);
        QPointF curAcc = QPointF(d->curAX(), d->curAY());
        if (m_relative) {
            pos *= dt;
            pos += curAcc;
        }
        if (pos != curAcc) {
            d->setInstantaneousAX(pos.x());
            d->setInstantaneousAY(pos.y());
            changed = true;
        }
    }

    if (m_velocity != &m_nullVector){
        QPointF pos = m_velocity->sample(curPos);
        QPointF curVel = QPointF(d->curVX(), d->curVY());
        if (m_relative) {
            pos *= dt;
            pos += curVel;
        }
        if (pos != curVel) {
            d->setInstantaneousVX(pos.x());
            d->setInstantaneousVY(pos.y());
            changed = true;
        }
    }

    if (m_position != &m_nullVector){
        QPointF pos = m_position->sample(curPos);
        if (m_relative) {
            pos *= dt;
            pos += curPos;
        }
        if (pos != curPos) {
            d->setInstantaneousX(pos.x());
            d->setInstantaneousY(pos.y());
            changed = true;
        }
    }

    return changed;
}
Пример #9
0
void ParticleField::Render() {
  glEnable(GL_TEXTURE_2D);
  m_ParticleTexture->bind();
  static ci::Color c = ci::Color(0.4f, 0.7f, 0.9f);
  static ci::Color c2 = ci::Color(0.9f, 0.6f, 0.1f);
  glPushMatrix();
  for (std::list<Particle>::iterator it = m_Particles.begin(); it != m_Particles.end(); it++) {
    const ci::Vec4f back = it->history.back();
    float temp = static_cast<float>((it->radius-MIN_RADIUS)/(MAX_RADIUS-MIN_RADIUS));
    ci::Color curColor = c*temp + c2*(1-temp);
    float radius = it->radius * back[3];
    ci::Vec3f pos(back[0], back[1], back[2]);
    scaleVec3(pos);
    glEnable(GL_TEXTURE_2D);
    renderImage(pos, radius, curColor, back[3]);
    glDisable(GL_TEXTURE_2D);
    glBegin(GL_QUAD_STRIP);
    float total = static_cast<float>(it->history.size());
    for (int i = static_cast<int>(it->history.size())-1; i>0; i--) {
      float per = static_cast<float>(i) / total;
      const ci::Vec4f& cur = it->history[i];
      const ci::Vec4f& last = it->history[i-1];
      ci::Vec3f curPos(cur[0], cur[1], cur[2]);
      ci::Vec3f lastPos(last[0], last[1], last[2]);
      scaleVec3(curPos);
      scaleVec3(lastPos);

      ci::Vec3f perp0 = curPos - lastPos;
      ci::Vec3f perp1 = perp0.cross(ci::Vec3f::zAxis());
      ci::Vec3f perp2 = perp0.cross(perp1);
      perp1 = perp0.cross(perp2).normalized();
      float offWidth = (it->radius * cur[3] * per * 0.07f);
      float opacityScale = 0.95f*back[3]*per;
      if (per > 0.8f) {
        float temp = (1.0f - per) / 0.2f;
        float tempScale = sqrt(temp);
        offWidth *= tempScale;
        opacityScale *= tempScale;
      }
      ci::Vec3f off = perp1 * offWidth;
      glColor4f(curColor.r, curColor.g, curColor.b, opacityScale);
      ci::gl::vertex(curPos - off);
      ci::gl::vertex(curPos + off);
    }
    glEnd();
  }
  glPopMatrix();
}
Пример #10
0
DirectX::XMFLOAT2 SpriteFont::MeasureText(const wchar *text, uint maxWidth) const {
	DirectX::XMFLOAT2 size(0.0f, 0.0f);
	DirectX::XMFLOAT2 curPos(0.0f, 0.0f);;

	size_t length = wcslen(text);

	for (uint64 i = 0; i < length; ++i) {
		wchar character = text[i];
		if (character == ' ') {
			// Check for wrapping
			if (maxWidth != 0U && curPos.x + m_spaceWidth > maxWidth) {
				size.x = std::max(size.x, curPos.x);
				curPos.y += m_charHeight;
				curPos.x = 0;
			}

			curPos.x += m_spaceWidth;
		} else if (character == '\t') {
			// Check for wrapping
			if (maxWidth != 0U && curPos.x + 4.0f * m_spaceWidth > maxWidth) {
				curPos.y += m_charHeight;
				curPos.x = 0;
			}

			curPos.x += 4.0f * m_spaceWidth;
		} else if (character == '\n' || character == '\r') {
			size.x = std::max(size.x, curPos.x);
			curPos.y += m_charHeight;
			curPos.x = 0;
		} else {
			SpriteFont::CharDesc desc = GetCharDescriptor(character);

			// Check for wrapping
			if (maxWidth != 0U && curPos.x + desc.Width + 1 > maxWidth) {
				size.x = std::max(size.x, curPos.x);
				curPos.y += m_charHeight;
				curPos.x = 0;
			}

			curPos.x += desc.Width + 1;
		}

		size.x = std::max(curPos.x, size.x);
		size.y = curPos.y + m_charHeight;
	}

	return size;
}
Пример #11
0
 void EObject::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
 {
	 if(myMode == RESIZE)
	 {
		 width = dashRect->rect().width() +margin*2;
		 height = dashRect->rect().height() +margin*2;
		 qreal curX = dashRect->rect().left() - margin;
		 qreal curY = dashRect->rect().top() - margin;
		 QPointF curPos(curX,curY);
		 setPos(mapToScene(curPos));
		 //scene()->removeItem(dashRect);
		 delete dashRect;
	 }
	 else
		QGraphicsItem::mouseReleaseEvent(event);
 }
Пример #12
0
	void Primitive2D::handleEvent(SoHandleEventAction* action)
	{
		if (!eventsHandles)
		{
			SoSeparator::handleEvent(action);
			return;
		}

		eventAction = action;
		const SoEvent* event = action->getEvent();

		SbViewportRegion viewRegion = sketcherView.getViewer().getViewportRegion();
		SbVec2f normalizedPos(event->getNormalizedPosition(viewRegion));

		SbViewVolume volume;
		volume = SoViewVolumeElement::get(eventAction->getState());
		SbVec3f curPos(sketcherView.projectPoint(normalizedPos, volume));

        if (event->getTypeId().isDerivedFrom(SoKeyboardEvent::getClassTypeId()))
		{
            const SoKeyboardEvent* keyEvent = static_cast<const SoKeyboardEvent*>(event);

			int key = keyEvent->getKey();

			if (key == SoKeyboardEvent::RETURN)
				emitCreated();
			else if (key == SoKeyboardEvent::ESCAPE)
				emitCreationCanceled();

			if (keyPressed(key))
				action->setHandled();
        }
        else if (event->getTypeId().isDerivedFrom(SoMouseButtonEvent::getClassTypeId()))
		{
            const SoMouseButtonEvent* mouseEvent = static_cast<const SoMouseButtonEvent*>(event);
            int button = mouseEvent->getButton();
            SbBool press = mouseEvent->getState() == SoButtonEvent::DOWN ? TRUE : FALSE;

            if (mouseButtonPressed(button, press, curPos))
                action->setHandled();
        }
        else if (event->getTypeId().isDerivedFrom(SoLocation2Event::getClassTypeId()))
		{
            if (mouseMove(curPos))
                action->setHandled();
        }
	}
Пример #13
0
bool SceneLoader::doSurface(istream &str, string& name) {
  name = getString(str);
  if (name.empty()) {
    *err << "Couldn't read surface name at "; errLine(str.tellg());
    return false;
  }

  if (_savedColors[name] != NULL) {
    *err << "Illegal re-use of surface name \"" << name << "\" at ";
    curPos(*err,str.tellg());
    *err << endl;
    return false;
  }

  do {
    int state = findOpenOrClosedParen(str);
    if (state == ERROR)
      return false;
    else if (state == CLOSED)
      return true;
    else if (state == OPEN) {
      string cmd;
      vector<ParametricValue*> values;
      if (readCommand(str, cmd)) {
	if (cmd == "rgb") {
	  int numv = getValues(str, values);
	  if (numv < 3) {
	    *err << "rgb with not enough args at "; errLine(str.tellg());
	  } else {
	    cleanAfter(values, 3);
	    Color *c = new Color();
	    for (int i = 0; i < 3; i++) {
	      c->_color[i] = values[i];
	    }
	    _savedColors[name] = c;
	  }
	} else if (cmd == "bitmap") {
	  // something with loading textures
	  string file = getQuoted(str);
	  _savedTextures[name] = file;
	}
	findCloseParen(str);
      }
    }
  } while (true);
}
Пример #14
0
bool SceneLoader::findOpenParen(istream &str) {
  char temp;
  string line;
  while (str >> temp) {
    if (temp == '(')
      return true;
    else if (temp == '#')
      getline(str,line);
    else {
      *err << "error: unexpected char " << temp << " at ";
      curPos(*err, str.tellg());
      *err << endl;
      return false;
    }
  }
  return false;
}
Пример #15
0
bool SceneLoader::doInclude(istream &str, string& name) {
  name = getString(str);
  if (name.empty()) {
    *err << "Couldn't read include name at "; errLine(str.tellg());
    return false;
  }

  if (groups[name] != NULL) {
    *err << "Illegal re-use of variable name \"" << name << "\" at ";
    curPos(*err,str.tellg());
    *err << endl;
    return false;
  }

  string file = getQuoted(str);
  SceneGroup *n = new SceneGroup();
  n->_poly = new Polygon(file);
  n->_name = name;
  groups[name] = n;
  return true;
}
Пример #16
0
int SceneLoader::findOpenOrClosedParen(istream &str) {
  char temp;
  string line;
  while (str >> temp) {
    if (temp == '(')
      return OPEN;
    else if (temp == '#')
      getline(str,line);
    else if (temp == ')') {
      str.putback(temp);
      return CLOSED;
    }
    else {
      *err << "error: unexpected char " << temp << " at ";
      curPos(*err, str.tellg());
      *err << endl;
      return false;
    }
  }
  return ERROR;
}
Пример #17
0
ParametricValue* SceneLoader::getValue(istream &str)
{
    char temp;
    str >> temp;
    if (temp == ')')
    {
        str.putback(temp);
        return NULL;
    }
    else if (temp == '#')
    {
        string no;
        getline(str,no);
        return getValue(str);
    }
    else
    {
        str.putback(temp);

        double val;
        str.peek();
        str >> val;
        if (str.fail())
        {
            str.clear();
            *err << "Failed to extract a numeric value at ";
            curPos(*err, str.tellg());
            *err << endl;

            str.peek();
            return NULL;
        } else {
            return new ConstValue(val);
        }
    }
}
Пример #18
0
//==============================
// BitmapFontSurfaceLocal::DrawText3D
void BitmapFontSurfaceLocal::DrawText3D( BitmapFont const & font, fontParms_t const & parms,
		Vector3f const & pos, Vector3f const & normal, Vector3f const & up,
		float scale, Vector4f const & color, char const * text )
{
	if ( text == NULL || text[0] == '\0' )
	{
		return;	// nothing to do here, move along
	}

	// TODO: multiple line support -- we would need to calculate the horizontal width
	// for each string ending in \n
	size_t len;
	float width;
	float height;
	float ascent;
	float descent;
	int const MAX_LINES = 128;
	float lineWidths[MAX_LINES];
	int numLines;
	AsLocal( font ).CalcTextMetrics( text, len, width, height, ascent, descent, lineWidths, MAX_LINES, numLines );
//	LOG( "BitmapFontSurfaceLocal::DrawText3D( \"%s\" %s %s ) : width = %.2f, height = %.2f, numLines = %i, fh = %.2f",
//			text, parms.CenterVert ? "cv" : "", parms.CenterHoriz ? "ch" : "",
//			width, height, numLines, AsLocal( font ).GetFontInfo().FontHeight );
	if ( len == 0 )
	{
		return;
	}

	DROID_ASSERT( normal.IsNormalized(), "BitmapFont" );
	DROID_ASSERT( up.IsNormalized(), "BitmapFont" );

	const FontInfoType & fontInfo = AsLocal( font ).GetFontInfo();

	float imageWidth = (float)AsLocal( font ).GetImageWidth();
	float const xScale = AsLocal( font ).GetFontInfo().ScaleFactor * scale;
	float const yScale = AsLocal( font ).GetFontInfo().ScaleFactor * scale;

	// allocate a vertex block
	size_t numVerts = 4 * len;
	VertexBlockType vb( font, numVerts, pos, Quatf(), parms.Billboard, parms.TrackRoll );

	Vector3f const right = up.Cross( normal );
	Vector3f const r = ( parms.Billboard ) ? Vector3f( 1.0f, 0.0f, 0.0f ) : right;
	Vector3f const u = ( parms.Billboard ) ? Vector3f( 0.0f, 1.0f, 0.0f ) : up;

	Vector3f curPos( 0.0f );
	if ( parms.CenterVert )
	{
		float const vofs = ( height * 0.5f ) - ascent;
		curPos += u * ( vofs * scale );
	}

	Vector3f basePos = curPos;
	if ( parms.CenterHoriz )
	{
		curPos -= r * ( lineWidths[0] * 0.5f * scale );
	}
	
	Vector3f lineInc = u * ( fontInfo.FontHeight * yScale );
	float const distanceScale = imageWidth / FontInfoType::DEFAULT_SCALE_FACTOR;
	const uint8_t fontParms[4] = 
	{
			(uint8_t)( OVR::Alg::Clamp( parms.AlphaCenter + fontInfo.CenterOffset, 0.0f, 1.0f ) * 255 ),
			(uint8_t)( OVR::Alg::Clamp( parms.ColorCenter + fontInfo.CenterOffset, 0.0f, 1.0f ) * 255 ),
			(uint8_t)( OVR::Alg::Clamp( distanceScale, 1.0f, 255.0f ) ),
			0
	};

    int iColor = ColorToABGR( color );

	int curLine = 0;
	fontVertex_t * v = vb.Verts;
	char const * p = text;
	size_t i = 0;
	uint32_t charCode = UTF8Util::DecodeNextChar( &p );
	for ( ; charCode != '\0'; i++, charCode = UTF8Util::DecodeNextChar( &p ) )
	{
		OVR_ASSERT( i < len );
		if ( charCode == '\n' && curLine < numLines && curLine < MAX_LINES )
		{
			// move to next line
			curLine++;
			basePos -= lineInc;
			curPos = basePos;
			if ( parms.CenterHoriz )
			{
				curPos -= r * ( lineWidths[curLine] * 0.5f * scale );
			}
		}

		FontGlyphType const & g = AsLocal( font ).GlyphForCharCode( charCode );

		float s0 = g.X;
		float t0 = g.Y;
		float s1 = ( g.X + g.Width );
		float t1 = ( g.Y + g.Height );

		float bearingX = g.BearingX * xScale;
		float bearingY = g.BearingY * yScale ;

		float rw = ( g.Width + g.BearingX ) * xScale;
		float rh = ( g.Height - g.BearingY ) * yScale;

        // lower left
        v[i * 4 + 0].xyz = curPos + ( r * bearingX ) - ( u * rh );
        v[i * 4 + 0].s = s0;
        v[i * 4 + 0].t = t1;
        *(UInt32*)(&v[i * 4 + 0].rgba[0]) = iColor;
		*(UInt32*)(&v[i * 4 + 0].fontParms[0]) = *(UInt32*)(&fontParms[0]);
	    // upper left
        v[i * 4 + 1].xyz = curPos + ( r * bearingX ) + ( u * bearingY );
        v[i * 4 + 1].s = s0;
        v[i * 4 + 1].t = t0;
        *(UInt32*)(&v[i * 4 + 1].rgba[0]) = iColor;
		*(UInt32*)(&v[i * 4 + 1].fontParms[0]) = *(UInt32*)(&fontParms[0]);
        // upper right
        v[i * 4 + 2].xyz = curPos + ( r * rw ) + ( u * bearingY );
        v[i * 4 + 2].s = s1;
        v[i * 4 + 2].t = t0;
        *(UInt32*)(&v[i * 4 + 2].rgba[0]) = iColor;
		*(UInt32*)(&v[i * 4 + 2].fontParms[0]) = *(UInt32*)(&fontParms[0]);
        // lower right
        v[i * 4 + 3].xyz = curPos + ( r * rw ) - ( u * rh );
        v[i * 4 + 3].s = s1;
        v[i * 4 + 3].t = t1;
        *(UInt32*)(&v[i * 4 + 3].rgba[0]) = iColor;
		*(UInt32*)(&v[i * 4 + 3].fontParms[0]) = *(UInt32*)(&fontParms[0]);
		// advance to start of next char
		curPos += r * ( g.AdvanceX * xScale );
	}
	// add the new vertex block to the array of vertex blocks
	VertexBlocks.PushBack( vb );
}
Пример #19
0
void CtrlDisAsmView::paintEvent(QPaintEvent *)
{
	QPainter painter(this);
	painter.setBrush(Qt::white);
	painter.setPen(Qt::white);
	painter.drawRect(rect());

	struct branch
	{
		int src,dst,srcAddr;
		bool conditional;
	};
	branch branches[256];
	int numBranches=0;

	int width = rect().width();
	int numRows=(rect().height()/rowHeight);

	QColor bgColor(0xFFFFFFFF);
	QPen nullPen(bgColor);
	QPen currentPen(QColor(0,0,0));
	QPen selPen(QColor(0xFF808080));
	QPen condPen(QColor(0xFFFF3020));

	QBrush lbr;
	lbr.setColor(bgColor);
	QBrush currentBrush(QColor(0xFFFFEfE8));
	QBrush pcBrush(QColor(0xFF70FF70));

	QFont normalFont("Arial", 10);
	QFont boldFont("Arial", 10);
	QFont alignedFont("Monospace", 10);
	alignedFont.setStyleHint(QFont::Monospace);
	boldFont.setBold(true);
	painter.setFont(normalFont);


	QImage breakPoint(":/resources/breakpoint.ico");
	int i;
	curAddress&=~(align-1);

	align=(debugger->getInstructionSize(0));
	for (i=0; i<=numRows; i++)
	{
		unsigned int address=curAddress + (i-(numRows/2))*align;

		int rowY1 = rect().top() + rowHeight*i;
		int rowY2 = rect().top() + rowHeight*i + rowHeight - 1;

		lbr.setColor((unsigned int)marker == address ? QColor(0xFFFFEEE0) : QColor(debugger->getColor(address)));
		QColor bg = lbr.color();
		painter.setBrush(currentBrush);
		painter.setPen(nullPen);
		painter.drawRect(0,rowY1,16-1,rowY2-rowY1);

		if (selecting && address == (unsigned int)selection)
			painter.setPen(selPen);
		else
		{
			if(i==numRows/2)
				painter.setPen(currentPen);
			else
				painter.setPen(bg);
		}
		painter.setBrush(QBrush(bg));

		if (address == debugger->getPC())
		{
			painter.setBrush(pcBrush);
		}

		painter.drawRect(16,rowY1,width-16-1,rowY2-rowY1);
		painter.setBrush(currentBrush);
		QPen textPen(QColor(halfAndHalf(bg.rgba(),0)));
		painter.setPen(textPen);
		painter.setFont(alignedFont);
		painter.drawText(17,rowY1-3+rowHeight,QString("%1").arg(address,8,16,QChar('0')));
		painter.setFont(normalFont);
		textPen.setColor(QColor(0xFF000000));
		painter.setPen(textPen);
		if (debugger->isAlive())
		{
			const char *dizz = debugger->disasm(address, align);
			char dis[512];
			strcpy(dis, dizz);
			char *dis2 = strchr(dis,'\t');
			char desc[256]="";
			if (dis2)
			{
				*dis2=0;
				dis2++;
				const char *mojs=strstr(dis2,"->$");
				if (mojs)
				{
					for (int i=0; i<8; i++)
					{
						bool found=false;
						for (int j=0; j<22; j++)
						{
							if (mojs[i+3]=="0123456789ABCDEFabcdef"[j])
								found=true;
						}
						if (!found)
						{
							mojs=0;
							break;
						}
					}
				}
				if (mojs)
				{
					int offs;
					sscanf(mojs+3,"%08x",&offs);
					branches[numBranches].src=rowY1 + rowHeight/2;
					branches[numBranches].srcAddr=address/align;
					branches[numBranches].dst=(int)(rowY1+((s64)offs-(s64)address)*rowHeight/align + rowHeight/2);
					branches[numBranches].conditional = (dis[1]!=0); //unconditional 'b' branch
					numBranches++;
					const char *t = debugger->getDescription(offs).c_str();
					if (memcmp(t,"z_",2)==0)
						t+=2;
					if (memcmp(t,"zz_",3)==0)
						t+=3;
					sprintf(desc,"-->%s", t);
					textPen.setColor(QColor(0xFF600060));
					painter.setPen(textPen);
				}
				else
				{
					textPen.setColor(QColor(0xFF000000));
					painter.setPen(textPen);
				}
				painter.drawText(149,rowY1-3+rowHeight,QString(dis2));
			}
			textPen.setColor(QColor(0xFF007000));
			painter.setPen(textPen);
			painter.setFont(boldFont);
			painter.drawText(84,rowY1-3+rowHeight,QString(dis));
			painter.setFont(normalFont);
			if (desc[0]==0)
			{
				const char *t = debugger->getDescription(address).c_str();
				if (memcmp(t,"z_",2)==0)
					t+=2;
				if (memcmp(t,"zz_",3)==0)
					t+=3;
				strcpy(desc,t);
			}
			if (memcmp(desc,"-->",3) == 0)
			{
				textPen.setColor(QColor(0xFF0000FF));
				painter.setPen(textPen);
			}
			else
			{
				textPen.setColor(halfAndHalf(halfAndHalf(bg.rgba(),0),bg.rgba()));
				painter.setPen(textPen);
			}
			if (strlen(desc))
				painter.drawText(std::max(280,width/3+190),rowY1-3+rowHeight,QString(desc));
			if (debugger->isBreakpoint(address))
			{
				painter.drawImage(2,rowY1+2,breakPoint);
			}
		}
	}
	for (i=0; i<numBranches; i++)
	{
		painter.setPen(branches[i].conditional ? condPen : currentPen);
		int x=280+(branches[i].srcAddr%9)*8;
		QPoint curPos(x-2,branches[i].src);

		if (branches[i].dst<rect().bottom()+200 && branches[i].dst>-200)
		{
			painter.drawLine(curPos, QPoint(x+2,branches[i].src));
			curPos = QPoint(x+2,branches[i].src);
			painter.drawLine(curPos, QPoint(x+2,branches[i].dst));
			curPos = QPoint(x+2,branches[i].dst);
			painter.drawLine(curPos, QPoint(x-4,branches[i].dst));

			curPos = QPoint(x,branches[i].dst-4);
			painter.drawLine(curPos, QPoint(x-4,branches[i].dst));
			curPos = QPoint(x-4,branches[i].dst);
			painter.drawLine(curPos, QPoint(x+1,branches[i].dst+5));
		}
		else
		{
			painter.drawLine(curPos, QPoint(x+4,branches[i].src));
		}
	}
}
Пример #20
0
void QD3D11MultiViewportViewer::mouseMoveEvent( QMouseEvent* event )
{
	Vector2i curPos( event->x(), event->y() );
	Vector2f delta = curPos - m_prevPos;

#if 1

	float pitchSpeed = m_flipMouseUpDown ? m_mousePitchSpeed : -m_mousePitchSpeed;
	const float yawSpeed = 0.005f;
	const float panSpeed = 0.005f;
	const float walkSpeed = -0.005f;

	Matrix3f worldToCamera = m_perspectiveCamera.viewMatrix().getSubmatrix3x3( 0, 0 );
	Matrix3f cameraToWorld = m_perspectiveCamera.inverseViewMatrix().getSubmatrix3x3( 0, 0 );
	
	Vector3f eye = m_perspectiveCamera.eye();
	Vector3f x = m_perspectiveCamera.right();
	Vector3f y = m_perspectiveCamera.up();
	Vector3f z = m_perspectiveCamera.forward();

	// rotate
	if( event->buttons() == Qt::LeftButton )
	{
		// pitch around the local x axis		
		float pitch = pitchSpeed * delta.y;

		Matrix3f pitchMatrix = Matrix3f::rotateX( pitch );		

		y = cameraToWorld * pitchMatrix * worldToCamera * y;
		z = cameraToWorld * pitchMatrix * worldToCamera * z;

		// yaw around the world up vector
		float yaw = yawSpeed * delta.x;

		Matrix3f yawMatrix = m_groundPlaneToWorld * Matrix3f::rotateY( yaw ) * m_worldToGroundPlane;

		x = yawMatrix * x;
		y = yawMatrix * y;
		z = yawMatrix * z;		

		m_perspectiveCamera.setLookAt( eye, eye + z, y );
	}
	// walk
	else if( event->buttons() == Qt::RightButton )
	{
		float dx = panSpeed * delta.x;
		float dz = walkSpeed * delta.y;

		translate( dx, 0, dz );
	}
	// move up/down
	else if( event->buttons() == Qt::MiddleButton )
	{
		float dy = -panSpeed * delta.y;
		translate( 0, dy, 0 );
	}

#else

	if(event->buttons() & Qt::RightButton) //rotate
	{
		float rotSpeed = 0.005f; //radians per pixel
		Quat4f rotation;
		rotation.setAxisAngle(rotSpeed * delta.abs(), Vector3f(-delta[1], -delta[0], 0));
		Matrix3f rotMatrix = Matrix3f::rotation(rotation);
		Matrix3f viewMatrix = m_camera.getViewMatrix().getSubmatrix3x3(0, 0);
		rotMatrix = viewMatrix.transposed() * rotMatrix * viewMatrix;

		Vector3f eye, center, up;
		m_camera.getLookAt(&eye, &center, &up);
		m_camera.setLookAt(center + rotMatrix * (eye - center), center, rotMatrix * up);
	}
	else if(event->buttons() & Qt::LeftButton) //translate
	{
		float speed = 10.f;
		Vector3f screenDelta(delta[0], delta[1], 0);
		screenDelta[0] /= -double(width());
		screenDelta[1] /= double(height());
		Matrix4f iViewProjMatrix = m_camera.getInverseViewProjectionMatrix();
		Vector3f worldDelta = iViewProjMatrix.getSubmatrix3x3(0, 0) * (speed * screenDelta);

		Vector3f eye, center, up;
		m_camera.getLookAt(&eye, &center, &up);
		m_camera.setLookAt(eye + worldDelta, center + worldDelta, up);
	}
#endif

	m_prevPos = curPos;
	update();
}
Пример #21
0
// select on glyph on line
REAL scTextline::Select( scMuPoint& 		charLoc,
						 long&				count,
						 const scMuPoint&	hitPt,
						 eContentMovement,
						 BOOL&				endOfLine )
{
	CharRecordP 	chStop;
	CharRecordP 	chStart;
	CharRecordP 	chRec;
	scSpecRecord	*specRec;
	scMuPoint		curPos( fOrigin );
	scXRect 		extents( fInkExtents ); 
	long			offset;
	MicroPoint		letterSpace;
	BOOL			searchDone	= false;
	BOOL			vertical;
	
	endOfLine		= false;

	vertical		= fColumn->GetFlowdir().IsVertical();

	chStart 		= (CharRecordP)fPara->GetCharArray().Lock();
	
	specRec 		= fPara->GetSpecRun().ptr( );

	letterSpace 	= fLspAdjustment;

	chStop			= chStart + fEndOffset;
	offset			= fStartOffset;
	chRec			= chStart + offset; 
		
	if ( vertical ) {
		curPos.Translate( -fVJOffset, 0 );
		extents.Translate( -fVJOffset, 0 );
	}	
	else {
		curPos.Translate( 0, fVJOffset );
		extents.Translate( 0, fVJOffset );
	}
	
	TypeSpec ts = specRec->spec();
	scCachedStyle::GetCachedStyle( ts );

		// now start the computation
	if ( !searchDone )
		specRec = LNSpecSelect( chRec, chStop, extents, vertical, offset, specRec, letterSpace, curPos, hitPt );		

	if ( offset >= fEndOffset ) {
		endOfLine = true;
		if ( offset == fEndOffset && IsHyphenated() ) {
			count	= offset;
			chRec	= chStart + ( offset - 1 );
			if ( chRec ->character != scBreakingHyphen )
				curPos.x += scCachedStyle::GetCurrentCache().GetEscapement( '-' );
		}
		else
			count = fEndOffset;
	}
	else
		count = offset;

	charLoc = curPos;

	fPara->GetCharArray().Unlock();

		// the hit is within the extents of the line now
		// determine how far from the selected point it
		// is and return the square of the distance
	REAL	x,
			y;

	if ( vertical ) {
		x = (REAL)(hitPt.y - curPos.x);
		y = (REAL)(hitPt.x - curPos.y);
	}
	else {
		x = (REAL)(hitPt.x - curPos.x);
		y = (REAL)(hitPt.y - curPos.y);
	}
	x = x * x;
	y = y * y;
	return( x + y );
}
Пример #22
0
SceneInstance* SceneLoader::doI(istream &str, string &name)
{
    name = getString(str);
    if (name.empty()) {
        *err << "Couldn't read instance name at ";
        errLine(str.tellg());
        return NULL;
    }

    string var = getString(str);
    if (groups[var] == NULL)
    {
        *err << "Instancing node " << var << " which doesn't exist yet at ";
        curPos(*err,str.tellg());
        *err << endl;
        return NULL;
    }

    SceneInstance *n = new SceneInstance();
    instances.push_back(n); //nodes[name] = n;
    n->_name = name;
    n->_child = groups[var];

    do {
        int state = findOpenOrClosedParen(str);
        if (state == ERROR)
            return NULL;
        else if (state == CLOSED)
            return n;
        else if (state == OPEN)
        {
            string cmd;
            vector<ParametricValue*> values;
            if (readCommand(str, cmd)) {

                if (cmd == "R") // load rotations
                {
                    int numv = getValues(str, values);
                    Rotate *r = NULL;
                    if (numv < 1) {
                        *err << "R with no args at ";
                        errLine(str.tellg());
                    } else if (numv < 4) {
                        cleanAfter(values, 1);
                        r = new Rotate();
                        r->angle = values[0];
                    } else {
                        cleanAfter(values, 4);
                        r = new Rotate();
                        r->angle = values[0];
                        for (int i = 0; i < 3; i++)
                            r->axis[i] = values[i+1];
                    }
                    if (r != NULL)
                        n->_transforms.push_back(r);
                }
                else if (cmd == "Xform")
                {
                    int numv = getValues(str, values);
                    GeneralTransform *g = NULL;
                    if (numv < 9) {
                        *err << "Xform with too few parameters at ";
                        errLine(str.tellg());
                    } else if (numv < 16) { // 2d
                        cleanAfter(values, 9);
                        g = new GeneralTransform();
                        for (int i = 0; i < 9; i++)
                            g->matrix.push_back(values[i]);
                    } else {
                        cleanAfter(values, 16);
                        g = new GeneralTransform();
                        for (int i = 0; i < 16; i++)
                            g->matrix.push_back(values[i]);
                    }
                    if (g != NULL)
                        n->_transforms.push_back(g);
                }
                else if (cmd == "T")
                {
                    int numv = getValues(str, values);
                    Translate *t = NULL;
                    if (numv < 2) {
                        *err << "T with too few parameters at ";
                        errLine(str.tellg());
                    } else if (numv == 2) {
                        t = new Translate();
                        for (int i = 0; i < 2; i++)
                            t->translate[i] = values[i];
                    } else {
                        cleanAfter(values, 3);
                        t = new Translate();
                        for (int i = 0; i < 3; i++)
                            t->translate[i] = values[i];
                    }
                    if (t != NULL)
                        n->_transforms.push_back(t);
                }
                else if (cmd == "S")
                {
                    int numv = getValues(str, values);
                    Scale *s = NULL;
                    if (numv < 2) {
                        *err << "S with too few parameters at ";
                        errLine(str.tellg());
                    } else if (numv == 2) {
                        s = new Scale();
                        for (int i = 0; i < 2; i++)
                            s->scale[i] = values[i];
                    } else {
                        s = new Scale();
                        for (int i = 0; i < 3; i++)
                            s->scale[i] = values[i];
                    }
                    if (s != NULL)
                        n->_transforms.push_back(s);
                }
                else if (cmd == "color")
                {
                    int numv = getValues(str, values);
                    ParametricColor *c = NULL;
                    if (numv < 3) {
                        *err << "color with too few parameters at ";
                        errLine(str.tellg());
                    } else {
                        cleanAfter(values, 3);
                        c = new ParametricColor();
                        for (int i = 0; i < 3; i++)
                            c->_color[i] = values[i];
                    }
                    if (c != NULL)
                        n->_color = c;
                }
                else if (cmd == "lod")
                {
                    int numv = getValues(str, values);
                    LOD *l = NULL;
                    if (numv < 1) {
                        *err << "lod with no parameters at ";
                        errLine(str.tellg());
                    } else {
                        //cout << "got lod" << endl;
                        cleanAfter(values, 1);
                        l = new LOD();
                        l->_level = values[0];
                    }
                    if (l != NULL)
                        n->_lod = l;
                }
                else
                {
                    *err << "Error: command " << cmd << " not recognized at ";
                    curPos(*err,str.tellg());
                    *err << endl;
                }
                findCloseParen(str);
            }
        }
    } while (true);
}
Пример #23
0
void SceneLoader::errLine(int at)
{
    curPos(*err, at);
    *err << endl;
}
Пример #24
0
ParametricValue* SceneLoader::getValue(istream &str)
{
    char temp;
    str >> temp;
    if (temp == '{') // time-varying expression
    {
        int start = str.tellg();
        string expr;
        while (str.get(temp))
        {
            if (temp == '}') // completed expr
            {
                ParametricValue *v = new ExprValue(expr.c_str());
                if (!v->good()) {
                    *err << "Error: couldn't parse expression \"" << expr << "\" at ";
                    curPos(*err,str.tellg());
                    *err << endl;
                    delete v;
                    return NULL;
                } else {
                    return v;
                }
            }
            else if (temp == '#')
            {
                string no;
                getline(str, no);
            }
            else {
                expr += temp;
            }
        }
        *err << "Error: No closing brace for expr at ";
        curPos(*err, start);
        *err << endl;
        return NULL;
    }
    else if (temp == ')')
    {
        str.putback(temp);
        return NULL;
    }
    else if (temp == '#')
    {
        string no;
        getline(str,no);
        return getValue(str);
    }
    else
    {
        str.putback(temp);

        double val;
        str.peek();
        str >> val;
        if (str.fail())
        {
            str.clear();
            *err << "Failed to extract a numeric value at ";
            curPos(*err, str.tellg());
            *err << endl;

            str.peek();
            return NULL;
        } else {
            return new ConstValue(val);
        }
    }
}
Пример #25
0
BallTrack::BallTrack(Vector3D* curLoc, double strength, double shootAngle, Vector3D* centerLoc, double level) {

	//strength *= 0.8;
    scoredLocation = -1;
    scored = false;
    int collideNextPoint = 0;
    double step = (strength / 900);
    double xChange = centerLoc->getValueAt(X) - curLoc->getValueAt(X), zChange = centerLoc->getValueAt(Z) - curLoc->getValueAt(Z);
    double d = sqrt(pow(zChange, 2) + pow(xChange, 2));
    double zStep = (step * zChange / d) * cos(shootAngle * PI / 180),
            xStep = (step * xChange / d) * cos(shootAngle * PI / 180), yStep = (step) / cos(shootAngle * PI / 180);
    Vector3D curPos(curLoc);
    Vector3D accelVector(0.0, -0.002, 0.0);
    Vector3D speedVector(xStep, yStep, zStep);
    double ballDiameter = 0.27;
    Bin tempBin(0.6, level, 100); // A bin used just for calculation
    while (scored == false && (route.size() < 350)) {
        route.push_back(new Vector3D(curPos));
        string infoString;
        infoString = "";
        speedVector.add(accelVector);
        curPos.add(speedVector);
        if (curPos.getValueAt(X) >= 8 - ballDiameter || curPos.getValueAt(X) <= -8 + ballDiameter) { // Wall collision
            (curPos.getValueAt(X) < 0) ? curPos.setValueAt(X, -8 + ballDiameter) : curPos.setValueAt(X, 8 - ballDiameter);
            speedVector.changeDirection(X);
            speedVector.setValueAt(X, 0.9 * speedVector.getValueAt(X));
			// Debug
            // infoString = "Wall Hit";
        }
		if (curPos.getValueAt(Y) <= -1.7 || curPos.getValueAt(Y) >= 6) {							// Floor collision
            curPos.getValueAt(Y) < 0 ? curPos.setValueAt(Y, -1.7) : curPos.setValueAt(Y, 6);
            speedVector.changeDirection(Y);
            speedVector.setValueAt(Y, 0.7 * speedVector.getValueAt(Y)); 
			// Debug
            // infoString = "Floor Hit";
        }
        if (curPos.getValueAt(Z) <= 0.5 || curPos.getValueAt(Z) >= 16) {							// Front wall collision
            curPos.getValueAt(Z) <= 0.5 ? curPos.setValueAt(Z, 0.5) : curPos.setValueAt(Z, 16);
            speedVector.changeDirection(Z);
			// Debug
            // infoString = "Wall Hit";
        }

		// Collision with the bin
        if (collideNextPoint == 0) {
            if (curPos.getValueAt(Y) < 0.0 && curPos.getValueAt(Y) > -1.9 && curPos.getValueAt(X) < 1.3 && curPos.getValueAt(X) > -1.3 && curPos.getValueAt(Z) > 1.4 && curPos.getValueAt(Z) < 3.5) { // Bin area
                Vector3D binLoc(0.0, -1, 2.3);
                double closestLength = ballDiameter;
                int closestLocation = -1;
                for (int i = 0; i < tempBin.getfaces(); i++) {
                    Vector3D tempVector = tempBin.getVertexAt(i);
                    tempVector.add(binLoc);
                    double test = curPos.distance(tempVector);
                    if (test < closestLength) {
                        closestLocation = i;
                        closestLength = test;
                    }
                }
                if (closestLocation > 0) {
                    double mag = speedVector.getLength();
                    speedVector.normalize();
                    Vector3D normalVec = tempBin.getNormalAt(closestLocation);
                    double dotProd = -2 * (speedVector.dot(normalVec));
                    normalVec.setValueAt(X, normalVec.getValueAt(X) * dotProd);
                    normalVec.setValueAt(Y, normalVec.getValueAt(Y) * dotProd);
                    normalVec.setValueAt(Z, normalVec.getValueAt(Z) * dotProd);
                    normalVec.add(speedVector);
                    normalVec.setValueAt(X, normalVec.getValueAt(X) * mag * 0.8); 
                    normalVec.setValueAt(Y, normalVec.getValueAt(Y) * mag * 0.8);
                    normalVec.setValueAt(Z, normalVec.getValueAt(Z) * mag * 0.8);
                    speedVector = normalVec;
                    if (curPos.getValueAt(Y) < 1.4) collideNextPoint = 10;
                    else collideNextPoint = 3;
					// Debug
                    // infoString = "Bin hit";
                }
            }
        } else {
            collideNextPoint--;
        }

        //Scored?
        if (((curPos.getValueAt(Y) < -1.05 && curPos.getValueAt(Y) > -1.5))//-1.3
                && (((curPos.getValueAt(Z) > 1.9 && curPos.getValueAt(Z) < 2.6) && (curPos.getValueAt(X) < 0.4 && curPos.getValueAt(X)> -0.4) && speedVector.getValueAt(Y) < 0))) {
            // Debug
			// infoString = "Scores!!!";
            scored = true;
            if (scoredLocation < 0) scoredLocation = route.size();
        }
        if (infoString == "" && information.size() != 0) infoString = information[information.size() - 1];
        information.push_back(infoString);
    }
}
Пример #26
0
bool SceneLoader::buildScene(string filename)
{
    buildEndlineTable(filename);

    ifstream file(filename.c_str());
    string line;
    int lastPos = 0;
    while (findOpenParen(file))
    {
        cout << "found open paren" << endl;
        file.tellg();
        if (readCommand(file, line)) {
            if (line == "Include")
            {
                string instName;
                if (doInclude(file, instName))
                {
                    cout << "included " << instName << endl;
                }
                else
                {
                    cout << "mangled include at ";
                    curPos(cout, file.tellg());
                    cout << endl;
                }
            }
            else if (line == "Sphere")
            {
                string gname;
                if (doSphere(file, gname))
                {
                    cout << "read sphere " << gname << endl;
                }
                else
                {
                    *err << "mangled sphere command at ";
                    errLine(file.tellg());
                }
            }
            else if (line == "Material")
            {
                string gname;
                if (doMaterial(file, gname))
                {
                    cout << "read material " << gname << endl;
                }
                else
                {
                    *err << "mangled material command at ";
                    errLine(file.tellg());
                }
            }
            else if (line == "Light")
            {
                string gname;
                if (doLight(file, gname))
                {
                    cout << "read light " << gname << endl;
                }
                else
                {
                    *err << "mangled light command at ";
                    errLine(file.tellg());
                }
            }
            else if (line == "Camera")
            {
                string gname;
                if (doCamera(file, gname))
                {
                    cout << "read camera " << gname << endl;
                }
                else
                {
                    *err << "mangled camera command at ";
                    errLine(file.tellg());
                }
            }
            else if (line == "I")
            {
                *err << "Error: Instance commands must belong to a group, but I found in global scope at ";
                errLine(file.tellg());
                /*string iname; // code to handle I at global scope (doesn't make much sense now that instance names skip the names table)
                if (doI(file, iname))
                {
                    cout << "got an instance named " << iname << endl;
                }*/
            }
            else if (line == "G")
            {
                string iname;
                if (doG(file, iname))
                {
                    cout << "got a group named " << iname << endl;
                }
            }
            else if (line == "Render")
            {
                string iname;
                if (doRender(file, iname))
                {
                    cout << "did render " << iname << endl;
                }
            }
            else
            {
                *err << "command not recognized: " << line << endl;
            }
            findCloseParen(file);
        } else {

        }

        lastPos = file.tellg();
    }

    return true;
}
Пример #27
0
MStatus geometrySurfaceConstraint::compute( const MPlug& plug, MDataBlock& block )
{	
	MStatus returnStatus;
 
    if(plug == constraintTranslateX || plug == constraintTranslateY || plug == constraintTranslateZ) {
        if(!m_isInitd) {
// read rest position
            MDataHandle htgo = block.inputValue(targetRestP);
            double3 & tgo = htgo.asDouble3();
            MGlobal::displayInfo(MString("target rest p ")+tgo[0]+" "+tgo[1]+" "+tgo[2]);
            m_restPos = MPoint(tgo[0],tgo[1],tgo[2]);
			m_isInitd = true;
		}
		
		MArrayDataHandle targetArray = block.inputArrayValue( compoundTarget );
		const unsigned int targetArrayCount = targetArray.elementCount();
        MMatrix tm;
        tm.setToIdentity();
        unsigned int i;
		for ( i = 0; i < targetArrayCount; i++ ) {
            MDataHandle targetElement = targetArray.inputValue(&returnStatus);
            if(!returnStatus) {
                MGlobal::displayInfo("failed to get input value target element");
            }
            MDataHandle htm = targetElement.child(targetTransform);
            MFnMatrixData ftm(htm.data(), &returnStatus);
            if(!returnStatus) {
                MGlobal::displayInfo("failed to get matrix data");
            }
            tm = ftm.matrix();
            targetArray.next();
        }
		
		MDataHandle hparentInvMat = block.inputValue(constraintParentInverseMatrix);
		MMatrix parentInvMat = hparentInvMat.asMatrix();

// world position
        MPoint curPos(tm(3,0), tm(3,1), tm(3,2));
// offset in local space
		m_offsetToRest = m_restPos - curPos;
// object position in world space
		MPoint localP = m_offsetToRest * tm + curPos;
// in local space
		localP *= parentInvMat;

        MDataHandle hout;
        if(plug == constraintTranslateX) {
            hout = block.outputValue(constraintTranslateX);
			hout.set(localP.x);
        }
        else if(plug == constraintTranslateY) {
            hout = block.outputValue(constraintTranslateY);
			hout.set(localP.y);
        }
        else if(plug == constraintTranslateZ) {
            hout = block.outputValue(constraintTranslateZ);
			hout.set(localP.z);
        }
		
		//MPlug pgTx(thisMObject(), constraintTargetX);
		//pgTx.setValue(m_lastPos.x);
		//MPlug pgTy(thisMObject(), constraintTargetY);
		//pgTy.setValue(m_lastPos.y);
		//MPlug pgTz(thisMObject(), constraintTargetZ);
		//pgTz.setValue(m_lastPos.z);
		
		MPlug pgOx(thisMObject(), constraintObjectX);
		pgOx.setValue(m_offsetToRest.x);
		MPlug pgOy(thisMObject(), constraintObjectY);
		pgOy.setValue(m_offsetToRest.y);
		MPlug pgOz(thisMObject(), constraintObjectZ);
		pgOz.setValue(m_offsetToRest.z);
        
       // MFnNumericData nd;
		//MObject offsetData = nd.create( MFnNumericData::k3Double);
        //nd.setData3Double(m_lastPos.x, m_lastPos.y, m_lastPos.z);
        //MPlug pgTgo(thisMObject(), targetOffset);
        //pgTgo.setValue(offsetData); 
    }
	else
		return MS::kUnknownParameter;

	return MS::kSuccess;
}
/**
 *  Zeichnet einen Text.
 *
 *  @param[in] x      X-Koordinate
 *  @param[in] y      Y-Koordinate
 *  @param[in] text   Der Text
 *  @param[in] format Format des Textes (verodern)
 *                      @p FontStyle::LEFT    - Text links ( standard )
 *                      @p FontStyle::CENTER  - Text mittig
 *                      @p FontStyle::RIGHT   - Text rechts
 *                      @p FontStyle::TOP     - Text oben ( standard )
 *                      @p FontStyle::VCENTER - Text vertikal zentriert
 *                      @p FontStyle::BOTTOM  - Text unten
 *  @param[in] color  Farbe des Textes
 *  @param[in] length Länge des Textes
 *  @param[in] max    maximale Länge
 *  @param     end    Suffix for displaying a truncation of the text (...)
 */
void glArchivItem_Font::Draw(DrawPoint pos, const std::string& text, FontStyle format, unsigned color, unsigned short length,
                             unsigned short maxWidth, const std::string& end)
{
    if(!fontNoOutline)
        initFont();

    RTTR_Assert(isValidUTF8(text));

    // Breite bestimmen
    if(length == 0)
        length = (unsigned short)text.length();

    unsigned maxNumChars;
    unsigned short textWidth;
    bool drawEnd;
    if(maxWidth == 0xFFFF)
    {
        maxNumChars = length;
        textWidth = getWidth(text, length);
        drawEnd = false;
    } else
    {
        RTTR_Assert(isValidUTF8(end));
        textWidth = getWidth(text, length, maxWidth, &maxNumChars);
        if(!end.empty() && maxNumChars < length)
        {
            unsigned short endWidth = getWidth(end);

            // If "end" does not fit, draw nothing
            if(textWidth < endWidth)
                return;

            // Wieviele Buchstaben gehen in den "Rest" (ohne "end")
            textWidth = getWidth(text, length, textWidth - endWidth, &maxNumChars) + endWidth;
            drawEnd = true;
        } else
            drawEnd = false;
    }

    if(maxNumChars == 0)
        return;
    auto itEnd = text.cbegin();
    std::advance(itEnd, maxNumChars);

    // Vertical alignment (assumes 1 line only!)
    if(format.is(FontStyle::BOTTOM))
        pos.y -= dy;
    else if(format.is(FontStyle::VCENTER))
        pos.y -= dy / 2;
    // Horizontal center must change current line only. Everything else changes the start point
    DrawPoint curPos(pos);
    // Horizontal alignment
    if(format.is(FontStyle::RIGHT))
        curPos.x = pos.x -= textWidth;
    else if(format.is(FontStyle::CENTER))
    {
        unsigned short line_width;
        const auto itNl = std::find(text.cbegin(), itEnd, '\n');
        if(itNl != itEnd)
            line_width = getWidthInternal(text.cbegin(), itNl);
        else
            line_width = textWidth;
        curPos.x = pos.x - line_width / 2;
    }

    texList.texCoords.clear();
    texList.vertices.clear();

    for(auto it = text.begin(); it != itEnd;)
    {
        const uint32_t curChar = utf8::next(it, itEnd);
        if(curChar == '\n')
        {
            if(format.is(FontStyle::CENTER))
            {
                unsigned short line_width;
                const auto itNl = std::find(it, itEnd, '\n');
                line_width = getWidthInternal(it, itNl);
                curPos.x = pos.x - line_width / 2;
            } else
                curPos.x = pos.x;
            curPos.y += dy;
        } else
            DrawChar(curChar, texList, curPos);
    }

    if(drawEnd)
    {
        for(auto it = end.begin(); it != end.end();)
        {
            const uint32_t curChar = utf8::next(it, end.end());
            if(curChar == '\n')
            {
                curPos.x = pos.x;
                curPos.y += dy;
            } else
                DrawChar(curChar, texList, curPos);
        }
    }

    if(texList.vertices.empty())
        return;

    // Get texture first as it might need to be created
    glArchivItem_Bitmap& usedFont = format.is(FontStyle::NO_OUTLINE) ? *fontNoOutline : *fontWithOutline;
    unsigned texture = usedFont.GetTexture();
    if(!texture)
        return;
    const GlPoint texSize(usedFont.GetTexSize());
    RTTR_Assert(texList.texCoords.size() == texList.vertices.size());
    RTTR_Assert(texList.texCoords.size() % 4u == 0);
    // Vectorizable loop
    for(unsigned i = 0; i < texList.texCoords.size(); i += 4)
    {
        for(int j = 0; j < 4; j++)
            texList.texCoords[i + j] /= texSize;
    }

    glVertexPointer(2, GL_FLOAT, 0, &texList.vertices[0]);
    glTexCoordPointer(2, GL_FLOAT, 0, &texList.texCoords[0]);
    VIDEODRIVER.BindTexture(texture);
    glColor4ub(GetRed(color), GetGreen(color), GetBlue(color), GetAlpha(color));
    glDrawArrays(GL_QUADS, 0, texList.vertices.size());
}
/**
 *  @brief
 */
void glArchivItem_Font::initFont()
{
    ClearCharInfoMapping();
    fontWithOutline = libsiedler2::getAllocator().create<glArchivItem_Bitmap>(libsiedler2::BOBTYPE_BITMAP_RLE);
    fontNoOutline = libsiedler2::getAllocator().create<glArchivItem_Bitmap>(libsiedler2::BOBTYPE_BITMAP_RLE);

    // first, we have to find how much chars we really have
    unsigned numChars = 0;
    for(unsigned i = 0; i < size(); ++i)
    {
        if(get(i))
            ++numChars;
    }

    if(numChars == 0)
        return;

    const auto numCharsPerLine = static_cast<unsigned>(std::sqrt(static_cast<double>(numChars)));
    // Calc lines required (rounding up)
    const unsigned numLines = (numChars + numCharsPerLine - 1) / numCharsPerLine;

    constexpr Extent spacing(1, 1);
    Extent texSize = (Extent(dx, dy) + spacing * 2u) * Extent(numCharsPerLine, numLines) + spacing * 2u;
    libsiedler2::PixelBufferARGB bufferWithOutline(texSize.x, texSize.y);
    libsiedler2::PixelBufferARGB bufferNoOutline(texSize.x, texSize.y);

    const libsiedler2::ArchivItem_Palette* const palette = LOADER.GetPaletteN("colors");
    Position curPos(spacing);
    numChars = 0;
    for(unsigned i = 0; i < size(); ++i)
    {
        const auto* c = dynamic_cast<const libsiedler2::ArchivItem_Bitmap_Player*>(get(i));
        if(!c)
            continue;

        if((numChars % numCharsPerLine) == 0 && numChars > 0)
        {
            curPos.y += dy + spacing.y * 2;
            curPos.x = spacing.x;
        }

        // Spezialpalette (blaue Spielerfarben sind Grau) verwenden, damit man per OpenGL einfärben kann!
        c->print(bufferNoOutline, palette, 128, curPos.x, curPos.y, 0, 0, 0, 0, true);
        c->print(bufferWithOutline, palette, 128, curPos.x, curPos.y);

        CharInfo ci(curPos, std::min<unsigned short>(dx + 2, c->getWidth()));

        AddCharInfo(i, ci);
        curPos.x += dx + spacing.x * 2;
        ++numChars;
    }

    fontNoOutline->create(bufferNoOutline);
    fontWithOutline->create(bufferWithOutline);

    // Set the placeholder for non-existant glyphs. Use '?' (should always be possible)
    if(CharExist('?'))
        placeHolder = GetCharInfo('?');
    else
    {
        // Fall back to first glyph in map (kinda random, but should not happen anyway)
        LOG.writeToFile("Cannot find '?' glyph in font!");
        throw std::runtime_error("Cannot find '?' glyph in font. What shall I use as fallback?");
    }

#ifdef RTTR_PRINT_FONTS
    Archiv items;
    items.pushC(*fontNoOutline);
    libsiedler2::Write("font" + getName() + "_noOutline.bmp", items);
    items.setC(0, *fontWithOutline);
    libsiedler2::Write("font" + getName() + "_Outline.bmp", items);
#endif
}
Пример #30
0
///////////////////////////////////////////////////////////////////////////////
/// @brief Finds the shortest path from start to any target in the list, avoiding units and walls.  A path will never be found if all targets are occupied or contains a wall.  Returns true if and only if a path was found.
///
/// @param path If the return value is true, path will contain the shortest path from start to the nearest target.
/// @param start Where pathing is to start from.
/// @param targetList A list of target destinations.
///////////////////////////////////////////////////////////////////////////////
bool baseAI::findPath(vector<Coordinate>& path,
                    const Coordinate start,
                    const vector<Coordinate> targetList)
{
  int dis[26][26];
  int via[26][26];
  bool success = false;
  bool changing = true;
  int newVal;
  static bool first = true;

  //via
  //    1
  // 2     0
  //    3

  if (start.x() < 0 || start.y() < 0 || start.x() > 25 || start.y() > 25)
  {
    cout << "Error: Path was called with a start coordinate that was out of bounds.";
    return false;
  }

  for (int i = 0; i < targetList.size(); i++)
  {
    if (targetList[i].x() < 0 || targetList[i].y() < 0 || targetList[i].x() > 25 || targetList[i].y() > 25)
    {
      cout << "Error: Path was called with a target coordinate that was out of bounds.";
      return false;
    }
  }

  if (first)
  {
    first = false;
    plotWalls();
  }

  plotUnits();

  for (int x = 0; x < 26; x++)
  {
    for (int y = 0; y < 26; y++)
    {
      dis[x][y] = 999;
      via[x][y] = -1;
    }
  }

  for (int i = 0; i < targetList.size(); i++)
  {
    if (!occupied[targetList[i].x()][targetList[i].y()] && !walled[targetList[i].x()][targetList[i].y()])
      dis[targetList[i].x()][targetList[i].y()] = 0;
  }

  while (changing)
  {
    changing = false;
    for (int x = 0; x < 26; x++)
    {
      for (int y = 0; y < 26; y++)
      {
        if (!walled[x][y] && (!occupied[x][y] || start == Coordinate(x,y)))
        {
          //newVal = dis[x][y];
          if (x > 0)
          {
            if (dis[x-1][y]+1 < dis[x][y])
            {
              dis[x][y] = dis[x-1][y]+1;
              via[x][y] = 2;
              changing = true;
            }
          }
          if (x < 25)
          {
            if (dis[x+1][y]+1 < dis[x][y])
            {
              dis[x][y] = dis[x+1][y]+1;
              via[x][y] = 0;
              changing = true;
            }
          }
          if (y > 0)
          {
            if (dis[x][y-1]+1 < dis[x][y])
            {
              dis[x][y] = dis[x][y-1]+1;
              via[x][y] = 3;
              changing = true;
            }
          }
          if (y < 25)
          {
            if (dis[x][y+1]+1 < dis[x][y])
            {
              dis[x][y] = dis[x][y+1]+1;
              via[x][y] = 1;
              changing = true;
            }
          }
        }
      }
    }
  }

  path.clear();

  Coordinate curPos(start.x(), start.y());

  if (via[start.x()][start.y()] == -1)
  {
    success = false;
  }
  else
  {
    success = true;
    while (dis[curPos.x()][curPos.y()] != 0)
    {
      switch (via[curPos.x()][curPos.y()])
      {
      case 0:
        curPos = curPos + Coordinate(1, 0);
      break;
      case 1:
        curPos = curPos + Coordinate(0, 1);
      break;
      case 2:
        curPos = curPos + Coordinate(-1, 0);
      break;
      case 3:
        curPos = curPos + Coordinate(0, -1);
      break;
      }
      path.push_back(curPos);
    }
  }
  return success;
}