Exemplo n.º 1
0
 ColorChooser::ColorChooser(Model::Color* color)
 : color(color),
   okAction(new Lum::Model::Action)
 {
   Observe(okAction);
   Observe(GetClosedAction());
 }
Exemplo n.º 2
0
void
CameraDirector::SetViewObjectGroup(ListIter<Ship> group, bool quick)
{
    if (!ship) return;

    Starshatter* stars = Starshatter::GetInstance();

    if (!stars->InCutscene()) {
        // only view solid contacts:
        while (++group) {
            Ship* s = group.value();

            if (s->GetIFF() != ship->GetIFF()) {
                Contact* c = ship->FindContact(s);
                if (!c || !c->ActLock())
                return;
            }

            if (s->Life() == 0 || s->IsDying() || s->IsDead())
            return;
        }
    }

    group.reset();

    if (external_group.size() > 1 &&
            external_group.size() == group.size()) {

        bool same = true;

        for (int i = 0; same && i < external_group.size(); i++) {
            if (external_group[i] != group.container()[i])
            same = false;
        }

        if (same) {
            SetMode(MODE_ZOOM);
            return;
        }
    }

    ClearGroup();

    if (quick) {
        mode = MODE_ORBIT;
        transition = 0;
    }
    else {
        SetMode(MODE_TRANSLATE);
    }

    external_group.append(group.container());

    ListIter<Ship> iter = external_group;
    while (++iter) {
        Ship* s = iter.value();
        region = s->GetRegion();
        Observe(s);
    }
}
Exemplo n.º 3
0
Shot*
Weapon::NetFirePrimary(SimObject* tgt, System* sub, int count)
{
    Shot* shot = 0;

    if (!IsPrimary() || Game::Paused())
    return shot;

    if (active_barrel < 0 || active_barrel >= nbarrels)
    active_barrel = 0;

    target    = tgt;
    subtarget = sub;
    aim_time  = 0;

    for (int i = 0; i < count; i++) {
        shot = FireBarrel(active_barrel++);

        if (active_barrel >= nbarrels) {
            active_barrel = 0;
            refire += design->salvo_delay;
        }
    }

    if (target)
    Observe(target);

    return shot;
}
Exemplo n.º 4
0
Shot*
Weapon::NetFireSecondary(SimObject* tgt, System* sub, DWORD objid)
{
    Shot* shot = 0;

    if (IsPrimary() || Game::Paused())
    return shot;

    if (active_barrel < 0 || active_barrel >= nbarrels)
    active_barrel = 0;

    target    = tgt;
    subtarget = sub;
    aim_time  = 0;

    shot = FireBarrel(active_barrel++);

    if (active_barrel >= nbarrels) {
        active_barrel = 0;
        refire += design->salvo_delay;
    }

    if (shot)
    shot->SetObjID(objid);

    if (target)
    Observe(target);

    return shot;
}
Exemplo n.º 5
0
void
CameraDirector::SetShip(Ship* s)
{
    sim = Sim::GetSim();
    hud = HUDView::GetInstance();

    // can't take control of a dead ship:
    if (s && (s->Life() == 0 || s->IsDying() || s->IsDead()))
    return;

    // leaving the old ship, so make sure it is visible:
    if (ship && ship != s) {
        ship->ShowRep();
        ship->HideCockpit();
    }

    // taking control of the new ship:
    ship = s;

    if (ship) {
        Observe(ship);
        region = ship->GetRegion();

        if (sim && ship->GetRegion() != sim->GetActiveRegion())
        sim->ActivateRegion(ship->GetRegion());

        range  = ship->Radius() * 4;

        if (mode == MODE_COCKPIT)
        mode = MODE_CHASE;

        SetMode(MODE_COCKPIT);
        ExecFrame(0);
    }
}
Exemplo n.º 6
0
void PathConstrainer::Apply( Property target, Property source, const Vector2& range, const Vector2& wrap)
{
  Dali::Property::Type propertyType = target.object.GetPropertyType( target.propertyIndex);
  if( propertyType == Dali::Property::VECTOR3)
  {
    // If property type is Vector3, constrain its value to the position of the path
    Dali::Constraint constraint = Dali::Constraint::New<Vector3>( target.object, target.propertyIndex, PathConstraintFunctor( mPath, range, wrap ) );
    constraint.AddSource( Dali::Source(source.object, source.propertyIndex ) );

    constraint.SetTag( reinterpret_cast<size_t>( this ) );
    constraint.SetRemoveAction( Dali::Constraint::Discard );
    constraint.Apply();
  }
  else if( propertyType == Dali::Property::ROTATION )
  {
    // If property type is Rotation, constrain its value to align the forward vector to the tangent of the path
    Dali::Constraint constraint = Dali::Constraint::New<Quaternion>( target.object, target.propertyIndex, PathConstraintFunctor( mPath, range, mForward, wrap) );
    constraint.AddSource( Dali::Source(source.object, source.propertyIndex ) );

    constraint.SetTag( reinterpret_cast<size_t>( this ) );
    constraint.SetRemoveAction( Dali::Constraint::Discard );
    constraint.Apply();
  }

  //Start observing the object
  Observe( target.object );
}
// RunL() completes a previously issued Observe call 
void CTargetObserver::RunL()
	{
    LOG_MSG2("->CTargetObserver::RunL(status:%d)", iStatus.Int());
	User::LeaveIfError(iStatus.Int()); //something bad happened

    iCrashEventInfo.iEventTime.UniversalTime(); //not 100% exact time of the crash, but as soon as we are notified about it

    Observe(); 

    RThread thread;
    LOG_MSG2("CTargetObserver::RunL() - opening handle to crashed thread:%Lu\n", iCrashEventInfo.iThreadId);
    TInt err = thread.Open(iCrashEventInfo.iThreadId);
    if(err != KErrNone)
        {
        LOG_MSG2("CTargetObserver::RunL - unable to open thread handle! err:%d\n", err); 
        User::Leave(err);
        }
    CleanupClosePushL(thread); 
    
    if( (iThreadList.Count() == 0) || (HasThread(thread.FullName())) )
        {
        //crash event of the whole process or thread that we observe
        LOG_MSG("CTargetObserver::RunL() -> HandleCrashEventL()");
        iHandler.HandleCrashEventL(iCrashEventInfo);
        }
    else //crash event of thread that we don't care about
        {
        LOG_MSG("CTargetObserver::RunL() - resuming crashed thread");
        iSecSess.ResumeThread(iCrashEventInfo.iThreadId);
        }
    CleanupStack::PopAndDestroy(); //thread

	}
Exemplo n.º 8
0
  Table::Table()
  : object(NULL),
    hScroller(NULL),vScroller(NULL),
    kineticScroller(new KineticScroller()),
    hVisible(false),vVisible(false),
    table(new TableView()),
    header(new Header()),headerModel(new Model::HeaderImpl()),showHeader(false)
  {
    SetBackground(OS::display->GetFill(OS::Display::scrolledBackgroundFillIndex));

    headerModel->AddColumn(L"",Base::Size::pixel,32000,true);

    Observe(table->GetHAdjustment()->GetTopModel());
    Observe(table->GetVAdjustment()->GetTopModel());
    Observe(table->GetHAdjustment()->GetTotalModel());
    Observe(table->GetVAdjustment()->GetTotalModel());
  }
Exemplo n.º 9
0
void
Instruction::SetTarget(SimObject* s)
{
    if (s && target != s) {
        tgt_name = s->Name();
        target   = s;
        Observe(target);
    }
}
Exemplo n.º 10
0
  void View::SetObject(Scrollable* object)
  {
    assert(object!=NULL);

    if (this->object!=NULL) {
      Forget(object->GetHAdjustment()->GetTotalModel());
      Forget(object->GetVAdjustment()->GetTotalModel());
      delete this->object;
    }

    this->object=object;

    object->SetParent(this);
    object->SetFlex(true,true);

    Observe(object->GetHAdjustment()->GetTotalModel());
    Observe(object->GetVAdjustment()->GetTotalModel());

    kineticScroller->SetScrollable(object);
  }
Exemplo n.º 11
0
double DelayAtomicSequence::GetDelay(const PrepareMode mode) {

	double dDelayTime = m_await_time;

	//if (m_mod_start==NULL && m_mod_stop==NULL) return dDelayTime;

	Module* pMod =  GetParent();
	if (pMod == NULL) return -1.0;

	//find other sequences between pModStart, myself, and pModStop
	int iMYpos=0, iS1pos=10000, iS2pos=-1;
	for (int i=0;i<pMod->GetNumberOfChildren();++i) {
		if(       this == pMod->GetChild(i)) iMYpos=i;
		if(m_mod_start == pMod->GetChild(i)) iS1pos=i;
		if(m_mod_stop  == pMod->GetChild(i)) iS2pos=i;
	}
	iS1pos = (iMYpos<iS1pos)?iMYpos:iS1pos;
	iS2pos = (iMYpos>iS2pos)?iMYpos:iS2pos;

	//Observe these sequences
	int j = 0;
	for (int i=iS1pos;i<=iS2pos;++i)
		if (i!=iMYpos && mode == PREP_VERBOSE) {
			char modules[10];
			sprintf( modules, "Module%02d", j ) ;
			Observe( GetAttribute(modules), pMod->GetChild(i)->GetName(),"Duration", mode == PREP_VERBOSE );
			j++;
		}

	//subtract duration of other sequences between pModStart, myself, and pModStop
	//do this twice, since cross-dependencies may hinder success in first attempt
	for (int j=0;j<2;j++) {
		dDelayTime = m_await_time;
		for (int i=iS1pos;i<=iS2pos;++i) {
			double dfact = ( ( i==iS2pos && (m_dt==DELAY_B2C || m_dt==DELAY_C2C) ) ||
							 ( i==iS1pos && (m_dt==DELAY_C2E || m_dt==DELAY_C2C) )   ) ? 0.5:1.0;
			if (i!=iMYpos)
				dDelayTime -= dfact * pMod->GetChild(i)->GetDuration();

		}
	}


#ifdef DEBUG
	cout	<< "  DELAYTOMICSEQUENCE: " << GetName() << " mode = " << mode << " , m_await_time = " << m_await_time
			<< " , (iS1pos, iMYpos, iS2pos) = (" << iS1pos << "," << iMYpos << "," << iS2pos << ")"
			<< "  =>  delay = " << dDelayTime << endl;
#endif


	return dDelayTime;

}
Exemplo n.º 12
0
void
SteerAI::SetTarget(SimObject* targ, System* sub)
{
    if (target != targ) {
        target = targ;

        if (target)
            Observe(target);
    }

    subtarget = sub;
}
Exemplo n.º 13
0
void LinearConstrainer::Apply( Property target, Property source, const Vector2& range, const Vector2& wrap)
{
  Dali::Constraint constraint = Dali::Constraint::New<float>( target.object, target.propertyIndex, LinearConstraintFunctor( mValue, mProgress, range, wrap ) );
  constraint.AddSource( Dali::Source(source.object, source.propertyIndex ) );

  constraint.SetTag( reinterpret_cast<size_t>( this ) );
  constraint.SetRemoveAction( Dali::Constraint::Discard );
  constraint.Apply();


  //Start observing the object
  Observe( target.object );
}
Exemplo n.º 14
0
  MapControl()
  : initial(true),
    lon(7.13601),
    lat(50.68924),
    magnification(2*1024),
    requestNewMap(true),
    backgroundColor(241.0/255,238.0/255,233.0/255,1.0)
  {
    SetCanFocus(true);
    RequestFocus();

    Observe(jobFinishedAction);
  }
Exemplo n.º 15
0
void
SeekerAI::SetTarget(SimObject* targ, System* sub)
{
    if (!orig_target && targ && targ->Type() == SimObject::SIM_SHIP) {
        orig_target = (Ship*) targ;
        Observe(orig_target);
    }

    SteerAI::SetTarget(targ, sub);

    if (!target) {
        shot->SetEta(0);

        if (shot->Owner())
        ((Ship*) shot->Owner())->SetMissileEta(shot->Identity(), 0);
    }
}
Exemplo n.º 16
0
  void DirSelect::GenerateItemList()
  {
    std::wstring itemPath;

    if (!model.Valid()) {
      return;
    }

    items.clear();

    items.resize(model->Get().GetPartCount()+1);

    for (size_t x=0; x<model->Get().GetPartCount(); x++) {
      items[model->Get().GetPartCount()-x-1].label=model->Get().GetPart(x);
    }

    items[model->Get().GetPartCount()].label=model->Get().GetRoot();

    // Resize arrays if required
    if (items.size()>models.size()) {
      models.resize(items.size());
    }

    if (items.size()>objects.size()) {
      objects.resize(items.size(),NULL);
    }

    // Create models and button for display if required
    for (size_t i=0; i<items.size(); i++) {
      if (!models[i].Valid()) {
        models[i]=new Model::Action();
        Observe(models[i]);
      }

      if (objects[i]==NULL) {
        objects[i]=CreateButton();
        dynamic_cast<Button*>(objects[i])->SetModel(models[i]);
      }

      objects[i]->SetId(i);
      dynamic_cast<Button*>(objects[i])->SetText(items[i].label);
      objects[i]->CalcSize();
    }

    SetRelayout();
  }
void
NetGameClient::Respawn(DWORD oid, Ship* spawn)
{
	if (!oid || !spawn) return;

	Print("NetGameClient::Respawn(%d, %s)\n", oid, spawn->Name());
	spawn->SetObjID(oid);
	Observe(spawn);

	NetPlayer* p = FindPlayerByObjID(oid);
	if (p)
	p->SetShip(spawn);

	if (objid == oid) {
		Print("  RESPAWN LOCAL PLAYER\n\n");
		local_player = spawn;
	}
}
Exemplo n.º 18
0
SimObject*
Instruction::GetTarget()
{
    if (!target && tgt_name.length() > 0) {
        Sim*  sim = Sim::GetSim();

        if (sim) {
            Ship* s = sim->FindShip(tgt_name, rgn_name);

            if (s) {
                target = s;
                Observe(target);
            }
        }
    }

    return target;
}
Exemplo n.º 19
0
  MainDialog()
   : locationSearchAction(new Lum::Model::Action()),
     routeAction(new Lum::Model::Action()),
     settingsAction(new Lum::Model::Action()),
     debugFlushCacheAction(new Lum::Model::Action()),
     debugStatisticsAction(new Lum::Model::Action()),
     aboutAction(new Lum::Model::Action()),
     map(NULL)
  {
    GetWindow()->SetScreenOrientationHint(Lum::OS::Window::screenOrientationBothSupported);

    Observe(GetOpenedAction());
    Observe(GetClosedAction());
    Observe(locationSearchAction);
    Observe(routeAction);
    Observe(settingsAction);
    Observe(debugFlushCacheAction);
    Observe(debugStatisticsAction);
    Observe(aboutAction);
  }
Exemplo n.º 20
0
void
CameraDirector::CycleViewObject()
{
    if (!ship) return;

    Ship* current = external_ship;
    external_ship  = 0;

    ListIter<Contact> iter = ship->ContactList();
    while (++iter && !external_ship) {
        Contact* c = iter.value();
        Ship*    c_ship = c->GetShip();

        if (c_ship && !current) {
            external_ship = c_ship;
        }
        
        else if (current && c_ship == current) {
            while (++iter && !external_ship) {
                c = iter.value();
                if (c->ActLock())
                external_ship = c->GetShip();
            }
        }
    }

    if (external_ship != current) {
        if (external_ship) {
            if (external_ship->Life() == 0 || external_ship->IsDying() || external_ship->IsDead()) {
                external_point = external_ship->Location();
                external_ship = 0;
            }
            else {
                Observe(external_ship);
            }
        }

        if (mode == MODE_ORBIT) {
            SetMode(MODE_TRANSLATE);
            ExternalRange(1);
        }
    }
}
Exemplo n.º 21
0
NS_IMETHODIMP
nsXPInstallManager::InitManagerWithHashes(const PRUnichar **aURLs,
                                          const char **aHashes,
                                          PRUint32 aURLCount,
                                          nsIXPIProgressDialog* aListener)
{
    // If Software Installation is not enabled, we don't want to proceed with
    // update.
    PRBool xpinstallEnabled = PR_TRUE;
    nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID));
    if (pref)
        pref->GetBoolPref(PREF_XPINSTALL_ENABLED, &xpinstallEnabled);

    if (!xpinstallEnabled)
        return NS_OK;

    mTriggers = new nsXPITriggerInfo();
    if (!mTriggers)
        return NS_ERROR_OUT_OF_MEMORY;

    mNeedsShutdown = PR_TRUE;

    for (PRUint32 i = 0; i < aURLCount; ++i)
    {
        nsXPITriggerItem* item = new nsXPITriggerItem(0, aURLs[i], nsnull,
                                                      aHashes ? aHashes[i] : nsnull);
        if (!item)
        {
            delete mTriggers; // nsXPITriggerInfo frees any alloc'ed nsXPITriggerItems
            mTriggers = nsnull;
            Shutdown();
            return NS_ERROR_OUT_OF_MEMORY;
        }
        mTriggers->Add(item);
    }

    mFromChrome = PR_TRUE;

    nsresult rv = Observe(aListener, XPI_PROGRESS_TOPIC, NS_LITERAL_STRING("open").get());
    if (NS_FAILED(rv))
        Shutdown();
    return rv;
}
Exemplo n.º 22
0
void
Weapon::SetTarget(SimObject* targ, System* sub)
{
    // check self targeting:
    if (targ == (SimObject*) ship)
    return;

    // check target class filter:
    if (targ) {
        switch (targ->Type()) {
        case SimObject::SIM_SHIP: {
                Ship* tgt_ship = (Ship*) targ;

                if ((tgt_ship->Class() & design->target_type) == 0)
                return;
            }
            break;

        case SimObject::SIM_SHOT:
            return;

        case SimObject::SIM_DRONE: {
                if ((design->target_type & Ship::DRONE) == 0)
                return;
            }
            break;

        default: 
            return;
        }
    }

    // if ok, target this object:
    if (target != targ) {
        target = targ;
        
        if (target)
        Observe(target);
    }

    subtarget = sub;
}
Exemplo n.º 23
0
void
NetPlayer::SetShip(Ship* s)
{
	if (ship != s) {
		if (ship) {
			ship->EnableRepair(true);
			Ignore(ship);
		}

		ship = s;

		if (ship) {
			Observe(ship);
			ship->SetNetworkControl(this);
			ship->SetObjID(objid);

			iff = ship->GetIFF();

			// Turn off auto-repair.  All repair data should
			// come in over the network from the remote player:

			ship->EnableRepair(false);

			// Set all ship weapons back to manual fire control.
			// All trigger events should come over the network,
			// not from weapon auto aiming ai:

			ListIter<WeaponGroup> iter = ship->Weapons();
			while (++iter) {
				WeaponGroup* group = iter.value();

				ListIter<Weapon> w_iter = group->GetWeapons();
				while (++w_iter) {
					Weapon* weapon = w_iter.value();

					weapon->SetFiringOrders(Weapon::MANUAL);
				}
			}
		}
	}
}
Exemplo n.º 24
0
int
Element::AddShip(Ship* ship, int index)
{
	if (ship && !ships.contains(ship)) {
		Observe(ship);

		if (index < 0) {
			ships.append(ship);
			index = ships.size();
		}
		else {
			ships.insert(ship, index-1);
		}

		ship->SetElement(this);

		if (respawns < ship->RespawnCount())
		respawns = ship->RespawnCount();
	}

	return index;
}
Exemplo n.º 25
0
        void Run()
        {
            cout << "Example 1 - Creating subject-bound observers (v2)" << endl;

            // Outer scope
            {
                // Unbound observer
                ObserverT obs; 

                // Inner scope
                {
                    auto mySignal = MakeSignal(x, [] (int x) { return x; } );

                    // Move-assign to obs
                    obs = Observe(mySignal, [] (int mySignal) {
                        cout << mySignal << endl;
                    });

                    // The node linked to mySignal is now also owned by obs

                    x <<= 2; // output: 2
                }
                // ~Inner scope

                // mySignal was destroyed, but as long as obs exists and is still
                // attached to the signal node, this signal node won't be destroyed

                x <<= 3; // output: 3
            }
            // ~Outer scope

            // obs was destroyed
            // -> the signal node is no longer owned by anything and is destroyed
            // -> the observer node is destroyed as it was bound to the subject

            x <<= 4; // no ouput

            cout << endl;
        }
Exemplo n.º 26
0
void Simulation::Step() {
	// dispatch the new frame, this wraps up the follow Viewer operations:
	//   advance() to the new frame
	//   eventTraversal() that collects events and passes them on to the event handlers and event callbacks
	//   updateTraversal() to calls the update callbacks
	//   renderingTraversals() that runs syncronizes all the rendering threads (if any) and dispatch cull, draw and swap buffers

	int64 tmptime = cvGetTickCount();
	int64 difftime = (tmptime-loop_time_)/cvGetTickFrequency();
//	if(difftime < loop_target_time_){
//		//std::cout<<"sleeping: "<<loop_target_time_-difftime<<std::endl;
//		usleep(loop_target_time_-difftime);
//		return;
//	}
	loop_time_ = tmptime;



	viewer_.advance();
	viewer_.eventTraversal();
	viewer_.updateTraversal();
	viewer_.renderingTraversals();

//	osg::Matrix testmat = viewer_.getView(2)->getCamera()->getProjectionMatrix();
//	testmat = viewer_.getView(2)->getCamera()->getProjectionMatrix();
//	std::cout<<testmat(0,0)<<"  "<<testmat(0,1)<<"  "<<testmat(0,2)<<"  "<<testmat(0,3)<<std::endl;
//	std::cout<<testmat(1,0)<<"  "<<testmat(1,1)<<"  "<<testmat(1,2)<<"  "<<testmat(1,3)<<std::endl;
//	std::cout<<testmat(2,0)<<"  "<<testmat(2,1)<<"  "<<testmat(2,2)<<"  "<<testmat(2,3)<<std::endl;
//	std::cout<<testmat(3,0)<<"  "<<testmat(3,1)<<"  "<<testmat(3,2)<<"  "<<testmat(3,3)<<std::endl;
//	std::cout<<std::endl;




	viewer_.getView(0)->getCamera()->getViewMatrixAsLookAt(view_matrix_eye_, view_matrix_center_, view_matrix_up_, view_matrix_distance_);
	view_matrix_ = viewer_.getView(0)->getCamera()->getViewMatrix();

//	osg::Matrix windowMatrix = viewer_.getView(2)->getCamera()->getViewport()->computeWindowMatrix();
//	osg::Matrix projectionMatrix = viewer_.getView(2)->getCamera()->getProjectionMatrix();
//	osg::Matrix mat = projectionMatrix*windowMatrix;
//	std::cout<<"mat: "<<mat(0,0)<<" "<<mat(1,1)<<" "<<mat(2,0)<<" "<<mat(2,1)<<std::endl;
//	std::cout<<"eye: "<<view_matrix_eye_.x()<<" "<<view_matrix_eye_.y()<<" "<<view_matrix_eye_.z()<<std::endl;

	if(particles_on_){
		// The dynamic update of the particle filter.
		localisation_->dynamic(robotdata_->incremente_left_,robotdata_->incremente_right_);

		// Update of simulations view of particles.
		particle_view_->Update(localisation_->getParticles(), particle_visibility_ratio_);
	}

	//Picture handling
	if(screen_shot_callback_->isPicTaken() && !picture_processed_){
		osg::ref_ptr<osg::Image> osgImage = screen_shot_callback_->getImage();
		cv::Mat cvImg(osgImage->t(), osgImage->s(), CV_8UC3);
		cv::Mat cvCopyImg(osgImage->t(), osgImage->s(), CV_8UC3);
		cvImg.data = (uchar*)osgImage->data();
		cv::flip(cvImg, cvCopyImg, 0); // Flipping because of different origins
		observedImg_ = &cvCopyImg;

		// Write position, orientation and image to log file.
		data_to_file_writer_.WriteData(robotdata_->incremente_left_, robotdata_->incremente_right_,
												robotdata_->x_pos_, view_matrix_eye_[0], localisation_->getPosition().at(0),
												robotdata_->y_pos_, view_matrix_eye_[1], localisation_->getPosition().at(2),
												robotdata_->psi_, view_matrix_(0,0), localisation_->getOrientation().at(1), cvCopyImg);
		Observe();
		//		old version
		//		data_to_file_writer_.WritePlotData(	robotdata_->x_pos_, robotdata_->y_pos_, robotdata_->psi_,
		//											localisation_->getPosition().at(0), localisation_->getPosition().at(2),
		//											localisation_->getPosition().at(1)*3, localisation_->getPosition().at(3)*3, true);
				es_ = localisation_->getEstimatedRobotPose();
				data_to_file_writer_.WritePlotData(	robotdata_->x_pos_, robotdata_->y_pos_,
													es_->x, es_->y,
													es_->sigmaXYLarge, es_->sigmaXYSmall,
													es_->sigmaXYAngle/M_PI*180, true);
		// observe for particle filter is done here.
		picture_processed_ = true;
	}

	else {
		// writes the current position and orientation of the robot to file.
		data_to_file_writer_.WriteData(robotdata_->incremente_left_, robotdata_->incremente_right_,
														robotdata_->x_pos_, view_matrix_eye_[0], localisation_->getPosition().at(0),
														robotdata_->y_pos_, view_matrix_eye_[1], localisation_->getPosition().at(2),
														robotdata_->psi_, view_matrix_(0,0), localisation_->getOrientation().at(1));

		es_ = localisation_->getEstimatedRobotPose();
		data_to_file_writer_.WritePlotData(	robotdata_->x_pos_, robotdata_->y_pos_,
											es_->x, es_->y,
											es_->sigmaXYLarge, es_->sigmaXYSmall,
											es_->sigmaXYAngle/M_PI*180);
	}

	UpdateHUD();

	// without pad_control pictures are taken every takepicture_intervall_ ms
//	if( (!pad_control_on_) && (0.001*(cvGetTickCount()-take_picture_timer_)/cvGetTickFrequency()>takepicture_intervall_) ){
//		std::cout<<"Sim: 'I queued a Shot!'"<<std::endl;
//		screen_shot_callback_->queueShot();
//		picture_processed_ = false;
//		take_picture_timer_ = cvGetTickCount();
//	}

	if(step_counter_ % takepicture_intervall_ == 0){
		screen_shot_callback_->queueShot();
		picture_processed_ = false;
		take_picture_timer_ = cvGetTickCount();
	}

	if(pad_control_on_){
		if(picture_processed_ && !take_picture_button_pressed_ && sixaxes_->buttonPressed(BUTTON_CIRCLE)){
				// Every 2 sec a Shot is queued to get a picture form the scene.
				screen_shot_callback_->queueShot();
				take_picture_button_pressed_ = true;
				picture_processed_ = false;
				take_picture_timer_ = cvGetTickCount();
		}

		if(!sixaxes_->buttonPressed(BUTTON_CIRCLE))
			take_picture_button_pressed_ = false;

		// If Padcontrol is enabled, the inputs from the pad are written to the robotData.
		// That way the callback will use the inputs to move the robot.
		if(sixaxes_->buttonPressed(BUTTON_L1) && sixaxes_->buttonPressed(BUTTON_R1)){
			robotdata_->speed_ = sixaxes_->axis(AXIS_LY)*-0.2;
			robotdata_->psi_speed_ = sixaxes_->axis(AXIS_RX)*-0.05;
		}
		else{
			robotdata_->speed_ = 0.0;
			robotdata_->psi_speed_ = 0.0;
		}
		if(sixaxes_->buttonPressed(BUTTON_TRIANGLE)){
			while(viewer_.areThreadsRunning()){
				viewer_.stopThreading();
			}
			viewer_.setDone(true);
		}
	}

	if(!trajectory_from_file_.empty()){
		double temp = trajectory_from_file_.front();
		if(temp<1){
			//screen_shot_callback_->queueShot();
			//picture_processed_ = false;
		}
		trajectory_from_file_.erase(trajectory_from_file_.begin());

		temp = trajectory_from_file_.front();
		if(temp>0){
			while(viewer_.areThreadsRunning()){
				viewer_.stopThreading();
			}
			viewer_.setDone(true);
		}
		trajectory_from_file_.erase(trajectory_from_file_.begin());

		temp = trajectory_from_file_.front();
		robotdata_->speed_ = temp;
		trajectory_from_file_.erase(trajectory_from_file_.begin());

		temp = trajectory_from_file_.front();
		robotdata_->psi_speed_ = temp;
		trajectory_from_file_.erase(trajectory_from_file_.begin());
	}
	else{
		trajectory_buffer_ << screen_shot_callback_->isPicTaken() << std::endl;
		trajectory_buffer_ << viewer_.done() << std::endl;
		trajectory_buffer_ << robotdata_->speed_ << std::endl;
		trajectory_buffer_ << robotdata_->psi_speed_ << std::endl;
	}
	//trajectory_buffer_ << "------------------" << std::endl;
	step_counter_ ++;
}
Exemplo n.º 27
0
void
CameraDirector::SetViewObject(Ship* obj, bool quick)
{
    if (!ship) return;
    if (!obj) {
        obj = ship;
        region = ship->GetRegion();
    }

    external_body  = 0;
    external_point = Point();

    Starshatter* stars = Starshatter::GetInstance();

    if (obj->GetIFF() != ship->GetIFF() && !stars->InCutscene()) {
        // only view solid contacts:
        Contact* c = ship->FindContact(obj);
        if (!c || !c->ActLock()) 
        return;
    }

    if (mode == MODE_TARGET) {
        ClearGroup();
        if (external_ship) {
            external_ship = 0;
        }
    }
    else if (mode >= MODE_ORBIT) {
        if (quick) {
            mode       = MODE_ORBIT;
            transition = 0;
        }
        else {
            SetMode(MODE_TRANSLATE);
        }

        if (external_group.size()) {
            ClearGroup();

            if (external_ship) {
                external_ship = 0;
            }
        }

        else {
            if ((obj == external_ship) || (obj==ship && external_ship==0)) {
                if (!quick)
                SetMode(MODE_ZOOM);
            }
            
            else if (external_ship) {
                external_ship = 0;
            }
        }
    }

    if (external_ship != obj) {
        external_ship = obj;

        if (external_ship) {
            region = external_ship->GetRegion();

            if (external_ship->Life() == 0 || external_ship->IsDying() || external_ship->IsDead()) {
                external_ship = 0;
                range_min = 100;
            }
            else {
                Observe(external_ship);

                if (sim)
                sim->ActivateRegion(external_ship->GetRegion());

                range_min = external_ship->Radius() * 1.5;
            }
        }

        Observe(external_ship);
        ExternalRange(1);
    }
}
void
NetGameClient::DoJoinAnnounce(NetMsg* msg)
{
	if (!msg) return;

	Sim* sim = Sim::GetSim();
	if (!sim) return;

	NetJoinAnnounce*  join_ann = new(__FILE__,__LINE__) NetJoinAnnounce;
	bool              saved    = false;

	if (join_ann->Unpack(msg->Data())) {
		DWORD nid       = msg->NetID();
		DWORD oid       = join_ann->GetObjID();
		Text  name      = join_ann->GetName();
		Text  elem_name = join_ann->GetElement();
		Text  region    = join_ann->GetRegion();
		Point loc       = join_ann->GetLocation();
		Point velocity  = join_ann->GetVelocity();
		int   index     = join_ann->GetIndex();
		int   shld_lvl  = join_ann->GetShield();
		join_ann->SetNetID(nid);
		Ship* ship      = 0;
		char  ship_name[128];

		strcpy_s(ship_name, Game::GetText("NetGameClient.no-ship").data());

		if (local_player && player_name == name) {
			HUDView::Message(Game::GetText("NetGameClient.local-accept"), name.data(), local_player->Name());

			objid = oid;
			netid = nid;
			local_player->SetObjID(oid);
			local_player->SetNetObserver(false);
			Observe(local_player);

			SimRegion* rgn = local_player->GetRegion();
			if (rgn && region != rgn->Name()) {
				SimRegion* dst = sim->FindRegion(region);
				if (dst) dst->InsertObject(local_player);
			}

			local_player->MoveTo(loc);
			local_player->SetVelocity(velocity);

			Shield* shield = local_player->GetShield();
			if (shield)
			shield->SetNetShieldLevel(shld_lvl);
		}
		else {
			NetPlayer* remote_player = FindPlayerByObjID(oid);
			if (remote_player) {
				remote_player->SetName(name);
				remote_player->SetObjID(oid);

				if (index > 0)
				sprintf_s(ship_name, "%s %d", elem_name.data(), index);
				else
				sprintf_s(ship_name, "%s", elem_name.data());
			}
			else {
				Element* element = sim->FindElement(elem_name);

				if (element) {
					ship = element->GetShip(index);
				}
				else {
					Print("NetGameClient::DoJoinAnnounce() could not find elem %s for player '%s' objid %d\n",
					elem_name.data(), name.data(), oid);

					NetUtil::SendElemRequest(elem_name.data());
				}

				if (!ship) {
					// save it for later:
					join_backlog.append(join_ann);
					saved = true;
				}
				else {
					strcpy_s(ship_name, ship->Name());

					SimRegion* rgn = ship->GetRegion();
					if (rgn && region != rgn->Name()) {
						SimRegion* dst = sim->FindRegion(region);
						if (dst) dst->InsertObject(ship);
					}

					ship->MoveTo(loc);
					ship->SetVelocity(velocity);

					Shield* shield = ship->GetShield();
					if (shield)
					shield->SetNetShieldLevel(shld_lvl);

					NetPlayer* remote_player = new(__FILE__,__LINE__) NetPlayer(nid);
					remote_player->SetName(name);
					remote_player->SetObjID(oid);
					remote_player->SetShip(ship);

					players.append(remote_player);

					if (name == "Server A.I. Ship") {
						Print("Remote Player '%s' has joined as '%s' with ID %d\n", name.data(), ship_name, oid);
					}
					else {
						HUDView::Message(Game::GetText("NetGameClient.remote-join").data(), name.data(), ship_name);
					}
				}
			}
		}
	}

	if (!saved)
	delete join_ann;
}
Exemplo n.º 29
0
Shot*
Weapon::FireBarrel(int n)
{
    const Point&   base_vel = ship->Velocity();
    Shot*          shot     = 0;
    SimRegion*     region   = ship->GetRegion();

    if (!region || n < 0 || n >= nbarrels || Game::Paused())
    return 0;

    firing = 1;
    Aim();

    Camera rail_cam;
    rail_cam.Clone(aim_cam);

    Point shotpos = muzzle_pts[n];
    if (design->length > 0)
    shotpos = shotpos + aim_cam.vpn() * design->length;

    // guns may be slewed towards target:
    if (design->primary) {
        shot = CreateShot(shotpos, aim_cam, design, ship);

        if (shot) {
            shot->SetVelocity(shot->Velocity() + base_vel);
        }
    }

    // missiles always launch in rail direction:
    else {
        // unless they are on a mobile launcher
        if (turret && design->self_aiming) {
            shot = CreateShot(shotpos, aim_cam, design, ship);
            shot->SetVelocity(base_vel);
        }
        else {
            shot = CreateShot(shotpos, rail_cam, design, ship);
            if (shot /* && !turret */) {
                Matrix orient = ship->Cam().Orientation();
                if (aim_azimuth != 0)   orient.Yaw(aim_azimuth);
                if (aim_elevation != 0) orient.Pitch(aim_elevation);

                Point eject = design->eject * orient;
                shot->SetVelocity(base_vel + eject);
            }
        }

        if (shot && visible_stores[n]) {
            GRAPHIC_DESTROY(visible_stores[n]);
        }
    }

    if (shot) {
        if (ammo > 0)
        ammo--;

        if (guided && target)
        shot->SeekTarget(target, subtarget);

        float shot_load;
        if (energy > design->charge)
        shot_load = design->charge;
        else
        shot_load = energy;   

        energy -= shot_load;
        shot->SetCharge(shot_load * availability);

        if (target && design->flak && !design->guided) {
            double speed = shot->Velocity().length();
            double range = (target->Location() - shot->Location()).length();

            if (range > design->min_range && range < design->max_range) {
                shot->SetFuse(range / speed);
            }
        }

        region->InsertObject(shot);

        if (beams) {
            beams[n] = shot;
            Observe(beams[n]);

            // aim beam at target:
            SetBeamPoints(true);
        }

        if (ship) {
            ShipStats* stats = ShipStats::Find(ship->Name());

            if (design->primary)
            stats->AddGunShot();
            else if (design->decoy_type == 0 && design->damage > 0)
            stats->AddMissileShot();
        }
    }

    return shot;
}
Exemplo n.º 30
0
void
RadioView::Refresh()
{
	sim = Sim::GetSim();

	if (!font)
	return;

	font->SetColor(txt_color);
	font->SetAlpha(1);

	if (sim && ship != sim->GetPlayerShip()) {
		ship = sim->GetPlayerShip();
		history.Clear();

		if (ship) {
			if (ship->Life() == 0 || ship->IsDying() || ship->IsDead()) {
				ship = 0;
			}
			else {
				Observe(ship);
			}
		}
	}

	QuantumView* qv = QuantumView::GetInstance();

	if (!qv || !qv->IsMenuShown()) {
		Menu* menu = history.GetCurrent();

		if (menu) {
			Rect menu_rect(width-115, 10, 115, 12);

			font->DrawText(menu->GetTitle(), 0, menu_rect, DT_CENTER);
			menu_rect.y += 15;

			ListIter<MenuItem> item = menu->GetItems();
			while (++item) {
				if (ship->GetEMCON() < 2 || 
						(TargetRequired(item.value()) && !ship->GetTarget()) ||
						item->GetText().contains("KIA")) {
					item->SetEnabled(false);
					font->SetAlpha(0.35);
				}
				else {
					item->SetEnabled(true);
					font->SetAlpha(1);
				}

				font->DrawText(item->GetText(), 0, menu_rect, DT_LEFT);
				menu_rect.y += 10;
			}
		}
	}

	int message_queue_empty = true;

	// age messages:
	for (int i = 0; i < MAX_MSG; i++) {
		if (msg_time[i] > 0) {
			msg_time[i] -= Game::GUITime();

			if (msg_time[i] <= 0) {
				msg_time[i] = 0;
				msg_text[i] = "";
			}

			message_queue_empty = false;
		}
	}

	if (!message_queue_empty) {
		// advance message pipeline:
		for (int i = 0; i < MAX_MSG; i++) {
			if (msg_time[0] == 0) {
				for (int j = 0; j < MAX_MSG-1; j++) {
					msg_time[j] = msg_time[j+1];
					msg_text[j] = msg_text[j+1];
				}

				msg_time[MAX_MSG-1] = 0;
				msg_text[MAX_MSG-1] = "";
			}
		}

		bool hud_off = false;

		if (HUDView::GetInstance())
		hud_off = (HUDView::GetInstance()->GetHUDMode() == HUDView::HUD_MODE_OFF);

		// draw messages:
		if (!hud_off) {
			for (int i = 0; i < MAX_MSG; i++) {
				if (msg_time[i] > 0) {
					Rect msg_rect(0, 95 + i*10, width, 12);

					if (msg_time[i] > 1)
					font->SetAlpha(1);
					else
					font->SetAlpha(0.5 + 0.5*msg_time[i]);

					font->DrawText(msg_text[i].data(), msg_text[i].length(), msg_rect, DT_CENTER);
				}
			}

			font->SetAlpha(1);
		}
	}

	Starshatter* stars = Starshatter::GetInstance();
	if (stars && stars->GetChatMode()) {
		Text chat;

		switch (stars->GetChatMode()) {
		case 1:  chat = "ALL:  ";  break;
		case 2:  chat = "TEAM:  ";  break;
		case 3:  chat = "WING:  ";  break;
		case 4:  chat = "UNIT:  ";  break;
		}

		chat += stars->GetChatText();

		Rect chat_rect(width/2 - 250, height-150, 500, 12);
		font->DrawText(chat, 0, chat_rect, DT_LEFT);

		chat_rect.Inflate(2,2);
		window->DrawRect(chat_rect, hud_color);
	}
}