Пример #1
0
/*
================
idTarget_FadeEntity::Event_Activate
================
*/
void idTarget_FadeEntity::Event_Activate( idEntity *activator ) {
	idEntity *ent;
	int i;

	if ( !targets.Num() ) {
		return;
	}

	// always allow during cinematics
	cinematic = true;
	BecomeActive( TH_THINK );

	ent = this;
	for( i = 0; i < targets.Num(); i++ ) {
		ent = targets[ i ].GetEntity();
		if ( ent ) {
			ent->GetColor( fadeFrom );
			break;
		}
	}

	fadeStart = gameLocal.time;
	fadeEnd = gameLocal.time + SEC2MS( spawnArgs.GetFloat( "fadetime" ) );
}
Пример #2
0
/*
================
idTrigger_Hurt::Event_Touch
================
*/
void idTrigger_Hurt::Event_Touch( idEntity *other, trace_t *trace )
{
	const char *damage;
	
	if( on && other && gameLocal.time >= nextTime )
	{
#ifdef _D3XP
		bool playerOnly = spawnArgs.GetBool( "playerOnly" );
		if( playerOnly )
		{
			if( !other->IsType( idPlayer::Type ) )
			{
				return;
			}
		}
#endif
		damage = spawnArgs.GetString( "def_damage", "damage_painTrigger" );
		
#ifdef _D3XP
		idVec3 dir = vec3_origin;
		if( spawnArgs.GetBool( "kick_from_center", "0" ) )
		{
			dir = other->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin();
			dir.Normalize();
		}
		other->Damage( NULL, NULL, dir, damage, 1.0f, INVALID_JOINT );
#else
		other->Damage( NULL, NULL, vec3_origin, damage, 1.0f, INVALID_JOINT );
#endif
		
		ActivateTargets( other );
		CallScript();
		
		nextTime = gameLocal.time + SEC2MS( delay );
	}
}
Пример #3
0
bool CClientList::IsKadFirewallCheckIP(uint32 dwIP) const{
	for (POSITION pos = listFirewallCheckRequests.GetHeadPosition(); pos != NULL; listFirewallCheckRequests.GetNext(pos)){
		if (listFirewallCheckRequests.GetAt(pos).dwIP == dwIP && ::GetTickCount() - listFirewallCheckRequests.GetAt(pos).dwInserted < SEC2MS(180))
			return true;
	}
	return false;
}
/**
 * The thread method that handles calling send for the individual sockets.
 *
 * Control packets will always be tried to be sent first. If there is any bandwidth leftover
 * after that, send() for the upload slot sockets will be called in priority order until we have run
 * out of available bandwidth for this loop. Upload slots will not be allowed to go without having sent
 * called for more than a defined amount of time (i.e. two seconds).
 *
 * @return always returns 0.
 */
UINT UploadBandwidthThrottler::RunInternal() {
    DWORD lastLoopTick = timeGetTime();
    sint64 realBytesToSpend = 0;
    uint32 allowedDataRate = 0;
    uint32 rememberedSlotCounter = 0;
    DWORD lastTickReachedBandwidth = timeGetTime();

    uint32 nEstiminatedLimit = 0;
    int nSlotsBusyLevel = 0;
    DWORD nUploadStartTime = 0;
    uint32 numberOfConsecutiveUpChanges = 0;
    uint32 numberOfConsecutiveDownChanges = 0;
    uint32 changesCount = 0;
    uint32 loopsCount = 0;

    bool estimateChangedLog = false;
    bool lotsOfLog = false;

    while(doRun) {
        pauseEvent->Lock();

        DWORD timeSinceLastLoop = timeGetTime() - lastLoopTick;

        // Get current speed from UploadSpeedSense
        allowedDataRate = theApp.lastCommonRouteFinder->GetUpload();

        // check busy level for all the slots (WSAEWOULDBLOCK status)
        uint32 cBusy = 0;
        uint32 nCanSend = 0;

        sendLocker.Lock();
        for (int i = 0; i < m_StandardOrder_list.GetSize() && (i < 3 || (UINT)i < GetSlotLimit(theApp.uploadqueue->GetDatarate())); i++) {
            if (m_StandardOrder_list[i] != NULL && m_StandardOrder_list[i]->HasQueues()) {
                nCanSend++;

                if(m_StandardOrder_list[i]->IsBusy())
                    cBusy++;
            }
        }
        sendLocker.Unlock();

        // if this is kept, the loop above can be a little optimized (don't count nCanSend, just use nCanSend = GetSlotLimit(theApp.uploadqueue->GetDatarate())
        if(theApp.uploadqueue)
            nCanSend = max(nCanSend, GetSlotLimit(theApp.uploadqueue->GetDatarate()));

        // When no upload limit has been set in options, try to guess a good upload limit.
        bool bUploadUnlimited = (thePrefs.GetMaxUpload() == UNLIMITED);
        if (bUploadUnlimited) {
            loopsCount++;

            //if(lotsOfLog) theApp.QueueDebugLogLine(false,_T("Throttler: busy: %i/%i nSlotsBusyLevel: %i Guessed limit: %0.5f changesCount: %i loopsCount: %i"), cBusy, nCanSend, nSlotsBusyLevel, (float)nEstiminatedLimit/1024.00f, changesCount, loopsCount);

            if(nCanSend > 0) {
                float fBusyPercent = ((float)cBusy/(float)nCanSend) * 100;
                if (cBusy > 2 && fBusyPercent > 75.00f && nSlotsBusyLevel < 255) {
                    nSlotsBusyLevel++;
                    changesCount++;
                    if(thePrefs.GetVerbose() && lotsOfLog && nSlotsBusyLevel%25==0) theApp.QueueDebugLogLine(false,_T("Throttler: nSlotsBusyLevel: %i Guessed limit: %0.5f changesCount: %i loopsCount: %i"), nSlotsBusyLevel, (float)nEstiminatedLimit/1024.00f, changesCount, loopsCount);
                }
                else if ( (cBusy <= 2 || fBusyPercent < 25.00f) && nSlotsBusyLevel > (-255)) {
                    nSlotsBusyLevel--;
                    changesCount++;
                    if(thePrefs.GetVerbose() && lotsOfLog && nSlotsBusyLevel%25==0) theApp.QueueDebugLogLine(false,_T("Throttler: nSlotsBusyLevel: %i Guessed limit: %0.5f changesCount %i loopsCount: %i"), nSlotsBusyLevel, (float)nEstiminatedLimit/1024.00f, changesCount, loopsCount);
                }
            }

            if(nUploadStartTime == 0) {
                if (m_StandardOrder_list.GetSize() >= 3)
                    nUploadStartTime = timeGetTime();
            } else if(timeGetTime()- nUploadStartTime > SEC2MS(60)) {
                if (theApp.uploadqueue) {
                    if (nEstiminatedLimit == 0) { // no autolimit was set yet
                        if (nSlotsBusyLevel >= 250) { // sockets indicated that the BW limit has been reached
                            nEstiminatedLimit = theApp.uploadqueue->GetDatarate();
                            allowedDataRate = min(nEstiminatedLimit, allowedDataRate);
                            nSlotsBusyLevel = -200;
                            if(thePrefs.GetVerbose() && estimateChangedLog) theApp.QueueDebugLogLine(false,_T("Throttler: Set inital estimated limit to %0.5f changesCount: %i loopsCount: %i"), (float)nEstiminatedLimit/1024.00f, changesCount, loopsCount);
                            changesCount = 0;
                            loopsCount = 0;
                        }
                    }
                    else {
                        if (nSlotsBusyLevel > 250) {
                            if(changesCount > 500 || changesCount > 300 && loopsCount > 1000 || loopsCount > 2000) {
                                numberOfConsecutiveDownChanges = 0;
                            }
                            numberOfConsecutiveDownChanges++;
                            uint32 changeDelta = CalculateChangeDelta(numberOfConsecutiveDownChanges);

                            // Don't lower speed below 1 KBytes/s
                            if(nEstiminatedLimit < changeDelta + 1024) {
                                if(nEstiminatedLimit > 1024) {
                                    changeDelta = nEstiminatedLimit - 1024;
                                } else {
                                    changeDelta = 0;
                                }
                            }
                            ASSERT(nEstiminatedLimit >= changeDelta + 1024);
                            nEstiminatedLimit -= changeDelta;

                            if(thePrefs.GetVerbose() && estimateChangedLog) theApp.QueueDebugLogLine(false,_T("Throttler: REDUCED limit #%i with %i bytes to: %0.5f changesCount: %i loopsCount: %i"), numberOfConsecutiveDownChanges, changeDelta, (float)nEstiminatedLimit/1024.00f, changesCount, loopsCount);

                            numberOfConsecutiveUpChanges = 0;
                            nSlotsBusyLevel = 0;
                            changesCount = 0;
                            loopsCount = 0;
                        }
                        else if (nSlotsBusyLevel < (-250)) {
                            if(changesCount > 500 || changesCount > 300 && loopsCount > 1000 || loopsCount > 2000) {
                                numberOfConsecutiveUpChanges = 0;
                            }
                            numberOfConsecutiveUpChanges++;
                            uint32 changeDelta = CalculateChangeDelta(numberOfConsecutiveUpChanges);

                            // Don't raise speed unless we are under current allowedDataRate
                            if(nEstiminatedLimit+changeDelta > allowedDataRate) {
                                if(nEstiminatedLimit < allowedDataRate) {
                                    changeDelta = allowedDataRate - nEstiminatedLimit;
                                } else {
                                    changeDelta = 0;
                                }
                            }
                            ASSERT(nEstiminatedLimit < allowedDataRate && nEstiminatedLimit+changeDelta <= allowedDataRate || nEstiminatedLimit >= allowedDataRate && changeDelta == 0);
                            nEstiminatedLimit += changeDelta;

                            if(thePrefs.GetVerbose() && estimateChangedLog) theApp.QueueDebugLogLine(false,_T("Throttler: INCREASED limit #%i with %i bytes to: %0.5f changesCount: %i loopsCount: %i"), numberOfConsecutiveUpChanges, changeDelta, (float)nEstiminatedLimit/1024.00f, changesCount, loopsCount);

                            numberOfConsecutiveDownChanges = 0;
                            nSlotsBusyLevel = 0;
                            changesCount = 0;
                            loopsCount = 0;
                        }

                        allowedDataRate = min(nEstiminatedLimit, allowedDataRate);
                    }
                }
            }
        }

        if(cBusy == nCanSend && m_StandardOrder_list.GetSize() > 0) {
            allowedDataRate = 0;
            if(nSlotsBusyLevel < 125 && bUploadUnlimited) {
                nSlotsBusyLevel = 125;
                if(thePrefs.GetVerbose() && lotsOfLog) theApp.QueueDebugLogLine(false,_T("Throttler: nSlotsBusyLevel: %i Guessed limit: %0.5f changesCount %i loopsCount: %i (set due to all slots busy)"), nSlotsBusyLevel, (float)nEstiminatedLimit/1024.00f, changesCount, loopsCount);
            }
        }

        uint32 minFragSize = 1300;
        uint32 doubleSendSize = minFragSize*2; // send two packages at a time so they can share an ACK
        if(allowedDataRate < 6*1024) {
            minFragSize = 536;
            doubleSendSize = minFragSize; // don't send two packages at a time at very low speeds to give them a smoother load
        }

#define TIME_BETWEEN_UPLOAD_LOOPS 1
        uint32 sleepTime;
        if(allowedDataRate == _UI32_MAX || realBytesToSpend >= 1000 || allowedDataRate == 0 && nEstiminatedLimit == 0) {
            // we could send at once, but sleep a while to not suck up all cpu
            sleepTime = TIME_BETWEEN_UPLOAD_LOOPS;
        } else if(allowedDataRate == 0) {
            sleepTime = max((uint32)ceil(((double)doubleSendSize*1000)/nEstiminatedLimit), TIME_BETWEEN_UPLOAD_LOOPS);
        } else {
            // sleep for just as long as we need to get back to having one byte to send
            sleepTime = max((uint32)ceil((double)(-realBytesToSpend + 1000)/allowedDataRate), TIME_BETWEEN_UPLOAD_LOOPS);

        }

        if(timeSinceLastLoop < sleepTime) {
            Sleep(sleepTime-timeSinceLastLoop);
        }

        const DWORD thisLoopTick = timeGetTime();
        timeSinceLastLoop = thisLoopTick - lastLoopTick;

        // Calculate how many bytes we can spend
        sint64 bytesToSpend = 0;

        if(allowedDataRate != _UI32_MAX) {
            // prevent overflow
            if(timeSinceLastLoop == 0) {
                // no time has passed, so don't add any bytes. Shouldn't happen.
                bytesToSpend = 0; //realBytesToSpend/1000;
            } else if(_I64_MAX/timeSinceLastLoop > allowedDataRate && _I64_MAX-allowedDataRate*timeSinceLastLoop > realBytesToSpend) {
                if(timeSinceLastLoop > sleepTime + 2000) {
                    theApp.QueueDebugLogLine(false,_T("UploadBandwidthThrottler: Time since last loop too long. time: %ims wanted: %ims Max: %ims"), timeSinceLastLoop, sleepTime, sleepTime + 2000);

                    timeSinceLastLoop = sleepTime + 2000;
                    lastLoopTick = thisLoopTick - timeSinceLastLoop;
                }

                realBytesToSpend += allowedDataRate*timeSinceLastLoop;

                bytesToSpend = realBytesToSpend/1000;
            } else {
                realBytesToSpend = _I64_MAX;
                bytesToSpend = _I32_MAX;
            }
        } else {
            realBytesToSpend = 0; //_I64_MAX;
            bytesToSpend = _I32_MAX;
        }

        lastLoopTick = thisLoopTick;

        if(bytesToSpend >= 1 || allowedDataRate == 0) {
            uint64 spentBytes = 0;
            uint64 spentOverhead = 0;

            sendLocker.Lock();

            tempQueueLocker.Lock();

            // are there any sockets in m_TempControlQueue_list? Move them to normal m_ControlQueue_list;
            while(!m_TempControlQueueFirst_list.IsEmpty()) {
                ThrottledControlSocket* moveSocket = m_TempControlQueueFirst_list.RemoveHead();
                m_ControlQueueFirst_list.AddTail(moveSocket);
            }
            while(!m_TempControlQueue_list.IsEmpty()) {
                ThrottledControlSocket* moveSocket = m_TempControlQueue_list.RemoveHead();
                m_ControlQueue_list.AddTail(moveSocket);
            }

            tempQueueLocker.Unlock();

            // Send any queued up control packets first
            while((bytesToSpend > 0 && spentBytes < (uint64)bytesToSpend || allowedDataRate == 0 && spentBytes < 500) && (!m_ControlQueueFirst_list.IsEmpty() || !m_ControlQueue_list.IsEmpty())) {
                ThrottledControlSocket* socket = NULL;

                if(!m_ControlQueueFirst_list.IsEmpty()) {
                    socket = m_ControlQueueFirst_list.RemoveHead();
                } else if(!m_ControlQueue_list.IsEmpty()) {
                    socket = m_ControlQueue_list.RemoveHead();
                }

                if(socket != NULL) {
                    SocketSentBytes socketSentBytes = socket->SendControlData(allowedDataRate > 0?(UINT)(bytesToSpend - spentBytes):1, minFragSize);
                    uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
                    spentBytes += lastSpentBytes;
                    spentOverhead += socketSentBytes.sentBytesControlPackets;
                }
            }

            // Check if any sockets haven't gotten data for a long time. Then trickle them a package.
            for(uint32 slotCounter = 0; slotCounter < (uint32)m_StandardOrder_list.GetSize(); slotCounter++) {
                ThrottledFileSocket* socket = m_StandardOrder_list.GetAt(slotCounter);

                if(socket != NULL) {
                    if(thisLoopTick-socket->GetLastCalledSend() > SEC2MS(1)) {
                        // trickle
                        uint32 neededBytes = socket->GetNeededBytes();

                        if(neededBytes > 0) {
                            SocketSentBytes socketSentBytes = socket->SendFileAndControlData(neededBytes, minFragSize);
                            uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
                            spentBytes += lastSpentBytes;
                            spentOverhead += socketSentBytes.sentBytesControlPackets;

                            if(lastSpentBytes > 0 && slotCounter < m_highestNumberOfFullyActivatedSlots) {
                                m_highestNumberOfFullyActivatedSlots = slotCounter;
                            }
                        }
                    }
                } else {
                    theApp.QueueDebugLogLine(false,_T("There was a NULL socket in the UploadBandwidthThrottler Standard list (trickle)! Prevented usage. Index: %i Size: %i"), slotCounter, m_StandardOrder_list.GetSize());
                }
            }

            // Equal bandwidth for all slots
            uint32 maxSlot = (uint32)m_StandardOrder_list.GetSize();
            if(maxSlot > 0 && allowedDataRate/maxSlot < UPLOAD_CLIENT_DATARATE) {
                maxSlot = allowedDataRate/UPLOAD_CLIENT_DATARATE;
            }

            if(maxSlot > m_highestNumberOfFullyActivatedSlots) {
                m_highestNumberOfFullyActivatedSlots = maxSlot;
            }

            for(uint32 maxCounter = 0; maxCounter < min(maxSlot, (uint32)m_StandardOrder_list.GetSize()) && bytesToSpend > 0 && spentBytes < (uint64)bytesToSpend; maxCounter++) {
                if(rememberedSlotCounter >= (uint32)m_StandardOrder_list.GetSize() ||
                        rememberedSlotCounter >= maxSlot) {
                    rememberedSlotCounter = 0;
                }

                ThrottledFileSocket* socket = m_StandardOrder_list.GetAt(rememberedSlotCounter);

                if(socket != NULL) {
                    SocketSentBytes socketSentBytes = socket->SendFileAndControlData((UINT)min(doubleSendSize, bytesToSpend-spentBytes), doubleSendSize);
                    uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;

                    spentBytes += lastSpentBytes;
                    spentOverhead += socketSentBytes.sentBytesControlPackets;
                } else {
                    theApp.QueueDebugLogLine(false,_T("There was a NULL socket in the UploadBandwidthThrottler Standard list (equal-for-all)! Prevented usage. Index: %i Size: %i"), rememberedSlotCounter, m_StandardOrder_list.GetSize());
                }

                rememberedSlotCounter++;
            }

            // Any bandwidth that hasn't been used yet are used first to last.
            for(uint32 slotCounter = 0; slotCounter < (uint32)m_StandardOrder_list.GetSize() && bytesToSpend > 0 && spentBytes < (uint64)bytesToSpend; slotCounter++) {
                ThrottledFileSocket* socket = m_StandardOrder_list.GetAt(slotCounter);

                if(socket != NULL) {
                    uint32 bytesToSpendTemp = (UINT)(bytesToSpend-spentBytes);
                    SocketSentBytes socketSentBytes = socket->SendFileAndControlData(bytesToSpendTemp, doubleSendSize);
                    uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;

                    spentBytes += lastSpentBytes;
                    spentOverhead += socketSentBytes.sentBytesControlPackets;

                    if(slotCounter+1 > m_highestNumberOfFullyActivatedSlots && (lastSpentBytes < bytesToSpendTemp || lastSpentBytes >= doubleSendSize)) { // || lastSpentBytes > 0 && spentBytes == bytesToSpend /*|| slotCounter+1 == (uint32)m_StandardOrder_list.GetSize())*/)) {
                        m_highestNumberOfFullyActivatedSlots = slotCounter+1;
                    }
                } else {
                    theApp.QueueDebugLogLine(false,_T("There was a NULL socket in the UploadBandwidthThrottler Standard list (fully activated)! Prevented usage. Index: %i Size: %i"), slotCounter, m_StandardOrder_list.GetSize());
                }
            }
            realBytesToSpend -= spentBytes*1000;

            // If we couldn't spend all allocated bandwidth this loop, some of it is allowed to be saved
            // and used the next loop
            if(realBytesToSpend < -(((sint64)m_StandardOrder_list.GetSize()+1)*minFragSize)*1000) {
                sint64 newRealBytesToSpend = -(((sint64)m_StandardOrder_list.GetSize()+1)*minFragSize)*1000;

                realBytesToSpend = newRealBytesToSpend;
                lastTickReachedBandwidth = thisLoopTick;
            } else {
                uint64 bandwidthSavedTolerance = 0;
                if(realBytesToSpend > 0 && (uint64)realBytesToSpend > 999+bandwidthSavedTolerance) {
                    sint64 newRealBytesToSpend = 999+bandwidthSavedTolerance;
                    //theApp.QueueDebugLogLine(false,_T("UploadBandwidthThrottler::RunInternal(): Too high saved bytesToSpend. Limiting value. Old value: %I64i New value: %I64i"), realBytesToSpend, newRealBytesToSpend);
                    realBytesToSpend = newRealBytesToSpend;

                    if(thisLoopTick-lastTickReachedBandwidth > max(1000, timeSinceLastLoop*2)) {
                        m_highestNumberOfFullyActivatedSlots = m_StandardOrder_list.GetSize()+1;
                        lastTickReachedBandwidth = thisLoopTick;
                        //theApp.QueueDebugLogLine(false, _T("UploadBandwidthThrottler: Throttler requests new slot due to bw not reached. m_highestNumberOfFullyActivatedSlots: %i m_StandardOrder_list.GetSize(): %i tick: %i"), m_highestNumberOfFullyActivatedSlots, m_StandardOrder_list.GetSize(), thisLoopTick);
                    }
                } else {
                    lastTickReachedBandwidth = thisLoopTick;
                }
            }

            // save info about how much bandwidth we've managed to use since the last time someone polled us about used bandwidth
            m_SentBytesSinceLastCall += spentBytes;
            m_SentBytesSinceLastCallOverhead += spentOverhead;

            sendLocker.Unlock();
        }
    }

    threadEndedEvent->SetEvent();

    tempQueueLocker.Lock();
    m_TempControlQueue_list.RemoveAll();
    m_TempControlQueueFirst_list.RemoveAll();
    tempQueueLocker.Unlock();

    sendLocker.Lock();

    m_ControlQueue_list.RemoveAll();
    m_StandardOrder_list.RemoveAll();
    sendLocker.Unlock();

    return 0;
}
Пример #5
0
/*
================
idClass::PostEventSec
================
*/
bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4 ) {
	return PostEventArgs( ev, SEC2MS( time ), 4, &arg1, &arg2, &arg3, &arg4 );
}
Пример #6
0
/*
====================
idRenderModelLiquid::InitFromFile
====================
*/
void idRenderModelLiquid::InitFromFile( const char* fileName )
{
	int				i, x, y;
	idToken			token;
	idParser		parser( LEXFL_ALLOWPATHNAMES | LEXFL_NOSTRINGESCAPECHARS );
	idList<int>		tris;
	float			size_x, size_y;
	float			rate;
	
	name = fileName;
	
	if( !parser.LoadFile( fileName ) )
	{
		MakeDefaultModel();
		return;
	}
	
	size_x = scale_x * verts_x;
	size_y = scale_y * verts_y;
	
	while( parser.ReadToken( &token ) )
	{
		if( !token.Icmp( "seed" ) )
		{
			seed = parser.ParseInt();
		}
		else if( !token.Icmp( "size_x" ) )
		{
			size_x = parser.ParseFloat();
		}
		else if( !token.Icmp( "size_y" ) )
		{
			size_y = parser.ParseFloat();
		}
		else if( !token.Icmp( "verts_x" ) )
		{
			verts_x = parser.ParseFloat();
			if( verts_x < 2 )
			{
				parser.Warning( "Invalid # of verts.  Using default model." );
				MakeDefaultModel();
				return;
			}
		}
		else if( !token.Icmp( "verts_y" ) )
		{
			verts_y = parser.ParseFloat();
			if( verts_y < 2 )
			{
				parser.Warning( "Invalid # of verts.  Using default model." );
				MakeDefaultModel();
				return;
			}
		}
		else if( !token.Icmp( "liquid_type" ) )
		{
			liquid_type = parser.ParseInt() - 1;
			if( ( liquid_type < 0 ) || ( liquid_type >= LIQUID_MAX_TYPES ) )
			{
				parser.Warning( "Invalid liquid_type.  Using default model." );
				MakeDefaultModel();
				return;
			}
		}
		else if( !token.Icmp( "density" ) )
		{
			density = parser.ParseFloat();
		}
		else if( !token.Icmp( "drop_height" ) )
		{
			drop_height = parser.ParseFloat();
		}
		else if( !token.Icmp( "drop_radius" ) )
		{
			drop_radius = parser.ParseInt();
		}
		else if( !token.Icmp( "drop_delay" ) )
		{
			drop_delay = SEC2MS( parser.ParseFloat() );
		}
		else if( !token.Icmp( "shader" ) )
		{
			parser.ReadToken( &token );
			shader = declManager->FindMaterial( token );
		}
		else if( !token.Icmp( "update_rate" ) )
		{
			rate = parser.ParseFloat();
			if( ( rate <= 0.0f ) || ( rate > 60.0f ) )
			{
				parser.Warning( "Invalid update_rate.  Must be between 0 and 60.  Using default model." );
				MakeDefaultModel();
				return;
			}
			update_tics = 1000 / rate;
		}
		else
		{
			parser.Warning( "Unknown parameter '%s'.  Using default model.", token.c_str() );
			MakeDefaultModel();
			return;
		}
	}
	
	scale_x = size_x / ( verts_x - 1 );
	scale_y = size_y / ( verts_y - 1 );
	
	pages.SetNum( 2 * verts_x * verts_y );
	page1 = pages.Ptr();
	page2 = page1 + verts_x * verts_y;
	
	verts.SetNum( verts_x * verts_y );
	for( i = 0, y = 0; y < verts_y; y++ )
	{
		for( x = 0; x < verts_x; x++, i++ )
		{
			page1[ i ] = 0.0f;
			page2[ i ] = 0.0f;
			verts[ i ].Clear();
			verts[ i ].xyz.Set( x * scale_x, y * scale_y, 0.0f );
			verts[ i ].SetTexCoord( ( float ) x / ( float )( verts_x - 1 ), ( float ) - y / ( float )( verts_y - 1 ) );
		}
	}
	
	tris.SetNum( ( verts_x - 1 ) * ( verts_y - 1 ) * 6 );
	for( i = 0, y = 0; y < verts_y - 1; y++ )
	{
		for( x = 1; x < verts_x; x++, i += 6 )
		{
			tris[ i + 0 ] = y * verts_x + x;
			tris[ i + 1 ] = y * verts_x + x - 1;
			tris[ i + 2 ] = ( y + 1 ) * verts_x + x - 1;
			
			tris[ i + 3 ] = ( y + 1 ) * verts_x + x - 1;
			tris[ i + 4 ] = ( y + 1 ) * verts_x + x;
			tris[ i + 5 ] = y * verts_x + x;
		}
	}
	
	// build the information that will be common to all animations of this mesh:
	// sil edge connectivity and normal / tangent generation information
	deformInfo = R_BuildDeformInfo( verts.Num(), verts.Ptr(), tris.Num(), tris.Ptr(), true );
	
	bounds.Clear();
	bounds.AddPoint( idVec3( 0.0f, 0.0f, drop_height * -10.0f ) );
	bounds.AddPoint( idVec3( ( verts_x - 1 ) * scale_x, ( verts_y - 1 ) * scale_y, drop_height * 10.0f ) );
	
	// set the timestamp for reloadmodels
	fileSystem->ReadFile( name, NULL, &timeStamp );
	
	Reset();
}
void rvMonsterStreamProtector::InitSpawnArgsVariables ( void ) {
	jointPlasmaMuzzle = animator.GetJointHandle ( spawnArgs.GetString ( "joint_plasmaMuzzle", "NM_muzzle" ) );
	
	plasmaAttackRate = SEC2MS ( spawnArgs.GetFloat ( "attack_plasma_rate", ".15" ) );
}
Пример #8
0
/*
================
idTarget_SetInfluence::Event_Activate
================
*/
void idTarget_SetInfluence::Event_Activate( idEntity *activator )
{
	int i, j;
	idEntity *ent;
	idLight *light;
	idSound *sound;
	idStaticEntity *generic;
	const char *parm;
	const char *skin;
	bool update;
	idVec3 color;
	idVec4 colorTo;
	idPlayer *player;
	
	player = gameLocal.GetLocalPlayer();
	
	if( spawnArgs.GetBool( "triggerActivate" ) )
	{
		if( restoreOnTrigger )
		{
			ProcessEvent( &EV_RestoreInfluence );
			restoreOnTrigger = false;
			return;
		}
		restoreOnTrigger = true;
	}
	
	float fadeTime = spawnArgs.GetFloat( "fadeWorldSounds" );
	
	if( delay > 0.0f )
	{
		PostEventSec( &EV_Activate, delay, activator );
		delay = 0.0f;
		// start any sound fading now
		if( fadeTime )
		{
			gameSoundWorld->FadeSoundClasses( 0, -40.0f, fadeTime );
			soundFaded = true;
		}
		return;
	}
	else if( fadeTime && !soundFaded )
	{
		gameSoundWorld->FadeSoundClasses( 0, -40.0f, fadeTime );
		soundFaded = true;
	}
	
	if( spawnArgs.GetBool( "triggerTargets" ) )
	{
		ActivateTargets( activator );
	}
	
	if( flashIn )
	{
		PostEventSec( &EV_Flash, 0.0f, flashIn, 0 );
	}
	
	parm = spawnArgs.GetString( "snd_influence" );
	if( parm && *parm )
	{
		PostEventSec( &EV_StartSoundShader, flashIn, parm, SND_CHANNEL_ANY );
	}
	
	if( switchToCamera )
	{
		switchToCamera->PostEventSec( &EV_Activate, flashIn + 0.05f, this );
	}
	
	int fov = spawnArgs.GetInt( "fov" );
	if( fov )
	{
		fovSetting.Init( gameLocal.time, SEC2MS( spawnArgs.GetFloat( "fovTime" ) ), player->DefaultFov(), fov );
		BecomeActive( TH_THINK );
	}
	
	for( i = 0; i < genericList.Num(); i++ )
	{
		ent = gameLocal.entities[genericList[i]];
		if( ent == NULL )
		{
			continue;
		}
		generic = static_cast<idStaticEntity *>( ent );
		color = generic->spawnArgs.GetVector( "color_demonic" );
		colorTo.Set( color.x, color.y, color.z, 1.0f );
		generic->Fade( colorTo, spawnArgs.GetFloat( "fade_time", "0.25" ) );
	}
	
	for( i = 0; i < lightList.Num(); i++ )
	{
		ent = gameLocal.entities[lightList[i]];
		if( ent == NULL || !ent->IsType( idLight::Type ) )
		{
			continue;
		}
		light = static_cast<idLight *>( ent );
		parm = light->spawnArgs.GetString( "mat_demonic" );
		if( parm && *parm )
		{
			light->SetShader( parm );
		}
		
		color = light->spawnArgs.GetVector( "_color" );
		color = light->spawnArgs.GetVector( "color_demonic", color.ToString() );
		colorTo.Set( color.x, color.y, color.z, 1.0f );
		light->Fade( colorTo, spawnArgs.GetFloat( "fade_time", "0.25" ) );
	}
	
	for( i = 0; i < soundList.Num(); i++ )
	{
		ent = gameLocal.entities[soundList[i]];
		if( ent == NULL || !ent->IsType( idSound::Type ) )
		{
			continue;
		}
		sound = static_cast<idSound *>( ent );
		parm = sound->spawnArgs.GetString( "snd_demonic" );
		if( parm && *parm )
		{
			if( sound->spawnArgs.GetBool( "overlayDemonic" ) )
			{
				sound->StartSound( "snd_demonic", SND_CHANNEL_DEMONIC, 0, false, NULL );
			}
			else
			{
				sound->StopSound( SND_CHANNEL_ANY, false );
				sound->SetSound( parm );
			}
		}
	}
	
	for( i = 0; i < guiList.Num(); i++ )
	{
		ent = gameLocal.entities[guiList[i]];
		if( ent == NULL || ent->GetRenderEntity() == NULL )
		{
			continue;
		}
		update = false;
		
		for( j = 0; j < MAX_RENDERENTITY_GUI; j++ )
		{
			if( ent->GetRenderEntity()->gui[ j ] && ent->spawnArgs.FindKey( j == 0 ? "gui_demonic" : va( "gui_demonic%d", j + 1 ) ) )
			{
#ifdef _D3XP
				//Backup the old one
				savedGuiList[i].gui[j] = ent->GetRenderEntity()->gui[ j ];
#endif
				ent->GetRenderEntity()->gui[ j ] = uiManager->FindGui( ent->spawnArgs.GetString( j == 0 ? "gui_demonic" : va( "gui_demonic%d", j + 1 ) ), true );
				update = true;
			}
		}
		
		if( update )
		{
			ent->UpdateVisuals();
			ent->Present();
		}
	}
	
	player->SetInfluenceLevel( spawnArgs.GetInt( "influenceLevel" ) );
	
	int snapAngle = spawnArgs.GetInt( "snapAngle" );
	if( snapAngle )
	{
		idAngles ang( 0, snapAngle, 0 );
		player->SetViewAngles( ang );
		player->SetAngles( ang );
	}
	
	if( spawnArgs.GetBool( "effect_vision" ) )
	{
		parm = spawnArgs.GetString( "mtrVision" );
		skin = spawnArgs.GetString( "skinVision" );
		player->SetInfluenceView( parm, skin, spawnArgs.GetInt( "visionRadius" ), this );
	}
	
	parm = spawnArgs.GetString( "mtrWorld" );
	if( parm && *parm )
	{
		gameLocal.SetGlobalMaterial( declManager->FindMaterial( parm ) );
	}
	
	if( !restoreOnTrigger )
	{
		PostEventMS( &EV_RestoreInfluence, SEC2MS( spawnArgs.GetFloat( "time" ) ) );
	}
}
Пример #9
0
Файл: kad.c Проект: mzhel/libkad
bool
kad_session_init(
                 uint16_t tcp_port,
                 uint16_t udp_port,
                 char* nodes_file_path,
                 KAD_SESSION** ks_out
                 )
{
  bool result = false;
  KAD_SESSION* ks = NULL;
  char host_name[HOST_NAME_MAX + 1];
  struct hostent* he = NULL;
  UINT128 zone_idx;
  uint32_t now = 0;

  do {

    LOG_PREFIX("[libkad] ");

    LOG_LEVEL_DEBUG;

    LOG_FILE_NAME("libkad.log");

    LOG_OUTPUT_CONSOLE_AND_FILE;
    
    if (!ks_out) break;

    ks = (KAD_SESSION*)mem_alloc(sizeof(KAD_SESSION));

    if (!ks){

      LOG_ERROR("Failed to allocate memory for kad session.");

      break;

    }

    ks->version = KADEMLIA_VERSION;

    random_init(ticks_now_ms());

    gethostname(host_name, HOST_NAME_MAX);

    LOG_DEBUG("Host name: %s", host_name);

    he = gethostbyname(host_name);

    ks->loc_ip4_no = *(uint32_t*)he->h_addr;

    kad_fw_set_status(&ks->fw, true);

    kad_fw_set_status_udp(&ks->fw, true);

    uint128_generate(&ks->kad_id);

    LOG_DEBUG_UINT128("kad_id: ", ((UINT128*)&ks->kad_id));

    for (uint32_t i = 0; i < sizeof(ks->user_hash); i++){

      ks->user_hash[i] = random_uint8();

    }

    ks->user_hash[5] = 14;

    ks->user_hash[14] = 111;

    kadhlp_gen_udp_key(&ks->udp_key);

    LOG_DEBUG("udp_key: %.8x", ks->udp_key);

    ks->udp_port = udp_port;

    ks->tcp_port = tcp_port;

    LOG_DEBUG("udp_port = %d", udp_port);

    LOG_DEBUG("tcp_port = %d", tcp_port);

    uint128_init(&zone_idx, 0);

    routing_create_zone(NULL, 0, &zone_idx, &ks->root_zone);

    list_add_entry(&ks->active_zones, ks->root_zone);

    now = ticks_now_ms();

    ks->timers.self_lookup = now + MIN2MS(3);

    ks->timers.udp_port_lookup = now;

    ks->timers.nodes_count_check = now + SEC2MS(10);

    ks->opts.use_extrn_udp_port = true;

    queue_create(CONTROL_PACKET_QUEUE_LENGTH, &ks->queue_in_udp);

    queue_create(CONTROL_PACKET_QUEUE_LENGTH, &ks->queue_out_udp);

    if (nodes_file_path) kadhlp_add_nodes_from_file(ks, nodes_file_path);

    kadusr_init(ks);
  
    *ks_out = ks;

    result = true;

  } while (false);

  return result;
}
Пример #10
0
/**
 * The thread method that handles calling send for the individual sockets.
 *
 * Control packets will always be tried to be sent first. If there is any bandwidth leftover
 * after that, send() for the upload slot sockets will be called in priority order until we have run
 * out of available bandwidth for this loop. Upload slots will not be allowed to go without having sent
 * called for more than a defined amount of time (i.e. two seconds).
 *
 * @return always returns 0.
 */
void* UploadBandwidthThrottler::Entry()
{
	const uint32 TIME_BETWEEN_UPLOAD_LOOPS = 1;
	
	uint32 lastLoopTick = GetTickCountFullRes();
	// Bytes to spend in current cycle. If we spend more this becomes negative and causes a wait next time.
	sint32 bytesToSpend = 0;
	uint32 allowedDataRate = 0;
	uint32 rememberedSlotCounter = 0;
	uint32 extraSleepTime = TIME_BETWEEN_UPLOAD_LOOPS;
	
	while (m_doRun && !TestDestroy()) {
		uint32 timeSinceLastLoop = GetTickCountFullRes() - lastLoopTick;

		// Calculate data rate
		if (thePrefs::GetMaxUpload() == UNLIMITED) {
			// Try to increase the upload rate from UploadSpeedSense
			allowedDataRate = (uint32)theStats::GetUploadRate() + 5 * 1024;
		} else {
			allowedDataRate = thePrefs::GetMaxUpload() * 1024;
		}

		uint32 minFragSize = 1300;
		uint32 doubleSendSize = minFragSize*2; // send two packages at a time so they can share an ACK
		if (allowedDataRate < 6*1024) {
			minFragSize = 536;
			doubleSendSize = minFragSize; // don't send two packages at a time at very low speeds to give them a smoother load
		}


		uint32 sleepTime;
		if (bytesToSpend < 1) {
			// We have sent more than allowed in last cycle so we have to wait now
			// until we can send at least 1 byte.
			sleepTime = std::max((-bytesToSpend + 1) * 1000 / allowedDataRate + 2, // add 2 ms to allow for rounding inaccuracies
									extraSleepTime);
		} else {
			// We could send at once, but sleep a while to not suck up all cpu
			sleepTime = extraSleepTime;
		}

		if (timeSinceLastLoop < sleepTime) {
			Sleep(sleepTime-timeSinceLastLoop);
		}

		// Check after sleep in case the thread has been signaled to end
		if (!m_doRun || TestDestroy()) {
			break;
		}

		const uint32 thisLoopTick = GetTickCountFullRes();
		timeSinceLastLoop = thisLoopTick - lastLoopTick;
		lastLoopTick = thisLoopTick;

		if (timeSinceLastLoop > sleepTime + 2000) {
			AddDebugLogLineN(logGeneral, CFormat(wxT("UploadBandwidthThrottler: Time since last loop too long. time: %ims wanted: %ims Max: %ims")) 
				% timeSinceLastLoop % sleepTime % (sleepTime + 2000));

			timeSinceLastLoop = sleepTime + 2000;
		}

		// Calculate how many bytes we can spend

		bytesToSpend += (sint32) (allowedDataRate / 1000.0 * timeSinceLastLoop);

		if (bytesToSpend >= 1) {
			sint32 spentBytes = 0;
			sint32 spentOverhead = 0;

			wxMutexLocker sendLock(m_sendLocker);

			{
				wxMutexLocker queueLock(m_tempQueueLocker);

				// are there any sockets in m_TempControlQueue_list? Move them to normal m_ControlQueue_list;
				m_ControlQueueFirst_list.insert(	m_ControlQueueFirst_list.end(),
													m_TempControlQueueFirst_list.begin(),
													m_TempControlQueueFirst_list.end() );

				m_ControlQueue_list.insert( m_ControlQueue_list.end(), 
											m_TempControlQueue_list.begin(),
											m_TempControlQueue_list.end() );

				m_TempControlQueue_list.clear();
				m_TempControlQueueFirst_list.clear();
			}
	
			// Send any queued up control packets first
			while (spentBytes < bytesToSpend && (!m_ControlQueueFirst_list.empty() || !m_ControlQueue_list.empty())) {
				ThrottledControlSocket* socket = NULL;
	
				if (!m_ControlQueueFirst_list.empty()) {
					socket = m_ControlQueueFirst_list.front();
					m_ControlQueueFirst_list.pop_front();
				} else if (!m_ControlQueue_list.empty()) {
					socket = m_ControlQueue_list.front();
					m_ControlQueue_list.pop_front();
				}
	
				if (socket != NULL) {
					SocketSentBytes socketSentBytes = socket->SendControlData(bytesToSpend-spentBytes, minFragSize);
					spentBytes += socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
					spentOverhead += socketSentBytes.sentBytesControlPackets;
				}
			}
	
			// Check if any sockets haven't gotten data for a long time. Then trickle them a package.
			uint32 slots = m_StandardOrder_list.size();
			for (uint32 slotCounter = 0; slotCounter < slots; slotCounter++) {
				ThrottledFileSocket* socket = m_StandardOrder_list[ slotCounter ];
	
				if (socket != NULL) {
					if (thisLoopTick-socket->GetLastCalledSend() > SEC2MS(1)) {
						// trickle
						uint32 neededBytes = socket->GetNeededBytes();
	
						if (neededBytes > 0) {
							SocketSentBytes socketSentBytes = socket->SendFileAndControlData(neededBytes, minFragSize);
							spentBytes += socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
							spentOverhead += socketSentBytes.sentBytesControlPackets;
						}
					}
				} else {
					AddDebugLogLineN(logGeneral, CFormat( wxT("There was a NULL socket in the UploadBandwidthThrottler Standard list (trickle)! Prevented usage. Index: %i Size: %i"))
						% slotCounter % m_StandardOrder_list.size());
				}
			}
	
			// Give available bandwidth to slots, starting with the one we ended with last time.
			// There are two passes. First pass gives packets of doubleSendSize, second pass
			// gives as much as possible.
			// Second pass starts with the last slot of the first pass actually.
			for (uint32 slotCounter = 0; (slotCounter < slots * 2) && spentBytes < bytesToSpend; slotCounter++) {
				if (rememberedSlotCounter >= slots) {	// wrap around pointer
					rememberedSlotCounter = 0;
				}

				uint32 data = (slotCounter < slots - 1)	? doubleSendSize				// pass 1
															: (bytesToSpend - spentBytes);	// pass 2

				ThrottledFileSocket* socket = m_StandardOrder_list[ rememberedSlotCounter ];

				if (socket != NULL) {
					SocketSentBytes socketSentBytes = socket->SendFileAndControlData(data, doubleSendSize);
					spentBytes += socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
					spentOverhead += socketSentBytes.sentBytesControlPackets;
				} else {
					AddDebugLogLineN(logGeneral, CFormat(wxT("There was a NULL socket in the UploadBandwidthThrottler Standard list (equal-for-all)! Prevented usage. Index: %i Size: %i"))
						% rememberedSlotCounter % m_StandardOrder_list.size());
				}

				rememberedSlotCounter++;
			}

			// Do some limiting of what we keep for the next loop.
			bytesToSpend -= spentBytes;
			sint32 minBytesToSpend = (slots + 1) * minFragSize;

			if (bytesToSpend < - minBytesToSpend) {
				bytesToSpend = - minBytesToSpend;
			} else {
				sint32 bandwidthSavedTolerance = slots * 512 + 1;
				if (bytesToSpend > bandwidthSavedTolerance) {
					bytesToSpend = bandwidthSavedTolerance;
				}
			}
			
			m_SentBytesSinceLastCall += spentBytes;
			m_SentBytesSinceLastCallOverhead += spentOverhead;

			if (spentBytes == 0) {	// spentBytes includes the overhead
				extraSleepTime = std::min<uint32>(extraSleepTime * 5, 1000); // 1s at most
			} else {
				extraSleepTime = TIME_BETWEEN_UPLOAD_LOOPS;
			}
		}
	}

	{
		wxMutexLocker queueLock(m_tempQueueLocker);
		m_TempControlQueue_list.clear();
		m_TempControlQueueFirst_list.clear();
	}

	wxMutexLocker sendLock(m_sendLocker);
	m_ControlQueue_list.clear();
	m_StandardOrder_list.clear();

	return 0;
}
Пример #11
0
// RAVEN BEGIN
// jnewquist: Controller rumble
void idPlayerView::DamageImpulse( idVec3 localKickDir, const idDict *damageDef, int damage ) {
	//
	// double vision effect
	//
	float tvTime = damageDef->GetFloat( "tv_time" );
	if ( tvTime ) {
		tvStartTime = gameLocal.time;
		tvFinishTime = gameLocal.time + tvTime;		
		damageDef->GetFloat ( "tv_scale", "1", tvScale );
	}

	if ( lastDamageTime > 0.0f && SEC2MS( lastDamageTime ) + IMPULSE_DELAY > gameLocal.time ) {
		// keep shotgun from obliterating the view
		return;
	}

	//
	// double vision effect
	//
	float dvTime = damageDef->GetFloat( "dv_time" );
	if ( dvTime ) {
		dvFinishTime = gameLocal.time + (g_dvTime.GetFloat() * dvTime);
		damageDef->GetFloat ( "dv_scale", "1", dvScale );
	}

	//
	// head angle kick
	//
	const float	modifierScale = 0.25f;
	const float inverseModifier = ( 1.0f - modifierScale );

	float		modifier = idMath::ClampFloat( 0.0f, inverseModifier, damage / 100.0f * inverseModifier ) + modifierScale;
	float	kickTime = damageDef->GetFloat( "kick_time" );

	if ( kickTime ) {
		kickFinishTime = gameLocal.time + g_kickTime.GetFloat() * kickTime;

		// forward / back kick will pitch view
		kickAngles[0] = localKickDir[0];

		// side kick will yaw view
		kickAngles[1] = localKickDir[1]*0.5f;

		// up / down kick will pitch view
		kickAngles[0] += localKickDir[2];

		// roll will come from  side
		kickAngles[2] = localKickDir[1];

		float kickAmplitude = damageDef->GetFloat( "kick_amplitude" );
		if ( kickAmplitude ) {
			kickAngles *= kickAmplitude;
		}

		if ( modifier < kickAmplitude ) {
			modifier = kickAmplitude;
		}
	}
	else {
		kickTime = 500;
	}

	//
	// screen blob
	//
	float	blobTime = damageDef->GetFloat( "blob_time" );
	if ( blobTime ) {
		screenBlob_t	*blob = GetScreenBlob();
		blob->startFadeTime = gameLocal.time;
		blob->finishTime = gameLocal.time + blobTime * g_blobTime.GetFloat();

		const char *materialName = damageDef->GetString( "mtr_blob" );
		blob->material = declManager->FindMaterial( materialName );
		blob->x = damageDef->GetFloat( "blob_x" );
		blob->x += ( gameLocal.random.RandomInt()&63 ) - 32;
		blob->y = damageDef->GetFloat( "blob_y" );
		blob->y += ( gameLocal.random.RandomInt()&63 ) - 32;
		
		float scale = ( 256 + ( ( gameLocal.random.RandomInt()&63 ) - 32 ) ) / 256.0f;
		blob->w = damageDef->GetFloat( "blob_width" ) * g_blobSize.GetFloat() * scale;
		blob->h = damageDef->GetFloat( "blob_height" ) * g_blobSize.GetFloat() * scale;
		blob->s1 = 0;
		blob->t1 = 0;
		blob->s2 = 1;
		blob->t2 = 1;
	}

	//
	// save lastDamageTime for tunnel vision accentuation
	//
	lastDamageTime = MS2SEC( gameLocal.time );
}
Пример #12
0
UINT GetPeerCacheSocketDownloadTimeout()
{
	return DOWNLOADTIMEOUT + SEC2MS(20);	// must be lower than Upload timeout
}
Пример #13
0
UINT GetPeerCacheSocketUploadTimeout()
{
	return DOWNLOADTIMEOUT + SEC2MS(20 + 30);
}
Пример #14
0
/*
================
idTrigger_Multi::Event_Touch
================
*/
void idTrigger_Multi::Event_Touch( idEntity* other, trace_t* trace )
{
	if( common->IsClient() )
	{
		return;
	}
	
	if( triggerFirst )
	{
		return;
	}
	
	bool player = other->IsType( idPlayer::Type );
	if( player )
	{
		if( !touchClient )
		{
			return;
		}
		if( static_cast< idPlayer* >( other )->spectating )
		{
			return;
		}
	}
	else if( !touchOther )
	{
		return;
	}
	
	if( nextTriggerTime > gameLocal.time )
	{
		// can't retrigger until the wait is over
		return;
	}
	
	// see if this trigger requires an item
	if( !gameLocal.RequirementMet( other, requires, removeItem ) )
	{
		return;
	}
	
	if( !CheckFacing( other ) )
	{
		return;
	}
	
	if( spawnArgs.GetBool( "toggleTriggerFirst" ) )
	{
		triggerFirst = true;
	}
	
	nextTriggerTime = gameLocal.time + 1;
	if( delay > 0 )
	{
		// don't allow it to trigger again until our delay has passed
		nextTriggerTime += SEC2MS( delay + random_delay * gameLocal.random.CRandomFloat() );
		PostEventSec( &EV_TriggerAction, delay, other );
	}
	else
	{
		TriggerAction( other );
	}
}
Пример #15
0
void CDownloadQueue::ProcessLocalRequests()
{
	wxMutexLocker lock( m_mutex );
	
	bool bServerSupportsLargeFiles = theApp->serverconnect 
									&& theApp->serverconnect->GetCurrentServer()
									&& theApp->serverconnect->GetCurrentServer()->SupportsLargeFilesTCP();
	
	if ( (!m_localServerReqQueue.empty()) && (m_dwNextTCPSrcReq < ::GetTickCount()) ) {
		CMemFile dataTcpFrame(22);
		const int iMaxFilesPerTcpFrame = 15;
		int iFiles = 0;
		while (!m_localServerReqQueue.empty() && iFiles < iMaxFilesPerTcpFrame) {
			// find the file with the longest waitingtime
			uint32 dwBestWaitTime = 0xFFFFFFFF;

			std::list<CPartFile*>::iterator posNextRequest = m_localServerReqQueue.end();
			std::list<CPartFile*>::iterator it = m_localServerReqQueue.begin();
			while( it != m_localServerReqQueue.end() ) {
				CPartFile* cur_file = (*it);
				if (cur_file->GetStatus() == PS_READY || cur_file->GetStatus() == PS_EMPTY) {
					uint8 nPriority = cur_file->GetDownPriority();
					if (nPriority > PR_HIGH) {
						wxFAIL;
						nPriority = PR_HIGH;
					}

					if (cur_file->GetLastSearchTime() + (PR_HIGH-nPriority) < dwBestWaitTime ){
						dwBestWaitTime = cur_file->GetLastSearchTime() + (PR_HIGH - nPriority);
						posNextRequest = it;
					}

					it++;
				} else {
					it = m_localServerReqQueue.erase(it);
					cur_file->SetLocalSrcRequestQueued(false);
					AddDebugLogLineN(logDownloadQueue,
						CFormat(wxT("Local server source request for file '%s' not sent because of status '%s'"))
							% cur_file->GetFileName() % cur_file->getPartfileStatus());
				}
			}

			if (posNextRequest != m_localServerReqQueue.end()) {
				CPartFile* cur_file = (*posNextRequest);
				cur_file->SetLocalSrcRequestQueued(false);
				cur_file->SetLastSearchTime(::GetTickCount());
				m_localServerReqQueue.erase(posNextRequest);
				iFiles++;

				if (!bServerSupportsLargeFiles && cur_file->IsLargeFile()) {
					AddDebugLogLineN(logDownloadQueue, wxT("TCP Request for sources on a large file ignored: server doesn't support it"));
				} else {
					AddDebugLogLineN(logDownloadQueue,
						CFormat(wxT("Creating local sources request packet for '%s'")) % cur_file->GetFileName());
					// create request packet
					CMemFile data(16 + (cur_file->IsLargeFile() ? 8 : 4));
					data.WriteHash(cur_file->GetFileHash());
					// Kry - lugdunum extended protocol on 17.3 to handle filesize properly.
					// There is no need to check anything, old server ignore the extra 4 bytes.
					// As of 17.9, servers accept a 0 32-bits size and then a 64bits size
					if (cur_file->IsLargeFile()) {
						wxASSERT(bServerSupportsLargeFiles);
						data.WriteUInt32(0);
						data.WriteUInt64(cur_file->GetFileSize());
					} else {
						data.WriteUInt32(cur_file->GetFileSize());
					}
					uint8 byOpcode = 0;
					if (thePrefs::IsClientCryptLayerSupported() && theApp->serverconnect->GetCurrentServer() != NULL && theApp->serverconnect->GetCurrentServer()->SupportsGetSourcesObfuscation()) {
						byOpcode = OP_GETSOURCES_OBFU;
					} else {
						byOpcode = OP_GETSOURCES;
					}
					CPacket packet(data, OP_EDONKEYPROT, byOpcode);
					dataTcpFrame.Write(packet.GetPacket(), packet.GetRealPacketSize());
				}
			}
		}

		int iSize = dataTcpFrame.GetLength();
		if (iSize > 0) {
			// create one 'packet' which contains all buffered OP_GETSOURCES ED2K packets to be sent with one TCP frame
			// server credits: (16+4)*regularfiles + (16+4+8)*largefiles +1
			CScopedPtr<CPacket> packet(new CPacket(new byte[iSize], dataTcpFrame.GetLength(), true, false));
			dataTcpFrame.Seek(0, wxFromStart);
			dataTcpFrame.Read(packet->GetPacket(), iSize);
			uint32 size = packet->GetPacketSize();
			theApp->serverconnect->SendPacket(packet.release(), true);	// Deletes `packet'.
			AddDebugLogLineN(logDownloadQueue, wxT("Sent local sources request packet."));
			theStats::AddUpOverheadServer(size);
		}

		// next TCP frame with up to 15 source requests is allowed to be sent in..
		m_dwNextTCPSrcReq = ::GetTickCount() + SEC2MS(iMaxFilesPerTcpFrame*(16+4));
	}

}
Пример #16
0
uint8_t
node_create(
            UINT128* id,
            uint32_t self_ip4_no,
            uint32_t ip4_no,
            uint16_t tcp_port_no,
            uint16_t udp_port_no,
            uint8_t version,
            uint32_t udp_key,
            bool ip_verified,
            UINT128* dist,
            KAD_NODE** kn_out
           )
{
  uint8_t result = 0;
  KAD_NODE* kn;
#ifdef CONFIG_VERBOSE
  struct in_addr ia = {0};
#endif
  uint32_t now;

  do {

    if (!id || !dist || !kn_out) break;

    LOG_DEBUG("+++node_create+++");

    LOG_DEBUG_UINT128("id:", id);

#ifdef CONFIG_VERBOSE
    ia.s_addr = ip4_no; 
#endif

    LOG_DEBUG("ip %s, tcp_port %.4d, udp_port %.4d, version %.2d", inet_ntoa(ia), ntohs(tcp_port_no), ntohs(udp_port_no), version);

    LOG_DEBUG_UINT128("distance", dist);

    kn = (KAD_NODE*)mem_alloc(sizeof(KAD_NODE));

    if (!kn) {

      LOG_ERROR("Failed to allocate memory for node.");

      break;

    }

    memcpy(&kn->id, id, sizeof(UINT128));

    uint128_copy(id, &kn->id);

    kn->ip4_no = ip4_no;

    kn->tcp_port_no = tcp_port_no;

    kn->udp_port_no = udp_port_no;

    uint128_copy(dist, &kn->dist);

    kn->status = NODE_STATUS_NEW;

    now = ticks_now_ms();

    kn->created = now;

    kn->next_check_time = now + SEC2MS(5);

    kn->packet_timeout = 0;

    kn->version = version;

    kn->check_kad2 = true;
    
    kn->ip_verified = ip_verified;

    kn->hello_received = false;

    node_set_udp_key_with_ip(kn, udp_key, self_ip4_no);

#ifdef CONFIG_VERBOSE

    strcpy(kn->ip4_str, inet_ntoa(ia));

#endif

    // Here should be node lock initializer

    *kn_out = kn;

    result = 1;

  } while (false);

  if (!result && kn) mem_free(kn);

  return result;

}
void SearchingState::Init( idAI *owner ) {
	// Init base class first
	State::Init( owner );
	DM_LOG( LC_AI, LT_INFO )LOGSTRING( "SearchingState initialised.\r" );
	assert( owner );
	// Ensure we are in the correct alert level
	if( !CheckAlertLevel( owner ) ) {
		return;
	}
	if( owner->GetMoveType() == MOVETYPE_SIT || owner->GetMoveType() == MOVETYPE_SLEEP ) {
		owner->GetUp();
	}
	// Shortcut reference
	Memory &memory = owner->GetMemory();
	float alertTime = owner->atime3 + owner->atime3_fuzzyness * ( gameLocal.random.RandomFloat() - 0.5 );
	_alertLevelDecreaseRate = ( owner->thresh_4 - owner->thresh_3 ) / alertTime;
	if( owner->AlertIndexIncreased() || memory.mandatory ) { // grayman #3331
		// Setup a new hiding spot search
		StartNewHidingSpotSearch( owner );
	}
	if( owner->AlertIndexIncreased() ) {
		// grayman #3423 - when the alert level is ascending, kill the repeated bark task
		owner->commSubsystem->ClearTasks();
		// Play bark if alert level is ascending
		// grayman #3496 - enough time passed since last alert bark?
		if( gameLocal.time >= memory.lastTimeAlertBark + MIN_TIME_BETWEEN_ALERT_BARKS ) {
			idStr bark;
			if( ( memory.alertedDueToCommunication == false ) && ( ( memory.alertType == EAlertTypeSuspicious ) || ( memory.alertType == EAlertTypeEnemy ) ) ) {
				bool friendsNear = ( ( MS2SEC( gameLocal.time - memory.lastTimeFriendlyAISeen ) ) <= MAX_FRIEND_SIGHTING_SECONDS_FOR_ACCOMPANIED_ALERT_BARK );
				if( ( memory.alertClass == EAlertVisual_1 ) ||
						( memory.alertClass == EAlertVisual_2 ) ||    // grayman #2603, #3424
						// (memory.alertClass == EAlertVisual_3) ) || // grayman #3472 - no longer needed
						( memory.alertClass == EAlertVisual_4 ) ) {   // grayman #3498
					if( friendsNear ) {
						bark = "snd_alert3sc";
					} else {
						bark = "snd_alert3s";
					}
				} else if( memory.alertClass == EAlertAudio ) {
					if( friendsNear ) {
						bark = "snd_alert3hc";
					} else {
						bark = "snd_alert3h";
					}
				} else if( friendsNear ) {
					bark = "snd_alert3c";
				} else {
					bark = "snd_alert3";
				}
				// Allocate a SingleBarkTask, set the sound and enqueue it
				owner->commSubsystem->AddCommTask( CommunicationTaskPtr( new SingleBarkTask( bark ) ) );
				memory.lastTimeAlertBark = gameLocal.time; // grayman #3496
				if( cv_ai_debug_transition_barks.GetBool() ) {
					gameLocal.Printf( "%d: %s rises to Searching state, barks '%s'\n", gameLocal.time, owner->GetName(), bark.c_str() );
				}
			}
		} else {
			if( cv_ai_debug_transition_barks.GetBool() ) {
				gameLocal.Printf( "%d: %s rises to Searching state, can't bark 'snd_alert3{s/sc/h/hc/c}' yet\n", gameLocal.time, owner->GetName() );
			}
		}
	} else if( memory.alertType == EAlertTypeEnemy ) {
		// reduce the alert type, so we can react to other alert types (such as a dead person)
		memory.alertType = EAlertTypeSuspicious;
	}
	// grayman #3472 - When ascending, set up a repeated bark
	if( owner->AlertIndexIncreased() ) {
		owner->commSubsystem->AddSilence( 5000 + gameLocal.random.RandomInt( 3000 ) ); // grayman #3424
		// This will hold the message to be delivered with the bark
		CommMessagePtr message( new CommMessage(
									CommMessage::DetectedEnemy_CommType,
									owner, NULL,// from this AI to anyone
									NULL,
									idVec3( idMath::INFINITY, idMath::INFINITY, idMath::INFINITY ),
									0
								) );
		int minTime = SEC2MS( owner->spawnArgs.GetFloat( "searchbark_delay_min", "10" ) );
		int maxTime = SEC2MS( owner->spawnArgs.GetFloat( "searchbark_delay_max", "15" ) );
		owner->commSubsystem->AddCommTask( CommunicationTaskPtr( new RepeatedBarkTask( "snd_state3", minTime, maxTime, message ) ) );
	} else { // descending
		// Allow repeated barks from Agitated Searching to continue.
	}
	if( !owner->HasSeenEvidence() ) {
		owner->SheathWeapon();
		owner->UpdateAttachmentContents( false );
	} else {
		// Let the AI update their weapons (make them solid)
		owner->UpdateAttachmentContents( true );
	}
}
Пример #18
0
Файл: kad.c Проект: mzhel/libkad
bool
kad_session_update(
                   KAD_SESSION* ks,
                   uint32_t now
                   )
{
  bool result = false;
  ROUTING_ZONE* rz;
  LIST* active_zones = NULL;
  bool zones_locked = false;
  uint32_t kn_cnt = 0;

  do {

    if (ks->timers.self_lookup <= now){

      LOG_DEBUG("Self-lookup.");

      kad_search_find_node(ks, ks->root_zone, &ks->kad_id, &ks->kad_id, true, &ks->searches);

      ks->timers.self_lookup = now + HR2MS(4);

    }

    if (ks->timers.udp_port_lookup <= now && kad_fw_udp_check_running(&ks->fw) && !kad_fw_extrn_port_valid(&ks->fw)){

      LOG_DEBUG("Ping packet to random node.");

      kadhlp_send_ping_pkt_to_rand_node(ks);

      ks->timers.udp_port_lookup = now + SEC2MS(15);

    }

    if (ks->timers.update_user_data <= now){

      kad_session_update_user_data(ks);

      ks->timers.update_user_data = now + SEC2MS(1);

    }

    if (
        !kad_fw_udp_check_started(&ks->fw) && 
        kad_fw_udp_check_running(&ks->fw) &&
        kad_fw_need_more_udp_checks(&ks->fw)
      ){

      ks->fw.udp_check_running = true; 

      LOG_DEBUG("Starting search for nodes for udp firewall check.");

      kad_search_find_node_for_fw_check(
                                        ks,
                                        ks->root_zone,
                                        &ks->kad_id, 
                                        &ks->searches
                                       );

    }

    if (kad_fw_extrn_port_valid(&ks->fw) && kad_fw_need_more_udp_checks(&ks->fw)){

      LOG_DEBUG("Sending udp firewall check request.");

      kad_fw_udp_check_request(ks);

    }

    ACTIVE_ZONES_LOCK(ks);

    zones_locked = true;

    LIST_EACH_ENTRY_WITH_DATA_BEGIN(ks->active_zones, e, rz);

      if (now >= rz->next_bucket_timer){

        kad_zone_update_bucket(ks, rz);

        rz->next_bucket_timer = now + MIN2MS(1);

      }

      if (now >= rz->next_lookup_timer){

        LOG_DEBUG("Random lookup.");

        kad_zone_random_lookup(ks, rz, &ks->kad_id);

        rz->next_lookup_timer = now + HR2MS(1);

      }

    LIST_EACH_ENTRY_WITH_DATA_END(e);

    // [IMPLEMENT] Empty zones consolidation.

    if (now >= ks->timers.nodes_count_check){

      if (routing_get_nodes_count(ks->root_zone, &kn_cnt, true) && kn_cnt < 200){

    //    LOG_DEBUG("Bootstrap packet.");

    //    kadhlp_send_bs_req_pkt_to_rand_node(ks);

      }

      LOG_DEBUG("Nodes count: %d", kn_cnt);

      ks->timers.nodes_count_check = now + SEC2MS(10);

    }

    ACTIVE_ZONES_UNLOCK(ks);

    zones_locked = false;

    // Jumpstart stalled searches.
  
    if (now >= ks->timers.search_jumpstart){

      // LOG_DEBUG("Jump-start searches.");

      kad_search_jumpstart_all(ks, &ks->searches);

      ks->timers.search_jumpstart = now + SEC2MS(1);

    }

  } while (false);

  return result;
}
/*
================
rvMonsterStreamProtector::State_Torso_PlasmaAttack
================
*/
stateResult_t rvMonsterStreamProtector::State_Torso_PlasmaAttack ( const stateParms_t& parms ) {	
	enum {
		STAGE_START,
		STAGE_START_WAIT,
		STAGE_FIRE,
		STAGE_INITIALFIRE_WAIT,
		STAGE_FIRE_WAIT,
		STAGE_END,
		STAGE_END_WAIT,
	};	
	switch ( parms.stage ) {
		case STAGE_START:
			DisableAnimState ( ANIMCHANNEL_LEGS );

			// Loop the flame animation
			PlayAnim( ANIMCHANNEL_TORSO, "range_plasma_start", parms.blendFrames );

			// Make sure we clean up some things when this state is finished (effects for one)			
			PostAnimState ( ANIMCHANNEL_TORSO, "Torso_FinishPlasmaAttack", 0, 0, SFLAG_ONCLEAR );
			
			return SRESULT_STAGE ( STAGE_START_WAIT );
		
		case STAGE_START_WAIT:
			if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
				return SRESULT_STAGE ( STAGE_FIRE );
			}
			return SRESULT_WAIT;

		case STAGE_FIRE:
			attackEndTime = gameLocal.time + 500;
			attackNextTime = gameLocal.time;
			
			// Flame effect
			PlayEffect ( "fx_plasma_muzzle", jointPlasmaMuzzle, true );
			
			PlayCycle ( ANIMCHANNEL_TORSO, "range_plasma_fire", 0 );
			
			return SRESULT_STAGE ( STAGE_INITIALFIRE_WAIT );

		case STAGE_INITIALFIRE_WAIT:
			if ( gameLocal.time > attackEndTime ) {
				attackEndTime = gameLocal.time + SEC2MS ( 1.0f + gameLocal.random.RandomFloat ( ) * 4.0f );
				return SRESULT_STAGE ( STAGE_FIRE_WAIT );
			}
			// Launch another attack?
			if ( gameLocal.time >= attackNextTime ) {
				Attack ( "plasma", jointPlasmaMuzzle, enemy.ent );
				attackNextTime = gameLocal.time + plasmaAttackRate;
			}
			return SRESULT_WAIT;
			
		case STAGE_FIRE_WAIT:
			// If we have been using plasma too long or havent seen our enemy for at least half a second then
			// stop now.
			if ( gameLocal.time > attackEndTime || gameLocal.time - enemy.lastVisibleTime > 500 || (IsEnemyVisible() && !enemy.fl.inFov) ) {
				StopEffect ( "fx_plasma_muzzle" );
				return SRESULT_STAGE ( STAGE_END );
			}
			// Launch another attack?
			if ( gameLocal.time >= attackNextTime  ) {
				Attack ( "plasma", jointPlasmaMuzzle, enemy.ent );
				attackNextTime = gameLocal.time + plasmaAttackRate;
			}
			return SRESULT_WAIT;
				
		case STAGE_END:
			// End animations
			PlayAnim( ANIMCHANNEL_TORSO, "range_plasma_end", parms.blendFrames );			
			return SRESULT_STAGE ( STAGE_END_WAIT );
		
		case STAGE_END_WAIT:
			if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
				return SRESULT_DONE;
			}
			return SRESULT_WAIT;						
	}

	return SRESULT_ERROR;
}
Пример #20
0
Файл: kad.c Проект: mzhel/libkad
bool
kad_zone_update_bucket(
                       KAD_SESSION* ks,
                       ROUTING_ZONE* rz
                       )
{
  bool result = false;
  KBUCKET* kb = NULL;
  uint32_t now = ticks_now_ms();
  uint32_t kn_cnt = 0;
  KAD_NODE* rmvd_kn = NULL;
  KAD_NODE* kn = NULL;
  void* pkt = NULL;
  uint32_t pkt_len = 0;
  struct in_addr ia;

  do {

    if (!ks || !rz || !rz->kb) break;

    kb = rz->kb;

    kn_cnt = kb->nodes_count;

    // Check all nodes for expiration,
    // if node expire time is not set -
    // set it to now. If node expiration time
    // is lesser than now remove node from bucket
    // and destroy it.

    for (uint32_t i = 0; i < kn_cnt; i++){

      kn = kb->nodes[i];

      if (kn->status == NODE_STATUS_TO_REMOVE || ((kn->status & NODE_STATUS_WAIT_MASK) && kn->packet_timeout < now)){

        LOG_DEBUG("Removing node: %s:%d with status %s, packet timeout.", kn->ip4_str, ntohs(kn->udp_port_no), node_status_str(kn));

        if (!kbucket_remove_node_by_idx(kb, i, &rmvd_kn)){

          LOG_ERROR("Failed to delete expired node.");

          break;

        }

        kn_cnt--;

        node_destroy(rmvd_kn);
          
      }

    }

    if (!kbucket_get_oldest_node(kb, &kn)) break;

    if (!kn) break;

    if (kn->next_check_time >= now){

      kbucket_push_node_up(kb, kn);

    } else {

      switch (kn->status){

        case NODE_STATUS_NEW:

          if (kadhlp_send_hello_req_pkt_to_node(ks, kn)){

            kn->packet_timeout = now + SEC2MS(15);

            kn->status = NODE_STATUS_HELLO_REQ_SENT;

            LOG_DEBUG("NODE_STATUS_HELLO_REQ_SENT for %s:%d", kn->ip4_str, ntohs(kn->udp_port_no));

          } else {

            // Something happened and hello request was not sent.
            
            if (kn->version < 2) kn->status = NODE_STATUS_TO_REMOVE;

          }

        break;

        case NODE_STATUS_HELLO_RES_RECEIVED:

        case NODE_STATUS_PONG_RECEIVED:

          kadhlp_send_ping_pkt_to_node(ks, kn);

          kn->packet_timeout = now + SEC2MS(10);

          kn->status = NODE_STATUS_PING_SENT;

          LOG_DEBUG("NODE_STATUS_PING_SENT for %s:%d", kn->ip4_str, ntohs(kn->udp_port_no));

        break;

      }

    }

    result = true;

  } while (false);

  return result;
}
Пример #21
0
void CMuleKad::Process(UINT Tick)
{
	if(m_MyBuddy && IsFirewalled() && m_NextBuddyPing < GetCurTick())
	{
		m_NextBuddyPing = GetCurTick() + MIN2MS(10);
		m_MyBuddy->SendBuddyPing();
	}

	QVariantMap Request;
	Request["Firewalled"] = theCore->m_MuleManager->IsFirewalled(CAddress::IPv4, false, true);
	Request["PublicIP"] = theCore->m_MuleManager->GetAddress(CAddress::IPv4, true).ToQString();
	if(theCore->m_MuleManager->IsFirewalled(CAddress::IPv4))
	{
		if(m_MyBuddy)
		{
			Request["BuddyIP"] = m_MyBuddy->GetMule().IPv4.ToQString();
			Request["BuddyPort"] = m_MyBuddy->GetKadPort();
		}
	}

	// Note: we always advertize IPv6 addresses
	CAddress IPv6 = theCore->m_MuleManager->GetAddress(CAddress::IPv6, true);
	if(!IPv6.IsNull())
		Request["IPv6"] = IPv6.ToQString();

	if(Tick & EPerSec)
	{
		if(theCore->Cfg()->GetBool("Log/Merge"))
			SyncLog();
	}

	QVariantMap Response = theCore->m_Interfaces->RemoteProcedureCall("MuleKad", "SyncState", Request).toMap();

	m_KadID = Response["KadID"].toByteArray();

	if(Response["Result"] == "Connected")
	{
		if(m_KadStatus != eConnected)
		{
			LogLine(LOG_SUCCESS, tr("MuleKad Connected, ID: %1").arg(QString(m_KadID.toHex()).toUpper()));
			m_KadStatus = eConnected;
		}
	}
	else if(Response["Result"] == "Connecting")
		m_KadStatus = eConnecting;
	else //if(Response["Result"] == "Disconnected")
		m_KadStatus = eDisconnected;

	if(m_KadStatus == eDisconnected)
	{
		if(GetCurTick() > m_NextConnectionAttempt)
		{
			LogLine(LOG_INFO, tr("Connecting emule kademlia"));
			m_NextConnectionAttempt = GetCurTick() + SEC2MS(theCore->Cfg()->GetInt("Ed2kMule/IdleTimeout"));
			StartKad();
		}
		return;
	}
	
	m_Address = CAddress(Response["PublicIP"].toString());
	m_KadPort = Response["KadPort"].toUInt(); // external kad port
	//m_UDPPort = Response["UDPPort"].toUInt(); // socket port
	m_Firewalled = Response["Firewalled"].toBool();
	m_KadFirewalled = Response["KadFirewalled"].toBool();
	
	if (m_KadFirewalled && m_uNextKadFirewallRecheck <= GetCurTick())
	{
		m_uNextKadFirewallRecheck = GetCurTick() + SEC2MS(theCore->Cfg()->GetInt("Ed2kMule/CheckFWInterval"));
		CheckFWState();
	}

	foreach(const QVariant& vQueuedFWCheck, Response["QueuedFWChecks"].toList())
	{
		QVariantMap QueuedFWCheck = vQueuedFWCheck.toMap();

		SMuleSource Mule;
		Mule.SetIP(CAddress(QueuedFWCheck["Address"].toString()));
		Mule.TCPPort = QueuedFWCheck["TCPPort"].toUInt();
		Mule.ConOpts.Bits = QueuedFWCheck["ConOpts"].toUInt(); 
		if(Mule.ConOpts.Fields.RequestsCryptLayer) // some cleints seam to mess this up
			Mule.ConOpts.Fields.SupportsCryptLayer = true;
		QByteArray UserHash = QueuedFWCheck["UserHash"].toByteArray();
		
		if(!Mule.SelectIP() || !theCore->m_PeerWatch->CheckPeer(Mule.GetIP(), Mule.TCPPort))
			continue;

		bool bAdded = false;
		CMuleClient* pClient = theCore->m_MuleManager->GetClient(Mule, &bAdded);
		if(!bAdded)
		{
			if(QueuedFWCheck["TestUDP"].toBool() == true)
				SetUDPFWCheckResult(pClient, true);
			continue;
		}

		if(QueuedFWCheck["TestUDP"].toBool() == true)
		{
			uint32 UDPKey;
			if(QueuedFWCheck.contains("UDPKey"))
				UDPKey = QueuedFWCheck["UDPKey"].toUInt();
			else
				UDPKey = theCore->m_MuleManager->GetServer()->GetUDPKey(Mule.GetIP());
			m_QueuedFWChecks.insert(pClient, SFWCheck(QueuedFWCheck["IntPort"].toUInt(), QueuedFWCheck["ExtPort"].toUInt(), UDPKey));
		}
		else
			m_QueuedFWChecks.insert(pClient, SFWCheck());

		connect(pClient, SIGNAL(HelloRecived()), this, SLOT(OnHelloRecived()));
		connect(pClient, SIGNAL(SocketClosed()), this, SLOT(OnSocketClosed()));

		pClient->SetUserHash(UserHash);
		pClient->Connect();
	}

	QList<CAddress> PendingFWChecks;
	foreach(const QVariant& vPendingFWCheck, Response["PendingFWChecks"].toList())
	{
		QVariantMap PendingFWCheck = vPendingFWCheck.toMap();
		PendingFWChecks.append(CAddress(PendingFWCheck["Address"].toString()));
	}
	theCore->m_MuleManager->GetServer()->SetExpected(PendingFWChecks);

	foreach(const QVariant& vBufferedCallback, Response["BufferedCallbacks"].toList())
	{
		QVariantMap BufferedCallback = vBufferedCallback.toMap();

		CAddress Address = CAddress(BufferedCallback["Address"].toString());
		uint16 uPort = BufferedCallback["TCPPort"].toUInt();
		QByteArray BuddyID = BufferedCallback["BuddyID"].toByteArray();
		QByteArray FileID = BufferedCallback["FileID"].toByteArray();

		if(m_MyBuddy && m_MyBuddy->IsFirewalled(CAddress::IPv4))
		{
			if(m_MyBuddy->GetBuddyID() == BuddyID)
				m_MyBuddy->RelayKadCallback(Address, uPort, BuddyID, FileID);
		}
	}

	// Note: This comes in on the normal UDP Socket, as we provide thesocket now we dont haveto pull it
	/*foreach(const QVariant& vBufferedPackets, Response["BufferedPackets"].toList())
	{
		QVariantMap BufferedPackets = vBufferedPackets.toMap();

		CAddress Address = CAddress(BufferedPackets["Address"].toString());
		uint16 uPort = BufferedPackets["UDPPort"].toUInt();
		QByteArray Data = BufferedPackets["Data"].toByteArray();
			
		CBuffer Packet((byte*)Data.data(), Data.size(), true);
		RelayUDPPacket(Address, uPort, Packet);
	}

	foreach(const QVariant& vPendingCallback, Response["PendingCallbacks"].toList())
	{
		QVariantMap PendingCallback = vPendingCallback.toMap();

		SMuleSource Mule;
		Mule.SetIP(CAddress(PendingCallback["Address"].toString()));
		Mule.TCPPort = PendingCallback["TCPPort"].toUInt();
		Mule.UserHash = PendingCallback["UserHash"].toByteArray();
		Mule.ConOpts.Bits = PendingCallback["ConOpts"].toUInt();
		if(Mule.ConOpts.Fields.RequestsCryptLayer) // some cleints seam to mess this up
			Mule.ConOpts.Fields.SupportsCryptLayer = true;
		theCore->m_MuleManager->CallbackRequested(Mule);
	}*/

	foreach(const QVariant& vPendingBuddys, Response["PendingBuddys"].toList())
	{
		if(m_MyBuddy) // if we have a buddy we are not interested in new ones
			break;

		QVariantMap PendingBuddy = vPendingBuddys.toMap();

		SMuleSource Mule;
		Mule.SetIP(CAddress(PendingBuddy["Address"].toString()));
		Mule.TCPPort = PendingBuddy["TCPPort"].toUInt();
		Mule.KadPort = PendingBuddy["KadPort"].toUInt();
		Mule.ConOpts.Bits = PendingBuddy["ConOpts"].toUInt();
		if(Mule.ConOpts.Fields.RequestsCryptLayer) // some cleints seam to mess this up
			Mule.ConOpts.Fields.SupportsCryptLayer = true;
		Mule.UserHash = PendingBuddy["UserHash"].toByteArray();
		Mule.BuddyID = PendingBuddy["BuddyID"].toByteArray();

		if(!theCore->m_PeerWatch->CheckPeer(Mule.GetIP(), Mule.TCPPort))
			continue;

		bool bAdded = false;
		CMuleClient* pClient = theCore->m_MuleManager->GetClient(Mule, &bAdded);
		if(!bAdded)
			continue; // already known clients are not viable budies

		connect(pClient, SIGNAL(HelloRecived()), this, SLOT(OnHelloRecived()));
		connect(pClient, SIGNAL(SocketClosed()), this, SLOT(OnSocketClosed()));
		if(m_PendingBuddys.contains(pClient))
			continue; // already listes
		m_PendingBuddys.append(pClient);

		if(PendingBuddy["Incoming"].toBool()) // is this a lowID client that wants us to become his buddy ans will soon connect us?
			pClient->ExpectConnection();
		else //this is a high ID client that agreed to become our buddy
			pClient->Connect();
	}

	m_KadStats = Response["Stats"].toMap();

	if(Tick & EPerSec)
	{
		if(IsConnected())
		{
			SyncFiles();
			SyncNotes();

			foreach(CAbstractSearch* pSearch, m_RunningSearches)
				SyncSearch(pSearch);
		}
	}
}
Пример #22
0
/*
================
idThread::Event_DebugArrow
================
*/
void idThread::Event_DebugArrow( const idVec3 &color, const idVec3 &start, const idVec3 &end, const int size, const float lifetime ) {
	gameRenderWorld->DebugArrow( idVec4( color.x, color.y, color.z, 0.0f ), start, end, size, SEC2MS( lifetime ) );
}
Пример #23
0
/*
================
idClass::PostEventSec
================
*/
bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1 ) {
	return PostEventArgs( ev, SEC2MS( time ), 1, &arg1 );
}
Пример #24
0
/*
================
idThread::Event_DebugCircle
================
*/
void idThread::Event_DebugCircle( const idVec3 &color, const idVec3 &origin, const idVec3 &dir, const float radius, const int numSteps, const float lifetime ) {
	gameRenderWorld->DebugCircle( idVec4( color.x, color.y, color.z, 0.0f ), origin, dir, radius, numSteps, SEC2MS( lifetime ) );
}
Пример #25
0
/*
================
idClass::PostEventSec
================
*/
bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6, idEventArg arg7, idEventArg arg8 ) {
	return PostEventArgs( ev, SEC2MS( time ), 8, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8 );
}
Пример #26
0
/*
================
idThread::Event_DebugBounds
================
*/
void idThread::Event_DebugBounds( const idVec3 &color, const idVec3 &mins, const idVec3 &maxs, const float lifetime ) {
	gameRenderWorld->DebugBounds( idVec4( color.x, color.y, color.z, 0.0f ), idBounds( mins, maxs ), vec3_origin, SEC2MS( lifetime ) );
}
Пример #27
0
/*
================
idTrigger_Multi::Event_Touch
================
*/
void idTrigger_Multi::Event_Touch( idEntity *other, trace_t *trace ) {
    if( triggerFirst ) {
        return;
    }

// RAVEN BEGIN
// jdischler: vehicle only trigger
    if ( touchVehicle ) {
        if ( !other->IsType(rvVehicle::GetClassType()) ) {
            return;
        }
    } else {
// RAVEN BEGIN
// jnewquist: Use accessor for static class type
        bool player = other->IsType( idPlayer::GetClassType() );
// RAVEN END
        if ( player ) {
            if ( !touchClient ) {
                return;
            }
            if ( static_cast< idPlayer * >( other )->spectating ) {
                return;
            }

            // Buy zone handling
            if ( buyZoneTrigger /*&& gameLocal.mpGame.mpGameState.gameState.currentState != 1*/ ) {
                idPlayer *p = static_cast< idPlayer * >( other );
                if ( buyZoneTrigger-1 == p->team || buyZoneTrigger == 3)
                {
                    p->inBuyZone = true;
                    p->inBuyZonePrev = true;
                }
            }

            // Control zone handling
            if ( controlZoneTrigger > 0 ) {
                idPlayer *p = static_cast< idPlayer * >( other );
                if ( p->PowerUpActive(POWERUP_DEADZONE) || !spawnArgs.GetBool("requiresDeadZonePowerup", "1") )
                    playersInTrigger.Append(p);
            }

        } else if ( !touchOther ) {
            return;
        }
    }

    if ( nextTriggerTime > gameLocal.time ) {
        // can't retrigger until the wait is over
        return;
    }

    // see if this trigger requires an item
    if ( !gameLocal.RequirementMet( other, requires, removeItem ) ) {
        return;
    }

    if ( !CheckFacing( other ) ) {
        return;
    }

    if ( spawnArgs.GetBool( "toggleTriggerFirst" ) ) {
        triggerFirst = true;
    }

// RAVEN BEGIN
// rjohnson: added block
    if ( developer.GetBool() && *spawnArgs.GetString ( "message" ) ) {
        gameLocal.DPrintf ( "Trigger: %s\n", spawnArgs.GetString ( "message" ) );
    }
// RAVEN END

    nextTriggerTime = gameLocal.time + 1;
    if ( delay > 0 ) {
        // don't allow it to trigger again until our delay has passed
        nextTriggerTime += SEC2MS( delay + random_delay * gameLocal.random.CRandomFloat() );
        PostEventSec( &EV_TriggerAction, delay, other );
    } else {
        TriggerAction( other );
    }
}
Пример #28
0
/*
================
idThread::Event_DrawText
================
*/
void idThread::Event_DrawText( const char *text, const idVec3 &origin, float scale, const idVec3 &color, const int align, const float lifetime ) {
	gameRenderWorld->DrawText( text, origin, scale, idVec4( color.x, color.y, color.z, 0.0f ), gameLocal.GetLocalPlayer()->viewAngles.ToMat3(), align, SEC2MS( lifetime ) );
}
Пример #29
0
/*
==============
idPlayerView::DamageImpulse

LocalKickDir is the direction of force in the player's coordinate system,
which will determine the head kick direction
==============
*/
void idPlayerView::DamageImpulse( idVec3 localKickDir, const idDict *damageDef ) {
	//
	// double vision effect
	//
	if ( lastDamageTime > 0.0f && SEC2MS( lastDamageTime ) + IMPULSE_DELAY > gameLocal.time ) {
		// keep shotgun from obliterating the view
		return;
	}

	float	dvTime = damageDef->GetFloat( "dv_time" );
	if ( dvTime ) {
		if ( dvFinishTime < gameLocal.time ) {
			dvFinishTime = gameLocal.time;
		}
		dvFinishTime += g_dvTime.GetFloat() * dvTime;
		// don't let it add up too much in god mode
		if ( dvFinishTime > gameLocal.time + 5000 ) {
			dvFinishTime = gameLocal.time + 5000;
		}
	}

	//
	// head angle kick
	//
	float	kickTime = damageDef->GetFloat( "kick_time" );
	if ( kickTime ) {
		kickFinishTime = gameLocal.time + g_kickTime.GetFloat() * kickTime;

		// forward / back kick will pitch view
		kickAngles[0] = localKickDir[0];

		// side kick will yaw view
		kickAngles[1] = localKickDir[1]*0.5f;

		// up / down kick will pitch view
		kickAngles[0] += localKickDir[2];

		// roll will come from  side
		kickAngles[2] = localKickDir[1];

		float kickAmplitude = damageDef->GetFloat( "kick_amplitude" );
		if ( kickAmplitude ) {
			kickAngles *= kickAmplitude;
		}
	}

	//
	// screen blob
	//
	float	blobTime = damageDef->GetFloat( "blob_time" );
	if ( blobTime ) {
		screenBlob_t	*blob = GetScreenBlob();
		blob->startFadeTime = gameLocal.time;
		blob->finishTime = gameLocal.time + blobTime * g_blobTime.GetFloat();

		const char *materialName = damageDef->GetString( "mtr_blob" );
		blob->material = declManager->FindMaterial( materialName );
		blob->x = damageDef->GetFloat( "blob_x" );
		blob->x += ( gameLocal.random.RandomInt()&63 ) - 32;
		blob->y = damageDef->GetFloat( "blob_y" );
		blob->y += ( gameLocal.random.RandomInt()&63 ) - 32;
		
		float scale = ( 256 + ( ( gameLocal.random.RandomInt()&63 ) - 32 ) ) / 256.0f;
		blob->w = damageDef->GetFloat( "blob_width" ) * g_blobSize.GetFloat() * scale;
		blob->h = damageDef->GetFloat( "blob_height" ) * g_blobSize.GetFloat() * scale;
		blob->s1 = 0;
		blob->t1 = 0;
		blob->s2 = 1;
		blob->t2 = 1;
	}

	//
	// save lastDamageTime for tunnel vision accentuation
	//
	lastDamageTime = MS2SEC( gameLocal.time );

}
Пример #30
0
/*
================
idThread::WaitSec
================
*/
void idThread::WaitSec( float time ) {
	WaitMS( SEC2MS( time ) );
}