// Computes the median in O(N) time. By making a copy this version assures no re-ordering. inline double median(vector<double> &data) { vector<double> data2(data.size()); for(size_t i = 0; i < data.size(); i++) data2[i] = data[i]; return median_unsafe(data2); }
void WorldSession::HandleGrantLevel(WorldPacket& recvData) { TC_LOG_DEBUG("network", "WORLD: CMSG_GRANT_LEVEL"); ObjectGuid guid; guid[2] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[3] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[5]); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[0]); Player* target = ObjectAccessor::GetObjectInWorld(guid, _player); // check cheating uint8 levels = _player->GetGrantableLevels(); uint8 error = 0; if (!target) error = ERR_REFER_A_FRIEND_NO_TARGET; else if (levels == 0) error = ERR_REFER_A_FRIEND_INSUFFICIENT_GRANTABLE_LEVELS; else if (GetRecruiterId() != target->GetSession()->GetAccountId()) error = ERR_REFER_A_FRIEND_NOT_REFERRED_BY; else if (target->GetTeamId() != _player->GetTeamId()) error = ERR_REFER_A_FRIEND_DIFFERENT_FACTION; else if (target->getLevel() >= _player->getLevel()) error = ERR_REFER_A_FRIEND_TARGET_TOO_HIGH; else if (target->getLevel() >= sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL)) error = ERR_REFER_A_FRIEND_GRANT_LEVEL_MAX_I; else if (target->GetGroup() != _player->GetGroup()) error = ERR_REFER_A_FRIEND_NOT_IN_GROUP; if (error) { WorldPacket data(SMSG_REFER_A_FRIEND_FAILURE, 24); data << uint32(error); if (error == ERR_REFER_A_FRIEND_NOT_IN_GROUP) data << target->GetName(); SendPacket(&data); return; } WorldPacket data2(SMSG_PROPOSE_LEVEL_GRANT, 8); data2.WriteBit(guid[6]); data2.WriteBit(guid[7]); data2.WriteBit(guid[2]); data2.WriteBit(guid[5]); data2.WriteBit(guid[3]); data2.WriteBit(guid[0]); data2.WriteBit(guid[1]); data2.WriteBit(guid[4]); data2.WriteByteSeq(guid[2]); data2.WriteByteSeq(guid[5]); data2.WriteByteSeq(guid[6]); data2.WriteByteSeq(guid[7]); data2.WriteByteSeq(guid[1]); data2.WriteByteSeq(guid[4]); data2.WriteByteSeq(guid[3]); data2.WriteByteSeq(guid[0]); target->GetSession()->SendPacket(&data2); }
void WorldSession::HandleBattleFieldPortOpcode( WorldPacket &recv_data ) { sLog.outDebug( "WORLD: Recvd CMSG_BATTLEFIELD_PORT Message"); uint8 type; // arenatype if arena uint8 unk2; // unk, can be 0x0 (may be if was invited?) and 0x1 uint32 bgTypeId_; // type id from dbc uint16 unk; // 0x1F90 constant? uint8 action; // enter battle 0x1, leave queue 0x0 recv_data >> type >> unk2 >> bgTypeId_ >> unk >> action; if (!sBattlemasterListStore.LookupEntry(bgTypeId_)) { sLog.outError("BattlegroundHandler: invalid bgtype (%u) received.", bgTypeId_); return; } if (!_player->InBattleGroundQueue()) { sLog.outError("BattlegroundHandler: Invalid CMSG_BATTLEFIELD_PORT received from player (%u), he is not in bg_queue.", _player->GetGUIDLow()); return; } //get GroupQueueInfo from BattleGroundQueue BattleGroundTypeId bgTypeId = BattleGroundTypeId(bgTypeId_); BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, type); BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId]; //we must use temporary variable, because GroupQueueInfo pointer can be deleted in BattleGroundQueue::RemovePlayer() function GroupQueueInfo ginfo; if (!bgQueue.GetPlayerGroupInfoData(_player->GetGUID(), &ginfo)) { sLog.outError("BattlegroundHandler: itrplayerstatus not found."); return; } // if action == 1, then instanceId is required if (!ginfo.IsInvitedToBGInstanceGUID && action == 1) { sLog.outError("BattlegroundHandler: instance not found."); return; } BattleGround *bg = sBattleGroundMgr.GetBattleGround(ginfo.IsInvitedToBGInstanceGUID, bgTypeId); // bg template might and must be used in case of leaving queue, when instance is not created yet if (!bg && action == 0) bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId); if (!bg) { sLog.outError("BattlegroundHandler: bg_template not found for type id %u.", bgTypeId); return; } // expected bracket entry PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(),_player->getLevel()); if (!bracketEntry) return; //some checks if player isn't cheating - it is not exactly cheating, but we cannot allow it if (action == 1 && ginfo.ArenaType == 0) { //if player is trying to enter battleground (not arena!) and he has deserter debuff, we must just remove him from queue if (!_player->CanJoinToBattleground()) { //send bg command result to show nice message WorldPacket data2(SMSG_GROUP_JOINED_BATTLEGROUND, 4); data2 << uint32(0xFFFFFFFE); _player->GetSession()->SendPacket(&data2); action = 0; sLog.outDebug("Battleground: player %s (%u) has a deserter debuff, do not port him to battleground!", _player->GetName(), _player->GetGUIDLow()); } //if player don't match battleground max level, then do not allow him to enter! (this might happen when player leveled up during his waiting in queue if (_player->getLevel() > bg->GetMaxLevel()) { sLog.outError("Battleground: Player %s (%u) has level (%u) higher than maxlevel (%u) of battleground (%u)! Do not port him to battleground!", _player->GetName(), _player->GetGUIDLow(), _player->getLevel(), bg->GetMaxLevel(), bg->GetTypeID()); action = 0; } } uint32 queueSlot = _player->GetBattleGroundQueueIndex(bgQueueTypeId); WorldPacket data; switch( action ) { case 1: // port to battleground if (!_player->IsInvitedForBattleGroundQueueType(bgQueueTypeId)) return; // cheating? if (!_player->InBattleGround()) _player->SetBattleGroundEntryPoint(); // resurrect the player if (!_player->isAlive()) { _player->ResurrectPlayer(1.0f); _player->SpawnCorpseBones(); } // stop taxi flight at port if (_player->isInFlight()) { _player->GetMotionMaster()->MovementExpired(); _player->m_taxi.ClearTaxiDestinations(); } sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_IN_PROGRESS, 0, bg->GetStartTime(), bg->GetArenaType()); _player->GetSession()->SendPacket(&data); // remove battleground queue status from BGmgr bgQueue.RemovePlayer(_player->GetGUID(), false); // this is still needed here if battleground "jumping" shouldn't add deserter debuff // also this is required to prevent stuck at old battleground after SetBattleGroundId set to new if (BattleGround *currentBg = _player->GetBattleGround()) currentBg->RemovePlayerAtLeave(_player->GetGUID(), false, true); // set the destination instance id _player->SetBattleGroundId(bg->GetInstanceID(), bgTypeId); // set the destination team _player->SetBGTeam(ginfo.Team); // bg->HandleBeforeTeleportToBattleGround(_player); sBattleGroundMgr.SendToBattleGround(_player, ginfo.IsInvitedToBGInstanceGUID, bgTypeId); // add only in HandleMoveWorldPortAck() // bg->AddPlayer(_player,team); sLog.outDebug("Battleground: player %s (%u) joined battle for bg %u, bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetInstanceID(), bg->GetTypeID(), bgQueueTypeId); break; case 0: // leave queue // if player leaves rated arena match before match start, it is counted as he played but he lost if (ginfo.IsRated) { ArenaTeam * at = sObjectMgr.GetArenaTeamById(ginfo.Team); if (at) { sLog.outDebug("UPDATING memberLost's personal arena rating for %u by opponents rating: %u, because he has left queue!", GUID_LOPART(_player->GetGUID()), ginfo.OpponentsTeamRating); at->MemberLost(_player, ginfo.OpponentsTeamRating); at->SaveToDB(); } } _player->RemoveBattleGroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to queue->removeplayer, it causes bugs sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, 0); bgQueue.RemovePlayer(_player->GetGUID(), true); // player left queue, we should update it - do not update Arena Queue if (!ginfo.ArenaType) sBattleGroundMgr.ScheduleQueueUpdate(ginfo.ArenaTeamRating, ginfo.ArenaType, bgQueueTypeId, bgTypeId, bracketEntry->GetBracketId()); SendPacket(&data); sLog.outDebug("Battleground: player %s (%u) left queue for bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetTypeID(), bgQueueTypeId); break; default: sLog.outError("Battleground port: unknown action %u", action); break; } }
void WorldSession::HandleClientAuthentication(WorldPacket& packet) { quint32 bufferSize; packet >> bufferSize; QByteArray buffer; buffer.resize(bufferSize); packet.ReadRawBytes(buffer.data(), buffer.size()); WorldPacket decrypted(0, Cryptography::Instance()->Decrypt(buffer)); quint64 rsaVerification; decrypted >> rsaVerification; QString account = decrypted.ReadString(); QString password = decrypted.ReadString(); QSqlQuery result = Database::Auth()->Query(SELECT_ACCOUNT_BY_USERNAME, QVariantList() << account); if (!result.first()) { SendLoginErrorResult(LOGIN_RESULT_INVALID_LOGIN); return; } QSqlRecord fields = result.record(); QString hashPassword = result.value(fields.indexOf("hash_password")).toString(); if (Utils::HashPassword(account, password) != hashPassword) { SendLoginErrorResult(LOGIN_RESULT_INVALID_LOGIN); return; } m_accountInfos.id = result.value(fields.indexOf("account_id")).toULongLong(); m_accountInfos.username = result.value(fields.indexOf("username")).toString(); m_accountInfos.pseudo = result.value(fields.indexOf("pseudo")).toString(); m_accountInfos.gmLevel = (quint8)result.value(fields.indexOf("username")).toUInt(); m_accountInfos.subscriptionTime = result.value(fields.indexOf("subscription_time")).toUInt(); // Send opcode 2 (connection retry ticket, not implemented) WorldPacket data2(SMSG_CONNECTION_RETRY_TICKET); SendPacket(data2); WorldPacket data(SMSG_CLIENT_AUTH_RESULT); data << quint8(LOGIN_RESULT_SUCCESS); data.StartBlock<quint16>(); { data << quint8(1); { data << quint8(0); data << quint32(6); data << quint8(0); data << quint64(result.value(fields.indexOf("account_id")).toULongLong()); data << quint32(1); // m_subscriptionLevel data << quint32(0); // antiAddictionLevel data << quint64(m_accountInfos.subscriptionTime); // Admin rights ? for (quint8 i = 0; i <= 75; ++i) data << quint32(0); data.WriteString(m_accountInfos.pseudo); data << quint32(0); // m_accountCommunity ID, see Wl.java for IDs data << quint16(0); // size of hdv, see bOE.java something with m_accountCommunity and check TS.java } } data.EndBlock<quint16>(); SendPacket(data); SendWorldSelectResult(); }
Sound Sounds_crossCorrelate (Sound me, Sound thee, enum kSounds_convolve_scaling scaling, enum kSounds_convolve_signalOutsideTimeDomain signalOutsideTimeDomain) { try { if (my ny > 1 && thy ny > 1 && my ny != thy ny) Melder_throw (U"The numbers of channels of the two sounds have to be equal or 1."); if (my dx != thy dx) Melder_throw (U"The sampling frequencies of the two sounds have to be equal."); long numberOfChannels = my ny > thy ny ? my ny : thy ny; long n1 = my nx, n2 = thy nx; long n3 = n1 + n2 - 1, nfft = 1; while (nfft < n3) nfft *= 2; autoNUMvector <double> data1 (1, nfft); autoNUMvector <double> data2 (1, nfft); double my_xlast = my x1 + (n1 - 1) * my dx; autoSound him = Sound_create (numberOfChannels, thy xmin - my xmax, thy xmax - my xmin, n3, my dx, thy x1 - my_xlast); for (long channel = 1; channel <= numberOfChannels; channel ++) { double *a = my z [my ny == 1 ? 1 : channel]; for (long i = n1; i > 0; i --) data1 [i] = a [i]; for (long i = n1 + 1; i <= nfft; i ++) data1 [i] = 0.0; a = thy z [thy ny == 1 ? 1 : channel]; for (long i = n2; i > 0; i --) data2 [i] = a [i]; for (long i = n2 + 1; i <= nfft; i ++) data2 [i] = 0.0; NUMrealft (data1.peek(), nfft, 1); NUMrealft (data2.peek(), nfft, 1); data2 [1] *= data1 [1]; data2 [2] *= data1 [2]; for (long i = 3; i <= nfft; i += 2) { double temp = data1 [i] * data2 [i] + data1 [i + 1] * data2 [i + 1]; // reverse me by taking the conjugate of data1 data2 [i + 1] = data1 [i] * data2 [i + 1] - data1 [i + 1] * data2 [i]; // reverse me by taking the conjugate of data1 data2 [i] = temp; } NUMrealft (data2.peek(), nfft, -1); a = him -> z [channel]; for (long i = 1; i < n1; i ++) { a [i] = data2 [i + (nfft - (n1 - 1))]; // data for the first part ("negative lags") is at the end of data2 } for (long i = 1; i <= n2; i ++) { a [i + (n1 - 1)] = data2 [i]; // data for the second part ("positive lags") is at the beginning of data2 } } switch (signalOutsideTimeDomain) { case kSounds_convolve_signalOutsideTimeDomain_ZERO: { // do nothing } break; case kSounds_convolve_signalOutsideTimeDomain_SIMILAR: { for (long channel = 1; channel <= numberOfChannels; channel ++) { double *a = his z [channel]; double edge = n1 < n2 ? n1 : n2; for (long i = 1; i < edge; i ++) { double factor = edge / i; a [i] *= factor; a [n3 + 1 - i] *= factor; } } } break; //case kSounds_convolve_signalOutsideTimeDomain_PERIODIC: { // do nothing //} break; default: Melder_fatal (U"Sounds_crossCorrelate: unimplemented outside-time-domain strategy ", signalOutsideTimeDomain); } switch (scaling) { case kSounds_convolve_scaling_INTEGRAL: { Vector_multiplyByScalar (him.peek(), my dx / nfft); } break; case kSounds_convolve_scaling_SUM: { Vector_multiplyByScalar (him.peek(), 1.0 / nfft); } break; case kSounds_convolve_scaling_NORMALIZE: { double normalizationFactor = Matrix_getNorm (me) * Matrix_getNorm (thee); if (normalizationFactor != 0.0) { Vector_multiplyByScalar (him.peek(), 1.0 / nfft / normalizationFactor); } } break; case kSounds_convolve_scaling_PEAK_099: { Vector_scale (him.peek(), 0.99); } break; default: Melder_fatal (U"Sounds_crossCorrelate: unimplemented scaling ", scaling); } return him.transfer(); } catch (MelderError) { Melder_throw (me, U" & ", thee, U": not cross-correlated."); } }
void SetData(uint32 type, uint32 data) { switch (type) { case DATA_RAGEWINTERCHILLEVENT: Encounters[0] = data; break; case DATA_ANETHERONEVENT: Encounters[1] = data; break; case DATA_KAZROGALEVENT: Encounters[2] = data; break; case DATA_AZGALOREVENT: { Encounters[3] = data; if (data == DONE) { if (ArchiYell)break; ArchiYell = true; Creature* creature = instance->GetCreature(Azgalor); if (creature) { Creature* pUnit = creature->SummonCreature(21987, creature->GetPositionX(),creature->GetPositionY(),creature->GetPositionZ(),0, TEMPSUMMON_TIMED_DESPAWN, 10000); Map* pMap = creature->GetMap(); if (pMap->IsDungeon() && pUnit) { pUnit->SetVisibility(VISIBILITY_OFF); Map::PlayerList const &PlayerList = pMap->GetPlayers(); if (PlayerList.isEmpty()) return; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->getSource()) { WorldPacket data(SMSG_MESSAGECHAT, 200); pUnit->BuildMonsterChat(&data, CHAT_MSG_MONSTER_YELL, YELL_EFFORTS, 0, YELL_EFFORTS_NAME, i->getSource()->GetGUID()); i->getSource()->GetSession()->SendPacket(&data); WorldPacket data2(SMSG_PLAY_SOUND, 4); data2 << 10986; i->getSource()->GetSession()->SendPacket(&data2); } } } } } } break; case DATA_ARCHIMONDEEVENT: Encounters[4] = data; break; case DATA_RESET_TRASH_COUNT: Trash = 0; break; case DATA_TRASH: if (data) Trash = data; else Trash--; UpdateWorldState(WORLD_STATE_ENEMYCOUNT, Trash); break; case DATA_ALLIANCE_RETREAT: allianceRetreat = data; OpenDoor(HordeGate, true); SaveToDB(); break; case DATA_HORDE_RETREAT: hordeRetreat = data; OpenDoor(ElfGate, true); SaveToDB(); break; case DATA_RAIDDAMAGE: RaidDamage += data; if (RaidDamage >= MINRAIDDAMAGE) RaidDamage = MINRAIDDAMAGE; break; case DATA_RESET_RAIDDAMAGE: RaidDamage = 0; break; } sLog->outDebug("TSCR: Instance Hyjal: Instance data updated for event %u (Data=%u)",type, data); if (data == DONE) SaveToDB(); }
/*Loot type MUST be 1-corpse, go 2-skinning/herbalism/minning 3-Fishing */ void Player::SendLoot(uint64 guid, uint8 loot_type, uint32 mapid) { Group* m_Group = m_playerInfo->m_Group; if(!IsInWorld()) return; Loot* pLoot = NULL; uint32 guidtype = GET_TYPE_FROM_GUID(guid); int8 loot_method; if(m_Group != NULL) loot_method = m_Group->GetMethod(); else loot_method = PARTY_LOOT_FFA; if(guidtype == HIGHGUID_TYPE_UNIT) { Creature* pCreature = GetMapMgr()->GetCreature(GET_LOWGUID_PART(guid)); if(!pCreature)return; pLoot = &pCreature->loot; m_currentLoot = pCreature->GetGUID(); } else if(guidtype == HIGHGUID_TYPE_GAMEOBJECT) { GameObject* pGO = GetMapMgr()->GetGameObject(GET_LOWGUID_PART(guid)); if(!pGO)return; pGO->SetByte(GAMEOBJECT_BYTES_1, 0, 0); pLoot = &pGO->loot; m_currentLoot = pGO->GetGUID(); } else if((guidtype == HIGHGUID_TYPE_PLAYER)) { Player* p = GetMapMgr()->GetPlayer((uint32)guid); if(!p)return; pLoot = &p->loot; m_currentLoot = p->GetGUID(); } else if((guidtype == HIGHGUID_TYPE_CORPSE)) { Corpse* pCorpse = objmgr.GetCorpse((uint32)guid); if(!pCorpse)return; pLoot = &pCorpse->loot; m_currentLoot = pCorpse->GetGUID(); } else if((guidtype == HIGHGUID_TYPE_ITEM)) { Item* pItem = GetItemInterface()->GetItemByGUID(guid); if(!pItem) return; pLoot = pItem->loot; m_currentLoot = pItem->GetGUID(); } if(!pLoot) { // something whack happened.. damn cheaters.. return; } // add to looter set pLoot->looters.insert(GetLowGUID()); WorldPacket data, data2(32); data.SetOpcode(SMSG_LOOT_RESPONSE); m_lootGuid = guid; data << uint64(guid); data << uint8(loot_type); //loot_type; data << uint32(pLoot->gold); data << uint8(0); //loot size reserve std::vector<__LootItem>::iterator iter = pLoot->items.begin(); uint32 count = 0; uint8 slottype = 0; for(uint32 x = 0; iter != pLoot->items.end(); iter++, x++) { if(iter->iItemsCount == 0) continue; LooterSet::iterator itr = iter->has_looted.find(GetLowGUID()); if(iter->has_looted.end() != itr) continue; ItemPrototype* itemProto = iter->item.itemproto; if(!itemProto) continue; // check if it's on ML if so only quest items and ffa loot should be shown based on mob if(loot_method == PARTY_LOOT_MASTER && m_Group && m_Group->GetLooter() != m_playerInfo) // pass on all ffa_loot and the grey / white items if(!iter->ffa_loot && !(itemProto->Quality < m_Group->GetThreshold())) continue; // team check if( itemProto->HasFlag2(ITEM_FLAG2_HORDE_ONLY) && IsTeamAlliance() ) continue; if( itemProto->HasFlag2(ITEM_FLAG2_ALLIANCE_ONLY) && IsTeamHorde() ) continue; //quest items check. type 4/5 //quest items that don't start quests. if((itemProto->Bonding == ITEM_BIND_QUEST) && !(itemProto->QuestId) && !HasQuestForItem(itemProto->ItemId)) continue; if((itemProto->Bonding == ITEM_BIND_QUEST2) && !(itemProto->QuestId) && !HasQuestForItem(itemProto->ItemId)) continue; //quest items that start quests need special check to avoid drops all the time. if((itemProto->Bonding == ITEM_BIND_QUEST) && (itemProto->QuestId) && GetQuestLogForEntry(itemProto->QuestId)) continue; if((itemProto->Bonding == ITEM_BIND_QUEST2) && (itemProto->QuestId) && GetQuestLogForEntry(itemProto->QuestId)) continue; if((itemProto->Bonding == ITEM_BIND_QUEST) && (itemProto->QuestId) && HasFinishedQuest(itemProto->QuestId)) continue; if((itemProto->Bonding == ITEM_BIND_QUEST2) && (itemProto->QuestId) && HasFinishedQuest(itemProto->QuestId)) continue; //check for starting item quests that need questlines. if((itemProto->QuestId && itemProto->Bonding != ITEM_BIND_QUEST && itemProto->Bonding != ITEM_BIND_QUEST2)) { Quest* pQuest = QuestStorage.LookupEntry(itemProto->QuestId); if(pQuest) { uint32 finishedCount = 0; //check if its a questline. for(uint32 i = 0; i < pQuest->count_requiredquests; i++) { if(pQuest->required_quests[i]) { if(!HasFinishedQuest(pQuest->required_quests[i]) || GetQuestLogForEntry(pQuest->required_quests[i])) { } else { finishedCount++; } } } } } slottype = 0; if(m_Group != NULL && loot_type < 2) { switch(loot_method) { case PARTY_LOOT_MASTER: slottype = 2; break; case PARTY_LOOT_GROUP: case PARTY_LOOT_RR: case PARTY_LOOT_NBG: slottype = 1; break; default: slottype = 0; break; } // only quality items are distributed if(itemProto->Quality < m_Group->GetThreshold()) { slottype = 0; } // if all people passed anyone can loot it? :P if(iter->passed) slottype = 0; // All players passed on the loot //if it is ffa loot and not an masterlooter if(iter->ffa_loot) slottype = 0; } data << uint8(x); data << uint32(itemProto->ItemId); data << uint32(iter->iItemsCount); //nr of items of this type data << uint32(iter->item.displayid); if(iter->iRandomSuffix) { data << uint32(Item::GenerateRandomSuffixFactor(itemProto)); data << uint32(-int32(iter->iRandomSuffix->id)); } else if(iter->iRandomProperty) { data << uint32(0); data << uint32(iter->iRandomProperty->ID); } else { data << uint32(0); data << uint32(0); } data << slottype; // "still being rolled for" flag if(slottype == 1) { if(iter->roll == NULL && !iter->passed) { int32 ipid = 0; uint32 factor = 0; if(iter->iRandomProperty) ipid = iter->iRandomProperty->ID; else if(iter->iRandomSuffix) { ipid = -int32(iter->iRandomSuffix->id); factor = Item::GenerateRandomSuffixFactor(iter->item.itemproto); } if(iter->item.itemproto) { iter->roll = new LootRoll(60000, (m_Group != NULL ? m_Group->MemberCount() : 1), guid, x, itemProto->ItemId, factor, uint32(ipid), GetMapMgr()); data2.Initialize(SMSG_LOOT_START_ROLL); data2 << guid; data2 << uint32(mapid); data2 << uint32(x); data2 << uint32(itemProto->ItemId); data2 << uint32(factor); if(iter->iRandomProperty) data2 << uint32(iter->iRandomProperty->ID); else if(iter->iRandomSuffix) data2 << uint32(ipid); else data2 << uint32(0); data2 << uint32(iter->iItemsCount); data2 << uint32(60000); // countdown data2 << uint8(7); // some sort of flags that require research } Group* pGroup = m_playerInfo->m_Group; if(pGroup) { pGroup->Lock(); for(uint32 i = 0; i < pGroup->GetSubGroupCount(); ++i) { for(GroupMembersSet::iterator itr2 = pGroup->GetSubGroup(i)->GetGroupMembersBegin(); itr2 != pGroup->GetSubGroup(i)->GetGroupMembersEnd(); ++itr2) { PlayerInfo* pinfo = *itr2; if(pinfo->m_loggedInPlayer && pinfo->m_loggedInPlayer->GetItemInterface()->CanReceiveItem(itemProto, iter->iItemsCount) == 0) { if(pinfo->m_loggedInPlayer->m_passOnLoot) iter->roll->PlayerRolled(pinfo->m_loggedInPlayer, 3); // passed else pinfo->m_loggedInPlayer->SendPacket(&data2); } } } pGroup->Unlock(); } else { m_session->SendPacket(&data2); } } } count++; } data.wpos(13); data << uint8(count); m_session->SendPacket(&data); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING); }
void ClipboardMonitor::checkClipboard(QClipboard::Mode mode) { #ifdef COPYQ_WS_X11 m_x11->cancelSynchronization(); #endif // Check clipboard after interval because someone is updating it very quickly. bool needToWait = m_updateTimer->isActive(); if (mode == QClipboard::Clipboard) m_needCheckClipboard = needToWait; #ifdef COPYQ_WS_X11 else if (mode == QClipboard::Selection) m_needCheckSelection = needToWait; #endif else return; m_updateTimer->start(); if (needToWait) return; #ifdef COPYQ_WS_X11 if ( mode == QClipboard::Selection && m_x11->isSelectionIncomplete() ) return; if ( m_x11->maybeResetClipboard(mode) ) return; #endif COPYQ_LOG( QString("Checking for new %1 content.") .arg(mode == QClipboard::Clipboard ? "clipboard" : "selection") ); // get clipboard data const QMimeData *data = clipboardData(mode); // data retrieved? if (!data) { log( tr("Cannot access clipboard data!"), LogError ); return; } // clone only mime types defined by user #if defined(Q_OS_MAC) // On OS X, when you copy files in Finder, etc. you get: // - The file name(s) (not paths) as plain text // - The file URI(s) // - The icon (not thumbnail) for the type of item you have in various image formants // We really only want the URI list, so throw the rest away QStringList formats = m_formats; if (data->formats().contains(mimeUriList) && formats.contains(mimeUriList)) { formats = QStringList() << mimeUriList; } QVariantMap data2( cloneData(*data, formats) ); #else QVariantMap data2( cloneData(*data, m_formats) ); #endif // add window title of clipboard owner if ( !data2.contains(mimeOwner) && !data2.contains(mimeWindowTitle) ) { PlatformPtr platform = createPlatformNativeInterface(); PlatformWindowPtr currentWindow = platform->getCurrentWindow(); if (currentWindow) data2.insert( mimeWindowTitle, currentWindow->getTitle().toUtf8() ); } #ifdef COPYQ_WS_X11 m_x11->setData(mode, data2); if (mode == QClipboard::Clipboard) { if ( !ownsClipboardData(data2) && m_x11->synchronize(QClipboard::Selection) ) m_needCheckSelection = false; clipboardChanged(data2); } else { data2.insert(mimeClipboardMode, "selection"); if ( !ownsClipboardData(data2) && m_x11->synchronize(QClipboard::Clipboard) ) m_needCheckClipboard = false; if ( m_x11->hasCheckSelection() ) clipboardChanged(data2); } #else /* !COPYQ_WS_X11 */ clipboardChanged(data2); #endif }
BOOST_FIXTURE_TEST_CASE(EndToEnd6, EndToEndFixture) { UdpFactory factory; factory.createChannel("::1", "20071"); factory.createFace(FaceUri("udp://[::1]:20070"), bind(&EndToEndFixture::channel2_onFaceCreated, this, _1), bind(&EndToEndFixture::channel2_onConnectFailed, this, _1)); BOOST_CHECK_MESSAGE(limitedIo.run(1, time::seconds(1)) == LimitedIo::EXCEED_OPS, "UdpChannel error: cannot connect or cannot accept connection"); BOOST_REQUIRE(static_cast<bool>(face2)); BOOST_CHECK_EQUAL(face2->getRemoteUri().toString(), "udp6://[::1]:20070"); BOOST_CHECK_EQUAL(face2->getLocalUri().toString(), "udp6://[::1]:20071"); BOOST_CHECK_EQUAL(face2->isLocal(), false); // face1 is not created yet shared_ptr<UdpChannel> channel1 = factory.createChannel("::1", "20070"); channel1->listen(bind(&EndToEndFixture::channel1_onFaceCreated, this, _1), bind(&EndToEndFixture::channel1_onConnectFailed, this, _1)); Interest interest1("ndn:/TpnzGvW9R"); Data data1 ("ndn:/KfczhUqVix"); data1.setContent(0, 0); Interest interest2("ndn:/QWiIMfj5sL"); Data data2 ("ndn:/XNBV796f"); data2.setContent(0, 0); Interest interest3("ndn:/QWiIhjgkj5sL"); Data data3 ("ndn:/XNBV794f"); data3.setContent(0, 0); ndn::SignatureSha256WithRsa fakeSignature; fakeSignature.setValue(ndn::dataBlock(tlv::SignatureValue, reinterpret_cast<const uint8_t*>(0), 0)); // set fake signature on data1 and data2 data1.setSignature(fakeSignature); data2.setSignature(fakeSignature); data3.setSignature(fakeSignature); face2->sendInterest(interest2); face2->sendData (data2 ); BOOST_CHECK_MESSAGE(limitedIo.run(3,//2 send + 1 listen return time::seconds(1)) == LimitedIo::EXCEED_OPS, "UdpChannel error: cannot send or receive Interest/Data packets"); BOOST_REQUIRE(static_cast<bool>(face1)); BOOST_CHECK_EQUAL(face1->getRemoteUri().toString(), "udp6://[::1]:20071"); BOOST_CHECK_EQUAL(face1->getLocalUri().toString(), "udp6://[::1]:20070"); BOOST_CHECK_EQUAL(face1->isLocal(), false); face1->sendInterest(interest1); face1->sendData (data1 ); BOOST_CHECK_MESSAGE(limitedIo.run(2, time::seconds(1)) == LimitedIo::EXCEED_OPS, "UdpChannel error: cannot send or receive Interest/Data packets"); BOOST_REQUIRE_EQUAL(face1_receivedInterests.size(), 1); BOOST_REQUIRE_EQUAL(face1_receivedDatas .size(), 1); BOOST_REQUIRE_EQUAL(face2_receivedInterests.size(), 1); BOOST_REQUIRE_EQUAL(face2_receivedDatas .size(), 1); BOOST_CHECK_EQUAL(face1_receivedInterests[0].getName(), interest2.getName()); BOOST_CHECK_EQUAL(face1_receivedDatas [0].getName(), data2.getName()); BOOST_CHECK_EQUAL(face2_receivedInterests[0].getName(), interest1.getName()); BOOST_CHECK_EQUAL(face2_receivedDatas [0].getName(), data1.getName()); //checking if the connection accepting mechanism works properly. face2->sendData (data3 ); face2->sendInterest(interest3); BOOST_CHECK_MESSAGE(limitedIo.run(2, time::seconds(1)) == LimitedIo::EXCEED_OPS, "UdpChannel error: cannot send or receive Interest/Data packets"); BOOST_REQUIRE_EQUAL(face1_receivedInterests.size(), 2); BOOST_REQUIRE_EQUAL(face1_receivedDatas .size(), 2); BOOST_CHECK_EQUAL(face1_receivedInterests[1].getName(), interest3.getName()); BOOST_CHECK_EQUAL(face1_receivedDatas [1].getName(), data3.getName()); }
void SetData(uint32 type, uint32 data) { switch(type) { case DATA_RAGEWINTERCHILLEVENT: Encounters[0] = data; break; case DATA_ANETHERONEVENT: Encounters[1] = data; break; case DATA_KAZROGALEVENT: Encounters[2] = data; break; case DATA_AZGALOREVENT: { Encounters[3] = data; if(data==DONE) { if(ArchiYell)break; ArchiYell = true; Creature* pCreature = instance->GetCreatureInMap(Azgalor); if(pCreature) { Creature* pUnit = pCreature->SummonCreature(21987,pCreature->GetPositionX(),pCreature->GetPositionY(),pCreature->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN,10000); Map *map = pCreature->GetMap(); if (map->IsDungeon() && pUnit) { pUnit->SetVisibility(VISIBILITY_OFF); Map::PlayerList const &PlayerList = map->GetPlayers(); if (PlayerList.isEmpty()) return; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->getSource()) { WorldPacket data(SMSG_MESSAGECHAT, 200); pUnit->BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,"All of your efforts have been in vain, for the draining of the World Tree has already begun. Soon the heart of your world will beat no more.",0,"Archimonde",i->getSource()->GetGUID()); i->getSource()->GetSession()->SendPacket(&data); WorldPacket data2(SMSG_PLAY_SOUND, 4); data2 << 10986; i->getSource()->GetSession()->SendPacket(&data2); } } } } } } break; case DATA_ARCHIMONDEEVENT: Encounters[4] = data; break; case DATA_RESET_TRASH_COUNT: Trash = 0; break; case DATA_TRASH: if(data) Trash = data; else Trash--; UpdateWorldState(WORLD_STATE_ENEMYCOUNT, Trash); break; case DATA_ALLIANCE_RETREAT: allianceRetreat = data; OpenDoor(HordeGate,true); SaveToDB(); break; case DATA_HORDE_RETREAT: hordeRetreat = data; OpenDoor(ElfGate,true); SaveToDB(); break; case DATA_RAIDDAMAGE: RaidDamage += data; if(RaidDamage >= MINRAIDDAMAGE) RaidDamage = MINRAIDDAMAGE; break; case DATA_RESET_RAIDDAMAGE: RaidDamage = 0; break; } debug_log("SD2: Instance Hyjal: Instance data updated for event %u (Data=%u)",type,data); if(data == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << Encounters[0] << " " << Encounters[1] << " " << Encounters[2] << " " << Encounters[3] << " " << Encounters[4] << " " << allianceRetreat << " " << hordeRetreat << " " << RaidDamage; str_data = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } }
int main(int argc, char** argv) { try { // Parse the command line if (argc != 2) { std::cerr << "Usage: " << sys::Path::basename(argv[0]) << " <output NITF pathname prefix>\n\n"; return 1; } const std::string outPathnamePrefix(argv[1]); verifySchemaEnvVariableIsSet(); // In order to make it easier to test segmenting, let's artificially set // the segment size really small const size_t numCols = 200; const size_t maxSize = numCols * 50; six::XMLControlRegistry xmlRegistry; xmlRegistry.addCreator( six::DataType::DERIVED, new six::XMLControlCreatorT< six::sidd::DerivedXMLControl>()); six::Container container(six::DataType::DERIVED); std::vector<six::UByte*> buffers; // First a single segment without a legend types::RowCol<size_t> dims1(40, numCols); std::auto_ptr<six::Data> data1(mockupDerivedData(dims1)); const mem::ScopedArray<sys::ubyte> buffer1(new sys::ubyte[dims1.normL1()]); std::fill_n(buffer1.get(), dims1.normL1(), 20); container.addData(data1); buffers.push_back(buffer1.get()); // Now a single segment with a mono legend types::RowCol<size_t> dims2(40, numCols); std::auto_ptr<six::Data> data2(mockupDerivedData(dims2)); const types::RowCol<size_t> legendDims(50, 50); std::auto_ptr<six::Legend> monoLegend(new six::Legend()); monoLegend->mType = six::PixelType::MONO8I; monoLegend->mLocation.row = 10; monoLegend->mLocation.col = 10; monoLegend->setDims(legendDims); const mem::ScopedArray<sys::ubyte> buffer2(new sys::ubyte[dims2.normL1()]); std::fill_n(buffer2.get(), dims2.normL1(), 100); container.addData(data2, monoLegend); buffers.push_back(buffer2.get()); // Now a multi-segment without a legend types::RowCol<size_t> dims3(150, numCols); std::auto_ptr<six::Data> data3(mockupDerivedData(dims3)); const mem::ScopedArray<sys::ubyte> buffer3(new sys::ubyte[dims3.normL1()]); std::fill_n(buffer3.get(), dims3.normL1(), 60); container.addData(data3); buffers.push_back(buffer3.get()); // Now a multi-segment with an RGB legend types::RowCol<size_t> dims4(155, numCols); std::auto_ptr<six::Data> data4(mockupDerivedData(dims4)); std::auto_ptr<six::Legend> rgbLegend(new six::Legend()); rgbLegend->mType = six::PixelType::RGB8LU; rgbLegend->mLocation.row = 10; rgbLegend->mLocation.col = 10; rgbLegend->setDims(legendDims); rgbLegend->mLUT.reset(new six::LUT(256, 3)); for (size_t ii = 0, idx = 0; ii < rgbLegend->mLUT->numEntries; ++ii, idx += 3) { rgbLegend->mLUT->table[idx] = ii; rgbLegend->mLUT->table[idx + 1] = ii; rgbLegend->mLUT->table[idx + 2] = ii; } const mem::ScopedArray<sys::ubyte> buffer4(new sys::ubyte[dims4.normL1()]); std::fill_n(buffer4.get(), dims4.normL1(), 200); container.addData(data4, rgbLegend); buffers.push_back(buffer4.get()); // Write it out { six::NITFWriteControl writer; writer.getOptions().setParameter( six::NITFWriteControl::OPT_MAX_PRODUCT_SIZE, str::toString(maxSize)); writer.setXMLControlRegistry(&xmlRegistry); writer.initialize(&container); writer.save(buffers, outPathnamePrefix + "_unblocked.nitf"); } // Write it out with blocking { six::NITFWriteControl writer; writer.getOptions().setParameter( six::NITFWriteControl::OPT_MAX_PRODUCT_SIZE, str::toString(maxSize)); const std::string blockSize("1024"); writer.getOptions().setParameter( six::NITFWriteControl::OPT_NUM_ROWS_PER_BLOCK, blockSize); writer.getOptions().setParameter( six::NITFWriteControl::OPT_NUM_COLS_PER_BLOCK, blockSize); writer.setXMLControlRegistry(&xmlRegistry); writer.initialize(&container); writer.save(buffers, outPathnamePrefix + "_blocked.nitf"); } return 0; } catch (const except::Exception& e) { std::cerr << "Caught exception: " << e.getMessage() << std::endl; return 1; } catch (const std::exception& e) { std::cerr << "Caught exception: " << e.what() << std::endl; return 1; } catch (...) { std::cerr << "Unknown exception\n"; return 1; } }
void WorldSession::HandleBattleFieldPortOpcode(WorldPacket& recv_data) { DEBUG_LOG("WORLD: Received opcode CMSG_BATTLEFIELD_PORT"); uint8 action; // enter battle 0x1, leave queue 0x0 uint32 mapId; recv_data >> mapId >> action; BattleGroundTypeId bgTypeId = GetBattleGroundTypeIdByMapId(mapId); if (bgTypeId == BATTLEGROUND_TYPE_NONE) { sLog.outError("BattlegroundHandler: invalid bg map (%u) received.", mapId); return; } if (!_player->InBattleGroundQueue()) { sLog.outError("BattlegroundHandler: Invalid CMSG_BATTLEFIELD_PORT received from player (%u), he is not in bg_queue.", _player->GetGUIDLow()); return; } // get GroupQueueInfo from BattleGroundQueue BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId); BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId]; // we must use temporary variable, because GroupQueueInfo pointer can be deleted in BattleGroundQueue::RemovePlayer() function GroupQueueInfo ginfo; if (!bgQueue.GetPlayerGroupInfoData(_player->GetObjectGuid(), &ginfo)) { sLog.outError("BattlegroundHandler: itrplayerstatus not found."); return; } // if action == 1, then instanceId is required if (!ginfo.IsInvitedToBGInstanceGUID && action == 1) { sLog.outError("BattlegroundHandler: instance not found."); return; } BattleGround* bg = sBattleGroundMgr.GetBattleGround(ginfo.IsInvitedToBGInstanceGUID, bgTypeId); // bg template might and must be used in case of leaving queue, when instance is not created yet if (!bg && action == 0) bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId); if (!bg) { sLog.outError("BattlegroundHandler: bg_template not found for type id %u.", bgTypeId); return; } // some checks if player isn't cheating - it is not exactly cheating, but we cannot allow it if (action == 1) { // if player is trying to enter battleground and he has deserter debuff, we must just remove him from queue if (!_player->CanJoinToBattleground()) { // send bg command result to show nice message WorldPacket data2(SMSG_GROUP_JOINED_BATTLEGROUND, 4); data2 << uint32(0xFFFFFFFE); _player->GetSession()->SendPacket(&data2); action = 0; DEBUG_LOG("Battleground: player %s (%u) has a deserter debuff, do not port him to battleground!", _player->GetName(), _player->GetGUIDLow()); } // if player don't match battleground max level, then do not allow him to enter! (this might happen when player leveled up during his waiting in queue if (_player->getLevel() > bg->GetMaxLevel()) { sLog.outError("Battleground: Player %s (%u) has level (%u) higher than maxlevel (%u) of battleground (%u)! Do not port him to battleground!", _player->GetName(), _player->GetGUIDLow(), _player->getLevel(), bg->GetMaxLevel(), bg->GetTypeID()); action = 0; } } uint32 queueSlot = _player->GetBattleGroundQueueIndex(bgQueueTypeId); WorldPacket data; switch (action) { case 1: // port to battleground if (!_player->IsInvitedForBattleGroundQueueType(bgQueueTypeId)) return; // cheating? // resurrect the player if (!_player->isAlive()) { _player->ResurrectPlayer(1.0f); _player->SpawnCorpseBones(); } // stop taxi flight at port if (_player->IsTaxiFlying()) { _player->GetMotionMaster()->MovementExpired(); _player->m_taxi.ClearTaxiDestinations(); } sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_IN_PROGRESS, 0, bg->GetStartTime()); _player->GetSession()->SendPacket(&data); // remove battleground queue status from BGmgr bgQueue.RemovePlayer(_player->GetObjectGuid(), false); // this is still needed here if battleground "jumping" shouldn't add deserter debuff // also this is required to prevent stuck at old battleground after SetBattleGroundId set to new if (BattleGround* currentBg = _player->GetBattleGround()) currentBg->RemovePlayerAtLeave(_player->GetObjectGuid(), false, true); // set the destination instance id _player->SetBattleGroundId(bg->GetInstanceID(), bgTypeId); // set the destination team _player->SetBGTeam(ginfo.GroupTeam); // bg->HandleBeforeTeleportToBattleGround(_player); sBattleGroundMgr.SendToBattleGround(_player, ginfo.IsInvitedToBGInstanceGUID, bgTypeId); // add only in HandleMoveWorldPortAck() // bg->AddPlayer(_player,team); DEBUG_LOG("Battleground: player %s (%u) joined battle for bg %u, bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetInstanceID(), bg->GetTypeID(), bgQueueTypeId); break; case 0: // leave queue _player->RemoveBattleGroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to queue->removeplayer, it causes bugs sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0); bgQueue.RemovePlayer(_player->GetObjectGuid(), true); // player left queue, we should update it sBattleGroundMgr.ScheduleQueueUpdate(bgQueueTypeId, bgTypeId, _player->GetBattleGroundBracketIdFromLevel(bgTypeId)); SendPacket(&data); DEBUG_LOG("Battleground: player %s (%u) left queue for bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetTypeID(), bgQueueTypeId); break; default: sLog.outError("Battleground port: unknown action %u", action); break; } }
string fmitcp::dataToString(const char* data, long size) { std::string data2(data, size); return data2; }
void Channel::Part(RPlayerInfo* plr, bool silent) { if(plr == NULL || plr->GetSession() == NULL) return; m_lock.Acquire(); WorldPacket data(SMSG_CHANNEL_NOTIFY, 100); uint32 flags; MemberMap::iterator itr = m_members.find(plr); if(itr == m_members.end()) { data << uint8(CHANNEL_NOTIFY_FLAG_NOTON) << m_name; plr->GetSession()->SendPacket(&data); m_lock.Release(); return; } flags = itr->second; m_members.erase(itr); WorldPacket data2(ISMSG_CHANNEL_ACTION, 9); data2 << uint8(CHANNEL_PART); // left channel data2 << uint32(plr->Guid); data2 << uint32(m_channelId); plr->GetSession()->GetServer()->SendPacket(&data2); if(flags & CHANNEL_FLAG_OWNER) { // we need to find a new owner SetOwner(NULL, NULL); } if(plr->GetSession()) { if( !silent ) { data << uint8(CHANNEL_NOTIFY_FLAG_YOULEFT) << m_name << m_typeId << uint32(0) << uint8(0); plr->GetSession()->SendPacket(&data); } } if(m_announce) { data.clear(); data << uint8(CHANNEL_NOTIFY_FLAG_LEFT) << m_name << uint64(plr->Guid); SendToAll(&data); } #ifndef WIN32 if(m_members.size() == 0 ) { m_lock.Release(); channelmgr.RemoveChannel(this); } else m_lock.Release(); #else m_lock.Release(); #endif }
int main (int argc, char** argv) { // get run number std::string inputName = std::string(argv[1]); char split_char = '/'; std::vector<std::string> tokens; std::istringstream split(inputName); for(std::string each; getline(split, each, split_char); tokens.push_back(each)); split_char = '_'; std::vector<std::string> tokens_name; std::istringstream split_name(tokens.at(1)); for(std::string each; getline(split_name, each, split_char); tokens_name.push_back(each)); const int Ch_ref1 = atoi((tokens_name.at(1)).c_str()); const int Ch_ref2 = atoi((tokens_name.at(3)).c_str()); const int Ch_1 = atoi((tokens_name.at(5)).c_str()); const int Ch_2 = atoi((tokens_name.at(7)).c_str()); const int Ch_3 = atoi((tokens_name.at(9)).c_str()); std::vector<std::string> nameMCP; nameMCP.push_back("MiB1"); nameMCP.push_back("MiB2"); nameMCP.push_back("ScB"); nameMCP.push_back("Planacon"); nameMCP.push_back("MiB3"); nameMCP.push_back("Roma2"); if(tokens_name.at(0) == "Scan3") nameMCP.at(1) = "Roma1"; std::vector<std::string> pcMCP; for(unsigned int ii=0; ii<nameMCP.size(); ++ii) pcMCP.push_back(""); pcMCP.at(Ch_ref1) = tokens_name.at(2); pcMCP.at(Ch_ref2) = tokens_name.at(4); pcMCP.at(Ch_1) = tokens_name.at(6); pcMCP.at(Ch_2) = tokens_name.at(8); pcMCP.at(Ch_3) = tokens_name.at(10); //---treshold setup Scan-dependent init(); const int iScanTh = atoi(argv[2])-1; float Ch_th[6]={0,0,0,0,0,0}; Ch_th[Ch_ref1] = _th[iScanTh][Ch_ref1]; Ch_th[Ch_ref2] = _th[iScanTh][Ch_ref2]; Ch_th[Ch_1] = _th[iScanTh][Ch_1]; Ch_th[Ch_2] = _th[iScanTh][Ch_2]; Ch_th[Ch_3] = _th[iScanTh][Ch_3]; TFile* out = TFile::Open((tokens_name.at(0)+"_outHistos.root").c_str(),"recreate"); out->cd(); //Output dat std::ofstream data1(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_1)+"_pc_"+pcMCP.at(Ch_1)+".dat").data()); std::ofstream data2(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_2)+"_pc_"+pcMCP.at(Ch_2)+".dat").data()); std::ofstream data3(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_3)+"_pc_"+pcMCP.at(Ch_3)+".dat").data()); int nFiles = 1, iRun = 0, goodEvt = 0; int iScan = 0; //---usefull histos TH1F* chHistoBase_All[9]; TH1F* chHistoSignal_All[9]; TH1F* timeDiffHisto[9]; TH1F* timeDiffHisto_Double = new TH1F("timeDiffHisto_Double", "timeDiffHisto_Double",5000,-10,10); //---histos initialization for(int iCh=0; iCh<6; ++iCh) { char h1[30], h2[30], h3[30]; sprintf(h1, "histoBase_All_Ch%d", iCh); sprintf(h2, "histoSignal_All_Ch%d", iCh); sprintf(h3, "histoTime_Ch%d", iCh); chHistoBase_All[iCh] = new TH1F(h1,h1,30000,-30000,1000); chHistoSignal_All[iCh] = new TH1F(h2, h2,30000,-30000,1000); timeDiffHisto[iCh] = new TH1F(h3, h3,1024,0,1024); } //---do runs loop ifstream log (argv[1], ios::in); while(log >> nFiles) { ++iScan; vector<float> digiCh[9]; float timeCF[9]; float baseline[9]; float intSignal[9], intBase[9]; int count[5]={0,0,0,0,0}, spare[5]={0,0,0,0,0}, spare2[5]={0,0,0,0,0}; int tot_tr1 = 0, tot_tr0 = 0, trig = 0; int HV1=0, HV2=0, HV3=0; TH1F* chHistoWF_Ch[9]; TH1F* chHistoBase_Ch[9]; TH1F* chHistoSignal_Ch[9]; TH1F* timeDiffHisto_Triple_Ch1 = new TH1F(Form("timeDiffHisto_Triple_Ch1_Scan%d",iScan), "", 5000,-100,100); TH1F* timeDiffHisto_Triple_Ch2 = new TH1F(Form("timeDiffHisto_Triple_Ch2_Scan%d",iScan), "", 5000,-100,100); TH1F* timeDiffHisto_Triple_Ch3 = new TH1F(Form("timeDiffHisto_Triple_Ch3_Scan%d",iScan), "", 5000,-100,100); char ha[10]; for (int iiw=0;iiw<9;++iiw){ sprintf (ha,"histoWF_Ch%d_Scan_%d",iiw, iScan); chHistoWF_Ch[iiw] = new TH1F( ha, "", 1024,0.,1024); chHistoWF_Ch[iiw]->SetXTitle("Waveform"); sprintf (ha,"histoBase_Ch%d_Scan_%d",iiw, iScan); chHistoBase_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000); chHistoBase_Ch[iiw] -> SetXTitle ("Integral BaseLine Ch(ADC)"); sprintf (ha,"histoSignal_Ch%d_Scan_%d",iiw, iScan); chHistoSignal_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000); chHistoSignal_Ch[iiw] -> SetXTitle ("Integral Signal Ch(ADC)"); } //---data chain TChain* chain = new TChain("eventRawData"); InitTree(chain); for(int iFiles=0; iFiles<nFiles; iFiles++){ log >> iRun; char iRun_str[30]; sprintf(iRun_str, "../Analysis_TB/DATA/run_IMCP_%d_*.root", iRun); chain->Add(iRun_str); cout << "Reading: ../Analysis_TB/DATA/run_IMCP_" << iRun << endl; } log >> HV1 >> HV2 >> HV3; for(int iEntry=0; iEntry<chain->GetEntries(); iEntry++) { //---always clear the std::vector !!! for(int iCh=0; iCh<9; iCh++) digiCh[iCh].clear(); //---Read the entry chain->GetEntry(iEntry); //---DAQ bug workaround if(iRun < 145) goodEvt = 10; else goodEvt = 1; if(evtNumber % goodEvt == 0){ //---Read SciFront ADC value and set the e- multiplicity //---(default = 1) trig = 1; for(int iCh=0; iCh<nAdcChannels; iCh++) { if(adcData[iCh] > 1500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=2; if(adcData[iCh] < 500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=0; } if(trig > 1) continue; //---Read digitizer samples for(int iSample=0; iSample<nDigiSamples; iSample++){ if(digiChannel[iSample] == 3){ digiCh[digiChannel[iSample]].push_back(-digiSampleValue[iSample]); chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, -digiSampleValue[iSample]); } else{ digiCh[digiChannel[iSample]].push_back(digiSampleValue[iSample]); chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, digiSampleValue[iSample]); } } for(int iCh=0; iCh<6; iCh++){ // baseline[iCh] = SubtractBaseline(5, 25, &digiCh[iCh]); baseline[iCh] = SubtractBaseline(26, 46, &digiCh[iCh]); intBase[iCh] = ComputeIntegral(26, 46, &digiCh[iCh]); if(trig == 0) { chHistoBase_All[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh])); chHistoBase_Ch[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh])); // chHistoBase_All[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh])); // chHistoBase_Ch[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh])); } timeCF[iCh]=TimeConstFrac(30, 500, &digiCh[iCh], 0.5); // timeDiffHisto[iCh]->Fill(timeCF[iCh]*0.2-timeCF[0]*0.2); timeDiffHisto[iCh]->Fill(timeCF[iCh]); int t1 = (int)(timeCF[iCh]/0.2) - 3; int t2 = (int)(timeCF[iCh]/0.2) + 17; //---Fill the signal integral histo only if the e- multiplicity is 1 if(t1 > 30 && t1 < 1024 && t2 > 30 && t2 < 1024 && trig == 1) { chHistoSignal_All[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh])); chHistoSignal_Ch[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh])); intSignal[iCh] = ComputeIntegral(t1, t2, &digiCh[iCh]); } else intSignal[iCh] = ComputeIntegral(50, 70, &digiCh[iCh]); }// loop over Ch //---Multiplicity == 1 --> compute efficency, fake rate and timing if(intSignal[Ch_ref1] < Ch_th[Ch_ref1] && intSignal[Ch_ref2] < Ch_th[Ch_ref2] && trig == 1){ ++tot_tr1; float tDiff = (timeCF[Ch_ref1] - timeCF[Ch_ref2]); float tMean = (timeCF[Ch_ref1] + timeCF[Ch_ref2])*0.5; timeDiffHisto_Double->Fill(tDiff); timeDiffHisto_Triple_Ch1->Fill(tMean - timeCF[Ch_1]); timeDiffHisto_Triple_Ch2->Fill(tMean - timeCF[Ch_2]); timeDiffHisto_Triple_Ch3->Fill(tMean - timeCF[Ch_3]); if(intSignal[Ch_1] < Ch_th[Ch_1]) ++count[1]; if(intSignal[Ch_2] < Ch_th[Ch_2]) ++count[2]; if(intSignal[Ch_3] < Ch_th[Ch_3]) ++count[3]; if(intBase[Ch_1] < Ch_th[Ch_1]) ++spare[1]; if(intBase[Ch_2] < Ch_th[Ch_2]) ++spare[2]; if(intBase[Ch_3] < Ch_th[Ch_3]) ++spare[3]; } }// good Event }// loop over entries std::cout << "HV1 = " << HV1 << " HV2 = " << HV2 << " HV3 = " << HV3 << std::endl; double eff1 = ((double)count[1]-(double)spare[1])/(double)tot_tr1; double eff2 = ((double)count[2]-(double)spare[2])/(double)tot_tr1; double eff3 = ((double)count[3]-(double)spare[3])/(double)tot_tr1; double eff1Err = TMath::Sqrt((eff1*(1-eff1))/tot_tr1); double eff2Err = TMath::Sqrt((eff2*(1-eff2))/tot_tr1); double eff3Err = TMath::Sqrt((eff3*(1-eff3))/tot_tr1); std::cout << "Ch_1 eff = " << eff1 << " +/- " << eff1Err << std::endl; std::cout << "Ch_2 eff = " << eff2 << " +/- " << eff2Err << std::endl; std::cout << "Ch_3 eff = " << eff3 << " +/- " << eff3Err << std::endl; /* data1 << HV1 << " " << eff1 << " " << 0 << " " << eff1Err << std::endl; data1 << HV2 << " " << eff2 << " " << 0 << " " << eff2Err << std::endl; data1 << HV3 << " " << eff3 << " " << 0 << " " << eff3Err << std::endl; */ for(int iw=0; iw<6; ++iw){ if(iw == 2) continue; chHistoBase_Ch[iw]->Write(); chHistoSignal_Ch[iw]->Write(); chHistoWF_Ch[iw]->Write(); } timeDiffHisto_Triple_Ch1->Write(); timeDiffHisto_Triple_Ch2->Write(); timeDiffHisto_Triple_Ch3->Write(); chain->Delete(); } for(int iw=0; iw<6; ++iw){ if(iw == 2) continue; chHistoBase_All[iw]->Write(); chHistoSignal_All[iw]->Write(); timeDiffHisto[iw]->Write(); } data1.close(); data2.close(); data3.close(); timeDiffHisto_Double->Write(); out->Close(); return 0; }
void Vehicle::AddPassenger(Unit *unit, int8 seatId, bool force) { SeatMap::iterator seat; seat = m_Seats.find(seatId); // this should never happen if(seat == m_Seats.end()) return; unit->SetVehicleGUID(GetGUID()); seat->second.passenger = unit; if(unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->isVehicle()) { if(((Vehicle*)unit)->GetEmptySeatsCount(true) == 0) seat->second.flags = SEAT_VEHICLE_FULL; else seat->second.flags = SEAT_VEHICLE_FREE; } else { seat->second.flags = SEAT_FULL; } if(unit->GetTypeId() == TYPEID_PLAYER) { WorldPacket data0(SMSG_FORCE_MOVE_ROOT, 10); data0.append(unit->GetPackGUID()); data0 << (uint32)((seat->second.vs_flags & SF_CAN_CAST) ? 2 : 0); unit->SendMessageToSet(&data0,true); } if(seat->second.vs_flags & SF_MAIN_RIDER) { if(!(GetVehicleFlags() & VF_MOVEMENT)) { GetMotionMaster()->Clear(false); GetMotionMaster()->MoveIdle(); SetCharmerGUID(unit->GetGUID()); unit->SetUInt64Value(UNIT_FIELD_CHARM, GetGUID()); if(unit->GetTypeId() == TYPEID_PLAYER) { ((Player*)unit)->SetMoverInQueve(this); ((Player*)unit)->SetClientControl(this, 1); } if(canFly() || HasAuraType(SPELL_AURA_FLY) || HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED)) { WorldPacket data3(SMSG_MOVE_SET_CAN_FLY, 12); data3.append(GetPackGUID()); data3 << (uint32)(0); SendMessageToSet(&data3,false); } //Make vehicle fly if(GetVehicleFlags() & VF_FLYING) CastSpell(this, 49303, false); } SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(GetEntry()); for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr) { if (unit->GetTypeId() == TYPEID_UNIT || itr->second.IsFitToRequirements((Player*)unit)) { Unit *caster = (itr->second.castFlags & 0x1) ? unit : this; Unit *target = (itr->second.castFlags & 0x2) ? unit : this; caster->CastSpell(target, itr->second.spellId, true); } } if(unit->GetTypeId() == TYPEID_PLAYER) { // it should be added only on rider enter? if(((Player*)unit)->GetGroup()) ((Player*)unit)->SetGroupUpdateFlag(GROUP_UPDATE_VEHICLE); ((Player*)unit)->SetFarSightGUID(GetGUID()); BuildVehicleActionBar((Player*)unit); } if(!(GetVehicleFlags() & VF_FACTION)) setFaction(unit->getFaction()); if(GetVehicleFlags() & VF_CANT_MOVE) { WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10); data2.append(GetPackGUID()); data2 << (uint32)(2); SendMessageToSet(&data2,false); } if(GetVehicleFlags() & VF_NON_SELECTABLE) SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } if(seat->second.vs_flags & SF_UNATTACKABLE) unit->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); EmptySeatsCountChanged(); }
int main(int argc, char **argv) { // // local variables used in test // Domain theDomain; FEM_ObjectBroker theBroker; int numColumns = 5; char *columns[numColumns]; char column1[] = "col1"; char column2[] = "col2"; char column3[] = "col3"; char column4[] = "col4"; char column5[] = "col5"; columns[0] = column1; columns[1] = column2; columns[2] = column3; columns[3] = column4; columns[4] = column5; int result, result1, result2, result3, result4; Vector data1(numColumns); Vector data2(numColumns-1); for (int i=0; i<numColumns; i++) data1(i) = i+1; for (int i=0; i<numColumns-1; i++) data2(i) = i+1; FileDatastore theDatabase("testDatabase", theDomain, theBroker); opserr << " *******************************************************************\n"; opserr << " DataOutputDatabaseHandler unit test\n"; opserr << " *******************************************************************\n\n"; opserr << " The DataOutputFile class provides implements 2 methods \n"; opserr << " open() - to open a connection to the o/p stream"; opserr << " write() - to send the contents of a vector to this stream\n\n"; opserr << " *******************************************************************\n"; // // first test we can create DataOutputFile object to test. // opserr << "TEST: Creation of DataOutputFile object - will create 4 objects 1,2,3 and 4 (3,4 have no assigned database)\n"; DataOutputDatabaseHandler *theHandler1 = new DataOutputDatabaseHandler(&theDatabase, "UnitTest1"); DataOutputDatabaseHandler *theHandler2 = new DataOutputDatabaseHandler(&theDatabase, "UnitTest2"); DataOutputDatabaseHandler *theHandler3 = new DataOutputDatabaseHandler(0, "UnitTest3"); DataOutputDatabaseHandler *theHandler4 = new DataOutputDatabaseHandler(0, 0); if (theHandler1 != 0 && theHandler2 != 0 && theHandler3 != 0 && theHandler4 != 0) opserr << "PASS: Creation of DataOutputDatabaseHandler object\n\n"; else { opserr << "FAIL: Creation of DataOutputDatabaseHandler object\n\n"; exit(-1); } // // test open() method // opserr << "Now We Test open()\n\t 1. invoke open() on 1 and 2\n"; opserr << "Invoking on handler 1\n"; result1 = theHandler1->open(columns, numColumns); opserr << "Invoking on handler 2\n"; result2 = theHandler2->open(columns, numColumns); if (result1 == 0 && result2 == 0) opserr << "PASS: open() method with VALID args\n\n"; else { opserr << "FAIL: open() method with VALID args\n\n"; } // // a number of tests to test open() method will fail if invalid args passed // expected result: should fail, print out an error message and return != 0 for all following tests. // opserr << "TEST: open() method with valid args but no database set\n"; result = theHandler4->open(columns, numColumns-1); if (result != 0) opserr << "PASS: open() method with valid args but no database set\n\n"; else { opserr << "FAIL: open() method with valid args but no database set\n\n"; } opserr << "TEST: open() method with bad column descriptions\n"; result = theHandler1->open(0, 2); if (result != 0) opserr << "PASS: open() method with bad column descriptors\n\n"; else { opserr << "FAIL: open() method with bad column descriptors\n\n"; } opserr << "TEST: open() method with negative number of columns\n"; result = theHandler1->open(columns, -1); if (result != 0) opserr << "PASS: open() method with negative columns\n\n"; else { opserr << "FAIL: open() method with negative columns\n\n"; } // // test setDatabase() // opserr << "Now We Test setDatabase & open after setDatabase on handler 2\n"; result = theHandler3->setDatabase(theDatabase, "UnitTest3"); result += theHandler3->open(columns, numColumns-1); if (result == 0) opserr << "PASS: setDatabase() then open()\n\n"; else { opserr << "FAIL: setDatabase() then open()\n\n"; } // // test we can insert data into the file // expected result: should return 0 and append line to <tableName>.out file // // // test: write() // opserr << "Now We Test write()\n\t 1. invoke write() 3 times with valid args on both handler1, handler2 and handler3\n"; opserr << "\t 2. invoke write() with invalid args a number of times\n\n"; // // test we can insert data into the file // expected result: should return 0 and append line to <tableName>.out file // result1 = 0; result2 = 0; result3 = 0; for (int i=0; i<3; i++) { result1 += theHandler1->write(data1); result1 += theHandler2->write(data1); result3 += theHandler3->write(data2); data1 += numColumns; data2 += numColumns-1; } // check the files exist and of correct size, UnitTest1.out should have 3 lines. if (result1 == 0 && result2 == 0 && result3 == 0) opserr << "PASS: write() method with VALID args\n\n"; else { opserr << "FAIL: write() method with VALID args\n\n"; } // // a number of tests to test the insert data will fail if data invalied // expected result: all should return negative values & possible warning messages // opserr << "TEST: call write() method with incorrect vector size\n"; result = theHandler3->write(data1); if (result != 0) opserr << "PASS: write() method with incorrect vector size\n\n"; else { opserr << "FAIL: write() method with incorrect vector size\n\n"; } opserr << "TEST: call write() method on handler which has not been set\n"; result = theHandler4->write(data1); if (result != 0) opserr << "PASS: write() method to handler where open has not been called\n\n"; else { opserr << "FAIL: write() method to handler where open has not been called\n\n"; } // // finally test we can destroy a DataOutputDatabaseHandler object. // opserr << "TEST: Destruction of DataOutputDatabaseHandler object\n"; delete theHandler1; delete theHandler2; delete theHandler3; delete theHandler4; // if get to here without a segmentation fault destructor passes opserr << "PASS: Destruction of DataOutputDatabaseHandler object\n\n"; exit(0); }
void Group::UpdateAllOutOfRangePlayersFor(Player* pPlayer) { WorldPacket data(150); WorldPacket data2(150); if(m_SubGroupCount > 8) return; /* tell the other players about us */ UpdateOutOfRangePlayer(pPlayer, GROUP_UPDATE_TYPE_FULL_CREATE, true, &data2); /* tell us any other players we don't know about */ Player* plr; bool u1, u2; UpdateMask myMask; myMask.SetCount(PLAYER_END); UpdateMask hisMask; hisMask.SetCount(PLAYER_END); m_groupLock.Acquire(); for(uint32 i = 0; i < m_SubGroupCount; ++i) { if(m_SubGroups[i] == NULL) continue; for(GroupMembersSet::iterator itr = m_SubGroups[i]->GetGroupMembersBegin(); itr != m_SubGroups[i]->GetGroupMembersEnd(); ++itr) { plr = (*itr)->m_loggedInPlayer; if(!plr || plr == pPlayer) continue; if(!plr->IsVisible(pPlayer->GetGUID())) { UpdateOutOfRangePlayer(plr, GROUP_UPDATE_TYPE_FULL_CREATE, false, &data); pPlayer->GetSession()->SendPacket(&data); } else { if(pPlayer->GetSubGroup() == plr->GetSubGroup()) { /* distribute quest fields to other players */ hisMask.Clear(); myMask.Clear(); u1 = u2 = false; for(uint32 j = PLAYER_QUEST_LOG_1_1; j <= PLAYER_QUEST_LOG_25_5; ++j) { if(plr->GetUInt32Value(j)) { hisMask.SetBit(j); u1 = true; } if(pPlayer->GetUInt32Value(j)) { u2 = true; myMask.SetBit(j); } } if(u1) { data.clear(); plr->BuildValuesUpdateBlockForPlayer(&data, &hisMask); pPlayer->PushUpdateData(&data, 1); } if(u2) { data.clear(); pPlayer->BuildValuesUpdateBlockForPlayer(&data, &myMask); plr->PushUpdateData(&data, 1); } } } } } m_groupLock.Release(); }
void WorldSession::HandleBattleFieldPortOpcode( WorldPacket &recv_data ) { sLog.outDebug( "WORLD: Recvd CMSG_BATTLEFIELD_PORT Message"); uint8 type; // arenatype if arena uint8 unk2; // unk, can be 0x0 (may be if was invited?) and 0x1 uint32 instanceId; uint32 bgTypeId_; // type id from dbc uint16 unk; // 0x1F90 constant? uint8 action; // enter battle 0x1, leave queue 0x0 recv_data >> type >> unk2 >> bgTypeId_ >> unk >> action; if (!sBattlemasterListStore.LookupEntry(bgTypeId_)) { sLog.outError("Battleground: invalid bgtype (%u) received.", bgTypeId_); // update battleground slots for the player to fix his UI and sent data. // this is a HACK, I don't know why the client starts sending invalid packets in the first place. // it usually happens with extremely high latency (if debugging / stepping in the code for example) if (_player->InBattleGroundQueue()) { // update all queues, send invitation info if player is invited, queue info if queued for (uint32 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) { BattleGroundQueueTypeId bgQueueTypeId = _player->GetBattleGroundQueueTypeId(i); if (!bgQueueTypeId) continue; BattleGroundTypeId bgTypeId = BattleGroundMgr::BGTemplateId(bgQueueTypeId); BattleGroundQueue::QueuedPlayersMap& qpMap = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId].m_QueuedPlayers; BattleGroundQueue::QueuedPlayersMap::iterator itrPlayerStatus = qpMap.find(_player->GetGUID()); // if the player is not in queue, continue or no group information - this should never happen if (itrPlayerStatus == qpMap.end() || !itrPlayerStatus->second.GroupInfo) continue; BattleGround * bg = NULL; // get possibly needed data from groupinfo uint8 arenatype = itrPlayerStatus->second.GroupInfo->ArenaType; uint8 status = 0; if (!itrPlayerStatus->second.GroupInfo->IsInvitedToBGInstanceGUID) { // not invited to bg, get template bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId); status = STATUS_WAIT_QUEUE; } else { // get the bg we're invited to bg = sBattleGroundMgr.GetBattleGround(itrPlayerStatus->second.GroupInfo->IsInvitedToBGInstanceGUID, bgTypeId); status = STATUS_WAIT_JOIN; } // if bg not found, then continue, don't invite if already in the instance if (!bg || (_player->InBattleGround() && _player->GetBattleGround() && _player->GetBattleGround()->GetInstanceID() == bg->GetInstanceID())) continue; // re - invite player with proper data WorldPacket data; sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, i, status, INVITE_ACCEPT_WAIT_TIME, 0, arenatype); SendPacket(&data); } } return; } //get GroupQueueInfo from BattleGroundQueue BattleGroundTypeId bgTypeId = BattleGroundTypeId(bgTypeId_); BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, type); BattleGroundQueue::QueuedPlayersMap& qpMap = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId].m_QueuedPlayers; BattleGroundQueue::QueuedPlayersMap::iterator itrPlayerStatus = qpMap.find(_player->GetGUID()); if (itrPlayerStatus == qpMap.end()) { sLog.outError("Battleground: itrplayerstatus not found."); return; } instanceId = itrPlayerStatus->second.GroupInfo->IsInvitedToBGInstanceGUID; // if action == 1, then instanceId is required if (!instanceId && action == 1) { sLog.outError("Battleground: instance not found."); return; } BattleGround *bg = sBattleGroundMgr.GetBattleGround(instanceId, bgTypeId); // bg template might and must be used in case of leaving queue, when instance is not created yet if (!bg && action == 0) bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId); if (!bg) { sLog.outError("Battleground: bg_template not found for type id %u.", bgTypeId); return; } if (_player->InBattleGroundQueue()) { //we must use temporary variables, because GroupQueueInfo pointer can be deleted in BattleGroundQueue::RemovePlayer() function! uint32 team = itrPlayerStatus->second.GroupInfo->Team; uint32 arenaType = itrPlayerStatus->second.GroupInfo->ArenaType; uint32 isRated = itrPlayerStatus->second.GroupInfo->IsRated; uint32 rating = itrPlayerStatus->second.GroupInfo->ArenaTeamRating; uint32 opponentsRating = itrPlayerStatus->second.GroupInfo->OpponentsTeamRating; //some checks if player isn't cheating - it is not exactly cheating, but we cannot allow it if (action == 1 && arenaType == 0) { //if player is trying to enter battleground (not arena!) and he has deserter debuff, we must just remove him from queue if (!_player->CanJoinToBattleground()) { //send bg command result to show nice message WorldPacket data2(SMSG_GROUP_JOINED_BATTLEGROUND, 4); data2 << uint32(0xFFFFFFFE); _player->GetSession()->SendPacket(&data2); action = 0; sLog.outDebug("Battleground: player %s (%u) has a deserter debuff, do not port him to battleground!", _player->GetName(), _player->GetGUIDLow()); } //if player don't match battleground max level, then do not allow him to enter! (this might happen when player leveled up during his waiting in queue if (_player->getLevel() > bg->GetMaxLevel()) { sLog.outError("Battleground: Player %s (%u) has level higher than maxlevel of battleground! Do not port him to battleground!", _player->GetName(), _player->GetGUIDLow()); action = 0; } } uint32 queueSlot = _player->GetBattleGroundQueueIndex(bgQueueTypeId); WorldPacket data; switch( action ) { case 1: // port to battleground if (!_player->IsInvitedForBattleGroundQueueType(bgQueueTypeId)) return; // cheating? _player->SetBattleGroundEntryPoint(); // resurrect the player if (!_player->isAlive()) { _player->ResurrectPlayer(1.0f); _player->SpawnCorpseBones(); } // stop taxi flight at port if (_player->isInFlight()) { _player->GetMotionMaster()->MovementExpired(); _player->m_taxi.ClearTaxiDestinations(); } sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_IN_PROGRESS, 0, bg->GetStartTime(), bg->GetArenaType()); _player->GetSession()->SendPacket(&data); // remove battleground queue status from BGmgr sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId].RemovePlayer(_player->GetGUID(), false); // this is still needed here if battleground "jumping" shouldn't add deserter debuff // also this is required to prevent stuck at old battleground after SetBattleGroundId set to new if (BattleGround *currentBg = _player->GetBattleGround()) currentBg->RemovePlayerAtLeave(_player->GetGUID(), false, true); // set the destination instance id _player->SetBattleGroundId(bg->GetInstanceID(), bgTypeId); // set the destination team _player->SetBGTeam(team); // bg->HandleBeforeTeleportToBattleGround(_player); sBattleGroundMgr.SendToBattleGround(_player, instanceId, bgTypeId); // add only in HandleMoveWorldPortAck() // bg->AddPlayer(_player,team); sLog.outDebug("Battleground: player %s (%u) joined battle for bg %u, bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetInstanceID(), bg->GetTypeID(), bgQueueTypeId); break; case 0: // leave queue // if player leaves rated arena match before match start, it is counted as he played but he lost if (isRated) { ArenaTeam * at = objmgr.GetArenaTeamById(team); if (at) { sLog.outDebug("UPDATING memberLost's personal arena rating for %u by opponents rating: %u, because he has left queue!", GUID_LOPART(_player->GetGUID()), opponentsRating); at->MemberLost(_player, opponentsRating); at->SaveToDB(); } } _player->RemoveBattleGroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to queue->removeplayer, it causes bugs sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, 0); sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId].RemovePlayer(_player->GetGUID(), true); // player left queue, we should update it - do not update Arena Queue if (!arenaType) sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId].Update(bgTypeId, _player->GetBattleGroundQueueIdFromLevel(), arenaType, isRated, rating); SendPacket(&data); sLog.outDebug("Battleground: player %s (%u) left queue for bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetTypeID(), bgQueueTypeId); break; default: sLog.outError("Battleground port: unknown action %u", action); break; } } }
void roo_fitWH() { TString poscharge = "Plus"; TString negcharge = "Minus"; std::vector<TString> charge(2); charge.at(0) = poscharge; charge.at(1) = negcharge; TString canvas_name_plus = "muon_MC_WHelicityFramePlots_PlusICVar"; TCanvas *c0 = new TCanvas(canvas_name_plus,"",450,400); TString canvas_name_minus = "muon_MC_WHelicityFramePlots_MinusICVar"; TCanvas *c1 = new TCanvas(canvas_name_minus,"",450,400); // Run both for + and - charges for(unsigned int j=0; j<charge.size(); j++) { // if (j==1) break; // do only + charge fit if (realData) { sfactor=36; } // Nominal values are taken from a fit to the MC W data (scaled to 100pb-1) RooRealVar *fLnom, *fRnom, *f0nom; if (j==0) { fLnom=new RooRealVar("fL_nom","fLnom",0.556); fRnom=new RooRealVar("fR_nom","fRnom",0.234); f0nom=new RooRealVar("f0_nom","f0nom",0.210); } else { fLnom=new RooRealVar("fL_nom","fLnom",0.523); fRnom=new RooRealVar("fR_nom","fRnom",0.265); f0nom=new RooRealVar("f0_nom","f0nom",0.212); } TString Hist1 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j) + "_LH"; TString Hist2 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j) + "_RH"; TString Hist3 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j) + "_LO"; TString Hist_data1 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j); TH1D *mc1 = (TH1D*)sigfile->Get(Hist1); TH1D *mc2 = (TH1D*)sigfile->Get(Hist2); TH1D *mc3 = (TH1D*)sigfile->Get(Hist3); TH1D *sighist = (TH1D*)sigfile->Get(Hist_data1); // W signal histogram TH1D *bkghist=(TH1D*)bkgfile->Get(Hist_data1); // Bkg histogram TH1D *hdata=(TH1D*)datafile->Get(Hist_data1); // Real data histogram // //we are only fitting for fL and fR // double accFactor1 = refTempHist1->Integral() / mc1->Integral(); // double accFactor2 = refTempHist2->Integral() / mc2->Integral(); // double accFactor3 = refTempHist3->Integral() / mc3->Integral(); // double normFactor = (mc1->Integral() + mc2->Integral() + mc3->Integral()) / (refTempHist1->Integral() + refTempHist2->Integral() + refTempHist3->Integral()); mc1->Rebin(rbin); mc2->Rebin(rbin); mc3->Rebin(rbin); sighist->Rebin(rbin); bkghist->Rebin(rbin); hdata->Rebin(rbin); // Scale to sfactor/pb if MC //if (!realData) { if (toyMC) sfactor=400; sighist->Scale(sfactor); bkghist->Scale(sfactor); // } //datahist->Scale(invWeightW);//to get MC errors - otherwise comment out Double_t nbkg=0; TH1D *datahist; if (realData) { datahist=hdata; } else { datahist=(TH1D*)sighist->Clone(); if (addbkg) {datahist->Add(bkghist); } } if (addbkg) { //nbkg=bkghist->Integral(); nbkg=bkghist->Integral(bkghist->FindBin(xmin+quanta),bkghist->FindBin(xmax-quanta)); } //Double_t istat=datahist->Integral(); //Double_t f_sig=(sighist->Integral())/istat; // signal fraction Double_t istat=datahist->Integral(datahist->FindBin(xmin+quanta),datahist->FindBin(xmax-quanta)); Double_t f_sig=(sighist->Integral(sighist->FindBin(xmin+quanta),sighist->FindBin(xmax-quanta)))/istat; Double_t f_bkg=nbkg/istat; // bkg fraction // Start RooFit session RooRealVar x("x","LP",xmin,xmax); // Import binned Data RooDataHist data1("data1","dataset with WHICVarPlus",x,mc1); RooDataHist data2("data2","dataset with WHICVarPlus",x,mc2); RooDataHist data3("data3","dataset with WHICVarPlus",x,mc3); RooDataHist test("data","dataset with WHICVarPlus",x,datahist); RooDataHist data_bkg("data4","dataset with ICVar",x,bkghist); // Relative fractions - allow them to float to negative values too if needs be // if (fitMode==0) { RooRealVar f1("fL","fL fraction",fLnom->getVal(),0.,1.); RooRealVar f2("fR","fR fraction", fRnom->getVal(),0.,1.); RooFormulaVar f3("f0","1-fL-fR",RooArgList(f1,f2)); if (fitMode) { f1.setVal((fLnom->getVal()-fRnom->getVal())); f1.setRange(-1.,1.); f1.setPlotLabel("f_{L}-f_{R}"); f2.setVal(f0nom->getVal()); f2.setPlotLabel("f_{0}"); } // } else { // RooRealVar f1("fL","fL fraction",(fLnom->getVal()-fRnom->getVal()),-1.,1.); // RooRealVar f2("fR","fR fraction", (fLnom->getVal()+fRnom->getVal()),-1.,1.); // RooFormulaVar f3("f0","1-fL-fR",RooArgList(f1,f2)); // } RooRealVar fsub("fsub","fsub par",(fLnom->getVal()-fRnom->getVal()),-1.,1.); RooRealVar fsum("fsum","fsum par",(fLnom->getVal()+fRnom->getVal()), -1.,1.); // Background template RooHistPdf *bkg = new RooHistPdf("bkg","bkg",x,data_bkg); // Bkg fraction RooRealVar fbkg("f_{bkg}","f_bkg fraction",f_bkg); // Templates RooHistPdf h1("h1","h1",x,data1); // left-handed template histogram RooHistPdf h2("h2","h2",x,data2); // right-handed template histo RooHistPdf h3("h3","h3",x,data3); // longitudinal template histo // Construct model PDF RooAbsPdf *sig, *model; if (charge.at(j) == "Plus") { // plus charge PDFs if (addParameter) { sig = new RooWPlusExtended("sigmodel","model",x,f1,f2,fsub); } else { sig = new RooWPlus("sigmodel","model",x,f1,f2); } } else if (charge.at(j) == "Minus") { // minus charge PDFs if (addParameter) { sig = new RooWMinusExtended("sigmodel","model",x,f1,f2,fsub); } else { sig = new RooWMinus("sigmodel","model",x,f1,f2); } } if (addbkg) { model = new RooAddPdf("model","model",RooArgList(*bkg,*sig),fbkg); } else { model = sig; } // Set the Fit Range x.setRange("fitrange",-0.0,1.3); // Construct likelihood ( + penalty term) RooNLLVar nll("nll","nll",*model,test,Range("fitrange")); RooRealVar pen("pen","penalty term",(0.5*1./(0.01*0.01))); RooFormulaVar nllPen("nllPen","nll+pen*fsub^2",RooArgList(nll,pen,fsub)); // Fitting RooMinuit *m; if (!addParameter) { m = new RooMinuit(nll); } else { m = new RooMinuit(nllPen);} if (!toyMC) { m->migrad(); m->hesse(); } RooFitResult *res1 = m->save(); // Re-diced data // Int_t nevt=static_cast<int>(istat); // RooDataSet *gtest = model->generate(x,nevt); // Fitting // RooFitResult * res1 = model.fitTo(test,Minos(kFALSE), Save()); // res1->Print(); if(makePlots) { // Temp PDF for plotting purposes // RooAddPdf temp("temp","component 1",RooArgList(*h1,*h2,*h3),RooArgList(*f1,*f2)) ; // Plotting gROOT->SetStyle("Plain"); gStyle->SetOptFit(0); gStyle->SetOptTitle(0); gStyle->SetOptStat(0); //gStyle->SetCanvasDefH(600); //Height of canvas //gStyle->SetCanvasDefW(600); //Width of canvas if(charge.at(j) == "Plus") { c0->cd(); //c0->Divide(2,1);c0->cd(1); } if(charge.at(j) == "Minus") { c1->cd(); //c1->Divide(2,1);c1->cd(1); } //RooPlot* frame = new RooPlot(0.0,1.3,0,800); RooPlot* frame = x.frame(); test.plotOn(frame,Name("data")); model->plotOn(frame,Name("model")); // model->paramOn(frame);//, Format("NELU", AutoPrecision(2)), Layout(0.1,0.5,0.9)); // h1.plotOn(frame); // h2.plotOn(frame); // h3.plotOn(frame); // model->plotOn(frame, Components(h1),LineColor(kRed),LineStyle(kDashed)); // temp->plotOn(frame, Components(h2),LineColor(kGreen),LineStyle(kDashed)); // temp->plotOn(frame, Components(h3),LineColor(kYellow),LineStyle(kDashed)); if (addbkg) { // model->plotOn(frame, Components(h1),FillColor(5),DrawOption("F")); //model->plotOn(frame,Components(*bkg),FillColor(5),DrawOption("")); } hdata->GetYaxis()->SetTitle("Events / 0.1"); if(charge.at(j) == "Plus") { hdata->GetXaxis()->SetTitle("#it{L_{P}}(#mu^{+})");} if(charge.at(j) == "Minus") {hdata->GetXaxis()->SetTitle("#it{L_{P}}(#mu^{-})");} hdata->GetXaxis()->SetTitleSize(0.06); hdata->GetXaxis()->SetTitleOffset(1.); hdata->GetYaxis()->SetTitleSize(0.06); hdata->GetYaxis()->SetTitleOffset(1.2); hdata->GetXaxis()->SetLabelSize(0.055); hdata->GetYaxis()->SetLabelSize(0.055); hdata->GetXaxis()->SetRangeUser(0.0,1.29); hdata->GetYaxis()->SetRangeUser(0.0,600); hdata->SetMarkerStyle(20); // mc1->Draw("same"); // Goodness-of-fit Double_t chi2= frame->chiSquare("model","data",3); Double_t nllmin=res1->minNll(); cout << "" << endl; cout << "Printing out the goodness-of-fit measure:" << endl; cout << "chi2 = " << chi2 << "\t" << "min NLL = " << nllmin << endl; res1->Print(); // TCanvas* testt = new TCanvas ("testt","hj"); cout <<"intetral: "<< hdata->Integral()<<endl; hdata->GetXaxis()->SetRangeUser(0.0,1.29); cout << hdata->Integral()<<endl; hdata->Draw(""); // frame->Draw("same"); mc1->GetXaxis()->SetRangeUser(0.0,1.29); float f_l_a = mc1->Integral(); mc2->GetXaxis()->SetRangeUser(0.0,1.29); float f_r_a = mc2->Integral(); mc3->GetXaxis()->SetRangeUser(0.0,1.29); float f_0_a = mc3->Integral(); float allData = hdata->Integral(); float EWKBkg = allData*(f_bkg); float WData = allData*(1-f_bkg); float f_l = 0.5*(1-f2.getVal()+f1.getVal()); float f_r = 0.5*(1-f2.getVal()-f1.getVal()); float f_0 = f2.getVal(); cout << "f_l: "<< f_l<< ",f_r: "<< f_r<< ", f_0: "<< f_0<< " 1= "<< f_l+f_r+f_0<< endl; float allW = f_l*f_l_a+f_r*f_r_a+f_0*f_0_a; //hdata->Draw(""); // bkghist->GetXaxis()->SetRangeUser(0.0,1.3); bkghist->Scale(EWKBkg/bkghist->Integral()); bkghist->Draw("samehist"); bkghist->SetLineColor(kYellow); bkghist->SetFillColor(kYellow); mc1->Scale(f_l*WData/allW); mc2->Scale(f_r*WData/allW); mc3->Scale(f_0*WData/allW); mc1->SetLineColor(kRed); mc2->SetLineColor(kGreen); mc3->SetLineColor(kBlue); mc1->SetLineWidth(3); mc2->SetLineWidth(3); mc3->SetLineWidth(3); mc1->SetLineStyle(2); mc2->SetLineStyle(3); mc3->SetLineStyle(4); mc1->Draw("samehist"); mc2->Draw("samehist"); mc3->Draw("samehist"); TH1D* allHists = (TH1D*)mc1->Clone(); allHists->Add(mc2,1); allHists->Add(mc3,1); allHists->Add(bkghist,1); allHists->SetLineWidth(3); // frame->SetOptFit(0); frame->Draw("same"); // allHists->Draw("same"); TLegend* aleg; //if(charge.at(j) == "Minus") aleg = new TLegend(0.2,0.69,0.6,0.9,""); // if(charge.at(j) == "Plus") //aleg = new TLegend(0.5,0.6,0.7,0.9,"");//new TLegend(0.8,0.69,0.95,0.9,""); aleg = new TLegend(0.2017937,0.7419355,0.4775785,0.9193548,NULL,"brNDC"); aleg->SetNColumns(2); aleg->SetFillColor(0); aleg->SetLineColor(0); aleg->AddEntry(mc1,"f_{L}","lf"); aleg->AddEntry(mc2,"f_{R}","lf"); aleg->AddEntry(mc3,"f_{0}","lf"); aleg->AddEntry(bkghist,"EWK","lf"); TH1* dummyhist = new TH1F("", "", 1, 0, 1); dummyhist->SetLineColor(kBlue); dummyhist->SetLineWidth(3); aleg->AddEntry(dummyhist, "fit result", "lf"); aleg->AddEntry(hdata, "data","P"); aleg->Draw("same"); //TLatex* preliminary; //TLatex* text; //if(false) { //text = new TLatex(0.35,480,"#splitline{f_{L}-f_{R}=0.240#pm0.036(stat.)#pm0.031(syst.)}{f_{0}=0.183#pm0.087(stat.)#pm0.123(syst.)}"); //preliminary = new TLatex(0.35,550,"CMS preliminary: #it{L} = 36pb^{-1}@ 7 TeV"); //} //if(true){ //text = new TLatex(0.05,480,"#splitline{f_{L}-f_{R}=0.310#pm0.036(stat.)#pm0.017(syst.)}{f_{0}=0.171#pm0.085(stat.)#pm0.099(syst.)}"); //preliminary = new TLatex(0.05,550,"#splitline{CMS, #sqrt{s} = 7 TeV,}{#it{L_{int}} = 36 pb^{-1}}");} //preliminary->SetTextSize(0.043); //preliminary->Draw("same"); //text->SetTextSize(0.043); // text->Draw("same"); /* // Draw Minuit contours if(charge.at(j) == "Plus") { c0->cd(2); } else { c1->cd(2); } // RooPlot *rcont=m->contour(f1,f2,1,2); // rcont->Draw(); RooPlot *rcontour=new RooPlot(f1,f2); res1->plotOn(rcontour,f1,f2,"ME123VHB"); rcontour->Draw(); if (fitMode) { rcontour->GetXaxis()->SetTitle("f_{L}-f_{R}"); rcontour->GetYaxis()->SetTitle("f_{0}"); } else { rcontour->GetXaxis()->SetTitle("f_{L}"); rcontour->GetYaxis()->SetTitle("f_{R}"); } */ } TLatex * text = new TLatex(0.7451931,500.8655,"#splitline{CMS, #sqrt{s} = 7 TeV}{L_{ int} = 36 pb^{-1}}"); text->SetTextSize(0.043); text->SetLineWidth(2); text->Draw("same"); const TMatrixDSym& cor = res1->correlationMatrix(); const TMatrixDSym& cov = res1->covarianceMatrix(); //Print correlation, covariance matrix cout << "correlation matrix" << endl; cor.Print(); cout << "covariance matrix" << endl; cov.Print(); cout << f1 << endl; cout << f2 << endl; if (!fitMode) { cout << "f0 = " << f3 << " +/- " << f3.getPropagatedError(*res1) << endl; } } if(makePlots) { c0->Print(canvas_name_plus+".pdf"); c1->Print(canvas_name_minus+".pdf"); } if (toyMC) { // MC STudies Int_t nevt=istat; Int_t nEXP=100; RooMCStudy mgr(*model,*model,x,"","mhrv"); mgr.generateAndFit(nEXP,nevt,kTRUE); TCanvas *cp0 = new TCanvas("c0","",1200,400); cp0->Divide(3,1); cp0->cd(1); RooPlot *p1=mgr.plotParam(f1); p1->Draw(); if (fitMode) p1->SetTitle(";f_{L}-f_{R};number of toys"); cp0->cd(2); RooPlot *p2 = mgr.plotError(f1); p2->Draw(); if (fitMode) p2->SetTitle(";#delta (f_{L}-f_{R});number of toys"); cp0->cd(3); // f1 pull RooPlot* m1pframe = mgr.plotPull(f1,-3.,3.,30,kTRUE); m1pframe->Draw(); if (fitMode) { m1pframe->SetTitle(";f_{L}-f_{R};number of toys"); } TCanvas *cp02 = new TCanvas("c1","",1200,400); cp02->Divide(3,1); cp02->cd(1); RooPlot *p3=mgr.plotParam(f2); p3->Draw(); if (fitMode) p3->SetTitle(";f_{0};number of toys"); cp02->cd(2); RooPlot *p4=mgr.plotError(f2); p4->Draw(); if (fitMode) p4->SetTitle(";#delta f_{0}; number of toys"); cp02->cd(3); // f2 pull RooPlot* m2pframe = mgr.plotPull(f2,-3.,3.,30,kTRUE); m2pframe->Draw(); if (fitMode) { m2pframe->SetTitle(";f_{0};number of toys"); } TCanvas *cnll = new TCanvas("cnll",""); RooPlot* nllframe = mgr.plotNLL(); // nllframe->Draw(); } return; }
bool VehicleKit::AddPassenger(Unit *passenger, int8 seatId) { SeatMap::iterator seat; if (seatId < 0) // no specific seat requirement { for (seat = m_Seats.begin(); seat != m_Seats.end(); ++seat) { if (!seat->second.passenger && (seat->second.seatInfo->IsUsable() || (seat->second.seatInfo->m_flags & SEAT_FLAG_UNCONTROLLED))) break; // some weird behaviour of some vehicles: Abomination (Putricide), Val'kyrs and Strangulate Vehicle (Lich King) if (GetBase()->GetEntry() == 37672 || GetBase()->GetEntry() == 38285 || GetBase()->GetEntry() == 36609 || GetBase()->GetEntry() == 36598 || GetBase()->GetEntry() == 37187) break; } if (seat == m_Seats.end()) // no available seat return false; } else { seat = m_Seats.find(seatId); if (seat == m_Seats.end()) return false; if (seat->second.passenger) return false; } VehicleSeatEntry const* seatInfo = seat->second.seatInfo; seat->second.passenger = passenger; if (!(seatInfo->m_flags & SEAT_FLAG_FREE_ACTION)) passenger->addUnitState(UNIT_STAT_ON_VEHICLE); m_pBase->SetPhaseMask(passenger->GetPhaseMask(), true); passenger->m_movementInfo.ClearTransportData(); passenger->m_movementInfo.AddMovementFlag(MOVEFLAG_ONTRANSPORT); if (GetBase()->m_movementInfo.HasMovementFlag(MOVEFLAG_ONTRANSPORT)) { passenger->m_movementInfo.SetTransportData(GetBase()->GetObjectGuid(), seatInfo->m_attachmentOffsetX + GetBase()->m_movementInfo.GetTransportPos()->x, seatInfo->m_attachmentOffsetY + GetBase()->m_movementInfo.GetTransportPos()->y, seatInfo->m_attachmentOffsetZ + GetBase()->m_movementInfo.GetTransportPos()->z, seatInfo->m_passengerYaw + GetBase()->m_movementInfo.GetTransportPos()->o, WorldTimer::getMSTime(), seat->first, seatInfo); DEBUG_LOG("VehicleKit::AddPassenger passenger %s transport offset on %s setted to %f %f %f %f (parent - %s)", passenger->GetObjectGuid().GetString().c_str(), passenger->m_movementInfo.GetTransportGuid().GetString().c_str(), passenger->m_movementInfo.GetTransportPos()->x, passenger->m_movementInfo.GetTransportPos()->y, passenger->m_movementInfo.GetTransportPos()->z, passenger->m_movementInfo.GetTransportPos()->o, GetBase()->m_movementInfo.GetTransportGuid().GetString().c_str()); } else if (passenger->GetTypeId() == TYPEID_UNIT && b_dstSet) { passenger->m_movementInfo.SetTransportData(m_pBase->GetObjectGuid(), seatInfo->m_attachmentOffsetX + m_dst_x, seatInfo->m_attachmentOffsetY + m_dst_y, seatInfo->m_attachmentOffsetZ + m_dst_z, seatInfo->m_passengerYaw + m_dst_o, WorldTimer::getMSTime(), seat->first, seatInfo); } else { passenger->m_movementInfo.SetTransportData(m_pBase->GetObjectGuid(), seatInfo->m_attachmentOffsetX, seatInfo->m_attachmentOffsetY, seatInfo->m_attachmentOffsetZ, seatInfo->m_passengerYaw, WorldTimer::getMSTime(), seat->first, seatInfo); } if (passenger->GetTypeId() == TYPEID_PLAYER) { ((Player*)passenger)->GetCamera().SetView(m_pBase); WorldPacket data(SMSG_FORCE_MOVE_ROOT, 8+4); data << passenger->GetPackGUID(); data << uint32((passenger->m_movementInfo.GetVehicleSeatFlags() & SEAT_FLAG_CAN_CAST) ? 2 : 0); passenger->SendMessageToSet(&data, true); } switch (m_pBase->GetEntry()) { case 28817: passenger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); break; } if (seat->second.seatInfo->m_flags & SEAT_FLAG_UNATTACKABLE || seat->second.seatInfo->m_flags & SEAT_FLAG_CAN_CONTROL) { switch (m_pBase->GetEntry()) { case 33651: // VX 001 case 33432: // Leviathan MX case 33118: // Ignis (Ulduar) case 32934: // Kologarn Right Arm (Ulduar) case 30234: // Nexus Lord's Hover Disk (Eye of Eternity, Malygos Encounter) case 30248: // Scion's of Eternity Hover Disk (Eye of Eternity, Malygos Encounter) break; default: passenger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); break; } if (seat->second.seatInfo->m_flags & SEAT_FLAG_CAN_CONTROL) passenger->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT); } if (seatInfo->m_flags & SEAT_FLAG_CAN_CONTROL) { if (!(m_pBase->GetVehicleInfo()->GetEntry()->m_flags & (VEHICLE_FLAG_ACCESSORY))) { m_pBase->StopMoving(); m_pBase->GetMotionMaster()->Clear(); m_pBase->CombatStop(true); } m_pBase->DeleteThreatList(); m_pBase->getHostileRefManager().deleteReferences(); m_pBase->SetCharmerGuid(passenger->GetObjectGuid()); m_pBase->addUnitState(UNIT_STAT_CONTROLLED); passenger->SetCharm(m_pBase); if (m_pBase->HasAuraType(SPELL_AURA_FLY) || m_pBase->HasAuraType(SPELL_AURA_MOD_FLIGHT_SPEED)) { WorldPacket data; data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12); data << m_pBase->GetPackGUID(); data << (uint32)(0); m_pBase->SendMessageToSet(&data,false); } if (passenger->GetTypeId() == TYPEID_PLAYER) { m_pBase->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); if (CharmInfo* charmInfo = m_pBase->InitCharmInfo(m_pBase)) { charmInfo->InitVehicleCreateSpells(seat->first); charmInfo->SetReactState(REACT_PASSIVE); } Player* player = (Player*)passenger; player->SetMover(m_pBase); player->SetClientControl(m_pBase, 1); player->VehicleSpellInitialize(); } if(!(((Creature*)m_pBase)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_KEEP_AI)) ((Creature*)m_pBase)->AIM_Initialize(); if (m_pBase->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) { WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 8+4); data2 << m_pBase->GetPackGUID(); data2 << (uint32)(2); m_pBase->SendMessageToSet(&data2,false); } else if (passenger->m_movementInfo.GetMovementFlags() & MOVEFLAG_WALK_MODE) ((Creature*)m_pBase)->SetWalk(true); else ((Creature*)m_pBase)->SetWalk(false); } passenger->SendMonsterMoveTransport(m_pBase, SPLINETYPE_FACINGANGLE, SPLINEFLAG_UNKNOWN5, 0, 0.0f); RelocatePassengers(m_pBase->GetPositionX(), m_pBase->GetPositionY(), m_pBase->GetPositionZ()+0.5f, m_pBase->GetOrientation()); UpdateFreeSeatCount(); if (m_pBase->GetTypeId() == TYPEID_UNIT) { if (((Creature*)m_pBase)->AI()) ((Creature*)m_pBase)->AI()->PassengerBoarded(passenger, seat->first, true); } if (seatInfo->m_flagsB & VEHICLE_SEAT_FLAG_B_EJECTABLE_FORCED) { uint32 delay = seatInfo->m_exitMaxDuration * IN_MILLISECONDS; m_pBase->AddEvent(new PassengerEjectEvent(passenger), delay); DEBUG_LOG("Vehicle::AddPassenger eject event for %s added, delay %u",passenger->GetObjectGuid().GetString().c_str(), delay); } return true; }
void operator()() { for(difference_type i = data.lower(); i <= up; ++i) data(i) = data2(i); }
void CUT_PBASE_T_USBDI_0498::TransferCompleteL(TInt aTransferId,TInt aCompletionCode) { OstTraceFunctionEntryExt( CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_ENTRY, this ); Cancel(); TInt err(KErrNone); TBuf<256> msg; OstTraceExt3(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL, "Transfer completed (id=%d), aCompletionCode = %d, test step = %d",aTransferId, aCompletionCode, iCaseStep); switch(iCaseStep) { case ETransfer: if(aCompletionCode != KErrNone) { iIfc1OutTransfer[0]->Cancel(); iIfc1OutTransfer[1]->Cancel(); iIfc2OutTransfer[0]->Cancel(); iIfc2OutTransfer[1]->Cancel(); iIfc1InTransfer[0]->Cancel(); iIfc1InTransfer[1]->Cancel(); iIfc2InTransfer[0]->Cancel(); iIfc2InTransfer[1]->Cancel(); err = KErrCorrupt; msg.Format(_L("<Error %d> The transfer completed with an error."), aCompletionCode); break; //switch(iCaseStep) } switch(aTransferId) { case KIfc1BulkTransferOutId1: case KIfc1BulkTransferOutId2: case KIfc2BulkTransferOutId1: case KIfc2BulkTransferOutId2: iTransferComplete |= aTransferId; OstTraceExt2(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP01, "Transfer OUT %d completed (Transfer Completion Aggregation Mask 0x%x)", aTransferId, iTransferComplete); break; //switch(aTransferId) case KIfc1BulkTransferInId1: case KIfc1BulkTransferInId2: case KIfc2BulkTransferInId1: case KIfc2BulkTransferInId2: iTransferComplete |= aTransferId; OstTraceExt2(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP02, "Transfer OUT %d completed (Transfer Completion Aggregation Mask 0x%x)", aTransferId, iTransferComplete); break; //switch(aTransferId) default: iTransferComplete = 0; //reset err = KUnexpectedTransferID; msg.Format(_L("<Error %d> Unexpected transfer ID, GOT %d, (wanted one of:- %d, %d, %d, %d, %d, %d, %d, or%d)"), err, aTransferId, KIfc1BulkTransferInId1, KIfc1BulkTransferInId2, KIfc2BulkTransferInId1, KIfc2BulkTransferInId2, KIfc1BulkTransferOutId1, KIfc1BulkTransferOutId2, KIfc2BulkTransferOutId1, KIfc2BulkTransferOutId2 ); break; //switch(aTransferId) } // Transfer Out Response if(err==KErrNone && iTimeElapsed[0] == 0 && (iTransferComplete & KIfc1BulkTransferOutIdMask) == KIfc1BulkTransferOutIdMask) //Record time elapsed for Interface 1 if not yet recorded. { RecordTime(0); } if(err==KErrNone && iTimeElapsed[1] == 0 && (iTransferComplete & KIfc2BulkTransferOutIdMask) == KIfc2BulkTransferOutIdMask) //Record time elapsed for Interface 2 if not yet recorded. { RecordTime(1); } if(err==KErrNone && (iTransferComplete & KBulkTransferOutIdMask) == KBulkTransferOutIdMask) { OstTrace1(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP03, "All OUT Transfers Completed Successfully: Transfer Completion Aggregation Mask 0x%x", iTransferComplete); //Leave validation to the point at which all transfers have completed. } // Transfer In Response if(err==KErrNone && iTimeElapsed[2] == 0 && (iTransferComplete & KIfc1BulkTransferInIdMask) == KIfc1BulkTransferInIdMask) //Record time elapsed for Interface 1 if not yet recorded. { RecordTime(2); } if(err==KErrNone && iTimeElapsed[3] == 0 && (iTransferComplete & KIfc2BulkTransferInIdMask) == KIfc2BulkTransferInIdMask) //Record time elapsed for Interface 2 if not yet recorded. { RecordTime(3); } if(err==KErrNone && (iTransferComplete & KBulkTransferInIdMask) == KBulkTransferInIdMask) { // ok, compare data rcvd now OstTrace1(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP04, "All IN Transfers Completed Successfully: Transfer Completion Aggregation Mask 0x%x", iTransferComplete); TPtrC8 data1(iIfc1InTransfer[0]->DataPolled()); TPtrC8 data2(iIfc1InTransfer[1]->DataPolled()); TPtrC8 data3(iIfc2InTransfer[0]->DataPolled()); TPtrC8 data4(iIfc2InTransfer[1]->DataPolled()); //Validate first transfer on Interface 1 for number of bytes originally written. if(ValidateData(data1, KLiteralFrench4(), KHostNumWriteBytes1) == EFalse) { OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP05, "Validation failure 1st transfer, Interface 1"); err = KErrCompletion; //indicates data validation failure break; //switch(iCaseStep) } //Validate second transfer on Interface 1 for number of bytes originally written. if(ValidateData(data2, KLiteralFrench4(), KHostNumWriteBytes1, KHostNumWriteBytes2) == EFalse) { OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP06, "Validation failure 2nd transfer, Interface 1"); err = KErrCompletion; //indicates data validation failure break; //switch(iCaseStep) } //Validate first transfer on Interface 2 for number of bytes originally written. if(ValidateData(data3, KLiteralEnglish2(), KHostNumWriteBytes1) == EFalse) { OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP07, "Validation failure 1st transfer, Interface 2"); err = KErrCompletion; //indicates data validation failure break; //switch(iCaseStep) } //Validate second transfer on Interface 2 for number of bytes originally written. if(ValidateData(data4, KLiteralEnglish2(), KHostNumWriteBytes1, KHostNumWriteBytes2) == EFalse) { OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP08, "Validation failure 2nd transfer, Interface 2"); err = KErrCompletion; //indicates data validation failure break; //switch(iCaseStep) } // Comparison is a match OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP09, "Comparison for IN transfer is a match"); } break; //switch(iCaseStep) default: err = KUndefinedStep; msg.Format(_L("<Error %d> Undefined case step %d reached"),KUndefinedStep, iCaseStep); break; //switch(iCaseStep) } if(err == KErrNone && iTransferComplete == KBulkTransferIdMask) /* Transfers all complete - now ask device to validate first interface's transfer OUT */ { OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP10, "Checking all times against each other"); err = CheckTimes(0, 1, KMaxTimeDiffPercentage); err = err?err:CheckTimes(0, 2, KMaxTimeDiffPercentage); err = err?err:CheckTimes(0, 3, KMaxTimeDiffPercentage); err = err?err:CheckTimes(1, 2, KMaxTimeDiffPercentage); err = err?err:CheckTimes(1, 3, KMaxTimeDiffPercentage); err = err?err:CheckTimes(2, 3, KMaxTimeDiffPercentage); ResetTimes(0); ResetTimes(1); ResetTimes(2); ResetTimes(3); if(err==KErrNone) { OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP11, "Asking client for 'Validate' data written on interface 1"); iCaseStep = ERequestDeviceValidateIFC1; TEndpointStringValidationRequest request(1,1,KLiteralFrench4(),KDeviceNumReadBytes); iControlEp0->SendRequest(request,this); } } if(err == KErrCompletion) //indicates data validation failure { msg.Format(_L("<Error %d> Bulk transfer IN data received does not match Bulk Transfer OUT data"), err); } if(err == KErrTooBig) //indicates timing validation failure { msg.Format(_L("<Error %d> Timer comparison showed too great a difference in transfer times between the two interfaces"), err); } if(err!=KErrNone) { OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP12, msg); iCaseStep = EFailed; TTestCaseFailed request(err,msg); return iControlEp0->SendRequest(request,this); } OstTraceFunctionExit1( CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_EXIT, this ); }
bool VehicleKit::AddPassenger(Unit *passenger, int8 seatId) { SeatMap::iterator seat; if (seatId < 0) // no specific seat requirement { for (seat = m_Seats.begin(); seat != m_Seats.end(); ++seat) if (!seat->second.passenger && (seat->second.seatInfo->IsUsable() || (seat->second.seatInfo->m_flags & SEAT_FLAG_UNCONTROLLED))) break; if (seat == m_Seats.end()) // no available seat return false; } else { seat = m_Seats.find(seatId); if (seat == m_Seats.end()) return false; if (seat->second.passenger) return false; } seat->second.passenger = passenger; passenger->addUnitState(UNIT_STAT_ON_VEHICLE); m_pBase->SetPhaseMask(passenger->GetPhaseMask(), true); VehicleSeatEntry const *seatInfo = seat->second.seatInfo; passenger->m_movementInfo.AddMovementFlag(MOVEFLAG_ONTRANSPORT); passenger->m_movementInfo.SetTransportData(m_pBase->GetObjectGuid(), seatInfo->m_attachmentOffsetX, seatInfo->m_attachmentOffsetY, seatInfo->m_attachmentOffsetZ, seatInfo->m_passengerYaw, WorldTimer::getMSTime(), seat->first, seatInfo); if (passenger->GetTypeId() == TYPEID_PLAYER) { ((Player*)passenger)->UnsummonPetTemporaryIfAny(); ((Player*)passenger)->GetCamera().SetView(m_pBase); WorldPacket data(SMSG_FORCE_MOVE_ROOT, 8+4); PacketWorker::BuildSetMovementPacket(SMSG_FORCE_MOVE_ROOT, &data, passenger->GetObjectGuid(), (passenger->m_movementInfo.GetVehicleSeatFlags() & SEAT_FLAG_CAN_CAST) ? 2 : 0); passenger->SendMessageToSet(&data, true); } if (seat->second.seatInfo->m_flags & SEAT_FLAG_UNATTACKABLE || seat->second.seatInfo->m_flags & SEAT_FLAG_CAN_CONTROL) { passenger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); passenger->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT); } if (seatInfo->m_flags & SEAT_FLAG_CAN_CONTROL) { // m_pBase->StopMoving(); m_pBase->GetMotionMaster()->Clear(); m_pBase->CombatStop(true); m_pBase->DeleteThreatList(); m_pBase->getHostileRefManager().deleteReferences(); m_pBase->SetCharmerGuid(passenger->GetObjectGuid()); m_pBase->addUnitState(UNIT_STAT_CONTROLLED); passenger->SetCharm(m_pBase); if(m_pBase->HasAuraType(SPELL_AURA_FLY) || m_pBase->HasAuraType(SPELL_AURA_MOD_FLIGHT_SPEED)) { WorldPacket data; data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12); data << m_pBase->GetPackGUID(); data << (uint32)(0); m_pBase->SendMessageToSet(&data,false); } if (passenger->GetTypeId() == TYPEID_PLAYER) { m_pBase->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); m_pBase->setFaction(passenger->getFaction()); if (CharmInfo* charmInfo = m_pBase->InitCharmInfo(m_pBase)) { charmInfo->InitVehicleCreateSpells(); charmInfo->SetReactState(REACT_PASSIVE); } Player* player = (Player*)passenger; player->SetMover(m_pBase); player->SetClientControl(m_pBase, 1); player->VehicleSpellInitialize(); } if(!(((Creature*)m_pBase)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_KEEP_AI)) ((Creature*)m_pBase)->AIM_Initialize(); if(m_pBase->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) { WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 8+4); PacketWorker::BuildSetMovementPacket(SMSG_FORCE_MOVE_ROOT, &data2, m_pBase->GetObjectGuid(), 2); m_pBase->SendMessageToSet(&data2,false); } } passenger->MonsterMoveTransport(m_pBase, 4/*SPLINETYPE_FACINGANGLE*/, 0x00800000/*SPLINEFLAG_UNKNOWN5*/, 0, 0.0f); RelocatePassengers(m_pBase->GetPositionX(), m_pBase->GetPositionY(), m_pBase->GetPositionZ()+0.5f, m_pBase->GetOrientation()); UpdateFreeSeatCount(); if (m_pBase->GetTypeId() == TYPEID_UNIT) { if (((Creature*)m_pBase)->AI()) ((Creature*)m_pBase)->AI()->PassengerBoarded(passenger, seat->first, true); } return true; }
void TestLpdu::testBuildLpdu() { /* application layer data for r1 */ uint8_t a1[] = { 0xcd, 0xcc, 0x01, 0x3c, 0x02, 0x06, 0x3c, 0x03, 0x06, 0x3c, 0x04, 0x06 }; /* application layer data for r2 */ uint8_t a2[] = { 0xc1, 0xe3, 0x81, 0x96, 0x00, 0x02, 0x01, 0x28, 0x01, 0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0x28, 0x01, 0x00, 0x01, 0x00, 0x01, 0x02, 0x01, 0x28, 0x01, 0x00, 0x02, 0x00, 0x01, 0x02, 0x01, 0x28, 0x01, 0x00, 0x03, 0x00, 0x01, 0x20, 0x02, 0x28, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x02, 0x28, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x03, 0x00, 0x00, 0x1e, 0x02, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00 }; /* these are known good DNP LPDUs */ uint8_t r0[] = { 0x05, 0x64, 0x05, 0xc0, 0x02, 0x00, 0x01, 0x00, 0x9e, 0x59 }; /* header only */ uint8_t r1[] = { 0x05, 0x64, 0x11, 0xc4, 0x15, 0x00, 0x17, 0x00, 0x63, 0x62, 0xcd, 0xcc, 0x01, 0x3c, 0x02, 0x06, 0x3c, 0x03, 0x06, 0x3c, 0x04, 0x06, 0x08, 0x9e }; uint8_t r2[] = { 0x05, 0x64, 0x53, 0x73, 0x00, 0x04, 0x01, 0x00, 0x03, 0xfc, 0xc1, 0xe3, 0x81, 0x96, 0x00, 0x02, 0x01, 0x28, 0x01, 0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0x28, 0x05, 0x24, 0x01, 0x00, 0x01, 0x00, 0x01, 0x02, 0x01, 0x28, 0x01, 0x00, 0x02, 0x00, 0x01, 0x02, 0x01, 0x28, 0xb4, 0x77, 0x01, 0x00, 0x03, 0x00, 0x01, 0x20, 0x02, 0x28, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0xa5, 0x25, 0x02, 0x28, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x03, 0x00, 0x2f, 0xac, 0x00, 0x1e, 0x02, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x16, 0xed }; uint8_t twoLpdus[] = { 0x05, 0x64, 0x08, 0xc4, 0x02, 0x00, 0x2d, 0x00, 0xa4, 0x1c, 0xc0, 0xcd, 0x00, 0x23, 0x65, 0x05, 0x64, 0x0b, 0xc4, 0x02, 0x00, 0x2d, 0x00, 0xf4, 0x8f, 0xc0, 0xce, 0x01, 0x3c, 0x02, 0x06, 0x09, 0x7f }; /* header only - no application data */ uint8_t r3[] = { 0x05, 0x64, 0x05, 0xc0, 0x01, 0x00, 0x00, 0x04, 0xe9, 0x21 }; /* header only - no application data */ uint8_t r4[] = { 0x05, 0x64, 0x05, 0x00, 0x00, 0x04, 0x01, 0x00, 0x19, 0xa6 }; uint8_t r5[] = { 0x05, 0x64, 0x0a, 0x44, 0x01, 0x00, 0x02, 0x00, 0xfa, 0x4a, 0xc1, 0xe1, 0x81, 0x10, 0x00, 0x6d, 0xd5 }; /* known bad lpdu data */ uint8_t r10[] ={ 108, 68, 3, 0, 17, 8, 127, 38, 193, 201 }; uint8_t r11[] ={ 129, 144, 0, 20, 6, 0, 0, 8, 16, 0 }; uint8_t r12[] ={ 0, 0, 16, 0, 48, 78, 16, 0, 7, 0 }; uint8_t r13[] ={ 0, 0, 7, 0, 7, 0, 17, 0, 30, 4 }; uint8_t r14[] ={ 0, 0, 156, 186, 34, 120, 0, 120, 0, 120 }; uint8_t r15[] ={ 0, 120, 0, 48, 81, 66, 81, 69, 81, 61 }; uint8_t r16[] ={ 76, 53, 81, 4, 0, 5, 0, 4, 0, 4 }; uint8_t r20[] ={ 81, 48, 81, 48, 223, 36, 81, 4, 0, 5 }; enum StatIndex { RX_START_OCTETS = 0, RX_LPDUS, LOST_BYTES, CRC_ERRORS, NUM_STATS }; Stats::Element statElements[] = { { RX_START_OCTETS, "Rx Start Octets", Stats::NORMAL,0,0}, { RX_LPDUS, "Rx Lpdus", Stats::NORMAL,0,0}, { LOST_BYTES, "Lost Bytes", Stats::ABNORMAL,0,0}, { CRC_ERRORS, "CRC Errors", Stats::ABNORMAL,0,0}, }; Stats stats; char name[Stats::MAX_USER_NAME_LEN]; int debugLevel = -1; DummyDb db; assert(sizeof(statElements)/sizeof(Stats::Element) == NUM_STATS); snprintf(name, Stats::MAX_USER_NAME_LEN, "DL TEST"); stats = Stats( name, 1, &debugLevel, statElements, NUM_STATS, &db); Lpdu lpdu = Lpdu( &stats); unsigned int i; bool lpduFound; lpdu.build( 1, 1, 0, 0, 0, 2, 1); lpduToArrayCmp( lpdu, r0); lpdu.build( 1, 1, 0, 0, 4, 21, 23, TO_BYTES(a1)); lpduToArrayCmp( lpdu, r1); lpdu.build( 0, 1, 1, 1, 3, 1024, 1, TO_BYTES(a2)); lpduToArrayCmp( lpdu, r2); lpdu.reset(); /* test building from incoming bytes */ Bytes data1( r5, r5 + 10); lpduFound = lpdu.buildFromBytes( data1); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 10); Bytes data2( &r5[10], &r5[10] + sizeof(r5) - 10); lpduFound = lpdu.buildFromBytes( data2); QVERIFY( lpduFound == true); QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS) == 1); QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES) == 0); QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS) == 0); Bytes data3(TO_BYTES(r3)); lpduFound = lpdu.buildFromBytes( data3); QVERIFY( lpduFound == true); Bytes data4(TO_BYTES(r4)); lpduFound = lpdu.buildFromBytes( data4); QVERIFY( lpduFound == true); /* create 4x a good lpdu */ Bytes data5(TO_BYTES(r1)); Bytes data6(data5); data6.insert(data6.end(), data5.begin(), data5.end()); data6.insert(data6.end(), data5.begin(), data5.end()); data6.insert(data6.end(), data5.begin(), data5.end()); /* ensure we receive 4 good ones */ for (i=0; i<4; i++) { lpdu.reset(); lpduFound = lpdu.buildFromBytes( data6); QVERIFY( lpduFound == true); QVERIFY (data6.size() == (sizeof(r1)*(3-i))); QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS) == (2+i)); QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES) == 0); QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS) == 0); } /* header only lpdu */ lpdu.reset(); Bytes data7(TO_BYTES(r0)); lpduFound = lpdu.buildFromBytes( data7); QVERIFY( lpduFound == true); QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS) == 6); QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES) == 0); QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS) == 0); /* building of two lpdus coming in across two simulated reads */ /* with the break on the last byte of the last CRC */ lpdu.reset(); Bytes data8(TO_BYTES(twoLpdus)); Bytes data9; data9.push_back(data8.back()); data8.pop_back(); lpduFound = lpdu.buildFromBytes( data8); QVERIFY( lpduFound == true); QVERIFY (lpdu.ab.size() == 15); /* manually counted */ QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS) == 7); QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES) == 0); QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS) == 0); QVERIFY( data8.size() == 17); lpdu.reset(); lpduFound = lpdu.buildFromBytes( data8); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 17); QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS) == 8); QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES) == 0); QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS) == 0); lpduFound = lpdu.buildFromBytes( data9); QVERIFY( lpduFound == true); QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS) == 8); QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES) == 0); QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS) == 0); lpdu.reset(); /* test known bad cases */ Bytes data10(TO_BYTES(r10)); lpduFound = lpdu.buildFromBytes( data10); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); lpdu.reset(); Bytes data11(TO_BYTES(r11)); lpduFound = lpdu.buildFromBytes( data11); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); lpdu.reset(); Bytes data12(TO_BYTES(r12)); lpduFound = lpdu.buildFromBytes( data12); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); lpdu.reset(); Bytes data13(TO_BYTES(r13)); lpduFound = lpdu.buildFromBytes( data13); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); lpdu.reset(); Bytes data14(TO_BYTES(r14)); lpduFound = lpdu.buildFromBytes( data14); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); lpdu.reset(); Bytes data15(TO_BYTES(r15)); lpduFound = lpdu.buildFromBytes( data15); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); lpdu.reset(); Bytes data16(TO_BYTES(r16)); lpduFound = lpdu.buildFromBytes( data16); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); lpdu.reset(); Bytes data20(TO_BYTES(r20)); lpduFound = lpdu.buildFromBytes( data20); QVERIFY( lpduFound == false); QVERIFY (lpdu.ab.size() == 0); }
TEST(ResourceRequestTest, CrossThreadResourceRequestData) { ResourceRequest original; original.setURL(KURL(ParsedURLString, "http://www.example.com/test.htm")); original.setCachePolicy(UseProtocolCachePolicy); original.setTimeoutInterval(10); original.setFirstPartyForCookies(KURL(ParsedURLString, "http://www.example.com/first_party.htm")); original.setHTTPMethod(AtomicString("GET", AtomicString::ConstructFromLiteral)); original.setHTTPHeaderField(AtomicString("Foo"), AtomicString("Bar")); original.setHTTPHeaderField(AtomicString("Piyo"), AtomicString("Fuga")); original.setPriority(ResourceLoadPriorityLow, 20); RefPtr<FormData> originalBody(FormData::create("Test Body")); original.setHTTPBody(originalBody); original.setAllowStoredCredentials(false); original.setReportUploadProgress(false); original.setHasUserGesture(false); original.setDownloadToFile(false); original.setSkipServiceWorker(false); original.setFetchRequestMode(WebURLRequest::FetchRequestModeCORS); original.setFetchCredentialsMode(WebURLRequest::FetchCredentialsModeSameOrigin); original.setRequestorID(30); original.setRequestorProcessID(40); original.setAppCacheHostID(50); original.setRequestContext(WebURLRequest::RequestContextAudio); original.setFrameType(WebURLRequest::FrameTypeNested); original.setHTTPReferrer(Referrer("http://www.example.com/referrer.htm", ReferrerPolicyDefault)); EXPECT_STREQ("http://www.example.com/test.htm", original.url().string().utf8().data()); EXPECT_EQ(UseProtocolCachePolicy, original.cachePolicy()); EXPECT_EQ(10, original.timeoutInterval()); EXPECT_STREQ("http://www.example.com/first_party.htm", original.firstPartyForCookies().string().utf8().data()); EXPECT_STREQ("GET", original.httpMethod().utf8().data()); EXPECT_STREQ("Bar", original.httpHeaderFields().get("Foo").utf8().data()); EXPECT_STREQ("Fuga", original.httpHeaderFields().get("Piyo").utf8().data()); EXPECT_EQ(ResourceLoadPriorityLow, original.priority()); EXPECT_STREQ("Test Body", original.httpBody()->flattenToString().utf8().data()); EXPECT_FALSE(original.allowStoredCredentials()); EXPECT_FALSE(original.reportUploadProgress()); EXPECT_FALSE(original.hasUserGesture()); EXPECT_FALSE(original.downloadToFile()); EXPECT_FALSE(original.skipServiceWorker()); EXPECT_EQ(WebURLRequest::FetchRequestModeCORS, original.fetchRequestMode()); EXPECT_EQ(WebURLRequest::FetchCredentialsModeSameOrigin, original.fetchCredentialsMode()); EXPECT_EQ(30, original.requestorID()); EXPECT_EQ(40, original.requestorProcessID()); EXPECT_EQ(50, original.appCacheHostID()); EXPECT_EQ(WebURLRequest::RequestContextAudio, original.requestContext()); EXPECT_EQ(WebURLRequest::FrameTypeNested, original.frameType()); EXPECT_STREQ("http://www.example.com/referrer.htm", original.httpReferrer().utf8().data()); EXPECT_EQ(ReferrerPolicyDefault, original.referrerPolicy()); OwnPtr<CrossThreadResourceRequestData> data1(original.copyData()); OwnPtr<ResourceRequest> copy1(ResourceRequest::adopt(data1.release())); EXPECT_STREQ("http://www.example.com/test.htm", copy1->url().string().utf8().data()); EXPECT_EQ(UseProtocolCachePolicy, copy1->cachePolicy()); EXPECT_EQ(10, copy1->timeoutInterval()); EXPECT_STREQ("http://www.example.com/first_party.htm", copy1->firstPartyForCookies().string().utf8().data()); EXPECT_STREQ("GET", copy1->httpMethod().utf8().data()); EXPECT_STREQ("Bar", copy1->httpHeaderFields().get("Foo").utf8().data()); EXPECT_EQ(ResourceLoadPriorityLow, copy1->priority()); EXPECT_STREQ("Test Body", copy1->httpBody()->flattenToString().utf8().data()); EXPECT_FALSE(copy1->allowStoredCredentials()); EXPECT_FALSE(copy1->reportUploadProgress()); EXPECT_FALSE(copy1->hasUserGesture()); EXPECT_FALSE(copy1->downloadToFile()); EXPECT_FALSE(copy1->skipServiceWorker()); EXPECT_EQ(WebURLRequest::FetchRequestModeCORS, copy1->fetchRequestMode()); EXPECT_EQ(WebURLRequest::FetchCredentialsModeSameOrigin, copy1->fetchCredentialsMode()); EXPECT_EQ(30, copy1->requestorID()); EXPECT_EQ(40, copy1->requestorProcessID()); EXPECT_EQ(50, copy1->appCacheHostID()); EXPECT_EQ(WebURLRequest::RequestContextAudio, copy1->requestContext()); EXPECT_EQ(WebURLRequest::FrameTypeNested, copy1->frameType()); EXPECT_STREQ("http://www.example.com/referrer.htm", copy1->httpReferrer().utf8().data()); EXPECT_EQ(ReferrerPolicyDefault, copy1->referrerPolicy()); copy1->setAllowStoredCredentials(true); copy1->setReportUploadProgress(true); copy1->setHasUserGesture(true); copy1->setDownloadToFile(true); copy1->setSkipServiceWorker(true); copy1->setFetchRequestMode(WebURLRequest::FetchRequestModeNoCORS); copy1->setFetchCredentialsMode(WebURLRequest::FetchCredentialsModeInclude); OwnPtr<CrossThreadResourceRequestData> data2(copy1->copyData()); OwnPtr<ResourceRequest> copy2(ResourceRequest::adopt(data2.release())); EXPECT_TRUE(copy2->allowStoredCredentials()); EXPECT_TRUE(copy2->reportUploadProgress()); EXPECT_TRUE(copy2->hasUserGesture()); EXPECT_TRUE(copy2->downloadToFile()); EXPECT_TRUE(copy2->skipServiceWorker()); EXPECT_EQ(WebURLRequest::FetchRequestModeNoCORS, copy1->fetchRequestMode()); EXPECT_EQ(WebURLRequest::FetchCredentialsModeInclude, copy1->fetchCredentialsMode()); }
void SetData(uint32 type, uint32 data) { switch(type) { case DATA_RAGEWINTERCHILLEVENT: m_auiEncounter[0] = data; break; case DATA_ANETHERONEVENT: m_auiEncounter[1] = data; break; case DATA_KAZROGALEVENT: m_auiEncounter[2] = data; break; case DATA_AZGALOREVENT: { m_auiEncounter[3] = data; if (data == DONE) { if (ArchiYell)break; ArchiYell = true; Creature* creature = instance->GetCreature(Azgalor); if (creature) { Creature* pUnit = creature->SummonCreature(21987, creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 10000); Map* pMap = creature->GetMap(); if (pMap->IsDungeon() && pUnit) { pUnit->SetVisible(false); Map::PlayerList const &PlayerList = pMap->GetPlayers(); if (PlayerList.isEmpty()) return; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->getSource()) { WorldPacket data(SMSG_MESSAGECHAT, 200); pUnit->BuildMonsterChat(&data, CHAT_MSG_MONSTER_YELL, YELL_EFFORTS, 0, YELL_EFFORTS_NAME, i->getSource()->GetGUID()); i->getSource()->GetSession()->SendPacket(&data); WorldPacket data2(SMSG_PLAY_SOUND, 4); data2 << 10986; i->getSource()->GetSession()->SendPacket(&data2); } } } } } } break; case DATA_ARCHIMONDEEVENT: m_auiEncounter[4] = data; break; case DATA_RESET_TRASH_COUNT: Trash = 0; break; case DATA_TRASH: if (data) Trash = data; else Trash--; DoUpdateWorldState(WORLD_STATE_ENEMYCOUNT, Trash); break; case TYPE_RETREAT: if (data == SPECIAL) { if (!m_uiAncientGemGUID.empty()) { for (std::list<uint64>::const_iterator itr = m_uiAncientGemGUID.begin(); itr != m_uiAncientGemGUID.end(); ++itr) { //don't know how long it expected DoRespawnGameObject(*itr, DAY); } } } break; case DATA_ALLIANCE_RETREAT: allianceRetreat = data; HandleGameObject(HordeGate, true); SaveToDB(); break; case DATA_HORDE_RETREAT: hordeRetreat = data; HandleGameObject(ElfGate, true); SaveToDB(); break; case DATA_RAIDDAMAGE: RaidDamage += data; if (RaidDamage >= MINRAIDDAMAGE) RaidDamage = MINRAIDDAMAGE; break; case DATA_RESET_RAIDDAMAGE: RaidDamage = 0; break; } sLog->outDebug(LOG_FILTER_TSCR, "TSCR: Instance Hyjal: Instance data updated for event %u (Data=%u)", type, data); if (data == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " " << m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << allianceRetreat << " " << hordeRetreat << " " << RaidDamage; str_data = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } }
TVerdict CTcpClientTestUPnP12::RunTestL() { switch ( iState ) { case ECreateTestServer: { iLogger.WriteFormat(_L("<i>Creating TestServer..... </i>")); iTestServer = CTestTcpServer::NewL ( *this ); iState = ECreateTestClient; iStatus = KRequestPending; Reschedule(); return EPass; } case ECreateTestClient: { iLogger.WriteFormat(_L("<i>TestServer is created..... </i>")); iLogger.WriteFormat(_L("<i>Creating TestClient..... </i>")); THttpClientFlowQuery flowQuery ( TAppProtAddr ( KInetAddrLoop, KHttpDefaultPort ), Id (), EHttpClientFlow, THttpClientFlowQuery::ECreateNew, iChunkManager ); const TUid requestedUid = { CUPnPFlowFactory::iUid }; TNodeId factoryContainer = SockManGlobals::Get( )->GetPlaneFC( TCFPlayerRole ( TCFPlayerRole::EDataPlane ) ); RClientInterface::OpenPostMessageClose ( NodeId (), TNodeCtxId ( KActivityNull, factoryContainer ), TCFFactory::TFindOrCreatePeer ( TCFPlayerRole::EDataPlane, requestedUid, &flowQuery ).CRef () ); iState = ESendRequestData; iStatus = KRequestPending; Reschedule(); return EPass; } case ESendRequestData: { iLogger.WriteFormat(_L("<i>Client is Created</i>")); iLogger.WriteFormat(_L("<i>Send data..... </i>")); TPtrC8 data(KData1); TPtrC8 data2(KData2); TPtrC8 data3(KData3); iSSP->SetOption(KCHOptionLevel, KCHAbsoluteUri, _L8 ("http://127.0.0.1")); TCHMessageOption option ( 1, data.Length()+data2.Length()+data3.Length() ); TPckg < TCHMessageOption > optionBuf ( option ); iSSP->SetOption(KCHOptionLevel, KCHMaxLength, optionBuf); RMBufChain bodyBuf; bodyBuf.CreateL(KData1); iSSPData->Write(bodyBuf, 0, NULL); /* TCHMessageOption option2 ( 1, data2.Length() ); TPckg < TCHMessageOption > optionBuf2 ( option2 ); iSSP->SetOption(KCHOptionLevel, KCHMaxLength, optionBuf2); */ RMBufChain bodyBuf1; bodyBuf1.CreateL(KData2); iSSPData->Write(bodyBuf1, 0, NULL); /* TCHMessageOption option3 ( 1, data3.Length() ); TPckg < TCHMessageOption > optionBuf3 ( option3 ); iSSP->SetOption(KCHOptionLevel, KCHMaxLength, optionBuf3); */ RMBufChain bodyBuf2; bodyBuf2.CreateL(KData3); iSSPData->Write(bodyBuf2, 0, NULL); iState = ECleanup; iStatus = KRequestPending; Reschedule (); return EPass; } case ECleanup: { delete iTestServer; // cleanup tcp client flow delete reinterpret_cast<CHttpClientFlow*> ( iClientId.Ptr () ); iTimer.After ( iStatus, 60000000 ); //10 secs iState = EComplete; iStatus = KRequestPending; Reschedule (); return EPass; } case EComplete: { iLogger.WriteFormat(_L("<i>TestCase: Complete..... </i>")); return EPass; } default: iLogger.WriteFormat(_L("<i> Failed: TestCase:..... </i>")); ASSERT(0); return EFail; } }
int U_EXPORT main (int argc, char* argv[]) { U_ULIB_INIT(argv); U_TRACE(5,"main(%d)",argc) UTimeDate data1(31,12,99), data2("31/12/99"); U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 ) U_ASSERT( UTimeDate("31/12/1900").getJulian() == 2415385 ) U_ASSERT( UTimeDate("01/01/1970").getJulian() == 2440588 ) U_ASSERT( data1 == data2 ) U_ASSERT( data1.getDayOfWeek() == 5 ) // Venerdi U_ASSERT( data2.getDayOfYear() == 365 ) U_ASSERT( UTimeDate("1/3/00").getDayOfWeek() == 3 ) // Mercoledi U_ASSERT( UTimeDate(31,12,0).getDayOfYear() == 366 ) UTimeDate data3(60,2000); UTimeDate data4("29/02/00"); U_ASSERT( data3 == data4 ) U_ASSERT( data3.getDayOfYear() == 60 ) UTimeDate data5(60,1901); UTimeDate data6("1/3/1901"); U_ASSERT( data5 == data6 ) U_ASSERT( UTimeDate(17, 5, 2002).isValid() == true ) // TRUE May 17th 2002 is valid U_ASSERT( UTimeDate(30, 2, 2002).isValid() == false ) // FALSE Feb 30th does not exist U_ASSERT( UTimeDate(29, 2, 2004).isValid() == true ) // TRUE 2004 is a leap year UTimeDate data7(29, 2, 2004); UString x = data7.strftime("%Y-%m-%d"); U_ASSERT( x == U_STRING_FROM_CONSTANT("2004-02-29") ) U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 ) cout << "Date: " << data6.strftime("%d/%m/%y") << '\n'; while (cin >> data6) cout << data6 << '\n'; U_ASSERT( UTimeDate::getSecondFromTime("19030314104248Z", true, "%4u%2u%2u%2u%2u%2uZ") < u_now->tv_sec ) /* typedef struct static_date { struct timeval _timeval; // => u_now char lock1[1]; char date1[17+1]; // 18/06/12 18:45:56 char lock2[1]; char date2[26+1]; // 04/Jun/2012:18:18:37 +0200 char lock3[1]; char date3[6+29+2+12+2+19+1]; // Date: Wed, 20 Jun 2012 11:43:17 GMT\r\nServer: ULib\r\nConnection: close\r\n } static_date; */ ULog::static_date log_data; (void) u_strftime2(log_data.date1, 17, "%d/%m/%y %T", u_now->tv_sec + u_now_adjust); (void) u_strftime2(log_data.date2, 26, "%d/%b/%Y:%T %z", u_now->tv_sec + u_now_adjust); (void) u_strftime2(log_data.date3, 6+29+2+12+2+17+2, "Date: %a, %d %b %Y %T GMT\r\nServer: ULib\r\nConnection: close\r\n", u_now->tv_sec); U_INTERNAL_DUMP("date1 = %.17S date2 = %.26S date3+6 = %.29S", log_data.date1, log_data.date2, log_data.date3+6) /* for (int i = 0; i < 360; ++i) { u_now->tv_sec++; UTimeDate::updateTime(log_data.date1 + 12); UTimeDate::updateTime(log_data.date2 + 15); UTimeDate::updateTime(log_data.date3+6 + 20); cout.write(log_data.date1, 17); cout.write(" - ", 3); cout.write(log_data.date2, 26); cout.write(" - ", 3); cout.write(log_data.date3+6, 29); cout.put('\n'); } */ }
BOOST_FIXTURE_TEST_CASE(GeneralSigningInterface, IdentityManagementV1Fixture) { Name id("/id"); Name certName = m_keyChain.createIdentity(id); shared_ptr<v1::IdentityCertificate> idCert = m_keyChain.getCertificate(certName); Name keyName = idCert->getPublicKeyName(); m_keyChain.setDefaultIdentity(id); Name id2("/id2"); Name cert2Name = m_keyChain.createIdentity(id2); shared_ptr<v1::IdentityCertificate> id2Cert = m_keyChain.getCertificate(cert2Name); // SigningInfo is set to default Data data1("/data1"); m_keyChain.sign(data1); BOOST_CHECK(Validator::verifySignature(data1, idCert->getPublicKeyInfo())); BOOST_CHECK_EQUAL(data1.getSignature().getKeyLocator().getName(), certName.getPrefix(-1)); Interest interest1("/interest1"); m_keyChain.sign(interest1); BOOST_CHECK(Validator::verifySignature(interest1, idCert->getPublicKeyInfo())); SignatureInfo sigInfo1(interest1.getName()[-2].blockFromValue()); BOOST_CHECK_EQUAL(sigInfo1.getKeyLocator().getName(), certName.getPrefix(-1)); // SigningInfo is set to Identity Data data2("/data2"); m_keyChain.sign(data2, SigningInfo(SigningInfo::SIGNER_TYPE_ID, id2)); BOOST_CHECK(Validator::verifySignature(data2, id2Cert->getPublicKeyInfo())); BOOST_CHECK_EQUAL(data2.getSignature().getKeyLocator().getName(), cert2Name.getPrefix(-1)); Interest interest2("/interest2"); m_keyChain.sign(interest2, SigningInfo(SigningInfo::SIGNER_TYPE_ID, id2)); BOOST_CHECK(Validator::verifySignature(interest2, id2Cert->getPublicKeyInfo())); SignatureInfo sigInfo2(interest2.getName()[-2].blockFromValue()); BOOST_CHECK_EQUAL(sigInfo2.getKeyLocator().getName(), cert2Name.getPrefix(-1)); // SigningInfo is set to Key Data data3("/data3"); m_keyChain.sign(data3, SigningInfo(SigningInfo::SIGNER_TYPE_KEY, keyName)); BOOST_CHECK(Validator::verifySignature(data3, idCert->getPublicKeyInfo())); BOOST_CHECK_EQUAL(data3.getSignature().getKeyLocator().getName(), certName.getPrefix(-1)); Interest interest3("/interest3"); m_keyChain.sign(interest3); BOOST_CHECK(Validator::verifySignature(interest3, idCert->getPublicKeyInfo())); SignatureInfo sigInfo3(interest1.getName()[-2].blockFromValue()); BOOST_CHECK_EQUAL(sigInfo3.getKeyLocator().getName(), certName.getPrefix(-1)); // SigningInfo is set to Cert Data data4("/data4"); m_keyChain.sign(data4, SigningInfo(SigningInfo::SIGNER_TYPE_CERT, certName)); BOOST_CHECK(Validator::verifySignature(data4, idCert->getPublicKeyInfo())); BOOST_CHECK_EQUAL(data4.getSignature().getKeyLocator().getName(), certName.getPrefix(-1)); Interest interest4("/interest4"); m_keyChain.sign(interest4, SigningInfo(SigningInfo::SIGNER_TYPE_CERT, certName)); BOOST_CHECK(Validator::verifySignature(interest4, idCert->getPublicKeyInfo())); SignatureInfo sigInfo4(interest4.getName()[-2].blockFromValue()); BOOST_CHECK_EQUAL(sigInfo4.getKeyLocator().getName(), certName.getPrefix(-1)); // SigningInfo is set to DigestSha256 Data data5("/data5"); m_keyChain.sign(data5, SigningInfo(SigningInfo::SIGNER_TYPE_SHA256)); BOOST_CHECK(Validator::verifySignature(data5, DigestSha256(data5.getSignature()))); Interest interest5("/interest4"); m_keyChain.sign(interest5, SigningInfo(SigningInfo::SIGNER_TYPE_SHA256)); BOOST_CHECK(Validator::verifySignature(interest5, DigestSha256(Signature(interest5.getName()[-2].blockFromValue(), interest5.getName()[-1].blockFromValue())))); }