Example #1
0
// =============================================================================
// Nat Ryall                                                         11-Jul-2008
// =============================================================================
void CPlayer::Move(t_PlayerDirection iDirection)
{
	m_pTargetBlock = m_pCurrentBlock->m_pAdjacents[iDirection];
	m_iMoveDir = iDirection;
	m_iTransitionDir = iDirection;
	m_iTime = 0;
	m_fTransition = 0.f;

	if (m_pCurrentBlock->m_pAdjacents[iDirection])
		SetState(PlayerState_Move);
	else
	{
		m_bLeaving = true;
		SetState(PlayerState_Warp);
	}

	// Network.
	if (NetworkManager.IsRunning())
	{
		if (m_iLogicType == PlayerLogicType_Local || m_iLogicType == PlayerLogicType_AI)
		{
			BitStream xStream;

			xStream.Write((xuint8)PlayerStreamType_Move);
			xStream.Write((xuint8)m_iIndex);
			xStream.Write((xuint8)iDirection);

			NetworkManager.Broadcast(NULL, NetworkStreamType_PlayerUpdate, &xStream, HIGH_PRIORITY, RELIABLE_ORDERED);
		}
	}
}
void TeamBalancer::NotifyNoTeam(RakNetGUID target)
{
    BitStream bsOut;
    bsOut.Write((MessageID)ID_TEAM_BALANCER_TEAM_ASSIGNED);
    bsOut.Write((unsigned char)UNASSIGNED_TEAM_ID);
    rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,target,false);
}
void RelayPlugin::SendMessageToRoom(StrAndGuidAndRoom **strAndGuidSender, BitStream* message)
{
	if ((*strAndGuidSender)->currentRoom.IsEmpty())
		return;

	for (unsigned int i=0; i < chatRooms.Size(); i++)
	{
		if (chatRooms[i]->roomName==(*strAndGuidSender)->currentRoom)
		{
			BitStream bsOut;
			bsOut.WriteCasted<MessageID>(ID_RELAY_PLUGIN);
			bsOut.WriteCasted<MessageID>(RPE_GROUP_MSG_FROM_SERVER);
			message->ResetReadPointer();
			bsOut.WriteCompressed((*strAndGuidSender)->str);
			bsOut.AlignWriteToByteBoundary();
			bsOut.Write(message);

			RP_Group *room = chatRooms[i];
			for (unsigned int i=0; i < room->usersInRoom.Size(); i++)
			{
				if (room->usersInRoom[i].guid!=(*strAndGuidSender)->guid)
					SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, room->usersInRoom[i].guid, false);
			}

			break;
		}
	}
}
void LobbyMenu::HandleKey( int key, int x, int y )
{
    BaseMenu::HandleKey(key, x, y);
    if((key == KEY_ENTER) || (key == KEY_SPACE))
    {
        switch(m_nSelectedItem)
        {
        case GOTO_LAST_MENU:
            {
                BaseMenu *menu = dynamic_cast<BaseMenu*>(menuSystem->mainMenu);
                if(menu != NULL)
                {
                    menuSystem->Switch(menu);
                }
            }
            break;
        case 1:
            {
                menuSystem->StartGame();
                BitStream * stream = new BitStream();
                stream->Write((MessageID)END_YOUR_TURN);
                Network::GetInstance()->Message(stream);
                delete stream;
            }
            break;
        }
    }
}
Example #5
0
// ********************************************************************************************
void Block::StoreDNAHuf(BitStream &bit_stream, LzMatcher &lz_matcher, uchar *sym_code, HuffmanEncoder::Code *sym_huf_codes, bool try_lz)
{
	// Info about LZ matches
	if (try_lz)
	{
		FindLzMatches(lz_matcher);

		StoreLzMatches(bit_stream, lz_matcher);

		for (uint32 i = 0; i < rec_count; ++i)
		{
			uint32 cur_sequence_len = records[i].sequence_len;
			uchar *cur_sequence = records[i].sequence;
			for (uint32 j = lz_matches[i].length; j < cur_sequence_len; ++j)
			{
				bit_stream.PutBits(sym_huf_codes[sym_code[cur_sequence[j]]].code, sym_huf_codes[sym_code[cur_sequence[j]]].len);
			}
		}
	}
	else
	{
		for (uint32 i = 0; i < rec_count; ++i)
		{
			uint32 cur_sequence_len = records[i].sequence_len;
			uchar *cur_sequence = records[i].sequence;
			for (uint32 j = 0; j < cur_sequence_len; ++j)
			{
				bit_stream.PutBits(sym_huf_codes[sym_code[cur_sequence[j]]].code, sym_huf_codes[sym_code[cur_sequence[j]]].len);
			}
		}
	}

	bit_stream.FlushPartialWordBuffer();
}
Example #6
0
void TeamBalancer::NotifyTeamsLocked(RakNetGUID target, TeamId requestedTeam)
{
	BitStream bsOut;
	bsOut.Write((MessageID)ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED);
	bsOut.Write(requestedTeam);
	rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,target,false);
}
pair<SystemAddress, QueryData> QueryClient::Update(const RakNet::SystemAddress &addr)
{
    qDebug() << "Locking mutex in QueryClient::Update(RakNet::SystemAddress addr)";
    pair<SystemAddress, QueryData> server;
    BitStream bs;
    bs.Write((unsigned char) (ID_MASTER_UPDATE));
    bs.Write(addr);

    mxServers.lock();
    status = -1;
    int attempts = 3;
    pmu->SetServer(&server);
    do
    {
        if (Connect() == IS_NOT_CONNECTED)
        {
            qDebug() << IS_NOT_CONNECTED;
            qDebug() << "Unlocking mutex in QueryClient::Update(RakNet::SystemAddress addr)";
            mxServers.unlock();
            return server;
        }

        peer->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_MASTER, masterAddr, false);
        status = GetAnswer(ID_MASTER_UPDATE);
        RakSleep(100);
    }
    while(status != ID_MASTER_UPDATE && attempts-- > 0);
    if(status != ID_MASTER_UPDATE)
        qDebug() << "Getting update was failed";
    peer->CloseConnection(masterAddr, true);
    qDebug() << "Unlocking mutex in QueryClient::Update(RakNet::SystemAddress addr)";
    mxServers.unlock();
    return server;
}
Example #8
0
void NetInterface::handleConnectChallengeRequest(const NetAddress *addr, BitStream *stream)
{
   char buf[256];
   Net::addressToString(addr, buf);
   Con::printf("Got Connect challenge Request from %s", buf);
   if(!mAllowConnections)
      return;

   U32 connectSequence;
   stream->read(&connectSequence);

   if(!mRandomDataInitialized)
      initRandomData();

   U32 addressDigest[4];
   computeNetMD5(addr, connectSequence, addressDigest);

   BitStream *out = BitStream::getPacketStream();
   out->write(U8(ConnectChallengeResponse));
   out->write(connectSequence);
   out->write(addressDigest[0]);
   out->write(addressDigest[1]);
   out->write(addressDigest[2]);
   out->write(addressDigest[3]);

   BitStream::sendPacketStream(addr);
}
Example #9
0
int Golomb::decode(uint m, int *value, BitStream& bs){
	int q = 0, r, v;
	int nbits = (int) floor(log2(m)) + 1;
	int err;
	uint32_t bit;


	do {
		if ((err=bs.readBit(&bit)) != 0)
			return err;

		if (bit == 0)
			break;
		q++;
	} while(true);


	if ((err = bs.readBits(nbits, &bit)) != 0)
		return err;

	r = (int) bit;

	v = q * m + r;
	if (v % 2 == 0)
		*value =  v/2;
	else
		*value = -(v+1)/2;

	return 0;
}
Example #10
0
void  RakClient::RequestClass( int classId )
{
    BitStream bsClass;

    bsClass.Write( classId );
    g_RakClient->RPC( RPC_RequestClass, &bsClass );
}
Example #11
0
void Character::GetCharBuildInfo(BitStream &src)
{
    src.GetString(m_char_data.m_class_name);
    src.GetString(m_char_data.m_origin_name);

    qInfo() << "Loading Starting Character Settings...";
    QSettings config(Settings::getSettingsPath(),QSettings::IniFormat,nullptr);

    config.beginGroup("StartingCharacter");
        QRegExp space("\\s");
        QStringList inherent_and_preorders = config.value(QStringLiteral("inherent_powers"), "Brawl").toString().remove(space).split(',');
        QStringList starting_temps = config.value(QStringLiteral("starting_temps"), "EMP_Glove").toString().remove(space).split(',');
        QStringList starting_insps = config.value(QStringLiteral("starting_inspirations"), "Resurgence").toString().remove(space).split(',');
        uint startlevel = config.value(QStringLiteral("starting_level"), "1").toUInt() -1; //convert from 1-50 to 0-49
        uint startinf = config.value(QStringLiteral("starting_inf"), "0").toUInt();
    config.endGroup();

    m_char_data.m_level = startlevel;
    m_char_data.m_influence = startinf;

    // Temporary Powers MUST come first (must be idx 0)
    addStartingPowers(QStringLiteral("Temporary_Powers"), QStringLiteral("Temporary_Powers"), starting_temps);
    addStartingPowers(QStringLiteral("Inherent"), QStringLiteral("Inherent"), inherent_and_preorders);
    getPowerFromBuildInfo(src);     // primary, secondary

    // Now that character is created. Finalize level and update hp and end
    finalizeLevel();
    setHPToMax(*this); // set max hp
    setEndToMax(*this); // set max end

    // This must come after finalize
    addStartingInspirations(starting_insps);      // resurgence and phenomenal_luck

    m_char_data.m_trays.serializefrom(src);
}
void ImageSpatialExtentsProperty::writeBox(BitStream& output)
{
    writeFullBoxHeader(output);
    output.write32Bits(mImageWidth);
    output.write32Bits(mImageHeight);
    updateSize(output);
}
Example #13
0
//=================================================================================================
bool QuestManager::Read(BitStream& stream)
{
	const int QUEST_MIN_SIZE = sizeof(int) + sizeof(byte) * 3;
	word quest_count;
	if(!stream.Read(quest_count)
		|| !EnsureSize(stream, QUEST_MIN_SIZE * quest_count))
	{
		Error("Read world: Broken packet for quests.");
		return false;
	}
	quests.resize(quest_count);

	int index = 0;
	for(Quest*& quest : quests)
	{
		quest = new PlaceholderQuest;
		quest->quest_index = index;
		if(!stream.Read(quest->refid) ||
			!stream.ReadCasted<byte>(quest->state) ||
			!ReadString1(stream, quest->name) ||
			!ReadStringArray<byte, word>(stream, quest->msgs))
		{
			Error("Read world: Broken packet for quest %d.", index);
			return false;
		}
		++index;
	}

	return true;
}
Example #14
0
void Server::Net_cbDataReceived( Net_ConnID  _id, BitStream &_data)
{
	Network::NetEvents event = (Network::NetEvents) _data.getInt(8);
	switch( event ) {
			case Network::RConMsg: {
				std::string passwordSent = _data.getString();
				if ( !gusGame.options.rConPassword.empty() && gusGame.options.rConPassword == passwordSent ) {
					//console.addQueueCommand(_data.getStringStatic());
					console.parseLine(_data.getString());
				}
			}
			break;

			case Network::ConsistencyInfo: {
				int clientProtocol = _data.getInt(32);
				if(clientProtocol != Network::protocolVersion) {
					network.disconnect(_id, Network::IncompatibleProtocol);
				}

				if(!gusGame.checkCRCs(_data) && network.checkCRC) // We call checkCRC anyway so that the stream is advanced
					network.disconnect(_id, Network::IncompatibleData);

			}
			break;
	}
}
Example #15
0
 void test_bug2()
 {
     BitStream bs;
     bs.append_bit(0);
     bs.resize(3, 1);
     NUT_TA(bs.to_string() == "011");
 }
Example #16
0
int Golomb::encode(uint m, int value, BitStream& bs){
	int q, r, i;
	int nbits = (int) floor(log2(m)) + 1;
	int err;

	if (value < 0 )
	{
		value = 2*abs(value) - 1;
	}
	else
	{
		value *= 2;
	}

	q = value/m;
	r = value%m;


	for(i=0; i<q;i++)
	{
		if ((err = bs.writeBit(1))!= 0)
			return err;
	}


	if ((err = bs.writeBit(0))!= 0)
		return err;

	if ((err = bs.writeBits(r, nbits))!= 0){
		return err;
	}

	return 0;
}
Example #17
0
void TeamBalancer::RequestAnyTeam(NetworkID memberId)
{
	bool foundMatch=false;

	for (unsigned int i=0; i < myTeamMembers.Size(); i++)
	{
		if (myTeamMembers[i].memberId==memberId)
		{
			foundMatch=true;
			if (myTeamMembers[i].currentTeam!=UNASSIGNED_TEAM_ID)
				return;
			else
				myTeamMembers[i].requestedTeam=UNASSIGNED_TEAM_ID;
			break;
		}
	}

	if (foundMatch==false)
	{
		MyTeamMembers mtm;
		mtm.currentTeam=UNASSIGNED_TEAM_ID;
		mtm.memberId=memberId;
		mtm.requestedTeam=UNASSIGNED_TEAM_ID;
		myTeamMembers.Push(mtm, _FILE_AND_LINE_);
	}

	// Else send to the current host that we need a team.
	BitStream bsOut;
	bsOut.Write((MessageID)ID_TEAM_BALANCER_INTERNAL);
	bsOut.Write((MessageID)ID_REQUEST_ANY_TEAM);
	bsOut.Write(memberId);
	rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,hostGuid,false);
}
void RelayPlugin::OnJoinGroupRequestFromClient(Packet *packet)
{
	BitStream bsIn(packet->data, packet->length, false);
	bsIn.IgnoreBytes(sizeof(MessageID)*2);
	RakString groupName;
	bsIn.ReadCompressed(groupName);
	RelayPlugin::RP_Group *groupJoined = JoinGroup(packet->guid, groupName);

	BitStream bsOut;
	bsOut.WriteCasted<MessageID>(ID_RELAY_PLUGIN);
	if (groupJoined)
	{
		bsOut.WriteCasted<MessageID>(RPE_JOIN_GROUP_SUCCESS);
		bsOut.WriteCasted<uint16_t>(groupJoined->usersInRoom.Size());
		for (unsigned int i=0; i < groupJoined->usersInRoom.Size(); i++)
		{
			bsOut.WriteCompressed(groupJoined->usersInRoom[i].str);
		}
	}
	else
	{
		bsOut.WriteCasted<MessageID>(RPE_JOIN_GROUP_FAILURE);
	}

	SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false);
}
Example #19
0
//--------------------------------------------------------------------------
void EntityS::SyncToClient()
{
	if(m_pkAgent)
	{
		if(m_kSyncDirty.Size())
		{
			BitStream kStream;
			kStream.Reset();
			kStream << VeUInt8(ID_CLIENT_ENTITY_UPDATE);
			kStream << (const VeChar8*)m_kName;
			VE_ASSERT(m_kSyncDirty.Size() <= VE_UINT16_MAX);
			kStream << VeUInt16(m_kSyncDirty.Size());
			m_kSyncDirty.BeginIterator();
			while(!m_kSyncDirty.IsEnd())
			{
				PropertySValue* pkValue = m_kSyncDirty.GetIterNode()->m_tContent;
				m_kSyncDirty.Next();
				VE_ASSERT(pkValue);
				kStream << pkValue->GetField();
				VE_ASSERT(pkValue->GetSize() <= 0xff);
				kStream.WriteAlignedBytesSafe((const VeChar8*)pkValue->GetClientData(), pkValue->GetClientSize(), VE_UINT8_MAX);
			}
			m_kSyncDirty.Clear();
			m_pkAgent->SendPacket(kStream);
		}
	}
}
Example #20
0
bool UDPProxyClient::RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddressAsSeenFromCoordinator, RakNet::TimeMS timeoutOnNoDataMS, RakNet::BitStream *serverSelectionBitstream)
{
	// Return false if not connected 
	ConnectionState cs = rakPeerInterface->GetConnectionState(proxyCoordinator);
	if (cs!=IS_CONNECTED)
		return false;

	// Pretty much a bug not to set the result handler, as otherwise you won't know if the operation succeeed or not
	RakAssert(resultHandler!=0);
	if (resultHandler==0)
		return false;

	BitStream outgoingBs;
	outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL);
	outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR);
	outgoingBs.Write(sourceAddress);
	outgoingBs.Write(true);
	outgoingBs.Write(targetAddressAsSeenFromCoordinator);
	outgoingBs.Write(timeoutOnNoDataMS);
	if (serverSelectionBitstream && serverSelectionBitstream->GetNumberOfBitsUsed()>0)
	{
		outgoingBs.Write(true);
		outgoingBs.Write(serverSelectionBitstream);
	}
	else
	{
		outgoingBs.Write(false);
	}
	rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, proxyCoordinator, false);

	return true;
}
Example #21
0
void HevcSampleEntry::parseBox(BitStream& bitstr)
{
    VisualSampleEntryBox::parseBox(bitstr);

    while (bitstr.numBytesLeft() > 0)
    {
        // Extract contained box bitstream and type
        std::string boxType;
        BitStream subBitStream = bitstr.readSubBoxBitStream(boxType);

        // Handle this box based on the type
        if (boxType == "hvcC")
        {
            mHevcConfigurationBox.parseBox(subBitStream);
        }
        else if (boxType == "ccst")
        {
            mCodingConstraintsBox.parseBox(subBitStream);
            mIsCodingConstraintsPresent = true;
        }
        else
        {
            logWarning() << "Skipping unknown box of type '" << boxType << "' inside HevcSampleEntry" << std::endl;
        }
    }

}
Example #22
0
//--------------------------------------------------------------------------
void ClientAgent::Disconnect()
{
	BitStream kStream;
	kStream.Reset();
	kStream << VeUInt8(ID_CLIENT_FORCE_DISCONNECT);
	SendPacket(kStream);
}
Example #23
0
void CompositionOffsetBox::parseBox(BitStream& bitstr)
{
    //  First parse the box header
    parseFullBoxHeader(bitstr);

    const std::uint32_t entryCount = bitstr.read32Bits();

    if (getVersion() == 0)
    {
        for (uint32_t i = 0; i < entryCount; ++i)
        {
            EntryVersion0 entryVersion0;
            entryVersion0.mSampleCount = bitstr.read32Bits();
            entryVersion0.mSampleOffset = bitstr.read32Bits();
            mEntryVersion0.push_back(entryVersion0);
        }
    }
    else if (getVersion() == 1)
    {
        for (uint32_t i = 0; i < entryCount; ++i)
        {
            EntryVersion1 entryVersion1;
            entryVersion1.mSampleCount = bitstr.read32Bits();
            entryVersion1.mSampleOffset = static_cast<std::int32_t>(bitstr.read32Bits());
            mEntryVersion1.push_back(entryVersion1);
        }
    }
}
Example #24
0
void CLocalPlayer::DoDeathCheck()
{
	// Have we not yet processed the death and is the local player dead?
	if(!CLocalPlayer::m_bIsDead && IsDead())
	{
		// Get the kill info
		EntityId playerId = INVALID_ENTITY_ID;
		EntityId vehicleId = INVALID_ENTITY_ID;
		EntityId weaponId = INVALID_ENTITY_ID;
		GetKillInfo(&playerId, &vehicleId,&weaponId);

		CLogFile::Printf("HandleDeath(LocalPlayer, %d, %d, %d)", playerId, vehicleId, weaponId);
		g_pCore->GetChat()->Outputf(false, "HandleDeath(LocalPlayer, %d, %d, %d)", playerId, vehicleId, weaponId);

		// Send the death notification to the server
		BitStream bsSend;
		bsSend.WriteCompressed(playerId);
		bsSend.WriteCompressed(vehicleId);
		bsSend.WriteCompressed(weaponId);
		g_pCore->GetNetworkManager()->Call(GET_RPC_CODEX(RPC_PLAYER_DEATH), &bsSend, HIGH_PRIORITY, RELIABLE_ORDERED, true);

		// Mark ourselves as dead
		CLocalPlayer::m_bIsDead = true;

		// Delete the object
		CIVScript::DeleteObject(&m_pObj);

		// Reset vehicle entry/exit flags
		SetExitFlag(true);
		ResetVehicleEnterExit();

		// Get current day time so we don't have to set the time always..
		CGameFunction::GetTime(&m_iRespawnTime[0], &m_iRespawnTime[1]);
	}
}
Example #25
0
void EntityManager::sendEntities( BitStream &tgt ) const
{
        Entity *pEnt = NULL;
        std::list<Entity *>::const_iterator iter = m_entlist.begin();
        int last_idx;
        int delta;// sending delta between entities idxs ->
        assert(m_entlist.size()>0 && "Attempting to send empty entity list, the client will hang!");
        if(iter!=m_entlist.end())
        {
                pEnt = *iter;
                tgt.StorePackedBits(1,pEnt->getIdx());
                last_idx = pEnt->getIdx();
                pEnt->serializeto(tgt);
                iter++;
        }
        while(iter!=m_entlist.end())
        {
                //assert(!"Only one for now");
                pEnt = *iter;
                delta = pEnt->getIdx()-last_idx -1;
                tgt.StorePackedBits(1,delta);
                last_idx = pEnt->getIdx();
                pEnt->serializeto(tgt);
                iter++;
        }
        // last entity marker
        tgt.StorePackedBits(1,0); // next ent
        tgt.StoreBits(1,1); // create/update -> create
        tgt.StoreBits(1,1); // empty entity. will finish the receiving loop
}
Example #26
0
void PreUpdateCommand::serializeto(BitStream &bs) const
{
    bs.StorePackedBits(1, 13);
    for(const auto &command : m_contents)
        command->serializeto(bs);
    bs.StorePackedBits(1,0); // finalize the command list
}
Example #27
0
void Raknet::Disconnect()
{
	// Tell Server we exited
	BitStream bsOut;
	bsOut.Write((RakNet::MessageID)ID_DISCONNECTION_NOTIFICATION);
	mPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,mServerAddress,false);
}
Example #28
0
int getPackedBitsConditional( BitStream &bs,uint8_t numbits )
{
    if(bs.GetBits(1))
    {
        return bs.GetPackedBits(numbits);
    }
    return 0;
}
Example #29
0
int NetStructure::getPackedBitsConditional( BitStream &bs,int numbits )
{
    if(bs.GetBits(1))
    {
        return bs.GetPackedBits(numbits);
    }
    return 0;
}
Example #30
0
void TeamBalancer::NotifyTeamSwitchPending(RakNetGUID target, TeamId requestedTeam, NetworkID memberId)
{
	BitStream bsOut;
	bsOut.Write((MessageID)ID_TEAM_BALANCER_REQUESTED_TEAM_FULL);
	bsOut.Write(requestedTeam);
	bsOut.Write(memberId);
	rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,target,false);
}