prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>bibmerge_merger.py<|end_file_name|><|fim▁begin|>## This file is part of Invenio. ## Copyright (C) 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # pylint: disable=C0103 from invenio.bibrecord import record_has_field, \ record_get_field_instances, \ record_delete_field, \ record_add_fields from invenio.bibmerge_differ import record_field_diff, match_subfields, \ diff_subfields from copy import deepcopy def merge_record(rec1, rec2, merge_conflicting_fields=False): """Merges all non-conflicting fields from 'rec2' to 'rec1' @param rec1: First record (a record dictionary structure)<|fim▁hole|> """ for fnum in rec2: if fnum[:2] != "00": #if it's not a controlfield merge_field_group(rec1, rec2, fnum, merge_conflicting_fields=merge_conflicting_fields) def merge_field_group(rec1, rec2, fnum, ind1='', ind2='', merge_conflicting_fields=False): """Merges non-conflicting fields from 'rec2' to 'rec1' for a specific tag. the second record. @param rec1: First record (a record dictionary structure) @param rec2: Second record (a record dictionary structure) @param fnum: a 3 characters long string indicating field tag number @param ind1: a 1 character long string @param ind2: a 1 character long string @param merge_conflicting_fields: whether to merge conflicting fields or not """ ### Check if merging goes for all indicators and set a boolean merging_all_indicators = not ind1 and not ind2 ### check if there is no field in rec2 to be merged in rec1 if not record_has_field(rec2, fnum): return ### get fields of rec2 if merging_all_indicators: fields2 = record_get_field_instances(rec2, fnum, '%', '%') else: fields2 = record_get_field_instances(rec2, fnum, ind1, ind2) if len(fields2)==0: return ### check if field in rec1 doesn't even exist if not record_has_field(rec1, fnum): record_add_fields(rec1, fnum, fields2) return ### compare the fields, get diffs for given indicators alldiffs = record_field_diff(rec1[fnum], rec2[fnum], fnum, match_subfields, ind1, ind2) ### check if fields are the same if alldiffs is None: return #nothing to merge ### find the diffing for the fields of the given indicators alldiffs = alldiffs[1] #keep only the list of diffs by indicators (without the 'c') if merging_all_indicators: #combine the diffs for each indicator to one list diff = _combine_diffs(alldiffs) else: #diffing for one indicator for diff in alldiffs: #look for indicator pair in diff result if diff[0] == (ind1, ind2): break else: raise Exception, "Indicators not in diff result." diff = diff[1] #keep only the list of diffs (without the indicator tuple) ### proceed to merging fields in a new field list fields1, fields2 = rec1[fnum], rec2[fnum] new_fields = [] if merge_conflicting_fields == False: #merge non-conflicting fields for m in diff: #for every match of fields in the diff if m[0] is not None: #if rec1 has a field in the diff, keep it new_fields.append( deepcopy(fields1[m[0]]) ) else: #else take the field from rec2 new_fields.append( deepcopy(fields2[m[1]]) ) else: #merge all fields for m in diff: #for every match of fields in the diff if m[1] is not None: #if rec2 has a field, add it new_fields.append( deepcopy(fields2[m[1]]) ) if m[0] is not None and fields1[m[0]][0] != fields2[m[1]][0]: #if the fields are not the same then add the field of rec1 new_fields.append( deepcopy(fields1[m[0]]) ) else: new_fields.append( deepcopy(fields1[m[0]]) ) ### delete existing fields record_delete_field(rec1, fnum, ind1, ind2) ## find where the new_fields should be inserted in rec1 (insert_index) if merging_all_indicators: insert_index = 0 else: insert_index = None ind_pair = (ind1, ind2) first_last_dict = _first_and_last_index_for_each_indicator( rec1.get(fnum, []) ) #find the indicator pair which is just before the one which will be inserted indicators = first_last_dict.keys() indicators.sort() ind_pair_before = None for pair in indicators: if pair > ind_pair: break else: ind_pair_before = pair if ind_pair_before is None: #if no smaller indicator pair exists insert_index = 0 #insertion will take place at the beginning else: #else insert after the last field index of the previous indicator pair insert_index = first_last_dict[ind_pair_before][1] + 1 ### add the new (merged) fields in correct 'in_field_index' position record_add_fields(rec1, fnum, new_fields, insert_index) return def _combine_diffs(alldiffs): """Takes all diffs of a field-tag which are separated by indicators and combine them in one list in correct index order.""" diff = [] for d in alldiffs: diff.extend( d[1] ) return diff def _first_and_last_index_for_each_indicator(fields): """return a dictionary with indicator pair tuples as keys and a pair as value that contains the first and the last in_field_index of the fields that have the specific indicators. Useful to find where to insert new fields.""" result = {} for index, field in enumerate(fields): indicators = (field[1], field[2]) if indicators not in result: #create first-last pair for indicator pair result[indicators] = [index, index] else: #if there is a first-last pair already, update the 'last' index result[indicators][1] = index return result def add_field(rec1, rec2, fnum, findex1, findex2): """Adds the field of rec2 into rec1 in a position that depends on the diffing of rec1 with rec2. @param rec1: First record (a record dictionary structure) @param rec2: Second record (a record dictionary structure) @param fnum: a 3 characters long string indicating field tag number @param findex1: the rec1 field position in the group of fields it belongs @param findex2: the rec2 field position in the group of fields it belongs """ field_to_add = rec2[fnum][findex2] ### if findex1 indicates an existing field in rec1, insert the field of rec2 ### before the field of rec1 if findex1 is not None: record_add_fields(rec1, fnum, [field_to_add], findex1) return ### check if field tag does not exist in record1 if not record_has_field(rec1, fnum): record_add_fields(rec1, fnum, [field_to_add]) #insert at the beginning return ### if findex1 is None and the fieldtag already exists #get diffs for all indicators of the field. alldiffs = record_field_diff(rec1[fnum], rec2[fnum], fnum, match_subfields) alldiffs = alldiffs[1] #keep only the list of diffs by indicators (without the 'c') diff = _combine_diffs(alldiffs) #combine results in one list #find the position of the field after which the insertion should take place findex1 = -1 for m in diff: if m[1] == findex2: break if m[0] is not None: findex1 = m[0] #finally add the field (one position after) record_add_fields(rec1, fnum, [field_to_add], findex1+1) def replace_field(rec1, rec2, fnum, findex1, findex2): """Replaces the contents of a field of rec1 with those of rec2. @param rec1: First record (a record dictionary structure) @param rec2: Second record (a record dictionary structure) @param fnum: a 3 characters long string indicating field tag number @param findex1: the rec1 field position in the group of fields it belongs @param findex2: the rec2 field position in the group of fields it belongs """ #if there is no field in rec1 to replace, just add a new one if findex1 is None: add_field(rec1, rec2, fnum, findex1, findex2) return #replace list of subfields from rec2 to rec1 for i in range( len(rec1[fnum][findex1][0]) ): rec1[fnum][findex1][0].pop() rec1[fnum][findex1][0].extend(rec2[fnum][findex2][0]) def merge_field(rec1, rec2, fnum, findex1, findex2): """Merges the contents of a field of rec1 with those of rec2, inserting them in the place of the field of rec1. @param rec1: First record (a record dictionary structure) @param rec2: Second record (a record dictionary structure) @param fnum: a 3 characters long string indicating field tag number @param findex1: the rec1 field position in the group of fields it belongs @param findex2: the rec2 field position in the group of fields it belongs """ #if there is no field in rec1 to merge to, just add a new one if findex1 is None: add_field(rec1, rec2, fnum, findex1, findex2) return field1 = rec1[fnum][findex1] sflist1 = field1[0] sflist2 = rec2[fnum][findex2][0] # diff the subfields diffs = diff_subfields(sflist1, sflist2) #merge subfields of field1 with those of field2 new_sflist = [] #for every match in the diff append the subfields of both fields for m in diffs: if m[1] is not None: new_sflist.append( sflist2[m[1]] ) #append the subfield if m[2] != 1.0 and m[0] is not None: new_sflist.append( sflist1[m[0]] ) #replace list of subfields of rec1 with the new one for i in range( len(sflist1) ): sflist1.pop() sflist1.extend(new_sflist) def delete_field(rec, fnum, findex): """Delete a specific field. @param rec: a record dictionary structure @param fnum: a 3 characters long string indicating field tag number @param findex: the rec field position in the group of fields it belongs """ record_delete_field(rec, fnum, field_position_local=findex) def delete_subfield(rec, fnum, findex, sfindex): """Delete a specific subfield. @param rec: a record dictionary structure @param fnum: a 3 characters long string indicating field tag number @param findex: the rec field position in the group of fields it belongs @param sfindex: the index position of the subfield in the field """ field = rec[fnum][findex] subfields = field[0] if len(subfields) > 1: del subfields[sfindex] def replace_subfield(rec1, rec2, fnum, findex1, findex2, sfindex1, sfindex2): """Replaces a subfield of rec1 with a subfield of rec2. @param rec1: First record (a record dictionary structure) @param rec2: Second record (a record dictionary structure) @param fnum: a 3 characters long string indicating field tag number @param findex1: the rec1 field position in the group of fields it belongs @param findex2: the rec2 field position in the group of fields it belongs @param sfindex1: the index position of the subfield in the field of rec1 @param sfindex2: the index position of the subfield in the field of rec2 """ subfields1 = rec1[fnum][findex1][0] subfields2 = rec2[fnum][findex2][0] subfields1[sfindex1] = subfields2[sfindex2] def add_subfield(rec1, rec2, fnum, findex1, findex2, sfindex1, sfindex2): """Adds a subfield of rec2 in a field of rec1, before or after sfindex1. @param rec1: First record (a record dictionary structure) @param rec2: Second record (a record dictionary structure) @param fnum: a 3 characters long string indicating field tag number @param findex1: the rec1 field position in the group of fields it belongs @param findex2: the rec2 field position in the group of fields it belongs @param sfindex1: the index position of the subfield in the field of rec1 @param sfindex2: the index position of the subfield in the field of rec2 """ subfield_to_insert = rec2[fnum][findex2][0][sfindex2] #insert at the sfindex1 position subfields1 = rec1[fnum][findex1][0] subfields1[sfindex1:sfindex1] = [ subfield_to_insert ] def copy_R2_to_R1(rec1, rec2): """Copies contents of R2 to R1 apart from the controlfields.""" tmprec = deepcopy(rec1) for fnum in tmprec: if fnum[:2] != '00': #if it's not a control field delete it from rec1 del rec1[fnum] for fnum in rec2: if fnum[:2] != '00': #if it's not a control field add it to rec2 rec1[fnum] = rec2[fnum]<|fim▁end|>
@param rec2: Second record (a record dictionary structure)
<|file_name|>id.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. use safe_nd::{AppFullId, ClientFullId, PublicId, PublicKey, Signature}; use std::sync::Arc; /// An enum representing the Full Id variants for a Client or App. #[derive(Clone)] pub enum SafeKey { /// Represents an application authorised by a client. App(Arc<AppFullId>), /// Represents a network client. Client(Arc<ClientFullId>), } impl SafeKey { /// Creates a client full ID. pub fn client(full_id: ClientFullId) -> Self { Self::Client(Arc::new(full_id)) } /// Creates an app full ID. pub fn app(full_id: AppFullId) -> Self { Self::App(Arc::new(full_id)) } /// Signs a given message using the App / Client full id as required. pub fn sign(&self, msg: &[u8]) -> Signature { match self { Self::App(app_full_id) => app_full_id.sign(msg), Self::Client(client_full_id) => client_full_id.sign(msg),<|fim▁hole|> } /// Returns a corresponding public ID. pub fn public_id(&self) -> PublicId { match self { Self::App(app_full_id) => PublicId::App(app_full_id.public_id().clone()), Self::Client(client_full_id) => PublicId::Client(client_full_id.public_id().clone()), } } /// Returns a corresponding public key. pub fn public_key(&self) -> PublicKey { match self { Self::App(app_full_id) => *app_full_id.public_id().public_key(), Self::Client(client_full_id) => *client_full_id.public_id().public_key(), } } }<|fim▁end|>
}
<|file_name|>SummaryBudgets.java<|end_file_name|><|fim▁begin|>package com.google.api.ads.adwords.jaxws.v201406.video; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import com.google.api.ads.adwords.jaxws.v201406.cm.Money; /** * * Class representing the various summary budgets for a campaign page. * * * <p>Java class for SummaryBudgets complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SummaryBudgets"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="totalVideoBudget" type="{https://adwords.google.com/api/adwords/video/v201406}VideoBudget" minOccurs="0"/> * &lt;element name="nonVideoBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/> * &lt;element name="combinedBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SummaryBudgets", propOrder = { "totalVideoBudget", "nonVideoBudget", "combinedBudget" }) public class SummaryBudgets { protected VideoBudget totalVideoBudget; protected Money nonVideoBudget; protected Money combinedBudget; /** * Gets the value of the totalVideoBudget property. * * @return * possible object is * {@link VideoBudget } * */ public VideoBudget getTotalVideoBudget() { return totalVideoBudget; } /** * Sets the value of the totalVideoBudget property. * * @param value * allowed object is * {@link VideoBudget } * */ public void setTotalVideoBudget(VideoBudget value) { this.totalVideoBudget = value; } /** * Gets the value of the nonVideoBudget property. * * @return * possible object is * {@link Money } * */ public Money getNonVideoBudget() { return nonVideoBudget; } /** * Sets the value of the nonVideoBudget property. * * @param value * allowed object is * {@link Money } * */ public void setNonVideoBudget(Money value) { this.nonVideoBudget = value; } /** * Gets the value of the combinedBudget property. * * @return * possible object is * {@link Money } * */ public Money getCombinedBudget() { return combinedBudget; } /** * Sets the value of the combinedBudget property.<|fim▁hole|> * * @param value * allowed object is * {@link Money } * */ public void setCombinedBudget(Money value) { this.combinedBudget = value; } }<|fim▁end|>
<|file_name|>test_revision_diffing.py<|end_file_name|><|fim▁begin|># Copyright 2017 AT&T Intellectual Property. All other rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy from deckhand.db.sqlalchemy import api as db_api from deckhand.tests import test_utils from deckhand.tests.unit.db import base class TestRevisionDiffing(base.TestDbBase): def _verify_buckets_status(self, revision_id, comparison_revision_id, expected): # Verify that actual and expected results match, despite the order of # `comparison_revision_id` and `revision_id` args. revision_ids = [revision_id, comparison_revision_id] for rev_ids in (revision_ids, reversed(revision_ids)): actual = db_api.revision_diff(*rev_ids) self.assertEqual(expected, actual) def test_revision_diff_null(self): self._verify_buckets_status(0, 0, {}) def test_revision_diff_created(self): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) bucket_name = test_utils.rand_name('bucket') documents = self.create_documents(bucket_name, payload) revision_id = documents[0]['revision_id'] self._verify_buckets_status( 0, revision_id, {bucket_name: 'created'}) def test_revision_diff_multi_bucket_created(self): revision_ids = [] bucket_names = [] for _ in range(3): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) bucket_name = test_utils.rand_name('bucket') bucket_names.append(bucket_name) documents = self.create_documents(bucket_name, payload) revision_id = documents[0]['revision_id'] revision_ids.append(revision_id) # Between revision 1 and 0, 1 bucket is created. self._verify_buckets_status( 0, revision_ids[0], {b: 'created' for b in bucket_names[:1]}) # Between revision 2 and 0, 2 buckets are created. self._verify_buckets_status( 0, revision_ids[1], {b: 'created' for b in bucket_names[:2]}) # Between revision 3 and 0, 3 buckets are created. self._verify_buckets_status( 0, revision_ids[2], {b: 'created' for b in bucket_names}) def test_revision_diff_self(self): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) bucket_name = test_utils.rand_name('bucket') documents = self.create_documents(bucket_name, payload) revision_id = documents[0]['revision_id'] self._verify_buckets_status( revision_id, revision_id, {bucket_name: 'unmodified'}) def test_revision_diff_multi_bucket_self(self): bucket_names = [] revision_ids = [] for _ in range(3): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) bucket_name = test_utils.rand_name('bucket') # Store each bucket that was created. bucket_names.append(bucket_name) documents = self.create_documents(bucket_name, payload) # Store each revision that was created. revision_id = documents[0]['revision_id'] revision_ids.append(revision_id) # The last revision should contain history for the previous 2 revisions # such that its diff history will show history for 3 buckets. Similarly # the 2nd revision will have history for 2 buckets and the 1st revision # for 1 bucket. # 1st revision has revision history for 1 bucket. self._verify_buckets_status( revision_ids[0], revision_ids[0], {bucket_names[0]: 'unmodified'}) # 2nd revision has revision history for 2 buckets. self._verify_buckets_status( revision_ids[1], revision_ids[1], {b: 'unmodified' for b in bucket_names[:2]}) # 3rd revision has revision history for 3 buckets. self._verify_buckets_status( revision_ids[2], revision_ids[2], {b: 'unmodified' for b in bucket_names}) def test_revision_diff_modified(self): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) bucket_name = test_utils.rand_name('bucket') documents = self.create_documents(bucket_name, payload) revision_id = documents[0]['revision_id'] payload[0]['data'] = {'modified': 'modified'} comparison_documents = self.create_documents(bucket_name, payload) comparison_revision_id = comparison_documents[0]['revision_id'] self._verify_buckets_status( revision_id, comparison_revision_id, {bucket_name: 'modified'}) def test_revision_diff_multi_revision_modified(self): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) bucket_name = test_utils.rand_name('bucket') revision_ids = [] for _ in range(3): payload[0]['data'] = {'modified': test_utils.rand_name('modified')} documents = self.create_documents(bucket_name, payload) revision_id = documents[0]['revision_id'] revision_ids.append(revision_id) for pair in [(0, 1), (0, 2), (1, 2)]: self._verify_buckets_status( revision_ids[pair[0]], revision_ids[pair[1]], {bucket_name: 'modified'}) def test_revision_diff_multi_revision_multi_bucket_modified(self): revision_ids = [] bucket_name = test_utils.rand_name('bucket') alt_bucket_name = test_utils.rand_name('bucket') bucket_names = [bucket_name, alt_bucket_name] * 2 # Create revisions by modifying documents in `bucket_name` and # `alt_bucket_name`. for bucket_idx in range(4): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) documents = self.create_documents( bucket_names[bucket_idx], payload) revision_id = documents[0]['revision_id'] revision_ids.append(revision_id) # Between revision_ids[0] and [1], bucket_name is unmodified and # alt_bucket_name is created. self._verify_buckets_status( revision_ids[0], revision_ids[1], {bucket_name: 'unmodified', alt_bucket_name: 'created'}) # Between revision_ids[0] and [2], bucket_name is modified (by 2) and # alt_bucket_name is created (by 1). self._verify_buckets_status( revision_ids[0], revision_ids[2], {bucket_name: 'modified', alt_bucket_name: 'created'}) # Between revision_ids[0] and [3], bucket_name is modified (by [2]) and # alt_bucket_name is created (by [1]) (as well as modified by [3]). self._verify_buckets_status( revision_ids[0], revision_ids[3], {bucket_name: 'modified', alt_bucket_name: 'created'}) # Between revision_ids[1] and [2], bucket_name is modified but # alt_bucket_name remains unmodified. self._verify_buckets_status( revision_ids[1], revision_ids[2], {bucket_name: 'modified', alt_bucket_name: 'unmodified'}) <|fim▁hole|> {bucket_name: 'modified', alt_bucket_name: 'modified'}) # Between revision_ids[2] and [3], alt_bucket_name is modified but # bucket_name remains unmodified. self._verify_buckets_status( revision_ids[2], revision_ids[3], {bucket_name: 'unmodified', alt_bucket_name: 'modified'}) def test_revision_diff_ignore_bucket_with_unrelated_documents(self): payload = base.DocumentFixture.get_minimal_fixture() alt_payload = base.DocumentFixture.get_minimal_fixture() bucket_name = test_utils.rand_name('bucket') alt_bucket_name = test_utils.rand_name('bucket') # Create a bucket with a single document. documents = self.create_documents(bucket_name, payload) revision_id = documents[0]['revision_id'] # Create another bucket with an entirely different document (different # schema and metadata.name). self.create_documents(alt_bucket_name, alt_payload) # Modify the document from the 1st bucket. payload['data'] = {'modified': 'modified'} documents = self.create_documents(bucket_name, payload) comparison_revision_id = documents[0]['revision_id'] # The `alt_bucket_name` should be created. self._verify_buckets_status( revision_id, comparison_revision_id, {bucket_name: 'modified', alt_bucket_name: 'created'}) def test_revision_diff_ignore_bucket_with_all_unrelated_documents(self): payload = base.DocumentFixture.get_minimal_multi_fixture(count=3) alt_payload = copy.deepcopy(payload) bucket_name = test_utils.rand_name('bucket') alt_bucket_name = test_utils.rand_name('bucket') # Create a bucket with 3 documents. documents = self.create_documents(bucket_name, payload) revision_id = documents[0]['revision_id'] # Modify all 3 documents from first bucket. for idx in range(3): alt_payload[idx]['name'] = test_utils.rand_name('name') alt_payload[idx]['schema'] = test_utils.rand_name('schema') self.create_documents( alt_bucket_name, alt_payload) # Modify the document from the 1st bucket. payload[0]['data'] = {'modified': 'modified'} documents = self.create_documents(bucket_name, payload) comparison_revision_id = documents[0]['revision_id'] # The alt_bucket_name should be created. self._verify_buckets_status( revision_id, comparison_revision_id, {bucket_name: 'modified', alt_bucket_name: 'created'}) def test_revision_diff_deleted(self): payload = base.DocumentFixture.get_minimal_fixture() bucket_name = test_utils.rand_name('bucket') created_documents = self.create_documents(bucket_name, payload) revision_id = created_documents[0]['revision_id'] # Delete the previously created document. deleted_documents = self.create_documents(bucket_name, []) comparison_revision_id = deleted_documents[0]['revision_id'] self._verify_buckets_status( revision_id, comparison_revision_id, {bucket_name: 'deleted'}) def test_revision_diff_delete_then_recreate(self): payload = base.DocumentFixture.get_minimal_fixture() bucket_name = test_utils.rand_name('bucket') created_documents = self.create_documents(bucket_name, payload) revision_id_1 = created_documents[0]['revision_id'] # Delete the previously created document. deleted_documents = self.create_documents(bucket_name, []) revision_id_2 = deleted_documents[0]['revision_id'] # Recreate the previously deleted document. recreated_documents = self.create_documents(bucket_name, payload) revision_id_3 = recreated_documents[0]['revision_id'] # Verify that the revision for recreated document compared to revision # for deleted document is created, ignoring order. self._verify_buckets_status( revision_id_2, revision_id_3, {bucket_name: 'created'}) # Verify that the revision for recreated document compared to revision # for created document is unmodified, ignoring order. self._verify_buckets_status( revision_id_1, revision_id_3, {bucket_name: 'unmodified'}) def test_revision_diff_ignore_mistake_document(self): payload = base.DocumentFixture.get_minimal_fixture() bucket_name = test_utils.rand_name('first_bucket') created_documents = self.create_documents(bucket_name, payload) revision_id_1 = created_documents[0]['revision_id'] # Create then delete an "accidental" document create request. alt_payload = base.DocumentFixture.get_minimal_fixture() alt_bucket_name = test_utils.rand_name('mistake_bucket') created_documents = self.create_documents(alt_bucket_name, alt_payload) revision_id_2 = created_documents[0]['revision_id'] deleted_documents = self.create_documents(alt_bucket_name, []) revision_id_3 = deleted_documents[0]['revision_id'] alt_payload_2 = base.DocumentFixture.get_minimal_fixture() alt_bucket_name_2 = test_utils.rand_name('second_bucket') created_documents = self.create_documents( alt_bucket_name_2, alt_payload_2) revision_id_4 = created_documents[0]['revision_id'] self._verify_buckets_status( revision_id_1, revision_id_2, {bucket_name: 'unmodified', alt_bucket_name: 'created'}) self._verify_buckets_status( revision_id_2, revision_id_3, {bucket_name: 'unmodified', alt_bucket_name: 'deleted'}) self._verify_buckets_status( revision_id_1, revision_id_3, {bucket_name: 'unmodified'}) # Should not contain information about `alt_bucket_name` as it was a # "mistake": created then deleted between the revisions in question. self._verify_buckets_status( revision_id_1, revision_id_4, {bucket_name: 'unmodified', alt_bucket_name_2: 'created'})<|fim▁end|>
# Between revision_ids[1] and [3], bucket_name is modified (by [2]) and # alt_bucket_name is modified by [3]. self._verify_buckets_status( revision_ids[1], revision_ids[3],
<|file_name|>token.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import datetime from flask import jsonify, request from app import token_auth from app.models.user_token_model import UserTokenModel @token_auth.verify_token def verify_token(hashed): token = UserTokenModel.query\ .filter(UserTokenModel.hashed == hashed, UserTokenModel.ip_address == request.remote_addr) if token.count(): token = token.first() if token.expired_at > datetime.datetime.now(): return True return False<|fim▁hole|> @token_auth.error_handler def error_handler(): return jsonify({'code': 401, 'status': 'fail', 'message': 'Token that does not exist or has expired.'})<|fim▁end|>
<|file_name|>update_interrupt_create.py<|end_file_name|><|fim▁begin|>def check_resource_count(expected_count): test.assertEqual(expected_count, len(reality.all_resources())) example_template = Template({<|fim▁hole|> 'A': RsrcDef({}, []), 'B': RsrcDef({'a': '4alpha'}, ['A']), 'C': RsrcDef({'a': 'foo'}, ['B']), 'D': RsrcDef({'a': 'bar'}, ['C']), }) engine.create_stack('foo', example_template) engine.noop(1) example_template2 = Template({ 'A': RsrcDef({}, []), 'B': RsrcDef({'a': '4alpha'}, ['A']), 'C': RsrcDef({'a': 'blarg'}, ['B']), 'D': RsrcDef({'a': 'wibble'}, ['C']), }) engine.update_stack('foo', example_template2) engine.call(check_resource_count, 2) engine.noop(11) engine.call(verify, example_template2)<|fim▁end|>
<|file_name|>HashVisualization.js<|end_file_name|><|fim▁begin|>var set = new HashSet(); //Array size var arrElementWidth = 150; var arrElementHeight = 40; //Key size var keyWidth = 50; var keyMargin = 5; var width = 800; var height = DEFAULT_TABLE_SIZE * (arrElementHeight + 5); //Hash function block size var blockWidth = keyWidth + keyMargin + arrElementWidth; var blockHeight = DEFAULT_TABLE_SIZE * (arrElementHeight + 5); var blockMargin = 30; var codeDisplayManager = new CodeDisplayManager('javascript', 'hashSet'); var drawingArea; var hashFunctionBlock; var bucket; var keys; var newestElement; var arrow; //Panning var pan; $(document).ready(function () { drawingArea = d3.select("#hash") .append("svg:svg") .attr("width", $('#graphics').width()) .attr("height", $('#graphics').height()) .append('g'); hashFunctionBlock = drawingArea.append("g"); keys = drawingArea.append("g"); bucket = drawingArea.append("g"); hashFunctionBlock.attr("id", "hashFunctionBlock"); keys.attr("id", "keys"); bucket.attr("id", "bucket"); hashFunctionBlock.append("rect") .attr("width", blockWidth) .attr("height", blockHeight) .attr("x", width - arrElementWidth - keyWidth - blockWidth - blockMargin) .attr("fill", "cornflowerBlue"); hashFunctionBlock.append("text") .attr("width", blockWidth) .attr("height", blockHeight) .attr("y", blockHeight - 10) .attr("x", width + 10 - arrElementWidth - keyWidth - blockWidth - blockMargin) .text("") .attr("class", 'noselect'); createKeysAndBuckets(DEFAULT_TABLE_SIZE, "1"); // arrow marker drawingArea.append('defs').append('marker') .attr('id', 'end-arrow') .attr('viewBox', '0 -5 10 10') .attr('refX', 6) .attr('markerWidth', 3) .attr('markerHeight', 3) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M0,-5L10,0L0,5') .attr('fill', 'red'); arrow = drawingArea.append("path") .attr("id", "arrow") .attr("fill", "none") .attr("stroke", "red") .attr("stroke-width", "4") .attr("opacity", "0") .style('marker-end', 'url(#end-arrow)'); pan = d3.zoom() .scaleExtent([1 / 10, 1]) .on("zoom", panning); drawingArea.call(pan); drawingArea.attr("transform", "translate(50,20) scale(0.70)"); }); function runAdd(x, probing, hashFunc) {<|fim▁hole|> codeDisplayManager.loadFunctions('add', 'rehash'); codeDisplayManager.changeFunction('add'); set.add(x); } function runRemove(x) { codeDisplayManager.loadFunctions('remove', 'rehash', 'add'); codeDisplayManager.changeFunction('remove'); set.remove(x); } function panning() { drawingArea.attr("transform", d3.event.transform); } function updateArrow(index) { unhighlightKey(); var targetY = index * (arrElementHeight + 5); var lineData = [{ "x": arrElementWidth, "y": height / 2 + arrElementHeight / 2 }, { "x": width + 30 - blockWidth - arrElementWidth - keyWidth - blockMargin, "y": height / 2 + arrElementHeight / 2 }, { "x": width - 30 - arrElementWidth - keyWidth - blockMargin, "y": targetY + arrElementHeight / 2 }, { "x": width - arrElementWidth - keyWidth - keyMargin, "y": targetY + arrElementHeight / 2 }]; var lineFunction = d3.line() .x(function (d) { return d.x; }) .y(function (d) { return d.y; }); appendAnimation(null, [{ e: '#arrow', p: { attr: { d: lineFunction(lineData), opacity: 1 } }, o: { duration: 1 } }], null); highlightKey(index); } function clearHighlight(array) { appendAnimation(null, [{ e: $(array + " rect"), p: { attr: { fill: "cornflowerBlue" } }, o: { duration: 1 } }], null); } function add(value) { prevOffset = 0; hideHash(); newestElement = bucket.append("svg:g") .attr("transform", "translate(0," + height / 2 + ")") .attr("class", "newElement") .attr("opacity", 0); newestElement.append("rect") .attr("width", arrElementWidth) .attr("height", arrElementHeight) .attr("fill", "#9c6dfc"); newestElement.append("text") .style("text-anchor", "middle") .attr("x", arrElementWidth / 2) .attr("y", arrElementHeight / 2 + 7) .text(value) .style("font-size", "22px") .style("font-weight", "bold"); appendAnimation(null, [{ e: newestElement.node(), p: { attr: { opacity: "1" } }, o: { duration: 1 } }], null); } function moveToHashFunctionBlock() { appendAnimation(null, [ { e: newestElement.node(), p: { x: width + 10 - blockWidth - arrElementWidth - keyWidth - blockMargin }, o: { duration: 1 } }, { e: $("#arrow"), p: { attr: { opacity: 0, d: "" } }, o: { duration: 1, position: '-=1' } } ], null); } function replaceElement(index) { moveToHashFunctionBlock(); appendAnimation(6, [ { e: $("#bucket").filter(".element" + index), p: { attr: { opacity: 0 } }, o: { duration: 1 } }, { e: newestElement.node(), p: { x: width - arrElementWidth, y: index * (arrElementHeight + 5) }, o: { duration: 1, position: '-=1' } }, ], codeDisplayManager); $("#bucket").filter(".element" + index).attr("class", "removed"); $(newestElement).attr("class", "element" + index); } function highlightKey(index) { appendAnimation(null, [{ e: $("#keys rect").filter(".key" + index), p: { attr: { stroke: "red" } }, o: { duration: 1 } }], null); } function unhighlightKey() { appendAnimation(null, [{ e: $("#keys rect"), p: { attr: { stroke: "none" } }, o: { duration: 1 } }], null); } function removeElement(index) { appendAnimation(4, [ { e: $(".element" + index), p: { attr: { stroke: "red", "stroke-width": "2" } }, o: { duration: 1 } }, { e: $("#arrow"), p: { attr: { opacity: 0, d: "" } }, o: { duration: 1, position: '-=1' } } ], codeDisplayManager); } var prevOffset = 0; function displayHash(hashValue, length, offset) { var hashString; if (set.probingType != "quadratic") { if (offset == 0) { hashString = hashValue + " % " + length + " = " + Math.abs(hashValue % length); } prevOffset += offset; hashString = hashValue + " % " + length + " + " + prevOffset + " = " + (Math.abs(hashValue % length) + prevOffset); } else { if (offset == 0) { hashString = hashValue + " % " + length + " = " + Math.abs(hashValue % length); } prevOffset += offset; hashString = hashValue + " % " + length + " + " + offset + " * " + offset + " = " + (Math.abs(hashValue % length) + offset * offset); } appendAnimation(null, [ { e: $("#hashFunctionBlock text"), p: { attr: { stroke: "red" }, text: hashString }, o: { duration: 1 } }, { e: $("#hashFunctionBlock text"), p: { attr: { stroke: "black" } }, o: { duration: 1 } } ], null); } function hideHash() { appendAnimation(null, [{ e: $("#hashFunctionBlock text"), p: { text: "" }, o: { duration: 1 } }], null); } function renewTable(length) { appendAnimation(null, [ { e: $("#bucket, #bucket *"), p: { attr: { opacity: 0 } }, o: { duration: 1 } }, { e: $("#keys, #keys *"), p: { attr: { opacity: 0 } }, o: { duration: 1, position: '-=1' } } ], null); $("#bucket *").attr("class", "removed"); $("#keys *").attr("class", "removed"); createKeysAndBuckets(length, "0"); appendAnimation(3, [ { e: $("#bucket, #bucket *").filter(":not(.removed)"), p: { attr: { opacity: 1 } }, o: { duration: 1 } }, { e: $("#keys, #keys *").filter(":not(.removed)"), p: { attr: { opacity: 1 } }, o: { duration: 1, position: '-=1' } } ], codeDisplayManager); } function createKeysAndBuckets(length, opacity) { for (var i = 0; i < length; i++) { //Key var keyPosX = width - arrElementWidth - keyWidth - keyMargin; var keyPosY = i * (arrElementHeight + 5); var keyGroup = keys.append("svg:g") .attr("transform", "translate(" + keyPosX + "," + keyPosY + ")"); keyGroup.append("svg:rect") .attr("height", arrElementHeight) .attr("width", keyWidth) .attr("fill", "cornflowerBlue") .attr("opacity", opacity) .attr("class", "key" + i); keyGroup.append("svg:text") .text(i) .attr("x", keyWidth / 2) .attr("y", arrElementHeight / 2 + 7) .attr("opacity", opacity) .attr("text-anchor", "middle") .style("font-size", "22px") .style("font-weight", "bold"); //Bucket var valueGroup = bucket.append("svg:g") .attr("transform", "translate(" + (width - arrElementWidth) + "," + i * (arrElementHeight + 5) + ")") .attr("class", "element" + i) .attr("opacity", opacity); valueGroup.append("svg:rect") .attr("width", arrElementWidth) .attr("height", arrElementHeight) .attr("fill", "cornflowerBlue"); valueGroup.append("svg:text") .style("text-anchor", "middle") .attr("x", arrElementWidth / 2) .attr("y", arrElementHeight / 2 + 7) .style("font-size", "22px") .style("font-weight", "bold"); } } function highlightCode(lines, functionName) { if (functionName) codeDisplayManager.changeFunction(functionName); appendCodeLines(lines, codeDisplayManager); }<|fim▁end|>
set.probingType = probing == "Quadratic" ? "quadratic" : "linear"; set.hashFunc = hashFunc == "Simple" ? getSimpleHashCode : getHashCode;
<|file_name|>UploadFileService.java<|end_file_name|><|fim▁begin|>package pl.edu.wat.tim.webstore.service; <|fim▁hole|>/** * Created by Piotr on 15.06.2017. */ public interface UploadFileService { void save(UploadFile uploadFile); UploadFile getUploadFile(String name); }<|fim▁end|>
import pl.edu.wat.tim.webstore.model.UploadFile;
<|file_name|>spar_no.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import scrapy from locations.items import GeojsonPointItem DAYS = [ 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su' ] class SparNoSpider(scrapy.Spider): name = "spar_no" allowed_domains = ["spar.no"] start_urls = ( 'https://spar.no/Finn-butikk/', ) def parse(self, response): shops = response.xpath('//div[@id="js_subnav"]//li[@class="level-1"]/a/@href') for shop in shops: yield scrapy.Request( response.urljoin(shop.extract()), callback=self.parse_shop ) def parse_shop(self, response): props = {} ref = response.xpath('//h1[@itemprop="name"]/text()').extract_first() if ref: # some links redirects back to list page props['ref'] = ref.strip("\n").strip() else:<|fim▁hole|> for day in days: day_list = day.xpath('.//link[@itemprop="dayOfWeek"]/@href').extract() first = 0 last = 0 for d in day_list: st = d.replace('https://purl.org/goodrelations/v1#', '')[:2] first = DAYS.index(st) if first>DAYS.index(st) else first last = DAYS.index(st) if first>DAYS.index(st) else first props['opening_hours'] = DAYS[first]+'-'+DAYS[last]+' '+day.xpath('.//meta[@itemprop="opens"]/@content').extract_first()+' '+day.xpath('.//meta[@itemprop="closes"]/@content').extract_first() phone = response.xpath('//a[@itemprop="telephone"]/text()').extract_first() if phone: props['phone'] = phone addr_full = response.xpath('//div[@itemprop="streetAddress"]/text()').extract_first() if addr_full: props['addr_full'] = addr_full postcode = response.xpath('//span[@itemprop="postalCode"]/text()').extract_first() if postcode: props['postcode'] = postcode city = response.xpath('//span[@itemprop="addressLocality"]/text()').extract_first() if city: props['city'] = city.strip() props['country'] = 'NO' lat = response.xpath('//meta[@itemprop="latitude"]/@content').extract_first() lon = response.xpath('//meta[@itemprop="longitude"]/@content').extract_first() if lat and lon: props['lat'] = float(lat) props['lon'] = float(lon) props['website'] = response.url yield GeojsonPointItem(**props)<|fim▁end|>
return days = response.xpath('//div[@itemprop="openingHoursSpecification"]') if days:
<|file_name|>data_type.rs<|end_file_name|><|fim▁begin|>extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; #[derive(Clone, PartialEq, Eq, Debug)] pub enum DataType { Boolean, Integer, Float, String, DateTime, Timestamp, Struct(String, Vec<Field>, String) } #[derive(Serialize)] struct SerializedDataType { name: String, fields: Vec<Field>, comment: String, user_defined: bool, } impl DataType { fn convert_serialized(&self) -> SerializedDataType { match *self { DataType::Boolean => SerializedDataType { name: "boolean".to_string(), fields: vec![], comment: "".to_string(), user_defined: false }, DataType::Integer => SerializedDataType { name: "integer".to_string(), fields: vec![], comment: "".to_string(), user_defined: false }, DataType::Float => SerializedDataType { name: "float".to_string(), fields: vec![], comment: "".to_string(), user_defined: false }, DataType::String => SerializedDataType { name: "string".to_string(), fields: vec![], comment: "".to_string(), user_defined: false }, DataType::DateTime => SerializedDataType { name: "datetime".to_string(), fields: vec![], comment: "".to_string(), user_defined: false }, DataType::Timestamp => SerializedDataType { name: "timestamp".to_string(), fields: vec![], comment: "".to_string(), user_defined: false }, DataType::Struct(ref name, ref fields, ref comment) => SerializedDataType { name: name.clone(), fields: fields.clone(), comment: comment.clone(), user_defined: true, }, } } pub fn name(&self) -> String { self.convert_serialized().name } } impl Serialize for DataType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { let data = self.convert_serialized(); let mut state = serializer.serialize_struct("DataType", 2)?; state.serialize_field("name", &data.name)?; state.serialize_field("fields", &data.fields)?; state.serialize_field("user_defined", &data.user_defined)?; state.end() } } #[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub enum TypeAttribute { None, Nullable } #[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub struct Field { #[allow(dead_code)] pub name: String, #[allow(dead_code)] pub data_type: DataType, #[allow(dead_code)] pub type_attribute: TypeAttribute, } #[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub struct LogSchema { #[allow(dead_code)] pub name: String, #[allow(dead_code)] pub fields: Vec<Field>, #[allow(dead_code)] pub comment: String, } #[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub struct DefaultLogSchema { #[allow(dead_code)]<|fim▁hole|>}<|fim▁end|>
pub front_fields: Vec<Field>, #[allow(dead_code)] pub back_fields: Vec<Field>,
<|file_name|>mk_ATCA_array_configs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python telescope = "ATCA" latitude_deg = -30.312906 diameter_m = 22.0 import os import sys from util_misc import ascii_dat_read #-----------------------------------------------------------------------------# def main(): # Read the station lookup table col, dummy = ascii_dat_read("ATCA_stations.txt", delim=" ", doFloatCols=[2, 3]) statDict = {} for station, N, W in zip(col[1], col[2], col[3]): statDict[station] = (-W+1622.449, N) # Read the array configuration file col, dummy = ascii_dat_read("ATCA_configs.txt", delim=" ", doFloatCols=[2, 3, 4, 5, 6, 7]) for confName, A1, A2, A3, A4, A5, A6 in zip(col[1], col[2], col[3], col[4], col[5], col[6], col[7]): if A1=='': continue outFileName = "ATCA_%s.config" % confName FH = open(outFileName, "w") FH.write("#" + "-"*78 + "#\n") FH.write("#\n") FH.write("# Array definition file for the %s %s configuration.\n" % (telescope, confName)) FH.write("#\n") FH.write("#" + "-"*78 + "#\n") FH.write("\n") FH.write("# Name of the telescope\n") FH.write("telescope = %s\n" % telescope) FH.write("\n") FH.write("# Name of the configuration\n") FH.write("config = %s\n" % confName) FH.write("\n") FH.write("# Latitude of the array centre\n") FH.write("latitude_deg = %f\n" % latitude_deg) FH.write("\n") FH.write("# Antenna diameter\n") FH.write("diameter_m = %f\n" % diameter_m) FH.write("\n") FH.write("# Antenna coordinates (offset E, offset N)\n") FH.write("%f, %f\n" % (statDict[A1][0], statDict[A1][1])) FH.write("%f, %f\n" % (statDict[A2][0], statDict[A2][1])) FH.write("%f, %f\n" % (statDict[A3][0], statDict[A3][1])) FH.write("%f, %f\n" % (statDict[A4][0], statDict[A4][1])) FH.write("%f, %f\n" % (statDict[A5][0], statDict[A5][1])) FH.write("%f, %f\n" % (statDict[A6][0], statDict[A6][1])) <|fim▁hole|> col[5], col[6]): if A1=='': continue confName += "_No_6" outFileName = "ATCA_%s.config" % confName FH = open(outFileName, "w") FH.write("#" + "-"*78 + "#\n") FH.write("#\n") FH.write("# Array definition file for the %s %s configuration.\n" % (telescope, confName)) FH.write("#\n") FH.write("#" + "-"*78 + "#\n") FH.write("\n") FH.write("# Name of the telescope\n") FH.write("telescope = %s\n" % telescope) FH.write("\n") FH.write("# Name of the configuration\n") FH.write("config = %s\n" % confName) FH.write("\n") FH.write("# Latitude of the array centre\n") FH.write("latitude_deg = %f\n" % latitude_deg) FH.write("\n") FH.write("# Antenna diameter\n") FH.write("diameter_m = %f\n" % diameter_m) FH.write("\n") FH.write("# Antenna coordinates (offset E, offset N)\n") FH.write("%f, %f\n" % (statDict[A1][0], statDict[A1][1])) FH.write("%f, %f\n" % (statDict[A2][0], statDict[A2][1])) FH.write("%f, %f\n" % (statDict[A3][0], statDict[A3][1])) FH.write("%f, %f\n" % (statDict[A4][0], statDict[A4][1])) FH.write("%f, %f\n" % (statDict[A5][0], statDict[A5][1])) FH.close() #-----------------------------------------------------------------------------# main()<|fim▁end|>
FH.close() for confName, A1, A2, A3, A4, A5 in zip(col[1], col[2], col[3], col[4],
<|file_name|>opf_metrics_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import numpy as np import unittest2 as unittest from nupic.frameworks.opf.metrics import getModule, MetricSpec, MetricMulti class OPFMetricsTest(unittest.TestCase): DELTA = 0.01 VERBOSITY = 0 def testRMSE(self): rmse = getModule(MetricSpec("rmse", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) gt = [9, 4, 5, 6] p = [0, 13, 8, 3] for i in xrange(len(gt)): rmse.addInstance(gt[i], p[i]) target = 6.71 self.assertTrue(abs(rmse.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testNRMSE(self): nrmse = getModule(MetricSpec("nrmse", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) gt = [9, 4, 5, 6] p = [0, 13, 8, 3] for i in xrange(len(gt)): nrmse.addInstance(gt[i], p[i]) target = 3.5856858280031814 self.assertAlmostEqual(nrmse.getMetric()["value"], target) def testWindowedRMSE(self): wrmse = getModule(MetricSpec("rmse", None, None, {"verbosity": OPFMetricsTest.VERBOSITY, "window":3})) gt = [9, 4, 4, 100, 44] p = [0, 13, 4, 6, 7] for gv, pv in zip(gt, p): wrmse.addInstance(gv, pv) target = 58.324 self.assertTrue (abs(wrmse.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testAAE(self): aae = getModule(MetricSpec("aae", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) gt = [9, 4, 5, 6] p = [0, 13, 8, 3] for i in xrange(len(gt)): aae.addInstance(gt[i], p[i]) target = 6.0 self.assertTrue(abs(aae.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testTrivialAAE(self): trivialaae = getModule(MetricSpec("trivial", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY,"errorMetric":"aae"})) gt = [i/4+1 for i in range(100)] p = [i for i in range(100)] for i in xrange(len(gt)): trivialaae.addInstance(gt[i], p[i]) target = .25 self.assertTrue(abs(trivialaae.getMetric()["value"]-target) \ < OPFMetricsTest.DELTA) def testTrivialAccuracy(self): trivialaccuracy = getModule(MetricSpec("trivial", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY,"errorMetric":"acc"})) gt = [str(i/4+1) for i in range(100)] p = [str(i) for i in range(100)] for i in xrange(len(gt)): trivialaccuracy.addInstance(gt[i], p[i]) target = .75 self.assertTrue(abs(trivialaccuracy.getMetric()["value"]-target) \ < OPFMetricsTest.DELTA) def testWindowedTrivialAAE (self): """Trivial Average Error metric test""" trivialAveErr = getModule(MetricSpec("trivial", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY,"errorMetric":"avg_err"})) gt = [str(i/4+1) for i in range(100)] p = [str(i) for i in range(100)] for i in xrange(len(gt)): trivialAveErr.addInstance(gt[i], p[i]) target = .25 self.assertTrue(abs(trivialAveErr.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testWindowedTrivialAccuract(self): """Trivial AAE metric test""" trivialaae = getModule(MetricSpec("trivial", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100,"errorMetric":"aae"})) gt = [i/4+1 for i in range(1000)] p = [i for i in range(1000)] for i in xrange(len(gt)): trivialaae.addInstance(gt[i], p[i]) target = .25 self.assertTrue(abs(trivialaae.getMetric()["value"]-target) \ < OPFMetricsTest.DELTA) def testWindowedTrivialAccuracy(self): """Trivial Accuracy metric test""" trivialaccuracy = getModule(MetricSpec("trivial", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100,"errorMetric":"acc"})) gt = [str(i/4+1) for i in range(1000)] p = [str(i) for i in range(1000)] for i in xrange(len(gt)): trivialaccuracy.addInstance(gt[i], p[i]) target = .75 self.assertTrue(abs(trivialaccuracy.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testWindowedTrivialAverageError (self): """Trivial Average Error metric test""" trivialAveErr = getModule(MetricSpec("trivial", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100,"errorMetric":"avg_err"})) gt = [str(i/4+1) for i in range(500, 1000)] p = [str(i) for i in range(1000)] for i in xrange(len(gt)): trivialAveErr.addInstance(gt[i], p[i]) target = .25 self.assertTrue(abs(trivialAveErr.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testMultistepAAE(self): """Multistep AAE metric test""" msp = getModule(MetricSpec("multiStep", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "errorMetric":"aae", "steps": 3})) # Make each ground truth 1 greater than the prediction gt = [i+1 for i in range(100)] p = [{3: {i: .7, 5: 0.3}} for i in range(100)] for i in xrange(len(gt)): msp.addInstance(gt[i], p[i]) target = 1 self.assertTrue(abs(msp.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testMultistepAAEMultipleSteps(self): """Multistep AAE metric test, predicting 2 different step sizes""" msp = getModule(MetricSpec("multiStep", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "errorMetric":"aae", "steps": [3,6]})) # Make each 3 step prediction +1 over ground truth and each 6 step # prediction +0.5 over ground truth gt = [i for i in range(100)] p = [{3: {i+1: .7, 5: 0.3}, 6: {i+0.5: .7, 5: 0.3}} for i in range(100)] for i in xrange(len(gt)): msp.addInstance(gt[i], p[i]) target = 0.75 # average of +1 error and 0.5 error self.assertTrue(abs(msp.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testMultistepProbability(self): """Multistep with probabilities metric test""" msp = getModule(MetricSpec("multiStepProbability", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "errorMetric":"aae", "steps":3})) gt = [5 for i in range(1000)] p = [{3: {i: .3, 5: .7}} for i in range(1000)] for i in xrange(len(gt)): msp.addInstance(gt[i], p[i]) #((999-5)(1000-5)/2-(899-5)(900-5)/2)*.3/100 target = 283.35 self.assertTrue(abs(msp.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testMultistepProbabilityMultipleSteps(self): """Multistep with probabilities metric test, predicting 2 different step sizes""" msp = getModule(MetricSpec("multiStepProbability", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "errorMetric":"aae", "steps": [1,3]})) gt = [5 for i in range(1000)] p = [{3: {i: .3, 5: .7}, 1: {5: 1.0}} for i in range(1000)] for i in xrange(len(gt)): msp.addInstance(gt[i], p[i]) #(((999-5)(1000-5)/2-(899-5)(900-5)/2)*.3/100) / 2 # / 2 because the 1-step prediction is 100% accurate target = 283.35/2 self.assertTrue(abs(msp.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testMovingMeanAbsoluteError(self): """Moving mean Average Absolute Error metric test""" movingMeanAAE = getModule(MetricSpec("moving_mean", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "mean_window":3, "errorMetric":"aae"})) gt = [i for i in range(890)] gt.extend([2*i for i in range(110)]) p = [i for i in range(1000)] res = [] for i in xrange(len(gt)): movingMeanAAE.addInstance(gt[i], p[i])<|fim▁hole|> self.assertTrue(min(res[891:])>=4.0) target = 4.0 self.assertTrue(abs(movingMeanAAE.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testMovingMeanRMSE(self): """Moving mean RMSE metric test""" movingMeanRMSE = getModule(MetricSpec("moving_mean", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "mean_window":3, "errorMetric":"rmse"})) gt = [i for i in range(890)] gt.extend([2*i for i in range(110)]) p = [i for i in range(1000)] res = [] for i in xrange(len(gt)): movingMeanRMSE.addInstance(gt[i], p[i]) res.append(movingMeanRMSE.getMetric()["value"]) self.assertTrue(max(res[1:890]) == 2.0) self.assertTrue(min(res[891:])>=4.0) target = 4.0 self.assertTrue(abs(movingMeanRMSE.getMetric()["value"]-target) \ < OPFMetricsTest.DELTA) def testMovingModeAverageError(self): """Moving mode Average Error metric test""" movingModeAvgErr = getModule(MetricSpec("moving_mode", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "mode_window":3, "errorMetric":"avg_err"})) #Should initially assymptote to .5 #Then after 900 should go to 1.0 as the predictions will always be offset gt = [i/4 for i in range(900)] gt.extend([2*i/4 for i in range(100)]) p = [i for i in range(1000)] res = [] for i in xrange(len(gt)): movingModeAvgErr.addInstance(gt[i], p[i]) res.append(movingModeAvgErr.getMetric()["value"]) #Make sure that there is no point where the average error is >.5 self.assertTrue(max(res[1:890]) == .5) #Make sure that after the statistics switch the error goes to 1.0 self.assertTrue(min(res[891:])>=.5) #Make sure that the statistics change is still noticeable while it is #in the window self.assertTrue(res[998]<1.0) target = 1.0 self.assertTrue(abs(movingModeAvgErr.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testMovingModeAccuracy(self): """Moving mode Accuracy metric test""" movingModeACC = getModule(MetricSpec("moving_mode", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "mode_window":3, "errorMetric":"acc"})) #Should initially asymptote to .5 #Then after 900 should go to 0.0 as the predictions will always be offset gt = [i/4 for i in range(900)] gt.extend([2*i/4 for i in range(100)]) p = [i for i in range(1000)] res = [] for i in xrange(len(gt)): movingModeACC.addInstance(gt[i], p[i]) res.append(movingModeACC.getMetric()["value"]) #Make sure that there is no point where the average acc is <.5 self.assertTrue(min(res[1:899]) == .5) #Make sure that after the statistics switch the acc goes to 0.0 self.assertTrue(max(res[900:])<=.5) #Make sure that the statistics change is still noticeable while it #is in the window self.assertTrue(res[998]>0.0) target = 0.0 self.assertTrue(abs(movingModeACC.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testTwoGramScalars(self): """Two gram scalars test""" oneGram = getModule(MetricSpec("two_gram", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, \ "window":100, "predictionField":"test", "errorMetric":"acc"})) # Sequences of 0,1,2,3,4,0,1,2,3,4,... encodings = [np.zeros(10) for i in range(5)] for i in range(len(encodings)): encoding = encodings[i] encoding[i] = 1 gt = [i%5 for i in range(1000)] res = [] for i in xrange(len(gt)): if i == 20: # Make sure we don"t barf with missing values oneGram.addInstance(np.zeros(10), prediction=None, record={"test":None}) else: # Feed in next groundTruth oneGram.addInstance(encodings[i%5], prediction=None, record={"test":gt[i]}) res.append(oneGram.getMetric()["value"]) target = 1.0 self.assertTrue(abs(oneGram.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testTwoGramScalarsStepsGreaterOne(self): """Two gram scalars test with step size other than 1""" oneGram = getModule(MetricSpec("two_gram", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY,\ "window":100, "predictionField":"test", "errorMetric":"acc", "steps": 2})) # Sequences of 0,1,2,3,4,0,1,2,3,4,... encodings = [np.zeros(10) for i in range(5)] for i in range(len(encodings)): encoding = encodings[i] encoding[i] = 1 gt = [i%5 for i in range(1000)] res = [] for i in xrange(len(gt)): if i == 20: # Make sure we don"t barf with missing values oneGram.addInstance(np.zeros(10), prediction=None, record={"test":None}) else: # Feed in next groundTruth oneGram.addInstance(encodings[i%5], prediction=None, record={"test":gt[i]}) res.append(oneGram.getMetric()["value"]) target = 1.0 self.assertTrue(abs(oneGram.getMetric()["value"]-target) \ < OPFMetricsTest.DELTA) def testTwoGramStrings(self): """One gram string test""" oneGram = getModule(MetricSpec("two_gram", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100, "errorMetric":"acc", "predictionField":"test"})) # Sequences of "0", "1", "2", "3", "4", "0", "1", ... gt = [str(i%5) for i in range(1000)] encodings = [np.zeros(10) for i in range(5)] for i in range(len(encodings)): encoding = encodings[i] encoding[i] = 1 # Make every 5th element random newElem = 100 for i in range(5, 1000, 5): gt[i] = str(newElem) newElem += 20 res = [] for i in xrange(len(gt)): if i==20: # Make sure we don"t barf with missing values oneGram.addInstance(np.zeros(10), prediction=None, record={"test":None}) else: oneGram.addInstance(encodings[i%5], prediction=None, record={"test":gt[i]}) res.append(oneGram.getMetric()["value"]) target = .8 self.assertTrue(abs(oneGram.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testWindowedAAE(self): """Windowed AAE""" waae = getModule(MetricSpec("aae", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":1})) gt = [9, 4, 5, 6] p = [0, 13, 8, 3] for i in xrange(len(gt)): waae.addInstance(gt[i], p[i]) target = 3.0 self.assertTrue( abs(waae.getMetric()["value"]-target) \ < OPFMetricsTest.DELTA, "Got %s" %waae.getMetric()) def testAccuracy(self): """Accuracy""" acc = getModule(MetricSpec("acc", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) gt = [0, 1, 2, 3, 4, 5] p = [0, 1, 2, 4, 5, 6] for i in xrange(len(gt)): acc.addInstance(gt[i], p[i]) target = 0.5 self.assertTrue(abs(acc.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testWindowedAccuracy(self): """Windowed accuracy""" acc = getModule(MetricSpec("acc", None, None, \ {"verbosity" : OPFMetricsTest.VERBOSITY, "window":2})) gt = [0, 1, 2, 3, 4, 5] p = [0, 1, 2, 4, 5, 6] for i in xrange(len(gt)): acc.addInstance(gt[i], p[i]) target = 0.0 self.assertTrue(abs(acc.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testAverageError(self): """Ave Error""" err = getModule(MetricSpec("avg_err", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) gt = [1, 1, 2, 3, 4, 5] p = [0, 1, 2, 4, 5, 6] for i in xrange(len(gt)): err.addInstance(gt[i], p[i]) target = (2.0/3.0) self.assertTrue(abs(err.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testWindowedAverageError(self): """Windowed Ave Error""" err = getModule(MetricSpec("avg_err", None, None, \ {"verbosity" : OPFMetricsTest.VERBOSITY, "window":2})) gt = [0, 1, 2, 3, 4, 5] p = [0, 1, 2, 4, 5, 6] for i in xrange(len(gt)): err.addInstance(gt[i], p[i]) target = 1.0 self.assertTrue(abs(err.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testLongWindowRMSE(self): """RMSE""" rmse = getModule(MetricSpec("rmse", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY, "window":100})) gt = [9, 4, 5, 6] p = [0, 13, 8, 3] for i in xrange(len(gt)): rmse.addInstance(gt[i], p[i]) target = 6.71 self.assertTrue(abs(rmse.getMetric()["value"]-target)\ < OPFMetricsTest.DELTA) def testNegativeLogLikelihood(self): # make sure negativeLogLikelihood returns correct LL numbers # mock objects for ClassifierInput and ModelResult (see opfutils.py) class MockClassifierInput(object): def __init__(self, bucketIdx): self.bucketIndex = bucketIdx class MockModelResult(object): def __init__(self, bucketll, bucketIdx): self.inferences = {'multiStepBucketLikelihoods': {1: bucketll}} self.classifierInput = MockClassifierInput(bucketIdx) bucketLL = {0: 1.0, 1: 0, 2: 0, 3: 0} # model prediction as a dictionary gt_bucketIdx = 0 # bucket index for ground truth negLL = getModule(MetricSpec("negativeLogLikelihood", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) negLL.addInstance(0, 0, record = None, result=MockModelResult(bucketLL, gt_bucketIdx)) target = 0.0 # -log(1.0) self.assertAlmostEqual(negLL.getMetric()["value"], target) bucketLL = {0: 0.5, 1: 0.5, 2: 0, 3: 0} # model prediction as a dictionary gt_bucketIdx = 0 # bucket index for ground truth negLL = getModule(MetricSpec("negativeLogLikelihood", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) negLL.addInstance(0, 0, record = None, result=MockModelResult(bucketLL, gt_bucketIdx)) target = 0.6931471 # -log(0.5) self.assertTrue(abs(negLL.getMetric()["value"]-target) < OPFMetricsTest.DELTA) # test accumulated negLL for multiple steps bucketLL = [] bucketLL.append({0: 1, 1: 0, 2: 0, 3: 0}) bucketLL.append({0: 0, 1: 1, 2: 0, 3: 0}) bucketLL.append({0: 0, 1: 0, 2: 1, 3: 0}) bucketLL.append({0: 0, 1: 0, 2: 0, 3: 1}) gt_bucketIdx = [0, 2, 1, 3] negLL = getModule(MetricSpec("negativeLogLikelihood", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) for i in xrange(len(bucketLL)): negLL.addInstance(0, 0, record = None, result=MockModelResult(bucketLL[i], gt_bucketIdx[i])) target = 5.756462 self.assertTrue(abs(negLL.getMetric()["value"]-target) < OPFMetricsTest.DELTA) def testNegLLMultiplePrediction(self): # In cases where the ground truth has multiple possible outcomes, make sure # that the prediction that captures ground truth distribution has best LL # and models that gives single prediction (either most likely outcome or # average outcome) has worse LL # mock objects for ClassifierInput and ModelResult (see opfutils.py) class MockClassifierInput(object): def __init__(self, bucketIdx): self.bucketIndex = bucketIdx class MockModelResult(object): def __init__(self, bucketll, bucketIdx): self.inferences = {'multiStepBucketLikelihoods': {1: bucketll}} self.classifierInput = MockClassifierInput(bucketIdx) # the ground truth lies in bucket 0 with p=0.45, in bucket 1 with p=0.0 # and in bucket 2 with p=0.55 gt_bucketIdx = [0]*45+[2]*55 # compare neg log-likelihood for three type of model predictions # a model that predicts ground truth distribution prediction_gt = {0: 0.45, 1: 0, 2: 0.55} # a model that predicts only the most likely outcome prediction_ml = {0: 0.0, 1: 0, 2: 1.0} # a model that only predicts mean (bucket 1) prediction_mean = {0: 0, 1: 1, 2: 0} negLL_gt = getModule(MetricSpec("negativeLogLikelihood", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) negLL_ml = getModule(MetricSpec("negativeLogLikelihood", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) negLL_mean = getModule(MetricSpec("negativeLogLikelihood", None, None, {"verbosity" : OPFMetricsTest.VERBOSITY})) for i in xrange(len(gt_bucketIdx)): negLL_gt.addInstance(0, 0, record = None, result=MockModelResult(prediction_gt, gt_bucketIdx[i])) negLL_ml.addInstance(0, 0, record = None, result=MockModelResult(prediction_ml, gt_bucketIdx[i])) negLL_mean.addInstance(0, 0, record = None, result=MockModelResult(prediction_mean, gt_bucketIdx[i])) self.assertTrue(negLL_gt.getMetric()["value"] < negLL_ml.getMetric()["value"]) self.assertTrue(negLL_gt.getMetric()["value"] < negLL_mean.getMetric()["value"]) def testCustomErrorMetric(self): customFunc = """def getError(pred,ground,tools): return abs(pred-ground)""" customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc, "errorWindow":3})) gt = [9, 4, 5, 6] p = [0, 13, 8, 3] for i in xrange(len(gt)): aggErr = customEM.addInstance(gt[i], p[i]) target = 5.0 delta = 0.001 # insure that addInstance returns the aggregate error - other # uber metrics depend on this behavior. self.assertEqual(aggErr, customEM.getMetric()["value"]) self.assertTrue(abs(customEM.getMetric()["value"]-target) < delta) customFunc = """def getError(pred,ground,tools): sum = 0 for i in range(min(3,tools.getBufferLen())): sum+=abs(tools.getPrediction(i)-tools.getGroundTruth(i)) return sum/3""" customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc})) gt = [9, 4, 5, 6] p = [0, 13, 8, 3] for i in xrange(len(gt)): customEM.addInstance(gt[i], p[i]) target = 5.0 delta = 0.001 self.assertTrue(abs(customEM.getMetric()["value"]-target) < delta) # Test custom error metric helper functions # Test getPrediction # Not-Windowed storeWindow=4 failed = False for lookBack in range(3): customFunc = """def getError(pred,ground,tools): return tools.getPrediction(%d)""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if i < lookBack: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue( not failed, "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue( customEM.getMetric()["value"] == p[i-lookBack]) #Windowed for lookBack in range(5): customFunc = """def getError(pred,ground,tools): return tools.getPrediction(%d)""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc,"storeWindow":storeWindow})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if lookBack>=storeWindow-1: pass if i < lookBack or lookBack>=storeWindow: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue (not failed , "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue (customEM.getMetric()["value"] == p[i-lookBack]) #Test getGroundTruth #Not-Windowed for lookBack in range(3): customFunc = """def getError(pred,ground,tools): return tools.getGroundTruth(%d)""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if i < lookBack: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue( not failed , "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue (customEM.getMetric()["value"] == gt[i-lookBack]) #Windowed for lookBack in range(5): customFunc = """def getError(pred,ground,tools): return tools.getGroundTruth(%d)""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc,"storeWindow":storeWindow})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if i < lookBack or lookBack>=storeWindow: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue( not failed , "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue( customEM.getMetric()["value"] == gt[i-lookBack]) #Test getFieldValue #Not-Windowed Scalar for lookBack in range(3): customFunc = """def getError(pred,ground,tools): return tools.getFieldValue(%d,"test1")""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if i < lookBack: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue( not failed , "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue (customEM.getMetric()["value"] == t1[i-lookBack]) #Windowed Scalar for lookBack in range(3): customFunc = """def getError(pred,ground,tools): return tools.getFieldValue(%d,"test1")""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc,"storeWindow":storeWindow})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if i < lookBack or lookBack>=storeWindow: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue (not failed , "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue( customEM.getMetric()["value"] == t1[i-lookBack]) #Not-Windowed category for lookBack in range(3): customFunc = """def getError(pred,ground,tools): return tools.getFieldValue(%d,"test1")""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if i < lookBack: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue( not failed , "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue (customEM.getMetric()["value"] == t1[i-lookBack]) #Windowed category for lookBack in range(3): customFunc = """def getError(pred,ground,tools): return tools.getFieldValue(%d,"test1")""" % lookBack customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc,"storeWindow":storeWindow})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} if i < lookBack or lookBack>=storeWindow: try: customEM.addInstance(gt[i], p[i], curRecord) failed = True except: self.assertTrue (not failed , "An exception should have been generated, but wasn't") else: customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue (customEM.getMetric()["value"] == t1[i-lookBack]) #Test getBufferLen #Not-Windowed customFunc = """def getError(pred,ground,tools): return tools.getBufferLen()""" customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue (customEM.getMetric()["value"] == i+1) #Windowed customFunc = """def getError(pred,ground,tools): return tools.getBufferLen()""" customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc,"storeWindow":storeWindow})) gt = [i for i in range(100)] p = [2*i for i in range(100)] t1 = [3*i for i in range(100)] t2 = [str(4*i) for i in range(100)] for i in xrange(len(gt)): curRecord = {"pred":p[i], "ground":gt[i], "test1":t1[i], "test2":t2[i]} customEM.addInstance(gt[i], p[i], curRecord) self.assertTrue (customEM.getMetric()["value"] == min(i+1, 4)) #Test initialization edge cases try: customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc,"errorWindow":0})) self.assertTrue (False , "error Window of 0 should fail self.assertTrue") except: pass try: customEM = getModule(MetricSpec("custom_error_metric", None, None, {"customFuncSource":customFunc,"storeWindow":0})) self.assertTrue (False , "error Window of 0 should fail self.assertTrue") except: pass def testMultiMetric(self): ms1 = MetricSpec(field='a', metric='trivial', inferenceElement='prediction', params={'errorMetric': 'aae', 'window': 1000, 'steps': 1}) ms2 = MetricSpec(metric='trivial', inferenceElement='prediction', field='a', params={'window': 10, 'steps': 1, 'errorMetric': 'rmse'}) metric1000 = getModule(ms1) metric10 = getModule(ms2) # create multi metric multi = MetricMulti(weights=[0.2, 0.8], metrics=[metric10, metric1000]) multi.verbosity = 1 # create reference metrics (must be diff from metrics above used in MultiMetric, as they keep history) metric1000ref = getModule(ms1) metric10ref = getModule(ms2) gt = range(500, 1000) p = range(500) for i in xrange(len(gt)): v10=metric10ref.addInstance(gt[i], p[i]) v1000=metric1000ref.addInstance(gt[i], p[i]) if v10 is None or v1000 is None: check=None else: check=0.2*float(v10) + 0.8*float(v1000) metricValue = multi.addInstance(gt[i], p[i]) self.assertEqual(check, metricValue, "iter i= %s gt=%s pred=%s multi=%s sub1=%s sub2=%s" % (i, gt[i], p[i], metricValue, v10, v1000)) if __name__ == "__main__": unittest.main()<|fim▁end|>
res.append(movingMeanAAE.getMetric()["value"]) self.assertTrue(max(res[1:890]) == 2.0)
<|file_name|>filecache.py<|end_file_name|><|fim▁begin|># Bulletproof Arma Launcher # Copyright (C) 2017 Lukasz Taczuk # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import unicode_literals import errno import hashlib import os from utils import paths from utils import context def get_cache_directory(): return paths.get_launcher_directory('filecache') def map_file(url): """Get the path where the file should be stored in the cache.""" file_name = hashlib.sha256(url).hexdigest() return os.path.join(get_cache_directory(), file_name) def get_file(url): """Get the file contents from the cache or None if the file is not present in the cache. """ path = map_file(url) f = None try: f = open(path, 'rb') return f.read() except IOError as ex: if ex.errno == errno.ENOENT: # No such file return None raise finally: if f: f.close() def save_file(url, data): """Save the file contents to the cache. The contents of the file are saved to a temporary file and then moved to ensure that no truncated file is present in the cache. """ # Ensure the directory exists paths.mkdir_p(get_cache_directory()) path = map_file(url) tmp_path = path + '_tmp' f = open(tmp_path, 'wb') f.write(data) f.close() # Ensure the file does not exist (would raise an exception on Windows with context.ignore_nosuchfile_exception(): os.unlink(path)<|fim▁hole|><|fim▁end|>
os.rename(tmp_path, path)
<|file_name|>VelocityTemplate.java<|end_file_name|><|fim▁begin|>package com.flora.support; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Map; import org.apache.velocity.VelocityContext; <|fim▁hole|>import org.apache.velocity.context.Context; import com.flora.Config; public class VelocityTemplate { private VelocityEngine velocityEngine; private Config config; public VelocityTemplate(){ } public String parseTemplate(String template, Map model){ model.putAll(Config.getPageTools()); Context context = new VelocityContext(model); Writer writer = new StringWriter(); try { velocityEngine.mergeTemplate(template, "UTF-8", context, writer); } catch (Exception e) { } return writer.toString(); } public void parseTemplate(String template, Map model, Writer writer){ model.putAll(Config.getPageTools()); Context context = new VelocityContext(model); try { velocityEngine.mergeTemplate(template, "UTF-8", context, writer); } catch (Exception e) { } } public void parseTemplate(String template, Map model, OutputStream os){ model.putAll(Config.getPageTools()); Context context = new VelocityContext(model); Writer writer = new OutputStreamWriter(os); try { velocityEngine.mergeTemplate(template, "UTF-8", context, writer); } catch (Exception e) { } } public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } public Config getConfig() { return config; } public void setConfig(Config config) { this.config = config; } }<|fim▁end|>
import org.apache.velocity.app.VelocityEngine;
<|file_name|>media_player.py<|end_file_name|><|fim▁begin|>"""Support to interface with the Plex API.""" from __future__ import annotations from functools import wraps import json import logging import plexapi.exceptions import requests.exceptions from homeassistant.components.media_player import DOMAIN as MP_DOMAIN, MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_TYPE_MUSIC, SUPPORT_BROWSE_MEDIA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_STOP, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_IDLE, STATE_PAUSED, STATE_PLAYING from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.network import is_internal_request from .const import ( COMMON_PLAYERS, CONF_SERVER_IDENTIFIER, DISPATCHERS, DOMAIN as PLEX_DOMAIN, NAME_FORMAT, PLEX_NEW_MP_SIGNAL, PLEX_UPDATE_MEDIA_PLAYER_SESSION_SIGNAL, PLEX_UPDATE_MEDIA_PLAYER_SIGNAL, PLEX_UPDATE_SENSOR_SIGNAL, PLEX_URI_SCHEME, SERVERS, TRANSIENT_DEVICE_MODELS, ) from .media_browser import browse_media _LOGGER = logging.getLogger(__name__) def needs_session(func): """Ensure session is available for certain attributes.""" @wraps(func) def get_session_attribute(self, *args): if self.session is None: return None return func(self, *args) return get_session_attribute async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Plex media_player from a config entry.""" server_id = config_entry.data[CONF_SERVER_IDENTIFIER] registry = await async_get_registry(hass) @callback def async_new_media_players(new_entities): _async_add_entities(hass, registry, async_add_entities, server_id, new_entities) unsub = async_dispatcher_connect( hass, PLEX_NEW_MP_SIGNAL.format(server_id), async_new_media_players ) hass.data[PLEX_DOMAIN][DISPATCHERS][server_id].append(unsub) _LOGGER.debug("New entity listener created") @callback def _async_add_entities(hass, registry, async_add_entities, server_id, new_entities): """Set up Plex media_player entities.""" _LOGGER.debug("New entities: %s", new_entities) entities = [] plexserver = hass.data[PLEX_DOMAIN][SERVERS][server_id] for entity_params in new_entities: plex_mp = PlexMediaPlayer(plexserver, **entity_params) entities.append(plex_mp) # Migration to per-server unique_ids old_entity_id = registry.async_get_entity_id( MP_DOMAIN, PLEX_DOMAIN, plex_mp.machine_identifier ) if old_entity_id is not None: new_unique_id = f"{server_id}:{plex_mp.machine_identifier}" _LOGGER.debug( "Migrating unique_id from [%s] to [%s]", plex_mp.machine_identifier, new_unique_id,<|fim▁hole|> ) registry.async_update_entity(old_entity_id, new_unique_id=new_unique_id) async_add_entities(entities, True) class PlexMediaPlayer(MediaPlayerEntity): """Representation of a Plex device.""" def __init__(self, plex_server, device, player_source, session=None): """Initialize the Plex device.""" self.plex_server = plex_server self.device = device self.player_source = player_source self.device_make = None self.device_platform = None self.device_product = None self.device_title = None self.device_version = None self.machine_identifier = device.machineIdentifier self.session_device = None self._device_protocol_capabilities = None self._previous_volume_level = 1 # Used in fake muting self._volume_level = 1 # since we can't retrieve remotely self._volume_muted = False # since we can't retrieve remotely self._attr_available = False self._attr_should_poll = False self._attr_state = STATE_IDLE self._attr_unique_id = ( f"{self.plex_server.machine_identifier}:{self.machine_identifier}" ) # Initializes other attributes self.session = session async def async_added_to_hass(self): """Run when about to be added to hass.""" _LOGGER.debug("Added %s [%s]", self.entity_id, self.unique_id) self.async_on_remove( async_dispatcher_connect( self.hass, PLEX_UPDATE_MEDIA_PLAYER_SIGNAL.format(self.unique_id), self.async_refresh_media_player, ) ) self.async_on_remove( async_dispatcher_connect( self.hass, PLEX_UPDATE_MEDIA_PLAYER_SESSION_SIGNAL.format(self.unique_id), self.async_update_from_websocket, ) ) @callback def async_refresh_media_player(self, device, session, source): """Set instance objects and trigger an entity state update.""" _LOGGER.debug("Refreshing %s [%s / %s]", self.entity_id, device, session) self.device = device self.session = session if source: self.player_source = source self.async_schedule_update_ha_state(True) async_dispatcher_send( self.hass, PLEX_UPDATE_SENSOR_SIGNAL.format(self.plex_server.machine_identifier), ) @callback def async_update_from_websocket(self, state): """Update the entity based on new websocket data.""" self.update_state(state) self.async_write_ha_state() async_dispatcher_send( self.hass, PLEX_UPDATE_SENSOR_SIGNAL.format(self.plex_server.machine_identifier), ) def update(self): """Refresh key device data.""" if not self.session: self.force_idle() if not self.device: self._attr_available = False return self._attr_available = True try: device_url = self.device.url("/") except plexapi.exceptions.BadRequest: device_url = "127.0.0.1" if "127.0.0.1" in device_url: self.device.proxyThroughServer() self._device_protocol_capabilities = self.device.protocolCapabilities for device in filter(None, [self.device, self.session_device]): self.device_make = self.device_make or device.device self.device_platform = self.device_platform or device.platform self.device_product = self.device_product or device.product self.device_title = self.device_title or device.title self.device_version = self.device_version or device.version name_parts = [self.device_product, self.device_title or self.device_platform] if (self.device_product in COMMON_PLAYERS) and self.device_make: # Add more context in name for likely duplicates name_parts.append(self.device_make) if self.username and self.username != self.plex_server.owner: # Prepend username for shared/managed clients name_parts.insert(0, self.username) self._attr_name = NAME_FORMAT.format(" - ".join(name_parts)) def force_idle(self): """Force client to idle.""" self._attr_state = STATE_IDLE if self.player_source == "session": self.device = None self.session_device = None self._attr_available = False @property def session(self): """Return the active session for this player.""" return self._session @session.setter def session(self, session): self._session = session if session: self.session_device = self.session.player self.update_state(self.session.state) else: self._attr_state = STATE_IDLE @property @needs_session def username(self): """Return the username of the client owner.""" return self.session.username def update_state(self, state): """Set the state of the device, handle session termination.""" if state == "playing": self._attr_state = STATE_PLAYING elif state == "paused": self._attr_state = STATE_PAUSED elif state == "stopped": self.session = None self.force_idle() else: self._attr_state = STATE_IDLE @property def _is_player_active(self): """Report if the client is playing media.""" return self.state in (STATE_PLAYING, STATE_PAUSED) @property def _active_media_plexapi_type(self): """Get the active media type required by PlexAPI commands.""" if self.media_content_type is MEDIA_TYPE_MUSIC: return "music" return "video" @property @needs_session def session_key(self): """Return current session key.""" return self.session.sessionKey @property @needs_session def media_library_title(self): """Return the library name of playing media.""" return self.session.media_library_title @property @needs_session def media_content_id(self): """Return the content ID of current playing media.""" return self.session.media_content_id @property @needs_session def media_content_type(self): """Return the content type of current playing media.""" return self.session.media_content_type @property @needs_session def media_content_rating(self): """Return the content rating of current playing media.""" return self.session.media_content_rating @property @needs_session def media_artist(self): """Return the artist of current playing media, music track only.""" return self.session.media_artist @property @needs_session def media_album_name(self): """Return the album name of current playing media, music track only.""" return self.session.media_album_name @property @needs_session def media_album_artist(self): """Return the album artist of current playing media, music only.""" return self.session.media_album_artist @property @needs_session def media_track(self): """Return the track number of current playing media, music only.""" return self.session.media_track @property @needs_session def media_duration(self): """Return the duration of current playing media in seconds.""" return self.session.media_duration @property @needs_session def media_position(self): """Return the duration of current playing media in seconds.""" return self.session.media_position @property @needs_session def media_position_updated_at(self): """When was the position of the current playing media valid.""" return self.session.media_position_updated_at @property @needs_session def media_image_url(self): """Return the image URL of current playing media.""" return self.session.media_image_url @property @needs_session def media_summary(self): """Return the summary of current playing media.""" return self.session.media_summary @property @needs_session def media_title(self): """Return the title of current playing media.""" return self.session.media_title @property @needs_session def media_season(self): """Return the season of current playing media (TV Show only).""" return self.session.media_season @property @needs_session def media_series_title(self): """Return the title of the series of current playing media.""" return self.session.media_series_title @property @needs_session def media_episode(self): """Return the episode of current playing media (TV Show only).""" return self.session.media_episode @property def supported_features(self): """Flag media player features that are supported.""" if self.device and "playback" in self._device_protocol_capabilities: return ( SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_STOP | SUPPORT_SEEK | SUPPORT_VOLUME_SET | SUPPORT_PLAY | SUPPORT_PLAY_MEDIA | SUPPORT_VOLUME_MUTE | SUPPORT_BROWSE_MEDIA ) return SUPPORT_BROWSE_MEDIA | SUPPORT_PLAY_MEDIA def set_volume_level(self, volume): """Set volume level, range 0..1.""" if self.device and "playback" in self._device_protocol_capabilities: self.device.setVolume(int(volume * 100), self._active_media_plexapi_type) self._volume_level = volume # store since we can't retrieve @property def volume_level(self): """Return the volume level of the client (0..1).""" if ( self._is_player_active and self.device and "playback" in self._device_protocol_capabilities ): return self._volume_level return None @property def is_volume_muted(self): """Return boolean if volume is currently muted.""" if self._is_player_active and self.device: return self._volume_muted return None def mute_volume(self, mute): """Mute the volume. Since we can't actually mute, we'll: - On mute, store volume and set volume to 0 - On unmute, set volume to previously stored volume """ if not (self.device and "playback" in self._device_protocol_capabilities): return self._volume_muted = mute if mute: self._previous_volume_level = self._volume_level self.set_volume_level(0) else: self.set_volume_level(self._previous_volume_level) def media_play(self): """Send play command.""" if self.device and "playback" in self._device_protocol_capabilities: self.device.play(self._active_media_plexapi_type) def media_pause(self): """Send pause command.""" if self.device and "playback" in self._device_protocol_capabilities: self.device.pause(self._active_media_plexapi_type) def media_stop(self): """Send stop command.""" if self.device and "playback" in self._device_protocol_capabilities: self.device.stop(self._active_media_plexapi_type) def media_seek(self, position): """Send the seek command.""" if self.device and "playback" in self._device_protocol_capabilities: self.device.seekTo(position * 1000, self._active_media_plexapi_type) def media_next_track(self): """Send next track command.""" if self.device and "playback" in self._device_protocol_capabilities: self.device.skipNext(self._active_media_plexapi_type) def media_previous_track(self): """Send previous track command.""" if self.device and "playback" in self._device_protocol_capabilities: self.device.skipPrevious(self._active_media_plexapi_type) def play_media(self, media_type, media_id, **kwargs): """Play a piece of media.""" if not (self.device and "playback" in self._device_protocol_capabilities): raise HomeAssistantError( f"Client is not currently accepting playback controls: {self.name}" ) if not self.plex_server.has_token: _LOGGER.warning( "Plex integration configured without a token, playback may fail" ) if media_id.startswith(PLEX_URI_SCHEME): media_id = media_id[len(PLEX_URI_SCHEME) :] if media_type == "station": playqueue = self.plex_server.create_station_playqueue(media_id) try: self.device.playMedia(playqueue) except requests.exceptions.ConnectTimeout as exc: raise HomeAssistantError( f"Request failed when playing on {self.name}" ) from exc return src = json.loads(media_id) if isinstance(src, int): src = {"plex_key": src} offset = 0 if playqueue_id := src.pop("playqueue_id", None): try: playqueue = self.plex_server.get_playqueue(playqueue_id) except plexapi.exceptions.NotFound as err: raise HomeAssistantError( f"PlayQueue '{playqueue_id}' could not be found" ) from err else: shuffle = src.pop("shuffle", 0) offset = src.pop("offset", 0) * 1000 resume = src.pop("resume", False) media = self.plex_server.lookup_media(media_type, **src) if media is None: raise HomeAssistantError(f"Media could not be found: {media_id}") if resume and not offset: offset = media.viewOffset _LOGGER.debug("Attempting to play %s on %s", media, self.name) playqueue = self.plex_server.create_playqueue(media, shuffle=shuffle) try: self.device.playMedia(playqueue, offset=offset) except requests.exceptions.ConnectTimeout as exc: raise HomeAssistantError( f"Request failed when playing on {self.name}" ) from exc @property def extra_state_attributes(self): """Return the scene state attributes.""" attributes = {} for attr in ( "media_content_rating", "media_library_title", "player_source", "media_summary", "username", ): if value := getattr(self, attr, None): attributes[attr] = value return attributes @property def device_info(self) -> DeviceInfo: """Return a device description for device registry.""" if self.machine_identifier is None: return None if self.device_product in TRANSIENT_DEVICE_MODELS: return DeviceInfo( identifiers={(PLEX_DOMAIN, "plex.tv-clients")}, name="Plex Client Service", manufacturer="Plex", model="Plex Clients", entry_type=DeviceEntryType.SERVICE, ) return DeviceInfo( identifiers={(PLEX_DOMAIN, self.machine_identifier)}, manufacturer=self.device_platform or "Plex", model=self.device_product or self.device_make, name=self.name, sw_version=self.device_version, via_device=(PLEX_DOMAIN, self.plex_server.machine_identifier), ) async def async_browse_media(self, media_content_type=None, media_content_id=None): """Implement the websocket media browsing helper.""" is_internal = is_internal_request(self.hass) return await self.hass.async_add_executor_job( browse_media, self.plex_server, is_internal, media_content_type, media_content_id, )<|fim▁end|>
<|file_name|>ConfidentialityClass.java<|end_file_name|><|fim▁begin|>// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.12.23 at 08:29:00 AM CST // package ca.ieso.reports.schema.iomspublicplannedoutageday; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ConfidentialityClass. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ConfidentialityClass"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="PUB"/> * &lt;enumeration value="CNF"/> * &lt;enumeration value="HCNF"/> * &lt;enumeration value="INT"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ConfidentialityClass") @XmlEnum public enum ConfidentialityClass { PUB, CNF, HCNF, INT; <|fim▁hole|> public static ConfidentialityClass fromValue(String v) { return valueOf(v); } }<|fim▁end|>
public String value() { return name(); }
<|file_name|>param_util.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramfile(aFile) cmtkey_list = [] for line in data: if line.find('CMT') >= 0: sidx = line.find('CMT') cmtkey_list.append(line[sidx:sidx+5]) return cmtkey_list def find_cmt_start_idx(data, cmtkey): ''' Finds the starting index for a CMT data block in a list of lines. Parameters ---------- data : [str, str, ...] A list of strings (maybe from a parameter file) cmtkey : str A a CMT code string like 'CMT05' to search for in the list. Returns ------- i : int The first index in the list where the CMT key is found. If key is not found returns None. ''' for i, line in enumerate(data): if cmtkey.upper() in line: return i # Key not found return None def read_paramfile(thefile): ''' Opens and reads a file, returning the data as a list of lines (with newlines). Parameters ---------- theFile : str A path to a file to open and read. Returns ------- d : [str, str, str, ...] A list of strings (with newlines at the end of each string). ''' with open(thefile, 'r') as f: data = f.readlines() return data def get_CMT_datablock(afile, cmtnum): ''' Search file, returns the first block of data for one CMT as a list of strings. Parameters ---------- afile : str Path to a file to search. cmtnum : int The CMT number to search for. Converted (internally) to the CMT key. Returns ------- d : [str, str, ...] A list of strings, one item for each line in the CMT's datablock. Each string will have a newline charachter in it. ''' data = read_paramfile(afile) cmtkey = 'CMT%02i' % cmtnum startidx = find_cmt_start_idx(data, cmtkey) end = None for i, line in enumerate(data[startidx:]): if i == 0: # Header line, e.g.: "// CMT07 // Heath Tundra - (ma....."" pass elif i == 1: # PFT name line, e,g.: "//Decid. E.green ...." # Not sure how/why this is working on non-PFT data blocks # but is seems to do the trick? pass if (i > 0) and "CMT" in line: #print "end of datablock, i=", i end = startidx + i break return data[startidx:end] def detect_block_with_pft_info(cmtdatablock): # Perhaps should look at all lines?? secondline = cmtdatablock[1].strip("//").split() if len(secondline) >= 9: #print "Looks like a PFT header line!" return True else: return False def parse_header_line(datablock): '''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma..... ''' # Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment def get_pft_verbose_name(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: raise ValueError("you must provide only one of pftkey or pftnumber") if cmtkey: # convert to number cmtnum = int(cmtkey.lstrip('CMT')) if pftnum: # convert to key pftkey = 'pft%i' % pftnum data = get_CMT_datablock(os.path.join(path2params, 'cmt_calparbgc.txt'), cmtnum) dd = cmtdatablock2dict(data) return dd[pftkey.lower()]['name'] def cmtdatablock2dict(cmtdatablock): ''' Converts a "CMT datablock" (list of strings) into a dict structure. Parameters ---------- cmtdatablock : [str, str, ...] A list of strings (with new lines) holding parameter data for a CMT. Returns ------- d : dict A multi-level dict mapping names (deduced from comments) to parameter values.holding parameter values. ''' cmtdict = {} pftblock = detect_block_with_pft_info(cmtdatablock) hdr_cmtkey, txtcmtname, hdrcomment = parse_header_line(cmtdatablock) cmtdict['tag'] = hdr_cmtkey cmtdict['cmtname'] = txtcmtname cmtdict['comment'] = hdrcomment if pftblock: # Look at the second line for something like this: # PFT name line, like: "//Decid. E.green ...." pftlist = cmtdatablock[1].strip("//").strip().split() pftnames = pftlist[0:10] for i, pftname in enumerate(pftnames): cmtdict['pft%i'%i] = {} cmtdict['pft%i'%i]['name'] = pftname for i, line in enumerate(cmtdatablock): if line.strip()[0:2] == "//": #print "passing line", i continue # Nothing to do...commented line else: # normal data line dline = line.strip().split("//") values = dline[0].split() comment = dline[1].strip().strip("//").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(value) else: cmtdict[comment] = float(values[0]) return cmtdict def format_CMTdatadict(dd, refFile, format=None): ''' Returns a formatted block of CMT data. Parameters ---------- dd : dict Dictionary containing parameter names and values for a CMT. refFile : str A path to a file that should be used for reference in formatting the output. format : str (optional) A string specifying which format to return. Defaults to None. Returns ------- d : [str, str, ...] A list of strings ''' if format is not None: print "NOT IMPLEMENTED YET!" exit(-1) ref_order = generate_reference_order(refFile) dwpftvs = False ll = [] ll.append("// First line comment...") ll.append("// Second line comment (?? PFT string?)") def is_pft_var(v): if v not in dd.keys() and v in dd['pft0'].keys(): return True else: return False for var in ref_order: if not is_pft_var(var): pass else: # get each item from dict, append to line linestring = '' for pft in get_datablock_pftkeys(dd): linestring += "{:>12.6f} ".format(dd[pft][var]) linestring += ('// %s: ' % var) ll.append(linestring) for var in ref_order: if is_pft_var(var): pass # Nothing to do; already did pft stuff else: # get item from dict, append to line ll.append('{:<12.5f} // comment??'.format(dd[var])) return ll def generate_reference_order(aFile): ''' Lists order that variables should be in in a parameter file based on CMT 0. Parameters ---------- aFile: str The file to use as a base. Returns ------- l : [str, str, ...] A list of strings containing the variable names, parsed from the input file in the order they appear in the input file. ''' cmt_calparbgc = [] db = get_CMT_datablock(aFile, 0) pftblock = detect_block_with_pft_info(db) ref_order = [] for line in db: t = comment_splitter(line) if t[0] == '': pass # nothing before the comment, ignore this line - is has no data else: # looks like t0 has some data, so now we need the # comment (t[1]) which we will further refine to get the # tag, which we will append to the "reference order" list tokens = t[1].strip().lstrip("//").strip().split(":") tag = tokens[0] desc = "".join(tokens[1:]) print "Found tag:", tag, " Desc: ", desc ref_order.append(tag) return ref_order def comment_splitter(line): ''' Splits a string into data before comment and after comment. The comment delimiter ('//') will be included in the after component. Parameters ---------- line : str A string representing the line of data. May or may not contain the comment delimiter. Returns ------- t : (str, str) - Tuple of strings. A tuple containing the "before comment" string, and the "after comment" string. The "after commnet" string will include the comment charachter. ''' cmtidx = line.find("//") if cmtidx < 0: return (line, '') else: return (line[0:cmtidx], line[cmtidx:]) def get_datablock_pftkeys(dd): ''' Returns a sorted list of the pft keys present in a CMT data dictionary.<|fim▁hole|> dd : dict A CMT data dictionary (as might be created from cmtdatablock2dict(..)). Returns ------- A sorted list of the keys present in dd that contain the string 'pft'. ''' return sorted([i for i in dd.keys() if 'pft' in i]) def enforce_initvegc_split(aFile, cmtnum): ''' Makes sure that the 'cpart' compartments variables match the proportions set in initvegc variables in a cmt_bgcvegetation.txt file. The initvegc(leaf, wood, root) variables in cmt_bgcvegetation.txt are the measured values from literature. The cpar(leaf, wood, root) variables, which are in the same file, should be set to the fractional make up of the the components. So if the initvegc values for l, w, r are 100, 200, 300, then the cpart values should be 0.166, 0.33, and 0.5. It is very easy for these values to get out of sync when users manually update the parameter file. Parameters ---------- aFile : str Path to a parameter file to work on. Must have bgcvegetation.txt in the name and must be a 'bgcvegetation' parameter file for this function to make sense and work. cmtnum : int The community number in the file to work on. Returns ------- d : dict A CMT data dictionary with the updated cpart values. ''' if ('bgcvegetation.txt' not in aFile): raise ValueError("This function only makes sense on cmt_bgcvegetation.txt files.") d = get_CMT_datablock(aFile, cmtnum) dd = cmtdatablock2dict(d) for pft in get_datablock_pftkeys(dd): sumC = dd[pft]['initvegcl'] + dd[pft]['initvegcw'] + dd[pft]['initvegcr'] if sumC > 0.0: dd[pft]['cpartl'] = dd[pft]['initvegcl'] / sumC dd[pft]['cpartw'] = dd[pft]['initvegcw'] / sumC dd[pft]['cpartr'] = dd[pft]['initvegcr'] / sumC else: dd[pft]['cpartl'] = 0.0 dd[pft]['cpartw'] = 0.0 dd[pft]['cpartr'] = 0.0 return dd if __name__ == '__main__': print "NOTE! Does not work correctly on non-PFT files yet!!" testFiles = [ 'parameters/cmt_calparbgc.txt', 'parameters/cmt_bgcsoil.txt', 'parameters/cmt_bgcvegetation.txt', 'parameters/cmt_calparbgc.txt.backupsomeparams', 'parameters/cmt_dimground.txt', 'parameters/cmt_dimvegetation.txt', 'parameters/cmt_envcanopy.txt', 'parameters/cmt_envground.txt', 'parameters/cmt_firepar.txt' ] for i in testFiles: print "{:>45s}: {}".format(i, get_CMTs_in_file(i)) # for i in testFiles: # print "{:>45s}".format(i) # print "".join(get_CMT_datablock(i, 2)) # print "{:45s}".format("DONE") d = get_CMT_datablock(testFiles[4], 2) print "".join(d) print json.dumps(cmtdatablock2dict(d), sort_keys=True, indent=2) print "NOTE! Does not work correctly on non-PFT files yet!!"<|fim▁end|>
Parameters ----------
<|file_name|>db_log_parser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2011-present, Facebook, Inc. All rights reserved. # This source code is licensed under both the GPLv2 (found in the # COPYING file in the root directory) and Apache 2.0 License # (found in the LICENSE.Apache file in the root directory). from abc import ABC, abstractmethod from calendar import timegm from enum import Enum import glob import re import time NO_COL_FAMILY = 'DB_WIDE' class DataSource(ABC): class Type(Enum): LOG = 1 DB_OPTIONS = 2 TIME_SERIES = 3 def __init__(self, type): self.type = type @abstractmethod def check_and_trigger_conditions(self, conditions): pass <|fim▁hole|> def is_new_log(log_line): # The assumption is that a new log will start with a date printed in # the below regex format. date_regex = '\d{4}/\d{2}/\d{2}-\d{2}:\d{2}:\d{2}\.\d{6}' return re.match(date_regex, log_line) def __init__(self, log_line, column_families): token_list = log_line.strip().split() self.time = token_list[0] self.context = token_list[1] self.message = " ".join(token_list[2:]) self.column_family = None # example log for 'default' column family: # "2018/07/25-17:29:05.176080 7f969de68700 [db/compaction_job.cc:1634] # [default] [JOB 3] Compacting 24@0 + 16@1 files to L1, score 6.00\n" for col_fam in column_families: search_for_str = '\[' + col_fam + '\]' if re.search(search_for_str, self.message): self.column_family = col_fam break if not self.column_family: self.column_family = NO_COL_FAMILY def get_human_readable_time(self): # example from a log line: '2018/07/25-11:25:45.782710' return self.time def get_column_family(self): return self.column_family def get_context(self): return self.context def get_message(self): return self.message def append_message(self, remaining_log): self.message = self.message + '\n' + remaining_log.strip() def get_timestamp(self): # example: '2018/07/25-11:25:45.782710' will be converted to the GMT # Unix timestamp 1532517945 (note: this method assumes that self.time # is in GMT) hr_time = self.time + 'GMT' timestamp = timegm(time.strptime(hr_time, "%Y/%m/%d-%H:%M:%S.%f%Z")) return timestamp def __repr__(self): return ( 'time: ' + self.time + '; context: ' + self.context + '; col_fam: ' + self.column_family + '; message: ' + self.message ) class DatabaseLogs(DataSource): def __init__(self, logs_path_prefix, column_families): super().__init__(DataSource.Type.LOG) self.logs_path_prefix = logs_path_prefix self.column_families = column_families def trigger_conditions_for_log(self, conditions, log): # For a LogCondition object, trigger is: # Dict[column_family_name, List[Log]]. This explains why the condition # was triggered and for which column families. for cond in conditions: if re.search(cond.regex, log.get_message(), re.IGNORECASE): trigger = cond.get_trigger() if not trigger: trigger = {} if log.get_column_family() not in trigger: trigger[log.get_column_family()] = [] trigger[log.get_column_family()].append(log) cond.set_trigger(trigger) def check_and_trigger_conditions(self, conditions): for file_name in glob.glob(self.logs_path_prefix + '*'): # TODO(poojam23): find a way to distinguish between log files # - generated in the current experiment but are labeled 'old' # because they LOGs exceeded the file size limit AND # - generated in some previous experiment that are also labeled # 'old' and were not deleted for some reason if re.search('old', file_name, re.IGNORECASE): continue with open(file_name, 'r') as db_logs: new_log = None for line in db_logs: if Log.is_new_log(line): if new_log: self.trigger_conditions_for_log( conditions, new_log ) new_log = Log(line, self.column_families) else: # To account for logs split into multiple lines new_log.append_message(line) # Check for the last log in the file. if new_log: self.trigger_conditions_for_log(conditions, new_log)<|fim▁end|>
class Log: @staticmethod
<|file_name|>medea.light.js<|end_file_name|><|fim▁begin|>/* medea.js - Open Source, High-Performance 3D Engine based on WebGL. * * (c) 2011-2013, Alexander C. Gessler * https://github.com/acgessler/medea.js * * Made available under the terms and conditions of a 3-clause BSD license. * */ medealib.define('light', ['entity', 'renderer'],function(medealib, undefined) { "use strict"; var medea = this, gl = medea.gl; // class LightJob medea.LightJob = medea.RenderJob.extend({ distance : null, light : null, init : function(light, node, camera) { this._super(light, node, camera); this.light = light; }, Draw : function(renderer, statepool) { renderer.DrawLight(this, statepool); }, }); // class Light this.Light = medea.Entity.extend( { cast_shadows : false, shadowmap_res_bias : 0, rq_idx : -1, init : function(color, rq) { this.color = color || [1,1,1]; this.rq_idx = rq === undefined ? medea.RENDERQUEUE_LIGHT : rq; }, Render : function(camera, node, rqmanager) { // Construct a renderable capable of drawing this light later rqmanager.Push(this.rq_idx, new medea.LightJob(this, node, camera)); }, CastShadows : medealib.Property('cast_shadows'), ShadowMapResolutionBias : medealib.Property('shadowmap_res_bias'), }); // class DirectionalLight this.DirectionalLight = medea.Light.extend( { dir : null, init : function(color, dir) { this._super(color); this.dir = vec3.create(dir || [0,-1,0]); vec3.normalize(this.dir); }, Direction : function(dir) { if (dir === undefined) { return this.dir; }<|fim▁hole|> vec3.normalize(this.dir); }, }); medea.CreateDirectionalLight = function(color, dir) { return new medea.DirectionalLight(color, dir); }; });<|fim▁end|>
this.dir = vec3.create(dir);
<|file_name|>DistinctOperator.java<|end_file_name|><|fim▁begin|>package org.qcri.rheem.basic.operators; import org.apache.commons.lang3.Validate; import org.qcri.rheem.core.api.Configuration; import org.qcri.rheem.core.function.DistinctPredicateDescriptor; import org.qcri.rheem.core.function.PredicateDescriptor; import org.qcri.rheem.core.optimizer.OptimizationContext; import org.qcri.rheem.core.optimizer.ProbabilisticDoubleInterval; import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimate; import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator; import org.qcri.rheem.core.optimizer.cardinality.DefaultCardinalityEstimator; import org.qcri.rheem.core.plan.rheemplan.UnaryToUnaryOperator; import org.qcri.rheem.core.types.DataSetType; import java.util.Optional; /** * This operator returns the distinct elements in this dataset. */ public class DistinctOperator<Type> extends UnaryToUnaryOperator<Type, Type> { protected final DistinctPredicateDescriptor<Type> predicateDescriptor; /** * Creates a new instance. * * @param type type of the dataunit elements */ public DistinctOperator(DataSetType<Type> type) { super(type, type, false); this.predicateDescriptor = null; } public DistinctOperator(DataSetType<Type> type, DistinctPredicateDescriptor<Type> predicateDescriptor) { super(type, type, false); this.predicateDescriptor = predicateDescriptor; } /** * Creates a new instance. *<|fim▁hole|> public DistinctOperator(Class<Type> typeClass) { this(DataSetType.createDefault(typeClass)); } /** * Copies an instance (exclusive of broadcasts). * * @param that that should be copied */ public DistinctOperator(DistinctOperator<Type> that) { super(that); this.predicateDescriptor = that.getPredicateDescriptor(); } public DistinctPredicateDescriptor<Type> getPredicateDescriptor() { return this.predicateDescriptor; } public String getSelectKeyString(){ if (this.getPredicateDescriptor() != null && this.getPredicateDescriptor().getUdfSelectivity() != null){ return this.getPredicateDescriptor().getUdfSelectivityKeyString(); } else { return ""; } } // // Assume with a confidence of 0.7 that 70% of the data quanta are pairwise distinct. // return Optional.of(new DefaultCardinalityEstimator(0.7d, 1, this.isSupportingBroadcastInputs(), // inputCards -> (long) (inputCards[0] * 0.7d))); // TODO JRK: Do not make baseline worse @Override public Optional<org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator> createCardinalityEstimator( final int outputIndex, final Configuration configuration) { Validate.inclusiveBetween(0, this.getNumOutputs() - 1, outputIndex); return Optional.of(new DistinctOperator.CardinalityEstimator(configuration)); } private class CardinalityEstimator implements org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator { /** * The expected selectivity to be applied in this instance. */ private final ProbabilisticDoubleInterval selectivity; Configuration configuration; public CardinalityEstimator(Configuration configuration) { this.selectivity = configuration.getUdfSelectivityProvider().provideFor(DistinctOperator.this.predicateDescriptor); this.configuration = configuration; } @Override public CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates) { Validate.isTrue(inputEstimates.length == DistinctOperator.this.getNumInputs()); final CardinalityEstimate inputEstimate = inputEstimates[0]; String mode = this.configuration.getStringProperty("rheem.optimizer.sr.mode", "best"); if (mode.equals("best")){ mode = this.selectivity.getBest(); } if (mode.equals("lin")) { return new CardinalityEstimate( (long) Math.max(0, ((inputEstimate.getLowerEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getLowerEstimate())), (long) Math.max(0, ((inputEstimate.getUpperEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } else if (mode.equals("log")) { return new CardinalityEstimate( (long) Math.max(0, ((Math.log(inputEstimate.getLowerEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getLowerEstimate())), (long) Math.max(0, ((Math.log(inputEstimate.getUpperEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } else { return new CardinalityEstimate( (long) Math.max(0, (inputEstimate.getLowerEstimate() * this.selectivity.getLowerEstimate())), (long) Math.max(0, (inputEstimate.getUpperEstimate() * this.selectivity.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } } } }<|fim▁end|>
* @param typeClass type of the dataunit elements */
<|file_name|>mock.rs<|end_file_name|><|fim▁begin|>use std::fmt; use std::ascii::AsciiExt; use std::io::{self, Read, Write, Cursor}; use std::cell::RefCell; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use solicit::http::HttpScheme; use solicit::http::transport::TransportStream; use solicit::http::frame::{SettingsFrame, Frame}; use solicit::http::connection::{HttpConnection, EndStream, DataChunk}; use header::Headers; use net::{NetworkStream, NetworkConnector}; pub struct MockStream { pub read: Cursor<Vec<u8>>, pub write: Vec<u8>, } impl Clone for MockStream { fn clone(&self) -> MockStream { MockStream { read: Cursor::new(self.read.get_ref().clone()), write: self.write.clone() } } } impl fmt::Debug for MockStream { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "MockStream {{ read: {:?}, write: {:?} }}", self.read.get_ref(), self.write) } } impl PartialEq for MockStream { fn eq(&self, other: &MockStream) -> bool { self.read.get_ref() == other.read.get_ref() && self.write == other.write } } impl MockStream { pub fn new() -> MockStream { MockStream { read: Cursor::new(vec![]), write: vec![], } } pub fn with_input(input: &[u8]) -> MockStream { MockStream { read: Cursor::new(input.to_vec()), write: vec![] } } } impl Read for MockStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.read.read(buf) } } impl Write for MockStream { fn write(&mut self, msg: &[u8]) -> io::Result<usize> { Write::write(&mut self.write, msg) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl NetworkStream for MockStream { fn peer_addr(&mut self) -> io::Result<SocketAddr> { Ok("127.0.0.1:1337".parse().unwrap()) } } /// A wrapper around a `MockStream` that allows one to clone it and keep an independent copy to the /// same underlying stream. #[derive(Clone)] pub struct CloneableMockStream { pub inner: Arc<Mutex<MockStream>>, } impl Write for CloneableMockStream { fn write(&mut self, msg: &[u8]) -> io::Result<usize> { self.inner.lock().unwrap().write(msg) } fn flush(&mut self) -> io::Result<()> { self.inner.lock().unwrap().flush() } } impl Read for CloneableMockStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.inner.lock().unwrap().read(buf) } } impl TransportStream for CloneableMockStream { fn try_split(&self) -> Result<CloneableMockStream, io::Error> { Ok(self.clone()) } fn close(&mut self) -> Result<(), io::Error> { Ok(()) } } impl NetworkStream for CloneableMockStream { fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.inner.lock().unwrap().peer_addr() } } impl CloneableMockStream { pub fn with_stream(stream: MockStream) -> CloneableMockStream { CloneableMockStream { inner: Arc::new(Mutex::new(stream)), } } } pub struct MockConnector; impl NetworkConnector for MockConnector { type Stream = MockStream; fn connect(&self, _host: &str, _port: u16, _scheme: &str) -> ::Result<MockStream> { Ok(MockStream::new()) } } /// new connectors must be created if you wish to intercept requests. macro_rules! mock_connector ( ($name:ident { $($url:expr => $res:expr)* }) => ( struct $name; impl ::net::NetworkConnector for $name { type Stream = ::mock::MockStream; fn connect(&self, host: &str, port: u16, scheme: &str) -> $crate::Result<::mock::MockStream> { use std::collections::HashMap; use std::io::Cursor; debug!("MockStream::connect({:?}, {:?}, {:?})", host, port, scheme); let mut map = HashMap::new(); $(map.insert($url, $res);)* let key = format!("{}://{}", scheme, host); // ignore port for now match map.get(&*key) { Some(&res) => Ok($crate::mock::MockStream { write: vec![], read: Cursor::new(res.to_owned().into_bytes()), }), None => panic!("{:?} doesn't know url {}", stringify!($name), key) } } } ) ); impl TransportStream for MockStream { fn try_split(&self) -> Result<MockStream, io::Error> { Ok(self.clone()) } fn close(&mut self) -> Result<(), io::Error> { Ok(()) } } impl MockStream { /// Creates a new `MockStream` that will return the response described by the parameters as an /// HTTP/2 response. This will also include the correct server preface. pub fn new_http2_response(status: &[u8], headers: &Headers, body: Option<Vec<u8>>) -> MockStream { let resp_bytes = build_http2_response(status, headers, body); MockStream::with_input(&resp_bytes) } } /// Builds up a sequence of bytes that represent a server's response based on the given parameters. pub fn build_http2_response(status: &[u8], headers: &Headers, body: Option<Vec<u8>>) -> Vec<u8> { let mut conn = HttpConnection::new(MockStream::new(), MockStream::new(), HttpScheme::Http); // Server preface first conn.sender.write(&SettingsFrame::new().serialize()).unwrap(); let mut resp_headers: Vec<_> = headers.iter().map(|h| { (h.name().to_ascii_lowercase().into_bytes(), h.value_string().into_bytes()) }).collect(); resp_headers.insert(0, (b":status".to_vec(), status.into())); let end = if body.is_none() { EndStream::Yes } else { EndStream::No }; conn.send_headers(resp_headers, 1, end).unwrap(); if body.is_some() { let chunk = DataChunk::new_borrowed(&body.as_ref().unwrap()[..], 1, EndStream::Yes); conn.send_data(chunk).unwrap(); } conn.sender.write } /// A mock connector that produces `MockStream`s that are set to return HTTP/2 responses. /// /// This means that the streams' payloads are fairly opaque byte sequences (as HTTP/2 is a binary /// protocol), which can be understood only be HTTP/2 clients. pub struct MockHttp2Connector { /// The list of streams that the connector returns, in the given order. pub streams: RefCell<Vec<CloneableMockStream>>, } impl MockHttp2Connector { /// Creates a new `MockHttp2Connector` with no streams. pub fn new() -> MockHttp2Connector { MockHttp2Connector { streams: RefCell::new(Vec::new()), } } /// Adds a new `CloneableMockStream` to the end of the connector's stream queue. /// /// Streams are returned in a FIFO manner. pub fn add_stream(&mut self, stream: CloneableMockStream) { self.streams.borrow_mut().push(stream); } /// Adds a new response stream that will be placed to the end of the connector's stream queue. /// /// Returns a separate `CloneableMockStream` that allows the user to inspect what is written /// into the original stream. pub fn new_response_stream(&mut self, status: &[u8], headers: &Headers, body: Option<Vec<u8>>) -> CloneableMockStream { let stream = MockStream::new_http2_response(status, headers, body); let stream = CloneableMockStream::with_stream(stream); let ret = stream.clone(); self.add_stream(stream); ret } } impl NetworkConnector for MockHttp2Connector { type Stream = CloneableMockStream; #[inline] fn connect(&self, _host: &str, _port: u16, _scheme: &str)<|fim▁hole|> -> ::Result<CloneableMockStream> { Ok(self.streams.borrow_mut().remove(0)) } }<|fim▁end|>
<|file_name|>TextDocument.ts<|end_file_name|><|fim▁begin|>import isEqual from '../util/isEqual'; import Delta from '../delta/Delta'; import Op from '../delta/Op'; import Line, { LineRanges, LineIds } from './Line'; import LineOp from './LineOp'; import AttributeMap from '../delta/AttributeMap'; import { EditorRange, normalizeRange } from './EditorRange'; import TextChange from './TextChange'; import { deltaToText } from './deltaToText'; const EMPTY_RANGE: EditorRange = [ 0, 0 ]; const EMPTY_OBJ = {}; const DELTA_CACHE = new WeakMap<TextDocument, Delta>(); const excludeProps = new Set([ 'id' ]); export interface FormattingOptions { nameOnly?: boolean; allFormats?: boolean; } export default class TextDocument { private _ranges: LineRanges; byId: LineIds; lines: Line[]; length: number; selection: EditorRange | null; constructor(lines?: TextDocument | Line[] | Delta, selection: EditorRange | null = null) { if (lines instanceof TextDocument) { this.lines = lines.lines; this.byId = lines.byId; this._ranges = lines._ranges; this.length = lines.length; } else { this.byId = new Map(); if (Array.isArray(lines)) { this.lines = lines; } else if (lines) { this.lines = Line.fromDelta(lines); } else { this.lines = [ Line.create() ]; } if (!this.lines.length) { this.lines.push(Line.create()); } this.byId = Line.linesToLineIds(this.lines); // Check for line id duplicates (should never happen, indicates bug) this.lines.forEach(line => { if (this.byId.get(line.id) !== line) throw new Error('TextDocument has duplicate line ids: ' + line.id); }); this._ranges = Line.getLineRanges(this.lines); this.length = this.lines.reduce((length, line) => length + line.length, 0); } this.selection = selection && selection.map(index => Math.min(this.length - 1, Math.max(0, index))) as EditorRange; } get change() { const change = new TextChange(this); change.apply = () => this.apply(change);<|fim▁hole|> getText(range?: EditorRange): string { if (range) range = normalizeRange(range); return deltaToText(range ? this.slice(range[0], range[1]) : this.slice(0, this.length - 1)); } getLineBy(id: string) { return this.byId.get(id) as Line; } getLineAt(at: number) { return this.lines.find(line => { const [ start, end ] = this.getLineRange(line); return start <= at && end > at; }) as Line; } getLinesAt(at: number | EditorRange, encompassed?: boolean) { let to = at as number; if (Array.isArray(at)) [ at, to ] = normalizeRange(at); return this.lines.filter(line => { const [ start, end ] = this.getLineRange(line); return encompassed ? start >= at && end <= to : (start < to || start === at) && end > at; }); } getLineRange(at: number | string | Line): EditorRange { const { lines, _ranges: lineRanges } = this; if (typeof at === 'number') { for (let i = 0; i < lines.length; i++) { const range = lineRanges.get(lines[i]) || EMPTY_RANGE; if (range[0] <= at && range[1] > at) return range; } return EMPTY_RANGE; } else { if (typeof at === 'string') at = this.getLineBy(at); return lineRanges.get(at) as EditorRange; } } getLineRanges(at?: number | EditorRange) { if (at == null) { return Array.from(this._ranges.values()); } else { return this.getLinesAt(at).map(line => this.getLineRange(line)); } } getLineFormat(at: number | EditorRange = this.selection as EditorRange, options?: FormattingOptions) { let to = at as number; if (Array.isArray(at)) [ at, to ] = normalizeRange(at); if (at === to) to++; return getAttributes(Line, this.lines, at, to, undefined, options); } getTextFormat(at: number | EditorRange = this.selection as EditorRange, options?: FormattingOptions) { let to = at as number; if (Array.isArray(at)) [ at, to ] = normalizeRange(at); if (at === to) at--; return getAttributes(LineOp, this.lines, at, to, op => op.insert !== '\n', options); } getFormats(at: number | EditorRange = this.selection as EditorRange, options?: FormattingOptions): AttributeMap { return { ...this.getTextFormat(at, options), ...this.getLineFormat(at, options) }; } slice(start: number = 0, end: number = Infinity): Delta { const ops: Op[] = []; const iter = LineOp.iterator(this.lines); let index = 0; while (index < end && iter.hasNext()) { let nextOp: Op; if (index < start) { nextOp = iter.next(start - index); } else { nextOp = iter.next(end - index); ops.push(nextOp); } index += Op.length(nextOp); } return new Delta(ops); } apply(change: Delta | TextChange, selection?: EditorRange | null, throwOnError?: boolean): TextDocument { let delta: Delta; if (change instanceof TextChange) { delta = change.delta; selection = change.selection; } else { delta = change; } // If no change, do nothing if (!delta.ops.length && (selection === undefined || isEqual(this.selection, selection))) { return this; } // Optimization for selection-only change if (!delta.ops.length && selection) { return new TextDocument(this, selection); } if (selection === undefined && this.selection) { selection = [ delta.transformPosition(this.selection[0]), delta.transformPosition(this.selection[1]) ]; // If the selection hasn't changed, keep the original reference if (isEqual(this.selection, selection)) { selection = this.selection; } } const thisIter = LineOp.iterator(this.lines, this.byId); const otherIter = Op.iterator(delta.ops); let lines: Line[] = []; const firstChange = otherIter.peek(); if (firstChange && firstChange.retain && !firstChange.attributes) { let firstLeft = firstChange.retain; while (thisIter.peekLineLength() <= firstLeft) { firstLeft -= thisIter.peekLineLength(); lines.push(thisIter.nextLine()); } if (firstChange.retain - firstLeft > 0) { otherIter.next(firstChange.retain - firstLeft); } } if (!thisIter.hasNext()) { if (throwOnError) throw new Error('apply() called with change that extends beyond document'); } let line = Line.createFrom(thisIter.peekLine()); // let wentBeyond = false; function addLine(line: Line) { line.length = line.content.length() + 1; lines.push(line); } while (thisIter.hasNext() || otherIter.hasNext()) { if (otherIter.peekType() === 'insert') { const otherOp = otherIter.peek(); const index = typeof otherOp.insert === 'string' ? otherOp.insert.indexOf('\n', otherIter.offset) : -1; if (index < 0) { line.content.push(otherIter.next()); } else { const nextIndex = index - otherIter.offset; if (nextIndex) line.content.push(otherIter.next(nextIndex)); const newlineOp = otherIter.next(1); const nextAttributes = line.attributes; line.attributes = newlineOp.attributes || {}; addLine(line); line = Line.create(undefined, nextAttributes, this.byId); } } else { const length = Math.min(thisIter.peekLength(), otherIter.peekLength()); const thisOp = thisIter.next(length); const otherOp = otherIter.next(length); if (typeof thisOp.retain === 'number') { if (throwOnError) throw new Error('apply() called with change that extends beyond document'); // line.content.push({ insert: '#'.repeat(otherOp.retain || 1) }); // wentBeyond = true; continue; } if (typeof otherOp.retain === 'number') { const isLine = thisOp.insert === '\n'; let newOp: Op = thisOp; // Preserve null when composing with a retain, otherwise remove it for inserts const attributes = otherOp.attributes && AttributeMap.compose(thisOp.attributes, otherOp.attributes); if (otherOp.attributes && !isEqual(attributes, thisOp.attributes)) { if (isLine) { line.attributes = attributes || {}; } else { newOp = { insert: thisOp.insert }; if (attributes) newOp.attributes = attributes; } } if (isLine) { addLine(line); line = Line.createFrom(thisIter.peekLine()); } else { line.content.push(newOp); } // Optimization if at the end of other if (otherOp.retain === Infinity || !otherIter.hasNext()) { if (thisIter.opIterator.index !== 0 || thisIter.opIterator.offset !== 0) { const ops = thisIter.restCurrentLine(); for (let i = 0; i < ops.length; i++) { line.content.push(ops[i]); } addLine(line); thisIter.nextLine(); } lines.push(...thisIter.restLines()); break; } } // else ... otherOp should be a delete so we won't add the next thisOp insert } } // if (wentBeyond) { // console.log('went beyond:', line); // addLine(line); // } return new TextDocument(lines, selection); } replace(delta?: Delta, selection?: EditorRange | null) { return new TextDocument(delta, selection); } toDelta(): Delta { const cache = DELTA_CACHE; let delta = cache.get(this); if (!delta) { delta = Line.toDelta(this.lines); cache.set(this, delta); } return delta; } equals(other: TextDocument, options?: { contentOnly?: boolean }) { return this === other || (options?.contentOnly || isEqual(this.selection, other.selection)) && isEqual(this.lines, other.lines, { excludeProps }); } toJSON() { return this.toDelta(); } toString() { return this.lines .map(line => line.content .map(op => typeof op.insert === 'string' ? op.insert : ' ') .join('')) .join('\n') + '\n'; } } function getAttributes(Type: any, data: any, from: number, to: number, filter?: (next: any) => boolean, options?: FormattingOptions): AttributeMap { const iter = Type.iterator(data); let attributes: AttributeMap | undefined; let index = 0; if (iter.skip) index += iter.skip(from); while (index < to && iter.hasNext()) { let next = iter.next() as { attributes: AttributeMap }; index += Type.length(next); if (index > from && (!filter || filter(next))) { if (!next.attributes) attributes = {}; else if (!attributes) attributes = { ...next.attributes }; else if (options?.allFormats) attributes = AttributeMap.compose(attributes, next.attributes); else attributes = intersectAttributes(attributes, next.attributes, options?.nameOnly); } } return attributes || EMPTY_OBJ; } // Intersect 2 attibute maps, keeping only those that are equal in both function intersectAttributes(attributes: AttributeMap, other: AttributeMap, nameOnly?: boolean) { return Object.keys(other).reduce(function(intersect, name) { if (nameOnly) { if (name in attributes && name in other) intersect[name] = true; } else if (isEqual(attributes[name], other[name], { partial: true })) { intersect[name] = other[name]; } else if (isEqual(other[name], attributes[name], { partial: true })) { intersect[name] = attributes[name]; } return intersect; }, {}); }<|fim▁end|>
return change; }
<|file_name|>mkdir.go<|end_file_name|><|fim▁begin|>package endpoints import ( "encoding/json" "fmt" "net/http" log "github.com/Sirupsen/logrus" ) // MkdirHandler implements http.Handler. type MkdirHandler struct { *State } // NewMkdirHandler creates a new mkdir handler. func NewMkdirHandler(s *State) *MkdirHandler { return &MkdirHandler{State: s} } // MkdirRequest is the request that can be sent to this endpoint as JSON. type MkdirRequest struct { // Path to create. Path string `json:"path"` } func (mh *MkdirHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { mkdirReq := MkdirRequest{} if err := json.NewDecoder(r.Body).Decode(&mkdirReq); err != nil { jsonifyErrf(w, http.StatusBadRequest, "bad json") return } if !mh.validatePath(mkdirReq.Path, w, r) { jsonifyErrf(w, http.StatusUnauthorized, "path forbidden") return } if err := mh.fs.Mkdir(mkdirReq.Path, true); err != nil { log.Debugf("failed to mkdir %s: %v", mkdirReq.Path, err) jsonifyErrf(w, http.StatusInternalServerError, "failed to mkdir") return } msg := fmt.Sprintf("mkdir'd »%s«", mkdirReq.Path)<|fim▁hole|> } jsonifySuccess(w) }<|fim▁end|>
if !mh.commitChange(msg, w, r) { return
<|file_name|>iso8859_1.py<|end_file_name|><|fim▁begin|>""" Python Character Mapping Codec iso8859_1 generated from 'MAPPINGS/ISO8859/8859-1.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='iso8859-1', encode=Codec().encode,<|fim▁hole|> decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( '\x00' # 0x00 -> NULL '\x01' # 0x01 -> START OF HEADING '\x02' # 0x02 -> START OF TEXT '\x03' # 0x03 -> END OF TEXT '\x04' # 0x04 -> END OF TRANSMISSION '\x05' # 0x05 -> ENQUIRY '\x06' # 0x06 -> ACKNOWLEDGE '\x07' # 0x07 -> BELL '\x08' # 0x08 -> BACKSPACE '\t' # 0x09 -> HORIZONTAL TABULATION '\n' # 0x0A -> LINE FEED '\x0b' # 0x0B -> VERTICAL TABULATION '\x0c' # 0x0C -> FORM FEED '\r' # 0x0D -> CARRIAGE RETURN '\x0e' # 0x0E -> SHIFT OUT '\x0f' # 0x0F -> SHIFT IN '\x10' # 0x10 -> DATA LINK ESCAPE '\x11' # 0x11 -> DEVICE CONTROL ONE '\x12' # 0x12 -> DEVICE CONTROL TWO '\x13' # 0x13 -> DEVICE CONTROL THREE '\x14' # 0x14 -> DEVICE CONTROL FOUR '\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x16 -> SYNCHRONOUS IDLE '\x17' # 0x17 -> END OF TRANSMISSION BLOCK '\x18' # 0x18 -> CANCEL '\x19' # 0x19 -> END OF MEDIUM '\x1a' # 0x1A -> SUBSTITUTE '\x1b' # 0x1B -> ESCAPE '\x1c' # 0x1C -> FILE SEPARATOR '\x1d' # 0x1D -> GROUP SEPARATOR '\x1e' # 0x1E -> RECORD SEPARATOR '\x1f' # 0x1F -> UNIT SEPARATOR ' ' # 0x20 -> SPACE '!' # 0x21 -> EXCLAMATION MARK '"' # 0x22 -> QUOTATION MARK '#' # 0x23 -> NUMBER SIGN '$' # 0x24 -> DOLLAR SIGN '%' # 0x25 -> PERCENT SIGN '&' # 0x26 -> AMPERSAND "'" # 0x27 -> APOSTROPHE '(' # 0x28 -> LEFT PARENTHESIS ')' # 0x29 -> RIGHT PARENTHESIS '*' # 0x2A -> ASTERISK '+' # 0x2B -> PLUS SIGN ',' # 0x2C -> COMMA '-' # 0x2D -> HYPHEN-MINUS '.' # 0x2E -> FULL STOP '/' # 0x2F -> SOLIDUS '0' # 0x30 -> DIGIT ZERO '1' # 0x31 -> DIGIT ONE '2' # 0x32 -> DIGIT TWO '3' # 0x33 -> DIGIT THREE '4' # 0x34 -> DIGIT FOUR '5' # 0x35 -> DIGIT FIVE '6' # 0x36 -> DIGIT SIX '7' # 0x37 -> DIGIT SEVEN '8' # 0x38 -> DIGIT EIGHT '9' # 0x39 -> DIGIT NINE ':' # 0x3A -> COLON ';' # 0x3B -> SEMICOLON '<' # 0x3C -> LESS-THAN SIGN '=' # 0x3D -> EQUALS SIGN '>' # 0x3E -> GREATER-THAN SIGN '?' # 0x3F -> QUESTION MARK '@' # 0x40 -> COMMERCIAL AT 'A' # 0x41 -> LATIN CAPITAL LETTER A 'B' # 0x42 -> LATIN CAPITAL LETTER B 'C' # 0x43 -> LATIN CAPITAL LETTER C 'D' # 0x44 -> LATIN CAPITAL LETTER D 'E' # 0x45 -> LATIN CAPITAL LETTER E 'F' # 0x46 -> LATIN CAPITAL LETTER F 'G' # 0x47 -> LATIN CAPITAL LETTER G 'H' # 0x48 -> LATIN CAPITAL LETTER H 'I' # 0x49 -> LATIN CAPITAL LETTER I 'J' # 0x4A -> LATIN CAPITAL LETTER J 'K' # 0x4B -> LATIN CAPITAL LETTER K 'L' # 0x4C -> LATIN CAPITAL LETTER L 'M' # 0x4D -> LATIN CAPITAL LETTER M 'N' # 0x4E -> LATIN CAPITAL LETTER N 'O' # 0x4F -> LATIN CAPITAL LETTER O 'P' # 0x50 -> LATIN CAPITAL LETTER P 'Q' # 0x51 -> LATIN CAPITAL LETTER Q 'R' # 0x52 -> LATIN CAPITAL LETTER R 'S' # 0x53 -> LATIN CAPITAL LETTER S 'T' # 0x54 -> LATIN CAPITAL LETTER T 'U' # 0x55 -> LATIN CAPITAL LETTER U 'V' # 0x56 -> LATIN CAPITAL LETTER V 'W' # 0x57 -> LATIN CAPITAL LETTER W 'X' # 0x58 -> LATIN CAPITAL LETTER X 'Y' # 0x59 -> LATIN CAPITAL LETTER Y 'Z' # 0x5A -> LATIN CAPITAL LETTER Z '[' # 0x5B -> LEFT SQUARE BRACKET '\\' # 0x5C -> REVERSE SOLIDUS ']' # 0x5D -> RIGHT SQUARE BRACKET '^' # 0x5E -> CIRCUMFLEX ACCENT '_' # 0x5F -> LOW LINE '`' # 0x60 -> GRAVE ACCENT 'a' # 0x61 -> LATIN SMALL LETTER A 'b' # 0x62 -> LATIN SMALL LETTER B 'c' # 0x63 -> LATIN SMALL LETTER C 'd' # 0x64 -> LATIN SMALL LETTER D 'e' # 0x65 -> LATIN SMALL LETTER E 'f' # 0x66 -> LATIN SMALL LETTER F 'g' # 0x67 -> LATIN SMALL LETTER G 'h' # 0x68 -> LATIN SMALL LETTER H 'i' # 0x69 -> LATIN SMALL LETTER I 'j' # 0x6A -> LATIN SMALL LETTER J 'k' # 0x6B -> LATIN SMALL LETTER K 'l' # 0x6C -> LATIN SMALL LETTER L 'm' # 0x6D -> LATIN SMALL LETTER M 'n' # 0x6E -> LATIN SMALL LETTER N 'o' # 0x6F -> LATIN SMALL LETTER O 'p' # 0x70 -> LATIN SMALL LETTER P 'q' # 0x71 -> LATIN SMALL LETTER Q 'r' # 0x72 -> LATIN SMALL LETTER R 's' # 0x73 -> LATIN SMALL LETTER S 't' # 0x74 -> LATIN SMALL LETTER T 'u' # 0x75 -> LATIN SMALL LETTER U 'v' # 0x76 -> LATIN SMALL LETTER V 'w' # 0x77 -> LATIN SMALL LETTER W 'x' # 0x78 -> LATIN SMALL LETTER X 'y' # 0x79 -> LATIN SMALL LETTER Y 'z' # 0x7A -> LATIN SMALL LETTER Z '{' # 0x7B -> LEFT CURLY BRACKET '|' # 0x7C -> VERTICAL LINE '}' # 0x7D -> RIGHT CURLY BRACKET '~' # 0x7E -> TILDE '\x7f' # 0x7F -> DELETE '\x80' # 0x80 -> <control> '\x81' # 0x81 -> <control> '\x82' # 0x82 -> <control> '\x83' # 0x83 -> <control> '\x84' # 0x84 -> <control> '\x85' # 0x85 -> <control> '\x86' # 0x86 -> <control> '\x87' # 0x87 -> <control> '\x88' # 0x88 -> <control> '\x89' # 0x89 -> <control> '\x8a' # 0x8A -> <control> '\x8b' # 0x8B -> <control> '\x8c' # 0x8C -> <control> '\x8d' # 0x8D -> <control> '\x8e' # 0x8E -> <control> '\x8f' # 0x8F -> <control> '\x90' # 0x90 -> <control> '\x91' # 0x91 -> <control> '\x92' # 0x92 -> <control> '\x93' # 0x93 -> <control> '\x94' # 0x94 -> <control> '\x95' # 0x95 -> <control> '\x96' # 0x96 -> <control> '\x97' # 0x97 -> <control> '\x98' # 0x98 -> <control> '\x99' # 0x99 -> <control> '\x9a' # 0x9A -> <control> '\x9b' # 0x9B -> <control> '\x9c' # 0x9C -> <control> '\x9d' # 0x9D -> <control> '\x9e' # 0x9E -> <control> '\x9f' # 0x9F -> <control> '\xa0' # 0xA0 -> NO-BREAK SPACE '\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK '\xa2' # 0xA2 -> CENT SIGN '\xa3' # 0xA3 -> POUND SIGN '\xa4' # 0xA4 -> CURRENCY SIGN '\xa5' # 0xA5 -> YEN SIGN '\xa6' # 0xA6 -> BROKEN BAR '\xa7' # 0xA7 -> SECTION SIGN '\xa8' # 0xA8 -> DIAERESIS '\xa9' # 0xA9 -> COPYRIGHT SIGN '\xaa' # 0xAA -> FEMININE ORDINAL INDICATOR '\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xac' # 0xAC -> NOT SIGN '\xad' # 0xAD -> SOFT HYPHEN '\xae' # 0xAE -> REGISTERED SIGN '\xaf' # 0xAF -> MACRON '\xb0' # 0xB0 -> DEGREE SIGN '\xb1' # 0xB1 -> PLUS-MINUS SIGN '\xb2' # 0xB2 -> SUPERSCRIPT TWO '\xb3' # 0xB3 -> SUPERSCRIPT THREE '\xb4' # 0xB4 -> ACUTE ACCENT '\xb5' # 0xB5 -> MICRO SIGN '\xb6' # 0xB6 -> PILCROW SIGN '\xb7' # 0xB7 -> MIDDLE DOT '\xb8' # 0xB8 -> CEDILLA '\xb9' # 0xB9 -> SUPERSCRIPT ONE '\xba' # 0xBA -> MASCULINE ORDINAL INDICATOR '\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER '\xbd' # 0xBD -> VULGAR FRACTION ONE HALF '\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS '\xbf' # 0xBF -> INVERTED QUESTION MARK '\xc0' # 0xC0 -> LATIN CAPITAL LETTER A WITH GRAVE '\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE '\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX '\xc3' # 0xC3 -> LATIN CAPITAL LETTER A WITH TILDE '\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS '\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE '\xc6' # 0xC6 -> LATIN CAPITAL LETTER AE '\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA '\xc8' # 0xC8 -> LATIN CAPITAL LETTER E WITH GRAVE '\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE '\xca' # 0xCA -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX '\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS '\xcc' # 0xCC -> LATIN CAPITAL LETTER I WITH GRAVE '\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE '\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX '\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS '\xd0' # 0xD0 -> LATIN CAPITAL LETTER ETH (Icelandic) '\xd1' # 0xD1 -> LATIN CAPITAL LETTER N WITH TILDE '\xd2' # 0xD2 -> LATIN CAPITAL LETTER O WITH GRAVE '\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE '\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX '\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE '\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS '\xd7' # 0xD7 -> MULTIPLICATION SIGN '\xd8' # 0xD8 -> LATIN CAPITAL LETTER O WITH STROKE '\xd9' # 0xD9 -> LATIN CAPITAL LETTER U WITH GRAVE '\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE '\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX '\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS '\xdd' # 0xDD -> LATIN CAPITAL LETTER Y WITH ACUTE '\xde' # 0xDE -> LATIN CAPITAL LETTER THORN (Icelandic) '\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S (German) '\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE '\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE '\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\xe3' # 0xE3 -> LATIN SMALL LETTER A WITH TILDE '\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS '\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE '\xe6' # 0xE6 -> LATIN SMALL LETTER AE '\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA '\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE '\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE '\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX '\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS '\xec' # 0xEC -> LATIN SMALL LETTER I WITH GRAVE '\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE '\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS '\xf0' # 0xF0 -> LATIN SMALL LETTER ETH (Icelandic) '\xf1' # 0xF1 -> LATIN SMALL LETTER N WITH TILDE '\xf2' # 0xF2 -> LATIN SMALL LETTER O WITH GRAVE '\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE '\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE '\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS '\xf7' # 0xF7 -> DIVISION SIGN '\xf8' # 0xF8 -> LATIN SMALL LETTER O WITH STROKE '\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE '\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE '\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX '\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS '\xfd' # 0xFD -> LATIN SMALL LETTER Y WITH ACUTE '\xfe' # 0xFE -> LATIN SMALL LETTER THORN (Icelandic) '\xff' # 0xFF -> LATIN SMALL LETTER Y WITH DIAERESIS '\ufffe' ## Widen to UCS2 for optimization ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)<|fim▁end|>
<|file_name|>hypercalls.rs<|end_file_name|><|fim▁begin|>#[derive(Debug)] #[repr(usize)] #[allow(non_camel_case_types)] pub enum Command { set_trap_table = 0, mmu_update = 1, set_gdt = 2, stack_switch = 3, set_callbacks = 4, fpu_taskswitch = 5, sched_op_compat = 6, platform_op = 7, set_debugreg = 8, get_debugreg = 9, update_descriptor = 10, memory_op = 12, multicall = 13, update_va_mapping = 14, set_timer_op = 15, event_channel_op_compat = 16, xen_version = 17, console_io = 18, physdev_op_compat = 19, grant_table_op = 20, vm_assist = 21, update_va_mapping_otherdomain = 22, iret = 23, vcpu_op = 24, set_segment_base = 25, mmuext_op = 26, xsm_op = 27, nmi_op = 28, sched_op = 29, callback_op = 30, xenoprof_op = 31, event_channel_op = 32, physdev_op = 33, hvm_op = 34, sysctl = 35, domctl = 36, kexec_op = 37, tmem_op = 38, xc_reserved_op = 39, xen_pmu_op = 40, arch_0 = 48, arch_1 = 49, arch_2 = 50, arch_3 = 51, arch_4 = 52, arch_5 = 53, arch_6 = 54, arch_7 = 55 } //pub mod set_trap_table; //pub mod mmu_update; //pub mod set_gdt; //pub mod stack_switch; //pub mod set_callbacks; //pub mod fpu_taskswitch; //pub mod sched_op_compat; //pub mod platform_op; //pub mod set_debugreg; //pub mod get_debugreg; //pub mod update_descriptor; //pub mod memory_op; //pub mod multicall; //pub mod update_va_mapping; //pub mod set_timer_op; //pub mod event_channel_op_compat; //pub mod xen_version; pub mod console_io { use xen::ffi::arch::x86_64::hypercall; use xen::ffi::hypercalls::Command; #[derive(Debug)] #[repr(usize)] #[allow(non_camel_case_types)] pub enum SubCommand { write = 0, read = 1 } pub fn write(buf: &[u8]) { hypercall(Command::console_io, SubCommand::write as usize, buf.len(), buf.as_ptr(), 0); } } //pub mod physdev_op_compat; pub mod grant_table_op { use xen::ffi::MachineFrameNumber; use xen::ffi::XenGuestHandle; use xen::ffi::arch::x86_64::hypercall; use xen::ffi::DomID; #[repr(usize)] #[allow(non_camel_case_types)] enum SubCommand { map_grant_ref = 0, unmap_grant_ref = 1, setup_table = 2, dump_table = 3, tranfer = 4, copy = 5, query_size = 6, unmap_and_replace = 7, set_version = 8, get_status_frames = 9, get_version = 10, swap_grant_ref = 11, cache_flush = 12 } //pub mod map_grant_ref; //pub mod unmap_grant ref; #[derive(Debug)] #[repr(C)] struct SetupTableArgs { dom : DomID, nr_frames : u32, /// Output status : i16, /// Output frame_list : XenGuestHandle<MachineFrameNumber<[u8; 1024]>> } /* pub unsafe fn arch_init_gnttab(nr_grant_frames : u32) { // TODO: FIX let frames = [0u64; 16]; let mut args = SetupTableArgs { dom: DomID::SELF, nr_frames: nr_grant_frames, status: 0, frame_list: XenGuestHandle(PageFrameNumber(&frames[0] as *)) // OK because we know we have > 0 elements }; let _result = hypercall!( i64, Command::grant_table_op, SubCommand::setup_table, &mut args as *mut SetupTableArgs, 16, // number of frames 1u32 // number of arguments: 1 ); //map_frames(frames) // TODO maybe - } */ //pub mod dump_table; //pub mod transfer; //pub mod copy; //pub mod query_size; //pub mod unmap_and_replace; //pub mod set_version; //pub mod get_status_frames; //pub mod get_version; //pub mod swap_grant_ref; //pub mod cache_flush; } //pub mod vm_assist; //pub mod update_va_mapping_otherdomain; //pub mod iret; //pub mod vcpu_op; //pub mod set_segment_base; //pub mod mmuext_op; //pub mod xsm_op; //pub mod nmi_op; pub mod sched_op { use xen::ffi::hypercalls::Command; use xen::ffi::arch::x86_64::hypercall; #[derive(Debug)] #[repr(usize)] #[allow(non_camel_case_types)] enum SubCommand { yield_ = 0, block = 1, shutdown = 2, poll = 3, remote_shutdown = 4, shutdown_code = 5, watchdog = 6 } //pub mod yield_; //pub mod block; #[derive(Debug)] #[repr(usize)] #[allow(non_camel_case_types)] pub enum ShutdownReason { poweroff = 0, reboot = 1, suspend = 2, crash = 3, watchdog = 4 } #[repr(C)] #[derive(Debug)] struct ShutdownArgs { reason: ShutdownReason } pub fn shutdown(reason: ShutdownReason) -> ! { hypercall( Command::sched_op, SubCommand::shutdown as usize, &ShutdownArgs { reason: reason } as *const ShutdownArgs as usize ); loop {} } //pub mod poll; //pub mod remote_shutdown; //pub mod shutdown_code; //pub mod watchdog; } //pub mod callback_op; //pub mod xenoprof_op; pub mod event_channel_op { use xen::ffi::hypercalls::{Command, NegErrnoval}; use xen::ffi::{DomID, Port, Vcpu}; use xen::ffi::arch::x86_64::hypercall; #[derive(Debug)] #[repr(usize)] #[allow(non_camel_case_types)] enum SubCommand { bind_interdomain = 0, bind_virq = 1, bind_pirq = 2, close = 3, send = 4, status = 5, alloc_unbound = 6, bind_ipi = 7, bind_vcpu = 8, unmask = 9, reset = 10, init_control = 11, expand_array = 12, set_priority = 13 } #[derive(Debug)] #[repr(C)] struct BindInterdomainArgs { remote_dom: DomID, remote_port: Port, /// Output local_port: Port } #[derive(Debug)] #[repr(C)] struct BindVirqArgs { virq: Virq, cpu: Vcpu, /// Output port: Port } #[derive(Debug)] #[repr(u32)] enum Virq { Timer = 0, Debug = 1, Console = 2, DomExc = 3, Tbuf = 4, Debugger = 6, Xenoprof = 7, ConRing = 8, PcpuState = 9, MemEvent = 10, XcReserved = 11, Enomem = 12, Xenpmu = 13, Arch0 = 16, Arch1 = 17, Arch2 = 18, Arch3 = 19, Arch4 = 20, Arch5 = 21, Arch6 = 22, Arch7 = 23 } //pub mod bind_pirq; pub fn close (p: Port) { unsafe { let mut args = CloseArgs { port: p }; let _result = hypercall( Command::event_channel_op, SubCommand::close as usize, &mut args as *mut CloseArgs as usize ); } } #[derive(Debug)] #[repr(C)] struct CloseArgs { port: Port } pub fn send(port: &mut Port) -> NegErrnoval { unsafe { use core::mem; use core::ptr; let mut args: SendArgs = mem::uninitialized(); args.port = ptr::read(port); hypercall( Command::event_channel_op, SubCommand::send as usize, &mut args as *mut _ as usize ) } } #[derive(Debug)] #[repr(C)] struct SendArgs { port: Port } //pub mod status; #[derive(Debug)] #[repr(C)] struct AllocUnboundArgs { dom: DomID, remote_dom: DomID, /// Output port: Port } //pub mod bind_ipi; //pub mod bind_vcpu; //pub mod unmask; //pub mod reset; //pub mod init_control; //pub mod expand_array; //pub mod set_priority; } //pub mod physdev_op; //pub mod hvm_op; //pub mod sysctl; //pub mod domctl; //pub mod kexec_op; //pub mod tmem_op; //pub mod xc_reserved_op; //pub mod xen_pmu_op; //pub mod arch_0; //pub mod arch_1; //pub mod arch_2; //pub mod arch_3; //pub mod arch_4; //pub mod arch_5; //pub mod arch_6; //pub mod arch_7; #[repr(i64)] #[derive(Debug, Clone, PartialEq, Copy)] pub enum NegErrnoval { ALLGOOD = 0, EPERM = -1, ENOENT = -2, ESRCH = -3, EINTR = -4, EIO = -5, ENXIO = -6, E2BIG = -7, ENOEXEC = -8, EBADF = -9, ECHILD = -10, EAGAIN = -11, ENOMEM = -12, EACCES = -13, EFAULT = -14, ENOTBLK = -15, EBUSY = -16, EEXIST = -17, EXDEV = -18, ENODEV = -19, ENOTDIR = -20, EISDIR = -21, EINVAL = -22, ENFILE = -23, EMFILE = -24, ENOTTY = -25, ETXTBSY = -26, EFBIG = -27, ENOSPC = -28, ESPIPE = -29, EROFS = -30, EMLINK = -31, EPIPE = -32, EDOM = -33, ERANGE = -34, EDEADLK = -35, ENAMETOOLONG = -36, ENOLCK = -37, ENOSYS = -38, ENOTEMPTY = -39, ELOOP = -40, ENOMSG = -42, EIDRM = -43, ECHRNG = -44, EL2NSYNC = -45, EL3HLT = -46, EL3RST = -47, ELNRNG = -48, EUNATCH = -49, ENOCSI = -50, EL2HLT = -51, EBADE = -52, EBADR = -53, EXFULL = -54, ENOANO = -55, EBADRQC = -56, EBADSLT = -57, EBFONT = -59, ENOSTR = -60, ENODATA = -61, ETIME = -62, ENOSR = -63, ENONET = -64, ENOPKG = -65, EREMOTE = -66, ENOLINK = -67, EADV = -68, ESRMNT = -69, ECOMM = -70, EPROTO = -71, EMULTIHOP = -72, EDOTDOT = -73, EBADMSG = -74, EOVERFLOW = -75, ENOTUNIQ = -76, EBADFD = -77, EREMCHG = -78, ELIBACC = -79, ELIBBAD = -80, ELIBSCN = -81, ELIBMAX = -82, ELIBEXEC = -83, EILSEQ = -84, ERESTART = -85, ESTRPIPE = -86, EUSERS = -87, ENOTSOCK = -88, EDESTADDRREQ = -89, EMSGSIZE = -90, EPROTOTYPE = -91, ENOPROTOOPT = -92, EPROTONOSUPPORT = -93, ESOCKTNOSUPPORT = -94,<|fim▁hole|> EOPNOTSUPP = -95, EPFNOSUPPORT = -96, EAFNOSUPPORT = -97, EADDRINUSE = -98, EADDRNOTAVAIL = -99, ENETDOWN = -100, ENETUNREACH = -101, ENETRESET = -102, ECONNABORTED = -103, ECONNRESET = -104, ENOBUFS = -105, EISCONN = -106, ENOTCONN = -107, ESHUTDOWN = -108, ETOOMANYREFS = -109, ETIMEDOUT = -110, ECONNREFUSED = -111, EHOSTDOWN = -112, EHOSTUNREACH = -113, EALREADY = -114, EINPROGRESS = -115, ESTALE = -116, EUCLEAN = -117, ENOTNAM = -118, ENAVAIL = -119, EISNAM = -120, EREMOTEIO = -121, EDQUOT = -122, ENOMEDIUM = -123, EMEDIUMTYPE = -124, ECANCELED = -125, ENOKEY = -126, EKEYEXPIRED = -127, EKEYREVOKED = -128, EKEYREJECTED = -129, EOWNERDEAD = -130, ENOTRECOVERABLE = -131, ERFKILL = -132, EHWPOISON = -133, }<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import Route from '@ember/routing/route'; export default Route.extend({ beforeModel: function(transition) { if (transition.targetName === this.routeName) { transition.abort(); return this.replaceWith('vault.cluster.settings.mount-secret-backend'); }<|fim▁hole|><|fim▁end|>
}, });
<|file_name|>submission_download.js<|end_file_name|><|fim▁begin|>define([ 'INST' /* INST */, 'i18n!submissions', 'jquery' /* $ */, 'str/htmlEscape', 'jquery.ajaxJSON' /* ajaxJSON */, 'jqueryui/dialog', 'jqueryui/progressbar' /* /\.progressbar/ */ ], function(INST, I18n, $, htmlEscape) { INST.downloadSubmissions = function(url) { var cancelled = false; var title = ENV.SUBMISSION_DOWNLOAD_DIALOG_TITLE; title = title || I18n.t('#submissions.download_submissions', 'Download Assignment Submissions'); $("#download_submissions_dialog").dialog({ title: title, close: function() { cancelled = true; } }); $("#download_submissions_dialog .progress").progressbar({value: 0}); var checkForChange = function() { if(cancelled || $("#download_submissions_dialog:visible").length == 0) { return; } $("#download_submissions_dialog .status_loader").css('visibility', 'visible'); var lastProgress = null; $.ajaxJSON(url, 'GET', {}, function(data) { if(data && data.attachment) { var attachment = data.attachment; if(attachment.workflow_state == 'zipped') { $("#download_submissions_dialog .progress").progressbar('value', 100); var message = I18n.t("#submissions.finished_redirecting", "Finished! Redirecting to File..."); var link = "<a href=\"" + htmlEscape(url) + "\"><b> " + htmlEscape(I18n.t("#submissions.click_to_download", "Click here to download %{size_of_file}", {size_of_file: attachment.readable_size})) + "</b></a>" $("#download_submissions_dialog .status").html(htmlEscape(message) + "<br>" + $.raw(link)); $("#download_submissions_dialog .status_loader").css('visibility', 'hidden'); location.href = url; return; } else { var progress = parseInt(attachment.file_state, 10); if(isNaN(progress)) { progress = 0; } progress += 5 $("#download_submissions_dialog .progress").progressbar('value', progress); var message = null; if(progress >= 95){ message = I18n.t("#submissions.creating_zip", "Creating zip file..."); } else { message = I18n.t("#submissions.gathering_files_progress", "Gathering Files (%{progress})...", {progress: I18n.toPercentage(progress)}); } $("#download_submissions_dialog .status").text(message); if(progress <= 5 || progress == lastProgress) { $.ajaxJSON(url + "&compile=1", 'GET', {}, function() {}, function() {}); } lastProgress = progress; } } $("#download_submissions_dialog .status_loader").css('visibility', 'hidden'); setTimeout(checkForChange, 3000); }, function(data) { $("#download_submissions_dialog .status_loader").css('visibility', 'hidden'); setTimeout(checkForChange, 1000); }); }<|fim▁hole|><|fim▁end|>
checkForChange(); }; });
<|file_name|>bitimage.cpp<|end_file_name|><|fim▁begin|>/* This file is part of Warzone 2100. Copyright (C) 1999-2004 Eidos Interactive Copyright (C) 2005-2011 Warzone 2100 Project Warzone 2100 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Warzone 2100 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Warzone 2100; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "lib/framework/frame.h" #include "lib/framework/frameresource.h" #include "lib/framework/file.h" #include "bitimage.h" #include "tex.h" static unsigned short LoadTextureFile(const char *FileName) { iV_Image *pSprite; unsigned int i; ASSERT_OR_RETURN( 0, resPresent("IMGPAGE", FileName), "Texture file \"%s\" not preloaded.", FileName); pSprite = (iV_Image*)resGetData("IMGPAGE", FileName); debug(LOG_TEXTURE, "Load texture from resource cache: %s (%d, %d)", FileName, pSprite->width, pSprite->height); /* Have we already uploaded this one? */ for (i = 0; i < _TEX_INDEX; ++i) { if (strcasecmp(FileName, _TEX_PAGE[i].name) == 0) { debug(LOG_TEXTURE, "LoadTextureFile: already uploaded"); return _TEX_PAGE[i].id; } } debug(LOG_TEXTURE, "LoadTextureFile: had to upload texture!"); return pie_AddTexPage(pSprite, FileName, 0, 0, true); } IMAGEFILE *iV_LoadImageFile(const char *fileName) { char *pFileData, *ptr, *dot; unsigned int pFileSize, numImages = 0, i, tPages = 0; IMAGEFILE *ImageFile; char texFileName[PATH_MAX]; if (!loadFile(fileName, &pFileData, &pFileSize)) { debug(LOG_ERROR, "iV_LoadImageFile: failed to open %s", fileName); return NULL; } ptr = pFileData; // count lines, which is identical to number of images while (ptr < pFileData + pFileSize && *ptr != '\0') { numImages += (*ptr == '\n') ? 1 : 0; ptr++; } ImageFile = (IMAGEFILE *)malloc(sizeof(IMAGEFILE) + sizeof(IMAGEDEF) * numImages); ImageFile->ImageDefs = (IMAGEDEF*)(ImageFile + 1); // we allocated extra space for it ptr = pFileData; numImages = 0; while (ptr < pFileData + pFileSize) { int temp, retval; IMAGEDEF *ImageDef = &ImageFile->ImageDefs[numImages]; retval = sscanf(ptr, "%u,%u,%u,%u,%u,%d,%d%n", &ImageDef->TPageID, &ImageDef->Tu, &ImageDef->Tv, &ImageDef->Width, &ImageDef->Height, &ImageDef->XOffset, &ImageDef->YOffset, &temp); if (retval != 7) { break; } ptr += temp; numImages++; // Find number of texture pages to load (no gaps allowed in number series, eg use intfac0, intfac1, etc.!) if (ImageDef->TPageID > tPages) { tPages = ImageDef->TPageID; } while (ptr < pFileData + pFileSize && *ptr++ != '\n') {} // skip rest of line } dot = (char *)strrchr(fileName, '/'); // go to last path character dot++; // skip it strcpy(texFileName, dot); // make a copy dot = strchr(texFileName, '.'); // find extension<|fim▁hole|> for (i = 0; i <= tPages; i++) { char path[PATH_MAX]; snprintf(path, PATH_MAX, "%s%u.png", texFileName, i); ImageFile->TPageIDs[i] = LoadTextureFile(path); } ImageFile->NumImages = numImages; free(pFileData); return ImageFile; } void iV_FreeImageFile(IMAGEFILE *ImageFile) { free(ImageFile); }<|fim▁end|>
*dot = '\0'; // then discard it // Load the texture pages.
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod log;<|fim▁hole|> pub use self::log::{LogConf, LogDevice};<|fim▁end|>
<|file_name|>utf8prober.py<|end_file_name|><|fim▁begin|>######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys from . import constants from .constants import eStart, eError, eItsMe from .charsetprober import CharSetProber from .codingstatemachine import CodingStateMachine from .mbcssm import UTF8SMModel ONE_CHAR_PROB = 0.5 class UTF8Prober(CharSetProber): def __init__(self): CharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(UTF8SMModel) self.reset() def reset(self): CharSetProber.reset(self) self._mCodingSM.reset() self._mNumOfMBChar = 0 def get_charset_name(self): return "utf-8" def feed(self, aBuf): for c in aBuf: codingState = self._mCodingSM.next_state(c) if codingState == eError: self._mState = constants.eNotMe break elif codingState == eItsMe: self._mState = constants.eFoundIt break elif codingState == eStart: if self._mCodingSM.get_current_charlen() >= 2: self._mNumOfMBChar += 1 if self.get_state() == constants.eDetecting: if self.get_confidence() > constants.SHORTCUT_THRESHOLD: self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): unlike = 0.99 if self._mNumOfMBChar < 6: for i in range(0, self._mNumOfMBChar): unlike = unlike * ONE_CHAR_PROB return 1.0 - unlike<|fim▁hole|><|fim▁end|>
else: return unlike
<|file_name|>OpenHillShade_September_6am_Listener.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
energymodels.OpenHillShade_September_6am_Listener
<|file_name|>C.cpp<|end_file_name|><|fim▁begin|>#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <fstream> #include <functional> #include <iostream> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <set><|fim▁hole|>#include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; #define rep(k, a, b) for (int k = (a); k < int(b); k++) #define rrep(k, a, b) for (int k = (a); k >= int(b); k--) #define irep(it, xs) for (auto it = xs.begin(); it!=xs.end(); it++) #define rirep(it, xs) for (auto it = xs.rbegin(); it!=xs.rend(); it++) #define erep(e, xs) for (auto& e : (xs)) #define rint(x) scanf("%d", &(x)) #define rfloat(x) scanf("%lf", &(x)) typedef long long LL; typedef pair<int,int> II; int n,m,b,mod; int a[501]; int dp[501][501]; int main() { cin >> n >> m >> b >> mod; rep(i, 0, n) cin >> a[i]; // people, lines, bug for(int i=0;i!=m;i++) { dp[] } for(int i=0;i<=m;i++) { for(int j=0;j!=b;j++) { for(int k=0;k<=m;k++) { for(int l=0;l<=b;l++) { dp[i][j] += dp[k][k] * dp[n-k][b-l]; } } } } cout << dp[n][b] << endl; return 0; }<|fim▁end|>
#include <stack>
<|file_name|>events_application_info_py3.py<|end_file_name|><|fim▁begin|># coding=utf-8<|fim▁hole|># # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class EventsApplicationInfo(Model): """Application info for an event result. :param version: Version of the application :type version: str """ _attribute_map = { 'version': {'key': 'version', 'type': 'str'}, } def __init__(self, *, version: str=None, **kwargs) -> None: super(EventsApplicationInfo, self).__init__(**kwargs) self.version = version<|fim▁end|>
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information.
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>""" Created on June 10, 2012 @author: peta15 """ from wtforms import fields from wtforms import Form from wtforms import validators from lib import utils from webapp2_extras.i18n import lazy_gettext as _ from webapp2_extras.i18n import ngettext, gettext FIELD_MAXLENGTH = 50 # intended to stop maliciously long input class FormTranslations(object): def gettext(self, string): return gettext(string) def ngettext(self, singular, plural, n): return ngettext(singular, plural, n) class BaseForm(Form): def __init__(self, request_handler): super(BaseForm, self).__init__(request_handler.request.POST) def _get_translations(self): return FormTranslations() # ==== Mixins ==== class PasswordConfirmMixin(BaseForm): password = fields.TextField(_('Password'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=_( "Field cannot be longer than %(max)d characters."))]) c_password = fields.TextField(_('Confirm Password'), [validators.Required(), validators.EqualTo('password', _('Passwords must match.')), validators.Length(max=FIELD_MAXLENGTH, message=_("Field cannot be longer than %(max)d characters."))]) class UsernameMixin(BaseForm): username = fields.TextField(_('Username'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=_( "Field cannot be longer than %(max)d characters.")), validators.regexp(utils.EMAIL_REGEXP, message=_( "Username / Email invalid."))]) class NameMixin(BaseForm): name = fields.TextField(_('Name'), [ validators.Length(max=FIELD_MAXLENGTH, message=_("Field cannot be longer than %(max)d characters.")), validators.regexp(utils.NAME_LASTNAME_REGEXP, message=_( "Name invalid. Use only letters and numbers."))]) last_name = fields.TextField(_('Last Name'), [ validators.Length(max=FIELD_MAXLENGTH, message=_("Field cannot be longer than %(max)d characters.")), validators.regexp(utils.NAME_LASTNAME_REGEXP, message=_( "Last Name invalid. Use only letters and numbers."))]) class EmailMixin(BaseForm): email = fields.TextField(_('Email'), [validators.Required(), validators.Length(min=8, max=FIELD_MAXLENGTH, message=_( "Field must be between %(min)d and %(max)d characters long.")), validators.regexp(utils.EMAIL_REGEXP, message=_('Invalid email address.'))]) # ==== Forms ==== class PasswordResetCompleteForm(PasswordConfirmMixin): pass class LoginForm(UsernameMixin): password = fields.TextField(_('Password'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=_( "Field cannot be longer than %(max)d characters."))], id='l_password') pass class ContactForm(EmailMixin): name = fields.TextField(_('Name'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=_( "Field cannot be longer than %(max)d characters.")), validators.regexp(utils.NAME_LASTNAME_REGEXP, message=_( "Name invalid. Use only letters and numbers."))]) message = fields.TextAreaField(_('Message'), [validators.Required(), validators.Length(max=65536)]) pass class RegisterForm(PasswordConfirmMixin, UsernameMixin, NameMixin, EmailMixin): country = fields.SelectField(_('Country'), choices=[]) tz = fields.SelectField(_('Timezone'), choices=[]) pass class EditProfileForm(UsernameMixin, NameMixin): country = fields.SelectField(_('Country'), choices=[]) tz = fields.SelectField(_('Timezone'), choices=[]) pass class EditPasswordForm(PasswordConfirmMixin): current_password = fields.TextField(_('Password'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=_(<|fim▁hole|> class EditEmailForm(BaseForm): new_email = fields.TextField(_('Email'), [validators.Required(), validators.Length(min=8, max=FIELD_MAXLENGTH, message=_( "Field must be between %(min)d and %(max)d characters long.")), validators.regexp(utils.EMAIL_REGEXP, message=_('Invalid email address.'))]) password = fields.TextField(_('Password'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=_( "Field cannot be longer than %(max)d characters."))]) pass<|fim▁end|>
"Field cannot be longer than %(max)d characters."))]) pass
<|file_name|>layers.js<|end_file_name|><|fim▁begin|>var _ = require('underscore') module.exports = function (cdb) { (function () { var Layers = cdb.vis.Layers; /* * if we are using http and the tiles of base map need to be fetched from * https try to fix it */ var HTTPS_TO_HTTP = { 'https://dnv9my2eseobd.cloudfront.net/': 'http://a.tiles.mapbox.com/', 'https://maps.nlp.nokia.com/': 'http://maps.nlp.nokia.com/', 'https://tile.stamen.com/': 'http://tile.stamen.com/', "https://{s}.maps.nlp.nokia.com/": "http://{s}.maps.nlp.nokia.com/", "https://cartocdn_{s}.global.ssl.fastly.net/": "http://{s}.api.cartocdn.com/", "https://cartodb-basemaps-{s}.global.ssl.fastly.net/": "http://{s}.basemaps.cartocdn.com/" }; function transformToHTTP(tilesTemplate) { for (var url in HTTPS_TO_HTTP) { if (tilesTemplate.indexOf(url) !== -1) { return tilesTemplate.replace(url, HTTPS_TO_HTTP[url]) } } return tilesTemplate; } function transformToHTTPS(tilesTemplate) { for (var url in HTTPS_TO_HTTP) { var httpsUrl = HTTPS_TO_HTTP[url]; if (tilesTemplate.indexOf(httpsUrl) !== -1) { return tilesTemplate.replace(httpsUrl, url); } } return tilesTemplate; } Layers.register('tilejson', function (vis, data) { var url = data.tiles[0]; if (vis.https === true) { url = transformToHTTPS(url); } else if (vis.https === false) { // Checking for an explicit false value. If it's undefined the url is left as is. url = transformToHTTP(url); } return new cdb.geo.TileLayer({ urlTemplate: url }); }); <|fim▁hole|> var url = data.urlTemplate; if (vis.https === true) { url = transformToHTTPS(url); } else if (vis.https === false) { // Checking for an explicit false value. If it's undefined the url is left as is. url = transformToHTTP(url); } data.urlTemplate = url; return new cdb.geo.TileLayer(data); }); Layers.register('wms', function (vis, data) { return new cdb.geo.WMSLayer(data); }); Layers.register('gmapsbase', function (vis, data) { return new cdb.geo.GMapsBaseLayer(data); }); Layers.register('plain', function (vis, data) { return new cdb.geo.PlainLayer(data); }); Layers.register('background', function (vis, data) { return new cdb.geo.PlainLayer(data); }); function normalizeOptions(vis, data) { if (data.infowindow && data.infowindow.fields) { if (data.interactivity) { if (data.interactivity.indexOf('cartodb_id') === -1) { data.interactivity = data.interactivity + ",cartodb_id"; } } else { data.interactivity = 'cartodb_id'; } } // if https is forced if (vis.https) { data.tiler_protocol = 'https'; data.tiler_port = 443; data.sql_api_protocol = 'https'; data.sql_api_port = 443; } data.cartodb_logo = vis.cartodb_logo == undefined ? data.cartodb_logo : vis.cartodb_logo; } var cartoLayer = function (vis, data) { normalizeOptions(vis, data); // if sublayers are included that means a layergroup should // be created if (data.sublayers) { data.type = 'layergroup'; return new cdb.geo.CartoDBGroupLayer(data); } return new cdb.geo.CartoDBLayer(data); }; Layers.register('cartodb', cartoLayer); Layers.register('carto', cartoLayer); Layers.register('layergroup', function (vis, data) { normalizeOptions(vis, data); return new cdb.geo.CartoDBGroupLayer(data); }); Layers.register('namedmap', function (vis, data) { normalizeOptions(vis, data); return new cdb.geo.CartoDBNamedMapLayer(data); }); Layers.register('torque', function (vis, data) { normalizeOptions(vis, data); // default is https if (vis.https) { if (data.sql_api_domain && data.sql_api_domain.indexOf('cartodb.com') !== -1) { data.sql_api_protocol = 'https'; data.sql_api_port = 443; data.tiler_protocol = 'https'; data.tiler_port = 443; } } data.cartodb_logo = vis.cartodb_logo == undefined ? data.cartodb_logo : vis.cartodb_logo; return new cdb.geo.TorqueLayer(data); }); })(); }<|fim▁end|>
Layers.register('tiled', function (vis, data) {
<|file_name|>Selectors.py<|end_file_name|><|fim▁begin|><|fim▁hole|>:mod:`Selectors` -- selection methods module ============================================================== This module have the *selection methods*, like roulette wheel, tournament, ranking, etc. """ import random import Consts def GRankSelector(population, **args): """ The Rank Selector - This selector will pick the best individual of the population every time. """ count = 0 if args["popID"] != GRankSelector.cachePopID: best_fitness = population.bestFitness().fitness for index in xrange(1, len(population.internalPop)): if population[index].fitness == best_fitness: count += 1 GRankSelector.cachePopID = args["popID"] GRankSelector.cacheCount = count else: count = GRankSelector.cacheCount return population[random.randint(0, count)] GRankSelector.cachePopID = None GRankSelector.cacheCount = None def GUniformSelector(population, **args): """ The Uniform Selector """ return population[random.randint(0, len(population) - 1)] def GTournamentSelector(population, **args): """ The Tournament Selector It accepts the *tournamentPool* population parameter. .. note:: the Tournament Selector uses the Roulette Wheel to pick individuals for the pool """ choosen = None poolSize = population.getParam("tournamentPool", Consts.CDefTournamentPoolSize) tournament_pool = [GRouletteWheel(population, **args) for i in xrange(poolSize)] choosen = min(tournament_pool, key=lambda ind: ind.fitness) return choosen def GTournamentSelectorAlternative(population, **args): """ The alternative Tournament Selector This Tournament Selector don't uses the Roulette Wheel It accepts the *tournamentPool* population parameter. """ pool_size = population.getParam("tournamentPool", Consts.CDefTournamentPoolSize) len_pop = len(population) tournament_pool = [population[random.randint(0, len_pop - 1)] for i in xrange(pool_size)] choosen = min(tournament_pool, key=lambda ind: ind.fitness) return choosen def GRouletteWheel(population, **args): """ The Roulette Wheel selector """ psum = None if args["popID"] != GRouletteWheel.cachePopID: GRouletteWheel.cachePopID = args["popID"] psum = GRouletteWheel_PrepareWheel(population) GRouletteWheel.cacheWheel = psum else: psum = GRouletteWheel.cacheWheel cutoff = random.random() lower = 0 upper = len(population) - 1 while(upper >= lower): i = lower + ((upper - lower) / 2) if psum[i] > cutoff: upper = i - 1 else: lower = i + 1 lower = min(len(population) - 1, lower) lower = max(0, lower) return population.bestFitness(lower) GRouletteWheel.cachePopID = None GRouletteWheel.cacheWheel = None def GRouletteWheel_PrepareWheel(population): """ A preparation for Roulette Wheel selection """ len_pop = len(population) psum = [i for i in xrange(len_pop)] population.statistics() pop_fitMax = population.stats["fitMax"] pop_fitMin = population.stats["fitMin"] if pop_fitMax == pop_fitMin: for index in xrange(len_pop): psum[index] = (index + 1) / float(len_pop) elif (pop_fitMax > 0 and pop_fitMin >= 0) or (pop_fitMax <= 0 and pop_fitMin < 0): population.sort() psum[0] = -population[0].fitness + pop_fitMax + pop_fitMin for i in xrange(1, len_pop): psum[i] = -population[i].fitness + pop_fitMax + pop_fitMin + psum[i - 1] for i in xrange(len_pop): psum[i] /= float(psum[len_pop - 1]) return psum<|fim▁end|>
"""
<|file_name|>plotting_tools.py<|end_file_name|><|fim▁begin|># Copyright (c) 2017, Udacity # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of the FreeBSD Project # Author: Devin Anzelmo import os import glob import numpy as np import matplotlib.patches as mpatches import matplotlib.pyplot as plt from tensorflow.contrib.keras.python import keras from scipy import misc def make_dir_if_not_exist(path): if not os.path.exists(path): os.makedirs(path) def show(im, x=5, y=5): plt.figure(figsize=(x,y)) plt.imshow(im) plt.show() def show_images(maybe_ims, x=4, y=4): if isinstance(maybe_ims, (list, tuple)): border = np.ones((maybe_ims[0].shape[0], 10, 3)) border = border.astype(np.uint8) new_im = maybe_ims[0] for i in maybe_ims[1:]: new_im = np.concatenate((new_im, border, i), axis=1) show(new_im, len(maybe_ims)*x, y) else: show(maybe_ims) # helpers for loading a few images from the grading data def get_im_files(path, subset_name): return sorted(glob.glob(os.path.join(path, subset_name, 'images', '*.jpeg'))) def get_mask_files(path, subset_name): return sorted(glob.glob(os.path.join(path, subset_name, 'masks', '*.png'))) def get_pred_files(subset_name): return sorted(glob.glob(os.path.join('..','data', 'runs', subset_name, '*.png'))) def get_im_file_sample(grading_data_dir_name, subset_name, pred_dir_suffix=None, n_file_names=10): path = os.path.join('..', 'data', grading_data_dir_name) ims = np.array(get_im_files(path, subset_name)) masks = np.array(get_mask_files(path, subset_name)) shuffed_inds = np.random.permutation(np.arange(masks.shape[0])) ims_subset = ims[shuffed_inds[:n_file_names]] masks_subset = masks[shuffed_inds[:n_file_names]] if not pred_dir_suffix: return list(zip(ims_subset, masks_subset)) else: preds = np.array(get_pred_files(subset_name+'_'+pred_dir_suffix)) preds_subset = preds[shuffed_inds[:n_file_names]] return list(zip(ims_subset, masks_subset, preds_subset)) def load_images(file_tuple): im = misc.imread(file_tuple[0]) mask = misc.imread(file_tuple[1]) if len(file_tuple) == 2: return im, mask else: pred = misc.imread(file_tuple[2]) if pred.shape[0] != im.shape[0]: mask = misc.imresize(mask, pred.shape) im = misc.imresize(im, pred.shape) return im, mask, pred def plot_keras_model(model, fig_name): base_path = os.path.join('..', 'data', 'figures') make_dir_if_not_exist(base_path) keras.utils.vis_utils.plot_model(model, os.path.join(base_path, fig_name)) keras.utils.vis_utils.plot_model(model, os.path.join(base_path, fig_name +'_with_shapes'), show_shapes=True) def train_val_curve(train_loss, val_loss=None): train_line = plt.plot(train_loss, label='train_loss') train_patch = mpatches.Patch(color='blue',label='train_loss') handles = [train_patch] if val_loss: val_line = plt.plot(val_loss, label='val_loss') val_patch = mpatches.Patch(color='orange',label='val_loss') handles.append(val_patch) plt.legend(handles=handles, loc=2) plt.title('training curves') plt.ylabel('loss') plt.xlabel('epochs') plt.show() # modified from the BaseLogger in file linked below # https://github.com/fchollet/keras/blob/master/keras/callbacks.py class LoggerPlotter(keras.callbacks.Callback): """Callback that accumulates epoch averages of metrics. and plots train and validation curves on end of epoch """ def __init__(self): self.hist_dict = {'loss':[], 'val_loss':[]} def on_epoch_begin(self, epoch, logs=None): self.seen = 0 self.totals = {} def on_batch_end(self, batch, logs=None): logs = logs or {} batch_size = logs.get('size', 0) self.seen += batch_size for k, v in logs.items(): if k in self.totals: self.totals[k] += v * batch_size else: self.totals[k] = v * batch_size def on_epoch_end(self, epoch, logs=None): if logs is not None: for k in self.params['metrics']: if k in self.totals: # Make value available to next callbacks. logs[k] = self.totals[k] / self.seen self.hist_dict['loss'].append(logs['loss']) if 'val_loss' in self.params['metrics']:<|fim▁hole|> train_val_curve(self.hist_dict['loss'], self.hist_dict['val_loss']) else: train_val_curve(self.hist_dict['loss'])<|fim▁end|>
self.hist_dict['val_loss'].append(logs['val_loss'])
<|file_name|>reactor_server.py<|end_file_name|><|fim▁begin|>from kivy.support import install_twisted_reactor install_twisted_reactor() from twisted.internet import reactor from twisted.internet import protocol class EchoProtocol(protocol.Protocol): def dataReceived(self, data): response = self.factory.app.handle_message(data) if response: self.transport.write(response) class EchoFactory(protocol.Factory): protocol = EchoProtocol def __init__(self, app): self.app = app from kivy.app import App from kivy.uix.label import Label class TwistedServerApp(App): def build(self): self.label = Label(text="server started\n") reactor.listenTCP(8000, EchoFactory(self)) return self.label def handle_message(self, msg): self.label.text = "received: %s\n" % msg if msg == "ping": msg = "pong" if msg == "plop": msg = "kivy rocks" self.label.text += "responded: %s\n" % msg return msg<|fim▁hole|>if __name__ == '__main__': TwistedServerApp().run()<|fim▁end|>
<|file_name|>htptProxy.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Ben Jones # Georgia Tech # Spring 2014 # # htpt-socks.py: this file builds upon the work of Zavier Lagraula's # PySocks code to create a SOCKS server for our HTTP circumvention tool import socks """SOCKS 4 proxy server class. Copyright (C) 2001 Xavier Lagraula See COPYRIGHT.txt and GPL.txt for copyrights information. Build upon the TCPServer class of the SocketServer module, the Socks4Proxy class is an implementation of the SOCKS protocol, version 4. This server uses one thread per connection request. Known bugs: - Some CONNECT request closed by the client are not detected and finish in an infinite loop of select always returning the "request" socket as ready to read even if there is nothing more to read on it. This situation is now detected and lead to a Closed_Connection exception. Implementation choices: - Protocol errors are handled by exceptions - The function that creates a socket is responsible for its closing -> never close a socket passed in as a parameter, and always use a try/finally block after creating a socket to ensure correct closing of sockets. """ import SocketServer2 import time import select import thread import IDENT_Client import IPv4_Tools import getopt import os import sys import socket import ConfigFile __all__ = [ 'DEFAULT_OPTIONS', 'SocksError', 'Connection_Closed', 'Bind_TimeOut_Expired', 'Request_Error', 'Client_Connection_Closed', 'Remote_Connection_Closed', 'Remote_Connection_Failed', 'Remote_Connection_Failed_Invalid_Host', 'Request_Failed', 'Request_Failed_No_Identd', 'Request_Failed_Ident_failed', 'Request_Refused', 'Request_Bad_Version', 'Request_Unknown_Command', 'Request_Unauthorized_Client', 'Request_Invalid_Port', 'Request_Invalid_Format', 'ThreadingSocks4Proxy' ] # Default server options. # Options are stored in a dictionary. DEFAULT_OPTIONS = {} OPTION_TYPE = {} # The interface on which the server listens for incoming SOCKS requests. DEFAULT_OPTIONS['bind_address'] = '127.0.0.1' # The port on which the server listens for incoming SOCKS requests. DEFAULT_OPTIONS['bind_port'] = 10000 # Will the server use IDENT request to authenticate the user making a request? DEFAULT_OPTIONS['use_ident'] = 0 # Maximum request size taken in consideration. DEFAULT_OPTIONS['req_buf_size'] = 1024 # Data is forwarded between the client and the remote peer by blocks of max # 'data_buf_size' bytes. DEFAULT_OPTIONS['data_buf_size'] = 1500 # After this delay n seconds without any activity on a connection between the # client and the remote peer, the connection is closed. DEFAULT_OPTIONS['inactivity_timeout'] = 360 # The SOCKS proxy waits no more than this number of seconds for an incoming # connection (BIND requests). It then rejects the client request. DEFAULT_OPTIONS['bind_timeout'] = 120 DEFAULT_OPTIONS['send_port'] = 8000 SHORT_OPTIONS = 'a:p:i:r:d:t:b:' # The map trick is useful here as all options LONG_OPTIONS = [ 'bind_address=', 'bind_port=', 'use_ident', 'req_buf_size=', 'data_buf_size=', 'inactivity_timeout=', 'bind_timeout=' ] DEFAULT_OPTIONS['configfile'] = '' OPTION_TYPE['configfile'] = ['string'] # SOCKS 4 protocol constant values. SOCKS_VERSION = 4 COMMAND_CONNECT = 1 COMMAND_BIND = 2 COMMANDS = [ COMMAND_CONNECT, COMMAND_BIND ] REQUEST_GRANTED = 90 REQUEST_REJECTED_FAILED = 91 REQUEST_REJECTED_NO_IDENTD = 92 REQUEST_REJECTED_IDENT_FAILED = 93 # Sockets protocol constant values. ERR_CONNECTION_RESET_BY_PEER = 10054 ERR_CONNECTION_REFUSED = 10061 # For debugging only. def now(): return time.ctime(time.time()) # Exception classes for the server class SocksError(Exception): pass class Connection_Closed(SocksError): pass class Bind_TimeOut_Expired(SocksError): pass class Request_Error(SocksError): pass class Client_Connection_Closed(Connection_Closed): pass class Remote_Connection_Closed(Connection_Closed): pass class Remote_Connection_Failed(Connection_Closed): pass class Remote_Connection_Failed_Invalid_Host(Remote_Connection_Failed): pass class Request_Failed(Request_Error): pass class Request_Failed_No_Identd(Request_Failed): pass class Request_Failed_Ident_failed(Request_Failed): pass class Request_Refused(Request_Error): pass class Request_Bad_Version(Request_Refused): pass class Request_Unknown_Command(Request_Refused): pass class Request_Unauthorized_Client(Request_Refused): pass class Request_Invalid_Port(Request_Refused): pass class Request_Invalid_Format(Request_Refused): pass # Server class class ThreadingSocks4Proxy(SocketServer2.ThreadingTCPServer): """Threading SOCKS4 proxy class. Note: this server maintains two lists of all CONNECTION and BIND requests being handled. This is not really useful for now but may become in the future. Moreover, it has been a good way to learn about the semaphores of the threading module :)""" def __Decode_Command_Line(self, argv = [], definitions = {}, defaults = {}): result = {} line_opts, rest = getopt.getopt(argv, SHORT_OPTIONS, LONG_OPTIONS) for item in line_opts: opt, value = item <|fim▁hole|> opt = 'bind_adress' elif opt in ['-p', '--bind_port']: opt = 'bind_port' elif opt in ['-i', '--use_ident']: opt = 'use_ident' value = 1 elif opt in ['-r', '--req_buf_size']: opt = 'req_buf_size' elif opt in ['-d', '--data_buf_size']: opt = 'data_buf_size' elif opt in ['-d', '--inactivity_timeout']: opt = 'inactivity_timeout' elif opt in ['-b', '--bind_timeout']: opt = 'bind_timeout' result[opt] = value return ConfigFile.evaluate(definitions, result, defaults) def __init__(self, RequestHandlerClass, *args): """Constructor of the server.""" self.Options = DEFAULT_OPTIONS listenPort = args[0] if len(args) > 1: sendPort = args[1] self.Options['send_port'] = sendPort self.Options['bind_port'] = listenPort print "Server starting with following options:" for i in self.Options.keys(): print i, ':', self.Options[i] print 'The choosen ip adress is', DEFAULT_OPTIONS['bind_address'] SocketServer2.ThreadingTCPServer.__init__( self, (self.Options['bind_address'], self.Options['bind_port']), RequestHandlerClass) class ForwardSocksReq(SocketServer2.BaseRequestHandler): """This request handler class handles sOCKS 4 requests.""" def handle(self): """This function is the main request handler function. It delegates each step of the request processing to a different function and handles raised exceptions in order to warn the client that its request has been rejected (if needed). The steps are: - decode_request: reads the request and splits it into a dictionary. it checks if the request is well-formed (correct socks version, correct command number, well-formed port number. - validate_request: checks if the current configuration accepts to handle the request (client identification, authorization rules) - handle_connect: handles CONNECT requests - handle_bind: handles BIND requests """ print thread.get_ident(), '-'*40 print thread.get_ident(), 'Request from ', self.client_address try: # Read and decode the request from the client and verify that it # is well-formed. req = self.decode_request() print thread.get_ident(), 'Decoded request:', req # We have some well-formed request to handle. # Let's validate it. self.validate_request(req) # We are here so the request is valid. # We must decide of the action to take according to the "command" # part of the request. if req['command'] == COMMAND_CONNECT: self.handle_connect(req) elif req['command'] == COMMAND_BIND: self.handle_bind(req) # Global SOCKS errors handling. except Request_Failed_No_Identd: self.answer_rejected(REQUEST_REJECTED_NO_IDENTD) except Request_Failed_Ident_failed: self.answer_rejected(REQUEST_REJECTED_IDENT_FAILED) except Request_Error: self.answer_rejected() except Remote_Connection_Failed: self.answer_rejected() except Bind_TimeOut_Expired: self.answer_rejected() # Once established, if the remote or the client connection is closed # we must exit silently. This exception is in fact the way the function # used to forward data between the client and the remote server tells # us it has finished working. except Connection_Closed: pass def validate_request(self, req): """This function validates the request against any validating rule. Two things are taken in consideration: - where does the request come from? (address check) - who is requesting? (identity check) Note: in fact, identity verification is disabled for now because ICQ does stupid things such as always providing a "a" user that doesn't exists in bind requests.""" # Address check. As for now, only requests from non routable addresses # are accepted. This is because of security issues and will later be # configurable with a system of validating rules. if IPv4_Tools.is_routable(self.client_address[0]): raise Request_Unauthorized_Client(req) # If a user ID is provided, we must make an identd control. As for now, # we accept request without userid without control but this behaviour # will be changed when configurations options will be provided. if req['userid'] and self.server.Options['use_ident']: # We must get some information about the request socket to build # the identd request. local_ip, local_port = self.request.getsockname() ident_srv_ip, ident_srv_port = self.request.getpeername() if (not IDENT_Client.check_IDENT( ident_srv_ip, ident_srv_port, local_port, req['userid'])): raise Request_Failed_Ident_failed(req) # If we managed to get here, then the request is valid. def decode_request(self): """This function reads the request socket for the request data, decodes it and checks that it is well formed.""" # reading the data from the socket. data = self.request.recv(self.server.Options['req_buf_size']) # It is useless to process too short a request. if len(data) < 9: raise Request_Invalid_Format(data) # Extracting components of the request. Checks are made at each step. req = {} # SOCKS version of the request. req['version'] = ord(data[0]) if req['version'] != SOCKS_VERSION: raise Request_Bad_Version(req) # Command used. req['command'] = ord(data[1]) if not req['command'] in COMMANDS: raise Request_Unknown_Command(req) # Address of the remote peer. req['address'] = ( socket.inet_ntoa(data[4:8]), self.string2port(data[2:4])) if not IPv4_Tools.is_port(req['address'][1]): raise Request_Invalid_Port(req) # Note: only the fact that the port is in [1, 65535] is checked here. # Address and port legitimity are later checked in validate_request. # Requester user ID. May not be provided. req['userid'] = self.get_string(data[8:]) req['data'] = data # If we are here, then the request is well-formed. Let us return it to # the caller. return req def handle_connect(self, req): """This function handles a CONNECT request. The actions taken are: - create a new socket, - register the connection into the server, - connect to the remote host, - tell the client the connection is established, - forward data between the client and the remote peer.""" # Create a socket to connect to the remote server print "Here- address: {}".format(req['address']) # remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote = socks.socksocket() remote.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) remote.setproxy(socks.PROXY_TYPE_SOCKS4, "localhost", self.server.Options['send_port']) # From now on, we must not forget to close this socket before leaving. try: try: # Connection to the remote server print thread.get_ident(), 'Connecting to', req['address'] # Possible way to handle the timeout defined in the protocol! # Make the connect non-blocking, then do a select and keep # an eye on the writable socket, just as I did with the # accept() from BIND requests. # Do this tomorrow... Geez... 00:47... Do this this evening. # remote.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # print "Trying to connect to server: {}".format(self.server.Options['send_port']) # remote.connect(("127.0.0.1",self.server.Options['send_port'])) remote.connect(req['address']) print "Success!" # remote.send(req['data']) # The only connection that can be reset here is the one of the # client, so we don't need to answer. Any other socket # exception forces us to try to answer to the client. except socket.error as e: print e exception, value, traceback = sys.exc_info() if value[0] == ERR_CONNECTION_RESET_BY_PEER: raise Client_Connection_Closed((ERR_CONNECTION_RESET_BY_PEER, socket.errorTab[ERR_CONNECTION_RESET_BY_PEER])) else: raise Remote_Connection_Failed except: raise Remote_Connection_Failed # From now on we will already have answered to the client. # Any exception occuring now must make us exit silently. try: # Telling the client that the connection it asked for is # granted. self.answer_granted() # Starting to relay information between the two peers. self.forward(self.request, remote) # We don't have the right to "speak" to the client anymore. # So any socket failure means a "connection closed" and silent # exit. except socket.error: raise Connection_Closed # Mandatory closing of the remote socket. finally: remote.close() def answer_granted(self, dst_ip = '0.0.0.0', dst_port = 0): """This function sends a REQUEST_GRANTED answer to the client.""" self.answer(REQUEST_GRANTED, dst_ip, dst_port) def answer_rejected(self, reason = REQUEST_REJECTED_FAILED, dst_ip = '0.0.0.0', dst_port = 0): """This function send a REQUEST_REJECTED answer to the client.""" self.answer(reason, dst_ip, dst_port) def answer(self, code = REQUEST_GRANTED, ip_str = '0.0.0.0', port_int = 0): """This function sends an answer to the client. This has been factorised because all answers follow the same format.""" # Any problem occuring here means that we are unable to "speak" to # the client -> we must act as if the connection to it had already # been closed. try: ip = socket.inet_aton(ip_str) port = self.port2string(port_int) packet = chr(0) # Version number is 0 in answer packet += chr(code) # Error code packet += port packet += ip print thread.get_ident(), 'Sending back:', code, self.string2port(port), socket.inet_ntoa(ip) self.request.send(packet) except: # Trying to keep a trace of the original exception. raise Client_Connection_Closed(sys.exc_info()) def forward(self, client_sock, server_sock): """This function makes the forwarding of data by listening to two sockets, and writing to one everything it reads on the other. This is done using select(), in order to be able to listen on both sockets simultaneously and to implement an inactivity timeout.""" # Once we're here, we are not supposed to "speak" with the client # anymore. So any error means for us to close the connection. print thread.get_ident(), 'Forwarding.' # These are not used to anything significant now, but I keep them in # case I would want to do some statistics/logging. octets_in, octets_out = 0, 0 try: try: # Here are the sockets we will be listening. sockslist = [client_sock, server_sock] while 1: # Let us listen... readables, writeables, exceptions = select.select( sockslist, [], [], self.server.Options['inactivity_timeout']) # If the "exceptions" list is not empty or if we are here # because of the timer (i.e. all lists are empty), then # we must must bail out, we have finished our work. if (exceptions or (readables, writeables, exceptions) == ([], [], [])): raise Connection_Closed # Only a precaution. data = '' # Just in case we would be in the improbable case of data # awaiting to be read on both sockets, we treat the # "readables" list as if it oculd contain more than one # element. Thus the "for" loop... for readable_sock in readables: # We know the socket we want to read of, but we still # must find what is the other socket. This method # builds a list containing one element. writeableslist = [client_sock, server_sock] writeableslist.remove(readable_sock) # We read one chunk of data and then send it to the # other socket data = readable_sock.recv( self.server.Options['data_buf_size']) # We must handle the case where data=='' because of a # bug: we sometimes end with an half-closed socket, # i.e. a socket closed by the peer, on which one can # always read, but where there is no data to read. # This must be detected or it would lead to an infinite # loop. if data: writeableslist[0].send(data) # This is only for future logging/stats. if readable_sock == client_sock: octets_out += len(data) else: octets_in += len(data) else: # The sock is readable but nothing can be read. # This means a poorly detected connection close. raise Connection_Closed # If one peer closes its conenction, we have finished our work. except socket.error: exception, value, traceback = sys.exc_info() if value[0] == ERR_CONNECTION_RESET_BY_PEER: raise Connection_Closed raise finally: print thread.get_ident(), octets_in, 'octets in and', octets_out, 'octets out. Connection closed.' def string2port(self, port_str): """This function converts between a packed (16 bits) port number to an integer.""" return (ord(port_str[0]) << 8) + ord(port_str[1]) def port2string(self, port): """This function converts a port number (16 bits integer) into a packed string (2 chars).""" return chr((port & 0xff00) >> 8)+ chr(port & 0x00ff) def get_string(self, nullterminated): """This function converts a null terminated string stored in a Python string to a "normal Python string.""" return nullterminated[0: nullterminated.index(chr(0))] class ReceiveSocksReq(SocketServer2.BaseRequestHandler): """This request handler class handles sOCKS 4 requests.""" def handle(self): """This function is the main request handler function. It delegates each step of the request processing to a different function and handles raised exceptions in order to warn the client that its request has been rejected (if needed). The steps are: - decode_request: reads the request and splits it into a dictionary. it checks if the request is well-formed (correct socks version, correct command number, well-formed port number. - validate_request: checks if the current configuration accepts to handle the request (client identification, authorization rules) - handle_connect: handles CONNECT requests - handle_bind: handles BIND requests """ print thread.get_ident(), '-'*40 print thread.get_ident(), 'Request from ', self.client_address try: # Read and decode the request from the client and verify that it # is well-formed. req = self.decode_request() print thread.get_ident(), 'Decoded request:', req # We have some well-formed request to handle. # Let's validate it. self.validate_request(req) # We are here so the request is valid. # We must decide of the action to take according to the "command" # part of the request. if req['command'] == COMMAND_CONNECT: self.handle_connect(req) elif req['command'] == COMMAND_BIND: self.handle_bind(req) # Global SOCKS errors handling. except Request_Failed_No_Identd: self.answer_rejected(REQUEST_REJECTED_NO_IDENTD) except Request_Failed_Ident_failed: self.answer_rejected(REQUEST_REJECTED_IDENT_FAILED) except Request_Error: self.answer_rejected() except Remote_Connection_Failed: self.answer_rejected() except Bind_TimeOut_Expired: self.answer_rejected() # Once established, if the remote or the client connection is closed # we must exit silently. This exception is in fact the way the function # used to forward data between the client and the remote server tells # us it has finished working. except Connection_Closed: pass def validate_request(self, req): """This function validates the request against any validating rule. Two things are taken in consideration: - where does the request come from? (address check) - who is requesting? (identity check) Note: in fact, identity verification is disabled for now because ICQ does stupid things such as always providing a "a" user that doesn't exists in bind requests.""" # Address check. As for now, only requests from non routable addresses # are accepted. This is because of security issues and will later be # configurable with a system of validating rules. if IPv4_Tools.is_routable(self.client_address[0]): raise Request_Unauthorized_Client(req) # If a user ID is provided, we must make an identd control. As for now, # we accept request without userid without control but this behaviour # will be changed when configurations options will be provided. if req['userid'] and self.server.Options['use_ident']: # We must get some information about the request socket to build # the identd request. local_ip, local_port = self.request.getsockname() ident_srv_ip, ident_srv_port = self.request.getpeername() if (not IDENT_Client.check_IDENT( ident_srv_ip, ident_srv_port, local_port, req['userid'])): raise Request_Failed_Ident_failed(req) # If we managed to get here, then the request is valid. def decode_request(self): """This function reads the request socket for the request data, decodes it and checks that it is well formed.""" # reading the data from the socket. data = self.request.recv(self.server.Options['req_buf_size']) # It is useless to process too short a request. if len(data) < 9: raise Request_Invalid_Format(data) # Extracting components of the request. Checks are made at each step. req = {} # SOCKS version of the request. req['version'] = ord(data[0]) if req['version'] != SOCKS_VERSION: raise Request_Bad_Version(req) # Command used. req['command'] = ord(data[1]) if not req['command'] in COMMANDS: raise Request_Unknown_Command(req) # Address of the remote peer. req['address'] = ( socket.inet_ntoa(data[4:8]), self.string2port(data[2:4])) if not IPv4_Tools.is_port(req['address'][1]): raise Request_Invalid_Port(req) # Note: only the fact that the port is in [1, 65535] is checked here. # Address and port legitimity are later checked in validate_request. # Requester user ID. May not be provided. req['userid'] = self.get_string(data[8:]) # If we are here, then the request is well-formed. Let us return it to # the caller. return req def handle_bind(self, req): """This function handles a BIND request. The actions taken are: - create a new socket, - bind it to the external ip chosen on init of the server, - listen for a connection on this socket, - register the bind into the server, - tell the client the bind is ready, - accept an incoming connection, - tell the client the connection is established, - forward data between the client and the remote peer.""" # Create a socket to receive incoming connection. remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # From now on, whatever we do, we must close the "remote" socket before # leaving. I love try/finally blocks. try: # In this block, the only open connection is the client one, so a # ERR_CONNECTION_RESET_BY_PEER exception means "exit silently # because you won't be able to send me anything anyway". # Any other exception must interrupt processing and exit from here. try: # Binding the new socket to the chosen external ip remote.bind((self.server.external_ip, 0)) remote.listen(1) # Collecting information about the socket to store it in the # "waiting binds" list. socket_ip, socket_port = remote.getsockname() except socket.error: # A "connection reset by peer" here means the client has closed # the connection. exception, value, traceback = sys.exc_info() if value[0] == ERR_CONNECTION_RESET_BY_PEER: raise Client_Connection_Closed((ERR_CONNECTION_RESET_BY_PEER, socket.errorTab[ERR_CONNECTION_RESET_BY_PEER])) else: # We may be able to make a more precise diagnostic, but # in fact, it doesn't seem useful here for now. raise Remote_Connection_Failed # Sending first answer meaning request is accepted and socket # is waiting for incoming connection. self.answer_granted(socket_ip, socket_port) try: # Waiting for incoming connection. I use a select here to # implement the timeout stuff. read_sock, junk, exception_sock = select.select( [remote], [], [remote], self.server.Options['bind_timeout']) # If all lists are empty, then the select has ended because # of the timer. if (read_sock, junk, exception_sock) == ([], [], []): raise Bind_TimeOut_Expired # We also drop the connection if an exception condition is # detected on the socket. We must also warn the client that # its request is rejecte (remember that for a bind, the client # expects TWO answers from the proxy). if exception_sock: raise Remote_Connection_Failed # An incoming connection is pending. Let us accept it incoming, peer = remote.accept() except: # We try to keep a trace of the previous exception # for debugging purpose. raise Remote_Connection_Failed(sys.exc_info()) # From now on , we must not forget to close this connection. try: # We must now check that the incoming connection is from # the expected server. if peer[0] != req['address'][0]: raise Remote_Connection_Failed_Invalid_Host # We can now tell the client the connection is OK, and # start the forwarding process. self.answer_granted() self.forward(self.request, incoming) # Mandatory closing of the socket with the remote peer. finally: incoming.close() # Mandatory closing ofthe listening socket finally: remote.close() def handle_connect(self, req): """This function handles a CONNECT request. The actions taken are: - create a new socket, - register the connection into the server, - connect to the remote host, - tell the client the connection is established, - forward data between the client and the remote peer.""" # Create a socket to connect to the remote server remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # From now on, we must not forget to close this socket before leaving. try: try: # Connection to the remote server print thread.get_ident(), 'Connecting to', req['address'] # Possible way to handle the timeout defined in the protocol! # Make the connect non-blocking, then do a select and keep # an eye on the writable socket, just as I did with the # accept() from BIND requests. # Do this tomorrow... Geez... 00:47... Do this this evening. remote.connect(req['address']) # The only connection that can be reset here is the one of the # client, so we don't need to answer. Any other socket # exception forces us to try to answer to the client. except socket.error: exception, value, traceback = sys.exc_info() if value[0] == ERR_CONNECTION_RESET_BY_PEER: raise Client_Connection_Closed((ERR_CONNECTION_RESET_BY_PEER, socket.errorTab[ERR_CONNECTION_RESET_BY_PEER])) else: raise Remote_Connection_Failed except: raise Remote_Connection_Failed # From now on we will already have answered to the client. # Any exception occuring now must make us exit silently. try: # Telling the client that the connection it asked for is # granted. self.answer_granted() # Starting to relay information between the two peers. self.forward(self.request, remote) # We don't have the right to "speak" to the client anymore. # So any socket failure means a "connection closed" and silent # exit. except socket.error: raise Connection_Closed # Mandatory closing of the remote socket. finally: remote.close() def answer_granted(self, dst_ip = '0.0.0.0', dst_port = 0): """This function sends a REQUEST_GRANTED answer to the client.""" self.answer(REQUEST_GRANTED, dst_ip, dst_port) def answer_rejected(self, reason = REQUEST_REJECTED_FAILED, dst_ip = '0.0.0.0', dst_port = 0): """This function send a REQUEST_REJECTED answer to the client.""" self.answer(reason, dst_ip, dst_port) def answer(self, code = REQUEST_GRANTED, ip_str = '0.0.0.0', port_int = 0): """This function sends an answer to the client. This has been factorised because all answers follow the same format.""" # Any problem occuring here means that we are unable to "speak" to # the client -> we must act as if the connection to it had already # been closed. try: ip = socket.inet_aton(ip_str) port = self.port2string(port_int) packet = chr(0) # Version number is 0 in answer packet += chr(code) # Error code packet += port packet += ip print thread.get_ident(), 'Sending back:', code, self.string2port(port), socket.inet_ntoa(ip) self.request.send(packet) except: # Trying to keep a trace of the original exception. raise Client_Connection_Closed(sys.exc_info()) def forward(self, client_sock, server_sock): """This function makes the forwarding of data by listening to two sockets, and writing to one everything it reads on the other. This is done using select(), in order to be able to listen on both sockets simultaneously and to implement an inactivity timeout.""" # Once we're here, we are not supposed to "speak" with the client # anymore. So any error means for us to close the connection. print thread.get_ident(), 'Forwarding.' # These are not used to anything significant now, but I keep them in # case I would want to do some statistics/logging. octets_in, octets_out = 0, 0 try: try: # Here are the sockets we will be listening. sockslist = [client_sock, server_sock] while 1: # Let us listen... readables, writeables, exceptions = select.select( sockslist, [], [], self.server.Options['inactivity_timeout']) # If the "exceptions" list is not empty or if we are here # because of the timer (i.e. all lists are empty), then # we must must bail out, we have finished our work. if (exceptions or (readables, writeables, exceptions) == ([], [], [])): raise Connection_Closed # Only a precaution. data = '' # Just in case we would be in the improbable case of data # awaiting to be read on both sockets, we treat the # "readables" list as if it oculd contain more than one # element. Thus the "for" loop... for readable_sock in readables: # We know the socket we want to read of, but we still # must find what is the other socket. This method # builds a list containing one element. writeableslist = [client_sock, server_sock] writeableslist.remove(readable_sock) # We read one chunk of data and then send it to the # other socket data = readable_sock.recv( self.server.Options['data_buf_size']) # We must handle the case where data=='' because of a # bug: we sometimes end with an half-closed socket, # i.e. a socket closed by the peer, on which one can # always read, but where there is no data to read. # This must be detected or it would lead to an infinite # loop. if data: writeableslist[0].send(data) # This is only for future logging/stats. if readable_sock == client_sock: octets_out += len(data) else: octets_in += len(data) else: # The sock is readable but nothing can be read. # This means a poorly detected connection close. raise Connection_Closed # If one peer closes its conenction, we have finished our work. except socket.error: exception, value, traceback = sys.exc_info() if value[0] == ERR_CONNECTION_RESET_BY_PEER: raise Connection_Closed raise finally: print thread.get_ident(), octets_in, 'octets in and', octets_out, 'octets out. Connection closed.' def string2port(self, port_str): """This function converts between a packed (16 bits) port number to an integer.""" return (ord(port_str[0]) << 8) + ord(port_str[1]) def port2string(self, port): """This function converts a port number (16 bits integer) into a packed string (2 chars).""" return chr((port & 0xff00) >> 8)+ chr(port & 0x00ff) def get_string(self, nullterminated): """This function converts a null terminated string stored in a Python string to a "normal Python string.""" return nullterminated[0: nullterminated.index(chr(0))] if __name__ == "__main__": server = ThreadingSocks4Proxy(ReceiveSocksReq, sys.argv[1:]) server.serve_forever()<|fim▁end|>
# First trying "opt" value against options that use an argument. if opt in ['-a', '--bind_adress']:
<|file_name|>return.js<|end_file_name|><|fim▁begin|>'use strict'; /*! * Snakeskin * https://github.com/SnakeskinTpl/Snakeskin * * Released under the MIT license * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE */ import Snakeskin from '../core'; import { ws } from '../helpers/string'; import { any } from '../helpers/gcc'; Snakeskin.addDirective( 'return', { block: true, deferInit: true, group: ['return', 'microTemplate'], placement: 'template', trim: true }, function (command) { if (command.slice(-1) === '/') { this.startInlineDir(null, {command: command.slice(0, -1)}); return; } this.startDir(null, {command}); if (!command) { this.wrap(`__RESULT__ = ${this.getResultDecl()};`); } }, function () { const {command} = this.structure.params; const val = command ? this.out(command, {unsafe: true}) : this.getReturnResultDecl(), parent = any(this.hasParentFunction()); if (!parent || parent.block) { this.append(`return ${val};`); return; } const def = ws` __RETURN__ = true; __RETURN_VAL__ = ${val}; `; let str = ''; if (parent.asyncParent) { if (this.getGroup('Async')[parent.asyncParent]) { str += def; if (this.getGroup('waterfall')[parent.asyncParent]) { str += 'return arguments[arguments.length - 1](__RETURN_VAL__);'; } else { str += ws` if (typeof arguments[0] === 'function') { return arguments[0](__RETURN_VAL__); } return false; `; }<|fim▁hole|> } else { str += 'return false;'; } } else { if (parent && !this.getGroup('async')[parent.target.name]) { str += def; this.deferReturn = 1; } str += 'return false;'; } this.append(str); } );<|fim▁end|>
<|file_name|>test_driver.py<|end_file_name|><|fim▁begin|># Copyright 2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from neutron_lib import constants from oslo_config import cfg from neutron.callbacks import events from neutron.callbacks import registry from neutron.plugins.ml2.drivers.openvswitch.agent.common import ( constants as agent_consts) from neutron.services.trunk.drivers.openvswitch import driver from neutron.tests import base GEN_TRUNK_BR_NAME_PATCH = ( 'neutron.services.trunk.drivers.openvswitch.utils.gen_trunk_br_name') class OVSDriverTestCase(base.BaseTestCase): def test_driver_creation(self): ovs_driver = driver.OVSDriver.create() self.assertFalse(ovs_driver.is_loaded) self.assertEqual(driver.NAME, ovs_driver.name) self.assertEqual(driver.SUPPORTED_INTERFACES, ovs_driver.interfaces) self.assertEqual(driver.SUPPORTED_SEGMENTATION_TYPES, ovs_driver.segmentation_types)<|fim▁hole|> self.assertTrue( ovs_driver.is_agent_compatible(constants.AGENT_TYPE_OVS)) self.assertTrue( ovs_driver.is_interface_compatible(driver.SUPPORTED_INTERFACES[0])) def test_driver_is_loaded(self): cfg.CONF.set_override('mechanism_drivers', 'openvswitch', group='ml2') ovs_driver = driver.OVSDriver.create() self.assertTrue(ovs_driver.is_loaded) def test_driver_is_not_loaded(self): cfg.CONF.set_override('core_plugin', 'my_foo_plugin') ovs_driver = driver.OVSDriver.create() self.assertFalse(ovs_driver.is_loaded) @mock.patch(GEN_TRUNK_BR_NAME_PATCH) def test_vif_details_bridge_name_handler_registration(self, mock_gen_br_name): driver.register() mock_gen_br_name.return_value = 'fake-trunk-br-name' test_trigger = mock.Mock() registry.notify(agent_consts.OVS_BRIDGE_NAME, events.BEFORE_READ, test_trigger, **{'port': {'trunk_details': {'trunk_id': 'foo'}}}) test_trigger.assert_called_once_with('fake-trunk-br-name')<|fim▁end|>
self.assertEqual(constants.AGENT_TYPE_OVS, ovs_driver.agent_type) self.assertFalse(ovs_driver.can_trunk_bound_port)
<|file_name|>rnatreemap.js<|end_file_name|><|fim▁begin|>import {rnaPlot} from './rnaplot.js'; export function rnaTreemapChart() { var width = 550; var height = 400; function rnaTreemapNode(selection) { // create a background rectangle for each RNA structure selection.each(function(d) { d3.select(this) .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')' }) .append('rect') .classed('structure-background-rect', true) .attr('width', function(d) { return Math.max(0, d.dx); }) .attr('height', function(d) { return Math.max(0, d.dy); }) // draw the actual RNA structure var chart = rnaPlot() .width( Math.max(0, d.dx)) .height( Math.max(0, d.dy)) .labelInterval(0) .rnaEdgePadding(10) .showNucleotideLabels(false); if ('structure' in d) d3.select(this).call(chart) }); } var chart = function(selection) { selection.each(function(data) { console.log('data:', data) // initialize the treemap structure // sample input // { 'name': 'blah', // 'children: [{'structure': '..((..))', // 'sequence': 'ACCGGCC', // 'size': 50}] // } var treemap = d3.layout.treemap() .size([width, height]) .sticky(false) .value(function(d) { return d.size; }); // create a new <g> for each node in the treemap // this may be a little redundant, since we expect the calling // selection to contain their own g elements var gEnter = d3.select(this).append('g'); var treemapGnodes = gEnter.datum(data).selectAll('.treemapNode') .data(treemap.nodes) .enter() .append('g') .attr('class', 'treemapNode') .call(rnaTreemapNode); }); }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart;<|fim▁hole|> chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; } return chart; } function rnaTreemapGridChart() { var chart = function(selection) { console.log('selection:', selection); selection.each(function(data) { console.log('data:', data); }); } return chart; }<|fim▁end|>
}
<|file_name|>BC7019.java<|end_file_name|><|fim▁begin|>/** * ByteCart, ByteCart Redux * Copyright (C) Catageek * Copyright (C) phroa * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package com.github.catageek.bytecart.sign; import com.github.catageek.bytecart.address.Address; import com.github.catageek.bytecart.address.AddressFactory; import com.github.catageek.bytecart.address.AddressString; import com.github.catageek.bytecart.hardware.RegistryBoth; import com.github.catageek.bytecart.hardware.RegistryInput; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.entity.Entity; import java.util.Random; /** * Gives random address to a cart */ final class BC7019 extends BC7010 implements Triggerable { BC7019(BlockSnapshot block, Entity vehicle) { super(block, vehicle); this.storageCartAllowed = true; } @Override public String getName() { return "BC7019"; } @Override public String getFriendlyName() { return "Random Destination"; } @Override protected Address getAddressToWrite() { int startRegion = getInput(3).getValue(); int endRegion = getInput(0).getValue(); int newRegion = startRegion + (new Random()).nextInt(endRegion - startRegion + 1); int startTrack = getInput(4).getValue(); int endTrack = getInput(1).getValue(); int newTrack = startTrack + (new Random()).nextInt(endTrack - startTrack + 1); int startStation = getInput(5).getValue(); int endStation = getInput(2).getValue(); int newStation = startStation + (new Random()).nextInt(endStation - startStation + 1); return new AddressString(String.format("%d.%d.%d", newRegion, newTrack, newStation), false); }<|fim▁hole|> protected void addIO() { // add input [0], [1] and [2] from 4th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 3)); // add input [3], [4] and [5] from 3th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 2)); } private void addAddressAsInputs(Address addr) { if (addr.isValid()) { RegistryInput region = addr.getRegion(); this.addInputRegistry(region); RegistryInput track = addr.getTrack(); this.addInputRegistry(track); RegistryBoth station = addr.getStation(); this.addInputRegistry(station); } } }<|fim▁end|>
<|file_name|>kill.rs<|end_file_name|><|fim▁begin|>#![crate_name = "uu_kill"] /* * This file is part of the uutils coreutils package. * * (c) Maciej Dziardziel <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use libc::{c_int, pid_t}; use std::io::{Error, Write}; use uucore::signals::ALL_SIGNALS; static NAME: &'static str = "kill"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); static EXIT_OK: i32 = 0; static EXIT_ERR: i32 = 1; #[derive(Clone, Copy)] pub enum Mode { Kill, Table, List, Help, Version, } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); opts.optopt("s", "signal", "specify the <signal> to be sent", "SIGNAL"); opts.optflagopt("l", "list", "list all signal names, or convert one to a name", "LIST"); opts.optflag("L", "table", "list all signal names in a nice table"); let (args, obs_signal) = handle_obsolete(args); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(_) => { help(&opts); return EXIT_ERR; }, }; let mode = if matches.opt_present("version") { Mode::Version } else if matches.opt_present("help") { Mode::Help } else if matches.opt_present("table") { Mode::Table } else if matches.opt_present("list") { Mode::List } else { Mode::Kill }; match mode {<|fim▁hole|> Mode::Help => help(&opts), Mode::Version => version(), } 0 } fn version() { println!("{} {}", NAME, VERSION); } fn handle_obsolete(mut args: Vec<String>) -> (Vec<String>, Option<String>) { let mut i = 0; while i < args.len() { // this is safe because slice is valid when it is referenced let slice = &args[i].clone(); if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) { let val = &slice[1..]; match val.parse() { Ok(num) => { if uucore::signals::is_signal(num) { args.remove(i); return (args, Some(val.to_owned())); } } Err(_)=> break /* getopts will error out for us */ } } i += 1; } (args, None) } fn table() { let mut name_width = 0; /* Compute the maximum width of a signal name. */ for s in &ALL_SIGNALS { if s.name.len() > name_width { name_width = s.name.len() } } for (idx, signal) in ALL_SIGNALS.iter().enumerate() { print!("{0: >#2} {1: <#8}", idx+1, signal.name); //TODO: obtain max signal width here if (idx+1) % 7 == 0 { println!(""); } } } fn print_signal(signal_name_or_value: &str) { for signal in &ALL_SIGNALS { if signal.name == signal_name_or_value || (format!("SIG{}", signal.name)) == signal_name_or_value { println!("{}", signal.value); exit!(EXIT_OK as i32) } else if signal_name_or_value == signal.value.to_string() { println!("{}", signal.name); exit!(EXIT_OK as i32) } } crash!(EXIT_ERR, "unknown signal name {}", signal_name_or_value) } fn print_signals() { let mut pos = 0; for (idx, signal) in ALL_SIGNALS.iter().enumerate() { pos += signal.name.len(); print!("{}", signal.name); if idx > 0 && pos > 73 { println!(""); pos = 0; } else { pos += 1; print!(" "); } } } fn list(arg: Option<String>) { match arg { Some(ref x) => print_signal(x), None => print_signals(), }; } fn help(opts: &getopts::Options) { let msg = format!("{0} {1} Usage: {0} [options] <pid> [...]", NAME, VERSION); println!("{}", opts.usage(&msg)); } fn kill(signalname: &str, pids: std::vec::Vec<String>) -> i32 { let mut status = 0; let optional_signal_value = uucore::signals::signal_by_name_or_value(signalname); let signal_value = match optional_signal_value { Some(x) => x, None => crash!(EXIT_ERR, "unknown signal name {}", signalname) }; for pid in &pids { match pid.parse::<usize>() { Ok(x) => { if unsafe { libc::kill(x as pid_t, signal_value as c_int) } != 0 { show_error!("{}", Error::last_os_error()); status = 1; } }, Err(e) => crash!(EXIT_ERR, "failed to parse argument {}: {}", pid, e) }; } status }<|fim▁end|>
Mode::Kill => return kill(&matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_owned())), matches.free), Mode::Table => table(), Mode::List => list(matches.opt_str("list")),
<|file_name|>getNameOfClass.py<|end_file_name|><|fim▁begin|># ========================================================================== # # Copyright NumFOCUS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ==========================================================================*/ # a short program to check the value returned by the GetNameOfClass() methods import itk import sys<|fim▁hole|># must force the load to return all the names with dir(itk) itk.force_load() # itk.ImageToImageFilter def wrongClassName(cl, name): o = cl.New() # be sure that the type of the instantiated object is the same # than the one of the class. It can be different if the class # is an "abstract" one and don't provide any New() method. # In that case, the one of the superclass is used. return o.GetNameOfClass() != name and itk.class_(o) == cl # a list of classes to exclude. Typically, the classes with a custom New() # method, which return a subclass of the current class exclude = [ "ForwardFFTImageFilter", "Forward1DFFTImageFilter", "InverseFFTImageFilter", "Inverse1DFFTImageFilter", "OutputWindow", "MultiThreaderBase", "FFTComplexToComplexImageFilter", "ComplexToComplexFFTImageFilter", "ComplexToComplex1DImageFilter", "templated_class", "HalfHermitianToRealInverseFFTImageFilter", "RealToHalfHermitianForwardFFTImageFilter", "CustomColormapFunction", "ScanlineFilterCommon", # Segfault "cvar", ] wrongName = 0 totalName = 0 for t in dir(itk): if t not in exclude: T = itk.__dict__[t] # first case - that's a templated class if isinstance(T, itk.Vector.__class__) and len(T) > 0: # use only the first specialization - all of them return the same # name i = T.values()[0] # GetNameOfClass() is a virtual method of the LightObject class, # so we must instantiate an object with the New() method if "New" in dir(i) and "GetNameOfClass" in dir(i): totalName += 1 if wrongClassName(i, t): msg = f"{T}: wrong class name: {t}" print(msg, file=sys.stderr) wrongName += 1 else: if "New" in dir(T) and "GetNameOfClass" in dir(T): totalName += 1 if wrongClassName(T, t): msg = f"{T}: wrong class name: {t}" print(msg, file=sys.stderr) o = T.New() print(itk.class_(o), file=sys.stderr) print(o.GetNameOfClass(), file=sys.stderr) wrongName += 1 print(f"{totalName} classes checked.") if wrongName: print(f"{wrongName} classes are not providing the correct name.", file=sys.stderr) sys.exit(1)<|fim▁end|>
itk.auto_progress(2)
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364) #![cfg_attr(stage0, feature(custom_attribute))] #![crate_name = "rustc_privacy"] #![unstable(feature = "rustc_private")] #![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://doc.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/nightly/")] #![feature(rustc_diagnostic_macros)] #![feature(rustc_private)] #![feature(staged_api)] #[macro_use] extern crate log; #[macro_use] extern crate syntax; extern crate rustc; use self::PrivacyResult::*; use self::FieldName::*; use std::mem::replace; use rustc::ast_map; use rustc::middle::def; use rustc::middle::privacy::ImportUse::*; use rustc::middle::privacy::LastPrivate::*; use rustc::middle::privacy::PrivateDep::*; use rustc::middle::privacy::{ExternalExports, ExportedItems, PublicItems}; use rustc::middle::ty::{self, Ty}; use rustc::util::nodemap::{NodeMap, NodeSet}; use syntax::ast; use syntax::ast_util::{is_local, local_def}; use syntax::codemap::Span; use syntax::visit::{self, Visitor}; type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap); /// Result of a checking operation - None => no errors were found. Some => an /// error and contains the span and message for reporting that error and /// optionally the same for a note about the error. type CheckResult = Option<(Span, String, Option<(Span, String)>)>; //////////////////////////////////////////////////////////////////////////////// /// The parent visitor, used to determine what's the parent of what (node-wise) //////////////////////////////////////////////////////////////////////////////// struct ParentVisitor { parents: NodeMap<ast::NodeId>, curparent: ast::NodeId, } impl<'v> Visitor<'v> for ParentVisitor { fn visit_item(&mut self, item: &ast::Item) { self.parents.insert(item.id, self.curparent); let prev = self.curparent; match item.node { ast::ItemMod(..) => { self.curparent = item.id; } // Enum variants are parented to the enum definition itself because // they inherit privacy ast::ItemEnum(ref def, _) => { for variant in &def.variants { // The parent is considered the enclosing enum because the // enum will dictate the privacy visibility of this variant // instead. self.parents.insert(variant.node.id, item.id); } } // Trait methods are always considered "public", but if the trait is // private then we need some private item in the chain from the // method to the root. In this case, if the trait is private, then // parent all the methods to the trait to indicate that they're // private. ast::ItemTrait(_, _, _, ref trait_items) if item.vis != ast::Public => { for trait_item in trait_items { self.parents.insert(trait_item.id, item.id); } } _ => {} } visit::walk_item(self, item); self.curparent = prev; } fn visit_foreign_item(&mut self, a: &ast::ForeignItem) { self.parents.insert(a.id, self.curparent); visit::walk_foreign_item(self, a); } fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl, c: &'v ast::Block, d: Span, id: ast::NodeId) { // We already took care of some trait methods above, otherwise things // like impl methods and pub trait methods are parented to the // containing module, not the containing trait. if !self.parents.contains_key(&id) { self.parents.insert(id, self.curparent); } visit::walk_fn(self, a, b, c, d); } fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) { // visit_fn handles methods, but associated consts have to be handled // here. if !self.parents.contains_key(&ii.id) { self.parents.insert(ii.id, self.curparent); } visit::walk_impl_item(self, ii); } fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident, _: &'v ast::Generics, n: ast::NodeId) { // Struct constructors are parented to their struct definitions because // they essentially are the struct definitions. match s.ctor_id { Some(id) => { self.parents.insert(id, n); } None => {} } // While we have the id of the struct definition, go ahead and parent // all the fields. for field in &s.fields { self.parents.insert(field.node.id, self.curparent); } visit::walk_struct_def(self, s) } } //////////////////////////////////////////////////////////////////////////////// /// The embargo visitor, used to determine the exports of the ast //////////////////////////////////////////////////////////////////////////////// struct EmbargoVisitor<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, export_map: &'a def::ExportMap, // This flag is an indicator of whether the previous item in the // hierarchical chain was exported or not. This is the indicator of whether // children should be exported as well. Note that this can flip from false // to true if a reexported module is entered (or an action similar). prev_exported: bool, // This is a list of all exported items in the AST. An exported item is any // function/method/item which is usable by external crates. This essentially // means that the result is "public all the way down", but the "path down" // may jump across private boundaries through reexport statements. exported_items: ExportedItems, // This sets contains all the destination nodes which are publicly // re-exported. This is *not* a set of all reexported nodes, only a set of // all nodes which are reexported *and* reachable from external crates. This // means that the destination of the reexport is exported, and hence the // destination must also be exported. reexports: NodeSet, // These two fields are closely related to one another in that they are only // used for generation of the 'PublicItems' set, not for privacy checking at // all public_items: PublicItems, prev_public: bool, } impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> { // There are checks inside of privacy which depend on knowing whether a // trait should be exported or not. The two current consumers of this are: // // 1. Should default methods of a trait be exported? // 2. Should the methods of an implementation of a trait be exported? // // The answer to both of these questions partly rely on whether the trait // itself is exported or not. If the trait is somehow exported, then the // answers to both questions must be yes. Right now this question involves // more analysis than is currently done in rustc, so we conservatively // answer "yes" so that all traits need to be exported. fn exported_trait(&self, _id: ast::NodeId) -> bool { true } } impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &ast::Item) { let orig_all_pub = self.prev_public; self.prev_public = orig_all_pub && item.vis == ast::Public; if self.prev_public { self.public_items.insert(item.id); } let orig_all_exported = self.prev_exported; match item.node { // impls/extern blocks do not break the "public chain" because they // cannot have visibility qualifiers on them anyway ast::ItemImpl(..) | ast::ItemDefaultImpl(..) | ast::ItemForeignMod(..) => {} // Traits are a little special in that even if they themselves are // not public they may still be exported. ast::ItemTrait(..) => { self.prev_exported = self.exported_trait(item.id); } // Private by default, hence we only retain the "public chain" if // `pub` is explicitly listed. _ => { self.prev_exported = (orig_all_exported && item.vis == ast::Public) || self.reexports.contains(&item.id); } } let public_first = self.prev_exported && self.exported_items.insert(item.id); match item.node { // Enum variants inherit from their parent, so if the enum is // public all variants are public unless they're explicitly priv ast::ItemEnum(ref def, _) if public_first => { for variant in &def.variants { self.exported_items.insert(variant.node.id); self.public_items.insert(variant.node.id); } } // Implementations are a little tricky to determine what's exported // out of them. Here's a few cases which are currently defined: // // * Impls for private types do not need to export their methods // (either public or private methods) // // * Impls for public types only have public methods exported // // * Public trait impls for public types must have all methods // exported. // // * Private trait impls for public types can be ignored // // * Public trait impls for private types have their methods // exported. I'm not entirely certain that this is the correct // thing to do, but I have seen use cases of where this will cause // undefined symbols at linkage time if this case is not handled. // // * Private trait impls for private types can be completely ignored ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => { let public_ty = match ty.node { ast::TyPath(..) => { match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() { def::DefPrimTy(..) => true, def => { let did = def.def_id(); !is_local(did) || self.exported_items.contains(&did.node) } } } _ => true, }; let tr = self.tcx.impl_trait_ref(local_def(item.id)); let public_trait = tr.clone().map_or(false, |tr| { !is_local(tr.def_id) || self.exported_items.contains(&tr.def_id.node) }); if public_ty || public_trait { for impl_item in impl_items { match impl_item.node { ast::ConstImplItem(..) => { if (public_ty && impl_item.vis == ast::Public) || tr.is_some() { self.exported_items.insert(impl_item.id); } } ast::MethodImplItem(ref sig, _) => { let meth_public = match sig.explicit_self.node { ast::SelfStatic => public_ty, _ => true, } && impl_item.vis == ast::Public; if meth_public || tr.is_some() { self.exported_items.insert(impl_item.id); } } ast::TypeImplItem(_) | ast::MacImplItem(_) => {} } } } } // Default methods on traits are all public so long as the trait // is public ast::ItemTrait(_, _, _, ref trait_items) if public_first => { for trait_item in trait_items { debug!("trait item {}", trait_item.id); self.exported_items.insert(trait_item.id); } } // Struct constructors are public if the struct is all public. ast::ItemStruct(ref def, _) if public_first => { match def.ctor_id { Some(id) => { self.exported_items.insert(id); } None => {} } // fields can be public or private, so lets check for field in &def.fields { let vis = match field.node.kind { ast::NamedField(_, vis) | ast::UnnamedField(vis) => vis }; if vis == ast::Public { self.public_items.insert(field.node.id); } } } ast::ItemTy(ref ty, _) if public_first => { if let ast::TyPath(..) = ty.node { match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() { def::DefPrimTy(..) | def::DefTyParam(..) => {}, def => { let did = def.def_id(); if is_local(did) { self.exported_items.insert(did.node); } } } } } _ => {} } visit::walk_item(self, item); self.prev_exported = orig_all_exported; self.prev_public = orig_all_pub; } fn visit_foreign_item(&mut self, a: &ast::ForeignItem) { if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) { self.exported_items.insert(a.id); } } fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) { // This code is here instead of in visit_item so that the // crate module gets processed as well. if self.prev_exported { assert!(self.export_map.contains_key(&id), "wut {}", id); for export in self.export_map.get(&id).unwrap() { if is_local(export.def_id) { self.reexports.insert(export.def_id.node); } } } visit::walk_mod(self, m) } } //////////////////////////////////////////////////////////////////////////////// /// The privacy visitor, where privacy checks take place (violations reported) //////////////////////////////////////////////////////////////////////////////// struct PrivacyVisitor<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, curitem: ast::NodeId, in_foreign: bool, parents: NodeMap<ast::NodeId>, external_exports: ExternalExports, } enum PrivacyResult { Allowable, ExternallyDenied, DisallowedBy(ast::NodeId), } enum FieldName { UnnamedField(usize), // index // (Name, not Ident, because struct fields are not macro-hygienic) NamedField(ast::Name), } impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { // used when debugging fn nodestr(&self, id: ast::NodeId) -> String { self.tcx.map.node_to_string(id).to_string() } // Determines whether the given definition is public from the point of view // of the current item. fn def_privacy(&self, did: ast::DefId) -> PrivacyResult { if !is_local(did) { if self.external_exports.contains(&did) { debug!("privacy - {:?} was externally exported", did); return Allowable; } debug!("privacy - is {:?} a public method", did); return match self.tcx.impl_or_trait_items.borrow().get(&did) { Some(&ty::ConstTraitItem(ref ac)) => { debug!("privacy - it's a const: {:?}", *ac); match ac.container { ty::TraitContainer(id) => { debug!("privacy - recursing on trait {:?}", id); self.def_privacy(id) } ty::ImplContainer(id) => { match self.tcx.impl_trait_ref(id) { Some(t) => { debug!("privacy - impl of trait {:?}", id); self.def_privacy(t.def_id) } None => { debug!("privacy - found inherent \ associated constant {:?}", ac.vis); if ac.vis == ast::Public { Allowable } else { ExternallyDenied } } } } } } Some(&ty::MethodTraitItem(ref meth)) => { debug!("privacy - well at least it's a method: {:?}", *meth); match meth.container { ty::TraitContainer(id) => { debug!("privacy - recursing on trait {:?}", id); self.def_privacy(id) } ty::ImplContainer(id) => { match self.tcx.impl_trait_ref(id) { Some(t) => { debug!("privacy - impl of trait {:?}", id); self.def_privacy(t.def_id) } None => { debug!("privacy - found a method {:?}", meth.vis); if meth.vis == ast::Public { Allowable } else { ExternallyDenied } } } } } } Some(&ty::TypeTraitItem(ref typedef)) => { match typedef.container { ty::TraitContainer(id) => { debug!("privacy - recursing on trait {:?}", id); self.def_privacy(id) } ty::ImplContainer(id) => { match self.tcx.impl_trait_ref(id) { Some(t) => { debug!("privacy - impl of trait {:?}", id); self.def_privacy(t.def_id) } None => { debug!("privacy - found a typedef {:?}", typedef.vis); if typedef.vis == ast::Public { Allowable } else { ExternallyDenied } } } } } } None => { debug!("privacy - nope, not even a method"); ExternallyDenied } }; } debug!("privacy - local {} not public all the way down", self.tcx.map.node_to_string(did.node)); // return quickly for things in the same module if self.parents.get(&did.node) == self.parents.get(&self.curitem) { debug!("privacy - same parent, we're done here"); return Allowable; } // We now know that there is at least one private member between the // destination and the root. let mut closest_private_id = did.node; loop { debug!("privacy - examining {}", self.nodestr(closest_private_id)); let vis = match self.tcx.map.find(closest_private_id) { // If this item is a method, then we know for sure that it's an // actual method and not a static method. The reason for this is // that these cases are only hit in the ExprMethodCall // expression, and ExprCall will have its path checked later // (the path of the trait/impl) if it's a static method. // // With this information, then we can completely ignore all // trait methods. The privacy violation would be if the trait // couldn't get imported, not if the method couldn't be used // (all trait methods are public). // // However, if this is an impl method, then we dictate this // decision solely based on the privacy of the method // invocation. // FIXME(#10573) is this the right behavior? Why not consider // where the method was defined? Some(ast_map::NodeImplItem(ii)) => { match ii.node { ast::ConstImplItem(..) | ast::MethodImplItem(..) => { let imp = self.tcx.map .get_parent_did(closest_private_id); match self.tcx.impl_trait_ref(imp) { Some(..) => return Allowable, _ if ii.vis == ast::Public => { return Allowable } _ => ii.vis } } ast::TypeImplItem(_) | ast::MacImplItem(_) => return Allowable, } } Some(ast_map::NodeTraitItem(_)) => { return Allowable; } // This is not a method call, extract the visibility as one // would normally look at it Some(ast_map::NodeItem(it)) => it.vis, Some(ast_map::NodeForeignItem(_)) => { self.tcx.map.get_foreign_vis(closest_private_id) } Some(ast_map::NodeVariant(..)) => { ast::Public // need to move up a level (to the enum) } _ => ast::Public, }; if vis != ast::Public { break } // if we've reached the root, then everything was allowable and this // access is public. if closest_private_id == ast::CRATE_NODE_ID { return Allowable } closest_private_id = *self.parents.get(&closest_private_id).unwrap(); // If we reached the top, then we were public all the way down and // we can allow this access. if closest_private_id == ast::DUMMY_NODE_ID { return Allowable } } debug!("privacy - closest priv {}", self.nodestr(closest_private_id)); if self.private_accessible(closest_private_id) { Allowable } else { DisallowedBy(closest_private_id) } } /// For a local private node in the AST, this function will determine /// whether the node is accessible by the current module that iteration is /// inside. fn private_accessible(&self, id: ast::NodeId) -> bool { let parent = *self.parents.get(&id).unwrap(); debug!("privacy - accessible parent {}", self.nodestr(parent)); // After finding `did`'s closest private member, we roll ourselves back // to see if this private member's parent is anywhere in our ancestry. // By the privacy rules, we can access all of our ancestor's private // members, so that's why we test the parent, and not the did itself. let mut cur = self.curitem; loop { debug!("privacy - questioning {}, {}", self.nodestr(cur), cur); match cur { // If the relevant parent is in our history, then we're allowed // to look inside any of our ancestor's immediate private items, // so this access is valid. x if x == parent => return true, // If we've reached the root, then we couldn't access this item // in the first place ast::DUMMY_NODE_ID => return false, // Keep going up _ => {} } cur = *self.parents.get(&cur).unwrap(); } } fn report_error(&self, result: CheckResult) -> bool { match result { None => true, Some((span, msg, note)) => { self.tcx.sess.span_err(span, &msg[..]); match note { Some((span, msg)) => { self.tcx.sess.span_note(span, &msg[..]) } None => {}, } false }, } } /// Guarantee that a particular definition is public. Returns a CheckResult /// which contains any errors found. These can be reported using `report_error`. /// If the result is `None`, no errors were found. fn ensure_public(&self, span: Span, to_check: ast::DefId, source_did: Option<ast::DefId>, msg: &str) -> CheckResult { let id = match self.def_privacy(to_check) { ExternallyDenied => { return Some((span, format!("{} is private", msg), None)) } Allowable => return None, DisallowedBy(id) => id, }; // If we're disallowed by a particular id, then we attempt to give a // nice error message to say why it was disallowed. It was either // because the item itself is private or because its parent is private // and its parent isn't in our ancestry. let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node { return Some((span, format!("{} is private", msg), None)); } else { (span, format!("{} is inaccessible", msg)) }; let item = match self.tcx.map.find(id) { Some(ast_map::NodeItem(item)) => { match item.node { // If an impl disallowed this item, then this is resolve's // way of saying that a struct/enum's static method was // invoked, and the struct/enum itself is private. Crawl // back up the chains to find the relevant struct/enum that // was private. ast::ItemImpl(_, _, _, _, ref ty, _) => { match ty.node { ast::TyPath(..) => {} _ => return Some((err_span, err_msg, None)), }; let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def(); let did = def.def_id(); assert!(is_local(did)); match self.tcx.map.get(did.node) { ast_map::NodeItem(item) => item, _ => self.tcx.sess.span_bug(item.span, "path is not an item") } } _ => item } } Some(..) | None => return Some((err_span, err_msg, None)), }; let desc = match item.node { ast::ItemMod(..) => "module", ast::ItemTrait(..) => "trait", ast::ItemStruct(..) => "struct", ast::ItemEnum(..) => "enum", _ => return Some((err_span, err_msg, None)) }; let msg = format!("{} `{}` is private", desc, item.ident); Some((err_span, err_msg, Some((span, msg)))) } // Checks that a field is in scope. fn check_field(&mut self, span: Span, def: ty::AdtDef<'tcx>, v: ty::VariantDef<'tcx>, name: FieldName) { let field = match name { NamedField(f_name) => { debug!("privacy - check named field {} in struct {:?}", f_name, def); v.field_named(f_name) } UnnamedField(idx) => &v.fields[idx] }; if field.vis == ast::Public || (is_local(field.did) && self.private_accessible(field.did.node)) { return } let struct_desc = match def.adt_kind() { ty::AdtKind::Struct => format!("struct `{}`", self.tcx.item_path_str(def.did)), // struct variant fields have inherited visibility ty::AdtKind::Enum => return }; let msg = match name { NamedField(name) => format!("field `{}` of {} is private", name, struct_desc), UnnamedField(idx) => format!("field #{} of {} is private", idx + 1, struct_desc), }; self.tcx.sess.span_err(span, &msg[..]); } // Given the ID of a method, checks to ensure it's in scope. fn check_static_method(&mut self, span: Span, method_id: ast::DefId, name: ast::Name) { // If the method is a default method, we need to use the def_id of // the default implementation. let method_id = match self.tcx.impl_or_trait_item(method_id) { ty::MethodTraitItem(method_type) => { method_type.provided_source.unwrap_or(method_id) } _ => { self.tcx.sess .span_bug(span, "got non-method item in check_static_method") } }; self.report_error(self.ensure_public(span, method_id, None, &format!("method `{}`", name))); } // Checks that a path is in scope. fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Name) { debug!("privacy - path {}", self.nodestr(path_id)); let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap(); let ck = |tyname: &str| { let ck_public = |def: ast::DefId| { debug!("privacy - ck_public {:?}", def); let origdid = path_res.def_id(); self.ensure_public(span, def, Some(origdid), &format!("{} `{}`", tyname, last)) }; match path_res.last_private { LastMod(AllPublic) => {}, LastMod(DependsOn(def)) => { self.report_error(ck_public(def)); }, LastImport { value_priv, value_used: check_value, type_priv, type_used: check_type } => { // This dance with found_error is because we don't want to // report a privacy error twice for the same directive. let found_error = match (type_priv, check_type) { (Some(DependsOn(def)), Used) => { !self.report_error(ck_public(def)) }, _ => false, }; if !found_error { match (value_priv, check_value) { (Some(DependsOn(def)), Used) => { self.report_error(ck_public(def)); }, _ => {}, } } // If an import is not used in either namespace, we still // want to check that it could be legal. Therefore we check // in both namespaces and only report an error if both would // be illegal. We only report one error, even if it is // illegal to import from both namespaces. match (value_priv, check_value, type_priv, check_type) { (Some(p), Unused, None, _) | (None, _, Some(p), Unused) => { let p = match p { AllPublic => None, DependsOn(def) => ck_public(def), }; if p.is_some() { self.report_error(p); } }, (Some(v), Unused, Some(t), Unused) => { let v = match v { AllPublic => None, DependsOn(def) => ck_public(def), }; let t = match t { AllPublic => None, DependsOn(def) => ck_public(def), }; if let (Some(_), Some(t)) = (v, t) { self.report_error(Some(t)); } }, _ => {}, } }, } }; // FIXME(#12334) Imports can refer to definitions in both the type and // value namespaces. The privacy information is aware of this, but the // def map is not. Therefore the names we work out below will not always // be accurate and we can get slightly wonky error messages (but type // checking is always correct). match path_res.full_def() { def::DefFn(..) => ck("function"), def::DefStatic(..) => ck("static"), def::DefConst(..) => ck("const"), def::DefAssociatedConst(..) => ck("associated const"), def::DefVariant(..) => ck("variant"), def::DefTy(_, false) => ck("type"), def::DefTy(_, true) => ck("enum"), def::DefTrait(..) => ck("trait"), def::DefStruct(..) => ck("struct"), def::DefMethod(..) => ck("method"), def::DefMod(..) => ck("module"), _ => {} } } // Checks that a method is in scope. fn check_method(&mut self, span: Span, method_def_id: ast::DefId, name: ast::Name) { match self.tcx.impl_or_trait_item(method_def_id).container() { ty::ImplContainer(_) => { self.check_static_method(span, method_def_id, name) } // Trait methods are always all public. The only controlling factor // is whether the trait itself is accessible or not. ty::TraitContainer(trait_def_id) => { self.report_error(self.ensure_public(span, trait_def_id, None, "source trait")); } } } } impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &ast::Item) { if let ast::ItemUse(ref vpath) = item.node { if let ast::ViewPathList(ref prefix, ref list) = vpath.node { for pid in list { match pid.node { ast::PathListIdent { id, name, .. } => { debug!("privacy - ident item {}", id); self.check_path(pid.span, id, name.name); } ast::PathListMod { id, .. } => { debug!("privacy - mod item {}", id); let name = prefix.segments.last().unwrap().identifier.name; self.check_path(pid.span, id, name); } } } } } let orig_curitem = replace(&mut self.curitem, item.id); visit::walk_item(self, item); self.curitem = orig_curitem; } fn visit_expr(&mut self, expr: &ast::Expr) { match expr.node { ast::ExprField(ref base, ident) => { if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty { self.check_field(expr.span, def, def.struct_variant(), NamedField(ident.node.name)); } } ast::ExprTupField(ref base, idx) => { if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty { self.check_field(expr.span, def, def.struct_variant(), UnnamedField(idx.node)); } } ast::ExprMethodCall(ident, _, _) => { let method_call = ty::MethodCall::expr(expr.id); let method = self.tcx.tables.borrow().method_map[&method_call]; debug!("(privacy checking) checking impl method"); self.check_method(expr.span, method.def_id, ident.node.name); } ast::ExprStruct(..) => { let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap(); let variant = adt.variant_of_def(self.tcx.resolve_expr(expr)); // RFC 736: ensure all unmentioned fields are visible. // Rather than computing the set of unmentioned fields // (i.e. `all_fields - fields`), just check them all. for field in &variant.fields { self.check_field(expr.span, adt, variant, NamedField(field.name)); } } ast::ExprPath(..) => { if let def::DefStruct(_) = self.tcx.resolve_expr(expr) { let expr_ty = self.tcx.expr_ty(expr); let def = match expr_ty.sty { ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig { output: ty::FnConverging(ty), .. }), ..}) => ty, _ => expr_ty }.ty_adt_def().unwrap(); let any_priv = def.struct_variant().fields.iter().any(|f| { f.vis != ast::Public && ( !is_local(f.did) || !self.private_accessible(f.did.node)) }); if any_priv { self.tcx.sess.span_err(expr.span, "cannot invoke tuple struct constructor \ with private fields"); } } } _ => {} } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pattern: &ast::Pat) { // Foreign functions do not have their patterns mapped in the def_map, // and there's nothing really relevant there anyway, so don't bother // checking privacy. If you can name the type then you can pass it to an // external C function anyway. if self.in_foreign { return } match pattern.node { ast::PatStruct(_, ref fields, _) => { let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap(); let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def(); let variant = adt.variant_of_def(def); for field in fields { self.check_field(pattern.span, adt, variant, NamedField(field.node.ident.name)); } } // Patterns which bind no fields are allowable (the path is check // elsewhere). ast::PatEnum(_, Some(ref fields)) => { match self.tcx.pat_ty(pattern).sty { ty::TyStruct(def, _) => { for (i, field) in fields.iter().enumerate() { if let ast::PatWild(..) = field.node { continue } self.check_field(field.span, def, def.struct_variant(), UnnamedField(i)); } } ty::TyEnum(..) => { // enum fields have no privacy at this time } _ => {} } } _ => {} } visit::walk_pat(self, pattern); } fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) { self.in_foreign = true; visit::walk_foreign_item(self, fi); self.in_foreign = false; } fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) { self.check_path(path.span, id, path.segments.last().unwrap().identifier.name); visit::walk_path(self, path); } } //////////////////////////////////////////////////////////////////////////////// /// The privacy sanity check visitor, ensures unnecessary visibility isn't here //////////////////////////////////////////////////////////////////////////////// struct SanePrivacyVisitor<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, in_fn: bool, } impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &ast::Item) { if self.in_fn { self.check_all_inherited(item); } else { self.check_sane_privacy(item); } let in_fn = self.in_fn; let orig_in_fn = replace(&mut self.in_fn, match item.node { ast::ItemMod(..) => false, // modules turn privacy back on _ => in_fn, // otherwise we inherit }); visit::walk_item(self, item); self.in_fn = orig_in_fn; } fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl, b: &'v ast::Block, s: Span, _: ast::NodeId) { // This catches both functions and methods let orig_in_fn = replace(&mut self.in_fn, true); visit::walk_fn(self, fk, fd, b, s); self.in_fn = orig_in_fn; } } impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { /// Validates all of the visibility qualifiers placed on the item given. This /// ensures that there are no extraneous qualifiers that don't actually do /// anything. In theory these qualifiers wouldn't parse, but that may happen /// later on down the road... fn check_sane_privacy(&self, item: &ast::Item) { let tcx = self.tcx; let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| { if vis != ast::Inherited { tcx.sess.span_err(sp, "unnecessary visibility qualifier"); if !note.is_empty() { tcx.sess.span_note(sp, note); } } }; match item.node { // implementations of traits don't need visibility qualifiers because // that's controlled by having the trait in scope. ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => { check_inherited(item.span, item.vis, "visibility qualifiers have no effect on trait \ impls"); for impl_item in impl_items { check_inherited(impl_item.span, impl_item.vis, ""); } } ast::ItemImpl(..) => { check_inherited(item.span, item.vis, "place qualifiers on individual methods instead"); } ast::ItemForeignMod(..) => { check_inherited(item.span, item.vis, "place qualifiers on individual functions \ instead"); } ast::ItemEnum(ref def, _) => { for v in &def.variants { match v.node.vis { ast::Public => { if item.vis == ast::Public { tcx.sess.span_err(v.span, "unnecessary `pub` \ visibility"); } } ast::Inherited => {} } } } ast::ItemTrait(..) | ast::ItemDefaultImpl(..) | ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) | ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) | ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemMac(..) => {} } } /// When inside of something like a function or a method, visibility has no /// control over anything so this forbids any mention of any visibility fn check_all_inherited(&self, item: &ast::Item) { let tcx = self.tcx; fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) { if vis != ast::Inherited { tcx.sess.span_err(sp, "visibility has no effect inside functions"); } } let check_struct = |def: &ast::StructDef| { for f in &def.fields { match f.node.kind { ast::NamedField(_, p) => check_inherited(tcx, f.span, p), ast::UnnamedField(..) => {} } } }; check_inherited(tcx, item.span, item.vis); match item.node { ast::ItemImpl(_, _, _, _, _, ref impl_items) => { for impl_item in impl_items { match impl_item.node { ast::MethodImplItem(..) => { check_inherited(tcx, impl_item.span, impl_item.vis); } _ => {} } } } ast::ItemForeignMod(ref fm) => { for i in &fm.items { check_inherited(tcx, i.span, i.vis); } } ast::ItemEnum(ref def, _) => { for v in &def.variants { check_inherited(tcx, v.span, v.node.vis); } } ast::ItemStruct(ref def, _) => check_struct(&**def), ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemTrait(..) | ast::ItemDefaultImpl(..) | ast::ItemStatic(..) | ast::ItemConst(..) | ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) | ast::ItemMac(..) => {} } } } struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, exported_items: &'a ExportedItems, public_items: &'a PublicItems, in_variant: bool, } struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> { inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>, /// whether the type refers to private types. contains_private: bool, /// whether we've recurred at all (i.e. if we're pointing at the /// first type on which visit_ty was called). at_outer_type: bool, // whether that first type is a public path. outer_type_is_public_path: bool, } impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> { fn path_is_private_type(&self, path_id: ast::NodeId) -> bool { let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) { // `int` etc. (None doesn't seem to occur.) None | Some(def::DefPrimTy(..)) => return false, Some(def) => def.def_id(), }; // A path can only be private if: // it's in this crate... if !is_local(did) { return false } // .. and it corresponds to a private type in the AST (this returns // None for type parameters) match self.tcx.map.find(did.node) { Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public, Some(_) | None => false, } } fn trait_is_public(&self, trait_id: ast::NodeId) -> bool { // FIXME: this would preferably be using `exported_items`, but all // traits are exported currently (see `EmbargoVisitor.exported_trait`) self.public_items.contains(&trait_id) } fn check_ty_param_bound(&self, ty_param_bound: &ast::TyParamBound) { if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound { if !self.tcx.sess.features.borrow().visible_private_types && self.path_is_private_type(trait_ref.trait_ref.ref_id) { let span = trait_ref.trait_ref.path.span; self.tcx.sess.span_err(span, "private trait in exported type \ parameter bound"); } } } fn item_is_public(&self, id: &ast::NodeId, vis: ast::Visibility) -> bool { self.exported_items.contains(id) || vis == ast::Public } } impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> { fn visit_ty(&mut self, ty: &ast::Ty) { if let ast::TyPath(..) = ty.node { if self.inner.path_is_private_type(ty.id) { self.contains_private = true; // found what we're looking for so let's stop // working. return } else if self.at_outer_type { self.outer_type_is_public_path = true; } } self.at_outer_type = false; visit::walk_ty(self, ty) } // don't want to recurse into [, .. expr] fn visit_expr(&mut self, _: &ast::Expr) {} } impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &ast::Item) { match item.node { // contents of a private mod can be reexported, so we need // to check internals. ast::ItemMod(_) => {} // An `extern {}` doesn't introduce a new privacy // namespace (the contents have their own privacies). ast::ItemForeignMod(_) => {} ast::ItemTrait(_, _, ref bounds, _) => { if !self.trait_is_public(item.id) { return } for bound in bounds.iter() { self.check_ty_param_bound(bound) } } // impls need some special handling to try to offer useful // error messages without (too many) false positives // (i.e. we could just return here to not check them at // all, or some worse estimation of whether an impl is // publicly visible). ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => { // `impl [... for] Private` is never visible. let self_contains_private; // impl [... for] Public<...>, but not `impl [... for] // Vec<Public>` or `(Public,)` etc. let self_is_public_path;<|fim▁hole|> let mut visitor = CheckTypeForPrivatenessVisitor { inner: self, contains_private: false, at_outer_type: true, outer_type_is_public_path: false, }; visitor.visit_ty(&**self_); self_contains_private = visitor.contains_private; self_is_public_path = visitor.outer_type_is_public_path; } // miscellaneous info about the impl // `true` iff this is `impl Private for ...`. let not_private_trait = trait_ref.as_ref().map_or(true, // no trait counts as public trait |tr| { let did = self.tcx.trait_ref_to_def_id(tr); !is_local(did) || self.trait_is_public(did.node) }); // `true` iff this is a trait impl or at least one method is public. // // `impl Public { $( fn ...() {} )* }` is not visible. // // This is required over just using the methods' privacy // directly because we might have `impl<T: Foo<Private>> ...`, // and we shouldn't warn about the generics if all the methods // are private (because `T` won't be visible externally). let trait_or_some_public_method = trait_ref.is_some() || impl_items.iter() .any(|impl_item| { match impl_item.node { ast::ConstImplItem(..) | ast::MethodImplItem(..) => { self.exported_items.contains(&impl_item.id) } ast::TypeImplItem(_) | ast::MacImplItem(_) => false, } }); if !self_contains_private && not_private_trait && trait_or_some_public_method { visit::walk_generics(self, g); match *trait_ref { None => { for impl_item in impl_items { // This is where we choose whether to walk down // further into the impl to check its items. We // should only walk into public items so that we // don't erroneously report errors for private // types in private items. match impl_item.node { ast::ConstImplItem(..) | ast::MethodImplItem(..) if self.item_is_public(&impl_item.id, impl_item.vis) => { visit::walk_impl_item(self, impl_item) } ast::TypeImplItem(..) => { visit::walk_impl_item(self, impl_item) } _ => {} } } } Some(ref tr) => { // Any private types in a trait impl fall into three // categories. // 1. mentioned in the trait definition // 2. mentioned in the type params/generics // 3. mentioned in the associated types of the impl // // Those in 1. can only occur if the trait is in // this crate and will've been warned about on the // trait definition (there's no need to warn twice // so we don't check the methods). // // Those in 2. are warned via walk_generics and this // call here. visit::walk_path(self, &tr.path); // Those in 3. are warned with this call. for impl_item in impl_items { if let ast::TypeImplItem(ref ty) = impl_item.node { self.visit_ty(ty); } } } } } else if trait_ref.is_none() && self_is_public_path { // impl Public<Private> { ... }. Any public static // methods will be visible as `Public::foo`. let mut found_pub_static = false; for impl_item in impl_items { match impl_item.node { ast::ConstImplItem(..) => { if self.item_is_public(&impl_item.id, impl_item.vis) { found_pub_static = true; visit::walk_impl_item(self, impl_item); } } ast::MethodImplItem(ref sig, _) => { if sig.explicit_self.node == ast::SelfStatic && self.item_is_public(&impl_item.id, impl_item.vis) { found_pub_static = true; visit::walk_impl_item(self, impl_item); } } _ => {} } } if found_pub_static { visit::walk_generics(self, g) } } return } // `type ... = ...;` can contain private types, because // we're introducing a new name. ast::ItemTy(..) => return, // not at all public, so we don't care _ if !self.item_is_public(&item.id, item.vis) => { return; } _ => {} } // We've carefully constructed it so that if we're here, then // any `visit_ty`'s will be called on things that are in // public signatures, i.e. things that we're interested in for // this visitor. debug!("VisiblePrivateTypesVisitor entering item {:?}", item); visit::walk_item(self, item); } fn visit_generics(&mut self, generics: &ast::Generics) { for ty_param in generics.ty_params.iter() { for bound in ty_param.bounds.iter() { self.check_ty_param_bound(bound) } } for predicate in &generics.where_clause.predicates { match predicate { &ast::WherePredicate::BoundPredicate(ref bound_pred) => { for bound in bound_pred.bounds.iter() { self.check_ty_param_bound(bound) } } &ast::WherePredicate::RegionPredicate(_) => {} &ast::WherePredicate::EqPredicate(ref eq_pred) => { self.visit_ty(&*eq_pred.ty); } } } } fn visit_foreign_item(&mut self, item: &ast::ForeignItem) { if self.exported_items.contains(&item.id) { visit::walk_foreign_item(self, item) } } fn visit_ty(&mut self, t: &ast::Ty) { debug!("VisiblePrivateTypesVisitor checking ty {:?}", t); if let ast::TyPath(_, ref p) = t.node { if !self.tcx.sess.features.borrow().visible_private_types && self.path_is_private_type(t.id) { self.tcx.sess.span_err(p.span, "private type in exported type signature"); } } visit::walk_ty(self, t) } fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) { if self.exported_items.contains(&v.node.id) { self.in_variant = true; visit::walk_variant(self, v, g); self.in_variant = false; } } fn visit_struct_field(&mut self, s: &ast::StructField) { match s.node.kind { ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => { visit::walk_struct_field(self, s); } _ => {} } } // we don't need to introspect into these at all: an // expression/block context can't possibly contain exported things. // (Making them no-ops stops us from traversing the whole AST without // having to be super careful about our `walk_...` calls above.) fn visit_block(&mut self, _: &ast::Block) {} fn visit_expr(&mut self, _: &ast::Expr) {} } pub fn check_crate(tcx: &ty::ctxt, export_map: &def::ExportMap, external_exports: ExternalExports) -> (ExportedItems, PublicItems) { let krate = tcx.map.krate(); // Figure out who everyone's parent is let mut visitor = ParentVisitor { parents: NodeMap(), curparent: ast::DUMMY_NODE_ID, }; visit::walk_crate(&mut visitor, krate); // Use the parent map to check the privacy of everything let mut visitor = PrivacyVisitor { curitem: ast::DUMMY_NODE_ID, in_foreign: false, tcx: tcx, parents: visitor.parents, external_exports: external_exports, }; visit::walk_crate(&mut visitor, krate); // Sanity check to make sure that all privacy usage and controls are // reasonable. let mut visitor = SanePrivacyVisitor { in_fn: false, tcx: tcx, }; visit::walk_crate(&mut visitor, krate); tcx.sess.abort_if_errors(); // Build up a set of all exported items in the AST. This is a set of all // items which are reachable from external crates based on visibility. let mut visitor = EmbargoVisitor { tcx: tcx, exported_items: NodeSet(), public_items: NodeSet(), reexports: NodeSet(), export_map: export_map, prev_exported: true, prev_public: true, }; loop { let before = visitor.exported_items.len(); visit::walk_crate(&mut visitor, krate); if before == visitor.exported_items.len() { break } } let EmbargoVisitor { exported_items, public_items, .. } = visitor; { let mut visitor = VisiblePrivateTypesVisitor { tcx: tcx, exported_items: &exported_items, public_items: &public_items, in_variant: false, }; visit::walk_crate(&mut visitor, krate); } return (exported_items, public_items); }<|fim▁end|>
// check the properties of the Self type: {
<|file_name|>progress.rs<|end_file_name|><|fim▁begin|>use std::io::{Read, Result}; use std::time::{Duration, Instant}; pub struct Progress<R> { bytes: usize, tick: Instant, stream: R, } impl<R> Progress<R> { pub fn new(stream: R) -> Self { Progress {<|fim▁hole|> bytes: 0, tick: Instant::now() + Duration::from_millis(2000), stream, } } } impl<R: Read> Read for Progress<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let num = self.stream.read(buf)?; self.bytes += num; let now = Instant::now(); if now > self.tick { self.tick = now + Duration::from_millis(500); errorf!("downloading... {} bytes\n", self.bytes); } Ok(num) } } impl<R> Drop for Progress<R> { fn drop(&mut self) { errorf!("done ({} bytes)\n", self.bytes); } }<|fim▁end|>
<|file_name|>mul_add.rs<|end_file_name|><|fim▁begin|>#![feature(core, core_float)] extern crate core; #[cfg(test)] mod tests { use core::num::Float; // impl Float for f32 { // #[inline] // fn nan() -> f32 { NAN } // // #[inline] // fn infinity() -> f32 { INFINITY } // // #[inline] // fn neg_infinity() -> f32 { NEG_INFINITY } // // #[inline] // fn zero() -> f32 { 0.0 } // // #[inline] // fn neg_zero() -> f32 { -0.0 } // // #[inline] // fn one() -> f32 { 1.0 } // // from_str_radix_float_impl! { f32 } // // /// Returns `true` if the number is NaN. // #[inline] // fn is_nan(self) -> bool { self != self } // // /// Returns `true` if the number is infinite. // #[inline] // fn is_infinite(self) -> bool { // self == Float::infinity() || self == Float::neg_infinity() // } // // /// Returns `true` if the number is neither infinite or NaN. // #[inline] // fn is_finite(self) -> bool { // !(self.is_nan() || self.is_infinite()) // } // // /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. // #[inline] // fn is_normal(self) -> bool { // self.classify() == Fp::Normal // } // // /// Returns the floating point category of the number. If only one property // /// is going to be tested, it is generally faster to use the specific // /// predicate instead. // fn classify(self) -> Fp { // const EXP_MASK: u32 = 0x7f800000; // const MAN_MASK: u32 = 0x007fffff; // // let bits: u32 = unsafe { mem::transmute(self) }; // match (bits & MAN_MASK, bits & EXP_MASK) { // (0, 0) => Fp::Zero, // (_, 0) => Fp::Subnormal, // (0, EXP_MASK) => Fp::Infinite, // (_, EXP_MASK) => Fp::Nan, // _ => Fp::Normal, // } // } // // /// Returns the mantissa, exponent and sign as integers. // fn integer_decode(self) -> (u64, i16, i8) { // let bits: u32 = unsafe { mem::transmute(self) }; // let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 }; // let mut exponent: i16 = ((bits >> 23) & 0xff) as i16; // let mantissa = if exponent == 0 { // (bits & 0x7fffff) << 1 // } else { // (bits & 0x7fffff) | 0x800000 // }; // // Exponent bias + mantissa shift // exponent -= 127 + 23; // (mantissa as u64, exponent, sign) // } // // /// Rounds towards minus infinity. // #[inline] // fn floor(self) -> f32 {<|fim▁hole|> // /// Rounds towards plus infinity. // #[inline] // fn ceil(self) -> f32 { // unsafe { intrinsics::ceilf32(self) } // } // // /// Rounds to nearest integer. Rounds half-way cases away from zero. // #[inline] // fn round(self) -> f32 { // unsafe { intrinsics::roundf32(self) } // } // // /// Returns the integer part of the number (rounds towards zero). // #[inline] // fn trunc(self) -> f32 { // unsafe { intrinsics::truncf32(self) } // } // // /// The fractional part of the number, satisfying: // /// // /// ``` // /// let x = 1.65f32; // /// assert!(x == x.trunc() + x.fract()) // /// ``` // #[inline] // fn fract(self) -> f32 { self - self.trunc() } // // /// Computes the absolute value of `self`. Returns `Float::nan()` if the // /// number is `Float::nan()`. // #[inline] // fn abs(self) -> f32 { // unsafe { intrinsics::fabsf32(self) } // } // // /// Returns a number that represents the sign of `self`. // /// // /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` // /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` // /// - `Float::nan()` if the number is `Float::nan()` // #[inline] // fn signum(self) -> f32 { // if self.is_nan() { // Float::nan() // } else { // unsafe { intrinsics::copysignf32(1.0, self) } // } // } // // /// Returns `true` if `self` is positive, including `+0.0` and // /// `Float::infinity()`. // #[inline] // fn is_positive(self) -> bool { // self > 0.0 || (1.0 / self) == Float::infinity() // } // // /// Returns `true` if `self` is negative, including `-0.0` and // /// `Float::neg_infinity()`. // #[inline] // fn is_negative(self) -> bool { // self < 0.0 || (1.0 / self) == Float::neg_infinity() // } // // /// Fused multiply-add. Computes `(self * a) + b` with only one rounding // /// error. This produces a more accurate result with better performance than // /// a separate multiplication operation followed by an add. // #[inline] // fn mul_add(self, a: f32, b: f32) -> f32 { // unsafe { intrinsics::fmaf32(self, a, b) } // } // // /// Returns the reciprocal (multiplicative inverse) of the number. // #[inline] // fn recip(self) -> f32 { 1.0 / self } // // #[inline] // fn powi(self, n: i32) -> f32 { // unsafe { intrinsics::powif32(self, n) } // } // // #[inline] // fn powf(self, n: f32) -> f32 { // unsafe { intrinsics::powf32(self, n) } // } // // #[inline] // fn sqrt(self) -> f32 { // if self < 0.0 { // NAN // } else { // unsafe { intrinsics::sqrtf32(self) } // } // } // // #[inline] // fn rsqrt(self) -> f32 { self.sqrt().recip() } // // /// Returns the exponential of the number. // #[inline] // fn exp(self) -> f32 { // unsafe { intrinsics::expf32(self) } // } // // /// Returns 2 raised to the power of the number. // #[inline] // fn exp2(self) -> f32 { // unsafe { intrinsics::exp2f32(self) } // } // // /// Returns the natural logarithm of the number. // #[inline] // fn ln(self) -> f32 { // unsafe { intrinsics::logf32(self) } // } // // /// Returns the logarithm of the number with respect to an arbitrary base. // #[inline] // fn log(self, base: f32) -> f32 { self.ln() / base.ln() } // // /// Returns the base 2 logarithm of the number. // #[inline] // fn log2(self) -> f32 { // unsafe { intrinsics::log2f32(self) } // } // // /// Returns the base 10 logarithm of the number. // #[inline] // fn log10(self) -> f32 { // unsafe { intrinsics::log10f32(self) } // } // // /// Converts to degrees, assuming the number is in radians. // #[inline] // fn to_degrees(self) -> f32 { self * (180.0f32 / consts::PI) } // // /// Converts to radians, assuming the number is in degrees. // #[inline] // fn to_radians(self) -> f32 { // let value: f32 = consts::PI; // self * (value / 180.0f32) // } // } #[test] fn mul_add_test1() { let value: f32 = f32::nan(); let a: f32 = -2.0_f32; let b: f32 = 3.0_f32; let result: f32 = value.mul_add(a, b); assert_eq!(result.is_nan(), true); } #[test] fn mul_add_test2() { let value: f32 = f32::infinity(); let a: f32 = -2.0_f32; let b: f32 = 3.0_f32; let result: f32 = value.mul_add(a, b); assert_eq!(result, f32::neg_infinity()); } #[test] fn mul_add_test3() { let value: f32 = f32::neg_infinity(); let a: f32 = -2.0_f32; let b: f32 = 3.0_f32; let result: f32 = value.mul_add(a, b); assert_eq!(result, f32::infinity()); } #[test] fn mul_add_test4() { let value: f32 = f32::infinity(); let a: f32 = 1.0_f32; let b: f32 = f32::neg_infinity(); let result: f32 = value.mul_add(a, b); assert_eq!(result.is_nan(), true); } #[test] fn mul_add_test5() { let value: f32 = 5.0_f32; let a: f32 = -2.0_f32; let b: f32 = 3.0_f32; let result: f32 = value.mul_add(a, b); assert_eq!(result, -7.0); } }<|fim▁end|>
// unsafe { intrinsics::floorf32(self) } // } //
<|file_name|>isomorph.py<|end_file_name|><|fim▁begin|>""" Graph isomorphism functions. """ import networkx as nx from networkx.exception import NetworkXError __author__ = """\n""".join(['Aric Hagberg ([email protected])', 'Pieter Swart ([email protected])', 'Christopher Ellison [email protected])']) # Copyright (C) 2004-2019 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. __all__ = ['could_be_isomorphic', 'fast_could_be_isomorphic', 'faster_could_be_isomorphic', 'is_isomorphic'] def could_be_isomorphic(G1, G2): """Returns False if graphs are definitely not isomorphic. True does NOT guarantee isomorphism. Parameters ---------- G1, G2 : graphs The two graphs G1 and G2 must be the same type. Notes ----- Checks for matching degree, triangle, and number of cliques sequences. """ # Check global properties if G1.order() != G2.order(): return False # Check local properties d1 = G1.degree() t1 = nx.triangles(G1) c1 = nx.number_of_cliques(G1) props1 = [[d, t1[v], c1[v]] for v, d in d1] props1.sort() d2 = G2.degree() t2 = nx.triangles(G2) c2 = nx.number_of_cliques(G2)<|fim▁hole|> props2 = [[d, t2[v], c2[v]] for v, d in d2] props2.sort() if props1 != props2: return False # OK... return True graph_could_be_isomorphic = could_be_isomorphic def fast_could_be_isomorphic(G1, G2): """Returns False if graphs are definitely not isomorphic. True does NOT guarantee isomorphism. Parameters ---------- G1, G2 : graphs The two graphs G1 and G2 must be the same type. Notes ----- Checks for matching degree and triangle sequences. """ # Check global properties if G1.order() != G2.order(): return False # Check local properties d1 = G1.degree() t1 = nx.triangles(G1) props1 = [[d, t1[v]] for v, d in d1] props1.sort() d2 = G2.degree() t2 = nx.triangles(G2) props2 = [[d, t2[v]] for v, d in d2] props2.sort() if props1 != props2: return False # OK... return True fast_graph_could_be_isomorphic = fast_could_be_isomorphic def faster_could_be_isomorphic(G1, G2): """Returns False if graphs are definitely not isomorphic. True does NOT guarantee isomorphism. Parameters ---------- G1, G2 : graphs The two graphs G1 and G2 must be the same type. Notes ----- Checks for matching degree sequences. """ # Check global properties if G1.order() != G2.order(): return False # Check local properties d1 = sorted(d for n, d in G1.degree()) d2 = sorted(d for n, d in G2.degree()) if d1 != d2: return False # OK... return True faster_graph_could_be_isomorphic = faster_could_be_isomorphic def is_isomorphic(G1, G2, node_match=None, edge_match=None): """Returns True if the graphs G1 and G2 are isomorphic and False otherwise. Parameters ---------- G1, G2: graphs The two graphs G1 and G2 must be the same type. node_match : callable A function that returns True if node n1 in G1 and n2 in G2 should be considered equal during the isomorphism test. If node_match is not specified then node attributes are not considered. The function will be called like node_match(G1.nodes[n1], G2.nodes[n2]). That is, the function will receive the node attribute dictionaries for n1 and n2 as inputs. edge_match : callable A function that returns True if the edge attribute dictionary for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should be considered equal during the isomorphism test. If edge_match is not specified then edge attributes are not considered. The function will be called like edge_match(G1[u1][v1], G2[u2][v2]). That is, the function will receive the edge attribute dictionaries of the edges under consideration. Notes ----- Uses the vf2 algorithm [1]_. Examples -------- >>> import networkx.algorithms.isomorphism as iso For digraphs G1 and G2, using 'weight' edge attribute (default: 1) >>> G1 = nx.DiGraph() >>> G2 = nx.DiGraph() >>> nx.add_path(G1, [1,2,3,4], weight=1) >>> nx.add_path(G2, [10,20,30,40], weight=2) >>> em = iso.numerical_edge_match('weight', 1) >>> nx.is_isomorphic(G1, G2) # no weights considered True >>> nx.is_isomorphic(G1, G2, edge_match=em) # match weights False For multidigraphs G1 and G2, using 'fill' node attribute (default: '') >>> G1 = nx.MultiDiGraph() >>> G2 = nx.MultiDiGraph() >>> G1.add_nodes_from([1,2,3], fill='red') >>> G2.add_nodes_from([10,20,30,40], fill='red') >>> nx.add_path(G1, [1,2,3,4], weight=3, linewidth=2.5) >>> nx.add_path(G2, [10,20,30,40], weight=3) >>> nm = iso.categorical_node_match('fill', 'red') >>> nx.is_isomorphic(G1, G2, node_match=nm) True For multidigraphs G1 and G2, using 'weight' edge attribute (default: 7) >>> G1.add_edge(1,2, weight=7) 1 >>> G2.add_edge(10,20) 1 >>> em = iso.numerical_multiedge_match('weight', 7, rtol=1e-6) >>> nx.is_isomorphic(G1, G2, edge_match=em) True For multigraphs G1 and G2, using 'weight' and 'linewidth' edge attributes with default values 7 and 2.5. Also using 'fill' node attribute with default value 'red'. >>> em = iso.numerical_multiedge_match(['weight', 'linewidth'], [7, 2.5]) >>> nm = iso.categorical_node_match('fill', 'red') >>> nx.is_isomorphic(G1, G2, edge_match=em, node_match=nm) True See Also -------- numerical_node_match, numerical_edge_match, numerical_multiedge_match categorical_node_match, categorical_edge_match, categorical_multiedge_match References ---------- .. [1] L. P. Cordella, P. Foggia, C. Sansone, M. Vento, "An Improved Algorithm for Matching Large Graphs", 3rd IAPR-TC15 Workshop on Graph-based Representations in Pattern Recognition, Cuen, pp. 149-159, 2001. http://amalfi.dis.unina.it/graph/db/papers/vf-algorithm.pdf """ if G1.is_directed() and G2.is_directed(): GM = nx.algorithms.isomorphism.DiGraphMatcher elif (not G1.is_directed()) and (not G2.is_directed()): GM = nx.algorithms.isomorphism.GraphMatcher else: raise NetworkXError("Graphs G1 and G2 are not of the same type.") gm = GM(G1, G2, node_match=node_match, edge_match=edge_match) return gm.is_isomorphic()<|fim▁end|>
<|file_name|>backend_lobby_mux_test.go<|end_file_name|><|fim▁begin|>// Copyright (C) 2011 by Krzysztof Kowalik <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package engine import "testing" func TestBackendLobbyMuxAddLobby(t *testing.T) { mux := NewBackendLobbyMux() mux.AddLobby("/foo", &backendLobby{}) if _, ok := mux.m["/foo"]; !ok { t.Errorf("Expected to add lobby") } } func TestBackendLobbyMuxDeleteLobby(t *testing.T) { mux := NewBackendLobbyMux() l := &backendLobby{queue: make(chan interface{})} mux.AddLobby("/foo", l) if ok := mux.DeleteLobby("/foo"); !ok { t.Errorf("Expected to delete lobby") } if l.IsAlive() { t.Errorf("Lobby should be killed when deleting from the mux") } if _, ok := mux.m["/foo"]; ok { t.Errorf("Expected to delete lobby") } if ok := mux.DeleteLobby("/bar"); ok { t.Errorf("Expected to not delete non existing lobby") } } func TestBackendLobbyMuxMatch(t *testing.T) { mux := NewBackendLobbyMux() mux.AddLobby("/foo", &backendLobby{}) if lobby := mux.Match("/foo"); lobby == nil {<|fim▁hole|> t.Errorf("Expected to match existing lobby") } if lobby := mux.Match("/bar"); lobby != nil { t.Errorf("Expected to not match non existing lobby") } }<|fim▁end|>
<|file_name|>auth.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! HTTP Authorization implementations use std::collections::HashMap; use hyper::{server, net, header, status}; use endpoint::Handler; use handlers::{AuthRequiredHandler, ContentHandler}; /// Authorization result pub enum Authorized { /// Authorization was successful. Yes, /// Unsuccessful authorization. Handler for further work is returned. No(Box<Handler>), } <|fim▁hole|>pub trait Authorization : Send + Sync { /// Checks if authorization is valid. fn is_authorized(&self, req: &server::Request<net::HttpStream>)-> Authorized; } /// HTTP Basic Authorization handler pub struct HttpBasicAuth { users: HashMap<String, String>, } /// No-authorization implementation (authorization disabled) pub struct NoAuth; impl Authorization for NoAuth { fn is_authorized(&self, _req: &server::Request<net::HttpStream>)-> Authorized { Authorized::Yes } } impl Authorization for HttpBasicAuth { fn is_authorized(&self, req: &server::Request<net::HttpStream>) -> Authorized { let auth = self.check_auth(&req); match auth { Access::Denied => { Authorized::No(Box::new(ContentHandler::error( status::StatusCode::Unauthorized, "Unauthorized", "You need to provide valid credentials to access this page.", None, None, ))) }, Access::AuthRequired => { Authorized::No(Box::new(AuthRequiredHandler)) }, Access::Granted => { Authorized::Yes }, } } } #[derive(Debug)] enum Access { Granted, Denied, AuthRequired, } impl HttpBasicAuth { /// Creates `HttpBasicAuth` instance with only one user. pub fn single_user(username: &str, password: &str) -> Self { let mut users = HashMap::new(); users.insert(username.to_owned(), password.to_owned()); HttpBasicAuth { users: users } } fn is_authorized(&self, username: &str, password: &str) -> bool { self.users.get(&username.to_owned()).map_or(false, |pass| pass == password) } fn check_auth(&self, req: &server::Request<net::HttpStream>) -> Access { match req.headers().get::<header::Authorization<header::Basic>>() { Some(&header::Authorization( header::Basic { ref username, password: Some(ref password) } )) if self.is_authorized(username, password) => Access::Granted, Some(_) => Access::Denied, None => Access::AuthRequired, } } }<|fim▁end|>
/// Authorization interface
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>with open('README.txt') as f: long_description = f.read() from distutils.core import setup setup( name = "nomit", packages = ["nomit"], version = "1.0",<|fim▁hole|> url = "https://github.com/mjuenema/nomit", download_url = "https://github.com/mjuenema/nomit/tarball/1.0", keywords = ["xml", "Monit", "MMonit"], classifiers = [ "Programming Language :: Python", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Monitoring", ], long_description = long_description )<|fim▁end|>
description = "Process Monit HTTP/XML", author = "Markus Juenemann", author_email = "[email protected]",
<|file_name|>InventoryGrid.java<|end_file_name|><|fim▁begin|>package edu.cmu.cs.cimds.geogame.client.ui; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import edu.cmu.cs.cimds.geogame.client.model.dto.ItemDTO; public class InventoryGrid extends Grid { // public static final String MONEY_ICON_FILENAME = "coinbag.jpg"; public static final String BLANK_ICON_FILENAME = "blank.png"; private int numCells; private VerticalPanel[] blanks; private List<ItemDTO> inventory = new ArrayList<ItemDTO>(); private ItemImageCreator imageCreator; private String imageWidth = null; public InventoryGrid(int numRows, int numColumns) { super(numRows, numColumns); this.numCells = numRows * numColumns; this.blanks = new VerticalPanel[this.numCells]; for(int i=0;i<numCells;i++) { this.blanks[i] = new VerticalPanel(); this.blanks[i].add(new Image(BLANK_ICON_FILENAME)); this.setWidget(i, this.blanks[i]); } this.clearContent(); } public InventoryGrid(int numRows, int numColumns, ItemImageCreator imageCreator) { this(numRows, numColumns); this.imageCreator = imageCreator; } public List<ItemDTO> getInventory() { return inventory; } public void setInventory(List<ItemDTO> inventory) { this.inventory = inventory; } // public void setInventory(List<ItemTypeDTO> inventory) { // this.inventory = new ArrayList<ItemTypeDTO>(); // for(ItemTypeDTO itemType : inventory) { // Item dummyItem = new Item(); // dummyItem.setItemType(itemType); // this.inventory.add(dummyItem); // } // } public ItemImageCreator getImageCreator() { return imageCreator; } public void setImageCreator(ItemImageCreator imageCreator) { this.imageCreator = imageCreator; } public void setImageWidth(String imageWidth) { this.imageWidth = imageWidth; } public void setWidget(int numCell, Widget w) { // if(numCell >= this.numCells) { // throw new IndexOutOfBoundsException(); // } super.setWidget((int)Math.floor(numCell/this.numColumns), numCell%this.numColumns, w);<|fim▁hole|> public void clearContent() { for(int i=0;i<numCells;i++) { this.setWidget(i, this.blanks[i]); } } public void refresh() { this.clearContent(); Collections.sort(this.inventory); for(int i=0;i<this.inventory.size();i++) { final ItemDTO item = this.inventory.get(i); Image image = this.imageCreator.createImage(item); if(this.imageWidth!=null) { image.setWidth(this.imageWidth); } //Label descriptionLabel = new Label(item.getItemType().getName() + " - " + item.getItemType().getBasePrice() + "G", true); VerticalPanel itemPanel = new VerticalPanel(); itemPanel.add(image); //itemPanel.add(descriptionLabel); this.setWidget(i, itemPanel); } } }<|fim▁end|>
}
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, url from django.views.generic import RedirectView from . import views APP_SLUGS = { 'chrono': 'Chrono', 'face_value': 'Face_Value', 'podcasts': 'Podcasts', 'roller': 'Roller', 'webfighter': 'Webfighter', 'generalnotes': 'General_Notes', 'rtcamera': 'rtcamera' } def redirect_doc(uri, request=None): view = RedirectView.as_view( url='https://developer.mozilla.org/docs%s' % uri) return view(request) if request else view <|fim▁hole|> redirect_patterns = patterns('', url('^docs/firefox_os_guideline$', redirect_doc('/Web/Apps/Design'), name='ecosystem.ffos_guideline'), url('^docs/responsive_design$', redirect_doc('/Web_Development/Mobile/Responsive_design'), name='ecosystem.responsive_design'), url('^docs/patterns$', redirect_doc('/Web/Apps/Design/Responsive_Navigation_Patterns'), name='ecosystem.design_patterns'), url('^docs/review$', redirect_doc('/Web/Apps/Publishing/Marketplace_review_criteria'), name='ecosystem.publish_review'), url('^docs/deploy$', redirect_doc('/Mozilla/Marketplace/Options'), name='ecosystem.publish_deploy'), url('^docs/hosted$', redirect_doc('/Mozilla/Marketplace/Publish_options#Hosted_apps'), name='ecosystem.publish_hosted'), url('^docs/submission$', redirect_doc('/Web/Apps/Publishing/Submitting_an_app'), name='ecosystem.publish_submit'), url('^docs/packaged$', redirect_doc('/Web/Apps/Developing/Packaged_apps'), name='ecosystem.publish_packaged'), url('^docs/intro_apps$', redirect_doc('/Web/Apps/Quickstart/Build/Intro_to_open_web_apps'), name='ecosystem.build_intro'), url('^docs/firefox_os$', redirect_doc('/Mozilla/Firefox_OS'), name='ecosystem.build_ffos'), url('^docs/manifests$', redirect_doc('/Web/Apps/FAQs/About_app_manifests'), name='ecosystem.build_manifests'), url('^docs/apps_offline$', redirect_doc('/Web/Apps/Offline_apps'), name='ecosystem.build_apps_offline'), url('^docs/game_apps$', redirect_doc('/Web/Apps/Developing/Games'), name='ecosystem.build_game_apps'), url('^docs/mobile_developers$', redirect_doc('/Web/Apps/Quickstart/Build/For_mobile_developers'), name='ecosystem.build_mobile_developers'), url('^docs/web_developers$', redirect_doc('/Web/Apps/Quickstart/Build/For_Web_developers'), name='ecosystem.build_web_developers'), url('^docs/firefox_os_simulator$', redirect_doc('/Tools/Firefox_OS_Simulator'), name='ecosystem.firefox_os_simulator'), url('^docs/payments$', redirect_doc('/Web/Apps/Quickstart/Build/Payments'), name='ecosystem.build_payments'), url('^docs/concept$', redirect_doc('/Web/Apps/Quickstart/Design/Concept_A_great_app'), name='ecosystem.design_concept'), url('^docs/fundamentals$', redirect_doc('/Web/Apps/Quickstart/Design/Design_Principles'), name='ecosystem.design_fundamentals'), url('^docs/ui_guidelines$', redirect_doc('/Apps/Design'), name='ecosystem.design_ui'), url('^docs/quick_start$', redirect_doc('/Web/Apps/Quickstart/Build/Your_first_app'), name='ecosystem.build_quick'), url('^docs/reference_apps$', redirect_doc('/Web/Apps/Reference_apps'), name='ecosystem.build_reference'), url('^docs/apps/(?P<page>\w+)?$', lambda req, page: redirect_doc('/Web/Apps/Reference_apps/' + APP_SLUGS.get(page, ''), req), name='ecosystem.apps_documentation'), url('^docs/payments/status$', redirect_doc('/Mozilla/Marketplace/Payments_Status'), name='ecosystem.publish_payments'), url('^docs/tools$', redirect_doc('/Web/Apps/Quickstart/Build/App_tools'), name='ecosystem.build_tools'), url('^docs/app_generator$', redirect_doc('/Web/Apps/Developing/App_templates'), name='ecosystem.build_app_generator'), url('^docs/app_manager$', redirect_doc('/Mozilla/Firefox_OS/Using_the_App_Manager'), name='ecosystem.app_manager'), url('^docs/dev_tools$', redirect_doc('/Tools'), name='ecosystem.build_dev_tools'), # Doesn't start with docs/, but still redirects to MDN. url('^dev_phone$', redirect_doc('/Mozilla/Firefox_OS/Developer_phone_guide/Flame'), name='ecosystem.dev_phone'), ) urlpatterns = redirect_patterns + patterns('', url('^$', views.landing, name='ecosystem.landing'), url('^partners$', views.partners, name='ecosystem.partners'), url('^support$', views.support, name='ecosystem.support'), url('^docs/badges$', views.publish_badges, name='ecosystem.publish_badges') )<|fim▁end|>
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>/** * ## `<md-toolbar>` is a container for headers, titles, or actions. * * You can see live examples in the Material [documentation](https://material.angular.io/components/toolbar/examples) * * &nbsp; * ## Basic example: * HTML * ```html * <md-toolbar>My App</md-toolbar> * ``` * * TS * ```ts * import {Component} from '@angular/core'; * * * \@Component({ * selector: 'toolbar-overview-example', * templateUrl: 'toolbar-overview-example.html', * }) * export class ToolbarOverviewExample {} * ``` * * * &nbsp; * # Overview * * ## Multiple rows * Toolbars can have multiple rows using `<md-toolbar-row>` elements. Any content outside of an * `<md-toolbar-row>` element are automatically placed inside of one at the beginning of the toolbar. * Each toolbar row is a `display: flex` container. * * ```html * <md-toolbar> * <span>First Row</span> * * <md-toolbar-row> * <span>Second Row</span> * </md-toolbar-row> * * <md-toolbar-row> * <span>Third Row</span> * </md-toolbar-row> * </md-toolbar> * ```<|fim▁hole|> * The toolbar does not perform any positioning of its content. This gives the user full power to * position the content as it suits their application. * * A common pattern is to position a title on the left with some actions on the right. This can be * easily accomplished with `display: flex`: * ```html * <md-toolbar color="primary"> * <span>Application Title</span> * * <!-- This fills the remaining space of the current row --> * <span class="example-fill-remaining-space"></span> * * <span>Right Aligned Text</span> * </md-toolbar> * ``` * ```scss * .example-fill-remaining-space { * // This fills the remaining space, by using flexbox. * // Every toolbar row uses a flexbox row layout. * flex: 1 1 auto; * } * ``` * * &nbsp; * ## Theming * The color of a `<md-toolbar>` can be changed by using the `color` property. By default, toolbars * use a neutral background color based on the current theme (light or dark). This can be changed to * `'primary'`, `'accent'`, or `'warn'`. * * * &nbsp; * # Directives * ## MdToolbarRow * * Selector: `md-toolbar-row` * * &nbsp; * ## MdToolbarRow * * Selector: `md-toolbar` * * @bit */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {NgModule} from '@angular/core'; import {MdCommonModule} from '../core/common-behaviors/common-module'; import {MdToolbar, MdToolbarRow} from './toolbar'; @NgModule({ imports: [MdCommonModule], exports: [MdToolbar, MdToolbarRow, MdCommonModule], declarations: [MdToolbar, MdToolbarRow], }) export class MdToolbarModule {} export * from './toolbar';<|fim▁end|>
* * &nbsp; * ## Positioning toolbar content
<|file_name|>admin.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package api import ( "bufio" "io" "io/ioutil" "net/http" "os" "strconv"<|fim▁hole|> "time" l4g "github.com/alecthomas/log4go" "github.com/gorilla/mux" "github.com/mattermost/platform/einterfaces" "github.com/mattermost/platform/model" "github.com/mattermost/platform/store" "github.com/mattermost/platform/utils" "github.com/mssola/user_agent" ) func InitAdmin() { l4g.Debug(utils.T("api.admin.init.debug")) BaseRoutes.Admin.Handle("/logs", ApiUserRequired(getLogs)).Methods("GET") BaseRoutes.Admin.Handle("/audits", ApiUserRequired(getAllAudits)).Methods("GET") BaseRoutes.Admin.Handle("/config", ApiUserRequired(getConfig)).Methods("GET") BaseRoutes.Admin.Handle("/save_config", ApiUserRequired(saveConfig)).Methods("POST") BaseRoutes.Admin.Handle("/reload_config", ApiUserRequired(reloadConfig)).Methods("GET") BaseRoutes.Admin.Handle("/test_email", ApiUserRequired(testEmail)).Methods("POST") BaseRoutes.Admin.Handle("/recycle_db_conn", ApiUserRequired(recycleDatabaseConnection)).Methods("GET") BaseRoutes.Admin.Handle("/analytics/{id:[A-Za-z0-9]+}/{name:[A-Za-z0-9_]+}", ApiUserRequired(getAnalytics)).Methods("GET") BaseRoutes.Admin.Handle("/analytics/{name:[A-Za-z0-9_]+}", ApiUserRequired(getAnalytics)).Methods("GET") BaseRoutes.Admin.Handle("/save_compliance_report", ApiUserRequired(saveComplianceReport)).Methods("POST") BaseRoutes.Admin.Handle("/compliance_reports", ApiUserRequired(getComplianceReports)).Methods("GET") BaseRoutes.Admin.Handle("/download_compliance_report/{id:[A-Za-z0-9]+}", ApiUserRequiredTrustRequester(downloadComplianceReport)).Methods("GET") BaseRoutes.Admin.Handle("/upload_brand_image", ApiAdminSystemRequired(uploadBrandImage)).Methods("POST") BaseRoutes.Admin.Handle("/get_brand_image", ApiAppHandlerTrustRequester(getBrandImage)).Methods("GET") BaseRoutes.Admin.Handle("/reset_mfa", ApiAdminSystemRequired(adminResetMfa)).Methods("POST") BaseRoutes.Admin.Handle("/reset_password", ApiAdminSystemRequired(adminResetPassword)).Methods("POST") BaseRoutes.Admin.Handle("/ldap_sync_now", ApiAdminSystemRequired(ldapSyncNow)).Methods("POST") BaseRoutes.Admin.Handle("/saml_metadata", ApiAppHandler(samlMetadata)).Methods("GET") BaseRoutes.Admin.Handle("/add_certificate", ApiAdminSystemRequired(addCertificate)).Methods("POST") BaseRoutes.Admin.Handle("/remove_certificate", ApiAdminSystemRequired(removeCertificate)).Methods("POST") BaseRoutes.Admin.Handle("/saml_cert_status", ApiAdminSystemRequired(samlCertificateStatus)).Methods("GET") BaseRoutes.Admin.Handle("/cluster_status", ApiAdminSystemRequired(getClusterStatus)).Methods("GET") } func getLogs(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getLogs") { return } lines, err := GetLogs() if err != nil { c.Err = err return } if einterfaces.GetClusterInterface() != nil { clines, err := einterfaces.GetClusterInterface().GetLogs() if err != nil { c.Err = err return } lines = append(lines, clines...) } w.Write([]byte(model.ArrayToJson(lines))) } func GetLogs() ([]string, *model.AppError) { var lines []string if utils.Cfg.LogSettings.EnableFile { file, err := os.Open(utils.GetLogFileLocation(utils.Cfg.LogSettings.FileLocation)) if err != nil { return nil, model.NewLocAppError("getLogs", "api.admin.file_read_error", nil, err.Error()) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } } else { lines = append(lines, "") } return lines, nil } func getClusterStatus(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getClusterStatus") { return } infos := make([]*model.ClusterInfo, 0) if einterfaces.GetClusterInterface() != nil { infos = einterfaces.GetClusterInterface().GetClusterInfos() } w.Write([]byte(model.ClusterInfosToJson(infos))) } func getAllAudits(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getAllAudits") { return } if result := <-Srv.Store.Audit().Get("", 200); result.Err != nil { c.Err = result.Err return } else { audits := result.Data.(model.Audits) etag := audits.Etag() if HandleEtag(etag, w, r) { return } if len(etag) > 0 { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } w.Write([]byte(audits.ToJson())) return } } func getConfig(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getConfig") { return } json := utils.Cfg.ToJson() cfg := model.ConfigFromJson(strings.NewReader(json)) cfg.Sanitize() w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Write([]byte(cfg.ToJson())) } func reloadConfig(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("reloadConfig") { return } utils.LoadConfig(utils.CfgFileName) // start/restart email batching job if necessary InitEmailBatching() w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") ReturnStatusOK(w) } func saveConfig(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getConfig") { return } cfg := model.ConfigFromJson(r.Body) if cfg == nil { c.SetInvalidParam("saveConfig", "config") return } cfg.SetDefaults() utils.Desanitize(cfg) if err := cfg.IsValid(); err != nil { c.Err = err return } if err := utils.ValidateLdapFilter(cfg); err != nil { c.Err = err return } if *utils.Cfg.ClusterSettings.Enable { c.Err = model.NewLocAppError("saveConfig", "ent.cluster.save_config.error", nil, "") return } c.LogAudit("") //oldCfg := utils.Cfg utils.SaveConfig(utils.CfgFileName, cfg) utils.LoadConfig(utils.CfgFileName) // Future feature is to sync the configuration files // if einterfaces.GetClusterInterface() != nil { // err := einterfaces.GetClusterInterface().ConfigChanged(cfg, oldCfg, true) // if err != nil { // c.Err = err // return // } // } // start/restart email batching job if necessary InitEmailBatching() rdata := map[string]string{} rdata["status"] = "OK" w.Write([]byte(model.MapToJson(rdata))) } func recycleDatabaseConnection(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("recycleDatabaseConnection") { return } oldStore := Srv.Store l4g.Warn(utils.T("api.admin.recycle_db_start.warn")) Srv.Store = store.NewSqlStore() time.Sleep(20 * time.Second) oldStore.Close() l4g.Warn(utils.T("api.admin.recycle_db_end.warn")) w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") ReturnStatusOK(w) } func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("testEmail") { return } cfg := model.ConfigFromJson(r.Body) if cfg == nil { c.SetInvalidParam("testEmail", "config") return } if len(cfg.EmailSettings.SMTPServer) == 0 { c.Err = model.NewLocAppError("testEmail", "api.admin.test_email.missing_server", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"})) return } // if the user hasn't changed their email settings, fill in the actual SMTP password so that // the user can verify an existing SMTP connection if cfg.EmailSettings.SMTPPassword == model.FAKE_SETTING { if cfg.EmailSettings.SMTPServer == utils.Cfg.EmailSettings.SMTPServer && cfg.EmailSettings.SMTPPort == utils.Cfg.EmailSettings.SMTPPort && cfg.EmailSettings.SMTPUsername == utils.Cfg.EmailSettings.SMTPUsername { cfg.EmailSettings.SMTPPassword = utils.Cfg.EmailSettings.SMTPPassword } else { c.Err = model.NewLocAppError("testEmail", "api.admin.test_email.reenter_password", nil, "") return } } if result := <-Srv.Store.User().Get(c.Session.UserId); result.Err != nil { c.Err = result.Err return } else { if err := utils.SendMailUsingConfig(result.Data.(*model.User).Email, c.T("api.admin.test_email.subject"), c.T("api.admin.test_email.body"), cfg); err != nil { c.Err = err return } } m := make(map[string]string) m["SUCCESS"] = "true" w.Write([]byte(model.MapToJson(m))) } func getComplianceReports(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getComplianceReports") { return } if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance { c.Err = model.NewLocAppError("getComplianceReports", "ent.compliance.licence_disable.app_error", nil, "") return } if result := <-Srv.Store.Compliance().GetAll(); result.Err != nil { c.Err = result.Err return } else { crs := result.Data.(model.Compliances) w.Write([]byte(crs.ToJson())) } } func saveComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getComplianceReports") { return } if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance || einterfaces.GetComplianceInterface() == nil { c.Err = model.NewLocAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "") return } job := model.ComplianceFromJson(r.Body) if job == nil { c.SetInvalidParam("saveComplianceReport", "compliance") return } job.UserId = c.Session.UserId job.Type = model.COMPLIANCE_TYPE_ADHOC if result := <-Srv.Store.Compliance().Save(job); result.Err != nil { c.Err = result.Err return } else { job = result.Data.(*model.Compliance) go einterfaces.GetComplianceInterface().RunComplianceJob(job) } w.Write([]byte(job.ToJson())) } func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("downloadComplianceReport") { return } if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance || einterfaces.GetComplianceInterface() == nil { c.Err = model.NewLocAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "") return } params := mux.Vars(r) id := params["id"] if len(id) != 26 { c.SetInvalidParam("downloadComplianceReport", "id") return } if result := <-Srv.Store.Compliance().Get(id); result.Err != nil { c.Err = result.Err return } else { job := result.Data.(*model.Compliance) c.LogAudit("downloaded " + job.Desc) if f, err := ioutil.ReadFile(*utils.Cfg.ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip"); err != nil { c.Err = model.NewLocAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error()) return } else { w.Header().Set("Cache-Control", "max-age=2592000, public") w.Header().Set("Content-Length", strconv.Itoa(len(f))) w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer // attach extra headers to trigger a download on IE, Edge, and Safari ua := user_agent.New(r.UserAgent()) bname, _ := ua.Browser() w.Header().Set("Content-Disposition", "attachment;filename=\""+job.JobName()+".zip\"") if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" { // trim off anything before the final / so we just get the file's name w.Header().Set("Content-Type", "application/octet-stream") } w.Write(f) } } } func getAnalytics(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getAnalytics") { return } params := mux.Vars(r) teamId := params["id"] name := params["name"] if name == "standard" { var rows model.AnalyticsRows = make([]*model.AnalyticsRow, 5) rows[0] = &model.AnalyticsRow{"channel_open_count", 0} rows[1] = &model.AnalyticsRow{"channel_private_count", 0} rows[2] = &model.AnalyticsRow{"post_count", 0} rows[3] = &model.AnalyticsRow{"unique_user_count", 0} rows[4] = &model.AnalyticsRow{"team_count", 0} openChan := Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) privateChan := Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) postChan := Srv.Store.Post().AnalyticsPostCount(teamId, false, false) userChan := Srv.Store.User().AnalyticsUniqueUserCount(teamId) teamChan := Srv.Store.Team().AnalyticsTeamCount() if r := <-openChan; r.Err != nil { c.Err = r.Err return } else { rows[0].Value = float64(r.Data.(int64)) } if r := <-privateChan; r.Err != nil { c.Err = r.Err return } else { rows[1].Value = float64(r.Data.(int64)) } if r := <-postChan; r.Err != nil { c.Err = r.Err return } else { rows[2].Value = float64(r.Data.(int64)) } if r := <-userChan; r.Err != nil { c.Err = r.Err return } else { rows[3].Value = float64(r.Data.(int64)) } if r := <-teamChan; r.Err != nil { c.Err = r.Err return } else { rows[4].Value = float64(r.Data.(int64)) } w.Write([]byte(rows.ToJson())) } else if name == "post_counts_day" { if r := <-Srv.Store.Post().AnalyticsPostCountsByDay(teamId); r.Err != nil { c.Err = r.Err return } else { w.Write([]byte(r.Data.(model.AnalyticsRows).ToJson())) } } else if name == "user_counts_with_posts_day" { if r := <-Srv.Store.Post().AnalyticsUserCountsWithPostsByDay(teamId); r.Err != nil { c.Err = r.Err return } else { w.Write([]byte(r.Data.(model.AnalyticsRows).ToJson())) } } else if name == "extra_counts" { var rows model.AnalyticsRows = make([]*model.AnalyticsRow, 6) rows[0] = &model.AnalyticsRow{"file_post_count", 0} rows[1] = &model.AnalyticsRow{"hashtag_post_count", 0} rows[2] = &model.AnalyticsRow{"incoming_webhook_count", 0} rows[3] = &model.AnalyticsRow{"outgoing_webhook_count", 0} rows[4] = &model.AnalyticsRow{"command_count", 0} rows[5] = &model.AnalyticsRow{"session_count", 0} fileChan := Srv.Store.Post().AnalyticsPostCount(teamId, true, false) hashtagChan := Srv.Store.Post().AnalyticsPostCount(teamId, false, true) iHookChan := Srv.Store.Webhook().AnalyticsIncomingCount(teamId) oHookChan := Srv.Store.Webhook().AnalyticsOutgoingCount(teamId) commandChan := Srv.Store.Command().AnalyticsCommandCount(teamId) sessionChan := Srv.Store.Session().AnalyticsSessionCount() if r := <-fileChan; r.Err != nil { c.Err = r.Err return } else { rows[0].Value = float64(r.Data.(int64)) } if r := <-hashtagChan; r.Err != nil { c.Err = r.Err return } else { rows[1].Value = float64(r.Data.(int64)) } if r := <-iHookChan; r.Err != nil { c.Err = r.Err return } else { rows[2].Value = float64(r.Data.(int64)) } if r := <-oHookChan; r.Err != nil { c.Err = r.Err return } else { rows[3].Value = float64(r.Data.(int64)) } if r := <-commandChan; r.Err != nil { c.Err = r.Err return } else { rows[4].Value = float64(r.Data.(int64)) } if r := <-sessionChan; r.Err != nil { c.Err = r.Err return } else { rows[5].Value = float64(r.Data.(int64)) } w.Write([]byte(rows.ToJson())) } else { c.SetInvalidParam("getAnalytics", "name") } } func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { if len(utils.Cfg.FileSettings.DriverName) == 0 { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.storage.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.too_large.app_error", nil, "") c.Err.StatusCode = http.StatusRequestEntityTooLarge return } if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.parse.app_error", nil, "") return } m := r.MultipartForm imageArray, ok := m.File["image"] if !ok { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.no_file.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } if len(imageArray) <= 0 { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.array.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } brandInterface := einterfaces.GetBrandInterface() if brandInterface == nil { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.not_available.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } if err := brandInterface.SaveBrandImage(imageArray[0]); err != nil { c.Err = err return } c.LogAudit("") rdata := map[string]string{} rdata["status"] = "OK" w.Write([]byte(model.MapToJson(rdata))) } func getBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { if len(utils.Cfg.FileSettings.DriverName) == 0 { c.Err = model.NewLocAppError("getBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } brandInterface := einterfaces.GetBrandInterface() if brandInterface == nil { c.Err = model.NewLocAppError("getBrandImage", "api.admin.get_brand_image.not_available.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } if img, err := brandInterface.GetBrandImage(); err != nil { w.Write(nil) } else { w.Header().Set("Content-Type", "image/png") w.Write(img) } } func adminResetMfa(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) userId := props["user_id"] if len(userId) != 26 { c.SetInvalidParam("adminResetMfa", "user_id") return } if err := DeactivateMfa(userId); err != nil { c.Err = err return } c.LogAudit("") rdata := map[string]string{} rdata["status"] = "ok" w.Write([]byte(model.MapToJson(rdata))) } func adminResetPassword(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) userId := props["user_id"] if len(userId) != 26 { c.SetInvalidParam("adminResetPassword", "user_id") return } newPassword := props["new_password"] if err := utils.IsPasswordValid(newPassword); err != nil { c.Err = err return } if err := ResetPassword(c, userId, newPassword); err != nil { c.Err = err return } c.LogAudit("") rdata := map[string]string{} rdata["status"] = "ok" w.Write([]byte(model.MapToJson(rdata))) } func ldapSyncNow(c *Context, w http.ResponseWriter, r *http.Request) { go func() { if utils.IsLicensed && *utils.License.Features.LDAP && *utils.Cfg.LdapSettings.Enable { if ldapI := einterfaces.GetLdapInterface(); ldapI != nil { ldapI.SyncNow() } else { l4g.Error("%v", model.NewLocAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "").Error()) } } }() rdata := map[string]string{} rdata["status"] = "ok" w.Write([]byte(model.MapToJson(rdata))) } func samlMetadata(c *Context, w http.ResponseWriter, r *http.Request) { samlInterface := einterfaces.GetSamlInterface() if samlInterface == nil { c.Err = model.NewLocAppError("loginWithSaml", "api.admin.saml.not_available.app_error", nil, "") c.Err.StatusCode = http.StatusFound return } if result, err := samlInterface.GetMetadata(); err != nil { c.Err = model.NewLocAppError("loginWithSaml", "api.admin.saml.metadata.app_error", nil, "err="+err.Message) return } else { w.Header().Set("Content-Type", "application/xml") w.Header().Set("Content-Disposition", "attachment; filename=\"metadata.xml\"") w.Write([]byte(result)) } } func addCertificate(c *Context, w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } m := r.MultipartForm fileArray, ok := m.File["certificate"] if !ok { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.no_file.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } if len(fileArray) <= 0 { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.array.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } fileData := fileArray[0] file, err := fileData.Open() defer file.Close() if err != nil { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.open.app_error", nil, err.Error()) return } out, err := os.Create(utils.FindDir("config") + fileData.Filename) if err != nil { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error()) return } defer out.Close() io.Copy(out, file) ReturnStatusOK(w) } func removeCertificate(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) filename := props["filename"] if err := os.Remove(utils.FindConfigFile(filename)); err != nil { c.Err = model.NewLocAppError("removeCertificate", "api.admin.remove_certificate.delete.app_error", map[string]interface{}{"Filename": filename}, err.Error()) return } ReturnStatusOK(w) } func samlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request) { status := make(map[string]interface{}) status["IdpCertificateFile"] = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.IdpCertificateFile) status["PrivateKeyFile"] = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.PrivateKeyFile) status["PublicCertificateFile"] = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.PublicCertificateFile) w.Write([]byte(model.StringInterfaceToJson(status))) }<|fim▁end|>
"strings"
<|file_name|>ViewerBO.java<|end_file_name|><|fim▁begin|>package osberbot.bo; /** * TODO: Description * * @author Tititesouris * @since 2016/03/20 */ public class ViewerBO { private Integer id; private String name; private Boolean moderator; private RankBO rank; public ViewerBO(Integer id, String name, RankBO rank) { this.id = id; this.name = name; this.rank = rank; } public boolean hasPower(PowerBO power) { if (rank != null) return rank.hasPower(power);<|fim▁hole|> return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public RankBO getRank() { return rank; } public void setRank(RankBO rank) { this.rank = rank; } }<|fim▁end|>
return moderator; } public Integer getId() {
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>/* Copyright 2013 Jesse 'Jeaye' Wilkerson See licensing in LICENSE file, or at: http://www.opensource.org/licenses/BSD-3-Clause File: shared/log/mod.rs Author: Jesse 'Jeaye' Wilkerson<|fim▁hole|>#[link(name = "log", vers = "0.2")]; #[crate_type = "lib"]; #[feature(globs)]; #[feature(macro_rules)]; #[feature(managed_boxes)]; extern mod extra; pub use self::log::{ Log, Verbosity }; pub use self::log::{ VERBOSITY_DEBUG, VERBOSITY_INFO, VERBOSITY_ERROR, VERBOSITY_NONE }; pub use self::listener::Listener; #[macro_escape] pub mod log; pub mod listener;<|fim▁end|>
Description: An aggregator of logging items. */
<|file_name|>navtreeindex17.js<|end_file_name|><|fim▁begin|>var NAVTREEINDEX17 = { "classIoss_1_1Tet4.html#ae945be949a6165bf9cebf2b770699ebd":[4,0,69,135,22], "classIoss_1_1Tet4.html#af2f9d7a80f796ded6a5ddfe374ed808e":[4,0,69,135,19], "classIoss_1_1Tet7.html":[4,0,69,136], "classIoss_1_1Tet7.html#a13df36e1096ef89227119e5d308ed628":[4,0,69,136,16], "classIoss_1_1Tet7.html#a16e6fa628f011addd36fc7322faa42c0":[4,0,69,136,19], "classIoss_1_1Tet7.html#a1e12d6c712675de8a1c8fc33b0b8c92d":[4,0,69,136,9], "classIoss_1_1Tet7.html#a29e1874549c01fd3c4be76ce3e4a9f67":[4,0,69,136,4], "classIoss_1_1Tet7.html#a37e0a7bce58a5da950d1ffb58ccbe8c4":[4,0,69,136,23], "classIoss_1_1Tet7.html#a497597e125f4502ff0a59a50b97ee0d9":[4,0,69,136,0], "classIoss_1_1Tet7.html#a508d1b597207d3872de42f3adf5b57fe":[4,0,69,136,2], "classIoss_1_1Tet7.html#a5b51028e307e1d244a5e6d17086f172e":[4,0,69,136,14], "classIoss_1_1Tet7.html#a5d0ff7276306ce77f9f6aa3ff1a04c68":[4,0,69,136,17], "classIoss_1_1Tet7.html#a6185f51cb7d94cb95220d98027ebaca0":[4,0,69,136,5], "classIoss_1_1Tet7.html#a64e46d81e51eda112c26105ec99c6cfe":[4,0,69,136,1], "classIoss_1_1Tet7.html#a8a12f05296d24f424b8466da9441bf0c":[4,0,69,136,22], "classIoss_1_1Tet7.html#a8bc616e8c2c9f2a493317979c67fa047":[4,0,69,136,7], "classIoss_1_1Tet7.html#a93b1ed3d1f0c22a79a794971845787f8":[4,0,69,136,12], "classIoss_1_1Tet7.html#aa99a6537359811e7ff5e8303c058faa2":[4,0,69,136,3], "classIoss_1_1Tet7.html#aad6a34b82fd2536894803cb9a6d3770a":[4,0,69,136,25], "classIoss_1_1Tet7.html#ab39e17b1fc522bfd33eccda8a0d770b8":[4,0,69,136,11], "classIoss_1_1Tet7.html#ab6ea8527499e31b590ff96a6f167adb0":[4,0,69,136,21], "classIoss_1_1Tet7.html#ac0cec8c082b6b0dd48b12849b3925792":[4,0,69,136,24], "classIoss_1_1Tet7.html#ac70c36c3acc282ddf505e21d263c5e70":[4,0,69,136,6], "classIoss_1_1Tet7.html#aca98ce328e3342d199d61e775601f966":[4,0,69,136,18], "classIoss_1_1Tet7.html#acdf346236e1c828a7f2465d3d90647c1":[4,0,69,136,20], "classIoss_1_1Tet7.html#ad2abb9b07e6f3cf751e664b9c8b8d597":[4,0,69,136,8], "classIoss_1_1Tet7.html#ad3c34a488797fe95f2ed9fa15d6421e9":[4,0,69,136,15], "classIoss_1_1Tet7.html#aeef6548bb945ed9834a9ceef46a0c20e":[4,0,69,136,13], "classIoss_1_1Tet7.html#af07d90322884ef186c3e2c777ed13084":[4,0,69,136,10], "classIoss_1_1Tet8.html":[4,0,69,137], "classIoss_1_1Tet8.html#a00b61be09130b0410063302f64f43bcc":[4,0,69,137,5], "classIoss_1_1Tet8.html#a011bc0eff2c9265228cdf52b83678c9b":[4,0,69,137,7], "classIoss_1_1Tet8.html#a03b2292e8a7cdd7351e603e73134d34e":[4,0,69,137,15], "classIoss_1_1Tet8.html#a25457b776295b67a48a9ca00674f0d94":[4,0,69,137,13], "classIoss_1_1Tet8.html#a2e8a36b032da95bed6b7e1571428964f":[4,0,69,137,1], "classIoss_1_1Tet8.html#a30f56430f429096f36a3972a0b80cbd1":[4,0,69,137,16], "classIoss_1_1Tet8.html#a35ecd3d481252dff9eb20dc4dc49e36c":[4,0,69,137,20], "classIoss_1_1Tet8.html#a3ed02b12943ee78a551128eb1c40544f":[4,0,69,137,17], "classIoss_1_1Tet8.html#a4c7f31adf0bc54963f73e7514a0848e4":[4,0,69,137,12], "classIoss_1_1Tet8.html#a548e6882af1baf769ff64113da6a3570":[4,0,69,137,14], "classIoss_1_1Tet8.html#a5e8d00b887f319058205ed9248ea492b":[4,0,69,137,21], "classIoss_1_1Tet8.html#a6669f4ba0986fb3a72da72a81759bd16":[4,0,69,137,23], "classIoss_1_1Tet8.html#a7de7e6c605fb27d31a803cd374c5e40e":[4,0,69,137,0], "classIoss_1_1Tet8.html#a9137b19a3fb4cec9a75d932a19fb88a4":[4,0,69,137,3], "classIoss_1_1Tet8.html#a9885a8df8a5deb1ebe64d055e0381edf":[4,0,69,137,2], "classIoss_1_1Tet8.html#a9cfdf666e5e3997eb04d6b64fca2aafe":[4,0,69,137,9], "classIoss_1_1Tet8.html#ab10481a406a6e6c21b9ad1927edea4f0":[4,0,69,137,4], "classIoss_1_1Tet8.html#ac3213933e5e7534d6e57785451788dd1":[4,0,69,137,8], "classIoss_1_1Tet8.html#ad8b8917b2d07797175cde71693211f70":[4,0,69,137,10], "classIoss_1_1Tet8.html#ae1058c79432e4ad3819aa6d1dc289da4":[4,0,69,137,22], "classIoss_1_1Tet8.html#ae34777703a05db0dea75a51fd4c9369f":[4,0,69,137,11], "classIoss_1_1Tet8.html#af22d74d02ec643002e8f29ed43afd1af":[4,0,69,137,6], "classIoss_1_1Tet8.html#afaf24cab8a279fa5198dd013d24435ca":[4,0,69,137,18], "classIoss_1_1Tet8.html#afd832344bca83f1bb0b6d6501b6d0403":[4,0,69,137,19], "classIoss_1_1Tracer.html":[4,0,69,138], "classIoss_1_1Tracer.html#a0424194979de9618ae5aa5ace9238059":[4,0,69,138,2], "classIoss_1_1Tracer.html#a162b60918f354c5b578dd176db7d18b5":[4,0,69,138,1], "classIoss_1_1Tracer.html#a77abfa36452763455cfae5f9b3dbec3c":[4,0,69,138,0], "classIoss_1_1Transform.html":[4,0,69,139], "classIoss_1_1Transform.html#a037d9cb9194d128d62c078c76e2a3e9c":[4,0,69,139,4], "classIoss_1_1Transform.html#a08b3d25e81aad971319e5226dbe6c5d4":[4,0,69,139,8], "classIoss_1_1Transform.html#a0a04fddfb90aa8093846bca0bfd5bae9":[4,0,69,139,9], "classIoss_1_1Transform.html#a2e07c7b72c70b6571745cad8c19829aa":[4,0,69,139,2], "classIoss_1_1Transform.html#a2ed9cede3ba9cca42682290603977b66":[4,0,69,139,1], "classIoss_1_1Transform.html#a38a16d4864b0c5b0fd9748a4546167a5":[4,0,69,139,6], "classIoss_1_1Transform.html#a73a8a80e4a4ff6a3c8b3a7c8ca6173c3":[4,0,69,139,3], "classIoss_1_1Transform.html#abf6cd01b7fdc9b09b9f956da4904e242":[4,0,69,139,5], "classIoss_1_1Transform.html#ad567453635ee4e6bcc3bb20279ddc74e":[4,0,69,139,0], "classIoss_1_1Transform.html#ae6af4e1c07b4dbbc84cc12ff1485b062":[4,0,69,139,7], "classIoss_1_1Tri3.html":[4,0,69,140], "classIoss_1_1Tri3.html#a00497b28142b0128564efc4485abac40":[4,0,69,140,21], "classIoss_1_1Tri3.html#a0afecfcc2808957fe70dc8eff7859d23":[4,0,69,140,13], "classIoss_1_1Tri3.html#a0c1427196558a2add60569c581948044":[4,0,69,140,7], "classIoss_1_1Tri3.html#a1dd94af979b99b166e4a97399d4aaa18":[4,0,69,140,3], "classIoss_1_1Tri3.html#a3fcd8ca13ccdb29ddde6b26a30800f09":[4,0,69,140,5], "classIoss_1_1Tri3.html#a44fb0127fc9e6387d76a56fdbb6aea36":[4,0,69,140,2], "classIoss_1_1Tri3.html#a5af625ebd0a0f5856791f94a6b19326b":[4,0,69,140,9], "classIoss_1_1Tri3.html#a70d571e1b83b73d99e2e2eb558e19f4c":[4,0,69,140,6], "classIoss_1_1Tri3.html#a70e465e12ad1fdd7e71d8d45a2cbf624":[4,0,69,140,20], "classIoss_1_1Tri3.html#a7d3559610a65520e9219ce2c6f596083":[4,0,69,140,12], "classIoss_1_1Tri3.html#a97ebfc797a34a6a75effb91965372580":[4,0,69,140,1], "classIoss_1_1Tri3.html#a99a9fcf57e733edceb2c868f3e670f3f":[4,0,69,140,14], "classIoss_1_1Tri3.html#a9d0a293948f686a44a6fc33ca79e59d3":[4,0,69,140,18], "classIoss_1_1Tri3.html#a9d3a5e2ff52cfa2d372963388fc4c8b9":[4,0,69,140,22], "classIoss_1_1Tri3.html#abcf3977487f14331b788a2244e5dfeed":[4,0,69,140,15], "classIoss_1_1Tri3.html#acd35db085d490501cc1861eaa15dd1de":[4,0,69,140,19], "classIoss_1_1Tri3.html#ad2193f85fe82211f182eda2e22f2d3b7":[4,0,69,140,10], "classIoss_1_1Tri3.html#ad2aeaef685733064c58871168b2da196":[4,0,69,140,16], "classIoss_1_1Tri3.html#ad58d40594c44f55f78620daf1e9beddd":[4,0,69,140,8], "classIoss_1_1Tri3.html#add8e943c4537c3ae5b8d5bd12a1412c9":[4,0,69,140,0], "classIoss_1_1Tri3.html#aeecc1f6ad221d7c624b3e255bbcfd25c":[4,0,69,140,11], "classIoss_1_1Tri3.html#afbfec6c87e7f29b04e226a6b921eb4b5":[4,0,69,140,4], "classIoss_1_1Tri3.html#afd12cfff5e317ce895ad210afaddac44":[4,0,69,140,17], "classIoss_1_1Tri4.html":[4,0,69,141], "classIoss_1_1Tri4.html#a013db626c1488d5b9aeefd90ded56274":[4,0,69,141,3], "classIoss_1_1Tri4.html#a089412d62e838525bae41dd2b3c8a863":[4,0,69,141,10], "classIoss_1_1Tri4.html#a0c3f8b9c919e0a203797a30e86989076":[4,0,69,141,4], "classIoss_1_1Tri4.html#a240083abc5d59f707bde11529a5e0251":[4,0,69,141,21], "classIoss_1_1Tri4.html#a2e741315708bd0bd49860bcc8a737677":[4,0,69,141,14], "classIoss_1_1Tri4.html#a35d4c4b88da6fbc2a012165929da6eda":[4,0,69,141,22], "classIoss_1_1Tri4.html#a5068f545c8885247fd7335f7558d6f3d":[4,0,69,141,12], "classIoss_1_1Tri4.html#a58650889ae52b5b76902bbbeb90ebd9b":[4,0,69,141,1], "classIoss_1_1Tri4.html#a5b5f986611e5685a1534813de33a673f":[4,0,69,141,0], "classIoss_1_1Tri4.html#a67f786bb5cfec7bec072ec06f32c0915":[4,0,69,141,18], "classIoss_1_1Tri4.html#a6a45356f2540b9387c5fbc22b3fba97d":[4,0,69,141,13], "classIoss_1_1Tri4.html#a71ef18b101d0c8d03890792977480271":[4,0,69,141,11], "classIoss_1_1Tri4.html#a8694a27fd6128adf1bbb3169eb71843e":[4,0,69,141,8], "classIoss_1_1Tri4.html#a8d04a744ec919be6705975b5410757e1":[4,0,69,141,9], "classIoss_1_1Tri4.html#a9559b34bd82633bcf034903c815fa0b6":[4,0,69,141,17], "classIoss_1_1Tri4.html#aa0c9dd8db3639cb06366eae3d7fba154":[4,0,69,141,6], "classIoss_1_1Tri4.html#ab6d214f03ef7b7f8438c04d08a6693f4":[4,0,69,141,16], "classIoss_1_1Tri4.html#ac5ef86f7468ed92ebd47434108b0e793":[4,0,69,141,15], "classIoss_1_1Tri4.html#ac8a61b40a3db3a2b4d35b2726b582d69":[4,0,69,141,2], "classIoss_1_1Tri4.html#ad4ae0392238aa94bf74cbd1fb4d72e39":[4,0,69,141,7], "classIoss_1_1Tri4.html#ae019a32790a14f676230d55bc11bcd23":[4,0,69,141,5], "classIoss_1_1Tri4.html#ae423f11a0fb84600efddb6bd11277112":[4,0,69,141,19], "classIoss_1_1Tri4.html#afe46a478baaa7c441ecec0924be27480":[4,0,69,141,20], "classIoss_1_1Tri4a.html":[4,0,69,142], "classIoss_1_1Tri4a.html#a25910996f609d6f00a3ba71f7ccb5fc3":[4,0,69,142,5], "classIoss_1_1Tri4a.html#a2815b2cd0b48f3dfc6f1c5a2b61d1178":[4,0,69,142,1], "classIoss_1_1Tri4a.html#a2a97cb506ec29eb05fc5130982610f92":[4,0,69,142,8], "classIoss_1_1Tri4a.html#a424c58fabd60b466719d6faaf0003f1f":[4,0,69,142,20], "classIoss_1_1Tri4a.html#a51beb2b1f3bc2ad9081722e8bb9d75cd":[4,0,69,142,19], "classIoss_1_1Tri4a.html#a59649ebbd2ddf4a5e14a6ae3f645f20e":[4,0,69,142,2], "classIoss_1_1Tri4a.html#a5dfe322ed0a094e93eaa992f99cec871":[4,0,69,142,12], "classIoss_1_1Tri4a.html#a6814569dd48827ad9762bf043666ccdf":[4,0,69,142,21], "classIoss_1_1Tri4a.html#a6c328ee45b3fe18d94942c14002d7dc4":[4,0,69,142,3], "classIoss_1_1Tri4a.html#a6e1d4ff5e717b1ab4db9cd36ae560c4e":[4,0,69,142,0], "classIoss_1_1Tri4a.html#a76478395a1e3567f128cf1cdbf9d2838":[4,0,69,142,17], "classIoss_1_1Tri4a.html#a77ed4a87c304c42a5a95baed8e64741b":[4,0,69,142,23], "classIoss_1_1Tri4a.html#a7bb3df352e69e1b9dae27f72dd45de04":[4,0,69,142,4], "classIoss_1_1Tri4a.html#a8056802fee146e9590b4f503cc151990":[4,0,69,142,22], "classIoss_1_1Tri4a.html#a8de8b020910eaeff60e169696a31b081":[4,0,69,142,10], "classIoss_1_1Tri4a.html#a9db31edf11f7f67633f8e4472e651558":[4,0,69,142,15], "classIoss_1_1Tri4a.html#ac4a6e2c1e1a9128dc0103b3dd5f60648":[4,0,69,142,7], "classIoss_1_1Tri4a.html#ac76ddceb4fb6b8e63abdb7973c00577f":[4,0,69,142,16], "classIoss_1_1Tri4a.html#ac8b593d930d34b65e8b229fc7b831163":[4,0,69,142,6], "classIoss_1_1Tri4a.html#ade855f124f71b4632990cc8a94715243":[4,0,69,142,14], "classIoss_1_1Tri4a.html#ae11cd6b6c936f596284fd30d427ede78":[4,0,69,142,18], "classIoss_1_1Tri4a.html#ae189248fdfffb9723f0940a28fba0f59":[4,0,69,142,13], "classIoss_1_1Tri4a.html#aecb707faf827cfa3d7674a50cd8a0e01":[4,0,69,142,11], "classIoss_1_1Tri4a.html#af7a441282b97165a2efc948dacd45d34":[4,0,69,142,9], "classIoss_1_1Tri6.html":[4,0,69,143], "classIoss_1_1Tri6.html#a1742a5d223acd57dd35601558a8e88ea":[4,0,69,143,18], "classIoss_1_1Tri6.html#a22e045b48cdd439d6ca9ada864f7c0fa":[4,0,69,143,12], "classIoss_1_1Tri6.html#a2342fb9e4e320d5d5aae6121ada1dda9":[4,0,69,143,19], "classIoss_1_1Tri6.html#a3100ba4a5d131f86c926b1159704d0f2":[4,0,69,143,5], "classIoss_1_1Tri6.html#a32453b699308c9fb01137085fffecc8f":[4,0,69,143,4], "classIoss_1_1Tri6.html#a4f08c83b56ff296e11f39206148703f9":[4,0,69,143,1], "classIoss_1_1Tri6.html#a770e5eaa73aeed57ea57a9b38f57de69":[4,0,69,143,16], "classIoss_1_1Tri6.html#a7f8deedf41a215512a738cd93eaaa0e1":[4,0,69,143,21], "classIoss_1_1Tri6.html#a879f00a93ef7588a1cd0fcff818e6230":[4,0,69,143,15], "classIoss_1_1Tri6.html#a9cd8881347532603f209a71824381589":[4,0,69,143,20], "classIoss_1_1Tri6.html#aa8b6274f991d8bd4cf3271d6ab727604":[4,0,69,143,17], "classIoss_1_1Tri6.html#aab22eefd376744d44ceebff8c26f1d44":[4,0,69,143,7], "classIoss_1_1Tri6.html#aab2eb3ab749d58b54e324f0ce144444e":[4,0,69,143,9], "classIoss_1_1Tri6.html#ab799c277be6ff03318328af89be88dc2":[4,0,69,143,2], "classIoss_1_1Tri6.html#ab8509e9f199d876eb3daca8296f544d9":[4,0,69,143,13], "classIoss_1_1Tri6.html#abe906bca33957d2182597376f861d14b":[4,0,69,143,14], "classIoss_1_1Tri6.html#ad2bccfaad6094b531d2f5819b61365e9":[4,0,69,143,0], "classIoss_1_1Tri6.html#ae7fd816d324b8f623f374926204233dd":[4,0,69,143,11], "classIoss_1_1Tri6.html#ae85c16cbeb78fca3f21009c965151e2a":[4,0,69,143,6], "classIoss_1_1Tri6.html#aec005d92c3ed3ea2c11934e4e717193c":[4,0,69,143,22], "classIoss_1_1Tri6.html#af2afd7e564e1fe0bcfee313bdaed11b8":[4,0,69,143,3], "classIoss_1_1Tri6.html#af445874fc040863b4b365dffb4cd42ba":[4,0,69,143,8], "classIoss_1_1Tri6.html#afeaf081098bce861ca91adfddc120341":[4,0,69,143,10], "classIoss_1_1Tri7.html":[4,0,69,144], "classIoss_1_1Tri7.html#a023e98ceb4d292a9eb7e859393c73133":[4,0,69,144,20], "classIoss_1_1Tri7.html#a08c0d7df5d23b5d167b3da41c471c5a8":[4,0,69,144,10], "classIoss_1_1Tri7.html#a0fd12222086391d13953446553357e24":[4,0,69,144,1], "classIoss_1_1Tri7.html#a177a84df7606246e26d4fdf6a45ccdff":[4,0,69,144,14], "classIoss_1_1Tri7.html#a1b46841ac4427ba6a7250ad01e48fd85":[4,0,69,144,17], "classIoss_1_1Tri7.html#a1caacfbbd85dacdfcea7456d4f34785b":[4,0,69,144,16], "classIoss_1_1Tri7.html#a243a435eb0062b91461ed2a13defc420":[4,0,69,144,19], "classIoss_1_1Tri7.html#a2767210d1ab21177f2fb73fa80701bcf":[4,0,69,144,6], "classIoss_1_1Tri7.html#a2e36fa4800efaa5612e5b603bbcd1bd8":[4,0,69,144,12], "classIoss_1_1Tri7.html#a2e3a4a6d48b34a490df162de77a51988":[4,0,69,144,9], "classIoss_1_1Tri7.html#a398c635a1787e692ab31c4cad5add040":[4,0,69,144,2], "classIoss_1_1Tri7.html#a47d03409072406d0d2a45f0cc2d7b86b":[4,0,69,144,5], "classIoss_1_1Tri7.html#a4fe80cae1ee5fd3070c1b17cade5e59f":[4,0,69,144,8], "classIoss_1_1Tri7.html#a651838ca5b586bd9419b6f98766c4365":[4,0,69,144,7], "classIoss_1_1Tri7.html#a6f48eb90ab2f175b55eafc66d0fffff1":[4,0,69,144,11], "classIoss_1_1Tri7.html#a8de757a487f8f32ae082a216078abaf2":[4,0,69,144,4], "classIoss_1_1Tri7.html#a9797e1b785695a4d26ee4fe2a67677c9":[4,0,69,144,18], "classIoss_1_1Tri7.html#a9e2e5de42b3a3efa1ddd9c7a6633f30d":[4,0,69,144,13], "classIoss_1_1Tri7.html#abfd7a5ef7840894f75b65ae35d45710a":[4,0,69,144,21], "classIoss_1_1Tri7.html#ac4c3eb039489a5f276e9a1492267502e":[4,0,69,144,3], "classIoss_1_1Tri7.html#ac4dbf0f7cae3c70328909d204084eba2":[4,0,69,144,0], "classIoss_1_1Tri7.html#ac60c95c0d3b0f4b380ad7456934c759e":[4,0,69,144,22], "classIoss_1_1Tri7.html#afc03e1ed3e41a9bd3f691ab2a5a83287":[4,0,69,144,15],<|fim▁hole|>"classIoss_1_1TriShell3.html#a190b3a5b0e4d4f626ad19c35b7fe4d01":[4,0,69,145,19], "classIoss_1_1TriShell3.html#a1e14fe5ed3c3f79ef106dc7a4245154e":[4,0,69,145,14], "classIoss_1_1TriShell3.html#a2c179e48f700166e5470c36a4d7b1c55":[4,0,69,145,13], "classIoss_1_1TriShell3.html#a3a2e43db0446b70dae125cea9103e250":[4,0,69,145,21], "classIoss_1_1TriShell3.html#a504a11c3dbb30648fbcf8cca05eb6496":[4,0,69,145,2], "classIoss_1_1TriShell3.html#a5bf8fbe762cbb91d057a644aecacea34":[4,0,69,145,17], "classIoss_1_1TriShell3.html#a5c399b2094722db9709c3f80540b50a8":[4,0,69,145,0], "classIoss_1_1TriShell3.html#a6e9c7dd07e5e92a148701b33061d1dd4":[4,0,69,145,8], "classIoss_1_1TriShell3.html#a71d65344c4cc54507ad01c5999f89e35":[4,0,69,145,23], "classIoss_1_1TriShell3.html#a830f20e54dba1b40d77ad72bee5e5836":[4,0,69,145,11], "classIoss_1_1TriShell3.html#a849f39ba598476953e68b20eb68afcf5":[4,0,69,145,15], "classIoss_1_1TriShell3.html#a8945846e559d73a82c949926ddbe8bd8":[4,0,69,145,5], "classIoss_1_1TriShell3.html#a982f9f10c322d7eed5f2f16e6f7a914e":[4,0,69,145,9], "classIoss_1_1TriShell3.html#ab0089b7b18ba4646977b43755c73f2c3":[4,0,69,145,6], "classIoss_1_1TriShell3.html#ab25e33b89086a7ee7d639919d5d8f107":[4,0,69,145,3], "classIoss_1_1TriShell3.html#abc756a25684952aa129837486d155744":[4,0,69,145,12], "classIoss_1_1TriShell3.html#ac85c51dd7e794a921c51cb7da9966fc9":[4,0,69,145,10], "classIoss_1_1TriShell3.html#ae7df765f22e03ab1e76c30e0b77fcdf5":[4,0,69,145,1], "classIoss_1_1TriShell3.html#aed8950ad60c701b815b8496a0c50e690":[4,0,69,145,20], "classIoss_1_1TriShell3.html#af4adcf209c460b2ebd782db1597601d0":[4,0,69,145,22], "classIoss_1_1TriShell3.html#afa185d68a0c59bd01751a48b97fcfd98":[4,0,69,145,18], "classIoss_1_1TriShell3.html#aff6973b37150283884832ca0a9564dab":[4,0,69,145,4], "classIoss_1_1TriShell4.html":[4,0,69,146], "classIoss_1_1TriShell4.html#a002a93c56b3124909307580a2a7316ae":[4,0,69,146,2], "classIoss_1_1TriShell4.html#a1988b9ea1ca6ff408342c89f2678101e":[4,0,69,146,3], "classIoss_1_1TriShell4.html#a1b9c25f1f7d7b7f995ce4717cdb56102":[4,0,69,146,17], "classIoss_1_1TriShell4.html#a20be75da2c06aaf57c3b4e051a8f9d63":[4,0,69,146,16], "classIoss_1_1TriShell4.html#a34f96eabcb67dd336f4bba6eae6547ae":[4,0,69,146,10], "classIoss_1_1TriShell4.html#a420e5437756539fceb08c38a614cea47":[4,0,69,146,1], "classIoss_1_1TriShell4.html#a4287b9b457030b490a4383ac36087439":[4,0,69,146,8], "classIoss_1_1TriShell4.html#a45d002b40c8e4f7001bf1cea049d7a0e":[4,0,69,146,5], "classIoss_1_1TriShell4.html#a4abc705677e620df0497c6e78b63e7ec":[4,0,69,146,12], "classIoss_1_1TriShell4.html#a4c20572cd3c4110a436a1e1cbfb2f8a9":[4,0,69,146,21], "classIoss_1_1TriShell4.html#a6d01004f3fc5053893de464fe61056f8":[4,0,69,146,14], "classIoss_1_1TriShell4.html#a7afc1d0da6821aefbe1eb103ff50dab4":[4,0,69,146,11], "classIoss_1_1TriShell4.html#a82ddc1635b0291c35c8498122d7e5dc1":[4,0,69,146,4], "classIoss_1_1TriShell4.html#a84d116f292724ce2e2112fa850f9b322":[4,0,69,146,20], "classIoss_1_1TriShell4.html#a87258b7f488a85a8138f0603e9d0acdc":[4,0,69,146,0], "classIoss_1_1TriShell4.html#a888eba93c31eb1b815559d1a77602c38":[4,0,69,146,7], "classIoss_1_1TriShell4.html#a98a21bb0323cb09b92909e66f9ed073c":[4,0,69,146,9], "classIoss_1_1TriShell4.html#aa7e22e4178c14763a481339179b4e137":[4,0,69,146,15], "classIoss_1_1TriShell4.html#aa87c9628c2332642aa96d1e405883238":[4,0,69,146,19], "classIoss_1_1TriShell4.html#aadb36aeda57340bd17137d8783b44e93":[4,0,69,146,22], "classIoss_1_1TriShell4.html#aaf10025253ad5d01cd9db87f4d916991":[4,0,69,146,18], "classIoss_1_1TriShell4.html#ad7afb332445b43a4788a44c63250ee42":[4,0,69,146,6], "classIoss_1_1TriShell4.html#ae9ce2d0c366d5d5c875a5cdda558c3d4":[4,0,69,146,23], "classIoss_1_1TriShell4.html#af1eb529200e7724ca1df486ab1aca437":[4,0,69,146,13], "classIoss_1_1TriShell6.html":[4,0,69,147], "classIoss_1_1TriShell6.html#a0ce4c50290a2f86e7df1e6399b03f046":[4,0,69,147,5], "classIoss_1_1TriShell6.html#a0ea48813e987a2edf0eb2782f0490532":[4,0,69,147,10], "classIoss_1_1TriShell6.html#a24313d5b5259f993b77f5b97d6f2e546":[4,0,69,147,7], "classIoss_1_1TriShell6.html#a2c2ab11aa74661eb2f1f419ca3c380e6":[4,0,69,147,2], "classIoss_1_1TriShell6.html#a3fea7f1a6bca3646c964f3dacb0865c9":[4,0,69,147,21], "classIoss_1_1TriShell6.html#a4641861d7b4a840480f4c237089faef9":[4,0,69,147,11], "classIoss_1_1TriShell6.html#a46b0355e6ca9e177b1b5b346062a8356":[4,0,69,147,4], "classIoss_1_1TriShell6.html#a6962dd09041216a482023cfa6f88c01a":[4,0,69,147,22], "classIoss_1_1TriShell6.html#a6addf0ab034e091a17d078ff745e1d47":[4,0,69,147,16] };<|fim▁end|>
"classIoss_1_1TriShell3.html":[4,0,69,145], "classIoss_1_1TriShell3.html#a036e26dedc61661127a9b1895218d946":[4,0,69,145,7], "classIoss_1_1TriShell3.html#a0dc6bebf7ea7657abc2e63a12bd0bddb":[4,0,69,145,16],
<|file_name|>GraphGrammar.py<|end_file_name|><|fim▁begin|># _ GraphGrammar.py __________________________________________________ # This class implements a graph grammar, that is basically an ordered # collecttion of GGrule's # ____________________________________________________________________ from GGrule import * class GraphGrammar: def __init__(self, GGrules = None): "Constructor, it receives GGrules, that is a list of GGrule elements" self.GGrules = [] # We'll insert rules by order of execution self.rewritingSystem = None # No rewriting system assigned yet while len(self.GGrules) < len(GGrules): # iterate until each rule is inserted min = 30000 # set mininum number to a very high number minRule = None # pointer to rule to be inserted for rule in GGrules: # search for the minimum execution order that is not inserted if rule.executionOrder < min and not rule in self.GGrules: min = rule.executionOrder minRule = rule self.GGrules.append(minRule) def setGraphRewritingSystem(self, rs): "Sets the attribute rewritingSystem to rs and also calls the same method for each rule" self.rewritingSystem = rs for rule in self.GGrules: rule.setGraphGrammar(self) rule.setGraphRewritingSystem(rs) def initialAction(self, graph): # , atom3i = None): "action to be performed before the graph grammar starts its execution (must be overriden)" <|fim▁hole|> pass def finalAction(self, graph): #, atom3i = None): "action to be performed after the graph grammar starts its execution (must be overriden)" pass<|fim▁end|>
<|file_name|>config.py<|end_file_name|><|fim▁begin|># Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from oslo_config import cfg from st2common.constants.system import VERSION_STRING def do_register_opts(opts, group=None, ignore_errors=False): try: cfg.CONF.register_opts(opts, group=group) except: if not ignore_errors: raise def do_register_cli_opts(opt, ignore_errors=False): # TODO: This function has broken name, it should work with lists :/ if not isinstance(opt, (list, tuple)): opts = [opt] else: opts = opt try: cfg.CONF.register_cli_opts(opts) except: if not ignore_errors: raise def register_opts(ignore_errors=False): auth_opts = [ cfg.BoolOpt('enable', default=True, help='Enable authentication middleware.'), cfg.IntOpt('token_ttl', default=86400, help='Access token ttl in seconds.') ] do_register_opts(auth_opts, 'auth', ignore_errors) rbac_opts = [ cfg.BoolOpt('enable', default=False, help='Enable RBAC.'), ] do_register_opts(rbac_opts, 'rbac', ignore_errors) system_user_opts = [ cfg.StrOpt('user', default='stanley', help='Default system user.'), cfg.StrOpt('ssh_key_file', default='/home/vagrant/.ssh/stanley_rsa', help='SSH private key for the system user.') ] do_register_opts(system_user_opts, 'system_user', ignore_errors) schema_opts = [ cfg.IntOpt('version', default=4, help='Version of JSON schema to use.'), cfg.StrOpt('draft', default='http://json-schema.org/draft-04/schema#', help='URL to the JSON schema draft.') ] do_register_opts(schema_opts, 'schema', ignore_errors) system_opts = [ cfg.StrOpt('base_path', default='/opt/stackstorm', help='Base path to all st2 artifacts.'), cfg.ListOpt('admin_users', default=[], help='A list of usernames for users which should have admin privileges') ] do_register_opts(system_opts, 'system', ignore_errors) system_packs_base_path = os.path.join(cfg.CONF.system.base_path, 'packs') content_opts = [ cfg.StrOpt('system_packs_base_path', default=system_packs_base_path, help='Path to the directory which contains system packs.'), cfg.StrOpt('packs_base_paths', default=None,<|fim▁hole|> ] do_register_opts(content_opts, 'content', ignore_errors) db_opts = [ cfg.StrOpt('host', default='0.0.0.0', help='host of db server'), cfg.IntOpt('port', default=27017, help='port of db server'), cfg.StrOpt('db_name', default='st2', help='name of database'), cfg.StrOpt('username', help='username for db login'), cfg.StrOpt('password', help='password for db login'), cfg.IntOpt('connection_retry_max_delay_m', help='Connection retry total time (minutes).', default=3), cfg.IntOpt('connection_retry_backoff_max_s', help='Connection retry backoff max (seconds).', default=10), cfg.IntOpt('connection_retry_backoff_mul', help='Backoff multiplier (seconds).', default=1) ] do_register_opts(db_opts, 'database', ignore_errors) messaging_opts = [ # It would be nice to be able to deprecate url and completely switch to using # url. However, this will be a breaking change and will have impact so allowing both. cfg.StrOpt('url', default='amqp://guest:[email protected]:5672//', help='URL of the messaging server.'), cfg.ListOpt('cluster_urls', default=[], help='URL of all the nodes in a messaging service cluster.') ] do_register_opts(messaging_opts, 'messaging', ignore_errors) syslog_opts = [ cfg.StrOpt('host', default='127.0.0.1', help='Host for the syslog server.'), cfg.IntOpt('port', default=514, help='Port for the syslog server.'), cfg.StrOpt('facility', default='local7', help='Syslog facility level.'), cfg.StrOpt('protocol', default='udp', help='Transport protocol to use (udp / tcp).') ] do_register_opts(syslog_opts, 'syslog', ignore_errors) log_opts = [ cfg.ListOpt('excludes', default='', help='Exclusion list of loggers to omit.'), cfg.BoolOpt('redirect_stderr', default=False, help='Controls if stderr should be redirected to the logs.'), cfg.BoolOpt('mask_secrets', default=True, help='True to mask secrets in the log files.') ] do_register_opts(log_opts, 'log', ignore_errors) # Common API options api_opts = [ cfg.StrOpt('host', default='0.0.0.0', help='StackStorm API server host'), cfg.IntOpt('port', default=9101, help='StackStorm API server port') ] do_register_opts(api_opts, 'api', ignore_errors) # Common auth options auth_opts = [ cfg.StrOpt('api_url', default=None, help='Base URL to the API endpoint excluding the version') ] do_register_opts(auth_opts, 'auth', ignore_errors) # Common options (used by action runner and sensor container) action_sensor_opts = [ cfg.BoolOpt('enable', default=True, help='Whether to enable or disable the ability to post a trigger on action.'), ] do_register_opts(action_sensor_opts, group='action_sensor') # Coordination options coord_opts = [ cfg.StrOpt('url', default=None, help='Endpoint for the coordination server.'), cfg.IntOpt('lock_timeout', default=60, help='TTL for the lock if backend suports it.') ] do_register_opts(coord_opts, 'coordination', ignore_errors) # Mistral options mistral_opts = [ cfg.StrOpt('v2_base_url', default='http://127.0.0.1:8989/v2', help='v2 API root endpoint.'), cfg.IntOpt('max_attempts', default=180, help='Max attempts to reconnect.'), cfg.IntOpt('retry_wait', default=5, help='Seconds to wait before reconnecting.'), cfg.StrOpt('keystone_username', default=None, help='Username for authentication.'), cfg.StrOpt('keystone_password', default=None, help='Password for authentication.'), cfg.StrOpt('keystone_project_name', default=None, help='OpenStack project scope.'), cfg.StrOpt('keystone_auth_url', default=None, help='Auth endpoint for Keystone.') ] do_register_opts(mistral_opts, group='mistral', ignore_errors=ignore_errors) # Common CLI options debug = cfg.BoolOpt('debug', default=False, help='Enable debug mode. By default this will set all log levels to DEBUG.') profile = cfg.BoolOpt('profile', default=False, help=('Enable profile mode. In the profile mode all the MongoDB queries and related ' 'profile data are logged.')) use_debugger = cfg.BoolOpt('use-debugger', default=True, help='Enables debugger. Note that using this option changes how the ' 'eventlet library is used to support async IO. This could result in ' 'failures that do not occur under normal operation.') cli_opts = [debug, profile, use_debugger] do_register_cli_opts(cli_opts, ignore_errors=ignore_errors) def parse_args(args=None): register_opts() cfg.CONF(args=args, version=VERSION_STRING)<|fim▁end|>
help='Paths which will be searched for integration packs.')
<|file_name|>AccumulateSameValues.cpp<|end_file_name|><|fim▁begin|>/** * Yaafe extension for the Cultural Broadcasting Archive. * * Copyright (c) 2012 University of Applied Sciences Ð Institute for Creative Media Technologies * * Author : Ewald Wieser B.Sc. (fhstp.ac.at) * * Co-Authors : * Dipl.-Ing. (FH) Matthias Husinsky (fhstp.ac.at) * FH-Prof. Dipl.-Ing. Markus Seidl (fhstp.ac.at) * * Contributes to : * Dr. Klaus Seyerlehner (jku.at) * * This file is an extension for Standard-Yaafe, developed for Music * detection with the Continuous Frequency Activation Feature (CFA) for * the Cultural Broadcasting Archive (CBA). * * Yaafe is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Yaafe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AccumulateSameValues.h" #include <Eigen/Dense> using namespace Eigen; namespace YAAFE { AccumulateSameValues::AccumulateSameValues() { } AccumulateSameValues::~AccumulateSameValues() { } bool AccumulateSameValues::init(const ParameterMap& params, const Ports<StreamInfo>& inp) { assert(inp.size()==1); const StreamInfo& in = inp[0].data; outStreamInfo().add(StreamInfo(in,2)); return true; }<|fim▁hole|>{ assert(inp.size()==1); InputBuffer* in = inp[0].data; if (in->empty()) return false; assert(outp.size()==1); OutputBuffer* out = outp[0].data; double sum = 1; double* inData; while (!in->empty()) { inData = in->readToken(); if (inData[0] == inData[1]) sum++; // accumulate same values else{ double* outData = out->writeToken(); outData[0] = sum; // write values outData[1] = inData[0]; sum = 1; } in->consumeToken(); } if (sum > 1){ // write last value double* outData = out->writeToken(); outData[0] = sum-1; outData[1] = inData[0]; } return true; } }<|fim▁end|>
bool AccumulateSameValues::process(Ports<InputBuffer*>& inp, Ports<OutputBuffer*>& outp)
<|file_name|>IGenerator.ts<|end_file_name|><|fim▁begin|>module tools.generator {<|fim▁hole|> addLine(line: string): IGenerator; getLines(): string[]; } }<|fim▁end|>
export interface IGenerator {
<|file_name|>bidi_checker_web_ui_test.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h" #include "base/base_paths.h" #include "base/i18n/rtl.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/history/history_service.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "content/public/browser/browser_thread.h" #include "ui/base/resource/resource_bundle.h" #if defined(TOOLKIT_GTK) #include <gtk/gtk.h> #endif using autofill::AutofillProfile; using autofill::PersonalDataManager; static const base::FilePath::CharType* kWebUIBidiCheckerLibraryJS = FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js"); namespace { base::FilePath WebUIBidiCheckerLibraryJSPath() { base::FilePath src_root; if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root)) LOG(ERROR) << "Couldn't find source root"; return src_root.Append(kWebUIBidiCheckerLibraryJS); } // Since synchronization isn't complete for the ResourceBundle class, reload // locale resources on the IO thread. // crbug.com/95425, crbug.com/132752 void ReloadLocaleResourcesOnIOThread(const std::string& new_locale) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) { LOG(ERROR) << content::BrowserThread::IO << " != " << base::PlatformThread::CurrentId(); NOTREACHED(); } std::string locale; { base::ThreadRestrictions::ScopedAllowIO allow_io_scope; locale.assign( ResourceBundle::GetSharedInstance().ReloadLocaleResources(new_locale)); } ASSERT_FALSE(locale.empty()); } // Since synchronization isn't complete for the ResourceBundle class, reload // locale resources on the IO thread. // crbug.com/95425, crbug.com/132752 void ReloadLocaleResources(const std::string& new_locale) { content::BrowserThread::PostTaskAndReply( content::BrowserThread::IO, FROM_HERE, base::Bind(&ReloadLocaleResourcesOnIOThread, base::ConstRef(new_locale)), base::MessageLoop::QuitClosure()); content::RunMessageLoop(); } } // namespace static const base::FilePath::CharType* kBidiCheckerTestsJS = FILE_PATH_LITERAL("bidichecker_tests.js"); void WebUIBidiCheckerBrowserTest::SetUp() { argv_ = CommandLine::ForCurrentProcess()->GetArgs(); } void WebUIBidiCheckerBrowserTest::TearDown() { // Reset command line to the way it was before the test was run. CommandLine::ForCurrentProcess()->InitFromArgv(argv_); } WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {} WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {} void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() { WebUIBrowserTest::SetUpInProcessBrowserTestFixture(); WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath()); WebUIBrowserTest::AddLibrary(base::FilePath(kBidiCheckerTestsJS)); } void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage( const std::string& page_url, bool is_rtl) { ui_test_utils::NavigateToURL(browser(), GURL(page_url)); ASSERT_TRUE(RunJavascriptTest("runBidiChecker", Value::CreateStringValue(page_url), Value::CreateBooleanValue(is_rtl))); } void WebUIBidiCheckerBrowserTestLTR::RunBidiCheckerOnPage( const std::string& page_url) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(page_url, false); } void WebUIBidiCheckerBrowserTestRTL::RunBidiCheckerOnPage( const std::string& page_url) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(page_url, true); } void WebUIBidiCheckerBrowserTestRTL::SetUpOnMainThread() { WebUIBidiCheckerBrowserTest::SetUpOnMainThread(); base::FilePath pak_path; app_locale_ = base::i18n::GetConfiguredLocale(); ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path)); pak_path = pak_path.DirName(); pak_path = pak_path.AppendASCII("pseudo_locales"); pak_path = pak_path.AppendASCII("fake-bidi"); pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak")); ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path); ReloadLocaleResources("he"); base::i18n::SetICUDefaultLocale("he"); #if defined(OS_POSIX) && defined(TOOLKIT_GTK) gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL); #endif } void WebUIBidiCheckerBrowserTestRTL::CleanUpOnMainThread() { WebUIBidiCheckerBrowserTest::CleanUpOnMainThread(); #if defined(OS_POSIX) && defined(TOOLKIT_GTK) gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR); #endif base::i18n::SetICUDefaultLocale(app_locale_); ResourceBundle::GetSharedInstance().OverrideLocalePakForTest( base::FilePath()); ReloadLocaleResources(app_locale_); } // Tests //============================== // chrome://settings/history //============================== static void SetupHistoryPageTest(Browser* browser, const std::string& page_url, const std::string& page_title) { HistoryService* history_service = HistoryServiceFactory::GetForProfile( browser->profile(), Profile::IMPLICIT_ACCESS); const GURL history_url = GURL(page_url); history_service->AddPage( history_url, base::Time::Now(), history::SOURCE_BROWSED); history_service->SetPageTitle(history_url, UTF8ToUTF16(page_title)); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestHistoryPage) { // Test an Israeli news site with a Hebrew title. SetupHistoryPageTest(browser(), "http://www.ynet.co.il", "\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21"); RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestHistoryPage) { SetupHistoryPageTest(browser(), "http://www.google.com", "Google"); RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL); } //============================== // chrome://about //============================== // This page isn't localized to an RTL language so we test it only in English. IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestAboutPage) { RunBidiCheckerOnPage(chrome::kChromeUIAboutURL); } //============================== // chrome://crashes //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestCrashesPage) { RunBidiCheckerOnPage(chrome::kChromeUICrashesURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestCrashesPage) { RunBidiCheckerOnPage(chrome::kChromeUICrashesURL); } //============================== // chrome://downloads //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestDownloadsPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestDownloadsPageRTL) { RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL); } //============================== // chrome://newtab //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestNewTabPage) { RunBidiCheckerOnPage(chrome::kChromeUINewTabURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestNewTabPage) { RunBidiCheckerOnPage(chrome::kChromeUINewTabURL); } //============================== // chrome://plugins //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestPluginsPage) { RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestPluginsPage) { RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL); } //============================== // chrome://settings-frame //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsPage) { RunBidiCheckerOnPage(chrome::kChromeUISettingsFrameURL); }<|fim▁hole|> RunBidiCheckerOnPage(chrome::kChromeUISettingsFrameURL); } static void SetupSettingsAutofillPageTest(Profile* profile, const char* first_name, const char* middle_name, const char* last_name, const char* email, const char* company, const char* address1, const char* address2, const char* city, const char* state, const char* zipcode, const char* country, const char* phone) { autofill::test::DisableSystemServices(profile); AutofillProfile autofill_profile; autofill::test::SetProfileInfo(&autofill_profile, first_name, middle_name, last_name, email, company, address1, address2, city, state, zipcode, country, phone); PersonalDataManager* personal_data_manager = autofill::PersonalDataManagerFactory::GetForProfile(profile); ASSERT_TRUE(personal_data_manager); personal_data_manager->AddProfile(autofill_profile); } // http://crbug.com/94642 IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, DISABLED_TestSettingsAutofillPage) { SetupSettingsAutofillPageTest(browser()->profile(), "\xD7\x9E\xD7\xA9\xD7\x94", "\xD7\x91", "\xD7\x9B\xD7\x94\xD7\x9F", "[email protected]", "\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20" "\xD7\x91\xD7\xA2\xD7\x9E", "\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0" "\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7" "\x99\xD7\x9F\x20\x32\x33", "\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36", "\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99" "\xD7\x91", "", "66183", "\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C", "0000"); std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kAutofillSubPage); RunBidiCheckerOnPage(url); } // http://crbug.com/94642 IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, DISABLED_TestSettingsAutofillPage) { SetupSettingsAutofillPageTest(browser()->profile(), "Milton", "C.", "Waddams", "[email protected]", "Initech", "4120 Freidrich Lane", "Basement", "Austin", "Texas", "78744", "United States", "5125551234"); std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kAutofillSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsClearBrowserDataPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kClearBrowserDataSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsClearBrowserDataPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kClearBrowserDataSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsContentSettingsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kContentSettingsSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsContentSettingsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kContentSettingsSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsContentSettingsExceptionsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kContentSettingsExceptionsSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsContentSettingsExceptionsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kContentSettingsExceptionsSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsLanguageOptionsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kLanguageOptionsSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsLanguageOptionsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kLanguageOptionsSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsSearchEnginesOptionsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kSearchEnginesSubPage); RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsSearchEnginesOptionsPage) { std::string url(chrome::kChromeUISettingsFrameURL); url += std::string(chrome::kSearchEnginesSubPage); RunBidiCheckerOnPage(url); } //=================================== // chrome://settings-frame/startup //=================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameStartup) { std::string url(chrome::kChromeUISettingsFrameURL); url += "startup"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameStartup) { std::string url(chrome::kChromeUISettingsFrameURL); url += "startup"; RunBidiCheckerOnPage(url); } //=================================== // chrome://settings-frame/importData //=================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameImportData) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kImportDataSubPage; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameImportData) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kImportDataSubPage; RunBidiCheckerOnPage(url); } //======================================== // chrome://settings-frame/manageProfile //======================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameMangageProfile) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kManageProfileSubPage; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameMangageProfile) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kManageProfileSubPage; RunBidiCheckerOnPage(url); } //=================================================== // chrome://settings-frame/contentExceptions#cookies //=================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsCookies) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#cookies"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsCookies) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#cookies"; RunBidiCheckerOnPage(url); } //=================================================== // chrome://settings-frame/contentExceptions#images //=================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsImages) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#images"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsImages) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#images"; RunBidiCheckerOnPage(url); } //====================================================== // chrome://settings-frame/contentExceptions#javascript //====================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsJavascript) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#javascript"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsJavascript) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#javascript"; RunBidiCheckerOnPage(url); } //=================================================== // chrome://settings-frame/contentExceptions#plugins //=================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsPlugins) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#plugins"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsPlugins) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#plugins"; RunBidiCheckerOnPage(url); } //=================================================== // chrome://settings-frame/contentExceptions#popups //=================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsPopups) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#popups"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsPopups) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#popups"; RunBidiCheckerOnPage(url); } //=================================================== // chrome://settings-frame/contentExceptions#location //=================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsLocation) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#location"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsLocation) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#location"; RunBidiCheckerOnPage(url); } //=================================================== // chrome://settings-frame/contentExceptions#notifications //=================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsNotifications) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#notifications"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsNotifications) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#notifications"; RunBidiCheckerOnPage(url); } //=================================================== // chrome://settings-frame/contentExceptions#mouselock //=================================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameContentExceptionsMouseLock) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#mouselock"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameContentExceptionsMouseLock) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kContentSettingsExceptionsSubPage; url += "#mouselock"; RunBidiCheckerOnPage(url); } //======================================== // chrome://settings-frame/handlers //======================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameHandler) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kHandlerSettingsSubPage; RunBidiCheckerOnPage(url); } // Fails on chromeos. http://crbug.com/125367 #if defined(OS_CHROMEOS) #define MAYBE_TestSettingsFrameHandler DISABLED_TestSettingsFrameHandler #else #define MAYBE_TestSettingsFrameHandler TestSettingsFrameHandler #endif IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, MAYBE_TestSettingsFrameHandler) { std::string url(chrome::kChromeUISettingsFrameURL); url += chrome::kHandlerSettingsSubPage; RunBidiCheckerOnPage(url); } //======================================== // chrome://settings-frame/cookies //======================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFrameCookies) { std::string url(chrome::kChromeUISettingsFrameURL); url += "cookies"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameCookies) { std::string url(chrome::kChromeUISettingsFrameURL); url += "cookies"; RunBidiCheckerOnPage(url); } //======================================== // chrome://settings-frame/passwords //======================================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsFramePasswords) { std::string url(chrome::kChromeUISettingsFrameURL); url += "passwords"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFramePasswords) { std::string url(chrome::kChromeUISettingsFrameURL); url += "passwords"; RunBidiCheckerOnPage(url); } //======================================== // chrome://settings-frame/fonts //======================================== #if defined(OS_MACOSX) #define MAYBE_TestSettingsFrameFonts DISABLED_TestSettingsFrameFonts #else #define MAYBE_TestSettingsFrameFonts TestSettingsFrameFonts #endif IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, MAYBE_TestSettingsFrameFonts) { std::string url(chrome::kChromeUISettingsFrameURL); url += "fonts"; RunBidiCheckerOnPage(url); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsFrameFonts) { std::string url(chrome::kChromeUISettingsFrameURL); url += "fonts"; RunBidiCheckerOnPage(url); } // Test other uber iframes. //============================== // chrome://extensions-frame //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestExtensionsFrame) { RunBidiCheckerOnPage(chrome::kChromeUIExtensionsFrameURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestExtensionsFrame) { RunBidiCheckerOnPage(chrome::kChromeUIExtensionsFrameURL); } //============================== // chrome://help-frame //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestHelpFrame) { RunBidiCheckerOnPage(chrome::kChromeUIHelpFrameURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestHelpFrame) { RunBidiCheckerOnPage(chrome::kChromeUIHelpFrameURL); } //============================== // chrome://history-frame //============================== IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestHistoryFrame) { RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestHistoryFrame) { RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL); }<|fim▁end|>
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsPage) {
<|file_name|>creatPredictdata.py<|end_file_name|><|fim▁begin|>import glob import os import pandas as pd class CTD(object): """docstring for CTD""" def __init__(self): self.format_l = [] self.td_l = []<|fim▁hole|> def feature(self,index): format_l = self.format_l feature = ((float(format_l[index+1][1])-float(format_l[index+3][1]))/float(format_l[index+1][1]))+((float(format_l[index+1][4])-float(format_l[index+3][4]))/float(format_l[index+1][4])) if (feature == 0): feature = 0.0001 return feature def format(self,path): a = path.split('/') self.formatname = a[2] with open(path, 'r') as f: a = f.read() f = a.split('\n') f.pop(0) self.iternum = len(f)-3 for a in range(len(f)): a = f[a].split(',') a.pop(0) self.format_l.append(a) def trainData(self): for index in range(self.iternum): try: format_l = self.format_l classify = (float(format_l[index][3])-float(format_l[index+1][3]))/float(format_l[index+1][3])*100 feature = self.feature(index) a = ['0']+format_l[index+1]+format_l[index+2]+format_l[index+3]+[feature] self.td_l.append(a) except: pass def storage_csv(self): rowname=['classify','feature','1-open','1-high','1-low','1-close','1-volume','1-adj close','2-open','2-high','2-low','2-close','2-volume','2-adj close','3-open','3-high','3-low','3-close','3-volume','3-adj close'] df = pd.DataFrame(self.td_l,columns=rowname) with open('./traindata/td_'+self.formatname+'.csv', 'w') as f: df.to_csv(f) print('td_'+self.formatname+'.csv is creat!') def storage_txt(self,pathname): with open('./predict/data/'+pathname,'ab') as f: for a in self.td_l: b = str(a[0])+'\t' for c in range(1,20): d = str(c)+':'+str(a[c])+'\t' b += d f.write(b+'\n') def run(self): path = './stock/*' paths=glob.glob(path) for index,path in enumerate(paths,1): print(index) self.format_l = [] self.td_l = [] self.format(path) self.trainData() path = path.split('/') pathname = path[2] self.storage_txt(pathname) print os.popen("./bin/svm-scale -s predict_scale_model ./predict/data/"+pathname+" > ./predict/scale/"+pathname+"predict_data.scale").read() print os.popen("./bin/rvkde --best --predict --classify -v ./train/scale/"+pathname+"train_data.scale -V ./predict/scale/"+pathname+"predict_data.scale > ./predict/result/"+pathname+"predict_result").read() def main(): ctd = CTD() ctd.run() if __name__ == '__main__' : main()<|fim▁end|>
self.iternum = 0 self.formatname = ""
<|file_name|>test_v1beta1_user_info.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1beta1_user_info import V1beta1UserInfo class TestV1beta1UserInfo(unittest.TestCase): """ V1beta1UserInfo unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1beta1UserInfo(self): """ Test V1beta1UserInfo """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v1beta1_user_info.V1beta1UserInfo()<|fim▁hole|> if __name__ == '__main__': unittest.main()<|fim▁end|>
pass
<|file_name|>transforms_test.py<|end_file_name|><|fim▁begin|># # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import typing import unittest import pandas as pd import apache_beam as beam from apache_beam import coders from apache_beam.dataframe import convert from apache_beam.dataframe import expressions from apache_beam.dataframe import frame_base from apache_beam.dataframe import transforms from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to def check_correct(expected, actual): if actual is None: raise AssertionError('Empty frame but expected: \n\n%s' % (expected)) if isinstance(expected, pd.core.generic.NDFrame): expected = expected.sort_index() actual = actual.sort_index() if isinstance(expected, pd.Series): pd.testing.assert_series_equal(expected, actual) elif isinstance(expected, pd.DataFrame): pd.testing.assert_frame_equal(expected, actual) else: raise ValueError( f"Expected value is a {type(expected)}," "not a Series or DataFrame.") else: if actual != expected: raise AssertionError('Scalars not equal: %s != %s' % (actual, expected)) def concat(parts): if len(parts) > 1: return pd.concat(parts) elif len(parts) == 1: return parts[0] else: return None def df_equal_to(expected): return lambda actual: check_correct(expected, concat(actual)) AnimalSpeed = typing.NamedTuple( 'AnimalSpeed', [('Animal', str), ('Speed', int)]) coders.registry.register_coder(AnimalSpeed, coders.RowCoder) Nested = typing.NamedTuple( 'Nested', [('id', int), ('animal_speed', AnimalSpeed)]) coders.registry.register_coder(Nested, coders.RowCoder) class TransformTest(unittest.TestCase): def run_scenario(self, input, func): expected = func(input) empty = input.iloc[0:0] input_placeholder = expressions.PlaceholderExpression(empty) input_deferred = frame_base.DeferredFrame.wrap(input_placeholder) actual_deferred = func(input_deferred)._expr.evaluate_at( expressions.Session({input_placeholder: input})) check_correct(expected, actual_deferred) with beam.Pipeline() as p: input_pcoll = p | beam.Create([input.iloc[::2], input.iloc[1::2]]) input_df = convert.to_dataframe(input_pcoll, proxy=empty) output_df = func(input_df) output_proxy = output_df._expr.proxy() if isinstance(output_proxy, pd.core.generic.NDFrame): self.assertTrue( output_proxy.iloc[:0].equals(expected.iloc[:0]), ( 'Output proxy is incorrect:\n' f'Expected:\n{expected.iloc[:0]}\n\n' f'Actual:\n{output_proxy.iloc[:0]}')) else: self.assertEqual(type(output_proxy), type(expected)) output_pcoll = convert.to_pcollection(output_df, yield_elements='pandas') assert_that( output_pcoll, lambda actual: check_correct(expected, concat(actual))) def test_identity(self): df = pd.DataFrame({ 'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 'Speed': [380., 370., 24., 26.] }) self.run_scenario(df, lambda x: x) def test_groupby_sum_mean(self): df = pd.DataFrame({ 'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 'Speed': [380., 370., 24., 26.] }) self.run_scenario(df, lambda df: df.groupby('Animal').sum()) with expressions.allow_non_parallel_operations(): self.run_scenario(df, lambda df: df.groupby('Animal').mean()) self.run_scenario( df, lambda df: df.loc[df.Speed > 25].groupby('Animal').sum()) def test_groupby_apply(self): df = pd.DataFrame({ 'group': ['a' if i % 5 == 0 or i % 3 == 0 else 'b' for i in range(100)], 'foo': [None if i % 11 == 0 else i for i in range(100)], 'bar': [None if i % 7 == 0 else 99 - i for i in range(100)], 'baz': [None if i % 13 == 0 else i * 2 for i in range(100)], }) def median_sum_fn(x): return (x.foo + x.bar).median() describe = lambda df: df.describe() self.run_scenario(df, lambda df: df.groupby('group').foo.apply(describe)) self.run_scenario( df, lambda df: df.groupby('group')[['foo', 'bar']].apply(describe)) self.run_scenario(df, lambda df: df.groupby('group').apply(median_sum_fn)) self.run_scenario( df, lambda df: df.set_index('group').foo.groupby(level=0).apply(describe)) self.run_scenario(df, lambda df: df.groupby(level=0).apply(median_sum_fn)) self.run_scenario( df, lambda df: df.groupby(lambda x: x % 3).apply(describe)) def test_filter(self): df = pd.DataFrame({ 'Animal': ['Aardvark', 'Ant', 'Elephant', 'Zebra'], 'Speed': [5, 2, 35, 40] }) self.run_scenario(df, lambda df: df.filter(items=['Animal'])) self.run_scenario(df, lambda df: df.filter(regex='Anim.*')) self.run_scenario( df, lambda df: df.set_index('Animal').filter(regex='F.*', axis='index')) with expressions.allow_non_parallel_operations(): a = pd.DataFrame({'col': [1, 2, 3]}) self.run_scenario(a, lambda a: a.agg(sum)) self.run_scenario(a, lambda a: a.agg(['mean', 'min', 'max'])) def test_scalar(self): with expressions.allow_non_parallel_operations(): a = pd.Series([1, 2, 6]) self.run_scenario(a, lambda a: a.agg(sum)) self.run_scenario(a, lambda a: a / a.agg(sum)) # Tests scalar being used as an input to a downstream stage. df = pd.DataFrame({'key': ['a', 'a', 'b'], 'val': [1, 2, 6]}) self.run_scenario( df, lambda df: df.groupby('key').sum().val / df.val.agg(sum)) def test_getitem_projection(self): df = pd.DataFrame({ 'Animal': ['Aardvark', 'Ant', 'Elephant', 'Zebra'], 'Speed': [5, 2, 35, 40], 'Size': ['Small', 'Extra Small', 'Large', 'Medium'] }) self.run_scenario(df, lambda df: df[['Speed', 'Size']]) def test_offset_elementwise(self): s = pd.Series(range(10)).astype(float) df = pd.DataFrame({'value': s, 'square': s * s, 'cube': s * s * s}) # Only those values that are both squares and cubes will intersect. self.run_scenario( df, lambda df: df.set_index('square').value + df.set_index('cube').value) def test_batching_named_tuple_input(self): with beam.Pipeline() as p: result = ( p | beam.Create([ AnimalSpeed('Aardvark', 5), AnimalSpeed('Ant', 2), AnimalSpeed('Elephant', 35), AnimalSpeed('Zebra', 40) ]).with_output_types(AnimalSpeed) | transforms.DataframeTransform(lambda df: df.filter(regex='Anim.*'))) assert_that( result, equal_to([('Aardvark', ), ('Ant', ), ('Elephant', ), ('Zebra', )])) def test_batching_beam_row_input(self): with beam.Pipeline() as p: result = ( p | beam.Create([(u'Falcon', 380.), (u'Falcon', 370.), (u'Parrot', 24.), (u'Parrot', 26.)]) | beam.Map(lambda tpl: beam.Row(Animal=tpl[0], Speed=tpl[1])) | transforms.DataframeTransform( lambda df: df.groupby('Animal').mean(), include_indexes=True)) assert_that(result, equal_to([('Falcon', 375.), ('Parrot', 25.)])) def test_batching_beam_row_to_dataframe(self): with beam.Pipeline() as p: df = convert.to_dataframe( p | beam.Create([(u'Falcon', 380.), (u'Falcon', 370.), ( u'Parrot', 24.), (u'Parrot', 26.)]) | beam.Map(lambda tpl: beam.Row(Animal=tpl[0], Speed=tpl[1]))) result = convert.to_pcollection( df.groupby('Animal').mean(), include_indexes=True) assert_that(result, equal_to([('Falcon', 375.), ('Parrot', 25.)])) def test_batching_passthrough_nested_schema(self): with beam.Pipeline() as p: nested_schema_pc = ( p | beam.Create([Nested(1, AnimalSpeed('Aardvark', 5)) ]).with_output_types(Nested)) result = nested_schema_pc | transforms.DataframeTransform( # pylint: disable=expression-not-assigned lambda df: df.filter(items=['animal_speed'])) assert_that(result, equal_to([(('Aardvark', 5), )])) def test_batching_passthrough_nested_array(self): Array = typing.NamedTuple( 'Array', [('id', int), ('business_numbers', typing.Sequence[int])]) coders.registry.register_coder(Array, coders.RowCoder) with beam.Pipeline() as p: array_schema_pc = (p | beam.Create([Array(1, [7, 8, 9])])) result = array_schema_pc | transforms.DataframeTransform( # pylint: disable=expression-not-assigned lambda df: df.filter(items=['business_numbers'])) assert_that(result, equal_to([([7, 8, 9], )])) def test_unbatching_series(self): with beam.Pipeline() as p: result = ( p | beam.Create([(u'Falcon', 380.), (u'Falcon', 370.), (u'Parrot', 24.), (u'Parrot', 26.)]) | beam.Map(lambda tpl: beam.Row(Animal=tpl[0], Speed=tpl[1])) | transforms.DataframeTransform(lambda df: df.Animal)) assert_that(result, equal_to(['Falcon', 'Falcon', 'Parrot', 'Parrot'])) def test_input_output_polymorphism(self): one_series = pd.Series([1]) two_series = pd.Series([2]) three_series = pd.Series([3]) proxy = one_series[:0] def equal_to_series(expected): def check(actual): actual = pd.concat(actual) if not expected.equals(actual): raise AssertionError( 'Series not equal: \n%s\n%s\n' % (expected, actual)) return check with beam.Pipeline() as p: one = p | 'One' >> beam.Create([one_series]) two = p | 'Two' >> beam.Create([two_series]) assert_that( one | 'PcollInPcollOut' >> transforms.DataframeTransform( lambda x: 3 * x, proxy=proxy, yield_elements='pandas'), equal_to_series(three_series), label='CheckPcollInPcollOut') assert_that( (one, two) | 'TupleIn' >> transforms.DataframeTransform( lambda x, y: (x + y), (proxy, proxy), yield_elements='pandas'), equal_to_series(three_series), label='CheckTupleIn') assert_that( dict(x=one, y=two) | 'DictIn' >> transforms.DataframeTransform( lambda x, y: (x + y), proxy=dict(x=proxy, y=proxy), yield_elements='pandas'), equal_to_series(three_series), label='CheckDictIn') double, triple = one | 'TupleOut' >> transforms.DataframeTransform( lambda x: (2*x, 3*x), proxy, yield_elements='pandas') assert_that(double, equal_to_series(two_series), 'CheckTupleOut0') assert_that(triple, equal_to_series(three_series), 'CheckTupleOut1') res = one | 'DictOut' >> transforms.DataframeTransform( lambda x: {'res': 3 * x}, proxy, yield_elements='pandas') assert_that(res['res'], equal_to_series(three_series), 'CheckDictOut') def test_cat(self): # verify that cat works with a List[Series] since this is # missing from doctests df = pd.DataFrame({ 'one': ['A', 'B', 'C'], 'two': ['BB', 'CC', 'A'], 'three': ['CCC', 'AA', 'B'], })<|fim▁hole|> self.run_scenario( df, lambda df: df.one.str.cat([df.two, df.three], join='outer')) def test_repeat(self): # verify that repeat works with a Series since this is # missing from doctests df = pd.DataFrame({ 'strings': ['A', 'B', 'C', 'D', 'E'], 'repeats': [3, 1, 4, 5, 2], }) self.run_scenario(df, lambda df: df.strings.str.repeat(df.repeats)) def test_rename(self): df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) self.run_scenario( df, lambda df: df.rename(columns={'B': 'C'}, index={ 0: 2, 2: 0 })) with expressions.allow_non_parallel_operations(): self.run_scenario( df, lambda df: df.rename( columns={'B': 'C'}, index={ 0: 2, 2: 0 }, errors='raise')) class TransformPartsTest(unittest.TestCase): def test_rebatch(self): with beam.Pipeline() as p: sA = pd.Series(range(1000)) sB = sA * sA pcA = p | 'CreatePCollA' >> beam.Create([('k0', sA[::3]), ('k1', sA[1::3]), ('k2', sA[2::3])]) pcB = p | 'CreatePCollB' >> beam.Create([('k0', sB[::3]), ('k1', sB[1::3]), ('k2', sB[2::3])]) input = {'A': pcA, 'B': pcB} | beam.CoGroupByKey() output = input | beam.ParDo( transforms._ReBatch(target_size=sA.memory_usage())) # There should be exactly two elements, as the target size will be # hit when 2/3 of pcA and 2/3 of pcB is seen, but not before. assert_that(output | beam.combiners.Count.Globally(), equal_to([2])) # Sanity check that we got all the right values. assert_that( output | beam.Map(lambda x: x['A'].sum()) | 'SumA' >> beam.CombineGlobally(sum), equal_to([sA.sum()]), label='CheckValuesA') assert_that( output | beam.Map(lambda x: x['B'].sum()) | 'SumB' >> beam.CombineGlobally(sum), equal_to([sB.sum()]), label='CheckValuesB') if __name__ == '__main__': unittest.main()<|fim▁end|>
self.run_scenario(df, lambda df: df.two.str.cat([df.three], join='outer'))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from typing import Any, Dict, Tuple, Union __cached_defs: Dict[str, Any] = {} def __getattr__(name: str) -> Any: import importlib # noqa # isort:skip if name in __cached_defs: return __cached_defs[name] if name == "JsonBase": module = importlib.import_module(".json_base", "tomodachi.envelope") elif name == "ProtobufBase": try: module = importlib.import_module(".protobuf_base", "tomodachi.envelope") except Exception: # pragma: no cover class ProtobufBase(object): @classmethod def validate(cls, **kwargs: Any) -> None: raise Exception("google.protobuf package not installed") @classmethod async def build_message(cls, service: Any, topic: str, data: Any, **kwargs: Any) -> str: raise Exception("google.protobuf package not installed") @classmethod async def parse_message( cls, payload: str, proto_class: Any = None, validator: Any = None, **kwargs: Any ) -> Union[Dict, Tuple]: raise Exception("google.protobuf package not installed") __cached_defs[name] = ProtobufBase return __cached_defs[name] else: raise AttributeError("module 'tomodachi.envelope' has no attribute '{}'".format(name)) __cached_defs[name] = getattr(module, name)<|fim▁hole|><|fim▁end|>
return __cached_defs[name] __all__ = ["JsonBase", "ProtobufBase"]
<|file_name|>device_recovery.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env vpython # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A script to recover devices in a known bad state.""" import argparse import glob import logging import os import signal import sys import psutil if __name__ == '__main__': sys.path.append( os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', '..'))) from devil.android import device_denylist from devil.android import device_errors from devil.android import device_utils from devil.android.sdk import adb_wrapper from devil.android.tools import device_status from devil.android.tools import script_common from devil.utils import logging_common from devil.utils import lsusb # TODO(jbudorick): Resolve this after experimenting w/ disabling the USB reset. from devil.utils import reset_usb # pylint: disable=unused-import logger = logging.getLogger(__name__) from py_utils import modules_util # Script depends on features from psutil version 2.0 or higher. modules_util.RequireVersion(psutil, '2.0') def KillAllAdb(): def get_all_adb(): for p in psutil.process_iter(): try: # Retrieve all required process infos at once. pinfo = p.as_dict(attrs=['pid', 'name', 'cmdline']) if pinfo['name'] == 'adb': pinfo['cmdline'] = ' '.join(pinfo['cmdline']) yield p, pinfo except (psutil.NoSuchProcess, psutil.AccessDenied): pass for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL]: for p, pinfo in get_all_adb(): try: pinfo['signal'] = sig logger.info('kill %(signal)s %(pid)s (%(name)s [%(cmdline)s])', pinfo) p.send_signal(sig) except (psutil.NoSuchProcess, psutil.AccessDenied): pass for _, pinfo in get_all_adb(): try: logger.error('Unable to kill %(pid)s (%(name)s [%(cmdline)s])', pinfo) except (psutil.NoSuchProcess, psutil.AccessDenied): pass def TryAuth(device): """Uses anything in ~/.android/ that looks like a key to auth with the device. Args: device: The DeviceUtils device to attempt to auth. Returns: True if device successfully authed. """ possible_keys = glob.glob(os.path.join(adb_wrapper.ADB_HOST_KEYS_DIR, '*key')) if len(possible_keys) <= 1:<|fim▁hole|> logger.warning('Only %d ADB keys available. Not forcing auth.', len(possible_keys)) return False KillAllAdb() adb_wrapper.AdbWrapper.StartServer(keys=possible_keys) new_state = device.adb.GetState() if new_state != 'device': logger.error('Auth failed. Device %s still stuck in %s.', str(device), new_state) return False # It worked! Now register the host's default ADB key on the device so we don't # have to do all that again. pub_key = os.path.join(adb_wrapper.ADB_HOST_KEYS_DIR, 'adbkey.pub') if not os.path.exists(pub_key): # This really shouldn't happen. logger.error('Default ADB key not available at %s.', pub_key) return False with open(pub_key) as f: pub_key_contents = f.read() try: device.WriteFile(adb_wrapper.ADB_KEYS_FILE, pub_key_contents, as_root=True) except (device_errors.CommandTimeoutError, device_errors.CommandFailedError, device_errors.DeviceUnreachableError): logger.exception('Unable to write default ADB key to %s.', str(device)) return False return True def RecoverDevice(device, denylist, should_reboot=lambda device: True): if device_status.IsDenylisted(device.adb.GetDeviceSerial(), denylist): logger.debug('%s is denylisted, skipping recovery.', str(device)) return if device.adb.GetState() == 'unauthorized' and TryAuth(device): logger.info('Successfully authed device %s!', str(device)) return if should_reboot(device): should_restore_root = device.HasRoot() try: device.WaitUntilFullyBooted(retries=0) except (device_errors.CommandTimeoutError, device_errors.CommandFailedError, device_errors.DeviceUnreachableError): logger.exception( 'Failure while waiting for %s. ' 'Attempting to recover.', str(device)) try: try: device.Reboot(block=False, timeout=5, retries=0) except device_errors.CommandTimeoutError: logger.warning( 'Timed out while attempting to reboot %s normally.' 'Attempting alternative reboot.', str(device)) # The device drops offline before we can grab the exit code, so # we don't check for status. try: device.adb.Root() finally: # We are already in a failure mode, attempt to reboot regardless of # what device.adb.Root() returns. If the sysrq reboot fails an # exception willbe thrown at that level. device.adb.Shell( 'echo b > /proc/sysrq-trigger', expect_status=None, timeout=5, retries=0) except (device_errors.CommandFailedError, device_errors.DeviceUnreachableError): logger.exception('Failed to reboot %s.', str(device)) if denylist: denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_failure') except device_errors.CommandTimeoutError: logger.exception('Timed out while rebooting %s.', str(device)) if denylist: denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_timeout') try: device.WaitUntilFullyBooted( retries=0, timeout=device.REBOOT_DEFAULT_TIMEOUT) if should_restore_root: device.EnableRoot() except (device_errors.CommandFailedError, device_errors.DeviceUnreachableError): logger.exception('Failure while waiting for %s.', str(device)) if denylist: denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_failure') except device_errors.CommandTimeoutError: logger.exception('Timed out while waiting for %s.', str(device)) if denylist: denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_timeout') def RecoverDevices(devices, denylist, enable_usb_reset=False): """Attempts to recover any inoperable devices in the provided list. Args: devices: The list of devices to attempt to recover. denylist: The current device denylist, which will be used then reset. """ statuses = device_status.DeviceStatus(devices, denylist) should_restart_usb = set( status['serial'] for status in statuses if (not status['usb_status'] or status['adb_status'] in ('offline', 'missing'))) should_restart_adb = should_restart_usb.union( set(status['serial'] for status in statuses if status['adb_status'] == 'unauthorized')) should_reboot_device = should_restart_usb.union( set(status['serial'] for status in statuses if status['denylisted'])) logger.debug('Should restart USB for:') for d in should_restart_usb: logger.debug(' %s', d) logger.debug('Should restart ADB for:') for d in should_restart_adb: logger.debug(' %s', d) logger.debug('Should reboot:') for d in should_reboot_device: logger.debug(' %s', d) if denylist: denylist.Reset() if should_restart_adb: KillAllAdb() adb_wrapper.AdbWrapper.StartServer() for serial in should_restart_usb: try: # TODO(crbug.com/642194): Resetting may be causing more harm # (specifically, kernel panics) than it does good. if enable_usb_reset: reset_usb.reset_android_usb(serial) else: logger.warning('USB reset disabled for %s (crbug.com/642914)', serial) except IOError: logger.exception('Unable to reset USB for %s.', serial) if denylist: denylist.Extend([serial], reason='USB failure') except device_errors.DeviceUnreachableError: logger.exception('Unable to reset USB for %s.', serial) if denylist: denylist.Extend([serial], reason='offline') device_utils.DeviceUtils.parallel(devices).pMap( RecoverDevice, denylist, should_reboot=lambda device: device.serial in should_reboot_device) def main(): parser = argparse.ArgumentParser() logging_common.AddLoggingArguments(parser) script_common.AddEnvironmentArguments(parser) parser.add_argument('--denylist-file', help='Device denylist JSON file.') parser.add_argument( '--known-devices-file', action='append', default=[], dest='known_devices_files', help='Path to known device lists.') parser.add_argument( '--enable-usb-reset', action='store_true', help='Reset USB if necessary.') args = parser.parse_args() logging_common.InitializeLogging(args) script_common.InitializeEnvironment(args) denylist = (device_denylist.Denylist(args.denylist_file) if args.denylist_file else None) expected_devices = device_status.GetExpectedDevices(args.known_devices_files) usb_devices = set(lsusb.get_android_devices()) devices = [ device_utils.DeviceUtils(s) for s in expected_devices.union(usb_devices) ] RecoverDevices(devices, denylist, enable_usb_reset=args.enable_usb_reset) if __name__ == '__main__': sys.exit(main())<|fim▁end|>
<|file_name|>insert_test.js<|end_file_name|><|fim▁begin|>var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); var testCase = require('../deps/nodeunit').testCase, debug = require('util').debug, inspect = require('util').inspect, nodeunit = require('../deps/nodeunit'), gleak = require('../tools/gleak'), Db = mongodb.Db, Cursor = mongodb.Cursor, Script = require('vm'), Collection = mongodb.Collection, Server = mongodb.Server, Step = require("../deps/step/lib/step"), ServerManager = require('./tools/server_manager').ServerManager; var MONGODB = 'integration_tests'; var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); /** * Module for parsing an ISO 8601 formatted string into a Date object. */ var ISODate = function (string) { var match; if (typeof string.getTime === "function") return string; else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { var date = new Date(); date.setUTCFullYear(Number(match[1])); date.setUTCMonth(Number(match[3]) - 1 || 0); date.setUTCDate(Number(match[5]) || 0); date.setUTCHours(Number(match[7]) || 0); date.setUTCMinutes(Number(match[8]) || 0); date.setUTCSeconds(Number(match[10]) || 0); date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); if (match[13] && match[13] !== "Z") { var h = Number(match[16]) || 0, m = Number(match[17]) || 0; h *= 3600000; m *= 60000; var offset = h + m; if (match[15] == "+") offset = -offset; new Date(date.valueOf() + offset); } return date; } else throw new Error("Invalid ISO 8601 date given.", __filename); }; // Define the tests, we want them to run as a nested test so we only clean up the // db connection once var tests = testCase({ setUp: function(callback) { client.open(function(err, db_p) { if(numberOfTestsRun == Object.keys(tests).length) { // If first test drop the db client.dropDatabase(function(err, done) { callback(); }); } else { return callback(); } }); }, tearDown: function(callback) { numberOfTestsRun = numberOfTestsRun - 1; // Drop the database and close it if(numberOfTestsRun <= 0) { // client.dropDatabase(function(err, done) { // Close the client client.close(); callback(); // }); } else { client.close(); callback(); } }, shouldForceMongoDbServerToAssignId : function(test) { /// Set up server with custom pk factory var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null), 'forceServerObjectId':true}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.open(function(err, client) { client.createCollection('test_insert2', function(err, r) { client.collection('test_insert2', function(err, collection) { Step( function inserts() { var group = this.group(); for(var i = 1; i < 1000; i++) { collection.insert({c:i}, {safe:true}, group()); } }, function done(err, result) { collection.insert({a:2}, {safe:true}, function(err, r) { collection.insert({a:3}, {safe:true}, function(err, r) { collection.count(function(err, count) { test.equal(1001, count); // Locate all the entries using find collection.find(function(err, cursor) { cursor.toArray(function(err, results) { test.equal(1001, results.length); test.ok(results[0] != null); client.close(); // Let's close the db test.done(); }); }); }); }); }); } ) }); }); }); }, shouldCorrectlyPerformSingleInsert : function(test) { client.createCollection('shouldCorrectlyPerformSingleInsert', function(err, collection) { collection.insert({a:1}, {safe:true}, function(err, result) { collection.findOne(function(err, item) { test.equal(1, item.a); test.done(); }) }) }) }, shouldCorrectlyPerformBasicInsert : function(test) { client.createCollection('test_insert', function(err, r) { client.collection('test_insert', function(err, collection) { Step( function inserts() { var group = this.group(); for(var i = 1; i < 1000; i++) { collection.insert({c:i}, {safe:true}, group()); } }, function done(err, result) { collection.insert({a:2}, {safe:true}, function(err, r) { collection.insert({a:3}, {safe:true}, function(err, r) { collection.count(function(err, count) { test.equal(1001, count); // Locate all the entries using find collection.find(function(err, cursor) { cursor.toArray(function(err, results) { test.equal(1001, results.length); test.ok(results[0] != null); // Let's close the db test.done(); }); }); }); }); }); } ) }); }); }, // Test multiple document insert shouldCorrectlyHandleMultipleDocumentInsert : function(test) { client.createCollection('test_multiple_insert', function(err, r) { var collection = client.collection('test_multiple_insert', function(err, collection) { var docs = [{a:1}, {a:2}]; collection.insert(docs, {safe:true}, function(err, ids) { ids.forEach(function(doc) { test.ok(((doc['_id']) instanceof client.bson_serializer.ObjectID || Object.prototype.toString.call(doc['_id']) === '[object ObjectID]')); }); // Let's ensure we have both documents collection.find(function(err, cursor) { cursor.toArray(function(err, docs) { test.equal(2, docs.length); var results = []; // Check that we have all the results we want docs.forEach(function(doc) { if(doc.a == 1 || doc.a == 2) results.push(1); }); test.equal(2, results.length); // Let's close the db test.done(); }); }); }); }); }); }, shouldCorrectlyExecuteSaveInsertUpdate: function(test) { client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { collection.save({ email : 'save' }, {safe:true}, function() { collection.insert({ email : 'insert' }, {safe:true}, function() { collection.update( { email : 'update' }, { email : 'update' }, { upsert: true, safe:true}, function() { collection.find(function(e, c) { c.toArray(function(e, a) { test.equal(3, a.length) test.done(); }); }); } ); }); }); }); }, shouldCorrectlyInsertAndRetrieveLargeIntegratedArrayDocument : function(test) { client.createCollection('test_should_deserialize_large_integrated_array', function(err, collection) { var doc = {'a':0, 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] }; // Insert the collection collection.insert(doc, {safe:true}, function(err, r) { // Fetch and check the collection collection.findOne({'a': 0}, function(err, result) { test.deepEqual(doc.a, result.a); test.deepEqual(doc.b, result.b); test.done(); }); }); }); }, shouldCorrectlyInsertAndRetrieveDocumentWithAllTypes : function(test) { client.createCollection('test_all_serialization_types', function(err, collection) { var date = new Date(); var oid = new client.bson_serializer.ObjectID(); var string = 'binstring' var bin = new client.bson_serializer.Binary() for(var index = 0; index < string.length; index++) { bin.put(string.charAt(index)) } var motherOfAllDocuments = { 'string': 'hello', 'array': [1,2,3], 'hash': {'a':1, 'b':2}, 'date': date, 'oid': oid, 'binary': bin, 'int': 42, 'float': 33.3333, 'regexp': /regexp/, 'boolean': true, 'long': date.getTime(), 'where': new client.bson_serializer.Code('this.a > i', {i:1}), 'dbref': new client.bson_serializer.DBRef('namespace', oid, 'integration_tests_') } collection.insert(motherOfAllDocuments, {safe:true}, function(err, docs) { collection.findOne(function(err, doc) { // Assert correct deserialization of the values test.equal(motherOfAllDocuments.string, doc.string); test.deepEqual(motherOfAllDocuments.array, doc.array); test.equal(motherOfAllDocuments.hash.a, doc.hash.a); test.equal(motherOfAllDocuments.hash.b, doc.hash.b); test.equal(date.getTime(), doc.long); test.equal(date.toString(), doc.date.toString()); test.equal(date.getTime(), doc.date.getTime()); test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); test.equal(motherOfAllDocuments.int, doc.int); test.equal(motherOfAllDocuments.long, doc.long); test.equal(motherOfAllDocuments.float, doc.float); test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); test.equal(motherOfAllDocuments.boolean, doc.boolean); test.equal(motherOfAllDocuments.where.code, doc.where.code); test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); test.done(); }) }); }); }, shouldCorrectlyInsertAndUpdateDocumentWithNewScriptContext: function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, db) { //convience curried handler for functions of type 'a -> (err, result) function getResult(callback){ return function(error, result) { test.ok(error == null); return callback(result); } }; db.collection('users', getResult(function(user_collection){ user_collection.remove({}, {safe:true}, function(err, result) { //first, create a user object var newUser = { name : 'Test Account', settings : {} }; user_collection.insert([newUser], {safe:true}, getResult(function(users){ var user = users[0]; var scriptCode = "settings.block = []; settings.block.push('test');"; var context = { settings : { thisOneWorks : "somestring" } }; Script.runInNewContext(scriptCode, context, "testScript"); //now create update command and issue it var updateCommand = { $set : context }; user_collection.update({_id : user._id}, updateCommand, {safe:true}, getResult(function(updateCommand) { // Fetch the object and check that the changes are persisted user_collection.findOne({_id : user._id}, function(err, doc) { test.ok(err == null); test.equal("Test Account", doc.name); test.equal("somestring", doc.settings.thisOneWorks); test.equal("test", doc.settings.block[0]); // Let's close the db db.close(); test.done(); }); }) ); })); }); })); }); }, shouldCorrectlySerializeDocumentWithAllTypesInNewContext : function(test) { client.createCollection('test_all_serialization_types_new_context', function(err, collection) { var date = new Date(); var scriptCode = "var string = 'binstring'\n" + "var bin = new mongo.Binary()\n" + "for(var index = 0; index < string.length; index++) {\n" + " bin.put(string.charAt(index))\n" + "}\n" + "motherOfAllDocuments['string'] = 'hello';" + "motherOfAllDocuments['array'] = [1,2,3];" + "motherOfAllDocuments['hash'] = {'a':1, 'b':2};" + "motherOfAllDocuments['date'] = date;" + "motherOfAllDocuments['oid'] = new mongo.ObjectID();" + "motherOfAllDocuments['binary'] = bin;" + "motherOfAllDocuments['int'] = 42;" + "motherOfAllDocuments['float'] = 33.3333;" + "motherOfAllDocuments['regexp'] = /regexp/;" + "motherOfAllDocuments['boolean'] = true;" + "motherOfAllDocuments['long'] = motherOfAllDocuments['date'].getTime();" + "motherOfAllDocuments['where'] = new mongo.Code('this.a > i', {i:1});" + "motherOfAllDocuments['dbref'] = new mongo.DBRef('namespace', motherOfAllDocuments['oid'], 'integration_tests_');"; var context = { motherOfAllDocuments : {}, mongo:client.bson_serializer, date:date}; // Execute function in context Script.runInNewContext(scriptCode, context, "testScript"); // sys.puts(sys.inspect(context.motherOfAllDocuments)) var motherOfAllDocuments = context.motherOfAllDocuments; collection.insert(context.motherOfAllDocuments, {safe:true}, function(err, docs) { collection.findOne(function(err, doc) { // Assert correct deserialization of the values test.equal(motherOfAllDocuments.string, doc.string); test.deepEqual(motherOfAllDocuments.array, doc.array); test.equal(motherOfAllDocuments.hash.a, doc.hash.a); test.equal(motherOfAllDocuments.hash.b, doc.hash.b); test.equal(date.getTime(), doc.long); test.equal(date.toString(), doc.date.toString()); test.equal(date.getTime(), doc.date.getTime()); test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); test.equal(motherOfAllDocuments.int, doc.int); test.equal(motherOfAllDocuments.long, doc.long); test.equal(motherOfAllDocuments.float, doc.float); test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); test.equal(motherOfAllDocuments.boolean, doc.boolean); test.equal(motherOfAllDocuments.where.code, doc.where.code); test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); test.done(); }) }); }); }, shouldCorrectlyDoToJsonForLongValue : function(test) { client.createCollection('test_to_json_for_long', function(err, collection) { test.ok(collection instanceof Collection); collection.insertAll([{value: client.bson_serializer.Long.fromNumber(32222432)}], {safe:true}, function(err, ids) { collection.findOne({}, function(err, item) { test.equal(32222432, item.value); test.done(); }); }); }); }, shouldCorrectlyInsertAndUpdateWithNoCallback : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, client) { client.createCollection('test_insert_and_update_no_callback', function(err, collection) { // Insert the update collection.insert({i:1}, {safe:true}) // Update the record collection.update({i:1}, {"$set":{i:2}}, {safe:true}) // Make sure we leave enough time for mongodb to record the data setTimeout(function() { // Locate document collection.findOne({}, function(err, item) { test.equal(2, item.i) client.close(); test.done(); }); }, 100) }) }); }, shouldInsertAndQueryTimestamp : function(test) { client.createCollection('test_insert_and_query_timestamp', function(err, collection) { // Insert the update collection.insert({i:client.bson_serializer.Timestamp.fromNumber(100), j:client.bson_serializer.Long.fromNumber(200)}, {safe:true}, function(err, r) { // Locate document collection.findOne({}, function(err, item) { test.ok(item.i instanceof client.bson_serializer.Timestamp); test.equal(100, item.i); test.ok(typeof item.j == "number"); test.equal(200, item.j); test.done(); }); }) }) }, shouldCorrectlyInsertAndQueryUndefined : function(test) { client.createCollection('test_insert_and_query_undefined', function(err, collection) { // Insert the update collection.insert({i:undefined}, {safe:true}, function(err, r) { // Locate document collection.findOne({}, function(err, item) { test.equal(null, item.i) test.done(); }); }) }) }, shouldCorrectlySerializeDBRefToJSON : function(test) { var dbref = new client.bson_serializer.DBRef("foo", client.bson_serializer.ObjectID.createFromHexString("fc24a04d4560531f00000000"), null); JSON.stringify(dbref); test.done(); }, shouldCorrectlyPerformSafeInsert : function(test) { var fixtures = [{ name: "empty", array: [], bool: false, dict: {}, float: 0.0, string: "" }, { name: "not empty", array: [1], bool: true, dict: {x: "y"}, float: 1.0, string: "something" }, { name: "simple nested", array: [1, [2, [3]]], bool: true, dict: {x: "y", array: [1,2,3,4], dict: {x: "y", array: [1,2,3,4]}}, float: 1.5, string: "something simply nested" }]; client.createCollection('test_safe_insert', function(err, collection) { Step( function inserts() { var group = this.group(); for(var i = 0; i < fixtures.length; i++) { collection.insert(fixtures[i], {safe:true}, group()); } }, function done() { collection.count(function(err, count) { test.equal(3, count); collection.find().toArray(function(err, docs) { test.equal(3, docs.length) }); }); collection.find({}, {}, function(err, cursor) { var counter = 0; cursor.each(function(err, doc) { if(doc == null) { test.equal(3, counter); test.done(); } else { counter = counter + 1; } }); }); } ) }) }, shouldThrowErrorIfSerializingFunction : function(test) { client.createCollection('test_should_throw_error_if_serializing_function', function(err, collection) { var func = function() { return 1}; // Insert the update collection.insert({i:1, z:func }, {safe:true}, function(err, result) { collection.findOne({_id:result[0]._id}, function(err, object) { test.equal(func.toString(), object.z.code); test.equal(1, object.i); test.done(); }) }) }) }, shouldCorrectlyInsertDocumentWithUUID : function(test) { client.collection("insert_doc_with_uuid", function(err, collection) { collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { test.equal(null, err); collection.find({_id : "12345678123456781234567812345678"}).toArray(function(err, items) { test.equal(null, err); test.equal(items[0]._id, "12345678123456781234567812345678") test.equal(items[0].field, '1') // Generate a binary id var binaryUUID = new client.bson_serializer.Binary('00000078123456781234567812345678', client.bson_serializer.BSON.BSON_BINARY_SUBTYPE_UUID); collection.insert({_id : binaryUUID, field: '2'}, {safe:true}, function(err, result) { collection.find({_id : binaryUUID}).toArray(function(err, items) { test.equal(null, err); test.equal(items[0].field, '2') test.done(); }); }); }) }); }); }, shouldCorrectlyCallCallbackWithDbDriverInStrictMode : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, client) { client.createCollection('test_insert_and_update_no_callback_strict', function(err, collection) { collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { test.equal(null, err); collection.update({ '_id': "12345678123456781234567812345678" }, { '$set': { 'field': 0 }}, function(err, numberOfUpdates) { test.equal(null, err); test.equal(1, numberOfUpdates); db.close(); test.done(); }); }); }); }); }, shouldCorrectlyInsertDBRefWithDbNotDefined : function(test) { client.createCollection('shouldCorrectlyInsertDBRefWithDbNotDefined', function(err, collection) { var doc = {_id: new client.bson_serializer.ObjectID()}; var doc2 = {_id: new client.bson_serializer.ObjectID()}; var doc3 = {_id: new client.bson_serializer.ObjectID()}; collection.insert(doc, {safe:true}, function(err, result) { // Create object with dbref doc2.ref = new client.bson_serializer.DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id); doc3.ref = new client.bson_serializer.DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id, MONGODB); collection.insert([doc2, doc3], {safe:true}, function(err, result) { // Get all items collection.find().toArray(function(err, items) { test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[1].ref.namespace); test.equal(doc._id.toString(), items[1].ref.oid.toString()); test.equal(null, items[1].ref.db); test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[2].ref.namespace); test.equal(doc._id.toString(), items[2].ref.oid.toString()); test.equal(MONGODB, items[2].ref.db); test.done(); }) }); }); }); }, shouldCorrectlyInsertUpdateRemoveWithNoOptions : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, db) { db.collection('shouldCorrectlyInsertUpdateRemoveWithNoOptions', function(err, collection) { collection.insert({a:1});//, function(err, result) { collection.update({a:1}, {a:2});//, function(err, result) { collection.remove({a:2});//, function(err, result) { collection.count(function(err, count) { test.equal(0, count); db.close(); test.done(); }) }); }); }, shouldCorrectlyExecuteMultipleFetches : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; // Search parameter var to = 'ralph' // Execute query db.open(function(err, db) { db.collection('shouldCorrectlyExecuteMultipleFetches', function(err, collection) { collection.insert({addresses:{localPart:'ralph'}}, {safe:true}, function(err, result) { <|fim▁hole|> collection.findOne({"addresses.localPart" : to}, function( err, doc ) { test.equal(null, err); test.equal(to, doc.addresses.localPart); db.close(); test.done(); }); }); }); }); }, shouldCorrectlyFailWhenNoObjectToUpdate: function(test) { client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { collection.update({_id : new client.bson_serializer.ObjectID()}, { email : 'update' }, {safe:true}, function(err, result) { test.equal(0, result); test.done(); } ); }); }, 'Should correctly insert object and retrieve it when containing array and IsoDate' : function(test) { var doc = { "_id" : new client.bson_serializer.ObjectID("4e886e687ff7ef5e00000162"), "str" : "foreign", "type" : 2, "timestamp" : ISODate("2011-10-02T14:00:08.383Z"), "links" : [ "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" ] } client.createCollection('Should_correctly_insert_object_and_retrieve_it_when_containing_array_and_IsoDate', function(err, collection) { collection.insert(doc, {safe:true}, function(err, result) { test.ok(err == null); collection.findOne(function(err, item) { test.ok(err == null); test.deepEqual(doc, item); test.done(); }); }); }); }, 'Should correctly insert object with timestamps' : function(test) { var doc = { "_id" : new client.bson_serializer.ObjectID("4e886e687ff7ef5e00000162"), "str" : "foreign", "type" : 2, "timestamp" : new client.bson_serializer.Timestamp(10000), "links" : [ "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" ], "timestamp2" : new client.bson_serializer.Timestamp(33333), } client.createCollection('Should_correctly_insert_object_with_timestamps', function(err, collection) { collection.insert(doc, {safe:true}, function(err, result) { test.ok(err == null); collection.findOne(function(err, item) { test.ok(err == null); test.deepEqual(doc, item); test.done(); }); }); }); }, noGlobalsLeaked : function(test) { var leaks = gleak.detectNew(); test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); test.done(); } }) // Stupid freaking workaround due to there being no way to run setup once for each suite var numberOfTestsRun = Object.keys(tests).length; // Assign out tests module.exports = tests;<|fim▁end|>
// Let's find our user
<|file_name|>index.js<|end_file_name|><|fim▁begin|>var path = require('path') module.exports = { // Webpack aliases aliases: { quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'),<|fim▁hole|> components: path.resolve(__dirname, '../src/components') }, // Progress Bar Webpack plugin format // https://github.com/clessg/progress-bar-webpack-plugin#options progressFormat: ' [:bar] ' + ':percent'.bold + ' (:msg)', // Default theme to build with ('ios' or 'mat') defaultTheme: 'mat', build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), publicPath: '', productionSourceMap: false, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./dev.env'), cssSourceMap: true, // auto open browser or not openBrowser: true, publicPath: '/', port: 8081, // If for example you are using Quasar Play // to generate a QR code then on each dev (re)compilation // you need to avoid clearing out the console, so set this // to "false", otherwise you can set it to "true" to always // have only the messages regarding your last (re)compilation. clearConsoleOnRebuild: false, // Proxy your API if using any. // Also see /build/script.dev.js and search for "proxy api requests" // https://github.com/chimurai/http-proxy-middleware proxyTable: {} } } /* * proxyTable example: * proxyTable: { // proxy all requests starting with /api '/api': { target: 'https://some.address.com/api', changeOrigin: true, pathRewrite: { '^/api': '' } } } */<|fim▁end|>
src: path.resolve(__dirname, '../src'), assets: path.resolve(__dirname, '../src/assets'),
<|file_name|>update_instances_utils.py<|end_file_name|><|fim▁begin|># Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for the instance-groups managed update-instances commands.""" import re from googlecloudsdk.calliope import exceptions STANDBY_NAME = 'standby' TARGET_SIZE_NAME = 'target-size' TEMPLATE_NAME = 'template' def _ParseFixed(fixed_or_percent_str): """Retrieves int value from string.""" if re.match(r'^\d+$', fixed_or_percent_str): return int(fixed_or_percent_str) return None <|fim▁hole|>def _ParsePercent(fixed_or_percent_str): """Retrieves percent value from string.""" if re.match(r'^\d+%$', fixed_or_percent_str): percent = int(fixed_or_percent_str[:-1]) return percent return None def ParseFixedOrPercent(flag_name, flag_param_name, fixed_or_percent_str, messages): """Retrieves value: number or percent. Args: flag_name: name of the flag associated with the parsed string. flag_param_name: name of the inner parameter of the flag. fixed_or_percent_str: string containing fixed or percent value. messages: module containing message classes. Returns: FixedOrPercent message object. """ if fixed_or_percent_str is None: return None fixed = _ParseFixed(fixed_or_percent_str) if fixed is not None: return messages.FixedOrPercent(fixed=fixed) percent = _ParsePercent(fixed_or_percent_str) if percent is not None: if percent > 100: raise exceptions.InvalidArgumentException( flag_name, 'percentage cannot be higher than 100%.') return messages.FixedOrPercent(percent=percent) raise exceptions.InvalidArgumentException( flag_name, flag_param_name + ' has to be non-negative integer number or percent.') def ParseUpdatePolicyType(flag_name, policy_type_str, messages): """Retrieves value of update policy type: opportunistic or proactive. Args: flag_name: name of the flag associated with the parsed string. policy_type_str: string containing update policy type. messages: module containing message classes. Returns: InstanceGroupManagerUpdatePolicy.TypeValueValuesEnum message enum value. """ if policy_type_str == 'opportunistic': return (messages.InstanceGroupManagerUpdatePolicy .TypeValueValuesEnum.OPPORTUNISTIC) elif policy_type_str == 'proactive': return (messages.InstanceGroupManagerUpdatePolicy .TypeValueValuesEnum.PROACTIVE) raise exceptions.InvalidArgumentException(flag_name, 'unknown update policy.') def ValidateUpdateInstancesArgs(args): """Validates update arguments provided by the user. Args: args: arguments provided by the user. """ if args.action == 'restart': if args.version_original: raise exceptions.InvalidArgumentException( '--version-original', 'can\'t be specified for --action restart.') if args.version_new: raise exceptions.InvalidArgumentException( '--version-new', 'can\'t be specified for --action restart.') elif args.action == 'replace': if not args.version_new: raise exceptions.RequiredArgumentException( '--version-new', 'must be specified for --action replace (or default).') if not args.version_original and (TARGET_SIZE_NAME in args.version_new): if args.version_new[TARGET_SIZE_NAME] == '100%': del args.version_new[TARGET_SIZE_NAME] else: raise exceptions.InvalidArgumentException( '--version-new', 'target-size can\'t be specified if there is only one version.') if (args.version_original and args.version_new and (TARGET_SIZE_NAME in args.version_original) == (TARGET_SIZE_NAME in args.version_new)): raise exceptions.ToolException( 'Exactly one version must have the target-size specified.') def ParseVersion(flag_name, version_map, resources, messages): """Retrieves version from input map. Args: flag_name: name of the flag associated with the parsed string. version_map: map containing version data provided by the user. resources: provides reference for instance template resource. messages: module containing message classes. Returns: InstanceGroupManagerVersion message object. """ if TEMPLATE_NAME not in version_map: raise exceptions.InvalidArgumentException(flag_name, 'template has to be specified.') template_ref = resources.Parse( version_map[TEMPLATE_NAME], collection='compute.instanceTemplates') if TARGET_SIZE_NAME in version_map: target_size = ParseFixedOrPercent(flag_name, TARGET_SIZE_NAME, version_map[TARGET_SIZE_NAME], messages) else: target_size = None name = version_map.get('name') return messages.InstanceGroupManagerVersion( instanceTemplate=template_ref.SelfLink(), targetSize=target_size, name=name) def ValidateCanaryVersionFlag(flag_name, version_map): """Retrieves canary version from input map. Args: flag_name: name of the flag associated with the parsed string. version_map: map containing version data provided by the user. """ if version_map and TARGET_SIZE_NAME not in version_map: raise exceptions.RequiredArgumentException( '{} {}={}'.format(flag_name, TARGET_SIZE_NAME, TARGET_SIZE_NAME.upper()), 'target size must be specified for canary version')<|fim▁end|>
<|file_name|>lib.py<|end_file_name|><|fim▁begin|>import re import datetime from collections import OrderedDict TimePattern = re.compile("^[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$") TimeFormat = "%Y-%m-%dT%H:%M:%S.%fZ" TimePatternSimple = re.compile("^[0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}$") TimeFormatSimple = "%Y-%m-%d %H:%M" def convert_time_fields(item): if not item: return for k, v in item.iteritems(): if v is None: continue if isinstance(v, dict): convert_time_fields(v) elif TimePattern.match(v): item[k] = datetime.datetime.strptime(v, TimeFormat) def convert_to_csv(items): def escape(s): if type(s) is str and ',' in s: return '"' + s + '"'<|fim▁hole|> def join(items): return ','.join(map(lambda i: escape(i), items)) header = join(items[0].keys()) lines = [join(item.values()) for item in items] return header + "\n" + "\n".join(lines) def parse_user_accept_languages(header): if header: return list(OrderedDict.fromkeys(map(lambda h: h.split(';')[0].split('-')[0], header.split(',')))) else: return []<|fim▁end|>
return str(s)
<|file_name|>OptaplannerIntegrationTest.java<|end_file_name|><|fim▁begin|>/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.integrationtests.optaplanner; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.BeforeClass; import org.junit.Test; import org.kie.api.KieServices; import org.kie.server.api.exception.KieServicesException; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.instance.ScoreWrapper; import org.kie.server.api.model.instance.SolverInstance; import org.kie.server.integrationtests.shared.KieServerAssert; import org.kie.server.integrationtests.shared.KieServerDeployer; import org.kie.server.integrationtests.shared.KieServerReflections; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; import org.optaplanner.core.impl.solver.ProblemFactChange; import static org.junit.Assert.*; public class OptaplannerIntegrationTest extends OptaplannerKieServerBaseIntegrationTest { private static final ReleaseId kjar1 = new ReleaseId( "org.kie.server.testing", "cloudbalance",<|fim▁hole|> private static final String SOLVER_1_ID = "cloudsolver"; private static final String SOLVER_1_CONFIG = "cloudbalance-solver.xml"; private static final String SOLVER_1_REALTIME_CONFIG = "cloudbalance-realtime-planning-solver.xml"; private static final String SOLVER_1_REALTIME_DAEMON_CONFIG = "cloudbalance-realtime-planning-daemon-solver.xml"; private static final String CLASS_CLOUD_BALANCE = "org.kie.server.testing.CloudBalance"; private static final String CLASS_CLOUD_COMPUTER = "org.kie.server.testing.CloudComputer"; private static final String CLASS_CLOUD_PROCESS = "org.kie.server.testing.CloudProcess"; private static final String CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE = "org.kie.server.testing.AddComputerProblemFactChange"; private static final String CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE = "org.kie.server.testing.DeleteComputerProblemFactChange"; private static final String CLASS_CLOUD_GENERATOR = "org.kie.server.testing.CloudBalancingGenerator"; @BeforeClass public static void deployArtifacts() { KieServerDeployer.buildAndDeployCommonMavenParent(); KieServerDeployer.buildAndDeployMavenProject(ClassLoader.class.getResource("/kjars-sources/cloudbalance").getFile()); kieContainer = KieServices.Factory.get().newKieContainer(kjar1); createContainer(CONTAINER_1_ID, kjar1); } @Override protected void addExtraCustomClasses(Map<String, Class<?>> extraClasses) throws ClassNotFoundException { extraClasses.put(CLASS_CLOUD_BALANCE, Class.forName(CLASS_CLOUD_BALANCE, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_CLOUD_COMPUTER, Class.forName(CLASS_CLOUD_COMPUTER, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_CLOUD_PROCESS, Class.forName(CLASS_CLOUD_PROCESS, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE, Class.forName(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE, Class.forName(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE, true, kieContainer.getClassLoader())); } @Test public void testCreateDisposeSolver() { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test public void testCreateSolverFromNotExistingContainer() { try { solverClient.createSolver(NOT_EXISTING_CONTAINER_ID, SOLVER_1_ID, SOLVER_1_CONFIG); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Container '" + NOT_EXISTING_CONTAINER_ID + "' is not instantiated or cannot find container for alias '" + NOT_EXISTING_CONTAINER_ID + "'.*"); } } @Test(expected = IllegalArgumentException.class) public void testCreateSolverWithoutConfigPath() { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, null); } @Test public void testCreateSolverWrongConfigPath() { try { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, "NonExistingPath"); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*The solverConfigResource \\(.*\\) does not exist as a classpath resource in the classLoader \\(.*\\)*"); } } @Test(expected = IllegalArgumentException.class) public void testCreateSolverNullContainer() { solverClient.createSolver(null, SOLVER_1_ID, SOLVER_1_CONFIG); } @Test public void testCreateDuplicitSolver() { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); try { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Failed to create solver. Solver .* already exists for container .*"); } } @Test public void testDisposeNotExistingSolver() { try { solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*from container.*not found.*"); } } @Test public void testGetSolverState() { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertNotNull(solverInstance); assertEquals(CONTAINER_1_ID, solverInstance.getContainerId()); assertEquals(SOLVER_1_CONFIG, solverInstance.getSolverConfigFile()); assertEquals(SOLVER_1_ID, solverInstance.getSolverId()); assertEquals(SolverInstance.getSolverInstanceKey(CONTAINER_1_ID, SOLVER_1_ID), solverInstance.getSolverInstanceKey()); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); assertNotNull(solverInstance.getScoreWrapper()); assertNull(solverInstance.getScoreWrapper().toScore()); } @Test public void testGetNotExistingSolverState() { try { solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*not found in container.*"); } } @Test public void testGetSolvers() { List<SolverInstance> solverInstanceList = solverClient.getSolvers(CONTAINER_1_ID); assertNotNull(solverInstanceList); assertEquals(0, solverInstanceList.size()); solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); solverInstanceList = solverClient.getSolvers(CONTAINER_1_ID); assertNotNull(solverInstanceList); assertEquals(1, solverInstanceList.size()); SolverInstance returnedInstance = solverInstanceList.get(0); assertEquals(CONTAINER_1_ID, returnedInstance.getContainerId()); assertEquals(SOLVER_1_CONFIG, returnedInstance.getSolverConfigFile()); assertEquals(SOLVER_1_ID, returnedInstance.getSolverId()); assertEquals(SolverInstance.getSolverInstanceKey(CONTAINER_1_ID, SOLVER_1_ID), returnedInstance.getSolverInstanceKey()); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, returnedInstance.getStatus()); assertNotNull(returnedInstance.getScoreWrapper()); assertNull(returnedInstance.getScoreWrapper().toScore()); } @Test public void testExecuteSolver() throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); // the following status starts the solver Object planningProblem = loadPlanningProblem(5, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); // solver should finish in 5 seconds, but we wait up to 15s before timing out for (int i = 0; i < 5 && solverInstance.getStatus() == SolverInstance.SolverStatus.SOLVING; i++) { Thread.sleep(3000); solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertNotNull(solverInstance); } assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverSingleItemSubmit() throws Exception { testExecuteRealtimePlanningSolverSingleItemSubmit(false); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverSingleItemSubmitDaemonEnabled() throws Exception { testExecuteRealtimePlanningSolverSingleItemSubmit(true); } private void testExecuteRealtimePlanningSolverSingleItemSubmit(boolean daemon) throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, daemon ? SOLVER_1_REALTIME_DAEMON_CONFIG : SOLVER_1_REALTIME_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); final int computerCount = 5; final int numberOfComputersToAdd = 5; final Object planningProblem = loadPlanningProblem(computerCount, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); SolverInstance solver = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, solver.getStatus()); Thread.sleep(3000); List computerList = null; for (int i = 0; i < numberOfComputersToAdd; i++) { ProblemFactChange<?> problemFactChange = loadAddProblemFactChange(computerCount + i); solverClient.addProblemFactChange(CONTAINER_1_ID, SOLVER_1_ID, problemFactChange); do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (computerCount + i + 1 != computerList.size()); } assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); Thread.sleep(3000); assertNotNull(computerList); for (int i = 0; i < numberOfComputersToAdd; i++) { ProblemFactChange<?> problemFactChange = loadDeleteProblemFactChange(computerList.get(i)); solverClient.addProblemFactChange(CONTAINER_1_ID, SOLVER_1_ID, problemFactChange); do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (computerCount + numberOfComputersToAdd - i - 1 != computerList.size()); } assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverBulkItemSubmit() throws Exception { testExecuteRealtimePlanningSolverBulkItemSubmit(false); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverBulkItemSubmitDaemonEnabled() throws Exception { testExecuteRealtimePlanningSolverBulkItemSubmit(true); } private void testExecuteRealtimePlanningSolverBulkItemSubmit(boolean daemon) throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, daemon ? SOLVER_1_REALTIME_DAEMON_CONFIG : SOLVER_1_REALTIME_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); final int initialComputerCount = 5; final int numberOfComputersToAdd = 5; final Object planningProblem = loadPlanningProblem(initialComputerCount, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); SolverInstance solver = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, solver.getStatus()); Thread.sleep(3000); List<ProblemFactChange> problemFactChangeList = new ArrayList<>(numberOfComputersToAdd); for (int i = 0; i < numberOfComputersToAdd; i++) { problemFactChangeList.add(loadAddProblemFactChange(initialComputerCount + i)); } solverClient.addProblemFactChanges(CONTAINER_1_ID, SOLVER_1_ID, problemFactChangeList); List computerList = null; do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (initialComputerCount + numberOfComputersToAdd != computerList.size()); assertNotNull(computerList); assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); Thread.sleep(3000); problemFactChangeList.clear(); for (int i = 0; i < numberOfComputersToAdd; i++) { problemFactChangeList.add(loadDeleteProblemFactChange(computerList.get(i))); } solverClient.addProblemFactChanges(CONTAINER_1_ID, SOLVER_1_ID, problemFactChangeList); do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (initialComputerCount != computerList.size()); assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } private Object verifySolverAndGetBestSolution() { SolverInstance solver = solverClient.getSolverWithBestSolution(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, solver.getStatus()); Object bestSolution = solver.getBestSolution(); assertEquals(bestSolution.getClass().getName(), CLASS_CLOUD_BALANCE); return bestSolution; } private List getCloudBalanceComputerList(final Object cloudBalance) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method computerListMethod = cloudBalance.getClass().getDeclaredMethod("getComputerList"); return (List) computerListMethod.invoke(cloudBalance); } @Test public void testExecuteRunningSolver() throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); // start solver Object planningProblem = loadPlanningProblem(5, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); // start solver again try { solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver .* on container .* is already executing.*"); } solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test(timeout = 60000) public void testGetBestSolution() throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); // Start the solver Object planningProblem = loadPlanningProblem(10, 30); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); Object solution = null; HardSoftScore score = null; // It can take a while for the Construction Heuristic to initialize the solution // The test timeout will interrupt this thread if it takes too long while (!Thread.currentThread().isInterrupted()) { solverInstance = solverClient.getSolverWithBestSolution(CONTAINER_1_ID, SOLVER_1_ID); assertNotNull(solverInstance); solution = solverInstance.getBestSolution(); ScoreWrapper scoreWrapper = solverInstance.getScoreWrapper(); assertNotNull(scoreWrapper); if (scoreWrapper.toScore() != null) { assertEquals(HardSoftScore.class, scoreWrapper.getScoreClass()); score = (HardSoftScore) scoreWrapper.toScore(); } // Wait until the solver finished initializing the solution if (solution != null && score != null && score.isSolutionInitialized()) { break; } Thread.sleep(1000); } assertNotNull(score); assertTrue(score.isSolutionInitialized()); assertTrue(score.getHardScore() <= 0); // A soft score of 0 is impossible because we'll always need at least 1 computer assertTrue(score.getSoftScore() < 0); List<?> computerList = (List<?>) KieServerReflections.valueOf(solution, "computerList"); assertEquals(10, computerList.size()); List<?> processList = (List<?>) KieServerReflections.valueOf(solution, "processList"); assertEquals(30, processList.size()); for (Object process : processList) { Object computer = KieServerReflections.valueOf(process, "computer"); assertNotNull(computer); // TODO: Change to identity comparation after @XmlID is implemented assertTrue(computerList.contains(computer)); } solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test public void testGetBestSolutionNotExistingSolver() { try { solverClient.getSolverWithBestSolution(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*not found in container.*"); } } @Test public void testTerminateEarlyNotExistingSolver() { try { solverClient.terminateSolverEarly(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*not found in container.*"); } } @Test public void testTerminateEarlyStoppedSolver() { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); try { solverClient.terminateSolverEarly(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*from container.*is not executing.*"); } } @Test public void testTerminateEarly() throws Exception { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); // start solver solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, loadPlanningProblem(50, 150)); SolverInstance instance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, instance.getStatus()); // and then terminate it solverClient.terminateSolverEarly(CONTAINER_1_ID, SOLVER_1_ID); instance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertTrue(instance.getStatus() == SolverInstance.SolverStatus.TERMINATING_EARLY || instance.getStatus() == SolverInstance.SolverStatus.NOT_SOLVING); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } private Object loadPlanningProblem(int computerListSize, int processListSize) throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { Class<?> cbgc = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_GENERATOR); Object cbgi = cbgc.newInstance(); Method method = cbgc.getMethod("createCloudBalance", int.class, int.class); return method.invoke(cbgi, computerListSize, processListSize); } private ProblemFactChange<?> loadAddProblemFactChange(final int currentNumberOfComputers) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class<?> cbgc = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_GENERATOR); Object cbgi = cbgc.newInstance(); Method method = cbgc.getMethod("createCloudComputer", int.class); Object cloudComputer = method.invoke(cbgi, currentNumberOfComputers); Class<?> cloudComputerClass = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_COMPUTER); Class<?> problemFactChangeClass = kieContainer.getClassLoader().loadClass(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE); Constructor<?> constructor = problemFactChangeClass.getConstructor(cloudComputerClass); return (ProblemFactChange) constructor.newInstance(cloudComputer); } private ProblemFactChange<?> loadDeleteProblemFactChange(final Object cloudComputer) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<?> cloudComputerClass = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_COMPUTER); Class<?> problemFactChangeClass = kieContainer.getClassLoader().loadClass(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE); Constructor<?> constructor = problemFactChangeClass.getConstructor(cloudComputerClass); return (ProblemFactChange) constructor.newInstance(cloudComputer); } }<|fim▁end|>
"1.0.0.Final"); private static final String NOT_EXISTING_CONTAINER_ID = "no_container"; private static final String CONTAINER_1_ID = "cloudbalance";
<|file_name|>moodle-mod_quiz-repaginate.js<|end_file_name|><|fim▁begin|>YUI.add('moodle-mod_quiz-repaginate', function (Y, NAME) { // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful,<|fim▁hole|>// // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Repaginate functionality for a popup in quiz editing page. * * @package mod_quiz * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ var CSS = { REPAGINATECONTAINERCLASS: '.rpcontainerclass', REPAGINATECOMMAND: '#repaginatecommand' }; var PARAMS = { CMID: 'cmid', HEADER: 'header', FORM: 'form' }; var POPUP = function() { POPUP.superclass.constructor.apply(this, arguments); }; Y.extend(POPUP, Y.Base, { header: null, body: null, initializer: function() { var rpcontainerclass = Y.one(CSS.REPAGINATECONTAINERCLASS); // Set popup header and body. this.header = rpcontainerclass.getAttribute(PARAMS.HEADER); this.body = rpcontainerclass.getAttribute(PARAMS.FORM); Y.one(CSS.REPAGINATECOMMAND).on('click', this.display_dialog, this); }, display_dialog: function(e) { e.preventDefault(); // Configure the popup. var config = { headerContent: this.header, bodyContent: this.body, draggable: true, modal: true, zIndex: 1000, context: [CSS.REPAGINATECOMMAND, 'tr', 'br', ['beforeShow']], centered: false, width: '30em', visible: false, postmethod: 'form', footerContent: null }; var popup = {dialog: null}; popup.dialog = new M.core.dialogue(config); popup.dialog.show(); } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.repaginate = M.mod_quiz.repaginate || {}; M.mod_quiz.repaginate.init = function() { return new POPUP(); }; }, '@VERSION@', {"requires": ["base", "event", "node", "io", "moodle-core-notification-dialogue"]});<|fim▁end|>
// but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details.
<|file_name|>Player.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Player.h" #include "Language.h" #include "Database/DatabaseEnv.h" #include "Log.h" #include "Opcodes.h" #include "SpellMgr.h" #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" #include "UpdateMask.h" #include "QuestDef.h" #include "GossipDef.h" #include "UpdateData.h" #include "Channel.h" #include "ChannelMgr.h" #include "MapManager.h" #include "MapPersistentStateMgr.h" #include "InstanceData.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" #include "ObjectMgr.h" #include "ObjectAccessor.h" #include "CreatureAI.h" #include "Formulas.h" #include "Group.h" #include "Guild.h" #include "GuildMgr.h" #include "Pet.h" #include "Util.h" #include "Transports.h" #include "Weather.h" #include "BattleGround.h" #include "BattleGroundAV.h" #include "BattleGroundMgr.h" #include "WorldPvP/WorldPvP.h" #include "WorldPvP/WorldPvPMgr.h" #include "ArenaTeam.h" #include "Chat.h" #include "Database/DatabaseImpl.h" #include "Spell.h" #include "ScriptMgr.h" #include "SocialMgr.h" #include "AchievementMgr.h" #include "Mail.h" #include "SpellAuras.h" #include <cmath> // Playerbot mod: #include "playerbot/PlayerbotAI.h" #include "playerbot/PlayerbotMgr.h" #include "Config/Config.h" #define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS) #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3)) #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1) #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2) #define SKILL_VALUE(x) PAIR32_LOPART(x) #define SKILL_MAX(x) PAIR32_HIPART(x) #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m) #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x)) #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x)) #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p) enum CharacterFlags { CHARACTER_FLAG_NONE = 0x00000000, CHARACTER_FLAG_UNK1 = 0x00000001, CHARACTER_FLAG_UNK2 = 0x00000002, CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004, CHARACTER_FLAG_UNK4 = 0x00000008, CHARACTER_FLAG_UNK5 = 0x00000010, CHARACTER_FLAG_UNK6 = 0x00000020, CHARACTER_FLAG_UNK7 = 0x00000040, CHARACTER_FLAG_UNK8 = 0x00000080, CHARACTER_FLAG_UNK9 = 0x00000100, CHARACTER_FLAG_UNK10 = 0x00000200, CHARACTER_FLAG_HIDE_HELM = 0x00000400, CHARACTER_FLAG_HIDE_CLOAK = 0x00000800, CHARACTER_FLAG_UNK13 = 0x00001000, CHARACTER_FLAG_GHOST = 0x00002000, CHARACTER_FLAG_RENAME = 0x00004000, CHARACTER_FLAG_UNK16 = 0x00008000, CHARACTER_FLAG_UNK17 = 0x00010000, CHARACTER_FLAG_UNK18 = 0x00020000, CHARACTER_FLAG_UNK19 = 0x00040000, CHARACTER_FLAG_UNK20 = 0x00080000, CHARACTER_FLAG_UNK21 = 0x00100000, CHARACTER_FLAG_UNK22 = 0x00200000, CHARACTER_FLAG_UNK23 = 0x00400000, CHARACTER_FLAG_UNK24 = 0x00800000, CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000, CHARACTER_FLAG_DECLINED = 0x02000000, CHARACTER_FLAG_UNK27 = 0x04000000, CHARACTER_FLAG_UNK28 = 0x08000000, CHARACTER_FLAG_UNK29 = 0x10000000, CHARACTER_FLAG_UNK30 = 0x20000000, CHARACTER_FLAG_UNK31 = 0x40000000, CHARACTER_FLAG_UNK32 = 0x80000000 }; enum CharacterCustomizeFlags { CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000, CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc... CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc... CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc... }; // corpse reclaim times #define DEATH_EXPIRE_STEP (5*MINUTE) #define MAX_DEATH_COUNT 3 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 }; //== PlayerTaxi ================================================ PlayerTaxi::PlayerTaxi() { // Taxi nodes memset(m_taximask, 0, sizeof(m_taximask)); } void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level) { // class specific initial known nodes switch(chrClass) { case CLASS_DEATH_KNIGHT: { for(int i = 0; i < TaxiMaskSize; ++i) m_taximask[i] |= sOldContinentsNodesMask[i]; break; } } // race specific initial known nodes: capital and taxi hub masks switch(race) { case RACE_HUMAN: SetTaximaskNode(2); break; // Human case RACE_ORC: SetTaximaskNode(23); break; // Orc case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf case RACE_NIGHTELF: SetTaximaskNode(26); SetTaximaskNode(27); break; // Night Elf case RACE_UNDEAD: SetTaximaskNode(11); break; // Undead case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren case RACE_GNOME: SetTaximaskNode(6); break; // Gnome case RACE_TROLL: SetTaximaskNode(23); break; // Troll case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei } // new continent starting masks (It will be accessible only at new map) switch(Player::TeamForRace(race)) { case ALLIANCE: SetTaximaskNode(100); break; case HORDE: SetTaximaskNode(99); break; default: break; } // level dependent taxi hubs if (level>=68) SetTaximaskNode(213); //Shattered Sun Staging Area } void PlayerTaxi::LoadTaxiMask(const char* data) { Tokens tokens(data, ' '); int index; Tokens::iterator iter; for (iter = tokens.begin(), index = 0; (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index) { // load and set bits only for existing taxi nodes m_taximask[index] = sTaxiNodesMask[index] & uint32(atol(*iter)); } } void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all ) { if (all) { for (uint8 i=0; i<TaxiMaskSize; ++i) data << uint32(sTaxiNodesMask[i]); // all existing nodes } else { for (uint8 i=0; i<TaxiMaskSize; ++i) data << uint32(m_taximask[i]); // known nodes } } bool PlayerTaxi::LoadTaxiDestinationsFromString(const std::string& values, Team team) { ClearTaxiDestinations(); Tokens tokens(values, ' '); for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter) { uint32 node = uint32(atol(*iter)); AddTaxiDestination(node); } if (m_TaxiDestinations.empty()) return true; // Check integrity if (m_TaxiDestinations.size() < 2) return false; for(size_t i = 1; i < m_TaxiDestinations.size(); ++i) { uint32 cost; uint32 path; sObjectMgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i], path, cost); if (!path) return false; } // can't load taxi path without mount set (quest taxi path?) if (!sObjectMgr.GetTaxiMountDisplayId(GetTaxiSource(), team, true)) return false; return true; } std::string PlayerTaxi::SaveTaxiDestinationsToString() { if (m_TaxiDestinations.empty()) return ""; std::ostringstream ss; for(size_t i=0; i < m_TaxiDestinations.size(); ++i) ss << m_TaxiDestinations[i] << " "; return ss.str(); } uint32 PlayerTaxi::GetCurrentTaxiPath() const { if (m_TaxiDestinations.size() < 2) return 0; uint32 path; uint32 cost; sObjectMgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost); return path; } std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi) { for(int i = 0; i < TaxiMaskSize; ++i) ss << taxi.m_taximask[i] << " "; return ss; } //== TradeData ================================================= TradeData* TradeData::GetTraderData() const { return m_trader->GetTradeData(); } Item* TradeData::GetItem( TradeSlots slot ) const { return m_items[slot] ? m_player->GetItemByGuid(m_items[slot]) : NULL; } bool TradeData::HasItem( ObjectGuid item_guid ) const { for(int i = 0; i < TRADE_SLOT_COUNT; ++i) if (m_items[i] == item_guid) return true; return false; } Item* TradeData::GetSpellCastItem() const { return m_spellCastItem ? m_player->GetItemByGuid(m_spellCastItem) : NULL; } void TradeData::SetItem( TradeSlots slot, Item* item ) { ObjectGuid itemGuid = item ? item->GetObjectGuid() : ObjectGuid(); if (m_items[slot] == itemGuid) return; m_items[slot] = itemGuid; SetAccepted(false); GetTraderData()->SetAccepted(false); Update(); // need remove possible trader spell applied to changed item if (slot == TRADE_SLOT_NONTRADED) GetTraderData()->SetSpell(0); // need remove possible player spell applied (possible move reagent) SetSpell(0); } void TradeData::SetSpell( uint32 spell_id, Item* castItem /*= NULL*/ ) { ObjectGuid itemGuid = castItem ? castItem->GetObjectGuid() : ObjectGuid(); if (m_spell == spell_id && m_spellCastItem == itemGuid) return; m_spell = spell_id; m_spellCastItem = itemGuid; SetAccepted(false); GetTraderData()->SetAccepted(false); Update(true); // send spell info to item owner Update(false); // send spell info to caster self } void TradeData::SetMoney( uint32 money ) { if (m_money == money) return; m_money = money; SetAccepted(false); GetTraderData()->SetAccepted(false); Update(); } void TradeData::Update( bool for_trader /*= true*/ ) { if (for_trader) m_trader->GetSession()->SendUpdateTrade(true); // player state for trader else m_player->GetSession()->SendUpdateTrade(false); // player state for player } void TradeData::SetAccepted(bool state, bool crosssend /*= false*/) { m_accepted = state; if (!state) { if (crosssend) m_trader->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE); else m_player->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE); } } //== Player ==================================================== UpdateMask Player::updateVisualBits; Player::Player (WorldSession *session): Unit(), m_mover(this), m_camera(this), m_achievementMgr(this), m_reputationMgr(this) { m_speakTime = 0; m_speakCount = 0; m_objectType |= TYPEMASK_PLAYER; m_objectTypeId = TYPEID_PLAYER; m_valuesCount = PLAYER_END; SetActiveObjectState(true); // player is always active object m_session = session; m_ExtraFlags = 0; if (GetSession()->GetSecurity() >= SEC_GAMEMASTER) SetAcceptTicket(true); // players always accept if (GetSession()->GetSecurity() == SEC_PLAYER) SetAcceptWhispers(true); m_usedTalentCount = 0; m_questRewardTalentCount = 0; m_regenTimer = REGEN_TIME_FULL; m_weaponChangeTimer = 0; m_zoneUpdateId = 0; m_zoneUpdateTimer = 0; m_areaUpdateId = 0; m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE); // randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE] // this must help in case next save after mass player load after server startup m_nextSave = urand(m_nextSave/2,m_nextSave*3/2); clearResurrectRequestData(); memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT); m_social = NULL; // group is initialized in the reference constructor SetGroupInvite(NULL); m_groupUpdateMask = 0; m_auraUpdateMask = 0; duel = NULL; m_GuildIdInvited = 0; m_ArenaTeamIdInvited = 0; m_atLoginFlags = AT_LOGIN_NONE; mSemaphoreTeleport_Near = false; mSemaphoreTeleport_Far = false; m_DelayedOperations = 0; m_bCanDelayTeleport = false; m_bHasDelayedTeleport = false; m_bHasBeenAliveAtDelayedTeleport = true; // overwrite always at setup teleport data, so not used infact m_teleport_options = 0; m_trade = NULL; m_cinematic = 0; PlayerTalkClass = new PlayerMenu( GetSession() ); m_currentBuybackSlot = BUYBACK_SLOT_START; m_DailyQuestChanged = false; m_WeeklyQuestChanged = false; for (int i=0; i<MAX_TIMERS; ++i) m_MirrorTimer[i] = DISABLED_MIRROR_TIMER; m_MirrorTimerFlags = UNDERWATER_NONE; m_MirrorTimerFlagsLast = UNDERWATER_NONE; m_isInWater = false; m_drunkTimer = 0; m_drunk = 0; m_restTime = 0; m_deathTimer = 0; m_deathExpireTime = 0; m_swingErrorMsg = 0; m_DetectInvTimer = 1*IN_MILLISECONDS; for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j) { m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE; m_bgBattleGroundQueueID[j].invitedToInstance = 0; } m_logintime = time(NULL); m_Last_tick = m_logintime; m_WeaponProficiency = 0; m_ArmorProficiency = 0; m_canParry = false; m_canBlock = false; m_canDualWield = false; m_canTitanGrip = false; m_ammoDPS = 0.0f; m_temporaryUnsummonedPetNumber.clear(); ////////////////////Rest System///////////////////// time_inn_enter=0; inn_trigger_id=0; m_rest_bonus=0; rest_type=REST_TYPE_NO; ////////////////////Rest System///////////////////// m_mailsUpdated = false; unReadMails = 0; m_nextMailDelivereTime = 0; m_resetTalentsCost = 0; m_resetTalentsTime = 0; m_itemUpdateQueueBlocked = false; for (int i = 0; i < MAX_MOVE_TYPE; ++i) m_forced_speed_changes[i] = 0; m_stableSlots = 0; /////////////////// Instance System ///////////////////// m_HomebindTimer = 0; m_InstanceValid = true; m_Difficulty = 0; SetDungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL); SetRaidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL); m_lastPotionId = 0; m_activeSpec = 0; m_specsCount = 1; for (int i = 0; i < BASEMOD_END; ++i) { m_auraBaseMod[i][FLAT_MOD] = 0.0f; m_auraBaseMod[i][PCT_MOD] = 1.0f; } for (int i = 0; i < MAX_COMBAT_RATING; ++i) m_baseRatingValue[i] = 0; m_baseSpellPower = 0; m_baseFeralAP = 0; m_baseManaRegen = 0; m_baseHealthRegen = 0; m_armorPenetrationPct = 0.0f; m_spellPenetrationItemMod = 0; // Honor System m_lastHonorUpdateTime = time(NULL); m_IsBGRandomWinner = false; // Player summoning m_summon_expire = 0; m_summon_mapid = 0; m_summon_x = 0.0f; m_summon_y = 0.0f; m_summon_z = 0.0f; m_contestedPvPTimer = 0; m_declinedname = NULL; m_runes = NULL; m_lastFallTime = 0; m_lastFallZ = 0; // Refer-A-Friend m_GrantableLevelsCount = 0; // Playerbot mod: m_playerbotAI = NULL; m_playerbotMgr = NULL; m_anticheat = new AntiCheat(this); SetPendingBind(NULL, 0); m_LFGState = new LFGPlayerState(this); m_cachedGS = 0; } Player::~Player () { CleanupsBeforeDelete(); // it must be unloaded already in PlayerLogout and accessed only for loggined player //m_social = NULL; // Note: buy back item already deleted from DB when player was saved for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i) { if (m_items[i]) delete m_items[i]; } CleanupChannels(); //all mailed items should be deleted, also all mail should be deallocated for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr) delete *itr; for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter) delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated delete PlayerTalkClass; if (m_transport) m_transport->RemovePassenger(this); for(size_t x = 0; x < ItemSetEff.size(); x++) if (ItemSetEff[x]) delete ItemSetEff[x]; // clean up player-instance binds, may unload some instance saves for(uint8 i = 0; i < MAX_DIFFICULTY; ++i) for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) itr->second.state->RemovePlayer(this); delete m_declinedname; delete m_runes; delete m_anticheat; delete m_LFGState; // Playerbot mod if (m_playerbotAI) { delete m_playerbotAI; m_playerbotAI = NULL; } if (m_playerbotMgr) { delete m_playerbotMgr; m_playerbotMgr = NULL; } } void Player::CleanupsBeforeDelete() { if (m_uint32Values) // only for fully created Object { TradeCancel(false); DuelComplete(DUEL_INTERUPTED); } // notify zone scripts for player logout sWorldPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId); Unit::CleanupsBeforeDelete(); } bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 /*outfitId */) { //FIXME: outfitId not used in player creating Object::_Create(ObjectGuid(HIGHGUID_PLAYER, guidlow)); m_name = name; PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_); if(!info) { sLog.outError("Player have incorrect race/class pair. Can't be loaded."); return false; } ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_); if(!cEntry) { sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_); return false; } // player store gender in single bit if (gender != uint8(GENDER_MALE) && gender != uint8(GENDER_FEMALE)) { sLog.outError("Invalid gender %u at player creating", uint32(gender)); return false; } for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i) m_items[i] = NULL; SetLocationMapId(info->mapId); Relocate(info->positionX,info->positionY,info->positionZ, info->orientation); setFactionForRace(race); SetMap(sMapMgr.CreateMap(info->mapId, this)); uint8 powertype = cEntry->powerType; SetByteValue(UNIT_FIELD_BYTES_0, 0, race); SetByteValue(UNIT_FIELD_BYTES_0, 1, class_); SetByteValue(UNIT_FIELD_BYTES_0, 2, gender); SetByteValue(UNIT_FIELD_BYTES_0, 3, powertype); InitDisplayIds(); // model, scale and model data SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP ); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER); SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1); // -1 is default value SetByteValue(PLAYER_BYTES, 0, skin); SetByteValue(PLAYER_BYTES, 1, face); SetByteValue(PLAYER_BYTES, 2, hairStyle); SetByteValue(PLAYER_BYTES, 3, hairColor); SetByteValue(PLAYER_BYTES_2, 0, facialHair); LoadAccountLinkedState(); if (GetAccountLinkedState() != STATE_NOT_LINKED) SetByteValue(PLAYER_BYTES_2, 3, 0x06); // rest state = refer-a-friend else SetByteValue(PLAYER_BYTES_2, 3, 0x02); // rest state = normal SetUInt16Value(PLAYER_BYTES_3, 0, gender); // only GENDER_MALE/GENDER_FEMALE (1 bit) allowed, drunk state = 0 SetByteValue(PLAYER_BYTES_3, 3, 0); // BattlefieldArenaFaction (0 or 1) SetUInt32Value( PLAYER_GUILDID, 0 ); SetUInt32Value( PLAYER_GUILDRANK, 0 ); SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 ); for(int i = 0; i < KNOWN_TITLES_SIZE; ++i) SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES + i, 0); // 0=disabled SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 ); SetUInt32Value( PLAYER_FIELD_KILLS, 0 ); SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 ); SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 ); SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 ); // set starting level uint32 start_level = getClass() != CLASS_DEATH_KNIGHT ? sWorld.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL) : sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL); if (GetSession()->GetSecurity() >= SEC_MODERATOR) { uint32 gm_level = sWorld.getConfig(CONFIG_UINT32_START_GM_LEVEL); if (gm_level > start_level) start_level = gm_level; } SetUInt32Value(UNIT_FIELD_LEVEL, start_level); InitRunes(); SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_UINT32_START_PLAYER_MONEY)); SetHonorPoints(sWorld.getConfig(CONFIG_UINT32_START_HONOR_POINTS)); SetArenaPoints(sWorld.getConfig(CONFIG_UINT32_START_ARENA_POINTS)); // Played time m_Last_tick = time(NULL); m_Played_time[PLAYED_TIME_TOTAL] = 0; m_Played_time[PLAYED_TIME_LEVEL] = 0; // base stats and related field values InitStatsForLevel(); InitTaxiNodesForLevel(); InitGlyphsForLevel(); InitTalentForLevel(); InitPrimaryProfessions(); // to max set before any spell added // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods() UpdateMaxHealth(); // Update max Health (for add bonus from stamina) SetHealth(GetMaxHealth()); if (getPowerType() == POWER_MANA) { UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect) SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); } if (getPowerType() != POWER_MANA) // hide additional mana bar if we have no mana { SetPower(POWER_MANA, 0); SetMaxPower(POWER_MANA, 0); } // original spells learnDefaultSpells(); // original action bar for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr) addActionButton(0, action_itr->button,action_itr->action,action_itr->type); // original items uint32 raceClassGender = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0x00FFFFFF; CharStartOutfitEntry const* oEntry = NULL; for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i) { if (CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i)) { if (entry->RaceClassGender == raceClassGender) { oEntry = entry; break; } } } if (oEntry) { for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j) { if (oEntry->ItemId[j] <= 0) continue; uint32 item_id = oEntry->ItemId[j]; // just skip, reported in ObjectMgr::LoadItemPrototypes ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id); if(!iProto) continue; // BuyCount by default int32 count = iProto->BuyCount; // special amount for foor/drink if (iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD) { switch(iProto->Spells[0].SpellCategory) { case 11: // food count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4; break; case 59: // drink count = 2; break; } if (iProto->Stackable < count) count = iProto->Stackable; } StoreNewItemInBestSlots(item_id, count); } } for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr != info->item.end(); ++item_id_itr) StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount); // bags and main-hand weapon must equipped at this moment // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon) // or ammo not equipped in special bag for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) { if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) { uint16 eDest; // equip offhand weapon/shield if it attempt equipped before main-hand weapon InventoryResult msg = CanEquipItem(NULL_SLOT, eDest, pItem, false); if (msg == EQUIP_ERR_OK) { RemoveItem(INVENTORY_SLOT_BAG_0, i, true); EquipItem(eDest, pItem, true); } // move other items to more appropriate slots (ammo not equipped in special bag) else { ItemPosCountVec sDest; msg = CanStoreItem(NULL_BAG, NULL_SLOT, sDest, pItem, false); if (msg == EQUIP_ERR_OK) { RemoveItem(INVENTORY_SLOT_BAG_0, i,true); pItem = StoreItem( sDest, pItem, true); } // if this is ammo then use it msg = CanUseAmmo(pItem->GetEntry()); if (msg == EQUIP_ERR_OK) SetAmmo(pItem->GetEntry()); } } } // all item positions resolved return true; } bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) { DEBUG_LOG("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount); // attempt equip by one while(titem_amount > 0) { uint16 eDest; uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false ); if ( msg != EQUIP_ERR_OK ) break; EquipNewItem( eDest, titem_id, true); AutoUnequipOffhandIfNeed(); --titem_amount; } if (titem_amount == 0) return true; // equipped // attempt store ItemPosCountVec sDest; // store in main bag to simplify second pass (special bags can be not equipped yet at this moment) uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount ); if ( msg == EQUIP_ERR_OK ) { StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) ); return true; // stored } // item can't be added sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg); return false; } // helper function, mainly for script side, but can be used for simple task in mangos also. Item* Player::StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount) { ItemPosCountVec vDest; uint8 msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, vDest, itemEntry, amount); if (msg == EQUIP_ERR_OK) { if (Item* pItem = StoreNewItem(vDest, itemEntry, true, Item::GenerateItemRandomPropertyId(itemEntry))) return pItem; } return NULL; } void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen) { if (int(MaxValue) == DISABLED_MIRROR_TIMER) { if (int(CurrentValue) != DISABLED_MIRROR_TIMER) StopMirrorTimer(Type); return; } WorldPacket data(SMSG_START_MIRROR_TIMER, (21)); data << (uint32)Type; data << CurrentValue; data << MaxValue; data << Regen; data << (uint8)0; data << (uint32)0; // spell id GetSession()->SendPacket( &data ); } void Player::StopMirrorTimer(MirrorTimerType Type) { m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER; WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4); data << (uint32)Type; GetSession()->SendPacket( &data ); } uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) { if(!isAlive() || isGameMaster()) return 0; // Absorb, resist some environmental damage type uint32 absorb = 0; uint32 resist = 0; if (type == DAMAGE_LAVA) CalculateDamageAbsorbAndResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist); else if (type == DAMAGE_SLIME) CalculateDamageAbsorbAndResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist); damage-=absorb+resist; DealDamageMods(this,damage,&absorb); WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21)); data << GetObjectGuid(); data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL); data << uint32(damage); data << uint32(absorb); data << uint32(resist); SendMessageToSet(&data, true); uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); if(!isAlive()) { if (type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage { DEBUG_LOG("We are fall to death, loosing 10 percents durability"); DurabilityLossAll(0.10f,false); // durability lost message WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0); GetSession()->SendPacket(&data2); } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type); } return final_damage; } int32 Player::getMaxTimer(MirrorTimerType timer) { switch (timer) { case FATIGUE_TIMER: if (GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL)) return DISABLED_MIRROR_TIMER; return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX)*IN_MILLISECONDS; case BREATH_TIMER: { if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL)) return DISABLED_MIRROR_TIMER; int32 UnderWaterTime = sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX)*IN_MILLISECONDS; AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING); for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i) UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f); return UnderWaterTime; } case FIRE_TIMER: { if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL)) return DISABLED_MIRROR_TIMER; return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX)*IN_MILLISECONDS; } default: return 0; } return 0; } void Player::UpdateMirrorTimers() { // Desync flags for update on next HandleDrowning if (m_MirrorTimerFlags) m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags; } void Player::HandleDrowning(uint32 time_diff) { if (!m_MirrorTimerFlags) return; // In water if (m_MirrorTimerFlags & UNDERWATER_INWATER) { // Breath timer not activated - activate it if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER) { m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER); SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1); } else // If activated - do tick { m_MirrorTimer[BREATH_TIMER]-=time_diff; // Timer limit - need deal damage if (m_MirrorTimer[BREATH_TIMER] < 0) { m_MirrorTimer[BREATH_TIMER] += 2 * IN_MILLISECONDS; // Calculate and deal damage // TODO: Check this formula uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); EnvironmentalDamage(DAMAGE_DROWNING, damage); } else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1); } } else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer { int32 UnderWaterTime = getMaxTimer(BREATH_TIMER); // Need breath regen m_MirrorTimer[BREATH_TIMER]+=10*time_diff; if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive()) StopMirrorTimer(BREATH_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER) SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10); } // In dark water if (m_MirrorTimerFlags & UNDERWATER_INDARKWATER) { // Fatigue timer not activated - activate it if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER) { m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER); SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1); } else { m_MirrorTimer[FATIGUE_TIMER]-=time_diff; // Timer limit - need deal damage or teleport ghost to graveyard if (m_MirrorTimer[FATIGUE_TIMER] < 0) { m_MirrorTimer[FATIGUE_TIMER] += 2 * IN_MILLISECONDS; if (isAlive()) // Calculate and deal damage { uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); EnvironmentalDamage(DAMAGE_EXHAUSTED, damage); } else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard RepopAtGraveyard(); } else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER)) SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1); } } else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer { int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER); m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff; if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive()) StopMirrorTimer(FATIGUE_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER) SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10); } if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME)) { // Breath timer not activated - activate it if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER) m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER); else { m_MirrorTimer[FIRE_TIMER]-=time_diff; if (m_MirrorTimer[FIRE_TIMER] < 0) { m_MirrorTimer[FIRE_TIMER] += 2 * IN_MILLISECONDS; // Calculate and deal damage // TODO: Check this formula uint32 damage = urand(600, 700); if (m_MirrorTimerFlags&UNDERWATER_INLAVA) EnvironmentalDamage(DAMAGE_LAVA, damage); // need to skip Slime damage in Undercity and Ruins of Lordaeron arena // maybe someone can find better way to handle environmental damage else if (m_zoneUpdateId != 1497 && m_zoneUpdateId != 3968) EnvironmentalDamage(DAMAGE_SLIME, damage); } } } else m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER; // Recheck timers flag m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS; for (int i = 0; i< MAX_TIMERS; ++i) if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER) { m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS; break; } m_MirrorTimerFlagsLast = m_MirrorTimerFlags; } ///The player sobers by 256 every 10 seconds void Player::HandleSobering() { m_drunkTimer = 0; uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256); SetDrunkValue(drunk); } DrunkenState Player::GetDrunkenstateByValue(uint16 value) { if (value >= 23000) return DRUNKEN_SMASHED; if (value >= 12800) return DRUNKEN_DRUNK; if (value & 0xFFFE) return DRUNKEN_TIPSY; return DRUNKEN_SOBER; } void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId) { uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk); m_drunk = newDrunkenValue; SetUInt16Value(PLAYER_BYTES_3, 0, uint16(getGender()) | (m_drunk & 0xFFFE)); uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk); // special drunk invisibility detection if (newDrunkenState >= DRUNKEN_DRUNK) m_detectInvisibilityMask |= (1<<6); else m_detectInvisibilityMask &= ~(1<<6); if (newDrunkenState == oldDrunkenState) return; WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4)); data << GetObjectGuid(); data << uint32(newDrunkenState); data << uint32(itemId); SendMessageToSet(&data, true); } void Player::Update( uint32 update_diff, uint32 p_time ) { if(!IsInWorld()) return; // remove failed timed Achievements GetAchievementMgr().DoFailedTimedAchievementCriterias(); // undelivered mail if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL)) { SendNewMail(); ++unReadMails; // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated) m_nextMailDelivereTime = 0; } //used to implement delayed far teleports SetCanDelayTeleport(true); Unit::Update( update_diff, p_time ); SetCanDelayTeleport(false); // update player only attacks if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK)) { setAttackTimer(RANGED_ATTACK, (update_diff >= ranged_att ? 0 : ranged_att - update_diff) ); } time_t now = time (NULL); UpdatePvPFlag(now); UpdateContestedPvP(update_diff); UpdateDuelFlag(now); CheckDuelDistance(now); UpdateAfkReport(now); // Update items that have just a limited lifetime if (now>m_Last_tick) UpdateItemDuration(uint32(now- m_Last_tick)); if (now > m_Last_tick + IN_MILLISECONDS) UpdateSoulboundTradeItems(); if (!m_timedquests.empty()) { QuestSet::iterator iter = m_timedquests.begin(); while (iter != m_timedquests.end()) { QuestStatusData& q_status = mQuestStatus[*iter]; if ( q_status.m_timer <= update_diff ) { uint32 quest_id = *iter; ++iter; // current iter will be removed in FailQuest FailQuest(quest_id); } else { q_status.m_timer -= update_diff; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; ++iter; } } } if (hasUnitState(UNIT_STAT_MELEE_ATTACKING)) { UpdateMeleeAttackingState(); Unit *pVictim = getVictim(); if (pVictim && !IsNonMeleeSpellCasted(false)) { Player *vOwner = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself(); if (vOwner && vOwner->IsPvP() && !IsInDuelWith(vOwner)) { UpdatePvP(true); RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); } } } if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) { if (roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update { time_t time_inn = time(NULL)-GetTimeInnEnter(); if (time_inn >= 10) //freeze update { float bubble = 0.125f*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_INGAME); //speed collect rest bonus (section/in hour) SetRestBonus( float(GetRestBonus()+ time_inn*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble )); UpdateInnerTime(time(NULL)); } } } if (m_regenTimer) { if (update_diff >= m_regenTimer) m_regenTimer = 0; else m_regenTimer -= update_diff; } if (m_weaponChangeTimer > 0) { if (update_diff >= m_weaponChangeTimer) m_weaponChangeTimer = 0; else m_weaponChangeTimer -= update_diff; } if (m_zoneUpdateTimer > 0) { if (update_diff >= m_zoneUpdateTimer) { uint32 newzone, newarea; GetZoneAndAreaId(newzone,newarea); if ( m_zoneUpdateId != newzone ) UpdateZone(newzone,newarea); // also update area else { // use area updates as well // needed for free far all arenas for example if ( m_areaUpdateId != newarea ) UpdateArea(newarea); m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL; } } else m_zoneUpdateTimer -= update_diff; } if (m_timeSyncTimer > 0) { if (update_diff >= m_timeSyncTimer) SendTimeSync(); else m_timeSyncTimer -= update_diff; } if (isAlive()) { // if no longer casting, set regen power as soon as it is up. if (!IsUnderLastManaUseEffect() && !HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN)) SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER); if (!m_regenTimer) RegenerateAll(IsUnderLastManaUseEffect() ? REGEN_TIME_PRECISE : REGEN_TIME_FULL); } if (!isAlive() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) && getDeathState() != GHOULED ) SetHealth(0); if (m_deathState == JUST_DIED) KillPlayer(); if (m_nextSave > 0) { if (update_diff >= m_nextSave) { // m_nextSave reseted in SaveToDB call SaveToDB(); DETAIL_LOG("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow()); } else m_nextSave -= update_diff; } //Handle Water/drowning HandleDrowning(update_diff); //Handle detect stealth players if (m_DetectInvTimer > 0) { if (update_diff >= m_DetectInvTimer) { HandleStealthedUnitsDetection(); m_DetectInvTimer = 3000; } else m_DetectInvTimer -= update_diff; } // Played time if (now > m_Last_tick) { uint32 elapsed = uint32(now - m_Last_tick); m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time m_Last_tick = now; } if (m_drunk) { m_drunkTimer += update_diff; if (m_drunkTimer > 10*IN_MILLISECONDS) HandleSobering(); } if (HasPendingBind()) { if (_pendingBindTimer <= p_time) { BindToInstance(); SetPendingBind(NULL, 0); } else _pendingBindTimer -= p_time; } // not auto-free ghost from body in instances if (m_deathTimer > 0 && !GetMap()->Instanceable() && getDeathState() != GHOULED) { if (p_time >= m_deathTimer) { m_deathTimer = 0; BuildPlayerRepop(); RepopAtGraveyard(); } else m_deathTimer -= p_time; } UpdateEnchantTime(update_diff); UpdateHomebindTime(update_diff); // group update SendUpdateToOutOfRangeGroupMembers(); Pet* pet = GetPet(); if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGuid() && (pet->GetObjectGuid() != GetCharmGuid()))) pet->Unsummon(PET_SAVE_REAGENTS, this); if (IsHasDelayedTeleport()) TeleportTo(m_teleport_dest, m_teleport_options); // Playerbot mod if (!sWorld.getConfig(CONFIG_BOOL_PLAYERBOT_DISABLE)) { if (m_playerbotAI) m_playerbotAI->UpdateAI(p_time); else if (m_playerbotMgr) m_playerbotMgr->UpdateAI(p_time); } } void Player::SetDeathState(DeathState s) { uint32 ressSpellId = 0; bool cur = isAlive(); if (s == JUST_DIED && cur) { // drunken state is cleared on death SetDrunkValue(0); // lost combo points at any target (targeted combo points clear in Unit::SetDeathState) ClearComboPoints(); clearResurrectRequestData(); // remove form before other mods to prevent incorrect stats calculation RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT); if (Pet* pet = GetPet()) { if (pet->isControlled()) SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber()); //FIXME: is pet dismissed at dying or releasing spirit? if second, add SetDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD) RemovePet(PET_SAVE_REAGENTS); } // save value before aura remove in Unit::SetDeathState ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL); // passive spell if(!ressSpellId) ressSpellId = GetResurrectionSpellId(); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1); if (InstanceData* mapInstance = GetInstanceData()) mapInstance->OnPlayerDeath(this); } Unit::SetDeathState(s); // restore resurrection spell id for player after aura remove if (s == JUST_DIED && cur && ressSpellId) SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); if (!cur && s == ALIVE) { _RemoveAllItemMods(); _ApplyAllItemMods(); } if (isAlive() && !cur) { //clear aura case after resurrection by another way (spells will be applied before next death) SetUInt32Value(PLAYER_SELF_RES_SPELL, 0); // restore default warrior stance if (getClass()== CLASS_WARRIOR) CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true); } } bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) { // 0 1 2 3 4 5 6 7 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, " // 8 9 10 11 12 13 14 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, " // 15 16 17 18 19 20 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache, character_declinedname.genitive " Field *fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); uint8 pRace = fields[2].GetUInt8(); uint8 pClass = fields[3].GetUInt8(); PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass); if(!info) { sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid); return false; } *p_data << ObjectGuid(HIGHGUID_PLAYER, guid); *p_data << fields[1].GetString(); // name *p_data << uint8(pRace); // race *p_data << uint8(pClass); // class *p_data << uint8(fields[4].GetUInt8()); // gender uint32 playerBytes = fields[5].GetUInt32(); *p_data << uint8(playerBytes); // skin *p_data << uint8(playerBytes >> 8); // face *p_data << uint8(playerBytes >> 16); // hair style *p_data << uint8(playerBytes >> 24); // hair color uint32 playerBytes2 = fields[6].GetUInt32(); *p_data << uint8(playerBytes2 & 0xFF); // facial hair *p_data << uint8(fields[7].GetUInt8()); // level *p_data << uint32(fields[8].GetUInt32()); // zone *p_data << uint32(fields[9].GetUInt32()); // map *p_data << fields[10].GetFloat(); // x *p_data << fields[11].GetFloat(); // y *p_data << fields[12].GetFloat(); // z *p_data << uint32(fields[13].GetUInt32()); // guild id uint32 char_flags = 0; uint32 playerFlags = fields[14].GetUInt32(); uint32 atLoginFlags = fields[15].GetUInt32(); if (playerFlags & PLAYER_FLAGS_HIDE_HELM) char_flags |= CHARACTER_FLAG_HIDE_HELM; if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK) char_flags |= CHARACTER_FLAG_HIDE_CLOAK; if (playerFlags & PLAYER_FLAGS_GHOST) char_flags |= CHARACTER_FLAG_GHOST; if (atLoginFlags & AT_LOGIN_RENAME) char_flags |= CHARACTER_FLAG_RENAME; if (sWorld.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED)) { if(!fields[20].GetCppString().empty()) char_flags |= CHARACTER_FLAG_DECLINED; } else char_flags |= CHARACTER_FLAG_DECLINED; *p_data << uint32(char_flags); // character flags // character customize/faction/race change flags if(atLoginFlags & AT_LOGIN_CUSTOMIZE) *p_data << uint32(CHAR_CUSTOMIZE_FLAG_CUSTOMIZE); else if(atLoginFlags & AT_LOGIN_CHANGE_FACTION) *p_data << uint32(CHAR_CUSTOMIZE_FLAG_FACTION); else if(atLoginFlags & AT_LOGIN_CHANGE_RACE) *p_data << uint32(CHAR_CUSTOMIZE_FLAG_RACE); else *p_data << uint32(CHAR_CUSTOMIZE_FLAG_NONE); // First login *p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0); // Pets info { uint32 petDisplayId = 0; uint32 petLevel = 0; uint32 petFamily = 0; // show pet at selection character in character list only for non-ghost character if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT)) { uint32 entry = fields[16].GetUInt32(); CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry); if (cInfo) { petDisplayId = fields[17].GetUInt32(); petLevel = fields[18].GetUInt32(); petFamily = cInfo->family; } } *p_data << uint32(petDisplayId); *p_data << uint32(petLevel); *p_data << uint32(petFamily); } Tokens data(fields[19].GetCppString(), ' '); for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++) { uint32 visualbase = slot * 2; uint32 item_id = atoi(data[visualbase]); const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id); if(!proto) { *p_data << uint32(0); *p_data << uint8(0); *p_data << uint32(0); continue; } SpellItemEnchantmentEntry const *enchant = NULL; uint32 enchants = atoi(data[visualbase + 1]); for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot) { // values stored in 2 uint16 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16); if(!enchantId) continue; if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))) break; } *p_data << uint32(proto->DisplayInfoID); *p_data << uint8(proto->InventoryType); *p_data << uint32(enchant ? enchant->aura_id : 0); } *p_data << uint32(0); // bag 1 display id *p_data << uint8(0); // bag 1 inventory type *p_data << uint32(0); // enchant? *p_data << uint32(0); // bag 2 display id *p_data << uint8(0); // bag 2 inventory type *p_data << uint32(0); // enchant? *p_data << uint32(0); // bag 3 display id *p_data << uint8(0); // bag 3 inventory type *p_data << uint32(0); // enchant? *p_data << uint32(0); // bag 4 display id *p_data << uint8(0); // bag 4 inventory type *p_data << uint32(0); // enchant? return true; } void Player::ToggleAFK() { ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); // afk player not allowed in battleground if (isAFK() && InBattleGround() && !InArena()) LeaveBattleground(); } void Player::ToggleDND() { ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); } uint8 Player::chatTag() const { // it's bitmask // 0x1 - afk // 0x2 - dnd // 0x4 - gm // 0x8 - ?? if (isGMChat()) // Always show GM icons if activated return 4; if (isAFK()) return 1; if (isDND()) return 3; return 0; } bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options) { if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation)) { sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid); return false; } if (GetMapId() != mapid) { if (!(options & TELE_TO_CHECKED)) { if (!CheckTransferPossibility(mapid)) { if (GetTransport()) TeleportToHomebind(); DEBUG_LOG("Player::TeleportTo %s is NOT teleported to map %u (requirements check failed)", GetName(), mapid); return false; // normal client can't teleport to this map... } else options |= TELE_TO_CHECKED; } DEBUG_LOG("Player::TeleportTo %s is being far teleported to map %u", GetName(), mapid); } else { DEBUG_LOG("Player::TeleportTo %s is being near teleported to map %u", GetName(), mapid); } // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later) Pet* pet = GetPet(); // Playerbot mod: if this user has bots, tell them to stop following master // so they don't try to follow the master after the master teleports if (GetPlayerbotMgr()) GetPlayerbotMgr()->Stay(); MapEntry const* mEntry = sMapStore.LookupEntry(mapid); if(!mEntry) { sLog.outError("TeleportTo: invalid map entry (id %d). possible disk or memory error.", mapid); return false; } // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)... // don't let gm level > 1 either if(!InBattleGround() && mEntry->IsBattleGroundOrArena()) return false; // client without expansion support if (Group* grp = GetGroup()) grp->SetPlayerMap(GetObjectGuid(), mapid); // if we were on a transport, leave if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport) { m_transport->RemovePassenger(this); SetTransport(NULL); m_movementInfo.ClearTransportData(); } if (GetVehicleKit()) GetVehicleKit()->RemoveAllPassengers(); ExitVehicle(); // The player was ported to another map and looses the duel immediately. // We have to perform this check before the teleport, otherwise the // ObjectAccessor won't find the flag. if (duel && GetMapId() != mapid) if (GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER))) DuelComplete(DUEL_FLED); // reset movement flags at teleport, because player will continue move with these flags after teleport m_movementInfo.SetMovementFlags(MOVEFLAG_NONE); DisableSpline(); if (GetMapId() == mapid && !m_transport) { //lets reset far teleport flag if it wasn't reset during chained teleports SetSemaphoreTeleportFar(false); //setup delayed teleport flag //if teleport spell is casted in Unit::Update() func //then we need to delay it until update process will be finished if (SetDelayedTeleportFlagIfCan()) { SetSemaphoreTeleportNear(true); //lets save teleport destination for player m_teleport_dest = WorldLocation(mapid, x, y, z, orientation); m_teleport_options = options; return true; } if (!(options & TELE_TO_NOT_UNSUMMON_PET)) { //same map, only remove pet if out of range for new position if (pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance())) UnsummonPetTemporaryIfAny(); } if (!(options & TELE_TO_NOT_LEAVE_COMBAT)) CombatStop(); // this will be used instead of the current location in SaveToDB m_teleport_dest = WorldLocation(mapid, x, y, z, orientation); SetFallInformation(0, z); // code for finish transfer called in WorldSession::HandleMovementOpcodes() // at client packet MSG_MOVE_TELEPORT_ACK SetSemaphoreTeleportNear(true); // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing if(!GetSession()->PlayerLogout()) { WorldPacket data; BuildTeleportAckMsg(data, x, y, z, orientation); GetSession()->SendPacket(&data); } } else { // far teleport to another map Map* oldmap = IsInWorld() ? GetMap() : NULL; // check if we can enter before stopping combat / removing pet / totems / interrupting spells // Check enter rights before map getting to avoid creating instance copy for player // this check not dependent from map instance copy and same for all instance copies of selected map if (!sMapMgr.CanPlayerEnter(mapid, this)) return false; // If the map is not created, assume it is possible to enter it. // It will be created in the WorldPortAck. DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(mapid); Map *map = sMapMgr.FindMap(mapid, state ? state->GetInstanceId() : 0); if (!map || map->CanEnter(this)) { //lets reset near teleport flag if it wasn't reset during chained teleports SetSemaphoreTeleportNear(false); //setup delayed teleport flag //if teleport spell is casted in Unit::Update() func //then we need to delay it until update process will be finished if (SetDelayedTeleportFlagIfCan()) { SetSemaphoreTeleportFar(true); //lets save teleport destination for player m_teleport_dest = WorldLocation(mapid, x, y, z, orientation); m_teleport_options = options; return true; } SetSelectionGuid(ObjectGuid()); CombatStop(); ResetContestedPvP(); // remove player from battleground on far teleport (when changing maps) if (BattleGround const* bg = GetBattleGround()) { // Note: at battleground join battleground id set before teleport // and we already will found "current" battleground // just need check that this is targeted map or leave if (bg->GetMapId() != mapid) LeaveBattleground(false); // don't teleport to entry point } // remove pet on map change UnsummonPetTemporaryIfAny(); // remove all dyn objects RemoveAllDynObjects(); // stop spellcasting // not attempt interrupt teleportation spell at caster teleport if (!(options & TELE_TO_SPELL)) if (IsNonMeleeSpellCasted(true)) InterruptNonMeleeSpells(true); //remove auras before removing from map... RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING); if (!GetSession()->PlayerLogout()) { // send transfer packet to display load screen WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4)); data << uint32(mapid); if (m_transport) { data << uint32(m_transport->GetEntry()); data << uint32(GetMapId()); } GetSession()->SendPacket(&data); } // remove from old map now if (oldmap) oldmap->Remove(this, false); // new final coordinates float final_x = x; float final_y = y; float final_z = z; float final_o = orientation; if (m_transport) { final_x += m_movementInfo.GetTransportPos()->x; final_y += m_movementInfo.GetTransportPos()->y; final_z += m_movementInfo.GetTransportPos()->z; final_o += m_movementInfo.GetTransportPos()->o; } m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o); SetFallInformation(0, final_z); // if the player is saved before worldport ack (at logout for example) // this will be used instead of the current location in SaveToDB // move packet sent by client always after far teleport // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet SetSemaphoreTeleportFar(true); if (!GetSession()->PlayerLogout()) { // transfer finished, inform client to start load WorldPacket data(SMSG_NEW_WORLD, (20)); data << uint32(mapid); if (m_transport) { data << float(m_movementInfo.GetTransportPos()->x); data << float(m_movementInfo.GetTransportPos()->y); data << float(m_movementInfo.GetTransportPos()->z); data << float(m_movementInfo.GetTransportPos()->o); } else { data << float(final_x); data << float(final_y); data << float(final_z); data << float(final_o); } GetSession()->SendPacket( &data ); SendSavedInstances(); } } else return false; } return true; } bool Player::TeleportToBGEntryPoint() { RemoveSpellsCausingAura(SPELL_AURA_MOUNTED); RemoveSpellsCausingAura(SPELL_AURA_FLY); ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE); ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE); return TeleportTo(m_bgData.joinPos); } void Player::ProcessDelayedOperations() { if (m_DelayedOperations == 0) return; if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER) { ResurrectPlayer(0.0f, false); if (GetMaxHealth() > m_resurrectHealth) SetHealth( m_resurrectHealth ); else SetHealth( GetMaxHealth() ); if (GetMaxPower(POWER_MANA) > m_resurrectMana) SetPower(POWER_MANA, m_resurrectMana ); else SetPower(POWER_MANA, GetMaxPower(POWER_MANA) ); SetPower(POWER_RAGE, 0 ); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) ); SpawnCorpseBones(); } if (m_DelayedOperations & DELAYED_SAVE_PLAYER) { SaveToDB(); } if (m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER) { CastSpell(this, 26013, true); // Deserter } if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE) { if (m_bgData.mountSpell) { CastSpell(this, m_bgData.mountSpell, true); m_bgData.mountSpell = 0; } } if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE) { if (m_bgData.HasTaxiPath()) { m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]); m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]); m_bgData.ClearTaxiPath(); ContinueTaxiFlight(); } } //we have executed ALL delayed ops, so clear the flag m_DelayedOperations = 0; } void Player::AddToWorld() { ///- Do not add/remove the player from the object storage ///- It will crash when updating the ObjectAccessor ///- The player should only be added when logging in Unit::AddToWorld(); for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i) { if (m_items[i]) m_items[i]->AddToWorld(); } } void Player::RemoveFromWorld() { for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i) { if (m_items[i]) m_items[i]->RemoveFromWorld(); } ///- Do not add/remove the player from the object storage ///- It will crash when updating the ObjectAccessor ///- The player should only be removed when logging out if (IsInWorld()) GetCamera().ResetView(); Unit::RemoveFromWorld(); } void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker ) { float addRage; float rageconversion = float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f; if (attacker) { addRage = ((damage/rageconversion*7.5f + weaponSpeedHitFactor)/2.0f); // talent who gave more rage on attack addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f; } else { addRage = damage/rageconversion*2.5f; // Berserker Rage effect if (HasAura(18499, EFFECT_INDEX_0)) addRage *= 1.3f; } addRage *= sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME); ModifyPower(POWER_RAGE, uint32(addRage*10)); } void Player::RegenerateAll(uint32 diff) { // Not in combat or they have regeneration if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) || HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() || m_baseHealthRegen ) { RegenerateHealth(diff); if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN)) { Regenerate(POWER_RAGE, diff); if (getClass() == CLASS_DEATH_KNIGHT) Regenerate(POWER_RUNIC_POWER, diff); } } Regenerate(POWER_ENERGY, diff); Regenerate(POWER_MANA, diff); if (getClass() == CLASS_DEATH_KNIGHT) Regenerate(POWER_RUNE, diff); m_regenTimer = IsUnderLastManaUseEffect() ? REGEN_TIME_PRECISE : REGEN_TIME_FULL; } // diff contains the time in milliseconds since last regen. void Player::Regenerate(Powers power, uint32 diff) { uint32 curValue = GetPower(power); uint32 maxValue = GetMaxPower(power); float addvalue = 0.0f; switch (power) { case POWER_MANA: { if (HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN)) break; float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA); if (IsUnderLastManaUseEffect()) { // Mangos Updates Mana in intervals of 2s, which is correct addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * (float)REGEN_TIME_FULL/IN_MILLISECONDS; } else { addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * (float)REGEN_TIME_FULL/IN_MILLISECONDS; } break; } case POWER_RAGE: // Regenerate rage { float RageDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS); addvalue += 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec) break; } case POWER_ENERGY: // Regenerate energy (rogue) { float EnergyRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_ENERGY); addvalue += 20 * EnergyRate; break; } case POWER_RUNIC_POWER: { float RunicPowerDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS); addvalue += 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick break; } case POWER_RUNE: { if (getClass() != CLASS_DEATH_KNIGHT) break; for(uint32 rune = 0; rune < MAX_RUNES; ++rune) { if (uint16 cd = GetRuneCooldown(rune)) // if we have cooldown, reduce it... { uint32 cd_diff = diff; AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i) if ((*i)->GetModifier()->m_miscvalue == int32(power) && (*i)->GetMiscBValue()==GetCurrentRune(rune)) cd_diff = cd_diff * ((*i)->GetModifier()->m_amount + 100) / 100; SetRuneCooldown(rune, (cd < cd_diff) ? 0 : cd - cd_diff); // check if we don't have cooldown, need convert and that our rune wasn't already converted if (cd < cd_diff && m_runes->IsRuneNeedsConvert(rune) && GetBaseRune(rune) == GetCurrentRune(rune)) { // currently all delayed rune converts happen with rune death // ConvertedBy was initialized at proc ConvertRune(rune, RUNE_DEATH); SetNeedConvertRune(rune, false); } } else if (m_runes->IsRuneNeedsConvert(rune) && GetBaseRune(rune) == GetCurrentRune(rune)) { // currently all delayed rune converts happen with rune death // ConvertedBy was initialized at proc ConvertRune(rune, RUNE_DEATH); SetNeedConvertRune(rune, false); } } break; } case POWER_FOCUS: case POWER_HAPPINESS: case POWER_HEALTH: default: break; } // Mana regen calculated in Player::UpdateManaRegen() // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras if (power != POWER_MANA) { AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i) if ((*i)->GetModifier()->m_miscvalue == int32(power)) addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f; } // addvalue computed on a 2sec basis. => update to diff time uint32 _addvalue = ceil(fabs(addvalue * float(diff) / (float)REGEN_TIME_FULL)); if (power != POWER_RAGE && power != POWER_RUNIC_POWER) { curValue += _addvalue; if (curValue > maxValue) curValue = maxValue; } else { if (curValue <= _addvalue) curValue = 0; else curValue -= _addvalue; } SetPower(power, curValue); } void Player::RegenerateHealth(uint32 diff) { uint32 curValue = GetHealth(); uint32 maxValue = GetMaxHealth(); if (curValue >= maxValue) return; float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH); float addvalue = 0.0f; // polymorphed case if ( IsPolymorphed() ) addvalue = (float)GetMaxHealth()/3; // normal regen case (maybe partly in combat case) else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ) { addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate; if (!isInCombat()) { AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT); for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i) addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; } else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT)) addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f; if(!IsStandState()) addvalue *= 1.5; } // always regeneration bonus (including combat) addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT); addvalue += m_baseHealthRegen / 2.5f; //From ITEM_MOD_HEALTH_REGEN. It is correct tick amount? if (addvalue < 0) addvalue = 0; addvalue *= (float)diff / REGEN_TIME_FULL; ModifyHealth(int32(addvalue)); } Creature* Player::GetNPCIfCanInteractWith(ObjectGuid guid, uint32 npcflagmask) { // some basic checks if (!guid || !IsInWorld() || IsTaxiFlying()) return NULL; // not in interactive state if (hasUnitState(UNIT_STAT_CAN_NOT_REACT_OR_LOST_CONTROL) && !hasUnitState(UNIT_STAT_ON_VEHICLE)) return NULL; // exist (we need look pets also for some interaction (quest/etc) Creature *unit = GetMap()->GetAnyTypeCreature(guid); if (!unit) return NULL; // appropriate npc type if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask )) return NULL; if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER) { if (getClass() != CLASS_HUNTER) return NULL; } // if a dead unit should be able to talk - the creature must be alive and have special flags if (!unit->isAlive()) return NULL; if (isAlive() && unit->isInvisibleForAlive()) return NULL; // not allow interaction under control, but allow with own pets if (unit->GetCharmerGuid()) return NULL; // not enemy if (unit->IsHostileTo(this)) return NULL; // not too far if (!unit->IsWithinDistInMap(this, INTERACTION_DISTANCE)) return NULL; return unit; } GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid, uint32 gameobject_type) const { // some basic checks if (!guid || !IsInWorld() || IsTaxiFlying()) return NULL; // not in interactive state if (hasUnitState(UNIT_STAT_CAN_NOT_REACT_OR_LOST_CONTROL) && !hasUnitState(UNIT_STAT_ON_VEHICLE)) return NULL; if (GameObject *go = GetMap()->GetGameObject(guid)) { if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE) { float maxdist; switch(go->GetGoType()) { // TODO: find out how the client calculates the maximal usage distance to spellless working // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number case GAMEOBJECT_TYPE_GUILD_BANK: case GAMEOBJECT_TYPE_MAILBOX: maxdist = 10.0f; break; case GAMEOBJECT_TYPE_FISHINGHOLE: maxdist = 20.0f+CONTACT_DISTANCE; // max spell range break; default: maxdist = INTERACTION_DISTANCE; break; } if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned()) return go; sLog.outError("GetGameObjectIfCanInteractWith: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal %f is allowed)", go->GetGOInfo()->name, go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this), maxdist); } } return NULL; } bool Player::IsUnderWater() const { return GetTerrain()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ()+2); } void Player::SetInWater(bool apply) { if (m_isInWater==apply) return; //define player in water by opcodes //move player's guid into HateOfflineList of those mobs //which can't swim and move guid back into ThreatList when //on surface. //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water m_isInWater = apply; // remove auras that need water/land RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER); getHostileRefManager().updateThreatTables(); } struct SetGameMasterOnHelper { explicit SetGameMasterOnHelper() {} void operator()(Unit* unit) const { unit->setFaction(35); unit->getHostileRefManager().setOnlineOfflineState(false); } }; struct SetGameMasterOffHelper { explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {} void operator()(Unit* unit) const { unit->setFaction(faction); unit->getHostileRefManager().setOnlineOfflineState(true); } uint32 faction; }; void Player::SetGameMaster(bool on) { if (on) { m_ExtraFlags |= PLAYER_EXTRA_GM_ON; setFaction(35); SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM); CallForAllControlledUnits(SetGameMasterOnHelper(), CONTROLLED_PET|CONTROLLED_TOTEMS|CONTROLLED_GUARDIANS|CONTROLLED_CHARM); SetFFAPvP(false); ResetContestedPvP(); getHostileRefManager().setOnlineOfflineState(false); CombatStopWithPets(); SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases } else { m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON; setFactionForRace(getRace()); RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM); // restore phase AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE); SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false); CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()), CONTROLLED_PET|CONTROLLED_TOTEMS|CONTROLLED_GUARDIANS|CONTROLLED_CHARM); // restore FFA PvP Server state if (sWorld.IsFFAPvPRealm()) SetFFAPvP(true); // restore FFA PvP area state, remove not allowed for GM mounts UpdateArea(m_areaUpdateId); getHostileRefManager().setOnlineOfflineState(true); } m_camera.UpdateVisibilityForOwner(); UpdateObjectVisibility(); UpdateForQuestWorldObjects(); } void Player::SetGMVisible(bool on) { if (on) { m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag // Reapply stealth/invisibility if active or show if not any if (HasAuraType(SPELL_AURA_MOD_STEALTH)) SetVisibility(VISIBILITY_GROUP_STEALTH); else if (HasAuraType(SPELL_AURA_MOD_INVISIBILITY)) SetVisibility(VISIBILITY_GROUP_INVISIBILITY); else SetVisibility(VISIBILITY_ON); } else { m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag SetAcceptWhispers(false); SetGameMaster(true); SetVisibility(VISIBILITY_OFF); } } bool Player::IsGroupVisibleFor(Player* p) const { switch(sWorld.getConfig(CONFIG_UINT32_GROUP_VISIBILITY)) { default: return IsInSameGroupWith(p); case 1: return IsInSameRaidWith(p); case 2: return GetTeam()==p->GetTeam(); } } bool Player::IsInSameGroupWith(Player const* p) const { return (p==this || (GetGroup() != NULL && GetGroup()->SameSubGroup((Player*)this, (Player*)p))); } ///- If the player is invited, remove him. If the group if then only 1 person, disband the group. /// \todo Shouldn't we also check if there is no other invitees before disbanding the group? void Player::UninviteFromGroup() { Group* group = GetGroupInvite(); if(!group) return; group->RemoveInvite(this); if (group->GetMembersCount() <= 1) // group has just 1 member => disband { if (group->IsCreated()) { group->Disband(true); sObjectMgr.RemoveGroup(group); } else group->RemoveAllInvites(); delete group; } } void Player::RemoveFromGroup(Group* group, ObjectGuid guid) { if (group) { // remove all auras affecting only group members if (Player *pLeaver = sObjectMgr.GetPlayer(guid)) { for(GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) { if (Player *pGroupGuy = itr->getSource()) { // dont remove my auras from myself if (pGroupGuy->GetObjectGuid() == guid) continue; // remove all buffs cast by me from group members before leaving pGroupGuy->RemoveAllGroupBuffsFromCaster(guid); // remove from me all buffs cast by group members pLeaver->RemoveAllGroupBuffsFromCaster(pGroupGuy->GetObjectGuid()); } } } // remove member from group if (group->RemoveMember(guid, 0) <= 1) { // group->Disband(); already disbanded in RemoveMember sObjectMgr.RemoveGroup(group); delete group; // removemember sets the player's group pointer to NULL } } } void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool ReferAFriend) { WorldPacket data(SMSG_LOG_XPGAIN, 21); data << (victim ? victim->GetObjectGuid() : ObjectGuid());// guid data << uint32(GivenXP+BonusXP); // total experience data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type if (victim) { data << uint32(GivenXP); // experience without rested bonus data << float(1); // 1 - none 0 - 100% group bonus output } data << uint8(ReferAFriend ? 1 : 0); // Refer-A-Friend State GetSession()->SendPacket(&data); } void Player::GiveXP(uint32 xp, Unit* victim) { if ( xp < 1 ) return; if(!isAlive()) return; if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_XP_USER_DISABLED)) return; if (hasUnitState(UNIT_STAT_ON_VEHICLE)) return; uint32 level = getLevel(); //prevent Northrend Level Leeching :P if (level < 66 && GetMapId() == 571) return; // XP to money conversion processed in Player::RewardQuest if (level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) return; if (victim) { // handle SPELL_AURA_MOD_KILL_XP_PCT auras Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT); for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i) xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f)); } else { // handle SPELL_AURA_MOD_QUEST_XP_PCT auras Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT); for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i) xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f)); } uint32 bonus_xp = 0; bool ReferAFriend = false; if (CheckRAFConditions()) { // RAF bonus exp don't decrease rest exp ReferAFriend = true; bonus_xp = xp * (sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_XP) - 1); } else // XP resting bonus for kill bonus_xp = victim ? GetXPRestBonus(xp) : 0; SendLogXPGain(xp,victim,bonus_xp,ReferAFriend); uint32 curXP = GetUInt32Value(PLAYER_XP); uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP); uint32 newXP = curXP + xp + bonus_xp; while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) ) { newXP -= nextLvlXP; if ( level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) ) { GiveLevel(level + 1); level = getLevel(); // Refer-A-Friend if (GetAccountLinkedState() == STATE_REFERRAL || GetAccountLinkedState() == STATE_DUAL) { if (level < sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL)) { if (sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL) < 1.0f) { if ( level%uint8(1.0f/sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL)) == 0 ) ChangeGrantableLevels(1); } else ChangeGrantableLevels(uint8(sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL))); } } } level = getLevel(); nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP); } SetUInt32Value(PLAYER_XP, newXP); } // Update player to next level // Current player experience not update (must be update by caller) void Player::GiveLevel(uint32 level) { if ( level == getLevel() ) return; PlayerLevelInfo info; sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info); PlayerClassLevelInfo classInfo; sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo); // send levelup info to client WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4)); data << uint32(level); data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth())); // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6) data << uint32(int32(classInfo.basemana) - int32(GetCreateMana())); data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); // end for for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4) data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i))); GetSession()->SendPacket(&data); SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level)); //update level, max level of skills m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset _ApplyAllLevelScaleItemMods(false); SetLevel(level); UpdateSkillsForLevel (); // save base values (bonuses already included in stored stats for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) SetCreateStat(Stats(i), info.stats[i]); SetCreateHealth(classInfo.basehealth); SetCreateMana(classInfo.basemana); InitTalentForLevel(); InitTaxiNodesForLevel(); InitGlyphsForLevel(); UpdateAllStats(); // set current level health and mana/energy to maximum after applying all mods. if (isAlive()) SetHealth(GetMaxHealth()); SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY)); if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE)) SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE)); SetPower(POWER_FOCUS, 0); SetPower(POWER_HAPPINESS, 0); _ApplyAllLevelScaleItemMods(true); // update level to hunter/summon pet if (Pet* pet = GetPet()) pet->SynchronizeLevelWithOwner(); if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask())) MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry)); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL); GetLFGState()->Update(); } void Player::UpdateFreeTalentPoints(bool resetIfNeed) { uint32 level = getLevel(); // talents base at level diff ( talents = level - 9 but some can be used already) if (level < 10) { // Remove all talent points if (m_usedTalentCount > 0) // Free any used talents { if (resetIfNeed) resetTalents(true); SetFreeTalentPoints(0); } } else { if (m_specsCount == 0) { m_specsCount = 1; m_activeSpec = 0; } uint32 talentPointsForLevel = CalculateTalentsPoints(); // if used more that have then reset if (m_usedTalentCount > talentPointsForLevel) { if (resetIfNeed && GetSession()->GetSecurity() < SEC_ADMINISTRATOR) resetTalents(true); else SetFreeTalentPoints(0); } // else update amount of free points else SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount); } ResetTalentsCount(); } void Player::InitTalentForLevel() { UpdateFreeTalentPoints(); if (!GetSession()->PlayerLoading()) SendTalentsInfoData(false); // update at client } void Player::InitStatsForLevel(bool reapplyMods) { if (reapplyMods) //reapply stats values only on .reset stats (level) command _RemoveAllStatBonuses(); PlayerClassLevelInfo classInfo; sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo); PlayerLevelInfo info; sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info); SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) ); SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel())); // reset before any aura state sources (health set/aura apply) SetUInt32Value(UNIT_FIELD_AURASTATE, 0); UpdateSkillsForLevel (); // set default cast time multiplier SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // save base values (bonuses already included in stored stats for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) SetCreateStat(Stats(i), info.stats[i]); for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) SetStat(Stats(i), info.stats[i]); SetCreateHealth(classInfo.basehealth); //set create powers SetCreateMana(classInfo.basemana); SetArmor(int32(m_createStats[STAT_AGILITY]*2)); InitStatBuffMods(); //reset rating fields values for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index) SetUInt32Value(index, 0); SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0); for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) { SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0); SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0); SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f); } //reset attack power, damage and attack speed fields SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f ); SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f ); SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f ); SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 ); SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 ); SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f); SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 ); SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 ); SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f); // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f); SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f); SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f); // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i) SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f); SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f); SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f); SetUInt32Value(PLAYER_SHIELD_BLOCK, 0); // Dodge percentage SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f); // set armor (resistance 0) to original value (create_agility*2) SetArmor(int32(m_createStats[STAT_AGILITY]*2)); SetResistanceBuffMods(SpellSchools(0), true, 0.0f); SetResistanceBuffMods(SpellSchools(0), false, 0.0f); // set other resistance to original value (0) for (int i = 1; i < MAX_SPELL_SCHOOL; ++i) { SetResistance(SpellSchools(i), 0); SetResistanceBuffMods(SpellSchools(i), true, 0.0f); SetResistanceBuffMods(SpellSchools(i), false, 0.0f); } SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0); SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0); for(int i = 0; i < MAX_SPELL_SCHOOL; ++i) { SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0); SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f); } // Reset no reagent cost field for(int i = 0; i < 3; ++i) SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0); // Init data for form but skip reapply item mods for form InitDataForForm(reapplyMods); // save new stats for (int i = POWER_MANA; i < MAX_POWERS; ++i) SetMaxPower(Powers(i), GetCreatePowers(Powers(i))); SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later // cleanup mounted state (it will set correctly at aura loading if player saved at mount. SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0); // cleanup unit flags (will be re-applied if need at aura load). RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_PASSIVE | UNIT_FLAG_LOOTING | UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED | UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT ); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example. RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST); RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY); // restore if need some important flags SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default if (reapplyMods) //reapply stats values only on .reset stats (level) command _ApplyAllStatBonuses(); // set current level health and mana/energy to maximum after applying all mods. SetHealth(GetMaxHealth()); SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY)); if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE)) SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE)); SetPower(POWER_FOCUS, 0); SetPower(POWER_HAPPINESS, 0); SetPower(POWER_RUNIC_POWER, 0); // update level to hunter/summon pet if (Pet* pet = GetPet()) pet->SynchronizeLevelWithOwner(); } void Player::SendInitialSpells() { time_t curTime = time(NULL); time_t infTime = curTime + infinityCooldownDelayCheck; uint16 spellCount = 0; WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4))); data << uint8(0); size_t countPos = data.wpos(); data << uint16(spellCount); // spell count placeholder for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) continue; if(!itr->second.active || itr->second.disabled) continue; data << uint32(itr->first); data << uint16(0); // it's not slot id spellCount +=1; } data.put<uint16>(countPos,spellCount); // write real count value uint16 spellCooldowns = m_spellCooldowns.size(); data << uint16(spellCooldowns); for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr) { SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first); if(!sEntry) continue; data << uint32(itr->first); data << uint16(itr->second.itemid); // cast item id data << uint16(sEntry->Category); // spell category // send infinity cooldown in special format if (itr->second.end >= infTime) { data << uint32(1); // cooldown data << uint32(0x80000000); // category cooldown continue; } time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILLISECONDS : 0; if (sEntry->Category) // may be wrong, but anyway better than nothing... { data << uint32(0); // cooldown data << uint32(cooldown); // category cooldown } else { data << uint32(cooldown); // cooldown data << uint32(0); // category cooldown } } GetSession()->SendPacket(&data); DETAIL_LOG( "CHARACTER: Sent Initial Spells" ); } void Player::SendCalendarResult(CalendarResponseResult result, std::string str) { WorldPacket data(SMSG_CALENDAR_COMMAND_RESULT, 200); data << uint32(0); // unused data << uint8(0); // std::string, currently unused data << str; data << uint32(result); GetSession()->SendPacket(&data); } void Player::RemoveMail(uint32 id) { for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr) { if ((*itr)->messageID == id) { //do not delete item, because Player::removeMail() is called when returning mail to sender. m_mail.erase(itr); return; } } } void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count) { WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0)))); data << (uint32) mailId; data << (uint32) mailAction; data << (uint32) mailError; if ( mailError == MAIL_ERR_EQUIP_ERROR ) data << (uint32) equipError; else if ( mailAction == MAIL_ITEM_TAKEN ) { data << (uint32) item_guid; // item guid low? data << (uint32) item_count; // item count? } GetSession()->SendPacket(&data); } void Player::SendNewMail() { // deliver undelivered mail WorldPacket data(SMSG_RECEIVED_MAIL, 4); data << (uint32) 0; GetSession()->SendPacket(&data); } void Player::UpdateNextMailTimeAndUnreads() { // calculate next delivery time (min. from non-delivered mails // and recalculate unReadMail time_t cTime = time(NULL); m_nextMailDelivereTime = 0; unReadMails = 0; for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) { if((*itr)->deliver_time > cTime) { if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time) m_nextMailDelivereTime = (*itr)->deliver_time; } else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0) ++unReadMails; } } void Player::AddNewMailDeliverTime(time_t deliver_time) { if (deliver_time <= time(NULL)) // ready now { ++unReadMails; SendNewMail(); } else // not ready and no have ready mails { if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time) m_nextMailDelivereTime = deliver_time; } } bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) { // do character spell book cleanup (all characters) if(!IsInWorld() && !learning) // spell load case { sLog.outError("Player::addSpell: nonexistent in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id); CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id); } else sLog.outError("Player::addSpell: nonexistent in SpellStore spell #%u request.",spell_id); return false; } if(!SpellMgr::IsSpellValid(spellInfo,this,false)) { // do character spell book cleanup (all characters) if(!IsInWorld() && !learning) // spell load case { sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id); CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id); } else sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id); return false; } PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED; bool dependent_set = false; bool disabled_case = false; bool superceded_old = false; PlayerSpellMap::iterator itr = m_spells.find(spell_id); if (itr != m_spells.end()) { uint32 next_active_spell_id = 0; // fix activate state for non-stackable low rank (and find next spell for !active case) if (sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo)) { SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext(); for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr) { if (HasSpell(next_itr->second)) { // high rank already known so this must !active active = false; next_active_spell_id = next_itr->second; break; } } } // not do anything if already known in expected state if (itr->second.state != PLAYERSPELL_REMOVED && itr->second.active == active && itr->second.dependent == dependent && itr->second.disabled == disabled) { if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly itr->second.state = PLAYERSPELL_UNCHANGED; return false; } // dependent spell known as not dependent, overwrite state if (itr->second.state != PLAYERSPELL_REMOVED && !itr->second.dependent && dependent) { itr->second.dependent = dependent; if (itr->second.state != PLAYERSPELL_NEW) itr->second.state = PLAYERSPELL_CHANGED; dependent_set = true; } // update active state for known spell if (itr->second.active != active && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled) { itr->second.active = active; if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly itr->second.state = PLAYERSPELL_UNCHANGED; else if (itr->second.state != PLAYERSPELL_NEW) itr->second.state = PLAYERSPELL_CHANGED; if (active) { if (IsNeedCastPassiveLikeSpellAtLearn(spellInfo)) CastSpell (this, spell_id, true); } else if (IsInWorld()) { if (next_active_spell_id) { // update spell ranks in spellbook and action bar WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4); data << uint32(spell_id); data << uint32(next_active_spell_id); GetSession()->SendPacket( &data ); } else { WorldPacket data(SMSG_REMOVED_SPELL, 4); data << uint32(spell_id); GetSession()->SendPacket(&data); } } return active; // learn (show in spell book if active now) } if (itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED) { if (itr->second.state != PLAYERSPELL_NEW) itr->second.state = PLAYERSPELL_CHANGED; itr->second.disabled = disabled; if (disabled) return false; disabled_case = true; } else switch(itr->second.state) { case PLAYERSPELL_UNCHANGED: // known saved spell return false; case PLAYERSPELL_REMOVED: // re-learning removed not saved spell { m_spells.erase(itr); state = PLAYERSPELL_CHANGED; break; // need re-add } default: // known not saved yet spell (new or modified) { // can be in case spell loading but learned at some previous spell loading if(!IsInWorld() && !learning && !dependent_set) itr->second.state = PLAYERSPELL_UNCHANGED; return false; } } } TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id); if(!disabled_case) // skip new spell adding if spell already known (disabled spells case) { // talent: unlearn all other talent ranks (high and low) if (talentPos) { if (TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id )) { for(int i=0; i < MAX_TALENT_RANK; ++i) { // skip learning spell and no rank spell case uint32 rankSpellId = talentInfo->RankID[i]; if(!rankSpellId || rankSpellId == spell_id) continue; removeSpell(rankSpellId, false, false); } } } // non talent spell: learn low ranks (recursive call) else if (uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id)) { if(!IsInWorld() || disabled) // at spells loading, no output, but allow save addSpell(prev_spell, active, true, true, disabled); else // at normal learning learnSpell(prev_spell, true); } PlayerSpell newspell; newspell.state = state; newspell.active = active; newspell.dependent = dependent; newspell.disabled = disabled; // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible if (newspell.active && !newspell.disabled && sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo)) { for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 ) { if (itr2->second.state == PLAYERSPELL_REMOVED) continue; SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first); if(!i_spellInfo) continue; if ( sSpellMgr.IsRankSpellDueToSpell(spellInfo, itr2->first) ) { if (itr2->second.active) { if (sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first)) { if (IsInWorld()) // not send spell (re-/over-)learn packets at loading { WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4); data << uint32(itr2->first); data << uint32(spell_id); GetSession()->SendPacket( &data ); } // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new) itr2->second.active = false; if (itr2->second.state != PLAYERSPELL_NEW) itr2->second.state = PLAYERSPELL_CHANGED; superceded_old = true; // new spell replace old in action bars and spell book. } else if (sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id)) { if (IsInWorld()) // not send spell (re-/over-)learn packets at loading { WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4); data << uint32(spell_id); data << uint32(itr2->first); GetSession()->SendPacket( &data ); } // mark new spell as disable (not learned yet for client and will not learned) newspell.active = false; if (newspell.state != PLAYERSPELL_NEW) newspell.state = PLAYERSPELL_CHANGED; } } } } } m_spells[spell_id] = newspell; // return false if spell disabled if (newspell.disabled) return false; } if (talentPos) { // update talent map PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id); if (iter != m_talents[m_activeSpec].end()) { // check if ranks different or removed if ((*iter).second.state == PLAYERSPELL_REMOVED || talentPos->rank != (*iter).second.currentRank) { (*iter).second.currentRank = talentPos->rank; if ((*iter).second.state != PLAYERSPELL_NEW) (*iter).second.state = PLAYERSPELL_CHANGED; } } else { PlayerTalent talent; talent.currentRank = talentPos->rank; talent.talentEntry = sTalentStore.LookupEntry(talentPos->talent_id); talent.state = IsInWorld() ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED; m_talents[m_activeSpec][talentPos->talent_id] = talent; } // update used talent points count m_usedTalentCount += GetTalentSpellCost(talentPos); UpdateFreeTalentPoints(false); } // update free primary prof.points (if any, can be none in case GM .learn prof. learning) if (uint32 freeProfs = GetFreePrimaryProfessionPoints()) { if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id)) SetFreePrimaryProfessions(freeProfs-1); } // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned) // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive if (talentPos && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL)) { // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show) CastSpell(this, spell_id, true); } // also cast passive (and passive like) spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks else if (IsNeedCastPassiveLikeSpellAtLearn(spellInfo)) { CastSpell(this, spell_id, true); } else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP)) { CastSpell(this, spell_id, true); return false; } // add dependent skills uint16 maxskill = GetMaxSkillValueForLevel(); SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id); SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id); if (spellLearnSkill) { uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill); uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill); if (skill_value < spellLearnSkill->value) skill_value = spellLearnSkill->value; uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue; if (skill_max_value < new_skill_max_value) skill_max_value = new_skill_max_value; SetSkill(spellLearnSkill->skill, skill_value, skill_max_value, spellLearnSkill->step); } else { // not ranked skills for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx) { SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId); if (!pSkill) continue; if (HasSkill(pSkill->id)) continue; if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL || // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0)) { switch(GetSkillRangeType(pSkill, _spell_idx->second->racemask != 0)) { case SKILL_RANGE_LANGUAGE: SetSkill(pSkill->id, 300, 300 ); break; case SKILL_RANGE_LEVEL: SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() ); break; case SKILL_RANGE_MONO: SetSkill(pSkill->id, 1, 1 ); break; default: break; } } } } // learn dependent spells SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id); for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2) { if (!itr2->second.autoLearned) { if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save addSpell(itr2->second.spell,itr2->second.active,true,true,false); else // at normal learning learnSpell(itr2->second.spell, true); } } if (!GetSession()->PlayerLoading()) { // not ranked skills for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx) { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId); } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id); } // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell return active && !disabled && !superceded_old; } bool Player::IsNeedCastPassiveLikeSpellAtLearn(SpellEntry const* spellInfo) const { ShapeshiftForm form = GetShapeshiftForm(); if (IsNeedCastSpellAtFormApply(spellInfo, form)) // SPELL_ATTR_PASSIVE | SPELL_ATTR_HIDDEN_CLIENTSIDE spells return true; // all stance req. cases, not have auarastate cases if (!(spellInfo->Attributes & SPELL_ATTR_PASSIVE)) return false; // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell // talent dependent passives activated at form apply have proper stance data bool need_cast = (!spellInfo->Stances || (!form && (spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT))); // Check CasterAuraStates return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState))); } void Player::learnSpell(uint32 spell_id, bool dependent) { PlayerSpellMap::iterator itr = m_spells.find(spell_id); bool disabled = (itr != m_spells.end()) ? itr->second.disabled : false; bool active = disabled ? itr->second.active : true; bool learning = addSpell(spell_id, active, true, dependent, false); // prevent duplicated entires in spell book, also not send if not in world (loading) if (learning && IsInWorld()) { WorldPacket data(SMSG_LEARNED_SPELL, 6); data << uint32(spell_id); data << uint16(0); // 3.3.3 unk GetSession()->SendPacket(&data); } // learn all disabled higher ranks (recursive) if (disabled) { SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext(); for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i) { PlayerSpellMap::iterator iter = m_spells.find(i->second); if (iter != m_spells.end() && iter->second.disabled) learnSpell(i->second, false); } } } void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate) { PlayerSpellMap::iterator itr = m_spells.find(spell_id); if (itr == m_spells.end()) return; if (itr->second.state == PLAYERSPELL_REMOVED || (disabled && itr->second.disabled)) return; // unlearn non talent higher ranks (recursive) SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext(); for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2) if (HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second)) removeSpell(itr2->second, disabled, false); // re-search, it can be corrupted in prev loop itr = m_spells.find(spell_id); if (itr == m_spells.end() || itr->second.state == PLAYERSPELL_REMOVED) return; // already unleared bool cur_active = itr->second.active; bool cur_dependent = itr->second.dependent; if (disabled) { itr->second.disabled = disabled; if (itr->second.state != PLAYERSPELL_NEW) itr->second.state = PLAYERSPELL_CHANGED; } else { if (itr->second.state == PLAYERSPELL_NEW) m_spells.erase(itr); else itr->second.state = PLAYERSPELL_REMOVED; } RemoveAurasDueToSpell(spell_id); // remove pet auras for(int i = 0; i < MAX_EFFECT_INDEX; ++i) if (PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, SpellEffectIndex(i))) RemovePetAura(petSpell); TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id); if (talentPos) { // update talent map PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id); if (iter != m_talents[m_activeSpec].end()) { if ((*iter).second.state != PLAYERSPELL_NEW) (*iter).second.state = PLAYERSPELL_REMOVED; else m_talents[m_activeSpec].erase(iter); } else sLog.outError("removeSpell: Player (GUID: %u) has talent spell (id: %u) but doesn't have talent",GetGUIDLow(), spell_id ); // free talent points uint32 talentCosts = GetTalentSpellCost(talentPos); if (talentCosts < m_usedTalentCount) m_usedTalentCount -= talentCosts; else m_usedTalentCount = 0; UpdateFreeTalentPoints(false); } // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning) if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id)) { uint32 freeProfs = GetFreePrimaryProfessionPoints()+1; uint32 maxProfs = GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT)) ? sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL) : 10; if (freeProfs <= maxProfs) SetFreePrimaryProfessions(freeProfs); } // remove dependent skill SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id); if (spellLearnSkill) { uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id); if(!prev_spell) // first rank, remove skill SetSkill(spellLearnSkill->skill, 0, 0); else { // search prev. skill setting by spell ranks chain SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell); while(!prevSkill && prev_spell) { prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell); prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell)); } if (!prevSkill) // not found prev skill setting, remove skill SetSkill(spellLearnSkill->skill, 0, 0); else // set to prev. skill setting values { uint32 skill_value = GetPureSkillValue(prevSkill->skill); uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill); if (skill_value > prevSkill->value) skill_value = prevSkill->value; uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue; if (skill_max_value > new_skill_max_value) skill_max_value = new_skill_max_value; SetSkill(prevSkill->skill, skill_value, skill_max_value, prevSkill->step); } } } else { // not ranked skills SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id); for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) { SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId); if (!pSkill) continue; if ((_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL && pSkill->categoryId != SKILL_CATEGORY_CLASS) ||// not unlearn class skills (spellbook/talent pages) // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0)) { // not reset skills for professions and racial abilities if ((pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION) && (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask != 0)) continue; SetSkill(pSkill->id, 0, 0); } } } // remove dependent spells SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id); for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2) removeSpell(itr2->second.spell, disabled); // activate lesser rank in spellbook/action bar, and cast it if need bool prev_activate = false; if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id)) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); // if talent then lesser rank also talent and need learn if (talentPos) { if (learn_low_rank) learnSpell(prev_id, false); } // if ranked non-stackable spell: need activate lesser rank and update dependence state else if (cur_active && sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo)) { // need manually update dependence state (learn spell ignore like attempts) PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id); if (prev_itr != m_spells.end()) { if (prev_itr->second.dependent != cur_dependent) { prev_itr->second.dependent = cur_dependent; if (prev_itr->second.state != PLAYERSPELL_NEW) prev_itr->second.state = PLAYERSPELL_CHANGED; } // now re-learn if need re-activate if (cur_active && !prev_itr->second.active && learn_low_rank) { if (addSpell(prev_id, true, false, prev_itr->second.dependent, prev_itr->second.disabled)) { // downgrade spell ranks in spellbook and action bar WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4); data << uint32(spell_id); data << uint32(prev_id); GetSession()->SendPacket( &data ); prev_activate = true; } } } } } // for Titan's Grip and shaman Dual-wield if (CanDualWield() || CanTitanGrip()) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); if (CanDualWield() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_DUAL_WIELD)) SetCanDualWield(false); if (CanTitanGrip() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_TITAN_GRIP)) { SetCanTitanGrip(false); // Remove Titan's Grip damage penalty now RemoveAurasDueToSpell(49152); } } // for talents and normal spell unlearn that allow offhand use for some weapons if (sWorld.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET)) AutoUnequipOffhandIfNeed(); // remove from spell book if not replaced by lesser rank if (!prev_activate && sendUpdate) { WorldPacket data(SMSG_REMOVED_SPELL, 4); data << uint32(spell_id); GetSession()->SendPacket(&data); } } void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ ) { MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT); m_spellCooldowns.erase(spell_id); if (update) SendClearCooldown(spell_id, this); } void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */) { if (m_spellCooldowns.empty()) return; SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat); if (ct == sSpellCategoryStore.end()) return; const SpellCategorySet& ct_set = ct->second; SpellCategorySet current_set; SpellCategorySet intersection_set; { MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT); std::transform(m_spellCooldowns.begin(), m_spellCooldowns.end(), std::inserter(current_set, current_set.begin()), select1st<SpellCooldowns::value_type>()); } std::set_intersection(ct_set.begin(),ct_set.end(), current_set.begin(),current_set.end(),std::inserter(intersection_set,intersection_set.begin())); if (intersection_set.empty()) return; for (SpellCategorySet::const_iterator itr = intersection_set.begin(); itr != intersection_set.end(); ++itr) RemoveSpellCooldown(*itr, update); } void Player::RemoveArenaSpellCooldowns() { // remove cooldowns on spells that has < 15 min CD SpellCooldowns::iterator itr, next; // iterate spell cooldowns for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next) { next = itr; ++next; SpellEntry const * entry = sSpellStore.LookupEntry(itr->first); // check if spellentry is present and if the cooldown is less than 15 mins if ( entry && entry->RecoveryTime <= 15 * MINUTE * IN_MILLISECONDS && entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILLISECONDS ) { // remove & notify RemoveSpellCooldown(itr->first, true); } } if (Pet *pet = GetPet()) { // notify player for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr) SendClearCooldown(itr->first, pet); // actually clear cooldowns pet->m_CreatureSpellCooldowns.clear(); } } void Player::RemoveAllSpellCooldown() { if(!m_spellCooldowns.empty()) { for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr) SendClearCooldown(itr->first, this); MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT); m_spellCooldowns.clear(); } } void Player::_LoadSpellCooldowns(QueryResult *result) { // some cooldowns can be already set at aura loading... //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow()); if (result) { time_t curTime = time(NULL); do { Field *fields = result->Fetch(); uint32 spell_id = fields[0].GetUInt32(); uint32 item_id = fields[1].GetUInt32(); time_t db_time = (time_t)fields[2].GetUInt64(); if(!sSpellStore.LookupEntry(spell_id)) { sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id); continue; } // skip outdated cooldown if (db_time <= curTime) continue; AddSpellCooldown(spell_id, item_id, db_time); DEBUG_LOG("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime)); } while( result->NextRow() ); delete result; } } void Player::_SaveSpellCooldowns() { static SqlStatementID deleteSpellCooldown ; static SqlStatementID insertSpellCooldown ; SqlStatement stmt = CharacterDatabase.CreateStatement(deleteSpellCooldown, "DELETE FROM character_spell_cooldown WHERE guid = ?"); stmt.PExecute(GetGUIDLow()); time_t curTime = time(NULL); time_t infTime = curTime + infinityCooldownDelayCheck; // remove outdated and save active for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();) { if (itr->second.end <= curTime) { MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT); m_spellCooldowns.erase(itr++); } else if (itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload { stmt = CharacterDatabase.CreateStatement(insertSpellCooldown, "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES( ?, ?, ?, ?)"); stmt.PExecute(GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end)); ++itr; } else ++itr; } } uint32 Player::resetTalentsCost() const { // The first time reset costs 1 gold if (m_resetTalentsCost < 1*GOLD) return 1*GOLD; // then 5 gold else if (m_resetTalentsCost < 5*GOLD) return 5*GOLD; // After that it increases in increments of 5 gold else if (m_resetTalentsCost < 10*GOLD) return 10*GOLD; else { time_t months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH; if (months > 0) { // This cost will be reduced by a rate of 5 gold per month int32 new_cost = int32((m_resetTalentsCost) - 5*GOLD*months); // to a minimum of 10 gold. return uint32(new_cost < 10*GOLD ? 10*GOLD : new_cost); } else { // After that it increases in increments of 5 gold int32 new_cost = m_resetTalentsCost + 5*GOLD; // until it hits a cap of 50 gold. if (new_cost > 50*GOLD) new_cost = 50*GOLD; return new_cost; } } } bool Player::resetTalents(bool no_cost, bool all_specs) { // not need after this call if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS) && all_specs) RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true); if (m_usedTalentCount == 0 && !all_specs) { UpdateFreeTalentPoints(false); // for fix if need counter return false; } uint32 cost = 0; if(!no_cost) { cost = resetTalentsCost(); if (GetMoney() < cost) { SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0); return false; } } RemoveAllEnchantments(TEMP_ENCHANTMENT_SLOT); for (PlayerTalentMap::iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end();) { if (iter->second.state == PLAYERSPELL_REMOVED) { ++iter; continue; } TalentEntry const* talentInfo = iter->second.talentEntry; if (!talentInfo) { m_talents[m_activeSpec].erase(iter++); continue; } TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) { m_talents[m_activeSpec].erase(iter++); continue; } // unlearn only talents for character class // some spell learned by one class as normal spells or know at creation but another class learn it as talent, // to prevent unexpected lost normal learned spell skip another class talents if ((getClassMask() & talentTabInfo->ClassMask) == 0) { ++iter; continue; } for (int j = 0; j < MAX_TALENT_RANK; ++j) if (talentInfo->RankID[j]) { removeSpell(talentInfo->RankID[j],!IsPassiveSpell(talentInfo->RankID[j]),false); SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[j]); for (int k = 0; k < MAX_EFFECT_INDEX; ++k) if (spellInfo->EffectTriggerSpell[k]) removeSpell(spellInfo->EffectTriggerSpell[k]); } iter = m_talents[m_activeSpec].begin(); } // for not current spec just mark removed all saved to DB case and drop not saved if (all_specs) { for (uint8 spec = 0; spec < MAX_TALENT_SPEC_COUNT; ++spec) { if (spec == m_activeSpec) continue; for (PlayerTalentMap::iterator iter = m_talents[spec].begin(); iter != m_talents[spec].end();) { switch (iter->second.state) { case PLAYERSPELL_REMOVED: ++iter; break; case PLAYERSPELL_NEW: m_talents[spec].erase(iter++); break; default: iter->second.state = PLAYERSPELL_REMOVED; ++iter; break; } } } } UpdateFreeTalentPoints(false); if(!no_cost) { ModifyMoney(-(int32)cost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1); m_resetTalentsCost = cost; m_resetTalentsTime = time(NULL); } //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras RemovePet(PET_SAVE_REAGENTS); /* when prev line will dropped use next line if (Pet* pet = GetPet()) { if (pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets())) pet->Unsummon(PET_SAVE_REAGENTS, this); } */ return true; } Mail* Player::GetMail(uint32 id) { for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) { if ((*itr)->messageID == id) { return (*itr); } } return NULL; } void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const { if (target == this) { Object::_SetCreateBits(updateMask, target); } else { for(uint16 index = 0; index < m_valuesCount; index++) { if (GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index)) updateMask->SetBit(index); } } } void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const { if (target == this) { Object::_SetUpdateBits(updateMask, target); } else { Object::_SetUpdateBits(updateMask, target); *updateMask &= updateVisualBits; } } void Player::InitVisibleBits() { updateVisualBits.SetCount(PLAYER_END); updateVisualBits.SetBit(OBJECT_FIELD_GUID); updateVisualBits.SetBit(OBJECT_FIELD_TYPE); updateVisualBits.SetBit(OBJECT_FIELD_ENTRY); updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X); updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0); updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1); updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0); updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1); updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0); updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1); updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0); updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1); updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0); updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1); updateVisualBits.SetBit(UNIT_FIELD_BYTES_0); updateVisualBits.SetBit(UNIT_FIELD_HEALTH); updateVisualBits.SetBit(UNIT_FIELD_POWER1); updateVisualBits.SetBit(UNIT_FIELD_POWER2); updateVisualBits.SetBit(UNIT_FIELD_POWER3); updateVisualBits.SetBit(UNIT_FIELD_POWER4); updateVisualBits.SetBit(UNIT_FIELD_POWER5); updateVisualBits.SetBit(UNIT_FIELD_POWER6); updateVisualBits.SetBit(UNIT_FIELD_POWER7); updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH); updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1); updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2); updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3); updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4); updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5); updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6); updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7); updateVisualBits.SetBit(UNIT_FIELD_LEVEL); updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE); updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0); updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1); updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2); updateVisualBits.SetBit(UNIT_FIELD_FLAGS); updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2); updateVisualBits.SetBit(UNIT_FIELD_AURASTATE); updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0); updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1); updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS); updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH); updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID); updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID); updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID); updateVisualBits.SetBit(UNIT_FIELD_BYTES_1); updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER); updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP); updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS); updateVisualBits.SetBit(UNIT_CHANNEL_SPELL); updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED); updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA); updateVisualBits.SetBit(UNIT_FIELD_BYTES_2); updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT); updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0); updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1); updateVisualBits.SetBit(PLAYER_FLAGS); updateVisualBits.SetBit(PLAYER_GUILDID); updateVisualBits.SetBit(PLAYER_GUILDRANK); updateVisualBits.SetBit(PLAYER_BYTES); updateVisualBits.SetBit(PLAYER_BYTES_2); updateVisualBits.SetBit(PLAYER_BYTES_3); updateVisualBits.SetBit(PLAYER_DUEL_TEAM); updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP); updateVisualBits.SetBit(UNIT_NPC_FLAGS); // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)... for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET) updateVisualBits.SetBit(i); // Players visible items are not inventory stuff for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i) { uint32 offset = i * 2; // item entry updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset); // enchant updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset); } updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE); } void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const { if (target == this) { for(int i = 0; i < EQUIPMENT_SLOT_END; ++i) { if (m_items[i] == NULL) continue; m_items[i]->BuildCreateUpdateBlockForPlayer( data, target ); } for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { if (m_items[i] == NULL) continue; m_items[i]->BuildCreateUpdateBlockForPlayer( data, target ); } for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { if (m_items[i] == NULL) continue; m_items[i]->BuildCreateUpdateBlockForPlayer( data, target ); } } Unit::BuildCreateUpdateBlockForPlayer( data, target ); } void Player::DestroyForPlayer( Player *target, bool anim ) const { Unit::DestroyForPlayer( target, anim ); for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i] == NULL) continue; m_items[i]->DestroyForPlayer( target ); } if (target == this) { for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { if (m_items[i] == NULL) continue; m_items[i]->DestroyForPlayer( target ); } for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { if (m_items[i] == NULL) continue; m_items[i]->DestroyForPlayer( target ); } } } bool Player::HasSpell(uint32 spell) const { PlayerSpellMap::const_iterator itr = m_spells.find(spell); return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled); } bool Player::HasActiveSpell(uint32 spell) const { PlayerSpellMap::const_iterator itr = m_spells.find(spell); return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED && itr->second.active && !itr->second.disabled); } TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell, uint32 reqLevel) const { if (!trainer_spell) return TRAINER_SPELL_RED; if (!trainer_spell->learnedSpell) return TRAINER_SPELL_RED; // known spell if (HasSpell(trainer_spell->learnedSpell)) return TRAINER_SPELL_GRAY; // check race/class requirement if (!IsSpellFitByClassAndRace(trainer_spell->learnedSpell)) return TRAINER_SPELL_RED; bool prof = SpellMgr::IsProfessionSpell(trainer_spell->learnedSpell); // check level requirement if (!prof || GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_LEVEL))) if (getLevel() < reqLevel) return TRAINER_SPELL_RED; if (SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell)) { // check prev.rank requirement if (spell_chain->prev && !HasSpell(spell_chain->prev)) return TRAINER_SPELL_RED; // check additional spell requirement if (spell_chain->req && !HasSpell(spell_chain->req)) return TRAINER_SPELL_RED; } // check skill requirement if (!prof || GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_SKILL))) if (trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue) return TRAINER_SPELL_RED; // exist, already checked at loading SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell); // secondary prof. or not prof. spell uint32 skill = spell->EffectMiscValue[1]; if (spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill)) return TRAINER_SPELL_GREEN; // check primary prof. limit if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0) return TRAINER_SPELL_GREEN_DISABLED; return TRAINER_SPELL_GREEN; } /** * Deletes a character from the database * * The way, how the characters will be deleted is decided based on the config option. * * @see Player::DeleteOldCharacters * * @param playerguid the low-GUID from the player which should be deleted * @param accountId the account id from the player * @param updateRealmChars when this flag is set, the amount of characters on that realm will be updated in the realmlist * @param deleteFinally if this flag is set, the config option will be ignored and the character will be permanently removed from the database */ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRealmChars, bool deleteFinally) { // for nonexistent account avoid update realm if (accountId == 0) updateRealmChars = false; uint32 charDelete_method = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_METHOD); uint32 charDelete_minLvl = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_MIN_LEVEL); // if we want to finally delete the character or the character does not meet the level requirement, we set it to mode 0 if (deleteFinally || Player::GetLevelFromDB(playerguid) < charDelete_minLvl) charDelete_method = 0; uint32 lowguid = playerguid.GetCounter(); // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry) // bones will be deleted by corpse/bones deleting thread shortly sObjectAccessor.ConvertCorpseForPlayer(playerguid); // remove from guild if (uint32 guildId = GetGuildIdFromDB(playerguid)) { if (Guild* guild = sGuildMgr.GetGuildById(guildId)) { if (guild->DelMember(playerguid)) { guild->Disband(); delete guild; } } } // remove from arena teams LeaveAllArenaTeams(playerguid); // the player was uninvited already on logout so just remove from group QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", lowguid); if (resultGroup) { uint32 groupId = (*resultGroup)[0].GetUInt32(); delete resultGroup; if (Group* group = sObjectMgr.GetGroupById(groupId)) RemoveFromGroup(group, playerguid); } // remove signs from petitions (also remove petitions if owner); RemovePetitionsAndSigns(playerguid, 10); switch(charDelete_method) { // completely remove from the database case 0: { // return back all mails with COD and Item 0 1 2 3 4 5 6 7 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,body,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", lowguid); if (resultMail) { do { Field *fields = resultMail->Fetch(); uint32 mail_id = fields[0].GetUInt32(); uint16 mailType = fields[1].GetUInt16(); uint16 mailTemplateId= fields[2].GetUInt16(); uint32 sender = fields[3].GetUInt32(); std::string subject = fields[4].GetCppString(); std::string body = fields[5].GetCppString(); uint32 money = fields[6].GetUInt32(); bool has_items = fields[7].GetBool(); //we can return mail now //so firstly delete the old one CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id); // mail not from player if (mailType != MAIL_NORMAL) { if (has_items) CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id); continue; } MailDraft draft; if (mailTemplateId) draft.SetMailTemplate(mailTemplateId, false);// items already included else draft.SetSubjectAndBody(subject, body); if (has_items) { // data needs to be at first place for Item::LoadFromDB // 0 1 2 3 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,text,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id); if (resultItems) { do { Field *fields2 = resultItems->Fetch(); uint32 item_guidlow = fields2[2].GetUInt32(); uint32 item_template = fields2[3].GetUInt32(); ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template); if (!itemProto) { CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow); continue; } Item *pItem = NewItemOrBag(itemProto); if (!pItem->LoadFromDB(item_guidlow, fields2, playerguid)) { pItem->FSetState(ITEM_REMOVED); pItem->SaveToDB(); // it also deletes item object ! continue; } draft.AddItem(pItem); } while (resultItems->NextRow()); delete resultItems; } } CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id); uint32 pl_account = sAccountMgr.GetPlayerAccountIdByGUID(playerguid); draft.SetMoney(money).SendReturnToSender(pl_account, playerguid, ObjectGuid(HIGHGUID_PLAYER, sender)); } while (resultMail->NextRow()); delete resultMail; } // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet. // Get guids of character's pets, will deleted in transaction QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'", lowguid); // delete char from friends list when selected chars is online (non existing - error) QueryResult *resultFriend = CharacterDatabase.PQuery("SELECT DISTINCT guid FROM character_social WHERE friend = '%u'", lowguid); // NOW we can finally clear other DB data related to character CharacterDatabase.BeginTransaction(); if (resultPets) { do { Field *fields3 = resultPets->Fetch(); uint32 petguidlow = fields3[0].GetUInt32(); //do not create separate transaction for pet delete otherwise we will get fatal error! Pet::DeleteFromDB(petguidlow, false); } while (resultPets->NextRow()); delete resultPets; } // cleanup friends for online players, offline case will cleanup later in code if (resultFriend) { do { Field* fieldsFriend = resultFriend->Fetch(); if (Player* sFriend = sObjectAccessor.FindPlayer(ObjectGuid(HIGHGUID_PLAYER, fieldsFriend[0].GetUInt32()))) { if (sFriend->IsInWorld()) { sFriend->GetSocial()->RemoveFromSocialList(playerguid, false); sSocialMgr.SendFriendStatus(sFriend, FRIEND_REMOVED, playerguid, false); } } } while (resultFriend->NextRow()); delete resultFriend; } CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_queststatus_weekly WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'", lowguid, lowguid); CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u' OR PlayerGuid2 = '%u'", lowguid, lowguid); CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'", lowguid); CharacterDatabase.CommitTransaction(); break; } // The character gets unlinked from the account, the name gets freed up and appears as deleted ingame case 1: CharacterDatabase.PExecute("UPDATE characters SET deleteInfos_Name=name, deleteInfos_Account=account, deleteDate='" UI64FMTD "', name='', account=0 WHERE guid=%u", uint64(time(NULL)), lowguid); break; default: sLog.outError("Player::DeleteFromDB: Unsupported delete method: %u.", charDelete_method); } if (updateRealmChars) sAccountMgr.UpdateCharactersCount(accountId, realmID); } /** * Characters which were kept back in the database after being deleted and are now too old (see config option "CharDelete.KeepDays"), will be completely deleted. * * @see Player::DeleteFromDB */ void Player::DeleteOldCharacters() { uint32 keepDays = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_KEEP_DAYS); if (!keepDays) return; Player::DeleteOldCharacters(keepDays); } /** * Characters which were kept back in the database after being deleted and are older than the specified amount of days, will be completely deleted. * * @see Player::DeleteFromDB * * @param keepDays overrite the config option by another amount of days */ void Player::DeleteOldCharacters(uint32 keepDays) { sLog.outString("Player::DeleteOldChars: Deleting all characters which have been deleted %u days before...", keepDays); QueryResult *resultChars = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < '" UI64FMTD "'", uint64(time(NULL) - time_t(keepDays * DAY))); if (resultChars) { sLog.outString("Player::DeleteOldChars: Found %u character(s) to delete",uint32(resultChars->GetRowCount())); do { Field *charFields = resultChars->Fetch(); ObjectGuid guid = ObjectGuid(HIGHGUID_PLAYER, charFields[0].GetUInt32()); Player::DeleteFromDB(guid, charFields[1].GetUInt32(), true, true); } while(resultChars->NextRow()); delete resultChars; } } void Player::SetMovement(PlayerMovementType pType) { WorldPacket data; switch(pType) { case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break; case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break; case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break; case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break; default: sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType); return; } data << GetPackGUID(); data << uint32(0); GetSession()->SendPacket( &data ); } /* Preconditions: - a resurrectable corpse must not be loaded for the player (only bones) - the player must be in world */ void Player::BuildPlayerRepop() { WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size()); data << GetPackGUID(); GetSession()->SendPacket(&data); if (getRace() == RACE_NIGHTELF) CastSpell(this, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form) CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?) // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK // there must be SMSG.STOP_MIRROR_TIMER // there we must send 888 opcode // the player cannot have a corpse already, only bones which are not returned by GetCorpse if (GetCorpse()) { sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow()); MANGOS_ASSERT(false); } // create a corpse and place it at the player's location Corpse *corpse = CreateCorpse(); if(!corpse) { sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow()); return; } GetMap()->Add(corpse); // convert player body to ghost if (getDeathState() != GHOULED) SetHealth( 1 ); SetMovement(MOVE_WATER_WALK); if(!GetSession()->isLogingOut()) SetMovement(MOVE_UNROOT); // BG - remove insignia related RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); if (getDeathState() != GHOULED) SendCorpseReclaimDelay(); // to prevent cheating corpse->ResetGhostTime(); StopMirrorTimers(); //disable timers(bars) // set and clear other SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND); } void Player::ResurrectPlayer(float restore_percent, bool applySickness) { WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position data << uint32(-1); data << float(0); data << float(0); data << float(0); GetSession()->SendPacket(&data); // speed change, land walk // remove death flag + set aura SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00); SetDeathState(ALIVE); if (getRace() == RACE_NIGHTELF) RemoveAurasDueToSpell(20584); // speed bonuses RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST // refer-a-friend flag - maybe wrong and hacky if (GetAccountLinkedState() != STATE_NOT_LINKED) SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND); SetMovement(MOVE_LAND_WALK); SetMovement(MOVE_UNROOT); m_deathTimer = 0; // set health/powers (0- will be set in caller) if (restore_percent>0.0f) { SetHealth(uint32(GetMaxHealth()*restore_percent)); SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent)); SetPower(POWER_RAGE, 0); SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent)); } // trigger update zone for alive state zone updates uint32 newzone, newarea; GetZoneAndAreaId(newzone,newarea); UpdateZone(newzone,newarea); // update visibility of world around viewpoint m_camera.UpdateVisibilityForOwner(); // update visibility of player for nearby cameras UpdateObjectVisibility(); if(!applySickness) return; //Characters from level 1-10 are not affected by resurrection sickness. //Characters from level 11-19 will suffer from one minute of sickness //for each level they are above 10. //Characters level 20 and up suffer from ten minutes of sickness. int32 startLevel = sWorld.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL); if (int32(getLevel()) >= startLevel) { // set resurrection sickness CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true); // not full duration if (int32(getLevel()) < startLevel+9) { int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE; if (SpellAuraHolderPtr holder = GetSpellAuraHolder(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS)) { holder->SetAuraDuration(delta*IN_MILLISECONDS); holder->SendAuraUpdate(false); } } } } void Player::KillPlayer() { SetMovement(MOVE_ROOT); StopMirrorTimers(); //disable timers(bars) SetDeathState(CORPSE); //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP ); SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE); ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable()); // 6 minutes until repop at graveyard m_deathTimer = 6*MINUTE*IN_MILLISECONDS; UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill // don't create corpse at this moment, player might be falling // update visibility UpdateObjectVisibility(); } Corpse* Player::CreateCorpse() { // prevent existence 2 corpse for player SpawnCorpseBones(); Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE ); SetPvPDeath(false); if (!corpse->Create(sObjectMgr.GenerateCorpseLowGuid(), this)) { delete corpse; return NULL; } uint8 skin = GetByteValue(PLAYER_BYTES, 0); uint8 face = GetByteValue(PLAYER_BYTES, 1); uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2); uint8 haircolor = GetByteValue(PLAYER_BYTES, 3); uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0); corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 1, getRace()); corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 2, getGender()); corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 3, skin); corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 0, face); corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 1, hairstyle); corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 2, haircolor); corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 3, facialhair); uint32 flags = CORPSE_FLAG_UNK2; if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM)) flags |= CORPSE_FLAG_HIDE_HELM; if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK)) flags |= CORPSE_FLAG_HIDE_CLOAK; if (InBattleGround() && !InArena()) flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags ); corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() ); corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() ); uint32 iDisplayID; uint32 iIventoryType; uint32 _cfi; for (int i = 0; i < EQUIPMENT_SLOT_END; ++i) { if (m_items[i]) { iDisplayID = m_items[i]->GetProto()->DisplayInfoID; iIventoryType = m_items[i]->GetProto()->InventoryType; _cfi = iDisplayID | (iIventoryType << 24); corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi); } } // we not need saved corpses for BG/arenas if (!GetMap()->IsBattleGroundOrArena()) corpse->SaveToDB(); // register for player, but not show sObjectAccessor.AddCorpse(corpse); return corpse; } void Player::SpawnCorpseBones() { if (sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid())) if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player SaveToDB(); // prevent loading as ghost without corpse } Corpse* Player::GetCorpse() const { return sObjectAccessor.GetCorpseForPlayerGUID(GetObjectGuid()); } void Player::DurabilityLossAll(double percent, bool inventory) { for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityLoss(pItem,percent); if (inventory) { // bags not have durability // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityLoss(pItem,percent); // keys not have durability //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i) for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) for(uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = GetItemByPos( i, j )) DurabilityLoss(pItem,percent); } } void Player::DurabilityLoss(Item* item, double percent) { if(!item ) return; uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); if(!pMaxDurability) return; uint32 pDurabilityLoss = uint32(pMaxDurability*percent); if (pDurabilityLoss < 1 ) pDurabilityLoss = 1; DurabilityPointsLoss(item,pDurabilityLoss); } void Player::DurabilityPointsLossAll(int32 points, bool inventory) { for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityPointsLoss(pItem,points); if (inventory) { // bags not have durability // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityPointsLoss(pItem,points); // keys not have durability //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i) for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) for(uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = GetItemByPos( i, j )) DurabilityPointsLoss(pItem,points); } } void Player::DurabilityPointsLoss(Item* item, int32 points) { int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY); int32 pNewDurability = pOldDurability - points; if (pNewDurability < 0) pNewDurability = 0; else if (pNewDurability > pMaxDurability) pNewDurability = pMaxDurability; if (pOldDurability != pNewDurability) { // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped()) _ApplyItemMods(item,item->GetSlot(), false); item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability); // modify item stats _after_ restore durability to pass _ApplyItemMods internal check if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped()) _ApplyItemMods(item,item->GetSlot(), true); item->SetState(ITEM_CHANGED, this); } } void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot) { if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot )) DurabilityPointsLoss(pItem,1); } uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank) { uint32 TotalCost = 0; // equipped, backpack, bags itself for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank); // bank, buyback and keys not repaired // items in inventory bags for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j) for(int i = 0; i < MAX_BAG_SIZE; ++i) TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank); return TotalCost; } uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank) { Item* item = GetItemByPos(pos); uint32 TotalCost = 0; if(!item) return TotalCost; uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); if(!maxDurability) return TotalCost; uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY); if (cost) { uint32 LostDurability = maxDurability - curDurability; if (LostDurability>0) { ItemPrototype const *ditemProto = item->GetProto(); DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel); if(!dcost) { sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel); return TotalCost; } uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2; DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId); if(!dQualitymodEntry) { sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId); return TotalCost; } uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)]; uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod)); costs = uint32(costs * discountMod); if (costs==0) //fix for ITEM_QUALITY_ARTIFACT costs = 1; if (guildBank) { if (GetGuildId()==0) { DEBUG_LOG("You are not member of a guild"); return TotalCost; } Guild* pGuild = sGuildMgr.GetGuildById(GetGuildId()); if (!pGuild) return TotalCost; if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR)) { DEBUG_LOG("You do not have rights to withdraw for repairs"); return TotalCost; } if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs) { DEBUG_LOG("You do not have enough money withdraw amount remaining"); return TotalCost; } if (pGuild->GetGuildBankMoney() < costs) { DEBUG_LOG("There is not enough money in bank"); return TotalCost; } pGuild->MemberMoneyWithdraw(costs, GetGUIDLow()); TotalCost = costs; } else if (GetMoney() < costs) { DEBUG_LOG("You do not have enough money"); return TotalCost; } else ModifyMoney( -int32(costs) ); } } item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability); item->SetState(ITEM_CHANGED, this); // reapply mods for total broken and repaired item if equipped if (IsEquipmentPos(pos) && !curDurability) _ApplyItemMods(item,pos & 255, true); return TotalCost; } void Player::RepopAtGraveyard() { // note: this can be called also when the player is alive // for example from WorldSession::HandleMovementOpcodes AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId()); // Such zones are considered unreachable as a ghost and the player must be automatically revived if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < -500.0f) { ResurrectPlayer(0.5f); SpawnCorpseBones(); } WorldSafeLocsEntry const *ClosestGrave = NULL; // Special handle for battleground maps if ( BattleGround *bg = GetBattleGround() ) ClosestGrave = bg->GetClosestGraveYard(this); else ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() ); // stop countdown until repop m_deathTimer = 0; // if no grave found, stay at the current location // and don't show spirit healer location if (ClosestGrave) { TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation()); if (isDead()) // not send if alive, because it used in TeleportTo() { WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap data << ClosestGrave->map_id; data << ClosestGrave->x; data << ClosestGrave->y; data << ClosestGrave->z; GetSession()->SendPacket(&data); } } } void Player::JoinedChannel(Channel *c) { m_channels.push_back(c); } void Player::LeftChannel(Channel *c) { m_channels.remove(c); } void Player::CleanupChannels() { while (!m_channels.empty()) { Channel* ch = *m_channels.begin(); m_channels.erase(m_channels.begin()); // remove from player's channel list ch->Leave(GetObjectGuid(), false); // not send to client, not remove from player's channel list if (ChannelMgr* cMgr = channelMgr(GetTeam())) cMgr->LeftChannel(ch->GetName()); // deleted channel if empty } DEBUG_LOG("Player: channels cleaned up!"); } void Player::UpdateLocalChannels(uint32 newZone ) { if (m_channels.empty()) return; AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone); if(!current_zone) return; ChannelMgr* cMgr = channelMgr(GetTeam()); if(!cMgr) return; std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()]; for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next) { next = i; ++next; // skip non built-in channels if(!(*i)->IsConstant()) continue; ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId()); if(!ch) continue; if((ch->flags & 4) == 4) // global channel without zone name in pattern continue; // new channel char new_channel_name_buf[100]; snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str()); Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID); if ((*i)!=new_channel) { new_channel->Join(GetObjectGuid(),""); // will output Changed Channel: N. Name // leave old channel (*i)->Leave(GetObjectGuid(),false); // not send leave channel, it already replaced at client std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel LeftChannel(*i); // remove from player's channel list cMgr->LeftChannel(name); // delete if empty } } DEBUG_LOG("Player: channels cleaned up!"); } void Player::LeaveLFGChannel() { for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i ) { if ((*i)->IsLFG()) { (*i)->Leave(GetObjectGuid()); break; } } } void Player::JoinLFGChannel() { for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i ) { if((*i)->IsLFG()) { (*i)->Join(GetObjectGuid(),""); break; } } } void Player::UpdateDefense() { uint32 defense_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE); if (UpdateSkill(SKILL_DEFENSE,defense_skill_gain)) { // update dependent from defense skill part UpdateDefenseBonusesMod(); } } void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply) { if (modGroup >= BASEMOD_END || modType >= MOD_END) { sLog.outError("ERROR in HandleBaseModValue(): nonexistent BaseModGroup of wrong BaseModType!"); return; } float val = 1.0f; switch(modType) { case FLAT_MOD: m_auraBaseMod[modGroup][modType] += apply ? amount : -amount; break; case PCT_MOD: if (amount <= -100.0f) amount = -200.0f; // Shield Block Value PCT_MODs should be added, not multiplied if (modGroup == SHIELD_BLOCK_VALUE) { val = amount / 100.0f; m_auraBaseMod[modGroup][modType] += apply ? val : -val; } else { val = (100.0f + amount) / 100.0f; m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val); } break; } if(!CanModifyStats()) return; switch(modGroup) { case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break; case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break; case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break; case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break; default: break; } } float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const { if (modGroup >= BASEMOD_END || modType > MOD_END) { sLog.outError("trial to access nonexistent BaseModGroup or wrong BaseModType!"); return 0.0f; } if (modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f) return 0.0f; return m_auraBaseMod[modGroup][modType]; } float Player::GetTotalBaseModValue(BaseModGroup modGroup) const { if (modGroup >= BASEMOD_END) { sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!"); return 0.0f; } if (m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f) return 0.0f; return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD]; } uint32 Player::GetShieldBlockValue() const { float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD]; value = (value < 0) ? 0 : value; return uint32(value); } float Player::GetMeleeCritFromAgility() { uint32 level = getLevel(); uint32 pclass = getClass(); if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1); GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (critBase==NULL || critRatio==NULL) return 0.0f; float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio; return crit*100.0f; } void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) { // Table for base dodge values const float dodge_base[MAX_CLASSES] = { 0.036640f, // Warrior 0.034943f, // Paladin -0.040873f, // Hunter 0.020957f, // Rogue 0.034178f, // Priest 0.036640f, // DK 0.021080f, // Shaman 0.036587f, // Mage 0.024211f, // Warlock 0.0f, // ?? 0.056097f // Druid }; // Crit/agility to dodge/agility coefficient multipliers; 3.2.0 increased required agility by 15% const float crit_to_dodge[MAX_CLASSES] = { 0.85f/1.15f, // Warrior 1.00f/1.15f, // Paladin 1.11f/1.15f, // Hunter 2.00f/1.15f, // Rogue 1.00f/1.15f, // Priest 0.85f/1.15f, // DK 1.60f/1.15f, // Shaman 1.00f/1.15f, // Mage 0.97f/1.15f, // Warlock (?) 0.0f, // ?? 2.00f/1.15f // Druid }; uint32 level = getLevel(); uint32 pclass = getClass(); if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; // Dodge per agility is proportional to crit per agility, which is available from DBC files GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (dodgeRatio==NULL || pclass > MAX_CLASSES) return; // TODO: research if talents/effects that increase total agility by x% should increase non-diminishing part float base_agility = GetCreateStat(STAT_AGILITY) * m_auraModifiersGroup[UNIT_MOD_STAT_START + STAT_AGILITY][BASE_PCT]; float bonus_agility = GetStat(STAT_AGILITY) - base_agility; // calculate diminishing (green in char screen) and non-diminishing (white) contribution diminishing = 100.0f * bonus_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]; nondiminishing = 100.0f * (dodge_base[pclass-1] + base_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]); } float Player::GetSpellCritFromIntellect() { uint32 level = getLevel(); uint32 pclass = getClass(); if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1); GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (critBase==NULL || critRatio==NULL) return 0.0f; float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio; return crit*100.0f; } float Player::GetRatingMultiplier(CombatRating cr) const { uint32 level = getLevel(); if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1); // gtOCTClassCombatRatingScalarStore.dbc starts with 1, CombatRating with zero, so cr+1 GtOCTClassCombatRatingScalarEntry const *classRating = sGtOCTClassCombatRatingScalarStore.LookupEntry((getClass()-1)*GT_MAX_RATING+cr+1); if (!Rating || !classRating) return 1.0f; // By default use minimum coefficient (not must be called) return classRating->ratio / Rating->ratio; } float Player::GetRatingBonusValue(CombatRating cr) const { return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) * GetRatingMultiplier(cr); } float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const { switch (attType) { case BASE_ATTACK: return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f; case OFF_ATTACK: return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f; default: break; } return 0.0f; } float Player::OCTRegenHPPerSpirit() { uint32 level = getLevel(); uint32 pclass = getClass(); if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (baseRatio==NULL || moreRatio==NULL) return 0.0f; // Formula from PaperDollFrame script float spirit = GetStat(STAT_SPIRIT); float baseSpirit = spirit; if (baseSpirit>50) baseSpirit = 50; float moreSpirit = spirit - baseSpirit; float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio; return regen; } float Player::OCTRegenMPPerSpirit() { uint32 level = getLevel(); uint32 pclass = getClass(); if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (moreRatio==NULL) return 0.0f; // Formula get from PaperDollFrame script float spirit = GetStat(STAT_SPIRIT); float regen = spirit * moreRatio->ratio; return regen; } void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply) { m_baseRatingValue[cr]+=(apply ? value : -value); // explicit affected values switch (cr) { case CR_HASTE_MELEE: { float RatingChange = value * GetRatingMultiplier(cr); ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply); ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply); break; } case CR_HASTE_RANGED: { float RatingChange = value * GetRatingMultiplier(cr); ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply); break; } case CR_HASTE_SPELL: { float RatingChange = value * GetRatingMultiplier(cr); ApplyCastTimePercentMod(RatingChange,apply); break; } default: break; } UpdateRating(cr); } void Player::UpdateRating(CombatRating cr) { int32 amount = m_baseRatingValue[cr]; // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT // stat used stored in miscValueB for this aura AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT); for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i) if ((*i)->GetMiscValue() & (1<<cr)) amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f); if (amount < 0) amount = 0; SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount)); bool affectStats = CanModifyStats(); switch (cr) { case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst case CR_DEFENSE_SKILL: UpdateDefenseBonusesMod(); break; case CR_DODGE: UpdateDodgePercentage(); break; case CR_PARRY: UpdateParryPercentage(); break; case CR_BLOCK: UpdateBlockPercentage(); break; case CR_HIT_MELEE: UpdateMeleeHitChances(); break; case CR_HIT_RANGED: UpdateRangedHitChances(); break; case CR_HIT_SPELL: UpdateSpellHitChances(); break; case CR_CRIT_MELEE: if (affectStats) { UpdateCritPercentage(BASE_ATTACK); UpdateCritPercentage(OFF_ATTACK); } break; case CR_CRIT_RANGED: if (affectStats) UpdateCritPercentage(RANGED_ATTACK); break; case CR_CRIT_SPELL: if (affectStats) UpdateAllSpellCritChances(); break; case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc case CR_HIT_TAKEN_RANGED: break; case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult break; case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit) case CR_CRIT_TAKEN_RANGED: break; case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit) break; case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod case CR_HASTE_RANGED: case CR_HASTE_SPELL: break; case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst case CR_WEAPON_SKILL_OFFHAND: case CR_WEAPON_SKILL_RANGED: break; case CR_EXPERTISE: if (affectStats) { UpdateExpertise(BASE_ATTACK); UpdateExpertise(OFF_ATTACK); } break; case CR_ARMOR_PENETRATION: if (affectStats) UpdateArmorPenetration(); break; } } void Player::UpdateAllRatings() { for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr) UpdateRating(CombatRating(cr)); } void Player::SetRegularAttackTime() { for(int i = 0; i < MAX_ATTACK; ++i) { Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false); if (tmpitem) { ItemPrototype const *proto = tmpitem->GetProto(); if (proto->Delay) SetAttackTime(WeaponAttackType(i), proto->Delay); else SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME); } } } //skill+step, checking for max value bool Player::UpdateSkill(uint32 skill_id, uint32 step) { if(!skill_id) return false; SkillStatusMap::iterator itr = mSkillStatus.find(skill_id); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return false; uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos); uint32 data = GetUInt32Value(valueIndex); uint32 value = SKILL_VALUE(data); uint32 max = SKILL_MAX(data); if ((!max) || (!value) || (value >= max)) return false; if (value*512 < max*urand(0,512)) { uint32 new_value = value+step; if (new_value > max) new_value = max; SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max)); if (itr->second.uState != SKILL_NEW) itr->second.uState = SKILL_CHANGED; GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id); return true; } return false; } inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel) { if ( SkillValue >= GrayLevel ) return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY)*10; if ( SkillValue >= GreenLevel ) return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN)*10; if ( SkillValue >= YellowLevel ) return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW)*10; return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE)*10; } bool Player::UpdateCraftSkill(uint32 spellid) { DEBUG_LOG("UpdateCraftSkill spellid %d", spellid); SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid); for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) { if (_spell_idx->second->skillId) { uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId); // Alchemy Discoveries here SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid); if (spellEntry && spellEntry->Mechanic == MECHANIC_DISCOVERY) { if (uint32 discoveredSpell = sSpellMgr.GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this)) learnSpell(discoveredSpell, false); } uint32 craft_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING); return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue, _spell_idx->second->max_value, (_spell_idx->second->max_value + _spell_idx->second->min_value)/2, _spell_idx->second->min_value), craft_skill_gain); } } return false; } bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator ) { DEBUG_LOG("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel); uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING); // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times switch (SkillId) { case SKILL_HERBALISM: case SKILL_LOCKPICKING: case SKILL_JEWELCRAFTING: case SKILL_INSCRIPTION: return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain); case SKILL_SKINNING: if ( sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)==0) return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain); else return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain); case SKILL_MINING: if (sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)==0) return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain); else return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain); } return false; } bool Player::UpdateFishingSkill() { DEBUG_LOG("UpdateFishingSkill"); uint32 SkillValue = GetPureSkillValue(SKILL_FISHING); int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50); uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING); return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain); } // levels sync. with spell requirement for skill levels to learn // bonus abilities in sSkillLineAbilityStore // Used only to avoid scan DBC at each skill grow static uint32 bonusSkillLevels[] = {75,150,225,300,375,450}; bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step) { DEBUG_LOG("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0); if ( !SkillId ) return false; if (Chance <= 0) // speedup in 0 chance case { DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0); return false; } SkillStatusMap::iterator itr = mSkillStatus.find(SkillId); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return false; uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos); uint32 data = GetUInt32Value(valueIndex); uint16 SkillValue = SKILL_VALUE(data); uint16 MaxValue = SKILL_MAX(data); if ( !MaxValue || !SkillValue || SkillValue >= MaxValue ) return false; int32 Roll = irand(1,1000); if ( Roll <= Chance ) { uint32 new_value = SkillValue+step; if (new_value > MaxValue) new_value = MaxValue; SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue)); if (itr->second.uState != SKILL_NEW) itr->second.uState = SKILL_CHANGED; for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl) { if((SkillValue < *bsl && new_value >= *bsl)) { learnSkillRewardedSpells( SkillId, new_value); break; } } // Update depended enchants for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot)); if (!enchant_id) continue; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) continue; if (pEnchant->requiredSkill != SkillId) continue; if (SkillValue < pEnchant->requiredSkillValue && new_value >= pEnchant->requiredSkillValue) ApplyEnchantment(pItem, EnchantmentSlot(slot), true); } } } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId); DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0); return true; } DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0); return false; } void Player::UpdateWeaponSkill(WeaponAttackType attType) { // no skill gain in pvp Unit* pVictim = getVictim(); if (pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself()) return; if (IsInFeralForm()) return; // always maximized SKILL_FERAL_COMBAT in fact if (GetShapeshiftForm() == FORM_TREE) return; // use weapon but not skill up uint32 weaponSkillGain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON); Item* pWeapon = GetWeaponForAttack(attType, true, true); if (pWeapon && pWeapon->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE) UpdateSkill(pWeapon->GetSkill(), weaponSkillGain); else if (!pWeapon && attType == BASE_ATTACK) UpdateSkill(SKILL_UNARMED, weaponSkillGain); UpdateAllCritPercentages(); } void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence) { uint32 plevel = getLevel(); // if defense than pVictim == attacker uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel); uint32 moblevel = pVictim->GetLevelForTarget(this); if (moblevel < greylevel) return; if (moblevel > plevel + 5) moblevel = plevel + 5; uint32 lvldif = moblevel - greylevel; if (lvldif < 3) lvldif = 3; int32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType)); // Max skill reached for level. // Can in some cases be less than 0: having max skill and then .level -1 as example. if (skilldif <= 0) return; float chance = float(3 * lvldif * skilldif) / plevel; if(!defence) chance *= 0.1f * GetStat(STAT_INTELLECT); chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1% if (roll_chance_f(chance)) { if (defence) UpdateDefense(); else UpdateWeaponSkill(attType); } else return; } void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent) { SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return; uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos); uint32 bonus_val = GetUInt32Value(bonusIndex); int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val); int16 perm_bonus = SKILL_PERM_BONUS(bonus_val); if (talent) // permanent bonus stored in high part SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val)); else // temporary/item bonus stored in low part SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus)); } void Player::UpdateSkillsForLevel() { uint16 maxconfskill = sWorld.GetConfigMaxSkillValue(); uint32 maxSkill = GetMaxSkillValueForLevel(); bool alwaysMaxSkill = sWorld.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL); for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr) { if (itr->second.uState == SKILL_DELETED) continue; uint32 pskill = itr->first; SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill); if(!pSkill) continue; if (GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL) continue; uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos); uint32 data = GetUInt32Value(valueIndex); uint32 max = SKILL_MAX(data); uint32 val = SKILL_VALUE(data); /// update only level dependent max skill values if (max!=1) { /// maximize skill always if (alwaysMaxSkill) { SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill)); if (itr->second.uState != SKILL_NEW) itr->second.uState = SKILL_CHANGED; GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, pskill); } else if (max != maxconfskill) /// update max skill value if current max skill not maximized { SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill)); if (itr->second.uState != SKILL_NEW) itr->second.uState = SKILL_CHANGED; } } } } void Player::UpdateSkillsToMaxSkillsForLevel() { for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr) { if (itr->second.uState == SKILL_DELETED) continue; uint32 pskill = itr->first; if ( IsProfessionOrRidingSkill(pskill)) continue; uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos); uint32 data = GetUInt32Value(valueIndex); uint32 max = SKILL_MAX(data); if (max > 1) { SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max)); if (itr->second.uState != SKILL_NEW) itr->second.uState = SKILL_CHANGED; GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, pskill); } if (pskill == SKILL_DEFENSE) UpdateDefenseBonusesMod(); } } // This functions sets a skill line value (and adds if doesn't exist yet) // To "remove" a skill line, set it's values to zero void Player::SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step /*=0*/) { if(!id) return; SkillStatusMap::iterator itr = mSkillStatus.find(id); // has skill if (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED) { if (currVal) { for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot)); if (!enchant_id) continue; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) continue; if (pEnchant->requiredSkill != id) continue; ApplyEnchantment(pItem, EnchantmentSlot(slot), false); } } } if (step) // need update step SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), MAKE_PAIR32(id, step)); // update value SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), MAKE_SKILL_VALUE(currVal, maxVal)); if (itr->second.uState != SKILL_NEW) itr->second.uState = SKILL_CHANGED; learnSkillRewardedSpells(id, currVal); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id); for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot)); if (!enchant_id) continue; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) continue; if (pEnchant->requiredSkill != id) continue; ApplyEnchantment(pItem, EnchantmentSlot(slot), true); } } } } else //remove { // Remove depended enchants for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot)); if (!enchant_id) continue; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) continue; if (pEnchant->requiredSkill != id) continue; ApplyEnchantment(pItem, EnchantmentSlot(slot), false); } } } // clear skill fields SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), 0); SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), 0); SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos), 0); // mark as deleted or simply remove from map if not saved yet if (itr->second.uState != SKILL_NEW) itr->second.uState = SKILL_DELETED; else mSkillStatus.erase(itr); // remove all spells that related to this skill for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) if (SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j)) if (pAbility->skillId == id) removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId)); } } else if (currVal) // add { for (int i = 0; i < PLAYER_MAX_SKILLS; ++i) { if (!GetUInt32Value(PLAYER_SKILL_INDEX(i))) { SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id); if(!pSkill) { sLog.outError("Skill not found in SkillLineStore: skill #%u", id); return; } SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id, step)); SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal, maxVal)); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id); // insert new entry or update if not deleted old entry yet if (itr != mSkillStatus.end()) { itr->second.pos = i; itr->second.uState = SKILL_CHANGED; } else mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW))); // apply skill bonuses SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i), 0); // temporary bonuses AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL); for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j) if ((*j)->GetModifier()->m_miscvalue == int32(id)) (*j)->ApplyModifier(true); // permanent bonuses AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT); for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j) if ((*j)->GetModifier()->m_miscvalue == int32(id)) (*j)->ApplyModifier(true); // Learn all spells for skill learnSkillRewardedSpells(id, currVal); return; } } } } bool Player::HasSkill(uint32 skill) const { if(!skill) return false; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED); } uint16 Player::GetSkillValue(uint32 skill) const { if(!skill) return 0; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return 0; uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)); int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)))); result += SKILL_TEMP_BONUS(bonus); result += SKILL_PERM_BONUS(bonus); return result < 0 ? 0 : result; } uint16 Player::GetMaxSkillValue(uint32 skill) const { if(!skill) return 0; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return 0; uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)); int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)))); result += SKILL_TEMP_BONUS(bonus); result += SKILL_PERM_BONUS(bonus); return result < 0 ? 0 : result; } uint16 Player::GetPureMaxSkillValue(uint32 skill) const { if(!skill) return 0; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return 0; return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))); } uint16 Player::GetBaseSkillValue(uint32 skill) const { if(!skill) return 0; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return 0; int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)))); result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos))); return result < 0 ? 0 : result; } uint16 Player::GetPureSkillValue(uint32 skill) const { if(!skill) return 0; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return 0; return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))); } int16 Player::GetSkillPermBonusValue(uint32 skill) const { if(!skill) return 0; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return 0; return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos))); } int16 Player::GetSkillTempBonusValue(uint32 skill) const { if(!skill) return 0; SkillStatusMap::const_iterator itr = mSkillStatus.find(skill); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) return 0; return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos))); } void Player::SendActionButtons(uint32 state) const { DETAIL_LOG( "Initializing Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec); WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4)); data << uint8(state); /* state can be 0, 1, 2 0 - Looks to be sent when initial action buttons get sent, however on Trinity we use 1 since 0 had some difficulties 1 - Used in any SMSG_ACTION_BUTTONS packet with button data on Trinity. Only used after spec swaps on retail. 2 - Clears the action bars client sided. This is sent during spec swap before unlearning and before sending the new buttons */ if (state != 2) { ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec]; for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button) { ActionButtonList::const_iterator itr = currentActionButtonList.find(button); if (itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED) data << uint32(itr->second.packedData); else data << uint32(0); } } GetSession()->SendPacket( &data ); DETAIL_LOG( "Action Buttons for '%u' spec '%u' Initialized", GetGUIDLow(), m_activeSpec ); } void Player::SendLockActionButtons() const { DETAIL_LOG( "Locking Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec); WorldPacket data(SMSG_ACTION_BUTTONS, 1); // sending 2 locks actions bars, neither user can remove buttons, nor client removes buttons at spell unlearn // they remain locked until server sends new action buttons data << uint8(2); GetSession()->SendPacket( &data ); } bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player, bool msg) { if (button >= MAX_ACTION_BUTTONS) { if (msg) { if (player) sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS ); else sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS ); } return false; } if (action >= MAX_ACTION_BUTTON_ACTION_VALUE) { if (msg) { if (player) sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE ); else sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE ); } return false; } switch(type) { case ACTION_BUTTON_SPELL: { SpellEntry const* spellProto = sSpellStore.LookupEntry(action); if(!spellProto) { if (msg) { if (player) sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() ); else sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button ); } return false; } if (player) { if(!player->HasSpell(spellProto->Id)) { if (msg) sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() ); return false; } else if (IsPassiveSpell(spellProto)) { if (msg) sLog.outError( "Spell action %u not added into button %u for player %s: spell is passive", action, button, player->GetName() ); return false; } // current range for button of totem bar is from ACTION_BUTTON_SHAMAN_TOTEMS_BAR to (but not including) ACTION_BUTTON_SHAMAN_TOTEMS_BAR + 12 else if (button >= ACTION_BUTTON_SHAMAN_TOTEMS_BAR && button < (ACTION_BUTTON_SHAMAN_TOTEMS_BAR + 12) && !(spellProto->AttributesEx7 & SPELL_ATTR_EX7_TOTEM_SPELL)) { if (msg) sLog.outError( "Spell action %u not added into button %u for player %s: attempt to add non totem spell to totem bar", action, button, player->GetName() ); return false; } } break; } case ACTION_BUTTON_ITEM: { if(!ObjectMgr::GetItemPrototype(action)) { if (msg) { if (player) sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() ); else sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button ); } return false; } break; } default: break; // other cases not checked at this moment } return true; } ActionButton* Player::addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type) { // check action only for active spec (so not check at copy/load passive spec) if (spec == GetActiveSpec() && !IsActionButtonDataValid(button,action,type,this)) return NULL; // it create new button (NEW state) if need or return existing ActionButton& ab = m_actionButtons[spec][button]; // set data and update to CHANGED if not NEW ab.SetActionAndType(action,ActionButtonType(type)); DETAIL_LOG("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action, uint32(type), button, spec); return &ab; } void Player::removeActionButton(uint8 spec, uint8 button) { ActionButtonList& currentActionButtonList = m_actionButtons[spec]; ActionButtonList::iterator buttonItr = currentActionButtonList.find(button); if (buttonItr == currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED) return; if (buttonItr->second.uState == ACTIONBUTTON_NEW) currentActionButtonList.erase(buttonItr); // new and not saved else buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save DETAIL_LOG("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec); } ActionButton const* Player::GetActionButton(uint8 button) { ActionButtonList& currentActionButtonList = m_actionButtons[m_activeSpec]; ActionButtonList::iterator buttonItr = currentActionButtonList.find(button); if (buttonItr==currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED) return NULL; return &buttonItr->second; } bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport) { if (!Unit::SetPosition(x, y, z, orientation, teleport)) return false; // group update if (GetGroup()) SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION); if (GetTrader() && !IsWithinDistInMap(GetTrader(), INTERACTION_DISTANCE)) GetSession()->SendCancelTrade(); // will close both side trade windows // code block for underwater state update UpdateUnderwaterState(GetMap(), x, y, z); CheckAreaExploreAndOutdoor(); return true; } void Player::SaveRecallPosition() { m_recallMap = GetMapId(); m_recallX = GetPositionX(); m_recallY = GetPositionY(); m_recallZ = GetPositionZ(); m_recallO = GetOrientation(); } void Player::SendMessageToSet(WorldPacket *data, bool self) { if (IsInWorld()) GetMap()->MessageBroadcast(this, data, false); //if player is not in world and map in not created/already destroyed //no need to create one, just send packet for itself! if (self) GetSession()->SendPacket(data); } void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self) { if (IsInWorld()) GetMap()->MessageDistBroadcast(this, data, dist, false); if (self) GetSession()->SendPacket(data); } void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only) { if (IsInWorld()) GetMap()->MessageDistBroadcast(this, data, dist, false, own_team_only); if (self) GetSession()->SendPacket(data); } void Player::SendDirectMessage(WorldPacket *data) { GetSession()->SendPacket(data); } void Player::SendCinematicStart(uint32 CinematicSequenceId) { WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4); data << uint32(CinematicSequenceId); SendDirectMessage(&data); } void Player::SendMovieStart(uint32 MovieId) { WorldPacket data(SMSG_TRIGGER_MOVIE, 4); data << uint32(MovieId); SendDirectMessage(&data); } void Player::CheckAreaExploreAndOutdoor() { if (!isAlive()) return; if (IsTaxiFlying() || !GetMap()) return; bool isOutdoor; uint16 areaFlag = GetTerrain()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ(), &isOutdoor); if (isOutdoor) { if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() == REST_TYPE_IN_TAVERN) { AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(inn_trigger_id); if (!at || !IsPointInAreaTriggerZone(at, GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ())) { // Player left inn (REST_TYPE_IN_CITY overrides REST_TYPE_IN_TAVERN, so just clear rest) SetRestType(REST_TYPE_NO); } } } else if (sWorld.getConfig(CONFIG_BOOL_VMAP_INDOOR_CHECK) && !isGameMaster()) RemoveAurasWithAttribute(SPELL_ATTR_OUTDOORS_ONLY); if (areaFlag==0xffff) return; int offset = areaFlag / 32; if (offset >= PLAYER_EXPLORED_ZONES_SIZE) { sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < %u ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset, PLAYER_EXPLORED_ZONES_SIZE); return; } uint32 val = (uint32)(1 << (areaFlag % 32)); uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset); if (!(currFields & val)) { SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val)); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA); AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId()); if(!p) { sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId()); } else if (p->area_level > 0) { uint32 area = p->ID; if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { SendExplorationExperience(area,0); } else { int32 diff = int32(getLevel()) - p->area_level; uint32 XP = 0; if (diff < -5) { XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE)); } else if (diff > 5) { int32 exploration_percent = (100-((diff-5)*5)); if (exploration_percent > 100) exploration_percent = 100; else if (exploration_percent < 0) exploration_percent = 0; XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE)); } else { XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE)); } XP = uint32(XP * (GetSession()->IsPremium() + 1)); GiveXP( XP, NULL ); SendExplorationExperience(area,XP); } DETAIL_LOG("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area); } } } Team Player::TeamForRace(uint8 race) { ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race); if (!rEntry) { sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race)); return ALLIANCE; } switch(rEntry->TeamID) { case 7: return ALLIANCE; case 1: return HORDE; } sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID); return TEAM_NONE; } uint32 Player::getFactionForRace(uint8 race) { ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race); if(!rEntry) { sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race)); return 0; } return rEntry->FactionID; } void Player::setFactionForRace(uint8 race) { m_team = TeamForRace(race); setFaction(getFactionForRace(race)); } ReputationRank Player::GetReputationRank(uint32 faction) const { FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction); return GetReputationMgr().GetRank(factionEntry); } //Calculate total reputation percent player gain with quest/creature level int32 Player::CalculateReputationGain(ReputationSource source, int32 rep, int32 faction, uint32 creatureOrQuestLevel, bool noAuraBonus) { float percent = 100.0f; float repMod = noAuraBonus ? 0.0f : (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN); // faction specific auras only seem to apply to kills if (source == REPUTATION_SOURCE_KILL) repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction); percent += rep > 0 ? repMod : -repMod; float rate; switch (source) { case REPUTATION_SOURCE_KILL: rate = sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL); break; case REPUTATION_SOURCE_QUEST: rate = sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST); break; case REPUTATION_SOURCE_SPELL: default: rate = 1.0f; break; } if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel())) percent *= rate; if (percent <= 0.0f) return 0; // Multiply result with the faction specific rate if (const RepRewardRate *repData = sObjectMgr.GetRepRewardRate(faction)) { float repRate = 0.0f; switch (source) { case REPUTATION_SOURCE_KILL: repRate = repData->creature_rate; break; case REPUTATION_SOURCE_QUEST: repRate = repData->quest_rate; break; case REPUTATION_SOURCE_SPELL: repRate = repData->spell_rate; break; } // for custom, a rate of 0.0 will totally disable reputation gain for this faction/type if (repRate <= 0.0f) return 0; percent *= repRate; } if (CheckRAFConditions()) { percent *= sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_XP); } return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN)*rep*percent/100.0f); } //Calculates how many reputation points player gains in victim's enemy factions void Player::RewardReputation(Unit *pVictim, float rate) { if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER) return; // used current difficulty creature entry instead normal version (GetEntry()) ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKillEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry); if(!Rep) return; uint32 Repfaction1 = Rep->repfaction1; uint32 Repfaction2 = Rep->repfaction2; uint32 tabardFactionID = 0; // Championning tabard reputation system if (HasAura(Rep->championingAura)) { if ( Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_TABARD ) ) { if ( tabardFactionID = pItem->GetProto()->RequiredReputationFaction ) { Repfaction1 = tabardFactionID; Repfaction2 = tabardFactionID; } } } if (Repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE)) { int32 donerep1 = CalculateReputationGain(REPUTATION_SOURCE_KILL, Rep->repvalue1, Repfaction1, pVictim->getLevel()); donerep1 = int32(donerep1*rate); FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Repfaction1); uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1); if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1) GetReputationMgr().ModifyReputation(factionEntry1, donerep1); // Wiki: Team factions value divided by 2 if (factionEntry1 && Rep->is_teamaward1) { FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team); if (team1_factionEntry) GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2); } } if (Repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE)) { int32 donerep2 = CalculateReputationGain(REPUTATION_SOURCE_KILL, Rep->repvalue2, Repfaction2, pVictim->getLevel()); donerep2 = int32(donerep2*rate); FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Repfaction2); uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2); if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2) GetReputationMgr().ModifyReputation(factionEntry2, donerep2); // Wiki: Team factions value divided by 2 if (factionEntry2 && Rep->is_teamaward2) { FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team); if (team2_factionEntry) GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2); } } } //Calculate how many reputation points player gain with the quest void Player::RewardReputation(Quest const *pQuest) { // quest reputation reward/loss for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) { if (!pQuest->RewRepFaction[i]) continue; // No diplomacy mod are applied to the final value (flat). Note the formula (finalValue = DBvalue/100) if (pQuest->RewRepValue[i]) { int32 rep = CalculateReputationGain(REPUTATION_SOURCE_QUEST, pQuest->RewRepValue[i]/100, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest), true); if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i])) GetReputationMgr().ModifyReputation(factionEntry, rep); } else { uint32 row = ((pQuest->RewRepValueId[i] < 0) ? 1 : 0) + 1; uint32 field = abs(pQuest->RewRepValueId[i]); if (const QuestFactionRewardEntry *pRow = sQuestFactionRewardStore.LookupEntry(row)) { int32 repPoints = pRow->rewardValue[field]; if (!repPoints) continue; repPoints = CalculateReputationGain(REPUTATION_SOURCE_QUEST, repPoints, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest)); if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i])) GetReputationMgr().ModifyReputation(factionEntry, repPoints); } } } // TODO: implement reputation spillover } void Player::UpdateArenaFields(void) { /* arena calcs go here */ } void Player::UpdateHonorFields() { /// called when rewarding honor and at each save time_t now = time(NULL); time_t today = (time(NULL) / DAY) * DAY; if (m_lastHonorUpdateTime < today) { time_t yesterday = today - DAY; uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS)); // update yesterday's contribution if (m_lastHonorUpdateTime >= yesterday ) { SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION)); // this is the first update today, reset today's contribution SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0); SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today)); } else { // no honor/kills yesterday or today, reset SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0); SetUInt32Value(PLAYER_FIELD_KILLS, 0); } } m_lastHonorUpdateTime = now; // START custom PvP Honor Kills Title System if (sWorld.getConfig(CONFIG_BOOL_ALLOW_HONOR_KILLS_TITLES)) { uint32 HonorKills = GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS); uint32 victim_rank = 0; // lets check if player fits to title brackets (none of players reached by now 50k HK. this is bad condition in aspect // of making code generic, but allows to save some CPU and avoid fourther steps execution if (HonorKills < 100 || HonorKills > 50000) return; if (HonorKills >= 100 && HonorKills < 200) victim_rank = 1; else if (HonorKills >= 200 && HonorKills < 500) victim_rank = 2; else if (HonorKills >= 500 && HonorKills < 1000) victim_rank = 3; else if (HonorKills >= 1000 && HonorKills < 2100) victim_rank = 4; else if (HonorKills >= 2100 && HonorKills < 3200) victim_rank = 5; else if (HonorKills >= 3200 && HonorKills < 4300) victim_rank = 6; else if (HonorKills >= 4300 && HonorKills < 5400) victim_rank = 7; else if (HonorKills >= 5400 && HonorKills < 6500) victim_rank = 8; else if (HonorKills >= 6500 && HonorKills < 7600) victim_rank = 9; else if (HonorKills >= 7600 && HonorKills < 9000) victim_rank = 10; else if (HonorKills >= 9000 && HonorKills < 15000) victim_rank = 11; else if (HonorKills >= 15000 && HonorKills < 30000) victim_rank = 12; else if (HonorKills >= 30000 && HonorKills < 50000) victim_rank = 13; else if (HonorKills == 50000) victim_rank = 14; // horde titles starting from 15+ if (GetTeam() == HORDE) victim_rank += 14; if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(victim_rank)) { // if player does have title there is no need to update fourther if (!HasTitle(titleEntry)) { // lets remove all previous ranks for (uint8 i = 1; i < 29; ++i) { if (CharTitlesEntry const* title = sCharTitlesStore.LookupEntry(i)) { if (HasTitle(title)) SetTitle(title, true); } } // finaly apply and set as active new title SetTitle(titleEntry); SetUInt32Value(PLAYER_CHOSEN_TITLE, victim_rank); } } } // END custom PvP Honor Kills Title System } ///Calculate the amount of honor gained based on the victim ///and the size of the group for which the honor is divided ///An exact honor value can also be given (overriding the calcs) bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor) { // do not reward honor in arenas, but enable onkill spellproc if (InArena()) { if (!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER) return false; if (GetBGTeam() == ((Player*)uVictim)->GetBGTeam()) return false; return true; } // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens if (GetDummyAura(SPELL_AURA_PLAYER_INACTIVE)) return false; ObjectGuid victim_guid; uint32 victim_rank = 0; // need call before fields update to have chance move yesterday data to appropriate fields before today data change. UpdateHonorFields(); if (honor <= 0) { if (!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT)) return false; victim_guid = uVictim->GetObjectGuid(); if (uVictim->GetTypeId() == TYPEID_PLAYER) { Player *pVictim = (Player *)uVictim; if (GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm()) return false; float f = 1; //need for total kills (?? need more info) uint32 k_grey = 0; uint32 k_level = getLevel(); uint32 v_level = pVictim->getLevel(); { // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION // [0] Just name // [1..14] Alliance honor titles and player name // [15..28] Horde honor titles and player name // [29..38] Other title and player name // [39+] Nothing uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE); // Get Killer titles, CharTitlesEntry::bit_index // Ranks: // title[1..14] -> rank[5..18] // title[15..28] -> rank[5..18] // title[other] -> 0 if (victim_title == 0) victim_guid.Clear(); // Don't show HK: <rank> message, only log. else if (victim_title < 15) victim_rank = victim_title + 4; else if (victim_title < 29) victim_rank = victim_title - 14 + 4; else victim_guid.Clear(); // Don't show HK: <rank> message, only log. } k_grey = MaNGOS::XP::GetGrayLevel(k_level); if (v_level<=k_grey) return false; float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey))); int32 v_rank =1; //need more info honor = ((f * diff_level * (190 + v_rank*10))/6); honor *= float(k_level) / 70.0f; //factor of dependence on levels of the killer // count the number of playerkills in one day ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true); // and those in a lifetime ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass()); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace()); } else { Creature *cVictim = (Creature *)uVictim; if (!cVictim->IsRacialLeader()) return false; honor = 2000; // ??? need more info victim_rank = 19; // HK: Leader if (groupsize > 1) honor *= groupsize; } } if (uVictim != NULL) { honor *= sWorld.getConfig(CONFIG_FLOAT_RATE_HONOR); honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f; if (groupsize > 1) honor /= groupsize; honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor honor *= 2.0f; // as of 3.3.3 HK have had a 100% increase to honor } // honor - for show honor points in log // victim_guid - for show victim name in log // victim_rank [1..4] HK: <dishonored rank> // victim_rank [5..19] HK: <alliance\horde rank> // victim_rank [0,20+] HK: <> WorldPacket data(SMSG_PVP_CREDIT, 4 + 8 + 4); data << uint32(honor); data << ObjectGuid(victim_guid); data << uint32(victim_rank); GetSession()->SendPacket(&data); // add honor points ModifyHonorPoints(int32(honor)); ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true); return true; } void Player::SetHonorPoints(uint32 value) { if (value > sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS)) value = sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS); SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, value); } void Player::SetArenaPoints(uint32 value) { if (value > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS)) value = sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS); SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, value); } void Player::ModifyHonorPoints(int32 value) { int32 newValue = (int32)GetHonorPoints() + value; if (newValue < 0) newValue = 0; SetHonorPoints(newValue); } void Player::ModifyArenaPoints(int32 value) { int32 newValue = (int32)GetArenaPoints() + value; if (newValue < 0) newValue = 0; SetArenaPoints(newValue); } uint32 Player::GetGuildIdFromDB(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", lowguid); if (!result) return 0; uint32 id = result->Fetch()[0].GetUInt32(); delete result; return id; } uint32 Player::GetRankFromDB(ObjectGuid guid) { QueryResult *result = CharacterDatabase.PQuery("SELECT rank FROM guild_member WHERE guid='%u'", guid.GetCounter()); if (result) { uint32 v = result->Fetch()[0].GetUInt32(); delete result; return v; } else return 0; } uint32 Player::GetArenaTeamIdFromDB(ObjectGuid guid, ArenaType type) { QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", guid.GetCounter(), type); if (!result) return 0; uint32 id = (*result)[0].GetUInt32(); delete result; return id; } uint32 Player::GetZoneIdFromDB(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); QueryResult *result = CharacterDatabase.PQuery("SELECT zone FROM characters WHERE guid='%u'", lowguid); if (!result) return 0; Field* fields = result->Fetch(); uint32 zone = fields[0].GetUInt32(); delete result; if (!zone) { // stored zone is zero, use generic and slow zone detection result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", lowguid); if ( !result ) return 0; fields = result->Fetch(); uint32 map = fields[0].GetUInt32(); float posx = fields[1].GetFloat(); float posy = fields[2].GetFloat(); float posz = fields[3].GetFloat(); delete result; zone = sTerrainMgr.GetZoneId(map,posx,posy,posz); if (zone > 0) CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, lowguid); } return zone; } uint32 Player::GetLevelFromDB(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); QueryResult *result = CharacterDatabase.PQuery("SELECT level FROM characters WHERE guid='%u'", lowguid); if (!result) return 0; Field* fields = result->Fetch(); uint32 level = fields[0].GetUInt32(); delete result; return level; } void Player::UpdateArea(uint32 newArea) { m_areaUpdateId = newArea; AreaTableEntry const* area = GetAreaEntryByAreaID(newArea); // FFA_PVP flags are area and not zone id dependent // so apply them accordingly if (area && (area->flags & AREA_FLAG_ARENA)) { if (!isGameMaster()) SetFFAPvP(true); } else { // remove ffa flag only if not ffapvp realm // removal in sanctuaries and capitals is handled in zone update if (IsFFAPvP() && !sWorld.IsFFAPvPRealm()) SetFFAPvP(false); } if (area) { // Dalaran restricted flight zone if ((area->flags & AREA_FLAG_CANNOT_FLY) && IsFreeFlying() && !isGameMaster() && !HasAura(58600)) CastSpell(this, 58600, true); // Restricted Flight Area // TODO: implement wintergrasp parachute when battle in progress /* if ((area->flags & AREA_FLAG_OUTDOOR_PVP) && IsFreeFlying() && <WINTERGRASP_BATTLE_IN_PROGRESS> && !isGameMaster()) CastSpell(this, 58730, true); */ } UpdateAreaDependentAuras(); } WorldPvP* Player::GetWorldPvP() const { return sWorldPvPMgr.GetWorldPvPToZoneId(GetZoneId()); } bool Player::IsWorldPvPActive() { return CanCaptureTowerPoint() && (IsPvP() || sWorld.IsPvPRealm()) && !HasMovementFlag(MOVEFLAG_FLYING) && !IsTaxiFlying() && !isGameMaster(); } void Player::UpdateZone(uint32 newZone, uint32 newArea) { AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone); if(!zone) return; if (m_zoneUpdateId != newZone) { //Called when a player leave zone if (InstanceData* mapInstance = GetInstanceData()) mapInstance->OnPlayerLeaveZone(this, m_zoneUpdateId); // handle world pvp zones sWorldPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId); SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange... sWorldPvPMgr.HandlePlayerEnterZone(this, newZone); // call this method in order to handle some scripted zones if (InstanceData* mapInstance = GetInstanceData()) mapInstance->OnPlayerEnterZone(this, newZone, newArea); if (sWorld.getConfig(CONFIG_BOOL_WEATHER)) { if (Weather *wth = sWorld.FindWeather(zone->ID)) wth->SendWeatherUpdateToPlayer(this); else if(!sWorld.AddWeather(zone->ID)) { // send fine weather packet to remove old zone's weather Weather::SendFineWeatherUpdateToPlayer(this); } } } m_zoneUpdateId = newZone; m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL; // zone changed, so area changed as well, update it UpdateArea(newArea); // in PvP, any not controlled zone (except zone->team == 6, default case) // in PvE, only opposition team capital switch(zone->team) { case AREATEAM_ALLY: pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL); break; case AREATEAM_HORDE: pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL); break; case AREATEAM_NONE: // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround(); break; default: // 6 in fact pvpInfo.inHostileArea = false; break; } if (pvpInfo.inHostileArea) // in hostile area { if(!IsPvP() || pvpInfo.endTimer != 0) UpdatePvP(true, true); } else // in friendly area { if (IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0) pvpInfo.endTimer = time(0); // start toggle-off } if (zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary { SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY); if (sWorld.IsFFAPvPRealm()) SetFFAPvP(false); } else { RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY); } if (zone->flags & AREA_FLAG_CAPITAL) // in capital city SetRestType(REST_TYPE_IN_CITY); else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() != REST_TYPE_IN_TAVERN) // resting and not in tavern (leave city then); tavern leave handled in CheckAreaExploreAndOutdoor SetRestType(REST_TYPE_NO); // remove items with area/map limitations (delete only for alive player to allow back in ghost mode) // if player resurrected at teleport this will be applied in resurrect code if (isAlive()) DestroyZoneLimitedItem( true, newZone ); // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example) AutoUnequipOffhandIfNeed(); // recent client version not send leave/join channel packets for built-in local channels UpdateLocalChannels( newZone ); // group update if (GetGroup()) SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE); UpdateZoneDependentAuras(); UpdateZoneDependentPets(); } //If players are too far way of duel flag... then player loose the duel void Player::CheckDuelDistance(time_t currTime) { if (!duel) return; GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER)); if (!obj) { // player not at duel start map DuelComplete(DUEL_FLED); return; } if (duel->outOfBound == 0) { if (!IsWithinDistInMap(obj, 50)) { duel->outOfBound = currTime; WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0); GetSession()->SendPacket(&data); } } else { if (IsWithinDistInMap(obj, 40)) { duel->outOfBound = 0; WorldPacket data(SMSG_DUEL_INBOUNDS, 0); GetSession()->SendPacket(&data); } else if (currTime >= (duel->outOfBound+10)) { DuelComplete(DUEL_FLED); } } } void Player::DuelComplete(DuelCompleteType type) { // duel not requested if (!duel) return; WorldPacket data(SMSG_DUEL_COMPLETE, (1)); data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0); GetSession()->SendPacket(&data); duel->opponent->GetSession()->SendPacket(&data); if (type != DUEL_INTERUPTED) { data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled data << duel->opponent->GetName(); data << GetName(); SendMessageToSet(&data,true); } if (type == DUEL_WON) { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1); if (duel->opponent) duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1); } //Remove Duel Flag object if (GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER))) duel->initiator->RemoveGameObject(obj, true); /* remove auras */ std::vector<uint32> auras2remove; SpellAuraHolderMap const& vAuras = duel->opponent->GetSpellAuraHolderMap(); for (SpellAuraHolderMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i) { if (!i->second->IsPositive() && i->second->GetCasterGuid() == GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime) auras2remove.push_back(i->second->GetId()); } for(size_t i=0; i<auras2remove.size(); ++i) duel->opponent->RemoveAurasDueToSpell(auras2remove[i]); auras2remove.clear(); SpellAuraHolderMap const& auras = GetSpellAuraHolderMap(); for (SpellAuraHolderMap::const_iterator i = auras.begin(); i != auras.end(); ++i) { if (!i->second->IsPositive() && i->second->GetCasterGuid() == duel->opponent->GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime) auras2remove.push_back(i->second->GetId()); } for (size_t i=0; i<auras2remove.size(); ++i) RemoveAurasDueToSpell(auras2remove[i]); // cleanup combo points if (GetComboTargetGuid() == duel->opponent->GetObjectGuid()) ClearComboPoints(); else if (GetComboTargetGuid() == duel->opponent->GetPetGuid()) ClearComboPoints(); if (duel->opponent->GetComboTargetGuid() == GetObjectGuid()) duel->opponent->ClearComboPoints(); else if (duel->opponent->GetComboTargetGuid() == GetPetGuid()) duel->opponent->ClearComboPoints(); //cleanups SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid()); SetUInt32Value(PLAYER_DUEL_TEAM, 0); duel->opponent->SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid()); duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0); delete duel->opponent->duel; duel->opponent->duel = NULL; delete duel; duel = NULL; } //---------------------------------------------------------// void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply) { if (slot >= INVENTORY_SLOT_BAG_END || !item) return; // not apply/remove mods for broken item if (item->IsBroken()) return; ItemPrototype const *proto = item->GetProto(); if(!proto) return; DETAIL_LOG("applying mods for item %u ",item->GetGUIDLow()); uint32 attacktype = Player::GetAttackBySlot(slot); if (attacktype < MAX_ATTACK) _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply); _ApplyItemBonuses(proto,slot,apply); if ( slot==EQUIPMENT_SLOT_RANGED ) _ApplyAmmoBonuses(); ApplyItemEquipSpell(item,apply); ApplyEnchantment(item, apply); if (proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items CorrectMetaGemEnchants(slot, apply); DEBUG_LOG("_ApplyItemMods complete."); } void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/) { if (slot >= INVENTORY_SLOT_BAG_END || !proto) return; ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL; if (only_level_scale && !ssd) return; // req. check at equip, but allow use for extended range if range limit max level, set proper level uint32 ssd_level = getLevel(); if (ssd && ssd_level > ssd->MaxLevel) ssd_level = ssd->MaxLevel; ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL; if (only_level_scale && !ssv) return; for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i) { uint32 statType = 0; int32 val = 0; // If set ScalingStatDistribution need get stats and values from it if (ssd && ssv) { if (ssd->StatMod[i] < 0) continue; statType = ssd->StatMod[i]; val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000; } else { if (i >= proto->StatsCount) continue; statType = proto->ItemStat[i].ItemStatType; val = proto->ItemStat[i].ItemStatValue; } if (val == 0) continue; switch (statType) { case ITEM_MOD_MANA: HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply); break; case ITEM_MOD_HEALTH: // modify HP HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply); break; case ITEM_MOD_AGILITY: // modify agility HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply); ApplyStatBuffMod(STAT_AGILITY, float(val), apply); break; case ITEM_MOD_STRENGTH: //modify strength HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply); ApplyStatBuffMod(STAT_STRENGTH, float(val), apply); break; case ITEM_MOD_INTELLECT: //modify intellect HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply); ApplyStatBuffMod(STAT_INTELLECT, float(val), apply); break; case ITEM_MOD_SPIRIT: //modify spirit HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply); ApplyStatBuffMod(STAT_SPIRIT, float(val), apply); break; case ITEM_MOD_STAMINA: //modify stamina HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply); ApplyStatBuffMod(STAT_STAMINA, float(val), apply); break; case ITEM_MOD_DEFENSE_SKILL_RATING: ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply); break; case ITEM_MOD_DODGE_RATING: ApplyRatingMod(CR_DODGE, int32(val), apply); break; case ITEM_MOD_PARRY_RATING: ApplyRatingMod(CR_PARRY, int32(val), apply); break; case ITEM_MOD_BLOCK_RATING: ApplyRatingMod(CR_BLOCK, int32(val), apply); break; case ITEM_MOD_HIT_MELEE_RATING: ApplyRatingMod(CR_HIT_MELEE, int32(val), apply); break; case ITEM_MOD_HIT_RANGED_RATING: ApplyRatingMod(CR_HIT_RANGED, int32(val), apply); break; case ITEM_MOD_HIT_SPELL_RATING: ApplyRatingMod(CR_HIT_SPELL, int32(val), apply); break; case ITEM_MOD_CRIT_MELEE_RATING: ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply); break; case ITEM_MOD_CRIT_RANGED_RATING: ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply); break; case ITEM_MOD_CRIT_SPELL_RATING: ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply); break; case ITEM_MOD_HIT_TAKEN_MELEE_RATING: ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply); break; case ITEM_MOD_HIT_TAKEN_RANGED_RATING: ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply); break; case ITEM_MOD_HIT_TAKEN_SPELL_RATING: ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply); break; case ITEM_MOD_CRIT_TAKEN_MELEE_RATING: ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply); break; case ITEM_MOD_CRIT_TAKEN_RANGED_RATING: ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply); break; case ITEM_MOD_CRIT_TAKEN_SPELL_RATING: ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply); break; case ITEM_MOD_HASTE_MELEE_RATING: ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply); break; case ITEM_MOD_HASTE_RANGED_RATING: ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply); break; case ITEM_MOD_HASTE_SPELL_RATING: ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply); break; case ITEM_MOD_HIT_RATING: ApplyRatingMod(CR_HIT_MELEE, int32(val), apply); ApplyRatingMod(CR_HIT_RANGED, int32(val), apply); ApplyRatingMod(CR_HIT_SPELL, int32(val), apply); break; case ITEM_MOD_CRIT_RATING: ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply); ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply); ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply); break; case ITEM_MOD_HIT_TAKEN_RATING: ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply); ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply); ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply); break; case ITEM_MOD_CRIT_TAKEN_RATING: ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply); ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply); ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply); break; case ITEM_MOD_RESILIENCE_RATING: ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply); ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply); ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply); break; case ITEM_MOD_HASTE_RATING: ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply); ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply); ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply); break; case ITEM_MOD_EXPERTISE_RATING: ApplyRatingMod(CR_EXPERTISE, int32(val), apply); break; case ITEM_MOD_ATTACK_POWER: HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply); HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply); break; case ITEM_MOD_RANGED_ATTACK_POWER: HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply); break; case ITEM_MOD_MANA_REGENERATION: ApplyManaRegenBonus(int32(val), apply); break; case ITEM_MOD_ARMOR_PENETRATION_RATING: ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply); break; case ITEM_MOD_SPELL_POWER: ApplySpellPowerBonus(int32(val), apply); break; case ITEM_MOD_HEALTH_REGEN: ApplyHealthRegenBonus(int32(val), apply); break; case ITEM_MOD_SPELL_PENETRATION: ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, -int32(val), apply); m_spellPenetrationItemMod += apply ? val : -val; break; case ITEM_MOD_BLOCK_VALUE: HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(val), apply); break; // deprecated item mods case ITEM_MOD_FERAL_ATTACK_POWER: case ITEM_MOD_SPELL_HEALING_DONE: case ITEM_MOD_SPELL_DAMAGE_DONE: break; } } // Apply Spell Power from ScalingStatValue if set if (ssv) { if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue)) ApplySpellPowerBonus(spellbonus, apply); } // If set ScalingStatValue armor get it or use item armor uint32 armor = proto->Armor; if (ssv) { if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue)) armor = ssvarmor; } // Add armor bonus from ArmorDamageModifier if > 0 if (proto->ArmorDamageModifier > 0) armor += uint32(proto->ArmorDamageModifier); if (armor) { switch(proto->InventoryType) { case INVTYPE_TRINKET: case INVTYPE_NECK: case INVTYPE_CLOAK: case INVTYPE_FINGER: HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(armor), apply); break; default: HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply); break; } } if (proto->Block) HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply); if (proto->HolyRes) HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply); if (proto->FireRes) HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply); if (proto->NatureRes) HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply); if (proto->FrostRes) HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply); if (proto->ShadowRes) HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply); if (proto->ArcaneRes) HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply); WeaponAttackType attType = BASE_ATTACK; float damage = 0.0f; if ( slot == EQUIPMENT_SLOT_RANGED && ( proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN || proto->InventoryType == INVTYPE_RANGEDRIGHT )) { attType = RANGED_ATTACK; } else if (slot==EQUIPMENT_SLOT_OFFHAND) { attType = OFF_ATTACK; } float minDamage = proto->Damage[0].DamageMin; float maxDamage = proto->Damage[0].DamageMax; int32 extraDPS = 0; // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage if (ssv) { if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue))) { float average = extraDPS * proto->Delay / 1000.0f; minDamage = 0.7f * average; maxDamage = 1.3f * average; } } if (minDamage > 0 ) { damage = apply ? minDamage : BASE_MINDAMAGE; SetBaseWeaponDamage(attType, MINDAMAGE, damage); //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE)); } if (maxDamage > 0 ) { damage = apply ? maxDamage : BASE_MAXDAMAGE; SetBaseWeaponDamage(attType, MAXDAMAGE, damage); } // Apply feral bonus from ScalingStatValue if set if (ssv) { if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue)) ApplyFeralAPBonus(feral_bonus, apply); } // Druids get feral AP bonus from weapon dps (also use DPS from ScalingStatValue) if (getClass() == CLASS_DRUID) { int32 feral_bonus = proto->getFeralBonus(extraDPS); if (feral_bonus > 0) ApplyFeralAPBonus(feral_bonus, apply); } if (!CanUseEquippedWeapon(attType)) return; if (proto->Delay) { if (slot == EQUIPMENT_SLOT_RANGED) SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME); else if (slot==EQUIPMENT_SLOT_MAINHAND) SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME); else if (slot==EQUIPMENT_SLOT_OFFHAND) SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME); } if (CanModifyStats() && (damage || proto->Delay)) UpdateDamagePhysical(attType); } void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply) { MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS); AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT); for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr) _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply); AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE); for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr) _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply); AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr) _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply); } void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply) { // generic not weapon specific case processes in aura code if (aura->GetSpellProto()->EquippedItemClass == -1) return; BaseModGroup mod = BASEMOD_END; switch(attackType) { case BASE_ATTACK: mod = CRIT_PERCENTAGE; break; case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break; case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break; default: return; } if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto())) { HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply); } } void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply) { // ignore spell mods for not wands Modifier const* modifier = aura->GetModifier(); if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0) return; // generic not weapon specific case processes in aura code if (aura->GetSpellProto()->EquippedItemClass == -1) return; UnitMods unitMod = UNIT_MOD_END; switch(attackType) { case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break; case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break; case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break; default: return; } UnitModifierType unitModType = TOTAL_VALUE; switch(modifier->m_auraname) { case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break; case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break; default: return; } if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto())) { HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply); } } void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change) { if(!item) return; ItemPrototype const *proto = item->GetProto(); if(!proto) return; for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = proto->Spells[i]; // no spell if(!spellData.SpellId ) continue; if (apply) { // apply only at-equip spells if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP) continue; } else { // at un-apply remove all spells (not only at-apply, so any at-use active affects from item and etc) // except with at-use with negative charges, so allow consuming item spells (including with extra flag that prevent consume really) // applied to player after item remove from equip slot if (spellData.SpellTrigger == ITEM_SPELLTRIGGER_ON_USE && spellData.SpellCharges < 0) continue; } // check if it is valid spell SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId); if(!spellproto) continue; ApplyEquipSpell(spellproto,item,apply,form_change); } } void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change) { if (apply) { // Cannot be used in this stance/form if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) != SPELL_CAST_OK) return; if (form_change) // check aura active state from other form { bool found = false; for (int k=0; k < MAX_EFFECT_INDEX; ++k) { SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellInfo->Id); for (SpellAuraHolderMap::const_iterator iter = spair.first; iter != spair.second; ++iter) { if(!item || iter->second->GetCastItemGuid() == item->GetObjectGuid()) { found = true; break; } } if (found) break; } if (found) // and skip re-cast already active aura at form change return; } DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id); CastSpell(this,spellInfo,true,item); } else { if (form_change) // check aura compatibility { // Cannot be used in this stance/form if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) == SPELL_CAST_OK) return; // and remove only not compatible at form change } if (item) RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped else RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case) } } void Player::UpdateEquipSpellsAtFormChange() { for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i] && !m_items[i]->IsBroken()) { ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active } } // item set bonuses not dependent from item broken state for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex) { ItemSetEffect* eff = ItemSetEff[setindex]; if(!eff) continue; for(uint32 y=0;y<8; ++y) { SpellEntry const* spellInfo = eff->spells[y]; if(!spellInfo) continue; ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active } } } /** * (un-)Apply item spells triggered at adding item to inventory ITEM_SPELLTRIGGER_ON_STORE * * @param item added/removed item to/from inventory * @param apply (un-)apply spell affects. * * Note: item moved from slot to slot in 2 steps RemoveItem and StoreItem/EquipItem * In result function not called in RemoveItem for prevent unexpected re-apply auras from related spells * with duration reset and etc. Instead unapply done in StoreItem/EquipItem and in specialized * functions for item final remove/destroy from inventory. If new RemoveItem calls added need be sure that * function will call after it in some way if need. */ void Player::ApplyItemOnStoreSpell(Item *item, bool apply) { if (!item) return; ItemPrototype const *proto = item->GetProto(); if (!proto) return; for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = proto->Spells[i]; // no spell if (!spellData.SpellId) continue; // apply/unapply only at-store spells if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE) continue; if (apply) { // can be attempt re-applied at move in inventory slots if (!HasAura(spellData.SpellId)) CastSpell(this, spellData.SpellId, true, item); } else RemoveAurasDueToItemSpell(item, spellData.SpellId); } } void Player::DestroyItemWithOnStoreSpell(Item* item, uint32 spellId) { if (!item) return; ItemPrototype const *proto = item->GetProto(); if (!proto) return; for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = proto->Spells[i]; if (spellData.SpellId != spellId) continue; // apply/unapply only at-store spells if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE) continue; DestroyItem(item->GetBagSlot(), item->GetSlot(), true); break; } } /// handles unique effect of Deadly Poison: apply poison of the other weapon when already at max. stack void Player::_HandleDeadlyPoison(Unit* Target, WeaponAttackType attType, SpellEntry const *spellInfo) { SpellAuraHolderPtr dPoison = SpellAuraHolderPtr(NULL); SpellAuraHolderConstBounds holders = Target->GetSpellAuraHolderBounds(spellInfo->Id); for (SpellAuraHolderMap::const_iterator iter = holders.first; iter != holders.second; ++iter) { if (iter->second->GetCaster() == this) { dPoison = iter->second; break; } } if (dPoison && dPoison->GetStackAmount() == spellInfo->StackAmount) { Item *otherWeapon = GetWeaponForAttack(attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK ); if (!otherWeapon) return; // all poison enchantments are temporary uint32 enchant_id = otherWeapon->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT); if (!enchant_id) return; SpellItemEnchantmentEntry const* pSecondEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pSecondEnchant) return; for (int s = 0; s < 3; ++s) { if (pSecondEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) continue; SpellEntry const* combatEntry = sSpellStore.LookupEntry(pSecondEnchant->spellid[s]); if (combatEntry && combatEntry->Dispel == DISPEL_POISON) CastSpell(Target, combatEntry, true, otherWeapon); } } } void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType) { Item *item = GetWeaponForAttack(attType, true, false); if(!item) return; ItemPrototype const *proto = item->GetProto(); if(!proto) return; if (!Target || Target == this ) return; for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = proto->Spells[i]; // no spell if(!spellData.SpellId ) continue; // wrong triggering type if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId); if(!spellInfo) { sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId); continue; } // not allow proc extra attack spell at extra attack if ( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) ) return; float chance = (float)spellInfo->procChance; if (spellData.SpellPPMRate) { uint32 WeaponSpeed = proto->Delay; chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate); } else if (chance > 100.0f) { chance = GetWeaponProcChance(); } if (roll_chance_f(chance)) CastSpell(Target, spellInfo->Id, true, item); } // item combat enchantments for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot) { uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot)); SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!pEnchant) continue; for (int s = 0; s < 3; ++s) { uint32 proc_spell_id = pEnchant->spellid[s]; if (pEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry(proc_spell_id); if (!spellInfo) { sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, proc_spell_id); continue; } // Use first rank to access spell item enchant procs float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id); float chance = ppmRate ? GetPPMProcChance(proto->Delay, ppmRate) : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance(); ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS, chance); ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS, chance); if (roll_chance_f(chance)) { if (IsPositiveSpell(spellInfo->Id)) CastSpell(this, spellInfo->Id, true, item); else { // Deadly Poison, unique effect needs to be handled before casting triggered spell if (spellInfo->IsFitToFamily<SPELLFAMILY_ROGUE, CF_ROGUE_DEADLY_POISON>()) _HandleDeadlyPoison(Target, attType, spellInfo); CastSpell(Target, spellInfo->Id, true, item); } } } } } void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex) { ItemPrototype const* proto = item->GetProto(); // special learning case if (proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET) { uint32 learn_spell_id = proto->Spells[0].SpellId; uint32 learning_spell_id = proto->Spells[1].SpellId; SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id); if (!spellInfo) { sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id); SendEquipError(EQUIP_ERR_NONE, item); return; } Spell *spell = new Spell(this, spellInfo, false); spell->m_CastItem = item; spell->m_cast_count = cast_count; //set count of casts spell->m_currentBasePoints[EFFECT_INDEX_0] = learning_spell_id; spell->prepare(&targets); return; } // use triggered flag only for items with many spell casts and for not first cast int count = 0; // item spells casted at use for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = proto->Spells[i]; // no spell if (!spellData.SpellId) continue; // wrong triggering type if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId); if (!spellInfo) { sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId); continue; } Spell *spell = new Spell(this, spellInfo, (count > 0)); spell->m_CastItem = item; spell->m_cast_count = cast_count; // set count of casts spell->m_glyphIndex = glyphIndex; // glyph index spell->prepare(&targets); ++count; } // Item enchantments spells casted at use for (int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot) { uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot)); SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) continue; for (int s = 0; s < 3; ++s) { if (pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]); if (!spellInfo) { sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]); continue; } Spell *spell = new Spell(this, spellInfo, (count > 0)); spell->m_CastItem = item; spell->m_cast_count = cast_count; // set count of casts spell->m_glyphIndex = glyphIndex; // glyph index spell->prepare(&targets); ++count; } } } void Player::_RemoveAllItemMods() { DEBUG_LOG("_RemoveAllItemMods start."); for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i]) { ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; // item set bonuses not dependent from item broken state if (proto->ItemSet) RemoveItemsSetItem(this,proto); if (m_items[i]->IsBroken()) continue; ApplyItemEquipSpell(m_items[i],false); ApplyEnchantment(m_items[i], false); } } for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i]) { if (m_items[i]->IsBroken()) continue; ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; uint32 attacktype = Player::GetAttackBySlot(i); if (attacktype < MAX_ATTACK) _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false); _ApplyItemBonuses(proto,i, false); if ( i == EQUIPMENT_SLOT_RANGED ) _ApplyAmmoBonuses(); } } DEBUG_LOG("_RemoveAllItemMods complete."); } void Player::_ApplyAllItemMods() { DEBUG_LOG("_ApplyAllItemMods start."); for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i]) { if (m_items[i]->IsBroken()) continue; ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; uint32 attacktype = Player::GetAttackBySlot(i); if (attacktype < MAX_ATTACK) _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true); _ApplyItemBonuses(proto,i, true); if ( i == EQUIPMENT_SLOT_RANGED ) _ApplyAmmoBonuses(); } } for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i]) { ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; // item set bonuses not dependent from item broken state if (proto->ItemSet) AddItemsSetItem(this,m_items[i]); if (m_items[i]->IsBroken()) continue; ApplyItemEquipSpell(m_items[i],true); ApplyEnchantment(m_items[i], true); } } DEBUG_LOG("_ApplyAllItemMods complete."); } void Player::_ApplyAllLevelScaleItemMods(bool apply) { for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i]) { if (m_items[i]->IsBroken()) continue; ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; _ApplyItemBonuses(proto,i, apply, true); } } } void Player::_ApplyAmmoBonuses() { // check ammo uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID); if(!ammo_id) return; float currentAmmoDPS; ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id ); if ( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto)) currentAmmoDPS = 0.0f; else currentAmmoDPS = ammo_proto->Damage[0].DamageMin; if (currentAmmoDPS == GetAmmoDPS()) return; m_ammoDPS = currentAmmoDPS; if (CanModifyStats()) UpdateDamagePhysical(RANGED_ATTACK); } bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const { if(!ammo_proto) return false; // check ranged weapon Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false ); if (!weapon) return false; ItemPrototype const* weapon_proto = weapon->GetProto(); if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON ) return false; // check ammo ws. weapon compatibility switch(weapon_proto->SubClass) { case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_CROSSBOW: if (ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW) return false; break; case ITEM_SUBCLASS_WEAPON_GUN: if (ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET) return false; break; default: return false; } return true; } /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable Called by remove insignia spell effect */ void Player::RemovedInsignia(Player* looterPlr) { if (!GetBattleGroundId()) return; // If not released spirit, do it ! if (m_deathTimer > 0) { m_deathTimer = 0; BuildPlayerRepop(); RepopAtGraveyard(); } Corpse *corpse = GetCorpse(); if (!corpse) return; // We have to convert player corpse to bones, not to be able to resurrect there // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid(), true); if (!bones) return; // Now we must make bones lootable, and send player loot bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE); // We store the level of our player in the gold field // We retrieve this information at Player::SendLoot() bones->loot.gold = getLevel(); bones->lootRecipient = looterPlr; looterPlr->SendLoot(bones->GetObjectGuid(), LOOT_INSIGNIA); } void Player::SendLootRelease(ObjectGuid guid) { WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) ); data << guid; data << uint8(1); SendDirectMessage( &data ); } void Player::SendLoot(ObjectGuid guid, LootType loot_type) { if (ObjectGuid lootGuid = GetLootGuid()) m_session->DoLootRelease(lootGuid); Loot* loot = NULL; PermissionTypes permission = ALL_PERMISSION; DEBUG_LOG("Player::SendLoot"); switch(guid.GetHigh()) { case HIGHGUID_GAMEOBJECT: { DEBUG_LOG(" IS_GAMEOBJECT_GUID(guid)"); GameObject *go = GetMap()->GetGameObject(guid); // not check distance for GO in case owned GO (fishing bobber case, for example) // And permit out of range GO with no owner in case fishing hole if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING && loot_type != LOOT_FISHING_FAIL || go->GetOwnerGuid() != GetObjectGuid()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE))) { SendLootRelease(guid); return; } loot = &go->loot; Player* recipient = go->GetLootRecipient(); if (!recipient) { go->SetLootRecipient(this); recipient = this; } // generate loot only if ready for open and spawned in world if (go->getLootState() == GO_READY && go->isSpawned()) { uint32 lootid = go->GetGOInfo()->GetLootId(); if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S)) if (BattleGround *bg = GetBattleGround()) if (bg->GetTypeID(true) == BATTLEGROUND_AV) if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam()))) { SendLootRelease(guid); return; } if (Group* group = this->GetGroup()) { if (go->GetGoType() == GAMEOBJECT_TYPE_CHEST) { if (go->GetGOInfo()->chest.groupLootRules == 1 || sWorld.getConfig(CONFIG_BOOL_LOOT_CHESTS_IGNORE_DB)) { group->UpdateLooterGuid(go,true); switch (group->GetLootMethod()) { case GROUP_LOOT: // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin group->GroupLoot(go, loot); permission = GROUP_PERMISSION; break; case NEED_BEFORE_GREED: group->NeedBeforeGreed(go, loot); permission = GROUP_PERMISSION; break; case MASTER_LOOT: group->MasterLoot(go, loot); permission = MASTER_PERMISSION; break; default: break; } } else permission = GROUP_PERMISSION; } } // Entry 0 in fishing loot template used for store junk fish loot at fishing fail it junk allowed by config option // this is overwrite fishinghole loot for example if (loot_type == LOOT_FISHING_FAIL) loot->FillLoot(0, LootTemplates_Fishing, this, true); else if (lootid) { DEBUG_LOG(" if (lootid)"); loot->clear(); loot->FillLoot(lootid, LootTemplates_Gameobject, this, false); loot->generateMoneyLoot(go->GetGOInfo()->MinMoneyLoot, go->GetGOInfo()->MaxMoneyLoot); if (go->GetGoType() == GAMEOBJECT_TYPE_CHEST && go->GetGOInfo()->chest.groupLootRules) { if (Group* group = go->GetGroupLootRecipient()) { group->UpdateLooterGuid(go, true); switch (group->GetLootMethod()) { case GROUP_LOOT: // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin group->GroupLoot(go, loot); permission = GROUP_PERMISSION; break; case NEED_BEFORE_GREED: group->NeedBeforeGreed(go, loot); permission = GROUP_PERMISSION; break; case MASTER_LOOT: group->MasterLoot(go, loot); permission = MASTER_PERMISSION; break; default: break; } } } } else if (loot_type == LOOT_FISHING) go->getFishLoot(loot,this); go->SetLootState(GO_ACTIVATED); } if (go->getLootState() == GO_ACTIVATED && go->GetGoType() == GAMEOBJECT_TYPE_CHEST && (go->GetGOInfo()->chest.groupLootRules || sWorld.getConfig(CONFIG_BOOL_LOOT_CHESTS_IGNORE_DB))) { if (Group* group = go->GetGroupLootRecipient()) { if (group == GetGroup()) { if (group->GetLootMethod() == FREE_FOR_ALL) permission = ALL_PERMISSION; else if (group->GetLooterGuid() == GetObjectGuid()) { if (group->GetLootMethod() == MASTER_LOOT) permission = MASTER_PERMISSION; else permission = ALL_PERMISSION; } else permission = GROUP_PERMISSION; } else permission = NONE_PERMISSION; } else if (recipient == this) permission = ALL_PERMISSION; else permission = NONE_PERMISSION; } break; } case HIGHGUID_ITEM: { Item *item = GetItemByGuid( guid ); if (!item) { SendLootRelease(guid); return; } permission = OWNER_PERMISSION; loot = &item->loot; if (!item->HasGeneratedLoot()) { item->loot.clear(); switch(loot_type) { case LOOT_DISENCHANTING: loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this, true); item->SetLootState(ITEM_LOOT_TEMPORARY); break; case LOOT_PROSPECTING: loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this, true); item->SetLootState(ITEM_LOOT_TEMPORARY); break; case LOOT_MILLING: loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this, true); item->SetLootState(ITEM_LOOT_TEMPORARY); break; default: loot->FillLoot(item->GetEntry(), LootTemplates_Item, this, true, item->GetProto()->MaxMoneyLoot == 0); loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot, item->GetProto()->MaxMoneyLoot); item->SetLootState(ITEM_LOOT_CHANGED); break; } } break; } case HIGHGUID_CORPSE: // remove insignia { Corpse *bones = GetMap()->GetCorpse(guid); if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) ) { SendLootRelease(guid); return; } loot = &bones->loot; if (!bones->lootForBody) { bones->lootForBody = true; uint32 pLevel = bones->loot.gold; bones->loot.clear(); if (GetBattleGround() && GetBattleGround()->GetTypeID(true) == BATTLEGROUND_AV) loot->FillLoot(0, LootTemplates_Creature, this, false); // It may need a better formula // Now it works like this: lvl10: ~6copper, lvl70: ~9silver bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY) ); } if (bones->lootRecipient != this) permission = NONE_PERMISSION; else permission = OWNER_PERMISSION; break; } case HIGHGUID_UNIT: case HIGHGUID_VEHICLE: { Creature *creature = GetMap()->GetCreature(guid); // must be in range and creature must be alive for pickpocket and must be dead for another loot if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE)) { SendLootRelease(guid); return; } if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature)) { SendLootRelease(guid); return; } loot = &creature->loot; if (loot_type == LOOT_PICKPOCKETING) { if (!creature->lootForPickPocketed) { creature->lootForPickPocketed = true; loot->clear(); if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId) loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false); // Generate extra money for pick pocket loot const uint32 a = urand(0, creature->getLevel()/2); const uint32 b = urand(0, getLevel()/2); loot->gold = uint32(10 * (a + b) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)); permission = OWNER_PERMISSION; } } else { // the player whose group may loot the corpse Player *recipient = creature->GetLootRecipient(); if (!recipient) { creature->SetLootRecipient(this); recipient = this; } if (creature->lootForPickPocketed) { creature->lootForPickPocketed = false; loot->clear(); } if (!creature->lootForBody) { creature->lootForBody = true; loot->clear(); if (uint32 lootid = creature->GetCreatureInfo()->lootid) loot->FillLoot(lootid, LootTemplates_Creature, recipient, false); loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold); if (Group* group = creature->GetGroupLootRecipient()) { group->UpdateLooterGuid(creature,true); switch (group->GetLootMethod()) { case GROUP_LOOT: // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin group->GroupLoot(creature, loot); break; case NEED_BEFORE_GREED: group->NeedBeforeGreed(creature, loot); break; case MASTER_LOOT: group->MasterLoot(creature, loot); break; default: break; } } } // possible only if creature->lootForBody && loot->empty() at spell cast check if (loot_type == LOOT_SKINNING) { if (!creature->lootForSkin) { creature->lootForSkin = true; loot->clear(); loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false); // let reopen skinning loot if will closed. if (!loot->empty()) creature->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); permission = OWNER_PERMISSION; } } // set group rights only for loot_type != LOOT_SKINNING else { if (Group* group = creature->GetGroupLootRecipient()) { if (group == GetGroup()) { if (group->GetLootMethod() == FREE_FOR_ALL) permission = ALL_PERMISSION; else if (group->GetLooterGuid() == GetObjectGuid()) { if (group->GetLootMethod() == MASTER_LOOT) permission = MASTER_PERMISSION; else permission = ALL_PERMISSION; } else permission = GROUP_PERMISSION; } else permission = NONE_PERMISSION; } else if (recipient == this) permission = OWNER_PERMISSION; else permission = NONE_PERMISSION; } } break; } default: { sLog.outError("%s is unsupported for looting.", guid.GetString().c_str()); return; } } SetLootGuid(guid); // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client switch(loot_type) { case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break; case LOOT_FISHING_FAIL: loot_type = LOOT_FISHING; break; case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break; default: break; } // need know merged fishing/corpse loot type for achievements loot->loot_type = loot_type; WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size data << ObjectGuid(guid); data << uint8(loot_type); data << LootView(*loot, this, permission); SendDirectMessage(&data); // add 'this' player as one of the players that are looting 'loot' if (permission != NONE_PERMISSION) loot->AddLooter(GetObjectGuid()); if (loot_type == LOOT_CORPSE && !guid.IsItem()) SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING); } void Player::SendNotifyLootMoneyRemoved() { WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0); GetSession()->SendPacket( &data ); } void Player::SendNotifyLootItemRemoved(uint8 lootSlot) { WorldPacket data(SMSG_LOOT_REMOVED, 1); data << uint8(lootSlot); GetSession()->SendPacket( &data ); } void Player::SendUpdateWorldState(uint32 Field, uint32 Value) { WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8); data << Field; data << Value; // Tempfix before WorldStateMgr implementing if (IsInWorld() && GetSession()) GetSession()->SendPacket(&data); } static WorldStatePair AV_world_states[] = { { 0x7ae, 0x1 }, // 1966 7 snowfall n { 0x532, 0x1 }, // 1330 8 frostwolfhut hc { 0x531, 0x0 }, // 1329 9 frostwolfhut ac { 0x52e, 0x0 }, // 1326 10 stormpike firstaid a_a { 0x571, 0x0 }, // 1393 11 east frostwolf tower horde assaulted -unused { 0x570, 0x0 }, // 1392 12 west frostwolf tower horde assaulted - unused { 0x567, 0x1 }, // 1383 13 frostwolfe c { 0x566, 0x1 }, // 1382 14 frostwolfw c { 0x550, 0x1 }, // 1360 15 irondeep (N) ally { 0x544, 0x0 }, // 1348 16 ice grave a_a { 0x536, 0x0 }, // 1334 17 stormpike grave h_c { 0x535, 0x1 }, // 1333 18 stormpike grave a_c { 0x518, 0x0 }, // 1304 19 stoneheart grave a_a { 0x517, 0x0 }, // 1303 20 stoneheart grave h_a { 0x574, 0x0 }, // 1396 21 unk { 0x573, 0x0 }, // 1395 22 iceblood tower horde assaulted -unused { 0x572, 0x0 }, // 1394 23 towerpoint horde assaulted - unused { 0x56f, 0x0 }, // 1391 24 unk { 0x56e, 0x0 }, // 1390 25 iceblood a { 0x56d, 0x0 }, // 1389 26 towerp a { 0x56c, 0x0 }, // 1388 27 frostwolfe a { 0x56b, 0x0 }, // 1387 28 froswolfw a { 0x56a, 0x1 }, // 1386 29 unk { 0x569, 0x1 }, // 1385 30 iceblood c { 0x568, 0x1 }, // 1384 31 towerp c { 0x565, 0x0 }, // 1381 32 stoneh tower a { 0x564, 0x0 }, // 1380 33 icewing tower a { 0x563, 0x0 }, // 1379 34 dunn a { 0x562, 0x0 }, // 1378 35 duns a { 0x561, 0x0 }, // 1377 36 stoneheart bunker alliance assaulted - unused { 0x560, 0x0 }, // 1376 37 icewing bunker alliance assaulted - unused { 0x55f, 0x0 }, // 1375 38 dunbaldar south alliance assaulted - unused { 0x55e, 0x0 }, // 1374 39 dunbaldar north alliance assaulted - unused { 0x55d, 0x0 }, // 1373 40 stone tower d { 0x3c6, 0x0 }, // 966 41 unk { 0x3c4, 0x0 }, // 964 42 unk { 0x3c2, 0x0 }, // 962 43 unk { 0x516, 0x1 }, // 1302 44 stoneheart grave a_c { 0x515, 0x0 }, // 1301 45 stonheart grave h_c { 0x3b6, 0x0 }, // 950 46 unk { 0x55c, 0x0 }, // 1372 47 icewing tower d { 0x55b, 0x0 }, // 1371 48 dunn d { 0x55a, 0x0 }, // 1370 49 duns d { 0x559, 0x0 }, // 1369 50 unk { 0x558, 0x0 }, // 1368 51 iceblood d { 0x557, 0x0 }, // 1367 52 towerp d { 0x556, 0x0 }, // 1366 53 frostwolfe d { 0x555, 0x0 }, // 1365 54 frostwolfw d { 0x554, 0x1 }, // 1364 55 stoneh tower c { 0x553, 0x1 }, // 1363 56 icewing tower c { 0x552, 0x1 }, // 1362 57 dunn c { 0x551, 0x1 }, // 1361 58 duns c { 0x54f, 0x0 }, // 1359 59 irondeep (N) horde { 0x54e, 0x0 }, // 1358 60 irondeep (N) ally { 0x54d, 0x1 }, // 1357 61 mine (S) neutral { 0x54c, 0x0 }, // 1356 62 mine (S) horde { 0x54b, 0x0 }, // 1355 63 mine (S) ally { 0x545, 0x0 }, // 1349 64 iceblood h_a { 0x543, 0x1 }, // 1347 65 iceblod h_c { 0x542, 0x0 }, // 1346 66 iceblood a_c { 0x540, 0x0 }, // 1344 67 snowfall h_a { 0x53f, 0x0 }, // 1343 68 snowfall a_a { 0x53e, 0x0 }, // 1342 69 snowfall h_c { 0x53d, 0x0 }, // 1341 70 snowfall a_c { 0x53c, 0x0 }, // 1340 71 frostwolf g h_a { 0x53b, 0x0 }, // 1339 72 frostwolf g a_a { 0x53a, 0x1 }, // 1338 73 frostwolf g h_c { 0x539, 0x0 }, // l33t 74 frostwolf g a_c { 0x538, 0x0 }, // 1336 75 stormpike grave h_a { 0x537, 0x0 }, // 1335 76 stormpike grave a_a { 0x534, 0x0 }, // 1332 77 frostwolf hut h_a { 0x533, 0x0 }, // 1331 78 frostwolf hut a_a { 0x530, 0x0 }, // 1328 79 stormpike first aid h_a { 0x52f, 0x0 }, // 1327 80 stormpike first aid h_c { 0x52d, 0x1 }, // 1325 81 stormpike first aid a_c { 0x0, 0x0 } }; static WorldStatePair WS_world_states[] = { { 0x62d, 0x0 }, // 1581 7 alliance flag captures { 0x62e, 0x0 }, // 1582 8 horde flag captures { 0x609, 0x0 }, // 1545 9 unk, set to 1 on alliance flag pickup... { 0x60a, 0x0 }, // 1546 10 unk, set to 1 on horde flag pickup, after drop it's -1 { 0x60b, 0x2 }, // 1547 11 unk { 0x641, 0x3 }, // 1601 12 unk (max flag captures?) { 0x922, 0x1 }, // 2338 13 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing) { 0x923, 0x1 }, // 2339 14 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing) { 0x1097,0x1 }, // 4247 15 show time limit? { 0x1098,0x19 }, // 4248 16 time remaining in minutes { 0x0, 0x0 } }; static WorldStatePair AB_world_states[] = { { 0x6e7, 0x0 }, // 1767 7 stables alliance { 0x6e8, 0x0 }, // 1768 8 stables horde { 0x6e9, 0x0 }, // 1769 9 unk, ST? { 0x6ea, 0x0 }, // 1770 10 stables (show/hide) { 0x6ec, 0x0 }, // 1772 11 farm (0 - horde controlled, 1 - alliance controlled) { 0x6ed, 0x0 }, // 1773 12 farm (show/hide) { 0x6ee, 0x0 }, // 1774 13 farm color { 0x6ef, 0x0 }, // 1775 14 gold mine color, may be FM? { 0x6f0, 0x0 }, // 1776 15 alliance resources { 0x6f1, 0x0 }, // 1777 16 horde resources { 0x6f2, 0x0 }, // 1778 17 horde bases { 0x6f3, 0x0 }, // 1779 18 alliance bases { 0x6f4, 0x7d0 }, // 1780 19 max resources (2000) { 0x6f6, 0x0 }, // 1782 20 blacksmith color { 0x6f7, 0x0 }, // 1783 21 blacksmith (show/hide) { 0x6f8, 0x0 }, // 1784 22 unk, bs? { 0x6f9, 0x0 }, // 1785 23 unk, bs? { 0x6fb, 0x0 }, // 1787 24 gold mine (0 - horde contr, 1 - alliance contr) { 0x6fc, 0x0 }, // 1788 25 gold mine (0 - conflict, 1 - horde) { 0x6fd, 0x0 }, // 1789 26 gold mine (1 - show/0 - hide) { 0x6fe, 0x0 }, // 1790 27 gold mine color { 0x700, 0x0 }, // 1792 28 gold mine color, wtf?, may be LM? { 0x701, 0x0 }, // 1793 29 lumber mill color (0 - conflict, 1 - horde contr) { 0x702, 0x0 }, // 1794 30 lumber mill (show/hide) { 0x703, 0x0 }, // 1795 31 lumber mill color color { 0x732, 0x1 }, // 1842 32 stables (1 - uncontrolled) { 0x733, 0x1 }, // 1843 33 gold mine (1 - uncontrolled) { 0x734, 0x1 }, // 1844 34 lumber mill (1 - uncontrolled) { 0x735, 0x1 }, // 1845 35 farm (1 - uncontrolled) { 0x736, 0x1 }, // 1846 36 blacksmith (1 - uncontrolled) { 0x745, 0x2 }, // 1861 37 unk { 0x7a3, 0x708 }, // 1955 38 warning limit (1800) { 0x0, 0x0 } }; static WorldStatePair EY_world_states[] = { { 0xac1, 0x0 }, // 2753 7 Horde Bases { 0xac0, 0x0 }, // 2752 8 Alliance Bases { 0xab6, 0x0 }, // 2742 9 Mage Tower - Horde conflict { 0xab5, 0x0 }, // 2741 10 Mage Tower - Alliance conflict { 0xab4, 0x0 }, // 2740 11 Fel Reaver - Horde conflict { 0xab3, 0x0 }, // 2739 12 Fel Reaver - Alliance conflict { 0xab2, 0x0 }, // 2738 13 Draenei - Alliance conflict { 0xab1, 0x0 }, // 2737 14 Draenei - Horde conflict { 0xab0, 0x0 }, // 2736 15 unk // 0 at start { 0xaaf, 0x0 }, // 2735 16 unk // 0 at start { 0xaad, 0x0 }, // 2733 17 Draenei - Horde control { 0xaac, 0x0 }, // 2732 18 Draenei - Alliance control { 0xaab, 0x1 }, // 2731 19 Draenei uncontrolled (1 - yes, 0 - no) { 0xaaa, 0x0 }, // 2730 20 Mage Tower - Alliance control { 0xaa9, 0x0 }, // 2729 21 Mage Tower - Horde control { 0xaa8, 0x1 }, // 2728 22 Mage Tower uncontrolled (1 - yes, 0 - no) { 0xaa7, 0x0 }, // 2727 23 Fel Reaver - Horde control { 0xaa6, 0x0 }, // 2726 24 Fel Reaver - Alliance control { 0xaa5, 0x1 }, // 2725 25 Fel Reaver uncontrolled (1 - yes, 0 - no) { 0xaa4, 0x0 }, // 2724 26 Boold Elf - Horde control { 0xaa3, 0x0 }, // 2723 27 Boold Elf - Alliance control { 0xaa2, 0x1 }, // 2722 28 Boold Elf uncontrolled (1 - yes, 0 - no) { 0xac5, 0x1 }, // 2757 29 Flag (1 - show, 0 - hide) - doesn't work exactly this way! { 0xad2, 0x1 }, // 2770 30 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag { 0xad1, 0x1 }, // 2769 31 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag { 0xabe, 0x0 }, // 2750 32 Horde resources { 0xabd, 0x0 }, // 2749 33 Alliance resources { 0xa05, 0x8e }, // 2565 34 unk, constant? { 0xaa0, 0x0 }, // 2720 35 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0) { 0xa9f, 0x0 }, // 2719 36 Capturing progress-bar (0 - left, 100 - right) { 0xa9e, 0x0 }, // 2718 37 Capturing progress-bar (1 - show, 0 - hide) { 0xc0d, 0x17b }, // 3085 38 unk // and some more ... unknown { 0x0, 0x0 } }; static WorldStatePair SI_world_states[] = // Silithus { { 2313, 0x0 }, // 1 ally silityst gathered { 2314, 0x0 }, // 2 horde silityst gathered { 2317, 0x0 } // 3 max silithyst }; static WorldStatePair EP_world_states[] = { { 0x97a, 0x0 }, // 10 2426 { 0x917, 0x0 }, // 11 2327 { 0x918, 0x0 }, // 12 2328 { 0x97b, 0x32 }, // 13 2427 { 0x97c, 0x32 }, // 14 2428 { 0x933, 0x1 }, // 15 2355 { 0x946, 0x0 }, // 16 2374 { 0x947, 0x0 }, // 17 2375 { 0x948, 0x0 }, // 18 2376 { 0x949, 0x0 }, // 19 2377 { 0x94a, 0x0 }, // 20 2378 { 0x94b, 0x0 }, // 21 2379 { 0x932, 0x0 }, // 22 2354 { 0x934, 0x0 }, // 23 2356 { 0x935, 0x0 }, // 24 2357 { 0x936, 0x0 }, // 25 2358 { 0x937, 0x0 }, // 26 2359 { 0x938, 0x0 }, // 27 2360 { 0x939, 0x1 }, // 28 2361 { 0x930, 0x1 }, // 29 2352 { 0x93a, 0x0 }, // 30 2362 { 0x93b, 0x0 }, // 31 2363 { 0x93c, 0x0 }, // 32 2364 { 0x93d, 0x0 }, // 33 2365 { 0x944, 0x0 }, // 34 2372 { 0x945, 0x0 }, // 35 2373 { 0x931, 0x1 }, // 36 2353 { 0x93e, 0x0 }, // 37 2366 { 0x931, 0x1 }, // 38 2367 ?? grey horde not in dbc! send for consistency's sake, and to match field count { 0x940, 0x0 }, // 39 2368 { 0x941, 0x0 }, // 7 2369 { 0x942, 0x0 }, // 8 2370 { 0x943, 0x0 } // 9 2371 }; static WorldStatePair HP_world_states[] = // Hellfire Peninsula { { 0x9ba, 0x1 }, // 2490 10 { 0x9b9, 0x1 }, // 2489 11 { 0x9b5, 0x0 }, // 2485 12 { 0x9b4, 0x1 }, // 2484 13 { 0x9b3, 0x0 }, // 2483 14 { 0x9b2, 0x0 }, // 2482 15 { 0x9b1, 0x1 }, // 2481 16 { 0x9b0, 0x0 }, // 2480 17 { 0x9ae, 0x0 }, // 2478 18 horde pvp objectives captured { 0x9ac, 0x0 }, // 2476 19 { 0x9a8, 0x0 }, // 2472 20 { 0x9a7, 0x0 }, // 2471 21 { 0x9a6, 0x1 }, // 2470 22 { 0x0, 0x0 } }; static WorldStatePair TF_world_states[] = // Terokkar Forest { { 0xa41, 0x0 }, // 2625 10 { 0xa40, 0x14 }, // 2624 11 { 0xa3f, 0x0 }, // 2623 12 { 0xa3e, 0x0 }, // 2622 13 { 0xa3d, 0x5 }, // 2621 14 { 0xa3c, 0x0 }, // 2620 15 { 0xa87, 0x0 }, // 2695 16 { 0xa86, 0x0 }, // 2694 17 { 0xa85, 0x0 }, // 2693 18 { 0xa84, 0x0 }, // 2692 19 { 0xa83, 0x0 }, // 2691 20 { 0xa82, 0x0 }, // 2690 21 { 0xa81, 0x0 }, // 2689 22 { 0xa80, 0x0 }, // 2688 23 { 0xa7e, 0x0 }, // 2686 24 { 0xa7d, 0x0 }, // 2685 25 { 0xa7c, 0x0 }, // 2684 26 { 0xa7b, 0x0 }, // 2683 27 { 0xa7a, 0x0 }, // 2682 28 { 0xa79, 0x0 }, // 2681 29 { 0x9d0, 0x5 }, // 2512 30 { 0x9ce, 0x0 }, // 2510 31 { 0x9cd, 0x0 }, // 2509 32 { 0x9cc, 0x0 }, // 2508 33 { 0xa88, 0x0 }, // 2696 34 { 0xad0, 0x0 }, // 2768 35 { 0xacf, 0x1 }, // 2767 36 { 0x0, 0x0 } }; static WorldStatePair ZM_world_states[] = // Zangarmarsh { { 0x9e1, 0x0 }, // 2529 10 { 0x9e0, 0x0 }, // 2528 11 { 0x9df, 0x0 }, // 2527 12 { 0xa5d, 0x1 }, // 2526 13 { 0xa5c, 0x0 }, // 2525 14 { 0xa5b, 0x1 }, // 2524 15 { 0xa5a, 0x0 }, // 2523 16 { 0xa59, 0x1 }, // 2649 17 { 0xa58, 0x0 }, // 2648 18 { 0xa57, 0x0 }, // 2647 19 { 0xa56, 0x0 }, // 2646 20 { 0xa55, 0x1 }, // 2645 21 { 0xa54, 0x0 }, // 2644 22 { 0x9e7, 0x0 }, // 2535 23 { 0x9e6, 0x0 }, // 2534 24 { 0x9e5, 0x0 }, // 2533 25 { 0xa00, 0x0 }, // 2560 26 { 0x9ff, 0x1 }, // 2559 27 { 0x9fe, 0x0 }, // 2558 28 { 0x9fd, 0x0 }, // 2557 29 { 0x9fc, 0x1 }, // 2556 30 { 0x9fb, 0x0 }, // 2555 31 { 0xa62, 0x0 }, // 2658 32 { 0xa61, 0x1 }, // 2657 33 { 0xa60, 0x1 }, // 2656 34 { 0xa5f, 0x0 }, // 2655 35 { 0x0, 0x0 } }; static WorldStatePair NA_world_states[] = { { 2503, 0x0 }, // 10 { 2502, 0x0 }, // 11 { 2493, 0x0 }, // 12 { 2491, 0x0 }, // 13 { 2495, 0x0 }, // 14 { 2494, 0x0 }, // 15 { 2497, 0x0 }, // 16 { 2762, 0x0 }, // 17 { 2662, 0x0 }, // 18 { 2663, 0x0 }, // 19 { 2664, 0x0 }, // 20 { 2760, 0x0 }, // 21 { 2670, 0x0 }, // 22 { 2668, 0x0 }, // 23 { 2669, 0x0 }, // 24 { 2761, 0x0 }, // 25 { 2667, 0x0 }, // 26 { 2665, 0x0 }, // 27 { 2666, 0x0 }, // 28 { 2763, 0x0 }, // 29 { 2659, 0x0 }, // 30 { 2660, 0x0 }, // 31 { 2661, 0x0 }, // 32 { 2671, 0x0 }, // 33 { 2676, 0x0 }, // 34 { 2677, 0x0 }, // 35 { 2672, 0x0 }, // 36 { 2673, 0x0 } // 37 }; void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) { // data depends on zoneid/mapid... BattleGround* bg = GetBattleGround(); uint32 mapid = GetMapId(); WorldPvP* outdoorBg = sWorldPvPMgr.GetWorldPvPToZoneId(zoneid); DEBUG_LOG("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid); uint32 count = 0; // count of world states in packet WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+8*8));// guess data << uint32(mapid); // mapid data << uint32(zoneid); // zone id data << uint32(areaid); // area id, new 2.1.0 size_t count_pos = data.wpos(); data << uint16(0); // count of uint64 blocks, placeholder // common fields FillInitialWorldState(data, count, 0x8d8, 0x0); // 2264 1 FillInitialWorldState(data, count, 0x8d7, 0x0); // 2263 2 FillInitialWorldState(data, count, 0x8d6, 0x0); // 2262 3 FillInitialWorldState(data, count, 0x8d5, 0x0); // 2261 4 FillInitialWorldState(data, count, 0x8d4, 0x0); // 2260 5 FillInitialWorldState(data, count, 0x8d3, 0x0); // 2259 6 // 3191 7 Current arena season FillInitialWorldState(data, count, 0xC77, sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID)); // 3901 8 Previous arena season FillInitialWorldState(data, count, 0xF3D, sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_PREVIOUS_ID)); FillInitialWorldState(data, count, 0xED9, 1); // 3801 9 0 - Battle for Wintergrasp in progress, 1 - otherwise // 4354 10 Time when next Battle for Wintergrasp starts FillInitialWorldState(data, count, 0x1102, uint32(time(NULL) + 9000)); if (mapid == 530) // Outland { FillInitialWorldState(data, count, 0x9bf, 0x0); // 2495 FillInitialWorldState(data, count, 0x9bd, 0xF); // 2493 FillInitialWorldState(data, count, 0x9bb, 0xF); // 2491 } switch(zoneid) { case 1: case 11: case 12: case 38: case 40: case 51: break; case 139: // Eastern plaguelands if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_EP) outdoorBg->FillInitialWorldStates(data, count); else FillInitialWorldState(data, count, EP_world_states); break; case 1377: // Silithus if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_SI) outdoorBg->FillInitialWorldStates(data, count); else FillInitialWorldState(data, count, SI_world_states); break; case 1519: case 1537: case 2257: break; case 2597: // AV if (bg && bg->GetTypeID(true) == BATTLEGROUND_AV) bg->FillInitialWorldStates(data, count); else FillInitialWorldState(data,count, AV_world_states); break; case 3277: // WS if (bg && bg->GetTypeID(true) == BATTLEGROUND_WS) bg->FillInitialWorldStates(data, count); else FillInitialWorldState(data,count, WS_world_states); break; case 3358: // AB if (bg && bg->GetTypeID(true) == BATTLEGROUND_AB) bg->FillInitialWorldStates(data, count); else FillInitialWorldState(data,count, AB_world_states); break; case 3820: // EY if (bg && bg->GetTypeID(true) == BATTLEGROUND_EY) bg->FillInitialWorldStates(data, count); else FillInitialWorldState(data,count, EY_world_states); break; case 3483: // Hellfire Peninsula if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_HP) outdoorBg->FillInitialWorldStates(data,count); else FillInitialWorldState(data,count, HP_world_states); break; case 3518: // Nargrand - Halaa if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_NA) outdoorBg->FillInitialWorldStates(data, count); else FillInitialWorldState(data, count, NA_world_states); break; case 3519: // Terokkar Forest if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_TF) outdoorBg->FillInitialWorldStates(data,count); else FillInitialWorldState(data,count, TF_world_states); break; case 3521: // Zangarmarsh if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_ZM) outdoorBg->FillInitialWorldStates(data,count); else FillInitialWorldState(data,count, ZM_world_states); break; case 3698: // Nagrand Arena if (bg && bg->GetTypeID(true) == BATTLEGROUND_NA) bg->FillInitialWorldStates(data, count); else { FillInitialWorldState(data,count,0xa0f,0x0);// 2575 7 FillInitialWorldState(data,count,0xa10,0x0);// 2576 8 FillInitialWorldState(data,count,0xa11,0x0);// 2577 9 show } break; case 3702: // Blade's Edge Arena if (bg && bg->GetTypeID(true) == BATTLEGROUND_BE) bg->FillInitialWorldStates(data, count); else { FillInitialWorldState(data,count,0x9f0,0x0);// 2544 7 gold FillInitialWorldState(data,count,0x9f1,0x0);// 2545 8 green FillInitialWorldState(data,count,0x9f3,0x0);// 2547 9 show } break; case 3968: // Ruins of Lordaeron if (bg && bg->GetTypeID(true) == BATTLEGROUND_RL) bg->FillInitialWorldStates(data, count); else { FillInitialWorldState(data,count,0xbb8,0x0);// 3000 7 gold FillInitialWorldState(data,count,0xbb9,0x0);// 3001 8 green FillInitialWorldState(data,count,0xbba,0x0);// 3002 9 show } break; case 4378: // Dalaran Severs if (bg && bg->GetTypeID() == BATTLEGROUND_DS) bg->FillInitialWorldStates(data, count); else { FillInitialWorldState(data,count,0xe11,0x0);// 7 gold FillInitialWorldState(data,count,0xe10,0x0);// 8 green FillInitialWorldState(data,count,0xe1a,0x0);// 9 show } break; case 4406: // Ring of Valor if (bg && bg->GetTypeID() == BATTLEGROUND_RV) bg->FillInitialWorldStates(data, count); else { FillInitialWorldState(data,count,0xe11,0x0);// 7 gold FillInitialWorldState(data,count,0xe10,0x0);// 8 green FillInitialWorldState(data,count,0xe1a,0x0);// 9 show } break; case 3703: // Shattrath City break; case 4384: // SA if (bg && bg->GetTypeID(true) == BATTLEGROUND_SA) bg->FillInitialWorldStates(data, count); else { // 1-3 A defend, 4-6 H defend, 7-9 unk defend, 1 - ok, 2 - half destroyed, 3 - destroyed data << uint32(0xf09) << uint32(0x4); // 7 3849 Gate of Temple data << uint32(0xe36) << uint32(0x4); // 8 3638 Gate of Yellow Moon data << uint32(0xe27) << uint32(0x4); // 9 3623 Gate of Green Emerald data << uint32(0xe24) << uint32(0x4); // 10 3620 Gate of Blue Sapphire data << uint32(0xe21) << uint32(0x4); // 11 3617 Gate of Red Sun data << uint32(0xe1e) << uint32(0x4); // 12 3614 Gate of Purple Ametyst data << uint32(0xdf3) << uint32(0x0); // 13 3571 bonus timer (1 - on, 0 - off) data << uint32(0xded) << uint32(0x0); // 14 3565 Horde Attacker data << uint32(0xdec) << uint32(0x1); // 15 3564 Alliance Attacker // End Round (timer), better explain this by example, eg. ends in 19:59 -> A:BC data << uint32(0xde9) << uint32(0x9); // 16 3561 C data << uint32(0xde8) << uint32(0x5); // 17 3560 B data << uint32(0xde7) << uint32(0x19); // 18 3559 A data << uint32(0xe35) << uint32(0x1); // 19 3637 East g - Horde control data << uint32(0xe34) << uint32(0x1); // 20 3636 West g - Horde control data << uint32(0xe33) << uint32(0x1); // 21 3635 South g - Horde control data << uint32(0xe32) << uint32(0x0); // 22 3634 East g - Alliance control data << uint32(0xe31) << uint32(0x0); // 23 3633 West g - Alliance control data << uint32(0xe30) << uint32(0x0); // 24 3632 South g - Alliance control data << uint32(0xe2f) << uint32(0x1); // 25 3631 Chamber of Ancients - Horde control data << uint32(0xe2e) << uint32(0x0); // 26 3630 Chamber of Ancients - Alliance control data << uint32(0xe2d) << uint32(0x0); // 27 3629 Beach1 - Horde control data << uint32(0xe2c) << uint32(0x0); // 28 3628 Beach2 - Horde control data << uint32(0xe2b) << uint32(0x1); // 29 3627 Beach1 - Alliance control data << uint32(0xe2a) << uint32(0x1); // 30 3626 Beach2 - Alliance control // and many unks... } break; case 4710: if (bg && bg->GetTypeID(true) == BATTLEGROUND_IC) bg->FillInitialWorldStates(data, count); else { data << uint32(4221) << uint32(1); // 7 data << uint32(4222) << uint32(1); // 8 data << uint32(4226) << uint32(300); // 9 data << uint32(4227) << uint32(300); // 10 data << uint32(4322) << uint32(1); // 11 data << uint32(4321) << uint32(1); // 12 data << uint32(4320) << uint32(1); // 13 data << uint32(4323) << uint32(1); // 14 data << uint32(4324) << uint32(1); // 15 data << uint32(4325) << uint32(1); // 16 data << uint32(4317) << uint32(1); // 17 data << uint32(4301) << uint32(1); // 18 data << uint32(4296) << uint32(1); // 19 data << uint32(4306) << uint32(1); // 20 data << uint32(4311) << uint32(1); // 21 data << uint32(4294) << uint32(1); // 22 data << uint32(4243) << uint32(1); // 23 data << uint32(4345) << uint32(1); // 24 } break; default: FillInitialWorldState(data,count, 0x914, 0x0); // 2324 7 FillInitialWorldState(data,count, 0x913, 0x0); // 2323 8 FillInitialWorldState(data,count, 0x912, 0x0); // 2322 9 FillInitialWorldState(data,count, 0x915, 0x0); // 2325 10 break; } FillBGWeekendWorldStates(data,count); data.put<uint16>(count_pos,count); // set actual world state amount GetSession()->SendPacket(&data); } void Player::FillBGWeekendWorldStates(WorldPacket& data, uint32& count) { for(uint32 i = 1; i < sBattlemasterListStore.GetNumRows(); ++i) { BattlemasterListEntry const * bl = sBattlemasterListStore.LookupEntry(i); if (bl && bl->HolidayWorldStateId) { if (BattleGroundMgr::IsBGWeekend(BattleGroundTypeId(bl->id))) FillInitialWorldState(data, count, bl->HolidayWorldStateId, 1); else FillInitialWorldState(data, count, bl->HolidayWorldStateId, 0); } } } uint32 Player::GetXPRestBonus(uint32 xp) { uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus if (rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp rested_bonus = xp; SetRestBonus( GetRestBonus() - rested_bonus); DETAIL_LOG("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus()); return rested_bonus; } void Player::SetBindPoint(ObjectGuid guid) { WorldPacket data(SMSG_BINDER_CONFIRM, 8); data << ObjectGuid(guid); GetSession()->SendPacket( &data ); } void Player::SendTalentWipeConfirm(ObjectGuid guid) { WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4)); data << ObjectGuid(guid); data << uint32(resetTalentsCost()); GetSession()->SendPacket( &data ); } void Player::SendPetSkillWipeConfirm() { Pet* pet = GetPet(); if(!pet) return; if (pet->getPetType() != HUNTER_PET || pet->m_usedTalentCount == 0) return; CharmInfo* charmInfo = pet->GetCharmInfo(); if (!charmInfo) { sLog.outError("WorldSession::HandlePetUnlearnOpcode: %s is considered pet-like but doesn't have a charminfo!", pet->GetGuidStr().c_str()); return; } pet->resetTalents(); SendTalentsInfoData(true); } /*********************************************************/ /*** STORAGE SYSTEM ***/ /*********************************************************/ void Player::SetVirtualItemSlot( uint8 i, Item* item) { MANGOS_ASSERT(i < 3); if (i < 2 && item) { if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT)) return; uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT); if (charges == 0) return; if (charges > 1) item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1); else if (charges <= 1) { ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false); item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT); } } } void Player::SetSheath( SheathState sheathed ) { switch (sheathed) { case SHEATH_STATE_UNARMED: // no prepared weapon SetVirtualItemSlot(0,NULL); SetVirtualItemSlot(1,NULL); SetVirtualItemSlot(2,NULL); break; case SHEATH_STATE_MELEE: // prepared melee weapon { SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true)); SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true)); SetVirtualItemSlot(2,NULL); }; break; case SHEATH_STATE_RANGED: // prepared ranged weapon SetVirtualItemSlot(0,NULL); SetVirtualItemSlot(1,NULL); SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true)); break; default: SetVirtualItemSlot(0,NULL); SetVirtualItemSlot(1,NULL); SetVirtualItemSlot(2,NULL); break; } Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players... } uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const { uint8 pClass = getClass(); uint8 slots[4]; slots[0] = NULL_SLOT; slots[1] = NULL_SLOT; slots[2] = NULL_SLOT; slots[3] = NULL_SLOT; switch( proto->InventoryType ) { case INVTYPE_HEAD: slots[0] = EQUIPMENT_SLOT_HEAD; break; case INVTYPE_NECK: slots[0] = EQUIPMENT_SLOT_NECK; break; case INVTYPE_SHOULDERS: slots[0] = EQUIPMENT_SLOT_SHOULDERS; break; case INVTYPE_BODY: slots[0] = EQUIPMENT_SLOT_BODY; break; case INVTYPE_CHEST: slots[0] = EQUIPMENT_SLOT_CHEST; break; case INVTYPE_ROBE: slots[0] = EQUIPMENT_SLOT_CHEST; break; case INVTYPE_WAIST: slots[0] = EQUIPMENT_SLOT_WAIST; break; case INVTYPE_LEGS: slots[0] = EQUIPMENT_SLOT_LEGS; break; case INVTYPE_FEET: slots[0] = EQUIPMENT_SLOT_FEET; break; case INVTYPE_WRISTS: slots[0] = EQUIPMENT_SLOT_WRISTS; break; case INVTYPE_HANDS: slots[0] = EQUIPMENT_SLOT_HANDS; break; case INVTYPE_FINGER: slots[0] = EQUIPMENT_SLOT_FINGER1; slots[1] = EQUIPMENT_SLOT_FINGER2; break; case INVTYPE_TRINKET: slots[0] = EQUIPMENT_SLOT_TRINKET1; slots[1] = EQUIPMENT_SLOT_TRINKET2; break; case INVTYPE_CLOAK: slots[0] = EQUIPMENT_SLOT_BACK; break; case INVTYPE_WEAPON: { slots[0] = EQUIPMENT_SLOT_MAINHAND; // suggest offhand slot only if know dual wielding // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ... if (CanDualWield()) slots[1] = EQUIPMENT_SLOT_OFFHAND; break; }; case INVTYPE_SHIELD: slots[0] = EQUIPMENT_SLOT_OFFHAND; break; case INVTYPE_RANGED: slots[0] = EQUIPMENT_SLOT_RANGED; break; case INVTYPE_2HWEAPON: slots[0] = EQUIPMENT_SLOT_MAINHAND; if (CanDualWield() && CanTitanGrip()) slots[1] = EQUIPMENT_SLOT_OFFHAND; break; case INVTYPE_TABARD: slots[0] = EQUIPMENT_SLOT_TABARD; break; case INVTYPE_WEAPONMAINHAND: slots[0] = EQUIPMENT_SLOT_MAINHAND; break; case INVTYPE_WEAPONOFFHAND: slots[0] = EQUIPMENT_SLOT_OFFHAND; break; case INVTYPE_HOLDABLE: slots[0] = EQUIPMENT_SLOT_OFFHAND; break; case INVTYPE_THROWN: slots[0] = EQUIPMENT_SLOT_RANGED; break; case INVTYPE_RANGEDRIGHT: slots[0] = EQUIPMENT_SLOT_RANGED; break; case INVTYPE_BAG: slots[0] = INVENTORY_SLOT_BAG_START + 0; slots[1] = INVENTORY_SLOT_BAG_START + 1; slots[2] = INVENTORY_SLOT_BAG_START + 2; slots[3] = INVENTORY_SLOT_BAG_START + 3; break; case INVTYPE_RELIC: { switch(proto->SubClass) { case ITEM_SUBCLASS_ARMOR_LIBRAM: if (pClass == CLASS_PALADIN) slots[0] = EQUIPMENT_SLOT_RANGED; break; case ITEM_SUBCLASS_ARMOR_IDOL: if (pClass == CLASS_DRUID) slots[0] = EQUIPMENT_SLOT_RANGED; break; case ITEM_SUBCLASS_ARMOR_TOTEM: if (pClass == CLASS_SHAMAN) slots[0] = EQUIPMENT_SLOT_RANGED; break; case ITEM_SUBCLASS_ARMOR_MISC: if (pClass == CLASS_WARLOCK) slots[0] = EQUIPMENT_SLOT_RANGED; break; case ITEM_SUBCLASS_ARMOR_SIGIL: if (pClass == CLASS_DEATH_KNIGHT) slots[0] = EQUIPMENT_SLOT_RANGED; break; } break; } default : return NULL_SLOT; } if ( slot != NULL_SLOT ) { if ( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) ) { for (int i = 0; i < 4; ++i) { if ( slots[i] == slot ) return slot; } } } else { // search free slot at first for (int i = 0; i < 4; ++i) { if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) ) { // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free if (slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed()) return slots[i]; } } // if not found free and can swap return first appropriate from used for (int i = 0; i < 4; ++i) { if ( slots[i] != NULL_SLOT && swap ) return slots[i]; } } // no free position return NULL_SLOT; } InventoryResult Player::CanUnequipItems( uint32 item, uint32 count ) const { Item *pItem; uint32 tempcount = 0; InventoryResult res = EQUIP_ERR_OK; for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) { pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem->GetEntry() == item ) { InventoryResult ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false); if (ires == EQUIP_ERR_OK) { tempcount += pItem->GetCount(); if ( tempcount >= count ) return EQUIP_ERR_OK; } else res = ires; } } for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) { pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem->GetEntry() == item ) { tempcount += pItem->GetCount(); if ( tempcount >= count ) return EQUIP_ERR_OK; } } for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem->GetEntry() == item ) { tempcount += pItem->GetCount(); if ( tempcount >= count ) return EQUIP_ERR_OK; } } Bag *pBag; for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pBag ) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { pItem = GetItemByPos( i, j ); if ( pItem && pItem->GetEntry() == item ) { tempcount += pItem->GetCount(); if ( tempcount >= count ) return EQUIP_ERR_OK; } } } } // not found req. item count and have unequippable items return res; } uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const { uint32 count = 0; for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) { Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem != skipItem && pItem->GetEntry() == item ) count += pItem->GetCount(); } for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem != skipItem && pItem->GetEntry() == item ) count += pItem->GetCount(); } for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pBag ) count += pBag->GetItemCount(item,skipItem); } if (skipItem && skipItem->GetProto()->GemProperties) { for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) { Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color ) count += pItem->GetGemCountWithID(item); } } if (inBankAlso) { for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) { Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem != skipItem && pItem->GetEntry() == item ) count += pItem->GetCount(); } for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pBag ) count += pBag->GetItemCount(item,skipItem); } if (skipItem && skipItem->GetProto()->GemProperties) { for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) { Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color ) count += pItem->GetGemCountWithID(item); } } } return count; } uint32 Player::GetItemCountWithLimitCategory( uint32 limitCategory, Item* skipItem) const { uint32 count = 0; for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem) count += pItem->GetCount(); for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem) count += pItem->GetCount(); for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem); for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem) count += pItem->GetCount(); for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem); return count; } Item* Player::GetItemByEntry( uint32 item ) const { for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetEntry() == item) return pItem; for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetEntry() == item) return pItem; for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i)) if (Item* itemPtr = pBag->GetItemByEntry(item)) return itemPtr; return NULL; } Item* Player::GetItemByLimitedCategory(uint32 limitedCategory) const { for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetProto()->ItemLimitCategory == limitedCategory) return pItem; for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetProto()->ItemLimitCategory == limitedCategory) return pItem; for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i)) if (Item* itemPtr = pBag->GetItemByLimitedCategory(limitedCategory)) return itemPtr; return NULL; } Item* Player::GetItemByGuid(ObjectGuid guid) const { for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetObjectGuid() == guid) return pItem; for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetObjectGuid() == guid) return pItem; for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) for(uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->GetObjectGuid() == guid) return pItem; for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetObjectGuid() == guid) return pItem; for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) for(uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->GetObjectGuid() == guid) return pItem; return NULL; } Item* Player::GetItemByPos( uint16 pos ) const { uint8 bag = pos >> 8; uint8 slot = pos & 255; return GetItemByPos( bag, slot ); } Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const { if ( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) ) return m_items[slot]; else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END) || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) ) { Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ); if ( pBag ) return pBag->GetItemByPos(slot); } return NULL; } uint32 Player::GetItemDisplayIdInSlot(uint8 bag, uint8 slot) const { const Item* pItem = GetItemByPos(bag, slot); if (!pItem) return 0; return pItem->GetProto()->DisplayInfoID; } Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const { uint8 slot; switch (attackType) { case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break; case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break; case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break; default: return NULL; } Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON) return NULL; if (useable && !CanUseEquippedWeapon(attackType)) return NULL; if (nonbroken && item->IsBroken()) return NULL; return item; } Item* Player::GetShield(bool useable) const { Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR) return NULL; if (!useable) return item; if (item->IsBroken() || !CanUseEquippedWeapon(OFF_ATTACK)) return NULL; return item; } uint32 Player::GetAttackBySlot( uint8 slot ) { switch(slot) { case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK; case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK; case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK; default: return MAX_ATTACK; } } bool Player::IsInventoryPos( uint8 bag, uint8 slot ) { if ( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT ) return true; if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) ) return true; if ( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END ) return true; if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) ) return true; return false; } bool Player::IsEquipmentPos( uint8 bag, uint8 slot ) { if ( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) ) return true; if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) ) return true; return false; } bool Player::IsBankPos( uint8 bag, uint8 slot ) { if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) ) return true; if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) ) return true; if ( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END ) return true; return false; } bool Player::IsBagPos( uint16 pos ) { uint8 bag = pos >> 8; uint8 slot = pos & 255; if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) ) return true; if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) ) return true; return false; } bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos ) const { // post selected if (bag == NULL_BAG && !explicit_pos) return true; if (bag == INVENTORY_SLOT_BAG_0) { // any post selected if (slot == NULL_SLOT && !explicit_pos) return true; // equipment if (slot < EQUIPMENT_SLOT_END) return true; // bag equip slots if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END) return true; // backpack slots if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END) return true; // keyring slots if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END) return true; // bank main slots if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END) return true; // bank bag slots if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END) return true; return false; } // bag content slots if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END) { Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag); if(!pBag) return false; // any post selected if (slot == NULL_SLOT && !explicit_pos) return true; return slot < pBag->GetBagSize(); } // bank bag content slots if ( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END ) { Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag); if(!pBag) return false; // any post selected if (slot == NULL_SLOT && !explicit_pos) return true; return slot < pBag->GetBagSize(); } // where this? return false; } bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const { uint32 tempcount = 0; for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) { Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade()) { tempcount += pItem->GetCount(); if (tempcount >= count) return true; } } for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade()) { tempcount += pItem->GetCount(); if (tempcount >= count) return true; } } for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { Item* pItem = GetItemByPos( i, j ); if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade()) { tempcount += pItem->GetCount(); if (tempcount >= count) return true; } } } } if (inBankAlso) { for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) { Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade()) { tempcount += pItem->GetCount(); if (tempcount >= count) return true; } } for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { Item* pItem = GetItemByPos( i, j ); if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade()) { tempcount += pItem->GetCount(); if (tempcount >= count) return true; } } } } } return false; } bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const { uint32 tempcount = 0; for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i==int(except_slot)) continue; Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && pItem->GetEntry() == item) { tempcount += pItem->GetCount(); if ( tempcount >= count ) return true; } } ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item); if (pProto && pProto->GemProperties) { for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i==int(except_slot)) continue; Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem && (pItem->GetProto()->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT))) { tempcount += pItem->GetGemCountWithID(item); if ( tempcount >= count ) return true; } } } return false; } bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const { uint32 tempcount = 0; for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i==int(except_slot)) continue; Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (!pItem) continue; ItemPrototype const *pProto = pItem->GetProto(); if (!pProto) continue; if (pProto->ItemLimitCategory == limitCategory) { tempcount += pItem->GetCount(); if ( tempcount >= count ) return true; } if ( pProto->Socket[0].Color) { tempcount += pItem->GetGemCountWithLimitCategory(limitCategory); if ( tempcount >= count ) return true; } } return false; } InventoryResult Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count) const { ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry); if (!pProto) { if (no_space_count) *no_space_count = count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } // no maximum if (pProto->MaxCount > 0) { uint32 curcount = GetItemCount(pProto->ItemId, true, pItem); if (curcount + count > uint32(pProto->MaxCount)) { if (no_space_count) *no_space_count = count +curcount - pProto->MaxCount; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } // check unique-equipped limit if (pProto->ItemLimitCategory) { ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory); if (!limitEntry) { if (no_space_count) *no_space_count = count; return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; } if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE) { uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory, pItem); if (curcount + count > uint32(limitEntry->maxCount)) { if (no_space_count) *no_space_count = count + curcount - limitEntry->maxCount; return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS; } } } return EQUIP_ERR_OK; } bool Player::HasItemTotemCategory( uint32 TotemCategory ) const { Item *pItem; for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) { pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory )) return true; } for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory )) return true; } for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { pItem = GetItemByPos( i, j ); if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory )) return true; } } } return false; } InventoryResult Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const { Item* pItem2 = GetItemByPos( bag, slot ); // ignore move item (this slot will be empty at move) if (pItem2==pSrcItem) pItem2 = NULL; uint32 need_space; // empty specific slot - check item fit to slot if (!pItem2 || swap) { if (bag == INVENTORY_SLOT_BAG_0) { // keyring case if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; // currencytoken case if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; // prevent cheating if ((slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) || slot >= PLAYER_SLOT_END) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; } else { Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ); if (!pBag) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; ItemPrototype const* pBagProto = pBag->GetProto(); if (!pBagProto) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; if (slot >= pBagProto->ContainerSlots) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; if (!ItemCanGoIntoBag(pProto,pBagProto)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; } // non empty stack with space need_space = pProto->GetMaxStackSize(); } // non empty slot, check item type else { // can be merged at least partly InventoryResult res = pItem2->CanBeMergedPartlyWith(pProto); if (res != EQUIP_ERR_OK) return res; // free stack space or infinity need_space = pProto->GetMaxStackSize() - pItem2->GetCount(); } if (need_space > count) need_space = count; ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space); if (!newPosition.isContainedIn(dest)) { dest.push_back(newPosition); count -= need_space; } return EQUIP_ERR_OK; } InventoryResult Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const { // skip specific bag already processed in first called _CanStoreItem_InBag if (bag == skip_bag) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; // skip nonexistent bag or self targeted bag Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ); if (!pBag || pBag==pSrcItem) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; ItemPrototype const* pBagProto = pBag->GetProto(); if (!pBagProto) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; // specialized bag mode or non-specilized if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; if (!ItemCanGoIntoBag(pProto,pBagProto)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot if (j==skip_slot) continue; Item* pItem2 = GetItemByPos( bag, j ); // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) pItem2 = NULL; // if merge skip empty, if !merge skip non-empty if ((pItem2 != NULL) != merge) continue; uint32 need_space = pProto->GetMaxStackSize(); if (pItem2) { // can be merged at least partly uint8 res = pItem2->CanBeMergedPartlyWith(pProto); if (res != EQUIP_ERR_OK) continue; // descrease at current stacksize need_space -= pItem2->GetCount(); } if (need_space > count) need_space = count; ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space); if (!newPosition.isContainedIn(dest)) { dest.push_back(newPosition); count -= need_space; if (count==0) return EQUIP_ERR_OK; } } return EQUIP_ERR_OK; } InventoryResult Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const { for(uint32 j = slot_begin; j < slot_end; ++j) { // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot) continue; Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j ); // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) pItem2 = NULL; // if merge skip empty, if !merge skip non-empty if ((pItem2 != NULL) != merge) continue; uint32 need_space = pProto->GetMaxStackSize(); if (pItem2) { // can be merged at least partly uint8 res = pItem2->CanBeMergedPartlyWith(pProto); if (res != EQUIP_ERR_OK) continue; // descrease at current stacksize need_space -= pItem2->GetCount(); } if (need_space > count) need_space = count; ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space); if (!newPosition.isContainedIn(dest)) { dest.push_back(newPosition); count -= need_space; if (count==0) return EQUIP_ERR_OK; } } return EQUIP_ERR_OK; } InventoryResult Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const { DEBUG_LOG( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count); ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry); if (!pProto) { if (no_space_count) *no_space_count = count; return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND; } if (pItem) { // item used if (pItem->HasTemporaryLoot()) { if (no_space_count) *no_space_count = count; return EQUIP_ERR_ALREADY_LOOTED; } if (pItem->IsBindedNotWith(this)) { if (no_space_count) *no_space_count = count; return EQUIP_ERR_DONT_OWN_THAT_ITEM; } } // check count of items (skip for auto move for same player from bank) uint32 no_similar_count = 0; // can't store this amount similar items InventoryResult res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count); if (res != EQUIP_ERR_OK) { if (count == no_similar_count) { if (no_space_count) *no_space_count = no_similar_count; return res; } count -= no_similar_count; } // in specific slot if (bag != NULL_BAG && slot != NULL_SLOT) { res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } // not specific slot or have space for partly store only in specific slot // in specific bag if (bag != NULL_BAG) { // search stack in bag for merge to if (pProto->Stackable != 1) { if (bag == INVENTORY_SLOT_BAG_0) // inventory { res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } else // equipped bag { // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot); if (res != EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } // search free slot in bag for place to if (bag == INVENTORY_SLOT_BAG_0) // inventory { // search free slot - keyring case if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS) { uint32 keyringSize = GetMaxKeyringSize(); res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count==0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS) { res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } else // equipped bag { res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot); if (res != EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } // not specific bag or have space for partly store only in specific bag // search stack for merge to if (pProto->Stackable != 1) { res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } if (pProto->BagFamily) { for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot); if (res != EQUIP_ERR_OK) continue; if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot); if (res != EQUIP_ERR_OK) continue; if (count == 0) { if (no_similar_count==0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } // search free slot - special bag case if (pProto->BagFamily) { if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS) { uint32 keyringSize = GetMaxKeyringSize(); res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS) { res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot); if (res != EQUIP_ERR_OK) continue; if (count == 0) { if (no_similar_count==0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } // Normally it would be impossible to autostore not empty bags if (pItem && pItem->IsBag() && !((Bag*)pItem)->IsEmpty()) return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG; // search free slot res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if (res != EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } if (count == 0) { if (no_similar_count==0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot); if (res != EQUIP_ERR_OK) continue; if (count == 0) { if (no_similar_count == 0) return EQUIP_ERR_OK; if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_INVENTORY_FULL; } ////////////////////////////////////////////////////////////////////////// InventoryResult Player::CanStoreItems( Item **pItems,int count) const { Item *pItem2; // fill space table int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START]; int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE]; int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START]; int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START]; memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START)); memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE); memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START)); memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START)); for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem2 && !pItem2->IsInTrade()) { inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount(); } } for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem2 && !pItem2->IsInTrade()) { inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount(); } } for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem2 && !pItem2->IsInTrade()) { inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount(); } } for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { pItem2 = GetItemByPos( i, j ); if (pItem2 && !pItem2->IsInTrade()) { inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount(); } } } } // check free space for all items for (int k = 0; k < count; ++k) { Item *pItem = pItems[k]; // no item if (!pItem) continue; DEBUG_LOG( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount()); ItemPrototype const *pProto = pItem->GetProto(); // strange item if (!pProto) return EQUIP_ERR_ITEM_NOT_FOUND; // item used if (pItem->HasTemporaryLoot()) return EQUIP_ERR_ALREADY_LOOTED; // item it 'bind' if (pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; Bag *pBag; ItemPrototype const *pBagProto; // item is 'one item only' InventoryResult res = CanTakeMoreSimilarItems(pItem); if (res != EQUIP_ERR_OK) return res; // search stack for merge to if (pProto->Stackable != 1) { bool b_found = false; for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t ); if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) { inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount(); b_found = true; break; } } if (b_found) continue; for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t ); if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) { inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount(); b_found = true; break; } } if (b_found) continue; for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t ); if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) { inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount(); b_found = true; break; } } if (b_found) continue; for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) { pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t ); if (pBag) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { pItem2 = GetItemByPos( t, j ); if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize()) { inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount(); b_found = true; break; } } } } if (b_found) continue; } // special bag case if (pProto->BagFamily) { bool b_found = false; if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS) { uint32 keyringSize = GetMaxKeyringSize(); for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t) { if (inv_keys[t-KEYRING_SLOT_START] == 0) { inv_keys[t-KEYRING_SLOT_START] = 1; b_found = true; break; } } } if (b_found) continue; if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS) { for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t) { if (inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0) { inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1; b_found = true; break; } } } if (b_found) continue; for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) { pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t ); if (pBag) { pBagProto = pBag->GetProto(); // not plain container check if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) && ItemCanGoIntoBag(pProto,pBagProto) ) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0) { inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1; b_found = true; break; } } } } } if (b_found) continue; } // search free slot bool b_found = false; for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t) { if (inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0) { inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1; b_found = true; break; } } if (b_found) continue; // search free slot in bags for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) { pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t ); if (pBag) { pBagProto = pBag->GetProto(); // special bag already checked if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER)) continue; for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0) { inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1; b_found = true; break; } } } } // no free slot found? if (!b_found) return EQUIP_ERR_INVENTORY_FULL; } return EQUIP_ERR_OK; } ////////////////////////////////////////////////////////////////////////// InventoryResult Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const { dest = 0; Item *pItem = Item::CreateItem( item, 1, this ); if (pItem) { InventoryResult result = CanEquipItem(slot, dest, pItem, swap ); delete pItem; return result; } return EQUIP_ERR_ITEM_NOT_FOUND; } InventoryResult Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool direct_action ) const { dest = 0; if (pItem) { DEBUG_LOG( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount()); ItemPrototype const *pProto = pItem->GetProto(); if (pProto) { // item used if (pItem->HasTemporaryLoot()) return EQUIP_ERR_ALREADY_LOOTED; if (pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; // check count of items (skip for auto move for same player from bank) InventoryResult res = CanTakeMoreSimilarItems(pItem); if (res != EQUIP_ERR_OK) return res; // check this only in game if (direct_action) { // May be here should be more stronger checks; STUNNED checked // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked. if (hasUnitState(UNIT_STAT_STUNNED)) return EQUIP_ERR_YOU_ARE_STUNNED; // do not allow equipping gear except weapons, offhands, projectiles, relics in // - combat // - in-progress arenas if (!pProto->CanChangeEquipStateInCombat()) { if (isInCombat()) return EQUIP_ERR_NOT_IN_COMBAT; if (BattleGround* bg = GetBattleGround()) if (bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS) return EQUIP_ERR_NOT_DURING_ARENA_MATCH; } // prevent equip item in process logout if (GetSession()->isLogingOut()) return EQUIP_ERR_YOU_ARE_STUNNED; if (isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0) return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err if (IsNonMeleeSpellCasted(false)) return EQUIP_ERR_CANT_DO_RIGHT_NOW; } ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0; // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items) if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel()) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; uint8 eslot = FindEquipSlot( pProto, slot, swap ); if (eslot == NULL_SLOT) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; // jewelcrafting gem check if (InventoryResult res2 = CanEquipMoreJewelcraftingGems(pItem->GetJewelcraftingGemCount(), swap ? eslot : NULL_SLOT)) return res2; InventoryResult msg = CanUseItem(pItem , direct_action); if (msg != EQUIP_ERR_OK) return msg; if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot)) return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE; // if swap ignore item (equipped also) if (InventoryResult res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT)) return res2; // check unique-equipped special item classes if (pProto->Class == ITEM_CLASS_QUIVER) { for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) { if (pBag != pItem) { if (ItemPrototype const* pBagProto = pBag->GetProto()) { if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot)) return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH) ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER; } } } } } uint32 type = pProto->InventoryType; if (eslot == EQUIPMENT_SLOT_OFFHAND) { if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND) { if (!CanDualWield()) return EQUIP_ERR_CANT_DUAL_WIELD; } else if (type == INVTYPE_2HWEAPON) { if (!CanDualWield() || !CanTitanGrip()) return EQUIP_ERR_CANT_DUAL_WIELD; } if (IsTwoHandUsed()) return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED; } // equip two-hand weapon case (with possible unequip 2 items) if (type == INVTYPE_2HWEAPON) { if (eslot == EQUIPMENT_SLOT_OFFHAND) { if (!CanTitanGrip()) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; } else if (eslot != EQUIPMENT_SLOT_MAINHAND) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; if (!CanTitanGrip()) { // offhand item must can be stored in inventory for offhand item and it also must be unequipped Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND ); ItemPosCountVec off_dest; if (offItem && (!direct_action || CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK || CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK )) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL; } } dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot); return EQUIP_ERR_OK; } } return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED; } InventoryResult Player::CanUnequipItem( uint16 pos, bool swap ) const { // Applied only to equipped items and bank bags if (!IsEquipmentPos(pos) && !IsBagPos(pos)) return EQUIP_ERR_OK; Item* pItem = GetItemByPos(pos); // Applied only to existing equipped item if (!pItem) return EQUIP_ERR_OK; DEBUG_LOG( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount()); ItemPrototype const *pProto = pItem->GetProto(); if (!pProto) return EQUIP_ERR_ITEM_NOT_FOUND; // item used if (pItem->HasTemporaryLoot()) return EQUIP_ERR_ALREADY_LOOTED; // do not allow unequipping gear except weapons, offhands, projectiles, relics in // - combat // - in-progress arenas if ( !pProto->CanChangeEquipStateInCombat() ) { if ( isInCombat() ) return EQUIP_ERR_NOT_IN_COMBAT; if (BattleGround* bg = GetBattleGround()) if ( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS ) return EQUIP_ERR_NOT_DURING_ARENA_MATCH; } // prevent unequip item in process logout if (GetSession()->isLogingOut()) return EQUIP_ERR_YOU_ARE_STUNNED; if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty()) return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS; return EQUIP_ERR_OK; } InventoryResult Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const { if (!pItem) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; uint32 count = pItem->GetCount(); DEBUG_LOG( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount()); ItemPrototype const *pProto = pItem->GetProto(); if (!pProto) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; // item used if (pItem->HasTemporaryLoot()) return EQUIP_ERR_ALREADY_LOOTED; if (pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; // check count of items (skip for auto move for same player from bank) InventoryResult res = CanTakeMoreSimilarItems(pItem); if (res != EQUIP_ERR_OK) return res; // in specific slot if (bag != NULL_BAG && slot != NULL_SLOT) { if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END) { if (!pItem->IsBag()) return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT; if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount()) return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT; res = CanUseItem( pItem, not_loading ); if (res != EQUIP_ERR_OK) return res; } res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem); if (res!=EQUIP_ERR_OK) return res; if (count==0) return EQUIP_ERR_OK; } // not specific slot or have space for partly store only in specific slot // in specific bag if ( bag != NULL_BAG ) { if ( pProto->InventoryType == INVTYPE_BAG ) { Bag *pBag = (Bag*)pItem; if ( pBag && !pBag->IsEmpty() ) return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG; } // search stack in bag for merge to if ( pProto->Stackable != 1 ) { if ( bag == INVENTORY_SLOT_BAG_0 ) { res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if (res!=EQUIP_ERR_OK) return res; if (count==0) return EQUIP_ERR_OK; } else { res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot); if (res!=EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot); if (res!=EQUIP_ERR_OK) return res; if (count==0) return EQUIP_ERR_OK; } } // search free slot in bag if ( bag == INVENTORY_SLOT_BAG_0 ) { res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) return res; if (count==0) return EQUIP_ERR_OK; } else { res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot); if (res != EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot); if (res != EQUIP_ERR_OK) return res; if (count == 0) return EQUIP_ERR_OK; } } // not specific bag or have space for partly store only in specific bag // search stack for merge to if ( pProto->Stackable != 1 ) { // in slots res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if (res != EQUIP_ERR_OK) return res; if (count == 0) return EQUIP_ERR_OK; // in special bags if ( pProto->BagFamily ) { for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; if (count==0) return EQUIP_ERR_OK; } } for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; if (count==0) return EQUIP_ERR_OK; } } // search free place in special bag if ( pProto->BagFamily ) { for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; if (count==0) return EQUIP_ERR_OK; } } // search free space res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) return res; if (count==0) return EQUIP_ERR_OK; for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; if (count==0) return EQUIP_ERR_OK; } return EQUIP_ERR_BANK_FULL; } InventoryResult Player::CanUseItem(Item *pItem, bool direct_action) const { if (pItem) { DEBUG_LOG( "STORAGE: CanUseItem item = %u", pItem->GetEntry()); if (!isAlive() && direct_action) return EQUIP_ERR_YOU_ARE_DEAD; //if (isStunned()) // return EQUIP_ERR_YOU_ARE_STUNNED; ItemPrototype const *pProto = pItem->GetProto(); if (pProto) { if (pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; InventoryResult msg = CanUseItem(pProto); if (msg != EQUIP_ERR_OK) return msg; if (uint32 item_use_skill = pItem->GetSkill()) { if (GetSkillValue(item_use_skill) == 0) { // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level if (pProto->Class != ITEM_CLASS_ARMOR) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL; if (!ssd) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; bool allowScaleSkill = false; for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i) { SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i); if (!skillInfo) continue; if (skillInfo->skillId != item_use_skill) continue; // can't learn if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0) continue; if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0) continue; allowScaleSkill = true; break; } if (!allowScaleSkill) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; } } if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank) return EQUIP_ERR_CANT_EQUIP_REPUTATION; return EQUIP_ERR_OK; } } return EQUIP_ERR_ITEM_NOT_FOUND; } InventoryResult Player::CanUseItem( ItemPrototype const *pProto ) const { // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player if ( pProto ) { if(!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP)) { if ((pProto->Flags2 & ITEM_FLAG2_HORDE_ONLY) && GetTeam() != HORDE) return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM; if ((pProto->Flags2 & ITEM_FLAG2_ALLIANCE_ONLY) && GetTeam() != ALLIANCE) return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM; } if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0) return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM; if ( pProto->RequiredSkill != 0 ) { if ( GetSkillValue( pProto->RequiredSkill ) == 0 ) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; else if ( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank ) return EQUIP_ERR_CANT_EQUIP_SKILL; } if ( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) ) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; if ( getLevel() < pProto->RequiredLevel ) return EQUIP_ERR_CANT_EQUIP_LEVEL_I; return EQUIP_ERR_OK; } return EQUIP_ERR_ITEM_NOT_FOUND; } InventoryResult Player::CanUseAmmo( uint32 item ) const { DEBUG_LOG( "STORAGE: CanUseAmmo item = %u", item); if ( !isAlive() ) return EQUIP_ERR_YOU_ARE_DEAD; //if ( isStunned() ) // return EQUIP_ERR_YOU_ARE_STUNNED; ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item ); if ( pProto ) { if ( pProto->InventoryType!= INVTYPE_AMMO ) return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE; InventoryResult msg = CanUseItem(pProto); if (msg != EQUIP_ERR_OK) return msg; /*if ( GetReputationMgr().GetReputation() < pProto->RequiredReputation ) return EQUIP_ERR_CANT_EQUIP_REPUTATION; */ // Requires No Ammo if (GetDummyAura(46699)) return EQUIP_ERR_BAG_FULL6; return EQUIP_ERR_OK; } return EQUIP_ERR_ITEM_NOT_FOUND; } void Player::SetAmmo( uint32 item ) { if(!item) return; // already set if ( GetUInt32Value(PLAYER_AMMO_ID) == item ) return; // check ammo if (item) { InventoryResult msg = CanUseAmmo( item ); if (msg != EQUIP_ERR_OK) { SendEquipError(msg, NULL, NULL, item); return; } } SetUInt32Value(PLAYER_AMMO_ID, item); _ApplyAmmoBonuses(); } void Player::RemoveAmmo() { SetUInt32Value(PLAYER_AMMO_ID, 0); m_ammoDPS = 0.0f; if (CanModifyStats()) UpdateDamagePhysical(RANGED_ATTACK); } // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case. Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId , AllowedLooterSet* allowedLooters) { uint32 count = 0; for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr) count += itr->count; Item *pItem = Item::CreateItem(item, count, this, randomPropertyId); if (pItem) { ResetCachedGearScore(); ItemAddedQuestCheck( item, count ); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count); pItem = StoreItem( dest, pItem, update ); if (allowedLooters && pItem->GetProto()->GetMaxStackSize() == 1 && pItem->IsSoulBound()) { pItem->SetSoulboundTradeable(allowedLooters, this, true); pItem->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, GetTotalPlayedTime()); m_itemSoulboundTradeable.push_back(pItem); // save data std::ostringstream ss; ss << "REPLACE INTO `item_soulbound_trade_data` VALUES ("; ss << pItem->GetGUIDLow(); ss << ", '"; for (AllowedLooterSet::iterator itr = allowedLooters->begin(); itr != allowedLooters->end(); ++itr) ss << *itr << " "; ss << "');"; CharacterDatabase.Execute(ss.str().c_str()); } } return pItem; } Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update ) { if ( !pItem ) return NULL; Item* lastItem = pItem; uint32 entry = pItem->GetEntry(); for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ) { uint16 pos = itr->pos; uint32 count = itr->count; ++itr; if (itr == dest.end()) { lastItem = _StoreItem(pos,pItem,count,false,update); break; } lastItem = _StoreItem(pos,pItem,count,true,update); } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry); return lastItem; } // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case. Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update ) { if ( !pItem ) return NULL; uint8 bag = pos >> 8; uint8 slot = pos & 255; DEBUG_LOG( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count); Item *pItem2 = GetItemByPos( bag, slot ); if (!pItem2) { if (clone) pItem = pItem->CloneItem(count, this); else pItem->SetCount(count); if (!pItem) return NULL; if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM || (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos))) pItem->SetBinding( true ); if (bag == INVENTORY_SLOT_BAG_0) { m_items[slot] = pItem; SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetObjectGuid()); pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetObjectGuid()); pItem->SetGuidValue(ITEM_FIELD_OWNER, GetObjectGuid()); pItem->SetSlot( slot ); pItem->SetContainer( NULL ); // need update known currency if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) UpdateKnownCurrencies(pItem->GetEntry(), true); if (IsInWorld() && update) { pItem->AddToWorld(); pItem->SendCreateUpdateToPlayer( this ); } pItem->SetState(ITEM_CHANGED, this); } else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag )) { pBag->StoreItem( slot, pItem, update ); if ( IsInWorld() && update ) { pItem->AddToWorld(); pItem->SendCreateUpdateToPlayer( this ); } pItem->SetState(ITEM_CHANGED, this); pBag->SetState(ITEM_CHANGED, this); } AddEnchantmentDurations(pItem); AddItemDurations(pItem); // at place into not appropriate slot (bank, for example) remove aura ApplyItemOnStoreSpell(pItem, IsEquipmentPos(pItem->GetBagSlot(), pItem->GetSlot()) || IsInventoryPos(pItem->GetBagSlot(), pItem->GetSlot())); return pItem; } else { if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem2->GetProto()->Bonding == BIND_QUEST_ITEM || (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos))) pItem2->SetBinding(true); pItem2->SetCount( pItem2->GetCount() + count ); if (IsInWorld() && update) pItem2->SendCreateUpdateToPlayer( this ); if (!clone) { // delete item (it not in any slot currently) if (IsInWorld() && update) { pItem->RemoveFromWorld(); pItem->DestroyForPlayer( this ); } RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); pItem->SetOwnerGuid(GetObjectGuid()); // prevent error at next SetState in case trade/mail/buy from vendor pItem->SetSoulboundTradeable(NULL, this, false); RemoveTradeableItem(pItem); pItem->SetState(ITEM_REMOVED, this); } // AddItemDurations(pItem2); - pItem2 already have duration listed for player AddEnchantmentDurations(pItem2); pItem2->SetState(ITEM_CHANGED, this); return pItem2; } } Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update ) { if (Item *pItem = Item::CreateItem(item, 1, this)) { ResetCachedGearScore(); ItemAddedQuestCheck( item, 1 ); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1); return EquipItem( pos, pItem, update ); } return NULL; } Item* Player::EquipItem( uint16 pos, Item *pItem, bool update ) { AddEnchantmentDurations(pItem); AddItemDurations(pItem); uint8 bag = pos >> 8; uint8 slot = pos & 255; Item *pItem2 = GetItemByPos(bag, slot); if (!pItem2) { VisualizeItem( slot, pItem); if (isAlive()) { ItemPrototype const *pProto = pItem->GetProto(); // item set bonuses applied only at equip and removed at unequip, and still active for broken items if (pProto && pProto->ItemSet) AddItemsSetItem(this, pItem); _ApplyItemMods(pItem, slot, true); ApplyItemOnStoreSpell(pItem, true); // Weapons and also Totem/Relic/Sigil/etc if (pProto && isInCombat() && (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer == 0) { uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s; if (getClass() == CLASS_ROGUE) cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s; SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell); if (!spellProto) sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell); else { m_weaponChangeTimer = spellProto->StartRecoveryTime; WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4); data << GetObjectGuid(); data << uint8(1); data << uint32(cooldownSpell); data << uint32(0); GetSession()->SendPacket(&data); } } } if ( IsInWorld() && update ) { pItem->AddToWorld(); pItem->SendCreateUpdateToPlayer( this ); } ApplyEquipCooldown(pItem); if ( slot == EQUIPMENT_SLOT_MAINHAND ) { UpdateExpertise(BASE_ATTACK); UpdateArmorPenetration(); } else if ( slot == EQUIPMENT_SLOT_OFFHAND ) { UpdateExpertise(OFF_ATTACK); UpdateArmorPenetration(); } } else { pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() ); if ( IsInWorld() && update ) pItem2->SendCreateUpdateToPlayer( this ); // delete item (it not in any slot currently) //pItem->DeleteFromDB(); if ( IsInWorld() && update ) { pItem->RemoveFromWorld(); pItem->DestroyForPlayer( this ); } RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); pItem->SetOwnerGuid(GetObjectGuid()); // prevent error at next SetState in case trade/mail/buy from vendor pItem->SetSoulboundTradeable(NULL, this, false); RemoveTradeableItem(pItem); pItem->SetState(ITEM_REMOVED, this); pItem2->SetState(ITEM_CHANGED, this); ApplyEquipCooldown(pItem2); return pItem2; } // Apply Titan's Grip damage penalty if necessary if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152)) CastSpell(this, 49152, true); // only for full equip instead adding to stack GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry()); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1); return pItem; } void Player::QuickEquipItem( uint16 pos, Item *pItem) { if ( pItem ) { AddEnchantmentDurations(pItem); AddItemDurations(pItem); ApplyItemOnStoreSpell(pItem, true); uint8 slot = pos & 255; VisualizeItem( slot, pItem); if ( IsInWorld() ) { pItem->AddToWorld(); pItem->SendCreateUpdateToPlayer( this ); } // Apply Titan's Grip damage penalty if necessary if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152)) CastSpell(this, 49152, true); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry()); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1); } } void Player::SetVisibleItemSlot(uint8 slot, Item *pItem) { if (pItem) { SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry()); SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT)); SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT)); } else { SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0); SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0); } } void Player::VisualizeItem( uint8 slot, Item *pItem) { if(!pItem) 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 ( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM ) pItem->SetBinding( true ); DEBUG_LOG( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry()); m_items[slot] = pItem; SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetObjectGuid()); pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetObjectGuid()); pItem->SetGuidValue(ITEM_FIELD_OWNER, GetObjectGuid()); pItem->SetSlot( slot ); pItem->SetContainer( NULL ); if ( slot < EQUIPMENT_SLOT_END ) SetVisibleItemSlot(slot, pItem); pItem->SetState(ITEM_CHANGED, this); } void Player::RemoveItem( uint8 bag, uint8 slot, bool update ) { // note: removeitem does not actually change the item // it only takes the item out of storage temporarily // note2: if removeitem is to be used for delinking // the item must be removed from the player's updatequeue if (Item *pItem = GetItemByPos(bag, slot)) { DEBUG_LOG( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry()); RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); if ( bag == INVENTORY_SLOT_BAG_0 ) { if ( slot < INVENTORY_SLOT_BAG_END ) { ItemPrototype const *pProto = pItem->GetProto(); // item set bonuses applied only at equip and removed at unequip, and still active for broken items if (pProto && pProto->ItemSet) RemoveItemsSetItem(this, pProto); _ApplyItemMods(pItem, slot, false); // remove item dependent auras and casts (only weapon and armor slots) if (slot < EQUIPMENT_SLOT_END) { RemoveItemDependentAurasAndCasts(pItem); // remove held enchantments, update expertise if ( slot == EQUIPMENT_SLOT_MAINHAND ) { if (pItem->GetItemSuffixFactor()) { pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3); pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4); } else { pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0); pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1); }<|fim▁hole|> else if ( slot == EQUIPMENT_SLOT_OFFHAND ) { UpdateExpertise(OFF_ATTACK); UpdateArmorPenetration(); } } } // need update known currency else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) UpdateKnownCurrencies(pItem->GetEntry(), false); m_items[slot] = NULL; SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid()); if ( slot < EQUIPMENT_SLOT_END ) { SetVisibleItemSlot(slot, NULL); // Remove Titan's Grip damage penalty if necessary if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && !HasTwoHandWeaponInOneHand()) RemoveAurasDueToSpell(49152); } } else { Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ); if ( pBag ) pBag->RemoveItem(slot, update); } pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid()); // pItem->SetGuidValue(ITEM_FIELD_OWNER, ObjectGuid()); not clear owner at remove (it will be set at store). This used in mail and auction code pItem->SetSlot( NULL_SLOT ); //ApplyItemOnStoreSpell, for avoid re-apply will remove at _adding_ to not appropriate slot if (IsInWorld() && update) pItem->SendCreateUpdateToPlayer( this ); } } // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail.... void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update) { if (Item* it = GetItemByPos(bag,slot)) { ItemRemovedQuestCheck(it->GetEntry(), it->GetCount()); RemoveItem(bag, slot, update); // item atStore spell not removed in RemoveItem (for avoid reappaly in slots changes), so do it directly if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot)) ApplyItemOnStoreSpell(it, false); it->RemoveFromUpdateQueueOf(this); if (it->IsInWorld()) { it->RemoveFromWorld(); it->DestroyForPlayer( this ); } } } // Common operation need to add item from inventory without delete in trade, guild bank, mail.... void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB) { // update quest counters ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount()); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount()); // store item Item* pLastItem = StoreItem(dest, pItem, update); // only set if not merged to existing stack (pItem can be deleted already but we can compare pointers any way) if (pLastItem == pItem) { // update owner for last item (this can be original item with wrong owner if (pLastItem->GetOwnerGuid() != GetObjectGuid()) pLastItem->SetOwnerGuid(GetObjectGuid()); // if this original item then it need create record in inventory // in case trade we already have item in other player inventory pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this); } if (pLastItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE)) m_itemSoulboundTradeable.push_back(pLastItem); } void Player::DestroyItem( uint8 bag, uint8 slot, bool update ) { Item *pItem = GetItemByPos( bag, slot ); if ( pItem ) { DEBUG_LOG( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry()); // start from destroy contained items (only equipped bag can have its) if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot { for (int i = 0; i < MAX_BAG_SIZE; ++i) DestroyItem(slot, i, update); } if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED)) { static SqlStatementID delGifts ; SqlStatement stmt = CharacterDatabase.CreateStatement(delGifts, "DELETE FROM character_gifts WHERE item_guid = ?"); stmt.PExecute(pItem->GetGUIDLow()); } RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); pItem->SetSoulboundTradeable(NULL, this, false); RemoveTradeableItem(pItem); if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot)) ApplyItemOnStoreSpell(pItem, false); ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() ); if ( bag == INVENTORY_SLOT_BAG_0 ) { SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid()); // equipment and equipped bags can have applied bonuses if ( slot < INVENTORY_SLOT_BAG_END ) { ItemPrototype const *pProto = pItem->GetProto(); // item set bonuses applied only at equip and removed at unequip, and still active for broken items if (pProto && pProto->ItemSet) RemoveItemsSetItem(this, pProto); _ApplyItemMods(pItem, slot, false); } if ( slot < EQUIPMENT_SLOT_END ) { // remove item dependent auras and casts (only weapon and armor slots) RemoveItemDependentAurasAndCasts(pItem); // update expertise if ( slot == EQUIPMENT_SLOT_MAINHAND ) { UpdateExpertise(BASE_ATTACK); UpdateArmorPenetration(); } else if ( slot == EQUIPMENT_SLOT_OFFHAND ) { UpdateExpertise(OFF_ATTACK); UpdateArmorPenetration(); } // equipment visual show SetVisibleItemSlot(slot, NULL); } // need update known currency else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) UpdateKnownCurrencies(pItem->GetEntry(), false); m_items[slot] = NULL; } else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag )) pBag->RemoveItem(slot, update); if ( IsInWorld() && update ) { pItem->RemoveFromWorld(); pItem->DestroyForPlayer(this); } //pItem->SetOwnerGUID(0); pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid()); pItem->SetSlot( NULL_SLOT ); pItem->SetState(ITEM_REMOVED, this); } } void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check) { DEBUG_LOG( "STORAGE: DestroyItemCount item = %u, count = %u", item, count); uint32 remcount = 0; // in inventory for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) { if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { if (pItem->GetEntry() == item && !pItem->IsInTrade()) { if (pItem->GetCount() + remcount <= count) { // all items in inventory can unequipped remcount += pItem->GetCount(); DestroyItem( INVENTORY_SLOT_BAG_0, i, update); if (remcount >= count) return; } else { ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount ); pItem->SetCount( pItem->GetCount() - count + remcount ); if (IsInWorld() & update) pItem->SendCreateUpdateToPlayer( this ); pItem->SetState(ITEM_CHANGED, this); return; } } } } for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { if (pItem->GetEntry() == item && !pItem->IsInTrade()) { if (pItem->GetCount() + remcount <= count) { // all keys can be unequipped remcount += pItem->GetCount(); DestroyItem( INVENTORY_SLOT_BAG_0, i, update); if (remcount >= count) return; } else { ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount ); pItem->SetCount( pItem->GetCount() - count + remcount ); if (IsInWorld() & update) pItem->SendCreateUpdateToPlayer( this ); pItem->SetState(ITEM_CHANGED, this); return; } } } } // in inventory bags for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { if (Item* pItem = pBag->GetItemByPos(j)) { if (pItem->GetEntry() == item && !pItem->IsInTrade()) { // all items in bags can be unequipped if (pItem->GetCount() + remcount <= count) { remcount += pItem->GetCount(); DestroyItem( i, j, update ); if (remcount >= count) return; } else { ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount ); pItem->SetCount( pItem->GetCount() - count + remcount ); if (IsInWorld() && update) pItem->SendCreateUpdateToPlayer( this ); pItem->SetState(ITEM_CHANGED, this); return; } } } } } } // in equipment and bag list for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) { if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) { if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade()) { if (pItem->GetCount() + remcount <= count) { if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK ) { remcount += pItem->GetCount(); DestroyItem( INVENTORY_SLOT_BAG_0, i, update); if (remcount >= count) return; } } else { ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount ); pItem->SetCount( pItem->GetCount() - count + remcount ); if (IsInWorld() & update) pItem->SendCreateUpdateToPlayer( this ); pItem->SetState(ITEM_CHANGED, this); return; } } } } } void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone ) { DEBUG_LOG( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone ); // in inventory for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); // in inventory bags for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) for(uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem(i, j, update); // in equipment and bag list for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); } void Player::DestroyConjuredItems( bool update ) { // used when entering arena // destroys all conjured items DEBUG_LOG( "STORAGE: DestroyConjuredItems" ); // in inventory for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsConjuredConsumable()) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); // in inventory bags for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) for(uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->IsConjuredConsumable()) DestroyItem( i, j, update); // in equipment and bag list for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsConjuredConsumable()) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); } void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update ) { if(!pItem) return; DEBUG_LOG( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count); if ( pItem->GetCount() <= count ) { count -= pItem->GetCount(); DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update); } else { ItemRemovedQuestCheck( pItem->GetEntry(), count); pItem->SetCount( pItem->GetCount() - count ); count = 0; if ( IsInWorld() & update ) pItem->SendCreateUpdateToPlayer( this ); pItem->SetState(ITEM_CHANGED, this); } } void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) { uint8 srcbag = src >> 8; uint8 srcslot = src & 255; uint8 dstbag = dst >> 8; uint8 dstslot = dst & 255; Item *pSrcItem = GetItemByPos( srcbag, srcslot ); if (!pSrcItem) { SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL ); return; } if (pSrcItem->HasGeneratedLoot()) // prevent split looting item (stackable items can has only temporary loot and this meaning that loot window open) { //best error message found for attempting to split while looting SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL ); return; } // not let split all items (can be only at cheating) if (pSrcItem->GetCount() == count) { SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL ); return; } // not let split more existing items (can be only at cheating) if (pSrcItem->GetCount() < count) { SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL ); return; } DEBUG_LOG( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count); Item *pNewItem = pSrcItem->CloneItem( count, this ); if (!pNewItem) { SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL ); return; } if (IsInventoryPos(dst)) { // change item amount before check (for unique max count check) pSrcItem->SetCount( pSrcItem->GetCount() - count ); ItemPosCountVec dest; InventoryResult msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false ); if (msg != EQUIP_ERR_OK) { delete pNewItem; pSrcItem->SetCount( pSrcItem->GetCount() + count ); SendEquipError( msg, pSrcItem, NULL ); return; } if (IsInWorld()) pSrcItem->SendCreateUpdateToPlayer( this ); pSrcItem->SetState(ITEM_CHANGED, this); StoreItem( dest, pNewItem, true); } else if (IsBankPos (dst)) { // change item amount before check (for unique max count check) pSrcItem->SetCount( pSrcItem->GetCount() - count ); ItemPosCountVec dest; InventoryResult msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false ); if ( msg != EQUIP_ERR_OK ) { delete pNewItem; pSrcItem->SetCount( pSrcItem->GetCount() + count ); SendEquipError( msg, pSrcItem, NULL ); return; } if (IsInWorld()) pSrcItem->SendCreateUpdateToPlayer( this ); pSrcItem->SetState(ITEM_CHANGED, this); BankItem( dest, pNewItem, true); } else if (IsEquipmentPos (dst)) { // change item amount before check (for unique max count check), provide space for splitted items pSrcItem->SetCount( pSrcItem->GetCount() - count ); uint16 dest; InventoryResult msg = CanEquipItem( dstslot, dest, pNewItem, false ); if (msg != EQUIP_ERR_OK) { delete pNewItem; pSrcItem->SetCount( pSrcItem->GetCount() + count ); SendEquipError( msg, pSrcItem, NULL ); return; } if (IsInWorld()) pSrcItem->SendCreateUpdateToPlayer( this ); pSrcItem->SetState(ITEM_CHANGED, this); EquipItem( dest, pNewItem, true); AutoUnequipOffhandIfNeed(); } } void Player::SwapItem( uint16 src, uint16 dst ) { uint8 srcbag = src >> 8; uint8 srcslot = src & 255; uint8 dstbag = dst >> 8; uint8 dstslot = dst & 255; Item *pSrcItem = GetItemByPos( srcbag, srcslot ); Item *pDstItem = GetItemByPos( dstbag, dstslot ); if (!pSrcItem) return; DEBUG_LOG( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry()); if (!isAlive()) { SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem ); return; } // SRC checks // check unequip potability for equipped items and bank bags if (IsEquipmentPos(src) || IsBagPos(src)) { // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later) InventoryResult msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty())); if (msg != EQUIP_ERR_OK) { SendEquipError( msg, pSrcItem, pDstItem ); return; } } // prevent put equipped/bank bag in self if (IsBagPos(src) && srcslot == dstbag) { SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem ); return; } // prevent put equipped/bank bag in self if (IsBagPos(dst) && dstslot == srcbag) { SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem ); return; } // DST checks if (pDstItem) { // check unequip potability for equipped items and bank bags if (IsEquipmentPos ( dst ) || IsBagPos ( dst )) { // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later) InventoryResult msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty())); if (msg != EQUIP_ERR_OK) { SendEquipError( msg, pSrcItem, pDstItem ); return; } } } // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions) // or swap empty bag with another empty or not empty bag (with items exchange) // Move case if ( !pDstItem ) { if ( IsInventoryPos( dst ) ) { ItemPosCountVec dest; InventoryResult msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false ); if ( msg != EQUIP_ERR_OK ) { SendEquipError( msg, pSrcItem, NULL ); return; } RemoveItem(srcbag, srcslot, true); StoreItem( dest, pSrcItem, true); } else if ( IsBankPos ( dst ) ) { ItemPosCountVec dest; InventoryResult msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false); if ( msg != EQUIP_ERR_OK ) { SendEquipError( msg, pSrcItem, NULL ); return; } RemoveItem(srcbag, srcslot, true); BankItem( dest, pSrcItem, true); } else if ( IsEquipmentPos ( dst ) ) { uint16 dest; InventoryResult msg = CanEquipItem( dstslot, dest, pSrcItem, false ); if ( msg != EQUIP_ERR_OK ) { SendEquipError( msg, pSrcItem, NULL ); return; } RemoveItem(srcbag, srcslot, true); EquipItem(dest, pSrcItem, true); AutoUnequipOffhandIfNeed(); } return; } // attempt merge to / fill target item if(!pSrcItem->IsBag() && !pDstItem->IsBag()) { InventoryResult msg; ItemPosCountVec sDest; uint16 eDest; if ( IsInventoryPos( dst ) ) msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false ); else if ( IsBankPos ( dst ) ) msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false ); else if ( IsEquipmentPos ( dst ) ) msg = CanEquipItem( dstslot, eDest, pSrcItem, false ); else return; // can be merge/fill if (msg == EQUIP_ERR_OK) { if ( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize()) { RemoveItem(srcbag, srcslot, true); if ( IsInventoryPos( dst ) ) StoreItem( sDest, pSrcItem, true); else if ( IsBankPos ( dst ) ) BankItem( sDest, pSrcItem, true); else if ( IsEquipmentPos ( dst ) ) { EquipItem( eDest, pSrcItem, true); AutoUnequipOffhandIfNeed(); } } else { pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize()); pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize()); pSrcItem->SetState(ITEM_CHANGED, this); pDstItem->SetState(ITEM_CHANGED, this); if ( IsInWorld() ) { pSrcItem->SendCreateUpdateToPlayer( this ); pDstItem->SendCreateUpdateToPlayer( this ); } } return; } } // impossible merge/fill, do real swap InventoryResult msg; // check src->dest move possibility ItemPosCountVec sDest; uint16 eDest = 0; if ( IsInventoryPos( dst ) ) msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true ); else if ( IsBankPos( dst ) ) msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true ); else if ( IsEquipmentPos( dst ) ) { msg = CanEquipItem( dstslot, eDest, pSrcItem, true ); if ( msg == EQUIP_ERR_OK ) msg = CanUnequipItem( eDest, true ); } if ( msg != EQUIP_ERR_OK ) { SendEquipError( msg, pSrcItem, pDstItem ); return; } // check dest->src move possibility ItemPosCountVec sDest2; uint16 eDest2 = 0; if ( IsInventoryPos( src ) ) msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true ); else if ( IsBankPos( src ) ) msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true ); else if ( IsEquipmentPos( src ) ) { msg = CanEquipItem( srcslot, eDest2, pDstItem, true); if ( msg == EQUIP_ERR_OK ) msg = CanUnequipItem( eDest2, true); } if ( msg != EQUIP_ERR_OK ) { SendEquipError( msg, pDstItem, pSrcItem ); return; } // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store) if (pSrcItem->IsBag() && pDstItem->IsBag()) { Bag* emptyBag = NULL; Bag* fullBag = NULL; if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src)) { emptyBag = (Bag*)pSrcItem; fullBag = (Bag*)pDstItem; } else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst)) { emptyBag = (Bag*)pDstItem; fullBag = (Bag*)pSrcItem; } // bag swap (with items exchange) case if (emptyBag && fullBag) { ItemPrototype const* emotyProto = emptyBag->GetProto(); uint32 count = 0; for(uint32 i=0; i < fullBag->GetBagSize(); ++i) { Item *bagItem = fullBag->GetItemByPos(i); if (!bagItem) continue; ItemPrototype const* bagItemProto = bagItem->GetProto(); if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto)) { // one from items not go to empty target bag SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem ); return; } ++count; } if (count > emptyBag->GetBagSize()) { // too small targeted bag SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem ); return; } // Items swap count = 0; // will pos in new bag for(uint32 i = 0; i< fullBag->GetBagSize(); ++i) { Item *bagItem = fullBag->GetItemByPos(i); if (!bagItem) continue; fullBag->RemoveItem(i, true); emptyBag->StoreItem(count, bagItem, true); bagItem->SetState(ITEM_CHANGED, this); ++count; } } } // now do moves, remove... RemoveItem(dstbag, dstslot, false); RemoveItem(srcbag, srcslot, false); // add to dest if (IsInventoryPos(dst)) StoreItem(sDest, pSrcItem, true); else if (IsBankPos(dst)) BankItem(sDest, pSrcItem, true); else if (IsEquipmentPos(dst)) EquipItem(eDest, pSrcItem, true); // add to src if (IsInventoryPos(src)) StoreItem(sDest2, pDstItem, true); else if (IsBankPos(src)) BankItem(sDest2, pDstItem, true); else if (IsEquipmentPos(src)) EquipItem(eDest2, pDstItem, true); AutoUnequipOffhandIfNeed(); } void Player::AddItemToBuyBackSlot( Item *pItem ) { if (pItem) { uint32 slot = m_currentBuybackSlot; // if current back slot non-empty search oldest or free if (m_items[slot]) { uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 ); uint32 oldest_slot = BUYBACK_SLOT_START; for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i ) { // found empty if (!m_items[i]) { slot = i; break; } uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START); if (oldest_time > i_time) { oldest_time = i_time; oldest_slot = i; } } // find oldest slot = oldest_slot; } RemoveItemFromBuyBackSlot( slot, true ); DEBUG_LOG( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot); m_items[slot] = pItem; time_t base = time(NULL); uint32 etime = uint32(base - m_logintime + (30 * 3600)); uint32 eslot = slot - BUYBACK_SLOT_START; SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetObjectGuid()); if (ItemPrototype const *pProto = pItem->GetProto()) SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() ); else SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 ); SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime ); // move to next (for non filled list is move most optimized choice) if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1) ++m_currentBuybackSlot; } } Item* Player::GetItemFromBuyBackSlot( uint32 slot ) { DEBUG_LOG( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot); if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) return m_items[slot]; return NULL; } void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del ) { DEBUG_LOG( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot); if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) { Item *pItem = m_items[slot]; if (pItem) { pItem->RemoveFromWorld(); if (del) pItem->SetState(ITEM_REMOVED, this); } m_items[slot] = NULL; uint32 eslot = slot - BUYBACK_SLOT_START; SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), ObjectGuid()); SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0); SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0); // if current backslot is filled set to now free slot if (m_items[m_currentBuybackSlot]) m_currentBuybackSlot = slot; } } void Player::SendEquipError( InventoryResult msg, Item* pItem, Item *pItem2, uint32 itemid /*= 0*/ ) const { DEBUG_LOG( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg); WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1); data << uint8(msg); if (msg != EQUIP_ERR_OK) { data << (pItem ? pItem->GetObjectGuid() : ObjectGuid()); data << (pItem2 ? pItem2->GetObjectGuid() : ObjectGuid()); data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2 switch(msg) { case EQUIP_ERR_CANT_EQUIP_LEVEL_I: case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW: { ItemPrototype const* proto = pItem ? pItem->GetProto() : ObjectMgr::GetItemPrototype(itemid); data << uint32(proto ? proto->RequiredLevel : 0); break; } case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one... { data << uint64(0); data << uint32(0); data << uint64(0); break; } case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS: case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS: case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS: { ItemPrototype const* proto = pItem ? pItem->GetProto() : ObjectMgr::GetItemPrototype(itemid); uint32 LimitCategory=proto ? proto->ItemLimitCategory : 0; if (pItem) // check unique-equipped on gems for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) continue; SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID); if(!pGem) continue; // include for check equip another gems with same limit category for not equipped item (and then not counted) uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1; if ( msg == CanEquipUniqueItem(pGem, pItem->GetSlot(),gem_limit_count)) { LimitCategory=pGem->ItemLimitCategory; break; } } data << uint32(LimitCategory); break; } default: break; } } GetSession()->SendPacket(&data); } void Player::SendBuyError( BuyResult msg, Creature* pCreature, uint32 item, uint32 param ) { DEBUG_LOG( "WORLD: Sent SMSG_BUY_FAILED" ); WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) ); data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid()); data << uint32(item); if (param > 0) data << uint32(param); data << uint8(msg); GetSession()->SendPacket(&data); } void Player::SendSellError( SellResult msg, Creature* pCreature, ObjectGuid itemGuid, uint32 param ) { DEBUG_LOG( "WORLD: Sent SMSG_SELL_ITEM" ); WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10 data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid()); data << ObjectGuid(itemGuid); if (param > 0) data << uint32(param); data << uint8(msg); GetSession()->SendPacket(&data); } void Player::TradeCancel(bool sendback) { if (m_trade) { Player* trader = m_trade->GetTrader(); // send yellow "Trade canceled" message to both traders if (sendback) GetSession()->SendCancelTrade(); trader->GetSession()->SendCancelTrade(); // cleanup delete m_trade; m_trade = NULL; delete trader->m_trade; trader->m_trade = NULL; } } void Player::UpdateSoulboundTradeItems() { if (m_itemSoulboundTradeable.empty()) return; // also checks for garbage data for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end();) { if (!*itr) { itr = m_itemSoulboundTradeable.erase(itr++); continue; } if ((*itr)->GetOwnerGuid() != GetObjectGuid()) { itr = m_itemSoulboundTradeable.erase(itr++); continue; } if ((*itr)->CheckSoulboundTradeExpire()) { itr = m_itemSoulboundTradeable.erase(itr++); continue; } ++itr; } } void Player::RemoveTradeableItem(Item* item) { for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end(); ++itr) { if ((*itr) == item) { m_itemSoulboundTradeable.erase(itr); break; } } } void Player::UpdateItemDuration(uint32 time, bool realtimeonly) { if (m_itemDuration.empty()) return; DEBUG_LOG("Player::UpdateItemDuration(%u,%u)", time, realtimeonly); for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ) { Item* item = *itr; ++itr; // current element can be erased in UpdateDuration if ((realtimeonly && (item->GetProto()->ExtraFlags & ITEM_EXTRA_REAL_TIME_DURATION)) || !realtimeonly) item->UpdateDuration(this,time); } } void Player::UpdateEnchantTime(uint32 time) { for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next) { MANGOS_ASSERT(itr->item); next = itr; if (!itr->item->GetEnchantmentId(itr->slot)) { next = m_enchantDuration.erase(itr); } else if (itr->leftduration <= time) { ApplyEnchantment(itr->item, itr->slot, false, false); itr->item->ClearEnchantment(itr->slot); next = m_enchantDuration.erase(itr); } else if (itr->leftduration > time) { itr->leftduration -= time; ++next; } } } void Player::AddEnchantmentDurations(Item *item) { for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x) { if (!item->GetEnchantmentId(EnchantmentSlot(x))) continue; uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x)); if (duration > 0) AddEnchantmentDuration(item, EnchantmentSlot(x), duration); } } void Player::RemoveEnchantmentDurations(Item *item) { for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();) { if (itr->item == item) { // save duration in item item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration); itr = m_enchantDuration.erase(itr); } else ++itr; } } void Player::RemoveAllEnchantments(EnchantmentSlot slot) { // remove enchantments from equipped items first to clean up the m_enchantDuration list for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next) { next = itr; if (itr->slot == slot) { if (itr->item && itr->item->GetEnchantmentId(slot)) { // remove from stats ApplyEnchantment(itr->item, slot, false, false); // remove visual itr->item->ClearEnchantment(slot); } // remove from update list next = m_enchantDuration.erase(itr); } else ++next; } // remove enchants from inventory items // NOTE: no need to remove these from stats, since these aren't equipped // in inventory for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetEnchantmentId(slot)) pItem->ClearEnchantment(slot); // in inventory bags for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) for(uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->GetEnchantmentId(slot)) pItem->ClearEnchantment(slot); } // duration == 0 will remove item enchant void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration) { if (!item) return; if (slot >= MAX_ENCHANTMENT_SLOT) return; for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr) { if (itr->item == item && itr->slot == slot) { itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration); m_enchantDuration.erase(itr); break; } } if (item && duration > 0 ) { GetSession()->SendItemEnchantTimeUpdate(GetObjectGuid(), item->GetObjectGuid(), slot, uint32(duration/1000)); m_enchantDuration.push_back(EnchantDuration(item, slot, duration)); } } void Player::ApplyEnchantment(Item *item,bool apply) { for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot) ApplyEnchantment(item, EnchantmentSlot(slot), apply); } void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition) { if (!item) return; if (!item->IsEquipped()) return; // Don't apply ANY enchantment if item is broken! It's offlike and avoid many exploits with broken items. // Not removing enchantments from broken items - not need. if (item->IsBroken()) return; if (slot >= MAX_ENCHANTMENT_SLOT) return; uint32 enchant_id = item->GetEnchantmentId(slot); if (!enchant_id) return; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return; if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1)) return; if ((pEnchant->requiredLevel) > ((Player*)this)->getLevel()) return; if ((pEnchant->requiredSkill) > 0) { if ((pEnchant->requiredSkillValue) > (((Player*)this)->GetSkillValue(pEnchant->requiredSkill))) return; } if (!item->IsBroken()) { for (int s = 0; s < 3; ++s) { uint32 enchant_display_type = pEnchant->type[s]; uint32 enchant_amount = pEnchant->amount[s]; uint32 enchant_spell_id = pEnchant->spellid[s]; switch(enchant_display_type) { case ITEM_ENCHANTMENT_TYPE_NONE: break; case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL: // processed in Player::CastItemCombatSpell break; case ITEM_ENCHANTMENT_TYPE_DAMAGE: if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND) HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply); else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND) HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply); else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED) HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply); break; case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL: if (enchant_spell_id) { if (apply) { int32 basepoints = 0; // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor) if (item->GetItemRandomPropertyId()) { ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId())); if (item_rand) { // Search enchant_amount for (int k = 0; k < 3; ++k) { if (item_rand->enchant_id[k] == enchant_id) { basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 ); break; } } } } // Cast custom spell vs all equal basepoints getted from enchant_amount if (basepoints) CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item); else CastSpell(this, enchant_spell_id, true, item); } else RemoveAurasDueToItemSpell(item, enchant_spell_id); } break; case ITEM_ENCHANTMENT_TYPE_RESISTANCE: if (!enchant_amount) { ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId())); if (item_rand) { for (int k = 0; k < 3; ++k) { if (item_rand->enchant_id[k] == enchant_id) { enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 ); break; } } } } HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply); break; case ITEM_ENCHANTMENT_TYPE_STAT: { if (!enchant_amount) { ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId())); if (item_rand_suffix) { for (int k = 0; k < 3; ++k) { if (item_rand_suffix->enchant_id[k] == enchant_id) { enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 ); break; } } } } DEBUG_LOG("Adding %u to stat nb %u",enchant_amount,enchant_spell_id); switch (enchant_spell_id) { case ITEM_MOD_MANA: DEBUG_LOG("+ %u MANA",enchant_amount); HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply); break; case ITEM_MOD_HEALTH: DEBUG_LOG("+ %u HEALTH",enchant_amount); HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply); break; case ITEM_MOD_AGILITY: DEBUG_LOG("+ %u AGILITY",enchant_amount); HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply); ApplyStatBuffMod(STAT_AGILITY, float(enchant_amount), apply); break; case ITEM_MOD_STRENGTH: DEBUG_LOG("+ %u STRENGTH",enchant_amount); HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply); ApplyStatBuffMod(STAT_STRENGTH, float(enchant_amount), apply); break; case ITEM_MOD_INTELLECT: DEBUG_LOG("+ %u INTELLECT",enchant_amount); HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply); ApplyStatBuffMod(STAT_INTELLECT, float(enchant_amount), apply); break; case ITEM_MOD_SPIRIT: DEBUG_LOG("+ %u SPIRIT",enchant_amount); HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply); ApplyStatBuffMod(STAT_SPIRIT, float(enchant_amount), apply); break; case ITEM_MOD_STAMINA: DEBUG_LOG("+ %u STAMINA",enchant_amount); HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply); ApplyStatBuffMod(STAT_STAMINA, float(enchant_amount), apply); break; case ITEM_MOD_DEFENSE_SKILL_RATING: ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply); DEBUG_LOG("+ %u DEFENCE", enchant_amount); break; case ITEM_MOD_DODGE_RATING: ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply); DEBUG_LOG("+ %u DODGE", enchant_amount); break; case ITEM_MOD_PARRY_RATING: ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply); DEBUG_LOG("+ %u PARRY", enchant_amount); break; case ITEM_MOD_BLOCK_RATING: ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply); DEBUG_LOG("+ %u SHIELD_BLOCK", enchant_amount); break; case ITEM_MOD_HIT_MELEE_RATING: ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply); DEBUG_LOG("+ %u MELEE_HIT", enchant_amount); break; case ITEM_MOD_HIT_RANGED_RATING: ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply); DEBUG_LOG("+ %u RANGED_HIT", enchant_amount); break; case ITEM_MOD_HIT_SPELL_RATING: ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply); DEBUG_LOG("+ %u SPELL_HIT", enchant_amount); break; case ITEM_MOD_CRIT_MELEE_RATING: ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply); DEBUG_LOG("+ %u MELEE_CRIT", enchant_amount); break; case ITEM_MOD_CRIT_RANGED_RATING: ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply); DEBUG_LOG("+ %u RANGED_CRIT", enchant_amount); break; case ITEM_MOD_CRIT_SPELL_RATING: ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply); DEBUG_LOG("+ %u SPELL_CRIT", enchant_amount); break; // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used // in Enchantments // case ITEM_MOD_HIT_TAKEN_MELEE_RATING: // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply); // break; // case ITEM_MOD_HIT_TAKEN_RANGED_RATING: // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply); // break; // case ITEM_MOD_HIT_TAKEN_SPELL_RATING: // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply); // break; // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING: // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); // break; // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING: // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); // break; // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING: // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); // break; // case ITEM_MOD_HASTE_MELEE_RATING: // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply); // break; // case ITEM_MOD_HASTE_RANGED_RATING: // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply); // break; case ITEM_MOD_HASTE_SPELL_RATING: ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply); break; case ITEM_MOD_HIT_RATING: ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply); DEBUG_LOG("+ %u HIT", enchant_amount); break; case ITEM_MOD_CRIT_RATING: ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply); DEBUG_LOG("+ %u CRITICAL", enchant_amount); break; // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment // case ITEM_MOD_HIT_TAKEN_RATING: // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply); // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply); // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply); // break; // case ITEM_MOD_CRIT_TAKEN_RATING: // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); // break; case ITEM_MOD_RESILIENCE_RATING: ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); DEBUG_LOG("+ %u RESILIENCE", enchant_amount); break; case ITEM_MOD_HASTE_RATING: ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply); ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply); DEBUG_LOG("+ %u HASTE", enchant_amount); break; case ITEM_MOD_EXPERTISE_RATING: ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply); DEBUG_LOG("+ %u EXPERTISE", enchant_amount); break; case ITEM_MOD_ATTACK_POWER: HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply); HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply); DEBUG_LOG("+ %u ATTACK_POWER", enchant_amount); break; case ITEM_MOD_RANGED_ATTACK_POWER: HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply); DEBUG_LOG("+ %u RANGED_ATTACK_POWER", enchant_amount); break; case ITEM_MOD_MANA_REGENERATION: ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply); DEBUG_LOG("+ %u MANA_REGENERATION", enchant_amount); break; case ITEM_MOD_ARMOR_PENETRATION_RATING: ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply); DEBUG_LOG("+ %u ARMOR PENETRATION", enchant_amount); break; case ITEM_MOD_SPELL_POWER: ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply); DEBUG_LOG("+ %u SPELL_POWER", enchant_amount); break; case ITEM_MOD_HEALTH_REGEN: ((Player*)this)->ApplyHealthRegenBonus(enchant_amount, apply); DEBUG_LOG("+ %u HEALTH_REGENERATION", enchant_amount); break; case ITEM_MOD_BLOCK_VALUE: HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply); break; case ITEM_MOD_FERAL_ATTACK_POWER: case ITEM_MOD_SPELL_HEALING_DONE: // deprecated case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated default: break; } break; } case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon { if (getClass() == CLASS_SHAMAN) { float addValue = 0.0f; if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND) { addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f); HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply); } else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND ) { addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f); HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply); } } break; } case ITEM_ENCHANTMENT_TYPE_USE_SPELL: // processed in Player::CastItemUseSpell break; case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET: // nothing do.. break; default: sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type); break; } /*switch(enchant_display_type)*/ } /*for*/ } // visualize enchantment at player and equipped items if (slot == PERM_ENCHANTMENT_SLOT) SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0); if (slot == TEMP_ENCHANTMENT_SLOT) SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0); if (apply_dur) { if (apply) { // set duration uint32 duration = item->GetEnchantmentDuration(slot); if (duration > 0) AddEnchantmentDuration(item, slot, duration); } else { // duration == 0 will remove EnchantDuration AddEnchantmentDuration(item, slot, 0); } } } void Player::SendEnchantmentDurations() { for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr) { GetSession()->SendItemEnchantTimeUpdate(GetObjectGuid(), itr->item->GetObjectGuid(), itr->slot, uint32(itr->leftduration) / 1000); } } void Player::SendItemDurations() { for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr) { (*itr)->SendTimeUpdate(this); } } void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast) { if(!item) // prevent crash return; // last check 2.0.10 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) ); data << GetObjectGuid(); // player GUID data << uint32(received); // 0=looted, 1=from npc data << uint32(created); // 0=received, 1=created data << uint32(1); // IsShowChatMessage data << uint8(item->GetBagSlot()); // bagslot // item slot, but when added to stack: 0xFFFFFFFF data << uint32((item->GetCount() == count) ? item->GetSlot() : -1); data << uint32(item->GetEntry()); // item id data << uint32(item->GetItemSuffixFactor()); // SuffixFactor data << uint32(item->GetItemRandomPropertyId()); // random item property id data << uint32(count); // count of items data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory if (broadcast && GetGroup()) GetGroup()->BroadcastPacket(&data, true); else GetSession()->SendPacket(&data); } /*********************************************************/ /*** GOSSIP SYSTEM ***/ /*********************************************************/ void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId) { PlayerMenu* pMenu = PlayerTalkClass; pMenu->ClearMenus(); pMenu->GetGossipMenu().SetMenuId(menuId); GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId); // prepares quest menu when true bool canSeeQuests = menuId == GetDefaultGossipMenuForSource(pSource); // if canSeeQuests (the default, top level menu) and no menu options exist for this, use options from default options if (pMenuItemBounds.first == pMenuItemBounds.second && canSeeQuests) pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0); bool canTalkToCredit = pSource->GetTypeId() == TYPEID_UNIT; for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr) { bool hasMenuItem = true; if (!isGameMaster()) // Let GM always see menu items regardless of conditions { if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1)) { if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER) canSeeQuests = false; continue; } if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2)) { if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER) canSeeQuests = false; continue; } if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3)) { if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER) canSeeQuests = false; continue; } } if (pSource->GetTypeId() == TYPEID_UNIT) { Creature *pCreature = (Creature*)pSource; uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS); if (!(itr->second.npc_option_npcflag & npcflags)) continue; switch(itr->second.option_id) { case GOSSIP_OPTION_GOSSIP: if (itr->second.action_menu_id != 0) // has sub menu (or close gossip), so do not "talk" with this NPC yet canTalkToCredit = false; break; case GOSSIP_OPTION_QUESTGIVER: hasMenuItem = false; break; case GOSSIP_OPTION_ARMORER: hasMenuItem = false; // added in special mode break; case GOSSIP_OPTION_SPIRITHEALER: if (!isDead()) hasMenuItem = false; break; case GOSSIP_OPTION_VENDOR: { VendorItemData const* vItems = pCreature->GetVendorItems(); VendorItemData const* tItems = pCreature->GetVendorTemplateItems(); if ((!vItems || vItems->Empty()) && (!tItems || tItems->Empty())) { sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry()); hasMenuItem = false; } break; } case GOSSIP_OPTION_TRAINER: // pet trainers not have spells in fact now /* FIXME: gossip menu with single unlearn pet talents option not show by some reason if (pCreature->GetCreatureInfo()->trainer_type == TRAINER_TYPE_PETS) hasMenuItem = false; else */ if (!pCreature->IsTrainerOf(this, false)) hasMenuItem = false; break; case GOSSIP_OPTION_UNLEARNTALENTS: if (!pCreature->CanTrainAndResetTalentsOf(this)) hasMenuItem = false; break; case GOSSIP_OPTION_UNLEARNPETSKILLS: if (pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER) hasMenuItem = false; else if (Pet * pet = GetPet()) { if (pet->getPetType() != HUNTER_PET || pet->m_spells.size() <= 1) hasMenuItem = false; } else hasMenuItem = false; break; case GOSSIP_OPTION_TAXIVENDOR: if (GetSession()->SendLearnNewTaxiNode(pCreature)) return; break; case GOSSIP_OPTION_BATTLEFIELD: if (!pCreature->CanInteractWithBattleMaster(this, false)) hasMenuItem = false; break; case GOSSIP_OPTION_STABLEPET: if (getClass() != CLASS_HUNTER) hasMenuItem = false; break; case GOSSIP_OPTION_SPIRITGUIDE: case GOSSIP_OPTION_INNKEEPER: case GOSSIP_OPTION_BANKER: case GOSSIP_OPTION_PETITIONER: case GOSSIP_OPTION_TABARDDESIGNER: case GOSSIP_OPTION_AUCTIONEER: case GOSSIP_OPTION_MAILBOX: break; // no checks default: sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id); hasMenuItem = false; break; } } else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT) { GameObject *pGo = (GameObject*)pSource; switch(itr->second.option_id) { case GOSSIP_OPTION_QUESTGIVER: hasMenuItem = false; break; case GOSSIP_OPTION_GOSSIP: if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER) hasMenuItem = false; break; default: hasMenuItem = false; break; } } if (hasMenuItem) { std::string strOptionText = itr->second.option_text; std::string strBoxText = itr->second.box_text; int loc_idx = GetSession()->GetSessionDbLocaleIndex(); if (loc_idx >= 0) { uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id); if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry)) { if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty()) strOptionText = no->OptionText[loc_idx]; if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty()) strBoxText = no->BoxText[loc_idx]; } } pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded); pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id); } } if (canSeeQuests) PrepareQuestMenu(pSource->GetObjectGuid()); if (canTalkToCredit) { if (pSource->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP) && !(((Creature*)pSource)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_TALKTO_CREDIT)) TalkedToCreature(pSource->GetEntry(), pSource->GetObjectGuid()); } // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-) /*if (pMenu->Empty()) { if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER)) { // output error message if need pCreature->IsTrainerOf(this, true); } if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER)) { // output error message if need pCreature->CanInteractWithBattleMaster(this, true); } }*/ } void Player::SendPreparedGossip(WorldObject *pSource) { if (!pSource) return; if (pSource->GetTypeId() == TYPEID_UNIT) { // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag) if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty()) { SendPreparedQuest(pSource->GetObjectGuid()); return; } } else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT) { // probably need to find a better way here if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty()) { SendPreparedQuest(pSource->GetObjectGuid()); return; } } // in case non empty gossip menu (that not included quests list size) show it // (quest entries from quest menu will be included in list) uint32 textId = GetGossipTextId(pSource); if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId()) textId = GetGossipTextId(menuId, pSource); PlayerTalkClass->SendGossipMenu(textId, pSource->GetObjectGuid()); } void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId) { GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu(); if (gossipListId >= gossipmenu.MenuItemCount()) return; // if not same, then something funky is going on if (menuId != gossipmenu.GetMenuId()) return; GossipMenuItem const& menu_item = gossipmenu.GetItem(gossipListId); uint32 gossipOptionId = menu_item.m_gOptionId; ObjectGuid guid = pSource->GetObjectGuid(); uint32 moneyTake = menu_item.m_gBoxMoney; // if this function called and player have money for pay MoneyTake or cheating, proccess both cases if (moneyTake > 0) { if (GetMoney() >= moneyTake) ModifyMoney(-int32(moneyTake)); else return; // cheating } if (pSource->GetTypeId() == TYPEID_GAMEOBJECT) { if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER) { sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry()); return; } } GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId); switch (gossipOptionId) { case GOSSIP_OPTION_GOSSIP: { if (pMenuData.m_gAction_poi) PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi); // send new menu || close gossip || stay at current menu if (pMenuData.m_gAction_menu > 0) { PrepareGossipMenu(pSource, uint32(pMenuData.m_gAction_menu)); SendPreparedGossip(pSource); } else if (pMenuData.m_gAction_menu < 0) { PlayerTalkClass->CloseGossip(); TalkedToCreature(pSource->GetEntry(), pSource->GetObjectGuid()); } break; } case GOSSIP_OPTION_SPIRITHEALER: if (isDead()) ((Creature*)pSource)->CastSpell(((Creature*)pSource), 17251, true, NULL, NULL, GetObjectGuid()); break; case GOSSIP_OPTION_QUESTGIVER: PrepareQuestMenu(guid); SendPreparedQuest(guid); break; case GOSSIP_OPTION_VENDOR: case GOSSIP_OPTION_ARMORER: GetSession()->SendListInventory(guid); break; case GOSSIP_OPTION_STABLEPET: GetSession()->SendStablePet(guid); break; case GOSSIP_OPTION_TRAINER: GetSession()->SendTrainerList(guid); break; case GOSSIP_OPTION_UNLEARNTALENTS: PlayerTalkClass->CloseGossip(); SendTalentWipeConfirm(guid); break; case GOSSIP_OPTION_UNLEARNPETSKILLS: PlayerTalkClass->CloseGossip(); SendPetSkillWipeConfirm(); break; case GOSSIP_OPTION_TAXIVENDOR: GetSession()->SendTaxiMenu(((Creature*)pSource)); break; case GOSSIP_OPTION_INNKEEPER: PlayerTalkClass->CloseGossip(); SetBindPoint(guid); break; case GOSSIP_OPTION_BANKER: GetSession()->SendShowBank(guid); break; case GOSSIP_OPTION_PETITIONER: PlayerTalkClass->CloseGossip(); GetSession()->SendPetitionShowList(guid); break; case GOSSIP_OPTION_TABARDDESIGNER: PlayerTalkClass->CloseGossip(); GetSession()->SendTabardVendorActivate(guid); break; case GOSSIP_OPTION_AUCTIONEER: GetSession()->SendAuctionHello(((Creature*)pSource)); break; case GOSSIP_OPTION_MAILBOX: PlayerTalkClass->CloseGossip(); GetSession()->SendShowMailBox(guid); break; case GOSSIP_OPTION_SPIRITGUIDE: PrepareGossipMenu(pSource); SendPreparedGossip(pSource); break; case GOSSIP_OPTION_BATTLEFIELD: { BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry()); if (bgTypeId == BATTLEGROUND_TYPE_NONE) { sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow()); return; } GetSession()->SendBattlegGroundList(guid, bgTypeId); break; } } if (pMenuData.m_gAction_script) { if (pSource->GetTypeId() == TYPEID_UNIT) GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this); else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT) GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource); } } uint32 Player::GetGossipTextId(WorldObject *pSource) { if (!pSource || pSource->GetTypeId() != TYPEID_UNIT) return DEFAULT_GOSSIP_MESSAGE; if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetGUIDLow())) return pos; return DEFAULT_GOSSIP_MESSAGE; } uint32 Player::GetGossipTextId(uint32 menuId, WorldObject* pSource) { uint32 textId = DEFAULT_GOSSIP_MESSAGE; if (!menuId) return textId; GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId); for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr) { if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2)) { textId = itr->second.text_id; // Start related script if (itr->second.script_id) GetMap()->ScriptsStart(sGossipScripts, itr->second.script_id, this, pSource); break; } } return textId; } uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource) { if (pSource->GetTypeId() == TYPEID_UNIT) return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId; else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT) return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId(); return 0; } /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ void Player::PrepareQuestMenu(ObjectGuid guid) { QuestRelationsMapBounds rbounds; QuestRelationsMapBounds irbounds; // pets also can have quests if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid)) { rbounds = sObjectMgr.GetCreatureQuestRelationsMapBounds(pCreature->GetEntry()); irbounds = sObjectMgr.GetCreatureQuestInvolvedRelationsMapBounds(pCreature->GetEntry()); } else { //we should obtain map pointer from GetMap() in 99% of cases. Special case //only for quests which cast teleport spells on player Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId()); MANGOS_ASSERT(_map); if (GameObject *pGameObject = _map->GetGameObject(guid)) { rbounds = sObjectMgr.GetGOQuestRelationsMapBounds(pGameObject->GetEntry()); irbounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(pGameObject->GetEntry()); } else return; } QuestMenu &qm = PlayerTalkClass->GetQuestMenu(); qm.ClearMenu(); for(QuestRelationsMap::const_iterator itr = irbounds.first; itr != irbounds.second; ++itr) { uint32 quest_id = itr->second; Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) continue; QuestStatus status = GetQuestStatus(quest_id); if (status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(quest_id)) qm.AddMenuItem(quest_id, 4); else if (status == QUEST_STATUS_INCOMPLETE) qm.AddMenuItem(quest_id, 4); else if (status == QUEST_STATUS_AVAILABLE) qm.AddMenuItem(quest_id, 2); } for(QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr) { uint32 quest_id = itr->second; Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) continue; QuestStatus status = GetQuestStatus(quest_id); if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false)) qm.AddMenuItem(quest_id, 4); else if (status == QUEST_STATUS_NONE && CanTakeQuest(pQuest, false)) qm.AddMenuItem(quest_id, 2); } } void Player::SendPreparedQuest(ObjectGuid guid) { QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu(); if (questMenu.Empty()) return; QuestMenuItem const& qmi0 = questMenu.GetItem(0); uint32 icon = qmi0.m_qIcon; // single element case if (questMenu.MenuItemCount() == 1) { // Auto open -- maybe also should verify there is no greeting uint32 quest_id = qmi0.m_qId; Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (pQuest) { if (icon == 4 && !GetQuestRewardStatus(quest_id)) PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true); else if (icon == 4) PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true); // Send completable on repeatable and autoCompletable quest if player don't have quest // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not) else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDailyOrWeekly()) PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true); else PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true); } } // multiply entries else { QEmote qe; qe._Delay = 0; qe._Emote = 0; std::string title = ""; // need pet case for some quests if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid)) { uint32 textid = GetGossipTextId(pCreature); GossipText const* gossiptext = sObjectMgr.GetGossipText(textid); if (!gossiptext) { qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote title = ""; } else { qe = gossiptext->Options[0].Emotes[0]; int loc_idx = GetSession()->GetSessionDbLocaleIndex(); std::string title0 = gossiptext->Options[0].Text_0; std::string title1 = gossiptext->Options[0].Text_1; sObjectMgr.GetNpcTextLocaleStrings0(textid, loc_idx, &title0, &title1); title = !title0.empty() ? title0 : title1; } } PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid); } } bool Player::IsActiveQuest( uint32 quest_id ) const { QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id); return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE; } bool Player::IsCurrentQuest(uint32 quest_id, uint8 completed_or_not) const { QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id); if (itr == mQuestStatus.end()) return false; switch (completed_or_not) { case 1: return itr->second.m_status == QUEST_STATUS_INCOMPLETE; case 2: return itr->second.m_status == QUEST_STATUS_COMPLETE && !itr->second.m_rewarded; default: return itr->second.m_status == QUEST_STATUS_INCOMPLETE || (itr->second.m_status == QUEST_STATUS_COMPLETE && !itr->second.m_rewarded); } } Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const *pQuest) { QuestRelationsMapBounds rbounds; if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid)) { rbounds = sObjectMgr.GetCreatureQuestRelationsMapBounds(pCreature->GetEntry()); } else { //we should obtain map pointer from GetMap() in 99% of cases. Special case //only for quests which cast teleport spells on player Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId()); MANGOS_ASSERT(_map); if (GameObject *pGameObject = _map->GetGameObject(guid)) { rbounds = sObjectMgr.GetGOQuestRelationsMapBounds(pGameObject->GetEntry()); } else return NULL; } uint32 nextQuestID = pQuest->GetNextQuestInChain(); for(QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr) { if (itr->second == nextQuestID) return sObjectMgr.GetQuestTemplate(nextQuestID); } return NULL; } bool Player::CanSeeStartQuest(Quest const *pQuest) const { if (SatisfyQuestClass(pQuest, false) && SatisfyQuestRace(pQuest, false) && SatisfyQuestSkill(pQuest, false) && SatisfyQuestExclusiveGroup(pQuest, false) && SatisfyQuestReputation(pQuest, false) && SatisfyQuestPreviousQuest(pQuest, false) && SatisfyQuestNextChain(pQuest, false) && SatisfyQuestPrevChain(pQuest, false) && SatisfyQuestDay(pQuest, false) && SatisfyQuestWeek(pQuest, false) && SatisfyQuestMonth(pQuest, false) && pQuest->IsActive()) { return int32(getLevel()) + sWorld.getConfig(CONFIG_INT32_QUEST_HIGH_LEVEL_HIDE_DIFF) >= int32(pQuest->GetMinLevel()); } return false; } bool Player::CanTakeQuest(Quest const *pQuest, bool msg) const { return SatisfyQuestStatus(pQuest, msg) && SatisfyQuestExclusiveGroup(pQuest, msg) && SatisfyQuestClass(pQuest, msg) && SatisfyQuestRace(pQuest, msg) && SatisfyQuestLevel(pQuest, msg) && SatisfyQuestSkill(pQuest, msg) && SatisfyQuestReputation(pQuest, msg) && SatisfyQuestPreviousQuest(pQuest, msg) && SatisfyQuestTimed(pQuest, msg) && SatisfyQuestNextChain(pQuest, msg) && SatisfyQuestPrevChain(pQuest, msg) && SatisfyQuestDay(pQuest, msg) && SatisfyQuestWeek(pQuest, msg) && SatisfyQuestMonth(pQuest, msg) && pQuest->IsActive(); } bool Player::CanAddQuest(Quest const *pQuest, bool msg) const { if (!SatisfyQuestLog(msg)) return false; if (!CanGiveQuestSourceItemIfNeed(pQuest)) return false; return true; } bool Player::CanCompleteQuest(uint32 quest_id) const { if (!quest_id) return false; QuestStatusMap::const_iterator q_itr = mQuestStatus.find(quest_id); // some quests can be auto taken and auto completed in one step QuestStatus status = q_itr != mQuestStatus.end() ? q_itr->second.m_status : QUEST_STATUS_NONE; if (status == QUEST_STATUS_COMPLETE) return false; // not allow re-complete quest Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id); if (!qInfo) return false; // only used for "flag" quests and not real in-game quests if (qInfo->HasQuestFlag(QUEST_FLAGS_AUTO_REWARDED)) { // a few checks, not all "satisfy" is needed if (SatisfyQuestPreviousQuest(qInfo, false) && SatisfyQuestLevel(qInfo, false) && SatisfyQuestSkill(qInfo, false) && SatisfyQuestRace(qInfo, false) && SatisfyQuestClass(qInfo, false)) return true; return false; } // Anti WPE for client command /script CompleteQuest() on quests with AutoComplete flag if (status == QUEST_STATUS_NONE) { for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { if (qInfo->ReqItemCount[i] != 0 && GetItemCount(qInfo->ReqItemId[i]) < qInfo->ReqItemCount[i]) { return false; } } } // auto complete quest if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false)) return true; if (status != QUEST_STATUS_INCOMPLETE) return false; // incomplete quest have status data QuestStatusData const& q_status = q_itr->second; if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) { for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { if (qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i]) return false; } } if (qInfo->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO))) { for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) { if (qInfo->ReqCreatureOrGOId[i] == 0) continue; if (qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i]) return false; } } if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_EXPLORATION_OR_EVENT) && !q_status.m_explored) return false; if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED) && q_status.m_timer == 0) return false; if (qInfo->GetRewOrReqMoney() < 0) { if (GetMoney() < uint32(-qInfo->GetRewOrReqMoney())) return false; } uint32 repFacId = qInfo->GetRepObjectiveFaction(); if (repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue()) return false; return true; } bool Player::CanCompleteRepeatableQuest(Quest const *pQuest) const { // Solve problem that player don't have the quest and try complete it. // if repeatable she must be able to complete event if player don't have it. // Seem that all repeatable quest are DELIVER Flag so, no need to add more. if (!CanTakeQuest(pQuest, false)) return false; if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) if (pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i])) return false; if (!CanRewardQuest(pQuest, false)) return false; return true; } bool Player::CanRewardQuest(Quest const *pQuest, bool msg) const { // not auto complete quest and not completed quest (only cheating case, then ignore without message) if (!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE) return false; // daily quest can't be rewarded (25 daily quest already completed) if (!SatisfyQuestDay(pQuest, true) || !SatisfyQuestWeek(pQuest, true) || !SatisfyQuestMonth(pQuest, true)) return false; // rewarded and not repeatable quest (only cheating case, then ignore without message) if (GetQuestRewardStatus(pQuest->GetQuestId())) return false; // prevent receive reward with quest items in bank if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) { for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { if (pQuest->ReqItemCount[i] != 0 && GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i]) { if (msg) SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, pQuest->ReqItemId[i]); return false; } } } // prevent receive reward with low money and GetRewOrReqMoney() < 0 if (pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney())) return false; return true; } bool Player::CanRewardQuest(Quest const *pQuest, uint32 reward, bool msg) const { // prevent receive reward with quest items in bank or for not completed quest if (!CanRewardQuest(pQuest,msg)) return false; if (pQuest->GetRewChoiceItemsCount() > 0) { if (pQuest->RewChoiceItemId[reward]) { ItemPosCountVec dest; InventoryResult res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ); if (res != EQUIP_ERR_OK) { SendEquipError(res, NULL, NULL, pQuest->RewChoiceItemId[reward]); return false; } } } if (pQuest->GetRewItemsCount() > 0) { for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i) { if (pQuest->RewItemId[i]) { ItemPosCountVec dest; InventoryResult res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ); if (res != EQUIP_ERR_OK) { SendEquipError(res, NULL, NULL); return false; } } } } return true; } void Player::SendPetTameFailure(PetTameFailureReason reason) { WorldPacket data(SMSG_PET_TAME_FAILURE, 1); data << uint8(reason); GetSession()->SendPacket(&data); } void Player::AddQuest( Quest const *pQuest, Object *questGiver ) { uint16 log_slot = FindQuestSlot( 0 ); MANGOS_ASSERT(log_slot < MAX_QUEST_LOG_SIZE); uint32 quest_id = pQuest->GetQuestId(); // if not exist then created with set uState==NEW and rewarded=false QuestStatusData& questStatusData = mQuestStatus[quest_id]; // check for repeatable quests status reset questStatusData.m_status = QUEST_STATUS_INCOMPLETE; questStatusData.m_explored = false; if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) { for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) questStatusData.m_itemcount[i] = 0; } if (pQuest->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO))) { for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) questStatusData.m_creatureOrGOcount[i] = 0; } if ( pQuest->GetRepObjectiveFaction() ) if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction())) GetReputationMgr().SetVisible(factionEntry); uint32 qtime = 0; if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED)) { uint32 limittime = pQuest->GetLimitTime(); // shared timed quest if (questGiver && questGiver->GetTypeId()==TYPEID_PLAYER) limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILLISECONDS; AddTimedQuest( quest_id ); questStatusData.m_timer = limittime * IN_MILLISECONDS; qtime = static_cast<uint32>(time(NULL)) + limittime; } else questStatusData.m_timer = 0; SetQuestSlot(log_slot, quest_id, qtime); if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED; // quest accept scripts if (questGiver) { switch (questGiver->GetTypeId()) { case TYPEID_UNIT: sScriptMgr.OnQuestAccept(this, (Creature*)questGiver, pQuest); break; case TYPEID_ITEM: case TYPEID_CONTAINER: sScriptMgr.OnQuestAccept(this, (Item*)questGiver, pQuest); break; case TYPEID_GAMEOBJECT: sScriptMgr.OnQuestAccept(this, (GameObject*)questGiver, pQuest); break; } // starting initial DB quest script if (pQuest->GetQuestStartScript() != 0) GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this); } // remove start item if not need if (questGiver && questGiver->isType(TYPEMASK_ITEM)) { // destroy not required for quest finish quest starting item bool notRequiredItem = true; for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { if (pQuest->ReqItemId[i] == questGiver->GetEntry()) { notRequiredItem = false; break; } } if (pQuest->GetSrcItemId() == questGiver->GetEntry()) notRequiredItem = false; if (notRequiredItem) DestroyItem(((Item*)questGiver)->GetBagSlot(), ((Item*)questGiver)->GetSlot(), true); } GiveQuestSourceItemIfNeed(pQuest); AdjustQuestReqItemCount( pQuest, questStatusData ); // Some spells applied at quest activation SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true); if (saBounds.first != saBounds.second) { uint32 zone, area; GetZoneAndAreaId(zone,area); for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) if (itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area)) if (!HasAura(itr->second->spellId, EFFECT_INDEX_0) ) CastSpell(this,itr->second->spellId,true); } UpdateForQuestWorldObjects(); } void Player::CompleteQuest(uint32 quest_id) { if (quest_id) { SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE); uint16 log_slot = FindQuestSlot(quest_id); if (log_slot < MAX_QUEST_LOG_SIZE) SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE); if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id)) { if (qInfo->HasQuestFlag(QUEST_FLAGS_AUTO_REWARDED)) RewardQuest(qInfo, 0, this, false); } } } void Player::IncompleteQuest(uint32 quest_id) { if (quest_id) { SetQuestStatus(quest_id, QUEST_STATUS_INCOMPLETE); uint16 log_slot = FindQuestSlot( quest_id ); if (log_slot < MAX_QUEST_LOG_SIZE) RemoveQuestSlotState(log_slot, QUEST_STATE_COMPLETE); } } void Player::RewardQuest(Quest const *pQuest, uint32 reward, Object* questGiver, bool announce) { uint32 quest_id = pQuest->GetQuestId(); // Destroy quest items uint32 srcItemId = pQuest->GetSrcItemId(); uint32 srcItemCount = 0; if (srcItemId) { srcItemCount = pQuest->GetSrcItemCount(); if (!srcItemCount) srcItemCount = 1; DestroyItemCount(srcItemId, srcItemCount, true, true); } // Destroy requered items for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { uint32 reqItemId = pQuest->ReqItemId[i]; uint32 reqItemCount = pQuest->ReqItemCount[i]; if (reqItemId) { if (reqItemId == srcItemId) reqItemCount -= srcItemCount; if (reqItemCount) DestroyItemCount(reqItemId, reqItemCount, true); } } RemoveTimedQuest(quest_id); if (BattleGround* bg = GetBattleGround()) if (bg->GetTypeID(true) == BATTLEGROUND_AV) ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this); if (pQuest->GetRewChoiceItemsCount() > 0) { if (uint32 itemId = pQuest->RewChoiceItemId[reward]) { ItemPosCountVec dest; if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward]) == EQUIP_ERR_OK) { Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false); } } } if (pQuest->GetRewItemsCount() > 0) { for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i) { if (uint32 itemId = pQuest->RewItemId[i]) { ItemPosCountVec dest; if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i]) == EQUIP_ERR_OK) { Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); SendNewItem(item, pQuest->RewItemCount[i], true, false); } } } } RewardReputation(pQuest); uint16 log_slot = FindQuestSlot(quest_id); if (log_slot < MAX_QUEST_LOG_SIZE) SetQuestSlot(log_slot,0); QuestStatusData& q_status = mQuestStatus[quest_id]; // Used for client inform but rewarded only in case not max level uint32 xp = uint32(pQuest->XPValue(this) * sWorld.getConfig(CONFIG_FLOAT_RATE_XP_QUEST)*(GetSession()->IsPremium()+1)); if (getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { GiveXP(xp , NULL); // Give player extra money (for max level already included in pQuest->GetRewMoneyMaxLevel()) if (pQuest->GetRewOrReqMoney() > 0) { ModifyMoney(pQuest->GetRewOrReqMoney()); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney()); } } else { // reward money for max level already included in pQuest->GetRewMoneyMaxLevel() uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)); // reward money used if > xp replacement money if (pQuest->GetRewOrReqMoney() > int32(money)) money = pQuest->GetRewOrReqMoney(); ModifyMoney(money); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money); } // req money case if (pQuest->GetRewOrReqMoney() < 0) ModifyMoney(pQuest->GetRewOrReqMoney()); // honor reward if (uint32 honor = pQuest->CalculateRewardHonor(getLevel())) RewardHonor(NULL, 0, honor); // title reward if (pQuest->GetCharTitleId()) { if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId())) SetTitle(titleEntry); } if (pQuest->GetBonusTalents()) { m_questRewardTalentCount += pQuest->GetBonusTalents(); InitTalentForLevel(); } // Send reward mail if (uint32 mail_template_id = pQuest->GetRewMailTemplateId()) MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_HAS_BODY, pQuest->GetRewMailDelaySecs()); if (pQuest->IsDaily()) { SetDailyQuestStatus(quest_id); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1); } if (pQuest->IsWeekly()) SetWeeklyQuestStatus(quest_id); if (pQuest->IsMonthly()) SetMonthlyQuestStatus(quest_id); if (!pQuest->IsRepeatable()) SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE); else SetQuestStatus(quest_id, QUEST_STATUS_NONE); q_status.m_rewarded = true; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; if (announce) SendQuestReward(pQuest, xp, questGiver); bool handled = false; if (questGiver) { switch(questGiver->GetTypeId()) { case TYPEID_UNIT: handled = sScriptMgr.OnQuestRewarded(this, (Creature*)questGiver, pQuest); break; case TYPEID_GAMEOBJECT: handled = sScriptMgr.OnQuestRewarded(this, (GameObject*)questGiver, pQuest); break; } } if (!handled && questGiver && pQuest->GetQuestCompleteScript() != 0) GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this); // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data) if (pQuest->GetRewSpellCast() > 0) CastSpell(this, pQuest->GetRewSpellCast(), true); else if (pQuest->GetRewSpell() > 0) CastSpell(this, pQuest->GetRewSpell(), true); if (pQuest->GetZoneOrSort() > 0) GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort()); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId()); uint32 zone = 0; uint32 area = 0; // remove auras from spells with quest reward state limitations SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id); if (saEndBounds.first != saEndBounds.second) { GetZoneAndAreaId(zone,area); for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr) if (!itr->second->IsFitToRequirements(this, zone, area)) RemoveAurasDueToSpell(itr->second->spellId); } // Some spells applied at quest reward SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id, false); if (saBounds.first != saBounds.second) { if (!zone || !area) GetZoneAndAreaId(zone, area); for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) if (itr->second->autocast && itr->second->IsFitToRequirements(this, zone, area)) if (!HasAura(itr->second->spellId, EFFECT_INDEX_0)) CastSpell(this, itr->second->spellId, true); } } void Player::FailQuest(uint32 questId) { if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId)) { SetQuestStatus(questId, QUEST_STATUS_FAILED); uint16 log_slot = FindQuestSlot(questId); if (log_slot < MAX_QUEST_LOG_SIZE) { SetQuestSlotTimer(log_slot, 1); SetQuestSlotState(log_slot, QUEST_STATE_FAIL); } if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED)) { QuestStatusData& q_status = mQuestStatus[questId]; RemoveTimedQuest(questId); q_status.m_timer = 0; SendQuestTimerFailed(questId); } else SendQuestFailed(questId); } } bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const { uint32 skill = qInfo->GetRequiredSkill(); // skip 0 case RequiredSkill if (skill == 0) return true; // check skill value if (GetSkillValue(skill) < qInfo->GetRequiredSkillValue()) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } return true; } bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg) const { if (getLevel() < qInfo->GetMinLevel()) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } return true; } bool Player::SatisfyQuestLog(bool msg) const { // exist free slot if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE) return true; if (msg) { WorldPacket data(SMSG_QUESTLOG_FULL, 0); GetSession()->SendPacket(&data); DEBUG_LOG("WORLD: Sent SMSG_QUESTLOG_FULL"); } return false; } bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const { // No previous quest (might be first quest in a series) if (qInfo->prevQuests.empty()) return true; for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter) { uint32 prevId = abs(*iter); QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find(prevId); Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId); if (qPrevInfo && i_prevstatus != mQuestStatus.end()) { // If any of the positive previous quests completed, return true if (*iter > 0 && i_prevstatus->second.m_rewarded) { // skip one-from-all exclusive group if (qPrevInfo->GetExclusiveGroup() >= 0) return true; // each-from-all exclusive group ( < 0) // can be start if only all quests in prev quest exclusive group completed and rewarded ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qPrevInfo->GetExclusiveGroup()); MANGOS_ASSERT(bounds.first != bounds.second); // always must be found if qPrevInfo->ExclusiveGroup != 0 for(ExclusiveQuestGroupsMap::const_iterator iter2 = bounds.first; iter2 != bounds.second; ++iter2) { uint32 exclude_Id = iter2->second; // skip checked quest id, only state of other quests in group is interesting if (exclude_Id == prevId) continue; QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find(exclude_Id); // alternative quest from group also must be completed and rewarded(reported) if (i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } } return true; } // If any of the negative previous quests active, return true if (*iter < 0 && IsCurrentQuest(prevId)) { // skip one-from-all exclusive group if (qPrevInfo->GetExclusiveGroup() >= 0) return true; // each-from-all exclusive group ( < 0) // can be start if only all quests in prev quest exclusive group active ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qPrevInfo->GetExclusiveGroup()); MANGOS_ASSERT(bounds.first != bounds.second); // always must be found if qPrevInfo->ExclusiveGroup != 0 for(ExclusiveQuestGroupsMap::const_iterator iter2 = bounds.first; iter2 != bounds.second; ++iter2) { uint32 exclude_Id = iter2->second; // skip checked quest id, only state of other quests in group is interesting if (exclude_Id == prevId) continue; // alternative quest from group also must be active if (!IsCurrentQuest(exclude_Id)) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } } return true; } } } // Has only positive prev. quests in non-rewarded state // and negative prev. quests in non-active state if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const { uint32 reqClass = qInfo->GetRequiredClasses(); if (reqClass == 0) return true; if ((reqClass & getClassMask()) == 0) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } return true; } bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) const { uint32 reqraces = qInfo->GetRequiredRaces(); if (reqraces == 0) return true; if ((reqraces & getRaceMask()) == 0) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE); return false; } return true; } bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) const { uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue()) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue()) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } return true; } bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg) const { QuestStatusMap::const_iterator itr = mQuestStatus.find(qInfo->GetQuestId()); if (itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON); return false; } return true; } bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) const { if (!m_timedquests.empty() && qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED)) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED); return false; } return true; } bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const { // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed if (qInfo->GetExclusiveGroup() <= 0) return true; ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qInfo->GetExclusiveGroup()); MANGOS_ASSERT(bounds.first != bounds.second); // must always be found if qInfo->ExclusiveGroup != 0 for(ExclusiveQuestGroupsMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter) { uint32 exclude_Id = iter->second; // skip checked quest id, only state of other quests in group is interesting if (exclude_Id == qInfo->GetQuestId()) continue; // not allow have daily quest if daily quest from exclusive group already recently completed Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id); if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false)) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find(exclude_Id); // alternative quest already started or completed if (i_exstatus != mQuestStatus.end() && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE)) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } } return true; } bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg) const { if (!qInfo->GetNextQuestInChain()) return true; // next quest in chain already started or completed QuestStatusMap::const_iterator itr = mQuestStatus.find(qInfo->GetNextQuestInChain()); if (itr != mQuestStatus.end() && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE)) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } // check for all quests further up the chain // only necessary if there are quest chains with more than one quest that can be skipped //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg ); return true; } bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg) const { // No previous quest in chain if (qInfo->prevChainQuests.empty()) return true; for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter) { uint32 prevId = *iter; // If any of the previous quests in chain active, return false if (IsCurrentQuest(prevId)) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); return false; } // check for all quests further down the chain // only necessary if there are quest chains with more than one quest that can be skipped //if ( !SatisfyQuestPrevChain( prevId, msg ) ) // return false; } // No previous quest in chain active return true; } bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) const { if (!qInfo->IsDaily()) return true; bool have_slot = false; for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) { uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx); if (qInfo->GetQuestId()==id) return false; if (!id) have_slot = true; } if (!have_slot) { if (msg) SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_TOO_MANY_DAILY_QUESTS); return false; } return true; } bool Player::SatisfyQuestWeek(Quest const* qInfo, bool msg) const { if (!qInfo->IsWeekly() || m_weeklyquests.empty()) return true; // if not found in cooldown list return m_weeklyquests.find(qInfo->GetQuestId()) == m_weeklyquests.end(); } bool Player::SatisfyQuestMonth(Quest const* qInfo, bool msg) const { if (!qInfo->IsMonthly() || m_monthlyquests.empty()) return true; // if not found in cooldown list return m_monthlyquests.find(qInfo->GetQuestId()) == m_monthlyquests.end(); } bool Player::CanGiveQuestSourceItemIfNeed( Quest const *pQuest, ItemPosCountVec* dest) const { if (uint32 srcitem = pQuest->GetSrcItemId()) { uint32 count = pQuest->GetSrcItemCount(); // player already have max amount required item (including bank), just report success uint32 has_count = GetItemCount(srcitem, true); if (has_count >= count) return true; count -= has_count; // real need amount InventoryResult msg; if (!dest) { ItemPosCountVec destTemp; msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, destTemp, srcitem, count ); } else msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, *dest, srcitem, count ); if (msg == EQUIP_ERR_OK) return true; else SendEquipError( msg, NULL, NULL, srcitem ); return false; } return true; } void Player::GiveQuestSourceItemIfNeed(Quest const *pQuest) { ItemPosCountVec dest; if (CanGiveQuestSourceItemIfNeed(pQuest, &dest) && !dest.empty()) { uint32 count = 0; for(ItemPosCountVec::const_iterator c_itr = dest.begin(); c_itr != dest.end(); ++c_itr) count += c_itr->count; Item * item = StoreNewItem(dest, pQuest->GetSrcItemId(), true); SendNewItem(item, count, true, false); } } bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg ) { Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id); if ( qInfo ) { uint32 srcitem = qInfo->GetSrcItemId(); if ( srcitem > 0 ) { uint32 count = qInfo->GetSrcItemCount(); if ( count <= 0 ) count = 1; // exist one case when destroy source quest item not possible: // non un-equippable item (equipped non-empty bag, for example) InventoryResult res = CanUnequipItems(srcitem,count); if (res != EQUIP_ERR_OK) { if (msg) SendEquipError( res, NULL, NULL, srcitem ); return false; } DestroyItemCount(srcitem, count, true, true); } } return true; } bool Player::GetQuestRewardStatus( uint32 quest_id ) const { Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id); if ( qInfo ) { // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id ); if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE && !qInfo->IsRepeatable() ) return itr->second.m_rewarded; return false; } return false; } QuestStatus Player::GetQuestStatus( uint32 quest_id ) const { if ( quest_id ) { QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id ); if ( itr != mQuestStatus.end() ) return itr->second.m_status; } return QUEST_STATUS_NONE; } bool Player::CanShareQuest(uint32 quest_id) const { if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id)) if (qInfo->HasQuestFlag(QUEST_FLAGS_SHARABLE)) return IsCurrentQuest(quest_id); return false; } void Player::SetQuestStatus(uint32 quest_id, QuestStatus status) { if (sObjectMgr.GetQuestTemplate(quest_id)) { QuestStatusData& q_status = mQuestStatus[quest_id]; q_status.m_status = status; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; } UpdateForQuestWorldObjects(); } // not used in MaNGOS, but used in scripting code uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry) { Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id); if ( !qInfo ) return 0; for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) if ( qInfo->ReqCreatureOrGOId[j] == entry ) return mQuestStatus[quest_id].m_creatureOrGOcount[j]; return 0; } void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData ) { if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) { for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { uint32 reqitemcount = pQuest->ReqItemCount[i]; if ( reqitemcount != 0 ) { uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true); questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount); if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED; } } } } uint16 Player::FindQuestSlot( uint32 quest_id ) const { for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) if ( GetQuestSlotQuestId(i) == quest_id ) return i; return MAX_QUEST_LOG_SIZE; } void Player::AreaExploredOrEventHappens( uint32 questId ) { if ( questId ) { uint16 log_slot = FindQuestSlot( questId ); if ( log_slot < MAX_QUEST_LOG_SIZE) { QuestStatusData& q_status = mQuestStatus[questId]; if(!q_status.m_explored) { SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE); SendQuestCompleteEvent(questId); q_status.m_explored = true; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; } } if ( CanCompleteQuest( questId ) ) CompleteQuest( questId ); } } //not used in mangosd, function for external script library void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject ) { if ( Group *pGroup = GetGroup() ) { for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player *pGroupGuy = itr->getSource(); // for any leave or dead (with not released body) group member at appropriate distance if ( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) ) pGroupGuy->AreaExploredOrEventHappens(questId); } } else AreaExploredOrEventHappens(questId); } void Player::ItemAddedQuestCheck( uint32 entry, uint32 count ) { for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { uint32 questid = GetQuestSlotQuestId(i); if ( questid == 0 ) continue; QuestStatusData& q_status = mQuestStatus[questid]; if ( q_status.m_status != QUEST_STATUS_INCOMPLETE ) continue; Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo || !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) continue; for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j) { uint32 reqitem = qInfo->ReqItemId[j]; if ( reqitem == entry ) { uint32 reqitemcount = qInfo->ReqItemCount[j]; uint32 curitemcount = q_status.m_itemcount[j]; if ( curitemcount < reqitemcount ) { uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount); q_status.m_itemcount[j] += additemcount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; } if ( CanCompleteQuest( questid ) ) CompleteQuest( questid ); return; } } } UpdateForQuestWorldObjects(); } void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count ) { for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { uint32 questid = GetQuestSlotQuestId(i); if(!questid) continue; Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if ( !qInfo ) continue; if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) continue; for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j) { uint32 reqitem = qInfo->ReqItemId[j]; if ( reqitem == entry ) { QuestStatusData& q_status = mQuestStatus[questid]; uint32 reqitemcount = qInfo->ReqItemCount[j]; uint32 curitemcount; if ( q_status.m_status != QUEST_STATUS_COMPLETE ) curitemcount = q_status.m_itemcount[j]; else curitemcount = GetItemCount(entry, true); if ( curitemcount < reqitemcount + count ) { uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount); q_status.m_itemcount[j] = curitemcount - remitemcount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; IncompleteQuest( questid ); } return; } } } UpdateForQuestWorldObjects(); } void Player::KilledMonster( CreatureInfo const* cInfo, ObjectGuid guid ) { if (cInfo->Entry) KilledMonsterCredit(cInfo->Entry, guid); for(int i = 0; i < MAX_KILL_CREDIT; ++i) if (cInfo->KillCredit[i]) KilledMonsterCredit(cInfo->KillCredit[i], guid); } void Player::KilledMonsterCredit( uint32 entry, ObjectGuid guid ) { uint32 addkillcount = 1; GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount); for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { uint32 questid = GetQuestSlotQuestId(i); if(!questid) continue; Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) continue; // just if !ingroup || !noraidgroup || raidgroup QuestStatusData& q_status = mQuestStatus[questid]; if (q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid())) { if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_KILL_OR_CAST)) { for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) { // skip GO activate objective or none if (qInfo->ReqCreatureOrGOId[j] <=0) continue; // skip Cast at creature objective if (qInfo->ReqSpell[j] !=0 ) continue; uint32 reqkill = qInfo->ReqCreatureOrGOId[j]; if (reqkill == entry) { uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j]; uint32 curkillcount = q_status.m_creatureOrGOcount[j]; if (curkillcount < reqkillcount) { q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]); } if (CanCompleteQuest( questid )) CompleteQuest( questid ); // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). continue; } } } } } } void Player::CastedCreatureOrGO( uint32 entry, ObjectGuid guid, uint32 spell_id, bool original_caster ) { bool isCreature = guid.IsCreatureOrVehicle(); uint32 addCastCount = 1; for(int i = 0; i < MAX_QUEST_LOG_SIZE; ++i) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) continue; Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) continue; if (!original_caster && !qInfo->HasQuestFlag(QUEST_FLAGS_SHARABLE)) continue; if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_KILL_OR_CAST)) continue; QuestStatusData& q_status = mQuestStatus[questid]; if (q_status.m_status != QUEST_STATUS_INCOMPLETE) continue; for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) { // skip kill creature objective (0) or wrong spell casts if (qInfo->ReqSpell[j] != spell_id) continue; uint32 reqTarget = 0; if (isCreature) { // creature activate objectives if (qInfo->ReqCreatureOrGOId[j] > 0) // checked at quest_template loading reqTarget = qInfo->ReqCreatureOrGOId[j]; } else { // GO activate objective if (qInfo->ReqCreatureOrGOId[j] < 0) // checked at quest_template loading reqTarget = - qInfo->ReqCreatureOrGOId[j]; } // other not this creature/GO related objectives if (reqTarget != entry) continue; uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j]; uint32 curCastCount = q_status.m_creatureOrGOcount[j]; if (curCastCount < reqCastCount) { q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]); } if (CanCompleteQuest(questid)) CompleteQuest(questid); // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). break; } } } void Player::TalkedToCreature( uint32 entry, ObjectGuid guid ) { uint32 addTalkCount = 1; for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { uint32 questid = GetQuestSlotQuestId(i); if(!questid) continue; Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if ( !qInfo ) continue; QuestStatusData& q_status = mQuestStatus[questid]; if ( q_status.m_status == QUEST_STATUS_INCOMPLETE ) { if (qInfo->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO))) { for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) { // skip spell casts and Gameobject objectives if (qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0) continue; uint32 reqTarget = 0; if (qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives // checked at quest_template loading reqTarget = qInfo->ReqCreatureOrGOId[j]; else continue; if ( reqTarget == entry ) { uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j]; uint32 curTalkCount = q_status.m_creatureOrGOcount[j]; if ( curTalkCount < reqTalkCount ) { q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]); } if ( CanCompleteQuest( questid ) ) CompleteQuest( questid ); // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). continue; } } } } } } void Player::MoneyChanged( uint32 count ) { for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) continue; Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if ( qInfo && qInfo->GetRewOrReqMoney() < 0 ) { QuestStatusData& q_status = mQuestStatus[questid]; if ( q_status.m_status == QUEST_STATUS_INCOMPLETE ) { if (int32(count) >= -qInfo->GetRewOrReqMoney()) { if ( CanCompleteQuest( questid ) ) CompleteQuest( questid ); } } else if ( q_status.m_status == QUEST_STATUS_COMPLETE ) { if (int32(count) < -qInfo->GetRewOrReqMoney()) IncompleteQuest( questid ); } } } } void Player::ReputationChanged(FactionEntry const* factionEntry ) { for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { if (uint32 questid = GetQuestSlotQuestId(i)) { if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid)) { if (qInfo->GetRepObjectiveFaction() == factionEntry->ID ) { QuestStatusData& q_status = mQuestStatus[questid]; if ( q_status.m_status == QUEST_STATUS_INCOMPLETE ) { if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue()) if ( CanCompleteQuest( questid ) ) CompleteQuest( questid ); } else if ( q_status.m_status == QUEST_STATUS_COMPLETE ) { if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue()) IncompleteQuest( questid ); } } } } } } bool Player::HasQuestForItem( uint32 itemid ) const { for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { uint32 questid = GetQuestSlotQuestId(i); if ( questid == 0 ) continue; QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid); if (qs_itr == mQuestStatus.end()) continue; QuestStatusData const& q_status = qs_itr->second; if (q_status.m_status == QUEST_STATUS_INCOMPLETE) { Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid); if(!qinfo) continue; // hide quest if player is in raid-group and quest is no raid quest if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid() && !InBattleGround()) continue; // There should be no mixed ReqItem/ReqSource drop // This part for ReqItem drop for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j) { if (itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] ) return true; } // This part - for ReqSource for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j) { // examined item is a source item if (qinfo->ReqSourceId[j] == itemid) { ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid); // 'unique' item if (pProto->MaxCount && (int32)GetItemCount(itemid,true) < pProto->MaxCount) return true; // allows custom amount drop when not 0 if (qinfo->ReqSourceCount[j]) { if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j]) return true; } else if ((int32)GetItemCount(itemid,true) < pProto->Stackable) return true; } } } } return false; } // Used for quests having some event (explore, escort, "external event") as quest objective. void Player::SendQuestCompleteEvent(uint32 quest_id) { if (quest_id) { WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4); data << uint32(quest_id); GetSession()->SendPacket(&data); DEBUG_LOG("WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id); } } void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver ) { uint32 questid = pQuest->GetQuestId(); DEBUG_LOG( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid ); WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) ); data << uint32(questid); if ( getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) ) { data << uint32(XP); data << uint32(pQuest->GetRewOrReqMoney()); } else { data << uint32(0); data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY))); } data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition())); data << uint32(pQuest->GetBonusTalents()); // bonus talents data << uint32(0); // arena points GetSession()->SendPacket( &data ); } void Player::SendQuestFailed( uint32 quest_id, InventoryResult reason) { if ( quest_id ) { WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 ); data << uint32(quest_id); data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message) GetSession()->SendPacket( &data ); DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED"); } } void Player::SendQuestTimerFailed( uint32 quest_id ) { if ( quest_id ) { WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 ); data << uint32(quest_id); GetSession()->SendPacket( &data ); DEBUG_LOG("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER"); } } void Player::SendCanTakeQuestResponse( uint32 msg ) const { WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 ); data << uint32(msg); GetSession()->SendPacket( &data ); DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID"); } void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver) { if (pReceiver) { int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex(); std::string title = pQuest->GetTitle(); sObjectMgr.GetQuestLocaleStrings(pQuest->GetQuestId(), loc_idx, &title); WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + title.size() + 8)); data << uint32(pQuest->GetQuestId()); data << title; data << GetObjectGuid(); pReceiver->GetSession()->SendPacket(&data); DEBUG_LOG("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT"); } } void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg ) { if ( pPlayer ) { WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) ); data << pPlayer->GetObjectGuid(); data << uint8(msg); // valid values: 0-8 GetSession()->SendPacket( &data ); DEBUG_LOG("WORLD: Sent MSG_QUEST_PUSH_RESULT"); } } void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, ObjectGuid guid, uint32 creatureOrGO_idx, uint32 count) { MANGOS_ASSERT(count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)"); int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ]; if (entry < 0) // client expected gameobject template id in form (id|0x80000000) entry = (-entry) | 0x80000000; WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) ); DEBUG_LOG( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" ); data << uint32(pQuest->GetQuestId()); data << uint32(entry); data << uint32(count); data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]); data << guid; GetSession()->SendPacket(&data); uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() ); if (log_slot < MAX_QUEST_LOG_SIZE) SetQuestSlotCounter(log_slot, creatureOrGO_idx, count); } /*********************************************************/ /*** LOAD SYSTEM ***/ /*********************************************************/ void Player::_LoadDeclinedNames(QueryResult* result) { if(!result) return; if (m_declinedname) delete m_declinedname; m_declinedname = new DeclinedName; Field *fields = result->Fetch(); for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i) m_declinedname->name[i] = fields[i].GetCppString(); delete result; } void Player::_LoadArenaTeamInfo(QueryResult *result) { // arenateamid, played_week, played_season, personal_rating memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END); if (!result) return; do { Field *fields = result->Fetch(); uint32 arenateamid = fields[0].GetUInt32(); uint32 played_week = fields[1].GetUInt32(); uint32 played_season = fields[2].GetUInt32(); uint32 wons_season = fields[3].GetUInt32(); uint32 personal_rating = fields[4].GetUInt32(); ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid); if(!aTeam) { sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid); continue; } uint8 arenaSlot = aTeam->GetSlot(); SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenateamid); SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, aTeam->GetType()); SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (aTeam->GetCaptainGuid() == GetObjectGuid()) ? 0 : 1); SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, played_week); SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, played_season); SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, wons_season); SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_PERSONAL_RATING, personal_rating); } while (result->NextRow()); delete result; } void Player::_LoadEquipmentSets(QueryResult *result) { // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, ignore_mask, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid)); if (!result) return; uint32 count = 0; do { Field *fields = result->Fetch(); EquipmentSet eqSet; eqSet.Guid = fields[0].GetUInt64(); uint32 index = fields[1].GetUInt32(); eqSet.Name = fields[2].GetCppString(); eqSet.IconName = fields[3].GetCppString(); eqSet.IgnoreMask = fields[4].GetUInt32(); eqSet.state = EQUIPMENT_SET_UNCHANGED; for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) eqSet.Items[i] = fields[5+i].GetUInt32(); m_EquipmentSets[index] = eqSet; ++count; if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit break; } while (result->NextRow()); delete result; } void Player::_LoadBGData(QueryResult* result) { if (!result) return; // Expecting only one row Field *fields = result->Fetch(); /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */ m_bgData.bgInstanceID = fields[0].GetUInt32(); m_bgData.bgTeam = Team(fields[1].GetUInt32()); m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map fields[2].GetFloat(), // X fields[3].GetFloat(), // Y fields[4].GetFloat(), // Z fields[5].GetFloat()); // Orientation m_bgData.taxiPath[0] = fields[7].GetUInt32(); m_bgData.taxiPath[1] = fields[8].GetUInt32(); m_bgData.mountSpell = fields[9].GetUInt32(); delete result; } bool Player::LoadPositionFromDB(ObjectGuid guid, uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight) { QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'", guid.GetCounter()); if(!result) return false; Field *fields = result->Fetch(); x = fields[0].GetFloat(); y = fields[1].GetFloat(); z = fields[2].GetFloat(); o = fields[3].GetFloat(); mapid = fields[4].GetUInt32(); in_flight = !fields[5].GetCppString().empty(); delete result; return true; } void Player::_LoadIntoDataField(const char* data, uint32 startOffset, uint32 count) { if(!data) return; Tokens tokens(data, ' ', count); if (tokens.size() != count) return; for (uint32 index = 0; index < count; ++index) m_uint32Values[startOffset + index] = atol(tokens[index]); } bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder *holder ) { // 0 1 2 3 4 5 6 7 8 9 10 11 //SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags," // 12 13 14 15 16 17 18 19 20 21 22 23 24 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost," // 25 26 27 28 29 30 31 32 33 34 35 36 37 38 //"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty," // 39 40 41 42 43 44 45 46 47 48 49 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk," // 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid)); QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM); if(!result) { sLog.outError("%s not found in table `characters`, can't load. ", guid.GetString().c_str()); return false; } Field *fields = result->Fetch(); uint32 dbAccountId = fields[1].GetUInt32(); // check if the character's account in the db and the logged in account match. // player should be able to load/delete character only with correct account! if ( dbAccountId != GetSession()->GetAccountId() ) { sLog.outError("%s loading from wrong account (is: %u, should be: %u)", guid.GetString().c_str(), GetSession()->GetAccountId(), dbAccountId); delete result; return false; } Object::_Create(guid); m_name = fields[2].GetCppString(); // check name limitations if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS || (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name))) { delete result; CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME), guid.GetCounter()); return false; } // overwrite possible wrong/corrupted guid SetGuidValue(OBJECT_FIELD_GUID, guid); // overwrite some data fields SetByteValue(UNIT_FIELD_BYTES_0,0,fields[3].GetUInt8());// race SetByteValue(UNIT_FIELD_BYTES_0,1,fields[4].GetUInt8());// class uint8 gender = fields[5].GetUInt8() & 0x01; // allowed only 1 bit values male/female cases (for fit drunk gender part) SetByteValue(UNIT_FIELD_BYTES_0,2,gender); // gender SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8()); SetUInt32Value(PLAYER_XP, fields[7].GetUInt32()); _LoadIntoDataField(fields[60].GetString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE); _LoadIntoDataField(fields[63].GetString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2); InitDisplayIds(); // model, scale and model data SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // just load criteria/achievement data, safe call before any load, and need, because some spell/item/quest loading // can triggering achievement criteria update that will be lost if this call will later m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS)); uint32 money = fields[8].GetUInt32(); if (money > MAX_MONEY_AMOUNT) money = MAX_MONEY_AMOUNT; SetMoney(money); SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32()); SetUInt32Value(PLAYER_BYTES_2, fields[10].GetUInt32()); m_drunk = fields[49].GetUInt16(); SetUInt16Value(PLAYER_BYTES_3, 0, (m_drunk & 0xFFFE) | gender); SetUInt32Value(PLAYER_FLAGS, fields[11].GetUInt32()); SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[48].GetInt32()); SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[47].GetUInt64()); SetUInt32Value(PLAYER_AMMO_ID, fields[62].GetUInt32()); // Action bars state SetByteValue(PLAYER_FIELD_BYTES, 2, fields[64].GetUInt8()); // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory) for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot) { SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid()); SetVisibleItemSlot(slot, NULL); if (m_items[slot]) { delete m_items[slot]; m_items[slot] = NULL; } } DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "Load Basic value of player %s is: ", m_name.c_str()); outDebugStatsValues(); //Need to call it to initialize m_team (m_team can be calculated from race) //Other way is to saves m_team into characters table. setFactionForRace(getRace()); SetCharm(NULL); // load home bind and check in same time class/race pair, it used later for restore broken positions if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND))) { delete result; return false; } InitPrimaryProfessions(); // to max set before any spell loaded // init saved position, and fix it later if problematic uint32 transGUID = fields[30].GetUInt32(); // Relocate(fields[12].GetFloat(),fields[13].GetFloat(),fields[14].GetFloat(),fields[16].GetFloat()); // SetLocationMapId(fields[15].GetUInt32()); WorldLocation savedLocation = WorldLocation(fields[15].GetUInt32(),fields[12].GetFloat(),fields[13].GetFloat(),fields[14].GetFloat(),fields[16].GetFloat()); m_Difficulty = fields[38].GetUInt32(); // may be changed in _LoadGroup if (GetDungeonDifficulty() >= MAX_DUNGEON_DIFFICULTY) SetDungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL); if (GetRaidDifficulty() >= MAX_RAID_DIFFICULTY) SetRaidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL); _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP)); _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO)); SetArenaPoints(fields[39].GetUInt32()); // check arena teams integrity for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) { uint32 arena_team_id = GetArenaTeamId(arena_slot); if (!arena_team_id) continue; if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id)) if (at->HaveMember(GetObjectGuid())) continue; // arena team not exist or not member, cleanup fields for(int j = 0; j < ARENA_TEAM_END; ++j) SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0); } SetHonorPoints(fields[40].GetUInt32()); SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[41].GetUInt32()); SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[42].GetUInt32()); SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[43].GetUInt32()); SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[44].GetUInt16()); SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[45].GetUInt16()); _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES)); MapEntry const* mapEntry = sMapStore.LookupEntry(savedLocation.mapid); if (!mapEntry || !MapManager::IsValidMapCoord(savedLocation) || // client without expansion support GetSession()->Expansion() < mapEntry->Expansion()) { sLog.outError("Player::LoadFromDB player %s have invalid coordinates (map: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid.GetString().c_str(), savedLocation.mapid, savedLocation.coord_x, savedLocation.coord_y, savedLocation.coord_z, savedLocation.orientation); RelocateToHomebind(); GetPosition(savedLocation); // reset saved position to homebind transGUID = 0; m_movementInfo.ClearTransportData(); } _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA)); bool player_at_bg = false; // player bounded instance saves loaded in _LoadBoundInstances, group versions at group loading DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(savedLocation.mapid); Map* targetMap = sMapMgr.FindMap(savedLocation.mapid, state ? state->GetInstanceId() : 0); if (m_bgData.bgInstanceID) //saved in BattleGround { BattleGround* currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE); player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetObjectGuid()); if (player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE) { BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType()); AddBattleGroundQueueId(bgQueueTypeId); m_bgData.bgTypeID = currentBg->GetTypeID(); // bg data not marked as modified //join player to battleground group currentBg->EventPlayerLoggedIn(this, GetObjectGuid()); currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetObjectGuid(), m_bgData.bgTeam); SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID()); } else { // leave bg if (player_at_bg) { currentBg->RemovePlayerAtLeave(GetObjectGuid(), false, true); player_at_bg = false; } // move to bg enter point const WorldLocation& _loc = GetBattleGroundEntryPoint(); SetLocationMapId(_loc.mapid); Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation); // We are not in BG anymore SetBattleGroundId(0, BATTLEGROUND_TYPE_NONE); // remove outdated DB data in DB _SaveBGData(true); } } else { mapEntry = sMapStore.LookupEntry(savedLocation.mapid); // if server restart after player save in BG or area // player can have current coordinates in to BG/Arena map, fix this if(mapEntry->IsBattleGroundOrArena()) { const WorldLocation& _loc = GetBattleGroundEntryPoint(); if (!MapManager::IsValidMapCoord(_loc)) { RelocateToHomebind(); transGUID = 0; m_movementInfo.ClearTransportData(); } else { SetLocationMapId(_loc.mapid); Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation); } // We are not in BG anymore SetBattleGroundId(0, BATTLEGROUND_TYPE_NONE); // remove outdated DB data in DB _SaveBGData(true); } // Cleanup LFG BG data, if char not in dungeon. else if (!mapEntry->IsDungeon()) { _SaveBGData(true); // Saved location checked before SetLocationMapId(savedLocation.mapid); Relocate(savedLocation.coord_x, savedLocation.coord_y, savedLocation.coord_z, savedLocation.orientation); } else if (mapEntry->IsDungeon()) { AreaTrigger const* gt = sObjectMgr.GetGoBackTrigger(savedLocation.mapid); if (gt) { // always put player at goback trigger before porting to instance SetLocationMapId(gt->target_mapId); Relocate(gt->target_X, gt->target_Y, gt->target_Z, gt->target_Orientation); AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(savedLocation.mapid); if (at) { if (CheckTransferPossibility(at)) { if (!state) { SetLocationMapId(at->target_mapId); Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation); } else { SetLocationMapId(savedLocation.mapid); Relocate(savedLocation.coord_x, savedLocation.coord_y, savedLocation.coord_z, savedLocation.orientation); } } else sLog.outError("Player::LoadFromDB %s try logged to instance (map: %u, difficulty %u), but transfer to map impossible. This _might_ be an exploit attempt.", GetObjectGuid().GetString().c_str(), savedLocation.mapid, GetDifficulty()); } else sLog.outError("Player::LoadFromDB %s logged in to a reset instance (map: %u, difficulty %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetObjectGuid().GetString().c_str(), savedLocation.mapid, GetDifficulty()); } else { transGUID = 0; m_movementInfo.ClearTransportData(); RelocateToHomebind(); } } } if (transGUID != 0) { m_movementInfo.SetTransportData(ObjectGuid(HIGHGUID_MO_TRANSPORT,transGUID), fields[26].GetFloat(), fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), 0, -1); if ( !MaNGOS::IsValidMapCoord( GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y, GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) || // transport size limited m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 ) { sLog.outError("%s have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid.GetString().c_str(), GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y, GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o); RelocateToHomebind(); m_movementInfo.ClearTransportData(); transGUID = 0; } } if (transGUID != 0) { for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter) { Transport* transport = *iter; if (transport->GetGUIDLow() == transGUID) { MapEntry const* transMapEntry = sMapStore.LookupEntry(transport->GetMapId()); // client without expansion support if (GetSession()->Expansion() < transMapEntry->Expansion()) { DEBUG_LOG("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), transport->GetMapId()); break; } SetTransport(transport); transport->AddPassenger(this); SetLocationMapId(transport->GetMapId()); break; } } if(!m_transport) { sLog.outError("%s have problems with transport guid (%u). Teleport to default race/class locations.", guid.GetString().c_str(), transGUID); RelocateToHomebind(); m_movementInfo.ClearTransportData(); transGUID = 0; } } // load the player's map here if it's not already loaded if (!GetMap()) { if (Map* map = sMapMgr.CreateMap(GetMapId(), this)) SetMap(map); else RelocateToHomebind(); } SaveRecallPosition(); time_t now = time(NULL); time_t logoutTime = time_t(fields[22].GetUInt64()); // since last logout (in seconds) uint32 time_diff = uint32(now - logoutTime); // set value, including drunk invisibility detection // calculate sobering. after 15 minutes logged out, the player will be sober again float soberFactor; if (time_diff > 15*MINUTE) soberFactor = 0; else soberFactor = 1-time_diff/(15.0f*MINUTE); uint16 newDrunkenValue = uint16(soberFactor* m_drunk); SetDrunkValue(newDrunkenValue); m_cinematic = fields[18].GetUInt32(); m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32(); m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32(); m_resetTalentsCost = fields[24].GetUInt32(); m_resetTalentsTime = time_t(fields[25].GetUInt64()); // reserve some flags uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM ); if ( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) ) SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags); m_taxi.LoadTaxiMask( fields[17].GetString() ); // must be before InitTaxiNodesForLevel uint32 extraflags = fields[31].GetUInt32(); m_stableSlots = fields[32].GetUInt32(); if (m_stableSlots > MAX_PET_STABLES) { sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots)); m_stableSlots = MAX_PET_STABLES; } m_atLoginFlags = fields[33].GetUInt32(); // Honor system // Update Honor kills data m_lastHonorUpdateTime = logoutTime; UpdateHonorFields(); m_deathExpireTime = (time_t)fields[36].GetUInt64(); if (m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP) m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1; std::string taxi_nodes = fields[37].GetCppString(); // clear channel spell data (if saved at channel spell casting) SetChannelObjectGuid(ObjectGuid()); SetUInt32Value(UNIT_CHANNEL_SPELL,0); // clear charm/summon related fields SetCharm(NULL); SetPet(NULL); SetTargetGuid(ObjectGuid()); SetCharmerGuid(ObjectGuid()); SetOwnerGuid(ObjectGuid()); SetCreatorGuid(ObjectGuid()); // reset some aura modifiers before aura apply SetGuidValue(PLAYER_FARSIGHT, ObjectGuid()); SetUInt32Value(PLAYER_TRACK_CREATURES, 0 ); SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 ); // cleanup aura list explicitly before skill load where some spells can be applied RemoveAllAuras(); // make sure the unit is considered out of combat for proper loading ClearInCombat(); // make sure the unit is considered not in duel for proper loading SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid()); SetUInt32Value(PLAYER_DUEL_TEAM, 0); // reset stats before loading any modifiers InitStatsForLevel(); InitGlyphsForLevel(); InitTaxiNodesForLevel(); InitRunes(); // rest bonus can only be calculated after InitStatsForLevel() m_rest_bonus = fields[21].GetFloat(); if (time_diff > 0) { //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour) float bubble0 = 0.031f; //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour) float bubble1 = 0.125f; float bubble = fields[23].GetUInt32() > 0 ? bubble1*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY) : bubble0*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS); SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble); } // load skills after InitStatsForLevel because it triggering aura apply also _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS)); // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods() // Mail _LoadMails(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILS)); _LoadMailedItems(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILEDITEMS)); UpdateNextMailTimeAndUnreads(); m_specsCount = fields[58].GetUInt8(); m_activeSpec = fields[59].GetUInt8(); m_GrantableLevelsCount = fields[65].GetUInt32(); // refer-a-friend flag - maybe wrong and hacky LoadAccountLinkedState(); if (GetAccountLinkedState() != STATE_NOT_LINKED) SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND); // set grant flag if (m_GrantableLevelsCount > 0) SetByteValue(PLAYER_FIELD_BYTES, 1, 0x01); _LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS)); _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff); ApplyGlyphs(true); // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura) if ( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) ) m_deathState = DEAD; _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS)); // after spell load, learn rewarded spell if need also _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS)); _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS)); _LoadWeeklyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADWEEKLYQUESTSTATUS)); _LoadMonthlyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMONTHLYQUESTSTATUS)); _LoadRandomBGStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADRANDOMBG)); _LoadTalents(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS)); // after spell and quest load InitTalentForLevel(); learnDefaultSpells(); // must be before inventory (some items required reputation check) m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION)); _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff); _LoadItemLoot(holder->GetResult(PLAYER_LOGIN_QUERY_LOADITEMLOOT)); // update items with duration and realtime UpdateItemDuration(time_diff, true); _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS)); m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetObjectGuid()); // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded uint32 curTitle = fields[46].GetUInt32(); if (curTitle && !HasTitle(curTitle)) curTitle = 0; SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle); // Not finish taxi flight path if (m_bgData.HasTaxiPath()) { m_taxi.ClearTaxiDestinations(); for (int i = 0; i < 2; ++i) m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]); } else if (!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes, GetTeam())) { // problems with taxi path loading TaxiNodesEntry const* nodeEntry = NULL; if (uint32 node_id = m_taxi.GetTaxiSource()) nodeEntry = sTaxiNodesStore.LookupEntry(node_id); if (!nodeEntry) // don't know taxi start node, to homebind { sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow()); RelocateToHomebind(); } else // have start node, to it { sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow()); SetLocationMapId(nodeEntry->map_id); Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f); } //we can be relocated from taxi and still have an outdated Map pointer! //so we need to get a new Map pointer! if (Map* map = sMapMgr.CreateMap(GetMapId(), this)) SetMap(map); else RelocateToHomebind(); SaveRecallPosition(); // save as recall also to prevent recall and fall from sky m_taxi.ClearTaxiDestinations(); } if (uint32 node_id = m_taxi.GetTaxiSource()) { // save source node as recall coord to prevent recall and fall from sky TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id); MANGOS_ASSERT(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString m_recallMap = nodeEntry->map_id; m_recallX = nodeEntry->x; m_recallY = nodeEntry->y; m_recallZ = nodeEntry->z; // flight will started later } // has to be called after last Relocate() in Player::LoadFromDB SetFallInformation(0, GetPositionZ()); _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS)); // Spell code allow apply any auras to dead character in load time in aura/spell/item loading // Do now before stats re-calculation cleanup for ghost state unexpected auras if(!isAlive()) RemoveAllAurasOnDeath(); //apply all stat bonuses from items and auras SetCanModifyStats(true); UpdateAllStats(); // restore remembered power/health values (but not more max values) uint32 savedhealth = fields[50].GetUInt32(); SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth); for(uint32 i = 0; i < MAX_POWERS; ++i) { uint32 savedpower = fields[51+i].GetUInt32(); SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower); } DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "The value of player %s after load item and aura is: ", m_name.c_str()); outDebugStatsValues(); // all fields read delete result; // GM state if (GetSession()->GetSecurity() > SEC_PLAYER) { switch(sWorld.getConfig(CONFIG_UINT32_GM_LOGIN_STATE)) { default: case 0: break; // disable case 1: SetGameMaster(true); break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_GM_ON) SetGameMaster(true); break; } switch(sWorld.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE)) { default: case 0: SetGMVisible(false); break; // invisible case 1: break; // visible case 2: // save state if (extraflags & PLAYER_EXTRA_GM_INVISIBLE) SetGMVisible(false); break; } switch(sWorld.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS)) { default: case 0: break; // disable case 1: SetAcceptTicket(true); break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS) SetAcceptTicket(true); break; } switch(sWorld.getConfig(CONFIG_UINT32_GM_CHAT)) { default: case 0: break; // disable case 1: SetGMChat(true); break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_GM_CHAT) SetGMChat(true); break; } switch(sWorld.getConfig(CONFIG_UINT32_GM_WISPERING_TO)) { default: case 0: break; // disable case 1: SetAcceptWhispers(true); break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS) SetAcceptWhispers(true); break; } } _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES)); m_achievementMgr.CheckAllAchievementCriteria(); _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS)); if (!GetGroup() || !GetGroup()->isLFDGroup()) { sLFGMgr.RemoveMemberFromLFDGroup(GetGroup(),GetObjectGuid()); } return true; } bool Player::isAllowedToLoot(Creature* creature) { // never tapped by any (mob solo kill) if (!creature->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED)) return false; if (Player* recipient = creature->GetLootRecipient()) { if (recipient == this) return true; if (Group* otherGroup = recipient->GetGroup()) { Group* thisGroup = GetGroup(); if (!thisGroup) return false; return thisGroup == otherGroup; } return false; } else // prevent other players from looting if the recipient got disconnected return !creature->HasLootRecipient(); } void Player::_LoadActions(QueryResult *result) { for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i) m_actionButtons[i].clear(); //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint8 spec = fields[0].GetUInt8(); uint8 button = fields[1].GetUInt8(); uint32 action = fields[2].GetUInt32(); uint8 type = fields[3].GetUInt8(); if (ActionButton* ab = addActionButton(spec, button, action, type)) ab->uState = ACTIONBUTTON_UNCHANGED; else { sLog.outError( " ...at loading, and will deleted in DB also"); // Will deleted in DB at next save (it can create data until save but marked as deleted) m_actionButtons[spec][button].uState = ACTIONBUTTON_DELETED; } } while( result->NextRow() ); delete result; } } void Player::_LoadAuras(QueryResult *result, uint32 timediff) { //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explicitly cleaned early //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,item_guid,spell,stackcount,remaincharges,basepoints0,basepoints1,basepoints2,periodictime0,periodictime1,periodictime2,maxduration,remaintime,effIndexMask FROM character_aura WHERE guid = '%u'",GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); ObjectGuid caster_guid = ObjectGuid(fields[0].GetUInt64()); uint32 item_lowguid = fields[1].GetUInt32(); uint32 spellid = fields[2].GetUInt32(); uint32 stackcount = fields[3].GetUInt32(); uint32 remaincharges = fields[4].GetUInt32(); int32 damage[MAX_EFFECT_INDEX]; uint32 periodicTime[MAX_EFFECT_INDEX]; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { damage[i] = fields[i+5].GetInt32(); periodicTime[i] = fields[i+8].GetUInt32(); } int32 maxduration = fields[11].GetInt32(); int32 remaintime = fields[12].GetInt32(); uint32 effIndexMask = fields[13].GetUInt32(); SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid); if (!spellproto) { sLog.outError("Unknown spell (spellid %u), ignore.",spellid); continue; } if (caster_guid.IsEmpty() || !caster_guid.IsUnit()) { sLog.outError("Player::LoadAuras Unknown caster %u, ignore.",fields[0].GetUInt64()); continue; } if (remaintime != -1 && !IsPositiveSpell(spellproto)) { if (remaintime/IN_MILLISECONDS <= int32(timediff)) continue; remaintime -= timediff*IN_MILLISECONDS; } // prevent wrong values of remaincharges if (spellproto->procCharges == 0) remaincharges = 0; if (!spellproto->StackAmount) stackcount = 1; else if (spellproto->StackAmount < stackcount) stackcount = spellproto->StackAmount; else if (!stackcount) stackcount = 1; SpellAuraHolderPtr holder = CreateSpellAuraHolder(spellproto, this, NULL); holder->SetLoadedState(caster_guid, ObjectGuid(HIGHGUID_ITEM, item_lowguid), stackcount, remaincharges, maxduration, remaintime); for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if ((effIndexMask & (1 << i)) == 0) continue; Aura* aura = holder->CreateAura(spellproto, SpellEffectIndex(i), NULL, holder, this, NULL, NULL); if (!damage[i]) damage[i] = aura->GetModifier()->m_amount; aura->SetLoadedState(damage[i], periodicTime[i]); } if (!holder->IsEmptyHolder()) { // reset stolen single target auras if (caster_guid != GetObjectGuid() && holder->IsSingleTarget()) holder->SetIsSingleTarget(false); AddSpellAuraHolder(holder); DETAIL_LOG("Added auras from spellid %u", spellproto->Id); } } while( result->NextRow() ); delete result; } if (getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true); } void Player::_LoadGlyphs(QueryResult *result) { if(!result) return; // 0 1 2 // "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'" do { Field *fields = result->Fetch(); uint8 spec = fields[0].GetUInt8(); uint8 slot = fields[1].GetUInt8(); uint32 glyph = fields[2].GetUInt32(); GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph); if(!gp) { sLog.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name.c_str(), glyph, slot, spec); continue; } GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(slot)); if (!gs) { sLog.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name.c_str(), GetGlyphSlot(slot), slot, spec); continue; } if (gp->TypeFlags != gs->TypeFlags) { sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags); continue; } m_glyphs[spec][slot].id = glyph; } while( result->NextRow() ); delete result; } void Player::LoadCorpse() { if ( isAlive() ) { sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid()); } else { if (Corpse *corpse = GetCorpse()) { ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() ); } else { //Prevent Dead Player login without corpse ResurrectPlayer(0.5f); } } } void Player::_LoadInventory(QueryResult *result, uint32 timediff) { //QueryResult *result = CharacterDatabase.PQuery("SELECT data,text,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow()); std::map<uint32, Bag*> bagMap; // fast guid lookup for bags //NOTE: the "order by `bag`" is important because it makes sure //the bagMap is filled before items in the bags are loaded //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?) //expected to be equipped before offhand items (TODO: fixme) uint32 zone = GetZoneId(); if (result) { std::list<Item*> problematicItems; // prevent items from being added to the queue when stored m_itemUpdateQueueBlocked = true; do { Field *fields = result->Fetch(); uint32 bag_guid = fields[2].GetUInt32(); uint8 slot = fields[3].GetUInt8(); uint32 item_lowguid = fields[4].GetUInt32(); uint32 item_id = fields[5].GetUInt32(); ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id); if (!proto) { CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid); CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_lowguid); sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id ); continue; } Item *item = NewItemOrBag(proto); if (!item->LoadFromDB(item_lowguid, fields, GetObjectGuid())) { sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id ); CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid); item->FSetState(ITEM_REMOVED); item->SaveToDB(); // it also deletes item object ! continue; } // not allow have in alive state item limited to another map/zone if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone)) { CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid); item->FSetState(ITEM_REMOVED); item->SaveToDB(); // it also deletes item object ! continue; } // "Conjured items disappear if you are logged out for more than 15 minutes" if (timediff > 15*MINUTE && (item->GetProto()->Flags & ITEM_FLAG_CONJURED)) { CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid); item->FSetState(ITEM_REMOVED); item->SaveToDB(); // it also deletes item object ! continue; } if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE)) { QueryResult *result = CharacterDatabase.PQuery("SELECT allowedPlayers FROM item_soulbound_trade_data WHERE itemGuid = '%u'", item->GetGUIDLow()); if (!result) { sLog.outError("Item::LoadFromDB, Item GUID: %u has flag ITEM_FLAG_BOP_TRADEABLE but has no data in item_soulbound_trade_data, removing flag.", item->GetGUIDLow()); item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE); } else { Field* fields2 = result->Fetch(); std::string strGUID = fields2[0].GetCppString(); Tokens GUIDlist(strGUID, ' '); AllowedLooterSet looters; for (Tokens::iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr) looters.insert(atol(*itr)); item->SetSoulboundTradeable(&looters, this, true); m_itemSoulboundTradeable.push_back(item); } } bool success = true; // the item/bag is not in a bag if (!bag_guid) { item->SetContainer( NULL ); item->SetSlot(slot); if (IsInventoryPos( INVENTORY_SLOT_BAG_0, slot)) { ItemPosCountVec dest; if (CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false) == EQUIP_ERR_OK) item = StoreItem(dest, item, true); else success = false; } else if (IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot)) { uint16 dest; if (CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK) QuickEquipItem(dest, item); else success = false; } else if (IsBankPos( INVENTORY_SLOT_BAG_0, slot)) { ItemPosCountVec dest; if (CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK) item = BankItem(dest, item, true); else success = false; } if (success) { // store bags that may contain items in them if (item->IsBag() && IsBagPos(item->GetPos())) bagMap[item_lowguid] = (Bag*)item; } } // the item/bag in a bag else { item->SetSlot(NULL_SLOT); // the item is in a bag, find the bag std::map<uint32, Bag*>::const_iterator itr = bagMap.find(bag_guid); if (itr != bagMap.end() && slot < itr->second->GetBagSize()) { ItemPosCountVec dest; if (CanStoreItem(itr->second->GetSlot(), slot, dest, item, false) == EQUIP_ERR_OK) item = StoreItem(dest, item, true); else success = false; } else success = false; } // item's state may have changed after stored if (success) { item->SetState(ITEM_UNCHANGED, this); // restore container unchanged state also if (item->GetContainer()) item->GetContainer()->SetState(ITEM_UNCHANGED, this); // recharged mana gem if (timediff > 15*MINUTE && proto->ItemLimitCategory ==ITEM_LIMIT_CATEGORY_MANA_GEM) item->RestoreCharges(); } else { sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_lowguid, item_id, bag_guid, slot); CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid); problematicItems.push_back(item); } } while (result->NextRow()); delete result; m_itemUpdateQueueBlocked = false; // send by mail problematic items while(!problematicItems.empty()) { std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM); // fill mail MailDraft draft(subject, "There's were problems with equipping item(s)."); for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i) { Item* item = problematicItems.front(); problematicItems.pop_front(); draft.AddItem(item); } draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED); } } //if (isAlive()) _ApplyAllItemMods(); } void Player::_LoadItemLoot(QueryResult *result) { //QueryResult *result = CharacterDatabase.PQuery("SELECT guid,itemid,amount,suffix,property FROM item_loot WHERE guid = '%u'", GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); Item* item = GetItemByGuid(ObjectGuid(HIGHGUID_ITEM, item_guid)); if (!item) { CharacterDatabase.PExecute("DELETE FROM item_loot WHERE guid = '%u'", item_guid); sLog.outError("Player::_LoadItemLoot: Player %s has loot for nonexistent item (GUID: %u) in `item_loot`, deleted.", GetName(), item_guid ); continue; } item->LoadLootFromDB(fields); } while (result->NextRow()); delete result; } } // load mailed item which should receive current player void Player::_LoadMailedItems(QueryResult *result) { // data needs to be at first place for Item::LoadFromDB // 0 1 2 3 4 // "SELECT data, text, mail_id, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE receiver = '%u'", GUID_LOPART(m_guid) if(!result) return; do { Field *fields = result->Fetch(); uint32 mail_id = fields[2].GetUInt32(); uint32 item_guid_low = fields[3].GetUInt32(); uint32 item_template = fields[4].GetUInt32(); Mail* mail = GetMail(mail_id); if(!mail) continue; mail->AddItem(item_guid_low, item_template); ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template); if(!proto) { sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID); CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low); CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low); continue; } Item *item = NewItemOrBag(proto); if (!item->LoadFromDB(item_guid_low, fields, GetObjectGuid())) { sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low); CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low); item->FSetState(ITEM_REMOVED); item->SaveToDB(); // it also deletes item object ! continue; } AddMItem(item); } while (result->NextRow()); delete result; } void Player::_LoadMails(QueryResult *result) { m_mail.clear(); // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 //"SELECT id,messageType,sender,receiver,subject,body,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId,has_items FROM mail WHERE receiver = '%u' ORDER BY id DESC", GetGUIDLow() if(!result) return; do { Field *fields = result->Fetch(); Mail *m = new Mail; m->messageID = fields[0].GetUInt32(); m->messageType = fields[1].GetUInt8(); m->sender = fields[2].GetUInt32(); m->receiverGuid = ObjectGuid(HIGHGUID_PLAYER, fields[3].GetUInt32()); m->subject = fields[4].GetCppString(); m->body = fields[5].GetCppString(); m->expire_time = (time_t)fields[6].GetUInt64(); m->deliver_time = (time_t)fields[7].GetUInt64(); m->money = fields[8].GetUInt32(); m->COD = fields[9].GetUInt32(); m->checked = fields[10].GetUInt32(); m->stationery = fields[11].GetUInt8(); m->mailTemplateId = fields[12].GetInt16(); m->has_items = fields[13].GetBool(); // true, if mail have items or mail have template and items generated (maybe none) if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId)) { sLog.outError( "Player::_LoadMail - Mail (%u) have nonexistent MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId); m->mailTemplateId = 0; } m->state = MAIL_STATE_UNCHANGED; m_mail.push_back(m); if (m->mailTemplateId && !m->has_items) m->prepareTemplateItems(this); } while( result->NextRow() ); delete result; } void Player::LoadPet() { // fixme: the pet should still be loaded if the player is not in world // just not added to the map if (IsInWorld()) { if (!sWorld.getConfig(CONFIG_BOOL_PET_SAVE_ALL)) { Pet* pet = new Pet; pet->SetPetCounter(0); if(!pet->LoadPetFromDB(this, 0, 0, true)) { delete pet; return; } } else { QueryResult* result = CharacterDatabase.PQuery("SELECT id, PetType, CreatedBySpell, savetime FROM character_pet WHERE owner = '%u' AND entry = (SELECT entry FROM character_pet WHERE owner = '%u' AND slot = '%u') ORDER BY slot ASC", GetGUIDLow(), GetGUIDLow(),PET_SAVE_AS_CURRENT); std::vector<uint32> petnumber; uint32 _PetType = 0; uint32 _CreatedBySpell = 0; uint64 _saveTime = 0; if (result) { do { Field* fields = result->Fetch(); uint32 petnum = fields[0].GetUInt32(); if (petnum) petnumber.push_back(petnum); if (!_PetType) _PetType = fields[1].GetUInt32(); if (!_CreatedBySpell) _CreatedBySpell = fields[2].GetUInt32(); if (!_saveTime) _saveTime = fields[3].GetUInt64(); } while (result->NextRow()); delete result; } else return; if (petnumber.empty()) return; if (_CreatedBySpell != 13481 && !HasSpell(_CreatedBySpell)) return; SpellEntry const* spellInfo = sSpellStore.LookupEntry(_CreatedBySpell); if (!spellInfo) return; uint32 count = 1; if (_CreatedBySpell == 51533 || _CreatedBySpell == 33831) count = spellInfo->CalculateSimpleValue(EFFECT_INDEX_0); petnumber.resize(count); if (GetSpellDuration(spellInfo) > 0) if (uint64(time(NULL)) - GetSpellDuration(spellInfo)/IN_MILLISECONDS > _saveTime) return; if (_CreatedBySpell != 13481 && !HasSpell(_CreatedBySpell)) return; if (!petnumber.empty()) { for(uint8 i = 0; i < petnumber.size(); ++i) { if (petnumber[i] == 0) continue; Pet* _pet = new Pet; _pet->SetPetCounter(petnumber.size() - i - 1); if (!_pet->LoadPetFromDB(this, 0, petnumber[i], true)) delete _pet; } } } } } void Player::_LoadQuestStatus(QueryResult *result) { mQuestStatus.clear(); uint32 slot = 0; //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4, itemcount5, itemcount6 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint32 quest_id = fields[0].GetUInt32(); // used to be new, no delete? Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if ( pQuest ) { // find or create QuestStatusData& questStatusData = mQuestStatus[quest_id]; uint32 qstatus = fields[1].GetUInt32(); if (qstatus < MAX_QUEST_STATUS) questStatusData.m_status = QuestStatus(qstatus); else { questStatusData.m_status = QUEST_STATUS_NONE; sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus); } questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 ); questStatusData.m_explored = ( fields[3].GetUInt8() > 0 ); time_t quest_time = time_t(fields[4].GetUInt64()); if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE) { AddTimedQuest( quest_id ); if (quest_time <= sWorld.GetGameTime()) questStatusData.m_timer = 1; else questStatusData.m_timer = uint32(quest_time - sWorld.GetGameTime()) * IN_MILLISECONDS; } else quest_time = 0; questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32(); questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32(); questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32(); questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32(); questStatusData.m_itemcount[0] = fields[9].GetUInt32(); questStatusData.m_itemcount[1] = fields[10].GetUInt32(); questStatusData.m_itemcount[2] = fields[11].GetUInt32(); questStatusData.m_itemcount[3] = fields[12].GetUInt32(); questStatusData.m_itemcount[4] = fields[13].GetUInt32(); questStatusData.m_itemcount[5] = fields[14].GetUInt32(); questStatusData.uState = QUEST_UNCHANGED; // add to quest log if (slot < MAX_QUEST_LOG_SIZE && ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE || questStatusData.m_status == QUEST_STATUS_COMPLETE || questStatusData.m_status == QUEST_STATUS_FAILED) && (!questStatusData.m_rewarded || pQuest->IsRepeatable()))) { SetQuestSlot(slot, quest_id, uint32(quest_time)); if (questStatusData.m_explored) SetQuestSlotState(slot, QUEST_STATE_COMPLETE); if (questStatusData.m_status == QUEST_STATUS_COMPLETE) SetQuestSlotState(slot, QUEST_STATE_COMPLETE); if (questStatusData.m_status == QUEST_STATUS_FAILED) SetQuestSlotState(slot, QUEST_STATE_FAIL); for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx) if (questStatusData.m_creatureOrGOcount[idx]) SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]); ++slot; } if (questStatusData.m_rewarded) { // learn rewarded spell if unknown learnQuestRewardedSpells(pQuest); // set rewarded title if any if (pQuest->GetCharTitleId()) { if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId())) SetTitle(titleEntry); } if (pQuest->GetBonusTalents()) m_questRewardTalentCount += pQuest->GetBonusTalents(); } DEBUG_LOG("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow()); } } while( result->NextRow() ); delete result; } // clear quest log tail for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i ) SetQuestSlot(i, 0); } void Player::_LoadDailyQuestStatus(QueryResult *result) { for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0); //QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow()); if (result) { uint32 quest_daily_idx = 0; do { if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query { sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow()); break; } Field *fields = result->Fetch(); uint32 quest_id = fields[0].GetUInt32(); Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if ( !pQuest ) continue; SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id); ++quest_daily_idx; DEBUG_LOG("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); } while( result->NextRow() ); delete result; } m_DailyQuestChanged = false; } void Player::_LoadWeeklyQuestStatus(QueryResult *result) { m_weeklyquests.clear(); //QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint32 quest_id = fields[0].GetUInt32(); Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest) continue; m_weeklyquests.insert(quest_id); DEBUG_LOG("Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); } while( result->NextRow() ); delete result; } m_WeeklyQuestChanged = false; } void Player::_LoadMonthlyQuestStatus(QueryResult *result) { m_monthlyquests.clear(); //QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint32 quest_id = fields[0].GetUInt32(); Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest) continue; m_monthlyquests.insert(quest_id); DEBUG_LOG("Monthly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); } while( result->NextRow() ); delete result; } m_MonthlyQuestChanged = false; } void Player::_LoadSpells(QueryResult *result) { //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint32 spell_id = fields[0].GetUInt32(); // skip talents & drop unneeded data if (GetTalentSpellPos(spell_id)) { sLog.outError("Player::_LoadSpells: %s has talent spell %u in character_spell, removing it.", GetGuidStr().c_str(), spell_id); CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'", spell_id); continue; } addSpell(spell_id, fields[1].GetBool(), false, false, fields[2].GetBool()); } while( result->NextRow() ); delete result; } } void Player::_LoadTalents(QueryResult *result) { //QueryResult *result = CharacterDatabase.PQuery("SELECT talent_id, current_rank, spec FROM character_talent WHERE guid = '%u'",GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint32 talent_id = fields[0].GetUInt32(); TalentEntry const* talentInfo = sTalentStore.LookupEntry(talent_id); if (!talentInfo) { sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent_id: %u , this talent will be deleted from character_talent",GetGUIDLow(), talent_id ); CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id); continue; } TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) { sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talentTabInfo: %u for talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentInfo->TalentTab, talentInfo->TalentID ); CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id); continue; } // prevent load talent for different class (cheating) if ((getClassMask() & talentTabInfo->ClassMask) == 0) { sLog.outError("Player::_LoadTalents:Player (GUID: %u) has talent with ClassMask: %u , but Player's ClassMask is: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentTabInfo->ClassMask, getClassMask() ,talentInfo->TalentID ); CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id); continue; } uint32 currentRank = fields[1].GetUInt32(); if (currentRank > MAX_TALENT_RANK || talentInfo->RankID[currentRank] == 0) { sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent rank: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), currentRank, talentInfo->TalentID ); CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id); continue; } uint32 spec = fields[2].GetUInt32(); if (spec > MAX_TALENT_SPEC_COUNT) { sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u, spec will be deleted from character_talent", GetGUIDLow(), spec); CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spec = '%u' ", spec); continue; } if (spec >= m_specsCount) { sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u , this spec will be deleted from character_talent.", GetGUIDLow(), spec); CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND spec = '%u' ", GetGUIDLow(), spec); continue; } if (m_activeSpec == spec) addSpell(talentInfo->RankID[currentRank], true,false,false,false); else { PlayerTalent talent; talent.currentRank = currentRank; talent.talentEntry = talentInfo; talent.state = PLAYERSPELL_UNCHANGED; m_talents[spec][talentInfo->TalentID] = talent; } } while (result->NextRow()); delete result; } } void Player::_LoadGroup(QueryResult *result) { //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow()); if (result) { uint32 groupId = (*result)[0].GetUInt32(); delete result; if (Group* group = sObjectMgr.GetGroupById(groupId)) { uint8 subgroup = group->GetMemberGroup(GetObjectGuid()); SetGroup(group, subgroup); if (getLevel() >= LEVELREQUIREMENT_HEROIC) { // the group leader may change the instance difficulty while the player is offline SetDungeonDifficulty(group->GetDungeonDifficulty()); SetRaidDifficulty(group->GetRaidDifficulty()); } if (group->isLFDGroup()) sLFGMgr.LoadLFDGroupPropertiesForPlayer(this); } } } void Player::_LoadBoundInstances(QueryResult *result) { for(uint8 i = 0; i < MAX_DIFFICULTY; ++i) m_boundInstances[i].clear(); Group *group = GetGroup(); //QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, extend, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid)); if (result) { do { Field *fields = result->Fetch(); bool perm = fields[1].GetBool(); uint32 mapId = fields[2].GetUInt32(); uint32 instanceId = fields[0].GetUInt32(); uint8 difficulty = fields[3].GetUInt8(); bool extend = fields[4].GetBool(); time_t resetTime = (time_t)fields[5].GetUInt64(); // the resettime for normal instances is only saved when the InstanceSave is unloaded // so the value read from the DB may be wrong here but only if the InstanceSave is loaded // and in that case it is not used MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); if(!mapEntry || !mapEntry->IsDungeon()) { sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent or not dungeon map %d", GetName(), GetGUIDLow(), mapId); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId); continue; } if (difficulty >= MAX_DIFFICULTY) { sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId); continue; } MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty)); if(!mapDiff) { sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId); continue; } if(!perm && group) { sLog.outError("_LoadBoundInstances: %s is in group (Id: %d) but has a non-permanent character bind to map %d,%d,%d", GetGuidStr().c_str(), group->GetId(), mapId, instanceId, difficulty); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId); continue; } // since non permanent binds are always solo bind, they can always be reset DungeonPersistentState *state = (DungeonPersistentState*)sMapPersistentStateMgr.AddPersistentState(mapEntry, instanceId, Difficulty(difficulty), resetTime, !perm, true); if (state) BindToInstance(state, perm, true, extend); } while(result->NextRow()); delete result; } } InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty) { // some instances only have one difficulty MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapid,difficulty); if(!mapDiff) return NULL; MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT); BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid); if (itr != m_boundInstances[difficulty].end()) return &itr->second; else return NULL; } void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload) { MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT); BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid); UnbindInstance(itr, difficulty, unload); } void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload) { if (itr != m_boundInstances[difficulty].end()) { if (!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u' AND extend = 0", GetGUIDLow(), itr->second.state->GetInstanceId()); itr->second.state->RemovePlayer(this); // state can become invalid m_boundInstances[difficulty].erase(itr++); } } InstancePlayerBind* Player::BindToInstance(DungeonPersistentState *state, bool permanent, bool load, bool extend) { if (state) { MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT); InstancePlayerBind& bind = m_boundInstances[state->GetDifficulty()][state->GetMapId()]; if (bind.state) { // update the state when the group kills a boss if (permanent != bind.perm || state != bind.state || extend != bind.extend) if (!load) CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u', permanent = '%u', extend ='%u' WHERE guid = '%u' AND instance = '%u'", state->GetInstanceId(), permanent, extend, GetGUIDLow(), bind.state->GetInstanceId()); } else { if (!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent, extend) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), state->GetInstanceId(), permanent, extend); } if (bind.state != state) { if (bind.state) bind.state->RemovePlayer(this); state->AddPlayer(this); } if (permanent) state->SetCanReset(false); bind.state = state; bind.perm = permanent; bind.extend = extend; if (!load) DEBUG_LOG("Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName(), GetGUIDLow(), state->GetMapId(), state->GetInstanceId(), state->GetDifficulty()); return &bind; } else return NULL; } DungeonPersistentState* Player::GetBoundInstanceSaveForSelfOrGroup(uint32 mapid) { MapEntry const* mapEntry = sMapStore.LookupEntry(mapid); if (!mapEntry) return NULL; InstancePlayerBind *pBind = GetBoundInstance(mapid, GetDifficulty(mapEntry->IsRaid())); DungeonPersistentState *state = pBind ? pBind->state : NULL; // the player's permanent player bind is taken into consideration first // then the player's group bind and finally the solo bind. if (!pBind || !pBind->perm) { InstanceGroupBind *groupBind = NULL; // use the player's difficulty setting (it may not be the same as the group's) if (Group *group = GetGroup()) if (groupBind = group->GetBoundInstance(mapid, this)) state = groupBind->state; } return state; } void Player::BindToInstance() { WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4); data << uint32(0); GetSession()->SendPacket(&data); BindToInstance(_pendingBind, true); } void Player::SendRaidInfo() { uint32 counter = 0; WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4); size_t p_counter = data.wpos(); data << uint32(counter); // placeholder time_t now = time(NULL); for(int i = 0; i < MAX_DIFFICULTY; ++i) { for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) { if (itr->second.perm) { DungeonPersistentState* state = itr->second.state; data << uint32(state->GetMapId()); // map id data << uint32(state->GetDifficulty()); // difficulty data << ObjectGuid(state->GetInstanceGuid()); // instance guid data << uint8((state->GetRealResetTime() > now) ? 1 : 0 ); // expired = 0 data << uint8(itr->second.extend ? 1 : 0); // extended = 1 data << uint32(state->GetRealResetTime() > now ? state->GetRealResetTime() - now : DungeonResetScheduler::CalculateNextResetTime(GetMapDifficultyData(state->GetMapId(), state->GetDifficulty()))); // reset time ++counter; } } } data.put<uint32>(p_counter, counter); GetSession()->SendPacket(&data); } /* - called on every successful teleportation to a map */ void Player::SendSavedInstances() { bool hasBeenSaved = false; WorldPacket data; for(uint8 i = 0; i < MAX_DIFFICULTY; ++i) { for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) { if (itr->second.perm) // only permanent binds are sent { hasBeenSaved = true; break; } } } //Send opcode 811. true or false means, whether you have current raid/heroic instances data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP); data << uint32(hasBeenSaved); GetSession()->SendPacket(&data); if(!hasBeenSaved) return; for(uint8 i = 0; i < MAX_DIFFICULTY; ++i) { for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) { if (itr->second.perm) { data.Initialize(SMSG_UPDATE_LAST_INSTANCE); data << uint32(itr->second.state->GetMapId()); GetSession()->SendPacket(&data); } } } } /// convert the player's binds to the group void Player::ConvertInstancesToGroup(Player *player, Group *group, ObjectGuid player_guid) { bool has_binds = false; bool has_solo = false; if (player) { player_guid = player->GetObjectGuid(); if (!group) group = player->GetGroup(); } MANGOS_ASSERT(player_guid); // copy all binds to the group, when changing leader it's assumed the character // will not have any solo binds if (player) { for(uint8 i = 0; i < MAX_DIFFICULTY; ++i) { for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();) { has_binds = true; if (group) group->BindToInstance(itr->second.state, itr->second.perm, true); // permanent binds are not removed if (!itr->second.perm) { // increments itr in call player->UnbindInstance(itr, Difficulty(i), true); has_solo = true; } else ++itr; } } } uint32 player_lowguid = player_guid.GetCounter(); // if the player's not online we don't know what binds it has if (!player || !group || has_binds) CharacterDatabase.PExecute("REPLACE INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", player_lowguid); // the following should not get executed when changing leaders if (!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND permanent = 0 AND extend = 0", player_lowguid); } bool Player::_LoadHomeBind(QueryResult *result) { PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass()); if(!info) { sLog.outError("Player have incorrect race/class pair. Can't be loaded."); return false; } bool ok = false; //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid)); if (result) { Field *fields = result->Fetch(); m_homebindMapId = fields[0].GetUInt32(); m_homebindAreaId = fields[1].GetUInt16(); m_homebindX = fields[2].GetFloat(); m_homebindY = fields[3].GetFloat(); m_homebindZ = fields[4].GetFloat(); delete result; MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId); // accept saved data only for valid position (and non instanceable), and accessable if ( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) && !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion()) { ok = true; } else CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow()); } if(!ok) { m_homebindMapId = info->mapId; m_homebindAreaId = info->areaId; m_homebindX = info->positionX; m_homebindY = info->positionY; m_homebindZ = info->positionZ; CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ); } DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f", m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ); return true; } /*********************************************************/ /*** SAVE SYSTEM ***/ /*********************************************************/ void Player::SaveToDB() { // we should assure this: ASSERT((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE))); // delay auto save at any saves (manual, in code, or autosave) m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE); //lets allow only players in world to be saved if (IsBeingTeleportedFar()) { ScheduleDelayedOperation(DELAYED_SAVE_PLAYER); return; } // first save/honor gain after midnight will also update the player's honor fields UpdateHonorFields(); DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "The value of player %s at save: ", m_name.c_str()); outDebugStatsValues(); CharacterDatabase.BeginTransaction(); static SqlStatementID delChar ; static SqlStatementID insChar ; SqlStatement stmt = CharacterDatabase.CreateStatement(delChar, "DELETE FROM characters WHERE guid = ?"); stmt.PExecute(GetGUIDLow()); SqlStatement uberInsert = CharacterDatabase.CreateStatement(insChar, "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags," "map, dungeon_difficulty, position_x, position_y, position_z, orientation, " "taximask, online, cinematic, " "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, " "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, " "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, " "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, " "power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " "?, ?, ?, ?, ?, ?, " "?, ?, ?, " "?, ?, ?, ?, ?, ?, ?, " "?, ?, ?, ?, ?, ?, ?, ?, ?, " "?, ?, ?, ?, ?, ?, ?, " "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "); uberInsert.addUInt32(GetGUIDLow()); uberInsert.addUInt32(GetSession()->GetAccountId()); uberInsert.addString(m_name); uberInsert.addUInt8(getRace()); uberInsert.addUInt8(getClass()); uberInsert.addUInt8(getGender()); uberInsert.addUInt32(getLevel()); uberInsert.addUInt32(GetUInt32Value(PLAYER_XP)); uberInsert.addUInt32(GetMoney()); uberInsert.addUInt32(GetUInt32Value(PLAYER_BYTES)); uberInsert.addUInt32(GetUInt32Value(PLAYER_BYTES_2)); uberInsert.addUInt32(GetUInt32Value(PLAYER_FLAGS)); if(!IsBeingTeleported()) { uberInsert.addUInt32(GetMapId()); uberInsert.addUInt32(GetDifficulty()); uberInsert.addFloat(finiteAlways(GetPositionX())); uberInsert.addFloat(finiteAlways(GetPositionY())); uberInsert.addFloat(finiteAlways(GetPositionZ())); uberInsert.addFloat(finiteAlways(GetOrientation())); } else { uberInsert.addUInt32(GetTeleportDest().mapid); uberInsert.addUInt32(GetDifficulty()); uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_x)); uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_y)); uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_z)); uberInsert.addFloat(finiteAlways(GetTeleportDest().orientation)); } std::ostringstream ss; ss << m_taxi; // string with TaxiMaskSize numbers uberInsert.addString(ss); uberInsert.addUInt32(IsInWorld() ? 1 : 0); uberInsert.addUInt32(m_cinematic); uberInsert.addUInt32(m_Played_time[PLAYED_TIME_TOTAL]); uberInsert.addUInt32(m_Played_time[PLAYED_TIME_LEVEL]); uberInsert.addFloat(finiteAlways(m_rest_bonus)); uberInsert.addUInt64(uint64(time(NULL))); uberInsert.addUInt32(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0); //save, far from tavern/city //save, but in tavern/city uberInsert.addUInt32(m_resetTalentsCost); uberInsert.addUInt64(uint64(m_resetTalentsTime)); uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->x)); uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->y)); uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->z)); uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->o)); if (m_transport) uberInsert.addUInt32(m_transport->GetGUIDLow()); else uberInsert.addUInt32(0); uberInsert.addUInt32(m_ExtraFlags); uberInsert.addUInt32(uint32(m_stableSlots)); // to prevent save uint8 as char uberInsert.addUInt32(uint32(m_atLoginFlags)); uberInsert.addUInt32(IsInWorld() ? GetZoneId() : GetCachedZoneId()); uberInsert.addUInt64(uint64(m_deathExpireTime)); ss << m_taxi.SaveTaxiDestinationsToString(); //string uberInsert.addString(ss); uberInsert.addUInt32(GetArenaPoints()); uberInsert.addUInt32(GetHonorPoints()); uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) ); uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION)); uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS)); uberInsert.addUInt16(GetUInt16Value(PLAYER_FIELD_KILLS, 0)); uberInsert.addUInt16(GetUInt16Value(PLAYER_FIELD_KILLS, 1)); uberInsert.addUInt32(GetUInt32Value(PLAYER_CHOSEN_TITLE)); uberInsert.addUInt64(GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES)); // FIXME: at this moment send to DB as unsigned, including unit32(-1) uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX)); uberInsert.addUInt16(uint16(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE)); uberInsert.addUInt32(GetHealth()); for(uint32 i = 0; i < MAX_POWERS; ++i) uberInsert.addUInt32(GetPower(Powers(i))); uberInsert.addUInt32(uint32(m_specsCount)); uberInsert.addUInt32(uint32(m_activeSpec)); for(uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i ) //string { ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << " "; } uberInsert.addString(ss); for(uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i ) //string { ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << " "; } uberInsert.addString(ss); uberInsert.addUInt32(GetUInt32Value(PLAYER_AMMO_ID)); for(uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i ) //string { ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << " "; } uberInsert.addString(ss); uberInsert.addUInt32(uint32(GetByteValue(PLAYER_FIELD_BYTES, 2))); uberInsert.addUInt32(uint32(m_GrantableLevelsCount)); uberInsert.Execute(); if (m_mailsUpdated) //save mails only when needed _SaveMail(); _SaveBGData(); _SaveInventory(); _SaveQuestStatus(); _SaveDailyQuestStatus(); _SaveWeeklyQuestStatus(); _SaveMonthlyQuestStatus(); _SaveSpells(); _SaveSpellCooldowns(); _SaveActions(); _SaveAuras(); _SaveSkills(); m_achievementMgr.SaveToDB(); m_reputationMgr.SaveToDB(); _SaveEquipmentSets(); GetSession()->SaveTutorialsData(); // changed only while character in game _SaveGlyphs(); _SaveTalents(); CharacterDatabase.CommitTransaction(); // check if stats should only be saved on logout // save stats can be out of transaction if (m_session->isLogingOut() || !sWorld.getConfig(CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT)) _SaveStats(); // save pet (hunter pet level and experience and all type pets health/mana). if (Pet* pet = GetPet()) pet->SavePetToDB(PET_SAVE_AS_CURRENT); } // fast save function for item/money cheating preventing - save only inventory and money state void Player::SaveInventoryAndGoldToDB() { _SaveInventory(); SaveGoldToDB(); } void Player::SaveGoldToDB() { static SqlStatementID updateGold ; SqlStatement stmt = CharacterDatabase.CreateStatement(updateGold, "UPDATE characters SET money = ? WHERE guid = ?"); stmt.PExecute(GetMoney(), GetGUIDLow()); } void Player::_SaveActions() { static SqlStatementID insertAction ; static SqlStatementID updateAction ; static SqlStatementID deleteAction ; for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i) { for(ActionButtonList::iterator itr = m_actionButtons[i].begin(); itr != m_actionButtons[i].end(); ) { switch (itr->second.uState) { case ACTIONBUTTON_NEW: { SqlStatement stmt = CharacterDatabase.CreateStatement(insertAction, "INSERT INTO character_action (guid,spec, button,action,type) VALUES (?, ?, ?, ?, ?)"); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(i); stmt.addUInt32(uint32(itr->first)); stmt.addUInt32(itr->second.GetAction()); stmt.addUInt32(uint32(itr->second.GetType())); stmt.Execute(); itr->second.uState = ACTIONBUTTON_UNCHANGED; ++itr; } break; case ACTIONBUTTON_CHANGED: { SqlStatement stmt = CharacterDatabase.CreateStatement(updateAction, "UPDATE character_action SET action = ?, type = ? WHERE guid = ? AND button = ? AND spec = ?"); stmt.addUInt32(itr->second.GetAction()); stmt.addUInt32(uint32(itr->second.GetType())); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(uint32(itr->first)); stmt.addUInt32(i); stmt.Execute(); itr->second.uState = ACTIONBUTTON_UNCHANGED; ++itr; } break; case ACTIONBUTTON_DELETED: { SqlStatement stmt = CharacterDatabase.CreateStatement(deleteAction, "DELETE FROM character_action WHERE guid = ? AND button = ? AND spec = ?"); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(uint32(itr->first)); stmt.addUInt32(i); stmt.Execute(); m_actionButtons[i].erase(itr++); } break; default: ++itr; break; } } } } void Player::_SaveAuras() { static SqlStatementID deleteAuras ; static SqlStatementID insertAuras ; MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS); SqlStatement stmt = CharacterDatabase.CreateStatement(deleteAuras, "DELETE FROM character_aura WHERE guid = ?"); stmt.PExecute(GetGUIDLow()); SpellAuraHolderMap const& auraHolders = GetSpellAuraHolderMap(); if (auraHolders.empty()) return; stmt = CharacterDatabase.CreateStatement(insertAuras, "INSERT INTO character_aura (guid, caster_guid, item_guid, spell, stackcount, remaincharges, " "basepoints0, basepoints1, basepoints2, periodictime0, periodictime1, periodictime2, maxduration, remaintime, effIndexMask) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); for(SpellAuraHolderMap::const_iterator itr = auraHolders.begin(); itr != auraHolders.end(); ++itr) { //skip all holders from spells that are passive or channeled //do not save single target holders (unless they were cast by the player) if (itr->second && !itr->second->IsDeleted() && !itr->second->IsPassive() && !IsChanneledSpell(itr->second->GetSpellProto()) && (itr->second->GetCasterGuid() == GetObjectGuid() || !itr->second->IsSingleTarget()) && !IsChanneledSpell(itr->second->GetSpellProto())) { int32 damage[MAX_EFFECT_INDEX]; uint32 periodicTime[MAX_EFFECT_INDEX]; uint32 effIndexMask = 0; for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) { damage[i] = 0; periodicTime[i] = 0; if (Aura *aur = itr->second->GetAuraByEffectIndex(SpellEffectIndex(i))) { // don't save not own area auras if (aur->IsAreaAura() && itr->second->GetCasterGuid() != GetObjectGuid()) continue; damage[i] = aur->GetModifier()->m_amount; periodicTime[i] = aur->GetModifier()->periodictime; effIndexMask |= (1 << i); } } if (!effIndexMask) continue; stmt.addUInt32(GetGUIDLow()); stmt.addUInt64(itr->second->GetCasterGuid().GetRawValue()); stmt.addUInt32(itr->second->GetCastItemGuid().GetCounter()); stmt.addUInt32(itr->second->GetId()); stmt.addUInt32(itr->second->GetStackAmount()); stmt.addUInt8(itr->second->GetAuraCharges()); for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) stmt.addInt32(damage[i]); for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) stmt.addUInt32(periodicTime[i]); stmt.addInt32(itr->second->GetAuraMaxDuration()); stmt.addInt32(itr->second->GetAuraDuration()); stmt.addUInt32(effIndexMask); stmt.Execute(); } } } void Player::_SaveGlyphs() { static SqlStatementID insertGlyph ; static SqlStatementID updateGlyph ; static SqlStatementID deleteGlyph ; for (uint8 spec = 0; spec < m_specsCount; ++spec) { for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot) { switch(m_glyphs[spec][slot].uState) { case GLYPH_NEW: { SqlStatement stmt = CharacterDatabase.CreateStatement(insertGlyph, "INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES (?, ?, ?, ?)"); stmt.PExecute(GetGUIDLow(), spec, slot, m_glyphs[spec][slot].GetId()); } break; case GLYPH_CHANGED: { SqlStatement stmt = CharacterDatabase.CreateStatement(updateGlyph, "UPDATE character_glyphs SET glyph = ? WHERE guid = ? AND spec = ? AND slot = ?"); stmt.PExecute(m_glyphs[spec][slot].GetId(), GetGUIDLow(), spec, slot); } break; case GLYPH_DELETED: { SqlStatement stmt = CharacterDatabase.CreateStatement(deleteGlyph, "DELETE FROM character_glyphs WHERE guid = ? AND spec = ? AND slot = ?"); stmt.PExecute(GetGUIDLow(), spec, slot); } break; case GLYPH_UNCHANGED: break; } m_glyphs[spec][slot].uState = GLYPH_UNCHANGED; } } } void Player::_SaveInventory() { // force items in buyback slots to new state // and remove those that aren't already for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i) { Item *item = m_items[i]; if (!item || item->GetState() == ITEM_NEW) continue; static SqlStatementID delInv ; static SqlStatementID delItemInst ; SqlStatement stmt = CharacterDatabase.CreateStatement(delInv, "DELETE FROM character_inventory WHERE item = ?"); stmt.PExecute(item->GetGUIDLow()); stmt = CharacterDatabase.CreateStatement(delItemInst, "DELETE FROM item_instance WHERE guid = ?"); stmt.PExecute(item->GetGUIDLow()); m_items[i]->FSetState(ITEM_NEW); } // update enchantment durations for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr) { itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration); } // if no changes if (m_itemUpdateQueue.empty()) return; // do not save if the update queue is corrupt bool error = false; for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i) { Item *item = m_itemUpdateQueue[i]; if(!item || item->GetState() == ITEM_REMOVED) continue; Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot()); GetAntiCheat()->DoAntiCheatCheck(CHECK_ITEM_UPDATE,item,test); if (test == NULL) { sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow()); error = true; } else if (test != item) { sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow()); error = true; } } if (error) { sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!"); ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED); return; } static SqlStatementID insertInventory ; static SqlStatementID updateInventory ; static SqlStatementID deleteInventory ; for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i) { Item *item = m_itemUpdateQueue[i]; if(!item) continue; Bag *container = item->GetContainer(); uint32 bag_guid = container ? container->GetGUIDLow() : 0; switch(item->GetState()) { case ITEM_NEW: { SqlStatement stmt = CharacterDatabase.CreateStatement(insertInventory, "INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES (?, ?, ?, ?, ?)"); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(bag_guid); stmt.addUInt8(item->GetSlot()); stmt.addUInt32(item->GetGUIDLow()); stmt.addUInt32(item->GetEntry()); stmt.Execute(); } break; case ITEM_CHANGED: { SqlStatement stmt = CharacterDatabase.CreateStatement(updateInventory, "UPDATE character_inventory SET guid = ?, bag = ?, slot = ?, item_template = ? WHERE item = ?"); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(bag_guid); stmt.addUInt8(item->GetSlot()); stmt.addUInt32(item->GetEntry()); stmt.addUInt32(item->GetGUIDLow()); stmt.Execute(); } break; case ITEM_REMOVED: { SqlStatement stmt = CharacterDatabase.CreateStatement(deleteInventory, "DELETE FROM character_inventory WHERE item = ?"); stmt.PExecute(item->GetGUIDLow()); } break; case ITEM_UNCHANGED: break; } item->SaveToDB(); // item have unchanged inventory record and can be save standalone } m_itemUpdateQueue.clear(); } void Player::_SaveMail() { static SqlStatementID updateMail ; static SqlStatementID deleteMailItems ; static SqlStatementID deleteItem ; static SqlStatementID deleteMain ; static SqlStatementID deleteItems ; for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) { Mail *m = (*itr); if (m->state == MAIL_STATE_CHANGED) { SqlStatement stmt = CharacterDatabase.CreateStatement(updateMail, "UPDATE mail SET has_items = ?, expire_time = ?, deliver_time = ?, money = ?, cod = ?, checked = ? WHERE id = ?"); stmt.addUInt32(m->HasItems() ? 1 : 0); stmt.addUInt64(uint64(m->expire_time)); stmt.addUInt64(uint64(m->deliver_time)); stmt.addUInt32(m->money); stmt.addUInt32(m->COD); stmt.addUInt32(m->checked); stmt.addUInt32(m->messageID); stmt.Execute(); if (m->removedItems.size()) { stmt = CharacterDatabase.CreateStatement(deleteMailItems, "DELETE FROM mail_items WHERE item_guid = ?"); for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2) stmt.PExecute(*itr2); m->removedItems.clear(); } m->state = MAIL_STATE_UNCHANGED; } else if (m->state == MAIL_STATE_DELETED) { if (m->HasItems()) { SqlStatement stmt = CharacterDatabase.CreateStatement(deleteItem, "DELETE FROM item_instance WHERE guid = ?"); for(MailItemInfoVec::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2) stmt.PExecute(itr2->item_guid); } SqlStatement stmt = CharacterDatabase.CreateStatement(deleteMain, "DELETE FROM mail WHERE id = ?"); stmt.PExecute(m->messageID); stmt = CharacterDatabase.CreateStatement(deleteItems, "DELETE FROM mail_items WHERE mail_id = ?"); stmt.PExecute(m->messageID); } } //deallocate deleted mails... for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ) { if ((*itr)->state == MAIL_STATE_DELETED) { Mail* m = *itr; m_mail.erase(itr); delete m; itr = m_mail.begin(); } else ++itr; } m_mailsUpdated = false; } void Player::_SaveQuestStatus() { static SqlStatementID insertQuestStatus ; static SqlStatementID updateQuestStatus ; // we don't need transactions here. for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i ) { switch (i->second.uState) { case QUEST_NEW : { SqlStatement stmt = CharacterDatabase.CreateStatement(insertQuestStatus, "INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4,itemcount5,itemcount6) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(i->first); stmt.addUInt8(i->second.m_status); stmt.addUInt8(i->second.m_rewarded); stmt.addUInt8(i->second.m_explored); stmt.addUInt64(uint64(i->second.m_timer / IN_MILLISECONDS+ sWorld.GetGameTime())); for (int k = 0; k < QUEST_OBJECTIVES_COUNT; ++k) stmt.addUInt32(i->second.m_creatureOrGOcount[k]); for (int k = 0; k < QUEST_ITEM_OBJECTIVES_COUNT; ++k) stmt.addUInt32(i->second.m_itemcount[k]); stmt.Execute(); } break; case QUEST_CHANGED : { SqlStatement stmt = CharacterDatabase.CreateStatement(updateQuestStatus, "UPDATE character_queststatus SET status = ?,rewarded = ?,explored = ?,timer = ?," "mobcount1 = ?,mobcount2 = ?,mobcount3 = ?,mobcount4 = ?,itemcount1 = ?,itemcount2 = ?,itemcount3 = ?,itemcount4 = ?,itemcount5 = ?,itemcount6 = ? WHERE guid = ? AND quest = ?"); stmt.addUInt8(i->second.m_status); stmt.addUInt8(i->second.m_rewarded); stmt.addUInt8(i->second.m_explored); stmt.addUInt64(uint64(i->second.m_timer / IN_MILLISECONDS + sWorld.GetGameTime())); for (int k = 0; k < QUEST_OBJECTIVES_COUNT; ++k) stmt.addUInt32(i->second.m_creatureOrGOcount[k]); for (int k = 0; k < QUEST_ITEM_OBJECTIVES_COUNT; ++k) stmt.addUInt32(i->second.m_itemcount[k]); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(i->first); stmt.Execute(); } break; case QUEST_UNCHANGED: break; }; i->second.uState = QUEST_UNCHANGED; } } void Player::_SaveDailyQuestStatus() { if (!m_DailyQuestChanged) return; // we don't need transactions here. static SqlStatementID delQuestStatus ; static SqlStatementID insQuestStatus ; SqlStatement stmtDel = CharacterDatabase.CreateStatement(delQuestStatus, "DELETE FROM character_queststatus_daily WHERE guid = ?"); SqlStatement stmtIns = CharacterDatabase.CreateStatement(insQuestStatus, "INSERT INTO character_queststatus_daily (guid,quest) VALUES (?, ?)"); stmtDel.PExecute(GetGUIDLow()); for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx)) stmtIns.PExecute(GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx)); m_DailyQuestChanged = false; } void Player::_SaveWeeklyQuestStatus() { if (!m_WeeklyQuestChanged || m_weeklyquests.empty()) return; // we don't need transactions here. static SqlStatementID delQuestStatus ; static SqlStatementID insQuestStatus ; SqlStatement stmtDel = CharacterDatabase.CreateStatement(delQuestStatus, "DELETE FROM character_queststatus_weekly WHERE guid = ?"); SqlStatement stmtIns = CharacterDatabase.CreateStatement(insQuestStatus, "INSERT INTO character_queststatus_weekly (guid,quest) VALUES (?, ?)"); stmtDel.PExecute(GetGUIDLow()); for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter) { uint32 quest_id = *iter; stmtIns.PExecute(GetGUIDLow(), quest_id); } m_WeeklyQuestChanged = false; } void Player::_SaveMonthlyQuestStatus() { if (!m_MonthlyQuestChanged || m_monthlyquests.empty()) return; // we don't need transactions here. static SqlStatementID deleteQuest ; static SqlStatementID insertQuest ; SqlStatement stmtDel = CharacterDatabase.CreateStatement(deleteQuest, "DELETE FROM character_queststatus_monthly WHERE guid = ?"); SqlStatement stmtIns = CharacterDatabase.CreateStatement(insertQuest, "INSERT INTO character_queststatus_monthly (guid, quest) VALUES (?, ?)"); stmtDel.PExecute(GetGUIDLow()); for (QuestSet::const_iterator iter = m_monthlyquests.begin(); iter != m_monthlyquests.end(); ++iter) { uint32 quest_id = *iter; stmtIns.PExecute(GetGUIDLow(), quest_id); } m_MonthlyQuestChanged = false; } void Player::_SaveSkills() { static SqlStatementID delSkills ; static SqlStatementID insSkills ; static SqlStatementID updSkills ; // we don't need transactions here. for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ) { if (itr->second.uState == SKILL_UNCHANGED) { ++itr; continue; } if (itr->second.uState == SKILL_DELETED) { SqlStatement stmt = CharacterDatabase.CreateStatement(delSkills, "DELETE FROM character_skills WHERE guid = ? AND skill = ?"); stmt.PExecute(GetGUIDLow(), itr->first ); mSkillStatus.erase(itr++); continue; } uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)); uint16 value = SKILL_VALUE(valueData); uint16 max = SKILL_MAX(valueData); switch (itr->second.uState) { case SKILL_NEW: { SqlStatement stmt = CharacterDatabase.CreateStatement(insSkills, "INSERT INTO character_skills (guid, skill, value, max) VALUES (?, ?, ?, ?)"); stmt.PExecute(GetGUIDLow(), itr->first, value, max); } break; case SKILL_CHANGED: { SqlStatement stmt = CharacterDatabase.CreateStatement(updSkills, "UPDATE character_skills SET value = ?, max = ? WHERE guid = ? AND skill = ?"); stmt.PExecute(value, max, GetGUIDLow(), itr->first ); } break; case SKILL_UNCHANGED: case SKILL_DELETED: MANGOS_ASSERT(false); break; }; itr->second.uState = SKILL_UNCHANGED; ++itr; } } void Player::_SaveSpells() { static SqlStatementID delSpells ; static SqlStatementID insSpells ; SqlStatement stmtDel = CharacterDatabase.CreateStatement(delSpells, "DELETE FROM character_spell WHERE guid = ? and spell = ?"); SqlStatement stmtIns = CharacterDatabase.CreateStatement(insSpells, "INSERT INTO character_spell (guid,spell,active,disabled) VALUES (?, ?, ?, ?)"); for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();) { uint32 talentCosts = GetTalentSpellCost(itr->first); if (!talentCosts) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED) stmtDel.PExecute(GetGUIDLow(), itr->first); // add only changed/new not dependent spells if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED)) stmtIns.PExecute(GetGUIDLow(), itr->first, uint8(itr->second.active ? 1 : 0), uint8(itr->second.disabled ? 1 : 0)); } if (itr->second.state == PLAYERSPELL_REMOVED) m_spells.erase(itr++); else { itr->second.state = PLAYERSPELL_UNCHANGED; ++itr; } } } void Player::_SaveTalents() { static SqlStatementID delTalents ; static SqlStatementID insTalents ; SqlStatement stmtDel = CharacterDatabase.CreateStatement(delTalents, "DELETE FROM character_talent WHERE guid = ? and talent_id = ? and spec = ?"); SqlStatement stmtIns = CharacterDatabase.CreateStatement(insTalents, "INSERT INTO character_talent (guid, talent_id, current_rank , spec) VALUES (?, ?, ?, ?)"); for (uint32 i = 0; i < MAX_TALENT_SPEC_COUNT; ++i) { for (PlayerTalentMap::iterator itr = m_talents[i].begin(); itr != m_talents[i].end();) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED) stmtDel.PExecute(GetGUIDLow(),itr->first, i); // add only changed/new talents if (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED) stmtIns.PExecute(GetGUIDLow(), itr->first, itr->second.currentRank, i); if (itr->second.state == PLAYERSPELL_REMOVED) m_talents[i].erase(itr++); else { itr->second.state = PLAYERSPELL_UNCHANGED; ++itr; } } } } // save player stats -- only for external usage // real stats will be recalculated on player login void Player::_SaveStats() { // check if stat saving is enabled and if char level is high enough if(!sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE) || getLevel() < sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE)) return; static SqlStatementID delStats ; static SqlStatementID insertStats ; SqlStatement stmt = CharacterDatabase.CreateStatement(delStats, "DELETE FROM character_stats WHERE guid = ?"); stmt.PExecute(GetGUIDLow()); stmt = CharacterDatabase.CreateStatement(insertStats, "INSERT INTO character_stats (guid, maxhealth, maxpower1, maxpower2, maxpower3, maxpower4, maxpower5, maxpower6, maxpower7, " "strength, agility, stamina, intellect, spirit, armor, resHoly, resFire, resNature, resFrost, resShadow, resArcane, " "blockPct, dodgePct, parryPct, critPct, rangedCritPct, spellCritPct, attackPower, rangedAttackPower, spellPower, " "apmelee, ranged, blockrating, defrating, dodgerating, parryrating, resilience, manaregen, " "melee_hitrating, melee_critrating, melee_hasterating, melee_mainmindmg, melee_mainmaxdmg, " "melee_offmindmg, melee_offmaxdmg, melee_maintime, melee_offtime, ranged_critrating, ranged_hasterating, " "ranged_hitrating, ranged_mindmg, ranged_maxdmg, ranged_attacktime, " "spell_hitrating, spell_critrating, spell_hasterating, spell_bonusdmg, spell_bonusheal, spell_critproc, account, name, race, class, gender, level, map, money, totaltime, online, arenaPoints, totalHonorPoints, totalKills, equipmentCache, specCount, activeSpec, data) " "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(GetMaxHealth()); for(int i = 0; i < MAX_POWERS; ++i) stmt.addUInt32(GetMaxPower(Powers(i))); for(int i = 0; i < MAX_STATS; ++i) stmt.addFloat(GetStat(Stats(i))); // armor + school resistances for(int i = 0; i < MAX_SPELL_SCHOOL; ++i) stmt.addUInt32(GetResistance(SpellSchools(i))); stmt.addFloat(GetFloatValue(PLAYER_BLOCK_PERCENTAGE)); stmt.addFloat(GetFloatValue(PLAYER_DODGE_PERCENTAGE)); stmt.addFloat(GetFloatValue(PLAYER_PARRY_PERCENTAGE)); stmt.addFloat(GetFloatValue(PLAYER_CRIT_PERCENTAGE)); stmt.addFloat(GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE)); stmt.addFloat(GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1)); stmt.addUInt32(GetUInt32Value(UNIT_FIELD_ATTACK_POWER)); stmt.addUInt32(GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER)); stmt.addUInt32(GetBaseSpellPowerBonus()); stmt.addUInt32(GetUInt32Value(MANGOSR2_AP_MELEE_1)+GetUInt32Value(MANGOSR2_AP_MELEE_2)); stmt.addUInt32(GetUInt32Value(MANGOSR2_AP_RANGED_1)+GetUInt32Value(MANGOSR2_AP_RANGED_2)); stmt.addUInt32(GetUInt32Value(MANGOSR2_BLOCKRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_DEFRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_DODGERATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_PARRYRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_RESILIENCE)); stmt.addFloat(GetFloatValue(MANGOSR2_MANAREGEN)); stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_HITRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_CRITRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_HASTERATING)); stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_MAINMINDMG)); stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_MAINMAXDMG)); stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_OFFMINDMG)); stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_OFFMAXDMG)); stmt.addFloat(GetFloatValue(MANGOSR2_MELLE_MAINTIME)); stmt.addFloat(GetFloatValue(MANGOSR2_MELLE_OFFTIME)); stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_CRITRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_HASTERATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_HITRATING)); stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_MINDMG)); stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_MAXDMG)); stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_ATTACKTIME)); stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_HITRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_CRITRATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_HASTERATING)); stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_BONUSDMG)); stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_BONUSHEAL)); stmt.addFloat(GetFloatValue(MANGOSR2_SPELL_CRITPROC)); stmt.addUInt32(GetSession()->GetAccountId()); stmt.addString(m_name); // duh stmt.addUInt32((uint32)getRace()); stmt.addUInt32((uint32)getClass()); stmt.addUInt32((uint32)getGender()); stmt.addUInt32(getLevel()); stmt.addUInt32(GetMapId()); stmt.addUInt32(GetMoney()); stmt.addUInt32(m_Played_time[PLAYED_TIME_TOTAL]); stmt.addUInt32(IsInWorld() ? 1 : 0); stmt.addUInt32(GetArenaPoints()); stmt.addUInt32(GetHonorPoints()); stmt.addUInt32(GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS)); std::ostringstream ss; // duh for(uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i ) // EquipmentCache string { ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << " "; } stmt.addString(ss); // equipment cache string stmt.addUInt32(uint32(m_specsCount)); stmt.addUInt32(uint32(m_activeSpec)); std::ostringstream ps; // duh for(uint16 i = 0; i < m_valuesCount; ++i ) //data string { ps << GetUInt32Value(i) << " "; } stmt.addString(ps); //data string stmt.Execute(); } void Player::outDebugStatsValues() const { // optimize disabled debug output if(!sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG) || sLog.HasLogFilter(LOG_FILTER_PLAYER_STATS)) return; sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA)); sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH)); sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT)); sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA)); sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE)); sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE)); sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST)); sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE)); sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE)); sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE)); sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE)); sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK)); } /*********************************************************/ /*** FLOOD FILTER SYSTEM ***/ /*********************************************************/ void Player::UpdateSpeakTime() { // ignore chat spam protection for GMs in any mode if (GetSession()->GetSecurity() > SEC_PLAYER) return; time_t current = time (NULL); if (m_speakTime > current) { uint32 max_count = sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT); if(!max_count) return; ++m_speakCount; if (m_speakCount >= max_count) { // prevent overwrite mute time, if message send just before mutes set, for example. time_t new_mute = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME); if (GetSession()->m_muteTime < new_mute) GetSession()->m_muteTime = new_mute; m_speakCount = 0; } } else m_speakCount = 0; m_speakTime = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY); } bool Player::CanSpeak() const { return GetSession()->m_muteTime <= time (NULL); } /*********************************************************/ /*** LOW LEVEL FUNCTIONS:Notifiers ***/ /*********************************************************/ void Player::SendAttackSwingNotInRange() { WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0); GetSession()->SendPacket( &data ); } void Player::SavePositionInDB(ObjectGuid guid, uint32 mapid, float x, float y, float z, float o, uint32 zone) { std::ostringstream ss; ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0'," << "transguid='0',taxi_path='' WHERE guid='"<< guid.GetCounter() <<"'"; DEBUG_LOG("%s", ss.str().c_str()); CharacterDatabase.Execute(ss.str().c_str()); } void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value) { char buf[11]; snprintf(buf,11,"%u",value); if (index >= tokens.size()) return; tokens[index] = buf; } void Player::Customize(ObjectGuid guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair) { // 0 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", guid.GetCounter()); if (!result) return; Field* fields = result->Fetch(); uint32 player_bytes2 = fields[0].GetUInt32(); player_bytes2 &= ~0xFF; player_bytes2 |= facialHair; CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, guid.GetCounter()); delete result; } void Player::SendAttackSwingDeadTarget() { WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0); GetSession()->SendPacket( &data ); } void Player::SendAttackSwingCantAttack() { WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0); GetSession()->SendPacket( &data ); } void Player::SendAttackSwingCancelAttack() { WorldPacket data(SMSG_CANCEL_COMBAT, 0); GetSession()->SendPacket( &data ); } void Player::SendAttackSwingBadFacingAttack() { WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0); GetSession()->SendPacket( &data ); } void Player::SendAutoRepeatCancel(Unit *target) { WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size()); data << target->GetPackGUID(); GetSession()->SendPacket( &data ); } void Player::SendExplorationExperience(uint32 Area, uint32 Experience) { WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 ); data << uint32(Area); data << uint32(Experience); GetSession()->SendPacket(&data); } void Player::SendDungeonDifficulty(bool IsInGroup) { uint8 val = 0x00000001; WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12); data << uint32(GetDungeonDifficulty()); data << uint32(val); data << uint32(IsInGroup); GetSession()->SendPacket(&data); } void Player::SendRaidDifficulty(bool IsInGroup) { uint8 val = 0x00000001; WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12); data << uint32(GetRaidDifficulty()); data << uint32(val); data << uint32(IsInGroup); GetSession()->SendPacket(&data); } void Player::SendResetFailedNotify(uint32 mapid) { WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4); data << uint32(mapid); GetSession()->SendPacket(&data); } /// Reset all solo instances and optionally send a message on success for each void Player::ResetInstances(InstanceResetMethod method, bool isRaid) { // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN // we assume that when the difficulty changes, all instances that can be reset will be Difficulty diff = GetDifficulty(isRaid); for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();) { DungeonPersistentState *state = itr->second.state; const MapEntry *entry = sMapStore.LookupEntry(itr->first); if (!entry || entry->IsRaid() != isRaid || !state->CanReset()) { ++itr; continue; } if (method == INSTANCE_RESET_ALL) { // the "reset all instances" method can only reset normal maps if (entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC) { ++itr; continue; } } // if the map is loaded, reset it if (Map *map = sMapMgr.FindMap(state->GetMapId(), state->GetInstanceId())) if (map->IsDungeon()) ((DungeonMap*)map)->Reset(method); // since this is a solo instance there should not be any players inside if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY) SendResetInstanceSuccess(state->GetMapId()); state->DeleteFromDB(); m_boundInstances[diff].erase(itr++); // the following should remove the instance save from the manager and delete it as well state->RemovePlayer(this); } } void Player::SendResetInstanceSuccess(uint32 MapId) { WorldPacket data(SMSG_INSTANCE_RESET, 4); data << uint32(MapId); GetSession()->SendPacket(&data); } void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) { // TODO: find what other fail reasons there are besides players in the instance WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4); data << uint32(reason); data << uint32(MapId); GetSession()->SendPacket(&data); } /*********************************************************/ /*** Update timers ***/ /*********************************************************/ ///checks the 15 afk reports per 5 minutes limit void Player::UpdateAfkReport(time_t currTime) { if (m_bgData.bgAfkReportedTimer <= currTime) { m_bgData.bgAfkReportedCount = 0; m_bgData.bgAfkReportedTimer = currTime+5*MINUTE; } } void Player::UpdateContestedPvP(uint32 diff) { if(!m_contestedPvPTimer||isInCombat()) return; if (m_contestedPvPTimer <= diff) { ResetContestedPvP(); } else m_contestedPvPTimer -= diff; } void Player::UpdatePvPFlag(time_t currTime) { if(!IsPvP()) return; if (pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300)) return; UpdatePvP(false); } void Player::UpdateDuelFlag(time_t currTime) { if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3) return; SetUInt32Value(PLAYER_DUEL_TEAM, 1); duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2); duel->startTimer = 0; duel->startTime = currTime; duel->opponent->duel->startTimer = 0; duel->opponent->duel->startTime = currTime; } void Player::RemovePet(PetSaveMode mode) { GroupPetList groupPets = GetPets(); if (!groupPets.empty()) { for (GroupPetList::const_iterator itr = groupPets.begin(); itr != groupPets.end(); ++itr) if (Pet* _pet = GetMap()->GetPet(*itr)) _pet->Unsummon(mode, this); } } void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const { *data << uint8(msgtype); *data << uint32(language); *data << ObjectGuid(GetObjectGuid()); *data << uint32(language); //language 2.1.0 ? *data << ObjectGuid(GetObjectGuid()); *data << uint32(text.length()+1); *data << text; *data << uint8(chatTag()); } void Player::Say(const std::string& text, const uint32 language) { WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_SAY, text, language); SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),true); } void Player::Yell(const std::string& text, const uint32 language) { WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_YELL, text, language); SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL),true); } void Player::TextEmote(const std::string& text) { WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL); SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT) ); } void Player::Whisper(const std::string& text, uint32 language, ObjectGuid receiver) { if (language != LANG_ADDON) // if not addon data language = LANG_UNIVERSAL; // whispers should always be readable Player *rPlayer = sObjectMgr.GetPlayer(receiver); WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language); rPlayer->GetSession()->SendPacket(&data); // not send confirmation for addon messages if (language != LANG_ADDON) { data.Initialize(SMSG_MESSAGECHAT, 200); rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language); GetSession()->SendPacket(&data); } if (!isAcceptWhispers()) { SetAcceptWhispers(true); ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON); } // announce afk or dnd message if (rPlayer->isAFK()) ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->autoReplyMsg.c_str()); else if (rPlayer->isDND()) ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->autoReplyMsg.c_str()); } void Player::PetSpellInitialize() { Pet* pet = GetPet(); if(!pet) return; DEBUG_LOG("Pet Spells Groups"); CharmInfo *charmInfo = pet->GetCharmInfo(); if (!charmInfo) return; WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1); data << pet->GetObjectGuid(); data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents) data << uint32(0); data << uint32(charmInfo->GetState()); // action bar loop charmInfo->BuildActionBar(&data); size_t spellsCountPos = data.wpos(); // spells count uint8 addlist = 0; data << uint8(addlist); // placeholder if (pet->IsPermanentPetFor(this)) { // spells loop for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr) { if (itr->second.state == PETSPELL_REMOVED) continue; data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active)); ++addlist; } } data.put<uint8>(spellsCountPos, addlist); uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size(); data << uint8(cooldownsCount); time_t curTime = time(NULL); for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr) { time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0; data << uint32(itr->first); // spellid data << uint16(0); // spell category? data << uint32(cooldown); // cooldown data << uint32(0); // category cooldown } for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr) { time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0; data << uint32(itr->first); // spellid data << uint16(0); // spell category? data << uint32(0); // cooldown data << uint32(cooldown); // category cooldown } GetSession()->SendPacket(&data); } void Player::SendPetGUIDs() { GroupPetList m_groupPets = GetPets(); WorldPacket data(SMSG_PET_GUIDS, 4+8*m_groupPets.size()); data << uint32(m_groupPets.size()); // count if (!m_groupPets.empty()) { for (GroupPetList::const_iterator itr = m_groupPets.begin(); itr != m_groupPets.end(); ++itr) data << (*itr); } GetSession()->SendPacket(&data); } void Player::PossessSpellInitialize() { Unit* charm = GetCharm(); if(!charm) return; CharmInfo *charmInfo = charm->GetCharmInfo(); if(!charmInfo) { sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId()); return; } WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1); data << charm->GetObjectGuid(); data << uint16(charm->GetObjectGuid().IsAnyTypeCreature() ? ((Creature*)charm)->GetCreatureInfo()->family : 0); data << uint32(0); data << uint32(charmInfo->GetState()); charmInfo->BuildActionBar(&data); data << uint8(0); // spells count data << uint8(0); // cooldowns count GetSession()->SendPacket(&data); } void Player::VehicleSpellInitialize() { Creature* charm = (Creature*)GetCharm(); if (!charm) return; CharmInfo *charmInfo = charm->GetCharmInfo(); if (!charmInfo) { sLog.outError("Player::VehicleSpellInitialize(): vehicle (GUID: %u) has no charminfo!", charm->GetGUIDLow()); return; } size_t cooldownsCount = charm->m_CreatureSpellCooldowns.size() + charm->m_CreatureCategoryCooldowns.size(); WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1+cooldownsCount*(4+2+4+4)); data << charm->GetObjectGuid(); data << uint16(((Creature*)charm)->GetCreatureInfo()->family); data << uint32(0); data << uint32(charmInfo->GetState()); charmInfo->BuildActionBar(&data); data << uint8(0); // additional spells count data << uint8(cooldownsCount); time_t curTime = time(NULL); for (CreatureSpellCooldowns::const_iterator itr = charm->m_CreatureSpellCooldowns.begin(); itr != charm->m_CreatureSpellCooldowns.end(); ++itr) { time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0; data << uint32(itr->first); // spellid data << uint16(0); // spell category? data << uint32(cooldown); // cooldown data << uint32(0); // category cooldown } for (CreatureSpellCooldowns::const_iterator itr = charm->m_CreatureCategoryCooldowns.begin(); itr != charm->m_CreatureCategoryCooldowns.end(); ++itr) { time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0; data << uint32(itr->first); // spellid data << uint16(0); // spell category? data << uint32(0); // cooldown data << uint32(cooldown); // category cooldown } GetSession()->SendPacket(&data); } void Player::CharmSpellInitialize() { Unit* charm = GetCharm(); if(!charm) return; CharmInfo *charmInfo = charm->GetCharmInfo(); if(!charmInfo) { sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId()); return; } uint8 addlist = 0; if (charm->GetTypeId() != TYPEID_PLAYER) { CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo(); if (cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK) { for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) { if (charmInfo->GetCharmSpell(i)->GetAction()) ++addlist; } } } WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1); data << charm->GetObjectGuid(); data << uint16(charm->GetObjectGuid().IsAnyTypeCreature() ? ((Creature*)charm)->GetCreatureInfo()->family : 0); data << uint32(0); data << uint32(charmInfo->GetState()); charmInfo->BuildActionBar(&data); data << uint8(addlist); if (addlist) { for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) { CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i); if (cspell->GetAction()) data << uint32(cspell->packedData); } } data << uint8(0); // cooldowns count GetSession()->SendPacket(&data); } void Player::RemovePetActionBar() { WorldPacket data(SMSG_PET_SPELLS, 8); data << ObjectGuid(); SendDirectMessage(&data); } void Player::AddSpellMod(Aura* aura, bool apply) { Modifier const* mod = aura->GetModifier(); uint16 Opcode= (mod->m_auraname == SPELL_AURA_ADD_FLAT_MODIFIER) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER; for(int eff = 0; eff < 96; ++eff) { if (aura->GetAuraSpellClassMask().test(eff)) { int32 val = 0; for (AuraList::const_iterator itr = m_spellMods[mod->m_miscvalue].begin(); itr != m_spellMods[mod->m_miscvalue].end(); ++itr) { if ((*itr)->GetModifier()->m_auraname == mod->m_auraname && ((*itr)->GetAuraSpellClassMask().test(eff))) val += (*itr)->GetModifier()->m_amount; } val += apply ? mod->m_amount : -(mod->m_amount); WorldPacket data(Opcode, (1+1+4)); data << uint8(eff); data << uint8(mod->m_miscvalue); data << int32(val); SendDirectMessage(&data); } } if (apply) m_spellMods[mod->m_miscvalue].push_back(aura); else m_spellMods[mod->m_miscvalue].remove(aura); } template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell const* spell) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) return 0; int32 totalpct = 0; int32 totalflat = 0; for (AuraList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr) { Aura *aura = *itr; Modifier const* mod = aura->GetModifier(); if (!aura->isAffectedOnSpell(spellInfo)) continue; if (mod->m_auraname == SPELL_AURA_ADD_FLAT_MODIFIER) totalflat += mod->m_amount; else { // skip percent mods for null basevalue (most important for spell mods with charges ) if (basevalue == T(0)) continue; // special case (skip >10sec spell casts for instant cast setting) if (mod->m_miscvalue == SPELLMOD_CASTING_TIME && basevalue >= T(10*IN_MILLISECONDS) && mod->m_amount <= -100) continue; totalpct += mod->m_amount; } } float diff = (float)basevalue*(float)totalpct/100.0f + (float)totalflat; basevalue = T((float)basevalue + diff); return T(diff); } template int32 Player::ApplySpellMod<int32>(uint32 spellId, SpellModOp op, int32 &basevalue, Spell const* spell); template uint32 Player::ApplySpellMod<uint32>(uint32 spellId, SpellModOp op, uint32 &basevalue, Spell const* spell); template float Player::ApplySpellMod<float>(uint32 spellId, SpellModOp op, float &basevalue, Spell const* spell); // send Proficiency void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) { WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4); data << uint8(itemClass) << uint32(itemSubclassMask); GetSession()->SendPacket (&data); } void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) { uint32 lowguid = guid.GetCounter(); QueryResult *result = NULL; if (type == 10) result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", lowguid); else result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type); if (result) { do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand. { // and SendPetitionQueryOpcode reads data from the DB Field *fields = result->Fetch(); ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); ObjectGuid petitionguid = ObjectGuid(HIGHGUID_ITEM, fields[1].GetUInt32()); // send update if charter owner in game Player* owner = sObjectMgr.GetPlayer(ownerguid); if (owner) owner->GetSession()->SendPetitionQueryOpcode(petitionguid); } while ( result->NextRow() ); delete result; if (type==10) CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", lowguid); else CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type); } CharacterDatabase.BeginTransaction(); if (type == 10) { CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", lowguid); CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", lowguid); } else { CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", lowguid, type); CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", lowguid, type); } CharacterDatabase.CommitTransaction(); } void Player::LeaveAllArenaTeams(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", lowguid); if (!result) return; do { Field *fields = result->Fetch(); if (uint32 at_id = fields[0].GetUInt32()) if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id)) at->DelMember(guid); } while (result->NextRow()); delete result; } void Player::SetRestBonus (float rest_bonus_new) { // Prevent resting on max level if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) rest_bonus_new = 0; if (rest_bonus_new < 0) rest_bonus_new = 0; float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2.0f; if (rest_bonus_new > rest_bonus_max) m_rest_bonus = rest_bonus_max; else m_rest_bonus = rest_bonus_new; // update data for client if (GetAccountLinkedState() != STATE_NOT_LINKED) SetByteValue(PLAYER_BYTES_2, 3, 0x06); // Set Reststate = Refer-A-Friend else { if (m_rest_bonus>10) SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested else if (m_rest_bonus<=1) SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal } //RestTickUpdate SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus)); } void Player::HandleStealthedUnitsDetection() { std::list<Unit*> stealthedUnits; MaNGOS::AnyStealthedCheck u_check(this); MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check); Cell::VisitAllObjects(this, searcher, MAX_PLAYER_STEALTH_DETECT_RANGE); WorldObject const* viewPoint = GetCamera().GetBody(); for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i) { if((*i)==this) continue; bool hasAtClient = HaveAtClient((*i)); bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true); if (hasDetected) { if(!hasAtClient) { ObjectGuid i_guid = (*i)->GetObjectGuid(); (*i)->SendCreateUpdateToPlayer(this); m_clientGUIDs.insert(i_guid); DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is detected in stealth by player %u. Distance = %f",i_guid.GetString().c_str(),GetGUIDLow(),GetDistance(*i)); // target aura duration for caster show only if target exist at caster client // send data at target visibility change (adding to client) if((*i)!=this && (*i)->isType(TYPEMASK_UNIT)) SendAurasForTarget(*i); } } else { if (hasAtClient) { (*i)->DestroyForPlayer(this); m_clientGUIDs.erase((*i)->GetObjectGuid()); } } } } bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/) { if (nodes.size() < 2) return false; // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi if (GetSession()->isLogingOut() || isInCombat()) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIPLAYERBUSY); GetSession()->SendPacket(&data); return false; } if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) return false; // taximaster case if (npc) { // not let cheating with start flight mounted if (IsMounted() || GetVehicle()) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIPLAYERALREADYMOUNTED); GetSession()->SendPacket(&data); return false; } if (IsInDisallowedMountForm()) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIPLAYERSHAPESHIFTED); GetSession()->SendPacket(&data); return false; } // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi if (IsNonMeleeSpellCasted(false)) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIPLAYERBUSY); GetSession()->SendPacket(&data); return false; } } // cast case or scripted call case else { RemoveSpellsCausingAura(SPELL_AURA_MOUNTED); ExitVehicle(); if (IsInDisallowedMountForm()) RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT); if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL)) if (spell->m_spellInfo->Id != spellid) InterruptSpell(CURRENT_GENERIC_SPELL,false); InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false); if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL)) if (spell->m_spellInfo->Id != spellid) InterruptSpell(CURRENT_CHANNELED_SPELL,true); } uint32 sourcenode = nodes[0]; // starting node too far away (cheat?) TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode); if (!node) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXINOSUCHPATH); GetSession()->SendPacket(&data); return false; } // check node starting pos data set case if provided if (fabs(node->x) > M_NULL_F || fabs(node->y) > M_NULL_F || fabs(node->z) > M_NULL_F) { if (node->map_id != GetMapId() || (node->x - GetPositionX())*(node->x - GetPositionX())+ (node->y - GetPositionY())*(node->y - GetPositionY())+ (node->z - GetPositionZ())*(node->z - GetPositionZ()) > (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXITOOFARAWAY); GetSession()->SendPacket(&data); return false; } } // node must have pos if taxi master case (npc != NULL) else if (npc) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR); GetSession()->SendPacket(&data); return false; } // Prepare to flight start now // stop combat at start taxi flight if any CombatStop(); // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it) TradeCancel(true); // clean not finished taxi path if any m_taxi.ClearTaxiDestinations(); // 0 element current node m_taxi.AddTaxiDestination(sourcenode); // fill destinations path tail uint32 sourcepath = 0; uint32 totalcost = 0; uint32 prevnode = sourcenode; uint32 lastnode = 0; for(uint32 i = 1; i < nodes.size(); ++i) { uint32 path, cost; lastnode = nodes[i]; sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost); if(!path) { m_taxi.ClearTaxiDestinations(); return false; } totalcost += cost; if (prevnode == sourcenode) sourcepath = path; m_taxi.AddTaxiDestination(lastnode); prevnode = lastnode; } // get mount model (in case non taximaster (npc==NULL) allow more wide lookup) uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL); // in spell case allow 0 model if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR); GetSession()->SendPacket(&data); m_taxi.ClearTaxiDestinations(); return false; } uint32 money = GetMoney(); if (npc) totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc)); if (money < totalcost) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXINOTENOUGHMONEY); GetSession()->SendPacket(&data); m_taxi.ClearTaxiDestinations(); return false; } //Checks and preparations done, DO FLIGHT ModifyMoney(-(int32)totalcost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1); // prevent stealth flight RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIOK); GetSession()->SendPacket(&data); DEBUG_LOG("WORLD: Sent SMSG_ACTIVATETAXIREPLY"); GetSession()->SendDoFlight(mount_display_id, sourcepath); return true; } bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ ) { TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id); if(!entry) return false; std::vector<uint32> nodes; nodes.resize(2); nodes[0] = entry->from; nodes[1] = entry->to; return ActivateTaxiPathTo(nodes,NULL,spellid); } void Player::ContinueTaxiFlight() { uint32 sourceNode = m_taxi.GetTaxiSource(); if (!sourceNode) return; DEBUG_LOG( "WORLD: Restart character %u taxi flight", GetGUIDLow() ); uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(), true); uint32 path = m_taxi.GetCurrentTaxiPath(); // search appropriate start path node uint32 startNode = 0; TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path]; float distPrev = MAP_SIZE*MAP_SIZE; float distNext = (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+ (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+ (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ()); for(uint32 i = 1; i < nodeList.size(); ++i) { TaxiPathNodeEntry const& node = nodeList[i]; TaxiPathNodeEntry const& prevNode = nodeList[i-1]; // skip nodes at another map if (node.mapid != GetMapId()) continue; distPrev = distNext; distNext = (node.x-GetPositionX())*(node.x-GetPositionX())+ (node.y-GetPositionY())*(node.y-GetPositionY())+ (node.z-GetPositionZ())*(node.z-GetPositionZ()); float distNodes = (node.x-prevNode.x)*(node.x-prevNode.x)+ (node.y-prevNode.y)*(node.y-prevNode.y)+ (node.z-prevNode.z)*(node.z-prevNode.z); if (distNext + distPrev < distNodes) { startNode = i; break; } } GetSession()->SendDoFlight(mountDisplayId, path, startNode); } void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs ) { // last check 2.0.10 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8); data << GetObjectGuid(); data << uint8(0x0); // flags (0x1, 0x2) time_t curTime = time(NULL); for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) continue; uint32 unSpellId = itr->first; SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId); if (!spellInfo) { MANGOS_ASSERT(spellInfo); continue; } // Not send cooldown for this spells if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) continue; if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs ) { data << uint32(unSpellId); data << uint32(unTimeMs); // in m.secs AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILLISECONDS); } } GetSession()->SendPacket(&data); } void Player::SendModifyCooldown( uint32 spell_id, int32 delta) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) return; uint32 cooldown = GetSpellCooldownDelay(spell_id); if (cooldown == 0 && delta < 0) return; int32 result = int32(cooldown * IN_MILLISECONDS + delta); if (result < 0) result = 0; AddSpellCooldown(spell_id, 0, uint32(time(NULL) + int32(result / IN_MILLISECONDS))); WorldPacket data(SMSG_MODIFY_COOLDOWN, 4 + 8 + 4); data << uint32(spell_id); data << GetObjectGuid(); data << int32(result > 0 ? delta : result - cooldown * IN_MILLISECONDS); GetSession()->SendPacket(&data); } void Player::InitDataForForm(bool reapplyMods) { ShapeshiftForm form = GetShapeshiftForm(); SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form); if (ssEntry && ssEntry->attackSpeed) { SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed); SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed); SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME); } else SetRegularAttackTime(); switch(form) { case FORM_CAT: { if (getPowerType()!=POWER_ENERGY) setPowerType(POWER_ENERGY); break; } case FORM_BEAR: case FORM_DIREBEAR: { if (getPowerType()!=POWER_RAGE) setPowerType(POWER_RAGE); break; } default: // 0, for example { ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass()); if (cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType) setPowerType(Powers(cEntry->powerType)); break; } } // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change. if (!reapplyMods) UpdateEquipSpellsAtFormChange(); UpdateAttackPowerAndDamage(); UpdateAttackPowerAndDamage(true); } void Player::InitDisplayIds() { PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass()); if(!info) { sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow()); return; } // reset scale before reapply auras SetObjectScale(DEFAULT_OBJECT_SCALE); uint8 gender = getGender(); switch(gender) { case GENDER_FEMALE: SetDisplayId(info->displayId_f ); SetNativeDisplayId(info->displayId_f ); break; case GENDER_MALE: SetDisplayId(info->displayId_m ); SetNativeDisplayId(info->displayId_m ); break; default: sLog.outError("Invalid gender %u for player",gender); return; } } void Player::TakeExtendedCost(uint32 extendedCostId, uint32 count) { ItemExtendedCostEntry const* extendedCost = sItemExtendedCostStore.LookupEntry(extendedCostId); if (extendedCost->reqhonorpoints) ModifyHonorPoints(-int32(extendedCost->reqhonorpoints * count)); if (extendedCost->reqarenapoints) ModifyArenaPoints(-int32(extendedCost->reqarenapoints * count)); for (uint8 i = 0; i < MAX_EXTENDED_COST_ITEMS; ++i) { if (extendedCost->reqitem[i]) DestroyItemCount(extendedCost->reqitem[i], extendedCost->reqitemcount[i] * count, true); } } // Return true is the bought item has a max count to force refresh of window by caller bool Player::BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot) { // cheating attempt if (count < 1) count = 1; if (!isAlive()) return false; ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item); if (!pProto) { SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0); return false; } Creature *pCreature = GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_VENDOR); if (!pCreature) { DEBUG_LOG("WORLD: BuyItemFromVendor - %s not found or you can't interact with him.", vendorGuid.GetString().c_str()); SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0); return false; } VendorItemData const* vItems = pCreature->GetVendorItems(); VendorItemData const* tItems = pCreature->GetVendorTemplateItems(); if ((!vItems || vItems->Empty()) && (!tItems || tItems->Empty())) { SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0); return false; } uint32 vCount = vItems ? vItems->GetItemCount() : 0; uint32 tCount = tItems ? tItems->GetItemCount() : 0; if (vendorslot >= vCount+tCount) { SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0); return false; } VendorItem const* crItem = vendorslot < vCount ? vItems->GetItem(vendorslot) : tItems->GetItem(vendorslot - vCount); if (!crItem) // store diff item (cheating) { SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0); return false; } if (crItem->item != item) // store diff item (cheating or special convert) { bool converted = false; // possible item converted for BoA case ItemPrototype const* crProto = ObjectMgr::GetItemPrototype(crItem->item); if (crProto->Flags & ITEM_FLAG_BOA && crProto->RequiredReputationFaction && uint32(GetReputationRank(crProto->RequiredReputationFaction)) >= crProto->RequiredReputationRank) converted = (sObjectMgr.GetItemConvert(crItem->item, getRaceMask()) != 0); if (!converted) { SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0); return false; } } uint32 totalCount = pProto->BuyCount * count; // check current item amount if it limited if (crItem->maxcount != 0) { if (pCreature->GetVendorItemCurrentCount(crItem) < totalCount) { SendBuyError(BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0); return false; } } if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank) { SendBuyError(BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0); return false; } if (uint32 extendedCostId = crItem->ExtendedCost) { ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(extendedCostId); if (!iece) { sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, extendedCostId); return false; } // honor points price if (GetHonorPoints() < (iece->reqhonorpoints * count)) { SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL); return false; } // arena points price if (GetArenaPoints() < (iece->reqarenapoints * count)) { SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL); return false; } // item base price for (uint8 i = 0; i < MAX_EXTENDED_COST_ITEMS; ++i) { if (iece->reqitem[i] && !HasItemCount(iece->reqitem[i], iece->reqitemcount[i] * count)) { SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); return false; } } // check for personal arena rating requirement if (GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating) { // probably not the proper equip err SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL); return false; } } uint32 price = (crItem->ExtendedCost == 0 || pProto->Flags2 & ITEM_FLAG2_EXT_COST_REQUIRES_GOLD) ? pProto->BuyPrice * count : 0; // reputation discount if (price) price = uint32(floor(price * GetReputationPriceDiscount(pCreature))); if (GetMoney() < price) { SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0); return false; } Item* pItem = NULL; if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot)) { ItemPosCountVec dest; InventoryResult msg = CanStoreNewItem(bag, slot, dest, item, totalCount); if (msg != EQUIP_ERR_OK) { SendEquipError(msg, NULL, NULL, item); return false; } ModifyMoney(-int32(price)); if (crItem->ExtendedCost) TakeExtendedCost(crItem->ExtendedCost, count); pItem = StoreNewItem(dest, item, true); } else if (IsEquipmentPos(bag, slot)) { if (totalCount != 1) { SendEquipError(EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL); return false; } uint16 dest; InventoryResult msg = CanEquipNewItem(slot, dest, item, false); if (msg != EQUIP_ERR_OK) { SendEquipError(msg, NULL, NULL, item); return false; } ModifyMoney(-int32(price)); if (crItem->ExtendedCost) TakeExtendedCost(crItem->ExtendedCost, count); pItem = EquipNewItem(dest, item, true); if (pItem) AutoUnequipOffhandIfNeed(); } else { SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL); return false; } if (!pItem) return false; uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem, totalCount); WorldPacket data(SMSG_BUY_ITEM, 8+4+4+4); data << pCreature->GetObjectGuid(); data << uint32(vendorslot + 1); // numbered from 1 at client data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF); data << uint32(count); GetSession()->SendPacket(&data); SendNewItem(pItem, totalCount, true, false, false); return crItem->maxcount != 0; } uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) { // returns the maximal personal arena rating that can be used to purchase items requiring this condition // the personal rating of the arena team must match the required limit as well // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype])) uint32 max_personal_rating = 0; for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i) { if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i))) { uint32 p_rating = GetArenaPersonalRating(i); uint32 t_rating = at->GetRating(); p_rating = p_rating < t_rating ? p_rating : t_rating; if (max_personal_rating < p_rating) max_personal_rating = p_rating; } } return max_personal_rating; } void Player::UpdateHomebindTime(uint32 time) { // GMs never get homebind timer online if (m_InstanceValid || isGameMaster()) { if (m_HomebindTimer) // instance valid, but timer not reset { // hide reminder WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); data << uint32(0); data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0 GetSession()->SendPacket(&data); } // instance is valid, reset homebind timer m_HomebindTimer = 0; } else if (m_HomebindTimer > 0) { if (time >= m_HomebindTimer) { // teleport to nearest graveyard RepopAtGraveyard(); } else m_HomebindTimer -= time; } else { // instance is invalid, start homebind timer m_HomebindTimer = 15000; // send message to player WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); data << uint32(m_HomebindTimer); data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0 GetSession()->SendPacket(&data); DEBUG_LOG("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow()); } } void Player::UpdatePvP(bool state, bool ovrride) { if(!state || ovrride) { SetPvP(state); pvpInfo.endTimer = 0; } else { if (pvpInfo.endTimer != 0) pvpInfo.endTimer = time(NULL); else SetPvP(state); } } void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown) { // init cooldown values uint32 cat = 0; int32 rec = -1; int32 catrec = -1; // some special item spells without correct cooldown in SpellInfo // cooldown information stored in item prototype // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client. if (itemId) { if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId)) { for(int idx = 0; idx < 5; ++idx) { if (proto->Spells[idx].SpellId == spellInfo->Id) { cat = proto->Spells[idx].SpellCategory; rec = proto->Spells[idx].SpellCooldown; catrec = proto->Spells[idx].SpellCategoryCooldown; break; } } } } // if no cooldown found above then base at DBC data if (rec < 0 && catrec < 0) { cat = spellInfo->Category; rec = spellInfo->RecoveryTime; catrec = spellInfo->CategoryRecoveryTime; } time_t curTime = time(NULL); time_t catrecTime; time_t recTime; // overwrite time for selected category if (infinityCooldown) { // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped) // but not allow ignore until reset or re-login catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0; recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime; } else { // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK) // prevent 0 cooldowns set by another way if (rec <= 0 && catrec <= 0 && (cat == 76 || (IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))) rec = GetAttackTime(RANGED_ATTACK); // Now we have cooldown data (if found any), time to apply mods if (rec > 0) ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell); if (catrec > 0) ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell); // replace negative cooldowns by 0 if (rec < 0) rec = 0; if (catrec < 0) catrec = 0; // no cooldown after applying spell mods if (rec == 0 && catrec == 0) return; catrecTime = catrec ? curTime+catrec/IN_MILLISECONDS : 0; recTime = rec ? curTime+rec/IN_MILLISECONDS : catrecTime; } // self spell cooldown if (recTime > 0) AddSpellCooldown(spellInfo->Id, itemId, recTime); // category spells if (cat && catrec > 0) { SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat); if (i_scstore != sSpellCategoryStore.end()) { for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset) { if (*i_scset == spellInfo->Id) // skip main spell, already handled above continue; AddSpellCooldown(*i_scset, itemId, catrecTime); } } } } void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time) { SpellCooldown sc; sc.end = end_time; sc.itemid = itemid; MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT); m_spellCooldowns[spellid] = sc; } void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell) { // start cooldowns at server side, if any AddSpellAndCategoryCooldowns(spellInfo, itemId, spell); // Send activate cooldown timer (possible 0) at client side WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8)); data << uint32(spellInfo->Id); data << GetObjectGuid(); SendDirectMessage(&data); } void Player::UpdatePotionCooldown(Spell* spell) { // no potion used in combat or still in combat if(!m_lastPotionId || isInCombat()) return; // Call not from spell cast, send cooldown event for item spells if no in combat if(!spell) { // spell/item pair let set proper cooldown (except nonexistent charged spell cooldown spellmods for potions) if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId)) for(int idx = 0; idx < 5; ++idx) if (proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE) if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId)) SendCooldownEvent(spellInfo,m_lastPotionId); } // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown) else SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell); m_lastPotionId = 0; } //slot to be excluded while counting bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) { if(!enchantmentcondition) return true; SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition); if(!Condition) return true; uint8 curcount[4] = {0, 0, 0, 0}; //counting current equipped gem colors for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i == slot) continue; Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (pItem2 && !pItem2->IsBroken() && pItem2->GetProto()->Socket[0].Color) { for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) continue; SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; uint32 gemid = enchantEntry->GemID; if(!gemid) continue; ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid); if(!gemProto) continue; GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties); if(!gemProperty) continue; uint8 GemColor = gemProperty->color; for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1) { if (tmpcolormask & GemColor) ++curcount[b]; } } } } bool activate = true; for(int i = 0; i < 5; ++i) { if(!Condition->Color[i]) continue; uint32 _cur_gem = curcount[Condition->Color[i] - 1]; // if have <CompareColor> use them as count, else use <value> from Condition uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i]; switch(Condition->Comparator[i]) { case 2: // requires less <color> than (<value> || <comparecolor>) gems activate &= (_cur_gem < _cmp_gem) ? true : false; break; case 3: // requires more <color> than (<value> || <comparecolor>) gems activate &= (_cur_gem > _cmp_gem) ? true : false; break; case 5: // requires at least <color> than (<value> || <comparecolor>) gems activate &= (_cur_gem >= _cmp_gem) ? true : false; break; } } DEBUG_LOG("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no"); return activate; } void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) { //cycle all equipped items for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot) { //enchants for the slot being socketed are handled by Player::ApplyItemMods if (slot == exceptslot) continue; Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ); if(!pItem || !pItem->GetProto()->Socket[0].Color) continue; for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) continue; SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; uint32 condition = enchantEntry->EnchantmentCondition; if (condition) { //was enchant active with/without item? bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1); //should it now be? if (wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot)) { // ignore item gem conditions //if state changed, (dis)apply enchant ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true); } } } } } //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply) { //cycle all equipped items for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot) { //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data) if (slot == exceptslot) continue; Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ); if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item continue; //cycle all (gem)enchants for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) //if no enchant go to next enchant(slot) continue; SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; //only metagems to be (de)activated, so only enchants with condition uint32 condition = enchantEntry->EnchantmentCondition; if (condition) ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply); } } } void Player::SetBattleGroundEntryPoint(bool forLFG) { m_bgData.forLFG = forLFG; // Taxi path store if (!m_taxi.empty()) { m_bgData.mountSpell = 0; m_bgData.taxiPath[0] = m_taxi.GetTaxiSource(); m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination(); // On taxi we don't need check for dungeon m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); m_bgData.m_needSave = true; return; } else { m_bgData.ClearTaxiPath(); // Mount spell id storing if (IsMounted()) { AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED); if (!auras.empty()) m_bgData.mountSpell = (*auras.begin())->GetId(); } else m_bgData.mountSpell = 0; // If map is dungeon find linked graveyard if (GetMap()->IsDungeon()) { if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam())) { m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f); m_bgData.m_needSave = true; return; } else sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId()); } // If new entry point is not BG or arena set it else if (!GetMap()->IsBattleGroundOrArena()) { m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); m_bgData.m_needSave = true; return; } } // In error cases use homebind position m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f); m_bgData.m_needSave = true; } void Player::LeaveBattleground(bool teleportToEntryPoint) { if (BattleGround *bg = GetBattleGround()) { bg->RemovePlayerAtLeave(GetObjectGuid(), teleportToEntryPoint, true); // call after remove to be sure that player resurrected for correct cast if ( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER) ) { if ( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN ) { //lets check if player was teleported from BG and schedule delayed Deserter spell cast if (IsBeingTeleportedFar()) { ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER); return; } CastSpell(this, 26013, true); // Deserter } } // Prevent more execute BG update codes if (bg->isBattleGround() && bg->GetStatus() == STATUS_IN_PROGRESS && !bg->GetPlayersSize()) bg->SetStatus(STATUS_WAIT_LEAVE); } } bool Player::CanJoinToBattleground() const { // check Deserter debuff if (GetDummyAura(26013)) return false; return true; } bool Player::CanReportAfkDueToLimit() { // a player can complain about 15 people per 5 minutes if (m_bgData.bgAfkReportedCount++ >= 15) return false; return true; } ///This player has been blamed to be inactive in a battleground void Player::ReportedAfkBy(Player* reporter) { BattleGround* bg = GetBattleGround(); // Battleground also must be in progress! if (!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam() || bg->GetStatus() != STATUS_IN_PROGRESS) return; // check if player has 'Idle' or 'Inactive' debuff if (m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, EFFECT_INDEX_0) && !HasAura(43681, EFFECT_INDEX_0) && reporter->CanReportAfkDueToLimit()) { m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow()); // 3 players have to complain to apply debuff if (m_bgData.bgAfkReporter.size() >= 3) { // cast 'Idle' spell CastSpell(this, 43680, true); m_bgData.bgAfkReporter.clear(); } } } bool Player::IsVisibleInGridForPlayer( Player* pl ) const { // gamemaster in GM mode see all, including ghosts if (pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity()) return true; // player see dead player/ghost from own group/raid if (IsInSameRaidWith(pl)) return true; // Live player see live player or dead player with not realized corpse if (pl->isAlive() || pl->m_deathTimer > 0) return isAlive() || m_deathTimer > 0; // Ghost see other friendly ghosts, that's for sure if (!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl)) return true; // Dead player see live players near own corpse if (isAlive()) { if (Corpse *corpse = pl->GetCorpse()) { // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level if (corpse->IsWithinDistInMap(this, (20 + 25) * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO))) return true; } } // and not see any other return false; } bool Player::IsVisibleGloballyFor( Player* u ) const { if (!u) return false; // Always can see self if (u==this) return true; // Visible units, always are visible for all players if (GetVisibility() == VISIBILITY_ON) return true; // GMs are visible for higher gms (or players are visible for gms) if (u->GetSession()->GetSecurity() > SEC_PLAYER) return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity(); // non faction visibility non-breakable for non-GMs if (GetVisibility() == VISIBILITY_OFF) return false; // non-gm stealth/invisibility not hide from global player lists return true; } template<class T> inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/) { } template<> inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p) { if (p->GetPetGuid() == t->GetObjectGuid() && ((Creature*)t)->IsPet()) ((Pet*)t)->Unsummon(PET_SAVE_REAGENTS); } void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target) { if (HaveAtClient(target)) { if(!target->isVisibleForInState(this, viewPoint, true)) { ObjectGuid t_guid = target->GetObjectGuid(); if (target->GetTypeId()==TYPEID_UNIT) { BeforeVisibilityDestroy<Creature>((Creature*)target,this); // at remove from map (destroy) show kill animation (in different out of range/stealth case) target->DestroyForPlayer(this, !target->IsInWorld() && ((Creature*)target)->isDead()); } else target->DestroyForPlayer(this); m_clientGUIDs.erase(t_guid); DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s out of range for player %u. Distance = %f",t_guid.GetString().c_str(),GetGUIDLow(),GetDistance(target)); } } else { if (target->isVisibleForInState(this, viewPoint, false)) { target->SendCreateUpdateToPlayer(this); if (target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport()) m_clientGUIDs.insert(target->GetObjectGuid()); DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target)); // target aura duration for caster show only if target exist at caster client // send data at target visibility change (adding to client) if (target!=this && target->isType(TYPEMASK_UNIT)) SendAurasForTarget((Unit*)target); } } } template<class T> inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, T* target) { s64.insert(target->GetObjectGuid()); } template<> inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, GameObject* target) { if(!target->IsTransport()) s64.insert(target->GetObjectGuid()); } template<class T> void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, std::set<WorldObject*>& visibleNow) { if (HaveAtClient(target)) { if(!target->isVisibleForInState(this,viewPoint,true)) { BeforeVisibilityDestroy<T>(target,this); ObjectGuid t_guid = target->GetObjectGuid(); target->BuildOutOfRangeUpdateBlock(&data); m_clientGUIDs.erase(t_guid); DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is out of range for %s. Distance = %f", t_guid.GetString().c_str(), GetGuidStr().c_str(), GetDistance(target)); } } else { if (target->isVisibleForInState(this,viewPoint,false)) { visibleNow.insert(target); target->BuildCreateUpdateBlockForPlayer(&data, this); UpdateVisibilityOf_helper(m_clientGUIDs,target); DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is visible now for %s. Distance = %f", target->GetGuidStr().c_str(), GetGuidStr().c_str(), GetDistance(target)); } } } template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow); void Player::SetPhaseMask(uint32 newPhaseMask, bool update) { // GM-mode have mask PHASEMASK_ANYWHERE always if (isGameMaster()) newPhaseMask = PHASEMASK_ANYWHERE; // phase auras normally not expected at BG but anyway better check if (BattleGround *bg = GetBattleGround()) bg->EventPlayerDroppedFlag(this); Unit::SetPhaseMask(newPhaseMask, update); GetSession()->SendSetPhaseShift(GetPhaseMask()); } void Player::InitPrimaryProfessions() { uint32 maxProfs = GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT)) ? sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL) : 10; SetFreePrimaryProfessions(maxProfs); } void Player::SendComboPoints(ObjectGuid targetGuid, uint8 combopoints) { Unit* combotarget = GetMap()->GetUnit(targetGuid); if (combotarget) { WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1); data << combotarget->GetPackGUID(); data << uint8(combopoints); GetSession()->SendPacket(&data); } /*else { // can be NULL, and then points=0. Use unknown; to reset points of some sort? data << PackedGuid(); data << uint8(0); GetSession()->SendPacket(&data); }*/ } void Player::SendPetComboPoints(Unit* pet, ObjectGuid targetGuid, uint8 combopoints) { Unit* combotarget = pet ? pet->GetMap()->GetUnit(targetGuid) : NULL; if (pet && combotarget) { WorldPacket data(SMSG_PET_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+pet->GetPackGUID().size()+1); data << pet->GetPackGUID(); data << combotarget->GetPackGUID(); data << uint8(combopoints); GetSession()->SendPacket(&data); } } void Player::SetGroup(Group *group, int8 subgroup) { if (group == NULL) m_group.unlink(); else { // never use SetGroup without a subgroup unless you specify NULL for group MANGOS_ASSERT(subgroup >= 0); m_group.link(group, this); m_group.setSubGroup((uint8)subgroup); } } void Player::SendInitialPacketsBeforeAddToMap() { GetSocial()->SendSocialList(); // Homebind WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4); data << m_homebindX << m_homebindY << m_homebindZ; data << (uint32) m_homebindMapId; data << (uint32) m_homebindAreaId; GetSession()->SendPacket(&data); // SMSG_SET_PROFICIENCY // SMSG_SET_PCT_SPELL_MODIFIER // SMSG_SET_FLAT_SPELL_MODIFIER SendTalentsInfoData(false); data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4); data << uint32(GetMap()->GetDifficulty()); data << uint32(0); GetSession()->SendPacket(&data); SendInitialSpells(); data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4); data << uint32(0); // count, for(count) uint32; GetSession()->SendPacket(&data); SendInitialActionButtons(); m_reputationMgr.SendInitialReputations(); if(!isAlive()) SendCorpseReclaimDelay(true); SendInitWorldStates(GetZoneId(), GetAreaId()); SendEquipmentSetList(); m_achievementMgr.SendAllAchievementData(); data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4); data << uint32(secsToTimeBitFields(sWorld.GetGameTime())); data << (float)0.01666667f; // game speed data << uint32(0); // added in 3.1.2 GetSession()->SendPacket( &data ); // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...) // SMSG_PET_GUIDS // SMSG_POWER_UPDATE // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment if (IsFreeFlying() || IsTaxiFlying()) m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING); SetMover(this); } void Player::SendInitialPacketsAfterAddToMap() { // update zone uint32 newzone, newarea; GetZoneAndAreaId(newzone,newarea); UpdateZone(newzone,newarea); // also call SendInitWorldStates(); ResetTimeSync(); SendTimeSync(); CastSpell(this, 836, true); // LOGINEFFECT // set some aura effects that send packet to player client after add player to map // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply // same auras state lost at far teleport, send it one more time in this case also static const AuraType auratypes[] = { SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK, SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL, SPELL_AURA_FLY, SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED, SPELL_AURA_NONE }; for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr) { Unit::AuraList const& auraList = GetAurasByType(*itr); if(!auraList.empty()) auraList.front()->ApplyModifier(true,true); } if (HasAuraType(SPELL_AURA_MOD_STUN)) SetMovement(MOVE_ROOT); // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied. if (HasAuraType(SPELL_AURA_MOD_ROOT)) { WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10); data2 << GetPackGUID(); data2 << (uint32)2; SendMessageToSet(&data2,true); } if (GetVehicle()) { WorldPacket data3(SMSG_FORCE_MOVE_ROOT, 10); data3 << GetPackGUID(); data3 << uint32((m_movementInfo.GetVehicleSeatFlags() & SEAT_FLAG_CAN_CAST) ? 2 : 0); SendMessageToSet(&data3,true); } SendAurasForTarget(this); SendEnchantmentDurations(); // must be after add to map SendItemDurations(); // must be after add to map } void Player::SendUpdateToOutOfRangeGroupMembers() { if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE) return; if (Group* group = GetGroup()) group->UpdatePlayerOutOfRange(this); m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE; m_auraUpdateMask = 0; if (Pet *pet = GetPet()) pet->ResetAuraUpdateMask(); } void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg) { WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2); data << uint32(mapid); data << uint8(reason); // transfer abort reason switch(reason) { case TRANSFER_ABORT_INSUF_EXPAN_LVL: case TRANSFER_ABORT_DIFFICULTY: case TRANSFER_ABORT_UNIQUE_MESSAGE: data << uint8(arg); break; } GetSession()->SendPacket(&data); } void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time ) { // type of warning, based on the time remaining until reset uint32 type; if (time > 3600) type = RAID_INSTANCE_WELCOME; else if (time > 900 && time <= 3600) type = RAID_INSTANCE_WARNING_HOURS; else if (time > 300 && time <= 900) type = RAID_INSTANCE_WARNING_MIN; else type = RAID_INSTANCE_WARNING_MIN_SOON; WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4); data << uint32(type); data << uint32(mapid); data << uint32(difficulty); // difficulty data << uint32(time); if (type == RAID_INSTANCE_WELCOME) { data << uint8(0); // is your (1) data << uint8(0); // is extended (1), ignored if prev field is 0 } GetSession()->SendPacket(&data); } void Player::ApplyEquipCooldown( Item * pItem ) { if (pItem->GetProto()->Flags & ITEM_FLAG_NO_EQUIP_COOLDOWN) return; for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = pItem->GetProto()->Spells[i]; // no spell if ( !spellData.SpellId ) continue; // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown) if ( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE ) continue; AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30); WorldPacket data(SMSG_ITEM_COOLDOWN, 12); data << ObjectGuid(pItem->GetObjectGuid()); data << uint32(spellData.SpellId); GetSession()->SendPacket(&data); } } void Player::resetSpells() { // not need after this call if (HasAtLoginFlag(AT_LOGIN_RESET_SPELLS)) RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true); // make full copy of map (spells removed and marked as deleted at another spell remove // and we can't use original map for safe iterative with visit each spell at loop end PlayerSpellMap smap = GetSpellMap(); for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter) removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already learnDefaultSpells(); learnQuestRewardedSpells(); } void Player::learnDefaultSpells() { // learn default race/class spells PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass()); for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr) { uint32 tspell = *itr; DEBUG_LOG("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell); if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add addSpell(tspell, true, true, true, false); else // but send in normal spell in game learn case learnSpell(tspell, true); } } void Player::learnQuestRewardedSpells(Quest const* quest) { uint32 spell_id = quest->GetRewSpellCast(); // skip quests without rewarded spell if ( !spell_id ) return; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); if(!spellInfo) return; // check learned spells state bool found = false; for(int i=0; i < MAX_EFFECT_INDEX; ++i) { if (spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i])) { found = true; break; } } // skip quests with not teaching spell or already known spell if(!found) return; // prevent learn non first rank unknown profession and second specialization for same profession) uint32 learned_0 = spellInfo->EffectTriggerSpell[EFFECT_INDEX_0]; if ( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) ) { // not have first rank learned (unlearned prof?) uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0); if ( !HasSpell(first_spell) ) return; SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0); if(!learnedInfo) return; // specialization if (learnedInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[EFFECT_INDEX_1] == 0) { // search other specialization for same prof for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->first==learned_0) continue; SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first); if(!itrInfo) return; // compare only specializations if (itrInfo->Effect[EFFECT_INDEX_0] != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[EFFECT_INDEX_1] != 0) continue; // compare same chain spells if (sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell) continue; // now we have 2 specialization, learn possible only if found is lesser specialization rank if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first)) return; } } } CastSpell( this, spell_id, true); } void Player::learnQuestRewardedSpells() { // learn spells received from quest completing for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr) { // skip no rewarded quests if(!itr->second.m_rewarded) continue; Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first); if ( !quest ) continue; learnQuestRewardedSpells(quest); } } void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value ) { uint32 raceMask = getRaceMask(); uint32 classMask = getClassMask(); for (uint32 j = 0; j<sSkillLineAbilityStore.GetNumRows(); ++j) { SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j); if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL) continue; // Check race if set if (pAbility->racemask && !(pAbility->racemask & raceMask)) continue; // Check class if set if (pAbility->classmask && !(pAbility->classmask & classMask)) continue; if (sSpellStore.LookupEntry(pAbility->spellId)) { // need unlearn spell if (skill_value < pAbility->req_skill_value) removeSpell(pAbility->spellId); // need learn else if (!IsInWorld()) addSpell(pAbility->spellId, true, true, true, false); else learnSpell(pAbility->spellId, true); } } } void Player::SendAurasForTarget(Unit *target) { WorldPacket data(SMSG_AURA_UPDATE_ALL); data << target->GetPackGUID(); MAPLOCK_READ(target,MAP_LOCK_TYPE_AURAS); Unit::VisibleAuraMap const& visibleAuras = target->GetVisibleAuras(); for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras.begin(); itr != visibleAuras.end(); ++itr) { SpellAuraHolderConstBounds bounds = target->GetSpellAuraHolderBounds(itr->second); for (SpellAuraHolderMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter) iter->second->BuildUpdatePacket(data); } GetSession()->SendPacket(&data); } void Player::SetDailyQuestStatus( uint32 quest_id ) { for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) { if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx)) { SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id); m_DailyQuestChanged = true; break; } } } void Player::SetWeeklyQuestStatus( uint32 quest_id ) { m_weeklyquests.insert(quest_id); m_WeeklyQuestChanged = true; } void Player::SetMonthlyQuestStatus(uint32 quest_id) { m_monthlyquests.insert(quest_id); m_MonthlyQuestChanged = true; } void Player::ResetDailyQuestStatus() { for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0); // DB data deleted in caller m_DailyQuestChanged = false; } void Player::ResetWeeklyQuestStatus() { if (m_weeklyquests.empty()) return; m_weeklyquests.clear(); // DB data deleted in caller m_WeeklyQuestChanged = false; } void Player::ResetMonthlyQuestStatus() { if (m_monthlyquests.empty()) return; m_monthlyquests.clear(); // DB data deleted in caller m_MonthlyQuestChanged = false; } BattleGround* Player::GetBattleGround() const { if (GetBattleGroundId()==0) return NULL; return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID); } bool Player::InArena() const { BattleGround *bg = GetBattleGround(); if(!bg || !bg->isArena()) return false; return true; } bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const { // get a template bg instead of running one BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId); if(!bg) return false; // limit check leel to dbc compatible level range uint32 level = getLevel(); if (level > DEFAULT_MAX_LEVEL) level = DEFAULT_MAX_LEVEL; if (level < bg->GetMinLevel() || level > bg->GetMaxLevel()) return false; return true; } float Player::GetReputationPriceDiscount( Creature const* pCreature ) const { FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry(); if(!vendor_faction || !vendor_faction->faction) return 1.0f; ReputationRank rank = GetReputationRank(vendor_faction->faction); if (rank <= REP_NEUTRAL) return 1.0f; return 1.0f - 0.05f* (rank - REP_NEUTRAL); } /** * Check spell availability for training base at SkillLineAbility/SkillRaceClassInfo data. * Checked allowed race/class and dependent from race/class allowed min level * * @param spell_id checked spell id * @param pReqlevel if arg provided then function work in view mode (level check not applied but detected minlevel returned to var by arg pointer. if arg not provided then considered train action mode and level checked * @return true if spell available for show in trainer list (with skip level check) or training. */ bool Player::IsSpellFitByClassAndRace(uint32 spell_id, uint32* pReqlevel /*= NULL*/) const { uint32 racemask = getRaceMask(); uint32 classmask = getClassMask(); SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id); if (bounds.first==bounds.second) return true; for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) { SkillLineAbilityEntry const* abilityEntry = _spell_idx->second; // skip wrong race skills if (abilityEntry->racemask && (abilityEntry->racemask & racemask) == 0) continue; // skip wrong class skills if (abilityEntry->classmask && (abilityEntry->classmask & classmask) == 0) continue; SkillRaceClassInfoMapBounds bounds = sSpellMgr.GetSkillRaceClassInfoMapBounds(abilityEntry->skillId); for (SkillRaceClassInfoMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr) { SkillRaceClassInfoEntry const* skillRCEntry = itr->second; if ((skillRCEntry->raceMask & racemask) && (skillRCEntry->classMask & classmask)) { if (skillRCEntry->flags & ABILITY_SKILL_NONTRAINABLE) return false; if (pReqlevel) // show trainers list case { if (skillRCEntry->reqLevel) { *pReqlevel = skillRCEntry->reqLevel; return true; } } else // check availble case at train { if (skillRCEntry->reqLevel && getLevel() < skillRCEntry->reqLevel) return false; } } } return true; } return false; } bool Player::HasQuestForGO(int32 GOId) const { for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) { uint32 questid = GetQuestSlotQuestId(i); if ( questid == 0 ) continue; QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid); if (qs_itr == mQuestStatus.end()) continue; QuestStatusData const& qs = qs_itr->second; if (qs.m_status == QUEST_STATUS_INCOMPLETE) { Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid); if(!qinfo) continue; if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid()) continue; for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) { if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case continue; if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j]) return true; } } } return false; } void Player::UpdateForQuestWorldObjects() { if (m_clientGUIDs.empty() || !GetMap()) return; UpdateData udata; WorldPacket packet; for(ObjectGuidSet::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr) { if (itr->IsGameObject()) { if (GameObject *obj = GetMap()->GetGameObject(*itr)) obj->BuildValuesUpdateBlockForPlayer(&udata,this); } else if (itr->IsCreatureOrVehicle()) { Creature *obj = GetMap()->GetAnyTypeCreature(*itr); if(!obj) continue; // check if this unit requires quest specific flags if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK)) continue; SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry()); for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr) { if (_itr->second.questStart || _itr->second.questEnd) { obj->BuildCreateUpdateBlockForPlayer(&udata,this); break; } } } } udata.BuildPacket(&packet); GetSession()->SendPacket(&packet); } void Player::SummonIfPossible(bool agree) { if(!agree) { m_summon_expire = 0; return; } // expire and auto declined if (m_summon_expire < time(NULL)) return; // stop taxi flight at summon if (IsTaxiFlying()) { GetMotionMaster()->MoveIdle(); m_taxi.ClearTaxiDestinations(); } // drop flag at summon // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag if (BattleGround *bg = GetBattleGround()) bg->EventPlayerDroppedFlag(this); m_summon_expire = 0; GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1); TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation()); } void Player::RemoveItemDurations( Item *item ) { for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr) { if(*itr==item) { m_itemDuration.erase(itr); break; } } } void Player::AddItemDurations( Item *item ) { if (item->GetUInt32Value(ITEM_FIELD_DURATION)) { m_itemDuration.push_back(item); item->SendTimeUpdate(this); } } void Player::AutoUnequipOffhandIfNeed() { Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND ); if(!offItem) return; // need unequip offhand for 2h-weapon without TitanGrip (in any from hands) if ((CanDualWield() || offItem->GetProto()->InventoryType == INVTYPE_SHIELD || offItem->GetProto()->InventoryType == INVTYPE_HOLDABLE) && (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))) return; ItemPosCountVec off_dest; uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ); if ( off_msg == EQUIP_ERR_OK ) { RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true); StoreItem( off_dest, offItem, true ); } else { MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true); CharacterDatabase.BeginTransaction(); offItem->DeleteFromInventoryDB(); // deletes item from character's inventory offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone CharacterDatabase.CommitTransaction(); std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM); MailDraft(subject, "There's were problems with equipping this item.").AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED); } } bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem) { if (spellInfo->EquippedItemClass < 0) return true; // scan other equipped items for same requirements (mostly 2 daggers/etc) // for optimize check 2 used cases only switch(spellInfo->EquippedItemClass) { case ITEM_CLASS_WEAPON: { for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i) if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; break; } case ITEM_CLASS_ARMOR: { // tabard not have dependent spells for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i) if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; // shields can be equipped to offhand slot if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; // ranged slot can have some armor subclasses if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED)) if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; break; } default: sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass); break; } return false; } bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const { // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION)) return true; // Check no reagent use mask ClassFamilyMask noReagentMask(GetUInt64Value(PLAYER_NO_REAGENT_COST_1), GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2)); if (spellInfo->IsFitToFamilyMask(noReagentMask)) return true; return false; } void Player::RemoveItemDependentAurasAndCasts( Item * pItem ) { SpellAuraHolderMap& auras = GetSpellAuraHolderMap(); for(SpellAuraHolderMap::const_iterator itr = auras.begin(); itr != auras.end(); ) { // skip passive (passive item dependent spells work in another way) and not self applied auras SpellEntry const* spellInfo = itr->second->GetSpellProto(); if (itr->second->IsPassive() || itr->second->GetCasterGuid() != GetObjectGuid()) { ++itr; continue; } // Remove spells triggered by equipped item auras if (pItem->HasTriggeredByAuraSpell(spellInfo)) { RemoveAurasDueToSpell(itr->second->GetId()); itr = auras.begin(); continue; } // skip if not item dependent or have alternative item if (HasItemFitToSpellReqirements(spellInfo,pItem)) { ++itr; continue; } // no alt item, remove aura, restart check RemoveAurasDueToSpell(itr->second->GetId()); itr = auras.begin(); } // currently casted spells can be dependent from item for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) ) InterruptSpell(CurrentSpellTypes(i)); } uint32 Player::GetResurrectionSpellId() { // search priceless resurrection possibilities uint32 prio = 0; uint32 spell_id = 0; AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY); for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr) { // Soulstone Resurrection // prio: 3 (max, non death persistent) if ( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 ) { switch((*itr)->GetId()) { case 20707: spell_id = 3026; break; // rank 1 case 20762: spell_id = 20758; break; // rank 2 case 20763: spell_id = 20759; break; // rank 3 case 20764: spell_id = 20760; break; // rank 4 case 20765: spell_id = 20761; break; // rank 5 case 27239: spell_id = 27240; break; // rank 6 case 47883: spell_id = 47882; break; // rank 7 default: sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId()); continue; } prio = 3; } // Twisting Nether // prio: 2 (max) else if((*itr)->GetId()==23701 && roll_chance_i(10)) { prio = 2; spell_id = 23700; } } // Reincarnation (passive spell) // prio: 1 // Glyph of Renewed Life remove reagent requiremnnt if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0))) spell_id = 21169; return spell_id; } // Used in triggers for check "Only to targets that grant experience or honor" req bool Player::isHonorOrXPTarget(Unit* pVictim) const { if (!pVictim) return false; uint32 v_level = pVictim->getLevel(); uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel()); // Victim level less gray level if (v_level<=k_grey) return false; if (pVictim->GetTypeId() == TYPEID_UNIT) { if (((Creature*)pVictim)->IsTotem() || ((Creature*)pVictim)->IsPet() || ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL) return false; } return true; } void Player::RewardSinglePlayerAtKill(Unit* pVictim) { bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer(); uint32 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim); // honor can be in PvP and !PvP (racial leader) cases RewardHonor(pVictim,1); // xp and reputation only in !PvP case if(!PvP) { RewardReputation(pVictim,1); GiveXP(xp, pVictim); if (Pet* pet = GetPet()) pet->GivePetXP(xp); // normal creature (not pet/etc) can be only in !PvP case if (pVictim->GetTypeId()==TYPEID_UNIT) if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry())) KilledMonster(normalInfo, pVictim->GetObjectGuid()); } } void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource) { ObjectGuid creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetObjectGuid() : ObjectGuid(); // prepare data for near group iteration if (Group *pGroup = GetGroup()) { for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* pGroupGuy = itr->getSource(); if (!pGroupGuy) continue; if (!pGroupGuy->IsAtGroupRewardDistance(pRewardSource)) continue; // member (alive or dead) or his corpse at req. distance // quest objectives updated only for alive group member or dead but with not released body if (pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) pGroupGuy->KilledMonsterCredit(creature_id, creature_guid); } } else // if (!pGroup) KilledMonsterCredit(creature_id, creature_guid); } void Player::RewardPlayerAndGroupAtCast(WorldObject* pRewardSource, uint32 spellid) { // prepare data for near group iteration if (Group *pGroup = GetGroup()) { for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* pGroupGuy = itr->getSource(); if(!pGroupGuy) continue; if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource)) continue; // member (alive or dead) or his corpse at req. distance // quest objectives updated only for alive group member or dead but with not released body if (pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) pGroupGuy->CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid, pGroupGuy == this); } } else // if (!pGroup) CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid); } bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const { if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE))) return true; if (isAlive()) return false; Corpse* corpse = GetCorpse(); if (!corpse) return false; return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)); } uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const { Item* item = GetWeaponForAttack(attType,true,true); // unarmed only with base attack if (attType != BASE_ATTACK && !item) return 0; // weapon skill or (unarmed for base attack) uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED); return GetBaseSkillValue(skill); } void Player::ResurectUsingRequestData() { /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse if (m_resurrectGuid.IsPlayer()) TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation()); //we cannot resurrect player when we triggered far teleport //player will be resurrected upon teleportation if (IsBeingTeleportedFar()) { ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER); return; } ResurrectPlayer(0.0f,false); if (GetMaxHealth() > m_resurrectHealth) SetHealth( m_resurrectHealth ); else SetHealth( GetMaxHealth() ); if (GetMaxPower(POWER_MANA) > m_resurrectMana) SetPower(POWER_MANA, m_resurrectMana ); else SetPower(POWER_MANA, GetMaxPower(POWER_MANA) ); SetPower(POWER_RAGE, 0 ); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) ); SpawnCorpseBones(); } void Player::SetClientControl(Unit* target, uint8 allowMove) { WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1); data << target->GetPackGUID(); data << uint8(allowMove); if (GetSession()) GetSession()->SendPacket(&data); } void Player::UpdateZoneDependentAuras() { // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(m_zoneUpdateId); for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, 0)) if (!HasAura(itr->second->spellId, EFFECT_INDEX_0)) CastSpell(this,itr->second->spellId,true); } void Player::UpdateAreaDependentAuras() { // remove auras from spells with area limitations SpellIdSet toRemoveSpellList; { MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS); SpellAuraHolderMap const& holdersMap = GetSpellAuraHolderMap(); for(SpellAuraHolderMap::const_iterator iter = holdersMap.begin(); iter != holdersMap.end(); ++iter) { // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date if (iter->second && (sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(), GetMapId(), m_zoneUpdateId, m_areaUpdateId, this) != SPELL_CAST_OK)) toRemoveSpellList.insert(iter->first); } } if (!toRemoveSpellList.empty()) for (SpellIdSet::iterator i = toRemoveSpellList.begin(); i != toRemoveSpellList.end(); ++i) RemoveAurasDueToSpell(*i); // some auras applied at subzone enter SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(m_areaUpdateId); for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, m_areaUpdateId)) if (!HasAura(itr->second->spellId, EFFECT_INDEX_0)) CastSpell(this,itr->second->spellId,true); } struct UpdateZoneDependentPetsHelper { explicit UpdateZoneDependentPetsHelper(Player* _owner, uint32 zone, uint32 area) : owner(_owner), zone_id(zone), area_id(area) {} void operator()(Unit* unit) const { if (unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->IsPet() && !((Pet*)unit)->IsPermanentPetFor(owner)) if (uint32 spell_id = unit->GetUInt32Value(UNIT_CREATED_BY_SPELL)) if (SpellEntry const* spellEntry = sSpellStore.LookupEntry(spell_id)) if (sSpellMgr.GetSpellAllowedInLocationError(spellEntry, owner->GetMapId(), zone_id, area_id, owner) != SPELL_CAST_OK) ((Pet*)unit)->Unsummon(PET_SAVE_AS_DELETED, owner); } Player* owner; uint32 zone_id; uint32 area_id; }; void Player::UpdateZoneDependentPets() { // check pet (permanent pets ignored), minipet, guardians (including protector) CallForAllControlledUnits(UpdateZoneDependentPetsHelper(this, m_zoneUpdateId, m_areaUpdateId), CONTROLLED_PET|CONTROLLED_GUARDIANS|CONTROLLED_MINIPET); } uint32 Player::GetCorpseReclaimDelay(bool pvp) const { if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) || (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) )) { return copseReclaimDelay[0]; } time_t now = time(NULL); // 0..2 full period uint32 count = (now < m_deathExpireTime) ? uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP) : 0; return copseReclaimDelay[count]; } void Player::UpdateCorpseReclaimDelay() { bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH; if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) || (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) )) return; time_t now = time(NULL); if (now < m_deathExpireTime) { // full and partly periods 1..3 uint32 count = uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1); if (count < MAX_DEATH_COUNT) m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP; else m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP; } else m_deathExpireTime = now+DEATH_EXPIRE_STEP; } void Player::SendCorpseReclaimDelay(bool load) { Corpse* corpse = GetCorpse(); if (!corpse) return; uint32 delay; if (load) { if (corpse->GetGhostTime() > m_deathExpireTime) return; bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP; uint32 count; if ((pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) || (!pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE))) { count = uint32(m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP; if (count>=MAX_DEATH_COUNT) count = MAX_DEATH_COUNT-1; } else count=0; time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count]; time_t now = time(NULL); if (now >= expected_time) return; delay = uint32(expected_time-now); } else delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP); //! corpse reclaim delay 30 * 1000ms or longer at often deaths WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4); data << uint32(delay*IN_MILLISECONDS); GetSession()->SendPacket( &data ); } Player* Player::GetNextRandomRaidMember(float radius) { Group *pGroup = GetGroup(); if(!pGroup) return NULL; std::vector<Player*> nearMembers; nearMembers.reserve(pGroup->GetMembersCount()); for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); // IsHostileTo check duel and controlled by enemy if ( Target && Target != this && IsWithinDistInMap(Target, radius) && !Target->HasInvisibilityAura() && !IsHostileTo(Target) ) nearMembers.push_back(Target); } if (nearMembers.empty()) return NULL; uint32 randTarget = urand(0,nearMembers.size()-1); return nearMembers[randTarget]; } PartyResult Player::CanUninviteFromGroup() const { const Group* grp = GetGroup(); if (!grp) return ERR_NOT_IN_GROUP; if (!grp->IsLeader(GetObjectGuid()) && !grp->IsAssistant(GetObjectGuid())) return ERR_NOT_LEADER; if (InBattleGround()) return ERR_INVITE_RESTRICTED; return ERR_PARTY_RESULT_OK; } void Player::SetBattleGroundRaid(Group* group, int8 subgroup) { //we must move references from m_group to m_originalGroup SetOriginalGroup(GetGroup(), GetSubGroup()); m_group.unlink(); m_group.link(group, this); m_group.setSubGroup((uint8)subgroup); } void Player::RemoveFromBattleGroundRaid() { //remove existing reference m_group.unlink(); if ( Group* group = GetOriginalGroup() ) { m_group.link(group, this); m_group.setSubGroup(GetOriginalSubGroup()); } SetOriginalGroup(NULL); } void Player::SetOriginalGroup(Group *group, int8 subgroup) { if ( group == NULL ) m_originalGroup.unlink(); else { // never use SetOriginalGroup without a subgroup unless you specify NULL for group MANGOS_ASSERT(subgroup >= 0); m_originalGroup.link(group, this); m_originalGroup.setSubGroup((uint8)subgroup); } } void Player::UpdateUnderwaterState( Map* m, float x, float y, float z ) { GridMapLiquidData liquid_status; GridMapLiquidStatus res = m->GetTerrain()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status); if (!res) { m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWATER_INDARKWATER); // Small hack for enable breath in WMO /* if (IsInWater()) m_MirrorTimerFlags|=UNDERWATER_INWATER; */ return; } // All liquids type - check under water position if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME)) { if ( res & LIQUID_MAP_UNDER_WATER) m_MirrorTimerFlags |= UNDERWATER_INWATER; else m_MirrorTimerFlags &= ~UNDERWATER_INWATER; } // Allow travel in dark water on taxi or transport if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !IsTaxiFlying() && !GetTransport()) m_MirrorTimerFlags |= UNDERWATER_INDARKWATER; else m_MirrorTimerFlags &= ~UNDERWATER_INDARKWATER; // in lava check, anywhere in lava level if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA) { if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK)) m_MirrorTimerFlags |= UNDERWATER_INLAVA; else m_MirrorTimerFlags &= ~UNDERWATER_INLAVA; } // in slime check, anywhere in slime level if (liquid_status.type&MAP_LIQUID_TYPE_SLIME) { if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK)) m_MirrorTimerFlags |= UNDERWATER_INSLIME; else m_MirrorTimerFlags &= ~UNDERWATER_INSLIME; } } void Player::SetCanParry( bool value ) { if (m_canParry==value) return; m_canParry = value; UpdateParryPercentage(); } void Player::SetCanBlock( bool value ) { if (m_canBlock==value) return; m_canBlock = value; UpdateBlockPercentage(); } bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const { for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr) if (itr->pos == pos) return true; return false; } bool Player::CanUseBattleGroundObject() { // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction) // maybe gameobject code should handle that ForceReaction usage // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet return ( //InBattleGround() && // in battleground - not need, check in other cases //!IsMounted() && - not correct, player is dismounted when he clicks on flag //player cannot use object when he is invulnerable (immune) !isTotalImmune() && // not totally immune //i'm not sure if these two are correct, because invisible players should get visible when they click on flag !HasStealthAura() && // not stealthed !HasInvisibilityAura() && // not invisible !HasAura(SPELL_RECENTLY_DROPPED_FLAG, EFFECT_INDEX_0) &&// can't pickup isAlive() // live player ); } bool Player::CanCaptureTowerPoint() { return ( !HasStealthAura() && // not stealthed !HasInvisibilityAura() && // not invisible isAlive() // live player ); } uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, uint8 newskintone) { uint32 level = getLevel(); if (level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; // max level in this dbc uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2); uint8 haircolor = GetByteValue(PLAYER_BYTES, 3); uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0); uint8 skintone = GetByteValue(PLAYER_BYTES, 0); if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && ((skintone == newskintone) || (newskintone == -1))) return 0; GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1); if(!bsc) // shouldn't happen return 0xFFFFFFFF; float cost = 0; if (hairstyle != newhairstyle) cost += bsc->cost; // full price if((haircolor != newhaircolor) && (hairstyle == newhairstyle)) cost += bsc->cost * 0.5f; // +1/2 of price if (facialhair != newfacialhair) cost += bsc->cost * 0.75f; // +3/4 of price if (skintone != newskintone && newskintone != -1) // +1/2 of price cost += bsc->cost * 0.5f; return uint32(cost); } void Player::InitGlyphsForLevel() { for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i) if (GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i)) if (gs->Order) SetGlyphSlot(gs->Order - 1, gs->Id); uint32 level = getLevel(); uint32 value = 0; // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level if (level >= 15) value |= (0x01 | 0x02); if (level >= 30) value |= 0x08; if (level >= 50) value |= 0x04; if (level >= 70) value |= 0x10; if (level >= 80) value |= 0x20; SetUInt32Value(PLAYER_GLYPHS_ENABLED, value); } void Player::ApplyGlyph(uint8 slot, bool apply) { if (uint32 glyph = GetGlyph(slot)) { if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph)) { if (apply) { CastSpell(this, gp->SpellId, true); SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph); } else { RemoveAurasDueToSpell(gp->SpellId); SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, 0); } } } } void Player::ApplyGlyphs(bool apply) { for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i) ApplyGlyph(i,apply); } bool Player::isTotalImmune() { AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY); uint32 immuneMask = 0; for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr) { immuneMask |= (*itr)->GetModifier()->m_miscvalue; if ( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity return true; } return false; } bool Player::HasTitle(uint32 bitIndex) const { if (bitIndex > MAX_TITLE_INDEX) return false; uint32 fieldIndexOffset = bitIndex / 32; uint32 flag = 1 << (bitIndex % 32); return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } void Player::SetTitle(CharTitlesEntry const* title, bool lost) { uint32 fieldIndexOffset = title->bit_index / 32; uint32 flag = 1 << (title->bit_index % 32); if (lost) { if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag)) return; RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } else { if (HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag)) return; SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } WorldPacket data(SMSG_TITLE_EARNED, 4 + 4); data << uint32(title->bit_index); data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost GetSession()->SendPacket(&data); } void Player::ConvertRune(uint8 index, RuneType newType, uint32 spellid) { SetCurrentRune(index, newType); if (spellid != 0) SetConvertedBy(index, spellid); WorldPacket data(SMSG_CONVERT_RUNE, 2); data << uint8(index); data << uint8(newType); GetSession()->SendPacket(&data); } bool Player::ActivateRunes(RuneType type, uint32 count) { bool modify = false; for(uint32 j = 0; count > 0 && j < MAX_RUNES; ++j) { if (GetCurrentRune(j) == type && GetRuneCooldown(j) > 0) { SetRuneCooldown(j, 0); --count; modify = true; } } return modify; } void Player::ResyncRunes() { WorldPacket data(SMSG_RESYNC_RUNES, 4 + MAX_RUNES * 2); data << uint32(MAX_RUNES); for(uint32 i = 0; i < MAX_RUNES; ++i) { data << uint8(GetCurrentRune(i)); // rune type data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255) } GetSession()->SendPacket(&data); } void Player::AddRunePower(uint8 index) { WorldPacket data(SMSG_ADD_RUNE_POWER, 4); data << uint32(1 << index); // mask (0x00-0x3F probably) GetSession()->SendPacket(&data); } static RuneType runeSlotTypes[MAX_RUNES] = { /*0*/ RUNE_BLOOD, /*1*/ RUNE_BLOOD, /*2*/ RUNE_UNHOLY, /*3*/ RUNE_UNHOLY, /*4*/ RUNE_FROST, /*5*/ RUNE_FROST }; void Player::InitRunes() { if (getClass() != CLASS_DEATH_KNIGHT) return; m_runes = new Runes; m_runes->runeState = 0; m_runes->needConvert = 0; for(uint32 i = 0; i < MAX_RUNES; ++i) { SetBaseRune(i, runeSlotTypes[i]); // init base types SetCurrentRune(i, runeSlotTypes[i]); // init current types SetRuneCooldown(i, 0); // reset cooldowns SetConvertedBy(i, 0); // init spellid m_runes->SetRuneState(i); } for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i) SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f); } bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const { for(uint32 i = 0; i < MAX_RUNES; ++i) if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0) return false; return true; } void Player::AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast, uint8 bag, uint8 slot) { Loot loot; loot.FillLoot (loot_id, store, this, true); AutoStoreLoot(loot, broadcast, bag, slot); } void Player::AutoStoreLoot(Loot& loot, bool broadcast, uint8 bag, uint8 slot) { uint32 max_slot = loot.GetMaxSlotInLootFor(this); for(uint32 i = 0; i < max_slot; ++i) { LootItem* lootItem = loot.LootItemInSlot(i,this); if (!lootItem) continue; ItemPosCountVec dest; InventoryResult msg = CanStoreNewItem(bag,slot,dest,lootItem->itemid,lootItem->count); if (msg != EQUIP_ERR_OK && slot != NULL_SLOT) msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count); if ( msg != EQUIP_ERR_OK && bag != NULL_BAG) msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count); if (msg != EQUIP_ERR_OK) { SendEquipError( msg, NULL, NULL, lootItem->itemid ); continue; } Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId); SendNewItem(pItem, lootItem->count, false, false, broadcast); } } Item* Player::ConvertItem(Item* item, uint32 newItemId) { uint16 pos = item->GetPos(); Item *pNewItem = Item::CreateItem(newItemId, 1, this); if (!pNewItem) return NULL; // copy enchantments for (uint8 j= PERM_ENCHANTMENT_SLOT; j<=TEMP_ENCHANTMENT_SLOT; ++j) { if (item->GetEnchantmentId(EnchantmentSlot(j))) pNewItem->SetEnchantment(EnchantmentSlot(j), item->GetEnchantmentId(EnchantmentSlot(j)), item->GetEnchantmentDuration(EnchantmentSlot(j)), item->GetEnchantmentCharges(EnchantmentSlot(j))); } // copy durability if (item->GetUInt32Value(ITEM_FIELD_DURABILITY) < item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)) { double loosePercent = 1 - item->GetUInt32Value(ITEM_FIELD_DURABILITY) / double(item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)); DurabilityLoss(pNewItem, loosePercent); } if (IsInventoryPos(pos)) { ItemPosCountVec dest; InventoryResult msg = CanStoreItem(item->GetBagSlot(), item->GetSlot(), dest, pNewItem, true); // ignore cast/combat time restriction if (msg == EQUIP_ERR_OK) { DestroyItem(item->GetBagSlot(), item->GetSlot(), true); return StoreItem( dest, pNewItem, true); } } else if (IsBankPos(pos)) { ItemPosCountVec dest; InventoryResult msg = CanBankItem(item->GetBagSlot(), item->GetSlot(), dest, pNewItem, true); // ignore cast/combat time restriction if (msg == EQUIP_ERR_OK) { DestroyItem(item->GetBagSlot(), item->GetSlot(), true); return BankItem(dest, pNewItem, true); } } else if (IsEquipmentPos (pos)) { uint16 dest; InventoryResult msg = CanEquipItem(item->GetSlot(), dest, pNewItem, true, false); // ignore cast/combat time restriction if (msg == EQUIP_ERR_OK) { DestroyItem(item->GetBagSlot(), item->GetSlot(), true); pNewItem = EquipItem(dest, pNewItem, true); AutoUnequipOffhandIfNeed(); return pNewItem; } } // fail delete pNewItem; return NULL; } uint32 Player::CalculateTalentsPoints() const { uint32 base_level = getClass() == CLASS_DEATH_KNIGHT ? 55 : 9; uint32 base_talent = getLevel() <= base_level ? 0 : getLevel() - base_level; uint32 talentPointsForLevel = base_talent + m_questRewardTalentCount; return uint32(talentPointsForLevel * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT)); } bool Player::CanStartFlyInArea(uint32 mapid, uint32 zone, uint32 area) const { if (isGameMaster()) return true; // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone); if (v_map == 571 && !HasSpell(54197)) // Cold Weather Flying return false; // don't allow flying in Dalaran restricted areas // (no other zones currently has areas with AREA_FLAG_CANNOT_FLY) if (AreaTableEntry const* atEntry = GetAreaEntryByAreaID(area)) return (!(atEntry->flags & AREA_FLAG_CANNOT_FLY)); // TODO: disallow mounting in wintergrasp too when battle is in progress // forced dismount part in Player::UpdateArea() return true; } struct DoPlayerLearnSpell { DoPlayerLearnSpell(Player& _player) : player(_player) {} void operator() (uint32 spell_id) { player.learnSpell(spell_id, false); } Player& player; }; void Player::learnSpellHighRank(uint32 spellid) { learnSpell(spellid, false); DoPlayerLearnSpell worker(*this); sSpellMgr.doForHighRanks(spellid, worker); } void Player::_LoadSkills(QueryResult *result) { // 0 1 2 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid)); uint32 count = 0; if (result) { do { Field *fields = result->Fetch(); uint16 skill = fields[0].GetUInt16(); uint16 value = fields[1].GetUInt16(); uint16 max = fields[2].GetUInt16(); SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill); if(!pSkill) { sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill); continue; } // set fixed skill ranges switch(GetSkillRangeType(pSkill,false)) { case SKILL_RANGE_LANGUAGE: // 300..300 value = max = 300; break; case SKILL_RANGE_MONO: // 1..1, grey monolite bar value = max = 1; break; default: break; } if (value == 0) { sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill); CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill ); continue; } SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0)); SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max)); SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0); mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED))); learnSkillRewardedSpells(skill, value); ++count; if (count >= PLAYER_MAX_SKILLS) // client limit { sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS); break; } } while (result->NextRow()); delete result; } for (; count < PLAYER_MAX_SKILLS; ++count) { SetUInt32Value(PLAYER_SKILL_INDEX(count), 0); SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0); SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0); } // special settings if (getClass()==CLASS_DEATH_KNIGHT) { uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL)); if (base_level < 1) base_level = 1; uint32 base_skill = (base_level-1)*5; // 270 at starting level 55 if (base_skill < 1) base_skill = 1; // skill mast be known and then > 0 in any case if (GetPureSkillValue (SKILL_FIRST_AID) < base_skill) SetSkill(SKILL_FIRST_AID, base_skill, base_skill); if (GetPureSkillValue (SKILL_AXES) < base_skill) SetSkill(SKILL_AXES, base_skill, base_skill); if (GetPureSkillValue (SKILL_DEFENSE) < base_skill) SetSkill(SKILL_DEFENSE, base_skill, base_skill); if (GetPureSkillValue (SKILL_POLEARMS) < base_skill) SetSkill(SKILL_POLEARMS, base_skill, base_skill); if (GetPureSkillValue (SKILL_SWORDS) < base_skill) SetSkill(SKILL_SWORDS, base_skill, base_skill); if (GetPureSkillValue (SKILL_2H_AXES) < base_skill) SetSkill(SKILL_2H_AXES, base_skill, base_skill); if (GetPureSkillValue (SKILL_2H_SWORDS) < base_skill) SetSkill(SKILL_2H_SWORDS, base_skill, base_skill); if (GetPureSkillValue (SKILL_UNARMED) < base_skill) SetSkill(SKILL_UNARMED, base_skill, base_skill); } } uint32 Player::GetPhaseMaskForSpawn() const { uint32 phase = PHASEMASK_NORMAL; if(!isGameMaster()) phase = GetPhaseMask(); else { AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE); if(!phases.empty()) phase = phases.front()->GetMiscValue(); } // some aura phases include 1 normal map in addition to phase itself if (uint32 n_phase = phase & ~PHASEMASK_NORMAL) return n_phase; return PHASEMASK_NORMAL; } InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const { ItemPrototype const* pProto = pItem->GetProto(); // proto based limitations if (InventoryResult res = CanEquipUniqueItem(pProto,eslot,limit_count)) return res; // check unique-equipped on gems for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) continue; SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID); if(!pGem) continue; // include for check equip another gems with same limit category for not equipped item (and then not counted) uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1; if (InventoryResult res = CanEquipUniqueItem(pGem, eslot,gem_limit_count)) return res; } return EQUIP_ERR_OK; } InventoryResult Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const { // check unique-equipped on item if (itemProto->Flags & ITEM_FLAG_UNIQUE_EQUIPPED) { // there is an equip limit on this item if (HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot)) return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; } // check unique-equipped limit if (itemProto->ItemLimitCategory) { ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory); if(!limitEntry) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case if (limit_count > limitEntry->maxCount) return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS; // there is an equip limit on this item if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot)) return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS; } return EQUIP_ERR_OK; } InventoryResult Player::CanEquipMoreJewelcraftingGems(uint32 count, uint8 except_slot) const { //uint32 tempcount = count; for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i == int(except_slot)) continue; Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (!pItem) continue; ItemPrototype const *pProto = pItem->GetProto(); if (!pProto) continue; if (pProto->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)) { count += pItem->GetJewelcraftingGemCount(); if (count > MAX_JEWELCRAFTING_GEMS) return EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED; } } return EQUIP_ERR_OK; } void Player::HandleFall(MovementInfo const& movementInfo) { // calculate total z distance of the fall float z_diff = m_lastFallZ - movementInfo.GetPos()->z; DEBUG_LOG("zDiff = %f", z_diff); //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored // 14.57 can be calculated by resolving damageperc formula below to 0 if (z_diff >= 14.57f && !isDead() && !isGameMaster() && !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) && !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) ) { //Safe fall, fall height reduction int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL); float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f; if (damageperc >0 ) { uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL)); float height = movementInfo.GetPos()->z; UpdateAllowedPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height); if (damage > 0) { //Prevent fall damage from being more than the player maximum health if (damage > GetMaxHealth()) damage = GetMaxHealth(); // Gust of Wind if (GetDummyAura(43621)) damage = GetMaxHealth()/2; uint32 original_health = GetHealth(); uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage); // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case if (isAlive() && final_damage < original_health) GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100)); } //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.GetPos()->z, height, GetPositionZ(), movementInfo.GetFallTime(), height, damage, safe_fall); } } RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // Remove auras that should be removed at landing } void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ ) { GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time); } void Player::StartTimedAchievementCriteria(AchievementCriteriaTypes type, uint32 timedRequirementId, time_t startTime /*= 0*/) { GetAchievementMgr().StartTimedAchievementCriteria(type, timedRequirementId, startTime); } PlayerTalent const* Player::GetKnownTalentById(int32 talentId) const { PlayerTalentMap::const_iterator itr = m_talents[m_activeSpec].find(talentId); if (itr != m_talents[m_activeSpec].end() && itr->second.state != PLAYERSPELL_REMOVED) return &itr->second; else return NULL; } SpellEntry const* Player::GetKnownTalentRankById(int32 talentId) const { if (PlayerTalent const* talent = GetKnownTalentById(talentId)) return sSpellStore.LookupEntry(talent->talentEntry->RankID[talent->currentRank]); else return NULL; } void Player::LearnTalent(uint32 talentId, uint32 talentRank) { uint32 CurTalentPoints = GetFreeTalentPoints(); if (CurTalentPoints == 0) return; if (talentRank >= MAX_TALENT_RANK) return; TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId); if(!talentInfo) return; TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if(!talentTabInfo) return; // prevent learn talent for different class (cheating) if ( (getClassMask() & talentTabInfo->ClassMask) == 0 ) return; // find current max talent rank uint32 curtalent_maxrank = 0; if (PlayerTalent const* talent = GetKnownTalentById(talentId)) curtalent_maxrank = talent->currentRank + 1; // we already have same or higher talent rank learned if (curtalent_maxrank >= (talentRank + 1)) return; // check if we have enough talent points if (CurTalentPoints < (talentRank - curtalent_maxrank + 1)) return; // Check if it requires another talent if (talentInfo->DependsOn > 0) { if (TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn)) { bool hasEnoughRank = false; PlayerTalentMap::iterator dependsOnTalent = m_talents[m_activeSpec].find(depTalentInfo->TalentID); if (dependsOnTalent != m_talents[m_activeSpec].end() && dependsOnTalent->second.state != PLAYERSPELL_REMOVED) { PlayerTalent depTalent = (*dependsOnTalent).second; if (depTalent.currentRank >= talentInfo->DependsOnRank) hasEnoughRank = true; } if (!hasEnoughRank) return; } } // Find out how many points we have in this field uint32 spentPoints = 0; uint32 tTab = talentInfo->TalentTab; if (talentInfo->Row > 0) { for (PlayerTalentMap::const_iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end(); ++iter) if (iter->second.state != PLAYERSPELL_REMOVED && iter->second.talentEntry->TalentTab == tTab) spentPoints += iter->second.currentRank + 1; } // not have required min points spent in talent tree if (spentPoints < (talentInfo->Row * MAX_TALENT_RANK)) return; // spell not set in talent.dbc uint32 spellid = talentInfo->RankID[talentRank]; if ( spellid == 0 ) { sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank); return; } // already known if (HasSpell(spellid)) return; // learn! (other talent ranks will unlearned at learning) learnSpell(spellid, false); DETAIL_LOG("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid); } void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRank) { Pet *pet = GetPet(); if (!pet) return; if (petGuid != pet->GetObjectGuid()) return; uint32 CurTalentPoints = pet->GetFreeTalentPoints(); if (CurTalentPoints == 0) return; if (talentRank >= MAX_PET_TALENT_RANK) return; TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId); if(!talentInfo) return; TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if(!talentTabInfo) return; CreatureInfo const *ci = pet->GetCreatureInfo(); if(!ci) return; CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family); if(!pet_family) return; if (pet_family->petTalentType < 0) // not hunter pet return; // prevent learn talent for different family (cheating) if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask)) return; // find current max talent rank int32 curtalent_maxrank = 0; for(int32 k = MAX_TALENT_RANK-1; k > -1; --k) { if (talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k])) { curtalent_maxrank = k + 1; break; } } // we already have same or higher talent rank learned if (curtalent_maxrank >= int32(talentRank + 1)) return; // check if we have enough talent points if (CurTalentPoints < (talentRank - curtalent_maxrank + 1)) return; // Check if it requires another talent if (talentInfo->DependsOn > 0) { if (TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn)) { bool hasEnoughRank = false; for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i) { if (depTalentInfo->RankID[i] != 0) if (pet->HasSpell(depTalentInfo->RankID[i])) hasEnoughRank = true; } if (!hasEnoughRank) return; } } // Find out how many points we have in this field uint32 spentPoints = 0; uint32 tTab = talentInfo->TalentTab; if (talentInfo->Row > 0) { unsigned int numRows = sTalentStore.GetNumRows(); for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents. { // Someday, someone needs to revamp const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i); if (tmpTalent) // the way talents are tracked { if (tmpTalent->TalentTab == tTab) { for (int j = 0; j < MAX_TALENT_RANK; ++j) { if (tmpTalent->RankID[j] != 0) { if (pet->HasSpell(tmpTalent->RankID[j])) { spentPoints += j + 1; } } } } } } } // not have required min points spent in talent tree if (spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK)) return; // spell not set in talent.dbc uint32 spellid = talentInfo->RankID[talentRank]; if ( spellid == 0 ) { sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank); return; } // already known if (pet->HasSpell(spellid)) return; // learn! (other talent ranks will unlearned at learning) pet->learnSpell(spellid); DETAIL_LOG("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid); } void Player::UpdateKnownCurrencies(uint32 itemId, bool apply) { if (CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId)) { if (apply) SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1))); else RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1))); } } void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode ) { if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND) SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z); } void Player::UnsummonPetTemporaryIfAny(bool full) { Pet* minipet = GetMiniPet(); if (full && minipet) minipet->Unsummon(PET_SAVE_AS_DELETED, this); Pet* pet = GetPet(); if (!pet) return; Map* petmap = pet->GetMap(); if (!petmap) return; GroupPetList m_groupPetsTmp = GetPets(); // Original list may be modified in this function if (m_groupPetsTmp.empty()) return; for (GroupPetList::const_iterator itr = m_groupPetsTmp.begin(); itr != m_groupPetsTmp.end(); ++itr) { if (Pet* pet = petmap->GetPet(*itr)) { if (!sWorld.getConfig(CONFIG_BOOL_PET_SAVE_ALL)) { if (!GetTemporaryUnsummonedPetCount() && pet->isControlled() && !pet->isTemporarySummoned() && !pet->GetPetCounter()) { SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber()); pet->Unsummon(PET_SAVE_AS_CURRENT, this); } else if (full) pet->Unsummon(PET_SAVE_NOT_IN_SLOT, this); } else { SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber(), pet->GetPetCounter()); if (!pet->GetPetCounter() && pet->getPetType() == HUNTER_PET) pet->Unsummon(PET_SAVE_AS_CURRENT, this); else pet->Unsummon(PET_SAVE_NOT_IN_SLOT, this); } DEBUG_LOG("Player::UnsummonPetTemporaryIfAny tempusummon pet %s ",(*itr).GetString().c_str()); } } } void Player::ResummonPetTemporaryUnSummonedIfAny() { if (!GetTemporaryUnsummonedPetCount()) return; // not resummon in not appropriate state if (IsPetNeedBeTemporaryUnsummoned()) return; // if (GetPetGuid()) // return; // sort petlist - 0 must be _last_ for (uint8 count = GetTemporaryUnsummonedPetCount(); count != 0; --count) { uint32 petnum = GetTemporaryUnsummonedPetNumber(count-1); if (petnum == 0) continue; DEBUG_LOG("Player::ResummonPetTemporaryUnSummonedIfAny summon pet %u count %u",petnum, count-1); Pet* NewPet = new Pet; NewPet->SetPetCounter(count-1); if(!NewPet->LoadPetFromDB(this, 0, petnum)) delete NewPet; } ClearTemporaryUnsummonedPetStorage(); } uint32 Player::GetTemporaryUnsummonedPetNumber(uint8 count) { PetNumberList::const_iterator itr = m_temporaryUnsummonedPetNumber.find(count); return itr != m_temporaryUnsummonedPetNumber.end() ? itr->second : 0; }; bool Player::canSeeSpellClickOn(Creature const *c) const { if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK)) return false; SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry()); for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr) if (itr->second.IsFitToRequirements(this)) return true; return false; } void Player::BuildPlayerTalentsInfoData(WorldPacket *data) { *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints *data << uint8(m_specsCount); // talent group count (0, 1 or 2) *data << uint8(m_activeSpec); // talent group index (0 or 1) if (m_specsCount) { // loop through all specs (only 1 for now) for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx) { uint8 talentIdCount = 0; size_t pos = data->wpos(); *data << uint8(talentIdCount); // [PH], talentIdCount // find class talent tabs (all players have 3 talent tabs) uint32 const* talentTabIds = GetTalentTabPages(getClass()); for(uint32 i = 0; i < 3; ++i) { uint32 talentTabId = talentTabIds[i]; for(PlayerTalentMap::iterator iter = m_talents[specIdx].begin(); iter != m_talents[specIdx].end(); ++iter) { PlayerTalent talent = (*iter).second; if (talent.state == PLAYERSPELL_REMOVED) continue; // skip another tab talents if (talent.talentEntry->TalentTab != talentTabId) continue; *data << uint32(talent.talentEntry->TalentID); // Talent.dbc *data << uint8(talent.currentRank); // talentMaxRank (0-4) ++talentIdCount; } } data->put<uint8>(pos, talentIdCount); // put real count *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count // GlyphProperties.dbc for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i) *data << uint16(m_glyphs[specIdx][i].GetId()); } } } void Player::BuildPetTalentsInfoData(WorldPacket *data) { uint32 unspentTalentPoints = 0; size_t pointsPos = data->wpos(); *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints uint8 talentIdCount = 0; size_t countPos = data->wpos(); *data << uint8(talentIdCount); // [PH], talentIdCount Pet *pet = GetPet(); if(!pet) return; unspentTalentPoints = pet->GetFreeTalentPoints(); data->put<uint32>(pointsPos, unspentTalentPoints); // put real points CreatureInfo const *ci = pet->GetCreatureInfo(); if(!ci) return; CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family); if(!pet_family || pet_family->petTalentType < 0) return; for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId) { TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId ); if(!talentTabInfo) continue; if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask)) continue; for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId); if(!talentInfo) continue; // skip another tab talents if (talentInfo->TalentTab != talentTabId) continue; // find max talent rank int32 curtalent_maxrank = -1; for(int32 k = 4; k > -1; --k) { if (talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k])) { curtalent_maxrank = k; break; } } // not learned talent if (curtalent_maxrank < 0) continue; *data << uint32(talentInfo->TalentID); // Talent.dbc *data << uint8(curtalent_maxrank); // talentMaxRank (0-4) ++talentIdCount; } data->put<uint8>(countPos, talentIdCount); // put real count break; } } void Player::SendTalentsInfoData(bool pet) { WorldPacket data(SMSG_TALENT_UPDATE, 50); data << uint8(pet ? 1 : 0); if (pet) BuildPetTalentsInfoData(&data); else BuildPlayerTalentsInfoData(&data); GetSession()->SendPacket(&data); } void Player::BuildEnchantmentsInfoData(WorldPacket *data) { uint32 slotUsedMask = 0; size_t slotUsedMaskPos = data->wpos(); *data << uint32(slotUsedMask); // slotUsedMask < 0x80000 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) { Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if(!item) continue; slotUsedMask |= (1 << i); *data << uint32(item->GetEntry()); // item entry uint16 enchantmentMask = 0; size_t enchantmentMaskPos = data->wpos(); *data << uint16(enchantmentMask); // enchantmentMask < 0x1000 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j) { uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j)); if(!enchId) continue; enchantmentMask |= (1 << j); *data << uint16(enchId); // enchantmentId? } data->put<uint16>(enchantmentMaskPos, enchantmentMask); *data << uint16(item->GetItemRandomPropertyId()); *data << item->GetGuidValue(ITEM_FIELD_CREATOR).WriteAsPacked(); *data << uint32(item->GetItemSuffixFactor()); } data->put<uint32>(slotUsedMaskPos, slotUsedMask); } void Player::SendEquipmentSetList() { uint32 count = 0; WorldPacket data(SMSG_LOAD_EQUIPMENT_SET, 4); size_t count_pos = data.wpos(); data << uint32(count); // count placeholder for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) { if (itr->second.state==EQUIPMENT_SET_DELETED) continue; data.appendPackGUID(itr->second.Guid); data << uint32(itr->first); data << itr->second.Name; data << itr->second.IconName; for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) { // ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HIGHGUID_ITEM if (itr->second.IgnoreMask & (1 << i)) data << ObjectGuid(uint64(1)).WriteAsPacked(); else data << ObjectGuid(HIGHGUID_ITEM, itr->second.Items[i]).WriteAsPacked(); } ++count; // client have limit but it checked at loading and set } data.put<uint32>(count_pos, count); GetSession()->SendPacket(&data); } void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset) { if (eqset.Guid != 0) { bool found = false; for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) { if((itr->second.Guid == eqset.Guid) && (itr->first == index)) { found = true; break; } } if(!found) // something wrong... { sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index); return; } } EquipmentSet& eqslot = m_EquipmentSets[index]; EquipmentSetUpdateState old_state = eqslot.state; eqslot = eqset; if (eqset.Guid == 0) { eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid(); WorldPacket data(SMSG_EQUIPMENT_SET_ID, 4 + 1); data << uint32(index); data.appendPackGUID(eqslot.Guid); GetSession()->SendPacket(&data); } eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED; } void Player::_SaveEquipmentSets() { static SqlStatementID updSets ; static SqlStatementID insSets ; static SqlStatementID delSets ; for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();) { uint32 index = itr->first; EquipmentSet& eqset = itr->second; switch(eqset.state) { case EQUIPMENT_SET_UNCHANGED: ++itr; break; // nothing do case EQUIPMENT_SET_CHANGED: { SqlStatement stmt = CharacterDatabase.CreateStatement(updSets, "UPDATE character_equipmentsets SET name=?, iconname=?, ignore_mask=?, item0=?, item1=?, item2=?, item3=?, item4=?, " "item5=?, item6=?, item7=?, item8=?, item9=?, item10=?, item11=?, item12=?, item13=?, item14=?, " "item15=?, item16=?, item17=?, item18=? WHERE guid=? AND setguid=? AND setindex=?"); stmt.addString(eqset.Name); stmt.addString(eqset.IconName); stmt.addUInt32(eqset.IgnoreMask); for (int i = 0; i < EQUIPMENT_SLOT_END; ++i) stmt.addUInt32(eqset.Items[i]); stmt.addUInt32(GetGUIDLow()); stmt.addUInt64(eqset.Guid); stmt.addUInt32(index); stmt.Execute(); eqset.state = EQUIPMENT_SET_UNCHANGED; ++itr; break; } case EQUIPMENT_SET_NEW: { SqlStatement stmt = CharacterDatabase.CreateStatement(insSets, "INSERT INTO character_equipmentsets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.addUInt32(GetGUIDLow()); stmt.addUInt64(eqset.Guid); stmt.addUInt32(index); stmt.addString(eqset.Name); stmt.addString(eqset.IconName); stmt.addUInt32(eqset.IgnoreMask); for (int i = 0; i < EQUIPMENT_SLOT_END; ++i) stmt.addUInt32(eqset.Items[i]); stmt.Execute(); eqset.state = EQUIPMENT_SET_UNCHANGED; ++itr; break; } case EQUIPMENT_SET_DELETED: { SqlStatement stmt = CharacterDatabase.CreateStatement(delSets, "DELETE FROM character_equipmentsets WHERE setguid = ?"); stmt.PExecute(eqset.Guid); m_EquipmentSets.erase(itr++); break; } } } } void Player::_SaveBGData(bool forceClean) { if (forceClean) m_bgData = BGData(); // nothing save else if (!m_bgData.m_needSave) return; static SqlStatementID delBGData ; static SqlStatementID insBGData ; SqlStatement stmt = CharacterDatabase.CreateStatement(delBGData, "DELETE FROM character_battleground_data WHERE guid = ?"); stmt.PExecute(GetGUIDLow()); if (m_bgData.bgInstanceID || m_bgData.forLFG) { stmt = CharacterDatabase.CreateStatement(insBGData, "INSERT INTO character_battleground_data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */ stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(m_bgData.bgInstanceID); stmt.addUInt32(uint32(m_bgData.bgTeam)); stmt.addFloat(m_bgData.joinPos.coord_x); stmt.addFloat(m_bgData.joinPos.coord_y); stmt.addFloat(m_bgData.joinPos.coord_z); stmt.addFloat(m_bgData.joinPos.orientation); stmt.addUInt32(m_bgData.joinPos.mapid); stmt.addUInt32(m_bgData.taxiPath[0]); stmt.addUInt32(m_bgData.taxiPath[1]); stmt.addUInt32(m_bgData.mountSpell); stmt.Execute(); } m_bgData.m_needSave = false; } void Player::DeleteEquipmentSet(uint64 setGuid) { for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) { if (itr->second.Guid == setGuid) { if (itr->second.state == EQUIPMENT_SET_NEW) m_EquipmentSets.erase(itr); else itr->second.state = EQUIPMENT_SET_DELETED; break; } } } void Player::ActivateSpec(uint8 specNum) { if (GetActiveSpec() == specNum) return; if (specNum >= GetSpecsCount()) return; if (Pet* pet = GetPet()) pet->Unsummon(PET_SAVE_REAGENTS, this); SendActionButtons(2); // prevent deletion of action buttons by client at spell unlearn or by player while spec change in progress SendLockActionButtons(); ApplyGlyphs(false); // copy of new talent spec (we will use it as model for converting current tlanet state to new) PlayerTalentMap tempSpec = m_talents[specNum]; // copy old spec talents to new one, must be before spec switch to have previous spec num(as m_activeSpec) m_talents[specNum] = m_talents[m_activeSpec]; SetActiveSpec(specNum); // remove all talent spells that don't exist in next spec but exist in old for (PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].begin(); specIter != m_talents[m_activeSpec].end();) { PlayerTalent& talent = specIter->second; if (talent.state == PLAYERSPELL_REMOVED) { ++specIter; continue; } PlayerTalentMap::iterator iterTempSpec = tempSpec.find(specIter->first); // remove any talent rank if talent not listed in temp spec if (iterTempSpec == tempSpec.end() || iterTempSpec->second.state == PLAYERSPELL_REMOVED) { TalentEntry const *talentInfo = talent.talentEntry; for(int r = 0; r < MAX_TALENT_RANK; ++r) if (talentInfo->RankID[r]) { removeSpell(talentInfo->RankID[r],!IsPassiveSpell(talentInfo->RankID[r]),false); SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[r]); for (int k = 0; k < MAX_EFFECT_INDEX; ++k) if (spellInfo->EffectTriggerSpell[k]) removeSpell(spellInfo->EffectTriggerSpell[k]); // if spell is a buff, remove it from group members // TODO: this should affect all players, not only group members? if (SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[r])) { bool bRemoveAura = false; for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if ((spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA || spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_RAID) && IsPositiveEffect(spellInfo, SpellEffectIndex(i))) { bRemoveAura = true; break; } } Group *group = GetGroup(); if (bRemoveAura && group) { for(GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) { if (Player *pGroupGuy = itr->getSource()) { if (pGroupGuy->GetObjectGuid() == GetObjectGuid()) continue; if (SpellAuraHolderPtr holder = pGroupGuy->GetSpellAuraHolder(talentInfo->RankID[r], GetObjectGuid())) pGroupGuy->RemoveSpellAuraHolder(holder); } } } } } specIter = m_talents[m_activeSpec].begin(); } else ++specIter; } // now new spec data have only talents (maybe different rank) as in temp spec data, sync ranks then. for (PlayerTalentMap::const_iterator tempIter = tempSpec.begin(); tempIter != tempSpec.end(); ++tempIter) { PlayerTalent const& talent = tempIter->second; // removed state talent already unlearned in prev. loop // but we need restore it if it deleted for finish removed-marked data in DB if (talent.state == PLAYERSPELL_REMOVED) { m_talents[m_activeSpec][tempIter->first] = talent; continue; } uint32 talentSpellId = talent.talentEntry->RankID[talent.currentRank]; // learn talent spells if they not in new spec (old spec copy) // and if they have different rank if (PlayerTalent const* cur_talent = GetKnownTalentById(tempIter->first)) { if (cur_talent->currentRank != talent.currentRank) learnSpell(talentSpellId, false); } else learnSpell(talentSpellId, false); // sync states - original state is changed in addSpell that learnSpell calls PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].find(tempIter->first); if (specIter != m_talents[m_activeSpec].end()) specIter->second.state = talent.state; else { sLog.outError("ActivateSpec: Talent spell %u expected to learned at spec switch but not listed in talents at final check!", talentSpellId); // attempt resync DB state (deleted lost spell from DB) if (talent.state != PLAYERSPELL_NEW) { PlayerTalent& talentNew = m_talents[m_activeSpec][tempIter->first]; talentNew = talent; talentNew.state = PLAYERSPELL_REMOVED; } } } InitTalentForLevel(); // recheck action buttons (not checked at loading/spec copy) ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec]; for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ) { if (itr->second.uState != ACTIONBUTTON_DELETED) { // remove broken without any output (it can be not correct because talents not copied at spec creating) if (!IsActionButtonDataValid(itr->first,itr->second.GetAction(),itr->second.GetType(), this, false)) { removeActionButton(m_activeSpec,itr->first); itr = currentActionButtonList.begin(); continue; } } ++itr; } ResummonPetTemporaryUnSummonedIfAny(); ApplyGlyphs(true); SendInitialActionButtons(); Powers pw = getPowerType(); if (pw != POWER_MANA) SetPower(POWER_MANA, 0); SetPower(pw, 0); } void Player::UpdateSpecCount(uint8 count) { uint8 curCount = GetSpecsCount(); if (curCount == count) return; // maybe current spec data must be copied to 0 spec? if (m_activeSpec >= count) ActivateSpec(0); // copy spec data from new specs if (count > curCount) { // copy action buttons from active spec (more easy in this case iterate first by button) ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec]; for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr) { if (itr->second.uState != ACTIONBUTTON_DELETED) { for(uint8 spec = curCount; spec < count; ++spec) addActionButton(spec,itr->first,itr->second.GetAction(),itr->second.GetType()); } } } // delete spec data for removed specs else if (count < curCount) { // delete action buttons for removed spec for(uint8 spec = count; spec < curCount; ++spec) { // delete action buttons for removed spec for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button) removeActionButton(spec,button); } } SetSpecsCount(count); SendTalentsInfoData(false); } void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ ) { m_atLoginFlags &= ~f; if (in_db_also) CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow()); } void Player::SendClearCooldown( uint32 spell_id, Unit* target ) { if (!target) return; WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8); data << uint32(spell_id); data << target->GetObjectGuid(); SendDirectMessage(&data); } void Player::BuildTeleportAckMsg(WorldPacket& data, float x, float y, float z, float ang) const { MovementInfo mi = m_movementInfo; mi.ChangePosition(x, y, z, ang); data.Initialize(MSG_MOVE_TELEPORT_ACK, 64); data << GetPackGUID(); data << uint32(0); // this value increments every time data << mi; } bool Player::HasMovementFlag( MovementFlags f ) const { return m_movementInfo.HasMovementFlag(f); } void Player::ResetTimeSync() { m_timeSyncCounter = 0; m_timeSyncTimer = 0; m_timeSyncClient = 0; m_timeSyncServer = WorldTimer::getMSTime(); } void Player::SendTimeSync() { WorldPacket data(SMSG_TIME_SYNC_REQ, 4); data << uint32(m_timeSyncCounter++); GetSession()->SendPacket(&data); // Schedule next sync in 10 sec m_timeSyncTimer = 10000; m_timeSyncServer = WorldTimer::getMSTime(); } void Player::SendDuelCountdown(uint32 counter) { WorldPacket data(SMSG_DUEL_COUNTDOWN, 4); data << uint32(counter); // seconds GetSession()->SendPacket(&data); } bool Player::IsImmuneToSpell(SpellEntry const* spellInfo) const { return Unit::IsImmuneToSpell(spellInfo); } bool Player::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const { switch(spellInfo->Effect[index]) { case SPELL_EFFECT_ATTACK_ME: return true; default: break; } switch(spellInfo->EffectApplyAuraName[index]) { case SPELL_AURA_MOD_TAUNT: return true; default: break; } return Unit::IsImmuneToSpellEffect(spellInfo, index); } void Player::SetHomebindToLocation(WorldLocation const& loc, uint32 area_id) { m_homebindMapId = loc.mapid; m_homebindAreaId = area_id; m_homebindX = loc.coord_x; m_homebindY = loc.coord_y; m_homebindZ = loc.coord_z; // update sql homebind CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'", m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow()); } Object* Player::GetObjectByTypeMask(ObjectGuid guid, TypeMask typemask) { switch(guid.GetHigh()) { case HIGHGUID_ITEM: if (typemask & TYPEMASK_ITEM) return GetItemByGuid(guid); break; case HIGHGUID_PLAYER: if (GetObjectGuid()==guid) return this; if ((typemask & TYPEMASK_PLAYER) && IsInWorld()) return ObjectAccessor::FindPlayer(guid); break; case HIGHGUID_GAMEOBJECT: if ((typemask & TYPEMASK_GAMEOBJECT) && IsInWorld()) return GetMap()->GetGameObject(guid); break; case HIGHGUID_UNIT: case HIGHGUID_VEHICLE: if ((typemask & TYPEMASK_UNIT) && IsInWorld()) return GetMap()->GetCreature(guid); break; case HIGHGUID_PET: if ((typemask & TYPEMASK_UNIT) && IsInWorld()) return GetMap()->GetPet(guid); break; case HIGHGUID_DYNAMICOBJECT: if ((typemask & TYPEMASK_DYNAMICOBJECT) && IsInWorld()) return GetMap()->GetDynamicObject(guid); break; case HIGHGUID_TRANSPORT: case HIGHGUID_CORPSE: case HIGHGUID_MO_TRANSPORT: case HIGHGUID_INSTANCE: case HIGHGUID_GROUP: default: break; } return NULL; } void Player::CompletedAchievement(AchievementEntry const* entry) { GetAchievementMgr().CompletedAchievement(entry); } void Player::CompletedAchievement(uint32 uiAchievementID) { GetAchievementMgr().CompletedAchievement(sAchievementStore.LookupEntry(uiAchievementID)); } void Player::SetRestType( RestType n_r_type, uint32 areaTriggerId /*= 0*/) { rest_type = n_r_type; if (rest_type == REST_TYPE_NO) { RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); // Set player to FFA PVP when not in rested environment. if (sWorld.IsFFAPvPRealm()) SetFFAPvP(true); } else { SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); inn_trigger_id = areaTriggerId; time_inn_enter = time(NULL); if (sWorld.IsFFAPvPRealm()) SetFFAPvP(false); } } void Player::SetRandomWinner(bool isWinner) { m_IsBGRandomWinner = isWinner; if (m_IsBGRandomWinner) CharacterDatabase.PExecute("INSERT INTO character_battleground_random (guid) VALUES ('%u')", GetGUIDLow()); } void Player::_LoadRandomBGStatus(QueryResult *result) { //QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM character_battleground_random WHERE guid = '%u'", GetGUIDLow()); if (result) { m_IsBGRandomWinner = true; delete result; } } // Refer-A-Friend void Player::SendReferFriendError(ReferAFriendError err, Player * target) { WorldPacket data(SMSG_REFER_A_FRIEND_ERROR, 24); data << uint32(err); if (target && (err == ERR_REFER_A_FRIEND_NOT_IN_GROUP || err == ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S)) data << target->GetName(); GetSession()->SendPacket(&data); } ReferAFriendError Player::GetReferFriendError(Player * target, bool summon) { if (!target || target->GetTypeId() != TYPEID_PLAYER) return summon ? ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S : ERR_REFER_A_FRIEND_NO_TARGET; if (!IsReferAFriendLinked(target)) return ERR_REFER_A_FRIEND_NOT_REFERRED_BY; if (Group * gr1 = GetGroup()) { Group * gr2 = target->GetGroup(); if (!gr2 || gr1->GetId() != gr2->GetId()) return ERR_REFER_A_FRIEND_NOT_IN_GROUP; } if (summon) { if (HasSpellCooldown(45927)) return ERR_REFER_A_FRIEND_SUMMON_COOLDOWN; if (target->getLevel() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL)) return ERR_REFER_A_FRIEND_SUMMON_LEVEL_MAX_I; if (MapEntry const* mEntry = sMapStore.LookupEntry(GetMapId())) if (mEntry->Expansion() > target->GetSession()->Expansion()) return ERR_REFER_A_FRIEND_INSUF_EXPAN_LVL; } else { if (GetTeam() != target->GetTeam() && !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP)) return ERR_REFER_A_FRIEND_DIFFERENT_FACTION; if (getLevel() <= target->getLevel()) return ERR_REFER_A_FRIEND_TARGET_TOO_HIGH; if (!GetGrantableLevels()) return ERR_REFER_A_FRIEND_INSUFFICIENT_GRANTABLE_LEVELS; if (GetDistance(target) > DEFAULT_VISIBILITY_DISTANCE || !target->IsVisibleGloballyFor(this)) return ERR_REFER_A_FRIEND_TOO_FAR; if (target->getLevel() >= sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL)) return ERR_REFER_A_FRIEND_GRANT_LEVEL_MAX_I; } return ERR_REFER_A_FRIEND_NONE; } void Player::ChangeGrantableLevels(uint8 increase) { if (increase) { if (m_GrantableLevelsCount <= int32(sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL) * sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL))) m_GrantableLevelsCount += increase; } else { m_GrantableLevelsCount -= 1; if (m_GrantableLevelsCount < 0) m_GrantableLevelsCount = 0; } // set/unset flag - granted levels if (m_GrantableLevelsCount > 0) { if (!HasByteFlag(PLAYER_FIELD_BYTES, 1, 0x01)) SetByteFlag(PLAYER_FIELD_BYTES, 1, 0x01); } else { if (HasByteFlag(PLAYER_FIELD_BYTES, 1, 0x01)) RemoveByteFlag(PLAYER_FIELD_BYTES, 1, 0x01); } } bool Player::CheckRAFConditions() { if (Group * grp = GetGroup()) { for(GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* member = itr->getSource(); if (!member || !member->isAlive()) continue; if (GetObjectGuid() == member->GetObjectGuid()) continue; if (member->GetAccountLinkedState() == STATE_NOT_LINKED) continue; if (GetDistance(member) < 100 && (getLevel() <= member->getLevel() + 4)) return true; } } return false; } AccountLinkedState Player::GetAccountLinkedState() { RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true); RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false); if (!referredAccounts || !referalAccounts) return STATE_NOT_LINKED; if (!referredAccounts->empty() && !referalAccounts->empty()) return STATE_DUAL; if (!referredAccounts->empty()) return STATE_REFER; if (!referalAccounts->empty()) return STATE_REFERRAL; return STATE_NOT_LINKED; } void Player::LoadAccountLinkedState() { RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true); if (referredAccounts) { if (referredAccounts->size() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERERS)) sLog.outError("Player:RAF:Warning: loaded %u referred accounts instead of %u for player %s",referredAccounts->size(),sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERERS),GetObjectGuid().GetString().c_str()); else DEBUG_LOG("Player:RAF: loaded %u referred accounts for player %u",referredAccounts->size(),GetObjectGuid().GetString().c_str()); } RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false); if (referalAccounts) { if (referalAccounts->size() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERALS)) sLog.outError("Player:RAF:Warning: loaded %u referal accounts instead of %u for player %u",referalAccounts->size(),sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERALS),GetObjectGuid().GetString().c_str()); else DEBUG_LOG("Player:RAF: loaded %u referal accounts for player %u",referalAccounts->size(),GetObjectGuid().GetString().c_str()); } } bool Player::IsReferAFriendLinked(Player* target) { // check link this(refer) - target(referral) RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false); if (referalAccounts) { for (RafLinkedList::const_iterator itr = referalAccounts->begin(); itr != referalAccounts->end(); ++itr) if ((*itr) == target->GetSession()->GetAccountId()) return true; } // check link target(refer) - this(referral) RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true); if (referredAccounts) { for (RafLinkedList::const_iterator itr = referredAccounts->begin(); itr != referredAccounts->end(); ++itr) if ((*itr) == target->GetSession()->GetAccountId()) return true; } return false; } AreaLockStatus Player::GetAreaTriggerLockStatus(AreaTrigger const* at, Difficulty difficulty) { if (!at) return AREA_LOCKSTATUS_UNKNOWN_ERROR; MapEntry const* mapEntry = sMapStore.LookupEntry(at->target_mapId); if (!mapEntry) return AREA_LOCKSTATUS_UNKNOWN_ERROR; MapDifficultyEntry const* mapDiff = GetMapDifficultyData(at->target_mapId,difficulty); if (mapEntry->IsDungeon() && !mapDiff) return AREA_LOCKSTATUS_MISSING_DIFFICULTY; if (isGameMaster()) return AREA_LOCKSTATUS_OK; if (GetSession()->Expansion() < mapEntry->Expansion()) return AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION; if (getLevel() < at->requiredLevel && !sWorld.getConfig(CONFIG_BOOL_INSTANCE_IGNORE_LEVEL)) return AREA_LOCKSTATUS_TOO_LOW_LEVEL; if (mapEntry->IsDungeon() && mapEntry->IsRaid() && !sWorld.getConfig(CONFIG_BOOL_INSTANCE_IGNORE_RAID)) if (!GetGroup() || !GetGroup()->isRaidGroup()) return AREA_LOCKSTATUS_RAID_LOCKED; // must have one or the other, report the first one that's missing if (at->requiredItem) { if (!HasItemCount(at->requiredItem, 1) && (!at->requiredItem2 || !HasItemCount(at->requiredItem2, 1))) return AREA_LOCKSTATUS_MISSING_ITEM; } else if (at->requiredItem2 && !HasItemCount(at->requiredItem2, 1)) return AREA_LOCKSTATUS_MISSING_ITEM; bool isRegularTargetMap = GetDifficulty(mapEntry->IsRaid()) == REGULAR_DIFFICULTY; if (!isRegularTargetMap) { if (at->heroicKey) { if(!HasItemCount(at->heroicKey, 1) && (!at->heroicKey2 || !HasItemCount(at->heroicKey2, 1))) return AREA_LOCKSTATUS_MISSING_ITEM; } else if (at->heroicKey2 && !HasItemCount(at->heroicKey2, 1)) return AREA_LOCKSTATUS_MISSING_ITEM; } if (GetTeam() == ALLIANCE) { if ((!isRegularTargetMap && (at->requiredQuestHeroicA && !GetQuestRewardStatus(at->requiredQuestHeroicA))) || (isRegularTargetMap && (at->requiredQuestA && !GetQuestRewardStatus(at->requiredQuestA)))) return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED; } else if (GetTeam() == HORDE) { if ((!isRegularTargetMap && (at->requiredQuestHeroicH && !GetQuestRewardStatus(at->requiredQuestHeroicH))) || (isRegularTargetMap && (at->requiredQuestH && !GetQuestRewardStatus(at->requiredQuestH)))) return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED; } uint32 achievCheck = 0; if (difficulty == RAID_DIFFICULTY_10MAN_HEROIC) achievCheck = at->achiev0; else if (difficulty == RAID_DIFFICULTY_25MAN_HEROIC) achievCheck = at->achiev1; if (achievCheck) { bool bHasAchiev = false; if (GetAchievementMgr().HasAchievement(achievCheck)) bHasAchiev = true; else if (Group* group = GetGroup()) { for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* member = itr->getSource(); if (member && member->IsInWorld()) if (member->GetAchievementMgr().HasAchievement(achievCheck)) bHasAchiev = true; } } if (!bHasAchiev) return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED; } // If the map is not created, assume it is possible to enter it. DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(at->target_mapId); Map* map = sMapMgr.FindMap(at->target_mapId, state ? state->GetInstanceId() : 0); if (map && at->combatMode == 1) { if (map->GetInstanceData() && map->GetInstanceData()->IsEncounterInProgress()) { DEBUG_LOG("MAP: Player '%s' can't enter instance '%s' while an encounter is in progress.", GetObjectGuid().GetString().c_str(), map->GetMapName()); return AREA_LOCKSTATUS_ZONE_IN_COMBAT; } } if (map && map->IsDungeon()) { // cannot enter if the instance is full (player cap), GMs don't count if (((DungeonMap*)map)->GetPlayersCountExceptGMs() >= ((DungeonMap*)map)->GetMaxPlayers()) return AREA_LOCKSTATUS_INSTANCE_IS_FULL; InstancePlayerBind* pBind = GetBoundInstance(at->target_mapId, GetDifficulty(mapEntry->IsRaid())); if (pBind && pBind->perm && pBind->state != state) return AREA_LOCKSTATUS_HAS_BIND; if (pBind && pBind->perm && pBind->state != map->GetPersistentState()) return AREA_LOCKSTATUS_HAS_BIND; } return AREA_LOCKSTATUS_OK; }; AreaLockStatus Player::GetAreaLockStatus(uint32 mapId, Difficulty difficulty) { return GetAreaTriggerLockStatus(sObjectMgr.GetMapEntranceTrigger(mapId), difficulty); }; bool Player::CheckTransferPossibility(uint32 mapId) { if (mapId == GetMapId()) return true; MapEntry const* targetMapEntry = sMapStore.LookupEntry(mapId); if (!targetMapEntry) { sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but map not exists!", GetObjectGuid().GetString().c_str(), mapId); return false; } // Battleground requirements checked in another place if(InBattleGround() && targetMapEntry->IsBattleGroundOrArena()) return true; AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(mapId); if (!at) { if (isGameMaster()) { sLog.outDetail("Player::CheckTransferPossibility: gamemaster %s try teleport to map %u, but entrance trigger not exists (possible for some test maps).", GetObjectGuid().GetString().c_str(), mapId); return true; } if (targetMapEntry->IsContinent()) { if (GetSession()->Expansion() < targetMapEntry->Expansion()) { sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but not has sufficient expansion (%u instead of %u)", GetObjectGuid().GetString().c_str(), mapId, GetSession()->Expansion(), targetMapEntry->Expansion()); return false; } return true; } sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but entrance trigger not exists!", GetObjectGuid().GetString().c_str(), mapId); return false; } return CheckTransferPossibility(at, targetMapEntry->IsContinent()); } bool Player::CheckTransferPossibility(AreaTrigger const*& at, bool b_onlyMainReq) { if (!at) return false; if (at->target_mapId == GetMapId()) return true; MapEntry const* targetMapEntry = sMapStore.LookupEntry(at->target_mapId); if (!targetMapEntry) return false; if (!isGameMaster()) { // ghost resurrected at enter attempt to dungeon with corpse (including fail enter cases) if (!isAlive() && targetMapEntry->IsDungeon()) { int32 corpseMapId = 0; if (Corpse *corpse = GetCorpse()) corpseMapId = corpse->GetMapId(); // check back way from corpse to entrance uint32 instance_map = corpseMapId; do { // most often fast case if (instance_map == targetMapEntry->MapID) break; InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(instance_map); instance_map = instance ? instance->parent : 0; } while (instance_map); // corpse not in dungeon or some linked deep dungeons if (!instance_map) { WorldPacket data(SMSG_AREA_TRIGGER_NO_CORPSE); GetSession()->SendPacket(&data); return false; } // need find areatrigger to inner dungeon for landing point if (at->target_mapId != corpseMapId) { if (AreaTrigger const* corpseAt = sObjectMgr.GetMapEntranceTrigger(corpseMapId)) { targetMapEntry = sMapStore.LookupEntry(corpseAt->target_mapId); at = corpseAt; } } // now we can resurrect player, and then check teleport requirements ResurrectPlayer(0.5f); SpawnCorpseBones(); } } AreaLockStatus status = GetAreaTriggerLockStatus(at, GetDifficulty(targetMapEntry->IsRaid())); DEBUG_LOG("Player::CheckTransferPossibility %s check lock status of map %u (difficulty %u), result is %u", GetObjectGuid().GetString().c_str(), at->target_mapId, GetDifficulty(targetMapEntry->IsRaid()), status); if (b_onlyMainReq) { switch (status) { case AREA_LOCKSTATUS_MISSING_ITEM: case AREA_LOCKSTATUS_QUEST_NOT_COMPLETED: case AREA_LOCKSTATUS_INSTANCE_IS_FULL: case AREA_LOCKSTATUS_ZONE_IN_COMBAT: case AREA_LOCKSTATUS_TOO_LOW_LEVEL: return true; default: break; } } switch (status) { case AREA_LOCKSTATUS_OK: return true; case AREA_LOCKSTATUS_TOO_LOW_LEVEL: GetSession()->SendAreaTriggerMessage(GetSession()->GetMangosString(LANG_LEVEL_MINREQUIRED), at->requiredLevel); return false; case AREA_LOCKSTATUS_ZONE_IN_COMBAT: SendTransferAborted(at->target_mapId, TRANSFER_ABORT_ZONE_IN_COMBAT); return false; case AREA_LOCKSTATUS_INSTANCE_IS_FULL: SendTransferAborted(at->target_mapId, TRANSFER_ABORT_MAX_PLAYERS); return false; case AREA_LOCKSTATUS_QUEST_NOT_COMPLETED: if(at->target_mapId == 269) { GetSession()->SendAreaTriggerMessage("%s", at->requiredFailedText.c_str()); return false; } // No break here! case AREA_LOCKSTATUS_MISSING_ITEM: { MapDifficultyEntry const* mapDiff = GetMapDifficultyData(targetMapEntry->MapID,GetDifficulty(targetMapEntry->IsRaid())); if (mapDiff && mapDiff->mapDifficultyFlags & MAP_DIFFICULTY_FLAG_CONDITION) { GetSession()->SendAreaTriggerMessage("%s", mapDiff->areaTriggerText[GetSession()->GetSessionDbcLocale()]); } // do not report anything for quest areatriggers DEBUG_LOG("HandleAreaTriggerOpcode: LockAreaStatus %u, do action", uint8(GetAreaTriggerLockStatus(at, GetDifficulty(targetMapEntry->IsRaid())))); return false; } case AREA_LOCKSTATUS_MISSING_DIFFICULTY: { Difficulty difficulty = GetDifficulty(targetMapEntry->IsRaid()); SendTransferAborted(at->target_mapId, TRANSFER_ABORT_DIFFICULTY, difficulty > RAID_DIFFICULTY_10MAN_HEROIC ? RAID_DIFFICULTY_10MAN_HEROIC : difficulty); return false; } case AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION: SendTransferAborted(at->target_mapId, TRANSFER_ABORT_INSUF_EXPAN_LVL, targetMapEntry->Expansion()); return false; case AREA_LOCKSTATUS_NOT_ALLOWED: case AREA_LOCKSTATUS_HAS_BIND: SendTransferAborted(at->target_mapId, TRANSFER_ABORT_MAP_NOT_ALLOWED); return false; // TODO: messages for other cases case AREA_LOCKSTATUS_RAID_LOCKED: SendTransferAborted(at->target_mapId, TRANSFER_ABORT_NEED_GROUP); return false; // TODO: messages for other cases case AREA_LOCKSTATUS_UNKNOWN_ERROR: default: SendTransferAborted(at->target_mapId, TRANSFER_ABORT_ERROR); sLog.outError("Player::CheckTransferPossibility player %s has unhandled AreaLockStatus %u in map %u (difficulty %u), do nothing", GetObjectGuid().GetString().c_str(), status, at->target_mapId, GetDifficulty(targetMapEntry->IsRaid())); return false; } return false; }; uint32 Player::GetEquipGearScore(bool withBags, bool withBank) { if (withBags && withBank && m_cachedGS > 0) return m_cachedGS; GearScoreVec gearScore (EQUIPMENT_SLOT_END); uint32 twoHandScore = 0; for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) _fillGearScoreData(item, &gearScore, twoHandScore); } if (withBags) { // check inventory for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) { if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) _fillGearScoreData(item, &gearScore, twoHandScore); } // check bags for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { if(Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) { for(uint32 j = 0; j < pBag->GetBagSize(); ++j) { if (Item* item2 = pBag->GetItemByPos(j)) _fillGearScoreData(item2, &gearScore, twoHandScore); } } } } if (withBank) { for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) { if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) _fillGearScoreData(item, &gearScore, twoHandScore); } for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) { if (item->IsBag()) { Bag* bag = (Bag*)item; for (uint8 j = 0; j < bag->GetBagSize(); ++j) { if (Item* item2 = bag->GetItemByPos(j)) _fillGearScoreData(item2, &gearScore, twoHandScore); } } } } } uint8 count = EQUIPMENT_SLOT_END - 2; // ignore body and tabard slots uint32 sum = 0; // check if 2h hand is higher level than main hand + off hand if (gearScore[EQUIPMENT_SLOT_MAINHAND] + gearScore[EQUIPMENT_SLOT_OFFHAND] < twoHandScore * 2) { gearScore[EQUIPMENT_SLOT_OFFHAND] = 0; // off hand is ignored in calculations if 2h weapon has higher score --count; gearScore[EQUIPMENT_SLOT_MAINHAND] = twoHandScore; } for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { sum += gearScore[i]; } if (count) { uint32 res = uint32(sum / count); DEBUG_LOG("Player: calculating gear score for %u. Result is %u", GetObjectGuid().GetCounter(), res); if (withBags && withBank) m_cachedGS = res; return res; } else return 0; } void Player::_fillGearScoreData(Item* item, GearScoreVec* gearScore, uint32& twoHandScore) { if (!item) return; if (CanUseItem(item->GetProto()) != EQUIP_ERR_OK) return; uint8 type = item->GetProto()->InventoryType; uint32 level = item->GetProto()->ItemLevel; switch (type) { case INVTYPE_2HWEAPON: twoHandScore = std::max(twoHandScore, level); break; case INVTYPE_WEAPON: case INVTYPE_WEAPONMAINHAND: (*gearScore)[SLOT_MAIN_HAND] = std::max((*gearScore)[SLOT_MAIN_HAND], level); break; case INVTYPE_SHIELD: case INVTYPE_WEAPONOFFHAND: (*gearScore)[EQUIPMENT_SLOT_OFFHAND] = std::max((*gearScore)[EQUIPMENT_SLOT_OFFHAND], level); break; case INVTYPE_THROWN: case INVTYPE_RANGEDRIGHT: case INVTYPE_RANGED: case INVTYPE_QUIVER: case INVTYPE_RELIC: (*gearScore)[EQUIPMENT_SLOT_RANGED] = std::max((*gearScore)[EQUIPMENT_SLOT_RANGED], level); break; case INVTYPE_HEAD: (*gearScore)[EQUIPMENT_SLOT_HEAD] = std::max((*gearScore)[EQUIPMENT_SLOT_HEAD], level); break; case INVTYPE_NECK: (*gearScore)[EQUIPMENT_SLOT_NECK] = std::max((*gearScore)[EQUIPMENT_SLOT_NECK], level); break; case INVTYPE_SHOULDERS: (*gearScore)[EQUIPMENT_SLOT_SHOULDERS] = std::max((*gearScore)[EQUIPMENT_SLOT_SHOULDERS], level); break; case INVTYPE_BODY: (*gearScore)[EQUIPMENT_SLOT_BODY] = std::max((*gearScore)[EQUIPMENT_SLOT_BODY], level); break; case INVTYPE_CHEST: (*gearScore)[EQUIPMENT_SLOT_CHEST] = std::max((*gearScore)[EQUIPMENT_SLOT_CHEST], level); break; case INVTYPE_WAIST: (*gearScore)[EQUIPMENT_SLOT_WAIST] = std::max((*gearScore)[EQUIPMENT_SLOT_WAIST], level); break; case INVTYPE_LEGS: (*gearScore)[EQUIPMENT_SLOT_LEGS] = std::max((*gearScore)[EQUIPMENT_SLOT_LEGS], level); break; case INVTYPE_FEET: (*gearScore)[EQUIPMENT_SLOT_FEET] = std::max((*gearScore)[EQUIPMENT_SLOT_FEET], level); break; case INVTYPE_WRISTS: (*gearScore)[EQUIPMENT_SLOT_WRISTS] = std::max((*gearScore)[EQUIPMENT_SLOT_WRISTS], level); break; case INVTYPE_HANDS: (*gearScore)[EQUIPMENT_SLOT_HEAD] = std::max((*gearScore)[EQUIPMENT_SLOT_HEAD], level); break; // equipped gear score check uses both rings and trinkets for calculation, assume that for bags/banks it is the same // with keeping second highest score at second slot case INVTYPE_FINGER: { if ((*gearScore)[EQUIPMENT_SLOT_FINGER1] < level) { (*gearScore)[EQUIPMENT_SLOT_FINGER2] = (*gearScore)[EQUIPMENT_SLOT_FINGER1]; (*gearScore)[EQUIPMENT_SLOT_FINGER1] = level; } else if ((*gearScore)[EQUIPMENT_SLOT_FINGER2] < level) (*gearScore)[EQUIPMENT_SLOT_FINGER2] = level; break; } case INVTYPE_TRINKET: { if ((*gearScore)[EQUIPMENT_SLOT_TRINKET1] < level) { (*gearScore)[EQUIPMENT_SLOT_TRINKET2] = (*gearScore)[EQUIPMENT_SLOT_TRINKET1]; (*gearScore)[EQUIPMENT_SLOT_TRINKET1] = level; } else if ((*gearScore)[EQUIPMENT_SLOT_TRINKET2] < level) (*gearScore)[EQUIPMENT_SLOT_TRINKET2] = level; break; } case INVTYPE_CLOAK: (*gearScore)[EQUIPMENT_SLOT_BACK] = std::max((*gearScore)[EQUIPMENT_SLOT_BACK], level); break; default: break; } } uint8 Player::GetTalentsCount(uint8 tab) { if (tab >2) return 0; if (m_cachedTC[tab] > 0) return m_cachedTC[tab]; uint8 talentCount = 0; uint32 const* talentTabIds = GetTalentTabPages(getClass()); uint32 talentTabId = talentTabIds[tab]; for (PlayerTalentMap::iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end(); ++iter) { PlayerTalent talent = (*iter).second; if (talent.state == PLAYERSPELL_REMOVED) continue; // skip another tab talents if (talent.talentEntry->TalentTab != talentTabId) continue; talentCount += talent.currentRank + 1; } m_cachedTC[tab] = talentCount; return talentCount; } uint32 Player::GetModelForForm(SpellShapeshiftFormEntry const* ssEntry) const { ShapeshiftForm form = ShapeshiftForm(ssEntry->ID); Team team = TeamForRace(getRace()); uint32 modelid = 0; // The following are the different shapeshifting models for cat/bear forms according // to hair color for druids and skin tone for tauren introduced in patch 3.2 if (form == FORM_CAT || form == FORM_BEAR || form == FORM_DIREBEAR) { if (team == ALLIANCE) { uint8 hairColour = GetByteValue(PLAYER_BYTES, 3); if (form == FORM_CAT) { if (hairColour >= 0 && hairColour <= 2) modelid = 29407; else if (hairColour == 3 || hairColour == 5) modelid = 29405; else if (hairColour == 6) modelid = 892; else if (hairColour == 7) modelid = 29406; else if (hairColour == 4) modelid = 29408; } else // form == FORM_BEAR || form == FORM_DIREBEAR { if (hairColour >= 0 && hairColour <= 2) modelid = 29413; else if (hairColour == 3 || hairColour == 5) modelid = 29415; else if (hairColour == 6) modelid = 29414; else if (hairColour == 7) modelid = 29417; else if (hairColour == 4) modelid = 29416; } } else if (team == HORDE) { uint8 skinColour = GetByteValue(PLAYER_BYTES, 0); if (getGender() == GENDER_MALE) { if (form == FORM_CAT) { if (skinColour >= 0 && skinColour <= 5) modelid = 29412; else if (skinColour >= 6 && skinColour <= 8) modelid = 29411; else if (skinColour >= 9 && skinColour <= 11) modelid = 29410; else if (skinColour >= 12 && skinColour <= 14 || skinColour == 18) modelid = 29409; else if (skinColour >= 15 && skinColour <= 17) modelid = 8571; } else // form == FORM_BEAR || form == FORM_DIREBEAR { if (skinColour >= 0 && skinColour <= 2) modelid = 29418; else if (skinColour >= 3 && skinColour <= 5 || skinColour >= 12 && skinColour <= 14) modelid = 29419; else if (skinColour >= 9 && skinColour <= 11 || skinColour >= 15 && skinColour <= 17) modelid = 29420; else if (skinColour >= 6 && skinColour <= 8) modelid = 2289; else if (skinColour == 18) modelid = 29421; } } else // getGender() == GENDER_FEMALE { if (form == FORM_CAT) { if (skinColour >= 0 && skinColour <= 3) modelid = 29412; else if (skinColour == 4 || skinColour == 5) modelid = 29411; else if (skinColour == 6 || skinColour == 7) modelid = 29410; else if (skinColour == 8 || skinColour == 9) modelid = 8571; else if (skinColour == 10) modelid = 29409; } else // form == FORM_BEAR || form == FORM_DIREBEAR { if (skinColour == 0 || skinColour == 1) modelid = 29418; else if (skinColour == 2 || skinColour == 3) modelid = 29419; else if (skinColour == 4 || skinColour == 5) modelid = 2289; else if (skinColour >= 6 && skinColour <= 9) modelid = 29420; else if (skinColour == 10) modelid = 29421; } } } } else if (team == HORDE) { if (ssEntry->modelID_H) modelid = ssEntry->modelID_H; // 3.2.3 only the moonkin form has this information else // get model for race modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, getRaceMask()); } // nothing found in above, so use default if (!modelid) modelid = ssEntry->modelID_A; return modelid; } float Player::GetCollisionHeight(bool mounted) { if (mounted) { CreatureDisplayInfoEntry const* mountDisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID)); if (!mountDisplayInfo) return GetCollisionHeight(false); CreatureModelDataEntry const* mountModelData = sCreatureModelDataStore.LookupEntry(mountDisplayInfo->ModelId); if (!mountModelData) return GetCollisionHeight(false); CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId()); MANGOS_ASSERT(displayInfo); CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId); MANGOS_ASSERT(modelData); float scaleMod = GetFloatValue(OBJECT_FIELD_SCALE_X); // 99% sure about this return scaleMod * mountModelData->MountHeight + modelData->CollisionHeight * 0.5f; } else { //! Dismounting case - use basic default model data CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId()); MANGOS_ASSERT(displayInfo); CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId); MANGOS_ASSERT(modelData); return modelData->CollisionHeight; } } void Player::InterruptTaxiFlying() { // stop flight if need if (IsTaxiFlying()) { GetUnitStateMgr().DropAction(UNIT_ACTION_TAXI); m_taxi.ClearTaxiDestinations(); GetUnitStateMgr().InitDefaults(); } // save only in non-flight case else SaveRecallPosition(); }<|fim▁end|>
UpdateExpertise(BASE_ATTACK); UpdateArmorPenetration(); }
<|file_name|>llwmr.py<|end_file_name|><|fim▁begin|>from ...utils.tests import base as base from ...utils.tests import mpi as mpit # key order: dataset; epsilon; C __REFERENCE_RESULTS__ = { "dryrun": { 0.1: { 0.1: { "accuracy": 1-0.9300, }, 1: { "accuracy": 1-0.9300, }, 10: { "accuracy": 1-0.9300, }, }, }, "glass": { 0.001: { 0.1: { "accuracy": 1-0.6667, }, 1: { "accuracy": 1-0.6190, }, 10: { "accuracy": 1-0.3333, }, }, }, "iris": { 0.001: { 0.1: { "accuracy": 1-0.1333, }, 1: { "accuracy": 1-0.2667, }, 10: { "accuracy": 1-0.2667, }, }, }, "news20": { 0.001: { 0.1: { "accuracy": 1-0.2923, }, 1: { "accuracy": 1-0.2297, }, 10: { "accuracy": 1-0.1615, }, }, }, } def do_llwmr_tsd(options_update={}, mpi_comm=None, datasets=None, reference=True): solver_id = "llw_mr_sparse" # default options options = { "epsilon": 0.001, "C": 10**-1, "mpi_comm": mpi_comm, } options.update(options_update) reference_results = __REFERENCE_RESULTS__ if reference is False: reference_results = None base._do_test_small_datasets(solver_id, options, datasets=datasets, reference_results=reference_results, mpi_comm=mpi_comm) pass def do_llwmr_tld(options_update={}, mpi_comm=None, datasets=None, reference=True): solver_id = "llw_mr_sparse" # default options options = { "epsilon": 0.1, "C": 10**-1, "mpi_comm": mpi_comm, } options.update(options_update) tolerance = 0.01 reference_results = __REFERENCE_RESULTS__ if reference is False: reference_results = None base._do_test_large_datasets(solver_id, options, datasets=datasets, reference_results=reference_results, mpi_comm=mpi_comm, tolerance=tolerance) pass <|fim▁hole|>############################################################################### # ............................................................................. # BASE SOLVER TESTS # ............................................................................. ############################################################################### ############################################################################### # Running default config def test_default_sd(): do_llwmr_tsd() @base.testattr("slow") def test_default_ld(): do_llwmr_tld() ############################################################################### # Parameter C and max_iter @base.testattr("slow") def test_C_1_sd(): do_llwmr_tsd({"C": 10**0}) @base.testattr("slow") def test_C_1_ld(): do_llwmr_tld({"C": 10**0}) @base.testattr("slow") def test_C_10_sd(): do_llwmr_tsd({"C": 10**1, "max_iter": 10000}) @base.testattr("slow") def test_C_10_ld(): do_llwmr_tld({"C": 10**1, "max_iter": 10000}) ############################################################################### # Parameter epsilon def test_small_epsilon_sd(): do_llwmr_tsd({"epsilon": 0.0001}, reference=False) @base.testattr("slow") def test_small_epsilon_ld(): do_llwmr_tld({"epsilon": 0.01}, reference=False) ############################################################################### # Parameter shuffle def test_no_shuffle_sd(): do_llwmr_tsd({"shuffle": False}) @base.testattr("slow") def test_no_shuffle_ld(): do_llwmr_tld({"shuffle": False}) ############################################################################### # Parameter seed def test_seed_12345_sd(): do_llwmr_tsd({"seed": 12345}) @base.testattr("slow") def test_seed_12345_ld(): do_llwmr_tld({"seed": 12345}) ############################################################################### # Parameter dtype @base.testattr("slow") def test_dtype_float32_sd(): do_llwmr_tsd({"dtype": "float32"}) @base.testattr("slow") def test_dtype_float32_ld(): do_llwmr_tld({"dtype": "float32"}) @base.testattr("slow") def test_dtype_float64_sd(): do_llwmr_tsd({"dtype": "float64"}) @base.testattr("slow") def test_dtype_float64_ld(): do_llwmr_tld({"dtype": "float64"}) ############################################################################### # Parameter idtype @base.testattr("slow") def test_idtype_uint32_sd(): do_llwmr_tsd({"idtype": "uint32"}) @base.testattr("slow") def test_idtype_uint32_ld(): do_llwmr_tld({"idtype": "uint32"}) @base.testattr("slow") def test_idtype_uint64_sd(): do_llwmr_tsd({"idtype": "uint64"}) @base.testattr("slow") def test_idtype_uint64_ld(): do_llwmr_tld({"idtype": "uint64"}) ############################################################################### # Parameter nr_threads def test_nr_threads_2_sd(): do_llwmr_tsd({"nr_threads": 2}) @base.testattr("slow") def test_nr_threads_2_ld(): do_llwmr_tld({"nr_threads": 2}) def test_nr_threads_5_sd(): do_llwmr_tsd({"nr_threads": 5}) @base.testattr("slow") def test_nr_threads_5_ld(): do_llwmr_tld({"nr_threads": 5}) ############################################################################### # ............................................................................. # LLW SOLVER TESTS # ............................................................................. ############################################################################### ############################################################################### # Parameter folds def test_folds_2_sd(): do_llwmr_tsd({"folds": 2}) @base.testattr("slow") def test_folds_2_ld(): do_llwmr_tld({"folds": 2}) def test_folds_5_sd(): do_llwmr_tsd({"folds": 5}) @base.testattr("slow") def test_folds_5_ld(): do_llwmr_tld({"folds": 5}) ############################################################################### # Parameter variant def test_variant_1_sd(): do_llwmr_tsd({"variant": 1}) @base.testattr("slow") def test_variant_1_ld(): do_llwmr_tld({"variant": 1}) ############################################################################### # Parameter shrinking def test_shrinking_1_sd(): do_llwmr_tsd({"shrinking": 1}) @base.testattr("slow") def test_shrinking_1_ld(): do_llwmr_tld({"shrinking": 1}) ############################################################################### # Spreading computation with openmpi @mpit.wrap(2) def test_nr_proc_2_sd(comm): do_llwmr_tsd({}, comm) @base.testattr("slow") @mpit.wrap(2) def test_nr_proc_2_ld(comm): do_llwmr_tld({}, comm) @mpit.wrap(3) def test_nr_proc_3_sd(comm): do_llwmr_tsd({}, comm) @base.testattr("slow") @mpit.wrap(3) def test_nr_proc_3_ld(comm): do_llwmr_tld({}, comm)<|fim▁end|>
<|file_name|>module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms';<|fim▁hole|> // components import { ShellComponent } from './components/shell'; import { HelloComponent } from './components/hello'; import { OpenFolderComponent } from './components/folder'; import { SettingsComponent } from './components/settings'; import { AboutComponent } from './components/about'; // pipes import { SVGPipe } from './pipes/SVGPipe'; // services import { IpcRendererService } from './services/ipcRender'; import { StorageService } from './services/storage'; import { ComponentService } from './services/componentService'; // directives import { WebviewDirective } from './directives/webview'; // routes import { appRoutes } from './routes'; @NgModule({ imports: [ BrowserModule, CommonModule, FormsModule, ReactiveFormsModule, ColorPickerModule, RouterModule.forRoot(appRoutes) ], declarations: [ ShellComponent, HelloComponent, OpenFolderComponent, SettingsComponent, AboutComponent, SVGPipe, WebviewDirective ], bootstrap: [ShellComponent], providers: [IpcRendererService, StorageService, ComponentService] }) export class Module { }<|fim▁end|>
import { ColorPickerModule } from 'angular2-color-picker';
<|file_name|>TransferInlineContentHandler.java<|end_file_name|><|fim▁begin|>/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2009. (c) 2009. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence<|fim▁hole|> * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 4 $ * ************************************************************************ */ package ca.nrc.cadc.vos.server; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import ca.nrc.cadc.io.ByteCountInputStream; import ca.nrc.cadc.uws.JobInfo; import ca.nrc.cadc.uws.Parameter; import ca.nrc.cadc.uws.web.InlineContentException; import ca.nrc.cadc.uws.web.InlineContentHandler; import ca.nrc.cadc.uws.web.UWSInlineContentHandler; import ca.nrc.cadc.vos.Transfer; import ca.nrc.cadc.vos.TransferParsingException; import ca.nrc.cadc.vos.TransferReader; import ca.nrc.cadc.vos.TransferWriter; import ca.nrc.cadc.vos.VOSURI; public class TransferInlineContentHandler implements UWSInlineContentHandler { private static Logger log = Logger.getLogger(TransferInlineContentHandler.class); // 6Kb XML Doc size limit private static final long DOCUMENT_SIZE_MAX = 6144L; private static final String TEXT_XML = "text/xml"; public TransferInlineContentHandler() { } public Content accept(String name, String contentType, InputStream inputStream) throws InlineContentException, IOException { if (!contentType.equals(TEXT_XML)) throw new IllegalArgumentException("Transfer document expected Content-Type is " + TEXT_XML + " not " + contentType); if (inputStream == null) throw new IOException("The InputStream is closed"); // wrap the input stream in a byte counter to limit bytes read ByteCountInputStream sizeLimitInputStream = new ByteCountInputStream(inputStream, DOCUMENT_SIZE_MAX); try { TransferReader reader = new TransferReader(true); Transfer transfer = reader.read(sizeLimitInputStream, VOSURI.SCHEME); log.debug("Transfer: read " + sizeLimitInputStream.getByteCount() + " bytes."); TransferWriter tw = new TransferWriter(); StringWriter sw = new StringWriter(); tw.write(transfer, sw); Content content = new Content(); content.name = CONTENT_JOBINFO; content.value = new JobInfo(sw.toString(), contentType, true);; return content; } catch (TransferParsingException e) { throw new InlineContentException("Unable to create JobInfo from Transfer Document", e); } } }<|fim▁end|>
* General Public License for Générale Publique GNU Affero * more details. pour plus de détails.
<|file_name|>PointerVectorExample.cpp<|end_file_name|><|fim▁begin|>#include <iostream> #include <vector> #include "PointerVectorExample.h" #include "Score.h" using namespace std; namespace samples { void PointerVectorExample() { vector<Score*> scores; scores.reserve(5); Score* cppScore = new Score(30, "C++"); Score* algoScore = new Score(59, "Algorithm"); Score* javaScore = new Score(87, "Java"); Score* dataCommScore = new Score(74, "Data Comm"); Score* androidScore = new Score(41, "Android"); scores.push_back(cppScore); scores.push_back(algoScore); scores.push_back(javaScore); scores.push_back(dataCommScore); scores.push_back(androidScore); PrintVector(scores); <|fim▁hole|> { Score* score = *iter; if (score->GetClassName() == "Java") { iter = scores.erase(iter); } else { iter++; } } PrintVector(scores); for (vector<Score*>::iterator iter = scores.begin(); iter != scores.end(); ++iter) { Score* score = *iter; if (score->GetScore() == 30) { score->SetScore(100); } } cout << "After chaning the score of class 1" << endl; PrintVector(scores); delete cppScore; delete algoScore; delete javaScore; delete dataCommScore; delete androidScore; } void PrintVector(const vector<Score*>& scores) { for (vector<Score*>::const_iterator iter = scores.begin(); iter != scores.end(); iter++) { Score* score = *iter; score->PrintVariables(); } cout << endl; } }<|fim▁end|>
vector<Score*>::iterator iter = scores.begin(); while (iter != scores.end())
<|file_name|>Command63QueryRemoteEncoderCancelNextRecording.java<|end_file_name|><|fim▁begin|><|fim▁hole|> * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.syphr.mythtv.protocol.impl; import org.syphr.mythtv.commons.exception.ProtocolException; import org.syphr.mythtv.commons.socket.CommandUtils; import org.syphr.mythtv.commons.translate.Translator; /* default */class Command63QueryRemoteEncoderCancelNextRecording extends AbstractCommand63QueryRemoteEncoder<Void> { private final boolean cancel; public Command63QueryRemoteEncoderCancelNextRecording(Translator translator, Parser parser, int recorderId, boolean cancel) { super(translator, parser, recorderId); this.cancel = cancel; } @Override protected String getSubCommand() throws ProtocolException { return getParser().combineArguments("CANCEL_NEXT_RECORDING", cancel ? "1" : "0"); } @Override protected Void parseResponse(String response) throws ProtocolException { CommandUtils.expectOk(response); return null; } }<|fim▁end|>
/* * Copyright 2011-2012 Gregory P. Moyer * * Licensed under the Apache License, Version 2.0 (the "License");
<|file_name|>gjoneska_pfenning.py<|end_file_name|><|fim▁begin|>"""Sections variable used for grouping Gjoneska 2015 GO IDs.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved." __author__ = "DV Klopfenstein" SECTIONS = [ # 18 sections ("immune", [ # 15 GO-headers "GO:0002376", # BP 564 L01 D01 M immune system process "GO:0002682", # BP 1,183 L02 D02 AB regulation of immune system process "GO:0030155", # BP 246 L02 D02 AB regulation of cell adhesion "GO:0006955", # BP 100 L02 D02 GM immune response "GO:0001817", # BP 476 L03 D03 AB regulation of cytokine production "GO:0001775", # BP 162 L03 D03 CD cell activation "GO:0001816", # BP 110 L03 D03 DK cytokine production "GO:1903037", # BP 155 L04 D04 AB regulation of leukocyte cell-cell adhesion "GO:0034097", # BP 59 L04 D04 G response to cytokine "GO:0006954", # BP 25 L04 D04 G inflammatory response "GO:0045087", # BP 25 L03 D04 GM innate immune response "GO:0002521", # BP 72 L05 D05 CDF leukocyte differentiation "GO:0007229", # BP 0 L05 D05 AB integrin-mediated signaling pathway "GO:0050900", # BP 57 L02 D06 CDMN leukocyte migration "GO:0042130", # BP 9 L07 D08 AB negative regulation of T cell proliferation #"GO:0002252", # BP 138 L02 D02 L immune effector process ]), ("viral/bacteria", [ # 4 GO-headers "GO:0016032", # BP 301 L03 D04 CJ viral process "GO:0050792", # BP 119 L03 D04 AB regulation of viral process "GO:0098542", # BP 37 L03 D05 GJ defense response to other organism "GO:0009617", # BP 12 L03 D05 GJ response to bacterium ]), ("neuro", [ # 25 GO-headers "GO:0099531", # BP 32 L01 D01 U presynaptic process in chemical synaptic Xmission "GO:0042391", # BP 117 L03 D03 A regulation of membrane potential "GO:0050877", # BP 96 L03 D03 K neurological system process "GO:0050808", # BP 20 L03 D03 CDI synapse organization "GO:0007272", # BP 13 L03 D03 CD ensheathment of neurons "GO:0051960", # BP 236 L04 D04 AB regulation of nervous system development "GO:0050804", # BP 120 L03 D04 AB modulation of synaptic transmission "GO:0097485", # BP 34 L04 D04 CD neuron projection guidance "GO:0031644", # BP 30 L04 D04 AB regulation of neurological system process "GO:0031175", # BP 14 L04 D04 CDI neuron projection development "GO:0035418", # BP 14 L04 D04 H protein localization to synapse "GO:0007399", # BP 0 L04 D04 F nervous system development "GO:0050767", # BP 192 L05 D05 AB regulation of neurogenesis "GO:0030182", # BP 71 L05 D05 CDF neuron differentiation "GO:0099536", # BP 40 L04 D05 CDR synaptic signaling "GO:0048666", # BP 29 L04 D05 CDF neuron development "GO:0010001", # BP 17 L05 D05 CDF glial cell differentiation "GO:0051969", # BP 5 L03 D05 AB regulation of transmission of nerve impulse "GO:0022008", # BP 3 L05 D05 CDF neurogenesis "GO:0007158", # BP 0 L04 D05 DP neuron cell-cell adhesion "GO:0014002", # BP 1 L05 D06 CDF astrocyte development "GO:0048812", # BP 27 L05 D07 CDFI neuron projection morphogenesis "GO:0048667", # BP 6 L06 D07 CDFI cell morphogenesis involved in neuron differen. "GO:0072578", # BP 5 L05 D07 CDHI neurotransmitter-gated ion channel clustering "GO:0007409", # BP 23 L06 D08 CDFI axonogenesis ]), ("cell death", [ # 6 GO-headers "GO:0010941", # BP 316 L03 D03 AB regulation of cell death "GO:0008219", # BP 104 L03 D03 CD cell death "GO:0060548", # BP 103 L04 D04 AB negative regulation of cell death "GO:0097190", # BP 22 L04 D04 AB apoptotic signaling pathway "GO:0097527", # BP 0 L04 D04 AB necroptotic signaling pathway "GO:0008637", # BP 7 L05 D05 CI apoptotic mitochondrial changes ]), ("lipid", [ # 7 GO-headers "GO:0006629", # BP 623 L03 D03 DE lipid metabolic process "GO:0019216", # BP 243 L04 D04 AB regulation of lipid metabolic process "GO:0032368", # BP 130 L04 D04 AB regulation of lipid transport "GO:0033993", # BP 112 L04 D04 G response to lipid "GO:0006869", # BP 93 L04 D05 DH lipid transport "GO:0055088", # BP 10 L05 D05 A lipid homeostasis "GO:0042158", # BP 3 L05 D06 CE lipoprotein biosynthetic process ]), ("adhesion", [ # 3 GO-headers "GO:0022610", # BP 194 L01 D01 P biological adhesion "GO:0030155", # BP 246 L02 D02 AB regulation of cell adhesion "GO:0007155", # BP 165 L02 D02 P cell adhesion ]), ("cell cycle", [ # 9 GO-headers "GO:0022402", # BP 463 L02 D02 C cell cycle process "GO:0022403", # BP 46 L02 D02 S cell cycle phase "GO:0051726", # BP 411 L03 D03 AB regulation of cell cycle "GO:0051301", # BP 54 L03 D03 CD cell division "GO:0007049", # BP 12 L03 D03 CD cell cycle "GO:0070192", # BP 17 L03 D05 CIL chromosome organization in meiotic cell cycle "GO:0007051", # BP 19 L03 D06 CDI spindle organization "GO:0007067", # BP 1 L04 D06 CI mitotic nuclear division "GO:0030071", # BP 11 L06 D09 AB regulation of mitotic metaphase/anaphase transition ]), ("chromosome", [ # 9 GO-headers "GO:0032259", # BP 119 L02 D02 E methylation "GO:0051983", # BP 108 L03 D03 AB regulation of chromosome segregation "GO:0007059", # BP 11 L03 D03 CD chromosome segregation "GO:0006325", # BP 184 L04 D04 CI chromatin organization "GO:0051276", # BP 107 L04 D04 CI chromosome organization "GO:0032204", # BP 29 L03 D06 AB regulation of telomere maintenance "GO:0034502", # BP 21 L06 D06 H protein localization to chromosome "GO:0031497", # BP 11 L05 D06 CI chromatin assembly "GO:0006334", # BP 3 L06 D07 CI nucleosome assembly ]), ("development", [ # 10 GO-headers "GO:0032502", # BP 3,173 L01 D01 F developmental process "GO:0022414", # BP 847 L01 D01 L reproductive process "GO:0050793", # BP 1,881 L02 D02 AB regulation of developmental process "GO:0048856", # BP 1,016 L02 D02 F anatomical structure development "GO:0048646", # BP 331 L02 D02 F anatomical structure formation in morphogenesis "GO:0007568", # BP 18 L03 D03 DF aging "GO:0022604", # BP 129 L04 D04 AB regulation of cell morphogenesis "GO:0000902", # BP 65 L04 D05 CDFI cell morphogenesis "GO:0045765", # BP 14 L04 D05 AB regulation of angiogenesis ]), ("extracellular matrix", [ # 1 GO-headers "GO:0030198", # BP 27 L04 D04 CDI extracellular matrix organization ]), ("ion", [ # 3 GO-headers<|fim▁hole|> ]), ("localization", [ # 3 GO-headers "GO:0051179", # BP 2,142 L01 D01 H localization "GO:0040011", # BP 394 L01 D01 N locomotion "GO:0032879", # BP 1,682 L02 D02 AB regulation of localization ]), ("membrane", [ # 1 GO-headers "GO:0061024", # BP 273 L03 D03 CI membrane organization ]), ("metabolic", [ # 7 GO-headers "GO:0008152", # BP 6,418 L01 D01 E metabolic process "GO:0019222", # BP 3,243 L02 D02 AB regulation of metabolic process "GO:0009056", # BP 1,369 L02 D02 E catabolic process "GO:0044281", # BP 2,139 L03 D03 DE small molecule metabolic process "GO:0050790", # BP 620 L03 D03 A regulation of catalytic activity "GO:0051186", # BP 373 L03 D03 CE cofactor metabolic process "GO:0006259", # BP 300 L04 D06 CE DNA metabolic process ]), ("phosphorylation", [ # 3 GO-headers "GO:0006793", # BP 798 L03 D03 CE phosphorus metabolic process "GO:0016310", # BP 138 L05 D05 CE phosphorylation "GO:0006468", # BP 97 L06 D07 CE protein phosphorylation ]), ("signaling", [ # 4 GO-headers "GO:0023052", # BP 116 L01 D01 R signaling "GO:0023051", # BP 1,364 L02 D02 AB regulation of signaling "GO:0007165", # BP 717 L03 D03 AB signal transduction "GO:0007267", # BP 99 L03 D04 CDR cell-cell signaling ]), ("stimulus", [ # 4 GO-headers "GO:0050896", # BP 2,218 L01 D01 G response to stimulus "GO:0048583", # BP 2,377 L02 D02 AB regulation of response to stimulus "GO:0006950", # BP 492 L02 D02 G response to stress "GO:0080134", # BP 940 L03 D03 AB regulation of response to stress ]), ("prolif_differ", [ # 3 GO-headers "GO:0008283", # BP 158 L02 D02 D cell proliferation "GO:0030154", # BP 494 L04 D04 CDF cell differentiation "GO:0045595", # BP 828 L03 D03 AB regulation of cell differentiation "GO:0042127", # BP 268 L03 D03 AB regulation of cell proliferation ]), ] # Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved.<|fim▁end|>
"GO:0006811", # BP 422 L04 D04 H ion transport "GO:0055085", # BP 330 L04 D04 H transmembrane transport "GO:0006874", # BP 33 L08 D09 ACD cellular calcium ion homeostasis
<|file_name|>view_mixins.py<|end_file_name|><|fim▁begin|>from django.apps import apps as django_apps from django.core.exceptions import ObjectDoesNotExist from django.views.generic.base import ContextMixin class SubjectOffstudyViewMixinError(Exception): pass class SubjectOffstudyViewMixin(ContextMixin): """Adds subject offstudy to the context. Declare with SubjectIdentifierViewMixin. """ offstudy_model_wrapper_cls = None subject_offstudy_model = None # def __init__(self, **kwargs): # super().__init__(**kwargs) # if not self.offstudy_model_wrapper_cls: # raise SubjectOffstudyViewMixinError( # 'subject_offstudy_model_wrapper_cls must be a valid ModelWrapper. Got None') # if not self.subject_offstudy_model: # raise SubjectOffstudyViewMixinError( # 'subject_offstudy_model must be a model (label_lower). Got None') # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # wrapper = self.offstudy_model_wrapper_cls( # model_obj=self.subject_offstudy) # context.update(subject_offstudy=wrapper) # return context @property def subject_offstudy_model_cls(self): try: model_cls = django_apps.get_model(self.subject_offstudy_model) except LookupError as e: raise SubjectOffstudyViewMixinError( f'Unable to lookup subject offstudy model. ' f'model={self.subject_offstudy_model}. Got {e}') return model_cls @property def subject_offstudy(self): """Returns a model instance either saved or unsaved. If a save instance does not exits, returns a new unsaved instance. """ model_cls = self.subject_offstudy_model_cls<|fim▁hole|> subject_offstudy = model_cls( subject_identifier=self.subject_identifier) except AttributeError as e: if 'subject_identifier' in str(e): raise SubjectOffstudyViewMixinError( f'Mixin must be declared together with SubjectIdentifierViewMixin. Got {e}') raise SubjectOffstudyViewMixinError(e) return subject_offstudy<|fim▁end|>
try: subject_offstudy = model_cls.objects.get( subject_identifier=self.subject_identifier) except ObjectDoesNotExist:
<|file_name|>_isEdge.js<|end_file_name|><|fim▁begin|>export default function _isEdge() {<|fim▁hole|><|fim▁end|>
const ua = navigator.userAgent.toLowerCase(); return Boolean(ua.match(/edge/i)); }
<|file_name|>modules.js<|end_file_name|><|fim▁begin|>var modules = { "success" : [ {id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}<|fim▁hole|> ], "error" : { code : "0200-ERROR", msg : "There are some errors occured." } } module.exports = { "modules": modules }<|fim▁end|>
<|file_name|>app.module.ts<|end_file_name|><|fim▁begin|>import { NgModule, ApplicationRef } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule, PreloadAllModules } from '@angular/router'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { StoreModule } from '@ngrx/store'; import { StoreDevtoolsModule } from "@ngrx/store-devtools"; import { StoreLogMonitorModule, useLogMonitor } from "@ngrx/store-log-monitor"; /* * Platform and Environment providers/directives/pipes */ import { ENV_PROVIDERS } from './environment'; import appRoutes from './app.routes'; // App is our top level component import { AppComponent } from './app.component'; import { HeaderComponent } from './header'; import { FooterComponent } from './footer'; import { APP_RESOLVER_PROVIDERS } from './app.resolver'; import { HomeComponent } from './home'; import { NoContentComponent } from './no-content'; import { productionReducer } from './demos/redux-demo/store'; // Application wide providers const APP_PROVIDERS = [ ...APP_RESOLVER_PROVIDERS ]; type StoreType = { restoreInputValues: () => void, disposeOldHosts: () => void }; /** * `AppModule` is the main entry point into Angular2's bootstraping process */ @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent, HomeComponent, HeaderComponent, FooterComponent, NoContentComponent ], imports: [ // import Angular's modules BrowserModule, FormsModule, HttpModule, appRoutes, NgbModule.forRoot(), /** * StoreModule.provideStore is imported once in the root module, accepting a reducer<|fim▁hole|> * based application. */ StoreModule.provideStore(productionReducer), // To use devtools as part of the page StoreDevtoolsModule.instrumentStore({ monitor: useLogMonitor({ visible: true, position: 'right' }) }), StoreLogMonitorModule ], providers: [ // expose our Services and Providers into Angular's dependency injection ENV_PROVIDERS, APP_PROVIDERS ] }) export class AppModule { constructor(public appRef: ApplicationRef) {} hmrOnInit(store: StoreType) { // set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues); } this.appRef.tick(); delete store.restoreInputValues; } hmrOnDestroy(store: StoreType) { const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement); // recreate root elements store.disposeOldHosts = createNewHosts(cmpLocation); // save input values store.restoreInputValues = createInputTransfer(); // remove styles removeNgStyles(); } hmrAfterDestroy(store: StoreType) { // display new elements store.disposeOldHosts(); delete store.disposeOldHosts; } }<|fim▁end|>
* function or object map of reducer functions. If passed an object of * reducers, combineReducers will be run creating your application * meta-reducer. This returns all providers for an @ngrx/store
<|file_name|>issue-53269.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //<|fim▁hole|>// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Ambiguity between a `macro_rules` macro and a non-existent import recovered as `Def::Err` macro_rules! mac { () => () } mod m { use nonexistent_module::mac; //~ ERROR unresolved import `nonexistent_module` mac!(); //~ ERROR `mac` is ambiguous } fn main() {}<|fim▁end|>
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
<|file_name|>symlink.test.js<|end_file_name|><|fim▁begin|>'use strict'; const fs = require('fs'); const path = require('path'); const test = require('ava'); const mockFs = require('mock-fs'); // const writeArtifacts = require('../../../lib/artifacts').writeArtifact; const writeArtifacts = require('../../../lib'); test.afterEach(() => mockFs.restore()); test('should include symlink to file by default', async t => { mockFs({ 'file.txt': 'Hi!', 'source-dir': { 'symlink.txt': mockFs.symlink({ path: path.join('..', 'file.txt') }) } }); await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' }); const link = fs.readlinkSync(path.join('artifact-dir', 'source-dir', 'symlink.txt')); t.is(link, path.join('..', 'file.txt')); }); test('should include symlink to dir by default', async t => { mockFs({ 'dir': { 'file.txt': 'Hi!' }, 'source-dir': { 'symdir': mockFs.symlink({ path: path.join('..', 'dir') }) } }); await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' }); const link = fs.readlinkSync(path.join('artifact-dir', 'source-dir', 'symdir')); t.is(link, path.join('..', 'dir')); }); test('should follow symlink to file', async t => { mockFs({ 'file.txt': 'Hi!', 'source-dir': { 'symlink.txt': mockFs.symlink({ path: path.join('..', 'file.txt') }) } }); await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' }, { followSymlinks: true }); const contents = fs.readFileSync(path.join('artifact-dir', 'source-dir', 'symlink.txt'), 'utf-8'); t.is(contents, 'Hi!'); }); test('should follow symlink to dir', async t => { mockFs({<|fim▁hole|> }, 'source-dir': { 'symdir': mockFs.symlink({ path: path.join('..', 'dir') }) } }); await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' }, { followSymlinks: true }); const contents = fs.readFileSync(path.join('artifact-dir', 'source-dir', 'symdir', 'file.txt'), 'utf-8'); t.is(contents, 'Hi!'); });<|fim▁end|>
'dir': { 'file.txt': 'Hi!'
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>import codecs from setuptools import setup VERSION = '0.2.0' def read_long_description(): long_desc = [] with codecs.open('README.rst', 'r', 'utf8') as longdesc: long_desc.append(longdesc.read()) with codecs.open('HISTORY.rst', 'r', 'utf8') as history: long_desc.append(history.read()) return u'\n\n'.join(long_desc) LONG_DESCRIPTION = read_long_description() setup( name='get_image_size', url='https://github.com/scardine/image_size', version=VERSION, long_description=LONG_DESCRIPTION,<|fim▁hole|> entry_points={ 'console_scripts': [ 'get-image-size = get_image_size:main', ], }, )<|fim▁end|>
author='github.com/scardine', author_email=' ', license='MIT', py_modules=['get_image_size'],
<|file_name|>order-address.js<|end_file_name|><|fim▁begin|>/* * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <[email protected]> * @copyright 2007-2015 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ $(document).ready(function(){ if (typeof formatedAddressFieldsValuesList !== 'undefined') updateAddressesDisplay(true); $(document).on('change', 'select[name=id_address_delivery], select[name=id_address_invoice]', function(){ updateAddressesDisplay(); if (typeof opc !=='undefined' && opc) updateAddressSelection(); }); $(document).on('click', 'input[name=same]', function(){ updateAddressesDisplay(); if (typeof opc !=='undefined' && opc) updateAddressSelection(); }); }); //update the display of the addresses function updateAddressesDisplay(first_view) { // update content of delivery address updateAddressDisplay('delivery'); var txtInvoiceTitle = ""; try{ var adrs_titles = getAddressesTitles(); txtInvoiceTitle = adrs_titles.invoice; } catch (e) {} // update content of invoice address //if addresses have to be equals... if ($('#addressesAreEquals:checked').length === 1 && ($('#multishipping_mode_checkbox:checked').length === 0)) { if ($('#multishipping_mode_checkbox:checked').length === 0) { $('#address_invoice_form:visible').hide('fast'); } $('ul#address_invoice').html($('ul#address_delivery').html()); $('ul#address_invoice li.address_title').html(txtInvoiceTitle); } else { $('#address_invoice_form:hidden').show('fast'); if ($('#id_address_invoice').val()) updateAddressDisplay('invoice'); else { $('ul#address_invoice').html($('ul#address_delivery').html()); $('ul#address_invoice li.address_title').html(txtInvoiceTitle); } } if(!first_view) { if (orderProcess === 'order') updateAddresses(); } return true; } function updateAddressDisplay(addressType) { if (typeof formatedAddressFieldsValuesList == 'undefined' || formatedAddressFieldsValuesList.length <= 0) return; var idAddress = parseInt($('#id_address_' + addressType + '').val()); buildAddressBlock(idAddress, addressType, $('#address_' + addressType)); // change update link var link = $('ul#address_' + addressType + ' li.address_update a').attr('href'); var expression = /id_address=\d+/; if (link) { link = link.replace(expression, 'id_address=' + idAddress); $('ul#address_' + addressType + ' li.address_update a').attr('href', link); } } function updateAddresses() { var idAddress_delivery = parseInt($('#id_address_delivery').val()); var idAddress_invoice = $('#addressesAreEquals:checked').length === 1 ? idAddress_delivery : parseInt($('#id_address_invoice').val()); if(isNaN(idAddress_delivery) == false && isNaN(idAddress_invoice) == false) { $('.addresses .waitimage').show(); $('.button[name="processAddress"]').prop('disabled', 'disabled'); $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType : "json", data: { processAddress: true, step: 2, ajax: 'true', controller: 'order', 'multi-shipping': $('#id_address_delivery:hidden').length, id_address_delivery: idAddress_delivery, id_address_invoice: idAddress_invoice, token: static_token }, success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) //IE6 bug fix if(error !== 'indexOf') errors += $('<div />').html(jsonData.errors[error]).text() + "\n"; if (!!$.prototype.fancybox) $.fancybox.open([ { type: 'inline', autoScale: true, minHeight: 30, content: '<p class="fancybox-error">' + errors + '</p>' } ], { padding: 0 }); else alert(errors); } $('.addresses .waitimage').hide(); $('.button[name="processAddress"]').prop('disabled', ''); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('.addresses .waitimage').hide(); $('.button[name="processAddress"]').prop('disabled', ''); if (textStatus !== 'abort') { error = "TECHNICAL ERROR: unable to save adresses \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus; if (!!$.prototype.fancybox) $.fancybox.open([ { type: 'inline', autoScale: true, minHeight: 30, content: '<p class="fancybox-error">' + error + '</p>' } ], { padding: 0 }); else alert(error); } } }); } } <|fim▁hole|> if (typeof titleInvoice !== 'undefined' && typeof titleDelivery !== 'undefined') return { 'invoice': titleInvoice, 'delivery': titleDelivery }; else return { 'invoice': '', 'delivery': '' }; } function buildAddressBlock(id_address, address_type, dest_comp) { if (isNaN(id_address)) return; var adr_titles_vals = getAddressesTitles(); var li_content = formatedAddressFieldsValuesList[id_address]['formated_fields_values']; var ordered_fields_name = ['title']; var reg = new RegExp("[ ]+", "g"); ordered_fields_name = ordered_fields_name.concat(formatedAddressFieldsValuesList[id_address]['ordered_fields']); ordered_fields_name = ordered_fields_name.concat(['update']); dest_comp.html(''); li_content['title'] = adr_titles_vals[address_type]; if (typeof liUpdate !== 'undefined') { var items = liUpdate.split(reg); var regUrl = new RegExp('(https?://[^"]*)', 'gi'); liUpdate = liUpdate.replace(regUrl, addressUrlAdd + parseInt(id_address)); li_content['update'] = liUpdate; } appendAddressList(dest_comp, li_content, ordered_fields_name); } function appendAddressList(dest_comp, values, fields_name) { for (var item in fields_name) { var name = fields_name[item].replace(",", ""); var value = getFieldValue(name, values); if (value != "") { var new_li = document.createElement('li'); var reg = new RegExp("[ ]+", "g"); var classes = name.split(reg); new_li.className = ''; for (clas in classes) new_li.className += 'address_' + classes[clas].toLowerCase().replace(":", "_") + ' '; new_li.className = $.trim(new_li.className); new_li.innerHTML = value; dest_comp.append(new_li); } } } function getFieldValue(field_name, values) { var reg = new RegExp("[ ]+", "g"); var items = field_name.split(reg); var vals = new Array(); for (var field_item in items) { items[field_item] = items[field_item].replace(",", ""); vals.push(values[items[field_item]]); } return vals.join(" "); }<|fim▁end|>
function getAddressesTitles() {
<|file_name|>snapshot.py<|end_file_name|><|fim▁begin|>import argparse import os import subprocess import mongoengine as me import rmc.html_snapshots.utils as utils import rmc.shared.constants as c def crawl_page(url): args = [ 'phantomjs', '--disk-cache=true', os.path.join(utils.FILE_DIR, 'phantom-server.js'), url, ] rendered_html = subprocess.check_output(args) return rendered_html def generate_snapshots(base_url, overwrite=False): urls = utils.generate_urls() for url in urls: # For urls that end with a trailing slash, create them # as the index page of a subdirectory if url and url[0] == '/': url = url[1:] if not url: file_path = 'index' file_url = '' elif url[-1] == '/': file_path = url + 'index' file_url = url else: file_path = url file_url = url file_path = os.path.join(utils.HTML_DIR, file_path) if os.path.isdir(file_path): print 'Cannot have file_path that is directory: %s' % file_path<|fim▁hole|> rendered_html = crawl_page(full_url) print 'Writing: %s' % url utils.write(file_path, rendered_html) if __name__ == "__main__": parser = argparse.ArgumentParser( description='Process snapshotting arguments') parser.add_argument('base_url', type=str) parser.add_argument('--overwrite', dest='overwrite', action='store_true') args = parser.parse_args() me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT) generate_snapshots(args.base_url, args.overwrite)<|fim▁end|>
if not overwrite and os.path.isfile(file_path): continue full_url = os.path.join(base_url, file_url)
<|file_name|>test_util.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict<|fim▁hole|> from nose.tools import eq_, assert_true, assert_false from mosql.compat import binary_type, text_type from mosql.util import ( autoparam, build_set, build_where, param, ___, _is_iterable_not_str, ) def test_is_iterable_not_str(): # Iterable objects. assert_true(_is_iterable_not_str([])) assert_true(_is_iterable_not_str(tuple())) assert_true(_is_iterable_not_str({})) assert_true(_is_iterable_not_str(set())) # Strings are iterable, but not included. assert_false(_is_iterable_not_str('')) assert_false(_is_iterable_not_str(b'')) assert_false(_is_iterable_not_str(u'')) assert_false(_is_iterable_not_str(binary_type())) assert_false(_is_iterable_not_str(text_type())) def test_build_where(): gen = build_where(OrderedDict([ ('detail_id', 1), ('age >= ', 20), ('created', date(2013, 4, 16)), ])) eq_(gen, '"detail_id" = 1 AND "age" >= 20 AND "created" = \'2013-04-16\'') def test_build_where_operator(): gen = build_where(OrderedDict([ ('detail_id', 1), (('age', '>='), 20), ('created', date(2013, 4, 16)), ])) eq_(gen, '"detail_id" = 1 AND "age" >= 20 AND "created" = \'2013-04-16\'') def test_build_where_prepared(): gen = build_where(OrderedDict([ ('custom_param', param('my_param')), ('auto_param', autoparam), ('using_alias', ___), ])) exp = ('"custom_param" = %(my_param)s AND "auto_param" = %(auto_param)s ' 'AND "using_alias" = %(using_alias)s') eq_(gen, exp) def test_build_set(): gen = build_set(OrderedDict([ ('a', 1), ('b', True), ('c', date(2013, 4, 16)), ])) eq_(gen, '"a"=1, "b"=TRUE, "c"=\'2013-04-16\'') def test_build_set_prepared(): gen = build_set(OrderedDict([ ('custom_param', param('myparam')), ('auto_param', autoparam), ])) eq_(gen, '"custom_param"=%(myparam)s, "auto_param"=%(auto_param)s')<|fim▁end|>
from datetime import date
<|file_name|>spritesheet.cpp<|end_file_name|><|fim▁begin|>#include "spritesheet.hpp" ////////// // Code // // Initializing the SpriteSheet sizes. void SpriteSheet::init(int cols, int rows, int width, int height) { this->cols = cols; this->rows = rows; this->width = width; this->height = height; } // Making a SpriteSheet from an existing SDL_Texture. SpriteSheet::SpriteSheet(SDL_Texture* tex, int cols , int rows, int width, int height) throw(HCException) { this->sprite = new Sprite(tex); init(cols, rows, width, height); } // Making a SpriteSheet from an SDL_Surface. SpriteSheet::SpriteSheet(SDL_Renderer* renderer, SDL_Surface* surf, int cols , int rows, int width, int height) throw(HCException) { this->sprite = new Sprite(renderer, surf); init(cols, rows, width, height); } // Loading a SpriteSheet from a location on the disk. SpriteSheet::SpriteSheet(SDL_Renderer* renderer, std::string path, int cols , int rows, int width, int height) throw(HCException) { this->sprite = new Sprite(renderer, path); init(cols, rows, width, height); } // The copy constructor. SpriteSheet::SpriteSheet(const SpriteSheet& ss) { this->sprite = ss.sprite; init(ss.rows, ss.cols, ss.width, ss.height); this->original = false; } // Destroying the SpriteSheet. SpriteSheet::~SpriteSheet() { if (this->original) delete this->sprite; } // Blitting a specific tile. void SpriteSheet::blit(Window& w, Rectangle dst, int x, int y) const { Rectangle r(x * this->width, y * this->height, this->width, this->height); this->sprite->blit(w, dst, r); }<|fim▁hole|>// Accessors int SpriteSheet::getCols() const { return this->cols; } int SpriteSheet::getRows() const { return this->rows; }<|fim▁end|>
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic import View from .models import \ Course, Registration, Task, TaskSubmission, ScoreProfile from .forms import TaskSubmissionForm class CourseListView(View): template_name = 'courses/course_select.html' @method_decorator(login_required) def get(self, request, *args, **kwargs): context = { 'courses': request.user.course_set.all(), 'profile': ScoreProfile.get_score_profile(request.user), 'highscore': ScoreProfile.objects.all().order_by('-score')[:10] } return render(request, self.template_name, context) @method_decorator(login_required) def post(self, request, *args, **kwargs): pass class ProfileView(View): @method_decorator(login_required) def get(self, request, *args, **kwargs): context = {} profile = ScoreProfile.get_score_profile(request.user) context['username'] = request.user.username context['rank'] = profile.current_rank context['score'] = profile.score context['courses'] = request.user.course_set.all() context['valid_submissions'] = \ TaskSubmission.objects.filter(submitted_by=request.user, valid=True).values_list('task', flat=True) return render(request, 'courses/profile.html', context) class TaskSubmissionView(View): form_class = TaskSubmissionForm template_name = 'courses/task.html' @method_decorator(login_required) def get(self, request, *args, **kwargs): context = self.get_context_data() context['form'] = self.form_class() context['subs'] = TaskSubmission.objects.filter( submitted_by=request.user, task=self.kwargs['task_id'] ) context['valid_subs'] = context['subs'].filter( valid=True ) return render(request, self.template_name, context) @method_decorator(login_required) def post(self, request, *args, **kwargs): task = Task.objects.get(pk=self.kwargs['task_id']) sub = TaskSubmission() sub.task = task sub.submitted_by = request.user sub.valid = False form = self.form_class(request.POST, request.FILES, instance=sub) if form.is_valid(): form.save() return self.get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = {} context['task'] = Task.objects.get(pk=self.kwargs['task_id']) return context class CourseRegistrationView(View): @method_decorator(login_required) def post(self, request, *args, **kwargs): course_id = request.POST['course_id'] course = Course.objects.get(pk=course_id) if course: Registration.objects.filter(user=request.user, course=course).delete() else: return if request.POST['sign_up'] == u'master': Registration(user=request.user, course=course, granted=False, code_master=True, role=Registration.CODE_MASTER).save() elif request.POST['sign_up'] == u'kid': Registration(user=request.user, course=course, granted=False, code_master=False, role=Registration.KID).save() elif request.POST['sign_up'] == u'reserve': Registration(user=request.user, course=course, granted=False,<|fim▁hole|> role=Registration.RESERVE).save() return<|fim▁end|>
code_master=False,
<|file_name|>rule_501.py<|end_file_name|><|fim▁begin|>from vsg.rules import token_case from vsg import token lTokens = [] lTokens.append(token.package_body.body_keyword) class rule_501(token_case):<|fim▁hole|> |configuring_uppercase_and_lowercase_rules_link| **Violation** .. code-block:: vhdl package BODY FIFO_PKG is **Fix** .. code-block:: vhdl package body FIFO_PKG is ''' def __init__(self): token_case.__init__(self, 'package_body', '501', lTokens) self.groups.append('case::keyword')<|fim▁end|>
''' This rule checks the **body** keyword has proper case.
<|file_name|>search_history_item.py<|end_file_name|><|fim▁begin|>__author__ = 'bromix' from .directory_item import DirectoryItem from .. import constants <|fim▁hole|>class SearchHistoryItem(DirectoryItem): def __init__(self, context, query, image=None, fanart=None): if image is None: image = context.create_resource_path('media/search.png') pass DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}), image=image) if fanart: self.set_fanart(fanart) pass else: self.set_fanart(context.get_fanart()) pass context_menu = [(context.localize(constants.localize.SEARCH_REMOVE), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'remove'], params={'q': query})), (context.localize(constants.localize.SEARCH_RENAME), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'rename'], params={'q': query})), (context.localize(constants.localize.SEARCH_CLEAR), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'clear']))] self.set_context_menu(context_menu) pass pass<|fim▁end|>
<|file_name|>add_comment.ts<|end_file_name|><|fim▁begin|>/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { httpGitRequest } from '../service/request'; export async function newDetachedCommentThread( currFilePath, serverRoot, commentString, lineNumber? ) { const body: Record<string, string> = { comment: commentString, }; if (lineNumber) { body.line = lineNumber; } httpGitRequest( 'addDetachedComment', 'POST', currFilePath, serverRoot, body ).then(response => { console.log(response); }); } export async function newDetachedCommentReply( currFilePath, serverRoot, commentString, parentHash ) { const body: Record<string, string> = { comment: commentString, parent: parentHash, }; httpGitRequest( 'addDetachedComment', 'POST', currFilePath, serverRoot, body ).then(response => { console.log(response); }); } export async function newReviewCommentThread( currFilePath, serverRoot, commentString, reviewHash, lineNumber? ) { const body: Record<string, string> = { comment: commentString, reviewHash: reviewHash, }; if (lineNumber) { body.line = lineNumber; } httpGitRequest( 'addReviewComment', 'POST', currFilePath, serverRoot, body ).then(response => { console.log(response); }); }<|fim▁hole|> serverRoot, commentString, parentHash, reviewHash ) { const body: Record<string, string> = { comment: commentString, parent: parentHash, reviewHash: reviewHash, }; httpGitRequest( 'addReviewComment', 'POST', currFilePath, serverRoot, body ).then(response => { console.log(response); }); }<|fim▁end|>
export async function newReviewCommentReply( currFilePath,
<|file_name|>on-finished.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for on-finished v2.2.0 // Project: https://github.com/jshttp/on-finished // Definitions by: Honza Dvorsky <http://github.com/czechboy0> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../node/node.d.ts" /> declare module 'on-finished' {<|fim▁hole|> export function isFinished(msg:NodeJS.EventEmitter):boolean; } export = onFinished; }<|fim▁end|>
function onFinished(msg:NodeJS.EventEmitter, listener:Function): NodeJS.EventEmitter; namespace onFinished {
<|file_name|>0002_auto_20170424_0117.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-23 22:17 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('backups', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='backupfirewall', name='file_location', ), migrations.RemoveField( model_name='backupfirewall', name='site_name', ), migrations.RemoveField( model_name='backuprouter', name='file_location', ),<|fim▁hole|> migrations.RemoveField( model_name='backuprouter', name='site_name', ), ]<|fim▁end|>
<|file_name|>extern-fail.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test linked failure // error-pattern:explicit failure // Testing that runtime failure doesn't cause callbacks to abort abnormally. // Instead the failure will be delivered after the callbacks return.<|fim▁hole|>mod rustrt { use std::libc; extern { pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1u { data } else { count(data - 1u) + count(data - 1u) } } fn count(n: uint) -> uint { unsafe { task::deschedule(); rustrt::rust_dbg_call(cb, n) } } fn main() { do 10u.times { do task::spawn { let result = count(5u); info!("result = %?", result); fail!(); }; } }<|fim▁end|>
use std::libc; use std::task;