Пример #1
0
void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket)
{
	CHECK_INWORLD_RETURN;
	
	PlayerPointer p_User = GetPlayer();
	DEBUG_LOG("WORLD","Received use Item packet, data length = %i",recvPacket.size());
	int8 tmp1,slot;
	uint8 unk; // 3.0.2 added unk
	uint64 item_guid;
	uint8 cn;
	uint32 spellId = 0;
	uint32 glyphIndex;

	recvPacket >> tmp1 >> slot >> cn >> spellId >> item_guid >> glyphIndex >> unk;
	ItemPointer tmpItem = NULLITEM;
	tmpItem = p_User->GetItemInterface()->GetInventoryItem(tmp1,slot);
	if (!tmpItem)
		tmpItem = p_User->GetItemInterface()->GetInventoryItem(slot);
	if (!tmpItem)
		return;
	ItemPrototype *itemProto = tmpItem->GetProto();
	if(!itemProto)
		return;

	if(_player->getDeathState()==CORPSE)
		return;

	if(itemProto->Bonding == ITEM_BIND_ON_USE)
		tmpItem->SoulBind();

	if(sScriptMgr.CallScriptedItem(tmpItem,_player))
		return;

	if(itemProto->QuestId)
	{
		// Item Starter
		Quest *qst = QuestStorage.LookupEntry(itemProto->QuestId);
		if(!qst) 
			return;

		if( sQuestMgr.PlayerMeetsReqs(_player, qst, false) != QMGR_QUEST_AVAILABLE || qst->min_level > _player->getLevel() )
			return;

        WorldPacket data;
        sQuestMgr.BuildQuestDetails(&data, qst, tmpItem, 0, language, _player);
		SendPacket(&data);
	}
	
	SpellCastTargets targets(recvPacket, _player->GetGUID());
	uint32 x;
	for(x = 0; x < 5; x++)
	{
		if(itemProto->Spells[x].Trigger == USE)
		{
			if(itemProto->Spells[x].Id)
			{
				spellId = itemProto->Spells[x].Id;
				break;
			}
		}
	}
	if(!spellId)
		return;
	// check for spell id
	SpellEntry *spellInfo = dbcSpell.LookupEntryForced( spellId );

	if(!spellInfo)
	{
		OUT_DEBUG("WORLD: unknown spell id %i\n", spellId);
		return;
	}

	if (spellInfo->AuraInterruptFlags & AURA_INTERRUPT_ON_STAND_UP)
	{
		if (p_User->CombatStatus.IsInCombat() || p_User->IsMounted())
		{
			_player->GetItemInterface()->BuildInventoryChangeError(tmpItem,NULLITEM,INV_ERR_CANT_DO_IN_COMBAT);
			return;
		}
	
		if(p_User->GetStandState()!=STANDSTATE_SIT)
			p_User->SetStandState(STANDSTATE_SIT);
	}

	if(itemProto->RequiredLevel)
	{
		if(_player->getLevel() < itemProto->RequiredLevel)
		{
			_player->GetItemInterface()->BuildInventoryChangeError(tmpItem,NULLITEM,INV_ERR_ITEM_RANK_NOT_ENOUGH);
			return;
		}
	}

	if(itemProto->RequiredSkill)
	{
		if(!_player->_HasSkillLine(itemProto->RequiredSkill))
		{
			_player->GetItemInterface()->BuildInventoryChangeError(tmpItem,NULLITEM,INV_ERR_ITEM_RANK_NOT_ENOUGH);
			return;
		}

		if(itemProto->RequiredSkillRank)
		{
			if(_player->_GetSkillLineCurrent(itemProto->RequiredSkill, false) < itemProto->RequiredSkillRank)
			{
				_player->GetItemInterface()->BuildInventoryChangeError(tmpItem,NULLITEM,INV_ERR_ITEM_RANK_NOT_ENOUGH);
				return;
			}
		}
	}
	
	if( itemProto->AllowableClass && !(_player->getClassMask() & itemProto->AllowableClass) || itemProto->AllowableRace && !(_player->getRaceMask() & itemProto->AllowableRace) )
	{
		_player->GetItemInterface()->BuildInventoryChangeError(tmpItem,NULLITEM,INV_ERR_YOU_CAN_NEVER_USE_THAT_ITEM);
		return;
	}		

	if( !_player->Cooldown_CanCast( itemProto, x ) )
	{
		_player->SendCastResult(spellInfo->Id, SPELL_FAILED_NOT_READY, cn, 0);
		return;
	}

	if(_player->m_currentSpell)
	{
		_player->SendCastResult(spellInfo->Id, SPELL_FAILED_SPELL_IN_PROGRESS, cn, 0);
		return;
	}

	if( itemProto->ForcedPetId >= 0 )
	{
		if( itemProto->ForcedPetId == 0 )
		{
			if( _player->GetGUID() != targets.m_unitTarget )
			{
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_BAD_TARGETS, cn, 0);
				return;
			}
		}
		else
		{
			if( !_player->GetSummon() || _player->GetSummon()->GetEntry() != (uint32)itemProto->ForcedPetId )
			{
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_SPELL_IN_PROGRESS, cn, 0);
				return;
			}
		}
	}

	if(!sHookInterface.OnCastSpell(_player, spellInfo))
	{
		_player->SendCastResult(spellInfo->Id, SPELL_FAILED_UNKNOWN, cn, 0);
		return;
	}

	SpellPointer spell(new Spell(_player, spellInfo, false, NULLAURA));
	spell->extra_cast_number=cn;
	spell->m_glyphIndex = glyphIndex;
	spell->i_caster = tmpItem;
	if( spell->prepare(&targets) == SPELL_CANCAST_OK )
		_player->Cooldown_AddItem( itemProto, x );
}
Пример #2
0
void EyeOfTheStorm::HookOnAreaTrigger(Player* plr, uint32 id)
{
	int32 tid = -1;
	int32 bonusid = -1;
	switch(id)
	{
		case 4476:			// BE Tower
			tid = EOTS_TOWER_BE;
			break;
		case 4568:			// BE Tower bonus
			bonusid = EOTS_TOWER_BE;
			break;
		case 4514:			// Fel Reaver Tower
			tid = EOTS_TOWER_FELREAVER;
			break;
		case 4569:			// Fel Reaver Tower bonus
			bonusid = EOTS_TOWER_FELREAVER;
			break;
		case 4518:			// Draenei Tower
			tid = EOTS_TOWER_DRAENEI;
			break;
		case 4571:			// Draenei Tower bonus
			bonusid = EOTS_TOWER_DRAENEI;
			break;
		case 4516:			// Mage Tower
			tid = EOTS_TOWER_MAGE;
			break;
		case 4570:			// Mage Tower bonus
			bonusid = EOTS_TOWER_MAGE;
			break;
		default:
			sLog.Error("EyeOfTheStorm", "Encountered unhandled areatrigger id %u", id);
			return;
			break;
	}

	if(plr->IsDead())		// on ne buff pas les joueurs morts ;)
		return;

	if(bonusid > -1)
	{
		uint32 spellid = 0;
		uint32 x = (uint32)bonusid;
		if(EOTSm_buffs[x] && EOTSm_buffs[x]->IsInWorld())
		{
			spellid = EOTSm_buffs[x]->GetInfo()->sound3;
			SpellEntry* sp = dbcSpell.LookupEntryForced(spellid);
			if(sp)
			{
				Spell* pSpell = sSpellFactoryMgr.NewSpell(plr, sp, true, NULL);
				SpellCastTargets targets(plr->GetGUID());
				pSpell->prepare(&targets);
			}
			EOTSm_buffs[x]->Despawn(0, EOTS_BUFF_RESPAWN_TIME);
		}
	}

	if(tid < 0)
		return;

#ifdef ANTI_CHEAT
	if(!m_started)
	{
		Anticheat_Log->writefromsession(plr->GetSession(), "%s tried to hook the flag in eye of the storm before battleground (ID %u) started.", plr->GetName(), this->m_id);
		SendChatMessage(CHAT_MSG_BG_EVENT_NEUTRAL, plr->GetGUID(), "%s will be removed from the game for cheating.", plr->GetName());
		// Remove player from battleground.
		this->RemovePlayer(plr, false);
		// Kick	player from server.
		plr->Kick(MSTIME_6SECONDS);
		return;
	}
#endif

	uint32 team = plr->GetTeam();
	if(plr->GetLowGUID() != m_flagHolder)
		return;

	int32 val;
	uint32 i;
	uint32 towers = 0;
	if(team == TEAM_ALLIANCE)
		val = EOTS_BANNER_ALLIANCE;
	else
		val = EOTS_BANNER_HORDE;

	if(!m_CPBanner[tid] || m_CPBanner[tid]->GetEntry() != static_cast<uint32>(val))
		return;			// not captured by our team

	for(i = 0; i < EOTS_TOWER_COUNT; ++i)
	{
		if(m_CPBanner[i] && m_CPBanner[i]->GetEntry() == static_cast<uint32>(val))
			towers++;
	}

	/*
	Points from flag captures
	* 1 towers controlled = 75 points
	* 2 towers controlled = 85 points
	* 3 towers controlled = 100 points
	* 4 towers controlled = 500 points
	*/

	// 25 is guessed
	const static uint32 points[5] = { 25, 75, 85, 100, 500 };
	const char* msgs[2] = { "The Alliance have captured the flag.", "The Horde have captured the flag." };

	SendChatMessage(CHAT_MSG_BG_EVENT_ALLIANCE + team, 0, msgs[team]);
	GivePoints(team, points[towers]);

	DropFlag2(plr, id);
	SetWorldState(2757, 1);

	plr->RemoveAura(EOTS_NETHERWING_FLAG_SPELL);
	plr->m_bgScore.MiscData[BG_SCORE_EOTS_FLAGS_CAPTURED]++;
	UpdatePvPData();
}
Пример #3
0
void WarsongGulch::HookOnAreaTrigger(Player * plr, uint32 id)
{
	int32 buffslot = -1;
	switch(id)
	{
	case 3686:	  // Speed
		buffslot = 0;
		break;
	case 3687:	  // Speed (Horde)
		buffslot = 1;
		break;
	case 3706:	  // Restoration
		buffslot = 2;
		break;
	case 3708:	  // Restoration (Horde)
		buffslot = 3;
		break;
	case 3707:	  // Berserking
		buffslot = 4;
		break;
	case 3709:	  // Berserking (Horde)
		buffslot = 5;
		break;
	}

	if(buffslot >= 0)
	{
		if(m_buffs[buffslot] != 0 && m_buffs[buffslot]->IsInWorld())
		{
			/* apply the buff */
			SpellEntry * sp = dbcSpell.LookupEntry(m_buffs[buffslot]->GetInfo()->sound3);
			Spell * s = new Spell(plr, sp, true, 0);
			SpellCastTargets targets(plr->GetGUID());
			s->prepare(&targets);

			/* despawn the gameobject (not delete!) */
			m_buffs[buffslot]->Despawn(0, BUFF_RESPAWN_TIME);
		}
		return;
	}

	if(((id == 3646 && plr->IsTeamAlliance()) || (id == 3647 && plr->IsTeamHorde())) && (plr->m_bgHasFlag && m_flagHolders[plr->GetTeam()] == plr->GetLowGUID()))
	{
		if(m_flagHolders[plr->IsTeamHorde() ? TEAM_ALLIANCE : TEAM_HORDE] != 0 || m_dropFlags[plr->IsTeamHorde() ? TEAM_ALLIANCE : TEAM_HORDE]->IsInWorld())
		{
			/* can't cap while flag dropped */
			return;
		}
		float distance = plr->IsTeamAlliance() ? plr->CalcDistance(1540.29f, 1481.34f, 352.64f) :plr->CalcDistance(915.367f, 1433.78f, 346.089f);
		if (distance > 50.0f)
		{
			//50 yards from the spawn, gtfo hacker.
			sCheatLog.writefromsession(plr->GetSession(),"Tried to capture the flag in WSG while being more then 50 yards away. (%f yards)",plr->CalcDistance(915.367f, 1433.78f, 346.089f));
			plr->GetSession()->Disconnect();
			return;
		}

		/* remove the bool from the player so the flag doesn't drop */
		m_flagHolders[plr->GetTeam()] = 0;
		plr->m_bgHasFlag = 0;

		/* remove flag aura from player */
		plr->RemoveAura(23333+(plr->GetTeam() * 2));

		/* capture flag points */
		plr->m_bgScore.MiscData[BG_SCORE_WSG_FLAGS_CAPTURED]++;

		PlaySoundToAll( plr->IsTeamHorde() ? SOUND_HORDE_SCORES : SOUND_ALLIANCE_SCORES );

		if( plr->IsTeamHorde() )
			SendChatMessage( CHAT_MSG_BG_EVENT_HORDE, plr->GetGUID(), "%s captured the Alliance flag!", plr->GetName() );
		else
			SendChatMessage( CHAT_MSG_BG_EVENT_ALLIANCE, plr->GetGUID(), "%s captured the Horde flag!", plr->GetName() );

		SetWorldState( plr->IsTeamHorde() ? WSG_ALLIANCE_FLAG_CAPTURED : WSG_HORDE_FLAG_CAPTURED, 1 );

		// Remove the Other Flag
		if (m_homeFlags[plr->IsTeamHorde() ? TEAM_ALLIANCE : TEAM_HORDE]->IsInWorld())
			m_homeFlags[plr->IsTeamHorde() ? TEAM_ALLIANCE : TEAM_HORDE]->RemoveFromWorld(false);

		// Add the Event to respawn the Flags
		sEventMgr.AddEvent(this, &WarsongGulch::EventReturnFlags, EVENT_BATTLEGROUND_WSG_AUTO_RETURN_FLAG, 20000, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);

		/* give each player on that team bonus honor and reputation*/
		uint32 honorToAdd = 2 * m_honorPerKill;
		uint32 repToAdd = m_isWeekend ? 45 : 35;
		uint32 fact = plr->IsTeamHorde() ? 889 : 890; /*Warsong Outriders : Sliverwing Sentinels*/
		for(set<Player*>::iterator itr = m_players[plr->GetTeam()].begin(); itr != m_players[plr->GetTeam()].end(); ++itr)
		{
			(*itr)->m_bgScore.BonusHonor += honorToAdd;
			HonorHandler::AddHonorPointsToPlayer((*itr), honorToAdd);
			plr->ModStanding(fact, repToAdd);
		}

		m_scores[plr->GetTeam()]++;
		if(m_scores[plr->GetTeam()] == 3)
		{
			/* victory! */
			m_ended = true;
			m_winningteam = (uint8)plr->GetTeam();
			m_nextPvPUpdateTime = 0;

			sEventMgr.RemoveEvents(this, EVENT_BATTLEGROUND_CLOSE);
			sEventMgr.AddEvent(((CBattleground*)this), &CBattleground::Close, EVENT_BATTLEGROUND_CLOSE, 120000, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
			/* add the marks of honor to all players */
			SpellEntry * winner_spell = dbcSpell.LookupEntry(24951);
			SpellEntry * loser_spell = dbcSpell.LookupEntry(24950);
			uint32 lostHonorToAdd = m_isWeekend ? 4 * m_honorPerKill : 2 * m_honorPerKill;
			uint32 winHonorToAdd = lostHonorToAdd + (m_isWeekend ? 3 * m_honorPerKill : m_honorPerKill);
			
			m_mainLock.Acquire();
			for(uint32 i = 0; i < 2; ++i)
			{
				for(set<Player*>::iterator itr = m_players[i].begin(); itr != m_players[i].end(); ++itr)
				{
					(*itr)->Root();
					if(i == m_winningteam)
					{
						(*itr)->m_bgScore.BonusHonor += winHonorToAdd;
						HonorHandler::AddHonorPointsToPlayer((*itr), winHonorToAdd);
						(*itr)->CastSpell((*itr), winner_spell, true);
						if(i && (*itr)->GetQuestLogForEntry(11342))
							(*itr)->GetQuestLogForEntry(11342)->SendQuestComplete();
						else if((*itr)->GetQuestLogForEntry(11338))
							(*itr)->GetQuestLogForEntry(11338)->SendQuestComplete();
					}
					else
					{
						(*itr)->m_bgScore.BonusHonor += lostHonorToAdd;
						HonorHandler::AddHonorPointsToPlayer((*itr), lostHonorToAdd);
						(*itr)->CastSpell((*itr), loser_spell, true);
					}
				}
			}
			m_mainLock.Release();
		}

		/* increment the score world state */
		SetWorldState(plr->IsTeamHorde() ? WSG_CURRENT_HORDE_SCORE : WSG_CURRENT_ALLIANCE_SCORE, m_scores[plr->GetTeam()]);

		UpdatePvPData();
	}
}
Пример #4
0
double CrossEntropyError::calculate_minimum_selection_performance(void) const
{
    // Control sentence

    #ifdef __OPENNN_DEBUG__

    check();

    #endif

    // Neural network stuff

    const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

    const size_t inputs_number = multilayer_perceptron_pointer->get_inputs_number();
    const size_t outputs_number = multilayer_perceptron_pointer->get_outputs_number();

    // Data set stuff

    const Instances& instances = data_set_pointer->get_instances();

    const size_t selection_instances_number = instances.count_selection_instances_number();

    const Vector<size_t> selection_indices = instances.arrange_selection_indices();

    size_t selection_index;

    const Variables& variables = data_set_pointer->get_variables();

    const Vector<size_t> inputs_indices = variables.arrange_inputs_indices();
    const Vector<size_t> targets_indices = variables.arrange_targets_indices();

    // Performance functional

    Vector<double> inputs(inputs_number);
    Vector<double> outputs(outputs_number);
    Vector<double> targets(outputs_number);

    double minimum_selection_performance = 0.0;

    int i = 0;

    #pragma omp parallel for private(i, selection_index, inputs, outputs, targets) reduction(- : minimum_selection_performance)

    for(i = 0; i < (int)selection_instances_number; i++)
    {
        selection_index = selection_indices[i];

       // Input vector

       inputs = data_set_pointer->get_instance(selection_index, inputs_indices);

       // Output vector

       outputs = multilayer_perceptron_pointer->calculate_outputs(inputs);

       // Target vector

       targets = data_set_pointer->get_instance(selection_index, targets_indices);

       // Cross entropy error

       for(size_t j = 0; j < outputs_number; j++)
       {
           if(outputs[j] == 0.0)
           {
               outputs[j] = 1.0e-6;
           }
           else if(outputs[j] == 1.0)
           {
               outputs[j] = 0.999999;
           }

           if(targets[j] == 0.0)
           {
               targets[j] = 1.0e-6;
           }
           else if(targets[j] == 1.0)
           {
               targets[j] = 0.999999;
           }

           minimum_selection_performance -= targets[j]*log(outputs[j]/targets[j]) + (1.0 - targets[j])*log((1.0 - outputs[j])/(1.0 - targets[j]));
       }
    }

    return(minimum_selection_performance);
}
Пример #5
0
  /**
   * @function setInitControl
   */
  void drchubo_Basics::SetInitControl() {

    // Set info to controller
    mCb.setSize( mNumActuatedJoints );    
    mCb.setJoints( mActuatedJoints );

    // Set target to keep : Initial hard-coded values
    std::vector<double> targets( mNumActuatedJoints );
    for( int i = 0; i < mNumActuatedJoints; ++i ) {
      targets[i] = mActuatedJoints[i]->GetAngle(0).Radian(); 
    }  
    mCb.setTargets(targets);
  
    // Set PID initial values

    // Left Leg
    mCb.initPID( 0, 50, 0, 5, 0, 0, 50, -50 );
    mCb.initPID( 1, 50, 0, 5, 0, 0, 50, -50 );
    mCb.initPID( 2, 50, 0, 5, 0, 0, 50, -50 );
    mCb.initPID( 3, 1000, 0, 5, 0, 0, 1000, -1000 ); // LKP
    mCb.initPID( 4, 200, 0, 10, 0, 0, 200, -200 ); // LAP
    mCb.initPID( 5, 50, 0, 5, 0, 0, 50, -50 );

    // Right Leg
    mCb.initPID( 6, 50, 0, 5, 0, 0, 50, -50 );
    mCb.initPID( 7, 50, 0, 5, 0, 0, 50, -50 );
    mCb.initPID( 8, 50, 0, 5, 0, 0, 50, -50 );
    mCb.initPID( 9, 1000, 0, 5, 0, 0, 1000, -1000 ); // RKP
    mCb.initPID( 10, 200, 0, 10, 0, 0, 200, -200 ); // RAP
    mCb.initPID( 11, 50, 0, 5, 0, 0, 50, -50 );
    
    // Left Arm
    mCb.initPID( 12, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 13, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 14, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 15, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 16, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 17, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 18, 50, 0, 0, 0, 0, 50, -50 );

    // Right Arm
    mCb.initPID( 19, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 20, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 21, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 22, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 23, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 24, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 25, 50, 0, 0, 0, 0, 50, -50 );

    // Torso and neck
    mCb.initPID( 26, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 27, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 28, 50, 0, 0, 0, 0, 50, -50 );


    // Left and right fingers ( 3 + 3 = 6 )
    mCb.initPID( 29, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 30, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 31, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 32, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 33, 50, 0, 0, 0, 0, 50, -50 );
    mCb.initPID( 34, 50, 0, 0, 0, 0, 50, -50 );

  }
Пример #6
0
int BioScan::caTarget( Id channel, vector< Id >& ret )
{
	return targets( channel, "IkSrc", ret, "CaConc" );
}
Пример #7
0
double CrossEntropyError::calculate_performance(void) const
{
   #ifdef __OPENNN_DEBUG__ 

   check();

   #endif

   // Neural network stuff

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   const size_t inputs_number = multilayer_perceptron_pointer->get_inputs_number();
   const size_t outputs_number = multilayer_perceptron_pointer->get_outputs_number();

   // Data set stuff 

   const Instances& instances = data_set_pointer->get_instances();

   const size_t training_instances_number = instances.count_training_instances_number();

   const Vector<size_t> training_indices = instances.arrange_training_indices();

   size_t training_index;

   const Variables& variables = data_set_pointer->get_variables();

   const Vector<size_t> inputs_indices = variables.arrange_inputs_indices();
   const Vector<size_t> targets_indices = variables.arrange_targets_indices();

   // Cross entropy error

   Vector<double> inputs(inputs_number);
   Vector<double> outputs(outputs_number);
   Vector<double> targets(outputs_number);

   double cross_entropy_error = 0.0;

   int i = 0;

   #pragma omp parallel for private(i, training_index, inputs, outputs, targets) reduction(+ : cross_entropy_error)

   for(i = 0; i < (int)training_instances_number; i++)
   {
       training_index = training_indices[i];

      // Input vector

      inputs = data_set_pointer->get_instance(training_index, inputs_indices);

      // Output vector

      outputs = multilayer_perceptron_pointer->calculate_outputs(inputs);

      // Target vector

      targets = data_set_pointer->get_instance(training_index, targets_indices);

      // Cross entropy error

      for(size_t j = 0; j < outputs_number; j++)
      {
          if(outputs[j] == 0.0)
          {
              outputs[j] = 1.0e-6;
          }
          else if(outputs[j] == 1.0)
          {
              outputs[j] = 0.999999;
          }

          cross_entropy_error -= targets[j]*log(outputs[j]) + (1.0 - targets[j])*log(1.0 - outputs[j]);
      }
   }

   return(cross_entropy_error);
}
Пример #8
0
void WorldSession::HandleCastSpellOpcode(WorldPacket & recvPacket)
{
	CHECK_INWORLD_RETURN

	uint32 spellId;
	uint8 cn, unk; //Alice : Added to 3.0.2

	recvPacket >> cn >> spellId  >> unk;
	// check for spell id
	SpellEntry* spellInfo = dbcSpell.LookupEntryForced(spellId);

	if(!spellInfo)
	{
		LOG_DETAIL("ERROR: WORLD: unknown spell id %i", spellId);
		return;
	}

	if(!_player->isAlive() && _player->GetShapeShift() != FORM_SPIRITOFREDEMPTION && !(spellInfo->Attributes & ATTRIBUTES_DEAD_CASTABLE)) //They're dead, not in spirit of redemption and the spell can't be cast while dead.
		return;

	LOG_DETAIL("WORLD: got cast spell packet, spellId - %i (%s), data length = %i",
	           spellId, spellInfo->Name, recvPacket.size());

	// Cheat Detection only if player and not from an item
	// this could f**k up things but meh it's needed ALOT of the newbs are using WPE now
	// WPE allows them to mod the outgoing packet and basically choose what ever spell they want :(

	if(!GetPlayer()->HasSpell(spellId))
	{
		sCheatLog.writefromsession(this, "Cast spell %lu but doesn't have that spell.", spellId);
		LOG_DETAIL("WORLD: Spell isn't cast because player \'%s\' is cheating", GetPlayer()->GetName());
		return;
	}
	if(spellInfo->Attributes & ATTRIBUTES_PASSIVE)
	{
		sCheatLog.writefromsession(this, "Cast passive spell %lu.", spellId);
		LOG_DETAIL("WORLD: Spell isn't cast because player \'%s\' is cheating", GetPlayer()->GetName());
		return;
	}

	if(GetPlayer()->GetOnMeleeSpell() != spellId)
	{
		//autoshot 75
		if((spellInfo->AttributesExB & ATTRIBUTESEXB_ACTIVATE_AUTO_SHOT) /*spellInfo->Attributes == 327698*/)	// auto shot..
		{
			//sLog.outString( "HandleSpellCast: Auto Shot-type spell cast (id %u, name %s)" , spellInfo->Id , spellInfo->Name );
			Item* weapon = GetPlayer()->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_RANGED);
			if(!weapon)
				return;
			uint32 spellid;
			switch(weapon->GetProto()->SubClass)
			{
				case 2:			 // bows
				case 3:			 // guns
				case 18:		 // crossbow
					spellid = SPELL_RANGED_GENERAL;
					break;
				case 16:			// thrown
					spellid = SPELL_RANGED_THROW;
					break;
				case 19:			// wands
					spellid = SPELL_RANGED_WAND;
					break;
				default:
					spellid = 0;
					break;
			}

			if(!spellid)
				spellid = spellInfo->Id;

			if(!_player->m_onAutoShot)
			{
				_player->m_AutoShotTarget = _player->GetSelection();
				uint32 duration = _player->GetBaseAttackTime(RANGED);
				SpellCastTargets targets(recvPacket, GetPlayer()->GetGUID());
				if(!targets.m_unitTarget)
				{
					LOG_DEBUG("Cancelling auto-shot cast because targets.m_unitTarget is null!");
					return;
				}
				SpellEntry* sp = dbcSpell.LookupEntry(spellid);

				_player->m_AutoShotSpell = sp;
				_player->m_AutoShotDuration = duration;
				//This will fix fast clicks
				if(_player->m_AutoShotAttackTimer < 500)
					_player->m_AutoShotAttackTimer = 500;
				_player->m_onAutoShot = true;
			}

			return;
		}

		if(_player->m_currentSpell)
		{
			if(_player->m_currentSpell->getState() == SPELL_STATE_CASTING)
			{
				// cancel the existing channel spell, cast this one
				_player->m_currentSpell->cancel();
			}
			else
			{
				// send the error message
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_SPELL_IN_PROGRESS, cn, 0);
				return;
			}
		}

		SpellCastTargets targets(recvPacket, GetPlayer()->GetGUID());

		// some anticheat stuff
		if(spellInfo->self_cast_only)
		{
			if(targets.m_unitTarget && targets.m_unitTarget != _player->GetGUID())
			{
				// send the error message
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_BAD_TARGETS, cn, 0);
				return;
			}
		}

		Spell* spell = sSpellFactoryMgr.NewSpell(GetPlayer(), spellInfo, false, NULL);
		spell->extra_cast_number = cn;
		spell->prepare(&targets);
	}
}
Пример #9
0
void Item::ApplyEnchantmentBonus( uint32 Slot, bool Apply )
{
	if( m_owner == NULL )
		return;

	EnchantmentMap::iterator itr = Enchantments.find( Slot );
	if( itr == Enchantments.end() )
		return;

	EnchantEntry* Entry = itr->second.Enchantment;
	uint32 RandomSuffixAmount = itr->second.RandomSuffix;

	if( itr->second.BonusApplied == Apply )
		return;

	itr->second.BonusApplied = Apply;

	if( Apply )
	{
		// Send the enchantment time update packet.
		SendEnchantTimeUpdate( itr->second.Slot, itr->second.Duration );
	}

	// Apply the visual on the player.
	uint32 ItemSlot = m_owner->GetItemInterface()->GetInventorySlotByGuid( GetGUID() ) * 16;
	uint32 VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + ItemSlot;
	m_owner->SetUInt32Value( VisibleBase + 1 + Slot, Apply ? Entry->Id : 0 );

	// Another one of those for loop that where not indented properly god knows what will break
	// but i made it actually affect the code below it
	for( uint32 c = 0; c < 3; c++ )
	{
		if( Entry->type[c] )
		{
			// Depending on the enchantment type, take the appropriate course of action.
			switch( Entry->type[c] )
			{
			case 1:		 // Trigger spell on melee attack.
				{
					if( Apply && Entry->spell[c] != 0 )
					{
						// Create a proc trigger spell

						ProcTriggerSpell TS;
						TS.caster = m_owner->GetGUID();
						TS.origId = 0;
						TS.procFlags = PROC_ON_MELEE_ATTACK;
						TS.procCharges = 0;
						/* This needs to be modified based on the attack speed of the weapon.
						 * Secondly, need to assign some static chance for instant attacks (ss,
						 * gouge, etc.) */
						if( !Entry->min[c] && GetProto()->Class == 2 )
						{
							float speed = (float)GetProto()->Delay;
							/////// procChance calc ///////
							float ppm = 0;
							SpellEntry* sp = dbcSpell.LookupEntry( Entry->spell[c] );
							if( sp )
							{
								switch( sp->NameHash )
								{
								case SPELL_HASH_FROSTBRAND_ATTACK:
									ppm = 9;
									break;
								}
							}
							if( ppm != 0 )
							{
								float pcount = 60/ppm;
								float chance = (speed/10) / pcount;
								TS.procChance = (uint32)chance;
							}
							else
								TS.procChance = (uint32)( speed / 600.0f );
							///////////////////////////////
						}
						else
							TS.procChance = Entry->min[c];
						Log.Debug( "Enchant", "Setting procChance to %u%%.", TS.procChance );
						TS.deleted = false;
						TS.spellId = Entry->spell[c];
						m_owner->m_procSpells.push_back( TS );
					}
					else
					{
						// Remove the proctriggerspell
						uint32 SpellId;
						list< struct ProcTriggerSpell >::iterator itr/*, itr2*/;
						for( itr = m_owner->m_procSpells.begin(); itr != m_owner->m_procSpells.end(); )
						{
							SpellId = itr->spellId;
							/*itr2 = itr++;*/
							
							if( SpellId == Entry->spell[c] )
							{
								//m_owner->m_procSpells.erase(itr2);
								itr->deleted = true;
							}
							itr++;
						}
					}
				}break;

			case 2:		 // Mod damage done.
				{
					int32 val = Entry->min[c];
					if( RandomSuffixAmount )
						val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

					if( Apply )
						m_owner->ModUnsigned32Value( PLAYER_FIELD_MOD_DAMAGE_DONE_POS, val );
					else
						m_owner->ModUnsigned32Value( PLAYER_FIELD_MOD_DAMAGE_DONE_POS, -val );
					m_owner->CalcDamage();
				}break;

			case 3:		 // Cast spell (usually means apply aura)
				{
					if( Apply )
					{
						SpellCastTargets targets( m_owner->GetGUID() );
						SpellEntry* sp;
						Spell* spell;
						
						if( Entry->spell[c] != 0 )
						{
							sp = dbcSpell.LookupEntry( Entry->spell[c] );
							if( sp == NULL )
								continue;

							spell = new Spell( m_owner, sp, true, 0 );
							spell->i_caster = this;
							spell->prepare( &targets );
						}
					}
					else
					{
						if( Entry->spell[c] != 0 )
								m_owner->RemoveAura( Entry->spell[c] );
					}

				}break;

			case 4:		 // Modify physical resistance
				{
					int32 val = Entry->min[c];
					if( RandomSuffixAmount )
						val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

					if( Apply )
					{
						m_owner->FlatResistanceModifierPos[Entry->spell[c]] += val;
					}
					else
					{
						m_owner->FlatResistanceModifierPos[Entry->spell[c]] -= val;
					}
					m_owner->CalcResistance( Entry->spell[c] );
				}break;

			case 5:	 //Modify rating ...order is PLAYER_FIELD_COMBAT_RATING_1 and above
				{
					//spellid is enum ITEM_STAT_TYPE
					//min=max is amount
					int32 val = Entry->min[c];
					if( RandomSuffixAmount )
						val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

					m_owner->ModifyBonuses( Entry->spell[c], Apply ? val : -val );
					m_owner->UpdateStats();
				}break;

			case 6:	 // Rockbiter weapon (increase damage per second... how the hell do you calc that)
				{
					if( Apply )
					{
						//m_owner->ModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, Entry->min[c]);
						//if i'm not wrong then we should apply DMPS formula for this. This will have somewhat a larger value 28->34
						int32 val = Entry->min[c];
						if( RandomSuffixAmount )
							val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

						int32 value = GetProto()->Delay * val / 1000;
						m_owner->ModUnsigned32Value( PLAYER_FIELD_MOD_DAMAGE_DONE_POS, value );
					}
					else
					{
						int32 val = Entry->min[c];
						if( RandomSuffixAmount )
							val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

						int32 value =- (int32)(GetProto()->Delay * val / 1000 );
						m_owner->ModUnsigned32Value( PLAYER_FIELD_MOD_DAMAGE_DONE_POS, value );
					}
					m_owner->CalcDamage();
				}break;

			default:
				{
					DEBUG_LOG( "Unknown enchantment type: %u (%u)", Entry->type[c], Entry->Id );
				}break;
			}
		}
	}
}
Пример #10
0
void WorldSession::HandleUseItemOpcode(WorldPacket & recvPacket)
{
	CHECK_INWORLD_RETURN

	typedef std::list<Aura*> AuraList;

	Player* p_User = GetPlayer();
	LOG_DETAIL("WORLD: got use Item packet, data length = %i", recvPacket.size());
	int8 tmp1, slot;
	uint8 unk; //Alice : added in 3.0.2
	uint64 item_guid;
	uint8 cn;
	uint32 spellId = 0;
	uint32 glyphIndex;
	bool found = false;

	recvPacket >> tmp1;
	recvPacket >> slot;
	recvPacket >> cn;
	recvPacket >> spellId;
	recvPacket >> item_guid;
	recvPacket >> glyphIndex;
	recvPacket >> unk;

	Item* tmpItem = NULL;
	tmpItem = p_User->GetItemInterface()->GetInventoryItem(tmp1, slot);
	if(!tmpItem)
		tmpItem = p_User->GetItemInterface()->GetInventoryItem(slot);
	if(!tmpItem)
		return;
	ItemPrototype* itemProto = tmpItem->GetProto();

	// only some consumable items can be used in arenas
	if( ( itemProto->Class == ITEM_CLASS_CONSUMABLE ) &&
		!itemProto->HasFlag( ITEM_FLAG_USEABLE_IN_ARENA ) &&
		( GetPlayer()->m_bg != NULL ) &&
		IS_ARENA( GetPlayer()->m_bg->GetType() ) )
	{
		GetPlayer()->GetItemInterface()->BuildInventoryChangeError(tmpItem, NULL, INV_ERR_NOT_DURING_ARENA_MATCH);
		return;
	}

	if(tmpItem->IsSoulbound())     // SouldBind item will be used after SouldBind()
	{
		if(sScriptMgr.CallScriptedItem(tmpItem, _player))
			return;
	}

	if(_player->getDeathState() == CORPSE)
		return;

	if(itemProto->Bonding == ITEM_BIND_ON_USE)
		tmpItem->SoulBind();

	if(sScriptMgr.CallScriptedItem(tmpItem, _player))
		return;

	if(itemProto->InventoryType != 0 && !_player->GetItemInterface()->IsEquipped(itemProto->ItemId))  //Equipable items cannot be used before they're equipped. Prevents exploits
		return;//Prevents exploits such as keeping an on-use trinket in your bag and using WPE to use it from your bag in mid-combat.

	if(itemProto->QuestId)
	{
		// Item Starter
		Quest* qst = QuestStorage.LookupEntry(itemProto->QuestId);
		if(!qst)
			return;

		WorldPacket data;
		sQuestMgr.BuildQuestDetails(&data, qst, tmpItem, 0, language, _player);
		SendPacket(&data);
	}

	// Let's check if the item even has that spell
	for(int i = 0; i < 5; ++i)
	{
		if(itemProto->Spells[i].Trigger == USE && itemProto->Spells[i].Id == spellId)
		{
			found = true;
			break;//found 1 already
		}
	}

	// Let's see if it is an onuse spellid
	if(tmpItem->HasOnUseSpellID(spellId))
		found = true;

	// We didn't find the spell, so the player is probably trying to cheat
	// with an edited itemcache.wdb
	//
	// Altough this could also happen after a DB update
	// if he/she didn't delete his/her cache.
	if(found == false)
	{

		this->Disconnect();
		Anticheat_Log->writefromsession(this, "Player tried to use an item with a spell that didn't match the spell in the database.");
		Anticheat_Log->writefromsession(this, "Possibly corrupted or intentionally altered itemcache.wdb");
		Anticheat_Log->writefromsession(this, "Itemid: %lu", itemProto->ItemId);
		Anticheat_Log->writefromsession(this, "Spellid: %lu", spellId);
		Anticheat_Log->writefromsession(this, "Player was disconnected");

		return;
	}

	SpellCastTargets targets(recvPacket, _player->GetGUID());

	SpellEntry* spellInfo = dbcSpell.LookupEntryForced(spellId);
	if(spellInfo == NULL)
	{
		LOG_DETAIL("ERROR: WORLD: unknown spell id %i", spellId);
		return;
	}

	if(spellInfo->AuraInterruptFlags & AURA_INTERRUPT_ON_STAND_UP)
	{
		if(p_User->CombatStatus.IsInCombat() || p_User->IsMounted())
		{
			_player->GetItemInterface()->BuildInventoryChangeError(tmpItem, NULL, INV_ERR_CANT_DO_IN_COMBAT);
			return;
		}

		if(p_User->GetStandState() != 1)
			p_User->SetStandState(STANDSTATE_SIT);
		// loop through the auras and removing existing eating spells
	}
	else   // cebernic: why not stand up
	{
		if(!p_User->CombatStatus.IsInCombat() && !p_User->IsMounted())
		{
			if(p_User->GetStandState())
			{
				p_User->SetStandState(STANDSTATE_STAND);
			}
		}
	}

	// cebernic: remove stealth on using item
	if(!(spellInfo->AuraInterruptFlags & ATTRIBUTESEX_NOT_BREAK_STEALTH))
	{
		if(p_User->IsStealth())
			p_User->RemoveAllAuraType(SPELL_AURA_MOD_STEALTH);
	}

	if(itemProto->RequiredLevel)
	{
		if(_player->getLevel() < itemProto->RequiredLevel)
		{
			_player->GetItemInterface()->BuildInventoryChangeError(tmpItem, NULL, INV_ERR_ITEM_RANK_NOT_ENOUGH);
			return;
		}
	}

	if(itemProto->RequiredSkill)
	{
		if(!_player->_HasSkillLine(itemProto->RequiredSkill))
		{
			_player->GetItemInterface()->BuildInventoryChangeError(tmpItem, NULL, INV_ERR_ITEM_RANK_NOT_ENOUGH);
			return;
		}

		if(itemProto->RequiredSkillRank)
		{
			if(_player->_GetSkillLineCurrent(itemProto->RequiredSkill, false) < itemProto->RequiredSkillRank)
			{
				_player->GetItemInterface()->BuildInventoryChangeError(tmpItem, NULL, INV_ERR_ITEM_RANK_NOT_ENOUGH);
				return;
			}
		}
	}

	if((itemProto->AllowableClass && !(_player->getClassMask() & itemProto->AllowableClass)) || (itemProto->AllowableRace && !(_player->getRaceMask() & itemProto->AllowableRace)))
	{
		_player->GetItemInterface()->BuildInventoryChangeError(tmpItem, NULL, INV_ERR_YOU_CAN_NEVER_USE_THAT_ITEM);
		return;
	}

	if(!_player->Cooldown_CanCast(spellInfo))
	{
		_player->SendCastResult(spellInfo->Id, SPELL_FAILED_NOT_READY, cn, 0);
		return;
	}


	if(_player->m_currentSpell)
	{
		_player->SendCastResult(spellInfo->Id, SPELL_FAILED_SPELL_IN_PROGRESS, cn, 0);
		return;
	}

	if(itemProto->ForcedPetId >= 0)
	{
		if(itemProto->ForcedPetId == 0)
		{
			if(_player->GetGUID() != targets.m_unitTarget)
			{
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_BAD_TARGETS, cn, 0);
				return;
			}
		}
		else
		{

			if(!_player->GetSummon() || _player->GetSummon()->GetEntry() != (uint32)itemProto->ForcedPetId)
			{
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_SPELL_IN_PROGRESS, cn, 0);
				return;
			}
		}
	}

	Spell* spell = sSpellFactoryMgr.NewSpell(_player, spellInfo, false, NULL);
	spell->extra_cast_number = cn;
	spell->i_caster = tmpItem;
	spell->m_glyphslot = glyphIndex;

	//GetPlayer()->setCurrentSpell(spell);
	spell->prepare(&targets);

#ifdef ENABLE_ACHIEVEMENTS
	_player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, itemProto->ItemId, 0, 0);
#endif

}
Пример #11
0
void WorldSession::HandleSpellClick(WorldPacket & recvPacket)
{
	CHECK_INWORLD_RETURN

	LOG_DETAIL("WORLD: got CMSG_SPELLCLICK packet, data length = %i", recvPacket.size());

	if(_player->getDeathState() == CORPSE)
		return;

	uint64 target_guid; // this will store the guid of the object we are going to use it's spell. There must be a dbc that indicates what spells a unit has

	recvPacket >> target_guid;

	//we have only 1 example atm for entry : 28605
	Unit* target_unit = _player->GetMapMgr()->GetUnit(target_guid);

	if(!target_unit)
		return;

	if( !_player->isInRange( target_unit, MAX_INTERACTION_RANGE ) )
		return;

	if( target_unit->IsVehicle() ){
		if( target_unit->GetVehicleComponent() != NULL )
			target_unit->GetVehicleComponent()->AddPassenger( _player );
		return;
	}

	uint32 creature_id = target_unit->GetEntry();
	uint32 cast_spell_id = 0;

	if(!_player->HasAurasWithNameHash(SPELL_HASH_LIGHTWELL_RENEW) && target_unit->RemoveAura(59907))
	{
		SpellClickSpell *sp = SpellClickSpellStorage.LookupEntry( creature_id );
		if( sp == NULL ){
			if( target_unit->IsCreature() ){
				Creature *c = TO< Creature* >( target_unit );
				
				sChatHandler.BlueSystemMessage( this, "NPC Id %u ( %s ) has no spellclick spell associated with it.", c->GetProto()->Id, c->GetCreatureInfo()->Name  );
				LOG_DETAIL("ERROR: Spellclick packet received for creature %u but there is no spell associated with it.", creature_id );
				return;
			}
		}

		cast_spell_id = sp->SpellID;

		target_unit->CastSpell(_player, cast_spell_id, true);

		if(!target_unit->HasAura(59907))
			TO_CREATURE(target_unit)->Despawn(0, 0); //IsCreature() check is not needed, refer to r2387 and r3230

		return;
	}
	
	SpellClickSpell *sp = SpellClickSpellStorage.LookupEntry( creature_id );
	if( sp == NULL ){
		if( target_unit->IsCreature() ){
			Creature *c = TO< Creature* >( target_unit );

			sChatHandler.BlueSystemMessage( this, "NPC Id %u ( %s ) has no spellclick spell associated with it.", c->GetProto()->Id, c->GetCreatureInfo()->Name  );
			LOG_DETAIL("ERROR: Spellclick packet received for creature %u but there is no spell associated with it.", creature_id );
			return;
		}
	}

	cast_spell_id = sp->SpellID;

	if(cast_spell_id == 0)
		return;

	SpellEntry* spellInfo = dbcSpell.LookupEntryForced(cast_spell_id);
	if(spellInfo == NULL)
		return;
	Spell* spell = sSpellFactoryMgr.NewSpell(_player, spellInfo, false, NULL);
	SpellCastTargets targets(target_guid);
	spell->prepare(&targets);
}
Пример #12
0
void WorldSession::HandleUseItemOpcode(WorldPackets::Spells::UseItem& packet)
{
    Player* user = _player;

    // ignore for remote control state
    if (user->m_mover != user)
        return;

    Item* item = user->GetUseableItemByPos(packet.PackSlot, packet.Slot);
    if (!item)
    {
        user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL);
        return;
    }

    if (item->GetGUID() != packet.CastItem)
    {
        user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL);
        return;
    }

    ItemTemplate const* proto = item->GetTemplate();
    if (!proto)
    {
        user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, NULL);
        return;
    }

    // some item classes can be used only in equipped state
    if (proto->GetInventoryType() != INVTYPE_NON_EQUIP && !item->IsEquipped())
    {
        user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, NULL);
        return;
    }

    InventoryResult msg = user->CanUseItem(item);
    if (msg != EQUIP_ERR_OK)
    {
        user->SendEquipError(msg, item, NULL);
        return;
    }

    // only allow conjured consumable, bandage, poisons (all should have the 2^21 item flag set in DB)
    if (proto->GetClass() == ITEM_CLASS_CONSUMABLE && !(proto->GetFlags() & ITEM_FLAG_USEABLE_IN_ARENA) && user->InArena())
    {
        user->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, item, NULL);
        return;
    }

    // don't allow items banned in arena
    if (proto->GetFlags() & ITEM_FLAG_NOT_USEABLE_IN_ARENA && user->InArena())
    {
        user->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, item, NULL);
        return;
    }

    if (user->IsInCombat())
    {
        for (uint32 i = 0; i < proto->Effects.size(); ++i)
        {
            if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(proto->Effects[i]->SpellID))
            {
                if (!spellInfo->CanBeUsedInCombat())
                {
                    user->SendEquipError(EQUIP_ERR_NOT_IN_COMBAT, item, NULL);
                    return;
                }
            }
        }
    }

    // check also  BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
    if (item->GetTemplate()->GetBonding() == BIND_WHEN_USE || item->GetTemplate()->GetBonding() == BIND_WHEN_PICKED_UP || item->GetTemplate()->GetBonding() == BIND_QUEST_ITEM)
    {
        if (!item->IsSoulBound())
        {
            item->SetState(ITEM_CHANGED, user);
            item->SetBinding(true);
        }
    }

    SpellCastTargets targets(user, packet.Cast);

    // Note: If script stop casting it must send appropriate data to client to prevent stuck item in gray state.
    if (!sScriptMgr->OnItemUse(user, item, targets))
    {
        // no script or script not process request by self
        user->CastItemUseSpell(item, targets, packet.Cast.CastID, packet.Cast.Misc);
    }
}
Пример #13
0
void WorldSession::HandleCastSpellOpcode(WorldPackets::Spells::CastSpell& cast)
{
    // ignore for remote control state (for player case)
    Unit* mover = _player->m_mover;
    if (mover != _player && mover->GetTypeId() == TYPEID_PLAYER)
        return;

    SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(cast.Cast.SpellID);
    if (!spellInfo)
    {
        TC_LOG_ERROR("network", "WORLD: unknown spell id %u", cast.Cast.SpellID);
        return;
    }

    if (spellInfo->IsPassive())
        return;

    Unit* caster = mover;
    if (caster->GetTypeId() == TYPEID_UNIT && !caster->ToCreature()->HasSpell(spellInfo->Id))
    {
        // If the vehicle creature does not have the spell but it allows the passenger to cast own spells
        // change caster to player and let him cast
        if (!_player->IsOnVehicle(caster) || spellInfo->CheckVehicle(_player) != SPELL_CAST_OK)
            return;

        caster = _player;
    }

    // check known spell or raid marker spell (which not requires player to know it)
    if (caster->GetTypeId() == TYPEID_PLAYER && !caster->ToPlayer()->HasActiveSpell(spellInfo->Id) && !spellInfo->HasEffect(SPELL_EFFECT_CHANGE_RAID_MARKER))
        return;

    // Check possible spell cast overrides
    spellInfo = caster->GetCastSpellInfo(spellInfo);

    // Client is resending autoshot cast opcode when other spell is cast during shoot rotation
    // Skip it to prevent "interrupt" message
    if (spellInfo->IsAutoRepeatRangedSpell() && caster->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL)
        && caster->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL)->m_spellInfo == spellInfo)
        return;

    // can't use our own spells when we're in possession of another unit,
    if (_player->isPossessing())
        return;

    // client provided targets
    SpellCastTargets targets(caster, cast.Cast);

    // auto-selection buff level base at target level (in spellInfo)
    if (targets.GetUnitTarget())
    {
        SpellInfo const* actualSpellInfo = spellInfo->GetAuraRankForLevel(targets.GetUnitTarget()->getLevel());

        // if rank not found then function return NULL but in explicit cast case original spell can be cast and later failed with appropriate error message
        if (actualSpellInfo)
            spellInfo = actualSpellInfo;
    }

    Spell* spell = new Spell(caster, spellInfo, TRIGGERED_NONE, ObjectGuid::Empty, false);
    spell->m_cast_count = cast.Cast.CastID;                         // set count of casts
    spell->m_misc.Raw.Data[0] = cast.Cast.Misc[0];
    spell->m_misc.Raw.Data[1] = cast.Cast.Misc[1];
    spell->prepare(&targets);
}
Пример #14
0
void Item::ApplyEnchantmentBonus(uint32 Slot, bool Apply)
{
    if (m_owner == NULL)
        return;

    EnchantmentMap::iterator itr = Enchantments.find(Slot);
    if (itr == Enchantments.end())
        return;

    EnchantEntry* Entry = itr->second.Enchantment;
    uint32 RandomSuffixAmount = itr->second.RandomSuffix;

    if (itr->second.BonusApplied == Apply)
        return;

    itr->second.BonusApplied = Apply;

    if (Apply)
    {
        // Send the enchantment time update packet.
        SendEnchantTimeUpdate(itr->second.Slot, itr->second.Duration);
    }

    // Apply the visual on the player.
    uint32 ItemSlot = m_owner->GetItemInterface()->GetInventorySlotByGuid(GetGUID()) * PLAYER_VISIBLE_ITEM_LENGTH;   //VLack: for 3.1.1 "* 18" is a bad idea, now it's "* 2"; but this could have been calculated based on UpdateFields.h! This is PLAYER_VISIBLE_ITEM_LENGTH
    uint32 VisibleBase = PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + ItemSlot;
    if (VisibleBase <= PLAYER_VISIBLE_ITEM_19_ENCHANTMENT)
        m_owner->SetUInt32Value(VisibleBase, Apply ? Entry->Id : 0);   //On 3.1 we can't add a Slot to the base now, as we no longer have multiple fields for storing them. This in some cases will try to write for example 3 visuals into one place, but now every item has only one field for this, and as we can't choose which visual to have, we'll accept the last one.
    else
        LOG_ERROR("Item::ApplyEnchantmentBonus visual out of range! Tried to address UInt32 field %i !!!", VisibleBase);

    // Another one of those for loop that where not indented properly god knows what will break
    // but i made it actually affect the code below it
    for (uint32 c = 0; c < 3; c++)
    {
        if (Entry->type[c])
        {
            // Depending on the enchantment type, take the appropriate course of action.
            switch (Entry->type[c])
            {
            case 1:         // Trigger spell on melee attack.
            {
                if (Apply)
                {
                    if (Entry->spell[c] != 0)
                        m_owner->AddProcTriggerSpell(Entry->spell[c], 0, m_owner->GetGUID(), Entry->min[c], PROC_ON_MELEE_ATTACK, 0, NULL, NULL, this);
                }
                else
                {
                    m_owner->RemoveProcTriggerSpell(Entry->spell[c], m_owner->GetGUID(), GetGUID());
                }
            }
                break;

            case 2:         // Mod damage done.
            {
                int32 val = Entry->min[c];
                if (RandomSuffixAmount)
                    val = RANDOM_SUFFIX_MAGIC_CALCULATION(RandomSuffixAmount, GetItemRandomSuffixFactor());

                if (Apply)
                    m_owner->ModPosDamageDoneMod(SCHOOL_NORMAL, val);
                else
                    m_owner->ModPosDamageDoneMod(SCHOOL_NORMAL, -val);
                m_owner->CalcDamage();
            }
                break;

            case 3:         // Cast spell (usually means apply aura)
            {
                if (Apply)
                {
                    SpellCastTargets targets(m_owner->GetGUID());
                    SpellEntry* sp;
                    Spell* spell;

                    if (Entry->spell[c] != 0)
                    {
                        sp = dbcSpell.LookupEntryForced(Entry->spell[c]);
                        if (sp == NULL)
                            continue;

                        spell = sSpellFactoryMgr.NewSpell(m_owner, sp, true, 0);
                        spell->i_caster = this;
                        spell->prepare(&targets);
                    }
                }
                else
                {
                    if (Entry->spell[c] != 0)
                        m_owner->RemoveAuraByItemGUID(Entry->spell[c], GetGUID());
                }
            }
                break;

            case 4:         // Modify physical resistance
            {
                int32 val = Entry->min[c];
                if (RandomSuffixAmount)
                    val = RANDOM_SUFFIX_MAGIC_CALCULATION(RandomSuffixAmount, GetItemRandomSuffixFactor());

                if (Apply)
                {
                    m_owner->FlatResistanceModifierPos[Entry->spell[c]] += val;
                }
                else
                {
                    m_owner->FlatResistanceModifierPos[Entry->spell[c]] -= val;
                }
                m_owner->CalcResistance(Entry->spell[c]);
            }
                break;

            case 5:     //Modify rating ...order is PLAYER_FIELD_COMBAT_RATING_1 and above
            {
                //spellid is enum ITEM_STAT_TYPE
                //min=max is amount
                int32 val = Entry->min[c];
                if (RandomSuffixAmount)
                    val = RANDOM_SUFFIX_MAGIC_CALCULATION(RandomSuffixAmount, GetItemRandomSuffixFactor());

                m_owner->ModifyBonuses(Entry->spell[c], val, Apply);
                m_owner->UpdateStats();
            }
                break;

            case 6:     // Rockbiter weapon (increase damage per second... how the hell do you calc that)
            {
                if (Apply)
                {
                    //m_owner->ModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, Entry->min[c]);
                    //if I'm not wrong then we should apply DMPS formula for this. This will have somewhat a larger value 28->34
                    int32 val = Entry->min[c];
                    if (RandomSuffixAmount)
                        val = RANDOM_SUFFIX_MAGIC_CALCULATION(RandomSuffixAmount, GetItemRandomSuffixFactor());

                    int32 value = GetProto()->Delay * val / 1000;
                    m_owner->ModPosDamageDoneMod(SCHOOL_NORMAL, value);
                }
                else
                {
                    int32 val = Entry->min[c];
                    if (RandomSuffixAmount)
                        val = RANDOM_SUFFIX_MAGIC_CALCULATION(RandomSuffixAmount, GetItemRandomSuffixFactor());

                    int32 value = -(int32)(GetProto()->Delay * val / 1000);
                    m_owner->ModPosDamageDoneMod(SCHOOL_NORMAL, value);
                }
                m_owner->CalcDamage();
            }
                break;

            case 7:
            {
                if (Apply)
                {
                    for (uint32 i = 0; i < 3; ++i)
                        OnUseSpellIDs[i] = Entry->spell[i];
                }
                else
                {
                    for (uint32 i = 0; i < 3; ++i)
                        OnUseSpellIDs[i] = 0;
                }
                break;
            }

            case 8:
            {
                // Adding a prismatic socket to belt, hands, etc is type 8, it has no bonus to apply HERE
                break;
            }

            default:
            {
                LOG_ERROR("Unknown enchantment type: %u (%u)", Entry->type[c], Entry->Id);
            }
                break;
            }
        }
    }
}
Пример #15
0
int BioScan::synchans( Id compartment, vector< Id >& ret )
{
	// "channel" msgs lead to SynChans as well HHChannels, so request
	// explicitly for former.
	return targets( compartment, "channel", ret, "SynChan" );
}
Пример #16
0
  static
  P2P_Compressed<typename Context::kernel_type>*
  make(Context& c, BoxPairIter first, BoxPairIter last) {
    typename Context::source_iterator first_source = c.source_begin();
    typename Context::source_iterator first_target = c.target_begin();

    unsigned num_targets = c.target_tree().bodies();
    //unsigned num_sources = c.source_tree().bodies();
    unsigned num_box_pairs = last - first;

    // Interaction list for each target box
    // (target_first,target_last) -> {(source_first, source_last), ...}
    // TODO: faster?
    typedef std::pair<unsigned, unsigned> upair;
    std::vector<std::vector<upair> > target2sources(num_targets);
    // A list of target ranges we've seen: {(target_first, target_last), ...}
    std::vector<upair> target_ranges;

    for ( ; first != last; ++first) {
      const typename BoxPairIter::value_type& bpair = *first;
      const typename Context::source_box_type& source_box = bpair.first;
      const typename Context::target_box_type& target_box = bpair.second;

      // Target boxes need to be leaf boxes because the computations are
      // grouped by disjoint target ranges
      // TODO: Generalize?
      FMMTL_ASSERT(target_box.is_leaf());

			// Target range
			unsigned i_begin = c.target_begin(target_box) - first_target;
      unsigned i_end   = c.target_end(target_box) - first_target;

			// Source range
			unsigned j_begin = c.source_begin(source_box) - first_source;
			unsigned j_end   = c.source_end(source_box) - first_source;

      // If this is the first time we've seen this target range
      if (target2sources[i_begin].empty())
        target_ranges.push_back(upair(i_begin, i_end));

      target2sources[i_begin].push_back(upair(j_begin,j_end));
    }

    unsigned num_target_ranges = target_ranges.size();

    // Construct a compressed interaction list
    std::vector<unsigned> target_ptr(num_target_ranges + 1);
    target_ptr[0] = 0;
    std::vector<upair> source_ranges(num_box_pairs);
    std::vector<upair>::iterator source_ranges_curr = source_ranges.begin();

    // For all the target ranges
    for (unsigned k = 0; k < num_target_ranges; ++k) {
      // Copy the source ranges that interact with the kth target range
      unsigned i_begin = target_ranges[k].first;
      source_ranges_curr = std::copy(target2sources[i_begin].begin(),
                                     target2sources[i_begin].end(),
                                     source_ranges_curr);

      // Record the stop index
      target_ptr[k+1] = source_ranges_curr - source_ranges.begin();
    }

    // Sanity checking
    FMMTL_ASSERT(target_ptr.back() == source_ranges.size());
    FMMTL_ASSERT(source_ranges_curr == source_ranges.end());

    // Copy the source and target ranges into contiguous vectors
    std::vector<source_type> sources(c.source_begin(), c.source_end());
    std::vector<target_type> targets(c.target_begin(), c.target_end());

    return new P2P_Compressed<Kernel>(target_ranges,
                                      target_ptr,
                                      source_ranges,
                                      sources,
                                      targets);
  }
Пример #17
0
int BioScan::leakageChannels( Id compartment, vector< Id >& ret )
{
    return targets( compartment, "channel", ret, "Leakage" );
}
Пример #18
0
 int LinearMatrix::targetCount() const
 {
    return targets().size();
 }
Пример #19
0
void createNToN(model::Node* router, int nodeNumber, glow::Dispatcher* dispatcher)
{
   auto nToN = new model::Node(nodeNumber, router, "nToN");
   nToN->setDescription("Non-Linear N:N");

   auto labels = new model::Node(1, nToN, "labels");
   auto targetLabels = new model::Node(1, labels, "targets");
   auto sourceLabels = new model::Node(2, labels, "sources");

   auto parameters = new model::Node(2, nToN, "parameters");
   auto targetParams = new model::Node(1, parameters, "targets");
   auto sourceParams = new model::Node(2, parameters, "sources");
   auto xpointParams = new model::Node(3, parameters, "connections");

   auto targets = model::matrix::Signal::Vector();
   auto sources = model::matrix::Signal::Vector();
   auto number = 0;

   for(int index = 0; index < 4; index++)
   {
      number += 3;

      auto targetLabel = new model::StringParameter(number, targetLabels, identOf("t", number), dispatcher);
      targetLabel->setValue(identOf("AES-T", number));
      targets.insert(targets.end(), new model::matrix::Signal(number));

      auto targetNode = new model::Node(number, targetParams, identOf("t", number));
      (new model::IntegerParameter(1, targetNode, "targetGain", dispatcher, -128, 15))->setValue(-64);
      (new model::StringParameter(2, targetNode, "targetMode", dispatcher))->setValue("something");

      auto sourceLabel = new model::StringParameter(number, sourceLabels, identOf("s", number), dispatcher);
      sourceLabel->setValue(identOf("AES-S", number));

      sources.insert(sources.end(), new model::matrix::Signal(number));
      auto sourceNode = new model::Node(number, sourceParams, identOf("s", number));
      (new model::IntegerParameter(1, sourceNode, "sourceGain", dispatcher, -128, 15))->setValue(-64);
   }

   auto const gainParameterNumber = 1;

   for(auto target : targets)
   {
      auto targetNode = new model::Node(target->number(), xpointParams, identOf("t", target->number()));

      for(auto source : sources)
      {
         auto sourceNode = new model::Node(source->number(), targetNode, identOf("s", source->number()));
         (new model::IntegerParameter(gainParameterNumber, sourceNode, "gain", dispatcher, -128, 15))->setValue(0);
      }
   }

   auto matrix = new model::matrix::NToNNonlinearMatrix(3, nToN, "matrix", dispatcher, targets.begin(), targets.end(), sources.begin(), sources.end());
   matrix->setLabelsPath(labels->path());
   matrix->setParametersPath(parameters->path());
   matrix->setGainParameterNumber(gainParameterNumber);

   for(auto target : matrix->targets())
   {
      if(target->number() % 2 == 0)
      {
         auto source = matrix->getSource(target->number());
         matrix->connect(target, &source, &source + 1, nullptr);
      }
   }
}
Пример #20
0
int BioScan::caDepend( Id channel, vector< Id >& ret )
{
	return targets( channel, "concen", ret, "CaConc" );
}
Пример #21
0
double CrossEntropyError::calculate_performance(const Vector<double>& parameters) const
{
    // Neural network stuff

    #ifdef __OPENNN_DEBUG__

    check();

    #endif

    // Cross-entropy error stuff

    #ifdef __OPENNN_DEBUG__

    std::ostringstream buffer;

    const size_t size = parameters.size();

    const size_t parameters_number = neural_network_pointer->count_parameters_number();

    if(size != parameters_number)
    {
       buffer << "OpenNN Exception: CrossEntropyError class." << std::endl
              << "double calculate_performance(const Vector<double>&) const method." << std::endl
              << "Size (" << size << ") must be equal to number of parameters (" << parameters_number << ")." << std::endl;

       throw std::logic_error(buffer.str());
    }

    #endif

    // Neural network stuff

    const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

    const size_t inputs_number = multilayer_perceptron_pointer->get_inputs_number();
    const size_t outputs_number = multilayer_perceptron_pointer->get_outputs_number();

    // Data set stuff

    const Instances& instances = data_set_pointer->get_instances();

    const size_t training_instances_number = instances.count_training_instances_number();

    const Vector<size_t> training_indices = instances.arrange_training_indices();

    size_t training_index;

    const Variables& variables = data_set_pointer->get_variables();

    const Vector<size_t> inputs_indices = variables.arrange_inputs_indices();
    const Vector<size_t> targets_indices = variables.arrange_targets_indices();

    // Cross-entropy error stuff

    Vector<double> inputs(inputs_number);
    Vector<double> outputs(outputs_number);
    Vector<double> targets(outputs_number);

    double cross_entropy_error = 0.0;

    int i = 0;

    #pragma omp parallel for private(i, training_index, inputs, outputs, targets) reduction(+ : cross_entropy_error)

    for(i = 0; i < (int)training_instances_number; i++)
    {
        training_index = training_indices[i];

       // Input vector

       inputs = data_set_pointer->get_instance(training_index, inputs_indices);

       // Output vector

       outputs = multilayer_perceptron_pointer->calculate_outputs(inputs, parameters);

       // Target vector

       targets = data_set_pointer->get_instance(training_index, targets_indices);

       // Cross-entropy error

       for(size_t j = 0; j < outputs_number; j++)
       {
           if(outputs[j] == 0.0)
           {
               outputs[j] = 1.0e-6;
           }
           else if(outputs[j] == 1)
           {
               outputs[j] = 0.99999;
           }

           cross_entropy_error -= targets[j]*log(outputs[j]) + (1.0 - targets[j])*log(1.0 - outputs[j]);
       }
    }

    return(cross_entropy_error);
}
Пример #22
0
int BioScan::children( Id compartment, vector< Id >& ret )
{
	return targets( compartment, "axial", ret, "Compartment" );
}
Пример #23
0
Vector<double> CrossEntropyError::calculate_gradient(void) const
{
   #ifdef __OPENNN_DEBUG__ 

   check();

   #endif

   // Neural network stuff

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   const size_t inputs_number = multilayer_perceptron_pointer->get_inputs_number();
   const size_t outputs_number = multilayer_perceptron_pointer->get_outputs_number();

   const size_t layers_number = multilayer_perceptron_pointer->get_layers_number();

   const size_t neural_parameters_number = multilayer_perceptron_pointer->count_parameters_number();

   const bool has_conditions_layer = neural_network_pointer->has_conditions_layer();

   const ConditionsLayer* conditions_layer_pointer = has_conditions_layer ? neural_network_pointer->get_conditions_layer_pointer() : NULL;

   #ifdef __OPENNN_DEBUG__ 

   std::ostringstream buffer;

   const Matrix<double> target_data = data_set_pointer->arrange_target_data();

   if(target_data < 0.0)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "Vector<double> calculate_gradient(void) const method.\n"
             << "Target data must be equal or greater than zero.\n";

      throw std::logic_error(buffer.str());
   }

   if(target_data > 1.0)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "Vector<double> calculate_gradient(void) const method.\n"
             << "Target data must be less or equal or than one.\n";

      throw std::logic_error(buffer.str());
   }

   #endif

   // Neural network stuff    

   Vector< Vector< Vector<double> > > first_order_forward_propagation(2); 

   Vector<double> particular_solution;
   Vector<double> homogeneous_solution;

   // Data set stuff

   const Instances& instances = data_set_pointer->get_instances();

   const size_t training_instances_number = instances.count_training_instances_number();

   const Vector<size_t> training_indices = instances.arrange_training_indices();

   size_t training_index;

   const Variables& variables = data_set_pointer->get_variables();

   const Vector<size_t> inputs_indices = variables.arrange_inputs_indices();
   const Vector<size_t> targets_indices = variables.arrange_targets_indices();

   Vector<double> inputs(inputs_number);
   Vector<double> targets(outputs_number);

   // Cross-entropy error stuff

   Vector<double> output_gradient(outputs_number);

   Vector< Vector<double> > layers_delta; 

   Vector<double> point_gradient(neural_parameters_number, 0.0);

   Vector<double> gradient(neural_parameters_number, 0.0);

   for(size_t i = 0; i < training_instances_number; i++)
   {
       training_index = training_indices[i];

      inputs = data_set_pointer->get_instance(training_index, inputs_indices);

      targets = data_set_pointer->get_instance(training_index, targets_indices);

      first_order_forward_propagation = multilayer_perceptron_pointer->calculate_first_order_forward_propagation(inputs);

      const Vector< Vector<double> >& layers_activation = first_order_forward_propagation[0];
      const Vector< Vector<double> >& layers_activation_derivative = first_order_forward_propagation[1];

      if(!has_conditions_layer)
      {
         const Vector<double>& outputs = layers_activation[layers_number-1];

         for(size_t j = 0; j < outputs_number; j++)
         {
             if(outputs[j] == 0.0)
             {
                 output_gradient[j] = -targets[j]/1.e-6 + (1.0 - targets[j])/(1.0 - 1.e-6);
             }
             else if(outputs[j] == 1.0)
             {
                 output_gradient[j] = -targets[j]/0.999999 + (1.0 - targets[j])/(1.0 - 0.999999);
             }
             else
             {
                output_gradient[j] = -targets[j]/outputs[j] + (1.0 - targets[j])/(1.0 - outputs[j]);
             }
         }

         layers_delta = calculate_layers_delta(layers_activation_derivative, output_gradient);
      }
      else
      {
         particular_solution = conditions_layer_pointer->calculate_particular_solution(inputs);
         homogeneous_solution = conditions_layer_pointer->calculate_homogeneous_solution(inputs);

         const Vector<double>& outputs = particular_solution + homogeneous_solution*layers_activation[layers_number-1];

         for(size_t j = 0; j < outputs_number; j++)
         {
             if(outputs[j] == 0.0)
             {
                 output_gradient[j] = -targets[j]/1.e-6 + (1.0 - targets[j])/(1.0 - 1.e-6);
             }
             else if(outputs[j] == 1.0)
             {
                 output_gradient[j] = -targets[j]/0.999999 + (1.0 - targets[j])/(1.0 - 0.999999);
             }
             else
             {
                output_gradient[j] = -targets[j]/outputs[j] + (1.0 - targets[j])/(1.0 - outputs[j]);
             }
         }

		 layers_delta = calculate_layers_delta(layers_activation_derivative, homogeneous_solution, output_gradient);
      }

      point_gradient = calculate_point_gradient(inputs, layers_activation, layers_delta);

      gradient += point_gradient;
   }

   return(gradient);
}
Пример #24
0
/**
 * Gives all channels (hhchannels, synchans, any other) attached to a given
 * compartment.
 */
int BioScan::channels( Id compartment, vector< Id >& ret )
{
	return targets( compartment, "channel", ret );
}
Пример #25
0
void Item::ApplyEnchantmentBonus( uint32 Slot, bool Apply )
{
    if( m_owner == NULL )
        return;

    EnchantmentMap::iterator itr = Enchantments.find( Slot );
    if( itr == Enchantments.end() )
        return;

    EnchantEntry* Entry = itr->second.Enchantment;
    uint32 RandomSuffixAmount = itr->second.RandomSuffix;

    if( itr->second.Dummy )
        return;

    if( itr->second.BonusApplied == Apply )
        return;

    itr->second.BonusApplied = Apply;

    // Apply the visual on the player.
    uint32 ItemSlot = m_owner->GetItemInterface()->GetInventorySlotByGuid( GetGUID() );
    if(ItemSlot < EQUIPMENT_SLOT_END && Slot < 1)
    {
        uint32 VisibleBase = PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + ItemSlot * PLAYER_VISIBLE_ITEM_LENGTH;
        m_owner->SetUInt16Value( VisibleBase, Slot, Apply ? Entry->Id : 0 );
    }

    if( Apply )
    {
        // Send the enchantment time update packet.
        SendEnchantTimeUpdate( itr->second.Slot, itr->second.Duration );
    }

    // Another one of those for loop that where not indented properly god knows what will break
    // but i made it actually affect the code below it
    for( uint32 c = 0; c < 3; c++ )
    {
        if( Entry->type[c] )
        {
            // Depending on the enchantment type, take the appropriate course of action.
            switch( Entry->type[c] )
            {
            case 1:      // Trigger spell on melee attack.
                {
                    if( Apply && Entry->spell[c] != 0 )
                    {
                        // Create a proc trigger spell
                        ProcTriggerSpell TS;
                        memset(&TS, 0, sizeof(ProcTriggerSpell));
                        TS.caster = m_owner->GetGUID();
                        TS.procFlags = PROC_ON_MELEE_ATTACK;
                        TS.origId = 0;
                        TS.procflags2 = 0;
                        TS.SpellClassMask[0] = 0;
                        TS.SpellClassMask[1] = 0;
                        TS.SpellClassMask[2] = 0;
                        TS.ProcType = 0;
                        TS.LastTrigger = 0;
                        TS.procValue = 0;
                        TS.procCharges = 0;
                        TS.procChance = 10;

                        if(ItemSlot == EQUIPMENT_SLOT_MAINHAND)
                            TS.weapon_damage_type = 1; // Proc only on main hand attacks
                        else if(ItemSlot == EQUIPMENT_SLOT_OFFHAND)
                            TS.weapon_damage_type = 2; // Proc only on off hand attacks
                        else
                            TS.weapon_damage_type = 0; // Doesn't depend on weapon

                        /* This needs to be modified based on the attack speed of the weapon.
                         * Secondly, need to assign some static chance for instant attacks (ss,
                         * gouge, etc.) */
                        if( GetProto()->Class == ITEM_CLASS_WEAPON )
                        {
                            if( !Entry->min[c] )
                            {
                                float speed = (float)GetProto()->Delay;

                                /////// procChance calc ///////
                                float ppm = 0;
                                SpellEntry* sp = dbcSpell.LookupEntry( Entry->spell[c] );
                                if( sp )
                                {
                                    switch( sp->NameHash )
                                    {
                                    case SPELL_HASH_FROSTBRAND_ATTACK:
                                        ppm = 9;
                                        break;
                                    }
                                }
                                if( ppm != 0 )
                                {
                                    float pcount = 60/ppm;
                                    float chance = (speed/10) / pcount;
                                    TS.procChance = (uint32)chance;
                                }
                                else
                                    TS.procChance = (uint32)( speed / 600.0f );
                                ///////////////////////////////
                            }
                            else
                                TS.procChance = Entry->min[c];
                        }

                        sLog.Debug( "Enchant", "Setting procChance to %u%%.", TS.procChance );
                        TS.deleted = false;
                        TS.spellId = Entry->spell[c];
                        m_owner->m_procSpells.push_back( TS );
                    }
                    else
                    {
                        // Remove the proctriggerspell
                        uint32 SpellId;
                        list< struct ProcTriggerSpell >::iterator itr/*, itr2*/;
                        for( itr = m_owner->m_procSpells.begin(); itr != m_owner->m_procSpells.end(); )
                        {
                            SpellId = itr->spellId;
                            /*itr2 = itr;*/
                            /*++itr;*/

                            if( SpellId == Entry->spell[c] )
                            {
                                //m_owner->m_procSpells.erase(itr2);
                                itr->deleted = true;
                            }
                            ++itr;
                        }
                    }
                }break;

            case 2:      // Mod damage done.
                {
                    int32 val = Entry->min[c];
                    if( RandomSuffixAmount )
                        val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

                    if( Apply )
                        m_owner->DamageDonePosMod[0] += val;
                    else
                        m_owner->DamageDonePosMod[0] -= val;
                    m_owner->UpdateStats();
                }break;

            case 3:      // Cast spell (usually means apply aura)
                {
                    if( Apply )
                    {
                        SpellCastTargets targets( m_owner->GetGUID() );
                        SpellEntry* sp;

                        if( Entry->spell[c] != 0 )
                        {
                            sp = dbcSpell.LookupEntryForced( Entry->spell[c] );
                            if( sp == NULL )
                                continue;

                            Spell* spell = NULLSPELL;
                            //Never found out why,
                            //but this Blade of Life's Inevitability spell must be casted by the item, not owner.
                            if( m_itemProto->ItemId != 34349  )
                                spell = (new Spell( m_owner, sp, true, NULLAURA ));
                            else
                                spell = (new Spell( TO_ITEM(this), sp, true, NULLAURA ));

                            spell->i_caster = TO_ITEM(this);
                            spell->prepare( &targets );
                        }
                    }
                    else
                    {
                        if( Entry->spell[c] != 0 )
                            m_owner->RemoveAura( Entry->spell[c] );
                    }
                }break;

            case 4:      // Modify physical resistance
                {
                    int32 val = Entry->min[c];
                    if( RandomSuffixAmount )
                        val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

                    if( Apply )
                        m_owner->FlatResistanceModifierPos[Entry->spell[c]] += val;
                    else
                        m_owner->FlatResistanceModifierPos[Entry->spell[c]] -= val;
                    m_owner->CalcResistance( Entry->spell[c] );
                }break;

            case 5:  //Modify rating ...order is PLAYER_FIELD_COMBAT_RATING_1 and above
                {
                    //spellid is enum ITEM_STAT_TYPE
                    //min=max is amount
                    int32 val = Entry->min[c];
                    if( RandomSuffixAmount )
                        val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

                    m_owner->ModifyBonuses( Entry->spell[c], Apply ? val : -val );
                }break;

            case 6:  // Rockbiter weapon (increase damage per second... how the hell do you calc that)
                {
                    if( Apply )
                    {
                        //if i'm not wrong then we should apply DMPS formula for this. This will have somewhat a larger value 28->34
                        int32 val = Entry->min[c];
                        if( RandomSuffixAmount )
                            val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

                        //int32 value = GetProto()->Delay * val / 1000;
                        m_owner->DamageDonePosMod[0] += val;
                    }
                    else
                    {
                        int32 val = Entry->min[c];
                        if( RandomSuffixAmount )
                            val = RANDOM_SUFFIX_MAGIC_CALCULATION( RandomSuffixAmount, GetItemRandomSuffixFactor() );

                        //int32 value =- (int32)(GetProto()->Delay * val / 1000 );
                        m_owner->DamageDonePosMod[0] += val;
                    }
                    m_owner->UpdateStats();
                }break;

            case 7:
                {
                    if( Apply )
                    {
                        for( uint32 i = 0; i < 3; ++i )
                            OnUseSpells[ i ] = Entry->spell[ i ];
                    }
                    else
                    {
                        for( uint32 i = 0; i < 3; ++i )
                            OnUseSpells[ i ] = 0;
                    }
                }break;

            case 8:{}break;

            default:
                {
                    sLog.Debug( "Enchant","Unknown enchantment type: %u (%u)", Entry->type[c], Entry->Id );
                }break;
            }
        }
    }
}
Пример #26
0
int BioScan::hhchannels( Id compartment, vector< Id >& ret )
{
	// Request for elements of type "HHChannel" only since
	// channel messages can lead to synchans as well.
	return targets( compartment, "channel", ret, "HHChannel" );
}
Пример #27
0
void ArathiBasin::HookOnAreaTrigger(Player * plr, uint32 id)
{
	uint32 spellid= 0;
	int32 buffslot = -1;
	switch(id)
	{
	case 3866:			// stables
		buffslot=AB_BUFF_STABLES;
		break;

	case 3867:			// farm
		buffslot=AB_BUFF_FARM;		
		break;

	case 3870:			// blacksmith
		buffslot=AB_BUFF_BLACKSMITH;
		break;

	case 3869:			// mine
		buffslot=AB_BUFF_MINE;
		break;

	case 3868:			// lumbermill
		buffslot=AB_BUFF_LUMBERMILL;
		break;

	case 3948:			// alliance/horde exits
	case 3949:
		{
			RemovePlayer(plr,false);
			return;
		}break;
	case 4020:			// Trollbane Hall
	case 4021:			// Defiler's Den
		return;
		break;
	default:
		Log.Error("ArathiBasin", "Encountered unhandled areatrigger id %u", id);
		return;
		break;
	}

	if(plr->IsDead())		// don't apply to dead players... :P
		return;	

	uint32 x = (uint32)buffslot;
	if(m_buffs[x] && m_buffs[x]->IsInWorld())
	{
		// apply the spell
		spellid = m_buffs[x]->GetInfo()->sound3;
		m_buffs[x]->RemoveFromWorld(false);

		// respawn it in buffrespawntime
		sEventMgr.AddEvent(this,&ArathiBasin::SpawnBuff,x,EVENT_AB_RESPAWN_BUFF,AB_BUFF_RESPAWN_TIME,1,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);

		// cast the spell on the player
		SpellEntry * sp = dbcSpell.LookupEntryForced(spellid);
		if(sp)
		{
			Spell * pSpell = new Spell(plr, sp, true, NULL);
			SpellCastTargets targets(plr->GetGUID());
			pSpell->prepare(&targets);
		}
	}
}
Пример #28
0
int BioScan::spikegens( Id compartment, vector< Id >& ret )
{
	return targets( compartment, "VmSrc", ret, "SpikeGen" );
}
Пример #29
0
void WarsongGulch::HookFlagDrop(Player * plr, GameObject * obj)
{
	/* picking up a dropped flag */
	if(m_dropFlags[plr->GetTeam()] != obj)
	{
		/* are we returning it? */
		if( (obj->GetEntry() == 179785 && plr->IsTeamAlliance()) ||
			(obj->GetEntry() == 179786 && plr->IsTeamHorde()) )
		{
			uint32 x = plr->GetTeam() ? 0 : 1;
			sEventMgr.RemoveEvents(this, EVENT_BATTLEGROUND_WSG_AUTO_RETURN_FLAG + (plr->IsTeamHorde() ? TEAM_ALLIANCE : TEAM_HORDE));

			if( m_dropFlags[x]->IsInWorld() )
				m_dropFlags[x]->RemoveFromWorld(false);

			if(m_homeFlags[x]->IsInWorld() == false)
				m_homeFlags[x]->PushToWorld(m_mapMgr);

			plr->m_bgScore.MiscData[BG_SCORE_WSG_FLAGS_RETURNED]++;
			UpdatePvPData();

			if( plr->IsTeamHorde() )
				SendChatMessage( CHAT_MSG_BG_EVENT_HORDE, plr->GetGUID(), "The Horde flag was returned to its base by %s!", plr->GetName() );
			else
				SendChatMessage( CHAT_MSG_BG_EVENT_ALLIANCE, plr->GetGUID(), "The Alliance flag was returned to its base by %s!", plr->GetName() );

			SetWorldState(plr->IsTeamHorde() ? WSG_ALLIANCE_FLAG_CAPTURED : WSG_HORDE_FLAG_CAPTURED, 1);
			PlaySoundToAll(plr->IsTeamHorde() ? SOUND_HORDE_RETURNED : SOUND_ALLIANCE_RETURNED);
		}
		return;
	}

	map<uint32,uint32>::iterator itr = plr->m_forcedReactions.find(1059);
	if (itr != plr->m_forcedReactions.end()) {
		return;
	}

	if( plr->IsTeamAlliance() )
		sEventMgr.RemoveEvents(this, EVENT_BATTLEGROUND_WSG_AUTO_RETURN_FLAG);
	else
		sEventMgr.RemoveEvents(this, EVENT_BATTLEGROUND_WSG_AUTO_RETURN_FLAG + 1);

	if( m_dropFlags[plr->GetTeam()]->IsInWorld() )
		m_dropFlags[plr->GetTeam()]->RemoveFromWorld(false);

	m_flagHolders[plr->GetTeam()] = plr->GetLowGUID();
	plr->m_bgHasFlag = true;

	/* This is *really* strange. Even though the A9 create sent to the client is exactly the same as the first one, if
	 * you spawn and despawn it, then spawn it again it will not show. So we'll assign it a new guid, hopefully that
	 * will work.
	 * - Burlex
	 */
	m_dropFlags[plr->GetTeam()]->SetNewGuid(m_mapMgr->GenerateGameobjectGuid());
	
	SpellEntry * pSp = dbcSpell.LookupEntry(23333 + (plr->GetTeam() * 2));
	Spell * sp = new Spell(plr, pSp, true, 0);
	SpellCastTargets targets(plr->GetGUID());
	sp->prepare(&targets);
	SetWorldState(plr->IsTeamHorde() ? WSG_ALLIANCE_FLAG_CAPTURED : WSG_HORDE_FLAG_CAPTURED, 2);
	if( plr->IsTeamHorde() )
		SendChatMessage( CHAT_MSG_BG_EVENT_HORDE, plr->GetGUID(), "The Alliance's flag has been taken by %s !", plr->GetName() );
	else
		SendChatMessage( CHAT_MSG_BG_EVENT_ALLIANCE, plr->GetGUID(), "The Horde's flag has been taken by %s !", plr->GetName() );
}
Пример #30
0
void WorldSession::HandleCastSpellOpcode(WorldPacket& recvPacket)
{
	CHECK_INWORLD_RETURN;
	if(_player->getDeathState()==CORPSE)
		return;

	uint32 spellId;
	uint8 cn, unk; // 3.0.2 unk

	recvPacket >> cn >> spellId  >> unk;
	if(!spellId)
	{
		OUT_DEBUG("WORLD: unknown spell id %i\n", spellId);
		return;
	}
	// check for spell id
	SpellEntry *spellInfo = dbcSpell.LookupEntryForced(spellId);

	if(!spellInfo || !sHookInterface.OnCastSpell(_player, spellInfo))
	{
		OUT_DEBUG("WORLD: unknown spell id %i\n", spellId);
		return;
	}

	OUT_DEBUG("WORLD: got cast spell packet, spellId - %i (%s), data length = %i",
		spellId, spellInfo->Name, recvPacket.size());
	
	// Cheat Detection only if player and not from an item
	// this could f**k up things but meh it's needed ALOT of the newbs are using WPE now
	// WPE allows them to mod the outgoing packet and basicly choose what ever spell they want :(

	if( !GetPlayer()->HasSpell(spellId) || spellInfo->Attributes & ATTRIBUTES_PASSIVE )
	{
		// Some spells the player doesn't actually know, but are given to him by his current shapeshift.
		// These spells should be allowed to be cast.
		uint8 shapeshift = GetPlayer()->GetShapeShift();
		SpellShapeshiftForm * ssf = dbcSpellShapeshiftForm.LookupEntryForced(shapeshift);
		if(!ssf) return;

		bool ok = false;
		for(uint8 i = 0; i < 7; ++i)
			if( ssf->spells[i] == spellId)
				ok = true;

		if( !ok )
			return;
	}

	if (GetPlayer()->GetOnMeleeSpell() != spellId)
	{
		//autoshot 75
		if((spellInfo->Flags3 & FLAGS3_ACTIVATE_AUTO_SHOT) /*spellInfo->Attributes == 327698*/)	// auto shot..
		{
			//sLog.outString( "HandleSpellCast: Auto Shot-type spell cast (id %u, name %s)" , spellInfo->Id , spellInfo->Name );
			ItemPointer weapon = GetPlayer()->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_RANGED);
			if(!weapon) 
				return;
			uint32 spellid;
			switch(weapon->GetProto()->SubClass)
			{
			case 2:			 // bows
			case 3:			 // guns
            case 18:		 // crossbow
				spellid = SPELL_RANGED_GENERAL;
				break;
			case 16:			// thrown
				spellid = SPELL_RANGED_THROW;
				break;
			case 19:			// wands
				spellid = SPELL_RANGED_WAND;
				break;
			default:
				spellid = 0;
				break;
			}
		   
			if(!spellid) 
				spellid = spellInfo->Id;
			
			if(!_player->m_onAutoShot)
			{
				_player->m_AutoShotTarget = _player->GetSelection();
				uint32 duration = _player->GetUInt32Value(UNIT_FIELD_RANGEDATTACKTIME);
				SpellCastTargets targets(recvPacket,GetPlayer()->GetGUID());
				if(!targets.m_unitTarget)
				{
					sLog.outString( "Cancelling auto-shot cast because targets.m_unitTarget is null!" );
					return;
				}
				SpellEntry *sp = dbcSpell.LookupEntry(spellid);
			
				_player->m_AutoShotSpell = sp;
				_player->m_AutoShotDuration = duration;
				//This will fix fast clicks
				if(_player->m_AutoShotAttackTimer < 500)
					_player->m_AutoShotAttackTimer = 500;
				_player->m_onAutoShot = true;
			}

			return;
		}

        if(_player->m_currentSpell)
        {
			if( _player->m_currentSpell->getState() == SPELL_STATE_CASTING )
			{
				// cancel the existing channel spell, cast this one
				_player->m_currentSpell->cancel();
			}
			else
			{
				// send the error message
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_SPELL_IN_PROGRESS, cn, 0);
				return;
			}
        }

		SpellCastTargets targets(recvPacket,GetPlayer()->GetGUID());

		// some anticheat stuff
		if( spellInfo->self_cast_only )
		{
			if( targets.m_unitTarget && targets.m_unitTarget != _player->GetGUID() )
			{
				// send the error message
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_BAD_TARGETS, cn, 0);
				return;
			}
		}

		if( targets.m_unitTarget && GetPlayer()->GetMapMgr() && spellInfo->c_is_flags & SPELL_FLAG_IS_DAMAGING )
		{
			UnitPointer pUnit = GetPlayer()->GetMapMgr()->GetUnit( targets.m_unitTarget );
			if( pUnit && pUnit != GetPlayer() && !isAttackable( GetPlayer(), pUnit, false ) && !pUnit->IsInRangeOppFactSet(GetPlayer()) && !pUnit->CombatStatus.DidDamageTo(GetPlayer()->GetGUID()))
			{
				//GetPlayer()->BroadcastMessage("Faction exploit detected. You will be disconnected in 5 seconds.");
				//GetPlayer()->Kick(5000);
				// Just cancel the cast
				_player->SendCastResult(spellInfo->Id, SPELL_FAILED_BAD_TARGETS, cn, 0);
				return;
			}
		}

		SpellPointer spell(new Spell(GetPlayer(), spellInfo, false, NULLAURA));
		spell->extra_cast_number=cn;
		spell->prepare(&targets);
	}
}