Exemplo n.º 1
0
/*
 * listener_spawn is responsible for creating a Listener class
 * and launching the listener. It is provided as a means for
 * the C thread subsystem to launch the listener C++ object.
 */
void listener_spawn( thread_Settings *thread ) {
    Listener *theListener = NULL;

    // start up a listener
    theListener = new Listener( thread );
#ifndef WIN32
    // handling of daemon mode in non-win32 builds
    if ( isDaemon( thread ) ) {
        theListener->runAsDaemon("iperf",LOG_DAEMON);
    }
#endif

    // Start listening
    theListener->Run();
    DELETE_PTR( theListener );
}
Exemplo n.º 2
0
void Entity::updateView(View &view , Listener &listener , RenderWindow &window)
{
	Vector2u sizeWindow = window.getSize();
	//sizeWindow.x /= 1.f;//SCALE_VIEW
	//sizeWindow.y /= 1.f;// TODO : increase zoom for camera, reason: small image
	view.setSize(Vector2f(sizeWindow));

	float tempX = getXPos();
	float tempY = getYPos();

	listener.setPosition(tempX, tempY, 0);

	float x = getXPos();
	float y = getYPos();

	int leftBorder = sizeWindow.x / 2;
	int rightBorder = SIZE_BLOCK * (WIDTH_MAP - BORDER1) - sizeWindow.x / 2;
	int topBorder = sizeWindow.y / 2;
	int lowBorder = SIZE_BLOCK * LONG_MAP - sizeWindow.y / 2;

	if (int(x) < leftBorder) tempX = float(leftBorder);
	else if (int(x) > rightBorder) tempX = float(rightBorder);
	if (int(y) < topBorder) tempY = float(topBorder);
	else if (int(y) > lowBorder) tempY = float(lowBorder);

	view.setCenter(tempX, tempY);
}
Exemplo n.º 3
0
/**
 * @param prop  SFXLP_ORIENTATION  (yaw, pitch) in degrees.
 */
void DS_SFX_Listenerv(int prop, float* values)
{
    switch(prop)
    {
    case SFXLP_POSITION:
        listener.position.set(values);
        //DSFMOD_TRACE("Pos:" << values[0] << "," << values[1] << "," << values[2]);
        break;

    case SFXLP_ORIENTATION:
        // Convert the angles to front and up vectors.
        listener.setOrientation(float(values[0]/180*M_PI), float(values[1]/180*M_PI));
        break;

    case SFXLP_VELOCITY:
        listener.velocity.set(values);
        break;

    case SFXLP_REVERB:
        updateListenerEnvironmentSettings(values);
        break;

    case SFXLP_PRIMARY_FORMAT:
        DSFMOD_TRACE("SFX_Listenerv: Ignoring SFXLP_PRIMARY_FORMAT.");
        return;

    default:
        return;
    }
}
RowType* ForexConnectWrapper::getTableRow(O2GTable table, std::string key, bool (*finderFunc)(RowType *, std::string), ReaderType* (*readerCreateFunc)(IO2GResponseReaderFactory* , IO2GResponse *)) {

    IO2GResponse *response;

    if( !loginRules->isTableLoadedByDefault(table) ) {
        IO2GRequest *request = mRequestFactory->createRefreshTableRequestByAccount(Trades, sAccountID.c_str());

        Listener *ll = new Listener(session);
        response = ll->sendRequest(request);
        request->release();
        ll->release();
        if (!response) {
            log("No response to manual table refresh request");
            throw "No response to manual table refresh request";
        }
    } else {
        response = loginRules->getTableRefreshResponse(table);
        if (!response) {
            log("No response to automatic table refresh request");
            throw "No response to automatic table refresh request";
        }
    }

    ReaderType *reader = readerCreateFunc(mResponseReaderFactory, response);
    response->release();

    RowType *row = NULL;

    for ( int i = 0; i < reader->size(); ++i ) {
        row = reader->getRow(i);
        if ( finderFunc(row, key) ) {
                break;
        }
        row->release();
        row = NULL;
    }
    reader->release();

    if (row == NULL) {
        std::stringstream ss;
        ss << "Could not find row for key " << key;
        log(ss.str());
        throw ss.str().c_str();
    }

    return row;
}
Exemplo n.º 5
0
int main()
{
	model = new Wrapper(new SimpleModel());
	Simulator<External*>* sim = new Simulator<External*>(model);
	Listener* l = new Listener();
	sim->addEventListener(l);
	// First input/output series. Internal event test.
	l->setExpected(1.0,FAST,1);
	Event<External*> e;
	e.model = model;
	e.value = new External(FAST,1);
	Bag<Event<External*> > x;
	x.insert(e);
	sim->computeNextState(x,0.0);
	assert(sim->nextEventTime() == 1.0);
	sim->execNextEvent();
	assert(output_happened);
	output_happened = false;
	// Second input/output series. External event test.
	l->setExpected(3.5,SLOW,1);
	x.clear();
	e.value = new External(SLOW,1);
	x.insert(e);
	sim->computeNextState(x,1.5);
	assert(!output_happened);
	assert(sim->nextEventTime() == 3.5);
	sim->execNextEvent();
	assert(output_happened);
	output_happened = false;
	// Third input/output series. Confluent event test
	l->setExpected(5.5,SLOW,2);
	x.clear();
	e.value = new External(STOP,1);
	x.insert(e);
	assert(sim->nextEventTime() == 5.5);
	sim->computeNextState(x,sim->nextEventTime());
	assert(output_happened);
	assert(sim->nextEventTime() == DBL_MAX);
	// Done. Try to clean up.
	assert(External::num_existing == 3);
	delete model;
	delete l;
	delete sim;
	assert(Internal::num_existing == 0);
	return 0;
}
void ForexConnectWrapper::openMarket(const std::string symbol, const std::string direction, int amount) {
    if (direction != O2G2::Sell && direction != O2G2::Buy) {
        log("Direction must be 'B' or 'S'");
        throw "Direction must be 'B' or 'S'";
    }

    std::string sOfferID = getOfferID(symbol);

    IO2GValueMap *valuemap = mRequestFactory->createValueMap();
    valuemap->setString(Command, O2G2::Commands::CreateOrder);
    valuemap->setString(OrderType, O2G2::Orders::TrueMarketOpen);
    valuemap->setString(AccountID, sAccountID.c_str());
    valuemap->setString(OfferID, sOfferID.c_str());
    valuemap->setString(BuySell, direction.c_str());
    valuemap->setInt(Amount, amount);
    valuemap->setString(TimeInForce, O2G2::TIF::IOC);

    IO2GRequest *orderRequest = mRequestFactory->createOrderRequest(valuemap);
    valuemap->release();

    TableListener *tableListener = new TableListener();
    tableListener->setRequestID(orderRequest->getRequestID());

    IO2GTableManager *tableManager = getLoadedTableManager();
    subscribeTableListener(tableManager, tableListener);

    Listener *ll = new Listener(session);
    IO2GResponse *response = ll->sendRequest(orderRequest);
    orderRequest->release();
    ll->release();

    if (!response) {
        std::stringstream ss;
        ss << "Failed to send openMarket request " << symbol << " " << direction << " " << amount;
        log(ss.str());
        throw ss.str().c_str();
    }

    tableListener->waitForTableUpdate();

    response->release();
    unsubscribeTableListener(tableManager, tableListener);
    tableListener->release();
    tableManager->release();
}
Exemplo n.º 7
0
void XmlSceneParser::Parse (const ParseNode& decl, Listener& node, Node& parent, SceneContext& context)
{
  try
  {
      //настройка узла
      
    node.SetGain (get<float> (decl, "gain", node.Gain ()));
    
      //разбор родительских параметров
    
    Parse (decl, static_cast<Entity&> (node), parent, context);    
  }
  catch (xtl::exception& e)
  {
    e.touch ("scene_graph::XmlSceneParser::Parse(const ParseNode&,Listener&,Node&,SceneContext&)");
    throw;
  }
}
Exemplo n.º 8
0
	LRESULT onCreate(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
	{
		// Add the window to the clipboard viewer chain. 
		RegisterHotKey(hWnd, 1, MOD_CONTROL | MOD_ALT, VK_RETURN);
		RegisterHotKey(hWnd, 2, MOD_CONTROL | MOD_ALT, VK_UP);
		if (listener.prepare())
			listener.start();
		hwndNextViewer = SetClipboardViewer(hWnd);
		hList = CreateWindowW(L"ListBox", L"Listbox", WS_CHILD | LBS_NOTIFY,
			CW_USEDEFAULT, 0, 600, 600, hWnd, (HMENU)ID_LIST, hInst, NULL);
		
		//SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)L"Text");
		//DefProc = (TDefProc)SetWindowLongPtr(hList, GWLP_WNDPROC, (LONG)&WndProc);
		ShowWindow(hList, SW_HIDE);
		//ShowWindow(hWnd, SW_HIDE);
		return 0;

	}
Exemplo n.º 9
0
void Entity::publish() {
    assert(!isPublished);
    isPublished = true;
    
    // Try find which listeners (systems) correspond with this entity's set of components
    for(std::vector<System*>::iterator sysIter = world->systems.begin(); sysIter != world->systems.end(); ++ sysIter) {
        System* sys = *sysIter;
        
        // Iterate over that system's requirements, check that each one is fulfilled
        bool haveAllRequirements = true;
        const std::vector<ComponentID>& requirements = sys->getRequiredComponents();
        for(std::vector<ComponentID>::const_iterator reqIter = requirements.begin(); reqIter != requirements.end(); ++ reqIter) {
            const ComponentID& reqId = *reqIter;
            
            // Check if we fulfill this requirements
            bool haveRequirement = false;
            for(std::vector<Component*>::iterator compIter = components.begin(); compIter != components.end(); ++ compIter) {
                Component* myComponent = *compIter;
                
                if(myComponent->getID() == reqId) {
                    haveRequirement = true;
                    break;
                }
            }
            
            // If we are missing a single requirement, then we do not have all of them
            if(!haveRequirement) {
                haveAllRequirements = false;
                break;
            }
        }
        
        // Entity has all requirements, therefore add it to our listener list
        if(haveAllRequirements) {
            listeners.push_back(sys);
        }
    }
    
    // Tell every listener that we exist
    for(std::vector<Listener*>::iterator listIter = listeners.begin(); listIter != listeners.end(); ++ listIter) {
        Listener* listener = *listIter;
        listener->onEntityExists(this);
    }
}
void ForexConnectWrapper::setSubscriptionStatus(std::string instrument, std::string status) {
    IO2GTableManager *tableManager = getLoadedTableManager();
    IO2GOffersTable *offersTable = (IO2GOffersTable *)tableManager->getTable(::Offers);
    tableManager->release();

    IO2GOfferTableRow *offerRow = NULL;
    IO2GTableIterator tableIterator;
    bool instrumentFound = false;

    while (offersTable->getNextRow(tableIterator, offerRow)) {
        if ( instrument == offerRow->getInstrument() ) {
            instrumentFound = true;
            IO2GRequestFactory *factory = session->getRequestFactory();

            IO2GValueMap *valueMap = factory->createValueMap();
            valueMap->setString(::Command, O2G2::Commands::SetSubscriptionStatus);
            valueMap->setString(::SubscriptionStatus, status.c_str());
            valueMap->setString(::OfferID, offerRow->getOfferID());

            IO2GRequest *request = factory->createOrderRequest(valueMap);
            valueMap->release();

            Listener *ll = new Listener(session);
            IO2GResponse *response = ll->sendRequest(request);
            response->release();
            request->release();
            ll->release();
            factory->release();

            break;
        }
    }
    offerRow->release();
    offersTable->release();

    if (!instrumentFound) {
        std::stringstream ss;
        ss << "Could not find offer row for instrument " << instrument;
        log(ss.str());
        throw ss.str().c_str();
    }
}
Exemplo n.º 11
0
void Transport::Send(Serializer& _ser, const Peer& _peer, netU32 _type)
{
	Listener *listener = GetListener(_type);

	if(listener)
	{
		_ser.ResetCursor();
		SerializerLess serless(_ser);
		listener->Push(serless, _peer);
	}
	else
	{
		// unavailable transport
		assert(false);
	}

	// update stats
	struct Activity* activity = GetActivity(_peer);
	activity->m_lastSend = Time::GetMsTime();
	activity->m_nbSend++;
}
const TypedEventHandler*
EventListenerManager::GetTypedEventHandler(nsIAtom* aEventName,
                                           const nsAString& aTypeString)
{
  uint32_t eventType = nsContentUtils::GetEventId(aEventName);
  Listener* listener = FindEventHandler(eventType, aEventName, aTypeString);

  if (!listener) {
    return nullptr;
  }

  JSEventHandler* jsEventHandler = listener->GetJSEventHandler();

  if (listener->mHandlerIsString) {
    CompileEventHandlerInternal(listener, nullptr, nullptr);
  }

  const TypedEventHandler& typedHandler =
    jsEventHandler->GetTypedEventHandler();
  return typedHandler.HasEventHandler() ? &typedHandler : nullptr;
}
Exemplo n.º 13
0
netBool Transport::Pull(SerializerLess &_ser, Peer& _peer)
{
	netBool isFound = false;

	for(listeners_t::iterator it=m_listeners.begin(); it != m_listeners.end(); ++it)
	{
		Listener *listener = (*it);
		if(listener->Pull(_ser, _peer))
		{
			isFound = true;

			// update stats
			struct Activity* activity = GetActivity(_peer);
			activity->m_lastRecv = Time::GetMsTime();
			activity->m_nbRecv++;

			break;
		}
	}

	return isFound;
}
Exemplo n.º 14
0
bool chainEvents(Listener& someListener, const LLSD& event)
{
	// Make this call so we can watch for side effects for test purposes.
	someListener.call(event);
	// This function represents a recursive event chain -- or some other
	// scenario in which an event handler raises additional events.
	int value = event.asInteger();
	if (value)
	{
		LLEventPumps::instance().obtain("login").post(value - 1);
	}
	return false;
}
Exemplo n.º 15
0
//
// Run motion detection on a saved file, provide debug images in matrix mode over HTTP
//
int main( int argc, const char *argv[] )
{
    debugInitialise( "example6", "", 5 );

    Info( "Starting" );

    avInit();

    Application app;

    NetworkAVInput input( "input", "/tmp/movie.mp4" );
    app.addThread( &input );

    MotionDetector motionDetector( "modect" );
    motionDetector.registerProvider( input );
    //EventRecorder eventRecorder( "/transfer/ozx" );
    app.addThread( &motionDetector );

    MatrixVideo matrixVideo( "matrix", PIX_FMT_YUV420P, 640, 480, FrameRate( 1, 10 ), 2, 2 );
    matrixVideo.registerProvider( *motionDetector.refImageSlave() );
    matrixVideo.registerProvider( *motionDetector.compImageSlave() );
    matrixVideo.registerProvider( *motionDetector.deltaImageSlave() );
    matrixVideo.registerProvider( *motionDetector.varImageSlave() );
    app.addThread( &matrixVideo );

    Listener listener;
    app.addThread( &listener );

    HttpController httpController( "p8080", 8080 );
    listener.addController( &httpController );

    httpController.addStream( "file", input );
    httpController.addStream( "debug", SlaveVideo::cClass() );
    httpController.addStream( "debug", matrixVideo );
    httpController.addStream( "debug", motionDetector );

    app.run();
}
Exemplo n.º 16
0
void ParticleL::update(const Listener& list, const ci::Vec2f pos){

	mAge++;
	if (mAge > mLifespan)
		mIsDead = true;
	float ageMap = 1.0f - (mAge / (float)mLifespan);

	mRadius = constrain(list.getVolume() * 2.f, .5f, 2.f );
	
	Vec2f expander = mAnchorPosition;
	expander.rotate(mAge/20.f);
	expander *= mRadius;
	addPosition( expander );
}
Exemplo n.º 17
0
  virtual void SetUp() {
    Listener listener;

    // The Matrix::LookAt function is hardcoded to be left handed
    listener = Listener(&state_1_);
    listener.SetOrientation(mathfu::Vector<float, 3>(0.0f, 0.0f, 0.0f),
                            mathfu::Vector<float, 3>(0.0f, 1.0f, 0.0f),
                            -mathfu::kAxisZ3f);

    listener = Listener(&state_2_);
    listener.SetOrientation(mathfu::Vector<float, 3>(12.0f, 34.0f, 56.0f),
                            mathfu::Vector<float, 3>(0.0f, 0.0f, 78.0f),
                            -mathfu::kAxisX3f);

    listener = Listener(&state_3_);
    listener.SetOrientation(mathfu::Vector<float, 3>(10.0f, 10.0f, 10.0f),
                            mathfu::Vector<float, 3>(20.0f, 0.0f, 0.0f),
                            -mathfu::kAxisY3f);

    listener_list_1_.InsertAfter(&state_1_);
    listener_list_2_.InsertAfter(&state_2_);
    listener_list_3_.InsertAfter(&state_3_);
  }
Exemplo n.º 18
0
// Starting a new listener, initialize it and LISTEN
ULONG
RequestQueue::StartListener(USHORT p_port,URL* p_url,USHORT p_timeout)
{
  AutoCritSec lock(&m_lock);

  Listeners::iterator it = m_listeners.find(p_port);
  if(it == m_listeners.end())
  {
    Listener* listener = new Listener(this,p_port,p_url,p_timeout);
    m_listeners.insert(std::make_pair(p_port,listener));

    if(listener->Initialize(p_port) == NoError)
    {
      listener->StartListener();
      return NO_ERROR;
    }
    else
    {
      // Log the error
      return ERROR_BAD_COMMAND;
    }
  }
  return ERROR_ALREADY_EXISTS;
}
Exemplo n.º 19
0
Listener* NetFactory::listen(const string& ip, int port, INetReactor &netReactor)
{
	if (0 == port) {
		LOG_SYSTEM_ERR << "listen at <" << ip << ": " << port << "> failed, port = 0!";
		return NULL;
	}

	// ´´½¨Ò»¸öÍøÂç¼àÌýÆ÷£¬¸ÃÍøÂç¼àÌýÆ÷½«±»×¢²áµ½ÍøÂçÖÐ
	Listener* listener = new Listener(nextNet(), &netReactor, this);
	if (NULL == listener) {
		LOG_SYSTEM_ERR << "listen at <" << ip << ": " << port << "> failed, not enough memory";
		return NULL;
	}

	if (!listener->open(ip, port)) {
		LOG_ERROR << "listen at <" << ip << ": " << port << "> failed";

		delete listener;
		return NULL;
	}

	m_listeners.push_back(listener);
	return listener;
}
Exemplo n.º 20
0
    MyApp() : scene(BLOCK_SIZE) {
        speakerLayout = new SpeakerLayout();
        if (onLaptop) {
            cout << "Using 2 speaker layout" << endl;
            speakerLayout->addSpeaker(Speaker(0, 45, 0, 1.0, 1.0));
            speakerLayout->addSpeaker(Speaker(1, -45, 0, 1.0, 1.0));
        }
        else {
            cout << "Using 3 speaker layout" << endl;
            speakerLayout->addSpeaker(Speaker(0,   0, 0, 100.0, 1.0));
            speakerLayout->addSpeaker(Speaker(1, 120, 0, 100.0, 1.0));
            speakerLayout->addSpeaker(Speaker(2,-120, 0, 100.0, 1.0));
            //speakerLayout->addSpeaker(Speaker(3,   0, 0,   0.0, 0.5));
        }
        panner = new Vbap(*speakerLayout);
        panner->setIs3D(false); // no 3d!

        listener = scene.createListener(panner);
        listener->compile();
        for (int i = 0; i < 10; i++) {
            source[i].dopplerType(DOPPLER_NONE); // XXX doppler kills when moving fast!
            source[i].law(ATTEN_LINEAR);
            scene.addSource(source[i]);
        }
        panner->print();

        scene.usePerSampleProcessing(false);

        AudioDevice::printAll();

        audioIO().print();
        fflush(stdout);

        if (onLaptop) {
            cout << "we're on a laptop, so use normal, default audio hardware" << endl;
            initAudio(44100, BLOCK_SIZE);
        }
        else {
            cout << "we're on the mini, so we will try the TASCAM" << endl;
//      audioIO().device(AudioDevice("TASCAM"));
            audioIO().device(AudioDevice(29));
            initAudio(44100, BLOCK_SIZE, 4, 0);
        }
        cout << "GOT HERE" << endl;

        audioIO().print();
        fflush(stdout);
    }
Exemplo n.º 21
0
ParticleI::ParticleI(const Vec2f& position, const Listener& list){
	addPosition(Vec2f::zero());
	addPosition(Vec2f::zero());
	mAnchorPosition = position;

	mRadius = list.getVolume() * 25;
	mRadiusAnchor = mRadius;

	mOverlayColor = Color::white();
	mDrag = .8f;

	mFillGaps = false;
	mVelThreshold = 5.f;
	mVel = randVec2f() * 40.f;
	mColor = ColorA(1.f, .4f, 0.6f, 1.f);

}
Exemplo n.º 22
0
/**
 * @brief This function walks a tree calling methods of the given listener.
 *
 * @param listener This argument specifies the listener which this function
 *                 uses to convert the tree to a key set.
 * @param root This variable stores the root of the tree this function
 *             visits.
 */
void walk (Listener & listener, node const & node)
{
	ELEKTRA_LOG_DEBUG ("Parse tree: %s", toString (node).c_str ());

	// If the document contains only one a single value we call `exitValue`
	// for that function. We need to handle that special case to not add
	// value multiple times for maps (once for `c_l_block_map_implicit_value`
	// and `c_l_block_seq_entry`) and once for the child of
	// `c_l_block_map_implicit_value`).
	if (node.is_root () && !node.children.empty () && ends_with (node.children.back ()->name (), "node"))
	{
		listener.exitValue (node.children.back ()->content ());
		return;
	}

	executeListenerMethods (listener, node);
}
Exemplo n.º 23
0
Executer::Executer(Environment* environment) {
	// create and initialize listeners
	Listener* compressor = new CompressorListener();
	compressor->init(environment);
	Listener* shooter = new ShooterListener();
	shooter->init(environment);
	Listener* intake = new IntakeListener();
	intake->init(environment);
	Listener* movement = new MovementListener();
	movement->init(environment);
	AutonomousListener* auton = new AutonomousListener();
	auton->init(environment);

	listeners.push_back(compressor);
	listeners.push_back(auton);
	listeners.push_back(shooter);
	listeners.push_back(intake);
	listeners.push_back(movement);
}
Exemplo n.º 24
0
	MyApp () :
	    audioScene(BLOCK_SIZE),
	    spatializer(speakerLayout)
	{
		initWindow();

		addSphere(graphics().mesh());
		graphics().mesh().generateNormals();
		for (int i = 0; i < 50; ++i) {
			source[i].freq(150 + random.uniform(-1, 1));
			audioScene.addSource(source[i]);
		}
		for (int i = 0; i < 50; ++i) {
			source[i + 50].freq(700 + random.uniform(-2, 2));
			audioScene.addSource(source[i + 50]);
		}
		for (int i = 0; i < 50; ++i) {
			source[i + 50].freq(1800 + random.uniform(-3, 3));
			audioScene.addSource(source[i + 100]);
		}
		gam::sampleRate(44100);
		audioIO().device(0);
		initAudio(44100, BLOCK_SIZE);
		listener = audioScene.createListener(&spatializer);
		listener->compile();

		for (int i = 0; i < 150; ++i) {
			double ft1 = data[i * 4];
			double ft2 = data[(i * 4)+ 1];
			double ft3 = data[(i * 4)+ 2];
			double ft4 = data[(i * 4)+ 3];
			double x = mapRange(ft1, 4.3, 7.9, -10.0, 10.0);
			double y = mapRange(ft2, 2.0, 4.4, -10.0, 10.0);
			double z = mapRange(ft3, 1.0, 6.9, -10.0, 10.0);
//			double size = mapRange(ft4, 0.1, 2.5, 0.25, 0.5);
			source[i].pos(x, y, z);
			source[i].farClip(2);
		}

		audioScene.usePerSampleProcessing(false);

	}
Exemplo n.º 25
0
void ParticleFactory::perform(const double elapsedSeconds, const Vec2f origin, const Listener& list, ParticleSystem & ps)
{
	double offsetSeconds = elapsedSeconds + d_adjustSeconds - d_offsetTime;
	if (offsetSeconds < 0)
		ci::app::console() << "waiting for song to start..." << std::endl;

	if (offsetSeconds >= 30 && offsetSeconds < 45)
	{
		while (ps.mParticles.size() < 3)
		{
			Particle* particle = new ParticleG(origin, list);
			ps.addParticle(particle);
		}
	}
	if (offsetSeconds >= 45 && offsetSeconds < 75)
	{
		Particle* particle = new ParticleC(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 75 && offsetSeconds < 105)
	{
		Particle* particle = new ParticleB(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 105 && offsetSeconds < 135)
	{
		Particle* particle = new ParticleL(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 135 && offsetSeconds < 150)
	{
		Particle* particle = new ParticleI(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 135 && offsetSeconds < 165)
	{
		for (int i = 0; i < (int)(list.getVolume()*10.f); ++i)
		{
			Particle* particle = new ParticleD(origin, list);
			ps.addParticle(particle);
		}
		for (int i = 0; i < 3; ++i)
		{
			Particle* particle = new ParticleA(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
	}
	if (offsetSeconds >= 165 && offsetSeconds < 195)
	{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleH(origin, list);
			ps.addParticle(particle);
		}
	}
	if (offsetSeconds >= 195 && offsetSeconds < 210)
	{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleF(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
		Particle* particle = new ParticleE(origin, list);
		particle->mOrientation = ps.mOrientation;
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 210 && offsetSeconds < 225)
	{
		Particle* particle = new ParticleJ(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 225 && offsetSeconds < 255)
	{
		Particle* particle = new ParticleN(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 255 )
	{
		Particle* particle = new ParticleK(origin, list);
		ps.addParticle(particle);
	}

}
Exemplo n.º 26
0
void ParticleFactory::create(const double elapsedSeconds, const Vec2f origin, const Listener& list, ParticleSystem & ps)
{
	ps.mUnderlays = 3;
	switch (d_particleToCreate)
	{
	
	case PARTICLE_A:{
		for (int i = 0; i < 3; ++i)
		{
			Particle* particle = new ParticleA(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_B:{
		Particle* particle = new ParticleB(origin, list);
			ps.addParticle(particle);
	}break;
	case PARTICLE_C:{
		Particle* particle = new ParticleC(origin, list);
			ps.addParticle(particle);
	}break;
	case PARTICLE_D:{
		for (int i = 0; i < (int)(list.getVolume()*20.f); ++i)
		{
			Particle* particle = new ParticleD(origin, list);
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_E:{
			Particle* particle = new ParticleE(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
	}break;
	case PARTICLE_F:{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleF(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_G:{
			while (ps.mParticles.size() < 3)
			{
				Particle* particle = new ParticleG(origin, list);
				ps.addParticle(particle);
			}
	}break;
	case PARTICLE_H:{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleH(origin, list);
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_I:{
			Particle* particle = new ParticleI(origin, list);
			ps.addParticle(particle);
	}break;
	case PARTICLE_J:{
		Particle* particle = new ParticleJ(origin, list);
		ps.addParticle(particle);
	}break;
	case PARTICLE_K:{
		Particle* particle = new ParticleK(origin, list);
		ps.addParticle(particle);
	}break;
	case PARTICLE_L:{
		Particle* particle = new ParticleL(origin, list);
		ps.addParticle(particle);
	}break;
	case PARTICLE_M:{
		Particle* particle = new ParticleM(origin, list);
		particle->mOrientation = ps.mOrientation;
		ps.addParticle(particle);
		ps.mUnderlays = 1;
	}break;
	case PARTICLE_N:{
		Particle* particle = new ParticleN(origin, list);
		ps.addParticle(particle);
	}break;
	default:
		ci::app::console() << "UNKNOWN PARTICLE: " << d_particleToCreate;
		break;
	}
}
Exemplo n.º 27
0
size_t
Communication::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr)
{
    lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION,
                                         "%p Communication::Read (dst = %p, dst_len = %" PRIu64 ", timeout = %u usec) connection = %p",
                                         this, 
                                         dst, 
                                         (uint64_t)dst_len,
                                         timeout_usec, 
                                         m_connection_sp.get());

    if (m_read_thread_enabled)
    {
        // We have a dedicated read thread that is getting data for us
        size_t cached_bytes = GetCachedBytes (dst, dst_len);
        if (cached_bytes > 0 || timeout_usec == 0)
        {
            status = eConnectionStatusSuccess;
            return cached_bytes;
        }

        if (m_connection_sp.get() == NULL)
        {
            if (error_ptr)
                error_ptr->SetErrorString("Invalid connection.");
            status = eConnectionStatusNoConnection;
            return 0;
        }
        // Set the timeout appropriately
        TimeValue timeout_time;
        if (timeout_usec != UINT32_MAX)
        {
            timeout_time = TimeValue::Now();
            timeout_time.OffsetWithMicroSeconds (timeout_usec);
        }

        Listener listener ("Communication::Read");
        listener.StartListeningForEvents (this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
        EventSP event_sp;
        while (listener.WaitForEvent (timeout_time.IsValid() ? &timeout_time : NULL, event_sp))
        {
            const uint32_t event_type = event_sp->GetType();
            if (event_type & eBroadcastBitReadThreadGotBytes)
            {
                return GetCachedBytes (dst, dst_len);
            }

            if (event_type & eBroadcastBitReadThreadDidExit)
            {
                Disconnect (NULL);
                break;
            }
        }
        return 0;
    }

    // We aren't using a read thread, just read the data synchronously in this
    // thread.
    lldb::ConnectionSP connection_sp (m_connection_sp);
    if (connection_sp.get())
    {
        return connection_sp->Read (dst, dst_len, timeout_usec, status, error_ptr);
    }

    if (error_ptr)
        error_ptr->SetErrorString("Invalid connection.");
    status = eConnectionStatusNoConnection;
    return 0;
}
Exemplo n.º 28
0
void *
ProcessKDP::AsyncThread (void *arg)
{
    ProcessKDP *process = (ProcessKDP*) arg;
    
    const lldb::pid_t pid = process->GetID();

    Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
    if (log)
        log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid);
    
    Listener listener ("ProcessKDP::AsyncThread");
    EventSP event_sp;
    const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
                                        eBroadcastBitAsyncThreadShouldExit;
    
    
    if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
    {
        bool done = false;
        while (!done)
        {
            if (log)
                log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...",
                             pid);
            if (listener.WaitForEvent (NULL, event_sp))
            {
                uint32_t event_type = event_sp->GetType();
                if (log)
                    log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...",
                                 pid,
                                 event_type);
                
                // When we are running, poll for 1 second to try and get an exception
                // to indicate the process has stopped. If we don't get one, check to
                // make sure no one asked us to exit
                bool is_running = false;
                DataExtractor exc_reply_packet;
                do
                {
                    switch (event_type)
                    {
                    case eBroadcastBitAsyncContinue:
                        {
                            is_running = true;
                            if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
                            {
                                ThreadSP thread_sp (process->GetKernelThread());
                                if (thread_sp)
                                {
                                    lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
                                    if (reg_ctx_sp)
                                        reg_ctx_sp->InvalidateAllRegisters();
                                    static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
                                }

                                // TODO: parse the stop reply packet
                                is_running = false;                                
                                process->SetPrivateState(eStateStopped);
                            }
                            else
                            {
                                // Check to see if we are supposed to exit. There is no way to
                                // interrupt a running kernel, so all we can do is wait for an
                                // exception or detach...
                                if (listener.GetNextEvent(event_sp))
                                {
                                    // We got an event, go through the loop again
                                    event_type = event_sp->GetType();
                                }
                            }
                        }
                        break;
                            
                    case eBroadcastBitAsyncThreadShouldExit:
                        if (log)
                            log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...",
                                         pid);
                        done = true;
                        is_running = false;
                        break;
                            
                    default:
                        if (log)
                            log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x",
                                         pid,
                                         event_type);
                        done = true;
                        is_running = false;
                        break;
                    }
                } while (is_running);
            }
            else
            {
                if (log)
                    log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false",
                                 pid);
                done = true;
            }
        }
    }
    
    if (log)
        log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...",
                     arg,
                     pid);

    process->m_async_thread.Reset();
    return NULL;
}
Exemplo n.º 29
0
void * listener_thread(void *data)
{
	Listener *listener = (Listener*) data;
	listener->main();
	return NULL;
}
Exemplo n.º 30
0
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
 USA.
 */
// Tests for Listener class
#include "catch.hpp"
#include "lib/listener.h"
#include "protocol/protocolfactory.h"

TEST_CASE("Listener: Unable to listen", "[server]") {
    SECTION("Bad protocolFactory") {
        ProtocolFactory protocolFactory(ProtocolType::None);
        std::shared_ptr<CommonHeaders> commonHeaders(new CommonHeaders());
        
        std::shared_ptr<ContentManagerCustomizer> contentManagerCustomizer(new ContentManagerCustomizer(100, 100000));
        std::shared_ptr<ContentManagerFactory> contentManagerFactory(new ContentManagerFactory(ContentManagerType::None, commonHeaders, contentManagerCustomizer));
        Listener listener(1, Host::ALL_INTERFACES4, protocolFactory, contentManagerFactory);
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        REQUIRE(listener.inErrorState());
    }
    SECTION("Compare to Host") {
        Host googleDNS("google-public-dns-a.google.com", 80, Host::ProtocolPreference::IPV4);
        ProtocolFactory protocolFactory(ProtocolType::None);

        std::shared_ptr<CommonHeaders> commonHeaders(new CommonHeaders());
        std::shared_ptr<ContentManagerCustomizer> contentManagerCustomizer(new ContentManagerCustomizer(100, 100000));
        std::shared_ptr<ContentManagerFactory> contentManagerFactory(new ContentManagerFactory(ContentManagerType::None, commonHeaders, contentManagerCustomizer));
        Listener listener(1, Host::ALL_INTERFACES4, protocolFactory, contentManagerFactory);
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        REQUIRE(listener == 1);
        REQUIRE(listener.getHost() == Host::ALL_INTERFACES4);
        REQUIRE_FALSE(listener == 2);