Ejemplo n.º 1
0
void CommunicationInterface::onRequestInformation(std::shared_ptr<Entity> const &entity,
                                                  std::vector<std::shared_ptr<InformationSpecification>> const &requests)
{
  _log->info("Information request received from '%v'", entity->toString());
  std::vector<std::shared_ptr<InformationElement<GContainer>>> infos;

  for (auto &request : requests)
  {
    this->bridge->informationStore->getInformation(request,infos);
  }

  int count = infos.size();
  if (count == 0)
  {
    _log->warn("No information found for request from '%v'", entity->toString());
    return;
  }


  _log->info("Sending '%v' information to '%v'", count, entity->toString());
  for (auto &info : infos)
  {
    auto m = std::make_shared<InformationMessage>();
    m->setEntity(entity);
    m->getInformations().push_back(info);
    this->sendMessage(m);
  }
}
Ejemplo n.º 2
0
/**
* Creates a tangent between a given point and a circle or arc.
* Out of the 2 possible tangents, the one closest to
* the given coordinate is returned.
*
* @param coord Coordinate to define which tangent we want (typically a
*              mouse coordinate).
* @param point Point.
* @param circle Circle, arc or ellipse entity.
*/
RS_Line* RS_Creation::createTangent1(const RS_Vector& coord,
                                     const RS_Vector& point,
                                     RS_Entity* circle) {
	RS_Line* ret = nullptr;
    //RS_Vector circleCenter;

    // check given entities:
	if(! (circle && point.valid)) return nullptr;
	if( !( circle->isArc() || circle->rtti()==RS2::EntitySplinePoints))
		return nullptr;

    // the two tangent points:
    RS_VectorSolutions sol=circle->getTangentPoint(point);

	if(sol.getNumber()==0) return nullptr;
    RS_Vector vp2(sol.getClosest(coord));
    RS_LineData d;
    if( (vp2-point).squared() > RS_TOLERANCE2 ) {
        d=RS_LineData(vp2,point);
    }else{//the given point is a tangential point
        d=RS_LineData(point+circle->getTangentDirection(point),point);
    }


    // create the closest tangent:

	if (document && handleUndo) {
        document->startUndoCycle();
    }

    ret = new RS_Line(container, d);
	setEntity(ret);

    return ret;
}
Ejemplo n.º 3
0
	void QTEntityParametersWidget::setEntity(int idx)
	{
		Entity* entity = SceneManager::getInstance()->getCurrentScene()->getEntity(idx);
		setEntity(entity);
		ui.titleEdit->setText(QString::fromStdString(entity->getName()));
		updateTransformView();
	}
Ejemplo n.º 4
0
//////////////////////////////////////////////////////////////////////////
// high level scripting interface
//////////////////////////////////////////////////////////////////////////
bool UIEntity::scCallMethod(ScScript *script, ScStack *stack, ScStack *thisStack, const char *name) {
	//////////////////////////////////////////////////////////////////////////
	// GetEntity
	//////////////////////////////////////////////////////////////////////////
	if (strcmp(name, "GetEntity") == 0) {
		stack->correctParams(0);

		if (_entity) {
			stack->pushNative(_entity, true);
		} else {
			stack->pushNULL();
		}

		return STATUS_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// SetEntity
	//////////////////////////////////////////////////////////////////////////
	else if (strcmp(name, "SetEntity") == 0) {
		stack->correctParams(1);

		const char *filename = stack->pop()->getString();

		if (DID_SUCCEED(setEntity(filename))) {
			stack->pushBool(true);
		} else {
			stack->pushBool(false);
		}

		return STATUS_OK;
	} else {
		return UIObject::scCallMethod(script, stack, thisStack, name);
	}
}
Ejemplo n.º 5
0
void CommunicationInterface::requestOffers(std::shared_ptr<Entity> const &entity)
{
  _log->info("Requesting offered information from '%v'", entity->toString());
  auto m = std::make_shared<CommandMessage>(IceCmd::SCMD_OFFERS_REQUEST);
  m->setEntity(entity);

  this->pushMessage(m);
}
Ejemplo n.º 6
0
/**
 * Creates a line parallel to the given line e.
 * Out of the 2 possible parallels, the one closest to
 * the given coordinate is returned.
 *
 * @param coord Coordinate to define which parallel we want (typically a
 *              mouse coordinate).
 * @param distance Distance of the parallel.
 * @param number Number of parallels.
 * @param e Original entity.
 *
 * @return Pointer to the first created parallel or nullptr if no
 *    parallel has been created.
 */
RS_Line* RS_Creation::createParallelLine(const RS_Vector& coord,
                                         double distance, int number,
                                         RS_Line* e) {

	if (e==nullptr) {
		return nullptr;
    }

	double ang = e->getAngle1() + M_PI_2;
    RS_Vector p1, p2;
    RS_LineData parallelData;
	RS_Line* ret = nullptr;

	if (document && handleUndo) {
        document->startUndoCycle();
    }

    for (int num=1; num<=number; ++num) {

        // calculate 1st parallel:
        p1.setPolar(distance*num, ang);
        p1 += e->getStartpoint();
        p2.setPolar(distance*num, ang);
        p2 += e->getEndpoint();
		RS_Line parallel1(nullptr, RS_LineData(p1, p2));

        // calculate 2nd parallel:
        p1.setPolar(distance*num, ang+M_PI);
        p1 += e->getStartpoint();
        p2.setPolar(distance*num, ang+M_PI);
        p2 += e->getEndpoint();
		RS_Line parallel2(nullptr, RS_LineData(p1, p2));

        double dist1 = parallel1.getDistanceToPoint(coord);
        double dist2 = parallel2.getDistanceToPoint(coord);
        double minDist = std::min(dist1, dist2);

        if (minDist<RS_MAXDOUBLE) {
            if (dist1<dist2) {
                parallelData = parallel1.getData();
            } else {
                parallelData = parallel2.getData();
            }

            RS_Line* newLine = new RS_Line(container, parallelData);
			if (ret==nullptr) {
				ret = newLine;
			}
			setEntity(newLine);
        }
    }

	if (document && handleUndo) {
        document->endUndoCycle();
    }

    return ret;
}
Ejemplo n.º 7
0
/**
 * Creates a arc parallel to the given arc e.
 * Out of the 2 possible parallels, the one closest to
 * the given coordinate is returned.
 *
 * @param coord Coordinate to define which parallel we want (typically a
 *              mouse coordinate).
 * @param distance Distance of the parallel.
 * @param number Number of parallels.
 * @param e Original entity.
 *
 * @return Pointer to the first created parallel or nullptr if no
 *    parallel has been created.
 */
RS_Arc* RS_Creation::createParallelArc(const RS_Vector& coord,
                                       double distance, int number,
                                       RS_Arc* e) {

	if (!e) {
		return nullptr;
    }

    RS_ArcData parallelData;
	RS_Arc* ret = nullptr;

    bool inside = (e->getCenter().distanceTo(coord) < e->getRadius());

    if (inside) {
        distance *= -1;
    }

    for (int num=1; num<=number; ++num) {

        // calculate parallel:
        bool ok = true;
		RS_Arc parallel1(nullptr, e->getData());
        parallel1.setRadius(e->getRadius() + distance*num);
        if (parallel1.getRadius()<0.0) {
            parallel1.setRadius(RS_MAXDOUBLE);
            ok = false;
        }

        // calculate 2nd parallel:
		//RS_Arc parallel2(nullptr, e->getData());
        //parallel2.setRadius(e->getRadius()+distance*num);

        //double dist1 = parallel1.getDistanceToPoint(coord);
        //double dist2 = parallel2.getDistanceToPoint(coord);
        //double minDist = min(dist1, dist2);

        //if (minDist<RS_MAXDOUBLE) {
		if (ok) {
            //if (dist1<dist2) {
            parallelData = parallel1.getData();
            //} else {
            //    parallelData = parallel2.getData();
            //}

			if (document && handleUndo) {
                document->startUndoCycle();
            }

            RS_Arc* newArc = new RS_Arc(container, parallelData);
			if (!ret) {
				ret = newArc;
			}
			setEntity(newArc);
        }
    }

    return ret;
}
Ejemplo n.º 8
0
void CommunicationInterface::onRequestIds(std::shared_ptr<Entity> const &entity)
{
  _log->info("Sending Ids to '%v'", entity->toString());
  auto m = std::make_shared<IdMessage>();
  m->setEntity(entity);
  this->self->pushIds(m->getIds());

  this->pushMessage(m);
}
Ejemplo n.º 9
0
void OgreEntityRenderer::unloadEntity()
{
	setEntity(nullptr);
	if (mEntity) {
		Ogre::SceneManager* scenemgr = mTexture->getRenderContext()->getSceneManager();
		scenemgr->destroyEntity(mEntity);
		mEntity = nullptr;
	}
}
Ejemplo n.º 10
0
/**
 * Creates a bisecting line of the angle between the entities
 * e1 and e2. Out of the 4 possible bisectors, the one closest to
 * the given coordinate is returned.
 *
 * @param coord Coordinate to define which bisector we want (typically a
 *              mouse coordinate).
 * @param length Length of the bisecting line.
 * @param num Number of bisectors
 * @param l1 First line.
 * @param l2 Second line.
 *
 * @return Pointer to the first bisector created or nullptr if no bisectors
 *   were created.
 */
RS_Line* RS_Creation::createBisector(const RS_Vector& coord1,
                                     const RS_Vector& coord2,
                                     double length,
                                     int num,
                                     RS_Line* l1,
                                     RS_Line* l2) {

    RS_VectorSolutions sol;
    // check given entities:
	if( ! (l1 && l2)) return nullptr;
	if(! (l1->rtti()==RS2::EntityLine && l1->rtti()==RS2::EntityLine)) return nullptr;

    // intersection between entities:
    sol = RS_Information::getIntersection(l1, l2, false);
    RS_Vector inters = sol.get(0);
    if (inters.valid==false) {
		return nullptr;
    }

    double angle1 = inters.angleTo(l1->getNearestPointOnEntity(coord1));
    double angle2 = inters.angleTo(l2->getNearestPointOnEntity(coord2));
    double angleDiff = RS_Math::getAngleDifference(angle1, angle2);
    if (angleDiff>M_PI) {
		angleDiff = angleDiff - 2.*M_PI;
    }
	RS_Line* ret = nullptr;

	if (document && handleUndo) {
        document->startUndoCycle();
    }

    for (int n=1; n<=num; ++n) {

        double angle = angle1 +
                (angleDiff / (num+1) * n);

        RS_LineData d;
        RS_Vector v;

        v.setPolar(length, angle);
        d = RS_LineData(inters, inters + v);

        RS_Line* newLine = new RS_Line(container, d);
		if (ret==nullptr) {
			ret = newLine;
		}
		setEntity(newLine);
    }
	if (document && handleUndo) {
        document->endUndoCycle();
    }

    return ret;
}
Ejemplo n.º 11
0
/**
     * Creates an image with the given data.
     */
RS_Image* RS_Creation::createImage(const RS_ImageData* data) {

	if (document && handleUndo) {
        document->startUndoCycle();
    }

	RS_Image* img = new RS_Image(container, *data);
    img->update();
	setEntity(img);

    return img;
}
Ejemplo n.º 12
0
void OgreEntityRenderer::showEntity(const std::string& mesh)
{
	unloadEntity();
	try {
		std::string entityName(mTexture->getImage()->getName().c_str());
		entityName += "_entity";
		mEntity = mTexture->getRenderContext()->getSceneNode()->getCreator()->createEntity(entityName, mesh);
		setEntity(mEntity);
		mTexture->getRenderContext()->setActive(true);
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when creating entity." << ex);
	}
}
Ejemplo n.º 13
0
void CommunicationInterface::onRequestOffers(std::shared_ptr<Entity> const &entity)
{
  _log->info("Sending offered information to '%v'", entity->toString());
  auto m = std::make_shared<OffersMessage>();
  m->setEntity(entity);

  auto &vec = m->getOfferes();
  for (auto info : this->bridge->getOfferedInfos())
  {
    vec.push_back(info->infoSpec);
  }

  this->pushMessage(m);
}
Ejemplo n.º 14
0
void CommunicationInterface::requestInformation(std::shared_ptr<Entity> const &entity,
                                std::vector<std::shared_ptr<InformationSpecification>> const &requests)
{
  _log->info("Requesting information from '%v'", entity->toString());
  auto m = std::make_shared<RequestMessage>();
  m->setEntity(entity);

  auto &vec = m->getRequests();
  for (auto info : requests)
  {
    vec.push_back(info);
  }

  this->pushMessage(m);
}
Ejemplo n.º 15
0
/**
     * Creates an insert with the given data.
     *
     * @param data Insert data (position, block name, ..)
     */
RS_Insert* RS_Creation::createInsert(const RS_InsertData* pdata) {

    RS_DEBUG->print("RS_Creation::createInsert");

	if (document && handleUndo) {
        document->startUndoCycle();
    }

	RS_Insert* ins = new RS_Insert(container, *pdata);
    // inserts are also on layers
	setEntity(ins);

    RS_DEBUG->print("RS_Creation::createInsert: OK");

    return ins;
}
Ejemplo n.º 16
0
/**
     * Creates a line with a relative angle to the given entity.
     *
     * @param coord Coordinate to define the point where the line should end.
     *              (typically a mouse coordinate).
     * @param entity Pointer to basis entity. The angle is relative to the
     *               angle of this entity.
     * @param angle Angle of the line relative to the angle of the basis entity.
     * @param length Length of the line we're creating.
     */
RS_Line* RS_Creation::createLineRelAngle(const RS_Vector& coord,
                                         RS_Entity* entity,
                                         double angle,
                                         double length) {

    // check given entity / coord:
	if (entity==nullptr || !coord.valid ||
            (entity->rtti()!=RS2::EntityArc && entity->rtti()!=RS2::EntityCircle
             && entity->rtti()!=RS2::EntityLine)) {

		return nullptr;
    }

    double a1=0.0;

    switch (entity->rtti()) {
    case RS2::EntityLine:
        a1 = ((RS_Line*)entity)->getAngle1();
        break;
    case RS2::EntityArc:
		a1 = ((RS_Arc*)entity)->getCenter().angleTo(coord) + M_PI_2;
        break;
    case RS2::EntityCircle:
        a1 = ((RS_Circle*)entity)->getCenter().angleTo(coord);
        break;
    default:
        // never reached
        break;
    }

    a1 += angle;

    RS_Vector v1;
    v1.setPolar(length, a1);
    //RS_ConstructionLineData(coord-v1, coord+v1);
    RS_LineData d(coord-v1, coord+v1);
    RS_Line* ret;

	if (document && handleUndo) {
        document->startUndoCycle();
    }

    ret = new RS_Line(container, d);
	setEntity(ret);

    return ret;
}
Ejemplo n.º 17
0
	void RTTLayer::deserialization(xml::ElementPtr _node, Version _version)
	{
		Base::deserialization(_node, _version);

		MyGUI::xml::ElementEnumerator propert = _node->getElementEnumerator();
		while (propert.next("Property"))
		{
			const std::string& key = propert->findAttribute("key");
			const std::string& value = propert->findAttribute("value");
			if (key == "TextureSize") setTextureSize(utility::parseValue<IntSize>(value));
#ifdef MYGUI_OGRE_PLATFORM
			else if (key == "Entity") setEntity(value);
			else if (key == "Material") setMaterial(value);
			else if (key == "SceneManager") setSceneManager(value);
			else if (key == "Camera") setCamera(value);
#endif
		}
	}
Ejemplo n.º 18
0
void getEntities( std::string path )
{
	DIR *dir;
	struct dirent *ent;
	if( ( dir = opendir( path.c_str() ) ) != NULL )
	{
		while( ( ent = readdir( dir ) ) != NULL)
		{
			if( ent->d_type == DT_REG )
			{
				setEntity( ent->d_name, path + "/"+ ent->d_name );
			}
		}
		closedir (dir);
	}
	else
	{
		Log::exit_error("Unable to access directory " + path );
	}
}
Ejemplo n.º 19
0
void RenderSystem::receive(const ComponentAddedEvent<SpriteComponent> &spriteAddedEvent)
{
	auto sprite = spriteAddedEvent.component->sprite;

	auto director = Director::getInstance();
	auto currentScene = director->getRunningScene();
	auto gameLayer = currentScene->getChildByTag(GAME_LAYER);

	if (gameLayer)
	{
		auto batchNode = gameLayer->getChildByTag(MAIN_SPRITEBATCHNODE);
		if (batchNode)
		{
            sprite->setEntity(spriteAddedEvent.entity);
			batchNode->addChild(sprite);
		}
		else CCLOG("batchNode: NULL REFERENCE, RenderSystem, spriteAddedEvent");
	}
	else CCLOG("gameLayer: NULL REFERENCE, RenderSystem, spriteAddedEvent");
}
Ejemplo n.º 20
0
void vApplyForcesAction::SetEntity(vHavokRigidBody *pRigidBody)
{
  hkpWorld *pHavokWorld = vHavokPhysicsModule::GetInstance()->GetPhysicsWorld();
  pHavokWorld->lock();
  if (pRigidBody)
  {
    hkpRigidBody* pRB = pRigidBody->GetHkRigidBody();
    setEntity(pRB);
    pHavokWorld->addAction(this);
    m_bActionAdded = true;
  }
  else
  {
    if (hkpUnaryAction::getWorld())
    {
      pHavokWorld->removeAction(this);
      m_bActionAdded = false;
    }
  }
  pHavokWorld->unlock();
}
Ejemplo n.º 21
0
Bubble::Bubble(NotificationEntity *entity)
    : DBlurEffectWidget(nullptr)
    , m_entity(entity)
    , m_icon(new AppIcon(this))
    , m_body(new AppBody(this))
    , m_actionButton(new ActionButton(this))
    , m_quitTimer(new QTimer(this))

{
    m_quitTimer->setInterval(60 * 1000);
    m_quitTimer->setSingleShot(true);

    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);

    m_wmHelper = DWindowManagerHelper::instance();

    m_handle = new DPlatformWindowHandle(this);
    m_handle->setTranslucentBackground(true);
    m_handle->setShadowRadius(14);
    m_handle->setShadowOffset(QPoint(0, 4));

    compositeChanged();

    setBlendMode(DBlurEffectWidget::BehindWindowBlend);
    setMaskColor(DBlurEffectWidget::LightColor);

    initUI();
    initAnimations();
    initTimers();

    setEntity(entity);

    connect(m_wmHelper, &DWindowManagerHelper::hasCompositeChanged, this, &Bubble::compositeChanged);
    connect(m_quitTimer, &QTimer::timeout, this, &Bubble::onDelayQuit);
}
Ejemplo n.º 22
0
/**
 * Creates a spline pseudo-parallel to the given circle e.
 * Out of the 2 possible parallels, the one closest to
 * the given coordinate is returned.
 *
 * @param coord Coordinate to define which parallel we want (typically a
 *              mouse coordinate).
 * @param distance Distance of the parallel.
 * @param number Number of parallels.
 * @param e Original entity.
 *
 * @return Pointer to the first created parallel or nullptr if no
 *    parallel has been created.
 */
LC_SplinePoints* RS_Creation::createParallelSplinePoints(const RS_Vector& coord,
	double distance, int number, LC_SplinePoints* e)
{
	if(!e) return nullptr;

	LC_SplinePoints *psp, *ret = nullptr;

	for(int i = 1; i <= number; ++i)
	{
		psp = (LC_SplinePoints*)e->clone();
		psp->offset(coord, i*distance);

		if(document && handleUndo)
		{
			document->startUndoCycle();
		}

		psp->setParent(container);
		if(!ret) ret = psp;
		setEntity(psp);
	}

	return ret;
}
Ejemplo n.º 23
0
OgreEntityRenderer::~OgreEntityRenderer()
{
	setEntity(nullptr);
	delete mMeshListener;
	delete mSkeletonListener;
}
Ejemplo n.º 24
0
 Brush::~Brush() {
     setEntity(NULL);
     delete m_geometry;
     m_geometry = NULL;
     Utility::deleteAll(m_faces);
 }
Ejemplo n.º 25
0
/**
* Creates a tangent between two circles or arcs.
* Out of the 4 possible tangents, the one closest to
* the given coordinate is returned.
*
* @param coord Coordinate to define which tangent we want (typically a
*              mouse coordinate).
* @param circle1 1st circle or arc entity.
* @param circle2 2nd circle or arc entity.
*/
RS_Line* RS_Creation::createTangent2(const RS_Vector& coord,
                                     RS_Entity* circle1,
                                     RS_Entity* circle2) {
	RS_Line* ret = nullptr;
    RS_Vector circleCenter1;
    RS_Vector circleCenter2;
    double circleRadius1 = 0.0;
    double circleRadius2 = 0.0;

    // check given entities:
	if(! (circle1 && circle2))
		return nullptr;
	if( !(circle1->isArc() && circle2->isArc()))
		return nullptr;

	std::vector<RS_Line*> poss;
    //        for (int i=0; i<4; ++i) {
	//            poss[i] = nullptr;
    //        }
    RS_LineData d;
    if( circle1->rtti() == RS2::EntityEllipse) {
        std::swap(circle1,circle2);//move Ellipse to the second place
    }
    circleCenter1=circle1->getCenter();
    circleRadius1=circle1->getRadius();
    circleCenter2=circle2->getCenter();
    circleRadius2=circle2->getRadius();
    if(circle2->rtti() != RS2::EntityEllipse) {
        //no ellipse

        // create all possible tangents:

        double angle1 = circleCenter1.angleTo(circleCenter2);
        double dist1 = circleCenter1.distanceTo(circleCenter2);

        if (dist1>1.0e-6) {
            // outer tangents:
            double dist2 = circleRadius2 - circleRadius1;
            if (dist1>dist2) {
                double angle2 = asin(dist2/dist1);
				double angt1 = angle1 + angle2 + M_PI_2;
				double angt2 = angle1 - angle2 - M_PI_2;
				RS_Vector offs1 = RS_Vector::polar(circleRadius1, angt1);
				RS_Vector offs2 = RS_Vector::polar(circleRadius2, angt1);

				poss.push_back( new RS_Line{circleCenter1 + offs1,
													  circleCenter2 + offs2});


                offs1.setPolar(circleRadius1, angt2);
                offs2.setPolar(circleRadius2, angt2);

				poss.push_back( new RS_Line{circleCenter1 + offs1,
													  circleCenter2 + offs2});
            }

            // inner tangents:
            double dist3 = circleRadius2 + circleRadius1;
            if (dist1>dist3) {
                double angle3 = asin(dist3/dist1);
				double angt3 = angle1 + angle3 + M_PI_2;
				double angt4 = angle1 - angle3 - M_PI_2;
                RS_Vector offs1;
                RS_Vector offs2;

                offs1.setPolar(circleRadius1, angt3);
                offs2.setPolar(circleRadius2, angt3);

				poss.push_back( new RS_Line{circleCenter1 - offs1,
													  circleCenter2 + offs2});


                offs1.setPolar(circleRadius1, angt4);
                offs2.setPolar(circleRadius2, angt4);

				poss.push_back( new RS_Line{circleCenter1 - offs1,
													  circleCenter2 + offs2});
            }

        }
    }else{
        //circle2 is Ellipse
		std::unique_ptr<RS_Ellipse> e2((RS_Ellipse*)circle2->clone());
//        RS_Ellipse* e2=new RS_Ellipse(nullptr,RS_EllipseData(RS_Vector(4.,1.),RS_Vector(2.,0.),0.5,0.,0.,false));
//        RS_Ellipse  e3(nullptr,RS_EllipseData(RS_Vector(4.,1.),RS_Vector(2.,0.),0.5,0.,0.,false));
//        RS_Ellipse* circle1=new RS_Ellipse(nullptr,RS_EllipseData(RS_Vector(0.,0.),RS_Vector(1.,0.),1.,0.,0.,false));
        RS_Vector m0(circle1->getCenter());
//        std::cout<<"translation: "<<-m0<<std::endl;
        e2->move(-m0); //circle1 centered at origin

        double a,b;
        double a0(0.);
        if(circle1->rtti() != RS2::EntityEllipse){//circle1 is either arc or circle
            a=fabs(circle1->getRadius());
            b=a;
			if(fabs(a)<RS_TOLERANCE) return nullptr;
        }else{//circle1 is ellipse
            RS_Ellipse* e1=static_cast<RS_Ellipse*>(circle1);
            a0=e1->getAngle();
//            std::cout<<"rotation: "<<-a0<<std::endl;
            e2->rotate(-a0);//e1 major axis along x-axis
            a=e1->getMajorRadius();
            b=e1->getRatio()*a;
			if(fabs(a)<RS_TOLERANCE || fabs(b)<RS_TOLERANCE) return nullptr;
        }
        RS_Vector factor1(1./a,1./b);
//        std::cout<<"scaling: factor1="<<factor1<<std::endl;
        e2->scale(RS_Vector(0.,0.),factor1);//circle1 is a unit circle
        factor1.set(a,b);
        double a2(e2->getAngle());
//        std::cout<<"rotation: a2="<<-a2<<std::endl;
        e2->rotate(-a2); //ellipse2 with major axis in x-axis direction
        a=e2->getMajorP().x;
        b=a*e2->getRatio();
        RS_Vector v(e2->getCenter());
//        std::cout<<"Center: (x,y)="<<v<<std::endl;


        std::vector<double> m(0,0.);
        m.push_back(1./(a*a)); //ma000
        m.push_back(1./(b*b)); //ma000
        m.push_back(v.y*v.y-1.); //ma100
        m.push_back(v.x*v.y); //ma101
        m.push_back(v.x*v.x-1.); //ma111
        m.push_back(2.*a*b*v.y); //mb10
        m.push_back(2.*a*b*v.x); //mb11
        m.push_back(a*a*b*b); //mc1

		auto vs0=RS_Math::simultaneousQuadraticSolver(m); //to hold solutions
		if (vs0.getNumber()<1) return nullptr;
//        for(size_t i=0;i<vs0.getNumber();i++){
		for(RS_Vector vpec: vs0){
			RS_Vector vpe2(e2->getCenter()+
						   RS_Vector(vpec.y/e2->getRatio(),vpec.x*e2->getRatio()));
            vpec.x *= -1.;//direction vector of tangent
            RS_Vector vpe1(vpe2 - vpec*(RS_Vector::dotP(vpec,vpe2)/vpec.squared()));
//            std::cout<<"vpe1.squared()="<<vpe1.squared()<<std::endl;
			RS_Line *l=new RS_Line{vpe1, vpe2};
            l->rotate(a2);
            l->scale(factor1);
            l->rotate(a0);
            l->move(m0);
            poss.push_back(l);

        }
        //debugging

    }
    // find closest tangent:
	if(poss.size()<1) return nullptr;
    double minDist = RS_MAXDOUBLE;
    double dist;
    int idx = -1;
	for (size_t i=0; i<poss.size(); ++i) {
		if (poss[i]) {
            poss[i]->getNearestPointOnEntity(coord,false,&dist);
//        std::cout<<poss.size()<<": i="<<i<<" dist="<<dist<<"\n";
            if (dist<minDist) {
                minDist = dist;
                idx = i;
            }
        }
    }
//idx=static_cast<int>(poss.size()*(random()/(double(1.0)+RAND_MAX)));
    if (idx!=-1) {
        RS_LineData d = poss[idx]->getData();
		for(auto p: poss){
			if(p)
				delete p;
		}

		if (document && handleUndo) {
            document->startUndoCycle();
        }

		ret = new RS_Line{container, d};
		setEntity(ret);
    } else {
		ret = nullptr;
    }

    return ret;
}
Ejemplo n.º 26
0
void Game::ConstructPrototypes() {

    const char* CategoryStrs[] = {
        "!NULL_DATA",
        "!MOB_DATA",
        "!ITEM_DATA",
        "!TURF_DATA",
        "!EFFECT_DATA"
    };

    unsigned int parse_flag = 0;

    std::cout << "[LOADING RESOURCES]" << std::endl;
    for(int i = 0; i < _resources.size(); i++) {

        const char* resource = _resources[i].c_str();

        // Found MOB_DATA; initiate mob parsing
        if(strcmp(resource, CategoryStrs[MOB_DATA]) == 0) {
            parse_flag = MOB_PARSE;
            std::cout << resource << std::endl;
            continue;
        // Found ITEM_DATA; initiate item parsing
        } else if(strcmp(resource, CategoryStrs[ITEM_DATA]) == 0) {
            parse_flag = ITEM_PARSE;
            std::cout << resource << std::endl;
            continue;
        // Found TURF_DATA; initiate turf parsing
        } else if(strcmp(resource, CategoryStrs[TURF_DATA]) == 0) {
            parse_flag = TURF_PARSE;
            std::cout << resource << std::endl;
            continue;
        // Found EFFECT_DATA; initiate effect parsing
        } else if(strcmp(resource, CategoryStrs[EFFECT_DATA]) == 0) {
            parse_flag = EFFECT_PARSE;
            std::cout << resource << std::endl;
            continue;
        }

        std::cout << resource << " ";

        std::vector< std::map<std::string, std::string> > data = Helper::SimpleXMLParse(resource);

        std::cout << "(" << data.size() << " entities located)" << std::endl;

        for(int j = 0; j < data.size(); j++) {
            std::map<std::string, std::string> datum = data[j];
            std::map<std::string, boost::any> parsed_data;
            char symbol;
            TCODColor color;
            std::vector<std::string> groups;
            std::vector<std::string> friendlies;
            std::vector<std::string> enemies;

            std::map<std::string, std::string>::iterator it;
            for(it = datum.begin(); it != datum.end(); ++it) {

                std::string index = it->first;
                std::string value = it->second;

                if(index == "symbol") {
                    symbol = Helper::str2char(value);
                } else if(index == "groups") {
                    groups = Helper::Explode(';', value);
                } else if(index == "friendy") {
                    friendlies = Helper::Explode(';', value);
                } else if(index == "hostile") {
                    enemies = Helper::Explode(';', value);
                } else if(index == "color") {
                    std::vector<std::string> color_rgb = Helper::Explode(',', value);
                    color = TCODColor(Helper::str2int(color_rgb[0]), Helper::str2int(color_rgb[1]), Helper::str2int(color_rgb[2]));
                } else {
                    if(Helper::strIsInt(value)) {
                        parsed_data[index] = Helper::str2int(value);
                    } else if(Helper::strIsFloat(value)) {
                        parsed_data[index] = Helper::str2float(value);
                    } else {

                        if(index == "id")
                            friendlies.push_back(value);

                        parsed_data[index] = value;
                    }
                }
            }

            if(parse_flag == MOB_PARSE) {
                Mob mob_make;
                mob_make.set_properties(parsed_data);
                mob_make.color = color;
                mob_make.symbol = symbol;
                mob_make.friendly = friendlies;
                mob_make.hostile = enemies;
                mob_make.groups = groups;
                setMob(mob_make.get_property<std::string>("id"), mob_make);
                setEntity(mob_make.get_property<std::string>("id"), mob_make);
            } else if(parse_flag == ITEM_PARSE) {
                Item item_make;
                item_make.set_properties(parsed_data);
                item_make.color = color;
                item_make.symbol = symbol;
                item_make.groups = groups;
                setItem(item_make.get_property<std::string>("id"), item_make);
                setEntity(item_make.get_property<std::string>("id"), item_make);
            } else if(parse_flag == TURF_PARSE) {
                Turf turf_make;
                turf_make.set_properties(parsed_data);
                turf_make.color = color;
                turf_make.symbol = symbol;
                turf_make.groups = groups;
                setTurf(turf_make.get_property<std::string>("id"), turf_make);
                setEntity(turf_make.get_property<std::string>("id"), turf_make);
            }
        }
    }

    std::cout << "[RESOURCES LOADED (Total resources: " << _entities.size() << ")" << std::endl << std::endl;
}
Ejemplo n.º 27
0
void GameBoard::pushEntities( int x, int y, int x_step, int y_step )
{
  if ( entity( x, y ).isWalkable() ) {
    return;
  }

  // only push cardinal directions, not in diagonals or idle
  if ( ! ( ( x_step == 0 && y_step != 0 ) ||
           ( x_step != 0 && y_step == 0 ) ) ) {
    return;
  }

  // normalize to 1 or -1
  x_step = ( x_step > 0 ) ?  1
         : ( x_step < 0 ) ? -1 : 0;

  // normalize to 1 or -1
  y_step = ( y_step > 0 ) ?  1
         : ( y_step < 0 ) ? -1 : 0;

  // iterate through pushables until we find a walkable
  int tx = x, ty = y;
  int pushCount = 0;
  while (true)
  {
    const ZZTEntity &ent = entity( tx, ty );
    if ( ent.isWalkable() ) {
      break;
    }

    if ( !ent.isPushable( x_step, y_step ) ) {
      return;
    }

    tx += x_step;
    ty += y_step;
    pushCount += 1;
  }

  // okay, we're at a walkable. copy everything back now.
  int px = tx, py = ty;
  while ( tx != x || ty != y )
  {
    px -= x_step;
    py -= y_step;

    if ( entity( px, py ).isThing() ) {
      moveThing( entity( px, py ).thing(), tx, ty );
    }
    else {
      ZZTEntity p_ent = entity( px, py );
      setEntity( tx, ty, p_ent );
    }

    tx = px;
    ty = py;
  }

  if ( pushCount >= 1 ) {
    musicStream()->playEvent( AbstractMusicStream::Push );
  }

  setEntity( x, y, ZZTEntity::createEntity( ZZTEntity::EmptySpace, 0x07 ) );
}
Ejemplo n.º 28
0
 /**
  * @brief Relation::setTo
  * @param to
  */
 void Relation::setTo(const EntityPtr &to)
 {
     setEntity(m_To, to);
 }
Ejemplo n.º 29
0
 /**
  * @brief Relation::setFrom
  * @param from
  */
 void Relation::setFrom(const EntityPtr &from)
 {
     setEntity(m_From, from);
 }
Ejemplo n.º 30
0
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
bool UIEntity::loadBuffer(byte *buffer, bool complete) {
	TOKEN_TABLE_START(commands)
	TOKEN_TABLE(ENTITY_CONTAINER)
	TOKEN_TABLE(TEMPLATE)
	TOKEN_TABLE(DISABLED)
	TOKEN_TABLE(VISIBLE)
	TOKEN_TABLE(X)
	TOKEN_TABLE(Y)
	TOKEN_TABLE(NAME)
	TOKEN_TABLE(ENTITY)
	TOKEN_TABLE(SCRIPT)
	TOKEN_TABLE(EDITOR_PROPERTY)
	TOKEN_TABLE_END

	byte *params;
	int cmd = 2;
	BaseParser parser;

	if (complete) {
		if (parser.getCommand((char **)&buffer, commands, (char **)&params) != TOKEN_ENTITY_CONTAINER) {
			_gameRef->LOG(0, "'ENTITY_CONTAINER' keyword expected.");
			return STATUS_FAILED;
		}
		buffer = params;
	}

	while (cmd > 0 && (cmd = parser.getCommand((char **)&buffer, commands, (char **)&params)) > 0) {
		switch (cmd) {
		case TOKEN_TEMPLATE:
			if (DID_FAIL(loadFile((char *)params))) {
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_NAME:
			setName((char *)params);
			break;

		case TOKEN_X:
			parser.scanStr((char *)params, "%d", &_posX);
			break;

		case TOKEN_Y:
			parser.scanStr((char *)params, "%d", &_posY);
			break;

		case TOKEN_DISABLED:
			parser.scanStr((char *)params, "%b", &_disable);
			break;

		case TOKEN_VISIBLE:
			parser.scanStr((char *)params, "%b", &_visible);
			break;

		case TOKEN_ENTITY:
			if (DID_FAIL(setEntity((char *)params))) {
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_SCRIPT:
			addScript((char *)params);
			break;

		case TOKEN_EDITOR_PROPERTY:
			parseEditorProperty(params, false);
			break;
		}
	}
	if (cmd == PARSERR_TOKENNOTFOUND) {
		_gameRef->LOG(0, "Syntax error in ENTITY_CONTAINER definition");
		return STATUS_FAILED;
	}
	if (cmd == PARSERR_GENERIC) {
		_gameRef->LOG(0, "Error loading ENTITY_CONTAINER definition");
		return STATUS_FAILED;
	}

	correctSize();

	if (_gameRef->_editorMode) {
		_width = 50;
		_height = 50;
	}

	return STATUS_OK;
}