예제 #1
0
void systemLoop()
{
	while(1) {	
#ifdef IS_MEASURE_PROCESSING_TIME		
		uint16_t startTime = getTimeMS();
#endif
		for(uint8_t i = 0; i < MAX_TASK; i++) {
			if(s_taskLoop[i] != 0) s_taskLoop[i]();
			else break;
		}

#ifdef IS_MEASURE_PROCESSING_TIME
		uint16_t finishTime = getTimeMS();
		uint8_t interval = 0;
		if(finishTime > startTime) {
			interval =  (finishTime - startTime)&0xff;
			} else {
			interval =  ((255 - startTime) + finishTime + 1)&0xff;	// to avoid using more than 16bit
		}
		if(interval > s_maxProcessingTime) s_maxProcessingTime = interval;
		s_currentProcessingTime = interval;
		//printHex(s_maxProcessingTime);
		//printHex(s_currentProcessingTime);
#endif
	}	
}
예제 #2
0
    void Stage::render(const Color* clearColor, const Rect& viewport, const Matrix& view, const Matrix& proj)
    {
        Material::setCurrent(0);

        IVideoDriver* driver = IVideoDriver::instance;
        driver->setViewport(viewport);

        if (clearColor)
            driver->clear(*clearColor);

        STDMaterial& mat = *STDMaterial::instance;
        mat.apply(0);
        mat.setViewProj(view, proj);

        timeMS t = getTimeMS();
        RenderState rs;
        rs.material = _material;
        Point ds = core::getDisplaySize();

        RectF clip(0.0f, 0.0f, (float)ds.x, (float)ds.y);
        rs.clip = &clip;

        if (_clipOuter)
        {
            driver->setScissorRect(&_viewport);
            clip = _viewport.cast<RectF>();
        }

        Actor::render(rs);

        mat.finish();

        _statRender = getTimeMS() - t;
    }
예제 #3
0
    void Stage::update()
    {
        timeMS t = getTimeMS();
        UpdateState us;
        Actor::update(us);

        _statUpdate = getTimeMS() - t;
    }
예제 #4
0
		void waitTime(timeMS time)
		{
			timeMS start = getTimeMS();
			while(getTimeMS() - start < time)
			{
				yield();
			}
		}
예제 #5
0
		void waitTime(timeMS time)
		{
#if OXYGINE_NO_YEILD
			log::error("%s not supported", __func__);
			return;
#endif
			timeMS start = getTimeMS();
			while(getTimeMS() - start < time)
			{
				yield();
			}
		}
예제 #6
0
    void TextRenderer2::draw(const AffineTransform& tr, spNativeTexture texture, unsigned int color, const RectF& srcRect, const RectF& destRect)
    {
        if (_texture != texture)
        {
            _renderer->setTexture(texture, 0, true);
            _texture = texture;
        }

        vertexPCT2 v[4];
        fillQuadT(v, srcRect, destRect, tr, color);

#ifdef OXYGINE_DEBUG_T2P
        if (_showTexel2PixelErrors)
        {
            Rect viewport;
            _renderer->getDriver()->getViewport(viewport);

            bool t = checkT2P(viewport, _renderer->getViewProjection(), &v[0], &v[3], _texture->getWidth(), _texture->getHeight());
            if (!t)
            {
                float c = (sinf((float)getTimeMS() / 200 + v[0].x * v[0].y) + 1) / 2.0f;
                Color b = interpolate(Color(rand() % 255, rand() % 255, rand() % 255, 255), color, c);
                fillQuadT(v, srcRect, destRect, tr, b.rgba());
            }
        }
#endif

        _renderer->addVertices(v, sizeof(v));
    }
예제 #7
0
    int64   getTimeUTCMS()
    {
#if __S3E__
        return s3eTimerGetUTC();
#elif _WIN32
        FILETIME tm;
        GetSystemTimeAsFileTime(&tm);
        int64 t = tm.dwLowDateTime + (int64(tm.dwHighDateTime) << 32);
        int64 utc = (t - 116444736000000000LL) / 10000;
        return utc;
#elif __ANDROID__
        return jniGetTimeUTCMS();
#elif EMSCRIPTEN
        struct timeval tv;
        gettimeofday(&tv, NULL);
        int64 tm =
            (unsigned long long)(tv.tv_sec) * 1000 +
            (unsigned long long)(tv.tv_usec) / 1000;
        return tm;
#elif __APPLE__
        struct timeval tv;
        gettimeofday(&tv, NULL);
        int64 tm =
            (unsigned long long)(tv.tv_sec) * 1000 +
            (unsigned long long)(tv.tv_usec) / 1000;
        return tm;

        /*
        CFAbsoluteTime tm = CFAbsoluteTimeGetCurrent();
        int64 v = int64(tm * 1000.0);
        return v;
         */
#endif
        return getTimeMS();
    }
예제 #8
0
void printPacketInfo(struct packet *pkt, struct sockaddr_storage *saddr) {
    if (pkt == NULL) {
        fprintf(stderr, "Unable to print info for null packet\n");
        return;
    }

    char *ipstr = ""; 
    unsigned short ipport = 0;
    if (saddr == NULL) {
        fprintf(stderr, "Unable to print packet source from null sockaddr\n");
    } else {
        struct sockaddr_in *sin = (struct sockaddr_in *)saddr;
        ipstr  = inet_ntoa(sin->sin_addr);
        ipport = ntohs(sin->sin_port);
    }

    char pl_bytes[5];
    pl_bytes[0] = pkt->payload[0]; 
    pl_bytes[1] = pkt->payload[1]; 
    pl_bytes[2] = pkt->payload[2]; 
    pl_bytes[3] = pkt->payload[3]; 
    pl_bytes[4] = '\0';

    printf("@%llu ms : ip %s:%u : seq %lu : len %lu : pld \"%s\"\n",
        getTimeMS(), ipstr, ipport, pkt->seq, pkt->len, pl_bytes);
    /*
    printf("  Packet from %s:%u (%lu payload bytes):\n",ipstr,ipport,pkt->len);
    printf("    type = %c\n", pkt->type);
    printf("    seq  = %lu\n", pkt->seq);
    printf("    len  = %lu\n", pkt->len);
    printf("    data = %s\n", pkt->payload);
    puts("");
    */
}
예제 #9
0
    void Draggable::onEvent(Event* event)
    {
        //if (event->currentTarget.get() != _actor)
        //  return;

        TouchEvent* te = safeCast<TouchEvent*>(event);
        switch (te->type)
        {
            case TouchEvent::TOUCH_DOWN:
            {
                startDrag(te->localPosition);
            }
            break;
            case TouchEvent::TOUCH_UP:
            {
                _pressed = false;
                _actor->_getStage()->removeEventListeners(this);
                if (getTimeMS() - _startTm < 2)
                {
                    _actor->setPosition(_clientPos);
                }
            }
            break;

            case TouchEvent::MOVE:
            {
                onMove(te->localPosition);
            }
            break;
        }
    }
예제 #10
0
void STDRenderer::draw(const Color& clr, const RectF& srcRect, const RectF& destRect)
{
    Color color = clr;
    if (_blend == blend_premultiplied_alpha)
        color = color.premultiplied();

    vertexPCT2 v[4];
    fillQuadT(v, srcRect, destRect, _transform, color.rgba());


#ifdef OXYGINE_DEBUG_T2P
    if (_base != white && _showTexel2PixelErrors)
    {
        Rect viewport;
        _driver->getViewport(viewport);

        bool t = checkT2P(viewport, _vp, &v[0], &v[3], _base->getWidth(), _base->getHeight());
        if (!t)
        {
            float c = (sinf((float)getTimeMS() / 200 + v[0].x * v[0].y) + 1) / 2.0f;
            Color b = lerp(Color(rand() % 255, rand() % 255, rand() % 255, 255), color, c);
            fillQuadT(v, srcRect, destRect, _transform, b.rgba());
        }
    }
#endif

    addVertices(v, sizeof(v));
}
예제 #11
0
	void Clock::update(timeMS globalTime)
	{
		timeMS time = globalTime;
		const double neg = -1; 
		if (time == neg)
			time = getTimeMS();

		if (_lastUpdateTime == neg)
			_lastUpdateTime = time;
		
		double dt = (time - _lastUpdateTime) * _multiplier;
		if (dt < 1 && dt > 0)
			dt = 1;

		if (dt > 100)
			dt = 100;

		if (_counter > 0)
			dt = 0;//todo destTime == srcTime ??

		//log::messageln("dt: %x %d", this, dt);
		_destTime += dt;

		_lastUpdateTime = time;

		//if (_fixedStep > 0)
		//	printf("ticks: %d\n", int((_destTime - _srcTime)/_fixedStep));
	}
예제 #12
0
    DebugActor::DebugActor(): _frames(0), _startTime(0), _corner(0), _showTexel2PixelErrors(false), _showTouchedActor(false)
    {
        DebugActor::initialize();

        setName(getDefaultName());

        _startTime = getTimeMS();
        setPriority(30000);

        setTouchEnabled(false);

        TextStyle st;
        st.font = NULL;

        if (ResFont* fnt = resSystem->getResFont("system"))
        {
            st.font = fnt->getFont();
        }

        OX_ASSERT(st.font != NULL);

        st.vAlign = TextStyle::VALIGN_TOP;
        //st.color = Color(rand()%255, rand()%255, rand()%255, 255);
        st.color = Color(Color::Black, 255);
        st.multiline = true;
        setWidth(230);
        setHeight(45);

        _bg = new ColorRectSprite;
        _bg->setColor(Color(Color::White, 64));
        _bg->setSize(getSize());
        _bg->setTouchEnabled(false);
        addChild(_bg);


        float x = getWidth();
        addButton(x, "tree", "tree");
        addButton(x, "finger", "finger");
#ifdef OXYGINE_DEBUG_T2P
        addButton(x, "t2p", "t2p");
#endif

#ifdef OXYGINE_DEBUG_TRACE_LEAKS

        addButton(x, "images", "images");
#endif



        _text = new TextField;
        addChild(_text);
        _text->setPosition(2, 5);
        _text->setTouchEnabled(false);
        _text->setStyle(st);
        _text->setWidth(getWidth());
        _text->setText("debug text");


        instance = this;
    }
예제 #13
0
void RemoteRateEstimator::Update(DWORD ssrc,RTPPacket* packet,DWORD size)
{
	//Get now
	QWORD now = getTimeMS();

	//Get rtp timestamp in ms
	QWORD ts = packet->GetClockTimestamp();

	/*
	if (packet->HasAbsSentTime())
	{
		//Use absolote time instead of rtp time for knowing timestamp at origin
		ts = packet->GetAbsSendTime()+64000*absSendTimeCycles;
		//Check if it has been a wrapp arround, absSendTime has 64s wraps
		if (ts+32000<curTS)
		{
			//Increase cycles
			absSendTimeCycles++;
			//Fix wrap for this one
			ts += 64000;
		}
	}
	*/
	
	//Update
	Update(packet->GetSSRC(),now,ts,size);
}
예제 #14
0
	DebugActor::DebugActor():_frames(0), _startTime(0), _corner(0), _showTexel2PixelErrors(false), _showTouchedActor(false)
	{
		DebugActor::initialize();

		setName(getDefaultName());

		_startTime = getTimeMS();
		setPriority(1000);

		float scale = 1.0f;
		if (getRoot())
			scale = 1.0f/getRoot()->getScaleX();

		setScale(scale);

		setInputEnabled(false);
		

		TextStyle st;
		st.font = resSystem->getResFont("system")->getFont();
		st.vAlign = TextStyle::VALIGN_TOP;
		//st.color = Color(rand()%255, rand()%255, rand()%255, 255);
		st.color = Color(Color::Black, 255);
		st.multiline = true;
		setWidth(230);
		setHeight(45);

		_bg = new ColorRectSprite;
		_bg->setColor(Color(Color::White, 64));
		_bg->setSize(getSize());
		_bg->setInputEnabled(false);
		addChild(_bg);


		float x = getWidth();
		addButton(x, "tree", "tree");
		addButton(x, "finger", "finger");		
#ifdef OXYGINE_DEBUG_T2P
		addButton(x, "t2p", "t2p");
#endif

#ifdef OXYGINE_DEBUG_TRACE_LEAKS
		
		addButton(x, "images", "images");		
#endif
		
		

		_text = new TextActor;
		addChild(_text);
		_text->setInputEnabled(false);
		_text->setStyle(st);
		_text->setWidth(getWidth());
		_text->setText("debug text");

		getRoot()->addEventListener(TouchEvent::MOVE, CLOSURE(this, &DebugActor::onDAEvent));

		instance = this;
	}
예제 #15
0
void pcapProcessEvalError(error_type error, pcap_pkthdr header, u_char *packet,
			  pcapProcessData *ppd, int pcapLinklayerHeaderType, pcap_dumper_t *pcapDumpHandle, const char *interfaceName) {
	switch(error) {
	case bad_eth_protocol: {
		static int info_tcpreplay = 0;
		if(ppd->protocol == 0 && !info_tcpreplay && interfaceName && !strcmp(interfaceName, "lo")) {
			syslog(LOG_ERR, "BAD PROTOCOL (not ipv4) IN %s (dlt %d) - TRY VERBOSE OPTION tcpreplay", interfaceName, pcapLinklayerHeaderType);
			info_tcpreplay = 1;
		}
		}
		break;
	case bad_ip_version:
		if(interfaceName) {
			extern BogusDumper *bogusDumper;
			static u_long lastTimeLogErrBadIpHeader = 0;
			if(bogusDumper) {
				bogusDumper->dump(&header, packet, pcapLinklayerHeaderType, interfaceName);
			}
			u_long actTime = getTimeMS(&header);
			if(actTime - 1000 > lastTimeLogErrBadIpHeader) {
				syslog(LOG_ERR, "BAD HEADER_IP: %s: bogus ip header version %i", interfaceName, ppd->header_ip->version);
				lastTimeLogErrBadIpHeader = actTime;
			}
		}
		break;
	case bad_ip_length:
		if(interfaceName) {
			extern BogusDumper *bogusDumper;
			static u_long lastTimeLogErrBadIpHeader = 0;
			if(bogusDumper) {
				bogusDumper->dump(&header, packet, pcapLinklayerHeaderType, interfaceName);
			}
			u_long actTime = getTimeMS(&header);
			if(actTime - 1000 > lastTimeLogErrBadIpHeader) {
				syslog(LOG_ERR, "BAD HEADER_IP: %s: bogus ip header length %i, len %i", interfaceName, htons(ppd->header_ip->tot_len), header.len);
				lastTimeLogErrBadIpHeader = actTime;
			}
		}
		break;
	case bad_datalink:
		syslog(LOG_ERR, "BAD DATALINK %s: datalink number [%d] is not supported", interfaceName ? interfaceName : "---", pcapLinklayerHeaderType);
		break;
	default:
		break;
	}
}
예제 #16
0
    void Stage::render(Renderer& r)
    {
        timeMS t = getTimeMS();
        RenderState rs;
        rs.renderer = &r;
        Point ds = core::getDisplaySize();

        RectF clip(0.0f, 0.0f, (float)ds.x, (float)ds.y);
        rs.clip = &clip;

        if (_clipOuter)
        {
            r.getDriver()->setScissorRect(&_viewport);
            clip = _viewport.cast<RectF>();
        }

        Actor::render(rs);

        _statRender = getTimeMS() - t;
    }
예제 #17
0
    void Draggable::startDrag(const Vector2& localCenter)
    {
        _startTm = getTimeMS();
        _pressed = true;
        _dragPos = localCenter;
        _clientPos = _dragClient->getPosition();

        //why I did add it?
        //event->stopPropagation();

        _actor->_getStage()->addEventListener(TouchEvent::MOVE, CLOSURE(this, &Draggable::onEvent));
    }
예제 #18
0
void main()
{
	fstream fs("ListHCPLabProceduresDetail.response", ios::in);
	fs.seekg(0,ios::end);
	int nSize = fs.tellg();
	fs.seekg(0,ios::beg);
	char *xmlBuf = new char[nSize + 1];
	memset(xmlBuf,0,nSize + 1);
	fs.read(xmlBuf,nSize);
	CXMLTree tree;

	// 940 milliseconds to Parse and build a tree for 
	// a 4.82 Megabyte XML file in a PII450 in Windows NT.
	long startTime = getTimeMS();
	tree.parseXML( xmlBuf );
	cout << "Time in milliseconds to parse XML into the tree: " << getTimeMS() - startTime;

	int nIndent = 0;
//	dump(tree.getRoot(), &nIndent);
	delete xmlBuf;
}
예제 #19
0
bool
RefFreeFrame::initGL(int screenWidth, int screenHeight)
{
    frameGL->init(screenWidth, screenHeight);

    QCAR::Renderer &renderer = QCAR::Renderer::getInstance();
    const QCAR::VideoBackgroundConfig &vc = renderer.getVideoBackgroundConfig();
    halfScreenSize.data[0] = vc.mSize.data[0] * 0.5f;
    halfScreenSize.data[1] = vc.mSize.data[1] * 0.5f;

    // sets last frame timer
    lastFrameTime = getTimeMS();

    reset();
}
예제 #20
0
 uint64_t Clock::getTime(uint64_t simTime) {
   switch (resolution) {
   case RESOLUTION_1US:
     return getTimeUS(simTime);
     break;
   case RESOLUTION_31US: {
     uint64_t time = getTimeUS(simTime);
     return floor(time/31) * 31;
   }			
     break;
   case RESOLUTION_1MS:
     return getTimeMS(simTime)*1000;
     break;
   default:
     cerr << "Undefined clock resolution" << endl;
     return 0;
   }
 }
예제 #21
0
bool RuntimeScheduler::submit(work* w) {
	double start = getTimeMS();
	ds->execPayload = true;
	if(TOTAL_DEVICES == 1) {
		ds->push(0, w);
		return true;
	}

	if (IS_DICEABLE(w->WORK_TYPE_ID)) {
		double* m = ds->getModel(w->getWorkTypeID());
		unsigned int part = TOTAL_DEVICES;

		ptrwork* l = w->dice(m, part);
		if (l == NULL) {
			int devSel = 0;
			int max = m[0];
			for (int dev = 1; dev < TOTAL_DEVICES; dev++) {
				if (max <= m[dev]) {
					max = m[dev];
					devSel = dev;
				}
			}
			ds->push(devSel, w);

		} else {

			for (int dev = 0; dev < TOTAL_DEVICES; dev++) {
				if (l[dev] != NULL) {
					l[dev]->start = start;
					SysDevices[dev]->submit(l[dev]);
//					SysDevices[dev]->wake.notify_all();
				}
			}

			delete l;
		}
		delete m;
	} else {
		unsigned dev = rand() % TOTAL_DEVICES;
		ds->push(dev, w);
//		SysDevices[dev]->wake.notify_all();
	}
	return true;
}
예제 #22
0
bool RemoteRateControl::UpdateLost(DWORD num)
{
	//Check lost is more than 2.5%
	if (packetCalc.GetInstantAvg()<num*40)
	{
		//Overusing
		hypothesis = OverUsing;
		//Reset counter
		overUseCount=0;
	}

	//Debug
	Debug("BWE: UpdateLostlost:%d hipothesis:%s\n",num,GetName(hypothesis));

	if (eventSource) eventSource->SendEvent("rrc.lost","[%llu,\"%s\",\"%d\"]",getTimeMS(),GetName(hypothesis),rtt);

	//true if overusing
	return hypothesis==OverUsing;
}
예제 #23
0
bool RemoteRateControl::UpdateRTT(DWORD rtt)
{
	//Check difference
	if (this->rtt>40 && rtt>this->rtt*1.50)
	{	
		//Overusing
		hypothesis = OverUsing;
		//Reset counter
		overUseCount=0;
	}
	
	//Update RTT
	this->rtt = rtt;

	//Debug
	Debug("BWE: UpdateRTT rtt:%dms hipothesis:%s\n",rtt,GetName(hypothesis));

	if (eventSource) eventSource->SendEvent("rrc.rtt","[%llu,\"%s\",\"%d\"]",getTimeMS(),GetName(hypothesis),rtt);

	//Return if we are overusing now
	return hypothesis==OverUsing;
}
예제 #24
0
    void SoundPlayer::update()
    {
        timeMS t = getTimeMS();
        timeMS d = t - _lastUpdateTime;
        if (_paused)
            d = 0;
        _time += d;

        for (size_t i = 0; i < _sounds.size();)
        {
            spSoundInstance s = _sounds[i];
            s->update();

            if (s->getChannel())
                ++i;
            else
                _sounds.erase(_sounds.begin() + i);
        }

        //log::messageln("sounds %d", _sounds.size());

        _lastUpdateTime = t;
    }
예제 #25
0
int main(int argc, char **argv) {
    // ------------------------------------------------------------------------
    // Handle commandline arguments
    if (argc < 5) {
        printf("usage: emulator -p <port> -f <filename>\n");
        exit(1);
    }

    char *portStr    = NULL;
    const char *filename   = NULL;

    int cmd;
    while ((cmd = getopt(argc, argv, "p:f:")) != -1) {
        switch(cmd) {
            case 'p': portStr   = optarg; break;
            case 'f': filename  = optarg; break;
            case '?':
                if (optopt == 'p' || optopt == 'f')
                    fprintf(stderr, "Option -%c requires an argument.\n", optopt);
                else if (isprint(optopt))
                    fprintf(stderr, "Unknown option -%c.\n", optopt);
                else
                    fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
                exit(EXIT_FAILURE);
            break;
            default: 
                printf("Unhandled argument: %d\n", cmd);
                exit(EXIT_FAILURE); 
        }
    }

    printf("Port        : %s\n", portStr);
    printf("File Name   : %s\n", filename);

    // Convert program args to values
    int emulPort  = atoi(portStr);
    int maxTime = 1500;
    int minTime = 500;

    // Validate the argument values
    if (emulPort <= 1024 ||emulPort >= 65536)
        ferrorExit("Invalid emul port");
    puts("");

    srand(time(NULL));
    initLog("log_file.txt");
	
    // ------------------------------------------------------------------------
    // Setup emul address info 
    struct addrinfo ehints;
    bzero(&ehints, sizeof(struct addrinfo));
    ehints.ai_family   = AF_INET;
    ehints.ai_socktype = SOCK_DGRAM;
    ehints.ai_flags    = AI_PASSIVE;
    
    char localhost[80];
    gethostname(localhost, sizeof(localhost));
    
    // Get the emul's address info
    struct addrinfo *emulinfo;
    int errcode = getaddrinfo(localhost, portStr, &ehints, &emulinfo);
    if (errcode != 0) {
        fprintf(stderr, "emul getaddrinfo: %s\n", gai_strerror(errcode));
        exit(EXIT_FAILURE);
    }

    // Loop through all the results of getaddrinfo and try to create a socket for emul
    int sockfd;
    struct addrinfo *sp;
    for(sp = emulinfo; sp != NULL; sp = sp->ai_next) {
        // Try to create a new socket
        sockfd = socket(sp->ai_family, sp->ai_socktype, sp->ai_protocol);
        if (sockfd == -1) {
            perror("Socket error");
            continue;
        }
		
		// Try to bind the socket
        if (bind(sockfd, sp->ai_addr, sp->ai_addrlen) == -1) {
            perror("Bind error");
            close(sockfd);
            continue;
        }
		
        break;
    }
    if (sp == NULL) perrorExit("Send socket creation failed");
    else            printf("emul socket created.\n");

	struct sockaddr_in *tmp = (struct sockaddr_in *)sp->ai_addr;
	unsigned long eIpAddr = tmp->sin_addr.s_addr;
	//printf("eIpAddr: %lu\n", eIpAddr);
  initTable(filename, tmp);

  exit(0);
  // ------------------------------------------------------------------------
	// The Big Loop of DOOM

	struct sockaddr_in *nextSock;
  int shouldForward;
	fd_set fds;
	
  struct timespec *tv = malloc(sizeof(struct timespec));
	tv->tv_sec = (long) 0;
	tv->tv_nsec = 0;
  int retval = 0;
	int numRecv = 0;
  int routesMade = 0;
	unsigned long long start;
  struct packet *dpkt;
  struct ip_packet *pkt = malloc(sizeof(struct ip_packet));
	void *msg = malloc(sizeof(struct ip_packet));
  for (;;) {
		FD_ZERO(&fds);
		FD_SET(sockfd, &fds);
		start = getTimeMS();
		retval = pselect(sockfd + 1, &fds, NULL, NULL, tv, NULL);
	
		// ------------------------------------------------------------------------
		// receiving half
        
		if (retval > 0 /*&& routesMade == 1*/) {
			// Receive and forward packet
			printf("retval > 0\n");
			bzero(msg, sizeof(struct ip_packet));
			size_t bytesRecvd = recvfrom(sockfd, msg, sizeof(struct ip_packet), 0, NULL, NULL);
			if (bytesRecvd == -1) {
				perror("Recvfrom error");
				fprintf(stderr, "Failed/incomplete receive: ignoring\n");
				continue;
			}
			
			// Deserialize the message into a packet 
			bzero(pkt, sizeof(struct ip_packet));
			deserializeIpPacket(msg, pkt);
			dpkt = (struct packet *)pkt->payload;
			printIpPacketInfo(pkt, NULL);
      
      // Check packet type to see if any action needs to be taken
      nextSock = malloc(sizeof(struct sockaddr_in));
      if (dpkt->type == 'T') {
        if (dpkt->len == 0) {
          bzero(nextSock, sizeof(struct sockaddr_in));
          shouldForward = 1;
          nextSock->sin_family = AF_INET;
					nextSock->sin_addr.s_addr = htonl(pkt->src);
					nextSock->sin_port = htons(pkt->srcPort);
          pkt->src = eIpAddr;
          pkt->srcPort = emulPort;
        }
        else {
          dpkt->len--;
          shouldForward = nextHop(pkt, nextSock);
        }
      }
      else if (dpkt->type == 'S') {
        /*if ((pkt->dest == eIpAddr && pkt->destPort == emulPort) || dpkt->len == 0) {
          dpkt = createNeighborPkt();
          bzero(pkt, sizeof(struct ip_packet));
          pkt->length = dpkt->len + HEADER_SIZE;
          pkt->priority = 0;
          memcpy(pkt->payload, dpkt, sizeof(struct packet));
          
        }*/
        if (updateLSP(pkt)) {
          floodLSP(sockfd, tmp, pkt);
        }
        shouldForward = 0;
        routesMade = 0;
      }
      else {
        shouldForward = nextHop(pkt, nextSock);
      }
      // Forward the packet if there is an entry for it
			if (shouldForward)	{
        printf("send packet\n");
        //printf("socket is %lu  %u", nextSock->sin_addr.s_addr, nextSock->sin_port);
        sendIpPacketTo(sockfd, pkt, (struct sockaddr*)nextSock);
        free(nextSock);
			}
			else {
				logP(pkt, "No forwarding entry found");
			}
			
      // update timespec
			long sec = tv->tv_sec - (long)((getTimeMS() - start) / 1000);
			long nsec = tv->tv_nsec - (long)(1000000 * ((getTimeMS() - start) % 1000));
			if (nsec < 0) {
				nsec = 1000000 * 1000 + nsec;
				sec--;
				
			}
			if (sec < 0 || !numRecv) {
					sec = 0;
					nsec = 0;
			}
			tv->tv_sec = sec;
			tv->tv_nsec = nsec;
		}
		if (retval == 0 || routesMade == 0) {
			// ------------------------------------------------------------------------
			// refresh forward table
			printf("retval == 0\n");
			if (retval == 0) {
        floodLSP(sockfd, tmp, NULL);
      }
      routesMade = createRoutes(tmp);
      
      int delay = minTime + (rand() % (maxTime - minTime));
      tv->tv_sec = (long)delay / 1000;
      tv->tv_nsec = (long)(delay % 1000) * 1000000;
		}
		else {
			//printf("Sockfd = %d\n", sockfd);
			//printf("tv%d  delay=%li s   %li us\n", x, tv->tv_sec, tv->tv_nsec);
			perrorExit("Select()");
		}
  }
	// Cleanup packets
  free(pkt);
  free(msg);
}
예제 #26
0
    void SlidingActor::doUpdate(const UpdateState& us)
    {
        if (!_content)
            return;

        //static float ml = 0;
        //ml = max(_speed.length(), ml);
        //log::messageln("sp: %.2f", ml);

        int ct = getTimeMS();
        if (_lastIterTime + NUM * fdt < ct)
            _lastIterTime = ct;

        if (_drag.isDragging())
        {
            Vector2 pos = _content->getPosition();
            //log::messageln("%d) pos %.2f %.2f", _current, pos.x, pos.y);
            _prev[_current].pos = pos;
            _prev[_current].tm = ct;
            _current = (_current + 1) % NUM;

            return;
        }

        if (_sliding)
        {
            const RectF& bounds = _drag.getDragBounds();
            while (_lastIterTime + fdt <= ct)
            {
                Vector2 pos = _content->getPosition();
                Vector2 newpos = pos + _speed * (fdt / 1000.0f);
                if (newpos.x < bounds.getLeft())
                {
                    newpos.x = bounds.getLeft();
                    _speed.x = 0;
                }
                else if (newpos.x > bounds.getRight())
                {
                    newpos.x = bounds.getRight();
                    _speed.x = 0;
                }

                if (newpos.y < bounds.getTop())
                {
                    newpos.y = bounds.getTop();
                    _speed.y = 0;
                }
                else if (newpos.y > bounds.getBottom())
                {
                    newpos.y = bounds.getBottom();
                    _speed.y = 0;
                }


                _speed *= 0.97f;
                _content->setPosition(newpos);

                _lastIterTime += fdt;
            }


            SlidingEvent sl(SlidingEvent::SLIDING);
            sl.speed = _speed;
            dispatchEvent(&sl);
            _speed = sl.speed;

            if (_speed.sqlength() < 8)
            {
                _sliding = false;
                SlidingEvent ev(SlidingEvent::END);
                dispatchEvent(&ev);
            }
        }

    }
예제 #27
0
	void DebugActor::doUpdate(const UpdateState &us)
	{
		static int fps = 0;
		++_frames;
		if (_frames > 50)
		{
			timeMS this_time = getTimeMS();
			if (this_time != _startTime)
			{
				fps = int(((float)_frames/(this_time - _startTime))*1000);
			}
			_startTime = this_time;
			_frames = 0;
		}

		int mem_used = -1;
		int mem_free = -1;

#ifdef __S3E__
		mem_used = s3eMemoryGetInt(S3E_MEMORY_USED);
		mem_free = s3eMemoryGetInt(S3E_MEMORY_FREE);
#endif

		stringstream s;
		s << "fps=" << fps << " mem=" << mem_used << endl;
		s << "mfree=" << mem_free << endl;

#ifdef OXYGINE_DEBUG_TRACE_LEAKS
		s << "objects=" << (int)ObjectBase::__getCreatedObjects().size() << endl;
#endif
		s << "batches="<< _videoStats.batches << " triangles=" << _videoStats.triangles << endl;
		s << "update=" << getRoot()->_statUpdate << "ms ";
		s << "render=" << getRoot()->_statRender << "ms ";
		s << "textures=" << NativeTexture::created << " ";
		s << "\nlisteners=" << getRoot()->getListenersCount() << "";

		s << "\n";
		s << _debugText;
		_debugText = "";

		_text->setText(s.str());

		
		setHeight(_text->getTextRect().size.y + 2.0f);
		_bg->setSize(getSize());


		float scale = getScaleX();
		Vector2 parentSize = getParent()->getSize();
		Vector2 realSize = getSize() * scale;

		setX(0);
		setY(0);

		switch(_corner)
		{			
		case 1:
			setX(parentSize.x - realSize.x);
			setY(0);
			break;
		case 2:
			setPosition(parentSize - realSize);
			break;
		case 3:
			setX(0);
			setY(parentSize.y - realSize.y);
			break;
		}
	}
예제 #28
0
 SoundPlayer::SoundPlayer(): _resources(0), _volume(1.0f), _time(0), _lastUpdateTime(0), _paused(false)
 {
     _time = getTimeMS();
     _lastUpdateTime = _time;
 }
예제 #29
0
    void SlidingActor::_newEvent(Event* event)
    {
        if (!_content)
            return;

        TouchEvent* te = safeCast<TouchEvent*>(event);
        //if (te->)
        timeMS tm = getTimeMS();
        switch (te->type)
        {
            case TouchEvent::TOUCH_DOWN:
            {
                _finger = te->index;
                _current = 0;
                _lastIterTime = tm;

                _prev[0].pos = _content->getPosition();
                _prev[0].tm = tm;

                for (int i = 1; i < NUM; ++i)
                    _prev[i].tm = 0;

                _holded = event->target;
                _downPos = te->localPosition;
                _downTime = tm;
            }
            break;

            case TouchEvent::TOUCH_UP:
            {
                if (_ignoreTouchUp)
                {
                    te->stopImmediatePropagation();
                }

                if (_drag.getDragEnabled() && te->index == _finger && _ignoreTouchUp == false)
                {
                    _finger = 0;
                    _downTime = 0;
                    Vector2 pos = _content->getPosition();

                    _holded = 0;

                    const iter* old = 0;
                    const iter* mid = 0;
                    const iter* last = _prev + _current;

                    for (int i = 1; i < NUM; ++i)
                    {
                        int n = (_current + NUM - i) % NUM;
                        if (_prev[n].tm)
                            last = _prev + n;
                        else
                            break;
                        if (!mid && (last->tm + 50 <= tm))
                            mid = last;
                        if (last->tm + 150 <= tm)
                        {
                            old = last;
                            break;
                        }
                    }
                    if (!old)
                        old = last;
                    if (!mid)
                        mid = last;



                    Vector2 midpos = mid->pos;
                    Vector2 dir = pos - midpos;
                    if (dir.sqlength() < 10 * 10)
                        _speed = Vector2(0, 0);
                    else
                    {
                        timeMS v = tm - old->tm;
                        if (!v)
                            return;

                        Vector2 dr = pos - old->pos;

                        Vector2 ns = (dr * 1000.0f) / v;

                        if (_speed.dot(ns) < 0)
                            _speed = ns;
                        else
                            _speed += ns;

                    }


                    if (!_sliding)
                    {
                        _sliding = true;
                    }

                    SlidingEvent sd(SlidingEvent::BEGIN);
                    sd.speed = _speed;
                    dispatchEvent(&sd);
                    _speed = sd.speed;

                    _lastIterTime = tm;
                }
            }
            break;

            case TouchEvent::MOVE:
            {
                if (te->index == _finger)
                {
                    Vector2 offset = _downPos - te->localPosition;
                    float d = offset.dot(offset);
                    if (_holded && (d >= _rad * _rad))
                    {
                        spActor act = safeSpCast<Actor>(_holded);

                        while (act && act.get() != _content.get())
                        {
                            for (int i = 0; i < MouseButton_Num; ++i)
                            {
                                act->setNotPressed((MouseButton)i);

                                TouchEvent ev(TouchEvent::TOUCH_UP, true, Vector2(-100000, -100000));
                                ev.mouseButton = (MouseButton)i;
                                ev.index = te->index;
                                ev.bubbles = false;
                                act->dispatchEvent(&ev);

                            }
                            act = act->getParent();
                        }

                        _holded = 0;
                    }
                }
            }
            break;
        }
    }
예제 #30
0
    void DebugActor::doUpdate(const UpdateState& us)
    {
        static int fps = 0;
        ++_frames;
        if (_frames > 50)
        {
            timeMS this_time = getTimeMS();
            if (this_time != _startTime)
            {
                fps = int(((float)_frames / (this_time - _startTime)) * 1000);
            }
            _startTime = this_time;
            _frames = 0;
        }

        std::stringstream s;
        s << "fps=" << fps << std::endl;



#ifdef __S3E__
        int mem_used = -1;
        int mem_free = -1;

        mem_used = s3eMemoryGetInt(S3E_MEMORY_USED);
        mem_free = s3eMemoryGetInt(S3E_MEMORY_FREE);

        s << "mfree=" << mem_free << " mem=" << mem_used << std::endl;
#endif



#ifdef OXYGINE_DEBUG_TRACE_LEAKS
        s << "objects=" << (int)ObjectBase::__getCreatedObjects().size() << std::endl;
#endif
#ifdef OXYGINE_TRACE_VIDEO_STATS
        s << "batches=" << _videoStats.batches << " triangles=" << _videoStats.triangles << std::endl;
#endif
        s << "update=" << getStage()->_statUpdate << "ms ";
        s << "render=" << getStage()->_statRender << "ms ";
        s << "textures=" << NativeTexture::created << " ";
        s << "\nlisteners=" << getStage()->getListenersCount() << "";

        if (!_debugText.empty())
        {
            s << "\n";
            s << _debugText;
        }
        _debugText = "";

        _text->setText(s.str());


        setHeight(_text->getTextRect().size.y + _text->getY() + 3);
        _bg->setSize(getSize());


        Vector2 ds = core::getDisplaySize();

        Vector2 pos(0, 0);

        switch (_corner)
        {
            case 1:
                pos.x = ds.x;
                break;
            case 2:
                pos = ds;
                break;
            case 3:
                pos.y = ds.y;
                break;
        }

        pos = getStage()->global2local(pos);

        Vector2 realSize = getScaledSize();
        switch (_corner)
        {
            case 1:
                pos.x -= realSize.x;
                break;
            case 2:
                pos -= realSize;
                break;
            case 3:
                pos.y -= realSize.y;
                break;
        }

        setPosition(pos);
        setScale(1.0f / getStage()->getScaleX());
    }