code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.map, name='map'),
url(r'^mapSim', views.mapSim, name='mapSim'),
url(r'^api/getPos', views.getPos, name='getPos'),
url(r'^api/getProjAndPos', views.getProjAndPos, name='getProjAndPos'),
]
| j-herrera/icarus | icarus_site/ISStrace/urls.py | Python | gpl-2.0 | 279 |
// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify
#define SA(n, p) int a##n[(p) ? 1 : -1]
struct A { int a; };
SA(0, sizeof(A) == 4);
struct B { };
SA(1, sizeof(B) == 1);
struct C : A, B { };
SA(2, sizeof(C) == 4);
struct D { };
struct E : D { };
struct F : E { };
struct G : E, F { };
SA(3, sizeof(G) == 2);
struct Empty { Empty(); };
struct I : Empty {
Empty e;
};
SA(4, sizeof(I) == 2);
struct J : Empty {
Empty e[2];
};
SA(5, sizeof(J) == 3);
template<int N> struct Derived : Empty, Derived<N - 1> {
};
template<> struct Derived<0> : Empty { };
struct S1 : virtual Derived<10> {
Empty e;
};
SA(6, sizeof(S1) == 24);
struct S2 : virtual Derived<10> {
Empty e[2];
};
SA(7, sizeof(S2) == 24);
struct S3 {
Empty e;
};
struct S4 : Empty, S3 {
};
SA(8, sizeof(S4) == 2);
struct S5 : S3, Empty {};
SA(9, sizeof(S5) == 2);
struct S6 : S5 { };
SA(10, sizeof(S6) == 2);
struct S7 : Empty {
void *v;
};
SA(11, sizeof(S7) == 8);
struct S8 : Empty, A {
};
SA(12, sizeof(S8) == 4);
| vrtadmin/clamav-bytecode-compiler | clang/test/SemaCXX/empty-class-layout.cpp | C++ | gpl-2.0 | 1,034 |
using Halsign.DWM.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
namespace Halsign.DWM.Domain
{
public class DwmHost : DwmBase
{
private int _numCpus = 1;
private int _numVCpus;
private int _cpuSpeed;
private int _numNics = 1;
private bool _isPoolMaster;
private bool _enabled = true;
private string _ipAddress;
private bool _isEnterpriseOrHigher;
private PowerStatus _powerState;
private bool _participatesInPowerManagement;
private bool _excludeFromPlacementRecommendations;
private bool _excludeFromEvacuationRecommendations;
private bool _excludeFromPoolOptimizationAcceptVMs;
private long _memOverhead;
private DateTime _metricsLastRetrieved = DateTime.MinValue;
private DwmVirtualMachineCollection _listVMs;
private DwmPifCollection _listPIFs;
private DwmPbdCollection _listPBDs;
private DwmStorageRepositoryCollection _availableStorage;
private DwmHostAverageMetric _metrics;
private static Dictionary<string, int> _uuidCache = new Dictionary<string, int>();
private static Dictionary<string, int> _nameCache = new Dictionary<string, int>();
private static Dictionary<string, string> _uuidNameCache = new Dictionary<string, string>();
private static object _uuidCacheLock = new object();
private static object _nameCacheLock = new object();
private static object _uuidNameCacheLock = new object();
private double _cpuScore;
public int NumCpus
{
get
{
return this._numCpus;
}
set
{
this._numCpus = value;
}
}
public int NumVCpus
{
get
{
return this._numVCpus;
}
set
{
this._numVCpus = value;
}
}
public int CpuSpeed
{
get
{
return this._cpuSpeed;
}
set
{
this._cpuSpeed = value;
}
}
public int NumNics
{
get
{
return this._numNics;
}
set
{
this._numNics = value;
}
}
public string IPAddress
{
get
{
return this._ipAddress;
}
set
{
this._ipAddress = value;
}
}
public bool IsPoolMaster
{
get
{
return this._isPoolMaster;
}
set
{
this._isPoolMaster = value;
}
}
public bool Enabled
{
get
{
return this._enabled;
}
set
{
this._enabled = value;
}
}
public bool IsEnterpriseOrHigher
{
get
{
return this._isEnterpriseOrHigher;
}
set
{
this._isEnterpriseOrHigher = value;
}
}
public PowerStatus PowerState
{
get
{
return this._powerState;
}
set
{
this._powerState = value;
}
}
public long MemoryOverhead
{
get
{
return this._memOverhead;
}
set
{
this._memOverhead = value;
}
}
internal bool ParticipatesInPowerManagement
{
get
{
return this._participatesInPowerManagement;
}
set
{
this._participatesInPowerManagement = value;
}
}
internal bool ExcludeFromPlacementRecommendations
{
get
{
return this._excludeFromPlacementRecommendations;
}
set
{
this._excludeFromPlacementRecommendations = value;
}
}
internal bool ExcludeFromEvacuationRecommendations
{
get
{
return this._excludeFromEvacuationRecommendations;
}
set
{
this._excludeFromEvacuationRecommendations = value;
}
}
internal bool ExcludeFromPoolOptimizationAcceptVMs
{
get
{
return this._excludeFromPoolOptimizationAcceptVMs;
}
set
{
this._excludeFromPoolOptimizationAcceptVMs = value;
}
}
public DwmVirtualMachineCollection VirtualMachines
{
get
{
return DwmBase.SafeGetItem<DwmVirtualMachineCollection>(ref this._listVMs);
}
internal set
{
this._listVMs = value;
}
}
public DwmPifCollection PIFs
{
get
{
return DwmBase.SafeGetItem<DwmPifCollection>(ref this._listPIFs);
}
}
public DwmPbdCollection PBDs
{
get
{
return DwmBase.SafeGetItem<DwmPbdCollection>(ref this._listPBDs);
}
}
public DwmStorageRepositoryCollection AvailableStorage
{
get
{
return DwmBase.SafeGetItem<DwmStorageRepositoryCollection>(ref this._availableStorage);
}
internal set
{
this._availableStorage = value;
}
}
public DwmHostAverageMetric Metrics
{
get
{
return DwmBase.SafeGetItem<DwmHostAverageMetric>(ref this._metrics);
}
internal set
{
this._metrics = value;
}
}
internal double CpuScore
{
get
{
this._cpuScore = (double)(this.NumCpus * this.CpuSpeed);
if (this.Metrics.MetricsNow != null)
{
this._cpuScore *= 1.0 - this.Metrics.MetricsNow.AverageCpuUtilization;
}
return this._cpuScore;
}
}
public DateTime MetricsLastRetrieved
{
get
{
if (this._metricsLastRetrieved == DateTime.MinValue)
{
string sqlStatement = "get_host_last_metric_time";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", base.Id));
using (DBAccess dBAccess = new DBAccess())
{
this._metricsLastRetrieved = dBAccess.ExecuteScalarDateTime(sqlStatement, storedProcParamCollection);
}
if (this._metricsLastRetrieved == DateTime.MinValue)
{
this._metricsLastRetrieved = DateTime.UtcNow.AddMinutes(-1.0);
}
}
return this._metricsLastRetrieved;
}
set
{
this._metricsLastRetrieved = value;
}
}
public DwmHost(string uuid, string name, string poolUuid) : base(uuid, name)
{
base.PoolId = DwmBase.PoolUuidToId(poolUuid);
if (!string.IsNullOrEmpty(uuid))
{
base.Id = DwmHost.UuidToId(uuid, base.PoolId);
}
else
{
if (string.IsNullOrEmpty(name))
{
throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null);
}
base.Id = DwmHost.NameToId(name, base.PoolId);
}
}
public DwmHost(string uuid, string name, int poolId) : base(uuid, name)
{
base.PoolId = poolId;
if (!string.IsNullOrEmpty(uuid))
{
base.Id = DwmHost.UuidToId(uuid, base.PoolId);
}
else
{
if (string.IsNullOrEmpty(name))
{
throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null);
}
base.Id = DwmHost.NameToId(name, base.PoolId);
}
}
public DwmHost(int hostID) : base(hostID)
{
}
internal static void RefreshCache()
{
object uuidCacheLock = DwmHost._uuidCacheLock;
Monitor.Enter(uuidCacheLock);
try
{
DwmHost._uuidCache.Clear();
}
finally
{
Monitor.Exit(uuidCacheLock);
}
object nameCacheLock = DwmHost._nameCacheLock;
Monitor.Enter(nameCacheLock);
try
{
DwmHost._nameCache.Clear();
}
finally
{
Monitor.Exit(nameCacheLock);
}
object uuidNameCacheLock = DwmHost._uuidNameCacheLock;
Monitor.Enter(uuidNameCacheLock);
try
{
DwmHost._uuidNameCache.Clear();
}
finally
{
Monitor.Exit(uuidNameCacheLock);
}
}
internal static int UuidToId(string uuid, int poolId)
{
int num = 0;
if (!string.IsNullOrEmpty(uuid))
{
string key = Localization.Format("{0}|{1}", uuid, poolId);
if (!DwmHost._uuidCache.TryGetValue(key, out num))
{
using (DBAccess dBAccess = new DBAccess())
{
num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where uuid='{0}' and poolid={1}", uuid.Replace("'", "''"), poolId));
if (num != 0)
{
object uuidCacheLock = DwmHost._uuidCacheLock;
Monitor.Enter(uuidCacheLock);
try
{
if (!DwmHost._uuidCache.ContainsKey(key))
{
DwmHost._uuidCache.Add(key, num);
}
}
finally
{
Monitor.Exit(uuidCacheLock);
}
}
}
}
}
return num;
}
public static int NameToId(string name, int poolId)
{
int num = 0;
if (!string.IsNullOrEmpty(name))
{
string key = Localization.Format("{0}|{1}", name, poolId);
if (!DwmHost._nameCache.TryGetValue(key, out num))
{
using (DBAccess dBAccess = new DBAccess())
{
num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where name='{0}' and poolid={1}", name.Replace("'", "''"), poolId));
if (num != 0)
{
object nameCacheLock = DwmHost._nameCacheLock;
Monitor.Enter(nameCacheLock);
try
{
if (!DwmHost._nameCache.ContainsKey(key))
{
DwmHost._nameCache.Add(key, num);
}
}
finally
{
Monitor.Exit(nameCacheLock);
}
}
}
}
}
return num;
}
public static string UuidToName(string uuid, int poolId)
{
string text = string.Empty;
if (!string.IsNullOrEmpty(uuid))
{
string key = Localization.Format("{0}|{1}", uuid, poolId);
if (!DwmHost._uuidNameCache.TryGetValue(key, out text))
{
using (DBAccess dBAccess = new DBAccess())
{
text = dBAccess.ExecuteScalarString(Localization.Format("select name from hv_host where uuid='{0}' and poolid={1}", uuid, poolId));
if (string.IsNullOrEmpty(text))
{
object uuidNameCacheLock = DwmHost._uuidNameCacheLock;
Monitor.Enter(uuidNameCacheLock);
try
{
if (!DwmHost._uuidNameCache.ContainsKey(key))
{
DwmHost._uuidNameCache.Add(key, text);
}
}
finally
{
Monitor.Exit(uuidNameCacheLock);
}
}
}
}
}
return text;
}
public DwmHost Copy()
{
return new DwmHost(base.Uuid, base.Name, base.PoolId)
{
Id = base.Id,
CpuSpeed = this.CpuSpeed,
Description = base.Description,
IsPoolMaster = this.IsPoolMaster,
Name = base.Name,
NumCpus = this.NumCpus,
NumVCpus = this.NumVCpus,
NumNics = this.NumNics,
ParticipatesInPowerManagement = this.ParticipatesInPowerManagement,
ExcludeFromPlacementRecommendations = this.ExcludeFromPlacementRecommendations,
ExcludeFromEvacuationRecommendations = this.ExcludeFromEvacuationRecommendations,
ExcludeFromPoolOptimizationAcceptVMs = this.ExcludeFromPoolOptimizationAcceptVMs,
PowerState = this.PowerState,
MemoryOverhead = this.MemoryOverhead,
Metrics = this.Metrics.Copy(),
AvailableStorage = this.AvailableStorage.Copy(),
VirtualMachines = this.VirtualMachines.Copy()
};
}
internal static void SetOtherConfig(int hostId, string name, string value)
{
DwmHost dwmHost = new DwmHost(hostId);
dwmHost.SetOtherConfig(name, value);
}
public void SetOtherConfig(string name, string value)
{
base.SetOtherConfig("hv_host_config_update", "@host_id", name, value);
if (Localization.Compare(name, "ParticipatesInPowerManagement", true) == 0)
{
DwmPool.GenerateFillOrder(base.PoolId);
}
}
public void SetOtherConfig(Dictionary<string, string> config)
{
base.SetOtherConfig("hv_host_config_update", "@host_id", config);
if (config.ContainsKey("ParticipatesInPowerManagement"))
{
DwmPool.GenerateFillOrder(base.PoolId);
}
}
public string GetOtherConfigItem(string itemName)
{
return base.GetOtherConfigItem("hv_host_config_get_item", "@host_id", itemName);
}
public Dictionary<string, string> GetOtherConfig()
{
return base.GetOtherConfig("hv_host_config_get", "@host_id");
}
public static void SetEnabled(string hostUuid, string poolUuid, bool enabled)
{
string sqlStatement = "hv_host_set_enabled";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_uuid", hostUuid));
storedProcParamCollection.Add(new StoredProcParam("@pool_uuid", poolUuid));
storedProcParamCollection.Add(new StoredProcParam("@enabled", enabled));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal static void SetStatus(int hostId, DwmStatus status)
{
string sqlStatement = "set_host_status";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
storedProcParamCollection.Add(new StoredProcParam("@status", (int)status));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal static void SetLastResult(int hostId, DwmStatus result)
{
string sqlStatement = "set_host_last_result";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
storedProcParamCollection.Add(new StoredProcParam("@last_result", (int)result));
storedProcParamCollection.Add(new StoredProcParam("@last_result_time", DateTime.UtcNow));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
public static void SetPoweredOffByWlb(int hostId, bool poweredOffByWlb)
{
string sqlStatement = "set_host_powered_off_by_wlb";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
if (poweredOffByWlb)
{
storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 1));
}
else
{
storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 0));
}
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal bool HasRequiredStorage(DwmStorageRepositoryCollection requiredSRs)
{
bool result = true;
int num = 0;
while (requiredSRs != null && num < requiredSRs.Count)
{
if (!this.AvailableStorage.ContainsKey(requiredSRs[num].Id))
{
result = false;
break;
}
num++;
}
return result;
}
public static void DeleteHost(string hostUuid, string poolUuid)
{
if (!string.IsNullOrEmpty(hostUuid) && !string.IsNullOrEmpty(poolUuid))
{
Logger.Trace("Deleting host {0} by setting active to false", new object[]
{
hostUuid
});
int num = DwmPoolBase.UuidToId(poolUuid);
int num2 = DwmHost.UuidToId(hostUuid, num);
string sqlStatement = "delete_hv_host";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@pool_id", num));
storedProcParamCollection.Add(new StoredProcParam("@host_id", num2));
storedProcParamCollection.Add(new StoredProcParam("@tstamp", DateTime.UtcNow));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
}
internal static DwmHost LoadWithMetrics(IDataReader reader)
{
string @string = DBAccess.GetString(reader, "uuid");
string string2 = DBAccess.GetString(reader, "name");
int @int = DBAccess.GetInt(reader, "poolid");
return new DwmHost(@string, string2, @int)
{
Id = DBAccess.GetInt(reader, "id"),
NumCpus = DBAccess.GetInt(reader, "num_cpus"),
NumVCpus = DBAccess.GetInt(reader, "num_vcpus"),
CpuSpeed = DBAccess.GetInt(reader, "cpu_speed"),
NumNics = DBAccess.GetInt(reader, "num_pifs"),
IsPoolMaster = DBAccess.GetBool(reader, "is_pool_master"),
PowerState = (PowerStatus)DBAccess.GetInt(reader, "power_state"),
ParticipatesInPowerManagement = DBAccess.GetBool(reader, "can_power"),
ExcludeFromPlacementRecommendations = DBAccess.GetBool(reader, "exclude_placements"),
ExcludeFromEvacuationRecommendations = DBAccess.GetBool(reader, "exclude_evacuations"),
Metrics =
{
FreeCPUs = DBAccess.GetInt(reader, "free_cpus"),
PotentialFreeMemory = DBAccess.GetInt64(reader, "potential_free_memory"),
FillOrder = DBAccess.GetInt(reader, "fill_order"),
TotalMemory = DBAccess.GetInt64(reader, "total_mem"),
FreeMemory = DBAccess.GetInt64(reader, "free_mem"),
NumHighFullContentionVCpus = DBAccess.GetInt(reader, "full_contention_count"),
NumHighConcurrencyHazardVCpus = DBAccess.GetInt(reader, "concurrency_hazard_count"),
NumHighPartialContentionVCpus = DBAccess.GetInt(reader, "partial_contention_count"),
NumHighFullrunVCpus = DBAccess.GetInt(reader, "fullrun_count"),
NumHighPartialRunVCpus = DBAccess.GetInt(reader, "partial_run_count"),
NumHighBlockedVCpus = DBAccess.GetInt(reader, "blocked_count"),
MetricsNow =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_now", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_now", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_now", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_now", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_now", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_now", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_now", 0.0)
},
MetricsLast30Minutes =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_30", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_30", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_30", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_30", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_30", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_30", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_30", 0.0)
},
MetricsYesterday =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_yesterday", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_yesterday", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_yesterday", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_yesterday", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_yesterday", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_yesterday", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_yesterday", 0.0)
}
}
};
}
internal void LoadPif(IDataReader reader)
{
int @int = DBAccess.GetInt(reader, "pif_id");
string @string = DBAccess.GetString(reader, "pif_uuid");
string string2 = DBAccess.GetString(reader, "pif_name");
int int2 = DBAccess.GetInt(reader, "networkid");
int int3 = DBAccess.GetInt(reader, "poolid");
bool @bool = DBAccess.GetBool(reader, "is_management_interface");
DwmPif dwmPif = new DwmPif(@string, string2, int2, int3);
dwmPif.Id = @int;
dwmPif.IsManagementInterface = @bool;
this.PIFs.Add(dwmPif);
}
public void Save()
{
using (DBAccess dBAccess = new DBAccess())
{
this.Save(dBAccess);
}
}
public void Save(DBAccess db)
{
if (db != null)
{
try
{
string sqlStatement = "add_update_hv_host";
base.Id = db.ExecuteScalarInt(sqlStatement, new StoredProcParamCollection
{
new StoredProcParam("@uuid", base.Uuid),
new StoredProcParam("@name", (base.Name == null) ? string.Empty : base.Name),
new StoredProcParam("@pool_id", base.PoolId),
new StoredProcParam("@description", (base.Description == null) ? string.Empty : base.Description),
new StoredProcParam("@num_cpus", this._numCpus),
new StoredProcParam("@cpu_speed", this._cpuSpeed),
new StoredProcParam("@num_nics", this._numNics),
new StoredProcParam("@is_pool_master", this._isPoolMaster),
new StoredProcParam("@ip_address", this._ipAddress),
new StoredProcParam("@memory_overhead", this._memOverhead),
new StoredProcParam("@enabled", this._enabled),
new StoredProcParam("@power_state", (int)this._powerState)
});
StringBuilder stringBuilder = new StringBuilder();
string value = "BEGIN;\n";
string value2 = "COMMIT;\n";
stringBuilder.Append(value);
stringBuilder.Append(this.SaveHostStorageRelationships());
stringBuilder.Append(this.SaveHostVmRelationships());
stringBuilder.Append(this.SaveHostPifRelationships());
stringBuilder.Append(this.SaveHostPbdRelationships());
stringBuilder.Append(value2);
DwmBase.WriteData(db, stringBuilder);
}
catch (Exception ex)
{
Logger.Trace("Caught exception saving host {0} uuid={1}", new object[]
{
base.Name,
base.Uuid
});
Logger.LogException(ex);
}
return;
}
throw new DwmException("Cannot pass null DBAccess instance to Save", DwmErrorCode.NullReference, null);
}
private StringBuilder SaveHostStorageRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._availableStorage != null && this._availableStorage.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._availableStorage.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_storage_repository (host_id, sr_id) select {0}, {1}\nwhere not exists (select id from hv_host_storage_repository where host_id={0} and sr_id={1});\n", base.Id, this._availableStorage[i].Id);
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._availableStorage[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0} and sr_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0};\n", base.Id);
}
return stringBuilder;
}
private StringBuilder SaveHostVmRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listVMs != null && this._listVMs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listVMs.Count; i++)
{
stringBuilder.AppendFormat("select * from add_update_host_vm( {0}, {1}, '{2}');\n", base.Id, this._listVMs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listVMs[i].Id);
}
stringBuilder.AppendFormat("delete from host_vm where hostid={0} and vmid not in ({1});\nupdate host_vm_history set end_time='{2}' \nwhere host_id={0}\n and end_time is null\n and vm_id not in ({1});\n", base.Id, stringBuilder2.ToString(), Localization.DateTimeToSqlString(DateTime.UtcNow));
}
else
{
stringBuilder.AppendFormat("delete from host_vm where hostid={0};\nupdate host_vm_history set end_time='{1}' \nwhere host_id={0} and end_time is null;\n", base.Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
}
return stringBuilder;
}
private StringBuilder SaveHostPifRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listPIFs != null && this._listPIFs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listPIFs.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_pif (hostid, pif_id, tstamp) select {0}, {1},'{2}'\nwhere not exists (select id from hv_host_pif where hostid={0} and pif_id={1});\n", base.Id, this._listPIFs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPIFs[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0} and pif_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0};\n", base.Id);
}
return stringBuilder;
}
private StringBuilder SaveHostPbdRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listPBDs != null && this._listPBDs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listPBDs.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_pbd (hostid, pbd_id, tstamp) select {0}, {1}, '{2}'\nwhere not exists (select id from hv_host_pbd where hostid={0} and pbd_id={1});\n", base.Id, this._listPBDs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPBDs[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0} and pbd_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0};\n", base.Id);
}
return stringBuilder;
}
public void Load()
{
string sql = "load_host_by_id";
this.InternalLoad(sql, new StoredProcParamCollection
{
new StoredProcParam("@host_id", base.Id)
});
}
internal void SimpleLoad()
{
string sql = "load_host_simple_by_id";
this.InternalLoad(sql, new StoredProcParamCollection
{
new StoredProcParam("@host_id", base.Id)
});
}
private void InternalLoad(string sql, StoredProcParamCollection parms)
{
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.UseTransaction = true;
using (IDataReader dataReader = dBAccess.ExecuteReader(sql, parms))
{
if (dataReader.Read())
{
if (string.IsNullOrEmpty(base.Uuid))
{
base.Uuid = DBAccess.GetString(dataReader, "uuid");
}
if (base.PoolId <= 0)
{
base.PoolId = DBAccess.GetInt(dataReader, "poolid");
}
base.Name = DBAccess.GetString(dataReader, "name");
base.Description = DBAccess.GetString(dataReader, "description");
this.NumCpus = DBAccess.GetInt(dataReader, "num_cpus");
this.CpuSpeed = DBAccess.GetInt(dataReader, "cpu_speed");
this.NumNics = DBAccess.GetInt(dataReader, "num_pifs");
this.IsPoolMaster = DBAccess.GetBool(dataReader, "is_pool_master");
this.Enabled = DBAccess.GetBool(dataReader, "enabled");
this.Metrics.FillOrder = DBAccess.GetInt(dataReader, "fill_order");
this.IPAddress = DBAccess.GetString(dataReader, "ip_address");
this.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead");
base.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status");
base.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result");
base.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time");
this.Metrics.TotalMemory = DBAccess.GetInt64(dataReader, "total_mem");
if (dataReader.NextResult())
{
while (dataReader.Read())
{
int @int = DBAccess.GetInt(dataReader, "hostid");
int int2 = DBAccess.GetInt(dataReader, "vmid");
string @string = DBAccess.GetString(dataReader, "name");
string string2 = DBAccess.GetString(dataReader, "uuid");
int int3 = DBAccess.GetInt(dataReader, "poolid");
DwmVirtualMachine dwmVirtualMachine = new DwmVirtualMachine(string2, @string, int3);
dwmVirtualMachine.Id = int2;
dwmVirtualMachine.Description = DBAccess.GetString(dataReader, "description");
dwmVirtualMachine.MinimumDynamicMemory = DBAccess.GetInt64(dataReader, "min_dynamic_memory");
dwmVirtualMachine.MaximumDynamicMemory = DBAccess.GetInt64(dataReader, "max_dynamic_memory");
dwmVirtualMachine.MinimumStaticMemory = DBAccess.GetInt64(dataReader, "min_static_memory");
dwmVirtualMachine.MaximumStaticMemory = DBAccess.GetInt64(dataReader, "max_static_memory");
dwmVirtualMachine.TargetMemory = DBAccess.GetInt64(dataReader, "target_memory");
dwmVirtualMachine.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead");
dwmVirtualMachine.MinimumCpus = DBAccess.GetInt(dataReader, "min_cpus");
dwmVirtualMachine.HvMemoryMultiplier = DBAccess.GetDouble(dataReader, "hv_memory_multiplier");
dwmVirtualMachine.RequiredMemory = DBAccess.GetInt64(dataReader, "required_memory");
dwmVirtualMachine.IsControlDomain = DBAccess.GetBool(dataReader, "is_control_domain");
dwmVirtualMachine.IsAgile = DBAccess.GetBool(dataReader, "is_agile");
dwmVirtualMachine.DriversUpToDate = DBAccess.GetBool(dataReader, "drivers_up_to_date");
dwmVirtualMachine.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status");
dwmVirtualMachine.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result");
dwmVirtualMachine.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time");
this.VirtualMachines.Add(dwmVirtualMachine);
}
}
}
}
}
}
public static DwmHost Load(string hostUuid, string poolUuid)
{
int poolId = DwmPoolBase.UuidToId(poolUuid);
int num = DwmHost.UuidToId(hostUuid, poolId);
if (num <= 0)
{
throw new DwmException("Invalid Host uuid", DwmErrorCode.InvalidParameter, null);
}
return DwmHost.Load(num);
}
public static DwmHost Load(int hostId)
{
if (hostId > 0)
{
DwmHost dwmHost = new DwmHost(hostId);
dwmHost.Load();
return dwmHost;
}
throw new DwmException("Invalid host ID", DwmErrorCode.InvalidParameter, null);
}
}
}
| yimng/wlb | wlb/Halsign.Dwm.Domain/Domain/DwmHost.cs | C# | gpl-2.0 | 29,482 |
#include "Converter.h"
#include <TFormula.h>
#include <iomanip>
#include <sstream>
std::string Converter::doubleToString(double x,int precision,bool scientifiStyle)
{
std::stringstream xs;
if(scientifiStyle)
xs<<std::scientific;
else
xs<<std::fixed;
xs<<std::setprecision(precision)<<x;
return xs.str();
};
std::string Converter::intToString(int x)
{
return doubleToString(x,0);
};
double Converter::stringToDouble(std::string formula)
{
TFormula myf("myf",formula.c_str());
return myf.Eval(0);
}
int Converter::stringToInt(std::string formula)
{
return (int)(stringToDouble(formula));
}
| DingXuefeng/LegendOfNeutrino | libsrc/Converter.cc | C++ | gpl-2.0 | 614 |
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("inline")
// #pragma GCC optimize("-fgcse")
// #pragma GCC optimize("-fgcse-lm")
// #pragma GCC optimize("-fipa-sra")
// #pragma GCC optimize("-ftree-pre")
// #pragma GCC optimize("-ftree-vrp")
// #pragma GCC optimize("-fpeephole2")
// #pragma GCC optimize("-ffast-math")
// #pragma GCC optimize("-fsched-spec")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC optimize("-falign-jumps")
// #pragma GCC optimize("-falign-loops")
// #pragma GCC optimize("-falign-labels")
// #pragma GCC optimize("-fdevirtualize")
// #pragma GCC optimize("-fcaller-saves")
// #pragma GCC optimize("-fcrossjumping")
// #pragma GCC optimize("-fthread-jumps")
// #pragma GCC optimize("-funroll-loops")
// #pragma GCC optimize("-fwhole-program")
// #pragma GCC optimize("-freorder-blocks")
// #pragma GCC optimize("-fschedule-insns")
// #pragma GCC optimize("inline-functions")
// #pragma GCC optimize("-ftree-tail-merge")
// #pragma GCC optimize("-fschedule-insns2")
// #pragma GCC optimize("-fstrict-aliasing")
// #pragma GCC optimize("-fstrict-overflow")
// #pragma GCC optimize("-falign-functions")
// #pragma GCC optimize("-fcse-skip-blocks")
// #pragma GCC optimize("-fcse-follow-jumps")
// #pragma GCC optimize("-fsched-interblock")
// #pragma GCC optimize("-fpartial-inlining")
// #pragma GCC optimize("no-stack-protector")
// #pragma GCC optimize("-freorder-functions")
// #pragma GCC optimize("-findirect-inlining")
// #pragma GCC optimize("-fhoist-adjacent-loads")
// #pragma GCC optimize("-frerun-cse-after-loop")
// #pragma GCC optimize("inline-small-functions")
// #pragma GCC optimize("-finline-small-functions")
// #pragma GCC optimize("-ftree-switch-conversion")
// #pragma GCC optimize("-foptimize-sibling-calls")
// #pragma GCC optimize("-fexpensive-optimizations")
// #pragma GCC optimize("-funsafe-loop-optimizations")
// #pragma GCC optimize("inline-functions-called-once")
// #pragma GCC optimize("-fdelete-null-pointer-checks")
#define rep(i, l, r) for (int i = (l); i <= (r); ++i)
#define per(i, l, r) for (int i = (l); i >= (r); --i)
using std::cerr;
using std::endl;
using std::make_pair;
using std::pair;
typedef pair<int, int> pii;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
// #define DEBUG 1 //调试开关
struct IO {
#define MAXSIZE (1 << 20)
#define isdigit(x) (x >= '0' && x <= '9')
char buf[MAXSIZE], *p1, *p2;
char pbuf[MAXSIZE], *pp;
#if DEBUG
#else
IO() : p1(buf), p2(buf), pp(pbuf) {}
~IO() { fwrite(pbuf, 1, pp - pbuf, stdout); }
#endif
inline char gc() {
#if DEBUG //调试,可显示字符
return getchar();
#endif
if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin);
return p1 == p2 ? -1 : *p1++;
}
inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; }
template <class T>
inline void read(T &x) {
register double tmp = 1;
register bool sign = 0;
x = 0;
register char ch = gc();
for (; !isdigit(ch); ch = gc())
if (ch == '-') sign = 1;
for (; isdigit(ch); ch = gc()) x = x * 10 + (ch - '0');
if (ch == '.')
for (ch = gc(); isdigit(ch); ch = gc()) tmp /= 10.0, x += tmp * (ch - '0');
if (sign) x = -x;
}
inline void read(char *s) {
register char ch = gc();
for (; blank(ch); ch = gc())
;
for (; !blank(ch); ch = gc()) *s++ = ch;
*s = 0;
}
inline void read(char &c) {
for (c = gc(); blank(c); c = gc())
;
}
inline void push(const char &c) {
#if DEBUG //调试,可显示字符
putchar(c);
#else
if (pp - pbuf == MAXSIZE) fwrite(pbuf, 1, MAXSIZE, stdout), pp = pbuf;
*pp++ = c;
#endif
}
template <class T>
inline void write(T x) {
if (x < 0) x = -x, push('-'); // 负数输出
static T sta[35];
T top = 0;
do {
sta[top++] = x % 10, x /= 10;
} while (x);
while (top) push(sta[--top] + '0');
}
inline void write(const char *s) {
while (*s != '\0') push(*(s++));
}
template <class T>
inline void write(T x, char lastChar) {
write(x), push(lastChar);
}
} io;
int a[510][510];
int main() {
#ifdef LOCAL
freopen("input", "r", stdin);
#endif
int n;
io.read(n);
rep(i, 1, n) {
rep(j, i + 1, n) {
io.read(a[i][j]);
a[j][i] = a[i][j];
}
}
int ans = 0;
rep(i, 1, n) {
std::sort(a[i] + 1, a[i] + 1 + n);
ans = std::max(ans, a[i][n - 1]);
}
io.write("1\n");
io.write(ans);
return 0;
} | Chaigidel/luogu-code | complete/LG-1199.cpp | C++ | gpl-2.0 | 4,983 |
<?
if (!defined("_GNUBOARD_")) exit; // °³º° ÆäÀÌÁö Á¢±Ù ºÒ°¡
if ($is_dhtml_editor) {
include_once("$g4[path]/lib/cheditor.lib.php");
echo "<script src='$g4[editor_path]/cheditor.js'></script>";
echo cheditor1('wr_content', $content);
}
?>
<script language="javascript">
// ±ÛÀÚ¼ö Á¦ÇÑ
var char_min = parseInt(<?=$write_min?>); // ÃÖ¼Ò
var char_max = parseInt(<?=$write_max?>); // ÃÖ´ë
</script>
<form name="fwrite" method="post" action="javascript:fwrite_check(document.fwrite);" enctype="multipart/form-data" style="margin:0px;">
<input type=hidden name=null>
<input type=hidden name=w value="<?=$w?>">
<input type=hidden name=bo_table value="<?=$bo_table?>">
<input type=hidden name=wr_id value="<?=$wr_id?>">
<input type=hidden name=sca value="<?=$sca?>">
<input type=hidden name=sfl value="<?=$sfl?>">
<input type=hidden name=stx value="<?=$stx?>">
<input type=hidden name=spt value="<?=$spt?>">
<input type=hidden name=sst value="<?=$sst?>">
<input type=hidden name=sod value="<?=$sod?>">
<input type=hidden name=page value="<?=$page?>">
<table width="<?=$width?>" align=center cellpadding=0 cellspacing=0><tr><td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<colgroup width=100>
<colgroup width=''>
<tr><td colspan=2 height=2 bgcolor=#b0adf5></td></tr>
<tr><td style='padding-left:20px' colspan=2 height=38 bgcolor=#f8f8f9><strong><?=$title_msg?></strong></td></tr>
<? if ($is_name) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ À̸§</td>
<td><input class=ed maxlength=20 size=15 name=wr_name itemname="À̸§" required value="<?=$name?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_password) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ÆÐ½º¿öµå</td>
<td><input class=ed type=password maxlength=20 size=15 name=wr_password itemname="ÆÐ½º¿öµå" <?=$password_required?>></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_email) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ À̸ÞÀÏ</td>
<td><input class=ed maxlength=100 size=50 name=wr_email email itemname="À̸ÞÀÏ" value="<?=$email?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_homepage) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ȨÆäÀÌÁö</td>
<td><input class=ed size=50 name=wr_homepage itemname="ȨÆäÀÌÁö" value="<?=$homepage?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_notice || $is_html || $is_secret || $is_mail) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ¿É¼Ç</td>
<td><? if ($is_notice) { ?><input type=checkbox name=notice value="1" <?=$notice_checked?>>°øÁö <? } ?>
<? if ($is_html) { ?>
<? if ($is_dhtml_editor) { ?>
<input type=hidden value="html1" name="html">
<? } else { ?>
<input onclick="html_auto_br(this);" type=checkbox value="<?=$html_value?>" name="html" <?=$html_checked?>><span class=w_title>html</span>
<? } ?>
<? } ?>
<? if ($is_secret) { ?>
<? if ($is_admin || $is_secret==1) { ?>
<input type=checkbox value="secret" name="secret" <?=$secret_checked?>><span class=w_title>ºñ¹Ð±Û</span>
<? } else { ?>
<input type=hidden value="secret" name="secret">
<? } ?>
<? } ?>
<? if ($is_mail) { ?><input type=checkbox value="mail" name="mail" <?=$recv_email_checked?>>´äº¯¸ÞÀϹޱâ <? } ?></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_category) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ºÐ·ù</td>
<td><select name=ca_name required itemname="ºÐ·ù"><option value="">¼±ÅÃÇϼ¼¿ä<?=$category_option?></select></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ Á¦¸ñ</td>
<td><input class=ed style="width:100%;" name=wr_subject itemname="Á¦¸ñ" required value="<?=$subject?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<tr>
<td style='padding-left:20px;'>¡¤ ³»¿ë</td>
<td style='padding:5 0 5 0;'>
<? if ($is_dhtml_editor) { ?>
<?=cheditor2('fwrite', 'wr_content', '100%', '350');?>
<? } else { ?>
<table width=100% cellpadding=0 cellspacing=0>
<tr>
<td width=50% align=left valign=bottom>
<span style="cursor: pointer;" onclick="textarea_decrease('wr_content', 10);"><img src="<?=$board_skin_path?>/img/up.gif"></span>
<span style="cursor: pointer;" onclick="textarea_original('wr_content', 10);"><img src="<?=$board_skin_path?>/img/start.gif"></span>
<span style="cursor: pointer;" onclick="textarea_increase('wr_content', 10);"><img src="<?=$board_skin_path?>/img/down.gif"></span></td>
<td width=50% align=right><? if ($write_min || $write_max) { ?><span id=char_count></span>±ÛÀÚ<?}?></td>
</tr>
</table>
<textarea id=wr_content name=wr_content class=tx style='width:100%; word-break:break-all;' rows=10 itemname="³»¿ë" required
<? if ($write_min || $write_max) { ?>onkeyup="check_byte('wr_content', 'char_count');"<?}?>><?=$content?></textarea>
<? if ($write_min || $write_max) { ?><script language="javascript"> check_byte('wr_content', 'char_count'); </script><?}?>
<? } ?>
</td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? if ($is_link) { ?>
<? for ($i=1; $i<=$g4[link_count]; $i++) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ¸µÅ© #<?=$i?></td>
<td><input type='text' class=ed size=50 name='wr_link<?=$i?>' itemname='¸µÅ© #<?=$i?>' value='<?=$write["wr_link{$i}"]?>'></td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? } ?>
<? if ($is_file) { ?>
<tr>
<td style='padding-left:20px; height:30px;'><table cellpadding=0 cellspacing=0><tr><td style=" padding-top: 10px;">¡¤ ÆÄÀÏ <span onclick="add_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>+</span> <span onclick="del_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>-</span></td></tr></table></td>
<td style='padding:5 0 5 0;'><table id="variableFiles" cellpadding=0 cellspacing=0></table><?// print_r2($file); ?>
<script language="JavaScript">
var flen = 0;
function add_file(delete_code)
{
var upload_count = <?=(int)$board[bo_upload_count]?>;
if (upload_count && flen >= upload_count)
{
alert("ÀÌ °Ô½ÃÆÇÀº "+upload_count+"°³ ±îÁö¸¸ ÆÄÀÏ ¾÷·Îµå°¡ °¡´ÉÇÕ´Ï´Ù.");
return;
}
var objTbl;
var objRow;
var objCell;
if (document.getElementById)
objTbl = document.getElementById("variableFiles");
else
objTbl = document.all["variableFiles"];
objRow = objTbl.insertRow(objTbl.rows.length);
objCell = objRow.insertCell(0);
objCell.innerHTML = "<input type='file' class=ed size=32 name='bf_file[]' title='ÆÄÀÏ ¿ë·® <?=$upload_max_filesize?> ÀÌÇϸ¸ ¾÷·Îµå °¡´É'>";
if (delete_code)
objCell.innerHTML += delete_code;
else
{
<? if ($is_file_content) { ?>
objCell.innerHTML += "<br><input type='text' class=ed size=50 name='bf_content[]' title='¾÷·Îµå À̹ÌÁö ÆÄÀÏ¿¡ ÇØ´ç µÇ´Â ³»¿ëÀ» ÀÔ·ÂÇϼ¼¿ä.'>";
<? } ?>
;
}
flen++;
}
<?=$file_script; //¼öÁ¤½Ã¿¡ ÇÊ¿äÇÑ ½ºÅ©¸³Æ®?>
function del_file()
{
// file_length ÀÌÇϷδ Çʵ尡 »èÁ¦µÇÁö ¾Ê¾Æ¾ß ÇÕ´Ï´Ù.
var file_length = <?=(int)$file_length?>;
var objTbl = document.getElementById("variableFiles");
if (objTbl.rows.length - 1 > file_length)
{
objTbl.deleteRow(objTbl.rows.length - 1);
flen--;
}
}
</script></td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_trackback) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ Æ®·¢¹éÁÖ¼Ò</td>
<td><input class=ed size=50 name=wr_trackback itemname="Æ®·¢¹é" value="<?=$trackback?>">
<? if ($w=="u") { ?><input type=checkbox name="re_trackback" value="1">ÇÎ º¸³¿<? } ?></td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_norobot) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ <?=$norobot_str?></td>
<td><input class=ed type=input size=10 name=wr_key itemname="ÀÚµ¿µî·Ï¹æÁö" required> * ¿ÞÂÊÀÇ ±ÛÀÚÁß <font color="red">»¡°£±ÛÀÚ¸¸</font> ¼ø¼´ë·Î ÀÔ·ÂÇϼ¼¿ä.</td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<tr><td colspan=2 height=1 bgcolor=#000000></td></tr>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" height="30" background="<?=$board_skin_path?>/img/write_down_bg.gif"></td>
</tr>
<tr>
<td width="100%" align="center" valign="top">
<input type=image id="btn_submit" src="<?=$board_skin_path?>/img/btn_write.gif" border=0 accesskey='s'>
<a href="./board.php?bo_table=<?=$bo_table?>"><img id="btn_list" src="<?=$board_skin_path?>/img/btn_list.gif" border=0></a></td>
</tr>
</table>
</td></tr></table>
</form>
<script language="javascript">
<?
// °ü¸®ÀÚ¶ó¸é ºÐ·ù ¼±Åÿ¡ '°øÁö' ¿É¼ÇÀ» Ãß°¡ÇÔ
if ($is_admin)
{
echo "
if (typeof(document.fwrite.ca_name) != 'undefined')
{
document.fwrite.ca_name.options.length += 1;
document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].value = '°øÁö';
document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].text = '°øÁö';
}";
}
?>
with (document.fwrite) {
if (typeof(wr_name) != "undefined")
wr_name.focus();
else if (typeof(wr_subject) != "undefined")
wr_subject.focus();
else if (typeof(wr_content) != "undefined")
wr_content.focus();
if (typeof(ca_name) != "undefined")
if (w.value == "u")
ca_name.value = "<?=$write[ca_name]?>";
}
function html_auto_br(obj) {
if (obj.checked) {
result = confirm("ÀÚµ¿ ÁٹٲÞÀ» ÇϽðڽÀ´Ï±î?\n\nÀÚµ¿ ÁٹٲÞÀº °Ô½Ã¹° ³»¿ëÁß ÁÙ¹Ù²ï °÷À»<br>ű׷Πº¯È¯ÇÏ´Â ±â´ÉÀÔ´Ï´Ù.");
if (result)
obj.value = "html2";
else
obj.value = "html1";
}
else
obj.value = "";
}
function fwrite_check(f) {
var s = "";
if (s = word_filter_check(f.wr_subject.value)) {
alert("Á¦¸ñ¿¡ ±ÝÁö´Ü¾î('"+s+"')°¡ Æ÷ÇԵǾîÀÖ½À´Ï´Ù");
return;
}
if (s = word_filter_check(f.wr_content.value)) {
alert("³»¿ë¿¡ ±ÝÁö´Ü¾î('"+s+"')°¡ Æ÷ÇԵǾîÀÖ½À´Ï´Ù");
return;
}
if (char_min > 0 || char_max > 0) {
var cnt = parseInt(document.getElementById('char_count').innerHTML);
if (char_min > 0 && char_min > cnt) {
alert("³»¿ëÀº "+char_min+"±ÛÀÚ ÀÌ»ó ¾²¼Å¾ß ÇÕ´Ï´Ù.");
return;
}
else if (char_max > 0 && char_max < cnt) {
alert("³»¿ëÀº "+char_max+"±ÛÀÚ ÀÌÇÏ·Î ¾²¼Å¾ß ÇÕ´Ï´Ù.");
return;
}
}
if (typeof(f.wr_key) != "undefined") {
if (hex_md5(f.wr_key.value) != md5_norobot_key) {
alert("ÀÚµ¿µî·Ï¹æÁö¿ë »¡°£±ÛÀÚ°¡ ¼ø¼´ë·Î ÀԷµÇÁö ¾Ê¾Ò½À´Ï´Ù.");
f.wr_key.focus();
return;
}
}
<?
if ($is_dhtml_editor) {
echo cheditor3('wr_content');
echo "if (!document.getElementById('wr_content').value) { alert('³»¿ëÀ» ÀÔ·ÂÇϽʽÿÀ.'); return; } ";
}
?>
document.getElementById('btn_submit').disabled = true;
document.getElementById('btn_list').disabled = true;
f.action = "./write_update.php";
f.submit();
}
</script> | mrquestion/gnuboard4 | skin/board/basic_old/write.skin.php | PHP | gpl-2.0 | 12,050 |
/* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.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
*/
/* ScriptData
SDName: boss_lord_marrowgar
SD%Complete: 0%
SDComment:
SDCategory: Icecrown Citadel
EndScriptData */
#include "precompiled.h"
enum
{
SAY_INTRO = -1631001,
SAY_AGGRO = -1631002,
SAY_BONE_STORM = -1631003,
SAY_BONE_SPIKE_1 = -1631004,
SAY_BONE_SPIKE_2 = -1631005,
SAY_BONE_SPIKE_3 = -1631006,
SAY_SLAY_1 = -1631007,
SAY_SLAY_2 = -1631008,
SAY_DEATH = -1631009,
SAY_BERSERK = -1631010,
};
void AddSC_boss_lord_marrowgar()
{
}
| udw/mangos_hw2system_335 | src/bindings/scriptdev2/scripts/northrend/icecrown_citadel/icecrown_citadel/boss_lord_marrowgar.cpp | C++ | gpl-2.0 | 1,417 |
var wocs_loading_first_time = true;//simply flag var
jQuery(function () {
if (woocs_drop_down_view == 'chosen') {
try {
if (jQuery("select.woocommerce-currency-switcher").length) {
jQuery("select.woocommerce-currency-switcher").chosen({
disable_search_threshold: 10
});
jQuery.each(jQuery('.woocommerce-currency-switcher-form .chosen-container'), function (index, obj) {
jQuery(obj).css({'width': jQuery(this).prev('select').data('width')});
});
}
} catch (e) {
console.log(e);
}
}
if (woocs_drop_down_view == 'ddslick') {
try {
jQuery.each(jQuery('select.woocommerce-currency-switcher'), function (index, obj) {
var width = jQuery(obj).data('width');
var flag_position = jQuery(obj).data('flag-position');
jQuery(obj).ddslick({
//data: ddData,
width: width,
imagePosition: flag_position,
selectText: "Select currency",
//background:'#ff0000',
onSelected: function (data) {
if (!wocs_loading_first_time) {
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').find('input[name="woocommerce-currency-switcher"]').eq(0).val(data.selectedData.value);
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').submit();
}
}
});
});
} catch (e) {
console.log(e);
}
}
//for flags view instead of drop-down
jQuery('.woocs_flag_view_item').click(function () {
if (jQuery(this).hasClass('woocs_flag_view_item_current')) {
return false;
}
//***
if (woocs_is_get_empty) {
window.location = window.location.href + '?currency=' + jQuery(this).data('currency');
} else {
var l = window.location.href;
l = l.replace(/(\?currency=[a-zA-Z]+)/g, '?');
l = l.replace(/(¤cy=[a-zA-Z]+)/g, '');
window.location = l + '¤cy=' + jQuery(this).data('currency');
}
return false;
});
wocs_loading_first_time = false;
});
| asshurimrepo/mont8 | wp-content/plugins/woocommerce-currency-switcher/js/front.js | JavaScript | gpl-2.0 | 2,447 |
# -*- coding: utf-8 -*-
#
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from django.db import transaction
from django.utils.translation import ugettext as _
from django.conf import settings
from orgs.mixins.api import RootOrgViewMixin
from common.permissions import IsValidUser
from perms.utils import AssetPermissionUtil
from ..models import CommandExecution
from ..serializers import CommandExecutionSerializer
from ..tasks import run_command_execution
class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet):
serializer_class = CommandExecutionSerializer
permission_classes = (IsValidUser,)
def get_queryset(self):
return CommandExecution.objects.filter(
user_id=str(self.request.user.id)
)
def check_hosts(self, serializer):
data = serializer.validated_data
assets = data["hosts"]
system_user = data["run_as"]
util = AssetPermissionUtil(self.request.user)
util.filter_permissions(system_users=system_user.id)
permed_assets = util.get_assets().filter(id__in=[a.id for a in assets])
invalid_assets = set(assets) - set(permed_assets)
if invalid_assets:
msg = _("Not has host {} permission").format(
[str(a.id) for a in invalid_assets]
)
raise ValidationError({"hosts": msg})
def check_permissions(self, request):
if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user:
return self.permission_denied(request, "Command execution disabled")
return super().check_permissions(request)
def perform_create(self, serializer):
self.check_hosts(serializer)
instance = serializer.save()
instance.user = self.request.user
instance.save()
cols = self.request.query_params.get("cols", '80')
rows = self.request.query_params.get("rows", '24')
transaction.on_commit(lambda: run_command_execution.apply_async(
args=(instance.id,), kwargs={"cols": cols, "rows": rows},
task_id=str(instance.id)
))
| zsjohny/jumpserver | apps/ops/api/command.py | Python | gpl-2.0 | 2,150 |
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match)
r, _ := regexp.Compile("p([a-z]+)ch")
fmt.Println(r.MatchString("peach"))
fmt.Println(r.FindString("peach punch"))
fmt.Println(r.FindStringIndex("peach punch"))
fmt.Println(r.FindStringSubmatch("peach punch"))
fmt.Println(r.FindStringSubmatchIndex("peach punch"))
fmt.Println(r.FindAllString("peach punch pinch", -1))
fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1))
fmt.Println(r.FindAllString("peach punch pinch", 2))
fmt.Println(r.Match([]byte("peach")))
r = regexp.MustCompile("p([a+z])ch")
fmt.Println(r)
fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
}
| coyotey/goLearnExample | 45_regularexpressions.go | GO | gpl-2.0 | 845 |
/*
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc.
Copyright (C) 2010, 2011 Adept Technology, Inc.
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
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.36
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.mobilerobots.Aria;
public class ArDPPTU extends ArPTZ {
/* (begin code from javabody_derived typemap) */
private long swigCPtr;
/* for internal use by swig only */
public ArDPPTU(long cPtr, boolean cMemoryOwn) {
super(AriaJavaJNI.SWIGArDPPTUUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/* for internal use by swig only */
public static long getCPtr(ArDPPTU obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
/* (end code from javabody_derived typemap) */
protected void finalize() {
delete();
}
public synchronized void delete() {
if(swigCPtr != 0 && swigCMemOwn) {
swigCMemOwn = false;
AriaJavaJNI.delete_ArDPPTU(swigCPtr);
}
swigCPtr = 0;
super.delete();
}
public ArDPPTU(ArRobot robot, ArDPPTU.DeviceType deviceType) {
this(AriaJavaJNI.new_ArDPPTU__SWIG_0(ArRobot.getCPtr(robot), robot, deviceType.swigValue()), true);
}
public ArDPPTU(ArRobot robot) {
this(AriaJavaJNI.new_ArDPPTU__SWIG_1(ArRobot.getCPtr(robot), robot), true);
}
public boolean init() {
return AriaJavaJNI.ArDPPTU_init(swigCPtr, this);
}
public boolean canZoom() {
return AriaJavaJNI.ArDPPTU_canZoom(swigCPtr, this);
}
public boolean blank() {
return AriaJavaJNI.ArDPPTU_blank(swigCPtr, this);
}
public boolean resetCalib() {
return AriaJavaJNI.ArDPPTU_resetCalib(swigCPtr, this);
}
public boolean disableReset() {
return AriaJavaJNI.ArDPPTU_disableReset(swigCPtr, this);
}
public boolean resetTilt() {
return AriaJavaJNI.ArDPPTU_resetTilt(swigCPtr, this);
}
public boolean resetPan() {
return AriaJavaJNI.ArDPPTU_resetPan(swigCPtr, this);
}
public boolean resetAll() {
return AriaJavaJNI.ArDPPTU_resetAll(swigCPtr, this);
}
public boolean saveSet() {
return AriaJavaJNI.ArDPPTU_saveSet(swigCPtr, this);
}
public boolean restoreSet() {
return AriaJavaJNI.ArDPPTU_restoreSet(swigCPtr, this);
}
public boolean factorySet() {
return AriaJavaJNI.ArDPPTU_factorySet(swigCPtr, this);
}
public boolean panTilt(double pdeg, double tdeg) {
return AriaJavaJNI.ArDPPTU_panTilt(swigCPtr, this, pdeg, tdeg);
}
public boolean pan(double deg) {
return AriaJavaJNI.ArDPPTU_pan(swigCPtr, this, deg);
}
public boolean panRel(double deg) {
return AriaJavaJNI.ArDPPTU_panRel(swigCPtr, this, deg);
}
public boolean tilt(double deg) {
return AriaJavaJNI.ArDPPTU_tilt(swigCPtr, this, deg);
}
public boolean tiltRel(double deg) {
return AriaJavaJNI.ArDPPTU_tiltRel(swigCPtr, this, deg);
}
public boolean panTiltRel(double pdeg, double tdeg) {
return AriaJavaJNI.ArDPPTU_panTiltRel(swigCPtr, this, pdeg, tdeg);
}
public boolean limitEnforce(boolean val) {
return AriaJavaJNI.ArDPPTU_limitEnforce(swigCPtr, this, val);
}
public boolean immedExec() {
return AriaJavaJNI.ArDPPTU_immedExec(swigCPtr, this);
}
public boolean slaveExec() {
return AriaJavaJNI.ArDPPTU_slaveExec(swigCPtr, this);
}
public boolean awaitExec() {
return AriaJavaJNI.ArDPPTU_awaitExec(swigCPtr, this);
}
public boolean haltAll() {
return AriaJavaJNI.ArDPPTU_haltAll(swigCPtr, this);
}
public boolean haltPan() {
return AriaJavaJNI.ArDPPTU_haltPan(swigCPtr, this);
}
public boolean haltTilt() {
return AriaJavaJNI.ArDPPTU_haltTilt(swigCPtr, this);
}
public double getMaxPosPan() {
return AriaJavaJNI.ArDPPTU_getMaxPosPan(swigCPtr, this);
}
public double getMaxNegPan() {
return AriaJavaJNI.ArDPPTU_getMaxNegPan(swigCPtr, this);
}
public double getMaxPosTilt() {
return AriaJavaJNI.ArDPPTU_getMaxPosTilt(swigCPtr, this);
}
public double getMaxNegTilt() {
return AriaJavaJNI.ArDPPTU_getMaxNegTilt(swigCPtr, this);
}
public double getMaxPanSlew() {
return AriaJavaJNI.ArDPPTU_getMaxPanSlew(swigCPtr, this);
}
public double getMinPanSlew() {
return AriaJavaJNI.ArDPPTU_getMinPanSlew(swigCPtr, this);
}
public double getMaxTiltSlew() {
return AriaJavaJNI.ArDPPTU_getMaxTiltSlew(swigCPtr, this);
}
public double getMinTiltSlew() {
return AriaJavaJNI.ArDPPTU_getMinTiltSlew(swigCPtr, this);
}
public double getMaxPanAccel() {
return AriaJavaJNI.ArDPPTU_getMaxPanAccel(swigCPtr, this);
}
public double getMinPanAccel() {
return AriaJavaJNI.ArDPPTU_getMinPanAccel(swigCPtr, this);
}
public double getMaxTiltAccel() {
return AriaJavaJNI.ArDPPTU_getMaxTiltAccel(swigCPtr, this);
}
public double getMinTiltAccel() {
return AriaJavaJNI.ArDPPTU_getMinTiltAccel(swigCPtr, this);
}
public boolean initMon(double deg1, double deg2, double deg3, double deg4) {
return AriaJavaJNI.ArDPPTU_initMon(swigCPtr, this, deg1, deg2, deg3, deg4);
}
public boolean enMon() {
return AriaJavaJNI.ArDPPTU_enMon(swigCPtr, this);
}
public boolean disMon() {
return AriaJavaJNI.ArDPPTU_disMon(swigCPtr, this);
}
public boolean offStatPower() {
return AriaJavaJNI.ArDPPTU_offStatPower(swigCPtr, this);
}
public boolean regStatPower() {
return AriaJavaJNI.ArDPPTU_regStatPower(swigCPtr, this);
}
public boolean lowStatPower() {
return AriaJavaJNI.ArDPPTU_lowStatPower(swigCPtr, this);
}
public boolean highMotPower() {
return AriaJavaJNI.ArDPPTU_highMotPower(swigCPtr, this);
}
public boolean regMotPower() {
return AriaJavaJNI.ArDPPTU_regMotPower(swigCPtr, this);
}
public boolean lowMotPower() {
return AriaJavaJNI.ArDPPTU_lowMotPower(swigCPtr, this);
}
public boolean panAccel(double deg) {
return AriaJavaJNI.ArDPPTU_panAccel(swigCPtr, this, deg);
}
public boolean tiltAccel(double deg) {
return AriaJavaJNI.ArDPPTU_tiltAccel(swigCPtr, this, deg);
}
public boolean basePanSlew(double deg) {
return AriaJavaJNI.ArDPPTU_basePanSlew(swigCPtr, this, deg);
}
public boolean baseTiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_baseTiltSlew(swigCPtr, this, deg);
}
public boolean upperPanSlew(double deg) {
return AriaJavaJNI.ArDPPTU_upperPanSlew(swigCPtr, this, deg);
}
public boolean lowerPanSlew(double deg) {
return AriaJavaJNI.ArDPPTU_lowerPanSlew(swigCPtr, this, deg);
}
public boolean upperTiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_upperTiltSlew(swigCPtr, this, deg);
}
public boolean lowerTiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_lowerTiltSlew(swigCPtr, this, deg);
}
public boolean indepMove() {
return AriaJavaJNI.ArDPPTU_indepMove(swigCPtr, this);
}
public boolean velMove() {
return AriaJavaJNI.ArDPPTU_velMove(swigCPtr, this);
}
public boolean panSlew(double deg) {
return AriaJavaJNI.ArDPPTU_panSlew(swigCPtr, this, deg);
}
public boolean tiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_tiltSlew(swigCPtr, this, deg);
}
public boolean panSlewRel(double deg) {
return AriaJavaJNI.ArDPPTU_panSlewRel(swigCPtr, this, deg);
}
public boolean tiltSlewRel(double deg) {
return AriaJavaJNI.ArDPPTU_tiltSlewRel(swigCPtr, this, deg);
}
public double getPan() {
return AriaJavaJNI.ArDPPTU_getPan(swigCPtr, this);
}
public double getTilt() {
return AriaJavaJNI.ArDPPTU_getTilt(swigCPtr, this);
}
public double getPanSlew() {
return AriaJavaJNI.ArDPPTU_getPanSlew(swigCPtr, this);
}
public double getTiltSlew() {
return AriaJavaJNI.ArDPPTU_getTiltSlew(swigCPtr, this);
}
public double getBasePanSlew() {
return AriaJavaJNI.ArDPPTU_getBasePanSlew(swigCPtr, this);
}
public double getBaseTiltSlew() {
return AriaJavaJNI.ArDPPTU_getBaseTiltSlew(swigCPtr, this);
}
public double getPanAccel() {
return AriaJavaJNI.ArDPPTU_getPanAccel(swigCPtr, this);
}
public double getTiltAccel() {
return AriaJavaJNI.ArDPPTU_getTiltAccel(swigCPtr, this);
}
public final static class DeviceType {
public final static DeviceType PANTILT_DEFAULT = new DeviceType("PANTILT_DEFAULT");
public final static DeviceType PANTILT_PTUD47 = new DeviceType("PANTILT_PTUD47");
public final int swigValue() {
return swigValue;
}
public String toString() {
return swigName;
}
public static DeviceType swigToEnum(int swigValue) {
if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
return swigValues[swigValue];
for (int i = 0; i < swigValues.length; i++)
if (swigValues[i].swigValue == swigValue)
return swigValues[i];
throw new IllegalArgumentException("No enum " + DeviceType.class + " with value " + swigValue);
}
private DeviceType(String swigName) {
this.swigName = swigName;
this.swigValue = swigNext++;
}
private DeviceType(String swigName, int swigValue) {
this.swigName = swigName;
this.swigValue = swigValue;
swigNext = swigValue+1;
}
private DeviceType(String swigName, DeviceType swigEnum) {
this.swigName = swigName;
this.swigValue = swigEnum.swigValue;
swigNext = this.swigValue+1;
}
private static DeviceType[] swigValues = { PANTILT_DEFAULT, PANTILT_PTUD47 };
private static int swigNext = 0;
private final int swigValue;
private final String swigName;
}
}
| admo/aria | aria/java/ArDPPTU.java | Java | gpl-2.0 | 10,851 |
<?php
/**********************************************************************************
*
* #####
* # # ##### ## ##### # # #### ###### # # #### # # # ######
* # # # # # # # # # ## # # # # ## # #
* ##### # # # # # # #### ##### # # # # # # # # #####
* # # ###### # # # # # # # # # ### # # # # #
* # # # # # # # # # # # # ## # # # # ## #
* ##### # # # # #### #### ###### # # #### # # # ######
*
* the missing event broker
* Perfdata Backend Extension for Rrdtool
*
* --------------------------------------------------------------------------------
*
* Copyright (c) 2014 - present Daniel Ziegler <daniel@statusengine.org>
*
* 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 in version 2
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* --------------------------------------------------------------------------------
*
* This extension for statusengine uses the parsed performance data and
* saves performance data to graphite
* So you dont need to install any additional software to get this job done
*
**********************************************************************************/
class GraphiteBackendTask extends AppShell{
public $Config = [];
private $host;
private $port;
private $prefix;
private $socket;
private $lastErrNo;
private $hostnameCache = [];
private $servicenameCache = [];
public function init($Config){
$this->Config = $Config;
$this->host = $this->Config['host'];
$this->port = $this->Config['port'];
$this->prefix = $this->Config['prefix'];
}
/**
* @param array $parsedPerfdata
* @param string $hostname
* @param string $servicedesc
* @param int $timestamp
*/
public function save($parsedPerfdata, $hostname, $servicedesc, $timestamp){
if($this->connect()){
foreach($parsedPerfdata as $ds => $_data){
$data = $this->buildString($ds, $_data, $hostname, $servicedesc, $timestamp);
$this->write($data);
}
}
$this->disconnect();
}
private function write($message){
$message .= PHP_EOL;
$this->lastErrNo = null;
if(!@socket_send($this->socket, $message, strlen($message), 0)){
CakeLog::error(sprintf(
'Graphite save error: %s %s',
$this->getLastErrNo(),
$this->getLastError()
));
return false;
}
return true;
}
private function connect(){
$this->socket = socket_create(AF_INET, SOCK_STREAM, IPPROTO_IP);
if(!@socket_connect($this->socket, $this->host, $this->port)){
CakeLog::error(sprintf(
'Graphite connection error: %s %s',
$this->getLastErrNo(),
$this->getLastError()
));
return false;
}
return true;
}
private function disconnect(){
if(is_resource($this->socket)){
socket_close($this->socket);
}
$this->socket = null;
}
private function getLastErrNo(){
if(is_resource($this->socket)){
$this->lastErrNo = socket_last_error($this->socket);
return $this->lastErrNo;
}
return false;
}
private function getLastError(){
return socket_strerror($this->lastErrNo);
}
private function buildString($datasource, $data, $hostname, $servicedesc, $timestamp){
$datasource = $this->replaceCharacters($datasource);
$hostname = $this->replaceCharacters($hostname);
$servicedesc = $this->replaceCharacters($servicedesc);
return sprintf(
'%s.%s.%s.%s %s %s',
$this->prefix,
$hostname,
$servicedesc,
$datasource,
$data['current'],
$timestamp
);
}
public function replaceCharacters($str){
return preg_replace($this->Config['replace_characters'], '_', $str);
}
public function requireHostNameCaching(){
if($this->Config['use_host_display_name'] === true){
return true;
}
return false;
}
public function requireServiceNameCaching(){
if($this->Config['use_service_display_name'] === true){
return true;
}
return false;
}
public function requireNameCaching(){
if($this->requireHostNameCaching() === true){
return true;
}
if($this->requireServiceNameCaching() === true){
return true;
}
return false;
}
public function addHostdisplayNameToCache($hostname, $hostdisplayname){
$this->hostnameCache[md5($hostname)] = $hostdisplayname;
}
public function getHostdisplayNameFromCache($hostname){
if(isset($this->hostnameCache[md5($hostname)])){
return $this->hostnameCache[md5($hostname)];
}
return null;
}
public function addServicedisplayNameToCache($hostname, $servicedesc, $servicedisplayname){
if(!isset($this->servicenameCache[md5($hostname)])){
$this->servicenameCache[md5($hostname)] = [];
}
$this->servicenameCache[md5($hostname)][md5($servicedesc)] = $servicedisplayname;
}
public function getServicedisplayNameFromCache($hostname, $servicedesc){
if(isset($this->servicenameCache[md5($hostname)][md5($servicedesc)])){
return $this->servicenameCache[md5($hostname)][md5($servicedesc)];
}
return null;
}
public function clearCache(){
$this->hostnameCache = [];
$this->servicenameCache = [];
}
}
| nook24/statusengine | cakephp/app/Console/Command/Task/GraphiteBackendTask.php | PHP | gpl-2.0 | 5,656 |
<?php
// Global variables
global $map_count, $ish_options;
$map_count++;
// Default SC attributes
$defaults = array(
'color' => '',
'zoom' => '15',
'invert_colors' => '',
'height' => '',
);
// Extract all attributes
$sc_atts = $this->extract_sc_attributes( $defaults, $atts );
// Add ID if empty as it is necessary for Google Maps to work
if ( empty( $sc_atts['id'] ) ){
$sc_atts['id'] = 'ish-gmap-' . $map_count;
}
// Make sure to include the scripts for Google Maps and the Generation of the marker infoboxes on click
wp_enqueue_script( 'ish-gmaps' );
// Convert color class to color value
if ( isset( $ish_options[ $sc_atts['color'] ] ) ){
$sc_atts['color'] = $ish_options[ $sc_atts['color'] ];
}
// SHORTCODE BEGIN
$return = '';
$return .= '<div class="' . apply_filters( 'ish_sc_classes', 'ish-sc_map_container', $tag ) . '"><div class="';
// CLASSES
$class = 'ish-sc_map';
$class .= ( '' != $sc_atts['css_class'] ) ? ' ' . esc_attr( $sc_atts['css_class'] ) : '' ;
$class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_color'] ) ? ' ish-tooltip-' . esc_attr( $sc_atts['tooltip_color'] ) : '';
$class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_text_color'] ) ? ' ish-tooltip-text-' . esc_attr( $sc_atts['tooltip_text_color'] ) : '';
//$return .= apply_filters( 'ish_sc_classes', $class, $tag );
$return .= $class;
$return .= '"' ;
// ID
$return .= ( '' != $sc_atts['id'] ) ? ' id="' . esc_attr( $sc_atts['id'] ) . '"' : '';
// STYLE
if ( '' != $sc_atts['style'] || '' != $sc_atts['height'] ){
$return .= ' style="';
$return .= ( '' != $sc_atts['height'] ) ? ' height: ' . esc_attr( $sc_atts['height'] ) . 'px;' : '';
$return .= ( '' != $sc_atts['style'] ) ? ' ' . esc_attr( $sc_atts['style'] ) : '';
$return .= '"';
}
// TOOLTIP
$return .= ( '' != $sc_atts['tooltip'] ) ? ' data-type="tooltip" title="' . esc_attr( $sc_atts['tooltip'] ) . '"' : '' ;
$return .= ( '' != $sc_atts['zoom'] ) ? ' data-zoom="' . esc_attr( $sc_atts['zoom'] ) . '"' : '' ;
$return .= ( 'yes' == $sc_atts['invert_colors'] ) ? ' data-invert="' . esc_attr( $sc_atts['invert_colors'] ) . '"' : '' ;
$return .= ( '' != $sc_atts['color'] ) ? ' data-color="' . esc_attr( $sc_atts['color'] ) . '"' : '' ;
$return .= '>';
$content = wpb_js_remove_wpautop($content, true);
// CONTENT
$return .= do_shortcode( $content );
// SHORTCODE END
$return .= '</div></div>';
echo $return; | tywzdbsd/wp_yanze | wp-content/plugins/ishyoboy-boldial-assets/ishyoboy-shortcodes/assets/backend/vc_extend/shortcodes_templates/ish_map.php | PHP | gpl-2.0 | 2,476 |
<?php
class acf_Wysiwyg extends acf_Field
{
/*--------------------------------------------------------------------------------------
*
* Constructor
*
* @author Elliot Condon
* @since 1.0.0
* @updated 2.2.0
*
*-------------------------------------------------------------------------------------*/
function __construct($parent)
{
parent::__construct($parent);
$this->name = 'wysiwyg';
$this->title = __("Wysiwyg Editor",'acf');
add_action( 'acf_head-input', array( $this, 'acf_head') );
add_filter( 'acf/fields/wysiwyg/toolbars', array( $this, 'toolbars'), 1, 1 );
}
/*
* get_toolbars
*
* @description:
* @since: 3.5.7
* @created: 10/01/13
*/
function toolbars( $toolbars )
{
$editor_id = 'acf_settings';
// Full
$toolbars['Full'] = array();
$toolbars['Full'][1] = apply_filters('mce_buttons', array('bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'justifyleft', 'justifycenter', 'justifyright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' ), $editor_id);
$toolbars['Full'][2] = apply_filters('mce_buttons_2', array( 'formatselect', 'underline', 'justifyfull', 'forecolor', 'pastetext', 'pasteword', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help', 'code' ), $editor_id);
$toolbars['Full'][3] = apply_filters('mce_buttons_3', array(), $editor_id);
$toolbars['Full'][4] = apply_filters('mce_buttons_4', array(), $editor_id);
// Basic
$toolbars['Basic'] = array();
$toolbars['Basic'][1] = apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id );
// Custom - can be added with acf/fields/wysiwyg/toolbars filter
return $toolbars;
}
/*--------------------------------------------------------------------------------------
*
* admin_head
* - Add the settings for a WYSIWYG editor (as used in wp_editor / wp_tiny_mce)
*
* @author Elliot Condon
* @since 3.2.3
*
*-------------------------------------------------------------------------------------*/
function acf_head()
{
add_action( 'admin_footer', array( $this, 'admin_footer') );
}
function admin_footer()
{
?>
<div style="display:none;">
<?php wp_editor( '', 'acf_settings' ); ?>
</div>
<?php
}
/*--------------------------------------------------------------------------------------
*
* create_options
*
* @author Elliot Condon
* @since 2.0.6
* @updated 2.2.0
*
*-------------------------------------------------------------------------------------*/
function create_options($key, $field)
{
// vars
$defaults = array(
'toolbar' => 'full',
'media_upload' => 'yes',
'the_content' => 'yes',
'default_value' => '',
);
$field = array_merge($defaults, $field);
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Toolbar",'acf'); ?></label>
</td>
<td>
<?php
$toolbars = apply_filters( 'acf/fields/wysiwyg/toolbars', array() );
$choices = array();
if( is_array($toolbars) )
{
foreach( $toolbars as $k => $v )
{
$label = $k;
$name = sanitize_title( $label );
$name = str_replace('-', '_', $name);
$choices[ $name ] = $label;
}
}
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][toolbar]',
'value' => $field['toolbar'],
'layout' => 'horizontal',
'choices' => $choices
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Show Media Upload Buttons?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][media_upload]',
'value' => $field['media_upload'],
'layout' => 'horizontal',
'choices' => array(
'yes' => __("Yes",'acf'),
'no' => __("No",'acf'),
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Run filter \"the_content\"?",'acf'); ?></label>
<p class="description"><?php _e("Enable this filter to use shortcodes within the WYSIWYG field",'acf'); ?></p>
<p class="description"><?php _e("Disable this filter if you encounter recursive template problems with plugins / themes",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][the_content]',
'value' => $field['the_content'],
'layout' => 'horizontal',
'choices' => array(
'yes' => __("Yes",'acf'),
'no' => __("No",'acf'),
)
));
?>
</td>
</tr>
<?php
}
/*--------------------------------------------------------------------------------------
*
* create_field
*
* @author Elliot Condon
* @since 2.0.5
* @updated 2.2.0
*
*-------------------------------------------------------------------------------------*/
function create_field($field)
{
global $wp_version;
// vars
$defaults = array(
'toolbar' => 'full',
'media_upload' => 'yes',
);
$field = array_merge($defaults, $field);
$id = 'wysiwyg-' . $field['id'];
?>
<div id="wp-<?php echo $id; ?>-wrap" class="acf_wysiwyg wp-editor-wrap" data-toolbar="<?php echo $field['toolbar']; ?>" data-upload="<?php echo $field['media_upload']; ?>">
<?php if($field['media_upload'] == 'yes'): ?>
<?php if( version_compare($wp_version, '3.3', '<') ): ?>
<div id="editor-toolbar">
<div id="media-buttons" class="hide-if-no-js">
<?php do_action( 'media_buttons' ); ?>
</div>
</div>
<?php else: ?>
<div id="wp-<?php echo $id; ?>-editor-tools" class="wp-editor-tools">
<div id="wp-<?php echo $id; ?>-media-buttons" class="hide-if-no-js wp-media-buttons">
<?php do_action( 'media_buttons' ); ?>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
<div id="wp-<?php echo $id; ?>-editor-container" class="wp-editor-container">
<textarea id="<?php echo $id; ?>" class="wp-editor-area" name="<?php echo $field['name']; ?>" ><?php echo wp_richedit_pre($field['value']); ?></textarea>
</div>
</div>
<?php
}
/*--------------------------------------------------------------------------------------
*
* get_value_for_api
*
* @author Elliot Condon
* @since 3.0.0
*
*-------------------------------------------------------------------------------------*/
function get_value_for_api($post_id, $field)
{
// vars
$defaults = array(
'the_content' => 'yes',
);
$field = array_merge($defaults, $field);
$value = parent::get_value($post_id, $field);
// filter
if( $field['the_content'] == 'yes' )
{
$value = apply_filters('the_content',$value);
}
else
{
$value = wpautop( $value );
}
return $value;
}
}
?> | SAEBelgradeWeb/vencanje | wp-content/plugins/acf-master/core/fields/wysiwyg.php | PHP | gpl-2.0 | 7,948 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ESPSharp.Enums
{
public enum PackageScheduleDays : sbyte
{
Any = -1,
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Weekdays,
Weekends,
Mon_Wed_Fri,
Tue_Thur
}
}
| TaleOfTwoWastelands/ESPSharp | ESPSharp/Enums/PackageScheduleDays.cs | C# | gpl-2.0 | 417 |
<?php
/**
* @package Adminimize
* @subpackage Backend Options
* @author Frank Bültge
*/
if ( ! function_exists( 'add_action' ) ) {
echo "Hi there! I'm just a part of plugin, not much I can do when called directly.";
exit;
}
?>
<div id="poststuff" class="ui-sortable meta-box-sortables">
<div class="postbox">
<div class="handlediv" title="<?php _e('Click to toggle'); ?>"><br/></div>
<h3 class="hndle" id="backend_options"><?php _e('Backend Options', FB_ADMINIMIZE_TEXTDOMAIN ); ?></h3>
<div class="inside">
<?php wp_nonce_field('mw_adminimize_nonce'); ?>
<br class="clear" />
<table summary="config" class="widefat">
<tbody>
<?php if ( function_exists('is_super_admin') ) { ?>
<!--
<tr valign="top" class="form-invalid">
<td><?php _e( 'Use Global Settings', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php
$mw_adminimize_use_global = '0';
$select_active = '';
$message = '';
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) ) {
$mw_adminimize_use_global = 1;
$select_active = ' disabled="disabled"';
$message = __( 'The plugin is active in multiste.', FB_ADMINIMIZE_TEXTDOMAIN );
}
$mw_adminimize_use_global = get_option( 'mw_adminimize_use_global' ); ?>
<select name="_mw_adminimize_use_global"<?php echo $select_active; ?>>
<option value="0"<?php if ( '0' === $mw_adminimize_use_global ) { echo ' selected="selected"'; } ?>><?php _e( 'False', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ( '1' === $mw_adminimize_use_global ) { echo ' selected="selected"'; } ?>><?php _e('True', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Use the settings global in your Multisite network.', FB_ADMINIMIZE_TEXTDOMAIN ); echo ' ' . $message; ?>
</td>
</tr>
-->
<tr valign="top" class="form-invalid">
<td><?php _e('Exclude Super Admin', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_exclude_super_admin = _mw_adminimize_get_option_value('_mw_adminimize_exclude_super_admin'); ?>
<select name="_mw_adminimize_exclude_super_admin">
<option value="0"<?php if ($_mw_adminimize_exclude_super_admin == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_exclude_super_admin == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Exclude the Super Admin on a WP Multisite Install from all limitations of this plugin.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php } ?>
<tr valign="top">
<td><?php _e('User-Info', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_user_info = _mw_adminimize_get_option_value('_mw_adminimize_user_info'); ?>
<select name="_mw_adminimize_user_info">
<option value="0"<?php if ($_mw_adminimize_user_info == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_user_info == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="2"<?php if ($_mw_adminimize_user_info == '2') { echo ' selected="selected"'; } ?>><?php _e('Only logout', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="3"<?php if ($_mw_adminimize_user_info == '3') { echo ' selected="selected"'; } ?>><?php _e('User & Logout', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('The "User-Info-area" is on the top right side of the backend. You can hide or reduced show.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php if ( ($_mw_adminimize_user_info == '') || ($_mw_adminimize_user_info == '1') || ($_mw_adminimize_user_info == '0') ) $disabled_item = ' disabled="disabled"' ?>
<tr valign="top" class="form-invalid">
<td><?php _e('Change User-Info, redirect to', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_ui_redirect = _mw_adminimize_get_option_value('_mw_adminimize_ui_redirect'); ?>
<select name="_mw_adminimize_ui_redirect" <?php if ( isset($disabled_item) ) echo $disabled_item; ?>>
<option value="0"<?php if ($_mw_adminimize_ui_redirect == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_ui_redirect == '1') { echo ' selected="selected"'; } ?>><?php _e('Frontpage of the Blog', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</select> <?php _e('When the "User-Info-area" change it, then it is possible to change the redirect.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Footer', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_footer = _mw_adminimize_get_option_value('_mw_adminimize_footer'); ?>
<select name="_mw_adminimize_footer">
<option value="0"<?php if ($_mw_adminimize_footer == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_footer == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('The Footer-area can hide, include all links and details.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Header', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_header = _mw_adminimize_get_option_value('_mw_adminimize_header'); ?>
<select name="_mw_adminimize_header">
<option value="0"<?php if ($_mw_adminimize_header == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_header == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('The Header-area can hide, include all links and details.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Timestamp', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_timestamp = _mw_adminimize_get_option_value('_mw_adminimize_timestamp'); ?>
<select name="_mw_adminimize_timestamp">
<option value="0"<?php if ($_mw_adminimize_timestamp == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_timestamp == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Opens the post timestamp editing fields without you having to click the "Edit" link every time.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Thickbox FullScreen', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_tb_window = _mw_adminimize_get_option_value('_mw_adminimize_tb_window'); ?>
<select name="_mw_adminimize_tb_window">
<option value="0"<?php if ($_mw_adminimize_tb_window == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_tb_window == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('All Thickbox-function use the full area of the browser. Thickbox is for example in upload media-files.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Flashuploader', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_control_flashloader = _mw_adminimize_get_option_value('_mw_adminimize_control_flashloader'); ?>
<select name="_mw_adminimize_control_flashloader">
<option value="0"<?php if ($_mw_adminimize_control_flashloader == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_control_flashloader == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Disable the flashuploader and users use only the standard uploader.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Category Height', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_cat_full = _mw_adminimize_get_option_value('_mw_adminimize_cat_full'); ?>
<select name="_mw_adminimize_cat_full">
<option value="0"<?php if ($_mw_adminimize_cat_full == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_cat_full == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('View the Meta Box with Categories in the full height, no scrollbar or whitespace.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Advice in Footer', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_advice = _mw_adminimize_get_option_value('_mw_adminimize_advice'); ?>
<select name="_mw_adminimize_advice">
<option value="0"<?php if ($_mw_adminimize_advice == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_advice == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select>
<textarea style="width: 85%;" class="code" rows="1" cols="60" name="_mw_adminimize_advice_txt" id="_mw_adminimize_advice_txt" ><?php echo htmlspecialchars(stripslashes(_mw_adminimize_get_option_value('_mw_adminimize_advice_txt'))); ?></textarea><br /><?php _e('In the Footer you can display an advice for changing the Default-design, (x)HTML is possible.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php
// when remove dashboard
foreach ($user_roles as $role) {
$disabled_menu_[$role] = _mw_adminimize_get_option_value('mw_adminimize_disabled_menu_'. $role .'_items');
$disabled_submenu_[$role] = _mw_adminimize_get_option_value('mw_adminimize_disabled_submenu_'. $role .'_items');
}
$disabled_menu_all = array();
foreach ($user_roles as $role) {
array_push($disabled_menu_all, $disabled_menu_[$role]);
array_push($disabled_menu_all, $disabled_submenu_[$role]);
}
if ( '' != $disabled_menu_all ) {
if ( ! _mw_adminimize_recursive_in_array('index.php', $disabled_menu_all) ) {
$disabled_item2 = ' disabled="disabled"';
}
?>
<tr valign="top" class="form-invalid">
<td><?php _e('Dashboard deactivate, redirect to', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_db_redirect = _mw_adminimize_get_option_value('_mw_adminimize_db_redirect'); ?>
<select name="_mw_adminimize_db_redirect"<?php if ( isset($disabled_item2) ) echo $disabled_item2; ?>>
<option value="0"<?php if ($_mw_adminimize_db_redirect == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (profile.php)</option>
<option value="1"<?php if ($_mw_adminimize_db_redirect == '1') { echo ' selected="selected"'; } ?>><?php _e('Manage Posts', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit.php)</option>
<option value="2"<?php if ($_mw_adminimize_db_redirect == '2') { echo ' selected="selected"'; } ?>><?php _e('Manage Pages', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit-pages.php)</option>
<option value="3"<?php if ($_mw_adminimize_db_redirect == '3') { echo ' selected="selected"'; } ?>><?php _e('Write Post', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (post-new.php)</option>
<option value="4"<?php if ($_mw_adminimize_db_redirect == '4') { echo ' selected="selected"'; } ?>><?php _e('Write Page', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (page-new.php)</option>
<option value="5"<?php if ($_mw_adminimize_db_redirect == '5') { echo ' selected="selected"'; } ?>><?php _e('Comments', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit-comments.php)</option>
<option value="6"<?php if ($_mw_adminimize_db_redirect == '6') { echo ' selected="selected"'; } ?>><?php _e('other Page', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select>
<textarea style="width: 85%;" class="code" rows="1" cols="60" name="_mw_adminimize_db_redirect_txt" id="_mw_adminimize_db_redirect_txt" ><?php echo htmlspecialchars(stripslashes(_mw_adminimize_get_option_value('_mw_adminimize_db_redirect_txt'))); ?></textarea>
<br /><?php _e('You have deactivated the Dashboard, please select a page for redirection or define custom url, include http://?', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<p id="submitbutton">
<input class="button button-primary" type="submit" name="_mw_adminimize_save" value="<?php _e('Update Options', FB_ADMINIMIZE_TEXTDOMAIN ); ?> »" /><input type="hidden" name="page_options" value="'dofollow_timeout'" />
</p>
<p><a class="alignright button" href="javascript:void(0);" onclick="window.scrollTo(0,0);" style="margin:3px 0 0 30px;"><?php _e('scroll to top', FB_ADMINIMIZE_TEXTDOMAIN); ?></a><br class="clear" /></p>
</div>
</div>
</div>
| overneath42/wp-custom-install | wp-content/plugins/adminimize/inc-options/backend_options.php | PHP | gpl-2.0 | 14,171 |
<?php
/**
* Footer functions.
*
* @package Sento
*/
/* ----------------------------------------------------------------------------------
FOOTER WIDGETS LAYOUT
---------------------------------------------------------------------------------- */
/* Assign function for widget area 1 */
function thinkup_input_footerw1() {
echo '<div id="footer-col1" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w1' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 1.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 2 */
function thinkup_input_footerw2() {
echo '<div id="footer-col2" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w2' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 2.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 3 */
function thinkup_input_footerw3() {
echo '<div id="footer-col3" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w3' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 3.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 4 */
function thinkup_input_footerw4() {
echo '<div id="footer-col4" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w4' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 4.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 5 */
function thinkup_input_footerw5() {
echo '<div id="footer-col5" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w5' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 5.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 6 */
function thinkup_input_footerw6() {
echo '<div id="footer-col6" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w6' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 6.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Add Custom Footer Layout */
function thinkup_input_footerlayout() {
global $thinkup_footer_layout;
global $thinkup_footer_widgetswitch;
if ( $thinkup_footer_widgetswitch !== "1" and ! empty( $thinkup_footer_layout ) ) {
echo '<div id="footer">';
if ( $thinkup_footer_layout == "option1" ) {
echo '<div id="footer-core" class="option1">';
thinkup_input_footerw1();
echo '</div>';
} else if ( $thinkup_footer_layout == "option2" ) {
echo '<div id="footer-core" class="option2">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option3" ) {
echo '<div id="footer-core" class="option3">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
echo '</div>';
} else if ( $thinkup_footer_layout == "option4" ) {
echo '<div id="footer-core" class="option4">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
echo '</div>';
} else if ( $thinkup_footer_layout == "option5" ) {
echo '<div id="footer-core" class="option5">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
echo '</div>';
} else if ( $thinkup_footer_layout == "option6" ) {
echo '<div id="footer-core" class="option6">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
thinkup_input_footerw6();
echo '</div>';
} else if ( $thinkup_footer_layout == "option7" ) {
echo '<div id="footer-core" class="option7">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option8" ) {
echo '<div id="footer-core" class="option8">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option9" ) {
echo '<div id="footer-core" class="option9">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option10" ) {
echo '<div id="footer-core" class="option10">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option11" ) {
echo '<div id="footer-core" class="option11">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option12" ) {
echo '<div id="footer-core" class="option12">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option13" ) {
echo '<div id="footer-core" class="option13">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
echo '</div>';
} else if ( $thinkup_footer_layout == "option14" ) {
echo '<div id="footer-core" class="option14">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
echo '</div>';
} else if ( $thinkup_footer_layout == "option15" ) {
echo '<div id="footer-core" class="option15">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
echo '</div>';
} else if ( $thinkup_footer_layout == "option16" ) {
echo '<div id="footer-core" class="option16">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
echo '</div>';
} else if ( $thinkup_footer_layout == "option17" ) {
echo '<div id="footer-core" class="option17">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
echo '</div>';
} else if ( $thinkup_footer_layout == "option18" ) {
echo '<div id="footer-core" class="option18">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
echo '</div>';
}
echo '</div>';
}
}
/* ----------------------------------------------------------------------------------
COPYRIGHT TEXT
---------------------------------------------------------------------------------- */
function thinkup_input_copyright() {
printf( __( 'Developed by %1$s. Powered by %2$s.', 'sento' ) , '<a href="//www.thinkupthemes.com/" target="_blank">Think Up Themes Ltd</a>', '<a href="//www.wordpress.org/" target="_blank">WordPress</a>');
}
?> | JulioKno/Portal-UNIVIM-2016 | wp-content/themes/sento/admin/main/options/04.footer.php | PHP | gpl-2.0 | 8,650 |
/*
* Copyright 2010, Intel Corporation
*
* This file is part of PowerTOP
*
* This program file 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; version 2 of the License.
*
* 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 in a file named COPYING; if not, write to the
* Free Software Foundation, Inc,
* 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
* or just google for it.
*
* Authors:
* Arjan van de Ven <arjan@linux.intel.com>
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include "calibrate.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <math.h>
#include <sys/types.h>
#include <dirent.h>
#include "../parameters/parameters.h"
extern "C" {
#include "../tuning/iw.h"
}
#include <map>
#include <vector>
#include <string>
using namespace std;
static vector<string> usb_devices;
static vector<string> rfkill_devices;
static vector<string> backlight_devices;
static vector<string> scsi_link_devices;
static int blmax;
static map<string, string> saved_sysfs;
static volatile int stop_measurement;
static int wireless_PS;
static void save_sysfs(const char *filename)
{
char line[4096];
ifstream file;
file.open(filename, ios::in);
if (!file)
return;
file.getline(line, 4096);
file.close();
saved_sysfs[filename] = line;
}
static void restore_all_sysfs(void)
{
map<string, string>::iterator it;
for (it = saved_sysfs.begin(); it != saved_sysfs.end(); it++)
write_sysfs(it->first, it->second);
set_wifi_power_saving("wlan0", wireless_PS);
}
static void find_all_usb(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/bus/usb/devices/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/bus/usb/devices/%s/power/active_duration", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
sprintf(filename, "/sys/bus/usb/devices/%s/power/idVendor", entry->d_name);
file.open(filename, ios::in);
if (file) {
file.getline(filename, 4096);
file.close();
if (strcmp(filename, "1d6b")==0)
continue;
}
sprintf(filename, "/sys/bus/usb/devices/%s/power/control", entry->d_name);
save_sysfs(filename);
usb_devices.push_back(filename);
}
closedir(dir);
}
static void suspend_all_usb_devices(void)
{
unsigned int i;
for (i = 0; i < usb_devices.size(); i++)
write_sysfs(usb_devices[i], "auto\n");
}
static void find_all_rfkill(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/class/rfkill/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/class/rfkill/%s/soft", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
save_sysfs(filename);
rfkill_devices.push_back(filename);
}
closedir(dir);
}
static void rfkill_all_radios(void)
{
unsigned int i;
for (i = 0; i < rfkill_devices.size(); i++)
write_sysfs(rfkill_devices[i], "1\n");
}
static void unrfkill_all_radios(void)
{
unsigned int i;
for (i = 0; i < rfkill_devices.size(); i++)
write_sysfs(rfkill_devices[i], "0\n");
}
static void find_backlight(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/class/backlight/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/class/backlight/%s/brightness", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
save_sysfs(filename);
backlight_devices.push_back(filename);
sprintf(filename, "/sys/class/backlight/%s/max_brightness", entry->d_name);
blmax = read_sysfs(filename);
}
closedir(dir);
}
static void lower_backlight(void)
{
unsigned int i;
for (i = 0; i < backlight_devices.size(); i++)
write_sysfs(backlight_devices[i], "0\n");
}
static void find_scsi_link(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/class/scsi_host/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/class/scsi_host/%s/link_power_management_policy", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
save_sysfs(filename);
scsi_link_devices.push_back(filename);
}
closedir(dir);
}
static void set_scsi_link(const char *state)
{
unsigned int i;
for (i = 0; i < scsi_link_devices.size(); i++)
write_sysfs(scsi_link_devices[i], state);
}
static void *burn_cpu(void *dummy)
{
volatile double d = 1.1;
while (!stop_measurement) {
d = pow(d, 1.0001);
}
return NULL;
}
static void *burn_cpu_wakeups(void *dummy)
{
struct timespec tm;
while (!stop_measurement) {
tm.tv_sec = 0;
tm.tv_nsec = (unsigned long)dummy;
nanosleep(&tm, NULL);
}
return NULL;
}
static void *burn_disk(void *dummy)
{
int fd;
char buffer[64*1024];
char filename[256];
strcpy(filename ,"/tmp/powertop.XXXXXX");
fd = mkstemp(filename);
if (fd < 0) {
printf(_("Cannot create temp file\n"));
return NULL;
}
while (!stop_measurement) {
lseek(fd, 0, SEEK_SET);
write(fd, buffer, 64*1024);
fdatasync(fd);
}
close(fd);
return NULL;
}
static void cpu_calibration(int threads)
{
int i;
pthread_t thr;
printf(_("Calibrating: CPU usage on %i threads\n"), threads);
stop_measurement = 0;
for (i = 0; i < threads; i++)
pthread_create(&thr, NULL, burn_cpu, NULL);
one_measurement(15);
stop_measurement = 1;
sleep(1);
}
static void wakeup_calibration(unsigned long interval)
{
pthread_t thr;
printf(_("Calibrating: CPU wakeup power consumption\n"));
stop_measurement = 0;
pthread_create(&thr, NULL, burn_cpu_wakeups, (void *)interval);
one_measurement(15);
stop_measurement = 1;
sleep(1);
}
static void usb_calibration(void)
{
unsigned int i;
/* chances are one of the USB devices is bluetooth; unrfkill first */
unrfkill_all_radios();
printf(_("Calibrating USB devices\n"));
for (i = 0; i < usb_devices.size(); i++) {
printf(_(".... device %s \n"), usb_devices[i].c_str());
suspend_all_usb_devices();
write_sysfs(usb_devices[i], "on\n");
one_measurement(15);
suspend_all_usb_devices();
sleep(3);
}
rfkill_all_radios();
sleep(4);
}
static void rfkill_calibration(void)
{
unsigned int i;
printf(_("Calibrating radio devices\n"));
for (i = 0; i < rfkill_devices.size(); i++) {
printf(_(".... device %s \n"), rfkill_devices[i].c_str());
rfkill_all_radios();
write_sysfs(rfkill_devices[i], "0\n");
one_measurement(15);
rfkill_all_radios();
sleep(3);
}
for (i = 0; i < rfkill_devices.size(); i++) {
printf(_(".... device %s \n"), rfkill_devices[i].c_str());
unrfkill_all_radios();
write_sysfs(rfkill_devices[i], "1\n");
one_measurement(15);
unrfkill_all_radios();
sleep(3);
}
rfkill_all_radios();
}
static void backlight_calibration(void)
{
unsigned int i;
printf(_("Calibrating backlight\n"));
for (i = 0; i < backlight_devices.size(); i++) {
char str[4096];
printf(_(".... device %s \n"), backlight_devices[i].c_str());
lower_backlight();
one_measurement(15);
sprintf(str, "%i\n", blmax / 4);
write_sysfs(backlight_devices[i], str);
one_measurement(15);
sprintf(str, "%i\n", blmax / 2);
write_sysfs(backlight_devices[i], str);
one_measurement(15);
sprintf(str, "%i\n", 3 * blmax / 4 );
write_sysfs(backlight_devices[i], str);
one_measurement(15);
sprintf(str, "%i\n", blmax);
write_sysfs(backlight_devices[i], str);
one_measurement(15);
lower_backlight();
sleep(1);
}
printf(_("Calibrating idle\n"));
system("DISPLAY=:0 /usr/bin/xset dpms force off");
one_measurement(15);
system("DISPLAY=:0 /usr/bin/xset dpms force on");
}
static void idle_calibration(void)
{
printf(_("Calibrating idle\n"));
system("DISPLAY=:0 /usr/bin/xset dpms force off");
one_measurement(15);
system("DISPLAY=:0 /usr/bin/xset dpms force on");
}
static void disk_calibration(void)
{
pthread_t thr;
printf(_("Calibrating: disk usage \n"));
set_scsi_link("min_power");
stop_measurement = 0;
pthread_create(&thr, NULL, burn_disk, NULL);
one_measurement(15);
stop_measurement = 1;
sleep(1);
}
void calibrate(void)
{
find_all_usb();
find_all_rfkill();
find_backlight();
find_scsi_link();
wireless_PS = get_wifi_power_saving("wlan0");
save_sysfs("/sys/module/snd_hda_intel/parameters/power_save");
cout << _("Starting PowerTOP power estimate calibration \n");
suspend_all_usb_devices();
rfkill_all_radios();
lower_backlight();
set_wifi_power_saving("wlan0", 1);
sleep(4);
idle_calibration();
disk_calibration();
backlight_calibration();
write_sysfs("/sys/module/snd_hda_intel/parameters/power_save", "1\n");
cpu_calibration(1);
cpu_calibration(4);
wakeup_calibration(10000);
wakeup_calibration(100000);
wakeup_calibration(1000000);
set_wifi_power_saving("wlan0", 0);
usb_calibration();
rfkill_calibration();
cout << _("Finishing PowerTOP power estimate calibration \n");
restore_all_sysfs();
learn_parameters(300, 1);
printf(_("Parameters after calibration:\n"));
dump_parameter_bundle();
save_parameters("saved_parameters.powertop");
save_all_results("saved_results.powertop");
}
| AllenDou/powertop | src/calibrate/calibrate.cpp | C++ | gpl-2.0 | 9,814 |
/* This file is part of the KDE project
Copyright (C) 2007, 2012 Dag Andersen danders@get2net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kptdocumentseditor.h"
#include "kptcommand.h"
#include "kptitemmodelbase.h"
#include "kptduration.h"
#include "kptnode.h"
#include "kptproject.h"
#include "kpttask.h"
#include "kptdocuments.h"
#include "kptdatetime.h"
#include "kptitemviewsettup.h"
#include "kptdebug.h"
#include <QMenu>
#include <QList>
#include <QVBoxLayout>
#include <kaction.h>
#include <kicon.h>
#include <kglobal.h>
#include <klocale.h>
#include <kactioncollection.h>
#include <kdebug.h>
#include <KoDocument.h>
namespace KPlato
{
//--------------------
DocumentTreeView::DocumentTreeView( QWidget *parent )
: TreeViewBase( parent )
{
// header()->setContextMenuPolicy( Qt::CustomContextMenu );
setStretchLastSection( true );
DocumentItemModel *m = new DocumentItemModel();
setModel( m );
setRootIsDecorated ( false );
setSelectionBehavior( QAbstractItemView::SelectRows );
setSelectionMode( QAbstractItemView::SingleSelection );
createItemDelegates( m );
setAcceptDrops( true );
setDropIndicatorShown( true );
connect( selectionModel(), SIGNAL( selectionChanged ( const QItemSelection&, const QItemSelection& ) ), SLOT( slotSelectionChanged( const QItemSelection& ) ) );
setColumnHidden( DocumentModel::Property_Status, true ); // not used atm
}
Document *DocumentTreeView::currentDocument() const
{
return model()->document( selectionModel()->currentIndex() );
}
QModelIndexList DocumentTreeView::selectedRows() const
{
return selectionModel()->selectedRows();
}
void DocumentTreeView::slotSelectionChanged( const QItemSelection &selected )
{
emit selectionChanged( selected.indexes() );
}
QList<Document*> DocumentTreeView::selectedDocuments() const
{
QList<Document*> lst;
foreach ( const QModelIndex &i, selectionModel()->selectedRows() ) {
Document *doc = model()->document( i );
if ( doc ) {
lst << doc;
}
}
return lst;
}
//-----------------------------------
DocumentsEditor::DocumentsEditor( KoDocument *part, QWidget *parent )
: ViewBase( part, parent )
{
setupGui();
QVBoxLayout * l = new QVBoxLayout( this );
l->setMargin( 0 );
m_view = new DocumentTreeView( this );
l->addWidget( m_view );
m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed );
connect( model(), SIGNAL( executeCommand( KUndo2Command* ) ), part, SLOT( addCommand( KUndo2Command* ) ) );
connect( m_view, SIGNAL( currentChanged( const QModelIndex &, const QModelIndex & ) ), this, SLOT( slotCurrentChanged( const QModelIndex & ) ) );
connect( m_view, SIGNAL( selectionChanged( const QModelIndexList ) ), this, SLOT( slotSelectionChanged( const QModelIndexList ) ) );
connect( m_view, SIGNAL( contextMenuRequested( QModelIndex, const QPoint& ) ), this, SLOT( slotContextMenuRequested( QModelIndex, const QPoint& ) ) );
connect( m_view, SIGNAL( headerContextMenuRequested( const QPoint& ) ), SLOT( slotHeaderContextMenuRequested( const QPoint& ) ) );
}
void DocumentsEditor::updateReadWrite( bool readwrite )
{
kDebug(planDbg())<<isReadWrite()<<"->"<<readwrite;
ViewBase::updateReadWrite( readwrite );
m_view->setReadWrite( readwrite );
updateActionsEnabled( readwrite );
}
void DocumentsEditor::draw( Documents &docs )
{
m_view->setDocuments( &docs );
}
void DocumentsEditor::draw()
{
}
void DocumentsEditor::setGuiActive( bool activate )
{
kDebug(planDbg())<<activate;
updateActionsEnabled( true );
ViewBase::setGuiActive( activate );
if ( activate && !m_view->selectionModel()->currentIndex().isValid() ) {
m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate);
}
}
void DocumentsEditor::slotContextMenuRequested( QModelIndex index, const QPoint& pos )
{
//kDebug(planDbg())<<index.row()<<","<<index.column()<<":"<<pos;
QString name;
if ( index.isValid() ) {
Document *obj = m_view->model()->document( index );
if ( obj ) {
name = "documentseditor_popup";
}
}
emit requestPopupMenu( name, pos );
}
void DocumentsEditor::slotHeaderContextMenuRequested( const QPoint &pos )
{
kDebug(planDbg());
QList<QAction*> lst = contextActionList();
if ( ! lst.isEmpty() ) {
QMenu::exec( lst, pos, lst.first() );
}
}
Document *DocumentsEditor::currentDocument() const
{
return m_view->currentDocument();
}
void DocumentsEditor::slotCurrentChanged( const QModelIndex & )
{
//kDebug(planDbg())<<curr.row()<<","<<curr.column();
// slotEnableActions();
}
void DocumentsEditor::slotSelectionChanged( const QModelIndexList list )
{
kDebug(planDbg())<<list.count();
updateActionsEnabled( true );
}
void DocumentsEditor::slotEnableActions( bool on )
{
updateActionsEnabled( on );
}
void DocumentsEditor::updateActionsEnabled( bool on )
{
QList<Document*> lst = m_view->selectedDocuments();
if ( lst.isEmpty() || lst.count() > 1 ) {
actionEditDocument->setEnabled( false );
actionViewDocument->setEnabled( false );
return;
}
Document *doc = lst.first();
actionViewDocument->setEnabled( on );
actionEditDocument->setEnabled( on && doc->type() == Document::Type_Product && isReadWrite() );
}
void DocumentsEditor::setupGui()
{
QString name = "documentseditor_edit_list";
actionEditDocument = new KAction(KIcon( "document-properties" ), i18n("Edit..."), this);
actionCollection()->addAction("edit_documents", actionEditDocument );
// actionEditDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) );
connect( actionEditDocument, SIGNAL( triggered( bool ) ), SLOT( slotEditDocument() ) );
addAction( name, actionEditDocument );
actionViewDocument = new KAction(KIcon( "document-preview" ), i18nc("@action View a document", "View..."), this);
actionCollection()->addAction("view_documents", actionViewDocument );
// actionViewDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) );
connect( actionViewDocument, SIGNAL( triggered( bool ) ), SLOT( slotViewDocument() ) );
addAction( name, actionViewDocument );
/* actionDeleteSelection = new KAction(KIcon( "edit-delete" ), i18n("Delete"), this);
actionCollection()->addAction("delete_selection", actionDeleteSelection );
actionDeleteSelection->setShortcut( KShortcut( Qt::Key_Delete ) );
connect( actionDeleteSelection, SIGNAL( triggered( bool ) ), SLOT( slotDeleteSelection() ) );
addAction( name, actionDeleteSelection );*/
// Add the context menu actions for the view options
createOptionAction();
}
void DocumentsEditor::slotOptions()
{
kDebug(planDbg());
ItemViewSettupDialog dlg( this, m_view/*->masterView()*/ );
dlg.exec();
}
void DocumentsEditor::slotEditDocument()
{
QList<Document*> dl = m_view->selectedDocuments();
if ( dl.isEmpty() ) {
return;
}
kDebug(planDbg())<<dl;
emit editDocument( dl.first() );
}
void DocumentsEditor::slotViewDocument()
{
QList<Document*> dl = m_view->selectedDocuments();
if ( dl.isEmpty() ) {
return;
}
kDebug(planDbg())<<dl;
emit viewDocument( dl.first() );
}
void DocumentsEditor::slotAddDocument()
{
//kDebug(planDbg());
QList<Document*> dl = m_view->selectedDocuments();
Document *after = 0;
if ( dl.count() > 0 ) {
after = dl.last();
}
Document *doc = new Document();
QModelIndex i = m_view->model()->insertDocument( doc, after );
if ( i.isValid() ) {
m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate );
m_view->edit( i );
}
}
void DocumentsEditor::slotDeleteSelection()
{
QList<Document*> lst = m_view->selectedDocuments();
//kDebug(planDbg())<<lst.count()<<" objects";
if ( ! lst.isEmpty() ) {
emit deleteDocumentList( lst );
}
}
bool DocumentsEditor::loadContext( const KoXmlElement &context )
{
return m_view->loadContext( m_view->model()->columnMap(), context );
}
void DocumentsEditor::saveContext( QDomElement &context ) const
{
m_view->saveContext( m_view->model()->columnMap(), context );
}
} // namespace KPlato
#include "kptdocumentseditor.moc"
| wyuka/calligra | plan/libs/ui/kptdocumentseditor.cpp | C++ | gpl-2.0 | 9,173 |
/**
* Copyright (C) 2004 - 2012 Nils Asmussen
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package bbcodeeditor.control.actions;
import bbcodeeditor.control.Controller;
import bbcodeeditor.control.SecImage;
import bbcodeeditor.control.SecSmiley;
/**
* @author Assi Nilsmussen
*
*/
public final class AddImageAction extends HistoryAction {
/**
* the image to add
*/
private final SecImage _image;
/**
* constructor
*
* @param con the controller of the text-field
* @param start the start-position of this action
* @param end the end-position of this action
* @param image the image
*/
public AddImageAction(Controller con,int start,int end,SecImage image) {
super(con,start,end);
_image = image;
}
public void performAction() {
switch(_actionType) {
case UNDO:
_con.removeText(_start,_end,false);
_actionType = REDO;
break;
case REDO:
_con.addImage(_image,_start);
_con.goToPosition(_start + 1);
_actionType = UNDO;
break;
}
}
public String getName() {
String imgName;
if(_image instanceof SecSmiley)
imgName = "smiley '" + ((SecSmiley)_image).getPrimaryCode() + "'";
else
imgName = "image";
String res;
if(_actionType == UNDO)
res = "Remove " + imgName;
else
res = "Add " + imgName;
return res + " [" + _start + "," + _end + "]";
}
public String toString() {
return getName();
}
} | script-solution/BBCodeEditor | bbcodeeditor/control/actions/AddImageAction.java | Java | gpl-2.0 | 2,158 |
<?php
/**
*
*/
# Define namespace
namespace WCFE\Modules\Editor\View\Editor\Templates\Tabs\Tabs;
# Imports
use WCFE\Modules\Editor\View\Editor\Templates\Tabs\FieldsTab;
/**
*
*/
class MultiSiteOptionsTab extends FieldsTab {
/**
* put your comment there...
*
* @var mixed
*/
protected $fieldsPluggableFilterName = \WCFE\Hooks::FILTER_VIEW_TABS_TAB_MULTISITE_FIELDS;
/**
* put your comment there...
*
* @var mixed
*/
protected $fields = array
(
'WCFE\Modules\Editor\View\Editor\Templates\Fields' => array
(
'MultiSiteAllow',
'MultiSite',
'MultiSiteSubDomainInstall',
'MultiSiteDomainCurrentSite',
'MultiSitePathCurrentSite',
'MultiSiteSiteId',
'MultiSiteBlogId',
'MultiSitePrimaryNetworkId',
)
);
/**
* put your comment there...
*
*/
protected function initialize()
{
$this->title = $this->_( 'Multi Sites' );
$this->fields = $this->bcCreateFieldsList( $this->fields );
}
} | kinko912000/public_html | wp-content/plugins/wp-config-file-editor/Modules/Editor/View/Editor/Templates/Tabs/Tabs/MultiSite.class.php | PHP | gpl-2.0 | 957 |
<?php
/***************************************************************************
*
* 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.
*
* Portions of this program are derived from publicly licensed software
* projects including, but not limited to phpBB, Magelo Clone,
* EQEmulator, EQEditor, and Allakhazam Clone.
*
* Author:
* Maudigan(Airwalking)
*
* November 24, 2013 - Maudigan
* Updated query to be compatible with the new way factions are stored in
* the database
* General code/comment/whitespace cleanup
* September 26, 2014 - Maudigan
* Updated character table name
* September 28, 2014 - Maudigan
* added code to monitor database performance
* altered character profile initialization to remove redundant query
* May 24, 2016 - Maudigan
* general code cleanup, whitespace correction, removed old comments,
* organized some code. A lot has changed, but not much functionally
* do a compare to 2.41 to see the differences.
* Implemented new database wrapper.
* October 3, 2016 - Maudigan
* Made the faction links customizable
* January 7, 2018 - Maudigan
* Modified database to use a class.
* March 9, 2020 - Maudigan
* modularized the profile menu output
* March 22, 2020 - Maudigan
* impemented common.php
* April 25, 2020 - Maudigan
* implement multi-tenancy
* May 4, 2020 - Maudigan
* clean up of the content/character data join
*
***************************************************************************/
/*********************************************
INCLUDES
*********************************************/
define('INCHARBROWSER', true);
include_once(__DIR__ . "/include/common.php");
include_once(__DIR__ . "/include/profile.php");
include_once(__DIR__ . "/include/db.php");
/*********************************************
SUPPORT FUNCTIONS
*********************************************/
//converts faction values into a the string from the language file.
function FactionToString($character_value) {
global $language;
if($character_value >= 1101) return $language['FACTION_ALLY'];
if($character_value >= 701 && $character_value <= 1100) return $language['FACTION_WARMLY'];
if($character_value >= 401 && $character_value <= 700) return $language['FACTION_KINDLY'];
if($character_value >= 101 && $character_value <= 400) return $language['FACTION_AMIABLE'];
if($character_value >= 0 && $character_value <= 100) return $language['FACTION_INDIFF'];
if($character_value >= -100 && $character_value <= -1) return $language['FACTION_APPR'];
if($character_value >= -700 && $character_value <= -101) return $language['FACTION_DUBIOUS'];
if($character_value >= -999 && $character_value <= -701) return $language['FACTION_THREAT'];
if($character_value <= -1000) return $language['FACTION_SCOWLS'];
return $language['FACTION_INDIFF'];
}
/*********************************************
SETUP PROFILE/PERMISSIONS
*********************************************/
if(!$_GET['char']) cb_message_die($language['MESSAGE_ERROR'],$language['MESSAGE_NO_CHAR']);
else $charName = $_GET['char'];
//character initializations
$char = new profile($charName, $cbsql, $cbsql_content, $language, $showsoftdelete, $charbrowser_is_admin_page); //the profile class will sanitize the character name
$charID = $char->char_id();
$name = $char->GetValue('name');
$mypermission = GetPermissions($char->GetValue('gm'), $char->GetValue('anon'), $char->char_id());
//block view if user level doesnt have permission
if ($mypermission['factions']) cb_message_die($language['MESSAGE_ERROR'],$language['MESSAGE_ITEM_NO_VIEW']);
/*********************************************
GATHER RELEVANT PAGE DATA
*********************************************/
//get content factions from the content db
$tpl = <<<TPL
SELECT fl.id,
fl.name,
IFNULL(fl.base, 0) AS base,
IFNULL(flmc.mod, 0) AS classmod,
IFNULL(flmr.mod, 0) AS racemod,
IFNULL(flmd.mod, 0) AS deitymod
FROM faction_list AS fl
LEFT JOIN faction_list_mod AS flmc
ON fl.id = flmc.faction_id
AND (flmc.mod_name = 'c%d')
LEFT JOIN faction_list_mod AS flmr
ON fl.id = flmr.faction_id
AND (flmr.mod_name = 'r%d')
LEFT JOIN faction_list_mod AS flmd
ON fl.id = flmd.faction_id
AND (flmd.mod_name = 'd%d')
ORDER BY name ASC
TPL;
$query = sprintf(
$tpl,
$char->GetValue('class'),
$char->GetValue('race'),
($char->GetValue('deity') == 396) ? "140" : $char->GetValue('deity')
);
$result = $cbsql_content->query($query);
$content_factions = $cbsql_content->fetch_all($result);
//get the characters factions from the player db
$tpl = <<<TPL
SELECT current_value,
faction_ID
FROM faction_values
WHERE char_id = '%s'
TPL;
$query = sprintf($tpl, $charID);
$result = $cbsql->query($query);
$character_factions = $cbsql->fetch_all($result);
//DO A MANUAL JOIN OF THE RESULTS
$joined_factions = manual_join($content_factions, 'id', $character_factions, 'faction_ID', 'left');
/*********************************************
DROP HEADER
*********************************************/
$d_title = " - ".$name.$language['PAGE_TITLES_FACTIONS'];
include(__DIR__ . "/include/header.php");
/*********************************************
DROP PROFILE MENU
*********************************************/
output_profile_menu($name, 'factions');
/*********************************************
POPULATE BODY
*********************************************/
if (!$mypermission['advfactions']) {
$cb_template->set_filenames(array(
'factions' => 'factions_advanced_body.tpl')
);
}
else {
$cb_template->set_filenames(array(
'factions' => 'factions_basic_body.tpl')
);
}
$cb_template->assign_both_vars(array(
'NAME' => $name)
);
$cb_template->assign_vars(array(
'L_FACTIONS' => $language['FACTION_FACTIONS'],
'L_NAME' => $language['FACTION_NAME'],
'L_FACTION' => $language['FACTION_FACTION'],
'L_BASE' => $language['FACTION_BASE'],
'L_CHAR' => $language['FACTION_CHAR'],
'L_CLASS' => $language['FACTION_CLASS'],
'L_RACE' => $language['FACTION_RACE'],
'L_DEITY' => $language['FACTION_DEITY'],
'L_TOTAL' => $language['FACTION_TOTAL'],
'L_DONE' => $language['BUTTON_DONE'])
);
foreach($joined_factions as $faction) {
$charmod = intval($faction['current_value']);
$total = $faction['base'] + $charmod + $faction['classmod'] + $faction['racemod'] + $faction['deitymod'];
$cb_template->assign_both_block_vars("factions", array(
'ID' => $faction['id'],
'LINK' => QuickTemplate($link_faction, array('FACTION_ID' => $faction['id'])),
'NAME' => $faction['name'],
'FACTION' => FactionToString($total),
'BASE' => $faction['base'],
'CHAR' => $charmod,
'CLASS' => $faction['classmod'],
'RACE' => $faction['racemod'],
'DEITY' => $faction['deitymod'],
'TOTAL' => $total)
);
}
/*********************************************
OUTPUT BODY AND FOOTER
*********************************************/
$cb_template->pparse('factions');
$cb_template->destroy;
include(__DIR__ . "/include/footer.php");
?>
| maudigan/charbrowser | factions.php | PHP | gpl-2.0 | 7,654 |
var elixir = require('laravel-elixir');
var gulp = require("gulp");
require('laravel-elixir-wiredep');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
var bowerDir = "public/vendor/";
var lessPaths = [
bowerDir + "bootstrap/less/"
]
var templatePaths = [
"resources/assets/js/app/components/*/*.html",
];
elixir.extend("templates", function(src, base, dest) {
gulp.task("templates", function () {
// the base option sets the relative root for the set of files,
// preserving the folder structure
gulp.src(src, {base: base})
.pipe(gulp.dest(dest));
});
// Watch each glob in src
for (idx in src){
var glob = src[idx];
this.registerWatcher("templates", glob);
}
return this.queueTask("templates");
});
elixir(function(mix) {
// Complile LESS into CSS
mix.less("main.less", "public/css/", {paths: lessPaths});
// Inject dependencies into layout (except bootstrap css, since that is compiled into main css)
mix.wiredep({src: "master.blade.php"}, {exclude: "vendor/bootstrap/dist/css/bootstrap.css"});
// Combine app js into one file
mix.scriptsIn("resources/assets/js/", "public/js/main.js");
// Copy angular templates to public folder
mix.templates(templatePaths, "resources/assets/js/app/components/", "public");
});
| levofski/web-2-cv | gulpfile.js | JavaScript | gpl-2.0 | 1,696 |
package thesis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import termo.component.Compound;
import termo.eos.Cubic;
import termo.eos.EquationsOfState;
import termo.eos.alpha.Alphas;
import termo.matter.Mixture;
import termo.matter.Substance;
import termo.phase.Phase;
import compounds.CompoundReader;
public class CubicFileGenerator extends FileGenerator {
Substance substance;
public CubicFileGenerator(){
CompoundReader reader = new CompoundReader();
Compound heptane = reader.getCompoundByExactName("N-heptane");
substance = new Substance(EquationsOfState.vanDerWaals()
,Alphas.getVanDerWaalsIndependent()
,heptane,Phase.VAPOR);
}
public void cubicEquationPressureVolumeTemperatureFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion Temperatura");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 60;
double pass = (max_volume- min_volume)/n;
int nt =20;
double min_temperature = 150;
double max_temperature = 400;
double tempPass = (max_temperature - min_temperature)/nt;
for(int j = 0; j < nt; j++){
double temperature = min_temperature + tempPass *j ;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure = calculatePressure(volume, temperature);
writer.println(" "+ volume + " " + temperature + " " + pressure);
}
writer.println();
}
writer.close();
}
public double calculatePressure(double volume, double temperature){
return substance.calculatePressure(temperature,volume);
//parametros de van der waals para el heptano
// double a = 3107000.0;
//double b = 0.2049;
// return cubic.calculatePressure(temperature, volume,a,b);
}
public void cubicEquationPressureVolumeFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 100;
double pass = (max_volume- min_volume)/n;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure =calculatePressure(volume, 300);
writer.println(" "+ volume + " " + pressure);
}
writer.close();
}
public void cubicEquationCompresibilitiFactorFiles(String folderName) throws FileNotFoundException, UnsupportedEncodingException{
File directory = new File(folderName);
if(!directory.exists()){
directory.mkdir();
}
Cubic cubic = EquationsOfState.vanDerWaals();
double min_reducedPressure = 0.1;
double max_reducedPressure= 7;
double pressurepass =( max_reducedPressure- min_reducedPressure)/ 100;
double min_reducedTemperature= 1 ;
double max_reducedTemperature=2;
double criticalTemperature = 540.2;
double criticalPressure = 2.74000E+06;
double a = 3107000.0;
double b = 0.2049;
PrintWriter writer= new PrintWriter(folderName + "pz_temp.dat", "UTF-8");
writer.println(" p z rt");
for(double reducedTemperature = min_reducedTemperature; reducedTemperature <= max_reducedTemperature; reducedTemperature +=0.1){
for(double reducedPressure = min_reducedPressure ; reducedPressure <= max_reducedPressure; reducedPressure+= pressurepass){
double temperature = criticalTemperature * reducedTemperature;
double pressure = criticalPressure * reducedPressure;
// double A =cubic.get_A(temperature, pressure, a);
// double B = cubic.get_B(temperature, pressure, b);
substance.setPressure(pressure);
substance.setTemperature(temperature);
double z = substance.calculateCompresibilityFactor();
//double z =cubic.calculateCompresibilityFactor(A, B, Phase.LIQUID);
writer.println(" " + reducedPressure + " " + z + " " + reducedTemperature);
}
writer.println();
}
writer.close();
}
}
| HugoRedon/thesis-examples | src/main/java/thesis/CubicFileGenerator.java | Java | gpl-2.0 | 4,031 |
/*
* FileBrowser.cpp - implementation of the project-, preset- and
* sample-file-browser
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - http://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMenu>
#include <QPushButton>
#include <QMdiArea>
#include <QMdiSubWindow>
#include "FileBrowser.h"
#include "BBTrackContainer.h"
#include "ConfigManager.h"
#include "debug.h"
#include "embed.h"
#include "Engine.h"
#include "gui_templates.h"
#include "ImportFilter.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
#include "MainWindow.h"
#include "DataFile.h"
#include "PresetPreviewPlayHandle.h"
#include "SamplePlayHandle.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "TextFloat.h"
enum TreeWidgetItemTypes
{
TypeFileItem = QTreeWidgetItem::UserType,
TypeDirectoryItem
} ;
FileBrowser::FileBrowser(const QString & directories, const QString & filter,
const QString & title, const QPixmap & pm,
QWidget * parent, bool dirs_as_items ) :
SideBarWidget( title, pm, parent ),
m_directories( directories ),
m_filter( filter ),
m_dirsAsItems( dirs_as_items )
{
setWindowTitle( tr( "Browser" ) );
m_l = new FileBrowserTreeWidget( contentParent() );
addContentWidget( m_l );
QWidget * ops = new QWidget( contentParent() );
ops->setFixedHeight( 24 );
QHBoxLayout * opl = new QHBoxLayout( ops );
opl->setMargin( 0 );
opl->setSpacing( 0 );
m_filterEdit = new QLineEdit( ops );
connect( m_filterEdit, SIGNAL( textEdited( const QString & ) ),
this, SLOT( filterItems( const QString & ) ) );
QPushButton * reload_btn = new QPushButton(
embed::getIconPixmap( "reload" ),
QString::null, ops );
connect( reload_btn, SIGNAL( clicked() ), this, SLOT( reloadTree() ) );
opl->addWidget( m_filterEdit );
opl->addSpacing( 5 );
opl->addWidget( reload_btn );
addContentWidget( ops );
reloadTree();
show();
}
FileBrowser::~FileBrowser()
{
}
void FileBrowser::filterItems( const QString & filter )
{
const bool show_all = filter.isEmpty();
for( int i = 0; i < m_l->topLevelItemCount(); ++i )
{
QTreeWidgetItem * it = m_l->topLevelItem( i );
// show all items if filter is empty
if( show_all )
{
it->setHidden( false );
if( it->childCount() )
{
filterItems( it, filter );
}
}
// is directory?
else if( it->childCount() )
{
// matches filter?
if( it->text( 0 ).
contains( filter, Qt::CaseInsensitive ) )
{
// yes, then show everything below
it->setHidden( false );
filterItems( it, QString::null );
}
else
{
// only show if item below matches filter
it->setHidden( !filterItems( it, filter ) );
}
}
// a standard item (i.e. no file or directory item?)
else if( it->type() == QTreeWidgetItem::Type )
{
// hide in every case when filtering
it->setHidden( true );
}
else
{
// file matches filter?
it->setHidden( !it->text( 0 ).
contains( filter, Qt::CaseInsensitive ) );
}
}
}
bool FileBrowser::filterItems(QTreeWidgetItem * item, const QString & filter )
{
const bool show_all = filter.isEmpty();
bool matched = false;
for( int i = 0; i < item->childCount(); ++i )
{
QTreeWidgetItem * it = item->child( i );
bool cm = false; // whether current item matched
// show all items if filter is empty
if( show_all )
{
it->setHidden( false );
if( it->childCount() )
{
filterItems( it, filter );
}
}
// is directory?
else if( it->childCount() )
{
// matches filter?
if( it->text( 0 ).
contains( filter, Qt::CaseInsensitive ) )
{
// yes, then show everything below
it->setHidden( false );
filterItems( it, QString::null );
cm = true;
}
else
{
// only show if item below matches filter
cm = filterItems( it, filter );
it->setHidden( !cm );
}
}
// a standard item (i.e. no file or directory item?)
else if( it->type() == QTreeWidgetItem::Type )
{
// hide in every case when filtering
it->setHidden( true );
}
else
{
// file matches filter?
cm = it->text( 0 ).
contains( filter, Qt::CaseInsensitive );
it->setHidden( !cm );
}
if( cm )
{
matched = true;
}
}
return matched;
}
void FileBrowser::reloadTree( void )
{
const QString text = m_filterEdit->text();
m_filterEdit->clear();
m_l->clear();
QStringList paths = m_directories.split( '*' );
for( QStringList::iterator it = paths.begin(); it != paths.end(); ++it )
{
addItems( *it );
}
m_filterEdit->setText( text );
filterItems( text );
}
void FileBrowser::addItems(const QString & path )
{
if( m_dirsAsItems )
{
m_l->addTopLevelItem( new Directory( path,
QString::null, m_filter ) );
return;
}
QDir cdir( path );
QStringList files = cdir.entryList( QDir::Dirs, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' )
{
bool orphan = true;
for( int i = 0; i < m_l->topLevelItemCount(); ++i )
{
Directory * d = dynamic_cast<Directory *>(
m_l->topLevelItem( i ) );
if( d == NULL || cur_file < d->text( 0 ) )
{
m_l->insertTopLevelItem( i,
new Directory( cur_file, path,
m_filter ) );
orphan = false;
break;
}
else if( cur_file == d->text( 0 ) )
{
d->addDirectory( path );
orphan = false;
break;
}
}
if( orphan )
{
m_l->addTopLevelItem( new Directory( cur_file,
path, m_filter ) );
}
}
}
files = cdir.entryList( QDir::Files, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' )
{
// TODO: don't insert instead of removing, order changed
// remove existing file-items
QList<QTreeWidgetItem *> existing = m_l->findItems(
cur_file, Qt::MatchFixedString );
if( !existing.empty() )
{
delete existing.front();
}
(void) new FileItem( m_l, cur_file, path );
}
}
}
void FileBrowser::keyPressEvent(QKeyEvent * ke )
{
if( ke->key() == Qt::Key_F5 )
{
reloadTree();
}
else
{
ke->ignore();
}
}
FileBrowserTreeWidget::FileBrowserTreeWidget(QWidget * parent ) :
QTreeWidget( parent ),
m_mousePressed( false ),
m_pressPos(),
m_previewPlayHandle( NULL ),
m_pphMutex( QMutex::Recursive ),
m_contextMenuItem( NULL )
{
setColumnCount( 1 );
headerItem()->setHidden( true );
setSortingEnabled( false );
setFont( pointSizeF( font(), 7.5f ) );
connect( this, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ),
SLOT( activateListItem( QTreeWidgetItem *, int ) ) );
connect( this, SIGNAL( itemCollapsed( QTreeWidgetItem * ) ),
SLOT( updateDirectory( QTreeWidgetItem * ) ) );
connect( this, SIGNAL( itemExpanded( QTreeWidgetItem * ) ),
SLOT( updateDirectory( QTreeWidgetItem * ) ) );
}
FileBrowserTreeWidget::~FileBrowserTreeWidget()
{
}
void FileBrowserTreeWidget::contextMenuEvent(QContextMenuEvent * e )
{
FileItem * f = dynamic_cast<FileItem *>( itemAt( e->pos() ) );
if( f != NULL && ( f->handling() == FileItem::LoadAsPreset ||
f->handling() == FileItem::LoadByPlugin ) )
{
m_contextMenuItem = f;
QMenu contextMenu( this );
contextMenu.addAction( tr( "Send to active instrument-track" ),
this,
SLOT( sendToActiveInstrumentTrack() ) );
contextMenu.addAction( tr( "Open in new instrument-track/"
"Song-Editor" ),
this,
SLOT( openInNewInstrumentTrackSE() ) );
contextMenu.addAction( tr( "Open in new instrument-track/"
"B+B Editor" ),
this,
SLOT( openInNewInstrumentTrackBBE() ) );
contextMenu.exec( e->globalPos() );
m_contextMenuItem = NULL;
}
}
void FileBrowserTreeWidget::mousePressEvent(QMouseEvent * me )
{
QTreeWidget::mousePressEvent( me );
if( me->button() != Qt::LeftButton )
{
return;
}
QTreeWidgetItem * i = itemAt( me->pos() );
if ( i )
{
// TODO: Restrict to visible selection
// if ( _me->x() > header()->cellPos( header()->mapToActual( 0 ) )
// + treeStepSize() * ( i->depth() + ( rootIsDecorated() ?
// 1 : 0 ) ) + itemMargin() ||
// _me->x() < header()->cellPos(
// header()->mapToActual( 0 ) ) )
// {
m_pressPos = me->pos();
m_mousePressed = true;
// }
}
FileItem * f = dynamic_cast<FileItem *>( i );
if( f != NULL )
{
m_pphMutex.lock();
if( m_previewPlayHandle != NULL )
{
Engine::mixer()->removePlayHandle(
m_previewPlayHandle );
m_previewPlayHandle = NULL;
}
// in special case of sample-files we do not care about
// handling() rather than directly creating a SamplePlayHandle
if( f->type() == FileItem::SampleFile )
{
TextFloat * tf = TextFloat::displayMessage(
tr( "Loading sample" ),
tr( "Please wait, loading sample for "
"preview..." ),
embed::getIconPixmap( "sample_file",
24, 24 ), 0 );
qApp->processEvents(
QEventLoop::ExcludeUserInputEvents );
SamplePlayHandle * s = new SamplePlayHandle(
f->fullName() );
s->setDoneMayReturnTrue( false );
m_previewPlayHandle = s;
delete tf;
}
else if( f->type() != FileItem::VstPluginFile &&
( f->handling() == FileItem::LoadAsPreset ||
f->handling() == FileItem::LoadByPlugin ) )
{
m_previewPlayHandle = new PresetPreviewPlayHandle( f->fullName(), f->handling() == FileItem::LoadByPlugin );
}
if( m_previewPlayHandle != NULL )
{
if( !Engine::mixer()->addPlayHandle(
m_previewPlayHandle ) )
{
m_previewPlayHandle = NULL;
}
}
m_pphMutex.unlock();
}
}
void FileBrowserTreeWidget::mouseMoveEvent( QMouseEvent * me )
{
if( m_mousePressed == true &&
( m_pressPos - me->pos() ).manhattanLength() >
QApplication::startDragDistance() )
{
// make sure any playback is stopped
mouseReleaseEvent( NULL );
FileItem * f = dynamic_cast<FileItem *>( itemAt( m_pressPos ) );
if( f != NULL )
{
switch( f->type() )
{
case FileItem::PresetFile:
new StringPairDrag( f->handling() == FileItem::LoadAsPreset ?
"presetfile" : "pluginpresetfile",
f->fullName(),
embed::getIconPixmap( "preset_file" ), this );
break;
case FileItem::SampleFile:
new StringPairDrag( "samplefile", f->fullName(),
embed::getIconPixmap( "sample_file" ), this );
break;
case FileItem::SoundFontFile:
new StringPairDrag( "soundfontfile", f->fullName(),
embed::getIconPixmap( "soundfont_file" ), this );
break;
case FileItem::VstPluginFile:
new StringPairDrag( "vstpluginfile", f->fullName(),
embed::getIconPixmap( "vst_plugin_file" ), this );
break;
case FileItem::MidiFile:
// don't allow dragging FLP-files as FLP import filter clears project
// without asking
// case fileItem::FlpFile:
new StringPairDrag( "importedproject", f->fullName(),
embed::getIconPixmap( "midi_file" ), this );
break;
default:
break;
}
}
}
}
void FileBrowserTreeWidget::mouseReleaseEvent(QMouseEvent * me )
{
m_mousePressed = false;
m_pphMutex.lock();
if( m_previewPlayHandle != NULL )
{
// if there're samples shorter than 3 seconds, we don't
// stop them if the user releases mouse-button...
if( m_previewPlayHandle->type() == PlayHandle::TypeSamplePlayHandle )
{
SamplePlayHandle * s = dynamic_cast<SamplePlayHandle *>(
m_previewPlayHandle );
if( s && s->totalFrames() - s->framesDone() <=
static_cast<f_cnt_t>( Engine::mixer()->
processingSampleRate() * 3 ) )
{
s->setDoneMayReturnTrue( true );
m_previewPlayHandle = NULL;
m_pphMutex.unlock();
return;
}
}
Engine::mixer()->removePlayHandle( m_previewPlayHandle );
m_previewPlayHandle = NULL;
}
m_pphMutex.unlock();
}
void FileBrowserTreeWidget::handleFile(FileItem * f, InstrumentTrack * it )
{
Engine::mixer()->lock();
switch( f->handling() )
{
case FileItem::LoadAsProject:
if( Engine::mainWindow()->mayChangeProject() )
{
Engine::getSong()->loadProject( f->fullName() );
}
break;
case FileItem::LoadByPlugin:
{
const QString e = f->extension();
Instrument * i = it->instrument();
if( i == NULL ||
!i->descriptor()->supportsFileType( e ) )
{
i = it->loadInstrument(
Engine::pluginFileHandling()[e] );
}
i->loadFile( f->fullName() );
break;
}
case FileItem::LoadAsPreset:
{
DataFile dataFile( f->fullName() );
InstrumentTrack::removeMidiPortNode( dataFile );
it->setSimpleSerializing();
it->loadSettings( dataFile.content().toElement() );
break;
}
case FileItem::ImportAsProject:
if( f->type() == FileItem::FlpFile &&
!Engine::mainWindow()->mayChangeProject() )
{
break;
}
ImportFilter::import( f->fullName(),
Engine::getSong() );
break;
case FileItem::NotSupported:
default:
break;
}
Engine::mixer()->unlock();
}
void FileBrowserTreeWidget::activateListItem(QTreeWidgetItem * item,
int column )
{
FileItem * f = dynamic_cast<FileItem *>( item );
if( f == NULL )
{
return;
}
if( f->handling() == FileItem::LoadAsProject ||
f->handling() == FileItem::ImportAsProject )
{
handleFile( f, NULL );
}
else if( f->handling() != FileItem::NotSupported )
{
// engine::mixer()->lock();
InstrumentTrack * it = dynamic_cast<InstrumentTrack *>(
Track::create( Track::InstrumentTrack,
Engine::getBBTrackContainer() ) );
handleFile( f, it );
// engine::mixer()->unlock();
}
}
void FileBrowserTreeWidget::openInNewInstrumentTrack( TrackContainer* tc )
{
if( m_contextMenuItem->handling() == FileItem::LoadAsPreset ||
m_contextMenuItem->handling() == FileItem::LoadByPlugin )
{
// engine::mixer()->lock();
InstrumentTrack * it = dynamic_cast<InstrumentTrack *>(
Track::create( Track::InstrumentTrack, tc ) );
handleFile( m_contextMenuItem, it );
// engine::mixer()->unlock();
}
}
void FileBrowserTreeWidget::openInNewInstrumentTrackBBE( void )
{
openInNewInstrumentTrack( Engine::getBBTrackContainer() );
}
void FileBrowserTreeWidget::openInNewInstrumentTrackSE( void )
{
openInNewInstrumentTrack( Engine::getSong() );
}
void FileBrowserTreeWidget::sendToActiveInstrumentTrack( void )
{
// get all windows opened in the workspace
QList<QMdiSubWindow*> pl =
Engine::mainWindow()->workspace()->
subWindowList( QMdiArea::StackingOrder );
QListIterator<QMdiSubWindow *> w( pl );
w.toBack();
// now we travel through the window-list until we find an
// instrument-track
while( w.hasPrevious() )
{
InstrumentTrackWindow * itw =
dynamic_cast<InstrumentTrackWindow *>(
w.previous()->widget() );
if( itw != NULL && itw->isHidden() == false )
{
handleFile( m_contextMenuItem, itw->model() );
break;
}
}
}
void FileBrowserTreeWidget::updateDirectory(QTreeWidgetItem * item )
{
Directory * dir = dynamic_cast<Directory *>( item );
if( dir != NULL )
{
dir->update();
}
}
QPixmap * Directory::s_folderPixmap = NULL;
QPixmap * Directory::s_folderOpenedPixmap = NULL;
QPixmap * Directory::s_folderLockedPixmap = NULL;
Directory::Directory(const QString & filename, const QString & path,
const QString & filter ) :
QTreeWidgetItem( QStringList( filename ), TypeDirectoryItem ),
m_directories( path ),
m_filter( filter )
{
initPixmaps();
setChildIndicatorPolicy( QTreeWidgetItem::ShowIndicator );
if( !QDir( fullName() ).isReadable() )
{
setIcon( 0, *s_folderLockedPixmap );
}
else
{
setIcon( 0, *s_folderPixmap );
}
}
void Directory::initPixmaps( void )
{
if( s_folderPixmap == NULL )
{
s_folderPixmap = new QPixmap(
embed::getIconPixmap( "folder" ) );
}
if( s_folderOpenedPixmap == NULL )
{
s_folderOpenedPixmap = new QPixmap(
embed::getIconPixmap( "folder_opened" ) );
}
if( s_folderLockedPixmap == NULL )
{
s_folderLockedPixmap = new QPixmap(
embed::getIconPixmap( "folder_locked" ) );
}
}
void Directory::update( void )
{
if( !isExpanded() )
{
setIcon( 0, *s_folderPixmap );
return;
}
setIcon( 0, *s_folderOpenedPixmap );
if( !childCount() )
{
for( QStringList::iterator it = m_directories.begin();
it != m_directories.end(); ++it )
{
int top_index = childCount();
if( addItems( fullName( *it ) ) &&
( *it ).contains(
ConfigManager::inst()->dataDir() ) )
{
QTreeWidgetItem * sep = new QTreeWidgetItem;
sep->setText( 0,
FileBrowserTreeWidget::tr(
"--- Factory files ---" ) );
sep->setIcon( 0, embed::getIconPixmap(
"factory_files" ) );
insertChild( top_index, sep );
}
}
}
}
bool Directory::addItems(const QString & path )
{
QDir thisDir( path );
if( !thisDir.isReadable() )
{
return false;
}
treeWidget()->setUpdatesEnabled( false );
bool added_something = false;
QStringList files = thisDir.entryList( QDir::Dirs, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' )
{
bool orphan = true;
for( int i = 0; i < childCount(); ++i )
{
Directory * d = dynamic_cast<Directory *>(
child( i ) );
if( d == NULL || cur_file < d->text( 0 ) )
{
insertChild( i, new Directory( cur_file,
path, m_filter ) );
orphan = false;
break;
}
else if( cur_file == d->text( 0 ) )
{
d->addDirectory( path );
orphan = false;
break;
}
}
if( orphan )
{
addChild( new Directory( cur_file, path,
m_filter ) );
}
added_something = true;
}
}
QList<QTreeWidgetItem*> items;
files = thisDir.entryList( QDir::Files, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' &&
thisDir.match( m_filter, cur_file.toLower() ) )
{
items << new FileItem( cur_file, path );
added_something = true;
}
}
addChildren( items );
treeWidget()->setUpdatesEnabled( true );
return added_something;
}
QPixmap * FileItem::s_projectFilePixmap = NULL;
QPixmap * FileItem::s_presetFilePixmap = NULL;
QPixmap * FileItem::s_sampleFilePixmap = NULL;
QPixmap * FileItem::s_soundfontFilePixmap = NULL;
QPixmap * FileItem::s_vstPluginFilePixmap = NULL;
QPixmap * FileItem::s_midiFilePixmap = NULL;
QPixmap * FileItem::s_flpFilePixmap = NULL;
QPixmap * FileItem::s_unknownFilePixmap = NULL;
FileItem::FileItem(QTreeWidget * parent, const QString & name,
const QString & path ) :
QTreeWidgetItem( parent, QStringList( name) , TypeFileItem ),
m_path( path )
{
determineFileType();
initPixmaps();
}
FileItem::FileItem(const QString & name, const QString & path ) :
QTreeWidgetItem( QStringList( name ), TypeFileItem ),
m_path( path )
{
determineFileType();
initPixmaps();
}
void FileItem::initPixmaps( void )
{
if( s_projectFilePixmap == NULL )
{
s_projectFilePixmap = new QPixmap( embed::getIconPixmap(
"project_file", 16, 16 ) );
}
if( s_presetFilePixmap == NULL )
{
s_presetFilePixmap = new QPixmap( embed::getIconPixmap(
"preset_file", 16, 16 ) );
}
if( s_sampleFilePixmap == NULL )
{
s_sampleFilePixmap = new QPixmap( embed::getIconPixmap(
"sample_file", 16, 16 ) );
}
if ( s_soundfontFilePixmap == NULL )
{
s_soundfontFilePixmap = new QPixmap( embed::getIconPixmap(
"soundfont_file", 16, 16 ) );
}
if ( s_vstPluginFilePixmap == NULL )
{
s_vstPluginFilePixmap = new QPixmap( embed::getIconPixmap(
"vst_plugin_file", 16, 16 ) );
}
if( s_midiFilePixmap == NULL )
{
s_midiFilePixmap = new QPixmap( embed::getIconPixmap(
"midi_file", 16, 16 ) );
}
if( s_flpFilePixmap == NULL )
{
s_flpFilePixmap = new QPixmap( embed::getIconPixmap(
"midi_file", 16, 16 ) );
}
if( s_unknownFilePixmap == NULL )
{
s_unknownFilePixmap = new QPixmap( embed::getIconPixmap(
"unknown_file" ) );
}
switch( m_type )
{
case ProjectFile:
setIcon( 0, *s_projectFilePixmap );
break;
case PresetFile:
setIcon( 0, *s_presetFilePixmap );
break;
case SoundFontFile:
setIcon( 0, *s_soundfontFilePixmap );
break;
case VstPluginFile:
setIcon( 0, *s_vstPluginFilePixmap );
break;
case SampleFile:
case PatchFile: // TODO
setIcon( 0, *s_sampleFilePixmap );
break;
case MidiFile:
setIcon( 0, *s_midiFilePixmap );
break;
case FlpFile:
setIcon( 0, *s_flpFilePixmap );
break;
case UnknownFile:
default:
setIcon( 0, *s_unknownFilePixmap );
break;
}
}
void FileItem::determineFileType( void )
{
m_handling = NotSupported;
const QString ext = extension();
if( ext == "mmp" || ext == "mpt" || ext == "mmpz" )
{
m_type = ProjectFile;
m_handling = LoadAsProject;
}
else if( ext == "xpf" || ext == "xml" )
{
m_type = PresetFile;
m_handling = LoadAsPreset;
}
else if( ext == "xiz" && Engine::pluginFileHandling().contains( ext ) )
{
m_type = PresetFile;
m_handling = LoadByPlugin;
}
else if( ext == "sf2" )
{
m_type = SoundFontFile;
}
else if( ext == "pat" )
{
m_type = PatchFile;
}
else if( ext == "mid" )
{
m_type = MidiFile;
m_handling = ImportAsProject;
}
else if( ext == "flp" )
{
m_type = FlpFile;
m_handling = ImportAsProject;
}
else if( ext == "dll" )
{
m_type = VstPluginFile;
m_handling = LoadByPlugin;
}
else
{
m_type = UnknownFile;
}
if( m_handling == NotSupported &&
!ext.isEmpty() && Engine::pluginFileHandling().contains( ext ) )
{
m_handling = LoadByPlugin;
// classify as sample if not classified by anything yet but can
// be handled by a certain plugin
if( m_type == UnknownFile )
{
m_type = SampleFile;
}
}
}
QString FileItem::extension( void )
{
return extension( fullName() );
}
QString FileItem::extension(const QString & file )
{
return QFileInfo( file ).suffix().toLower();
}
| badosu/lmms | src/gui/FileBrowser.cpp | C++ | gpl-2.0 | 22,711 |
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 12:20:59 2013
=== MAYAXES (v1.1) ===
Generates a set of MayaVI axes using the mayavi.mlab.axes() object with a
white background, small black text and a centred title. Designed to better
mimic MATLAB style plots.
Unspecified arguments will be set to default values when mayaxes is called
(note that default settings are configured for a figure measuring 1024 x 768
pixels and may not display correctly on plots that are significantly larger
or smaller).
=== Inputs ===
'title' Figure title text (default = 'VOID')
'xlabel' X axis label text (default = 'X')
'ylabel' Y axis label text (default = 'Y')
'zlabel' Z axis label text (default = 'Z')
'handle' Graphics handle of object (if bounding box is to be plotted)
'title_size' Font size of the title text (default = 25)
'ticks' Number of divisions on each axis (default = 7)
'font_scaling' Font scaling factor for axis text (default = 0.7)
'background' Background colour (can be 'b' (black) or 'w' (white))
=== Notes ===
Disbaling figure title: specify title_string='void' OR title_string='Void' OR
title_string='VOID' to disable figure title.
Disabling bounding box: specify handle='void' OR handle='Void' OR handle='VOID'
to disable figure bounding box.
=== Usage ===
from mayaxes import mayaxes
mayaxes('Figure title','X axis label','Y axis label','Z axis label')
OR
mayaxes(title_string='TITLE',xlabel='X',ylabel='Y',zlabel='Z',title_size=25,ticks=7,font_scaling=0.7)
=== Example ===
from mayaxes import test_mayaxes
test_mayaxes()
@author: Nathan Donaldson
"""
def mayaxes(title_string='VOID', xlabel='VOID', ylabel='VOID', zlabel='VOID', handle='VOID', \
title_size=25, ticks=7, font_scaling=0.7, background='w'):
if type(title_string) != str or type(xlabel) != str or type(ylabel) != str or type(zlabel) != str:
print('ERROR: label inputs must all be strings')
return
elif type(ticks) != int:
print('ERROR: number of ticks must be an integer')
return
elif type(font_scaling) != float and type(font_scaling) != int:
print('Error: font scaling factor must be an integer or a float')
return
from mayavi.mlab import axes,title,gcf,outline
# Create axes object
ax = axes()
# Font factor globally adjusts figure text size
ax.axes.font_factor = font_scaling
# Number of ticks along each axis
ax.axes.number_of_labels = ticks
# Set axis labels to input strings
# (spaces are included for padding so that labels do not intersect with axes)
if xlabel=='void' or xlabel=='Void' or xlabel=='VOID':
print 'X axis label title disabled'
else:
ax.axes.x_label = ' ' + xlabel
if ylabel=='void' or ylabel=='Void' or ylabel=='VOID':
print 'Y axis label disabled'
else:
ax.axes.y_label = ylabel + ' '
if zlabel=='void' or zlabel=='Void' or zlabel=='VOID':
print 'Z axis label disabled'
else:
ax.axes.z_label = zlabel + ' '
# Create figure title
if title_string=='void' or title_string=='Void' or title_string=='VOID':
print 'Figure title disabled'
else:
text_title = title(title_string)
text_title.x_position = 0.5
text_title.y_position = 0.9
text_title.property.color = (0.0, 0.0, 0.0)
text_title.actor.text_scale_mode = 'none'
text_title.property.font_size = title_size
text_title.property.justification = 'centered'
# Create bounding box
if handle=='void' or handle=='Void' or handle=='VOID':
print 'Bounding box disabled'
else:
if background == 'w':
bounding_box = outline(handle, color=(0.0, 0.0, 0.0), opacity=0.2)
elif background == 'b':
bounding_box = outline(handle, color=(1.0, 1.0, 1.0), opacity=0.2)
# Set axis, labels and titles to neat black text
#ax.property.color = (0.0, 0.0, 0.0)
#ax.title_text_property.color = (0.0, 0.0, 0.0)
#ax.label_text_property.color = (0.0, 0.0, 0.0)
ax.label_text_property.bold = False
ax.label_text_property.italic = False
ax.title_text_property.italic = False
ax.title_text_property.bold = False
# Reset axis range
ax.axes.use_ranges = True
# Set scene background, axis and text colours
fig = gcf()
if background == 'w':
fig.scene.background = (1.0, 1.0, 1.0)
ax.label_text_property.color = (0.0, 0.0, 0.0)
ax.property.color = (0.0, 0.0, 0.0)
ax.title_text_property.color = (0.0, 0.0, 0.0)
elif background == 'b':
fig.scene.background = (0.0, 0.0, 0.0)
ax.label_text_property.color = (1.0, 1.0, 1.0)
ax.property.color = (1.0, 1.0, 1.0)
ax.title_text_property.color = (1.0, 1.0, 1.0)
fig.scene.parallel_projection = True
def test_mayaxes():
from mayaxes import mayaxes
from scipy import sqrt,sin,meshgrid,linspace,pi
import mayavi.mlab as mlab
resolution = 200
lambda_var = 3
theta = linspace(-lambda_var*2*pi,lambda_var*2*pi,resolution)
x, y = meshgrid(theta, theta)
r = sqrt(x**2 + y**2)
z = sin(r)/r
fig = mlab.figure(size=(1024,768))
surf = mlab.surf(theta,theta,z,colormap='jet',opacity=1.0,warp_scale='auto')
mayaxes(title_string='Figure 1: Diminishing polar cosine series', \
xlabel='X data',ylabel='Y data',zlabel='Z data',handle=surf)
fig.scene.camera.position = [435.4093863309094, 434.1268937227623, 315.90311468125287]
fig.scene.camera.focal_point = [94.434632665253829, 93.152140057106593, -25.071638984402856]
fig.scene.camera.view_angle = 30.0
fig.scene.camera.view_up = [0.0, 0.0, 1.0]
fig.scene.camera.clipping_range = [287.45231734040635, 973.59247058049255]
fig.scene.camera.compute_view_plane_normal()
fig.scene.render()
mlab.show()
| Nate28/mayaxes | mayaxes.py | Python | gpl-2.0 | 6,007 |
/*
This file is a part of the Depecher (Telegram client)
Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <QGuiApplication>
#include <QQuickView>
#include <sailfishapp.h>
int main(int argc, char *argv[])
{
QScopedPointer<QGuiApplication> application(SailfishApp::application(argc, argv));
application->setApplicationName(QStringLiteral("depecher"));
application->setApplicationDisplayName(QStringLiteral("Depecher"));
QScopedPointer<QQuickView> view(SailfishApp::createView());
view->setSource(SailfishApp::pathTo(QStringLiteral("qml/main.qml")));
view->setTitle(application->applicationDisplayName());
view->setResizeMode(QQuickView::SizeRootObjectToView);
view->show();
return application->exec();
}
| depecher/depecher | main.cpp | C++ | gpl-2.0 | 1,505 |
<?php
/**
* @version 1.0.0
* @package com_farmapp
* @copyright Copyright (C) 2012. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Created by com_combuilder - http://www.notwebdesign.com
*/
// No direct access.
defined('_JEXEC') or die;
/**
* Items list controller class.
*/
class CropsControllerFarmapp extends FarmappController
{
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
parent::__construct($config);
}
function display()
{
$model=$this->getModel('crops');
$items=$model->getItems();
$pagination = $model->getPagination();
$state = $model->getState();
$view=$this->getView('crops','html');
$view->assign('items',$items);
$view->assign('pagination',$pagination);
$view->assign('state',$state);
$view->display();
}
function edit()
{
$id = JRequest::getVar('cid','0');
$model=$this->getModel('crop');
// get the Data
$item = $model->getItem($id[0]);
$form = $model->getForm($id[0]);
$view=$this->getView('crop','html');
$view->assign('form',$form);
$view->assign('item',$item);
$view->setLayout('edit');
$view->display();
}
/*
* Method for save data from farm-form......
*
*/
function save()
{
$task = $this->getTask();
$data=JRequest::get('post');
$bed_ids = $data['bed_id'];
$bed_id = implode(',',$bed_ids);
$data['bed_id'] = $bed_id;
$model=$this->getModel('crop');
$id=$model->save($data);
if($id!=='')
{
switch ( $task )
{
case 'save2new':
$link = 'index.php?option=com_farmapp&view=crops&task=add';
$this->setRedirect($link, $msg);
break;
case 'save':
$msg = JText::_( 'Crop save successfully' );
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
break;
case 'apply':
$msg = JText::_( 'Crop save successfully' );
$link = 'index.php?option=com_farmapp&view=crops&task=edit&cid[]='.$id;
$this->setRedirect($link, $msg);
break;
}
}
}
/*
* Method for deleting single/multiple crops......
*
*/
function delete()
{
$model = $this->getModel('crops');
if(!$model->delete()) {
$msg = JText::_( 'Error: One or More crop Could not be Deleted' );
}else{
$msg = JText::_( 'crop(s) Deleted' );
}
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
}
/*
* Method for publish single/multiple farms......
*
*/
function multiplepublish()
{
$model = $this->getModel('crops');
if(!$model->multiplepublish()) {
$msg = JText::_( 'Error: One or More crops Could not be published' );
} else {
$msg = JText::_( 'crop(s) Published.' );
}
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
}
/*
* Method for unpublish single/multiple farms......
*
*/
function multipleunpublish()
{
$model = $this->getModel('crops');
if(!$model->multipleunpublish()){
$msg = JText::_( 'Error: One or More crop Could not be unpublished' );
}else{
$msg = JText::_( 'crop(s) UnPublished.' );
}
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
}
/*method single row publish and unpublish on click on tick mark*/
function publish(){
// Initialise variables.
$ids = JRequest::getVar('cid', array(), '', 'array');
$values = array('publish' => 1, 'unpublish' => 0);
$task = $this->getTask();
$value = JArrayHelper::getValue($values, $task, 0, 'int');
if (empty($ids)) {
JError::raiseWarning(500, JText::_('JERROR_NO_ITEMS_SELECTED'));
}
else {
// Get the model.
$model = $this->getModel('crops');
// Publish the items.
if (!$model->publish($ids, $value)) {
JError::raiseWarning(500, $model->getError());
}
}
$this->setRedirect('index.php?option=com_farmapp&view=crops');
}
/*
*
* Method to get the beds according to the farm/zones........
*/
function findbeds()
{
$model=$this->getModel('crops');
$farmzoneid = JRequest::getVar('val');
$cropid = JRequest::getVar('cropid');
$bedslist = $model->getbedslist($farmzoneid, $cropid);
echo $bedslist;
}
}
| yogendra9891/farmapplication | administrator/components/com_farmapp/controllers/crops.php | PHP | gpl-2.0 | 4,429 |
<?php
namespace Drupal\search_api_autocomplete\Suggestion;
use Drupal\Core\Render\RenderableInterface;
/**
* Defines a single autocompletion suggestion.
*/
interface SuggestionInterface extends RenderableInterface {
/**
* Retrieves the keywords this suggestion will autocomplete to.
*
* @return string|null
* The suggested keywords, or NULL if the suggestion should direct to a URL
* instead.
*/
public function getSuggestedKeys();
/**
* Retrieves the URL to which the suggestion should redirect.
*
* A URL to which the suggestion should redirect instead of completing the
* user input in the text field. This overrides the normal behavior and thus
* makes the suggested keys obsolete.
*
* @return \Drupal\Core\Url|null
* The URL to which the suggestion should redirect to, or NULL if none was
* set.
*/
public function getUrl();
/**
* Retrieves the prefix for the suggestion.
*
* For special kinds of suggestions, this will contain some kind of prefix
* describing them.
*
* @return string|null
* The prefix, if set.
*/
public function getPrefix();
/**
* Retrieves the label to use for the suggestion.
*
* Should only be used if the other fields that will be displayed (suggestion
* prefix/suffix and user input) are empty.
*
* @return string
* The suggestion's label.
*/
public function getLabel();
/**
* Retrieves the prefix suggested for the entered keys.
*
* @return string|null
* The suggested prefix, if any.
*/
public function getSuggestionPrefix();
/**
* The input entered by the user, if it should be included in the label.
*
* @return string|null
* The input provided by the user.
*/
public function getUserInput();
/**
* A suggested suffix for the entered input.
*
* @return string|null
* A suffix.
*/
public function getSuggestionSuffix();
/**
* Returns the estimated number of results for this suggestion.
*
* @return int|null
* The estimated number of results, or NULL if no estimate is available.
*/
public function getResultsCount();
/**
* Returns the render array set for this suggestion.
*
* This should be displayed to the user for this suggestion. If missing, the
* suggestion is instead rendered with the
* "search_api_autocomplete_suggestion" theme.
*
* @return array|null
* A renderable array of the suggestion results, or NULL if none was set.
*/
public function getRender();
/**
* Sets the keys.
*
* @param string|null $keys
* The keys.
*
* @return $this
*/
public function setSuggestedKeys($keys);
/**
* Sets the URL.
*
* @param \Drupal\Core\Url|null $url
* The URL.
*
* @return $this
*/
public function setUrl($url);
/**
* Sets the prefix.
*
* @param string|null $prefix
* The prefix.
*
* @return $this
*/
public function setPrefix($prefix);
/**
* Sets the label.
*
* @param string|null $label
* The new label.
*
* @return $this
*/
public function setLabel($label);
/**
* Sets the suggestion prefix.
*
* @param string|null $suggestion_prefix
* The suggestion prefix.
*
* @return $this
*/
public function setSuggestionPrefix($suggestion_prefix);
/**
* Sets the user input.
*
* @param string|null $user_input
* The user input.
*
* @return $this
*/
public function setUserInput($user_input);
/**
* Sets the suggestion suffix.
*
* @param string|null $suggestion_suffix
* The suggestion suffix.
*
* @return $this
*/
public function setSuggestionSuffix($suggestion_suffix);
/**
* Sets the result count.
*
* @param string|null $results
* The result count.
*
* @return $this
*/
public function setResultsCount($results);
/**
* Sets the render array.
*
* @param array|null $render
* The render array.
*
* @return $this
*/
public function setRender($render);
}
| NickGH/agronomia | web/modules/contrib/search_api_autocomplete/src/Suggestion/SuggestionInterface.php | PHP | gpl-2.0 | 4,087 |
<?php
/**
* @package FrameworkOnFramework
* @subpackage database
* @copyright Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*
* This file is adapted from the Joomla! Platform. It is used to iterate a database cursor returning FOFTable objects
* instead of plain stdClass objects
*/
// Protect from unauthorized access
defined('FOF_INCLUDED') or die;
/**
* Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 3.4
*/
class FOFDatabaseQueryPdomysql extends FOFDatabaseQueryMysqli
{
}
| alessandrorusso/Furia | libraries/fof/database/query/pdomysql.php | PHP | gpl-2.0 | 687 |
package sergio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.GregorianCalendar;
//Ejercicio Metodos 18
//Realiza una clase llamada milibreria que contenga al menos cinco de los metodos realizados.
//Usalas de 3 formas diferentes
//Autor: Sergio Tobal
//Fecha: 12-02-2012
public class EjerMetods18 {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in));
int numsend=10,edad;
char nombre;
boolean nombreceive;
String msgname = null;
System.out.println("Dame tu inicial:");
nombre=lectura.readLine().charAt(0);
nombreceive=EsMayus(nombre);
if (nombreceive==true) {
msgname="MAYUSCULAS";
} else if (nombreceive==false) {
msgname="minusculas";
}
EsPerfecto(numsend);
System.out.println("Tu primer numero perfecto es "+numsend+" porque tienes "+(edad=ObtenerEdad())+" años, y tu inicial esta escrita en "+msgname);
}
private static boolean EsPerfecto(int numsend) {
int perfect=0;
for (int i = 1; i < numsend; i++) {
if (numsend % i == 0) {
perfect += i;
}
}
if (perfect == numsend) {
return true;
}else {
return false;
}
}
private static int ObtenerEdad()throws NumberFormatException, IOException{
BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in));
int year,month,day;
System.out.println("Dime tu dia de nacimiento: ");
day=Integer.parseInt(lectura.readLine());
System.out.println("Dime tu mes de nacimiento: ");
month=Integer.parseInt(lectura.readLine());
System.out.println("Dime tu año de nacimiento: ");
year=Integer.parseInt(lectura.readLine());
Calendar cal = new GregorianCalendar(year, month, day);
Calendar now = new GregorianCalendar();
int edad = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH)) || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
edad--;
}
return edad;
}
private static int Factorial(int num) {
int factorial=1;
// Va multiplicando el numero del usuario por 1 hasta que el numero llega ha cero y retorna
// la multiplicacion de todos los numeros
while (num!=0) {
factorial=factorial*num;
num--;
}
return factorial;
}
private static boolean ValFecha(int day, int month) {
if ((day>=1 && day<=31) && (month>=1 && month<=12)) {
return true;
}else {
return false;
}
}
private static boolean EsMayus(char nombre) {
boolean opt=true;
// La funcion isUpperCase comprueba que el contenido de num sea mayuscula
if (Character.isUpperCase(nombre) == true) {
opt=true;
// La funcion isLowerCase comprueba que el contenido de num sea minuscula
} else if(Character.isLowerCase(nombre) == true){
opt=false;
}
return opt;
}
}
| set92/Small-Programs | Java/CFGS/Interfaces-Ejercicios/Ejercicios propuestos de metodos/sergio/EjerMetods18.java | Java | gpl-2.0 | 3,147 |
#region
using System.Collections.Generic;
using System.Data;
using Albian.Persistence.Model;
#endregion
namespace Albian.Persistence.Context
{
public interface IStorageContext
{
string StorageName { get; set; }
IList<IFakeCommandAttribute> FakeCommand { get; set; }
IDbConnection Connection { get; set; }
IDbTransaction Transaction { get; set; }
IList<IDbCommand> Command { get; set; }
IStorageAttribute Storage { get; set; }
}
} | xvhfeng/albian | Albian.Persistence/Context/IStorageContext.cs | C# | gpl-2.0 | 514 |
/**
* $Id$
* Copyright (C) 2008 - 2014 Nils Asmussen
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <esc/proto/socket.h>
#include <esc/stream/fstream.h>
#include <esc/stream/istringstream.h>
#include <esc/stream/ostream.h>
#include <esc/dns.h>
#include <sys/common.h>
#include <sys/endian.h>
#include <sys/proc.h>
#include <sys/thread.h>
#include <signal.h>
namespace esc {
/* based on http://tools.ietf.org/html/rfc1035 */
#define DNS_RECURSION_DESIRED 0x100
#define DNS_PORT 53
#define BUF_SIZE 512
uint16_t DNS::_nextId = 0;
esc::Net::IPv4Addr DNS::_nameserver;
enum Type {
TYPE_A = 1, /* a host address */
TYPE_NS = 2, /* an authoritative name server */
TYPE_CNAME = 5, /* the canonical name for an alias */
TYPE_HINFO = 13, /* host information */
TYPE_MX = 15, /* mail exchange */
};
enum Class {
CLASS_IN = 1 /* the Internet */
};
struct DNSHeader {
uint16_t id;
uint16_t flags;
uint16_t qdCount;
uint16_t anCount;
uint16_t nsCount;
uint16_t arCount;
} A_PACKED;
struct DNSQuestionEnd {
uint16_t type;
uint16_t cls;
} A_PACKED;
struct DNSAnswer {
uint16_t name;
uint16_t type;
uint16_t cls;
uint32_t ttl;
uint16_t length;
} A_PACKED;
esc::Net::IPv4Addr DNS::getHost(const char *name,uint timeout) {
if(isIPAddress(name)) {
esc::Net::IPv4Addr addr;
IStringStream is(name);
is >> addr;
return addr;
}
return resolve(name,timeout);
}
bool DNS::isIPAddress(const char *name) {
int dots = 0;
int len = 0;
// ignore whitespace at the beginning
while(isspace(*name))
name++;
while(dots < 4 && len < 4 && *name) {
if(*name == '.') {
dots++;
len = 0;
}
else if(isdigit(*name))
len++;
else
break;
name++;
}
// ignore whitespace at the end
while(isspace(*name))
name++;
return dots == 3 && len > 0 && len < 4;
}
esc::Net::IPv4Addr DNS::resolve(const char *name,uint timeout) {
uint8_t buffer[BUF_SIZE];
if(_nameserver.value() == 0) {
FStream in(getResolveFile(),"r");
in >> _nameserver;
if(_nameserver.value() == 0)
VTHROWE("No nameserver",-EHOSTNOTFOUND);
}
size_t nameLen = strlen(name);
size_t total = sizeof(DNSHeader) + nameLen + 2 + sizeof(DNSQuestionEnd);
if(total > sizeof(buffer))
VTHROWE("Hostname too long",-EINVAL);
// generate a unique
uint16_t txid = (getpid() << 16) | _nextId;
// build DNS request message
DNSHeader *h = reinterpret_cast<DNSHeader*>(buffer);
h->id = cputobe16(txid);
h->flags = cputobe16(DNS_RECURSION_DESIRED);
h->qdCount = cputobe16(1);
h->anCount = 0;
h->nsCount = 0;
h->arCount = 0;
convertHostname(reinterpret_cast<char*>(h + 1),name,nameLen);
DNSQuestionEnd *qend = reinterpret_cast<DNSQuestionEnd*>(buffer + sizeof(*h) + nameLen + 2);
qend->type = cputobe16(TYPE_A);
qend->cls = cputobe16(CLASS_IN);
// create socket
esc::Socket sock(esc::Socket::SOCK_DGRAM,esc::Socket::PROTO_UDP);
// send over socket
esc::Socket::Addr addr;
addr.family = esc::Socket::AF_INET;
addr.d.ipv4.addr = _nameserver.value();
addr.d.ipv4.port = DNS_PORT;
sock.sendto(addr,buffer,total);
sighandler_t oldhandler;
if((oldhandler = signal(SIGALRM,sigalarm)) == SIG_ERR)
VTHROW("Unable to set SIGALRM handler");
int res;
if((res = ualarm(timeout * 1000)) < 0)
VTHROWE("ualarm(" << (timeout * 1000) << ")",res);
try {
// receive response
sock.recvfrom(addr,buffer,sizeof(buffer));
}
catch(const esc::default_error &e) {
if(e.error() == -EINTR)
VTHROWE("Received no response from DNS server " << _nameserver,-ETIMEOUT);
// ignore errors here
if(signal(SIGALRM,oldhandler) == SIG_ERR) {}
throw;
}
// ignore errors here
if(signal(SIGALRM,oldhandler) == SIG_ERR) {}
if(be16tocpu(h->id) != txid)
VTHROWE("Received DNS response with wrong transaction id",-EHOSTNOTFOUND);
int questions = be16tocpu(h->qdCount);
int answers = be16tocpu(h->anCount);
// skip questions
uint8_t *data = reinterpret_cast<uint8_t*>(h + 1);
for(int i = 0; i < questions; ++i) {
size_t len = questionLength(data);
data += len + sizeof(DNSQuestionEnd);
}
// parse answers
for(int i = 0; i < answers; ++i) {
DNSAnswer *ans = reinterpret_cast<DNSAnswer*>(data);
if(be16tocpu(ans->type) == TYPE_A && be16tocpu(ans->length) == esc::Net::IPv4Addr::LEN)
return esc::Net::IPv4Addr(data + sizeof(DNSAnswer));
}
VTHROWE("Unable to find IP address in DNS response",-EHOSTNOTFOUND);
}
void DNS::convertHostname(char *dst,const char *src,size_t len) {
// leave one byte space for the length of the first part
const char *from = src + len++;
char *to = dst + len;
// we start with the \0 at the end
int partLen = -1;
for(size_t i = 0; i < len; i++, to--, from--) {
if(*from == '.') {
*to = partLen;
partLen = 0;
}
else {
*to = *from;
partLen++;
}
}
*to = partLen;
}
size_t DNS::questionLength(const uint8_t *data) {
size_t total = 0;
while(*data != 0) {
uint8_t len = *data;
// skip this name-part
total += len + 1;
data += len + 1;
}
// skip zero ending, too
return total + 1;
}
}
| Nils-TUD/Escape | source/lib/esc/dns.cc | C++ | gpl-2.0 | 5,678 |
<?php /* included from WPML_Translation_Management::icl_dashboard_widget_content */?>
<p><?php if ($docs_sent)
printf(__('%d documents sent to translation.<br />%d are complete, %d waiting for translation.', 'wpml-translation-management'),
$docs_sent, $docs_completed, $docs_waiting); ?></p>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php" class="button secondary"><strong><?php
_e('Translate content', 'wpml-translation-management'); ?></strong></a></p>
<?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?>
<h5 style="margin: 15px 0 0 0;"><?php _e('Need translation work?', 'wpml-translation-management'); ?></h5>
<p><?php printf(__('%s offers affordable professional translation via a streamlined process.','wpml-translation-management'),
'<a target="_blank" href="http://www.icanlocalize.com/site/">ICanLocalize</a>') ?></p>
<p><a href="<?php echo admin_url('index.php?icl_ajx_action=quote-get'); ?>" class="button secondary thickbox"><strong><?php
_e('Get quote','wpml-translation-management') ?></strong></a>
<a href="admin.php?page=<?php echo WPML_TM_FOLDER;
?>/menu/main.php&sm=translators&service=icanlocalize" class="button secondary"><strong><?php
_e('Get translators','wpml-translation-management') ?></strong></a>
</p>
<?php endif;?>
<?php
// shows only when translation polling is on and there are translations in progress
$ICL_Pro_Translation->get_icl_manually_tranlations_box('icl_cyan_box');
?>
<?php if (count($active_languages = $sitepress->get_active_languages()) > 1): ?>
<div><a href="javascript:void(0)" onclick="jQuery(this).parent().next('.wrapper').slideToggle();"
style="display:block; padding:5px; border: 1px solid #eee; margin-bottom:2px; background-color: #F7F7F7;"><?php
_e('Content translation', 'wpml-translation-management') ?></a>
</div>
<div class="wrapper" style="display:none; padding: 5px 10px; border: 1px solid #eee; border-top: 0px; margin:-11px 0 2px 0;">
<?php
$your_translators = TranslationManagement::get_blog_translators();
$other_service_translators = TranslationManagement::icanlocalize_translators_list();
if (!empty($your_translators) || !empty($other_service_translators)) {
echo '<p><strong>' . __('Your translators', 'wpml-translation-management') . '</strong></p><ul>';
if (!empty($your_translators))
foreach ($your_translators as $your_translator) {
echo '<li>';
if ($current_user->ID == $your_translator->ID) {
$edit_link = 'profile.php';
} else {
$edit_link = esc_url(add_query_arg('wp_http_referer', urlencode(esc_url(stripslashes($_SERVER['REQUEST_URI']))), "user-edit.php?user_id=$your_translator->ID"));
}
echo '<a href="' . $edit_link . '"><strong>' . $your_translator->display_name . '</strong></a> - ';
foreach ($your_translator->language_pairs as $from => $lp) {
$tos = array();
foreach ($lp as $to => $null) {
$tos[] = $active_languages[$to]['display_name'];
}
printf(__('%s to %s', 'wpml-translation-management'), $active_languages[$from]['display_name'], join(', ', $tos));
}
echo '</li>';
}
if (!empty($other_service_translators)){
$langs = $sitepress->get_active_languages();
foreach ($other_service_translators as $rows){
foreach($rows['langs'] as $from => $lp){
$from = isset($langs[$from]['display_name']) ? $langs[$from]['display_name'] : $from;
$tos = array();
foreach($lp as $to){
$tos[] = isset($langs[$to]['display_name']) ? $langs[$to]['display_name'] : $to;
}
}
echo '<li>';
echo '<strong>' . $rows['name'] . '</strong> | ' .
sprintf(__('%s to %s', 'wpml-translation-management'), $from, join(', ', $tos)) . ' | ' . $rows['action'];
echo '</li>';
}
}
echo '</ul><hr />';
}
?>
<?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&sm=translators&service=icanlocalize"><strong><?php _e('Add translators from ICanLocalize »', 'wpml-translation-management'); ?></strong></a></p>
<?php endif; ?>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&sm=translators&service=local"><strong><?php _e('Add your own translators »', 'wpml-translation-management'); ?></strong></a></p>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php"><strong><?php _e('Translate contents »', 'wpml-translation-management'); ?></strong></a></p>
</div>
<?php endif; ?> | ilfungo/stefanopierini | wp-content/plugins/wpml-translation-management/menu/_icl_dashboard_widget.php | PHP | gpl-2.0 | 5,985 |
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <cstring>
#include "../../Port.h"
#include "../../NLS.h"
#include "../GBA.h"
#include "../GBAGlobals.h"
#include "../GBAinline.h"
#include "../GBACheats.h"
#include "GBACpu.h"
#include "../GBAGfx.h"
#include "../GBASound.h"
#include "../EEprom.h"
#include "../Flash.h"
#include "../Sram.h"
#include "../bios.h"
#include "../elf.h"
#include "../RTC.h"
#include "../agbprint.h"
#include "../../common/System.h"
#include "../../common/SystemGlobals.h"
#include "../../common/Util.h"
#include "../../common/movie.h"
#include "../../common/vbalua.h"
#ifdef PROFILING
#include "../prof/prof.h"
#endif
#ifdef __GNUC__
#define _stricmp strcasecmp
#endif
static inline void interp_rate()
{ /* empty for now */ }
int32 SWITicks = 0;
int32 IRQTicks = 0;
u32 mastercode = 0;
int32 layerEnableDelay = 0;
bool8 busPrefetch = false;
bool8 busPrefetchEnable = false;
u32 busPrefetchCount = 0;
u32 cpuPrefetch[2];
int32 cpuDmaTicksToUpdate = 0;
int32 cpuDmaCount = 0;
bool8 cpuDmaHack = 0;
u32 cpuDmaLast = 0;
int32 dummyAddress = 0;
int32 gbaSaveType = 0; // used to remember the save type on reset
bool8 intState = false;
bool8 stopState = false;
bool8 holdState = false;
int32 holdType = 0;
bool8 cpuSramEnabled = true;
bool8 cpuFlashEnabled = true;
bool8 cpuEEPROMEnabled = true;
bool8 cpuEEPROMSensorEnabled = false;
#ifdef SDL
bool8 cpuBreakLoop = false;
#endif
// These don't seem to affect determinism
int32 cpuNextEvent = 0;
int32 cpuTotalTicks = 0;
#ifdef PROFILING
int profilingTicks = 0;
int profilingTicksReload = 0;
static profile_segment *profilSegment = NULL;
#endif
#ifdef BKPT_SUPPORT
u8 freezeWorkRAM[0x40000];
u8 freezeInternalRAM[0x8000];
u8 freezeVRAM[0x18000];
u8 freezePRAM[0x400];
u8 freezeOAM[0x400];
bool debugger_last;
#endif
int32 lcdTicks = (useBios && !skipBios) ? 1008 : 208;
u8 timerOnOffDelay = 0;
u16 timer0Value = 0;
bool8 timer0On = false;
int32 timer0Ticks = 0;
int32 timer0Reload = 0;
int32 timer0ClockReload = 0;
u16 timer1Value = 0;
bool8 timer1On = false;
int32 timer1Ticks = 0;
int32 timer1Reload = 0;
int32 timer1ClockReload = 0;
u16 timer2Value = 0;
bool8 timer2On = false;
int32 timer2Ticks = 0;
int32 timer2Reload = 0;
int32 timer2ClockReload = 0;
u16 timer3Value = 0;
bool8 timer3On = false;
int32 timer3Ticks = 0;
int32 timer3Reload = 0;
int32 timer3ClockReload = 0;
u32 dma0Source = 0;
u32 dma0Dest = 0;
u32 dma1Source = 0;
u32 dma1Dest = 0;
u32 dma2Source = 0;
u32 dma2Dest = 0;
u32 dma3Source = 0;
u32 dma3Dest = 0;
void (*cpuSaveGameFunc)(u32, u8) = flashSaveDecide;
void (*renderLine)() = mode0RenderLine;
bool8 fxOn = false;
bool8 windowOn = false;
char buffer[1024];
FILE *out = NULL;
const int32 TIMER_TICKS[4] = { 0, 6, 8, 10 };
extern bool8 cpuIsMultiBoot;
extern const u32 objTilesAddress[3] = { 0x010000, 0x014000, 0x014000 };
const u8 gamepakRamWaitState[4] = { 4, 3, 2, 8 };
const u8 gamepakWaitState[4] = { 4, 3, 2, 8 };
const u8 gamepakWaitState0[2] = { 2, 1 };
const u8 gamepakWaitState1[2] = { 4, 1 };
const u8 gamepakWaitState2[2] = { 8, 1 };
const bool8 isInRom[16] =
{ false, false, false, false, false, false, false, false,
true, true, true, true, true, true, false, false };
u8 memoryWait[16] =
{ 0, 0, 2, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 0 };
u8 memoryWait32[16] =
{ 0, 0, 5, 0, 0, 1, 1, 0, 7, 7, 9, 9, 13, 13, 4, 0 };
u8 memoryWaitSeq[16] =
{ 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 4, 4, 8, 8, 4, 0 };
u8 memoryWaitSeq32[16] =
{ 0, 0, 5, 0, 0, 1, 1, 0, 5, 5, 9, 9, 17, 17, 4, 0 };
// The videoMemoryWait constants are used to add some waitstates
// if the opcode access video memory data outside of vblank/hblank
// It seems to happen on only one ticks for each pixel.
// Not used for now (too problematic with current code).
//const u8 videoMemoryWait[16] =
// {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static int32 romSize = 0x2000000;
u8 biosProtected[4];
u8 cpuBitsSet[256];
u8 cpuLowestBitSet[256];
#ifdef WORDS_BIGENDIAN
bool8 cpuBiosSwapped = false;
#endif
u32 myROM[] = {
0xEA000006,
0xEA000093,
0xEA000006,
0x00000000,
0x00000000,
0x00000000,
0xEA000088,
0x00000000,
0xE3A00302,
0xE1A0F000,
0xE92D5800,
0xE55EC002,
0xE28FB03C,
0xE79BC10C,
0xE14FB000,
0xE92D0800,
0xE20BB080,
0xE38BB01F,
0xE129F00B,
0xE92D4004,
0xE1A0E00F,
0xE12FFF1C,
0xE8BD4004,
0xE3A0C0D3,
0xE129F00C,
0xE8BD0800,
0xE169F00B,
0xE8BD5800,
0xE1B0F00E,
0x0000009C,
0x0000009C,
0x0000009C,
0x0000009C,
0x000001F8,
0x000001F0,
0x000000AC,
0x000000A0,
0x000000FC,
0x00000168,
0xE12FFF1E,
0xE1A03000,
0xE1A00001,
0xE1A01003,
0xE2113102,
0x42611000,
0xE033C040,
0x22600000,
0xE1B02001,
0xE15200A0,
0x91A02082,
0x3AFFFFFC,
0xE1500002,
0xE0A33003,
0x20400002,
0xE1320001,
0x11A020A2,
0x1AFFFFF9,
0xE1A01000,
0xE1A00003,
0xE1B0C08C,
0x22600000,
0x42611000,
0xE12FFF1E,
0xE92D0010,
0xE1A0C000,
0xE3A01001,
0xE1500001,
0x81A000A0,
0x81A01081,
0x8AFFFFFB,
0xE1A0000C,
0xE1A04001,
0xE3A03000,
0xE1A02001,
0xE15200A0,
0x91A02082,
0x3AFFFFFC,
0xE1500002,
0xE0A33003,
0x20400002,
0xE1320001,
0x11A020A2,
0x1AFFFFF9,
0xE0811003,
0xE1B010A1,
0xE1510004,
0x3AFFFFEE,
0xE1A00004,
0xE8BD0010,
0xE12FFF1E,
0xE0010090,
0xE1A01741,
0xE2611000,
0xE3A030A9,
0xE0030391,
0xE1A03743,
0xE2833E39,
0xE0030391,
0xE1A03743,
0xE2833C09,
0xE283301C,
0xE0030391,
0xE1A03743,
0xE2833C0F,
0xE28330B6,
0xE0030391,
0xE1A03743,
0xE2833C16,
0xE28330AA,
0xE0030391,
0xE1A03743,
0xE2833A02,
0xE2833081,
0xE0030391,
0xE1A03743,
0xE2833C36,
0xE2833051,
0xE0030391,
0xE1A03743,
0xE2833CA2,
0xE28330F9,
0xE0000093,
0xE1A00840,
0xE12FFF1E,
0xE3A00001,
0xE3A01001,
0xE92D4010,
0xE3A03000,
0xE3A04001,
0xE3500000,
0x1B000004,
0xE5CC3301,
0xEB000002,
0x0AFFFFFC,
0xE8BD4010,
0xE12FFF1E,
0xE3A0C301,
0xE5CC3208,
0xE15C20B8,
0xE0110002,
0x10222000,
0x114C20B8,
0xE5CC4208,
0xE12FFF1E,
0xE92D500F,
0xE3A00301,
0xE1A0E00F,
0xE510F004,
0xE8BD500F,
0xE25EF004,
0xE59FD044,
0xE92D5000,
0xE14FC000,
0xE10FE000,
0xE92D5000,
0xE3A0C302,
0xE5DCE09C,
0xE35E00A5,
0x1A000004,
0x05DCE0B4,
0x021EE080,
0xE28FE004,
0x159FF018,
0x059FF018,
0xE59FD018,
0xE8BD5000,
0xE169F00C,
0xE8BD5000,
0xE25EF004,
0x03007FF0,
0x09FE2000,
0x09FFC000,
0x03007FE0
};
variable_desc saveGameStruct[] = {
{ &DISPCNT, sizeof(u16) },
{ &DISPSTAT, sizeof(u16) },
{ &VCOUNT, sizeof(u16) },
{ &BG0CNT, sizeof(u16) },
{ &BG1CNT, sizeof(u16) },
{ &BG2CNT, sizeof(u16) },
{ &BG3CNT, sizeof(u16) },
{ &BG0HOFS, sizeof(u16) },
{ &BG0VOFS, sizeof(u16) },
{ &BG1HOFS, sizeof(u16) },
{ &BG1VOFS, sizeof(u16) },
{ &BG2HOFS, sizeof(u16) },
{ &BG2VOFS, sizeof(u16) },
{ &BG3HOFS, sizeof(u16) },
{ &BG3VOFS, sizeof(u16) },
{ &BG2PA, sizeof(u16) },
{ &BG2PB, sizeof(u16) },
{ &BG2PC, sizeof(u16) },
{ &BG2PD, sizeof(u16) },
{ &BG2X_L, sizeof(u16) },
{ &BG2X_H, sizeof(u16) },
{ &BG2Y_L, sizeof(u16) },
{ &BG2Y_H, sizeof(u16) },
{ &BG3PA, sizeof(u16) },
{ &BG3PB, sizeof(u16) },
{ &BG3PC, sizeof(u16) },
{ &BG3PD, sizeof(u16) },
{ &BG3X_L, sizeof(u16) },
{ &BG3X_H, sizeof(u16) },
{ &BG3Y_L, sizeof(u16) },
{ &BG3Y_H, sizeof(u16) },
{ &WIN0H, sizeof(u16) },
{ &WIN1H, sizeof(u16) },
{ &WIN0V, sizeof(u16) },
{ &WIN1V, sizeof(u16) },
{ &WININ, sizeof(u16) },
{ &WINOUT, sizeof(u16) },
{ &MOSAIC, sizeof(u16) },
{ &BLDMOD, sizeof(u16) },
{ &COLEV, sizeof(u16) },
{ &COLY, sizeof(u16) },
{ &DM0SAD_L, sizeof(u16) },
{ &DM0SAD_H, sizeof(u16) },
{ &DM0DAD_L, sizeof(u16) },
{ &DM0DAD_H, sizeof(u16) },
{ &DM0CNT_L, sizeof(u16) },
{ &DM0CNT_H, sizeof(u16) },
{ &DM1SAD_L, sizeof(u16) },
{ &DM1SAD_H, sizeof(u16) },
{ &DM1DAD_L, sizeof(u16) },
{ &DM1DAD_H, sizeof(u16) },
{ &DM1CNT_L, sizeof(u16) },
{ &DM1CNT_H, sizeof(u16) },
{ &DM2SAD_L, sizeof(u16) },
{ &DM2SAD_H, sizeof(u16) },
{ &DM2DAD_L, sizeof(u16) },
{ &DM2DAD_H, sizeof(u16) },
{ &DM2CNT_L, sizeof(u16) },
{ &DM2CNT_H, sizeof(u16) },
{ &DM3SAD_L, sizeof(u16) },
{ &DM3SAD_H, sizeof(u16) },
{ &DM3DAD_L, sizeof(u16) },
{ &DM3DAD_H, sizeof(u16) },
{ &DM3CNT_L, sizeof(u16) },
{ &DM3CNT_H, sizeof(u16) },
{ &TM0D, sizeof(u16) },
{ &TM0CNT, sizeof(u16) },
{ &TM1D, sizeof(u16) },
{ &TM1CNT, sizeof(u16) },
{ &TM2D, sizeof(u16) },
{ &TM2CNT, sizeof(u16) },
{ &TM3D, sizeof(u16) },
{ &TM3CNT, sizeof(u16) },
{ &P1, sizeof(u16) },
{ &IE, sizeof(u16) },
{ &IF, sizeof(u16) },
{ &IME, sizeof(u16) },
{ &holdState, sizeof(bool8) },
{ &holdType, sizeof(int32) },
{ &lcdTicks, sizeof(int32) },
{ &timer0On, sizeof(bool8) },
{ &timer0Ticks, sizeof(int32) },
{ &timer0Reload, sizeof(int32) },
{ &timer0ClockReload, sizeof(int32) },
{ &timer1On, sizeof(bool8) },
{ &timer1Ticks, sizeof(int32) },
{ &timer1Reload, sizeof(int32) },
{ &timer1ClockReload, sizeof(int32) },
{ &timer2On, sizeof(bool8) },
{ &timer2Ticks, sizeof(int32) },
{ &timer2Reload, sizeof(int32) },
{ &timer2ClockReload, sizeof(int32) },
{ &timer3On, sizeof(bool8) },
{ &timer3Ticks, sizeof(int32) },
{ &timer3Reload, sizeof(int32) },
{ &timer3ClockReload, sizeof(int32) },
{ &dma0Source, sizeof(u32) },
{ &dma0Dest, sizeof(u32) },
{ &dma1Source, sizeof(u32) },
{ &dma1Dest, sizeof(u32) },
{ &dma2Source, sizeof(u32) },
{ &dma2Dest, sizeof(u32) },
{ &dma3Source, sizeof(u32) },
{ &dma3Dest, sizeof(u32) },
{ &fxOn, sizeof(bool8) },
{ &windowOn, sizeof(bool8) },
{ &N_FLAG, sizeof(bool8) },
{ &C_FLAG, sizeof(bool8) },
{ &Z_FLAG, sizeof(bool8) },
{ &V_FLAG, sizeof(bool8) },
{ &armState, sizeof(bool8) },
{ &armIrqEnable, sizeof(bool8) },
{ &armNextPC, sizeof(u32) },
{ &armMode, sizeof(int32) },
{ &saveType, sizeof(int32) },
{ NULL, 0 }
};
/////////////////////////////////////////////
#ifdef PROFILING
void cpuProfil(profile_segment *seg)
{
profilSegment = seg;
}
void cpuEnableProfiling(int hz)
{
if (hz == 0)
hz = 100;
profilingTicks = profilingTicksReload = 16777216 / hz;
profSetHertz(hz);
}
#endif
inline int CPUUpdateTicks()
{
int cpuLoopTicks = lcdTicks;
if (soundTicks < cpuLoopTicks)
cpuLoopTicks = soundTicks;
if (timer0On && (timer0Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer0Ticks;
}
if (timer1On && !(TM1CNT & 4) && (timer1Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer1Ticks;
}
if (timer2On && !(TM2CNT & 4) && (timer2Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer2Ticks;
}
if (timer3On && !(TM3CNT & 4) && (timer3Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer3Ticks;
}
#ifdef PROFILING
if (profilingTicksReload != 0)
{
if (profilingTicks < cpuLoopTicks)
{
cpuLoopTicks = profilingTicks;
}
}
#endif
if (SWITicks)
{
if (SWITicks < cpuLoopTicks)
cpuLoopTicks = SWITicks;
}
if (IRQTicks)
{
if (IRQTicks < cpuLoopTicks)
cpuLoopTicks = IRQTicks;
}
return cpuLoopTicks;
}
void CPUUpdateWindow0()
{
int x00 = WIN0H >> 8;
int x01 = WIN0H & 255;
if (x00 <= x01)
{
for (int i = 0; i < 240; i++)
{
gfxInWin0[i] = (i >= x00 && i < x01);
}
}
else
{
for (int i = 0; i < 240; i++)
{
gfxInWin0[i] = (i >= x00 || i < x01);
}
}
}
void CPUUpdateWindow1()
{
int x00 = WIN1H >> 8;
int x01 = WIN1H & 255;
if (x00 <= x01)
{
for (int i = 0; i < 240; i++)
{
gfxInWin1[i] = (i >= x00 && i < x01);
}
}
else
{
for (int i = 0; i < 240; i++)
{
gfxInWin1[i] = (i >= x00 || i < x01);
}
}
}
#define CLEAR_ARRAY(a) \
{ \
u32 *array = (a); \
for (int i = 0; i < 240; i++) { \
*array++ = 0x80000000; \
} \
} \
void CPUUpdateRenderBuffers(bool force)
{
if (!(layerEnable & 0x0100) || force)
{
CLEAR_ARRAY(line0);
}
if (!(layerEnable & 0x0200) || force)
{
CLEAR_ARRAY(line1);
}
if (!(layerEnable & 0x0400) || force)
{
CLEAR_ARRAY(line2);
}
if (!(layerEnable & 0x0800) || force)
{
CLEAR_ARRAY(line3);
}
}
#undef CLEAR_ARRAY
bool CPUWriteStateToStream(gzFile gzFile)
{
utilWriteInt(gzFile, SAVE_GAME_VERSION);
utilGzWrite(gzFile, &rom[0xa0], 16);
utilWriteInt(gzFile, useBios);
utilGzWrite(gzFile, ®[0], sizeof(reg));
utilWriteData(gzFile, saveGameStruct);
// new to version 0.7.1
utilWriteInt(gzFile, stopState);
// new to version 0.8
utilWriteInt(gzFile, intState);
utilGzWrite(gzFile, internalRAM, 0x8000);
utilGzWrite(gzFile, paletteRAM, 0x400);
utilGzWrite(gzFile, workRAM, 0x40000);
utilGzWrite(gzFile, vram, 0x20000);
utilGzWrite(gzFile, oam, 0x400);
utilGzWrite(gzFile, pix, 4 * 241 * 162);
utilGzWrite(gzFile, ioMem, 0x400);
eepromSaveGame(gzFile);
flashSaveGame(gzFile);
soundSaveGame(gzFile);
cheatsSaveGame(gzFile);
// version 1.5
rtcSaveGame(gzFile);
// SAVE_GAME_VERSION_9 (new to re-recording version which is based on 1.72)
{
utilGzWrite(gzFile, &sensorX, sizeof(sensorX));
utilGzWrite(gzFile, &sensorY, sizeof(sensorY));
bool8 movieActive = VBAMovieIsActive();
utilGzWrite(gzFile, &movieActive, sizeof(movieActive));
if (movieActive)
{
uint8 *movie_freeze_buf = NULL;
uint32 movie_freeze_size = 0;
int code = VBAMovieFreeze(&movie_freeze_buf, &movie_freeze_size);
if (movie_freeze_buf)
{
utilGzWrite(gzFile, &movie_freeze_size, sizeof(movie_freeze_size));
utilGzWrite(gzFile, movie_freeze_buf, movie_freeze_size);
delete [] movie_freeze_buf;
}
else
{
if (code == MOVIE_UNRECORDED_INPUT)
{
systemMessage(0, N_("Cannot make a movie snapshot as long as there are unrecorded input changes."));
}
else
{
systemMessage(0, N_("Failed to save movie snapshot."));
}
return false;
}
}
utilGzWrite(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount));
}
// SAVE_GAME_VERSION_13
{
utilGzWrite(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount));
utilGzWrite(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged));
utilGzWrite(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast));
}
// SAVE_GAME_VERSION_14
{
utilGzWrite(gzFile, memoryWait, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWait32, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWaitSeq, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWaitSeq32, 16 * sizeof(u8));
utilGzWrite(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used...
}
return true;
}
bool CPUWriteState(const char *file)
{
gzFile gzFile = utilGzOpen(file, "wb");
if (gzFile == NULL)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"), file);
return false;
}
bool res = CPUWriteStateToStream(gzFile);
utilGzClose(gzFile);
return res;
}
bool CPUWriteMemState(char *memory, int available)
{
gzFile gzFile = utilMemGzOpen(memory, available, "w");
if (gzFile == NULL)
{
return false;
}
bool res = CPUWriteStateToStream(gzFile);
long pos = utilGzTell(gzFile) + 8;
if (pos >= (available))
res = false;
utilGzClose(gzFile);
return res;
}
bool CPUReadStateFromStream(gzFile gzFile)
{
char tempBackupName[128];
if (tempSaveSafe)
{
sprintf(tempBackupName, "gbatempsave%d.sav", tempSaveID++);
CPUWriteState(tempBackupName);
}
int version = utilReadInt(gzFile);
if (version > SAVE_GAME_VERSION || version < SAVE_GAME_VERSION_1)
{
systemMessage(MSG_UNSUPPORTED_VBA_SGM,
N_("Unsupported VisualBoyAdvance save game version %d"),
version);
goto failedLoad;
}
u8 romname[17];
utilGzRead(gzFile, romname, 16);
if (memcmp(&rom[0xa0], romname, 16) != 0)
{
romname[16] = 0;
for (int i = 0; i < 16; i++)
if (romname[i] < 32)
romname[i] = 32;
systemMessage(MSG_CANNOT_LOAD_SGM, N_("Cannot load save game for %s"), romname);
goto failedLoad;
}
bool8 ub = utilReadInt(gzFile) ? true : false;
if (ub != useBios)
{
if (useBios)
systemMessage(MSG_SAVE_GAME_NOT_USING_BIOS,
N_("Save game is not using the BIOS files"));
else
systemMessage(MSG_SAVE_GAME_USING_BIOS,
N_("Save game is using the BIOS file"));
goto failedLoad;
}
utilGzRead(gzFile, ®[0], sizeof(reg));
utilReadData(gzFile, saveGameStruct);
if (version < SAVE_GAME_VERSION_3)
stopState = false;
else
stopState = utilReadInt(gzFile) ? true : false;
if (version < SAVE_GAME_VERSION_4)
intState = false;
else
intState = utilReadInt(gzFile) ? true : false;
utilGzRead(gzFile, internalRAM, 0x8000);
utilGzRead(gzFile, paletteRAM, 0x400);
utilGzRead(gzFile, workRAM, 0x40000);
utilGzRead(gzFile, vram, 0x20000);
utilGzRead(gzFile, oam, 0x400);
if (version < SAVE_GAME_VERSION_6)
utilGzRead(gzFile, pix, 4 * 240 * 160);
else
utilGzRead(gzFile, pix, 4 * 241 * 162);
utilGzRead(gzFile, ioMem, 0x400);
if (skipSaveGameBattery)
{
// skip eeprom data
eepromReadGameSkip(gzFile, version);
// skip flash data
flashReadGameSkip(gzFile, version);
}
else
{
eepromReadGame(gzFile, version);
flashReadGame(gzFile, version);
}
soundReadGame(gzFile, version);
if (version > SAVE_GAME_VERSION_1)
{
if (skipSaveGameCheats)
{
// skip cheats list data
cheatsReadGameSkip(gzFile, version);
}
else
{
cheatsReadGame(gzFile, version);
}
}
if (version > SAVE_GAME_VERSION_6)
{
rtcReadGame(gzFile);
}
if (version <= SAVE_GAME_VERSION_7)
{
u32 temp;
#define SWAP(a, b, c) \
temp = (a); \
(a) = (b) << 16 | (c); \
(b) = (temp) >> 16; \
(c) = (temp) & 0xFFFF;
SWAP(dma0Source, DM0SAD_H, DM0SAD_L);
SWAP(dma0Dest, DM0DAD_H, DM0DAD_L);
SWAP(dma1Source, DM1SAD_H, DM1SAD_L);
SWAP(dma1Dest, DM1DAD_H, DM1DAD_L);
SWAP(dma2Source, DM2SAD_H, DM2SAD_L);
SWAP(dma2Dest, DM2DAD_H, DM2DAD_L);
SWAP(dma3Source, DM3SAD_H, DM3SAD_L);
SWAP(dma3Dest, DM3DAD_H, DM3DAD_L);
}
#undef SWAP
if (version <= SAVE_GAME_VERSION_8)
{
timer0ClockReload = TIMER_TICKS[TM0CNT & 3];
timer1ClockReload = TIMER_TICKS[TM1CNT & 3];
timer2ClockReload = TIMER_TICKS[TM2CNT & 3];
timer3ClockReload = TIMER_TICKS[TM3CNT & 3];
timer0Ticks = ((0x10000 - TM0D) << timer0ClockReload) - timer0Ticks;
timer1Ticks = ((0x10000 - TM1D) << timer1ClockReload) - timer1Ticks;
timer2Ticks = ((0x10000 - TM2D) << timer2ClockReload) - timer2Ticks;
timer3Ticks = ((0x10000 - TM3D) << timer3ClockReload) - timer3Ticks;
interp_rate();
}
// set pointers!
layerEnable = layerSettings & DISPCNT;
CPUUpdateRender();
CPUUpdateRenderBuffers(true);
CPUUpdateWindow0();
CPUUpdateWindow1();
gbaSaveType = 0;
switch (saveType)
{
case 0:
cpuSaveGameFunc = flashSaveDecide;
break;
case 1:
cpuSaveGameFunc = sramWrite;
gbaSaveType = 1;
break;
case 2:
cpuSaveGameFunc = flashWrite;
gbaSaveType = 2;
break;
case 3:
break;
case 5:
gbaSaveType = 5;
break;
default:
systemMessage(MSG_UNSUPPORTED_SAVE_TYPE,
N_("Unsupported save type %d"), saveType);
break;
}
if (eepromInUse)
gbaSaveType = 3;
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
bool wasPlayingMovie = VBAMovieIsActive() && VBAMovieIsPlaying();
if (version >= SAVE_GAME_VERSION_9) // new to re-recording version:
{
utilGzRead(gzFile, &sensorX, sizeof(sensorX));
utilGzRead(gzFile, &sensorY, sizeof(sensorY));
bool8 movieSnapshot;
utilGzRead(gzFile, &movieSnapshot, sizeof(movieSnapshot));
if (VBAMovieIsActive() && !movieSnapshot)
{
systemMessage(0, N_("Can't load a non-movie snapshot while a movie is active."));
goto failedLoad;
}
if (movieSnapshot) // even if a movie isn't active we still want to parse through this
// because we have already got stuff added in this save format
{
uint32 movieInputDataSize = 0;
utilGzRead(gzFile, &movieInputDataSize, sizeof(movieInputDataSize));
uint8 *local_movie_data = new uint8[movieInputDataSize];
int readBytes = utilGzRead(gzFile, local_movie_data, movieInputDataSize);
if (readBytes != movieInputDataSize)
{
systemMessage(0, N_("Corrupt movie snapshot."));
delete [] local_movie_data;
goto failedLoad;
}
int code = VBAMovieUnfreeze(local_movie_data, movieInputDataSize);
delete [] local_movie_data;
if (code != MOVIE_SUCCESS && VBAMovieIsActive())
{
char errStr [1024];
strcpy(errStr, "Failed to load movie snapshot");
switch (code)
{
case MOVIE_NOT_FROM_THIS_MOVIE:
strcat(errStr, ";\nSnapshot not from this movie"); break;
case MOVIE_NOT_FROM_A_MOVIE:
strcat(errStr, ";\nNot a movie snapshot"); break; // shouldn't get here...
case MOVIE_UNVERIFIABLE_POST_END:
sprintf(errStr, "%s;\nSnapshot unverifiable with movie after End Frame %u", errStr, VBAMovieGetLastErrorInfo()); break;
case MOVIE_TIMELINE_INCONSISTENT_AT:
sprintf(errStr, "%s;\nSnapshot inconsistent with movie at Frame %u", errStr, VBAMovieGetLastErrorInfo()); break;
case MOVIE_WRONG_FORMAT:
strcat(errStr, ";\nWrong format"); break;
}
strcat(errStr, ".");
systemMessage(0, N_(errStr));
goto failedLoad;
}
}
utilGzRead(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount));
}
if (version < SAVE_GAME_VERSION_14)
{
if (version >= SAVE_GAME_VERSION_10)
{
utilGzSeek(gzFile, 16 * sizeof(int32) * 6, SEEK_CUR);
}
if (version >= SAVE_GAME_VERSION_11)
{
utilGzSeek(gzFile, sizeof(bool8) * 3, SEEK_CUR);
}
if (version >= SAVE_GAME_VERSION_12)
{
utilGzSeek(gzFile, sizeof(bool8) * 2, SEEK_CUR);
}
}
if (version >= SAVE_GAME_VERSION_13)
{
utilGzRead(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount));
utilGzRead(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged));
utilGzRead(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast));
}
if (version >= SAVE_GAME_VERSION_14)
{
utilGzRead(gzFile, memoryWait, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWait32, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWaitSeq, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWaitSeq32, 16 * sizeof(u8));
utilGzRead(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used...
}
if (armState)
{
ARM_PREFETCH;
}
else
{
THUMB_PREFETCH;
}
CPUUpdateRegister(0x204, CPUReadHalfWordQuick(0x4000204));
systemSetJoypad(0, ~P1 & 0x3FF);
VBAUpdateButtonPressDisplay();
VBAUpdateFrameCountDisplay();
systemRefreshScreen();
if (tempSaveSafe)
{
remove(tempBackupName);
tempSaveAttempts = 0;
}
return true;
failedLoad:
if (tempSaveSafe)
{
tempSaveAttempts++;
if (tempSaveAttempts < 3) // fail no more than 2 times in a row
CPUReadState(tempBackupName);
remove(tempBackupName);
}
if (wasPlayingMovie && VBAMovieIsRecording())
{
VBAMovieSwitchToPlaying();
}
return false;
}
bool CPUReadMemState(char *memory, int available)
{
gzFile gzFile = utilMemGzOpen(memory, available, "r");
tempSaveSafe = false;
bool res = CPUReadStateFromStream(gzFile);
tempSaveSafe = true;
utilGzClose(gzFile);
return res;
}
bool CPUReadState(const char *file)
{
gzFile gzFile = utilGzOpen(file, "rb");
if (gzFile == NULL)
return false;
bool res = CPUReadStateFromStream(gzFile);
utilGzClose(gzFile);
return res;
}
bool CPUExportEepromFile(const char *fileName)
{
if (eepromInUse)
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"),
fileName);
return false;
}
for (int i = 0; i < eepromSize; )
{
for (int j = 0; j < 8; j++)
{
if (fwrite(&eepromData[i + 7 - j], 1, 1, file) != 1)
{
fclose(file);
return false;
}
}
i += 8;
}
fclose(file);
}
return true;
}
bool CPUWriteBatteryToStream(gzFile gzFile)
{
if (!gzFile)
return false;
utilWriteInt(gzFile, SAVE_GAME_VERSION);
// for simplicity, we put both types of battery files should be in the stream, even if one's empty
eepromSaveGame(gzFile);
flashSaveGame(gzFile);
return true;
}
bool CPUWriteBatteryFile(const char *fileName)
{
if (gbaSaveType == 0)
{
if (eepromInUse)
gbaSaveType = 3;
else
switch (saveType)
{
case 1:
gbaSaveType = 1;
break;
case 2:
gbaSaveType = 2;
break;
}
}
if ((gbaSaveType != 0) && (gbaSaveType != 5))
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"),
fileName);
return false;
}
// only save if Flash/Sram in use or EEprom in use
if (gbaSaveType != 3)
{
if (gbaSaveType == 2)
{
if (fwrite(flashSaveMemory, 1, flashSize, file) != (size_t)flashSize)
{
fclose(file);
return false;
}
}
else
{
if (fwrite(flashSaveMemory, 1, 0x10000, file) != 0x10000)
{
fclose(file);
return false;
}
}
}
else
{
if (fwrite(eepromData, 1, eepromSize, file) != (size_t)eepromSize)
{
fclose(file);
return false;
}
}
fclose(file);
}
return true;
}
bool CPUReadGSASnapshot(const char *fileName)
{
int i;
FILE *file = fopen(fileName, "rb");
if (!file)
{
systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName);
return false;
}
// check file size to know what we should read
fseek(file, 0, SEEK_END);
// long size = ftell(file);
fseek(file, 0x0, SEEK_SET);
fread(&i, 1, 4, file);
fseek(file, i, SEEK_CUR); // Skip SharkPortSave
fseek(file, 4, SEEK_CUR); // skip some sort of flag
fread(&i, 1, 4, file); // name length
fseek(file, i, SEEK_CUR); // skip name
fread(&i, 1, 4, file); // desc length
fseek(file, i, SEEK_CUR); // skip desc
fread(&i, 1, 4, file); // notes length
fseek(file, i, SEEK_CUR); // skip notes
int saveSize;
fread(&saveSize, 1, 4, file); // read length
saveSize -= 0x1c; // remove header size
char buffer[17];
char buffer2[17];
fread(buffer, 1, 16, file);
buffer[16] = 0;
for (i = 0; i < 16; i++)
if (buffer[i] < 32)
buffer[i] = 32;
memcpy(buffer2, &rom[0xa0], 16);
buffer2[16] = 0;
for (i = 0; i < 16; i++)
if (buffer2[i] < 32)
buffer2[i] = 32;
if (memcmp(buffer, buffer2, 16))
{
systemMessage(MSG_CANNOT_IMPORT_SNAPSHOT_FOR,
N_("Cannot import snapshot for %s. Current game is %s"),
buffer,
buffer2);
fclose(file);
return false;
}
fseek(file, 12, SEEK_CUR); // skip some flags
if (saveSize >= 65536)
{
if (fread(flashSaveMemory, 1, saveSize, file) != (size_t)saveSize)
{
fclose(file);
return false;
}
}
else
{
systemMessage(MSG_UNSUPPORTED_SNAPSHOT_FILE,
N_("Unsupported snapshot file %s"),
fileName);
fclose(file);
return false;
}
fclose(file);
CPUReset();
return true;
}
bool CPUWriteGSASnapshot(const char *fileName,
const char *title,
const char *desc,
const char *notes)
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName);
return false;
}
u8 buffer[17];
utilPutDword(buffer, 0x0d); // SharkPortSave length
fwrite(buffer, 1, 4, file);
fwrite("SharkPortSave", 1, 0x0d, file);
utilPutDword(buffer, 0x000f0000);
fwrite(buffer, 1, 4, file); // save type 0x000f0000 = GBA save
utilPutDword(buffer, (u32)strlen(title));
fwrite(buffer, 1, 4, file); // title length
fwrite(title, 1, strlen(title), file);
utilPutDword(buffer, (u32)strlen(desc));
fwrite(buffer, 1, 4, file); // desc length
fwrite(desc, 1, strlen(desc), file);
utilPutDword(buffer, (u32)strlen(notes));
fwrite(buffer, 1, 4, file); // notes length
fwrite(notes, 1, strlen(notes), file);
int saveSize = 0x10000;
if (gbaSaveType == 2)
saveSize = flashSize;
int totalSize = saveSize + 0x1c;
utilPutDword(buffer, totalSize); // length of remainder of save - CRC
fwrite(buffer, 1, 4, file);
char *temp = new char[0x2001c];
memset(temp, 0, 28);
memcpy(temp, &rom[0xa0], 16); // copy internal name
temp[0x10] = rom[0xbe]; // reserved area (old checksum)
temp[0x11] = rom[0xbf]; // reserved area (old checksum)
temp[0x12] = rom[0xbd]; // complement check
temp[0x13] = rom[0xb0]; // maker
temp[0x14] = 1; // 1 save ?
memcpy(&temp[0x1c], flashSaveMemory, saveSize); // copy save
fwrite(temp, 1, totalSize, file); // write save + header
u32 crc = 0;
for (int i = 0; i < totalSize; i++)
{
crc += ((u32)temp[i] << (crc % 0x18));
}
utilPutDword(buffer, crc);
fwrite(buffer, 1, 4, file); // CRC?
fclose(file);
delete [] temp;
return true;
}
bool CPUImportEepromFile(const char *fileName)
{
FILE *file = fopen(fileName, "rb");
if (!file)
return false;
// check file size to know what we should read
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
if (size == 512 || size == 0x2000)
{
if (fread(eepromData, 1, size, file) != (size_t)size)
{
fclose(file);
return false;
}
for (int i = 0; i < size; )
{
u8 tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
i += 4;
}
}
else
{
fclose(file);
return false;
}
fclose(file);
return true;
}
bool CPUReadBatteryFromStream(gzFile gzFile)
{
if (!gzFile)
return false;
int version = utilReadInt(gzFile);
// for simplicity, we put both types of battery files should be in the stream, even if one's empty
eepromReadGame(gzFile, version);
flashReadGame(gzFile, version);
return true;
}
bool CPUReadBatteryFile(const char *fileName)
{
FILE *file = fopen(fileName, "rb");
if (!file)
return false;
// check file size to know what we should read
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
if (size == 512 || size == 0x2000)
{
if (fread(eepromData, 1, size, file) != (size_t)size)
{
fclose(file);
return false;
}
}
else
{
if (size == 0x20000)
{
if (fread(flashSaveMemory, 1, 0x20000, file) != 0x20000)
{
fclose(file);
return false;
}
flashSetSize(0x20000);
}
else
{
if (fread(flashSaveMemory, 1, 0x10000, file) != 0x10000)
{
fclose(file);
return false;
}
flashSetSize(0x10000);
}
}
fclose(file);
return true;
}
bool CPUWritePNGFile(const char *fileName)
{
return utilWritePNGFile(fileName, 240, 160, pix);
}
bool CPUWriteBMPFile(const char *fileName)
{
return utilWriteBMPFile(fileName, 240, 160, pix);
}
void CPUCleanUp()
{
#ifdef PROFILING
if (profilingTicksReload)
{
profCleanup();
}
#endif
PIX_FREE(pix);
pix = NULL;
free(bios);
bios = NULL;
free(rom);
rom = NULL;
free(internalRAM);
internalRAM = NULL;
free(workRAM);
workRAM = NULL;
free(paletteRAM);
paletteRAM = NULL;
free(vram);
vram = NULL;
free(oam);
oam = NULL;
free(ioMem);
ioMem = NULL;
#if 0
eepromErase();
flashErase();
#endif
#ifndef NO_DEBUGGER
elfCleanUp();
#endif
systemCleanUp();
systemRefreshScreen();
}
int CPULoadRom(const char *szFile)
{
int size = 0x2000000;
if (rom != NULL)
{
CPUCleanUp();
}
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
rom = (u8 *)malloc(0x2000000);
if (rom == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"ROM");
return 0;
}
// FIXME: size+4 is so RAM search and watch are safe to read any byte in the allocated region as a 4-byte int
workRAM = (u8 *)RAM_CALLOC(0x40000);
if (workRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"WRAM");
return 0;
}
u8 *whereToLoad = cpuIsMultiBoot ? workRAM : rom;
#ifndef NO_DEBUGGER
if (utilIsELF(szFile))
{
FILE *f = fopen(szFile, "rb");
if (!f)
{
systemMessage(MSG_ERROR_OPENING_IMAGE, N_("Error opening image %s"),
szFile);
CPUCleanUp();
return 0;
}
bool res = elfRead(szFile, size, f);
if (!res || size == 0)
{
CPUCleanUp();
elfCleanUp();
return 0;
}
}
else
#endif //NO_DEBUGGER
if (szFile != NULL)
{
if (!utilLoad(szFile,
utilIsGBAImage,
whereToLoad,
size))
{
CPUCleanUp();
return 0;
}
}
u16 *temp = (u16 *)(rom + ((size + 1) & ~1));
for (int i = (size + 1) & ~1; i < 0x2000000; i += 2)
{
WRITE16LE(temp, (i >> 1) & 0xFFFF);
temp++;
}
pix = (u8 *)PIX_CALLOC(4 * 241 * 162);
if (pix == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"PIX");
CPUCleanUp();
return 0;
}
bios = (u8 *)RAM_CALLOC(0x4000);
if (bios == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"BIOS");
CPUCleanUp();
return 0;
}
internalRAM = (u8 *)RAM_CALLOC(0x8000);
if (internalRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"IRAM");
CPUCleanUp();
return 0;
}
paletteRAM = (u8 *)RAM_CALLOC(0x400);
if (paletteRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"PRAM");
CPUCleanUp();
return 0;
}
vram = (u8 *)RAM_CALLOC(0x20000);
if (vram == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"VRAM");
CPUCleanUp();
return 0;
}
oam = (u8 *)RAM_CALLOC(0x400);
if (oam == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"OAM");
CPUCleanUp();
return 0;
}
ioMem = (u8 *)RAM_CALLOC(0x400);
if (ioMem == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"IO");
CPUCleanUp();
return 0;
}
flashInit();
eepromInit();
CPUUpdateRenderBuffers(true);
romSize = size;
return size;
}
void CPUDoMirroring(bool b)
{
u32 mirroredRomSize = (((romSize) >> 20) & 0x3F) << 20;
u32 mirroredRomAddress = romSize;
if ((mirroredRomSize <= 0x800000) && (b))
{
mirroredRomAddress = mirroredRomSize;
if (mirroredRomSize == 0)
mirroredRomSize = 0x100000;
while (mirroredRomAddress < 0x01000000)
{
memcpy((u16 *)(rom + mirroredRomAddress), (u16 *)(rom), mirroredRomSize);
mirroredRomAddress += mirroredRomSize;
}
}
}
// Emulates the Cheat System (m) code
void CPUMasterCodeCheck()
{
if (cheatsEnabled)
{
if ((mastercode) && (mastercode == armNextPC))
{
u32 joy = 0;
if (systemReadJoypads())
joy = systemGetJoypad(0, cpuEEPROMSensorEnabled);
u32 ext = (joy >> 10);
cpuTotalTicks += cheatsCheckKeys(P1 ^ 0x3FF, ext);
}
}
}
void CPUUpdateRender()
{
switch (DISPCNT & 7)
{
case 0:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode0RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode0RenderLineNoWindow;
else
renderLine = mode0RenderLineAll;
break;
case 1:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode1RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode1RenderLineNoWindow;
else
renderLine = mode1RenderLineAll;
break;
case 2:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode2RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode2RenderLineNoWindow;
else
renderLine = mode2RenderLineAll;
break;
case 3:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode3RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode3RenderLineNoWindow;
else
renderLine = mode3RenderLineAll;
break;
case 4:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode4RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode4RenderLineNoWindow;
else
renderLine = mode4RenderLineAll;
break;
case 5:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode5RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode5RenderLineNoWindow;
else
renderLine = mode5RenderLineAll;
default:
break;
}
}
void CPUUpdateCPSR()
{
u32 CPSR = reg[16].I & 0x40;
if (N_FLAG)
CPSR |= 0x80000000;
if (Z_FLAG)
CPSR |= 0x40000000;
if (C_FLAG)
CPSR |= 0x20000000;
if (V_FLAG)
CPSR |= 0x10000000;
if (!armState)
CPSR |= 0x00000020;
if (!armIrqEnable)
CPSR |= 0x80;
CPSR |= (armMode & 0x1F);
reg[16].I = CPSR;
}
void CPUUpdateFlags(bool breakLoop)
{
u32 CPSR = reg[16].I;
N_FLAG = (CPSR & 0x80000000) ? true : false;
Z_FLAG = (CPSR & 0x40000000) ? true : false;
C_FLAG = (CPSR & 0x20000000) ? true : false;
V_FLAG = (CPSR & 0x10000000) ? true : false;
armState = (CPSR & 0x20) ? false : true;
armIrqEnable = (CPSR & 0x80) ? false : true;
if (breakLoop)
{
if (armIrqEnable && (IF & IE) && (IME & 1))
cpuNextEvent = cpuTotalTicks;
}
}
void CPUUpdateFlags()
{
CPUUpdateFlags(true);
}
#ifdef WORDS_BIGENDIAN
static void CPUSwap(volatile u32 *a, volatile u32 *b)
{
volatile u32 c = *b;
*b = *a;
*a = c;
}
#else
static void CPUSwap(u32 *a, u32 *b)
{
u32 c = *b;
*b = *a;
*a = c;
}
#endif
void CPUSwitchMode(int mode, bool saveState, bool breakLoop)
{
// if(armMode == mode)
// return;
CPUUpdateCPSR();
switch (armMode)
{
case 0x10:
case 0x1F:
reg[R13_USR].I = reg[13].I;
reg[R14_USR].I = reg[14].I;
reg[17].I = reg[16].I;
break;
case 0x11:
CPUSwap(®[R8_FIQ].I, ®[8].I);
CPUSwap(®[R9_FIQ].I, ®[9].I);
CPUSwap(®[R10_FIQ].I, ®[10].I);
CPUSwap(®[R11_FIQ].I, ®[11].I);
CPUSwap(®[R12_FIQ].I, ®[12].I);
reg[R13_FIQ].I = reg[13].I;
reg[R14_FIQ].I = reg[14].I;
reg[SPSR_FIQ].I = reg[17].I;
break;
case 0x12:
reg[R13_IRQ].I = reg[13].I;
reg[R14_IRQ].I = reg[14].I;
reg[SPSR_IRQ].I = reg[17].I;
break;
case 0x13:
reg[R13_SVC].I = reg[13].I;
reg[R14_SVC].I = reg[14].I;
reg[SPSR_SVC].I = reg[17].I;
break;
case 0x17:
reg[R13_ABT].I = reg[13].I;
reg[R14_ABT].I = reg[14].I;
reg[SPSR_ABT].I = reg[17].I;
break;
case 0x1b:
reg[R13_UND].I = reg[13].I;
reg[R14_UND].I = reg[14].I;
reg[SPSR_UND].I = reg[17].I;
break;
}
u32 CPSR = reg[16].I;
u32 SPSR = reg[17].I;
switch (mode)
{
case 0x10:
case 0x1F:
reg[13].I = reg[R13_USR].I;
reg[14].I = reg[R14_USR].I;
reg[16].I = SPSR;
break;
case 0x11:
CPUSwap(®[8].I, ®[R8_FIQ].I);
CPUSwap(®[9].I, ®[R9_FIQ].I);
CPUSwap(®[10].I, ®[R10_FIQ].I);
CPUSwap(®[11].I, ®[R11_FIQ].I);
CPUSwap(®[12].I, ®[R12_FIQ].I);
reg[13].I = reg[R13_FIQ].I;
reg[14].I = reg[R14_FIQ].I;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_FIQ].I;
break;
case 0x12:
reg[13].I = reg[R13_IRQ].I;
reg[14].I = reg[R14_IRQ].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_IRQ].I;
break;
case 0x13:
reg[13].I = reg[R13_SVC].I;
reg[14].I = reg[R14_SVC].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_SVC].I;
break;
case 0x17:
reg[13].I = reg[R13_ABT].I;
reg[14].I = reg[R14_ABT].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_ABT].I;
break;
case 0x1b:
reg[13].I = reg[R13_UND].I;
reg[14].I = reg[R14_UND].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_UND].I;
break;
default:
systemMessage(MSG_UNSUPPORTED_ARM_MODE, N_("Unsupported ARM mode %02x"), mode);
break;
}
armMode = mode;
CPUUpdateFlags(breakLoop);
CPUUpdateCPSR();
}
void CPUSwitchMode(int mode, bool saveState)
{
CPUSwitchMode(mode, saveState, true);
}
void CPUUndefinedException()
{
u32 PC = reg[15].I;
bool savedArmState = armState;
CPUSwitchMode(0x1b, true, false);
reg[14].I = PC - (savedArmState ? 4 : 2);
reg[15].I = 0x04;
armState = true;
armIrqEnable = false;
armNextPC = 0x04;
ARM_PREFETCH;
reg[15].I += 4;
}
void CPUSoftwareInterrupt()
{
u32 PC = reg[15].I;
bool savedArmState = armState;
CPUSwitchMode(0x13, true, false);
reg[14].I = PC - (savedArmState ? 4 : 2);
reg[15].I = 0x08;
armState = true;
armIrqEnable = false;
armNextPC = 0x08;
ARM_PREFETCH;
reg[15].I += 4;
}
void CPUSoftwareInterrupt(int comment)
{
static bool disableMessage = false;
if (armState)
comment >>= 16;
#ifdef BKPT_SUPPORT
if (comment == 0xff)
{
dbgOutput(NULL, reg[0].I);
return;
}
#endif
#ifdef PROFILING
if (comment == 0xfe)
{
profStartup(reg[0].I, reg[1].I);
return;
}
if (comment == 0xfd)
{
profControl(reg[0].I);
return;
}
if (comment == 0xfc)
{
profCleanup();
return;
}
if (comment == 0xfb)
{
profCount();
return;
}
#endif
if (comment == 0xfa)
{
agbPrintFlush();
return;
}
#ifdef SDL
if (comment == 0xf9)
{
emulating = 0;
cpuNextEvent = cpuTotalTicks;
cpuBreakLoop = true;
return;
}
#endif
if (useBios)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment,
armState ? armNextPC - 4 : armNextPC - 2,
reg[0].I,
reg[1].I,
reg[2].I,
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
return;
}
// This would be correct, but it causes problems if uncommented
// else {
// biosProtected = 0xe3a02004;
// }
switch (comment)
{
case 0x00:
BIOS_SoftReset();
ARM_PREFETCH;
break;
case 0x01:
BIOS_RegisterRamReset();
break;
case 0x02:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("Halt: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
holdState = true;
holdType = -1;
cpuNextEvent = cpuTotalTicks;
break;
case 0x03:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("Stop: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
holdState = true;
holdType = -1;
stopState = true;
cpuNextEvent = cpuTotalTicks;
break;
case 0x04:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("IntrWait: 0x%08x,0x%08x (VCOUNT = %2d)\n",
reg[0].I,
reg[1].I,
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
break;
case 0x05:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("VBlankIntrWait: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
break;
case 0x06:
CPUSoftwareInterrupt();
break;
case 0x07:
CPUSoftwareInterrupt();
break;
case 0x08:
BIOS_Sqrt();
break;
case 0x09:
BIOS_ArcTan();
break;
case 0x0A:
BIOS_ArcTan2();
break;
case 0x0B:
{
int len = (reg[2].I & 0x1FFFFF) >> 1;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
{
if ((reg[2].I >> 24) & 1)
{
if ((reg[2].I >> 26) & 1)
SWITicks = (7 + memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1);
else
SWITicks = (8 + memoryWait[(reg[1].I >> 24) & 0xF]) * (len);
}
else
{
if ((reg[2].I >> 26) & 1)
SWITicks = (10 + memoryWait32[(reg[0].I >> 24) & 0xF] +
memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1);
else
SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
}
}
BIOS_CpuSet();
break;
case 0x0C:
{
int len = (reg[2].I & 0x1FFFFF) >> 5;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
{
if ((reg[2].I >> 24) & 1)
SWITicks = (6 + memoryWait32[(reg[1].I >> 24) & 0xF] +
7 * (memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 1)) * len;
else
SWITicks = (9 + memoryWait32[(reg[0].I >> 24) & 0xF] +
memoryWait32[(reg[1].I >> 24) & 0xF] +
7 * (memoryWaitSeq32[(reg[0].I >> 24) & 0xF] +
memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 2)) * len;
}
}
BIOS_CpuFastSet();
break;
case 0x0D:
BIOS_GetBiosChecksum();
break;
case 0x0E:
BIOS_BgAffineSet();
break;
case 0x0F:
BIOS_ObjAffineSet();
break;
case 0x10:
{
int len = CPUReadHalfWord(reg[2].I);
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
SWITicks = (32 + memoryWait[(reg[0].I >> 24) & 0xF]) * len;
}
BIOS_BitUnPack();
break;
case 0x11:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (9 + memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_LZ77UnCompWram();
break;
case 0x12:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (19 + memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_LZ77UnCompVram();
break;
case 0x13:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (29 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1)) * len;
}
BIOS_HuffUnComp();
break;
case 0x14:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_RLUnCompWram();
break;
case 0x15:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (34 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_RLUnCompVram();
break;
case 0x16:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff8bitUnFilterWram();
break;
case 0x17:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (39 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff8bitUnFilterVram();
break;
case 0x18:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff16bitUnFilter();
break;
case 0x19:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SoundBiasSet: 0x%08x (VCOUNT = %2d)\n",
reg[0].I,
VCOUNT);
}
#endif
if (reg[0].I)
systemSoundPause();
else
systemSoundResume();
break;
case 0x1F:
BIOS_MidiKey2Freq();
break;
case 0x2A:
BIOS_SndDriverJmpTableCopy();
// let it go, because we don't really emulate this function // FIXME (?)
default:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment,
armState ? armNextPC - 4 : armNextPC - 2,
reg[0].I,
reg[1].I,
reg[2].I,
VCOUNT);
}
#endif
if (!disableMessage)
{
systemMessage(MSG_UNSUPPORTED_BIOS_FUNCTION,
N_("Unsupported BIOS function %02x called from %08x. A BIOS file is needed in order to get correct behaviour."),
comment,
armMode ? armNextPC - 4 : armNextPC - 2);
disableMessage = true;
}
break;
}
}
void CPUCompareVCOUNT()
{
if (VCOUNT == (DISPSTAT >> 8))
{
DISPSTAT |= 4;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 0x20)
{
IF |= 4;
UPDATE_REG(0x202, IF);
}
}
else
{
DISPSTAT &= 0xFFFB;
UPDATE_REG(0x4, DISPSTAT);
}
if (layerEnableDelay > 0)
{
--layerEnableDelay;
if (layerEnableDelay == 1)
layerEnable = layerSettings & DISPCNT;
}
}
static void doDMA(u32 &s, u32 &d, u32 si, u32 di, u32 c, int transfer32)
{
int sm = s >> 24;
int dm = d >> 24;
int sw = 0;
int dw = 0;
int sc = c;
cpuDmaCount = c;
// This is done to get the correct waitstates.
if (sm > 15)
sm = 15;
if (dm > 15)
dm = 15;
//if ((sm>=0x05) && (sm<=0x07) || (dm>=0x05) && (dm <=0x07))
// blank = (((DISPSTAT | ((DISPSTAT>>1)&1))==1) ? true : false);
if (transfer32)
{
s &= 0xFFFFFFFC;
if (s < 0x02000000 && (reg[15].I >> 24))
{
while (c != 0)
{
CPUWriteMemory(d, 0);
d += di;
c--;
}
}
else
{
while (c != 0)
{
cpuDmaLast = CPUReadMemory(s);
CPUWriteMemory(d, cpuDmaLast);
d += di;
s += si;
c--;
}
}
}
else
{
s &= 0xFFFFFFFE;
si = (int)si >> 1;
di = (int)di >> 1;
if (s < 0x02000000 && (reg[15].I >> 24))
{
while (c != 0)
{
CPUWriteHalfWord(d, 0);
d += di;
c--;
}
}
else
{
while (c != 0)
{
cpuDmaLast = CPUReadHalfWord(s);
CPUWriteHalfWord(d, cpuDmaLast);
cpuDmaLast |= (cpuDmaLast << 16);
d += di;
s += si;
c--;
}
}
}
cpuDmaCount = 0;
int totalTicks = 0;
if (transfer32)
{
sw = 1 + memoryWaitSeq32[sm & 15];
dw = 1 + memoryWaitSeq32[dm & 15];
totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait32[sm & 15] +
memoryWaitSeq32[dm & 15];
}
else
{
sw = 1 + memoryWaitSeq[sm & 15];
dw = 1 + memoryWaitSeq[dm & 15];
totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait[sm & 15] +
memoryWaitSeq[dm & 15];
}
cpuDmaTicksToUpdate += totalTicks;
}
void CPUCheckDMA(int reason, int dmamask)
{
// DMA 0
if ((DM0CNT_H & 0x8000) && (dmamask & 1))
{
if (((DM0CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM0CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM0CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA0)
{
int count = (DM0CNT_L ? DM0CNT_L : 0x4000) << 1;
if (DM0CNT_H & 0x0400)
count <<= 1;
log("DMA0: s=%08x d=%08x c=%04x count=%08x\n", dma0Source, dma0Dest,
DM0CNT_H,
count);
}
#endif
doDMA(dma0Source, dma0Dest, sourceIncrement, destIncrement,
DM0CNT_L ? DM0CNT_L : 0x4000,
DM0CNT_H & 0x0400);
cpuDmaHack = true;
if (DM0CNT_H & 0x4000)
{
IF |= 0x0100;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM0CNT_H >> 5) & 3) == 3)
{
dma0Dest = DM0DAD_L | (DM0DAD_H << 16);
}
if (!(DM0CNT_H & 0x0200) || (reason == 0))
{
DM0CNT_H &= 0x7FFF;
UPDATE_REG(0xBA, DM0CNT_H);
}
}
}
// DMA 1
if ((DM1CNT_H & 0x8000) && (dmamask & 2))
{
if (((DM1CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM1CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM1CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
if (reason == 3)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA1)
{
log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest,
DM1CNT_H,
16);
}
#endif
doDMA(dma1Source, dma1Dest, sourceIncrement, 0, 4,
0x0400);
}
else
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA1)
{
int count = (DM1CNT_L ? DM1CNT_L : 0x4000) << 1;
if (DM1CNT_H & 0x0400)
count <<= 1;
log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest,
DM1CNT_H,
count);
}
#endif
doDMA(dma1Source, dma1Dest, sourceIncrement, destIncrement,
DM1CNT_L ? DM1CNT_L : 0x4000,
DM1CNT_H & 0x0400);
}
cpuDmaHack = true;
if (DM1CNT_H & 0x4000)
{
IF |= 0x0200;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM1CNT_H >> 5) & 3) == 3)
{
dma1Dest = DM1DAD_L | (DM1DAD_H << 16);
}
if (!(DM1CNT_H & 0x0200) || (reason == 0))
{
DM1CNT_H &= 0x7FFF;
UPDATE_REG(0xC6, DM1CNT_H);
}
}
}
// DMA 2
if ((DM2CNT_H & 0x8000) && (dmamask & 4))
{
if (((DM2CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM2CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM2CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
if (reason == 3)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA2)
{
int count = (4) << 2;
log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest,
DM2CNT_H,
count);
}
#endif
doDMA(dma2Source, dma2Dest, sourceIncrement, 0, 4,
0x0400);
}
else
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA2)
{
int count = (DM2CNT_L ? DM2CNT_L : 0x4000) << 1;
if (DM2CNT_H & 0x0400)
count <<= 1;
log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest,
DM2CNT_H,
count);
}
#endif
doDMA(dma2Source, dma2Dest, sourceIncrement, destIncrement,
DM2CNT_L ? DM2CNT_L : 0x4000,
DM2CNT_H & 0x0400);
}
cpuDmaHack = true;
if (DM2CNT_H & 0x4000)
{
IF |= 0x0400;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM2CNT_H >> 5) & 3) == 3)
{
dma2Dest = DM2DAD_L | (DM2DAD_H << 16);
}
if (!(DM2CNT_H & 0x0200) || (reason == 0))
{
DM2CNT_H &= 0x7FFF;
UPDATE_REG(0xD2, DM2CNT_H);
}
}
}
// DMA 3
if ((DM3CNT_H & 0x8000) && (dmamask & 8))
{
if (((DM3CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM3CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM3CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA3)
{
int count = (DM3CNT_L ? DM3CNT_L : 0x10000) << 1;
if (DM3CNT_H & 0x0400)
count <<= 1;
log("DMA3: s=%08x d=%08x c=%04x count=%08x\n", dma3Source, dma3Dest,
DM3CNT_H,
count);
}
#endif
doDMA(dma3Source, dma3Dest, sourceIncrement, destIncrement,
DM3CNT_L ? DM3CNT_L : 0x10000,
DM3CNT_H & 0x0400);
if (DM3CNT_H & 0x4000)
{
IF |= 0x0800;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM3CNT_H >> 5) & 3) == 3)
{
dma3Dest = DM3DAD_L | (DM3DAD_H << 16);
}
if (!(DM3CNT_H & 0x0200) || (reason == 0))
{
DM3CNT_H &= 0x7FFF;
UPDATE_REG(0xDE, DM3CNT_H);
}
}
}
}
void CPUUpdateRegister(u32 address, u16 value)
{
switch (address)
{
case 0x00:
{
if ((value & 7) > 5)
{
// display modes above 0-5 are prohibited
DISPCNT = (value & 7);
}
bool change = (0 != ((DISPCNT ^ value) & 0x80));
bool changeBG = (0 != ((DISPCNT ^ value) & 0x0F00));
u16 changeBGon = ((~DISPCNT) & value) & 0x0F00; // these layers are being activated
DISPCNT = (value & 0xFFF7); // bit 3 can only be accessed by the BIOS to enable GBC mode
UPDATE_REG(0x00, DISPCNT);
if (changeBGon)
{
layerEnableDelay = 4;
layerEnable = layerSettings & value & (~changeBGon);
}
else
{
layerEnable = layerSettings & value;
// CPUUpdateTicks(); // what does this do?
}
windowOn = (layerEnable & 0x6000) ? true : false;
if (change && !((value & 0x80)))
{
if (!(DISPSTAT & 1))
{
lcdTicks = 1008;
// VCOUNT = 0;
// UPDATE_REG(0x06, VCOUNT);
DISPSTAT &= 0xFFFC;
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
// (*renderLine)();
}
CPUUpdateRender();
// we only care about changes in BG0-BG3
if (changeBG)
{
CPUUpdateRenderBuffers(false);
}
break;
}
case 0x04:
DISPSTAT = (value & 0xFF38) | (DISPSTAT & 7);
UPDATE_REG(0x04, DISPSTAT);
break;
case 0x06:
// not writable
break;
case 0x08:
BG0CNT = (value & 0xDFCF);
UPDATE_REG(0x08, BG0CNT);
break;
case 0x0A:
BG1CNT = (value & 0xDFCF);
UPDATE_REG(0x0A, BG1CNT);
break;
case 0x0C:
BG2CNT = (value & 0xFFCF);
UPDATE_REG(0x0C, BG2CNT);
break;
case 0x0E:
BG3CNT = (value & 0xFFCF);
UPDATE_REG(0x0E, BG3CNT);
break;
case 0x10:
BG0HOFS = value & 511;
UPDATE_REG(0x10, BG0HOFS);
break;
case 0x12:
BG0VOFS = value & 511;
UPDATE_REG(0x12, BG0VOFS);
break;
case 0x14:
BG1HOFS = value & 511;
UPDATE_REG(0x14, BG1HOFS);
break;
case 0x16:
BG1VOFS = value & 511;
UPDATE_REG(0x16, BG1VOFS);
break;
case 0x18:
BG2HOFS = value & 511;
UPDATE_REG(0x18, BG2HOFS);
break;
case 0x1A:
BG2VOFS = value & 511;
UPDATE_REG(0x1A, BG2VOFS);
break;
case 0x1C:
BG3HOFS = value & 511;
UPDATE_REG(0x1C, BG3HOFS);
break;
case 0x1E:
BG3VOFS = value & 511;
UPDATE_REG(0x1E, BG3VOFS);
break;
case 0x20:
BG2PA = value;
UPDATE_REG(0x20, BG2PA);
break;
case 0x22:
BG2PB = value;
UPDATE_REG(0x22, BG2PB);
break;
case 0x24:
BG2PC = value;
UPDATE_REG(0x24, BG2PC);
break;
case 0x26:
BG2PD = value;
UPDATE_REG(0x26, BG2PD);
break;
case 0x28:
BG2X_L = value;
UPDATE_REG(0x28, BG2X_L);
gfxBG2Changed |= 1;
break;
case 0x2A:
BG2X_H = (value & 0xFFF);
UPDATE_REG(0x2A, BG2X_H);
gfxBG2Changed |= 1;
break;
case 0x2C:
BG2Y_L = value;
UPDATE_REG(0x2C, BG2Y_L);
gfxBG2Changed |= 2;
break;
case 0x2E:
BG2Y_H = value & 0xFFF;
UPDATE_REG(0x2E, BG2Y_H);
gfxBG2Changed |= 2;
break;
case 0x30:
BG3PA = value;
UPDATE_REG(0x30, BG3PA);
break;
case 0x32:
BG3PB = value;
UPDATE_REG(0x32, BG3PB);
break;
case 0x34:
BG3PC = value;
UPDATE_REG(0x34, BG3PC);
break;
case 0x36:
BG3PD = value;
UPDATE_REG(0x36, BG3PD);
break;
case 0x38:
BG3X_L = value;
UPDATE_REG(0x38, BG3X_L);
gfxBG3Changed |= 1;
break;
case 0x3A:
BG3X_H = value & 0xFFF;
UPDATE_REG(0x3A, BG3X_H);
gfxBG3Changed |= 1;
break;
case 0x3C:
BG3Y_L = value;
UPDATE_REG(0x3C, BG3Y_L);
gfxBG3Changed |= 2;
break;
case 0x3E:
BG3Y_H = value & 0xFFF;
UPDATE_REG(0x3E, BG3Y_H);
gfxBG3Changed |= 2;
break;
case 0x40:
WIN0H = value;
UPDATE_REG(0x40, WIN0H);
CPUUpdateWindow0();
break;
case 0x42:
WIN1H = value;
UPDATE_REG(0x42, WIN1H);
CPUUpdateWindow1();
break;
case 0x44:
WIN0V = value;
UPDATE_REG(0x44, WIN0V);
break;
case 0x46:
WIN1V = value;
UPDATE_REG(0x46, WIN1V);
break;
case 0x48:
WININ = value & 0x3F3F;
UPDATE_REG(0x48, WININ);
break;
case 0x4A:
WINOUT = value & 0x3F3F;
UPDATE_REG(0x4A, WINOUT);
break;
case 0x4C:
MOSAIC = value;
UPDATE_REG(0x4C, MOSAIC);
break;
case 0x50:
BLDMOD = value & 0x3FFF;
UPDATE_REG(0x50, BLDMOD);
fxOn = ((BLDMOD >> 6) & 3) != 0;
CPUUpdateRender();
break;
case 0x52:
COLEV = value & 0x1F1F;
UPDATE_REG(0x52, COLEV);
break;
case 0x54:
COLY = value & 0x1F;
UPDATE_REG(0x54, COLY);
break;
case 0x60:
case 0x62:
case 0x64:
case 0x68:
case 0x6c:
case 0x70:
case 0x72:
case 0x74:
case 0x78:
case 0x7c:
case 0x80:
case 0x84:
soundEvent(address & 0xFF, (u8)(value & 0xFF));
soundEvent((address & 0xFF) + 1, (u8)(value >> 8));
break;
case 0x82:
case 0x88:
case 0xa0:
case 0xa2:
case 0xa4:
case 0xa6:
case 0x90:
case 0x92:
case 0x94:
case 0x96:
case 0x98:
case 0x9a:
case 0x9c:
case 0x9e:
soundEvent(address & 0xFF, value);
break;
case 0xB0:
DM0SAD_L = value;
UPDATE_REG(0xB0, DM0SAD_L);
break;
case 0xB2:
DM0SAD_H = value & 0x07FF;
UPDATE_REG(0xB2, DM0SAD_H);
break;
case 0xB4:
DM0DAD_L = value;
UPDATE_REG(0xB4, DM0DAD_L);
break;
case 0xB6:
DM0DAD_H = value & 0x07FF;
UPDATE_REG(0xB6, DM0DAD_H);
break;
case 0xB8:
DM0CNT_L = value & 0x3FFF;
UPDATE_REG(0xB8, 0);
break;
case 0xBA:
{
bool start = ((DM0CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM0CNT_H = value;
UPDATE_REG(0xBA, DM0CNT_H);
if (start && (value & 0x8000))
{
dma0Source = DM0SAD_L | (DM0SAD_H << 16);
dma0Dest = DM0DAD_L | (DM0DAD_H << 16);
CPUCheckDMA(0, 1);
}
break;
}
case 0xBC:
DM1SAD_L = value;
UPDATE_REG(0xBC, DM1SAD_L);
break;
case 0xBE:
DM1SAD_H = value & 0x0FFF;
UPDATE_REG(0xBE, DM1SAD_H);
break;
case 0xC0:
DM1DAD_L = value;
UPDATE_REG(0xC0, DM1DAD_L);
break;
case 0xC2:
DM1DAD_H = value & 0x07FF;
UPDATE_REG(0xC2, DM1DAD_H);
break;
case 0xC4:
DM1CNT_L = value & 0x3FFF;
UPDATE_REG(0xC4, 0);
break;
case 0xC6:
{
bool start = ((DM1CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM1CNT_H = value;
UPDATE_REG(0xC6, DM1CNT_H);
if (start && (value & 0x8000))
{
dma1Source = DM1SAD_L | (DM1SAD_H << 16);
dma1Dest = DM1DAD_L | (DM1DAD_H << 16);
CPUCheckDMA(0, 2);
}
break;
}
case 0xC8:
DM2SAD_L = value;
UPDATE_REG(0xC8, DM2SAD_L);
break;
case 0xCA:
DM2SAD_H = value & 0x0FFF;
UPDATE_REG(0xCA, DM2SAD_H);
break;
case 0xCC:
DM2DAD_L = value;
UPDATE_REG(0xCC, DM2DAD_L);
break;
case 0xCE:
DM2DAD_H = value & 0x07FF;
UPDATE_REG(0xCE, DM2DAD_H);
break;
case 0xD0:
DM2CNT_L = value & 0x3FFF;
UPDATE_REG(0xD0, 0);
break;
case 0xD2:
{
bool start = ((DM2CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM2CNT_H = value;
UPDATE_REG(0xD2, DM2CNT_H);
if (start && (value & 0x8000))
{
dma2Source = DM2SAD_L | (DM2SAD_H << 16);
dma2Dest = DM2DAD_L | (DM2DAD_H << 16);
CPUCheckDMA(0, 4);
}
break;
}
case 0xD4:
DM3SAD_L = value;
UPDATE_REG(0xD4, DM3SAD_L);
break;
case 0xD6:
DM3SAD_H = value & 0x0FFF;
UPDATE_REG(0xD6, DM3SAD_H);
break;
case 0xD8:
DM3DAD_L = value;
UPDATE_REG(0xD8, DM3DAD_L);
break;
case 0xDA:
DM3DAD_H = value & 0x0FFF;
UPDATE_REG(0xDA, DM3DAD_H);
break;
case 0xDC:
DM3CNT_L = value;
UPDATE_REG(0xDC, 0);
break;
case 0xDE:
{
bool start = ((DM3CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xFFE0;
DM3CNT_H = value;
UPDATE_REG(0xDE, DM3CNT_H);
if (start && (value & 0x8000))
{
dma3Source = DM3SAD_L | (DM3SAD_H << 16);
dma3Dest = DM3DAD_L | (DM3DAD_H << 16);
CPUCheckDMA(0, 8);
}
break;
}
case 0x100:
timer0Reload = value;
interp_rate();
break;
case 0x102:
timer0Value = value;
timerOnOffDelay |= 1;
cpuNextEvent = cpuTotalTicks;
break;
case 0x104:
timer1Reload = value;
interp_rate();
break;
case 0x106:
timer1Value = value;
timerOnOffDelay |= 2;
cpuNextEvent = cpuTotalTicks;
break;
case 0x108:
timer2Reload = value;
break;
case 0x10A:
timer2Value = value;
timerOnOffDelay |= 4;
cpuNextEvent = cpuTotalTicks;
break;
case 0x10C:
timer3Reload = value;
break;
case 0x10E:
timer3Value = value;
timerOnOffDelay |= 8;
cpuNextEvent = cpuTotalTicks;
break;
case 0x128:
if (value & 0x80)
{
value &= 0xff7f;
if (value & 1 && (value & 0x4000))
{
UPDATE_REG(0x12a, 0xFF);
IF |= 0x80;
UPDATE_REG(0x202, IF);
value &= 0x7f7f;
}
}
UPDATE_REG(0x128, value);
break;
case 0x130:
P1 |= (value & 0x3FF);
UPDATE_REG(0x130, P1);
break;
case 0x132:
UPDATE_REG(0x132, value & 0xC3FF);
break;
case 0x200:
IE = value & 0x3FFF;
UPDATE_REG(0x200, IE);
if ((IME & 1) && (IF & IE) && armIrqEnable)
cpuNextEvent = cpuTotalTicks;
break;
case 0x202:
IF ^= (value & IF);
UPDATE_REG(0x202, IF);
break;
case 0x204:
{
memoryWait[0x0e] = memoryWaitSeq[0x0e] = gamepakRamWaitState[value & 3];
if (!speedHack)
{
memoryWait[0x08] = memoryWait[0x09] = gamepakWaitState[(value >> 2) & 3];
memoryWaitSeq[0x08] = memoryWaitSeq[0x09] =
gamepakWaitState0[(value >> 4) & 1];
memoryWait[0x0a] = memoryWait[0x0b] = gamepakWaitState[(value >> 5) & 3];
memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] =
gamepakWaitState1[(value >> 7) & 1];
memoryWait[0x0c] = memoryWait[0x0d] = gamepakWaitState[(value >> 8) & 3];
memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] =
gamepakWaitState2[(value >> 10) & 1];
}
else
{
memoryWait[0x08] = memoryWait[0x09] = 3;
memoryWaitSeq[0x08] = memoryWaitSeq[0x09] = 1;
memoryWait[0x0a] = memoryWait[0x0b] = 3;
memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] = 1;
memoryWait[0x0c] = memoryWait[0x0d] = 3;
memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] = 1;
}
for (int i = 8; i < 15; i++)
{
memoryWait32[i] = memoryWait[i] + memoryWaitSeq[i] + 1;
memoryWaitSeq32[i] = memoryWaitSeq[i] * 2 + 1;
}
if ((value & 0x4000) == 0x4000)
{
busPrefetchEnable = true;
busPrefetch = false;
busPrefetchCount = 0;
}
else
{
busPrefetchEnable = false;
busPrefetch = false;
busPrefetchCount = 0;
}
UPDATE_REG(0x204, value & 0x7FFF);
}
break;
case 0x208:
IME = value & 1;
UPDATE_REG(0x208, IME);
if ((IME & 1) && (IF & IE) && armIrqEnable)
cpuNextEvent = cpuTotalTicks;
break;
case 0x300:
if (value != 0)
value &= 0xFFFE;
UPDATE_REG(0x300, value);
break;
default:
UPDATE_REG(address & 0x3FE, value);
break;
}
}
void applyTimer()
{
if (timerOnOffDelay & 1)
{
timer0ClockReload = TIMER_TICKS[timer0Value & 3];
if (!timer0On && (timer0Value & 0x80))
{
// reload the counter
TM0D = timer0Reload;
timer0Ticks = (0x10000 - TM0D) << timer0ClockReload;
UPDATE_REG(0x100, TM0D);
}
timer0On = timer0Value & 0x80 ? true : false;
TM0CNT = timer0Value & 0xC7;
interp_rate();
UPDATE_REG(0x102, TM0CNT);
// CPUUpdateTicks();
}
if (timerOnOffDelay & 2)
{
timer1ClockReload = TIMER_TICKS[timer1Value & 3];
if (!timer1On && (timer1Value & 0x80))
{
// reload the counter
TM1D = timer1Reload;
timer1Ticks = (0x10000 - TM1D) << timer1ClockReload;
UPDATE_REG(0x104, TM1D);
}
timer1On = timer1Value & 0x80 ? true : false;
TM1CNT = timer1Value & 0xC7;
interp_rate();
UPDATE_REG(0x106, TM1CNT);
}
if (timerOnOffDelay & 4)
{
timer2ClockReload = TIMER_TICKS[timer2Value & 3];
if (!timer2On && (timer2Value & 0x80))
{
// reload the counter
TM2D = timer2Reload;
timer2Ticks = (0x10000 - TM2D) << timer2ClockReload;
UPDATE_REG(0x108, TM2D);
}
timer2On = timer2Value & 0x80 ? true : false;
TM2CNT = timer2Value & 0xC7;
UPDATE_REG(0x10A, TM2CNT);
}
if (timerOnOffDelay & 8)
{
timer3ClockReload = TIMER_TICKS[timer3Value & 3];
if (!timer3On && (timer3Value & 0x80))
{
// reload the counter
TM3D = timer3Reload;
timer3Ticks = (0x10000 - TM3D) << timer3ClockReload;
UPDATE_REG(0x10C, TM3D);
}
timer3On = timer3Value & 0x80 ? true : false;
TM3CNT = timer3Value & 0xC7;
UPDATE_REG(0x10E, TM3CNT);
}
cpuNextEvent = CPUUpdateTicks();
timerOnOffDelay = 0;
}
void CPULoadInternalBios()
{
// load internal BIOS
#ifdef WORDS_BIGENDIAN
for (size_t i = 0; i < sizeof(myROM) / 4; ++i)
{
WRITE32LE(&bios[i], myROM[i]);
}
#else
memcpy(bios, myROM, sizeof(myROM));
#endif
}
void CPUInit()
{
biosProtected[0] = 0x00;
biosProtected[1] = 0xf0;
biosProtected[2] = 0x29;
biosProtected[3] = 0xe1;
int i = 0;
for (i = 0; i < 256; i++)
{
int cpuBitSetCount = 0;
int j;
for (j = 0; j < 8; j++)
if (i & (1 << j))
cpuBitSetCount++;
cpuBitsSet[i] = cpuBitSetCount;
for (j = 0; j < 8; j++)
if (i & (1 << j))
break;
cpuLowestBitSet[i] = j;
}
for (i = 0; i < 0x400; i++)
ioReadable[i] = true;
for (i = 0x10; i < 0x48; i++)
ioReadable[i] = false;
for (i = 0x4c; i < 0x50; i++)
ioReadable[i] = false;
for (i = 0x54; i < 0x60; i++)
ioReadable[i] = false;
for (i = 0x8c; i < 0x90; i++)
ioReadable[i] = false;
for (i = 0xa0; i < 0xb8; i++)
ioReadable[i] = false;
for (i = 0xbc; i < 0xc4; i++)
ioReadable[i] = false;
for (i = 0xc8; i < 0xd0; i++)
ioReadable[i] = false;
for (i = 0xd4; i < 0xdc; i++)
ioReadable[i] = false;
for (i = 0xe0; i < 0x100; i++)
ioReadable[i] = false;
for (i = 0x110; i < 0x120; i++)
ioReadable[i] = false;
for (i = 0x12c; i < 0x130; i++)
ioReadable[i] = false;
for (i = 0x138; i < 0x140; i++)
ioReadable[i] = false;
for (i = 0x144; i < 0x150; i++)
ioReadable[i] = false;
for (i = 0x15c; i < 0x200; i++)
ioReadable[i] = false;
for (i = 0x20c; i < 0x300; i++)
ioReadable[i] = false;
for (i = 0x304; i < 0x400; i++)
ioReadable[i] = false;
if (romSize < 0x1fe2000)
{
*((u16 *)&rom[0x1fe209c]) = 0xdffa; // SWI 0xFA
*((u16 *)&rom[0x1fe209e]) = 0x4770; // BX LR
}
else
{
agbPrintEnable(false);
}
gbaSaveType = 0;
eepromInUse = 0;
saveType = 0;
}
void CPUReset()
{
systemReset();
if (gbaSaveType == 0)
{
if (eepromInUse)
gbaSaveType = 3;
else
switch (saveType)
{
case 1:
gbaSaveType = 1;
break;
case 2:
gbaSaveType = 2;
break;
}
}
// clean picture
memset(pix, 0, 4 * 241 * 162);
// clean registers
memset(®[0], 0, sizeof(reg));
// clean OAM
memset(oam, 0, 0x400);
// clean palette
memset(paletteRAM, 0, 0x400);
// clean vram
memset(vram, 0, 0x20000);
// clean io memory
memset(ioMem, 0, 0x400);
DISPCNT = 0x0080;
DISPSTAT = 0x0000;
VCOUNT = (useBios && !skipBios) ? 0 : 0x007E;
BG0CNT = 0x0000;
BG1CNT = 0x0000;
BG2CNT = 0x0000;
BG3CNT = 0x0000;
BG0HOFS = 0x0000;
BG0VOFS = 0x0000;
BG1HOFS = 0x0000;
BG1VOFS = 0x0000;
BG2HOFS = 0x0000;
BG2VOFS = 0x0000;
BG3HOFS = 0x0000;
BG3VOFS = 0x0000;
BG2PA = 0x0100;
BG2PB = 0x0000;
BG2PC = 0x0000;
BG2PD = 0x0100;
BG2X_L = 0x0000;
BG2X_H = 0x0000;
BG2Y_L = 0x0000;
BG2Y_H = 0x0000;
BG3PA = 0x0100;
BG3PB = 0x0000;
BG3PC = 0x0000;
BG3PD = 0x0100;
BG3X_L = 0x0000;
BG3X_H = 0x0000;
BG3Y_L = 0x0000;
BG3Y_H = 0x0000;
WIN0H = 0x0000;
WIN1H = 0x0000;
WIN0V = 0x0000;
WIN1V = 0x0000;
WININ = 0x0000;
WINOUT = 0x0000;
MOSAIC = 0x0000;
BLDMOD = 0x0000;
COLEV = 0x0000;
COLY = 0x0000;
DM0SAD_L = 0x0000;
DM0SAD_H = 0x0000;
DM0DAD_L = 0x0000;
DM0DAD_H = 0x0000;
DM0CNT_L = 0x0000;
DM0CNT_H = 0x0000;
DM1SAD_L = 0x0000;
DM1SAD_H = 0x0000;
DM1DAD_L = 0x0000;
DM1DAD_H = 0x0000;
DM1CNT_L = 0x0000;
DM1CNT_H = 0x0000;
DM2SAD_L = 0x0000;
DM2SAD_H = 0x0000;
DM2DAD_L = 0x0000;
DM2DAD_H = 0x0000;
DM2CNT_L = 0x0000;
DM2CNT_H = 0x0000;
DM3SAD_L = 0x0000;
DM3SAD_H = 0x0000;
DM3DAD_L = 0x0000;
DM3DAD_H = 0x0000;
DM3CNT_L = 0x0000;
DM3CNT_H = 0x0000;
TM0D = 0x0000;
TM0CNT = 0x0000;
TM1D = 0x0000;
TM1CNT = 0x0000;
TM2D = 0x0000;
TM2CNT = 0x0000;
TM3D = 0x0000;
TM3CNT = 0x0000;
P1 = 0x03FF;
IE = 0x0000;
IF = 0x0000;
IME = 0x0000;
armMode = 0x1F;
armState = true;
if (cpuIsMultiBoot)
{
reg[13].I = 0x03007F00;
reg[15].I = 0x02000000;
reg[16].I = 0x00000000;
reg[R13_IRQ].I = 0x03007FA0;
reg[R13_SVC].I = 0x03007FE0;
armIrqEnable = true;
}
else
{
if (useBios && !skipBios)
{
reg[15].I = 0x00000000;
armMode = 0x13;
armIrqEnable = false;
}
else
{
reg[13].I = 0x03007F00;
reg[15].I = 0x08000000;
reg[16].I = 0x00000000;
reg[R13_IRQ].I = 0x03007FA0;
reg[R13_SVC].I = 0x03007FE0;
armIrqEnable = true;
}
}
C_FLAG = V_FLAG = N_FLAG = Z_FLAG = false;
UPDATE_REG(0x00, DISPCNT);
UPDATE_REG(0x06, VCOUNT);
UPDATE_REG(0x20, BG2PA);
UPDATE_REG(0x26, BG2PD);
UPDATE_REG(0x30, BG3PA);
UPDATE_REG(0x36, BG3PD);
UPDATE_REG(0x130, P1);
UPDATE_REG(0x88, 0x200);
// disable FIQ
reg[16].I |= 0x40;
CPUUpdateCPSR();
armNextPC = reg[15].I;
reg[15].I += 4;
// reset internal state
intState = false;
stopState = false;
holdState = false;
holdType = 0;
biosProtected[0] = 0x00;
biosProtected[1] = 0xf0;
biosProtected[2] = 0x29;
biosProtected[3] = 0xe1;
lcdTicks = (useBios && !skipBios) ? 1008 : 208;
timer0On = false;
timer0Ticks = 0;
timer0Reload = 0;
timer0ClockReload = 0;
timer1On = false;
timer1Ticks = 0;
timer1Reload = 0;
timer1ClockReload = 0;
timer2On = false;
timer2Ticks = 0;
timer2Reload = 0;
timer2ClockReload = 0;
timer3On = false;
timer3Ticks = 0;
timer3Reload = 0;
timer3ClockReload = 0;
dma0Source = 0;
dma0Dest = 0;
dma1Source = 0;
dma1Dest = 0;
dma2Source = 0;
dma2Dest = 0;
dma3Source = 0;
dma3Dest = 0;
cpuSaveGameFunc = flashSaveDecide;
renderLine = mode0RenderLine;
fxOn = false;
windowOn = false;
saveType = 0;
layerEnable = DISPCNT & layerSettings;
CPUUpdateRenderBuffers(true);
for (int i = 0; i < 256; i++)
{
memoryMap[i].address = (u8 *)&dummyAddress;
memoryMap[i].mask = 0;
}
memoryMap[0].address = bios;
memoryMap[0].mask = 0x3FFF;
memoryMap[2].address = workRAM;
memoryMap[2].mask = 0x3FFFF;
memoryMap[3].address = internalRAM;
memoryMap[3].mask = 0x7FFF;
memoryMap[4].address = ioMem;
memoryMap[4].mask = 0x3FF;
memoryMap[5].address = paletteRAM;
memoryMap[5].mask = 0x3FF;
memoryMap[6].address = vram;
memoryMap[6].mask = 0x1FFFF;
memoryMap[7].address = oam;
memoryMap[7].mask = 0x3FF;
memoryMap[8].address = rom;
memoryMap[8].mask = 0x1FFFFFF;
memoryMap[9].address = rom;
memoryMap[9].mask = 0x1FFFFFF;
memoryMap[10].address = rom;
memoryMap[10].mask = 0x1FFFFFF;
memoryMap[12].address = rom;
memoryMap[12].mask = 0x1FFFFFF;
memoryMap[14].address = flashSaveMemory;
memoryMap[14].mask = 0xFFFF;
eepromReset();
flashReset();
rtcReset();
CPUUpdateWindow0();
CPUUpdateWindow1();
// make sure registers are correctly initialized if not using BIOS
if (!useBios)
{
if (cpuIsMultiBoot)
BIOS_RegisterRamReset(0xfe);
else
BIOS_RegisterRamReset(0xff);
}
else
{
if (cpuIsMultiBoot)
BIOS_RegisterRamReset(0xfe);
}
switch (cpuSaveType)
{
case 0: // automatic
cpuSramEnabled = true;
cpuFlashEnabled = true;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = false;
saveType = gbaSaveType = 0;
break;
case 1: // EEPROM
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = false;
saveType = gbaSaveType = 3;
// EEPROM usage is automatically detected
break;
case 2: // SRAM
cpuSramEnabled = true;
cpuFlashEnabled = false;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
cpuSaveGameFunc = sramDelayedWrite; // to insure we detect the write
saveType = gbaSaveType = 1;
break;
case 3: // FLASH
cpuSramEnabled = false;
cpuFlashEnabled = true;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
cpuSaveGameFunc = flashDelayedWrite; // to insure we detect the write
saveType = gbaSaveType = 2;
break;
case 4: // EEPROM+Sensor
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = true;
// EEPROM usage is automatically detected
saveType = gbaSaveType = 3;
break;
case 5: // NONE
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
// no save at all
saveType = gbaSaveType = 5;
break;
}
ARM_PREFETCH;
cpuDmaHack = false;
SWITicks = 0;
IRQTicks = 0;
soundReset();
systemRefreshScreen();
}
void CPUInterrupt()
{
u32 PC = reg[15].I;
bool savedState = armState;
CPUSwitchMode(0x12, true, false);
reg[14].I = PC;
if (!savedState)
reg[14].I += 2;
reg[15].I = 0x18;
armState = true;
armIrqEnable = false;
armNextPC = reg[15].I;
reg[15].I += 4;
ARM_PREFETCH;
// if(!holdState)
biosProtected[0] = 0x02;
biosProtected[1] = 0xc0;
biosProtected[2] = 0x5e;
biosProtected[3] = 0xe5;
}
static inline void CPUDrawPixLine()
{
switch (systemColorDepth)
{
case 16:
{
u16 *dest = (u16 *)pix + 241 * (VCOUNT + 1);
for (int x = 0; x < 240; )
{
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
}
// for filters that read past the screen
*dest++ = 0;
break;
}
case 24:
{
u8 *dest = (u8 *)pix + 240 * VCOUNT * 3;
for (int x = 0; x < 240; )
{
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
}
break;
}
case 32:
{
u32 *dest = (u32 *)pix + 241 * (VCOUNT + 1);
for (int x = 0; x < 240; )
{
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
}
break;
}
}
}
static inline u32 CPUGetUserInput()
{
// update joystick information
systemReadJoypads();
u32 joy = systemGetJoypad(0, cpuEEPROMSensorEnabled);
P1 = 0x03FF ^ (joy & 0x3FF);
UPDATE_REG(0x130, P1);
// HACK: some special "buttons"
extButtons = (joy >> 18);
speedup = (extButtons & 1) != 0;
return joy;
}
static inline void CPUBeforeEmulation()
{
if (newFrame)
{
CallRegisteredLuaFunctions(LUACALL_BEFOREEMULATION);
u32 joy = CPUGetUserInput();
// this seems wrong, but there are cases where the game
// can enter the stop state without requesting an IRQ from
// the joypad.
// FIXME: where is the right place???
u16 P1CNT = READ16LE(((u16 *)&ioMem[0x132]));
if ((P1CNT & 0x4000) || stopState)
{
u16 p1 = (0x3FF ^ P1) & 0x3FF;
if (P1CNT & 0x8000)
{
if (p1 == (P1CNT & 0x3FF))
{
IF |= 0x1000;
UPDATE_REG(0x202, IF);
}
}
else
{
if (p1 & P1CNT)
{
IF |= 0x1000;
UPDATE_REG(0x202, IF);
}
}
}
//if (cpuEEPROMSensorEnabled)
//systemUpdateMotionSensor(0);
VBAMovieResetIfRequested();
newFrame = false;
}
}
static inline void CPUFrameBoundaryWork()
{
// HACK: some special "buttons"
if (cheatsEnabled)
cheatsCheckKeys(P1 ^ 0x3FF, extButtons);
systemFrameBoundaryWork();
}
void CPULoop(int _ticks)
{
CPUBeforeEmulation();
int32 ticks = _ticks;
int32 clockTicks;
int32 timerOverflow = 0;
bool newVideoFrame = false;
// variable used by the CPU core
cpuTotalTicks = 0;
cpuNextEvent = CPUUpdateTicks();
if (cpuNextEvent > ticks)
cpuNextEvent = ticks;
#ifdef SDL
cpuBreakLoop = false;
#endif
for (;;)
{
#ifndef FINAL_VERSION
if (systemDebug)
{
if (systemDebug >= 10 && !holdState)
{
CPUUpdateCPSR();
#ifdef BKPT_SUPPORT
if (debugger_last)
{
sprintf(
buffer,
"R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n",
oldreg[0],
oldreg[1],
oldreg[2],
oldreg[3],
oldreg[4],
oldreg[5],
oldreg[6],
oldreg[7],
oldreg[8],
oldreg[9],
oldreg[10],
oldreg[11],
oldreg[12],
oldreg[13],
oldreg[14],
oldreg[15],
oldreg[16],
oldreg[17]);
}
#endif
sprintf(
buffer,
"R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x"
"R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n",
reg[0].I,
reg[1].I,
reg[2].I,
reg[3].I,
reg[4].I,
reg[5].I,
reg[6].I,
reg[7].I,
reg[8].I,
reg[9].I,
reg[10].I,
reg[11].I,
reg[12].I,
reg[13].I,
reg[14].I,
reg[15].I,
reg[16].I,
reg[17].I);
log(buffer);
}
else if (!holdState)
{
log("PC=%08x\n", armNextPC);
}
}
#endif /* FINAL_VERSION */
if (!holdState && !SWITicks)
{
if (armState)
{
if (!armExecute())
return;
}
else
{
if (!thumbExecute())
return;
}
clockTicks = 0;
}
else
clockTicks = CPUUpdateTicks();
cpuTotalTicks += clockTicks;
if (cpuTotalTicks >= cpuNextEvent)
{
int32 remainingTicks = cpuTotalTicks - cpuNextEvent;
if (SWITicks)
{
SWITicks -= clockTicks;
if (SWITicks < 0)
SWITicks = 0;
}
clockTicks = cpuNextEvent;
cpuTotalTicks = 0;
cpuDmaHack = false;
updateLoop:
if (IRQTicks)
{
IRQTicks -= clockTicks;
if (IRQTicks < 0)
IRQTicks = 0;
}
lcdTicks -= clockTicks;
if (lcdTicks <= 0)
{
if (DISPSTAT & 1) // V-BLANK
{ // if in V-Blank mode, keep computing...
if (DISPSTAT & 2)
{
lcdTicks += 1008;
VCOUNT++;
UPDATE_REG(0x06, VCOUNT);
DISPSTAT &= 0xFFFD;
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
else
{
lcdTicks += 224;
DISPSTAT |= 2;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 16)
{
IF |= 2;
UPDATE_REG(0x202, IF);
}
}
if (VCOUNT >= 228) //Reaching last line
{
DISPSTAT &= 0xFFFC;
UPDATE_REG(0x04, DISPSTAT);
VCOUNT = 0;
UPDATE_REG(0x06, VCOUNT);
CPUCompareVCOUNT();
}
}
else
{
if (DISPSTAT & 2)
{
// if in H-Blank, leave it and move to drawing mode
VCOUNT++;
UPDATE_REG(0x06, VCOUNT);
lcdTicks += 1008;
DISPSTAT &= 0xFFFD;
if (VCOUNT == 160)
{
DISPSTAT |= 1;
DISPSTAT &= 0xFFFD;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 0x0008)
{
IF |= 1;
UPDATE_REG(0x202, IF);
}
CPUCheckDMA(1, 0x0f);
newVideoFrame = true;
}
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
else
{
if (systemFrameDrawingRequired())
{
(*renderLine)();
CPUDrawPixLine();
}
// entering H-Blank
DISPSTAT |= 2;
UPDATE_REG(0x04, DISPSTAT);
lcdTicks += 224;
CPUCheckDMA(2, 0x0f);
if (DISPSTAT & 16)
{
IF |= 2;
UPDATE_REG(0x202, IF);
}
}
}
}
// we shouldn't be doing sound in stop state, but we lose synchronization
// if sound is disabled, so in stop state, soundTick will just produce
// mute sound
soundTicks -= clockTicks;
if (soundTicks <= 0)
{
soundTick();
soundTicks += soundTickStep;
}
if (!stopState)
{
if (timer0On)
{
timer0Ticks -= clockTicks;
if (timer0Ticks <= 0)
{
timer0Ticks += (0x10000 - timer0Reload) << timer0ClockReload;
timerOverflow |= 1;
soundTimerOverflow(0);
if (TM0CNT & 0x40)
{
IF |= 0x08;
UPDATE_REG(0x202, IF);
}
}
TM0D = 0xFFFF - (timer0Ticks >> timer0ClockReload) & 0xFFFF;
UPDATE_REG(0x100, TM0D);
}
if (timer1On)
{
if (TM1CNT & 4)
{
if (timerOverflow & 1)
{
TM1D++;
if (TM1D == 0)
{
TM1D += timer1Reload;
timerOverflow |= 2;
soundTimerOverflow(1);
if (TM1CNT & 0x40)
{
IF |= 0x10;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x104, TM1D);
}
}
else
{
timer1Ticks -= clockTicks;
if (timer1Ticks <= 0)
{
timer1Ticks += (0x10000 - timer1Reload) << timer1ClockReload;
timerOverflow |= 2;
soundTimerOverflow(1);
if (TM1CNT & 0x40)
{
IF |= 0x10;
UPDATE_REG(0x202, IF);
}
}
TM1D = 0xFFFF - (timer1Ticks >> timer1ClockReload) & 0xFFFF;
UPDATE_REG(0x104, TM1D);
}
}
if (timer2On)
{
if (TM2CNT & 4)
{
if (timerOverflow & 2)
{
TM2D++;
if (TM2D == 0)
{
TM2D += timer2Reload;
timerOverflow |= 4;
if (TM2CNT & 0x40)
{
IF |= 0x20;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x108, TM2D);
}
}
else
{
timer2Ticks -= clockTicks;
if (timer2Ticks <= 0)
{
timer2Ticks += (0x10000 - timer2Reload) << timer2ClockReload;
timerOverflow |= 4;
if (TM2CNT & 0x40)
{
IF |= 0x20;
UPDATE_REG(0x202, IF);
}
}
TM2D = 0xFFFF - (timer2Ticks >> timer2ClockReload) & 0xFFFF;
UPDATE_REG(0x108, TM2D);
}
}
if (timer3On)
{
if (TM3CNT & 4)
{
if (timerOverflow & 4)
{
TM3D++;
if (TM3D == 0)
{
TM3D += timer3Reload;
if (TM3CNT & 0x40)
{
IF |= 0x40;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x10C, TM3D);
}
}
else
{
timer3Ticks -= clockTicks;
if (timer3Ticks <= 0)
{
timer3Ticks += (0x10000 - timer3Reload) << timer3ClockReload;
if (TM3CNT & 0x40)
{
IF |= 0x40;
UPDATE_REG(0x202, IF);
}
}
TM3D = 0xFFFF - (timer3Ticks >> timer3ClockReload) & 0xFFFF;
UPDATE_REG(0x10C, TM3D);
}
}
}
timerOverflow = 0;
#ifdef PROFILING
profilingTicks -= clockTicks;
if (profilingTicks <= 0)
{
profilingTicks += profilingTicksReload;
if (profilSegment)
{
profile_segment *seg = profilSegment;
do
{
u16 *b = (u16 *)seg->sbuf;
int pc = ((reg[15].I - seg->s_lowpc) * seg->s_scale) / 0x10000;
if (pc >= 0 && pc < seg->ssiz)
{
b[pc]++;
break;
}
seg = seg->next;
}
while (seg);
}
}
#endif
if (newVideoFrame)
{
newVideoFrame = false;
CPUFrameBoundaryWork();
}
ticks -= clockTicks;
cpuNextEvent = CPUUpdateTicks();
if (cpuDmaTicksToUpdate > 0)
{
if (cpuDmaTicksToUpdate > cpuNextEvent)
clockTicks = cpuNextEvent;
else
clockTicks = cpuDmaTicksToUpdate;
cpuDmaTicksToUpdate -= clockTicks;
cpuDmaHack = true;
goto updateLoop; // this is evil
}
if (IF && (IME & 1) && armIrqEnable)
{
int res = IF & IE;
if (stopState)
res &= 0x3080;
if (res)
{
if (intState)
{
if (!IRQTicks)
{
CPUInterrupt();
intState = false;
holdState = false;
stopState = false;
holdType = 0;
}
}
else
{
if (!holdState)
{
intState = true;
IRQTicks = 7;
if (cpuNextEvent > IRQTicks)
cpuNextEvent = IRQTicks;
}
else
{
CPUInterrupt();
holdState = false;
stopState = false;
holdType = 0;
}
}
// Stops the SWI Ticks emulation if an IRQ is executed
//(to avoid problems with nested IRQ/SWI)
if (SWITicks)
SWITicks = 0;
}
}
if (remainingTicks > 0)
{
if (remainingTicks > cpuNextEvent)
clockTicks = cpuNextEvent;
else
clockTicks = remainingTicks;
remainingTicks -= clockTicks;
goto updateLoop; // this is evil, too
}
if (timerOnOffDelay)
applyTimer();
//if (cpuNextEvent > ticks) // FIXME: can be negative and slow down
// cpuNextEvent = ticks;
#ifdef SDL
if (newFrame || useOldFrameTiming && ticks <= 0 || cpuBreakLoop)
#else
if (newFrame || useOldFrameTiming && ticks <= 0)
#endif
{
break;
}
}
}
}
struct EmulatedSystem GBASystem =
{
// emuMain
CPULoop,
// emuReset
CPUReset,
// emuCleanUp
CPUCleanUp,
// emuReadBattery
CPUReadBatteryFile,
// emuWriteBattery
CPUWriteBatteryFile,
// emuReadBatteryFromStream
CPUReadBatteryFromStream,
// emuWriteBatteryToStream
CPUWriteBatteryToStream,
// emuReadState
CPUReadState,
// emuWriteState
CPUWriteState,
// emuReadStateFromStream
CPUReadStateFromStream,
// emuWriteStateToStream
CPUWriteStateToStream,
// emuReadMemState
CPUReadMemState,
// emuWriteMemState
CPUWriteMemState,
// emuWritePNG
CPUWritePNGFile,
// emuWriteBMP
CPUWriteBMPFile,
// emuUpdateCPSR
CPUUpdateCPSR,
// emuHasDebugger
true,
// emuCount
#ifdef FINAL_VERSION
250000,
#else
5000,
#endif
};
| TASVideos/vba-rerecording | src/gba/V8/GBA.cpp | C++ | gpl-2.0 | 91,319 |
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(SpriteRenderer))]
public class SpriteRandomiser : MonoBehaviour {
[System.Serializable]
public class PossibleState
{
public Sprite texture = null;
public Color color = Color.white;
};
public PossibleState[] possibleStates = new PossibleState[0];
public void RandomiseSprite()
{
Random.seed = (int)Time.time;
if(possibleStates.Length > 0)
{
PossibleState state = possibleStates[Random.Range(0,possibleStates.Length)];
SpriteRenderer spriteRenderer = GetComponent<Renderer>() as SpriteRenderer;
spriteRenderer.sprite = state.texture;
spriteRenderer.color = state.color;
}
}
// Use this for initialization
void Start ()
{
RandomiseSprite();
}
}
| Almax27/LD31 | Assets/Scripts/Utility/SpriteRandomiser.cs | C# | gpl-2.0 | 759 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AppTestDeployment")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AppTestDeployment")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| EpicPonyTeam/RarityUpdater | AppTestDeployment/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 2,393 |
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Session;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
namespace MediaBrowser.Controller.Net
{
public interface ISessionContext
{
Task<SessionInfo> GetSession(object requestContext);
Task<User> GetUser(object requestContext);
Task<SessionInfo> GetSession(IRequest requestContext);
Task<User> GetUser(IRequest requestContext);
}
}
| jose-pr/Emby | MediaBrowser.Controller/Net/ISessionContext.cs | C# | gpl-2.0 | 469 |
<section id="options">
<?php
$terms = array();
$vid = NULL;
$vid_machine_name = 'portfolio_categories';
$vocabulary = taxonomy_vocabulary_machine_name_load($vid_machine_name);
if (!empty($vocabulary->vid)) {
$vid = $vocabulary->vid;
}
if (!empty($vid)) {
$terms = taxonomy_get_tree($vid);
}
?>
<ul id="filters" class="option-set right" data-option-key="filter">
<li><a href="#filter" data-option-value="*" class="button small selected"><?php print t('Show All'); ?></a></li>
<?php if (!empty($terms)): ?>
<?php foreach ($terms as $term): ?>
<li><a href="#filter" data-option-value=".tid-<?php print $term->tid; ?>" class="button small"><?php print $term->name; ?></a></li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</section> | emperorcow/chaosbrewclub | sites/all/modules/tabvn/portfolio/portfolio_filter.tpl.php | PHP | gpl-2.0 | 791 |
/**
* jBorZoi - An Elliptic Curve Cryptography Library
*
* Copyright (C) 2003 Dragongate Technologies Ltd.
*
* 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, 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.
*/
package com.dragongate_technologies.borZoi;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* Elliptic Curve Private Keys consisting of two member variables: dp,
* the EC domain parameters and s, the private key which must
* be kept secret.
* @author <a href="http://www.dragongate-technologies.com">Dragongate Technologies Ltd.</a>
* @version 0.90
*/
public class ECPrivKey {
/**
* The EC Domain Parameters
*/
public ECDomainParameters dp;
/**
* The Private Key
*/
public BigInteger s;
/**
* Generate a random private key with ECDomainParameters dp
*/
public ECPrivKey(ECDomainParameters dp) {
this.dp = (ECDomainParameters) dp.clone();
SecureRandom rnd = new SecureRandom();
s = new BigInteger(dp.m, rnd);
s = s.mod(dp.r);
}
/**
* Generate a private key with ECDomainParameters dp
* and private key s
*/
public ECPrivKey(ECDomainParameters dp, BigInteger s) {
this.dp = dp;
this.s = s;
}
public String toString() {
String str = new String("dp: ").concat(dp.toString()).concat("\n");
str = str.concat("s: ").concat(s.toString()).concat("\n");
return str;
}
protected Object clone() {
return new ECPrivKey(dp, s);
}
}
| HateBreed/old-codes-from-studies | cryptoclient_in_java/com/dragongate_technologies/borZoi/ECPrivKey.java | Java | gpl-2.0 | 2,027 |
/*
The GTKWorkbook Project <http://gtkworkbook.sourceforge.net/>
Copyright (C) 2008, 2009 John Bellone, Jr. <jvb4@njit.edu>
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 PRACTICAL 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 the library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA
*/
#include <sstream>
#include <gdk/gdkkeysyms.h>
#include <libgtkworkbook/workbook.h>
#include <proactor/Proactor.hpp>
#include <proactor/Event.hpp>
#include <network/Tcp.hpp>
#include "Realtime.hpp"
using namespace realtime;
/* @description: This method creates a filename with the prefix supplied and
uses the pid of the process as its suffix.
@pre: The prefix (should be a file path, obviously). */
static std::string
AppendProcessId (const gchar * pre) {
std::stringstream s;
s << pre << getppid();
return s.str();
}
static void
StreamOpenDialogCallback (GtkWidget * w, gpointer data) {
Realtime * rt = (Realtime *)data;
OpenStreamDialog * dialog = rt->streamdialog();
if (dialog->widget == NULL) {
dialog->rt = rt;
dialog->widget = gtk_dialog_new_with_buttons ("Open stream ", GTK_WINDOW (rt->app()->gtkwindow()),
(GtkDialogFlags) (GTK_DIALOG_MODAL|GTK_DIALOG_NO_SEPARATOR),
GTK_STOCK_OK,
GTK_RESPONSE_OK,
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
NULL);
GtkWidget * gtk_frame = gtk_frame_new ("Connection Options");
GtkWidget * hbox = gtk_hbox_new(FALSE, 0);
GtkWidget * box = GTK_DIALOG (dialog->widget)->vbox;
dialog->host_entry = gtk_entry_new();
dialog->port_entry = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (dialog->host_entry), 15);
gtk_entry_set_max_length (GTK_ENTRY (dialog->port_entry), 5);
gtk_entry_set_width_chars (GTK_ENTRY (dialog->host_entry), 15);
gtk_entry_set_width_chars (GTK_ENTRY (dialog->port_entry), 5);
gtk_box_pack_start (GTK_BOX (hbox), dialog->host_entry, FALSE, FALSE, 0);
gtk_box_pack_end (GTK_BOX (hbox), dialog->port_entry, FALSE, FALSE, 0);
gtk_container_add (GTK_CONTAINER (gtk_frame), hbox);
gtk_box_pack_start (GTK_BOX (box), gtk_frame, FALSE, FALSE, 0);
g_signal_connect (G_OBJECT (dialog->widget), "delete-event",
G_CALLBACK (gtk_widget_hide_on_delete), NULL);
}
gtk_widget_show_all ( dialog->widget );
if (gtk_dialog_run (GTK_DIALOG (dialog->widget)) == GTK_RESPONSE_OK) {
const char * host_value = gtk_entry_get_text (GTK_ENTRY (dialog->host_entry));
const char * port_value = gtk_entry_get_text (GTK_ENTRY (dialog->port_entry));
Sheet * sheet = rt->workbook()->add_new_sheet (rt->workbook(), host_value, 100, 20);
if (IS_NULLSTR (host_value) || IS_NULLSTR (port_value)) {
g_warning ("One of requird values are empty");
}
else if (sheet == NULL) {
g_warning ("Cannot open connection to %s:%s because of failure to add sheet",
host_value, port_value);
}
else if (rt->OpenTcpClient (sheet, host_value, atoi (port_value)) == false) {
// STUB: Popup an alertbox about failing to connect?
}
else {
// STUB: Success. Do we want to do anything else here?
g_message ("Client connection opened on %s:%s on sheet %s", host_value, port_value, sheet->name);
}
}
gtk_widget_hide_all ( dialog->widget );
}
Realtime::Realtime (Application * appstate, Handle * platform)
: Plugin (appstate, platform) {
ConfigPair * logpath =
appstate->config()->get_pair (appstate->config(), "realtime", "log", "path");
if (IS_NULL (logpath)) {
g_critical ("Failed loading log->path from configuration file. Exiting application.");
exit(1);
}
std::string logname = std::string (logpath->value).append("/");
logname.append (AppendProcessId("realtime.").append(".log"));
if ((pktlog = fopen (logname.c_str(), "w")) == NULL) {
g_critical ("Failed opening file '%s' for packet logging", logname.c_str());
}
this->wb = workbook_open (appstate->gtkwindow(), "realtime");
this->packet_parser = NULL;
this->tcp_server = NULL;
}
Realtime::~Realtime (void) {
// Iterate through the list of active connections, and begin closing them. This should also
// include deleting the pointers to all of the accepting threads. Eventually there should be
// a boost::shared_ptr here so that we don't have to do the dirty work.
ActiveThreads::iterator it = this->threads.begin();
while (it != this->threads.end()) {
network::TcpSocket * socket = ((*it).first);
concurrent::Thread * thread = ((*it).second);
it = this->threads.erase (it);
if (socket) delete socket;
if (thread) {
thread->stop();
delete thread;
}
}
if (this->packet_parser) {
this->packet_parser->stop();
delete this->packet_parser;
}
if (this->tcp_server) {
this->tcp_server->stop();
delete this->tcp_server;
}
FCLOSE (this->pktlog);
}
bool
Realtime::CreateNewServerConnection (network::TcpServerSocket * socket, AcceptThread * accept_thread) {
this->threads.push_back ( ActiveThread (socket, accept_thread) );
if (this->tcp_server->addWorker (accept_thread) == false) {
g_critical ("Failed starting accepting thread on socket %d", socket->getPort() );
return false;
}
return true;
}
bool
Realtime::CreateNewClientConnection (network::TcpClientSocket * socket, CsvParser * csv, NetworkDispatcher * nd) {
this->threads.push_back ( ActiveThread (socket, csv) );
this->threads.push_back ( ActiveThread (NULL, nd) ); // this is a hack
ConnectionThread * reader = new ConnectionThread (socket);
if (nd->addWorker (reader) == false) {
g_critical ("Failed starting the client reader");
delete reader;
return false;
}
this->threads.push_back ( ActiveThread (NULL, reader) ); // this is a hack
return true;
}
bool
Realtime::OpenTcpServer (int port) {
// Has to be above the service ports.
if (port < 1000) {
g_warning ("Failed starting Tcp server: port (%d) must be above 1000", port);
return false;
}
// The first time we attempt to create a port to receive input on we need to create a dispatcher, and
// specify an event identifier so that we can communicate with it from workers. At this point the
// Packet Parser is created as well.
if (this->tcp_server == NULL) {
int eventId = proactor::Event::uniqueEventId();
NetworkDispatcher * nd = new NetworkDispatcher (eventId);
PacketParser * pp = new PacketParser (this->workbook(), this->pktlog, 0);
if (nd->start() == false) {
g_critical ("Failed starting network dispatcher for tcp server");
return false;
}
if (this->app()->proactor()->addWorker (eventId, pp) == false) {
g_critical ("Failed starting packet parser for tcp server");
return false;
}
this->tcp_server = nd;
this->packet_parser = pp;
}
network::TcpServerSocket * socket = new network::TcpServerSocket (port);
if (socket->start(5) == false) {
g_critical ("Failed starting network socket for tcp server on port %d", port);
return false;
}
AcceptThread * accept_thread = new AcceptThread (socket->newAcceptor());
return this->CreateNewServerConnection (socket, accept_thread);
}
bool
Realtime::OpenTcpClient (Sheet * sheet, const std::string & address, int port) {
// Has to be above the service ports.
if (port < 1000) {
g_warning ("Failed starting Tcp client: port (%d) must be above 1000", port);
return false;
}
// We need to create a network dispatcher for each one of these connections because of
// the current limitation of the Proactor design. It really needs to be rewritten, but
// that is a separate project in and of itself. For now a list of dispatchers must be
// kept so that we do not lose track.
int eventId = proactor::Event::uniqueEventId();
NetworkDispatcher * dispatcher = new NetworkDispatcher (eventId);
if (dispatcher->start() == false) {
g_critical ("Failed starting network dispatcher for %s:%d", address.c_str(), port);
delete dispatcher;
return false;
}
// Keeping this simple is the reason why we need multiple dispatchers. If I could come
// up with a simple way to strap on the ability to have multiple sheets without the need
// for an additioanl dispatcher/csv combo I would. It totally destroys the principle of
// the proactor design.
CsvParser * csv = new CsvParser (sheet, this->pktlog, 0);
if (this->app()->proactor()->addWorker (eventId, csv) == false) {
g_critical ("Failed starting csv parser and adding to proactor for %s:%d",
address.c_str(), port);
delete csv;
delete dispatcher;
return false;
}
network::TcpClientSocket * socket = new network::TcpClientSocket;
if (socket->connect (address.c_str(), port) == false) {
g_critical ("Failed making Tcp connection to %s:%d", address.c_str(), port);
delete socket;
delete csv;
delete dispatcher;
return false;
}
return this->CreateNewClientConnection (socket, csv, dispatcher);
}
void
Realtime::Start(void) {
Config * cfg = this->app()->config();
ConfigPair * servport = cfg->get_pair (cfg, "realtime", "tcp", "port");
int port = atoi (servport->value);
if (this->OpenTcpServer (port) == true) {
g_message ("Opened Tcp server on port %d", port);
}
}
GtkWidget *
Realtime::CreateMainMenu (void) {
GtkWidget * rtmenu = gtk_menu_new();
GtkWidget * rtmenu_item = gtk_menu_item_new_with_label ("Realtime");
GtkWidget * rtmenu_open = gtk_menu_item_new_with_label ("Open Csv stream...");
gtk_menu_shell_append (GTK_MENU_SHELL (rtmenu), rtmenu_open);
g_signal_connect (G_OBJECT (rtmenu_open), "activate",
G_CALLBACK (StreamOpenDialogCallback), this);
gtk_menu_item_set_submenu (GTK_MENU_ITEM (rtmenu_item), rtmenu);
return rtmenu_item;
}
GtkWidget *
Realtime::BuildLayout (void) {
GtkWidget * gtk_menu = this->app()->gtkmenu();
GtkWidget * box = gtk_vbox_new (FALSE, 0);
GtkWidget * realtime_menu = this->CreateMainMenu();
// Append to the existing menu structure from the application.
gtk_menu_shell_prepend (GTK_MENU_SHELL (gtk_menu), realtime_menu);
// Setup the workbook.
wb->signals[SIG_WORKBOOK_CHANGED] = this->app()->signals[Application::SHEET_CHANGED];
wb->gtk_box = box;
// Pack all of the objects into a vertical box, and then pack that box into the application.
gtk_box_pack_start (GTK_BOX (box), wb->gtk_notebook, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (this->app()->gtkvbox()), box, TRUE, TRUE, 0);
return box;
}
| johnbellone/gtkworkbook | src/realtime/Realtime.cpp | C++ | gpl-2.0 | 10,844 |
/***************************************************************************
qgscalloutwidget.cpp
---------------------
begin : July 2019
copyright : (C) 2019 by Nyall Dawson
email : nyall dot dawson at gmail dot 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. *
* *
***************************************************************************/
#include "qgscalloutwidget.h"
#include "qgsvectorlayer.h"
#include "qgsexpressioncontextutils.h"
#include "qgsunitselectionwidget.h"
#include "qgscallout.h"
#include "qgsnewauxiliaryfielddialog.h"
#include "qgsnewauxiliarylayerdialog.h"
#include "qgsauxiliarystorage.h"
QgsExpressionContext QgsCalloutWidget::createExpressionContext() const
{
if ( auto *lExpressionContext = mContext.expressionContext() )
return *lExpressionContext;
QgsExpressionContext expContext( mContext.globalProjectAtlasMapLayerScopes( vectorLayer() ) );
QgsExpressionContextScope *symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() );
symbolScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, QColor(), true ) );
expContext << symbolScope;
// additional scopes
const auto constAdditionalExpressionContextScopes = mContext.additionalExpressionContextScopes();
for ( const QgsExpressionContextScope &scope : constAdditionalExpressionContextScopes )
{
expContext.appendScope( new QgsExpressionContextScope( scope ) );
}
//TODO - show actual value
expContext.setOriginalValueVariable( QVariant() );
expContext.setHighlightedVariables( QStringList() << QgsExpressionContext::EXPR_ORIGINAL_VALUE << QgsExpressionContext::EXPR_SYMBOL_COLOR );
return expContext;
}
void QgsCalloutWidget::setContext( const QgsSymbolWidgetContext &context )
{
mContext = context;
const auto unitSelectionWidgets = findChildren<QgsUnitSelectionWidget *>();
for ( QgsUnitSelectionWidget *unitWidget : unitSelectionWidgets )
{
unitWidget->setMapCanvas( mContext.mapCanvas() );
}
const auto symbolButtonWidgets = findChildren<QgsSymbolButton *>();
for ( QgsSymbolButton *symbolWidget : symbolButtonWidgets )
{
symbolWidget->setMapCanvas( mContext.mapCanvas() );
symbolWidget->setMessageBar( mContext.messageBar() );
}
}
QgsSymbolWidgetContext QgsCalloutWidget::context() const
{
return mContext;
}
void QgsCalloutWidget::registerDataDefinedButton( QgsPropertyOverrideButton *button, QgsCallout::Property key )
{
button->init( key, callout()->dataDefinedProperties(), QgsCallout::propertyDefinitions(), mVectorLayer, true );
connect( button, &QgsPropertyOverrideButton::changed, this, &QgsCalloutWidget::updateDataDefinedProperty );
connect( button, &QgsPropertyOverrideButton::createAuxiliaryField, this, &QgsCalloutWidget::createAuxiliaryField );
button->registerExpressionContextGenerator( this );
}
void QgsCalloutWidget::createAuxiliaryField()
{
// try to create an auxiliary layer if not yet created
if ( !mVectorLayer->auxiliaryLayer() )
{
QgsNewAuxiliaryLayerDialog dlg( mVectorLayer, this );
dlg.exec();
}
// return if still not exists
if ( !mVectorLayer->auxiliaryLayer() )
return;
QgsPropertyOverrideButton *button = qobject_cast<QgsPropertyOverrideButton *>( sender() );
QgsCallout::Property key = static_cast< QgsCallout::Property >( button->propertyKey() );
QgsPropertyDefinition def = QgsCallout::propertyDefinitions()[key];
// create property in auxiliary storage if necessary
if ( !mVectorLayer->auxiliaryLayer()->exists( def ) )
{
QgsNewAuxiliaryFieldDialog dlg( def, mVectorLayer, true, this );
if ( dlg.exec() == QDialog::Accepted )
def = dlg.propertyDefinition();
}
// return if still not exist
if ( !mVectorLayer->auxiliaryLayer()->exists( def ) )
return;
// update property with join field name from auxiliary storage
QgsProperty property = button->toProperty();
property.setField( QgsAuxiliaryLayer::nameFromProperty( def, true ) );
property.setActive( true );
button->updateFieldLists();
button->setToProperty( property );
callout()->dataDefinedProperties().setProperty( key, button->toProperty() );
emit changed();
}
void QgsCalloutWidget::updateDataDefinedProperty()
{
QgsPropertyOverrideButton *button = qobject_cast<QgsPropertyOverrideButton *>( sender() );
QgsCallout::Property key = static_cast< QgsCallout::Property >( button->propertyKey() );
callout()->dataDefinedProperties().setProperty( key, button->toProperty() );
emit changed();
}
/// @cond PRIVATE
//
// QgsSimpleLineCalloutWidget
//
QgsSimpleLineCalloutWidget::QgsSimpleLineCalloutWidget( QgsVectorLayer *vl, QWidget *parent )
: QgsCalloutWidget( parent, vl )
{
setupUi( this );
// Callout options - to move to custom widgets when multiple callout styles exist
mCalloutLineStyleButton->setSymbolType( QgsSymbol::Line );
mCalloutLineStyleButton->setDialogTitle( tr( "Callout Symbol" ) );
mCalloutLineStyleButton->registerExpressionContextGenerator( this );
mCalloutLineStyleButton->setLayer( vl );
mMinCalloutWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
mOffsetFromAnchorUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
mOffsetFromLabelUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
connect( mMinCalloutWidthUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::minimumLengthUnitWidgetChanged );
connect( mMinCalloutLengthSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::minimumLengthChanged );
connect( mOffsetFromAnchorUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::offsetFromAnchorUnitWidgetChanged );
connect( mOffsetFromAnchorSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::offsetFromAnchorChanged );
connect( mOffsetFromLabelUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::offsetFromLabelUnitWidgetChanged );
connect( mOffsetFromLabelSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::offsetFromLabelChanged );
connect( mDrawToAllPartsCheck, &QCheckBox::toggled, this, &QgsSimpleLineCalloutWidget::drawToAllPartsToggled );
// Anchor point options
mAnchorPointComboBox->addItem( tr( "Pole of Inaccessibility" ), static_cast< int >( QgsCallout::PoleOfInaccessibility ) );
mAnchorPointComboBox->addItem( tr( "Point on Exterior" ), static_cast< int >( QgsCallout::PointOnExterior ) );
mAnchorPointComboBox->addItem( tr( "Point on Surface" ), static_cast< int >( QgsCallout::PointOnSurface ) );
mAnchorPointComboBox->addItem( tr( "Centroid" ), static_cast< int >( QgsCallout::Centroid ) );
connect( mAnchorPointComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsSimpleLineCalloutWidget::mAnchorPointComboBox_currentIndexChanged );
mLabelAnchorPointComboBox->addItem( tr( "Closest Point" ), static_cast< int >( QgsCallout::LabelPointOnExterior ) );
mLabelAnchorPointComboBox->addItem( tr( "Centroid" ), static_cast< int >( QgsCallout::LabelCentroid ) );
mLabelAnchorPointComboBox->addItem( tr( "Top Left" ), static_cast< int >( QgsCallout::LabelTopLeft ) );
mLabelAnchorPointComboBox->addItem( tr( "Top Center" ), static_cast< int >( QgsCallout::LabelTopMiddle ) );
mLabelAnchorPointComboBox->addItem( tr( "Top Right" ), static_cast< int >( QgsCallout::LabelTopRight ) );
mLabelAnchorPointComboBox->addItem( tr( "Left Middle" ), static_cast< int >( QgsCallout::LabelMiddleLeft ) );
mLabelAnchorPointComboBox->addItem( tr( "Right Middle" ), static_cast< int >( QgsCallout::LabelMiddleRight ) );
mLabelAnchorPointComboBox->addItem( tr( "Bottom Left" ), static_cast< int >( QgsCallout::LabelBottomLeft ) );
mLabelAnchorPointComboBox->addItem( tr( "Bottom Center" ), static_cast< int >( QgsCallout::LabelBottomMiddle ) );
mLabelAnchorPointComboBox->addItem( tr( "Bottom Right" ), static_cast< int >( QgsCallout::LabelBottomRight ) );
connect( mLabelAnchorPointComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsSimpleLineCalloutWidget::mLabelAnchorPointComboBox_currentIndexChanged );
connect( mCalloutLineStyleButton, &QgsSymbolButton::changed, this, &QgsSimpleLineCalloutWidget::lineSymbolChanged );
}
void QgsSimpleLineCalloutWidget::setCallout( QgsCallout *callout )
{
if ( !callout )
return;
mCallout.reset( dynamic_cast<QgsSimpleLineCallout *>( callout->clone() ) );
if ( !mCallout )
return;
mMinCalloutWidthUnitWidget->blockSignals( true );
mMinCalloutWidthUnitWidget->setUnit( mCallout->minimumLengthUnit() );
mMinCalloutWidthUnitWidget->setMapUnitScale( mCallout->minimumLengthMapUnitScale() );
mMinCalloutWidthUnitWidget->blockSignals( false );
whileBlocking( mMinCalloutLengthSpin )->setValue( mCallout->minimumLength() );
mOffsetFromAnchorUnitWidget->blockSignals( true );
mOffsetFromAnchorUnitWidget->setUnit( mCallout->offsetFromAnchorUnit() );
mOffsetFromAnchorUnitWidget->setMapUnitScale( mCallout->offsetFromAnchorMapUnitScale() );
mOffsetFromAnchorUnitWidget->blockSignals( false );
mOffsetFromLabelUnitWidget->blockSignals( true );
mOffsetFromLabelUnitWidget->setUnit( mCallout->offsetFromLabelUnit() );
mOffsetFromLabelUnitWidget->setMapUnitScale( mCallout->offsetFromLabelMapUnitScale() );
mOffsetFromLabelUnitWidget->blockSignals( false );
whileBlocking( mOffsetFromAnchorSpin )->setValue( mCallout->offsetFromAnchor() );
whileBlocking( mOffsetFromLabelSpin )->setValue( mCallout->offsetFromLabel() );
whileBlocking( mCalloutLineStyleButton )->setSymbol( mCallout->lineSymbol()->clone() );
whileBlocking( mDrawToAllPartsCheck )->setChecked( mCallout->drawCalloutToAllParts() );
whileBlocking( mAnchorPointComboBox )->setCurrentIndex( mAnchorPointComboBox->findData( static_cast< int >( callout->anchorPoint() ) ) );
whileBlocking( mLabelAnchorPointComboBox )->setCurrentIndex( mLabelAnchorPointComboBox->findData( static_cast< int >( callout->labelAnchorPoint() ) ) );
registerDataDefinedButton( mMinCalloutLengthDDBtn, QgsCallout::MinimumCalloutLength );
registerDataDefinedButton( mOffsetFromAnchorDDBtn, QgsCallout::OffsetFromAnchor );
registerDataDefinedButton( mOffsetFromLabelDDBtn, QgsCallout::OffsetFromLabel );
registerDataDefinedButton( mDrawToAllPartsDDBtn, QgsCallout::DrawCalloutToAllParts );
registerDataDefinedButton( mAnchorPointDDBtn, QgsCallout::AnchorPointPosition );
registerDataDefinedButton( mLabelAnchorPointDDBtn, QgsCallout::LabelAnchorPointPosition );
registerDataDefinedButton( mOriginXDDBtn, QgsCallout::OriginX );
registerDataDefinedButton( mOriginYDDBtn, QgsCallout::OriginY );
registerDataDefinedButton( mDestXDDBtn, QgsCallout::DestinationX );
registerDataDefinedButton( mDestYDDBtn, QgsCallout::DestinationY );
}
void QgsSimpleLineCalloutWidget::setGeometryType( QgsWkbTypes::GeometryType type )
{
bool isPolygon = type == QgsWkbTypes::PolygonGeometry;
mAnchorPointLbl->setEnabled( isPolygon );
mAnchorPointLbl->setVisible( isPolygon );
mAnchorPointComboBox->setEnabled( isPolygon );
mAnchorPointComboBox->setVisible( isPolygon );
mAnchorPointDDBtn->setEnabled( isPolygon );
mAnchorPointDDBtn->setVisible( isPolygon );
}
QgsCallout *QgsSimpleLineCalloutWidget::callout()
{
return mCallout.get();
}
void QgsSimpleLineCalloutWidget::minimumLengthChanged()
{
mCallout->setMinimumLength( mMinCalloutLengthSpin->value() );
emit changed();
}
void QgsSimpleLineCalloutWidget::minimumLengthUnitWidgetChanged()
{
mCallout->setMinimumLengthUnit( mMinCalloutWidthUnitWidget->unit() );
mCallout->setMinimumLengthMapUnitScale( mMinCalloutWidthUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromAnchorUnitWidgetChanged()
{
mCallout->setOffsetFromAnchorUnit( mOffsetFromAnchorUnitWidget->unit() );
mCallout->setOffsetFromAnchorMapUnitScale( mOffsetFromAnchorUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromAnchorChanged()
{
mCallout->setOffsetFromAnchor( mOffsetFromAnchorSpin->value() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromLabelUnitWidgetChanged()
{
mCallout->setOffsetFromLabelUnit( mOffsetFromLabelUnitWidget->unit() );
mCallout->setOffsetFromLabelMapUnitScale( mOffsetFromLabelUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromLabelChanged()
{
mCallout->setOffsetFromLabel( mOffsetFromLabelSpin->value() );
emit changed();
}
void QgsSimpleLineCalloutWidget::lineSymbolChanged()
{
mCallout->setLineSymbol( mCalloutLineStyleButton->clonedSymbol< QgsLineSymbol >() );
emit changed();
}
void QgsSimpleLineCalloutWidget::mAnchorPointComboBox_currentIndexChanged( int index )
{
mCallout->setAnchorPoint( static_cast<QgsCallout::AnchorPoint>( mAnchorPointComboBox->itemData( index ).toInt() ) );
emit changed();
}
void QgsSimpleLineCalloutWidget::mLabelAnchorPointComboBox_currentIndexChanged( int index )
{
mCallout->setLabelAnchorPoint( static_cast<QgsCallout::LabelAnchorPoint>( mLabelAnchorPointComboBox->itemData( index ).toInt() ) );
emit changed();
}
void QgsSimpleLineCalloutWidget::drawToAllPartsToggled( bool active )
{
mCallout->setDrawCalloutToAllParts( active );
emit changed();
}
//
// QgsManhattanLineCalloutWidget
//
QgsManhattanLineCalloutWidget::QgsManhattanLineCalloutWidget( QgsVectorLayer *vl, QWidget *parent )
: QgsSimpleLineCalloutWidget( vl, parent )
{
}
///@endcond
| JamesShaeffer/QGIS | src/gui/callouts/qgscalloutwidget.cpp | C++ | gpl-2.0 | 15,015 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.atomic;
/**
* An {@code AtomicMarkableReference} maintains an object reference
* along with a mark bit, that can be updated atomically.
*
* <p>Implementation note: This implementation maintains markable
* references by creating internal objects representing "boxed"
* [reference, boolean] pairs.
*
* @since 1.5
* @author Doug Lea
* @param <V> The type of object referred to by this reference
*/
public class AtomicMarkableReference<V> {
private static class Pair<T> {
final T reference;
final boolean mark;
private Pair(T reference, boolean mark) {
this.reference = reference;
this.mark = mark;
}
static <T> Pair<T> of(T reference, boolean mark) {
return new Pair<T>(reference, mark);
}
}
private volatile Pair<V> pair;
/**
* Creates a new {@code AtomicMarkableReference} with the given
* initial values.
*
* @param initialRef the initial reference
* @param initialMark the initial mark
*/
public AtomicMarkableReference(V initialRef, boolean initialMark) {
pair = Pair.of(initialRef, initialMark);
}
/**
* Returns the current value of the reference.
*
* @return the current value of the reference
*/
public V getReference() {
return pair.reference;
}
/**
* Returns the current value of the mark.
*
* @return the current value of the mark
*/
public boolean isMarked() {
return pair.mark;
}
/**
* Returns the current values of both the reference and the mark.
* Typical usage is {@code boolean[1] holder; ref = v.get(holder); }.
*
* @param markHolder an array of size of at least one. On return,
* {@code markholder[0]} will hold the value of the mark.
* @return the current value of the reference
*/
public V get(boolean[] markHolder) {
Pair<V> pair = this.pair;
markHolder[0] = pair.mark;
return pair.reference;
}
/**
* Atomically sets the value of both the reference and mark
* to the given update values if the
* current reference is {@code ==} to the expected reference
* and the current mark is equal to the expected mark.
*
* <p><a href="package-summary.html#weakCompareAndSet">May fail
* spuriously and does not provide ordering guarantees</a>, so is
* only rarely an appropriate alternative to {@code compareAndSet}.
*
* @param expectedReference the expected value of the reference
* @param newReference the new value for the reference
* @param expectedMark the expected value of the mark
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean weakCompareAndSet(V expectedReference,
V newReference,
boolean expectedMark,
boolean newMark) {
return compareAndSet(expectedReference, newReference,
expectedMark, newMark);
}
/**
* Atomically sets the value of both the reference and mark
* to the given update values if the
* current reference is {@code ==} to the expected reference
* and the current mark is equal to the expected mark.
*
* @param expectedReference the expected value of the reference
* @param newReference the new value for the reference
* @param expectedMark the expected value of the mark
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean compareAndSet(V expectedReference,
V newReference,
boolean expectedMark,
boolean newMark) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
expectedMark == current.mark &&
((newReference == current.reference &&
newMark == current.mark) ||
casPair(current, Pair.of(newReference, newMark)));
}
/**
* Unconditionally sets the value of both the reference and mark.
*
* @param newReference the new value for the reference
* @param newMark the new value for the mark
*/
public void set(V newReference, boolean newMark) {
Pair<V> current = pair;
if (newReference != current.reference || newMark != current.mark)
this.pair = Pair.of(newReference, newMark);
}
/**
* Atomically sets the value of the mark to the given update value
* if the current reference is {@code ==} to the expected
* reference. Any given invocation of this operation may fail
* (return {@code false}) spuriously, but repeated invocation
* when the current value holds the expected value and no other
* thread is also attempting to set the value will eventually
* succeed.
*
* @param expectedReference the expected value of the reference
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean attemptMark(V expectedReference, boolean newMark) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
(newMark == current.mark ||
casPair(current, Pair.of(expectedReference, newMark)));
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
// private static final long pairOffset =
// objectFieldOffset(UNSAFE, "pair", AtomicMarkableReference.class);
private boolean casPair(Pair<V> cmp, Pair<V> val) {
return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val);
}
public static volatile long pairOffset;
static {
try {
pairOffset = 0;
UNSAFE.registerStaticFieldOffset(
AtomicMarkableReference.class.getDeclaredField("pairOffset"),
AtomicMarkableReference.class.getDeclaredField("pair"));
} catch (Exception ex) { throw new Error(ex); }
}
}
| upenn-acg/REMIX | jvm-remix/openjdk/jdk/src/share/classes/java/util/concurrent/atomic/AtomicMarkableReference.java | Java | gpl-2.0 | 7,816 |
(function ($) {
$(document).ready(function(){
$("#edit-title-0-value").change(update);
$("#edit-field-carac1-0-value").click(update);
$("#edit-field-carac1-0-value").change(update);
$("#edit-field-carac2-0-value").change(update);
$("#edit-field-carac3-0-value").change(update);
$("#edit-field-carac4-0-value").change(update);
$("#edit-field-skill-0-value").change(update);
$("#edit-field-question-0-value").change(update);
$("#edit-field-answer-0-value").change(update);
$("#edit-field-img-game-card-0-upload").change(update);
$("#edit-field-upload_image_verso").change(update);
var bgimagerecto = undefined;
var bgimageverso = undefined;
if($('span.file--image > a').length == 1) {
if($('#edit-field-img-game-card-0-remove-button')) {
console.log("length11");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
}
else {
console.log("length12");
bgimageverso = $("span.file--image > a:eq(0)").attr('href');
}
}
if($('span.file--image > a').length == 2) {
console.log("length2");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
bgimageverso = $("span.file--image > a:eq(1)").attr('href');
}
if (bgimagerecto !== undefined) {
console.log("imagerecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
}
if (bgimageverso !== undefined) {
console.log("imageverso");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
}
$(document).ajaxComplete(function(event, xhr, settings) {
//RECTO
console.log(event.target);
console.log("azer " + bgimagerecto);
console.log("qsdf " + bgimageverso);
if(~settings.url.indexOf("field_img_game_card")) {
console.log('entering recto');
if ($('.field--name-field-img-game-card .ajax-new-content').hasClass('processed')) {
console.log("remove recto");
//$('.ajax-new-content').remove();
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
if(!$('#edit-field-img-game-card-0-remove-button')) {
console.log("remoooooove");
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
console.log("addingrecto");
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); //Manage here when single or double
if (bgimagerecto !== undefined) {
console.log("gorecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
}
return;
}
//VERSO
if(~settings.url.indexOf("field_upload_image_verso")) {
if ($('.field--name-field-upload-image-verso .ajax-new-content').hasClass('processed') || !$('#edit-field-upload-image-verso-0-remove-button')) {
console.log("remove verso");
//$('.ajax-new-content').remove();
$('#gamecardversolayout').removeAttr('style');
$('.field--name-field-upload-image-verso .ajax-new-content').removeClass('processed');
return;
}
console.log("adding verso");
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
if($('span.file--image > a').length == 1) bgimageverso = $("span.file--image > a:eq(0)").attr('href');
if($('span.file--image > a').length == 2) bgimageverso = $("span.file--image > a:eq(1)").attr('href');
if (bgimageverso !== undefined) {
console.log("Verso added");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
}
}
});
});
function update(){
var cardname = (($("#edit-title-0-value").val() != "") ? $("#edit-title-0-value").val() : "");
var carac1 = (($("#edit-field-carac1-0-value").val() != "") ? $("#edit-field-carac1-0-value").val() : "");
var carac2 = (($("#edit-field-carac2-0-value").val() != "") ? $("#edit-field-carac2-0-value").val() : "");
var carac3 = (($("#edit-field-carac3-0-value").val() != "") ? $("#edit-field-carac3-0-value").val() : "");
var carac4 = (($("#edit-field-carac4-0-value").val() != "") ? $("#edit-field-carac4-0-value").val() : "");
var skill = (($("#edit-field-skill-0-value").val() != "") ? $("#edit-field-skill-0-value").val() : "") ;
var question = (($("#edit-field-question-0-value").val() != "") ? $("#edit-field-question-0-value").val() : "");
var answer = (($("#edit-field-answer-0-value").val() != "") ? $("#edit-field-answer-0-value").val() : "") ;
var rectoImg = (($("#edit-field-img-game-card-0-upload").val() != "") ? $("#edit-field-img-game-card-0-upload").val() : "");
var versoImg = (($("#edit-field-upload_image_verso").val() != "") ? $("#edit-field-upload_image_verso").val() : "");
if(rectoImg !== undefined) {
if (rectoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + rectoImg + '")');
}
else {
rectoImg = $("span.file--image > a:eq(0)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + rectoImg + ')');
}
}
if(versoImg !== undefined) {
if (versoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + versoImg + '")');
}
else {
versoImg = $("span.file--image > a:eq(1)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + versoImg + ')');
}
}
$('#displayCardname').html(cardname);
$('#displayCarac1').html(carac1);
$('#displayCarac2').html(carac2);
$('#displayCarac3').html(carac3);
$('#displayCarac4').html(carac4);
$('#displaySkill').html(skill);
$('#displayQuestion').html(question);
$('#displayAnswer').html(answer);
}
})(jQuery);
| TGR05/POEI-mini-projet | modules/custom/cardform/js/gamecards.js | JavaScript | gpl-2.0 | 6,227 |
<?php
/**
* @package WordPress
* @subpackage HTML5-Reset-WordPress-Theme
* @since HTML5 Reset 2.0
Template Name: Groups
*/
get_header(); ?>
<div class="content-background">
<div id="content-wrap">
<div class="grid">
<div class="col col-1-4">
<?php wp_nav_menu( array('menu' => 'Groups Menu', 'container_class' => 'side-menu-container', 'menu_class' => 'side-menu' )); ?>
<div class="fb-like-box" data-href="https://www.facebook.com/skisnowstar" data-width="200" data-height="300" data-colorscheme="light" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div>
<a href="https://twitter.com/SkiSnowstar" class="twitter-follow-button" data-width="90%" data-align="right" data-show-count="false" data-lang="en" data-size="large">Follow @twitter</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div><!-- END COL-1-4 -->
<div class="col col-3-4">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post" id="post-<?php the_ID(); ?>">
<!-- <h2><?php the_title(); ?></h2> -->
<!-- <?php posted_on(); ?> -->
<?php if ( has_post_thumbnail() ) {the_post_thumbnail('full', array('class' => 'content-img'));} ?>
<div class="entry">
<?php the_content(); ?>
<?php wp_link_pages(array('before' => __('Pages: '), 'next_or_number' => 'number')); ?>
</div>
<?php edit_post_link(__('Edit this entry.'), '<p>', '</p>'); ?>
</article>
<?php endwhile; endif; ?>
</div><!-- END COL-3-4 -->
</div><!-- END GRID -->
</div> <!-- End Content Wrap -->
<?php get_footer(); ?>
| markfaust/snowstar | wp-content/themes/snowstar/groups.php | PHP | gpl-2.0 | 1,854 |
/*
* Turbo Sliders++
* Copyright (C) 2013-2014 Martin Newhouse
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#ifndef TRACK_METADATA_HPP
#define TRACK_METADATA_HPP
#include "track_identifier.hpp"
namespace ts
{
namespace resources
{
class Track_handle;
struct Track_metadata
{
Track_identifier identifier;
utf8_string gamemode;
};
Track_metadata load_track_metadata(const resources::Track_handle& track_handle);
}
}
#endif | mnewhouse/tspp | src/resources/track_metadata.hpp | C++ | gpl-2.0 | 1,222 |
package edu.stanford.nlp.time;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Map;
import java.util.regex.Pattern;
import edu.stanford.nlp.util.Pair;
import org.w3c.dom.Element;
/**
* Stores one TIMEX3 expression. This class is used for both TimeAnnotator and
* GUTimeAnnotator for storing information for TIMEX3 tags.
*
* <p>
* Example text with TIMEX3 annotation:<br>
* <code>In Washington <TIMEX3 tid="t1" TYPE="DATE" VAL="PRESENT_REF"
* temporalFunction="true" valueFromFunction="tf1"
* anchorTimeID="t0">today</TIMEX3>, the Federal Aviation Administration
* released air traffic control tapes from the night the TWA Flight eight
* hundred went down.
* </code>
* <p>
* <br>
* TIMEX3 specification:
* <br>
* <pre><code>
* attributes ::= tid type [functionInDocument] [beginPoint] [endPoint]
* [quant] [freq] [temporalFunction] (value | valueFromFunction)
* [mod] [anchorTimeID] [comment]
*
* tid ::= ID
* {tid ::= TimeID
* TimeID ::= t<integer>}
* type ::= 'DATE' | 'TIME' | 'DURATION' | 'SET'
* beginPoint ::= IDREF
* {beginPoint ::= TimeID}
* endPoint ::= IDREF
* {endPoint ::= TimeID}
* quant ::= CDATA
* freq ::= Duration
* functionInDocument ::= 'CREATION_TIME' | 'EXPIRATION_TIME' | 'MODIFICATION_TIME' |
* 'PUBLICATION_TIME' | 'RELEASE_TIME'| 'RECEPTION_TIME' |
* 'NONE' {default, if absent, is 'NONE'}
* temporalFunction ::= 'true' | 'false' {default, if absent, is 'false'}
* {temporalFunction ::= boolean}
* value ::= Duration | Date | Time | WeekDate | WeekTime | Season | PartOfYear | PaPrFu
* valueFromFunction ::= IDREF
* {valueFromFunction ::= TemporalFunctionID
* TemporalFunctionID ::= tf<integer>}
* mod ::= 'BEFORE' | 'AFTER' | 'ON_OR_BEFORE' | 'ON_OR_AFTER' |'LESS_THAN' | 'MORE_THAN' |
* 'EQUAL_OR_LESS' | 'EQUAL_OR_MORE' | 'START' | 'MID' | 'END' | 'APPROX'
* anchorTimeID ::= IDREF
* {anchorTimeID ::= TimeID}
* comment ::= CDATA
* </code></pre>
*
* <p>
* References
* <br>
* Guidelines: <a href="http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf">
* http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf</a>
* <br>
* Specifications: <a href="http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3">
* http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3</a>
* <br>
* XSD: <a href="http://www.timeml.org/timeMLdocs/TimeML.xsd">http://www.timeml.org/timeMLdocs/TimeML.xsd</a>
**/
public class Timex implements Serializable {
private static final long serialVersionUID = 385847729549981302L;
/**
* XML representation of the TIMEX tag
*/
private String xml;
/**
* TIMEX3 value attribute - Time value (given in extended ISO 8601 format).
*/
private String val;
/**
* Alternate representation for time value (not part of TIMEX3 standard).
* used when value of the time expression cannot be expressed as a standard TIMEX3 value.
*/
private String altVal;
/**
* Actual text that make up the time expression
*/
private String text;
/**
* TIMEX3 type attribute - Type of the time expression (DATE, TIME, DURATION, or SET)
*/
private String type;
/**
* TIMEX3 tid attribute - TimeID. ID to identify this time expression.
* Should have the format of {@code t<integer>}
*/
private String tid;
// TODO: maybe its easier if these are just strings...
/**
* TIMEX3 beginPoint attribute - integer indicating the TimeID of the begin time
* that anchors this duration/range (-1 is not present).
*/
private int beginPoint;
/**
* TIMEX3 beginPoint attribute - integer indicating the TimeID of the end time
* that anchors this duration/range (-1 is not present).
*/
private int endPoint;
/**
* Range begin/end/duration
* (this is not part of the timex standard and is typically null, available if sutime.includeRange is true)
*/
private Range range;
public static class Range implements Serializable {
private static final long serialVersionUID = 1L;
public String begin;
public String end;
public String duration;
public Range(String begin, String end, String duration) {
this.begin = begin;
this.end = end;
this.duration = duration;
}
}
public String value() {
return val;
}
public String altVal() {
return altVal;
}
public String text() {
return text;
}
public String timexType() {
return type;
}
public String tid() {
return tid;
}
public Range range() {
return range;
}
public Timex() {
}
public Timex(Element element) {
this.val = null;
this.beginPoint = -1;
this.endPoint = -1;
/*
* ByteArrayOutputStream os = new ByteArrayOutputStream(); Serializer ser =
* new Serializer(os, "UTF-8"); ser.setIndent(2); // this is the default in
* JDOM so let's keep the same ser.setMaxLength(0); // no line wrapping for
* content ser.write(new Document(element));
*/
init(element);
}
public Timex(String val) {
this(null, val);
}
public Timex(String type, String val) {
this.val = val;
this.type = type;
this.beginPoint = -1;
this.endPoint = -1;
this.xml = (val == null ? "<TIMEX3/>" : String.format("<TIMEX3 VAL=\"%s\" TYPE=\"%s\"/>", this.val, this.type));
}
public Timex(String type, String val, String altVal, String tid, String text, int beginPoint, int endPoint) {
this.type = type;
this.val = val;
this.altVal = altVal;
this.tid = tid;
this.text = text;
this.beginPoint = beginPoint;
this.endPoint = endPoint;
}
private void init(Element element) {
init(XMLUtils.nodeToString(element, false), element);
}
private void init(String xml, Element element) {
this.xml = xml;
this.text = element.getTextContent();
// Mandatory attributes
this.tid = XMLUtils.getAttribute(element, "tid");
this.val = XMLUtils.getAttribute(element, "VAL");
if (this.val == null) {
this.val = XMLUtils.getAttribute(element, "value");
}
this.altVal = XMLUtils.getAttribute(element, "alt_value");
this.type = XMLUtils.getAttribute(element, "type");
if (type == null) {
this.type = XMLUtils.getAttribute(element, "TYPE");
}
// if (this.type != null) {
// this.type = this.type.intern();
// }
// Optional attributes
String beginPoint = XMLUtils.getAttribute(element, "beginPoint");
this.beginPoint = (beginPoint == null || beginPoint.length() == 0)? -1 : Integer.parseInt(beginPoint.substring(1));
String endPoint = XMLUtils.getAttribute(element, "endPoint");
this.endPoint = (endPoint == null || endPoint.length() == 0)? -1 : Integer.parseInt(endPoint.substring(1));
// Optional range
String rangeStr = XMLUtils.getAttribute(element, "range");
if (rangeStr != null) {
if (rangeStr.startsWith("(") && rangeStr.endsWith(")")) {
rangeStr = rangeStr.substring(1, rangeStr.length()-1);
}
String[] parts = rangeStr.split(",");
this.range = new Range(parts.length > 0? parts[0]:"", parts.length > 1? parts[1]:"", parts.length > 2? parts[2]:"");
}
}
public int beginPoint() { return beginPoint; }
public int endPoint() { return endPoint; }
public String toString() {
return (this.xml != null) ? this.xml : this.val;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Timex timex = (Timex) o;
if (beginPoint != timex.beginPoint) {
return false;
}
if (endPoint != timex.endPoint) {
return false;
}
if (type != null ? !type.equals(timex.type) : timex.type != null) {
return false;
}
if (val != null ? !val.equals(timex.val) : timex.val != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = val != null ? val.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + beginPoint;
result = 31 * result + endPoint;
return result;
}
public Element toXmlElement() {
Element element = XMLUtils.createElement("TIMEX3");
if (tid != null) {
element.setAttribute("tid", tid);
}
if (value() != null) {
element.setAttribute("value", val);
}
if (altVal != null) {
element.setAttribute("altVal", altVal);
}
if (type != null) {
element.setAttribute("type", type);
}
if (beginPoint != -1) {
element.setAttribute("beginPoint", "t" + String.valueOf(beginPoint));
}
if (endPoint != -1) {
element.setAttribute("endPoint", "t" + String.valueOf(endPoint));
}
if (text != null) {
element.setTextContent(text);
}
return element;
}
// Used to create timex from XML (mainly for testing)
public static Timex fromXml(String xml) {
Element element = XMLUtils.parseElement(xml);
if ("TIMEX3".equals(element.getNodeName())) {
Timex t = new Timex();
// t.init(xml, element);
// Doesn't preserve original input xml
// Will reorder attributes of xml so can match xml of test timex and actual timex
// (for which we can't control the order of the attributes now we don't use nu.xom...)
t.init(element);
return t;
} else {
throw new IllegalArgumentException("Invalid timex xml: " + xml);
}
}
public static Timex fromMap(String text, Map<String, String> map) {
try {
Element element = XMLUtils.createElement("TIMEX3");
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() != null) {
element.setAttribute(entry.getKey(), entry.getValue());
}
}
element.setTextContent(text);
return new Timex(element);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Gets the Calendar matching the year, month and day of this Timex.
*
* @return The matching Calendar.
*/
public Calendar getDate() {
if (Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
int day = Integer.parseInt(this.val.substring(8, 10));
return makeCalendar(year, month, day);
} else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return makeCalendar(year, month, day);
}
throw new UnsupportedOperationException(String.format("%s is not a fully specified date", this));
}
/**
* Gets two Calendars, marking the beginning and ending of this Timex's range.
*
* @return The begin point and end point Calendars.
*/
public Pair<Calendar, Calendar> getRange() {
return this.getRange(null);
}
/**
* Gets two Calendars, marking the beginning and ending of this Timex's range.
*
* @param documentTime
* The time the document containing this Timex was written. (Not
* necessary for resolving all Timex expressions. This may be
* {@code null}, but then relative time expressions cannot be
* resolved.)
* @return The begin point and end point Calendars.
*/
public Pair<Calendar, Calendar> getRange(Timex documentTime) {
if (this.val == null) {
throw new UnsupportedOperationException("no value specified for " + this);
}
// YYYYMMDD or YYYYMMDDT... where the time is concatenated directly with the
// date
else if (val.length() >= 8 && Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val.substring(0, 8))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYY-MM-DD or YYYY-MM-DDT...
else if (val.length() >= 10 && Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val.substring(0, 10))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
int day = Integer.parseInt(this.val.substring(8, 10));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYYMMDDL+
else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d[A-Z]+", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYYMM or YYYYMMT...
else if (val.length() >= 6 && Pattern.matches("\\d\\d\\d\\d\\d\\d", this.val.substring(0, 6))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
Calendar begin = makeCalendar(year, month, 1);
int lastDay = begin.getActualMaximum(Calendar.DATE);
Calendar end = makeCalendar(year, month, lastDay);
return new Pair<>(begin, end);
}
// YYYY-MM or YYYY-MMT...
else if (val.length() >= 7 && Pattern.matches("\\d\\d\\d\\d-\\d\\d", this.val.substring(0, 7))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
Calendar begin = makeCalendar(year, month, 1);
int lastDay = begin.getActualMaximum(Calendar.DATE);
Calendar end = makeCalendar(year, month, lastDay);
return new Pair<>(begin, end);
}
// YYYY or YYYYT...
else if (val.length() >= 4 && Pattern.matches("\\d\\d\\d\\d", this.val.substring(0, 4))) {
int year = Integer.parseInt(this.val.substring(0, 4));
return new Pair<>(makeCalendar(year, 1, 1), makeCalendar(year, 12, 31));
}
// PDDY
if (Pattern.matches("P\\d+Y", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int yearRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.YEAR, yearRange);
return new Pair<>(start, end);
}
// in the past
else if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.YEAR, 0 - yearRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// PDDM
if (Pattern.matches("P\\d+M", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int monthRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.MONTH, monthRange);
return new Pair<>(start, end);
}
// in the past
if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.MONTH, 0 - monthRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// PDDD
if (Pattern.matches("P\\d+D", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int dayRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.DAY_OF_MONTH, dayRange);
return new Pair<>(start, end);
}
// in the past
if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.DAY_OF_MONTH, 0 - dayRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// YYYYSP
if (Pattern.matches("\\d+SP", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 2, 1);
Calendar end = makeCalendar(year, 4, 31);
return new Pair<>(start, end);
}
// YYYYSU
if (Pattern.matches("\\d+SU", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 5, 1);
Calendar end = makeCalendar(year, 7, 31);
return new Pair<>(start, end);
}
// YYYYFA
if (Pattern.matches("\\d+FA", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 8, 1);
Calendar end = makeCalendar(year, 10, 31);
return new Pair<>(start, end);
}
// YYYYWI
if (Pattern.matches("\\d+WI", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 11, 1);
Calendar end = makeCalendar(year + 1, 1, 29);
return new Pair<>(start, end);
}
// YYYYWDD
if (Pattern.matches("\\d\\d\\d\\dW\\d+", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int week = Integer.parseInt(this.val.substring(5));
int startDay = (week - 1) * 7;
int endDay = startDay + 6;
Calendar start = makeCalendar(year, startDay);
Calendar end = makeCalendar(year, endDay);
return new Pair<>(start, end);
}
// PRESENT_REF
if (this.val.equals("PRESENT_REF")) {
Calendar rc = documentTime.getDate(); // todo: This case doesn't check for documentTime being null and will NPE
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
return new Pair<>(start, end);
}
throw new RuntimeException(String.format("unknown value \"%s\" in %s", this.val, this));
}
private static Calendar makeCalendar(int year, int month, int day) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(year, month - 1, day, 0, 0, 0);
return date;
}
private static Calendar makeCalendar(int year, int dayOfYear) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(Calendar.YEAR, year);
date.set(Calendar.DAY_OF_YEAR, dayOfYear);
return date;
}
private static Calendar copyCalendar(Calendar c) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c
.get(Calendar.MINUTE), c.get(Calendar.SECOND));
return date;
}
}
| rupenp/CoreNLP | src/edu/stanford/nlp/time/Timex.java | Java | gpl-2.0 | 19,256 |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* This file is part of guh. *
* *
* Guh 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, version 2 of the License. *
* *
* Guh 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 guh. If not, see <http://www.gnu.org/licenses/>. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*!
\page openweathermap.html
\title Open Weather Map
\ingroup plugins
\ingroup services
This plugin alows you to get the current weather data from \l{http://www.openweathermap.org}.
The plugin offers two different search methods: if the user searches for a empty string,
the plugin makes an autodetction with the WAN ip and offers the user the found autodetectresult.
Otherwise the plugin return the list with the found searchresults.
\section1 Examples
\section2 Autodetect location
If you want to autodetect your location dend a discovery request with an empty string.
\code
{
"id":1,
"method":"Devices.GetDiscoveredDevices",
"params":{
"deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7",
"discoveryParams": {
"location":""
}
}
}
\endcode
response from autodetection...
\code
{
"id": 1,
"params": {
"deviceDescriptors": [
{
"description": "AT",
"id": "{75607672-5354-428f-a752-910140c22b18}",
"title": "Vienna"
}
],
"errorMessage": "",
"success": true
},
"status": "success"
}
\endcode
\section2 Searching city
If you want to search a string send following discovery message:
\code
{
"id":1,
"method":"Devices.GetDiscoveredDevices",
"params":{
"deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7",
"discoveryParams": {
"location":"Vie"
}
}
}
\endcode
response...
\code
{
"id": 1,
"params": {
"deviceDescriptors": [
{
"description": "DE",
"id": "{6dc6be43-5bdc-4dbd-bcbf-6f8e1f90000b}",
"title": "Viersen"
},
{
"description": "VN",
"id": "{af275298-77f1-40b4-843a-d0f3c7aef6bb}",
"title": "Viet Tri"
},
{
"description": "DE",
"id": "{86a4ab63-41b4-4348-9830-4bf6c87474bf}",
"title": "Viernheim"
},
{
"description": "AR",
"id": "{3b5f8eea-6159-4375-bd01-1f07de9c3a9d}",
"title": "Viedma"
},
{
"description": "FR",
"id": "{f3b91f26-3275-4bb4-a594-924202a2124e}",
"title": "Vierzon"
},
{
"description": "AT",
"id": "{b59d15f7-f52b-43a0-a9c5-a3fa80cbc2bd}",
"title": "Vienna"
}
],
"errorMessage": "",
"success": true
},
"status": "success"
}
\endcode
\section2 Adding a discovered city
If you want to add a dicovered city send the add "AddConfiguredDevice" message
with the deviceDescriptorId from the searchresult list. In this example the id for Vienna.
\code
{
"id":1,
"method":"Devices.AddConfiguredDevice",
"params":{
"deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7",
"deviceDescriptorId": "b59d15f7-f52b-43a0-a9c5-a3fa80cbc2bd"
}
}
\endcode
response...
\code
{
"id": 1,
"params": {
"deviceId": "{af0f1958-b901-48da-ad97-d4d64af88cf8}",
"errorMessage": "",
"success": true
},
"status": "success"
}
\endcode
\section1 Plugin propertys:
\section2 Plugin parameters
Each configured plugin has following paramters:
\table
\header
\li Name
\li Description
\li Data Type
\row
\li location
\li This parameter holds the name of the city
\li string
\row
\li country
\li This parameter holds the country of the city
\li string
\row
\li id
\li This parameter holds the city id from \l{http://www.openweathermap.org}
\li string
\endtable
\section2 Actions
Following list contains all plugin \l{Action}s:
\table
\header
\li Name
\li Description
\li UUID
\row
\li refresh
\li This action refreshes all states.
\li cfbc6504-d86f-4856-8dfa-97b6fbb385e4
\endtable
\section2 States
Following list contains all plugin \l{State}s:
\table
\header
\li Name
\li Description
\li UUID
\li Data Type
\row
\li city name
\li The name of the city
\li fd9e7b7f-cf1f-4093-8f6d-fff5b223471f
\li string
\row
\li city id
\li The city ID for openweathermap.org
\li c6ef1c07-e817-4251-b83d-115bbf6f0ae9
\li string
\row
\li country name
\li The country name
\li 0e607a5f-1938-4e77-a146-15e9ad15bfad
\li string
\row
\li last update
\li The timestamp of the weather data from the weatherstation in unixtime
format
\li 98e48095-87da-47a4-b812-28c6c17a3e76
\li unsignend int
\row
\li temperature
\li Current temperature [Celsius]
\li 2f949fa3-ff21-4721-87ec-0a5c9d0a5b8a
\li double
\row
\li temperature minimum
\li Today temperature minimum [Clesius]
\li 701338b3-80de-4c95-8abf-26f44529d620
\li double
\row
\li temperature maximum
\li Today temperature maximum [Clesius]
\li f69bedd2-c997-4a7d-9242-76bf2aab3d3d
\li double
\row
\li humidity
\li Current relative humidity [%]
\li 3f01c9f0-206b-4477-afa2-80d6e5e54fbb
\li int
\row
\li pressure
\li Current pressure [hPa]
\li 6a57b6e9-7010-4a89-982c-ce0bc2a71f11
\li double
\row
\li wind speed
\li Current wind speed [m/s]
\li 12dc85a9-825d-4375-bef4-abd66e9e301b
\li double
\row
\li wind direction
\li The wind direction rellative to the north pole [degree]
\li a8b0383c-d615-41fe-82b8-9b797f045cc9
\li int
\row
\li cloudiness
\li This value represents how much of the sky is clowdy [%]
\li 0c1dc881-560e-40ac-a4a1-9ab69138cfe3
\li int
\row
\li weather description
\li This string describes the current weather condition in clear words
\li e71d98e3-ebd8-4abf-ad25-9ecc2d05276a
\li string
\row
\li sunset
\li The time of todays sunset in unixtime format
\li 5dd6f5a3-25d6-4e60-82ca-e934ad76a4b6
\li unsigned int
\row
\li sunrise
\li The time of todays sunrise in unixtime format
\li 413b3fc6-bd1c-46fb-8c86-03096254f94f
\li unsigned int
\endtable
*/
#include "devicepluginopenweathermap.h"
#include "plugin/device.h"
#include "devicemanager.h"
#include <QDebug>
#include <QJsonDocument>
#include <QVariantMap>
#include <QDateTime>
DeviceClassId openweathermapDeviceClassId = DeviceClassId("985195aa-17ad-4530-88a4-cdd753d747d7");
ActionTypeId updateWeatherActionTypeId = ActionTypeId("cfbc6504-d86f-4856-8dfa-97b6fbb385e4");
StateTypeId updateTimeStateTypeId = StateTypeId("36b2f09b-7d77-4fbc-a68f-23d735dda0b1");
StateTypeId temperatureStateTypeId = StateTypeId("6013402f-b5b1-46b3-8490-f0c20d62fe61");
StateTypeId temperatureMinStateTypeId = StateTypeId("14ec2781-cb04-4bbf-b097-7d01ef982630");
StateTypeId temperatureMaxStateTypeId = StateTypeId("fefe5563-452f-4833-b5cf-49c3cc67c772");
StateTypeId humidityStateTypeId = StateTypeId("6f32ec73-3240-4630-ada9-1c10b8e98123");
StateTypeId pressureStateTypeId = StateTypeId("4a42eea9-00eb-440b-915e-dbe42180f83b");
StateTypeId windSpeedStateTypeId = StateTypeId("2bf63430-e9e2-4fbf-88e6-6f1b4770f287");
StateTypeId windDirectionStateTypeId = StateTypeId("589e2ea5-65b2-4afd-9b72-e3708a589a12");
StateTypeId cloudinessStateTypeId = StateTypeId("798553bc-45c7-42eb-9105-430bddb5d9b7");
StateTypeId weatherDescriptionStateTypeId = StateTypeId("f9539108-0e0e-4736-a306-6408f8e20a26");
StateTypeId sunriseStateTypeId = StateTypeId("af155e94-9492-44e1-8608-7d0ee8b5d50d");
StateTypeId sunsetStateTypeId = StateTypeId("a1dddc3d-549f-4f20-b78b-be850548f286");
DevicePluginOpenweathermap::DevicePluginOpenweathermap()
{
m_openweaher = new OpenWeatherMap(this);
connect(m_openweaher, &OpenWeatherMap::searchResultReady, this, &DevicePluginOpenweathermap::searchResultsReady);
connect(m_openweaher, &OpenWeatherMap::weatherDataReady, this, &DevicePluginOpenweathermap::weatherDataReady);
}
DeviceManager::DeviceError DevicePluginOpenweathermap::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms)
{
if(deviceClassId != openweathermapDeviceClassId){
return DeviceManager::DeviceErrorDeviceClassNotFound;
}
QString location;
foreach (const Param ¶m, params) {
if (param.name() == "location") {
location = param.value().toString();
}
}
// if we have an empty search string, perform an autodetection of the location with the WAN ip...
if (location.isEmpty()){
m_openweaher->searchAutodetect();
} else {
m_openweaher->search(location);
}
// otherwise search the given string
m_openweaher->search(location);
return DeviceManager::DeviceErrorAsync;
}
DeviceManager::DeviceSetupStatus DevicePluginOpenweathermap::setupDevice(Device *device)
{
foreach (Device *deviceListDevice, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) {
if(deviceListDevice->paramValue("id").toString() == device->paramValue("id").toString()){
qWarning() << QString("Location " + device->paramValue("location").toString() + " already added.");
return DeviceManager::DeviceSetupStatusFailure;
}
}
device->setName("Weather from OpenWeatherMap (" + device->paramValue("location").toString() + ")");
m_openweaher->update(device->paramValue("id").toString(), device->id());
return DeviceManager::DeviceSetupStatusSuccess;
}
DeviceManager::HardwareResources DevicePluginOpenweathermap::requiredHardware() const
{
return DeviceManager::HardwareResourceTimer;
}
DeviceManager::DeviceError DevicePluginOpenweathermap::executeAction(Device *device, const Action &action)
{
if(action.actionTypeId() == updateWeatherActionTypeId){
m_openweaher->update(device->paramValue("id").toString(), device->id());
}
return DeviceManager::DeviceErrorNoError;
}
void DevicePluginOpenweathermap::guhTimer()
{
foreach (Device *device, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) {
m_openweaher->update(device->paramValue("id").toString(), device->id());
}
}
void DevicePluginOpenweathermap::searchResultsReady(const QList<QVariantMap> &cityList)
{
QList<DeviceDescriptor> retList;
foreach (QVariantMap elemant, cityList) {
DeviceDescriptor descriptor(openweathermapDeviceClassId, elemant.value("name").toString(),elemant.value("country").toString());
ParamList params;
Param locationParam("location", elemant.value("name"));
params.append(locationParam);
Param countryParam("country", elemant.value("country"));
params.append(countryParam);
Param idParam("id", elemant.value("id"));
params.append(idParam);
descriptor.setParams(params);
retList.append(descriptor);
}
emit devicesDiscovered(openweathermapDeviceClassId,retList);
}
void DevicePluginOpenweathermap::weatherDataReady(const QByteArray &data, const DeviceId &deviceId)
{
QJsonParseError error;
QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
if(error.error != QJsonParseError::NoError) {
qWarning() << "failed to parse data" << data << ":" << error.errorString();
return;
}
QVariantMap dataMap = jsonDoc.toVariant().toMap();
foreach (Device *device, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) {
if(device->id() == deviceId){
if(dataMap.contains("clouds")){
int cloudiness = dataMap.value("clouds").toMap().value("all").toInt();
device->setStateValue(cloudinessStateTypeId,cloudiness);
}
if(dataMap.contains("dt")){
uint lastUpdate = dataMap.value("dt").toUInt();
device->setStateValue(updateTimeStateTypeId,lastUpdate);
}
if(dataMap.contains("main")){
double temperatur = dataMap.value("main").toMap().value("temp").toDouble();
double temperaturMax = dataMap.value("main").toMap().value("temp_max").toDouble();
double temperaturMin = dataMap.value("main").toMap().value("temp_min").toDouble();
double pressure = dataMap.value("main").toMap().value("pressure").toDouble();
int humidity = dataMap.value("main").toMap().value("humidity").toInt();
device->setStateValue(temperatureStateTypeId,temperatur);
device->setStateValue(temperatureMinStateTypeId,temperaturMin);
device->setStateValue(temperatureMaxStateTypeId,temperaturMax);
device->setStateValue(pressureStateTypeId,pressure);
device->setStateValue(humidityStateTypeId,humidity);
}
if(dataMap.contains("sys")){
uint sunrise = dataMap.value("sys").toMap().value("sunrise").toUInt();
uint sunset = dataMap.value("sys").toMap().value("sunset").toUInt();
device->setStateValue(sunriseStateTypeId,sunrise);
device->setStateValue(sunsetStateTypeId,sunset);
}
if(dataMap.contains("weather")){
QString description = dataMap.value("weather").toMap().value("description").toString();
device->setStateValue(weatherDescriptionStateTypeId,description);
}
if(dataMap.contains("wind")){
int windDirection = dataMap.value("wind").toMap().value("deg").toInt();
double windSpeed = dataMap.value("wind").toMap().value("speed").toDouble();
device->setStateValue(windDirectionStateTypeId,windDirection);
device->setStateValue(windSpeedStateTypeId,windSpeed);
}
}
}
}
| mzanetti/guh | plugins/deviceplugins/openweathermap/devicepluginopenweathermap.cpp | C++ | gpl-2.0 | 17,008 |
#!/usr/bin/env python
#
# Copyright (C) 2007 Sascha Peilicke <sasch.pe@gmx.de>
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
from random import randrange
from zipfile import ZipFile
from StringIO import StringIO
# Constants
DEFAULT_LEVELPACK = './data/default_pack.zip'
SKILL_EASY = 'Easy' # These values should match the
SKILL_MEDIUM = 'Medium' # the level files!
SKILL_HARD = 'Hard'
FIELD_INVALID = 0 # Constants describing a field on
FIELD_VALID = 1 # the playfield
FIELD_MARKED_VALID = 2
FIELD_MARKED_INVALID = 4
FIELD_OPEN = 8
class Game(object):
"""A paint by numbers game also called nonogram.
"""
def __init__(self, skill=None):
"""Creates a picross game.
Parameters:
skill - Desired skill level (None == random)
"""
self.__level = None
self.__name = None
self.__skill = None
self.__fieldsToOpen = 0
self.__fieldsOpened = 0
self.load(skill=skill)
#
# Miscellaneous methods
#
def _debug_print(self):
print self.getInfo()
print 'go: %s' % (self.__gameOver)
for row in self.__level:
print row
#
# Game information retrieval
#
def getInfo(self):
"""Returns the name, skill and size of the level
"""
return self.__name,self.__skill,len(self.__level)
def getRowHint(self,row):
"""Returns the hint for a specific row.
"""
hint,count = [],0
for columnItem in self.__level[row]:
if columnItem == FIELD_VALID:
count += 1
else:
if count > 0:
hint.append(count)
count = 0
if count > 0:
hint.append(count)
if not hint:
hint.append(0)
return hint
def getColumnHint(self,col):
"""Returns the hint for a specific column.
"""
hint,count = [],0
for row in self.__level:
if row[col] == FIELD_VALID:
count += 1
else:
if count > 0:
hint.append(count)
count = 0
if count > 0:
hint.append(count)
if not hint:
hint.append(0)
return hint
def getField(self,col,row):
return self.__level[row][col]
def isGameWon(self):
return self.__fieldsOpened == self.__fieldsToOpen
#
# Game manipulation methods
#
def restart(self):
"""Reinitializes the current game
"""
for i, row in enumerate(self.__level):
for j, field in enumerate(row):
if field == FIELD_OPEN or field == FIELD_MARKED_VALID:
self.__level[i][j] = FIELD_VALID
elif field == FIELD_MARKED_INVALID:
self.__level[i][j] = FIELD_INVALID
self.__gameOver = False
self.__fieldsOpened = 0
def openField(self,col,row):
field = self.__level[row][col]
if field == FIELD_VALID or field == FIELD_MARKED_VALID:
self.__level[row][col] = FIELD_OPEN
self.__fieldsOpened += 1
return True
else:
return False
def markField(self,col,row):
field = self.__level[row][col]
if field == FIELD_VALID:
self.__level[row][col] = FIELD_MARKED_VALID
elif field == FIELD_MARKED_VALID:
self.__level[row][col] = FIELD_VALID
elif field == FIELD_INVALID:
self.__level[row][col] = FIELD_MARKED_INVALID
elif field == FIELD_MARKED_INVALID:
self.__level[row][col] = FIELD_INVALID
return self.__level[row][col]
def load(self,file=DEFAULT_LEVELPACK,skill=None):
"""Loads a level either from a zipped levelpack or from a textfile.
Parameters:
file - Can be a file path or zipped levelpack
skill - Desired level skill (None == random)
"""
if file.endswith('.lvl'):
# Set the skill variable
if file.startswith('easy'): self.__skill = SKILL_EASY
elif file.startswith('medium'): self.__skill = SKILL_MEDIUM
elif file.startswith('hard'): self.__skill = SKILL_HARD
self.__loadFileContent(open(file,'r'))
elif file.endswith('.zip'):
zip = ZipFile(file)
# We have to select from which files in the zipfile we
# want to choose randomly based on the level's skill
candidates = []
if skill == SKILL_EASY:
for file in zip.namelist():
if file.startswith('easy'):
candidates.append(file)
elif skill == SKILL_MEDIUM:
for file in zip.namelist():
if file.startswith('medium'):
candidates.append(file)
elif skill == SKILL_HARD:
for file in zip.namelist():
if file.startswith('hard'):
candidates.append(file)
# This should never happen in a good levelpack, but if it
# is malformed, just pick something!
if not candidates:
candidates = zip.namelist()
# Select one candidate randomly
which = candidates[randrange(len(candidates))]
# Set the skill variable
if which.startswith('easy'): self.__skill = SKILL_EASY
elif which.startswith('medium'):self.__skill = SKILL_MEDIUM
elif which.startswith('hard'): self.__skill = SKILL_HARD
# Read from zipfile and load file content
buf = zip.read(which)
self.__loadFileContent(StringIO(buf))
def __loadFileContent(self,file):
"""Actually loads the level data from a file.
"""
self.__level = []
for line in file:
if line.startswith('name:'):
self.__name = line[5:].strip()
elif line[0] == '0' or line[0] == '1':
row = []
for field in line:
if field == '0':
row.append(FIELD_INVALID)
elif field == '1':
self.__fieldsToOpen += 1
row.append(FIELD_VALID)
self.__level.append(row)
| saschpe/gnome_picross | gnomepicross/game.py | Python | gpl-2.0 | 5,836 |
/*
* Copyright (C) 2001-2015 Jacek Sieka, arnetheduck on gmail point 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 "stdinc.h"
#include "Mapper_WinUPnP.h"
#include "Util.h"
#include "Text.h"
#include "w.h"
#include "AirUtil.h"
#ifdef HAVE_WINUPNP_H
#include <ole2.h>
#include <natupnp.h>
#else // HAVE_WINUPNP_H
struct IUPnPNAT { };
struct IStaticPortMappingCollection { };
#endif // HAVE_WINUPNP_H
namespace dcpp {
const string Mapper_WinUPnP::name = "Windows UPnP";
Mapper_WinUPnP::Mapper_WinUPnP(const string& localIp, bool v6) :
Mapper(localIp, v6)
{
}
bool Mapper_WinUPnP::supportsProtocol(bool aV6) const {
return !aV6;
}
#ifdef HAVE_WINUPNP_H
bool Mapper_WinUPnP::init() {
HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if(FAILED(hr))
return false;
if(pUN)
return true;
// Lacking the __uuidof in mingw...
CLSID upnp;
OLECHAR upnps[] = L"{AE1E00AA-3FD5-403C-8A27-2BBDC30CD0E1}";
CLSIDFromString(upnps, &upnp);
IID iupnp;
OLECHAR iupnps[] = L"{B171C812-CC76-485A-94D8-B6B3A2794E99}";
CLSIDFromString(iupnps, &iupnp);
pUN = 0;
hr = ::CoCreateInstance(upnp, 0, CLSCTX_INPROC_SERVER, iupnp, reinterpret_cast<LPVOID*>(&pUN));
if(FAILED(hr))
pUN = 0;
return pUN ? true : false;
}
void Mapper_WinUPnP::uninit() {
::CoUninitialize();
}
bool Mapper_WinUPnP::add(const string& port, const Protocol protocol, const string& description) {
IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection();
if(!pSPMC)
return false;
/// @todo use a BSTR wrapper
BSTR protocol_ = SysAllocString(Text::toT(protocols[protocol]).c_str());
BSTR description_ = SysAllocString(Text::toT(description).c_str());
BSTR localIP = !localIp.empty() ? SysAllocString(Text::toT(localIp).c_str()) : nullptr;
auto port_ = Util::toInt(port);
IStaticPortMapping* pSPM = 0;
HRESULT hr = pSPMC->Add(port_, protocol_, port_, localIP, VARIANT_TRUE, description_, &pSPM);
SysFreeString(protocol_);
SysFreeString(description_);
SysFreeString(localIP);
bool ret = SUCCEEDED(hr);
if(ret) {
pSPM->Release();
lastPort = port_;
lastProtocol = protocol;
}
pSPMC->Release();
return ret;
}
bool Mapper_WinUPnP::remove(const string& port, const Protocol protocol) {
IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection();
if(!pSPMC)
return false;
/// @todo use a BSTR wrapper
BSTR protocol_ = SysAllocString(Text::toT(protocols[protocol]).c_str());
auto port_ = Util::toInt(port);
HRESULT hr = pSPMC->Remove(port_, protocol_);
pSPMC->Release();
SysFreeString(protocol_);
bool ret = SUCCEEDED(hr);
if(ret && port_ == lastPort && protocol == lastProtocol) {
lastPort = 0;
}
return ret;
}
string Mapper_WinUPnP::getDeviceName() {
/// @todo use IUPnPDevice::ModelName <http://msdn.microsoft.com/en-us/library/aa381670(VS.85).aspx>?
return Util::emptyString;
}
string Mapper_WinUPnP::getExternalIP() {
// Get the External IP from the last added mapping
if(!lastPort)
return Util::emptyString;
IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection();
if(!pSPMC)
return Util::emptyString;
/// @todo use a BSTR wrapper
BSTR protocol_ = SysAllocString(Text::toT(protocols[lastProtocol]).c_str());
// Lets Query our mapping
IStaticPortMapping* pSPM;
HRESULT hr = pSPMC->get_Item(lastPort, protocol_, &pSPM);
SysFreeString(protocol_);
// Query failed!
if(FAILED(hr) || !pSPM) {
pSPMC->Release();
return Util::emptyString;
}
BSTR bstrExternal = 0;
hr = pSPM->get_ExternalIPAddress(&bstrExternal);
if(FAILED(hr) || !bstrExternal) {
pSPM->Release();
pSPMC->Release();
return Util::emptyString;
}
// convert the result
string ret = Text::wideToAcp(bstrExternal);
// no longer needed
SysFreeString(bstrExternal);
// no longer needed
pSPM->Release();
pSPMC->Release();
return ret;
}
IStaticPortMappingCollection* Mapper_WinUPnP::getStaticPortMappingCollection() {
if(!pUN)
return 0;
IStaticPortMappingCollection* ret = 0;
HRESULT hr = 0;
// some routers lag here
for(int i = 0; i < 3; i++) {
hr = pUN->get_StaticPortMappingCollection (&ret);
if(SUCCEEDED(hr) && ret) break;
Sleep(1500);
}
if(FAILED(hr))
return 0;
return ret;
}
#else // HAVE_WINUPNP_H
bool Mapper_WinUPnP::init() {
return false;
}
void Mapper_WinUPnP::uninit() {
}
bool Mapper_WinUPnP::add(const string& /*port*/, const Protocol /*protocol*/, const string& /*description*/) {
return false;
}
bool Mapper_WinUPnP::remove(const string& /*port*/, const Protocol /*protocol*/) {
return false;
}
string Mapper_WinUPnP::getDeviceName() {
return Util::emptyString;
}
string Mapper_WinUPnP::getExternalIP() {
return Util::emptyString;
}
IStaticPortMappingCollection* Mapper_WinUPnP::getStaticPortMappingCollection() {
return 0;
}
#endif // HAVE_WINUPNP_H
} // dcpp namespace
| airdcnano/airdcnano | client/Mapper_WinUPnP.cpp | C++ | gpl-2.0 | 5,723 |
<?php
/*******************************************************************************
* HA2.php
* year : 2014
*
* The HA2 algorithm is a combination between two algorithms (CBA and WBA), where
* the first one is based on the language characters, and the second one is
* based on the language and common words. The HA2 algorithm consists of adding
* the sum of frequencies of the two algorithms for each language, and
* consequently, the promising language is the one having the highest new sum.
*
* NOTE: the algorithm requires including CBA.h, WBA.h and defines.h header
* files to work perfectly.
******************************************************************************/
require_once('CBA.php');
require_once('WBA.php');
class HA2
{
private $cba;
private $wba;
/*
* Constructor, in which the reference characters and reference words are
* loaded for each language.
*/
public function HA2()
{
// instantiate the CBA and WBA classes
$this->cba = new CBA();
$this->wba = new WBA();
}
/*
* Identification: function concerns the identification of an input text
* file, and it consists of adding the probabilities computed by the CBA
* and WBA for each language.
*
* [output]: the number of the promising language (between 0-31).
*
* @param text: is the text to identify.
*/
public function identification($text)
{
$cbaProbabilities = $this->cba->computeProbabilities($text); // retrieve probabilities computed by CBA
$wbaProbabilities = $this->wba->computeProbabilities($text); // retrieve probabilities computed by WBA
// add the probabilities for each language
$probabilities = array();
for($language=0; $language<NUMBER_LANGUAGES; $language++)
{
$probabilities[$language] = $cbaProbabilities[$language] + $wbaProbabilities[$language];
}
return $this->classification($probabilities);
}
/*
* Classification: function to classify the input text to the
* corresponding language using the sum of probabilities (CBA + WBA).
*
* [output]: the number of the promising language (between 0-31).
*
* @param probabilities: a table of probabilities of all the languages.
*/
public function classification($probabilities)
{
// retrieve the highest probability (sum of frequencies)
$max = 0; // keeps the highest probability
$promising_language = -1; // keeps the promising language
for($language=0; $language<NUMBER_LANGUAGES; $language++)
{
if($probabilities[$language] > $max)
{
$max = $probabilities[$language];
$promising_language = $language;
}
}
// determine exactly the promising language by applying an order of classification
if($promising_language != LNG_CHINESE && $promising_language != LNG_GREEK &&
$promising_language != LNG_HEBREW && $promising_language != LNG_HINDI &&
$promising_language != LNG_THAI)
{
if($max == $probabilities[LNG_ARABIC]) $promising_language = LNG_ARABIC;
else if($max == $probabilities[LNG_PERSIAN]) $promising_language = LNG_PERSIAN;
else if($max == $probabilities[LNG_URDU]) $promising_language = LNG_URDU;
else if($max == $probabilities[LNG_BULGARIAN]) $promising_language = LNG_BULGARIAN;
else if($max == $probabilities[LNG_RUSSIAN]) $promising_language = LNG_RUSSIAN;
else if($max == $probabilities[LNG_ENGLISH]) $promising_language = LNG_ENGLISH;
else if($max == $probabilities[LNG_DUTCH]) $promising_language = LNG_DUTCH;
else if($max == $probabilities[LNG_INDONESIAN]) $promising_language = LNG_INDONESIAN;
else if($max == $probabilities[LNG_MALAYSIAN]) $promising_language = LNG_MALAYSIAN;
else if($max == $probabilities[LNG_LATIN]) $promising_language = LNG_LATIN;
else if($max == $probabilities[LNG_ROMAN]) $promising_language = LNG_ROMAN;
else if($max == $probabilities[LNG_FRENCH]) $promising_language = LNG_FRENCH;
else if($max == $probabilities[LNG_ITALIAN]) $promising_language = LNG_ITALIAN;
else if($max == $probabilities[LNG_IRISH]) $promising_language = LNG_IRISH;
else if($max == $probabilities[LNG_SPANISH]) $promising_language = LNG_SPANISH;
else if($max == $probabilities[LNG_PORTUGUESE]) $promising_language = LNG_PORTUGUESE;
else if($max == $probabilities[LNG_ALBANIAN]) $promising_language = LNG_ALBANIAN;
else if($max == $probabilities[LNG_CZECH]) $promising_language = LNG_CZECH;
else if($max == $probabilities[LNG_FINNISH]) $promising_language = LNG_FINNISH;
else if($max == $probabilities[LNG_HUNGARIAN]) $promising_language = LNG_HUNGARIAN;
else if($max == $probabilities[LNG_SWEDISH]) $promising_language = LNG_SWEDISH;
else if($max == $probabilities[LNG_GERMAN]) $promising_language = LNG_GERMAN;
else if($max == $probabilities[LNG_NORWEGIAN]) $promising_language = LNG_NORWEGIAN;
else if($max == $probabilities[LNG_DANISH]) $promising_language = LNG_DANISH;
else if($max == $probabilities[LNG_ICELANDIC]) $promising_language = LNG_ICELANDIC;
else if($max == $probabilities[LNG_TURKISH]) $promising_language = LNG_TURKISH;
else if($max == $probabilities[LNG_POLISH]) $promising_language = LNG_POLISH;
}
return $promising_language;
}
}
?> | xprogramer/Language-Identification | HA2.php | PHP | gpl-2.0 | 5,238 |
/*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2007-2016 Minnesota Department of Transportation
* Copyright (C) 2014 AHMCT, University of California
*
* 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.
*/
package us.mn.state.dot.tms.server.comm;
import us.mn.state.dot.tms.DeviceRequest;
import us.mn.state.dot.tms.server.CameraImpl;
/**
* CameraPoller is an interface for pollers which can send camera control
* messages.
*
* @author Douglas Lau
* @author Travis Swanston
*/
public interface CameraPoller {
/** Send a PTZ camera move command */
void sendPTZ(CameraImpl c, float p, float t, float z);
/** Send a store camera preset command */
void sendStorePreset(CameraImpl c, int preset);
/** Send a recall camera preset command */
void sendRecallPreset(CameraImpl c, int preset);
/** Send a device request
* @param c The CameraImpl object.
* @param r The desired DeviceRequest. */
void sendRequest(CameraImpl c, DeviceRequest r);
}
| CA-IRIS/mn-iris | src/us/mn/state/dot/tms/server/comm/CameraPoller.java | Java | gpl-2.0 | 1,437 |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# 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.
# ----------------------------------------------------------------------------
"""Windowing and user-interface events.
This module allows applications to create and display windows with an
OpenGL context. Windows can be created with a variety of border styles
or set fullscreen.
You can register event handlers for keyboard, mouse and window events.
For games and kiosks you can also restrict the input to your windows,
for example disabling users from switching away from the application
with certain key combinations or capturing and hiding the mouse.
Getting started
---------------
Call the Window constructor to create a new window::
from pyglet.window import Window
win = Window(width=640, height=480)
Attach your own event handlers::
@win.event
def on_key_press(symbol, modifiers):
# ... handle this event ...
Place drawing code for the window within the `Window.on_draw` event handler::
@win.event
def on_draw():
# ... drawing code ...
Call `pyglet.app.run` to enter the main event loop (by default, this
returns when all open windows are closed)::
from pyglet import app
app.run()
Creating a game window
----------------------
Use `Window.set_exclusive_mouse` to hide the mouse cursor and receive relative
mouse movement events. Specify ``fullscreen=True`` as a keyword argument to
the `Window` constructor to render to the entire screen rather than opening a
window::
win = Window(fullscreen=True)
win.set_exclusive_mouse()
Working with multiple screens
-----------------------------
By default, fullscreen windows are opened on the primary display (typically
set by the user in their operating system settings). You can retrieve a list
of attached screens and select one manually if you prefer. This is useful for
opening a fullscreen window on each screen::
display = window.get_platform().get_default_display()
screens = display.get_screens()
windows = []
for screen in screens:
windows.append(window.Window(fullscreen=True, screen=screen))
Specifying a screen has no effect if the window is not fullscreen.
Specifying the OpenGL context properties
----------------------------------------
Each window has its own context which is created when the window is created.
You can specify the properties of the context before it is created
by creating a "template" configuration::
from pyglet import gl
# Create template config
config = gl.Config()
config.stencil_size = 8
config.aux_buffers = 4
# Create a window using this config
win = window.Window(config=config)
To determine if a given configuration is supported, query the screen (see
above, "Working with multiple screens")::
configs = screen.get_matching_configs(config)
if not configs:
# ... config is not supported
else:
win = window.Window(config=configs[0])
"""
from __future__ import division
from builtins import object
from future.utils import with_metaclass
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
import pyglet
from pyglet import gl
from pyglet.event import EventDispatcher
import pyglet.window.key
import pyglet.window.event
_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc
class WindowException(Exception):
"""The root exception for all window-related errors."""
pass
class NoSuchDisplayException(WindowException):
"""An exception indicating the requested display is not available."""
pass
class NoSuchConfigException(WindowException):
"""An exception indicating the requested configuration is not
available."""
pass
class NoSuchScreenModeException(WindowException):
"""An exception indicating the requested screen resolution could not be
met."""
pass
class MouseCursorException(WindowException):
"""The root exception for all mouse cursor-related errors."""
pass
class MouseCursor(object):
"""An abstract mouse cursor."""
#: Indicates if the cursor is drawn using OpenGL. This is True
#: for all mouse cursors except system cursors.
drawable = True
def draw(self, x, y):
"""Abstract render method.
The cursor should be drawn with the "hot" spot at the given
coordinates. The projection is set to the pyglet default (i.e.,
orthographic in window-space), however no other aspects of the
state can be assumed.
:Parameters:
`x` : int
X coordinate of the mouse pointer's hot spot.
`y` : int
Y coordinate of the mouse pointer's hot spot.
"""
raise NotImplementedError('abstract')
class DefaultMouseCursor(MouseCursor):
"""The default mouse cursor used by the operating system."""
drawable = False
class ImageMouseCursor(MouseCursor):
"""A user-defined mouse cursor created from an image.
Use this class to create your own mouse cursors and assign them
to windows. There are no constraints on the image size or format.
"""
drawable = True
def __init__(self, image, hot_x=0, hot_y=0):
"""Create a mouse cursor from an image.
:Parameters:
`image` : `pyglet.image.AbstractImage`
Image to use for the mouse cursor. It must have a
valid ``texture`` attribute.
`hot_x` : int
X coordinate of the "hot" spot in the image relative to the
image's anchor.
`hot_y` : int
Y coordinate of the "hot" spot in the image, relative to the
image's anchor.
"""
self.texture = image.get_texture()
self.hot_x = hot_x
self.hot_y = hot_y
def draw(self, x, y):
gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT)
gl.glColor4f(1, 1, 1, 1)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
self.texture.blit(x - self.hot_x, y - self.hot_y, 0)
gl.glPopAttrib()
def _PlatformEventHandler(data):
"""Decorator for platform event handlers.
Apply giving the platform-specific data needed by the window to associate
the method with an event. See platform-specific subclasses of this
decorator for examples.
The following attributes are set on the function, which is returned
otherwise unchanged:
_platform_event
True
_platform_event_data
List of data applied to the function (permitting multiple decorators
on the same method).
"""
def _event_wrapper(f):
f._platform_event = True
if not hasattr(f, '_platform_event_data'):
f._platform_event_data = []
f._platform_event_data.append(data)
return f
return _event_wrapper
def _ViewEventHandler(f):
f._view = True
return f
class _WindowMetaclass(type):
"""Sets the _platform_event_names class variable on the window
subclass.
"""
def __init__(cls, name, bases, dict):
cls._platform_event_names = set()
for base in bases:
if hasattr(base, '_platform_event_names'):
cls._platform_event_names.update(base._platform_event_names)
for name, func in dict.items():
if hasattr(func, '_platform_event'):
cls._platform_event_names.add(name)
super(_WindowMetaclass, cls).__init__(name, bases, dict)
class BaseWindow(with_metaclass(_WindowMetaclass, EventDispatcher)):
"""Platform-independent application window.
A window is a "heavyweight" object occupying operating system resources.
The "client" or "content" area of a window is filled entirely with
an OpenGL viewport. Applications have no access to operating system
widgets or controls; all rendering must be done via OpenGL.
Windows may appear as floating regions or can be set to fill an entire
screen (fullscreen). When floating, windows may appear borderless or
decorated with a platform-specific frame (including, for example, the
title bar, minimize and close buttons, resize handles, and so on).
While it is possible to set the location of a window, it is recommended
that applications allow the platform to place it according to local
conventions. This will ensure it is not obscured by other windows,
and appears on an appropriate screen for the user.
To render into a window, you must first call `switch_to`, to make
it the current OpenGL context. If you use only one window in the
application, there is no need to do this.
:Ivariables:
`has_exit` : bool
True if the user has attempted to close the window.
:deprecated: Windows are closed immediately by the default
`on_close` handler when `pyglet.app.event_loop` is being
used.
"""
# Filled in by metaclass with the names of all methods on this (sub)class
# that are platform event handlers.
_platform_event_names = set()
#: The default window style.
WINDOW_STYLE_DEFAULT = None
#: The window style for pop-up dialogs.
WINDOW_STYLE_DIALOG = 'dialog'
#: The window style for tool windows.
WINDOW_STYLE_TOOL = 'tool'
#: A window style without any decoration.
WINDOW_STYLE_BORDERLESS = 'borderless'
#: The default mouse cursor.
CURSOR_DEFAULT = None
#: A crosshair mouse cursor.
CURSOR_CROSSHAIR = 'crosshair'
#: A pointing hand mouse cursor.
CURSOR_HAND = 'hand'
#: A "help" mouse cursor; typically a question mark and an arrow.
CURSOR_HELP = 'help'
#: A mouse cursor indicating that the selected operation is not permitted.
CURSOR_NO = 'no'
#: A mouse cursor indicating the element can be resized.
CURSOR_SIZE = 'size'
#: A mouse cursor indicating the element can be resized from the top
#: border.
CURSOR_SIZE_UP = 'size_up'
#: A mouse cursor indicating the element can be resized from the
#: upper-right corner.
CURSOR_SIZE_UP_RIGHT = 'size_up_right'
#: A mouse cursor indicating the element can be resized from the right
#: border.
CURSOR_SIZE_RIGHT = 'size_right'
#: A mouse cursor indicating the element can be resized from the lower-right
#: corner.
CURSOR_SIZE_DOWN_RIGHT = 'size_down_right'
#: A mouse cursor indicating the element can be resized from the bottom
#: border.
CURSOR_SIZE_DOWN = 'size_down'
#: A mouse cursor indicating the element can be resized from the lower-left
#: corner.
CURSOR_SIZE_DOWN_LEFT = 'size_down_left'
#: A mouse cursor indicating the element can be resized from the left
#: border.
CURSOR_SIZE_LEFT = 'size_left'
#: A mouse cursor indicating the element can be resized from the upper-left
#: corner.
CURSOR_SIZE_UP_LEFT = 'size_up_left'
#: A mouse cursor indicating the element can be resized vertically.
CURSOR_SIZE_UP_DOWN = 'size_up_down'
#: A mouse cursor indicating the element can be resized horizontally.
CURSOR_SIZE_LEFT_RIGHT = 'size_left_right'
#: A text input mouse cursor (I-beam).
CURSOR_TEXT = 'text'
#: A "wait" mouse cursor; typically an hourglass or watch.
CURSOR_WAIT = 'wait'
#: The "wait" mouse cursor combined with an arrow.
CURSOR_WAIT_ARROW = 'wait_arrow'
has_exit = False
#: Window display contents validity. The `pyglet.app` event loop
#: examines every window each iteration and only dispatches the `on_draw`
#: event to windows that have `invalid` set. By default, windows always
#: have `invalid` set to ``True``.
#:
#: You can prevent redundant redraws by setting this variable to ``False``
#: in the window's `on_draw` handler, and setting it to True again in
#: response to any events that actually do require a window contents
#: update.
#:
#: :type: bool
#: :since: pyglet 1.1
invalid = True
#: Legacy invalidation flag introduced in pyglet 1.2: set by all event
#: dispatches that go to non-empty handlers. The default 1.2 event loop
#: will therefore redraw after any handled event or scheduled function.
_legacy_invalid = True
# Instance variables accessible only via properties
_width = None
_height = None
_caption = None
_resizable = False
_style = WINDOW_STYLE_DEFAULT
_fullscreen = False
_visible = False
_vsync = False
_screen = None
_config = None
_context = None
# Used to restore window size and position after fullscreen
_windowed_size = None
_windowed_location = None
# Subclasses should update these after relevant events
_mouse_cursor = DefaultMouseCursor()
_mouse_x = 0
_mouse_y = 0
_mouse_visible = True
_mouse_exclusive = False
_mouse_in_window = False
_event_queue = None
_enable_event_queue = True # overridden by EventLoop.
_allow_dispatch_event = False # controlled by dispatch_events stack frame
# Class attributes
_default_width = 640
_default_height = 480
def __init__(self,
width=None,
height=None,
caption=None,
resizable=False,
style=WINDOW_STYLE_DEFAULT,
fullscreen=False,
visible=True,
vsync=True,
display=None,
screen=None,
config=None,
context=None,
mode=None):
"""Create a window.
All parameters are optional, and reasonable defaults are assumed
where they are not specified.
The `display`, `screen`, `config` and `context` parameters form
a hierarchy of control: there is no need to specify more than
one of these. For example, if you specify `screen` the `display`
will be inferred, and a default `config` and `context` will be
created.
`config` is a special case; it can be a template created by the
user specifying the attributes desired, or it can be a complete
`config` as returned from `Screen.get_matching_configs` or similar.
The context will be active as soon as the window is created, as if
`switch_to` was just called.
:Parameters:
`width` : int
Width of the window, in pixels. Defaults to 640, or the
screen width if `fullscreen` is True.
`height` : int
Height of the window, in pixels. Defaults to 480, or the
screen height if `fullscreen` is True.
`caption` : str or unicode
Initial caption (title) of the window. Defaults to
``sys.argv[0]``.
`resizable` : bool
If True, the window will be resizable. Defaults to False.
`style` : int
One of the ``WINDOW_STYLE_*`` constants specifying the
border style of the window.
`fullscreen` : bool
If True, the window will cover the entire screen rather
than floating. Defaults to False.
`visible` : bool
Determines if the window is visible immediately after
creation. Defaults to True. Set this to False if you
would like to change attributes of the window before
having it appear to the user.
`vsync` : bool
If True, buffer flips are synchronised to the primary screen's
vertical retrace, eliminating flicker.
`display` : `Display`
The display device to use. Useful only under X11.
`screen` : `Screen`
The screen to use, if in fullscreen.
`config` : `pyglet.gl.Config`
Either a template from which to create a complete config,
or a complete config.
`context` : `pyglet.gl.Context`
The context to attach to this window. The context must
not already be attached to another window.
`mode` : `ScreenMode`
The screen will be switched to this mode if `fullscreen` is
True. If None, an appropriate mode is selected to accomodate
`width` and `height.`
"""
EventDispatcher.__init__(self)
self._event_queue = []
if not display:
display = get_platform().get_default_display()
if not screen:
screen = display.get_default_screen()
if not config:
for template_config in [
gl.Config(double_buffer=True, depth_size=24),
gl.Config(double_buffer=True, depth_size=16),
None]:
try:
config = screen.get_best_config(template_config)
break
except NoSuchConfigException:
pass
if not config:
raise NoSuchConfigException('No standard config is available.')
if not config.is_complete():
config = screen.get_best_config(config)
if not context:
context = config.create_context(gl.current_context)
# Set these in reverse order to above, to ensure we get user
# preference
self._context = context
self._config = self._context.config
# XXX deprecate config's being screen-specific
if hasattr(self._config, 'screen'):
self._screen = self._config.screen
else:
display = self._config.canvas.display
self._screen = display.get_default_screen()
self._display = self._screen.display
if fullscreen:
if width is None and height is None:
self._windowed_size = self._default_width, self._default_height
width, height = self._set_fullscreen_mode(mode, width, height)
if not self._windowed_size:
self._windowed_size = width, height
else:
if width is None:
width = self._default_width
if height is None:
height = self._default_height
self._width = width
self._height = height
self._resizable = resizable
self._fullscreen = fullscreen
self._style = style
if pyglet.options['vsync'] is not None:
self._vsync = pyglet.options['vsync']
else:
self._vsync = vsync
if caption is None:
caption = sys.argv[0]
# Decode hack for Python2 unicode support:
if hasattr(caption, "decode"):
try:
caption = caption.decode("utf8")
except UnicodeDecodeError:
caption = "pyglet"
self._caption = caption
from pyglet import app
app.windows.add(self)
self._create()
self.switch_to()
if visible:
self.set_visible(True)
self.activate()
def __del__(self):
# Always try to clean up the window when it is dereferenced.
# Makes sure there are no dangling pointers or memory leaks.
# If the window is already closed, pass silently.
try:
self.close()
except: # XXX Avoid a NoneType error if already closed.
pass
def __repr__(self):
return '%s(width=%d, height=%d)' % \
(self.__class__.__name__, self.width, self.height)
def _create(self):
raise NotImplementedError('abstract')
def _recreate(self, changes):
"""Recreate the window with current attributes.
:Parameters:
`changes` : list of str
List of attribute names that were changed since the last
`_create` or `_recreate`. For example, ``['fullscreen']``
is given if the window is to be toggled to or from fullscreen.
"""
raise NotImplementedError('abstract')
def flip(self):
"""Swap the OpenGL front and back buffers.
Call this method on a double-buffered window to update the
visible display with the back buffer. The contents of the back buffer
is undefined after this operation.
Windows are double-buffered by default. This method is called
automatically by `EventLoop` after the `on_draw` event.
"""
raise NotImplementedError('abstract')
def switch_to(self):
"""Make this window the current OpenGL rendering context.
Only one OpenGL context can be active at a time. This method sets
the current window's context to be current. You should use this
method in preference to `pyglet.gl.Context.set_current`, as it may
perform additional initialisation functions.
"""
raise NotImplementedError('abstract')
def set_fullscreen(self, fullscreen=True, screen=None, mode=None,
width=None, height=None):
"""Toggle to or from fullscreen.
After toggling fullscreen, the GL context should have retained its
state and objects, however the buffers will need to be cleared and
redrawn.
If `width` and `height` are specified and `fullscreen` is True, the
screen may be switched to a different resolution that most closely
matches the given size. If the resolution doesn't match exactly,
a higher resolution is selected and the window will be centered
within a black border covering the rest of the screen.
:Parameters:
`fullscreen` : bool
True if the window should be made fullscreen, False if it
should be windowed.
`screen` : Screen
If not None and fullscreen is True, the window is moved to the
given screen. The screen must belong to the same display as
the window.
`mode` : `ScreenMode`
The screen will be switched to the given mode. The mode must
have been obtained by enumerating `Screen.get_modes`. If
None, an appropriate mode will be selected from the given
`width` and `height`.
`width` : int
Optional width of the window. If unspecified, defaults to the
previous window size when windowed, or the screen size if
fullscreen.
**Since:** pyglet 1.2
`height` : int
Optional height of the window. If unspecified, defaults to
the previous window size when windowed, or the screen size if
fullscreen.
**Since:** pyglet 1.2
"""
if (fullscreen == self._fullscreen and
(screen is None or screen is self._screen) and
(width is None or width == self._width) and
(height is None or height == self._height)):
return
if not self._fullscreen:
# Save windowed size
self._windowed_size = self.get_size()
self._windowed_location = self.get_location()
if fullscreen and screen is not None:
assert screen.display is self.display
self._screen = screen
self._fullscreen = fullscreen
if self._fullscreen:
self._width, self._height = self._set_fullscreen_mode(
mode, width, height)
else:
self.screen.restore_mode()
self._width, self._height = self._windowed_size
if width is not None:
self._width = width
if height is not None:
self._height = height
self._recreate(['fullscreen'])
if not self._fullscreen and self._windowed_location:
# Restore windowed location.
# TODO: Move into platform _create?
# Not harmless on Carbon because upsets _width and _height
# via _on_window_bounds_changed.
if pyglet.compat_platform != 'darwin' or pyglet.options['darwin_cocoa']:
self.set_location(*self._windowed_location)
def _set_fullscreen_mode(self, mode, width, height):
if mode is not None:
self.screen.set_mode(mode)
if width is None:
width = self.screen.width
if height is None:
height = self.screen.height
elif width is not None or height is not None:
if width is None:
width = 0
if height is None:
height = 0
mode = self.screen.get_closest_mode(width, height)
if mode is not None:
self.screen.set_mode(mode)
elif self.screen.get_modes():
# Only raise exception if mode switching is at all possible.
raise NoSuchScreenModeException(
'No mode matching %dx%d' % (width, height))
else:
width = self.screen.width
height = self.screen.height
return width, height
def on_resize(self, width, height):
"""A default resize event handler.
This default handler updates the GL viewport to cover the entire
window and sets the ``GL_PROJECTION`` matrix to be orthogonal in
window space. The bottom-left corner is (0, 0) and the top-right
corner is the width and height of the window in pixels.
Override this event handler with your own to create another
projection, for example in perspective.
"""
# XXX avoid GLException by not allowing 0 width or height.
width = max(1, width)
height = max(1, height)
gl.glViewport(0, 0, width, height)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(0, width, 0, height, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
def on_close(self):
"""Default on_close handler."""
self.has_exit = True
from pyglet import app
if app.event_loop.is_running:
self.close()
def on_key_press(self, symbol, modifiers):
"""Default on_key_press handler."""
if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK |
key.MOD_CAPSLOCK |
key.MOD_SCROLLLOCK)):
self.dispatch_event('on_close')
def close(self):
"""Close the window.
After closing the window, the GL context will be invalid. The
window instance cannot be reused once closed (see also `set_visible`).
The `pyglet.app.EventLoop.on_window_close` event is dispatched on
`pyglet.app.event_loop` when this method is called.
"""
from pyglet import app
if not self._context:
return
app.windows.remove(self)
self._context.destroy()
self._config = None
self._context = None
if app.event_loop:
app.event_loop.dispatch_event('on_window_close', self)
self._event_queue = []
def draw_mouse_cursor(self):
"""Draw the custom mouse cursor.
If the current mouse cursor has ``drawable`` set, this method
is called before the buffers are flipped to render it.
This method always leaves the ``GL_MODELVIEW`` matrix as current,
regardless of what it was set to previously. No other GL state
is affected.
There is little need to override this method; instead, subclass
``MouseCursor`` and provide your own ``draw`` method.
"""
# Draw mouse cursor if set and visible.
# XXX leaves state in modelview regardless of starting state
if (self._mouse_cursor.drawable and
self._mouse_visible and
self._mouse_in_window):
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0, self.width, 0, self.height, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
self._mouse_cursor.draw(self._mouse_x, self._mouse_y)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPopMatrix()
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPopMatrix()
# Properties provide read-only access to instance variables. Use
# set_* methods to change them if applicable.
@property
def caption(self):
"""The window caption (title). Read-only.
:type: str
"""
return self._caption
@property
def resizeable(self):
"""True if the window is resizable. Read-only.
:type: bool
"""
return self._resizable
@property
def style(self):
"""The window style; one of the ``WINDOW_STYLE_*`` constants.
Read-only.
:type: int
"""
return self._style
@property
def fullscreen(self):
"""True if the window is currently fullscreen. Read-only.
:type: bool
"""
return self._fullscreen
@property
def visible(self):
"""True if the window is currently visible. Read-only.
:type: bool
"""
return self._visible
@property
def vsync(self):
"""True if buffer flips are synchronised to the screen's vertical
retrace. Read-only.
:type: bool
"""
return self._vsync
@property
def display(self):
"""The display this window belongs to. Read-only.
:type: `Display`
"""
return self._display
@property
def screen(self):
"""The screen this window is fullscreen in. Read-only.
:type: `Screen`
"""
return self._screen
@property
def config(self):
"""A GL config describing the context of this window. Read-only.
:type: `pyglet.gl.Config`
"""
return self._config
@property
def context(self):
"""The OpenGL context attached to this window. Read-only.
:type: `pyglet.gl.Context`
"""
return self._context
# These are the only properties that can be set
@property
def width(self):
"""The width of the window, in pixels. Read-write.
:type: int
"""
return self.get_size()[0]
@width.setter
def width(self, new_width):
self.set_size(new_width, self.height)
@property
def height(self):
"""The height of the window, in pixels. Read-write.
:type: int
"""
return self.get_size()[1]
@height.setter
def height(self, new_height):
self.set_size(self.width, new_height)
def set_caption(self, caption):
"""Set the window's caption.
The caption appears in the titlebar of the window, if it has one,
and in the taskbar on Windows and many X11 window managers.
:Parameters:
`caption` : str or unicode
The caption to set.
"""
raise NotImplementedError('abstract')
def set_minimum_size(self, width, height):
"""Set the minimum size of the window.
Once set, the user will not be able to resize the window smaller
than the given dimensions. There is no way to remove the
minimum size constraint on a window (but you could set it to 0,0).
The behaviour is undefined if the minimum size is set larger than
the current size of the window.
The window size does not include the border or title bar.
:Parameters:
`width` : int
Minimum width of the window, in pixels.
`height` : int
Minimum height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_maximum_size(self, width, height):
"""Set the maximum size of the window.
Once set, the user will not be able to resize the window larger
than the given dimensions. There is no way to remove the
maximum size constraint on a window (but you could set it to a large
value).
The behaviour is undefined if the maximum size is set smaller than
the current size of the window.
The window size does not include the border or title bar.
:Parameters:
`width` : int
Maximum width of the window, in pixels.
`height` : int
Maximum height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_size(self, width, height):
"""Resize the window.
The behaviour is undefined if the window is not resizable, or if
it is currently fullscreen.
The window size does not include the border or title bar.
:Parameters:
`width` : int
New width of the window, in pixels.
`height` : int
New height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def get_size(self):
"""Return the current size of the window.
The window size does not include the border or title bar.
:rtype: (int, int)
:return: The width and height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_location(self, x, y):
"""Set the position of the window.
:Parameters:
`x` : int
Distance of the left edge of the window from the left edge
of the virtual desktop, in pixels.
`y` : int
Distance of the top edge of the window from the top edge of
the virtual desktop, in pixels.
"""
raise NotImplementedError('abstract')
def get_location(self):
"""Return the current position of the window.
:rtype: (int, int)
:return: The distances of the left and top edges from their respective
edges on the virtual desktop, in pixels.
"""
raise NotImplementedError('abstract')
def activate(self):
"""Attempt to restore keyboard focus to the window.
Depending on the window manager or operating system, this may not
be successful. For example, on Windows XP an application is not
allowed to "steal" focus from another application. Instead, the
window's taskbar icon will flash, indicating it requires attention.
"""
raise NotImplementedError('abstract')
def set_visible(self, visible=True):
"""Show or hide the window.
:Parameters:
`visible` : bool
If True, the window will be shown; otherwise it will be
hidden.
"""
raise NotImplementedError('abstract')
def minimize(self):
"""Minimize the window.
"""
raise NotImplementedError('abstract')
def maximize(self):
"""Maximize the window.
The behaviour of this method is somewhat dependent on the user's
display setup. On a multi-monitor system, the window may maximize
to either a single screen or the entire virtual desktop.
"""
raise NotImplementedError('abstract')
def set_vsync(self, vsync):
"""Enable or disable vertical sync control.
When enabled, this option ensures flips from the back to the front
buffer are performed only during the vertical retrace period of the
primary display. This can prevent "tearing" or flickering when
the buffer is updated in the middle of a video scan.
Note that LCD monitors have an analogous time in which they are not
reading from the video buffer; while it does not correspond to
a vertical retrace it has the same effect.
With multi-monitor systems the secondary monitor cannot be
synchronised to, so tearing and flicker cannot be avoided when the
window is positioned outside of the primary display. In this case
it may be advisable to forcibly reduce the framerate (for example,
using `pyglet.clock.set_fps_limit`).
:Parameters:
`vsync` : bool
If True, vsync is enabled, otherwise it is disabled.
"""
raise NotImplementedError('abstract')
def set_mouse_visible(self, visible=True):
"""Show or hide the mouse cursor.
The mouse cursor will only be hidden while it is positioned within
this window. Mouse events will still be processed as usual.
:Parameters:
`visible` : bool
If True, the mouse cursor will be visible, otherwise it
will be hidden.
"""
self._mouse_visible = visible
self.set_mouse_platform_visible()
def set_mouse_platform_visible(self, platform_visible=None):
"""Set the platform-drawn mouse cursor visibility. This is called
automatically after changing the mouse cursor or exclusive mode.
Applications should not normally need to call this method, see
`set_mouse_visible` instead.
:Parameters:
`platform_visible` : bool or None
If None, sets platform visibility to the required visibility
for the current exclusive mode and cursor type. Otherwise,
a bool value will override and force a visibility.
"""
raise NotImplementedError()
def set_mouse_cursor(self, cursor=None):
"""Change the appearance of the mouse cursor.
The appearance of the mouse cursor is only changed while it is
within this window.
:Parameters:
`cursor` : `MouseCursor`
The cursor to set, or None to restore the default cursor.
"""
if cursor is None:
cursor = DefaultMouseCursor()
self._mouse_cursor = cursor
self.set_mouse_platform_visible()
def set_exclusive_mouse(self, exclusive=True):
"""Hide the mouse cursor and direct all mouse events to this
window.
When enabled, this feature prevents the mouse leaving the window. It
is useful for certain styles of games that require complete control of
the mouse. The position of the mouse as reported in subsequent events
is meaningless when exclusive mouse is enabled; you should only use
the relative motion parameters ``dx`` and ``dy``.
:Parameters:
`exclusive` : bool
If True, exclusive mouse is enabled, otherwise it is disabled.
"""
raise NotImplementedError('abstract')
def set_exclusive_keyboard(self, exclusive=True):
"""Prevent the user from switching away from this window using
keyboard accelerators.
When enabled, this feature disables certain operating-system specific
key combinations such as Alt+Tab (Command+Tab on OS X). This can be
useful in certain kiosk applications, it should be avoided in general
applications or games.
:Parameters:
`exclusive` : bool
If True, exclusive keyboard is enabled, otherwise it is
disabled.
"""
raise NotImplementedError('abstract')
def get_system_mouse_cursor(self, name):
"""Obtain a system mouse cursor.
Use `set_mouse_cursor` to make the cursor returned by this method
active. The names accepted by this method are the ``CURSOR_*``
constants defined on this class.
:Parameters:
`name` : str
Name describing the mouse cursor to return. For example,
``CURSOR_WAIT``, ``CURSOR_HELP``, etc.
:rtype: `MouseCursor`
:return: A mouse cursor which can be used with `set_mouse_cursor`.
"""
raise NotImplementedError()
def set_icon(self, *images):
"""Set the window icon.
If multiple images are provided, one with an appropriate size
will be selected (if the correct size is not provided, the image
will be scaled).
Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and
128x128 (Mac only).
:Parameters:
`images` : sequence of `pyglet.image.AbstractImage`
List of images to use for the window icon.
"""
pass
def clear(self):
"""Clear the window.
This is a convenience method for clearing the color and depth
buffer. The window must be the active context (see `switch_to`).
"""
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
def dispatch_event(self, *args):
if not self._enable_event_queue or self._allow_dispatch_event:
if EventDispatcher.dispatch_event(self, *args) != False:
self._legacy_invalid = True
else:
self._event_queue.append(args)
def dispatch_events(self):
"""Poll the operating system event queue for new events and call
attached event handlers.
This method is provided for legacy applications targeting pyglet 1.0,
and advanced applications that must integrate their event loop
into another framework.
Typical applications should use `pyglet.app.run`.
"""
raise NotImplementedError('abstract')
# If documenting, show the event methods. Otherwise, leave them out
# as they are not really methods.
if _is_epydoc:
def on_key_press(symbol, modifiers):
"""A key on the keyboard was pressed (and held down).
In pyglet 1.0 the default handler sets `has_exit` to ``True`` if
the ``ESC`` key is pressed.
In pyglet 1.1 the default handler dispatches the `on_close`
event if the ``ESC`` key is pressed.
:Parameters:
`symbol` : int
The key symbol pressed.
`modifiers` : int
Bitwise combination of the key modifiers active.
:event:
"""
def on_key_release(symbol, modifiers):
"""A key on the keyboard was released.
:Parameters:
`symbol` : int
The key symbol pressed.
`modifiers` : int
Bitwise combination of the key modifiers active.
:event:
"""
def on_text(text):
"""The user input some text.
Typically this is called after `on_key_press` and before
`on_key_release`, but may also be called multiple times if the key
is held down (key repeating); or called without key presses if
another input method was used (e.g., a pen input).
You should always use this method for interpreting text, as the
key symbols often have complex mappings to their unicode
representation which this event takes care of.
:Parameters:
`text` : unicode
The text entered by the user.
:event:
"""
def on_text_motion(motion):
"""The user moved the text input cursor.
Typically this is called after `on_key_press` and before
`on_key_release`, but may also be called multiple times if the key
is help down (key repeating).
You should always use this method for moving the text input cursor
(caret), as different platforms have different default keyboard
mappings, and key repeats are handled correctly.
The values that `motion` can take are defined in
`pyglet.window.key`:
* MOTION_UP
* MOTION_RIGHT
* MOTION_DOWN
* MOTION_LEFT
* MOTION_NEXT_WORD
* MOTION_PREVIOUS_WORD
* MOTION_BEGINNING_OF_LINE
* MOTION_END_OF_LINE
* MOTION_NEXT_PAGE
* MOTION_PREVIOUS_PAGE
* MOTION_BEGINNING_OF_FILE
* MOTION_END_OF_FILE
* MOTION_BACKSPACE
* MOTION_DELETE
:Parameters:
`motion` : int
The direction of motion; see remarks.
:event:
"""
def on_text_motion_select(motion):
"""The user moved the text input cursor while extending the
selection.
Typically this is called after `on_key_press` and before
`on_key_release`, but may also be called multiple times if the key
is help down (key repeating).
You should always use this method for responding to text selection
events rather than the raw `on_key_press`, as different platforms
have different default keyboard mappings, and key repeats are
handled correctly.
The values that `motion` can take are defined in `pyglet.window.key`:
* MOTION_UP
* MOTION_RIGHT
* MOTION_DOWN
* MOTION_LEFT
* MOTION_NEXT_WORD
* MOTION_PREVIOUS_WORD
* MOTION_BEGINNING_OF_LINE
* MOTION_END_OF_LINE
* MOTION_NEXT_PAGE
* MOTION_PREVIOUS_PAGE
* MOTION_BEGINNING_OF_FILE
* MOTION_END_OF_FILE
:Parameters:
`motion` : int
The direction of selection motion; see remarks.
:event:
"""
def on_mouse_motion(x, y, dx, dy):
"""The mouse was moved with no buttons held down.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`dx` : int
Relative X position from the previous mouse position.
`dy` : int
Relative Y position from the previous mouse position.
:event:
"""
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
"""The mouse was moved with one or more mouse buttons pressed.
This event will continue to be fired even if the mouse leaves
the window, so long as the drag buttons are continuously held down.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`dx` : int
Relative X position from the previous mouse position.
`dy` : int
Relative Y position from the previous mouse position.
`buttons` : int
Bitwise combination of the mouse buttons currently pressed.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_press(x, y, button, modifiers):
"""A mouse button was pressed (and held down).
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`button` : int
The mouse button that was pressed.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_release(x, y, button, modifiers):
"""A mouse button was released.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`button` : int
The mouse button that was released.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_scroll(x, y, scroll_x, scroll_y):
"""The mouse wheel was scrolled.
Note that most mice have only a vertical scroll wheel, so
`scroll_x` is usually 0. An exception to this is the Apple Mighty
Mouse, which has a mouse ball in place of the wheel which allows
both `scroll_x` and `scroll_y` movement.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`scroll_x` : int
Number of "clicks" towards the right (left if negative).
`scroll_y` : int
Number of "clicks" upwards (downwards if negative).
:event:
"""
def on_close():
"""The user attempted to close the window.
This event can be triggered by clicking on the "X" control box in
the window title bar, or by some other platform-dependent manner.
The default handler sets `has_exit` to ``True``. In pyglet 1.1, if
`pyglet.app.event_loop` is being used, `close` is also called,
closing the window immediately.
:event:
"""
def on_mouse_enter(x, y):
"""The mouse was moved into the window.
This event will not be trigged if the mouse is currently being
dragged.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
:event:
"""
def on_mouse_leave(x, y):
"""The mouse was moved outside of the window.
This event will not be trigged if the mouse is currently being
dragged. Note that the coordinates of the mouse pointer will be
outside of the window rectangle.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
:event:
"""
def on_expose():
"""A portion of the window needs to be redrawn.
This event is triggered when the window first appears, and any time
the contents of the window is invalidated due to another window
obscuring it.
There is no way to determine which portion of the window needs
redrawing. Note that the use of this method is becoming
increasingly uncommon, as newer window managers composite windows
automatically and keep a backing store of the window contents.
:event:
"""
def on_resize(width, height):
"""The window was resized.
The window will have the GL context when this event is dispatched;
there is no need to call `switch_to` in this handler.
:Parameters:
`width` : int
The new width of the window, in pixels.
`height` : int
The new height of the window, in pixels.
:event:
"""
def on_move(x, y):
"""The window was moved.
:Parameters:
`x` : int
Distance from the left edge of the screen to the left edge
of the window.
`y` : int
Distance from the top edge of the screen to the top edge of
the window. Note that this is one of few methods in pyglet
which use a Y-down coordinate system.
:event:
"""
def on_activate():
"""The window was activated.
This event can be triggered by clicking on the title bar, bringing
it to the foreground; or by some platform-specific method.
When a window is "active" it has the keyboard focus.
:event:
"""
def on_deactivate():
"""The window was deactivated.
This event can be triggered by clicking on another application
window. When a window is deactivated it no longer has the
keyboard focus.
:event:
"""
def on_show():
"""The window was shown.
This event is triggered when a window is restored after being
minimised, or after being displayed for the first time.
:event:
"""
def on_hide():
"""The window was hidden.
This event is triggered when a window is minimised or (on Mac OS X)
hidden by the user.
:event:
"""
def on_context_lost():
"""The window's GL context was lost.
When the context is lost no more GL methods can be called until it
is recreated. This is a rare event, triggered perhaps by the user
switching to an incompatible video mode. When it occurs, an
application will need to reload all objects (display lists, texture
objects, shaders) as well as restore the GL state.
:event:
"""
def on_context_state_lost():
"""The state of the window's GL context was lost.
pyglet may sometimes need to recreate the window's GL context if
the window is moved to another video device, or between fullscreen
or windowed mode. In this case it will try to share the objects
(display lists, texture objects, shaders) between the old and new
contexts. If this is possible, only the current state of the GL
context is lost, and the application should simply restore state.
:event:
"""
def on_draw():
"""The window contents must be redrawn.
The `EventLoop` will dispatch this event when the window
should be redrawn. This will happen during idle time after
any window events and after any scheduled functions were called.
The window will already have the GL context, so there is no
need to call `switch_to`. The window's `flip` method will
be called after this event, so your event handler should not.
You should make no assumptions about the window contents when
this event is triggered; a resize or expose event may have
invalidated the framebuffer since the last time it was drawn.
:since: pyglet 1.1
:event:
"""
BaseWindow.register_event_type('on_key_press')
BaseWindow.register_event_type('on_key_release')
BaseWindow.register_event_type('on_text')
BaseWindow.register_event_type('on_text_motion')
BaseWindow.register_event_type('on_text_motion_select')
BaseWindow.register_event_type('on_mouse_motion')
BaseWindow.register_event_type('on_mouse_drag')
BaseWindow.register_event_type('on_mouse_press')
BaseWindow.register_event_type('on_mouse_release')
BaseWindow.register_event_type('on_mouse_scroll')
BaseWindow.register_event_type('on_mouse_enter')
BaseWindow.register_event_type('on_mouse_leave')
BaseWindow.register_event_type('on_close')
BaseWindow.register_event_type('on_expose')
BaseWindow.register_event_type('on_resize')
BaseWindow.register_event_type('on_move')
BaseWindow.register_event_type('on_activate')
BaseWindow.register_event_type('on_deactivate')
BaseWindow.register_event_type('on_show')
BaseWindow.register_event_type('on_hide')
BaseWindow.register_event_type('on_context_lost')
BaseWindow.register_event_type('on_context_state_lost')
BaseWindow.register_event_type('on_draw')
class FPSDisplay(object):
"""Display of a window's framerate.
This is a convenience class to aid in profiling and debugging. Typical
usage is to create an `FPSDisplay` for each window, and draw the display
at the end of the windows' `on_draw` event handler::
window = pyglet.window.Window()
fps_display = FPSDisplay(window)
@window.event
def on_draw():
# ... perform ordinary window drawing operations ...
fps_display.draw()
The style and position of the display can be modified via the `label`
attribute. Different text can be substituted by overriding the
`set_fps` method. The display can be set to update more or less often
by setting the `update_period` attribute.
:Ivariables:
`label` : Label
The text label displaying the framerate.
"""
#: Time in seconds between updates.
#:
#: :type: float
update_period = 0.25
def __init__(self, window):
from time import time
from pyglet.text import Label
self.label = Label('', x=10, y=10,
font_size=24, bold=True,
color=(127, 127, 127, 127))
self.window = window
self._window_flip = window.flip
window.flip = self._hook_flip
self.time = 0.0
self.last_time = time()
self.count = 0
def update(self):
"""Records a new data point at the current time. This method
is called automatically when the window buffer is flipped.
"""
from time import time
t = time()
self.count += 1
self.time += t - self.last_time
self.last_time = t
if self.time >= self.update_period:
self.set_fps(self.count / self.update_period)
self.time %= self.update_period
self.count = 0
def set_fps(self, fps):
"""Set the label text for the given FPS estimation.
Called by `update` every `update_period` seconds.
:Parameters:
`fps` : float
Estimated framerate of the window.
"""
self.label.text = '%.2f' % fps
def draw(self):
"""Draw the label.
The OpenGL state is assumed to be at default values, except
that the MODELVIEW and PROJECTION matrices are ignored. At
the return of this method the matrix mode will be MODELVIEW.
"""
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0, self.window.width, 0, self.window.height, -1, 1)
self.label.draw()
gl.glPopMatrix()
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPopMatrix()
def _hook_flip(self):
self.update()
self._window_flip()
if _is_epydoc:
# We are building documentation
Window = BaseWindow
Window.__name__ = 'Window'
del BaseWindow
else:
# Try to determine which platform to use.
if pyglet.compat_platform == 'darwin':
if pyglet.options['darwin_cocoa']:
from pyglet.window.cocoa import CocoaWindow as Window
else:
from pyglet.window.carbon import CarbonWindow as Window
elif pyglet.compat_platform in ('win32', 'cygwin'):
from pyglet.window.win32 import Win32Window as Window
else:
# XXX HACK around circ problem, should be fixed after removal of
# shadow nonsense
#pyglet.window = sys.modules[__name__]
#import key, mouse
from pyglet.window.xlib import XlibWindow as Window
# Deprecated API
def get_platform():
"""Get an instance of the Platform most appropriate for this
system.
:deprecated: Use `pyglet.canvas.Display`.
:rtype: `Platform`
:return: The platform instance.
"""
return Platform()
class Platform(object):
"""Operating-system-level functionality.
The platform instance can only be obtained with `get_platform`. Use
the platform to obtain a `Display` instance.
:deprecated: Use `pyglet.canvas.Display`
"""
def get_display(self, name):
"""Get a display device by name.
This is meaningful only under X11, where the `name` is a
string including the host name and display number; for example
``"localhost:1"``.
On platforms other than X11, `name` is ignored and the default
display is returned. pyglet does not support multiple multiple
video devices on Windows or OS X. If more than one device is
attached, they will appear as a single virtual device comprising
all the attached screens.
:deprecated: Use `pyglet.canvas.get_display`.
:Parameters:
`name` : str
The name of the display to connect to.
:rtype: `Display`
"""
for display in pyglet.app.displays:
if display.name == name:
return display
return pyglet.canvas.Display(name)
def get_default_display(self):
"""Get the default display device.
:deprecated: Use `pyglet.canvas.get_display`.
:rtype: `Display`
"""
return pyglet.canvas.get_display()
if _is_epydoc:
class Display(object):
"""A display device supporting one or more screens.
Use `Platform.get_display` or `Platform.get_default_display` to obtain
an instance of this class. Use a display to obtain `Screen` instances.
:deprecated: Use `pyglet.canvas.Display`.
"""
def __init__(self):
raise NotImplementedError('deprecated')
def get_screens(self):
"""Get the available screens.
A typical multi-monitor workstation comprises one `Display` with
multiple `Screen` s. This method returns a list of screens which
can be enumerated to select one for full-screen display.
For the purposes of creating an OpenGL config, the default screen
will suffice.
:rtype: list of `Screen`
"""
raise NotImplementedError('deprecated')
def get_default_screen(self):
"""Get the default screen as specified by the user's operating system
preferences.
:rtype: `Screen`
"""
raise NotImplementedError('deprecated')
def get_windows(self):
"""Get the windows currently attached to this display.
:rtype: sequence of `Window`
"""
raise NotImplementedError('deprecated')
else:
Display = pyglet.canvas.Display
Screen = pyglet.canvas.Screen
# XXX remove
# Create shadow window. (trickery is for circular import)
if not _is_epydoc:
pyglet.window = sys.modules[__name__]
gl._create_shadow_window()
| ajhager/copycat | lib/pyglet/window/__init__.py | Python | gpl-2.0 | 65,226 |
// **********************************************************************
//
// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
//
// **********************************************************************
#include <Ice/Ice.h>
#include <IceGrid/IceGrid.h>
#include <Hello.h>
using namespace std;
using namespace Demo;
class HelloClient : public Ice::Application
{
public:
HelloClient();
virtual int run(int, char*[]);
private:
void menu();
void usage();
};
int
main(int argc, char* argv[])
{
HelloClient app;
return app.main(argc, argv, "config.client");
}
HelloClient::HelloClient() :
//
// Since this is an interactive demo we don't want any signal
// handling.
//
Ice::Application(Ice::NoSignalHandling)
{
}
int
HelloClient::run(int argc, char* argv[])
{
if(argc > 2)
{
usage();
return EXIT_FAILURE;
}
bool addContext = false;
if(argc == 2)
{
if(string(argv[1]) == "--context")
{
addContext = true;
}
else
{
usage();
return EXIT_FAILURE;
}
}
//
// Add the context entry that allows the client to use the locator
//
if(addContext)
{
Ice::LocatorPrx locator = communicator()->getDefaultLocator();
Ice::Context ctx;
ctx["SECRET"] = "LetMeIn";
communicator()->setDefaultLocator(locator->ice_context(ctx));
}
//
// Now we try to connect to the object with the `hello' identity.
//
HelloPrx hello = HelloPrx::checkedCast(communicator()->stringToProxy("hello"));
if(!hello)
{
cerr << argv[0] << ": couldn't find a `hello' object." << endl;
return EXIT_FAILURE;
}
menu();
char c = 'x';
do
{
try
{
cout << "==> ";
cin >> c;
if(c == 't')
{
hello->sayHello();
}
else if(c == 't')
{
hello->sayHello();
}
else if(c == 's')
{
hello->shutdown();
}
else if(c == 'x')
{
// Nothing to do
}
else if(c == '?')
{
menu();
}
else
{
cout << "unknown command `" << c << "'" << endl;
menu();
}
}
catch(const Ice::Exception& ex)
{
cerr << ex << endl;
}
}
while(cin.good() && c != 'x');
return EXIT_SUCCESS;
}
void
HelloClient::menu()
{
cout <<
"usage:\n"
"t: send greeting\n"
"s: shutdown server\n"
"x: exit\n"
"?: help\n";
}
void
HelloClient::usage()
{
cerr << "Usage: " << appName() << " [--context]" << endl;
}
| lejingw/ice-java | cpp/IceGrid/customLocator/Client.cpp | C++ | gpl-2.0 | 2,877 |
<?php
/**
* @package Joomla.Site
* @subpackage mod_menu
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
<<<<<<< HEAD
// Note. It is important to remove spaces between elements.
$class = $item->anchor_css ? ' ' . $item->anchor_css : '';
$title = $item->anchor_title ? ' title="' . $item->anchor_title . '" ' : '';
=======
$title = $item->anchor_title ? ' title="' . $item->anchor_title . '"' : '';
$anchor_css = $item->anchor_css ? $item->anchor_css : '';
$linktype = $item->title;
>>>>>>> joomla/staging
if ($item->menu_image)
{
$linktype = JHtml::_('image', $item->menu_image, $item->title);
if ($item->params->get('menu_text', 1))
{
<<<<<<< HEAD
$item->params->get('menu_text', 1) ?
$linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" /><span class="image-title">' . $item->title . '</span> ' :
$linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" />';
}
else
{
$linktype = $item->title;
}
?>
<span class="separator<?php echo $class;?>"<?php echo $title; ?>>
<?php echo $linktype; ?>
</span>
=======
$linktype .= '<span class="image-title">' . $item->title . '</span>';
}
}
?>
<span class="separator <?php echo $anchor_css; ?>"<?php echo $title; ?>><?php echo $linktype; ?></span>
>>>>>>> joomla/staging
| JoomliC/joomla-cms | modules/mod_menu/tmpl/default_separator.php | PHP | gpl-2.0 | 1,436 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Data;
using System.Windows.Controls.Primitives;
using System.Reflection;
using System.Windows.Threading;
using System.ComponentModel;
using System.Windows.Shapes;
namespace MusicCollectionWPF.Infra
{
public class CustoSlider : Slider
{
private Canvas _Matrix;
private Image _Cursor;
private Popup _autoToolTip;
private TextBlock _TB;
private Line _B;
private DispatcherTimer _Time;
private int _ImobileCount=0;
public event EventHandler<EventArgs> DragStarted;
public event EventHandler<EventArgs> DragCompleted;
public CustoSlider()
: base()
{
NeedTP = false;
_Time = new DispatcherTimer();
_Time.Interval = TimeSpan.FromMilliseconds(200);
_Time.Tick += Tick;
_Time.IsEnabled = false;
}
private void UpdateToolTip(double xp)
{
_TB.Text = AutoToolTipContent.Convert(ConvertToValue(xp), this.Minimum, this.Maximum);
FrameworkElement ch = (this._autoToolTip.Child as FrameworkElement);
bool force = false;
if (ch.ActualWidth==0)
{
_TB.Visibility=Visibility.Hidden;
_autoToolTip.IsOpen = true;
force = true;
}
this._autoToolTip.HorizontalOffset = xp - ch.ActualWidth / 2;
if (force)
{
_autoToolTip.IsOpen = false;
_TB.Visibility = Visibility.Visible;
}
}
private void UpdateToolTip(Point p)
{
UpdateToolTip(p.X);
}
private Point _Current;
private void Tick(object s, EventArgs ea)
{
Point nCurrent = Mouse.GetPosition(_Matrix);
if (nCurrent == _Current)
{
_ImobileCount++;
if (_ImobileCount==3)
OnImmobile(nCurrent);
}
else
{
_ImobileCount = 0;
if (_autoToolTip.IsOpen)
{
UpdateToolTip(nCurrent);
}
}
_Current = nCurrent;
}
private void OnImmobile(Point p)
{
if (!this.NeedTP)
return;
if (this._Trig)
return;
UpdateToolTip(p);
_autoToolTip.IsOpen = true;
}
private void ME(object s, EventArgs ea)
{
_Time.IsEnabled = true;
}
private void ML(object s, MouseEventArgs ea)
{
_Time.IsEnabled = false;
_autoToolTip.IsOpen = false;
}
private double ConvertToValue(double delta)
{
return Math.Min(this.Maximum, Math.Max(this.Minimum, this.Minimum + (delta * (this.Maximum - this.Minimum)) / _Matrix.ActualWidth));
}
private double ConvertToRealValue(double delta)
{
return Math.Min(_Matrix.ActualWidth, Math.Max(0, delta));
}
public double LineThickness
{
get { return (double)GetValue(LineTicknessProperty); }
set { SetValue(LineTicknessProperty, value); }
}
public static readonly DependencyProperty LineTicknessProperty = DependencyProperty.Register(
"LineThickness",
typeof(double),
typeof(CustoSlider),
new FrameworkPropertyMetadata(2D));
public bool FillLineVisible
{
get { return (bool)GetValue(FillLineVisibleProperty); }
set { SetValue(FillLineVisibleProperty, value); }
}
public static readonly DependencyProperty TickLineBrushProperty = DependencyProperty.Register(
"TickLineBrush", typeof(Brush), typeof(CustoSlider));
public Brush TickLineBrush
{
get { return (Brush)GetValue(TickLineBrushProperty); }
set { SetValue(TickLineBrushProperty, value); }
}
public static readonly DependencyProperty FillLineVisibleProperty = DependencyProperty.Register(
"FillLineVisible",
typeof(bool),
typeof(CustoSlider),
new FrameworkPropertyMetadata(false));
public ISliderMultiConverter AutoToolTipContent
{
get { return (ISliderMultiConverter)GetValue(AutoToolTipContentProperty); }
set { SetValue(AutoToolTipContentProperty, value); }
}
public static readonly DependencyProperty AutoToolTipContentProperty = DependencyProperty.Register(
"AutoToolTipContent",
typeof(ISliderMultiConverter),
typeof(CustoSlider),
new FrameworkPropertyMetadata(null, AutoToolTipPropertyChangedCallback));
private static void AutoToolTipPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustoSlider cs = d as CustoSlider;
cs.NeedTP = true;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
try
{
_Matrix = (Canvas)GetTemplateChild("Matrix");
this.MouseDown += Canvas_MouseDown;
_Cursor = (Image)GetTemplateChild("Cursor");
_Cursor.PreviewMouseLeftButtonDown += Image_PreviewMouseDown;
_Cursor.MouseLeftButtonUp += Image_MouseUp;
_Cursor.MouseMove += Image_MouseMove;
_B = (Line)GetTemplateChild("Bar");
_B.MouseEnter += ME;
_B.MouseLeave += ML;
_autoToolTip = GetTemplateChild("AutoToolTip") as Popup;
_TB = (TextBlock)GetTemplateChild("AutoToolTipContentTextBox");
}
catch (Exception)
{
}
}
protected override void OnRender(DrawingContext dc)
{
if (TickPlacement != TickPlacement.None)
{
Size size = new Size(base.ActualWidth, base.ActualHeight);
double MidHeight = size.Height / 2;
double BigCircle = size.Height / 5;
double SmallCircle = (BigCircle * 2) / 3;
dc.DrawEllipse(FillLineVisible? this.TickLineBrush: this.BorderBrush, new Pen(), new Point(10, MidHeight), BigCircle, BigCircle);
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(size.Width + 10, MidHeight), BigCircle, BigCircle);
int tickCount = (int)((this.Maximum - this.Minimum) / this.TickFrequency) -1;
Double tickFrequencySize = (size.Width * this.TickFrequency / (this.Maximum - this.Minimum));
for (int i = 0; i <tickCount; i++)
{
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(10 + (i + 1) * tickFrequencySize, MidHeight),
SmallCircle, SmallCircle);
}
}
base.OnRender(dc);
}
private async void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_Trig)
return;
Point p = Mouse.GetPosition(_Matrix);
_autoToolTip.IsOpen = false;
_Trig = true;
var target = ConvertToValue(p.X);
await this.SmoothSetAsync(ValueProperty, target, TimeSpan.FromSeconds(0.1));
Value = target;
OnThumbDragCompleted(new DragCompletedEventArgs(0, 0, false));
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
_Trig = false;
}
private void Image_MouseMove(object sender, MouseEventArgs e)
{
if (!_Trig)
return;
OnThumbDragDelta(e);
}
private bool _Trig = false;
private void Image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
_Cursor.CaptureMouse();
e.Handled = true;
_Trig = true;
_autoToolTip.IsOpen = false;
OnThumbDragStarted(e);
if (DragStarted != null)
DragStarted(this, new EventArgs());
}
private void Image_MouseUp(object sender, MouseButtonEventArgs e)
{
if (!_Trig)
return;
_Cursor.ReleaseMouseCapture();
e.Handled = true;
_Trig = false;
OnThumbDragCompleted(e);
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
}
private void OnThumbDragStarted(MouseEventArgs e)
{
if (NeedTP)
{
_autoToolTip.IsOpen = true;
UpdateToolTip(e.GetPosition(_Matrix));
}
}
private void OnThumbDragDelta(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
UpdateToolTip(e.GetPosition(_Matrix));
}
}
public bool InDrag
{
get{ return _Trig; }
}
private void OnThumbDragCompleted(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
_autoToolTip.IsOpen = false;
}
}
private bool NeedTP
{
get;
set;
}
protected void OnPropertyChanged(string pn)
{
if (PropertyChanged == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(pn));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| David-Desmaisons/MusicCollection | MusicCollectionWPF/MusicCollectionWPF/Infra/Element/CustoSlider.cs | C# | gpl-2.0 | 10,166 |
#include "stdafx.h"
#include "Emu/SysCalls/SysCalls.h"
#include "Emu/SysCalls/SC_FUNC.h"
#include "Emu/GS/GCM.h"
void cellGcmSys_init();
void cellGcmSys_load();
void cellGcmSys_unload();
Module cellGcmSys(0x0010, cellGcmSys_init, cellGcmSys_load, cellGcmSys_unload);
u32 local_size = 0;
u32 local_addr = 0;
enum
{
CELL_GCM_ERROR_FAILURE = 0x802100ff,
CELL_GCM_ERROR_NO_IO_PAGE_TABLE = 0x80210001,
CELL_GCM_ERROR_INVALID_ENUM = 0x80210002,
CELL_GCM_ERROR_INVALID_VALUE = 0x80210003,
CELL_GCM_ERROR_INVALID_ALIGNMENT = 0x80210004,
CELL_GCM_ERROR_ADDRESS_OVERWRAP = 0x80210005
};
// Function declaration
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id);
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
struct gcm_offset
{
u64 io;
u64 ea;
};
void InitOffsetTable();
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset);
uint32_t cellGcmGetMaxIoMapSize();
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table);
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address);
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size);
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags);
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset);
int32_t cellGcmReserveIoMapSize(const u32 size);
int32_t cellGcmUnmapEaIoAddress(u64 ea);
int32_t cellGcmUnmapIoAddress(u64 io);
int32_t cellGcmUnreserveIoMapSize(u32 size);
//----------------------------------------------------------------------------
CellGcmConfig current_config;
CellGcmContextData current_context;
gcmInfo gcm_info;
u32 map_offset_addr = 0;
u32 map_offset_pos = 0;
//----------------------------------------------------------------------------
// Data Retrieval
//----------------------------------------------------------------------------
u32 cellGcmGetLabelAddress(u8 index)
{
cellGcmSys.Log("cellGcmGetLabelAddress(index=%d)", index);
return Memory.RSXCMDMem.GetStartAddr() + 0x10 * index;
}
u32 cellGcmGetReportDataAddressLocation(u8 location, u32 index)
{
ConLog.Warning("cellGcmGetReportDataAddressLocation(location=%d, index=%d)", location, index);
return Emu.GetGSManager().GetRender().m_report_main_addr;
}
u64 cellGcmGetTimeStamp(u32 index)
{
cellGcmSys.Log("cellGcmGetTimeStamp(index=%d)", index);
return Memory.Read64(Memory.RSXFBMem.GetStartAddr() + index * 0x10);
}
//----------------------------------------------------------------------------
// Command Buffer Control
//----------------------------------------------------------------------------
u32 cellGcmGetControlRegister()
{
cellGcmSys.Log("cellGcmGetControlRegister()");
return gcm_info.control_addr;
}
u32 cellGcmGetDefaultCommandWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultCommandWordSize()");
return 0x400;
}
u32 cellGcmGetDefaultSegmentWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultSegmentWordSize()");
return 0x100;
}
int cellGcmInitDefaultFifoMode(s32 mode)
{
cellGcmSys.Warning("cellGcmInitDefaultFifoMode(mode=%d)", mode);
return CELL_OK;
}
int cellGcmSetDefaultFifoSize(u32 bufferSize, u32 segmentSize)
{
cellGcmSys.Warning("cellGcmSetDefaultFifoSize(bufferSize=0x%x, segmentSize=0x%x)", bufferSize, segmentSize);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Hardware Resource Management
//----------------------------------------------------------------------------
int cellGcmBindTile(u8 index)
{
cellGcmSys.Warning("cellGcmBindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = true;
return CELL_OK;
}
int cellGcmBindZcull(u8 index)
{
cellGcmSys.Warning("TODO: cellGcmBindZcull(index=%d)", index);
return CELL_OK;
}
int cellGcmGetConfiguration(mem_ptr_t<CellGcmConfig> config)
{
cellGcmSys.Log("cellGcmGetConfiguration(config_addr=0x%x)", config.GetAddr());
if (!config.IsGood()) return CELL_EFAULT;
*config = current_config;
return CELL_OK;
}
int cellGcmGetFlipStatus()
{
return Emu.GetGSManager().GetRender().m_flip_status;
}
u32 cellGcmGetTiledPitchSize(u32 size)
{
//TODO
cellGcmSys.Warning("cellGcmGetTiledPitchSize(size=%d)", size);
return size;
}
int cellGcmInit(u32 context_addr, u32 cmdSize, u32 ioSize, u32 ioAddress)
{
cellGcmSys.Warning("cellGcmInit(context_addr=0x%x,cmdSize=0x%x,ioSize=0x%x,ioAddress=0x%x)", context_addr, cmdSize, ioSize, ioAddress);
if(!cellGcmSys.IsLoaded())
cellGcmSys.Load();
if(!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
}
cellGcmSys.Warning("*** local memory(addr=0x%x, size=0x%x)", local_addr, local_size);
InitOffsetTable();
Memory.MemoryBlocks.push_back(Memory.RSXIOMem.SetRange(0x50000000, 0x10000000/*256MB*/));//TODO: implement allocateAdressSpace in memoryBase
if(cellGcmMapEaIoAddress(ioAddress, 0, ioSize) != CELL_OK)
{
Memory.MemoryBlocks.pop_back();
return CELL_GCM_ERROR_FAILURE;
}
map_offset_addr = 0;
map_offset_pos = 0;
current_config.ioSize = ioSize;
current_config.ioAddress = ioAddress;
current_config.localSize = local_size;
current_config.localAddress = local_addr;
current_config.memoryFrequency = 650000000;
current_config.coreFrequency = 500000000;
Memory.RSXCMDMem.AllocAlign(cmdSize);
u32 ctx_begin = ioAddress/* + 0x1000*/;
u32 ctx_size = 0x6ffc;
current_context.begin = ctx_begin;
current_context.end = ctx_begin + ctx_size;
current_context.current = current_context.begin;
current_context.callback = Emu.GetRSXCallback() - 4;
gcm_info.context_addr = Memory.MainMem.AllocAlign(0x1000);
gcm_info.control_addr = gcm_info.context_addr + 0x40;
Memory.WriteData(gcm_info.context_addr, current_context);
Memory.Write32(context_addr, gcm_info.context_addr);
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put = 0;
ctrl.get = 0;
ctrl.ref = -1;
auto& render = Emu.GetGSManager().GetRender();
render.m_ctxt_addr = context_addr;
render.m_gcm_buffers_addr = Memory.Alloc(sizeof(gcmBuffer) * 8, sizeof(gcmBuffer));
render.m_zculls_addr = Memory.Alloc(sizeof(CellGcmZcullInfo) * 8, sizeof(CellGcmZcullInfo));
render.m_tiles_addr = Memory.Alloc(sizeof(CellGcmTileInfo) * 15, sizeof(CellGcmTileInfo));
render.m_gcm_buffers_count = 0;
render.m_gcm_current_buffer = 0;
render.m_main_mem_addr = 0;
render.Init(ctx_begin, ctx_size, gcm_info.control_addr, local_addr);
return CELL_OK;
}
int cellGcmResetFlipStatus()
{
Emu.GetGSManager().GetRender().m_flip_status = 1;
return CELL_OK;
}
int cellGcmSetDebugOutputLevel(int level)
{
cellGcmSys.Warning("cellGcmSetDebugOutputLevel(level=%d)", level);
switch (level)
{
case CELL_GCM_DEBUG_LEVEL0:
case CELL_GCM_DEBUG_LEVEL1:
case CELL_GCM_DEBUG_LEVEL2:
Emu.GetGSManager().GetRender().m_debug_level = level;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetDisplayBuffer(u32 id, u32 offset, u32 pitch, u32 width, u32 height)
{
cellGcmSys.Warning("cellGcmSetDisplayBuffer(id=0x%x,offset=0x%x,pitch=%d,width=%d,height=%d)",
id, offset, width ? pitch/width : pitch, width, height);
if(id > 7) return CELL_EINVAL;
gcmBuffer* buffers = (gcmBuffer*)Memory.GetMemFromAddr(Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
buffers[id].offset = re(offset);
buffers[id].pitch = re(pitch);
buffers[id].width = re(width);
buffers[id].height = re(height);
if(id + 1 > Emu.GetGSManager().GetRender().m_gcm_buffers_count)
{
Emu.GetGSManager().GetRender().m_gcm_buffers_count = id + 1;
}
return CELL_OK;
}
int cellGcmSetFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
int res = cellGcmSetPrepareFlip(ctxt, id);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetFlipHandler(u32 handler_addr)
{
cellGcmSys.Warning("cellGcmSetFlipHandler(handler_addr=%d)", handler_addr);
if (handler_addr != 0 && !Memory.IsGoodAddr(handler_addr))
{
return CELL_EFAULT;
}
Emu.GetGSManager().GetRender().m_flip_handler.SetAddr(handler_addr);
return CELL_OK;
}
int cellGcmSetFlipMode(u32 mode)
{
cellGcmSys.Warning("cellGcmSetFlipMode(mode=%d)", mode);
switch (mode)
{
case CELL_GCM_DISPLAY_HSYNC:
case CELL_GCM_DISPLAY_VSYNC:
case CELL_GCM_DISPLAY_HSYNC_WITH_NOISE:
Emu.GetGSManager().GetRender().m_flip_mode = mode;
break;
default:
return CELL_EINVAL;
}
return CELL_OK;
}
void cellGcmSetFlipStatus()
{
cellGcmSys.Warning("cellGcmSetFlipStatus()");
Emu.GetGSManager().GetRender().m_flip_status = 0;
}
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetPrepareFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
if(id >= 8)
{
return CELL_GCM_ERROR_FAILURE;
}
GSLockCurrent gslock(GS_LOCK_WAIT_FLUSH); // could stall on exit
u32 current = ctxt->current;
u32 end = ctxt->end;
if(current + 8 >= end)
{
ConLog.Warning("bad flip!");
//cellGcmCallback(ctxt.GetAddr(), current + 8 - end);
//copied:
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
const s32 res = ctxt->current - ctxt->begin - ctrl.put;
if(res > 0) Memory.Copy(ctxt->begin, ctxt->current - res, res);
ctxt->current = ctxt->begin + res;
ctrl.put = res;
ctrl.get = 0;
}
current = ctxt->current;
Memory.Write32(current, 0x3fead | (1 << 18));
Memory.Write32(current + 4, id);
ctxt->current += 8;
if(ctxt.GetAddr() == gcm_info.context_addr)
{
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put += 8;
}
return id;
}
int cellGcmSetSecondVFrequency(u32 freq)
{
cellGcmSys.Warning("cellGcmSetSecondVFrequency(level=%d)", freq);
switch (freq)
{
case CELL_GCM_DISPLAY_FREQUENCY_59_94HZ:
case CELL_GCM_DISPLAY_FREQUENCY_SCANOUT:
case CELL_GCM_DISPLAY_FREQUENCY_DISABLE:
Emu.GetGSManager().GetRender().m_frequency_mode = freq;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetTileInfo(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTileInfo(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
if (index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
if (offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if (location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if (comp)
{
cellGcmSys.Error("cellGcmSetTileInfo: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo)* index, tile.Pack());
return CELL_OK;
}
u32 cellGcmSetUserHandler(u32 handler)
{
cellGcmSys.Warning("cellGcmSetUserHandler(handler=0x%x)", handler);
return handler;
}
int cellGcmSetVBlankHandler()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetWaitFlip(mem_ptr_t<CellGcmContextData> ctxt)
{
cellGcmSys.Log("cellGcmSetWaitFlip(ctx=0x%x)", ctxt.GetAddr());
GSLockCurrent lock(GS_LOCK_WAIT_FLIP);
return CELL_OK;
}
int cellGcmSetZcull(u8 index, u32 offset, u32 width, u32 height, u32 cullStart, u32 zFormat, u32 aaFormat, u32 zCullDir, u32 zCullFormat, u32 sFunc, u32 sRef, u32 sMask)
{
cellGcmSys.Warning("TODO: cellGcmSetZcull(index=%d, offset=0x%x, width=%d, height=%d, cullStart=0x%x, zFormat=0x%x, aaFormat=0x%x, zCullDir=0x%x, zCullFormat=0x%x, sFunc=0x%x, sRef=0x%x, sMask=0x%x)",
index, offset, width, height, cullStart, zFormat, aaFormat, zCullDir, zCullFormat, sFunc, sRef, sMask);
return CELL_OK;
}
int cellGcmUnbindTile(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = false;
return CELL_OK;
}
int cellGcmUnbindZcull(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindZcull(index=%d)", index);
if (index >= 8)
return CELL_EINVAL;
return CELL_OK;
}
u32 cellGcmGetTileInfo()
{
cellGcmSys.Warning("cellGcmGetTileInfo()");
return Emu.GetGSManager().GetRender().m_tiles_addr;
}
u32 cellGcmGetZcullInfo()
{
cellGcmSys.Warning("cellGcmGetZcullInfo()");
return Emu.GetGSManager().GetRender().m_zculls_addr;
}
u32 cellGcmGetDisplayInfo()
{
cellGcmSys.Warning("cellGcmGetDisplayInfo() = 0x%x", Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
return Emu.GetGSManager().GetRender().m_gcm_buffers_addr;
}
int cellGcmGetCurrentDisplayBufferId(u32 id_addr)
{
cellGcmSys.Warning("cellGcmGetCurrentDisplayBufferId(id_addr=0x%x)", id_addr);
if (!Memory.IsGoodAddr(id_addr))
{
return CELL_EFAULT;
}
Memory.Write32(id_addr, Emu.GetGSManager().GetRender().m_gcm_current_buffer);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
gcm_offset offsetTable = { 0, 0 };
void InitOffsetTable()
{
offsetTable.io = Memory.Alloc(3072 * sizeof(u16), 1);
for (int i = 0; i<3072; i++)
{
Memory.Write16(offsetTable.io + sizeof(u16)*i, 0xFFFF);
}
offsetTable.ea = Memory.Alloc(256 * sizeof(u16), 1);//TODO: check flags
for (int i = 0; i<256; i++)
{
Memory.Write16(offsetTable.ea + sizeof(u16)*i, 0xFFFF);
}
}
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset)
{
cellGcmSys.Log("cellGcmAddressToOffset(address=0x%x,offset_addr=0x%x)", address, offset.GetAddr());
if (address >= 0xD0000000/*not on main memory or local*/)
return CELL_GCM_ERROR_FAILURE;
u32 result;
// If address is in range of local memory
if (Memory.RSXFBMem.IsInMyRange(address))
{
result = address - Memory.RSXFBMem.GetStartAddr();
}
// else check if the adress (main memory) is mapped in IO
else
{
u16 upper12Bits = Memory.Read16(offsetTable.io + sizeof(u16)*(address >> 20));
if (upper12Bits != 0xFFFF)
{
result = (((u64)upper12Bits << 20) | (address & (0xFFFFF)));
}
// address is not mapped in IO
else
{
return CELL_GCM_ERROR_FAILURE;
}
}
offset = result;
return CELL_OK;
}
uint32_t cellGcmGetMaxIoMapSize()
{
return Memory.RSXIOMem.GetEndAddr() - Memory.RSXIOMem.GetStartAddr() - Memory.RSXIOMem.GetReservedAmount();
}
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table)
{
table->io = re(offsetTable.io);
table->ea = re(offsetTable.ea);
}
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address)
{
u64 realAddr;
realAddr = Memory.RSXIOMem.getRealAddr(Memory.RSXIOMem.GetStartAddr() + ioOffset);
if (!realAddr)
return CELL_GCM_ERROR_FAILURE;
Memory.Write64(address, realAddr);
return CELL_OK;
}
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size)
{
cellGcmSys.Warning("cellGcmMapEaIoAddress(ea=0x%x, io=0x%x, size=0x%x)", ea, io, size);
if ((ea & 0xFFFFF) || (io & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (Memory.RSXIOMem.Map(ea, size, Memory.RSXIOMem.GetStartAddr() + io))
{
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags)
{
cellGcmSys.Warning("cellGcmMapEaIoAddressWithFlags(ea=0x%x, io=0x%x, size=0x%x, flags=0x%x)", ea, io, size, flags);
return cellGcmMapEaIoAddress(ea, io, size); // TODO: strict ordering
}
int32_t cellGcmMapLocalMemory(u64 address, u64 size)
{
if (!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
Memory.Write32(address, local_addr);
Memory.Write32(size, local_size);
}
else
{
cellGcmSys.Error("RSX local memory already mapped");
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset)
{
cellGcmSys.Warning("cellGcmMapMainMemory(ea=0x%x,size=0x%x,offset_addr=0x%x)", ea, size, offset.GetAddr());
u64 io;
if ((ea & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (io = Memory.RSXIOMem.Map(ea, size, 0))
{
// convert to offset
io = io - Memory.RSXIOMem.GetStartAddr();
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
offset = io;
}
else
{
return CELL_GCM_ERROR_NO_IO_PAGE_TABLE;
}
Emu.GetGSManager().GetRender().m_main_mem_addr = Emu.GetGSManager().GetRender().m_ioAddress;
return CELL_OK;
}
int32_t cellGcmReserveIoMapSize(const u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > cellGcmGetMaxIoMapSize())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Reserve(size);
return CELL_OK;
}
int32_t cellGcmUnmapEaIoAddress(u64 ea)
{
u32 size = Memory.RSXIOMem.UnmapRealAddress(ea);
if (size)
{
u64 io;
ea = ea >> 20;
io = Memory.Read16(offsetTable.io + (ea*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnmapIoAddress(u64 io)
{
u32 size = Memory.RSXIOMem.UnmapAddress(io);
if (size)
{
u64 ea;
io = io >> 20;
ea = Memory.Read16(offsetTable.ea + (io*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnreserveIoMapSize(u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > Memory.RSXIOMem.GetReservedAmount())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Unreserve(size);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Cursor
//----------------------------------------------------------------------------
int cellGcmInitCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorPosition(s32 x, s32 y)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorDisable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmUpdateCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorEnable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorImageOffset(u32 offset)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
//------------------------------------------------------------------------
// Functions for Maintaining Compatibility
//------------------------------------------------------------------------
void cellGcmSetDefaultCommandBuffer()
{
cellGcmSys.Warning("cellGcmSetDefaultCommandBuffer()");
Memory.Write32(Emu.GetGSManager().GetRender().m_ctxt_addr, gcm_info.context_addr);
}
//------------------------------------------------------------------------
// Other
//------------------------------------------------------------------------
int cellGcmSetFlipCommand(u32 ctx, u32 id)
{
return cellGcmSetPrepareFlip(ctx, id);
}
s64 cellGcmFunc15()
{
cellGcmSys.Error("cellGcmFunc15()");
return 0;
}
int cellGcmSetFlipCommandWithWaitLabel(u32 ctx, u32 id, u32 label_index, u32 label_value)
{
int res = cellGcmSetPrepareFlip(ctx, id);
Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + 0x10 * label_index, label_value);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetTile(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTile(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
// Copied form cellGcmSetTileInfo
if(index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
if(offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if(location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if(comp)
{
cellGcmSys.Error("cellGcmSetTile: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo) * index, tile.Pack());
return CELL_OK;
}
//----------------------------------------------------------------------------
void cellGcmSys_init()
{
// Data Retrieval
//cellGcmSys.AddFunc(0xc8f3bd09, cellGcmGetCurrentField);
cellGcmSys.AddFunc(0xf80196c1, cellGcmGetLabelAddress);
//cellGcmSys.AddFunc(0x21cee035, cellGcmGetNotifyDataAddress);
//cellGcmSys.AddFunc(0x99d397ac, cellGcmGetReport);
//cellGcmSys.AddFunc(0x9a0159af, cellGcmGetReportDataAddress);
cellGcmSys.AddFunc(0x8572bce2, cellGcmGetReportDataAddressLocation);
//cellGcmSys.AddFunc(0xa6b180ac, cellGcmGetReportDataLocation);
cellGcmSys.AddFunc(0x5a41c10f, cellGcmGetTimeStamp);
//cellGcmSys.AddFunc(0x2ad4951b, cellGcmGetTimeStampLocation);
// Command Buffer Control
//cellGcmSys.AddFunc(, cellGcmCallbackForSnc);
//cellGcmSys.AddFunc(, cellGcmFinish);
//cellGcmSys.AddFunc(, cellGcmFlush);
cellGcmSys.AddFunc(0xa547adde, cellGcmGetControlRegister);
cellGcmSys.AddFunc(0x5e2ee0f0, cellGcmGetDefaultCommandWordSize);
cellGcmSys.AddFunc(0x8cdf8c70, cellGcmGetDefaultSegmentWordSize);
cellGcmSys.AddFunc(0xcaabd992, cellGcmInitDefaultFifoMode);
//cellGcmSys.AddFunc(, cellGcmReserveMethodSize);
//cellGcmSys.AddFunc(, cellGcmResetDefaultCommandBuffer);
cellGcmSys.AddFunc(0x9ba451e4, cellGcmSetDefaultFifoSize);
//cellGcmSys.AddFunc(, cellGcmSetupContextData);
// Hardware Resource Management
cellGcmSys.AddFunc(0x4524cccd, cellGcmBindTile);
cellGcmSys.AddFunc(0x9dc04436, cellGcmBindZcull);
//cellGcmSys.AddFunc(0x1f61b3ff, cellGcmDumpGraphicsError);
cellGcmSys.AddFunc(0xe315a0b2, cellGcmGetConfiguration);
//cellGcmSys.AddFunc(0x371674cf, cellGcmGetDisplayBufferByFlipIndex);
cellGcmSys.AddFunc(0x72a577ce, cellGcmGetFlipStatus);
//cellGcmSys.AddFunc(0x63387071, cellGcmgetLastFlipTime);
//cellGcmSys.AddFunc(0x23ae55a3, cellGcmGetLastSecondVTime);
cellGcmSys.AddFunc(0x055bd74d, cellGcmGetTiledPitchSize);
//cellGcmSys.AddFunc(0x723bbc7e, cellGcmGetVBlankCount);
cellGcmSys.AddFunc(0x15bae46b, cellGcmInit);
//cellGcmSys.AddFunc(0xfce9e764, cellGcmInitSystemMode);
cellGcmSys.AddFunc(0xb2e761d4, cellGcmResetFlipStatus);
cellGcmSys.AddFunc(0x51c9d62b, cellGcmSetDebugOutputLevel);
cellGcmSys.AddFunc(0xa53d12ae, cellGcmSetDisplayBuffer);
cellGcmSys.AddFunc(0xdc09357e, cellGcmSetFlip);
cellGcmSys.AddFunc(0xa41ef7e8, cellGcmSetFlipHandler);
//cellGcmSys.AddFunc(0xacee8542, cellGcmSetFlipImmediate);
cellGcmSys.AddFunc(0x4ae8d215, cellGcmSetFlipMode);
cellGcmSys.AddFunc(0xa47c09ff, cellGcmSetFlipStatus);
//cellGcmSys.AddFunc(, cellGcmSetFlipWithWaitLabel);
//cellGcmSys.AddFunc(0xd01b570d, cellGcmSetGraphicsHandler);
cellGcmSys.AddFunc(0x0b4b62d5, cellGcmSetPrepareFlip);
//cellGcmSys.AddFunc(0x0a862772, cellGcmSetQueueHandler);
cellGcmSys.AddFunc(0x4d7ce993, cellGcmSetSecondVFrequency);
//cellGcmSys.AddFunc(0xdc494430, cellGcmSetSecondVHandler);
cellGcmSys.AddFunc(0xbd100dbc, cellGcmSetTileInfo);
cellGcmSys.AddFunc(0x06edea9e, cellGcmSetUserHandler);
//cellGcmSys.AddFunc(0xffe0160e, cellGcmSetVBlankFrequency);
cellGcmSys.AddFunc(0xa91b0402, cellGcmSetVBlankHandler);
cellGcmSys.AddFunc(0x983fb9aa, cellGcmSetWaitFlip);
cellGcmSys.AddFunc(0xd34a420d, cellGcmSetZcull);
//cellGcmSys.AddFunc(0x25b40ab4, cellGcmSortRemapEaIoAddress);
cellGcmSys.AddFunc(0xd9b7653e, cellGcmUnbindTile);
cellGcmSys.AddFunc(0xa75640e8, cellGcmUnbindZcull);
cellGcmSys.AddFunc(0x657571f7, cellGcmGetTileInfo);
cellGcmSys.AddFunc(0xd9a0a879, cellGcmGetZcullInfo);
cellGcmSys.AddFunc(0x0e6b0dae, cellGcmGetDisplayInfo);
cellGcmSys.AddFunc(0x93806525, cellGcmGetCurrentDisplayBufferId);
// Memory Mapping
cellGcmSys.AddFunc(0x21ac3697, cellGcmAddressToOffset);
cellGcmSys.AddFunc(0xfb81c03e, cellGcmGetMaxIoMapSize);
cellGcmSys.AddFunc(0x2922aed0, cellGcmGetOffsetTable);
cellGcmSys.AddFunc(0x2a6fba9c, cellGcmIoOffsetToAddress);
cellGcmSys.AddFunc(0x63441cb4, cellGcmMapEaIoAddress);
cellGcmSys.AddFunc(0x626e8518, cellGcmMapEaIoAddressWithFlags);
cellGcmSys.AddFunc(0xdb769b32, cellGcmMapLocalMemory);
cellGcmSys.AddFunc(0xa114ec67, cellGcmMapMainMemory);
cellGcmSys.AddFunc(0xa7ede268, cellGcmReserveIoMapSize);
cellGcmSys.AddFunc(0xefd00f54, cellGcmUnmapEaIoAddress);
cellGcmSys.AddFunc(0xdb23e867, cellGcmUnmapIoAddress);
cellGcmSys.AddFunc(0x3b9bd5bd, cellGcmUnreserveIoMapSize);
// Cursor
cellGcmSys.AddFunc(0x107bf3a1, cellGcmInitCursor);
cellGcmSys.AddFunc(0xc47d0812, cellGcmSetCursorEnable);
cellGcmSys.AddFunc(0x69c6cc82, cellGcmSetCursorDisable);
cellGcmSys.AddFunc(0xf9bfdc72, cellGcmSetCursorImageOffset);
cellGcmSys.AddFunc(0x1a0de550, cellGcmSetCursorPosition);
cellGcmSys.AddFunc(0xbd2fa0a7, cellGcmUpdateCursor);
// Functions for Maintaining Compatibility
//cellGcmSys.AddFunc(, cellGcmGetCurrentBuffer);
//cellGcmSys.AddFunc(, cellGcmSetCurrentBuffer);
cellGcmSys.AddFunc(0xbc982946, cellGcmSetDefaultCommandBuffer);
//cellGcmSys.AddFunc(, cellGcmSetDefaultCommandBufferAndSegmentWordSize);
//cellGcmSys.AddFunc(, cellGcmSetUserCallback);
// Other
cellGcmSys.AddFunc(0x21397818, cellGcmSetFlipCommand);
cellGcmSys.AddFunc(0x3a33c1fd, cellGcmFunc15);
cellGcmSys.AddFunc(0xd8f88e1a, cellGcmSetFlipCommandWithWaitLabel);
cellGcmSys.AddFunc(0xd0b1d189, cellGcmSetTile);
}
void cellGcmSys_load()
{
current_config.ioAddress = 0;
current_config.localAddress = 0;
local_size = 0;
local_addr = 0;
}
void cellGcmSys_unload()
{
}
| unknownbrackets/rpcs3 | rpcs3/Emu/SysCalls/Modules/cellGcmSys.cpp | C++ | gpl-2.0 | 26,937 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2021 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI 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.
*
* GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
use Glpi\Toolbox\VersionParser;
/**
* Update class
**/
class Update {
private $args = [];
private $DB;
private $migration;
private $version;
private $dbversion;
private $language;
/**
* Constructor
*
* @param object $DB Database instance
* @param array $args Command line arguments; default to empty array
*/
public function __construct($DB, $args = []) {
$this->DB = $DB;
$this->args = $args;
}
/**
* Initialize session for update
*
* @return void
*/
public function initSession() {
if (is_writable(GLPI_SESSION_DIR)) {
Session::setPath();
} else {
if (isCommandLine()) {
die("Can't write in ".GLPI_SESSION_DIR."\n");
}
}
Session::start();
if (isCommandLine()) {
// Init debug variable
$_SESSION = ['glpilanguage' => (isset($this->args['lang']) ? $this->args['lang'] : 'en_GB')];
$_SESSION["glpi_currenttime"] = date("Y-m-d H:i:s");
}
// Init debug variable
// Only show errors
Toolbox::setDebugMode(Session::DEBUG_MODE, 0, 0, 1);
}
/**
* Get current values (versions, lang, ...)
*
* @return array
*/
public function getCurrents() {
$currents = [];
$DB = $this->DB;
if (!$DB->tableExists('glpi_config') && !$DB->tableExists('glpi_configs')) {
//very, very old version!
$currents = [
'version' => '0.1',
'dbversion' => '0.1',
'language' => 'en_GB'
];
} else if (!$DB->tableExists("glpi_configs")) {
// < 0.78
// Get current version
$result = $DB->request([
'SELECT' => ['version', 'language'],
'FROM' => 'glpi_config'
])->current();
$currents['version'] = trim($result['version']);
$currents['dbversion'] = $currents['version'];
$currents['language'] = trim($result['language']);
} else if ($DB->fieldExists('glpi_configs', 'version')) {
// < 0.85
// Get current version and language
$result = $DB->request([
'SELECT' => ['version', 'language'],
'FROM' => 'glpi_configs'
])->current();
$currents['version'] = trim($result['version']);
$currents['dbversion'] = $currents['version'];
$currents['language'] = trim($result['language']);
} else {
$currents = Config::getConfigurationValues(
'core',
['version', 'dbversion', 'language']
);
if (!isset($currents['dbversion'])) {
$currents['dbversion'] = $currents['version'];
}
}
$this->version = $currents['version'];
$this->dbversion = $currents['dbversion'];
$this->language = $currents['language'];
return $currents;
}
/**
* Run updates
*
* @param string $current_version Current version
* @param bool $force_latest Force replay of latest migration
*
* @return void
*/
public function doUpdates($current_version = null, bool $force_latest = false) {
if ($current_version === null) {
if ($this->version === null) {
throw new \RuntimeException('Cannot process updates without any version specified!');
}
$current_version = $this->version;
}
$DB = $this->DB;
// To prevent problem of execution time
ini_set("max_execution_time", "0");
if (version_compare($current_version, '0.80', 'lt')) {
die('Upgrade is not supported before 0.80!');
die(1);
}
// Update process desactivate all plugins
$plugin = new Plugin();
$plugin->unactivateAll();
if (version_compare($current_version, '0.80', '<') || version_compare($current_version, GLPI_VERSION, '>')) {
$message = sprintf(
__('Unsupported version (%1$s)'),
$current_version
);
if (isCommandLine()) {
echo "$message\n";
die(1);
} else {
$this->migration->displayWarning($message, true);
die(1);
}
}
$migrations = $this->getMigrationsToDo($current_version, $force_latest);
foreach ($migrations as $file => $function) {
include_once($file);
$function();
}
if (($myisam_count = $DB->getMyIsamTables()->count()) > 0) {
$message = sprintf(__('%d tables are using the deprecated MyISAM storage engine.'), $myisam_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:myisam_to_innodb');
$this->migration->displayError($message);
}
if (($datetime_count = $DB->getTzIncompatibleTables()->count()) > 0) {
$message = sprintf(__('%1$s columns are using the deprecated datetime storage field type.'), $datetime_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:timestamps');
$this->migration->displayError($message);
}
/*
* FIXME: Remove `$DB->use_utf8mb4` condition GLPI 10.1.
* This condition is here only to prevent having this message on every migration GLPI 10.0.
* Indeed, as migration command was not available in previous versions, users may not understand
* why this is considered as an error.
*/
if ($DB->use_utf8mb4 && ($non_utf8mb4_count = $DB->getNonUtf8mb4Tables()->count()) > 0) {
$message = sprintf(__('%1$s tables are using the deprecated utf8mb3 storage charset.'), $non_utf8mb4_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:utf8mb4');
$this->migration->displayError($message);
}
// Update version number and default langage and new version_founded ---- LEAVE AT THE END
Config::setConfigurationValues('core', ['version' => GLPI_VERSION,
'dbversion' => GLPI_SCHEMA_VERSION,
'language' => $this->language,
'founded_new_version' => '']);
if (defined('GLPI_SYSTEM_CRON')) {
// Downstream packages may provide a good system cron
$DB->updateOrDie(
'glpi_crontasks', [
'mode' => 2
], [
'name' => ['!=', 'watcher'],
'allowmode' => ['&', 2]
]
);
}
// Reset telemetry if its state is running, assuming it remained stuck due to telemetry service issue (see #7492).
$crontask_telemetry = new CronTask();
$crontask_telemetry->getFromDBbyName("Telemetry", "telemetry");
if ($crontask_telemetry->fields['state'] === CronTask::STATE_RUNNING) {
$crontask_telemetry->resetDate();
$crontask_telemetry->resetState();
}
//generate security key if missing, and update db
$glpikey = new GLPIKey();
if (!$glpikey->keyExists() && !$glpikey->generate()) {
$this->migration->displayWarning(__('Unable to create security key file! You have to run "php bin/console glpi:security:change_key" command to manually create this file.'), true);
}
}
/**
* Set migration
*
* @param Migration $migration Migration instance
*
* @return Update
*/
public function setMigration(Migration $migration) {
$this->migration = $migration;
return $this;
}
/**
* Check if expected security key file is missing.
*
* @return bool
*/
public function isExpectedSecurityKeyFileMissing(): bool {
$expected_key_path = $this->getExpectedSecurityKeyFilePath();
if ($expected_key_path === null) {
return false;
}
return !file_exists($expected_key_path);
}
/**
* Returns expected security key file path.
* Will return null for GLPI versions that was not yet handling a custom security key.
*
* @return string|null
*/
public function getExpectedSecurityKeyFilePath(): ?string {
$glpikey = new GLPIKey();
return $glpikey->getExpectedKeyPath($this->getCurrents()['version']);
}
/**
* Get migrations that have to be ran.
*
* @param string $current_version
* @param bool $force_latest
*
* @return array
*/
public function getMigrationsToDo(string $current_version, bool $force_latest = false): array {
$migrations = [];
$current_version = VersionParser::getNormalizedVersion($current_version);
$pattern = '/^update_(?<source_version>\d+\.\d+\.(?:\d+|x))_to_(?<target_version>\d+\.\d+\.(?:\d+|x))\.php$/';
$migration_iterator = new DirectoryIterator(GLPI_ROOT . '/install/migrations/');
foreach ($migration_iterator as $file) {
$versions_matches = [];
if ($file->isDir() || $file->isDot() || preg_match($pattern, $file->getFilename(), $versions_matches) !== 1) {
continue;
}
$force_migration = false;
if ($current_version === '9.2.2' && $versions_matches['target_version'] === '9.2.2') {
//9.2.2 upgrade script was not run from the release, see https://github.com/glpi-project/glpi/issues/3659
$force_migration = true;
} else if ($force_latest && version_compare($versions_matches['target_version'], $current_version, '=')) {
$force_migration = true;
}
if (version_compare($versions_matches['target_version'], $current_version, '>') || $force_migration) {
$migrations[$file->getRealPath()] = preg_replace(
'/^update_(\d+)\.(\d+)\.(\d+|x)_to_(\d+)\.(\d+)\.(\d+|x)\.php$/',
'update$1$2$3to$4$5$6',
$file->getBasename()
);
}
}
ksort($migrations);
return $migrations;
}
}
| trasher/glpi | inc/update.class.php | PHP | gpl-2.0 | 11,319 |
#!/usr/bin/env rspec
require_relative "../../../test_helper"
require "yaml"
require "users/clients/auto"
require "y2users/autoinst/reader"
require "y2issues"
Yast.import "Report"
# defines exported users
require_relative "../../../fixtures/users_export"
describe Y2Users::Clients::Auto do
let(:mode) { "autoinstallation" }
let(:args) { [func] }
before do
allow(Yast).to receive(:import).and_call_original
allow(Yast).to receive(:import).with("Ldap")
allow(Yast).to receive(:import).with("LdapPopup")
allow(Yast::Mode).to receive(:mode).and_return(mode)
allow(Yast::Stage).to receive(:initial).and_return(true)
allow(Yast::WFM).to receive(:Args).and_return(args)
end
describe "#run" do
context "Import" do
let(:func) { "Import" }
let(:args) { [func, users] }
context "when double users have been given in the profile" do
let(:mode) { "normal" }
let(:users) { YAML.load_file(FIXTURES_PATH.join("users_error.yml")) }
it "report error" do
allow(Yast::Stage).to receive(:initial).and_return(false)
expect(Yast::Report).to receive(:Error)
.with(_("Found users in profile with equal <username>."))
expect(Yast::Report).to receive(:Error)
.with(_("Found users in profile with equal <uid>."))
expect(subject.run).to eq(true)
end
end
context "when users without any UID are defined in the profile" do
let(:users) { YAML.load_file(FIXTURES_PATH.join("users_no_error.yml")) }
it "will not be checked for double UIDs" do
expect(Yast::Report).not_to receive(:Error)
.with(_("Found users in profile with equal <username>."))
expect(Yast::Report).not_to receive(:Error)
.with(_("Found users in profile with equal <uid>."))
expect(subject.run).to eq(true)
end
end
context "when root password linuxrc attribute is set" do
before do
allow(Yast::Linuxrc).to receive(:InstallInf).with("RootPassword").and_return("test")
end
context "when profile contain root password" do
let(:users) { USERS_EXPORT }
it "keeps root password from profile" do
allow(Y2Issues).to receive(:report).and_return(true) # fixture contain dup uids
expect(subject.run).to eq(true)
config = Y2Users::ConfigManager.instance.target
root_user = config.users.root
expect(root_user.password.value.encrypted?).to eq true
expect(root_user.password.value.content).to match(/^\$6\$AS/)
end
end
context "when profile does not contain root password" do
let(:users) { {} }
it "sets root password to linuxrc value" do
expect(subject.run).to eq(true)
config = Y2Users::ConfigManager.instance.target
root_user = config.users.root
expect(root_user.password.value.encrypted?).to eq false
expect(root_user.password.value.content).to eq "test"
end
end
end
context "when some issue is registered" do
let(:users) { { "users" => [] } }
let(:reader) { Y2Users::Autoinst::Reader.new(users) }
let(:issues) { Y2Issues::List.new }
let(:continue?) { true }
let(:result) do
Y2Users::ReadResult.new(Y2Users::Config.new, issues)
end
before do
allow(Y2Users::Autoinst::Reader).to receive(:new).and_return(reader)
allow(reader).to receive(:read).and_return(result)
issues << Y2Issues::InvalidValue.new("dummy", location: nil)
allow(Y2Issues).to receive(:report).and_return(continue?)
end
it "reports the issues" do
expect(Y2Issues).to receive(:report).with(issues)
subject.run
end
context "and the user wants to continue" do
let(:continue?) { true }
it "returns true" do
expect(subject.run).to eq(true)
end
end
context "and the user does not want to continue" do
let(:continue?) { false }
it "returns false" do
expect(subject.run).to eq(false)
end
end
end
end
context "Change" do
let(:func) { "Change" }
it "returns the 'summary' autosequence result" do
expect(subject).to receive(:AutoSequence).and_return(:next)
expect(subject.run).to eq(:next)
end
end
context "Summary" do
let(:func) { "Summary" }
before do
allow(Yast::Users).to receive(:Summary).and_return("summary")
end
it "returns the users summary" do
expect(subject.run).to eq("summary")
end
end
context "Export" do
let(:func) { "Export" }
let(:args) { [func] }
let(:local_users) { double("local_users") }
let(:all_users) { double("all_users") }
before do
allow(Yast::WFM).to receive(:Args).and_return(args)
allow(Yast::Users).to receive(:Export).with("default")
.and_return(all_users)
allow(Yast::Users).to receive(:Export).with("compact")
.and_return(local_users)
end
it "exports all users and groups" do
expect(subject.run).to eq(all_users)
end
context "when 'compact' export is wanted" do
let(:args) { [func, "target" => "compact"] }
it "it exports only local users and groups" do
expect(subject.run).to eq(local_users)
end
end
end
context "Modified" do
let(:func) { "GetModified" }
before do
allow(Yast::Users).to receive(:Modified).and_return(true)
end
it "returns whether the data in Users module has been modified" do
expect(subject.run).to eq(true)
end
end
context "SetModified" do
let(:func) { "SetModified" }
it "sets the Users module as modified" do
expect(Yast::Users).to receive(:SetModified).with(true)
subject.run
end
end
context "Reset" do
let(:func) { "Reset" }
it "removes the configuration object" do
# reset is not called during installation
allow(Yast::Stage).to receive(:initial).and_return(false)
expect(Yast::Users).to receive(:Import).with({})
subject.run
end
end
end
end
| yast/yast-users | test/lib/users/clients/auto_test.rb | Ruby | gpl-2.0 | 6,417 |
using System;
using Server.Engines.Craft;
namespace Server.Items
{
public abstract class BaseRing : BaseJewel
{
public BaseRing(int itemID)
: base(itemID, Layer.Ring)
{
}
public BaseRing(Serial serial)
: base(serial)
{
}
public override int BaseGemTypeNumber
{
get
{
return 1044176;
}
}// star sapphire ring
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class GoldRing : BaseRing
{
[Constructable]
public GoldRing()
: base(0x108a)
{
this.Weight = 0.1;
}
public GoldRing(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class SilverRing : BaseRing, IRepairable
{
public CraftSystem RepairSystem { get { return DefTinkering.CraftSystem; } }
[Constructable]
public SilverRing()
: base(0x1F09)
{
this.Weight = 0.1;
}
public SilverRing(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | ppardalj/ServUO | Scripts/Items/Equipment/Jewelry/Ring.cs | C# | gpl-2.0 | 2,101 |
# plugins module for amsn2
"""
Plugins with amsn2 will be a subclass of the aMSNPlugin() class.
When this module is initially imported it should load the plugins from the last session. Done in the init() proc.
Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins.
"""
# init()
# Called when the plugins module is imported (only for the first time).
# Should find plugins and populate a list ready for getPlugins().
# Should also auto-update all plugins.
def init(): pass
# loadPlugin(plugin_name)
# Called (by the GUI or from init()) to load a plugin. plugin_name as set in plugin's XML (or from getPlugins()).
# This loads the module for the plugin. The module is then responsible for calling plugins.registerPlugin(instance).
def loadPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# unLoadPlugin(plugin_name)
# Called to unload a plugin. Name is name as set in plugin's XML.
def unLoadPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# registerPlugin(plugin_instance)
# Saves the instance of the plugin, and registers it in the loaded list.
def registerPlugin(plugin_instance):
"""
@type plugin_instance: L{amsn2.plugins.developers.aMSNPlugin}
"""
pass
# getPlugins()
# Returns a list of all available plugins, as in ['Plugin 1', 'Plugin 2']
def getPlugins(): pass
# getPluginsWithStatus()
# Returns a list with a list item for each plugin with the plugin's name, and Loaded or NotLoaded either way.
# IE: [['Plugin 1', 'Loaded'], ['Plugin 2', 'NotLoaded']]
def getPluginsWithStatus(): pass
# getLoadedPlugins()
# Returns a list of loaded plugins. as in ['Plugin 1', 'Plugin N']
def getLoadedPlugins(): pass
# findPlugin(plugin_name)
# Retruns the running instance of the plugin with name plugin_name, or None if not found.
def findPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# saveConfig(plugin_name, data)
def saveConfig(plugin_name, data):
"""
@type plugin_name: str
@type data: object
"""
pass
# Calls the init procedure.
# Will only be called on the first import (thanks to python).
init()
| amsn/amsn2 | amsn2/plugins/core.py | Python | gpl-2.0 | 2,184 |
<?php
/*
Plugin Name: PoP CDN WordPress
Description: Implementation of the CDN for PoP
Plugin URI: https://getpop.org
Version: 0.1
Author: Leonardo Losovizen/u/leo/
*/
//-------------------------------------------------------------------------------------
// Constants Definition
//-------------------------------------------------------------------------------------
define('POP_CDNWP_VERSION', 0.157);
define('POP_CDNWP_DIR', dirname(__FILE__));
class PoP_CDNWP
{
public function __construct()
{
// Priority: after PoP Engine Web Platform
\PoP\Root\App::addAction('plugins_loaded', array($this, 'init'), 888412);
}
public function init()
{
define('POP_CDNWP_URL', plugins_url('', __FILE__));
if ($this->validate()) {
$this->initialize();
define('POP_CDNWP_INITIALIZED', true);
}
}
public function validate()
{
return true;
include_once 'validation.php';
$validation = new PoP_CDNWP_Validation();
return $validation->validate();
}
public function initialize()
{
include_once 'initialization.php';
$initialization = new PoP_CDNWP_Initialization();
return $initialization->initialize();
}
}
/**
* Initialization
*/
new PoP_CDNWP();
| leoloso/PoP | layers/Legacy/Schema/packages/migrate-everythingelse/migrate/plugins/pop-cdn-wp/pop-cdn-wp.php | PHP | gpl-2.0 | 1,305 |
#
# Copyright 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the implied warranties of MERCHANTABILITY,
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
# have received a copy of GPLv2 along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
# The Errata module contains methods that are common for supporting errata
# in several controllers (e.g. SystemErrataController and SystemGroupErrataController)
module Katello
module Util
module Errata
def filter_by_type(errata_list, filter_type)
filtered_list = []
if filter_type != "All"
pulp_filter_type = get_pulp_filter_type(filter_type)
errata_list.each do |erratum|
if erratum.respond_to?(:type)
if erratum.type == pulp_filter_type
filtered_list << erratum
end
else
if erratum["type"] == pulp_filter_type
filtered_list << erratum
end
end
end
else
filtered_list = errata_list
end
return filtered_list
end
def get_pulp_filter_type(type)
filter_type = type.downcase
if filter_type == "bugfix"
return Glue::Pulp::Errata::BUGZILLA
elsif filter_type == "enhancement"
return Glue::Pulp::Errata::ENHANCEMENT
elsif filter_type == "security"
return Glue::Pulp::Errata::SECURITY
end
end
def filter_by_state(errata_list, errata_state)
if errata_state == "applied"
return []
else
return errata_list
end
end
end
end
end
| dustints/katello | app/lib/katello/util/errata.rb | Ruby | gpl-2.0 | 1,852 |
define(["require", "exports"], function (require, exports) {
"use strict";
exports.ZaOverviewPanelController = ZaOverviewPanelController;
});
| ZeXtras/zimbra-lib-ts | zimbraAdmin/common/ZaOverviewPanelController.js | JavaScript | gpl-2.0 | 146 |
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
// CHECK: ; ModuleID
struct A {
template<typename T>
A(T);
};
template<typename T> A::A(T) {}
struct B {
template<typename T>
B(T);
};
template<typename T> B::B(T) {}
// CHECK: define void @_ZN1BC1IiEET_(%struct.B* %this, i32)
// CHECK: define void @_ZN1BC2IiEET_(%struct.B* %this, i32)
template B::B(int);
template<typename T>
struct C {
void f() {
int a[] = { 1, 2, 3 };
}
};
void f(C<int>& c) {
c.f();
}
| vrtadmin/clamav-bytecode-compiler | clang/test/CodeGenCXX/member-templates.cpp | C++ | gpl-2.0 | 515 |
function playAudioVisualize(track) {
var bars = 50;
var waveResolution = 128;
var style = "bars"; //set default style upon loading here
var audio = new Audio();
var canvas, source, context, analyser, fFrequencyData, barX, barWidth, barHeight, red, green, blue, ctx;
audio.controls = true;
audio.src = track;
audio.loop = false;
audio.autoplay = false;
window.addEventListener("load", initPlayer, false);
function initPlayer() {
document.getElementById('audio-container').appendChild(audio);
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById('audio-display');
canvas.addEventListener("click", toggleStyle);
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
drawFrames();
function toggleStyle() {
style = (style === "wave" ? "bars" : "wave");
}
}
var k = 0; //keep track of total number of frames drawn
function drawFrames() {
window.requestAnimationFrame(drawFrames);
analyser.fftsize = 128;
fFrequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fFrequencyData);
ctx.clearRect(0,0,canvas.width,canvas.height);
numBarsBars = 16;
//calculate average frequency for color
var total = 0;
for(var j = 0; j < fFrequencyData.length; j++) {
total += fFrequencyData[j];
}
var avg = total / fFrequencyData.length;
avg = avg / 1.2;
//bar style visual representation
function drawBars(numBars) {
for(var i = 0; i < numBars; i++) {
barX = i * (canvas.width / numBars);
barWidth = (canvas.width / numBars - 1);
barHeight = -(fFrequencyData[i] / 2);
//reduce frequency of color changing to avoid flickering
if(k % 15 === 0) {
getColors();
k = 0;
}
ctx.fillStyle = 'rgb('+red+','+green+','+blue+')';
ctx.fillRect(barX, canvas.height, barWidth, barHeight);
}
}
//waveform visualization
function drawWave(resolution, lineWidth) {
ctx.beginPath();
ctx.lineWidth = lineWidth;
var barX, barY;
for(var i = 0; i < resolution; i++) {
barX = i * (Math.ceil(canvas.width / resolution));
barY = -(fFrequencyData[i] / 2);
getColors();
k = 0;
ctx.strokeStyle = 'rgb('+red+','+green+','+blue+')';
ctx.lineTo(barX, barY + canvas.height );
ctx.stroke();
}
}
function getColors() {
//can edit these values to get overall different coloration!!
red = Math.round(Math.sin(avg/29.0 + 6.1) * 127 + 128);
green = Math.round(Math.sin(avg/42.0 - 7.4) * 127 + 128);
blue = Math.round(Math.sin(avg/34.0 - 3.8) * 127 + 128);
}
if(style === "wave") {
drawWave(waveResolution, 2);
}
if(style === "bars") {
drawBars(bars);
}
k++;
}
}
| cp2846/audio-visualizer | visualizer.js | JavaScript | gpl-2.0 | 3,591 |
<?php
/**
* Plugin Name: Category Image Video
* Plugin URI: https://github.com/cheh/
* Description: This is a WordPress plugin that adds two additional fields to the taxonomy "Category".
* Version: 1.0.0
* Author: Dmitriy Chekhovkiy <chehovskiy.dima@gmail.com>
* Author URI: https://github.com/cheh/
* Text Domain: category-image-video
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Domain Path: /languages
*
* @package Category_Image_Video
* @author Dmitriy Chekhovkiy <chehovskiy.dima@gmail.com>
* @license GPL-2.0+
* @link https://github.com/cheh/
* @copyright 2017 Dmitriy Chekhovkiy
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
if ( ! version_compare( PHP_VERSION, '5.4', '>=' ) ) {
add_action( 'admin_notices', 'civ_fail_wp_version' );
} else {
// Public-Facing Functionality.
require_once( plugin_dir_path( __FILE__ ) . 'includes/class-category-image-video-tools.php' );
require_once( plugin_dir_path( __FILE__ ) . 'public/class-category-image-video.php' );
add_action( 'plugins_loaded', array( 'CIV_Plugin', 'get_instance' ) );
// Dashboard and Administrative Functionality.
if ( is_admin() ) {
require_once( plugin_dir_path( __FILE__ ) . 'admin/class-category-image-video-admin.php' );
add_action( 'plugins_loaded', array( 'CIV_Plugin_Admin', 'get_instance' ) );
}
}
add_action( 'plugins_loaded', 'civ_load_plugin_textdomain' );
/**
* Load the plugin text domain for translation.
*
* @since 1.0.0
*/
function civ_load_plugin_textdomain() {
load_plugin_textdomain( 'category-image-video', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
/**
* Show in WP Dashboard notice about the plugin is not activated.
*
* @since 1.0.0
*/
function civ_fail_wp_version() {
$message = esc_html__( 'This plugin requires WordPress version 4.4, plugin is currently NOT ACTIVE.', 'category-image-video' );
$html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
echo wp_kses_post( $html_message );
}
| cheh88/category-image-video | category-image-video.php | PHP | gpl-2.0 | 2,076 |
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/php_header.php';
$problem = $u->getProblemById($_GET['p']);
if($_POST){
$data = $_POST;
$data['figure'] = file_get_contents($_FILES['figure']['tmp_name']);
$data['figure_file'] = $_FILES['figure']['tmp_name'];
$data['mml'] = file_get_contents($_FILES['mml']['tmp_name']);
if(!$u->submitSolution($data)){
$error = $u->error;
}
else{
$msg = 'Solution submitted successfully. It will appear on the website after approval of an editor. Thank you for contributing to this growing collection of science-problems!';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>New problem</title>
<?php include 'includes/html_head_include.php'; ?>
</head>
<body class="no-sidebar">
<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/header.php'; ?>
<!-- Main Wrapper -->
<div id="main-wrapper">
<div class="container">
<div class="row">
<div class="12u">
<!-- Portfolio -->
<section>
<div>
<div class="row">
<div class="12u skel-cell-mainContent">
<!-- Content -->
<article class="box is-post">
<header>
<h2>New Solution</h2>
</header>
<p>
<h3>Problem</h3>
<?php
echo $problem['mml'];
?>
<h3>Upload solution file</h3>
<span class="error"><?php echo $error; ?></span>
<span class="message"><?php echo $msg; ?></span>
<form class="fullwidth" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="problem_id" value="<?php echo $_GET['p']; ?>"/>
<label>Figure (optional)</label>
<input type="file" class="file" name="figure" />
<label>MathML file</label>
<input type="file" class="file" name="mml" required/>
<br/>
<input type="submit"/>
</form>
</p>
</article>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/footer.php'; ?>
</body>
</html>
| CarvingIT/science-problems | public_html/new_solution.php | PHP | gpl-2.0 | 2,151 |
/*global chrome */
// Check if the feature is enable
let promise = new Promise(function (resolve) {
chrome.storage.sync.get({
isEdEnable: true
}, function (items) {
if (items.isEdEnable === true) {
resolve();
}
});
});
promise.then(function () {
/*global removeIfExist */
/*eslint no-undef: "error"*/
removeIfExist(".blockheader");
removeIfExist(".blockcontent .upload-infos");
removeIfExist(".blockfooter");
}); | hochgenug/BADW | scripts/ed.js | JavaScript | gpl-2.0 | 481 |
<?php
/*------------------------------------------------------------------------
# view.html.php - TrackClub Component
# ------------------------------------------------------------------------
# author Michael
# copyright Copyright (C) 2014. All Rights Reserved
# license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
# website tuscaloosatrackclub.com
-------------------------------------------------------------------------*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
/**
* athletes View
*/
class TrackclubsViewathletes extends JViewLegacy
{
/**
* Athletes view display method
* @return void
*/
function display($tpl = null)
{
// Include helper submenu
TrackclubsHelper::addSubmenu('athletes');
// Get data from the model
$items = $this->get('Items');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))){
JError::raiseError(500, implode('<br />', $errors));
return false;
};
// Assign data to the view
$this->items = $items;
$this->pagination = $pagination;
// Set the toolbar
$this->addToolBar();
// Show sidebar
$this->sidebar = JHtmlSidebar::render();
// Display the template
parent::display($tpl);
// Set the document
$this->setDocument();
}
/**
* Setting the toolbar
*/
protected function addToolBar()
{
$canDo = TrackclubsHelper::getActions();
JToolBarHelper::title(JText::_('Trackclubs Manager'), 'trackclubs');
if($canDo->get('core.create')){
JToolBarHelper::addNew('athlete.add', 'JTOOLBAR_NEW');
};
if($canDo->get('core.edit')){
JToolBarHelper::editList('athlete.edit', 'JTOOLBAR_EDIT');
};
if($canDo->get('core.delete')){
JToolBarHelper::deleteList('', 'athletes.delete', 'JTOOLBAR_DELETE');
};
if($canDo->get('core.admin')){
JToolBarHelper::divider();
JToolBarHelper::preferences('com_trackclubs');
};
}
/**
* Method to set up the document properties
*
*
* @return void
*/
protected function setDocument()
{
$document = JFactory::getDocument();
$document->setTitle(JText::_('Trackclubs Manager - Administrator'));
}
}
?> | mstewartua/newprod | administrator/components/com_trackclubs/views/athletes/view.html.php | PHP | gpl-2.0 | 2,263 |
package com.nilsonmassarenti.app.currencyfair.model;
/**
* This class is to manager URL of Rest.
* @author nilsonmassarenti - nilsonmassarenti@gmail.com
* @version 0.1
* Last update: 03-Mar-2015 12:20 am
*/
public class CurrencyFairURI {
public static final String DUMMY_BP = "/rest/currencyfair/dummy";
public static final String GET_CURRENCY_FAIR = "/rest/currencyfair/get/{id}";
public static final String GET_ALL_CURRENCY_FAIR = "/rest/currencyfairs";
public static final String CREATE_CURRENCY_FAIR = "/rest/currencyfair/create";
public static final String DELETE_CURRENCY_FAIR = "/rest/currencyfair/delete/{id}";
}
| nilsonmassarenti/currencyfair | currencyfair/src/main/java/com/nilsonmassarenti/app/currencyfair/model/CurrencyFairURI.java | Java | gpl-2.0 | 632 |
<?php
/*
Plugin Name: Vertical marquee post title
Description: This plug-in will create the vertical marquee effect in your website, if you want your post title to move vertically (scroll upward or downwards) in the screen use this plug-in.
Author: Gopi Ramasamy
Version: 2.5
Plugin URI: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
Author URI: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
Donate link: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
function vmptshow()
{
$vmpt_setting = get_option('vmpt_setting');
$array = array("setting" => $vmpt_setting);
echo vmpt_shortcode($array);
}
function vmpt_shortcode( $atts )
{
global $wpdb;
$vmpt_marquee = "";
$vmpt = "";
$link = "";
//[vmpt setting="1"]
if ( ! is_array( $atts ) ) { return ''; }
$setting = $atts['setting'];
switch ($setting)
{
case 1:
$vmpt_setting = get_option('vmpt_setting1');
break;
case 2:
$vmpt_setting = get_option('vmpt_setting2');
break;
case 3:
$vmpt_setting = get_option('vmpt_setting3');
break;
case 4:
$vmpt_setting = get_option('vmpt_setting4');
break;
default:
$vmpt_setting = get_option('vmpt_setting1');
}
@list($vmpt_scrollamount, $vmpt_scrolldelay, $vmpt_direction, $vmpt_style, $vmpt_noofpost, $vmpt_categories, $vmpt_orderbys, $vmpt_order, $vmpt_spliter) = explode("~~", @$vmpt_setting);
if(!is_numeric($vmpt_scrollamount)){ $vmpt_scrollamount = 2; }
if(!is_numeric($vmpt_scrolldelay)){ $vmpt_scrolldelay = 5; }
if(!is_numeric($vmpt_noofpost)){ $vmpt_noofpost = 10; }
$sSql = query_posts('cat='.$vmpt_categories.'&orderby='.$vmpt_orderbys.'&order='.$vmpt_order.'&showposts='.$vmpt_noofpost);
if ( ! empty($sSql) )
{
$count = 0;
foreach ( $sSql as $sSql )
{
$title = stripslashes($sSql->post_title);
$link = get_permalink($sSql->ID);
if($count==0)
{
if($link != "") { $vmpt = $vmpt . "<a target='' href='".$link."'>"; }
$vmpt = $vmpt . $title;
if($link != "") { $vmpt = $vmpt . "</a>"; }
}
else
{
$vmpt = $vmpt . " <br /><br /> ";
if($link != "") { $vmpt = $vmpt . "<a target='' href='".$link."'>"; }
$vmpt = $vmpt . $title;
if($link != "") { $vmpt = $vmpt . "</a>"; }
}
$count = $count + 1;
}
}
else
{
$vmpt = __('No records found.', 'vertical-marquee-post-title');
}
wp_reset_query();
$vmpt_marquee = $vmpt_marquee . "<div style='padding:3px;' class='vmpt_marquee'>";
$vmpt_marquee = $vmpt_marquee . "<marquee style='$vmpt_style' scrollamount='$vmpt_scrollamount' scrolldelay='$vmpt_scrolldelay' direction='$vmpt_direction' onmouseover='this.stop()' onmouseout='this.start()'>";
$vmpt_marquee = $vmpt_marquee . $vmpt;
$vmpt_marquee = $vmpt_marquee . "</marquee>";
$vmpt_marquee = $vmpt_marquee . "</div>";
return $vmpt_marquee;
}
function vmpt_install()
{
add_option('vmpt_title', "Marquee post title");
add_option('vmpt_setting', "1");
add_option('vmpt_setting1', "2~~5~~up~~height:100px;~~10~~~~ID~~DESC");
add_option('vmpt_setting2', "2~~5~~up~~color:#FF0000;font:Arial;height:100px;~~10~~~~ID~~DESC");
add_option('vmpt_setting3', "2~~5~~down~~color:#FF0000;font:Arial;height:120px;~~10~~~~title~~DESC");
add_option('vmpt_setting4', "2~~5~~down~~color:#FF0000;font:Arial;height:140px;~~10~~~~rand~~DESC");
}
function vmpt_deactivation()
{
// No action required.
}
function vmpt_option()
{
?>
<div class="wrap">
<div class="form-wrap">
<div id="icon-edit" class="icon32 icon32-posts-post"><br>
</div>
<h2><?php _e('Vertical marquee post title', 'vertical-marquee-post-title'); ?></h2>
<?php
global $wpdb;
$vmpt_setting1 = get_option('vmpt_setting1');
$vmpt_setting2 = get_option('vmpt_setting2');
$vmpt_setting3 = get_option('vmpt_setting3');
$vmpt_setting4 = get_option('vmpt_setting4');
list($a1, $b1, $c1, $d1, $e1, $f1, $g1, $h1) = explode("~~", $vmpt_setting1);
list($a2, $b2, $c2, $d2, $e2, $f2, $g2, $h2) = explode("~~", $vmpt_setting2);
list($a3, $b3, $c3, $d3, $e3, $f3, $g3, $h3) = explode("~~", $vmpt_setting3);
list($a4, $b4, $c4, $d4, $e4, $f4, $g4, $h4) = explode("~~", $vmpt_setting4);
if (isset($_POST['vmpt_submit']))
{
// Just security thingy that wordpress offers us
check_admin_referer('vmpt_form_setting');
$a1 = stripslashes($_POST['vmpt_scrollamount1']);
$b1 = stripslashes($_POST['vmpt_scrolldelay1']);
$c1 = stripslashes($_POST['vmpt_direction1']);
$d1 = stripslashes($_POST['vmpt_style1']);
$e1 = stripslashes($_POST['vmpt_noofpost1']);
$f1 = stripslashes($_POST['vmpt_categories1']);
$g1 = stripslashes($_POST['vmpt_orderbys1']);
$h1 = stripslashes($_POST['vmpt_order1']);
$a2 = stripslashes($_POST['vmpt_scrollamount2']);
$b2 = stripslashes($_POST['vmpt_scrolldelay2']);
$c2 = stripslashes($_POST['vmpt_direction2']);
$d2 = stripslashes($_POST['vmpt_style2']);
$e2 = stripslashes($_POST['vmpt_noofpost2']);
$f2 = stripslashes($_POST['vmpt_categories2']);
$g2 = stripslashes($_POST['vmpt_orderbys2']);
$h2 = stripslashes($_POST['vmpt_order2']);
$a3 = stripslashes($_POST['vmpt_scrollamount3']);
$b3 = stripslashes($_POST['vmpt_scrolldelay3']);
$c3 = stripslashes($_POST['vmpt_direction3']);
$d3 = stripslashes($_POST['vmpt_style3']);
$e3 = stripslashes($_POST['vmpt_noofpost3']);
$f3 = stripslashes($_POST['vmpt_categories3']);
$g3 = stripslashes($_POST['vmpt_orderbys3']);
$h3 = stripslashes($_POST['vmpt_order3']);
$a4 = stripslashes($_POST['vmpt_scrollamount4']);
$b4 = stripslashes($_POST['vmpt_scrolldelay4']);
$c4 = stripslashes($_POST['vmpt_direction4']);
$d4 = stripslashes($_POST['vmpt_style4']);
$e4 = stripslashes($_POST['vmpt_noofpost4']);
$f4 = stripslashes($_POST['vmpt_categories4']);
$g4 = stripslashes($_POST['vmpt_orderbys4']);
$h4 = stripslashes($_POST['vmpt_order4']);
update_option('vmpt_setting1', @$a1 . "~~" . @$b1 . "~~" . @$c1 . "~~" . @$d1 . "~~" . @$e1 . "~~" . @$f1 . "~~" . @$g1 . "~~" . @$h1 . "~~" . @$i1 );
update_option('vmpt_setting2', @$a2 . "~~" . @$b2 . "~~" . @$c2 . "~~" . @$d2 . "~~" . @$e2 . "~~" . @$f2 . "~~" . @$g2 . "~~" . @$h2 . "~~" . @$i2 );
update_option('vmpt_setting3', @$a3 . "~~" . @$b3 . "~~" . @$c3 . "~~" . @$d3 . "~~" . @$e3 . "~~" . @$f3 . "~~" . @$g3 . "~~" . @$h3 . "~~" . @$i3 );
update_option('vmpt_setting4', @$a4 . "~~" . @$b4 . "~~" . @$c4 . "~~" . @$d4 . "~~" . @$e4 . "~~" . @$f4 . "~~" . @$g4 . "~~" . @$h4 . "~~" . @$i4 );
?>
<div class="updated fade">
<p><strong><?php _e('Details successfully updated.', 'vertical-marquee-post-title'); ?></strong></p>
</div>
<?php
}
echo '<form name="vmpt_form" method="post" action="">';
?>
<table width="800" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><?php
echo '<h3>'.__('Setting 1', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a1 . '" name="vmpt_scrollamount1" id="vmpt_scrollamount1" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b1 . '" name="vmpt_scrolldelay1" id="vmpt_scrolldelay1" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c1 . '" name="vmpt_direction1" id="vmpt_direction1" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d1 . '" name="vmpt_style1" id="vmpt_style1" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e1 . '" name="vmpt_noofpost1" id="vmpt_noofpost1" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f1 . '" name="vmpt_categories1" id="vmpt_categories1" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g1 . '" name="vmpt_orderbys1" id="vmpt_orderbys1" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h1 . '" name="vmpt_order1" id="vmpt_order1" /> ASC/DESC </p>';
?>
</td>
<td><?php
echo '<h3>'.__('Setting 2', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a2 . '" name="vmpt_scrollamount2" id="vmpt_scrollamount2" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b2 . '" name="vmpt_scrolldelay2" id="vmpt_scrolldelay2" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c2 . '" name="vmpt_direction2" id="vmpt_direction2" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d2 . '" name="vmpt_style2" id="vmpt_style2" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e2 . '" name="vmpt_noofpost2" id="vmpt_noofpost2" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f2 . '" name="vmpt_categories2" id="vmpt_categories2" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g2 . '" name="vmpt_orderbys2" id="vmpt_orderbys2" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h2 . '" name="vmpt_order2" id="vmpt_order2" /> ASC/DESC </p>';
?>
</td>
</tr>
<tr>
<td><?php
echo '<h3>'.__('Setting 3', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a3 . '" name="vmpt_scrollamount3" id="vmpt_scrollamount3" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b3 . '" name="vmpt_scrolldelay3" id="vmpt_scrolldelay3" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c3 . '" name="vmpt_direction3" id="vmpt_direction3" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d3 . '" name="vmpt_style3" id="vmpt_style3" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e3 . '" name="vmpt_noofpost3" id="vmpt_noofpost3" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f3 . '" name="vmpt_categories3" id="vmpt_categories3" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g3 . '" name="vmpt_orderbys3" id="vmpt_orderbys3" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h3 . '" name="vmpt_order3" id="vmpt_order3" /> ASC/DESC </p>';
?>
</td>
<td><?php
echo '<h3>'.__('Setting 4', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a4 . '" name="vmpt_scrollamount4" id="vmpt_scrollamount4" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b4 . '" name="vmpt_scrolldelay4" id="vmpt_scrolldelay4" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c4 . '" name="vmpt_direction4" id="vmpt_direction4" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d4 . '" name="vmpt_style4" id="vmpt_style4" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e4 . '" name="vmpt_noofpost4" id="vmpt_noofpost4" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f4 . '" name="vmpt_categories4" id="vmpt_categories4" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g4 . '" name="vmpt_orderbys4" id="vmpt_orderbys4" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h4 . '" name="vmpt_order4" id="vmpt_order4" /> ASC/DESC </p>';
?>
</td>
</tr>
</table>
<br />
<input name="vmpt_submit" id="vmpt_submit" lang="publish" class="button-primary" value="<?php _e('Update all 4 settings', 'vertical-marquee-post-title'); ?>" type="Submit" />
<?php wp_nonce_field('vmpt_form_setting'); ?>
</form>
<h3><?php _e('Plugin configuration option', 'vertical-marquee-post-title'); ?></h3>
<ol>
<li><?php _e('Drag and drop the widget.', 'vertical-marquee-post-title'); ?></li>
<li><?php _e('Add the plugin in the posts or pages using short code.', 'vertical-marquee-post-title'); ?></li>
<li><?php _e('Add directly in to the theme using PHP code.', 'vertical-marquee-post-title'); ?></li>
</ol>
<p class="description"><?php _e('Check official website for more information ', 'vertical-marquee-post-title'); ?>
<a href="http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/" target="_blank"><?php _e('Click here', 'vertical-marquee-post-title'); ?></a></p>
</div>
</div>
<?php
}
function vmpt_add_to_menu()
{
add_options_page( __('Vertical marquee post title', 'vertical-marquee-post-title'),
__('Vertical marquee post title', 'vertical-marquee-post-title'), 'manage_options', __FILE__, 'vmpt_option' );
}
if (is_admin())
{
add_action('admin_menu', 'vmpt_add_to_menu');
}
class vmpt_widget_register extends WP_Widget
{
function __construct()
{
$widget_ops = array('classname' => 'widget_text newsticker-widget', 'description' => __('Vertical marquee post title', 'vertical-marquee-post-title'), 'vertical-marquee-post-title');
parent::__construct('vertical-marquee-post-title', __('Vertical marquee post title', 'vertical-marquee-post-title'), $widget_ops);
}
function widget( $args, $instance )
{
extract( $args, EXTR_SKIP );
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
$vmpt_setting = $instance['vmpt_setting'];
echo $args['before_widget'];
if ( ! empty( $title ) )
{
echo $args['before_title'] . $title . $args['after_title'];
}
// Call widget method
$arr = array();
$arr["setting"] = $vmpt_setting;
echo vmpt_shortcode($arr);
// Call widget method
echo $args['after_widget'];
}
function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['vmpt_setting'] = ( ! empty( $new_instance['vmpt_setting'] ) ) ? strip_tags( $new_instance['vmpt_setting'] ) : '';
return $instance;
}
function form( $instance )
{
$defaults = array(
'title' => '',
'vmpt_setting' => ''
);
$instance = wp_parse_args( (array) $instance, $defaults);
$title = $instance['title'];
$vmpt_setting = $instance['vmpt_setting'];
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget title', 'vertical-marquee-post-title'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('vmpt_setting'); ?>"><?php _e('Setting', 'vertical-marquee-post-title'); ?></label>
<select class="widefat" id="<?php echo $this->get_field_id('vmpt_setting'); ?>" name="<?php echo $this->get_field_name('vmpt_setting'); ?>">
<option value="1" <?php $this->vmpt_render_selected($vmpt_setting=='1'); ?>>Setting 1</option>
<option value="2" <?php $this->vmpt_render_selected($vmpt_setting=='2'); ?>>Setting 2</option>
<option value="3" <?php $this->vmpt_render_selected($vmpt_setting=='3'); ?>>Setting 3</option>
<option value="4" <?php $this->vmpt_render_selected($vmpt_setting=='4'); ?>>Setting 4</option>
</select>
</p>
<p>
<?php _e('Check official website for more information', 'vertical-marquee-post-title'); ?>
<a target="_blank" href="http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/"><?php _e('click here', 'vertical-marquee-post-title'); ?></a>
</p>
<?php
}
function vmpt_render_selected($var)
{
if ($var==1 || $var==true)
{
echo 'selected="selected"';
}
}
}
function vmpt_widget_loading()
{
register_widget( 'vmpt_widget_register' );
}
function vmpt_textdomain()
{
load_plugin_textdomain( 'vertical-marquee-post-title', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'vmpt_textdomain');
register_activation_hook(__FILE__, 'vmpt_install');
register_deactivation_hook(__FILE__, 'vmpt_deactivation');
add_action( 'widgets_init', 'vmpt_widget_loading');
add_shortcode( 'vmpt', 'vmpt_shortcode' );
?> | SK8-PTY-LTD/PinkRose | wp-content/plugins/vertical-marquee-post-title/vertical-marquee-post-title.php | PHP | gpl-2.0 | 19,986 |
<?php
namespace Icinga\Module\Businessprocess\Web\Form;
use Icinga\Application\Icinga;
use Icinga\Exception\ProgrammingError;
use Icinga\Web\Notification;
use Icinga\Web\Request;
use Icinga\Web\Response;
use Icinga\Web\Url;
use Exception;
/**
* QuickForm wants to be a base class for simple forms
*/
abstract class QuickForm extends QuickBaseForm
{
const ID = '__FORM_NAME';
const CSRF = '__FORM_CSRF';
/**
* The name of this form
*/
protected $formName;
/**
* Whether the form has been sent
*/
protected $hasBeenSent;
/**
* Whether the form has been sent
*/
protected $hasBeenSubmitted;
/**
* The submit caption, element - still tbd
*/
// protected $submit;
/**
* Our request
*/
protected $request;
/**
* @var Url
*/
protected $successUrl;
protected $successMessage;
protected $submitLabel;
protected $submitButtonName;
protected $deleteButtonName;
protected $fakeSubmitButtonName;
/**
* Whether form elements have already been created
*/
protected $didSetup = false;
protected $isApiRequest = false;
public function __construct($options = null)
{
parent::__construct($options);
$this->setMethod('post');
$this->getActionFromRequest()
->createIdElement()
->regenerateCsrfToken()
->setPreferredDecorators();
}
protected function getActionFromRequest()
{
$this->setAction(Url::fromRequest());
return $this;
}
protected function setPreferredDecorators()
{
$this->setAttrib('class', 'autofocus icinga-controls');
$this->setDecorators(
array(
'Description',
array('FormErrors', array('onlyCustomFormErrors' => true)),
'FormElements',
'Form'
)
);
return $this;
}
protected function addSubmitButtonIfSet()
{
if (false === ($label = $this->getSubmitLabel())) {
return;
}
if ($this->submitButtonName && $el = $this->getElement($this->submitButtonName)) {
return;
}
$el = $this->createElement('submit', $label)
->setLabel($label)
->setDecorators(array('ViewHelper'));
$this->submitButtonName = $el->getName();
$this->addElement($el);
$fakeEl = $this->createElement('submit', '_FAKE_SUBMIT')
->setLabel($label)
->setDecorators(array('ViewHelper'));
$this->fakeSubmitButtonName = $fakeEl->getName();
$this->addElement($fakeEl);
$this->addDisplayGroup(
array($this->fakeSubmitButtonName),
'fake_button',
array(
'decorators' => array('FormElements'),
'order' => 1,
)
);
$grp = array(
$this->submitButtonName,
$this->deleteButtonName
);
$this->addDisplayGroup($grp, 'buttons', array(
'decorators' => array(
'FormElements',
array('HtmlTag', array('tag' => 'dl')),
'DtDdWrapper',
),
'order' => 1000,
));
}
protected function addSimpleDisplayGroup($elements, $name, $options)
{
if (! array_key_exists('decorators', $options)) {
$options['decorators'] = array(
'FormElements',
array('HtmlTag', array('tag' => 'dl')),
'Fieldset',
);
}
return $this->addDisplayGroup($elements, $name, $options);
}
protected function createIdElement()
{
$this->detectName();
$this->addHidden(self::ID, $this->getName());
$this->getElement(self::ID)->setIgnore(true);
return $this;
}
public function getSentValue($name, $default = null)
{
$request = $this->getRequest();
if ($request->isPost() && $this->hasBeenSent()) {
return $request->getPost($name);
} else {
return $default;
}
}
public function getSubmitLabel()
{
if ($this->submitLabel === null) {
return $this->translate('Submit');
}
return $this->submitLabel;
}
public function setSubmitLabel($label)
{
$this->submitLabel = $label;
return $this;
}
public function setApiRequest($isApiRequest = true)
{
$this->isApiRequest = $isApiRequest;
return $this;
}
public function isApiRequest()
{
return $this->isApiRequest;
}
public function regenerateCsrfToken()
{
if (! $element = $this->getElement(self::CSRF)) {
$this->addHidden(self::CSRF, CsrfToken::generate());
$element = $this->getElement(self::CSRF);
}
$element->setIgnore(true);
return $this;
}
public function removeCsrfToken()
{
$this->removeElement(self::CSRF);
return $this;
}
public function setSuccessUrl($url, $params = null)
{
if (! $url instanceof Url) {
$url = Url::fromPath($url);
}
if ($params !== null) {
$url->setParams($params);
}
$this->successUrl = $url;
return $this;
}
public function getSuccessUrl()
{
$url = $this->successUrl ?: $this->getAction();
if (! $url instanceof Url) {
$url = Url::fromPath($url);
}
return $url;
}
protected function beforeSetup()
{
}
public function setup()
{
}
protected function onSetup()
{
}
public function setAction($action)
{
if ($action instanceof Url) {
$action = $action->getAbsoluteUrl('&');
}
return parent::setAction($action);
}
public function hasBeenSubmitted()
{
if ($this->hasBeenSubmitted === null) {
$req = $this->getRequest();
if ($req->isPost()) {
if (! $this->hasSubmitButton()) {
return $this->hasBeenSubmitted = $this->hasBeenSent();
}
$this->hasBeenSubmitted = $this->pressedButton(
$this->fakeSubmitButtonName,
$this->getSubmitLabel()
) || $this->pressedButton(
$this->submitButtonName,
$this->getSubmitLabel()
);
} else {
$this->hasBeenSubmitted = false;
}
}
return $this->hasBeenSubmitted;
}
protected function hasSubmitButton()
{
return $this->submitButtonName !== null;
}
protected function pressedButton($name, $label)
{
$req = $this->getRequest();
if (! $req->isPost()) {
return false;
}
$req = $this->getRequest();
$post = $req->getPost();
return array_key_exists($name, $post)
&& $post[$name] === $label;
}
protected function beforeValidation($data = array())
{
}
public function prepareElements()
{
if (! $this->didSetup) {
$this->beforeSetup();
$this->setup();
$this->addSubmitButtonIfSet();
$this->onSetup();
$this->didSetup = true;
}
return $this;
}
public function handleRequest(Request $request = null)
{
if ($request === null) {
$request = $this->getRequest();
} else {
$this->setRequest($request);
}
$this->prepareElements();
if ($this->hasBeenSent()) {
$post = $request->getPost();
if ($this->hasBeenSubmitted()) {
$this->beforeValidation($post);
if ($this->isValid($post)) {
try {
$this->onSuccess();
} catch (Exception $e) {
$this->addException($e);
$this->onFailure();
}
} else {
$this->onFailure();
}
} else {
$this->setDefaults($post);
}
} else {
// Well...
}
return $this;
}
public function addException(Exception $e, $elementName = null)
{
$file = preg_split('/[\/\\\]/', $e->getFile(), -1, PREG_SPLIT_NO_EMPTY);
$file = array_pop($file);
$msg = sprintf(
'%s (%s:%d)',
$e->getMessage(),
$file,
$e->getLine()
);
if ($el = $this->getElement($elementName)) {
$el->addError($msg);
} else {
$this->addError($msg);
}
}
public function onSuccess()
{
$this->redirectOnSuccess();
}
public function setSuccessMessage($message)
{
$this->successMessage = $message;
return $this;
}
public function getSuccessMessage($message = null)
{
if ($message !== null) {
return $message;
}
if ($this->successMessage === null) {
return t('Form has successfully been sent');
}
return $this->successMessage;
}
public function redirectOnSuccess($message = null)
{
if ($this->isApiRequest()) {
// TODO: Set the status line message?
$this->successMessage = $this->getSuccessMessage($message);
return;
}
$url = $this->getSuccessUrl();
$this->notifySuccess($this->getSuccessMessage($message));
$this->redirectAndExit($url);
}
public function onFailure()
{
}
public function notifySuccess($message = null)
{
if ($message === null) {
$message = t('Form has successfully been sent');
}
Notification::success($message);
return $this;
}
public function notifyError($message)
{
Notification::error($message);
return $this;
}
protected function redirectAndExit($url)
{
/** @var Response $response */
$response = Icinga::app()->getFrontController()->getResponse();
$response->redirectAndExit($url);
}
protected function setHttpResponseCode($code)
{
Icinga::app()->getFrontController()->getResponse()->setHttpResponseCode($code);
return $this;
}
protected function onRequest()
{
}
public function setRequest(Request $request)
{
if ($this->request !== null) {
throw new ProgrammingError('Unable to set request twice');
}
$this->request = $request;
$this->prepareElements();
$this->onRequest();
return $this;
}
/**
* @return Request
*/
public function getRequest()
{
if ($this->request === null) {
/** @var Request $request */
$request = Icinga::app()->getFrontController()->getRequest();
$this->setRequest($request);
}
return $this->request;
}
public function hasBeenSent()
{
if ($this->hasBeenSent === null) {
/** @var Request $req */
if ($this->request === null) {
$req = Icinga::app()->getFrontController()->getRequest();
} else {
$req = $this->request;
}
if ($req->isPost()) {
$post = $req->getPost();
$this->hasBeenSent = array_key_exists(self::ID, $post) &&
$post[self::ID] === $this->getName();
} else {
$this->hasBeenSent = false;
}
}
return $this->hasBeenSent;
}
protected function detectName()
{
if ($this->formName !== null) {
$this->setName($this->formName);
} else {
$this->setName(get_class($this));
}
}
}
| Icinga/icingaweb2-module-businessprocess | library/Businessprocess/Web/Form/QuickForm.php | PHP | gpl-2.0 | 12,131 |
<?php
/****************************************************************************************\
** @name EXP Autos 2.0 **
** @package Joomla 1.6 **
** @author EXP TEAM::Alexey Kurguz (Grusha) **
** @copyright Copyright (C) 2005 - 2011 EXP TEAM::Alexey Kurguz (Grusha) **
** @link http://www.feellove.eu **
** @license Commercial License **
\****************************************************************************************/
defined('_JEXEC') or die;
jimport('joomla.application.component.controllerform');
class ExpautosproControllerExplist extends JControllerForm
{
public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true))
{
return parent::getModel($name, $prefix, array('ignore_request' => false));
}
public function solid(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$value = (int) JRequest::getInt('value','0');
$field = 'solid';
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->insertdata($id,$field,$value)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
public function expreserved(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$value = (int) JRequest::getInt('value','0');
$field = 'expreserved';
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->insertdata($id,$field,$value)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
public function deletelink(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->delete_ads($id)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
}
public function extend(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->extend_ads($id)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
} | Chubaskin/buscarautos | components/com_expautospro/controllers/explist.php | PHP | gpl-2.0 | 4,236 |
<?php $captcha_word = 'BKPS'; ?> | CoordCulturaDigital-Minc/culturadigital.br | wp-content/plugins/si-captcha-for-wordpress/captcha-secureimage/captcha-temp/WX2pCemM1b2iQHf2.php | PHP | gpl-2.0 | 32 |
#include"population.h"
population::population() {
pop.clear();
}
population::population(Random *r) {
pop.clear();
this->r = r;
}
population::population(int n_individuos, int n_gene, Random *r) {
pop.clear();
for(int i = 0; i < n_individuos; i++) pop.push_back(*(new individuo(n_gene, r)));
this->r = r;
}
population::population(vector<individuo> i, Random *r) {
pop = i;
this->r = r;
}
vector<individuo> population::get_population() {
return pop;
}
void population::set_population(vector<individuo> i) {
pop = i;
}
void population::set_population(population p) {
pop = p.get_population();
}
int population::size() {
return pop.size();
}
void population::print() {
for(int i = 0; i < size(); i++) pop[i].print();
}
population *population::elitismo(double pel) {
int num = (int) (pel * ((double) size()));
return elitismo(num);
}
population *population::elitismo(int num) {
ranking();
vector<individuo> newp;
newp.clear();
for(int i = 0; i < num; i++)
newp.push_back(pop[i]);
return (new population(newp, r));
}
void population::calc_fitness() {
for(int i = 0; i < size(); i++) pop[i].get_objective();
}
void population::ranking() {
calc_fitness();
for(int i = 0; i < size() - 1; i++) {
for(int j = i + 1; j < size(); j++) {
if(pop[i] < pop[j]) {
individuo aux = pop[i];
pop[i] = pop[j];
pop[j] = aux;
}
}
}
int counter = 0;
pop[size() - 1].set_rank(0);
for(int i = size() - 2; i >= 0; i--) {
if(pop[i] > pop[i+1]) counter++;
pop[i].set_rank(counter);
}
}
void population::crowd() {
calc_fitness();
double *crowd = new double[size()];
for(int i = 0; i < size(); i++)
crowd[i] = 0;
for(int i = 0; i < pop[0].get_objective().size(); i++) {
// ordena por objetivo.
for(int j = 0; j < size(); j++) {
for(int k = j + 1; k < size(); k++) {
if(pop[j].get_objective(i) > pop[k].get_objective(i))
swap(pop[j], pop[k]);
}
}
for(int j = 1; j < size() - 1; j++)
crowd[j] += pop[j + 1].get_objective(i) - pop[j - 1].get_objective(i);
crowd[0] = crowd[size() - 1] = 3000; //numeric_limits<double>::infinity();
}
for(int i = 0; i < size(); i++)
pop[i].set_crowd(crowd[i]);
}
void population::sort() {
for(int i = 0; i < size() - 1; i++) {
for(int j = i + 1; j < size(); j++) {
if(pop[i].get_rank() < pop[j].get_rank()) {
swap(pop[i], pop[j]);
} else if(pop[i].get_rank() == pop[j].get_rank() && pop[i].get_crowd() < pop[j].get_crowd()) {
swap(pop[i], pop[j]);
}
}
}
}
population population::operator+(const population &p) {
vector<individuo> n;
n = p.pop;
for(int i = 0; i < pop.size(); i++) n.push_back(pop[i]);
return *(new population(n, r));
}
//population population::operator+=(const population &p) {return *this = *this + p;}
population *population::mutation(int num_ind, int num_gene) {
printf("mut a\n");
population *newp = new population(num_ind, pop[0].get_cromossomo().get_n_gene(), r);
printf("mut b\n");
for(int i = 0; i < num_ind; i++) {
newp->pop[i] = pop[r->nextLongInt(pop.size())].mutation(num_gene);
}
printf("mut c\n");
return newp;
}
population *population::mutation(int num_ind) { return mutation(num_ind, 1);}
population *population::mutation(double pmut, int num_gene) {
int num_ind = (int) (pmut * ((double) pop.size()));
return mutation(num_ind,num_gene);
}
population *population::mutation(double pmut) { return mutation(pmut, 1);}
individuo population::get_individuo(int index){
return pop[index];
}
void population::add_individuo(individuo i){ pop.push_back(i);}
void population::add_individuo(vector<individuo> i){
for (int index = 0; index < i.size(); index ++){
add_individuo(i[index]);
}
}
population *population::crossover( double pcrv){
int ncrv = (int) (pcrv * ((double) size()));
return crossover(ncrv);
}
population *population::crossover( int ncrv){
population *p = new population();
for (int i = 0; i < ncrv; i ++ ) {
p->add_individuo(pop[r->nextLongInt(size())] + pop[r->nextLongInt(size())]);
}
return p;
}
population *population::tournament(int num_ind, int num_group) {
printf("inicio\n");
vector<individuo> group;
if(num_ind < 1) return NULL;
population *newp = new population(r);
for(int i = 0; i < num_ind; i++) {
group.clear();
for(int j = 0; j < num_group; j++)
group.push_back(pop[r->nextLongInt(pop.size())]);
individuo maior = group[0];
for(int j = 1; j < group.size(); j++)
if(group[j] > maior)
maior = group[j];
newp->add_individuo(maior);
}
printf("fim\n");
return newp;
}
population *population::roulette(int num_ind, int param) {
population *newp = new population(r);
double max = 0;
vector<double> roulette;
roulette.clear();
if(param == ROULETTE_RANK || param == ROULETTE_MULTIPOINTER_RANK) {
for(int i = 0; i < pop.size(); i++) {
max += (double) pop[i].get_rank();
roulette.push_back(max);
}
} else {
for(int i = 0; i < pop.size(); i++) {
max += pop[i].get_objective(0);
roulette.push_back(max);
}
}
if(param == ROULETTE_RANK || param == ROULETTE_OBJECTIVE) {
for(int i = 0; i < num_ind; i++) {
double pointer = r->nextDouble(max);
int j;
for(j = 0; roulette[j] < pointer; j++);
newp->add_individuo(pop[j]);
}
}
else {
double pointer;
double delta = max / (double) num_ind;
pointer = r->nextDouble(max / (double) num_ind);
int j = 0;
for(int i = 0; i < num_ind; i++) {
for(j; roulette[j] < pointer; j++);
newp->add_individuo(pop[j]);
pointer += delta;
}
}
return newp;
}
void population::resize(int n ){
if(n < pop.size())
pop.resize(n);
}
| dmelo/uspds | src/genetic_algorithm/population.cc | C++ | gpl-2.0 | 5,814 |
#Date: 2015-10-01 16:06:58 UTC
#Software: Joomla Platform 13.1.0 Stable [ Curiosity ] 24-Apr-2013 00:00 GMT
#Fields: datetime priority message
2015-10-01T16:06:58+00:00 INFO |¯¯¯ Starting
2015-10-01T16:06:58+00:00 INFO | ^^ Connecting to ...
2015-10-01T16:06:58+00:00 ERROR | XX Unable to connect to FTP server
2015-10-01T16:06:58+00:00 ERROR |___ :(
2015-10-01T16:06:58+00:00 ERROR
| esorone/efcpw | logs/ecr_log.php | PHP | gpl-2.0 | 389 |
/*
* 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);
}
UpdateExpertise(BASE_ATTACK);
UpdateArmorPenetration();
}
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();
}
| bwsrv/mangos | src/game/Player.cpp | C++ | gpl-2.0 | 923,318 |
package com.javarush.task.task11.task1109;
/*
Как кошка с собакой
*/
public class Solution {
public static void main(String[] args) {
Cat cat = new Cat("Vaska", 5);
Dog dog = new Dog("Sharik", 4);
cat.isDogNear(dog);
dog.isCatNear(cat);
}
public static class Cat {
private String name;
private int speed;
public Cat(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isDogNear(Dog dog) {
return this.speed > dog.getSpeed();
}
}
public static class Dog {
private String name;
private int speed;
public Dog(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isCatNear(Cat cat) {
return this.speed > cat.getSpeed();
}
}
} | biblelamp/JavaExercises | JavaRushTasks/2.JavaCore/src/com/javarush/task/task11/task1109/Solution.java | Java | gpl-2.0 | 1,210 |
<?php
/**
* Lost password form
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php wc_print_notices(); ?>
<section id="content">
<form method="post" class="form lost_reset_password">
<?php if( 'lost_password' == $args['form'] ) : ?>
<p class="red"><?php echo apply_filters( 'woocommerce_lost_password_message', __( 'Lost your password? Please enter your username or email address. You will receive a link to create a new password via email.', 'woocommerce' ) ); ?></p>
<!--<p class="form-row form-row-first"><label for="user_login"><?php _e( 'Username or email', 'woocommerce' ); ?></label> <input class="input-text" type="text" name="user_login" id="user_login" /></p>-->
<div class="col">
<div class="left">
<input class="input-text" type="text" name="user_login" id="user_login" placeholder="Username or email" />
</div>
</div>
<?php else : ?>
<p><?php echo apply_filters( 'woocommerce_reset_password_message', __( 'Enter a new password below.', 'woocommerce') ); ?></p>
<!--
<p class="form-row form-row-first">
<label for="password_1"><?php _e( 'New password', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="password" class="email" name="password_1" id="password_1" />
</p>
<p class="form-row form-row-last">
<label for="password_2"><?php _e( 'Re-enter new password', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="password" class="input-text" name="password_2" id="password_2" />
</p>-->
<div class="col">
<div class="left">
<input type="password" class="email" name="password_1" id="password_1" placeholder="Password*" />
</div>
</div>
<div class="col">
<div class="left">
<input type="password" class="input-text" name="password_2" id="password_2" placeholder="Re-enter Password*" />
</div>
</div>
<input type="hidden" name="reset_key" value="<?php echo isset( $args['key'] ) ? $args['key'] : ''; ?>" />
<input type="hidden" name="reset_login" value="<?php echo isset( $args['login'] ) ? $args['login'] : ''; ?>" />
<?php endif; ?>
<div class="clear"></div>
<div class="col">
<div class="left">
<input type="submit" class="button" name="wc_reset_password" value="<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>" />
</div>
</div>
<!--<p class="form-row"><input type="submit" class="button" name="wc_reset_password" value="<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>" /></p>-->
<?php wp_nonce_field( $args['form'] ); ?>
</form>
</section>
<script type="text/javascript">
jQuery('#reg_passmail').html('');
jQuery('#reg_passmail').append('<div class="col"></div>');
</script> | kamil-incubasys/carpets | wp-content/plugins/woocommerce/templates/myaccount/form-lost-password.php | PHP | gpl-2.0 | 3,174 |
<?php
/**
* @package FOF
* @copyright Copyright (c)2010-2020 Nicholas K. Dionysopoulos / Akeeba Ltd
* @license GNU General Public License version 2, or later
*/
namespace FOF30\Less\Parser;
use FOF30\Less\Less;
use Exception;
defined('_JEXEC') or die;
/**
* This class is taken verbatim from:
*
* lessphp v0.3.9
* http://leafo.net/lessphp
*
* LESS css compiler, adapted from http://lesscss.org
*
* Copyright 2012, Leaf Corcoran <leafot@gmail.com>
* Licensed under MIT or GPLv3, see LICENSE
*
* Responsible for taking a string of LESS code and converting it into a syntax tree
*
* @since 2.0
*/
class Parser
{
// Used to uniquely identify blocks
protected static $nextBlockId = 0;
protected static $precedence = array(
'=<' => 0,
'>=' => 0,
'=' => 0,
'<' => 0,
'>' => 0,
'+' => 1,
'-' => 1,
'*' => 2,
'/' => 2,
'%' => 2,
);
protected static $whitePattern;
protected static $commentMulti;
protected static $commentSingle = "//";
protected static $commentMultiLeft = "/*";
protected static $commentMultiRight = "*/";
// Regex string to match any of the operators
protected static $operatorString;
// These properties will supress division unless it's inside parenthases
protected static $supressDivisionProps = array('/border-radius$/i', '/^font$/i');
protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document");
protected $lineDirectives = array("charset");
/**
* if we are in parens we can be more liberal with whitespace around
* operators because it must resolve to a single value and thus is less
* ambiguous.
*
* Consider:
* property1: 10 -5; // is two numbers, 10 and -5
* property2: (10 -5); // should resolve to 5
*/
protected $inParens = false;
// Caches preg escaped literals
protected static $literalCache = array();
/**
* Constructor
*
* @param [type] $lessc [description]
* @param string $sourceName [description]
*/
public function __construct($lessc, $sourceName = null)
{
$this->eatWhiteDefault = true;
// Reference to less needed for vPrefix, mPrefix, and parentSelector
$this->lessc = $lessc;
// Name used for error messages
$this->sourceName = $sourceName;
$this->writeComments = false;
if (!self::$operatorString)
{
self::$operatorString = '(' . implode('|', array_map(array('\\FOF30\\Less\\Less', 'preg_quote'), array_keys(self::$precedence))) . ')';
$commentSingle = Less::preg_quote(self::$commentSingle);
$commentMultiLeft = Less::preg_quote(self::$commentMultiLeft);
$commentMultiRight = Less::preg_quote(self::$commentMultiRight);
self::$commentMulti = $commentMultiLeft . '.*?' . $commentMultiRight;
self::$whitePattern = '/' . $commentSingle . '[^\n]*\s*|(' . self::$commentMulti . ')\s*|\s+/Ais';
}
}
/**
* Parse text
*
* @param string $buffer [description]
*
* @return [type] [description]
*/
public function parse($buffer)
{
$this->count = 0;
$this->line = 1;
// Block stack
$this->env = null;
$this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
$this->pushSpecialBlock("root");
$this->eatWhiteDefault = true;
$this->seenComments = array();
/*
* trim whitespace on head
* if (preg_match('/^\s+/', $this->buffer, $m)) {
* $this->line += substr_count($m[0], "\n");
* $this->buffer = ltrim($this->buffer);
* }
*/
$this->whitespace();
// Parse the entire file
$lastCount = $this->count;
while (false !== $this->parseChunk());
if ($this->count != strlen($this->buffer))
{
$this->throwError();
}
// TODO report where the block was opened
if (!is_null($this->env->parent))
{
throw new exception('parse error: unclosed block');
}
return $this->env;
}
/**
* Parse a single chunk off the head of the buffer and append it to the
* current parse environment.
* Returns false when the buffer is empty, or when there is an error.
*
* This function is called repeatedly until the entire document is
* parsed.
*
* This parser is most similar to a recursive descent parser. Single
* functions represent discrete grammatical rules for the language, and
* they are able to capture the text that represents those rules.
*
* Consider the function lessc::keyword(). (all parse functions are
* structured the same)
*
* The function takes a single reference argument. When calling the
* function it will attempt to match a keyword on the head of the buffer.
* If it is successful, it will place the keyword in the referenced
* argument, advance the position in the buffer, and return true. If it
* fails then it won't advance the buffer and it will return false.
*
* All of these parse functions are powered by lessc::match(), which behaves
* the same way, but takes a literal regular expression. Sometimes it is
* more convenient to use match instead of creating a new function.
*
* Because of the format of the functions, to parse an entire string of
* grammatical rules, you can chain them together using &&.
*
* But, if some of the rules in the chain succeed before one fails, then
* the buffer position will be left at an invalid state. In order to
* avoid this, lessc::seek() is used to remember and set buffer positions.
*
* Before parsing a chain, use $s = $this->seek() to remember the current
* position into $s. Then if a chain fails, use $this->seek($s) to
* go back where we started.
*
* @return boolean
*/
protected function parseChunk()
{
if (empty($this->buffer))
{
return false;
}
$s = $this->seek();
// Setting a property
if ($this->keyword($key) && $this->assign()
&& $this->propertyValue($value, $key) && $this->end())
{
$this->append(array('assign', $key, $value), $s);
return true;
}
else
{
$this->seek($s);
}
// Look for special css blocks
if ($this->literal('@', false))
{
$this->count--;
// Media
if ($this->literal('@media'))
{
if (($this->mediaQueryList($mediaQueries) || true)
&& $this->literal('{'))
{
$media = $this->pushSpecialBlock("media");
$media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
return true;
}
else
{
$this->seek($s);
return false;
}
}
if ($this->literal("@", false) && $this->keyword($dirName))
{
if ($this->isDirective($dirName, $this->blockDirectives))
{
if (($this->openString("{", $dirValue, null, array(";")) || true)
&& $this->literal("{"))
{
$dir = $this->pushSpecialBlock("directive");
$dir->name = $dirName;
if (isset($dirValue))
{
$dir->value = $dirValue;
}
return true;
}
}
elseif ($this->isDirective($dirName, $this->lineDirectives))
{
if ($this->propertyValue($dirValue) && $this->end())
{
$this->append(array("directive", $dirName, $dirValue));
return true;
}
}
}
$this->seek($s);
}
// Setting a variable
if ($this->variable($var) && $this->assign()
&& $this->propertyValue($value) && $this->end())
{
$this->append(array('assign', $var, $value), $s);
return true;
}
else
{
$this->seek($s);
}
if ($this->import($importValue))
{
$this->append($importValue, $s);
return true;
}
// Opening parametric mixin
if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg)
&& ($this->guards($guards) || true)
&& $this->literal('{'))
{
$block = $this->pushBlock($this->fixTags(array($tag)));
$block->args = $args;
$block->isVararg = $isVararg;
if (!empty($guards))
{
$block->guards = $guards;
}
return true;
}
else
{
$this->seek($s);
}
// Opening a simple block
if ($this->tags($tags) && $this->literal('{'))
{
$tags = $this->fixTags($tags);
$this->pushBlock($tags);
return true;
}
else
{
$this->seek($s);
}
// Closing a block
if ($this->literal('}', false))
{
try
{
$block = $this->pop();
}
catch (exception $e)
{
$this->seek($s);
$this->throwError($e->getMessage());
}
$hidden = false;
if (is_null($block->type))
{
$hidden = true;
if (!isset($block->args))
{
foreach ($block->tags as $tag)
{
if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix)
{
$hidden = false;
break;
}
}
}
foreach ($block->tags as $tag)
{
if (is_string($tag))
{
$this->env->children[$tag][] = $block;
}
}
}
if (!$hidden)
{
$this->append(array('block', $block), $s);
}
// This is done here so comments aren't bundled into he block that was just closed
$this->whitespace();
return true;
}
// Mixin
if ($this->mixinTags($tags)
&& ($this->argumentValues($argv) || true)
&& ($this->keyword($suffix) || true)
&& $this->end())
{
$tags = $this->fixTags($tags);
$this->append(array('mixin', $tags, $argv, $suffix), $s);
return true;
}
else
{
$this->seek($s);
}
// Spare ;
if ($this->literal(';'))
{
return true;
}
// Got nothing, throw error
return false;
}
/**
* [isDirective description]
*
* @param string $dirname [description]
* @param [type] $directives [description]
*
* @return boolean
*/
protected function isDirective($dirname, $directives)
{
// TODO: cache pattern in parser
$pattern = implode("|", array_map(array("\\FOF30\\Less\\Less", "preg_quote"), $directives));
$pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
return preg_match($pattern, $dirname);
}
/**
* [fixTags description]
*
* @param [type] $tags [description]
*
* @return [type] [description]
*/
protected function fixTags($tags)
{
// Move @ tags out of variable namespace
foreach ($tags as &$tag)
{
if ($tag[0] == $this->lessc->vPrefix)
{
$tag[0] = $this->lessc->mPrefix;
}
}
return $tags;
}
/**
* a list of expressions
*
* @param [type] &$exps [description]
*
* @return boolean
*/
protected function expressionList(&$exps)
{
$values = array();
while ($this->expression($exp))
{
$values[] = $exp;
}
if (count($values) == 0)
{
return false;
}
$exps = Less::compressList($values, ' ');
return true;
}
/**
* Attempt to consume an expression.
*
* @param string &$out [description]
*
* @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
*
* @return boolean
*/
protected function expression(&$out)
{
if ($this->value($lhs))
{
$out = $this->expHelper($lhs, 0);
// Look for / shorthand
if (!empty($this->env->supressedDivision))
{
unset($this->env->supressedDivision);
$s = $this->seek();
if ($this->literal("/") && $this->value($rhs))
{
$out = array("list", "",
array($out, array("keyword", "/"), $rhs));
}
else
{
$this->seek($s);
}
}
return true;
}
return false;
}
/**
* Recursively parse infix equation with $lhs at precedence $minP
*
* @param type $lhs [description]
* @param type $minP [description]
*
* @return string
*/
protected function expHelper($lhs, $minP)
{
$this->inExp = true;
$ss = $this->seek();
while (true)
{
$whiteBefore = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]);
// If there is whitespace before the operator, then we require
// whitespace after the operator for it to be an expression
$needWhite = $whiteBefore && !$this->inParens;
if ($this->match(self::$operatorString . ($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP)
{
if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision))
{
foreach (self::$supressDivisionProps as $pattern)
{
if (preg_match($pattern, $this->env->currentProperty))
{
$this->env->supressedDivision = true;
break 2;
}
}
}
$whiteAfter = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]);
if (!$this->value($rhs))
{
break;
}
// Peek for next operator to see what to do with rhs
if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]])
{
$rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
}
$lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
$ss = $this->seek();
continue;
}
break;
}
$this->seek($ss);
return $lhs;
}
/**
* Consume a list of values for a property
*
* @param [type] &$value [description]
* @param [type] $keyName [description]
*
* @return boolean
*/
public function propertyValue(&$value, $keyName = null)
{
$values = array();
if ($keyName !== null)
{
$this->env->currentProperty = $keyName;
}
$s = null;
while ($this->expressionList($v))
{
$values[] = $v;
$s = $this->seek();
if (!$this->literal(','))
{
break;
}
}
if ($s)
{
$this->seek($s);
}
if ($keyName !== null)
{
unset($this->env->currentProperty);
}
if (count($values) == 0)
{
return false;
}
$value = Less::compressList($values, ', ');
return true;
}
/**
* [parenValue description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function parenValue(&$out)
{
$s = $this->seek();
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(")
{
return false;
}
$inParens = $this->inParens;
if ($this->literal("(") && ($this->inParens = true) && $this->expression($exp) && $this->literal(")"))
{
$out = $exp;
$this->inParens = $inParens;
return true;
}
else
{
$this->inParens = $inParens;
$this->seek($s);
}
return false;
}
/**
* a single value
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function value(&$value)
{
$s = $this->seek();
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-")
{
// Negation
if ($this->literal("-", false) &&(($this->variable($inner) && $inner = array("variable", $inner))
|| $this->unit($inner) || $this->parenValue($inner)))
{
$value = array("unary", "-", $inner);
return true;
}
else
{
$this->seek($s);
}
}
if ($this->parenValue($value))
{
return true;
}
if ($this->unit($value))
{
return true;
}
if ($this->color($value))
{
return true;
}
if ($this->func($value))
{
return true;
}
if ($this->string($value))
{
return true;
}
if ($this->keyword($word))
{
$value = array('keyword', $word);
return true;
}
// Try a variable
if ($this->variable($var))
{
$value = array('variable', $var);
return true;
}
// Unquote string (should this work on any type?
if ($this->literal("~") && $this->string($str))
{
$value = array("escape", $str);
return true;
}
else
{
$this->seek($s);
}
// Css hack: \0
if ($this->literal('\\') && $this->match('([0-9]+)', $m))
{
$value = array('keyword', '\\' . $m[1]);
return true;
}
else
{
$this->seek($s);
}
return false;
}
/**
* an import statement
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function import(&$out)
{
$s = $this->seek();
if (!$this->literal('@import'))
{
return false;
}
/*
* @import "something.css" media;
* @import url("something.css") media;
* @import url(something.css) media;
*/
if ($this->propertyValue($value))
{
$out = array("import", $value);
return true;
}
}
/**
* [mediaQueryList description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function mediaQueryList(&$out)
{
if ($this->genericList($list, "mediaQuery", ",", false))
{
$out = $list[2];
return true;
}
return false;
}
/**
* [mediaQuery description]
*
* @param [type] &$out [description]
*
* @return [type] [description]
*/
protected function mediaQuery(&$out)
{
$s = $this->seek();
$expressions = null;
$parts = array();
if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType))
{
$prop = array("mediaType");
if (isset($only))
{
$prop[] = "only";
}
if (isset($not))
{
$prop[] = "not";
}
$prop[] = $mediaType;
$parts[] = $prop;
}
else
{
$this->seek($s);
}
if (!empty($mediaType) && !$this->literal("and"))
{
// ~
}
else
{
$this->genericList($expressions, "mediaExpression", "and", false);
if (is_array($expressions))
{
$parts = array_merge($parts, $expressions[2]);
}
}
if (count($parts) == 0)
{
$this->seek($s);
return false;
}
$out = $parts;
return true;
}
/**
* [mediaExpression description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function mediaExpression(&$out)
{
$s = $this->seek();
$value = null;
if ($this->literal("(") && $this->keyword($feature) && ($this->literal(":")
&& $this->expression($value) || true) && $this->literal(")"))
{
$out = array("mediaExp", $feature);
if ($value)
{
$out[] = $value;
}
return true;
}
elseif ($this->variable($variable))
{
$out = array('variable', $variable);
return true;
}
$this->seek($s);
return false;
}
/**
* An unbounded string stopped by $end
*
* @param [type] $end [description]
* @param [type] &$out [description]
* @param [type] $nestingOpen [description]
* @param [type] $rejectStrs [description]
*
* @return boolean
*/
protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
$stop = array("'", '"', "@{", $end);
$stop = array_map(array("\\FOF30\\Less\\Less", "preg_quote"), $stop);
// $stop[] = self::$commentMulti;
if (!is_null($rejectStrs))
{
$stop = array_merge($stop, $rejectStrs);
}
$patt = '(.*?)(' . implode("|", $stop) . ')';
$nestingLevel = 0;
$content = array();
while ($this->match($patt, $m, false))
{
if (!empty($m[1]))
{
$content[] = $m[1];
if ($nestingOpen)
{
$nestingLevel += substr_count($m[1], $nestingOpen);
}
}
$tok = $m[2];
$this->count -= strlen($tok);
if ($tok == $end)
{
if ($nestingLevel == 0)
{
break;
}
else
{
$nestingLevel--;
}
}
if (($tok == "'" || $tok == '"') && $this->string($str))
{
$content[] = $str;
continue;
}
if ($tok == "@{" && $this->interpolation($inter))
{
$content[] = $inter;
continue;
}
if (in_array($tok, $rejectStrs))
{
$count = null;
break;
}
$content[] = $tok;
$this->count += strlen($tok);
}
$this->eatWhiteDefault = $oldWhite;
if (count($content) == 0)
return false;
// Trim the end
if (is_string(end($content)))
{
$content[count($content) - 1] = rtrim(end($content));
}
$out = array("string", "", $content);
return true;
}
/**
* [string description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function string(&$out)
{
$s = $this->seek();
if ($this->literal('"', false))
{
$delim = '"';
}
elseif ($this->literal("'", false))
{
$delim = "'";
}
else
{
return false;
}
$content = array();
// Look for either ending delim , escape, or string interpolation
$patt = '([^\n]*?)(@\{|\\\\|' . Less::preg_quote($delim) . ')';
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
while ($this->match($patt, $m, false))
{
$content[] = $m[1];
if ($m[2] == "@{")
{
$this->count -= strlen($m[2]);
if ($this->interpolation($inter, false))
{
$content[] = $inter;
}
else
{
$this->count += strlen($m[2]);
// Ignore it
$content[] = "@{";
}
}
elseif ($m[2] == '\\')
{
$content[] = $m[2];
if ($this->literal($delim, false))
{
$content[] = $delim;
}
}
else
{
$this->count -= strlen($delim);
// Delim
break;
}
}
$this->eatWhiteDefault = $oldWhite;
if ($this->literal($delim))
{
$out = array("string", $delim, $content);
return true;
}
$this->seek($s);
return false;
}
/**
* [interpolation description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function interpolation(&$out)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = true;
$s = $this->seek();
if ($this->literal("@{") && $this->openString("}", $interp, null, array("'", '"', ";")) && $this->literal("}", false))
{
$out = array("interpolate", $interp);
$this->eatWhiteDefault = $oldWhite;
if ($this->eatWhiteDefault)
{
$this->whitespace();
}
return true;
}
$this->eatWhiteDefault = $oldWhite;
$this->seek($s);
return false;
}
/**
* [unit description]
*
* @param [type] &$unit [description]
*
* @return boolean
*/
protected function unit(&$unit)
{
// Speed shortcut
if (isset($this->buffer[$this->count]))
{
$char = $this->buffer[$this->count];
if (!ctype_digit($char) && $char != ".")
{
return false;
}
}
if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m))
{
$unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
return true;
}
return false;
}
/**
* a # color
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function color(&$out)
{
if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m))
{
if (strlen($m[1]) > 7)
{
$out = array("string", "", array($m[1]));
}
else
{
$out = array("raw_color", $m[1]);
}
return true;
}
return false;
}
/**
* Consume a list of property values delimited by ; and wrapped in ()
*
* @param [type] &$args [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function argumentValues(&$args, $delim = ',')
{
$s = $this->seek();
if (!$this->literal('('))
{
return false;
}
$values = array();
while (true)
{
if ($this->expressionList($value))
{
$values[] = $value;
}
if (!$this->literal($delim))
{
break;
}
else
{
if ($value == null)
{
$values[] = null;
}
$value = null;
}
}
if (!$this->literal(')'))
{
$this->seek($s);
return false;
}
$args = $values;
return true;
}
/**
* Consume an argument definition list surrounded by ()
* each argument is a variable name with optional value
* or at the end a ... or a variable named followed by ...
*
* @param [type] &$args [description]
* @param [type] &$isVararg [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function argumentDef(&$args, &$isVararg, $delim = ',')
{
$s = $this->seek();
if (!$this->literal('('))
return false;
$values = array();
$isVararg = false;
while (true)
{
if ($this->literal("..."))
{
$isVararg = true;
break;
}
if ($this->variable($vname))
{
$arg = array("arg", $vname);
$ss = $this->seek();
if ($this->assign() && $this->expressionList($value))
{
$arg[] = $value;
}
else
{
$this->seek($ss);
if ($this->literal("..."))
{
$arg[0] = "rest";
$isVararg = true;
}
}
$values[] = $arg;
if ($isVararg)
{
break;
}
continue;
}
if ($this->value($literal))
{
$values[] = array("lit", $literal);
}
if (!$this->literal($delim))
{
break;
}
}
if (!$this->literal(')'))
{
$this->seek($s);
return false;
}
$args = $values;
return true;
}
/**
* Consume a list of tags
* This accepts a hanging delimiter
*
* @param [type] &$tags [description]
* @param [type] $simple [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function tags(&$tags, $simple = false, $delim = ',')
{
$tags = array();
while ($this->tag($tt, $simple))
{
$tags[] = $tt;
if (!$this->literal($delim))
{
break;
}
}
if (count($tags) == 0)
{
return false;
}
return true;
}
/**
* List of tags of specifying mixin path
* Optionally separated by > (lazy, accepts extra >)
*
* @param [type] &$tags [description]
*
* @return boolean
*/
protected function mixinTags(&$tags)
{
$s = $this->seek();
$tags = array();
while ($this->tag($tt, true))
{
$tags[] = $tt;
$this->literal(">");
}
if (count($tags) == 0)
{
return false;
}
return true;
}
/**
* A bracketed value (contained within in a tag definition)
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function tagBracket(&$value)
{
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[")
{
return false;
}
$s = $this->seek();
if ($this->literal('[') && $this->to(']', $c, true) && $this->literal(']', false))
{
$value = '[' . $c . ']';
// Whitespace?
if ($this->whitespace())
{
$value .= " ";
}
// Escape parent selector, (yuck)
$value = str_replace($this->lessc->parentSelector, "$&$", $value);
return true;
}
$this->seek($s);
return false;
}
/**
* [tagExpression description]
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function tagExpression(&$value)
{
$s = $this->seek();
if ($this->literal("(") && $this->expression($exp) && $this->literal(")"))
{
$value = array('exp', $exp);
return true;
}
$this->seek($s);
return false;
}
/**
* A single tag
*
* @param [type] &$tag [description]
* @param boolean $simple [description]
*
* @return boolean
*/
protected function tag(&$tag, $simple = false)
{
if ($simple)
{
$chars = '^@,:;{}\][>\(\) "\'';
}
else
{
$chars = '^@,;{}["\'';
}
$s = $this->seek();
if (!$simple && $this->tagExpression($tag))
{
return true;
}
$hasExpression = false;
$parts = array();
while ($this->tagBracket($first))
{
$parts[] = $first;
}
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
while (true)
{
if ($this->match('([' . $chars . '0-9][' . $chars . ']*)', $m))
{
$parts[] = $m[1];
if ($simple)
{
break;
}
while ($this->tagBracket($brack))
{
$parts[] = $brack;
}
continue;
}
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@")
{
if ($this->interpolation($interp))
{
$hasExpression = true;
// Don't unescape
$interp[2] = true;
$parts[] = $interp;
continue;
}
if ($this->literal("@"))
{
$parts[] = "@";
continue;
}
}
// For keyframes
if ($this->unit($unit))
{
$parts[] = $unit[1];
$parts[] = $unit[2];
continue;
}
break;
}
$this->eatWhiteDefault = $oldWhite;
if (!$parts)
{
$this->seek($s);
return false;
}
if ($hasExpression)
{
$tag = array("exp", array("string", "", $parts));
}
else
{
$tag = trim(implode($parts));
}
$this->whitespace();
return true;
}
/**
* A css function
*
* @param [type] &$func [description]
*
* @return boolean
*/
protected function func(&$func)
{
$s = $this->seek();
if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('('))
{
$fname = $m[1];
$sPreArgs = $this->seek();
$args = array();
while (true)
{
$ss = $this->seek();
// This ugly nonsense is for ie filter properties
if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value))
{
$args[] = array("string", "", array($name, "=", $value));
}
else
{
$this->seek($ss);
if ($this->expressionList($value))
{
$args[] = $value;
}
}
if (!$this->literal(','))
{
break;
}
}
$args = array('list', ',', $args);
if ($this->literal(')'))
{
$func = array('function', $fname, $args);
return true;
}
elseif ($fname == 'url')
{
// Couldn't parse and in url? treat as string
$this->seek($sPreArgs);
if ($this->openString(")", $string) && $this->literal(")"))
{
$func = array('function', $fname, $string);
return true;
}
}
}
$this->seek($s);
return false;
}
/**
* Consume a less variable
*
* @param [type] &$name [description]
*
* @return boolean
*/
protected function variable(&$name)
{
$s = $this->seek();
if ($this->literal($this->lessc->vPrefix, false) && ($this->variable($sub) || $this->keyword($name)))
{
if (!empty($sub))
{
$name = array('variable', $sub);
}
else
{
$name = $this->lessc->vPrefix . $name;
}
return true;
}
$name = null;
$this->seek($s);
return false;
}
/**
* Consume an assignment operator
* Can optionally take a name that will be set to the current property name
*
* @param string $name [description]
*
* @return boolean
*/
protected function assign($name = null)
{
if ($name)
{
$this->currentProperty = $name;
}
return $this->literal(':') || $this->literal('=');
}
/**
* Consume a keyword
*
* @param [type] &$word [description]
*
* @return boolean
*/
protected function keyword(&$word)
{
if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m))
{
$word = $m[1];
return true;
}
return false;
}
/**
* Consume an end of statement delimiter
*
* @return boolean
*/
protected function end()
{
if ($this->literal(';'))
{
return true;
}
elseif ($this->count == strlen($this->buffer) || $this->buffer{$this->count} == '}')
{
// If there is end of file or a closing block next then we don't need a ;
return true;
}
return false;
}
/**
* [guards description]
*
* @param [type] &$guards [description]
*
* @return boolean
*/
protected function guards(&$guards)
{
$s = $this->seek();
if (!$this->literal("when"))
{
$this->seek($s);
return false;
}
$guards = array();
while ($this->guardGroup($g))
{
$guards[] = $g;
if (!$this->literal(","))
{
break;
}
}
if (count($guards) == 0)
{
$guards = null;
$this->seek($s);
return false;
}
return true;
}
/**
* A bunch of guards that are and'd together
*
* @param [type] &$guardGroup [description]
*
* @todo rename to guardGroup
*
* @return boolean
*/
protected function guardGroup(&$guardGroup)
{
$s = $this->seek();
$guardGroup = array();
while ($this->guard($guard))
{
$guardGroup[] = $guard;
if (!$this->literal("and"))
{
break;
}
}
if (count($guardGroup) == 0)
{
$guardGroup = null;
$this->seek($s);
return false;
}
return true;
}
/**
* [guard description]
*
* @param [type] &$guard [description]
*
* @return boolean
*/
protected function guard(&$guard)
{
$s = $this->seek();
$negate = $this->literal("not");
if ($this->literal("(") && $this->expression($exp) && $this->literal(")"))
{
$guard = $exp;
if ($negate)
{
$guard = array("negate", $guard);
}
return true;
}
$this->seek($s);
return false;
}
/* raw parsing functions */
/**
* [literal description]
*
* @param [type] $what [description]
* @param [type] $eatWhitespace [description]
*
* @return boolean
*/
protected function literal($what, $eatWhitespace = null)
{
if ($eatWhitespace === null)
{
$eatWhitespace = $this->eatWhiteDefault;
}
// Shortcut on single letter
if (!isset($what[1]) && isset($this->buffer[$this->count]))
{
if ($this->buffer[$this->count] == $what)
{
if (!$eatWhitespace)
{
$this->count++;
return true;
}
}
else
{
return false;
}
}
if (!isset(self::$literalCache[$what]))
{
self::$literalCache[$what] = Less::preg_quote($what);
}
return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
}
/**
* [genericList description]
*
* @param [type] &$out [description]
* @param [type] $parseItem [description]
* @param string $delim [description]
* @param boolean $flatten [description]
*
* @return boolean
*/
protected function genericList(&$out, $parseItem, $delim = "", $flatten = true)
{
$s = $this->seek();
$items = array();
while ($this->$parseItem($value))
{
$items[] = $value;
if ($delim)
{
if (!$this->literal($delim))
{
break;
}
}
}
if (count($items) == 0)
{
$this->seek($s);
return false;
}
if ($flatten && count($items) == 1)
{
$out = $items[0];
}
else
{
$out = array("list", $delim, $items);
}
return true;
}
/**
* Advance counter to next occurrence of $what
* $until - don't include $what in advance
* $allowNewline, if string, will be used as valid char set
*
* @param [type] $what [description]
* @param [type] &$out [description]
* @param boolean $until [description]
* @param boolean $allowNewline [description]
*
* @return boolean
*/
protected function to($what, &$out, $until = false, $allowNewline = false)
{
if (is_string($allowNewline))
{
$validChars = $allowNewline;
}
else
{
$validChars = $allowNewline ? "." : "[^\n]";
}
if (!$this->match('(' . $validChars . '*?)' . Less::preg_quote($what), $m, !$until))
{
return false;
}
if ($until)
{
// Give back $what
$this->count -= strlen($what);
}
$out = $m[1];
return true;
}
/**
* Try to match something on head of buffer
*
* @param [type] $regex [description]
* @param [type] &$out [description]
* @param [type] $eatWhitespace [description]
*
* @return boolean
*/
protected function match($regex, &$out, $eatWhitespace = null)
{
if ($eatWhitespace === null)
{
$eatWhitespace = $this->eatWhiteDefault;
}
$r = '/' . $regex . ($eatWhitespace && !$this->writeComments ? '\s*' : '') . '/Ais';
if (preg_match($r, $this->buffer, $out, null, $this->count))
{
$this->count += strlen($out[0]);
if ($eatWhitespace && $this->writeComments)
{
$this->whitespace();
}
return true;
}
return false;
}
/**
* Watch some whitespace
*
* @return boolean
*/
protected function whitespace()
{
if ($this->writeComments)
{
$gotWhite = false;
while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count))
{
if (isset($m[1]) && empty($this->commentsSeen[$this->count]))
{
$this->append(array("comment", $m[1]));
$this->commentsSeen[$this->count] = true;
}
$this->count += strlen($m[0]);
$gotWhite = true;
}
return $gotWhite;
}
else
{
$this->match("", $m);
return strlen($m[0]) > 0;
}
}
/**
* Match something without consuming it
*
* @param [type] $regex [description]
* @param [type] &$out [description]
* @param [type] $from [description]
*
* @return boolean
*/
protected function peek($regex, &$out = null, $from = null)
{
if (is_null($from))
{
$from = $this->count;
}
$r = '/' . $regex . '/Ais';
$result = preg_match($r, $this->buffer, $out, null, $from);
return $result;
}
/**
* Seek to a spot in the buffer or return where we are on no argument
*
* @param [type] $where [description]
*
* @return boolean
*/
protected function seek($where = null)
{
if ($where === null)
{
return $this->count;
}
else
{
$this->count = $where;
}
return true;
}
/* misc functions */
/**
* [throwError description]
*
* @param string $msg [description]
* @param [type] $count [description]
*
* @return void
*/
public function throwError($msg = "parse error", $count = null)
{
$count = is_null($count) ? $this->count : $count;
$line = $this->line + substr_count(substr($this->buffer, 0, $count), "\n");
if (!empty($this->sourceName))
{
$loc = "$this->sourceName on line $line";
}
else
{
$loc = "line: $line";
}
// TODO this depends on $this->count
if ($this->peek("(.*?)(\n|$)", $m, $count))
{
throw new exception("$msg: failed at `$m[1]` $loc");
}
else
{
throw new exception("$msg: $loc");
}
}
/**
* [pushBlock description]
*
* @param [type] $selectors [description]
* @param [type] $type [description]
*
* @return \stdClass
*/
protected function pushBlock($selectors = null, $type = null)
{
$b = new \stdClass;
$b->parent = $this->env;
$b->type = $type;
$b->id = self::$nextBlockId++;
// TODO: kill me from here
$b->isVararg = false;
$b->tags = $selectors;
$b->props = array();
$b->children = array();
$this->env = $b;
return $b;
}
/**
* Push a block that doesn't multiply tags
*
* @param [type] $type [description]
*
* @return \stdClass
*/
protected function pushSpecialBlock($type)
{
return $this->pushBlock(null, $type);
}
/**
* Append a property to the current block
*
* @param [type] $prop [description]
* @param [type] $pos [description]
*
* @return void
*/
protected function append($prop, $pos = null)
{
if ($pos !== null)
{
$prop[-1] = $pos;
}
$this->env->props[] = $prop;
}
/**
* Pop something off the stack
*
* @return [type] [description]
*/
protected function pop()
{
$old = $this->env;
$this->env = $this->env->parent;
return $old;
}
/**
* Remove comments from $text
*
* @param [type] $text [description]
*
* @todo: make it work for all functions, not just url
*
* @return [type] [description]
*/
protected function removeComments($text)
{
$look = array(
'url(', '//', '/*', '"', "'"
);
$out = '';
$min = null;
while (true)
{
// Find the next item
foreach ($look as $token)
{
$pos = strpos($text, $token);
if ($pos !== false)
{
if (!isset($min) || $pos < $min[1])
{
$min = array($token, $pos);
}
}
}
if (is_null($min))
break;
$count = $min[1];
$skip = 0;
$newlines = 0;
switch ($min[0])
{
case 'url(':
if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
{
$count += strlen($m[0]) - strlen($min[0]);
}
break;
case '"':
case "'":
if (preg_match('/' . $min[0] . '.*?' . $min[0] . '/', $text, $m, 0, $count))
{
$count += strlen($m[0]) - 1;
}
break;
case '//':
$skip = strpos($text, "\n", $count);
if ($skip === false)
{
$skip = strlen($text) - $count;
}
else
{
$skip -= $count;
}
break;
case '/*':
if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count))
{
$skip = strlen($m[0]);
$newlines = substr_count($m[0], "\n");
}
break;
}
if ($skip == 0)
{
$count += strlen($min[0]);
}
$out .= substr($text, 0, $count) . str_repeat("\n", $newlines);
$text = substr($text, $count + $skip);
$min = null;
}
return $out . $text;
}
}
| pabloarias/Joomla3-Base | libraries/fof30/Less/Parser/Parser.php | PHP | gpl-2.0 | 39,937 |
namespace Rantory.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ChemicalType : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ChemicalTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.ChemicalTypes");
}
}
}
| NurymKenzh/Rantory | Rantory/Rantory/Migrations/201604220851182_ChemicalType.cs | C# | gpl-2.0 | 621 |
using Windows.UI.Xaml.Navigation;
using Vocabulary;
using Vocabulary.ViewModels;
namespace Vocabulary.Views
{
public sealed partial class HomePage : PageBase
{
public HomePage()
{
this.ViewModel = new MainViewModel(8);
this.InitializeComponent();
}
public MainViewModel ViewModel { get; set; }
protected async override void LoadState(object navParameter)
{
await this.ViewModel.LoadDataAsync();
}
}
}
| mabaer/norwegian | Vocabulary.W10/Views/HomePage.xaml.cs | C# | gpl-2.0 | 520 |
<?php
/**
* @version 1.0.0
* @package com_somosmaestros
* @copyright Copyright (C) 2015. Todos los derechos reservados.
* @license Licencia Pública General GNU versión 2 o posterior. Consulte LICENSE.txt
* @author Daniel Gustavo Álvarez Gaitán <info@danielalvarez.com.co> - http://danielalvarez.com.co
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
/**
* Methods supporting a list of Somosmaestros records.
*/
class SomosmaestrosModelFormacions extends JModelList
{
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
*
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'ordering', 'a.ordering',
'state', 'a.state',
'created_by', 'a.created_by',
'titulo', 'a.titulo',
'contenido', 'a.contenido',
'imagen_grande', 'a.imagen_grande',
'imagen_pequena', 'a.imagen_pequena',
'destacado', 'a.destacado',
'delegacion', 'a.delegacion',
'tipo_institucion', 'a.tipo_institucion',
'segmento', 'a.segmento',
'nivel', 'a.nivel',
'ciudad', 'a.ciudad',
'area', 'a.area',
'rol', 'a.rol',
'proyecto', 'a.proyecto',
'publico', 'a.publico',
'asistentes', 'a.asistentes',
'disponibilidad', 'a.disponibilidad',
'fuente', 'a.fuente',
'preview', 'a.preview',
);
}
parent::__construct($config);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication();
// List state information
$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'));
$this->setState('list.limit', $limit);
$limitstart = $app->input->getInt('limitstart', 0);
$this->setState('list.start', $limitstart);
if ($list = $app->getUserStateFromRequest($this->context . '.list', 'list', array(), 'array'))
{
foreach ($list as $name => $value)
{
// Extra validations
switch ($name)
{
case 'fullordering':
$orderingParts = explode(' ', $value);
if (count($orderingParts) >= 2)
{
// Latest part will be considered the direction
$fullDirection = end($orderingParts);
if (in_array(strtoupper($fullDirection), array('ASC', 'DESC', '')))
{
$this->setState('list.direction', $fullDirection);
}
unset($orderingParts[count($orderingParts) - 1]);
// The rest will be the ordering
$fullOrdering = implode(' ', $orderingParts);
if (in_array($fullOrdering, $this->filter_fields))
{
$this->setState('list.ordering', $fullOrdering);
}
}
else
{
$this->setState('list.ordering', $ordering);
$this->setState('list.direction', $direction);
}
break;
case 'ordering':
if (!in_array($value, $this->filter_fields))
{
$value = $ordering;
}
break;
case 'direction':
if (!in_array(strtoupper($value), array('ASC', 'DESC', '')))
{
$value = $direction;
}
break;
case 'limit':
$limit = $value;
break;
// Just to keep the default case
default:
$value = $value;
break;
}
$this->setState('list.' . $name, $value);
}
}
// Receive & set filters
if ($filters = $app->getUserStateFromRequest($this->context . '.filter', 'filter', array(), 'array'))
{
foreach ($filters as $name => $value)
{
$this->setState('filter.' . $name, $value);
}
}
$ordering = $app->input->get('filter_order');
if (!empty($ordering))
{
$list = $app->getUserState($this->context . '.list');
$list['ordering'] = $app->input->get('filter_order');
$app->setUserState($this->context . '.list', $list);
}
$orderingDirection = $app->input->get('filter_order_Dir');
if (!empty($orderingDirection))
{
$list = $app->getUserState($this->context . '.list');
$list['direction'] = $app->input->get('filter_order_Dir');
$app->setUserState($this->context . '.list', $list);
}
$list = $app->getUserState($this->context . '.list');
if (empty($list['ordering']))
{
$list['ordering'] = 'ordering';
}
if (empty($list['direction']))
{
$list['direction'] = 'asc';
}
$this->setState('list.ordering', $list['ordering']);
$this->setState('list.direction', $list['direction']);
}
/**
* Build an SQL query to load the list data.
*
* @return JDatabaseQuery
* @since 1.6
*/
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query
->select(
$this->getState(
'list.select', 'DISTINCT a.*'
)
);
$query->from('`#__somosmaestros_formacion` AS a');
// Join over the users for the checked out user.
$query->select('uc.name AS editor');
$query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
// Join over the created by field 'created_by'
$query->join('LEFT', '#__users AS created_by ON created_by.id = a.created_by');
if (!JFactory::getUser()->authorise('core.edit.state', 'com_somosmaestros'))
{
$query->where('a.state = 1');
}
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.id = ' . (int) substr($search, 3));
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.titulo LIKE '.$search.' OR a.delegacion LIKE '.$search.' OR a.tipo_institucion LIKE '.$search.' OR a.segmento LIKE '.$search.' OR a.nivel LIKE '.$search.' OR a.ciudad LIKE '.$search.' OR a.area LIKE '.$search.' OR a.rol LIKE '.$search.' OR a.proyecto LIKE '.$search.' )');
}
}
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering');
$orderDirn = $this->state->get('list.direction');
if ($orderCol && $orderDirn)
{
$query->order($db->escape($orderCol . ' ' . $orderDirn));
}
return $query;
}
public function getItems()
{
$items = parent::getItems();
return $items;
}
/**
* Overrides the default function to check Date fields format, identified by
* "_dateformat" suffix, and erases the field if it's not correct.
*/
protected function loadFormData()
{
$app = JFactory::getApplication();
$filters = $app->getUserState($this->context . '.filter', array());
$error_dateformat = false;
foreach ($filters as $key => $value)
{
if (strpos($key, '_dateformat') && !empty($value) && !$this->isValidDate($value))
{
$filters[$key] = '';
$error_dateformat = true;
}
}
if ($error_dateformat)
{
$app->enqueueMessage(JText::_("COM_SOMOSMAESTROS_SEARCH_FILTER_DATE_FORMAT"), "warning");
$app->setUserState($this->context . '.filter', $filters);
}
return parent::loadFormData();
}
/**
* Checks if a given date is valid and in an specified format (YYYY-MM-DD)
*
* @param string Contains the date to be checked
*
*/
private function isValidDate($date)
{
return preg_match("/^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/", $date) && date_create($date);
}
}
| emeraldstudio/somosmaestros | components/com_somosmaestros/models/formacions.php | PHP | gpl-2.0 | 7,857 |
class Admin::BadgesController < Admin::AdminController
def badge_types
badge_types = BadgeType.all.to_a
render_serialized(badge_types, BadgeTypeSerializer, root: "badge_types")
end
def create
badge = Badge.new
update_badge_from_params(badge)
badge.save!
render_serialized(badge, BadgeSerializer, root: "badge")
end
def update
badge = find_badge
update_badge_from_params(badge)
badge.save!
render_serialized(badge, BadgeSerializer, root: "badge")
end
def destroy
find_badge.destroy
render nothing: true
end
private
def find_badge
params.require(:id)
Badge.find(params[:id])
end
def update_badge_from_params(badge)
params.permit(:name, :description, :badge_type_id, :allow_title, :multiple_grant)
badge.name = params[:name]
badge.description = params[:description]
badge.badge_type = BadgeType.find(params[:badge_type_id])
badge.allow_title = params[:allow_title]
badge.multiple_grant = params[:multiple_grant]
badge.icon = params[:icon]
badge
end
end
| vipuldadhich/discourse | app/controllers/admin/badges_controller.rb | Ruby | gpl-2.0 | 1,097 |
<?php
class UsuarioController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Usuario;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Usuario']))
{
$model->attributes=$_POST['Usuario'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Usuario']))
{
$model->attributes=$_POST['Usuario'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Usuario');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Usuario('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Usuario']))
$model->attributes=$_GET['Usuario'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Usuario::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='usuario-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
| bbidesenvolvimento/dm | protected/controllers/UsuarioController.php | PHP | gpl-2.0 | 4,143 |
import web
urls = (
'/hello','Index'
)
app = web.application(urls,globals())
render = web.template.render('/usr/local/LPTHW/ex51/gothonweb/templates/',base="layout")
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="Nobody",greet="Hello")
greeting = "%s,%s" % (form.greet,form.name)
return render.index(greeting = greeting)
if __name__ == '__main__':
app.run()
| tridvaodin/Assignments-Valya-Maskaliova | LPTHW/projects/gothonweb/bin/app.py | Python | gpl-2.0 | 488 |
/*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.activation;
import java.io.IOException;
/**
* JavaBeans components that are Activation Framework aware implement
* this interface to find out which command verb they're being asked
* to perform, and to obtain the DataHandler representing the
* data they should operate on. JavaBeans that don't implement
* this interface may be used as well. Such commands may obtain
* the data using the Externalizable interface, or using an
* application-specific method.<p>
*
* @since 1.6
*/
public interface CommandObject {
/**
* Initialize the Command with the verb it is requested to handle
* and the DataHandler that describes the data it will
* operate on. <b>NOTE:</b> it is acceptable for the caller
* to pass <i>null</i> as the value for <code>DataHandler</code>.
*
* @param verb The Command Verb this object refers to.
* @param dh The DataHandler.
*/
public void setCommandContext(String verb, DataHandler dh)
throws IOException;
}
| TheTypoMaster/Scaper | openjdk/jaxws/drop_included/jaf_src/src/javax/activation/CommandObject.java | Java | gpl-2.0 | 2,259 |
package edu.xored.tracker;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Issue {
private String hash;
private String summary;
private String description;
private User author;
private Status status;
private LocalDateTime createdDateTime;
@JsonIgnore
private List<Comment> comments = new ArrayList<>();
public Issue() {
}
public Issue(String hash, String summary, String description, Status status) {
this.hash = hash;
this.summary = summary;
this.description = description;
this.status = status;
this.createdDateTime = LocalDateTime.now();
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public LocalDateTime getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(LocalDateTime createdDateTime) {
this.createdDateTime = createdDateTime;
}
public List<Comment> getComments() {
return Collections.unmodifiableList(comments);
}
public void addComment(Comment comment) {
if (comment != null) {
comments.add(comment);
}
}
public void addComments(Collection<Comment> comments) {
if (comments != null) {
this.comments.addAll(comments);
}
}
public Issue updateIssue(Issue other) {
if (other.getSummary() != null) {
setSummary(other.getSummary());
}
if (other.getDescription() != null) {
setDescription(other.getDescription());
}
if (other.getAuthor() != null) {
setAuthor(other.getAuthor());
}
if (other.getStatus() != null) {
setStatus(other.getStatus());
}
if (other.getCreatedDateTime() != null) {
setCreatedDateTime(other.getCreatedDateTime());
}
if (other.getComments() != null) {
addComments(other.getComments());
}
return this;
}
public enum Status {
OPEN, RESOLVED;
}
}
| edu-xored/tracker-web | src/main/java/edu/xored/tracker/Issue.java | Java | gpl-2.0 | 2,861 |
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="../css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="../css/install.css">
</head>
<body>
<div class="container container-fluid">
<div class="container container-fluid ">
<marquee><h1>Bienvenido A Cultura Caleña!</h1></marquee>
<p> <h2>Lo felicitamos usted a terminado la configuracion de su sistema con</h2>
<h3>Exito</h3>
</p>
<a href="../../web/" type="button" class="btn btn-primary">inicio</a>
</div>
</div>
</body>
</html>
| Kellin-Andrea/culturaCalena | installer/view/felicidades.html.php | PHP | gpl-2.0 | 858 |
/*
NEshare is a peer-to-peer file sharing toolkit.
Copyright (C) 2001, 2002 Neill Miller
This file is part of NEshare.
NEshare 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.
NEshare 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 NEshare; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "neclientheaders.h"
namespace neShareClientThreads
{
static ncThread s_processClientPeersThread;
static ncThread s_processServentPeersThread;
static ncThread s_clientListenerThread;
static ncThread s_processUploadsThread;
static int s_processClientPeersThreadStop = 0;
static int s_processServentPeersThreadStop = 0;
static int s_processUploadsThreadStop = 0;
static ncSocketListener *g_nsl = (ncSocketListener *)0;
/*
the following are defined only to store pointers to the
internal objects stored in the neClientConnection object
to use internally in this namespace
*/
static neConfig *g_config = (neConfig *)0;
static nePeerManager *g_peerClientManager = (nePeerManager *)0;
static nePeerManager *g_peerServentManager = (nePeerManager *)0;
static nePeerDownloadManager *g_peerDownloadManager =
(nePeerDownloadManager *)0;
static nePeerUploadManager *g_peerUploadManager =
(nePeerUploadManager *)0;
void *processLoginMessage(void *ptr)
{
ncSocket *newSock = (ncSocket *)ptr;
if (newSock)
{
/*
read the login message and return
an appropriate response
*/
nemsgPeerLogin peerLoginMsg(newSock);
if (peerLoginMsg.recv() == 0)
{
iprintf("neShareClientThreads::processLoginMessage | "
"Login Message Received.\n");
/*
FIXME: default TTL of connected peer is 300 seconds...
this should be configurable
*/
nePeer *newPeer = new nePeer(newSock,300);
if (newPeer)
{
if (g_peerServentManager->addPeer(newPeer))
{
eprintf("neShareClientThreads::processLoginMessa"
"ge | addPeer failed.\n");
neClientUtils::rejectNewServentPeer(newPeer);
newSock->flush();
delete newSock;
return (void *)0;
}
/* send a peer login ack */
nemsgPeerLoginAck peerLoginAckMsg(newSock);
if (peerLoginAckMsg.send() == 0)
{
iprintf("New Peer Added (addr = %x) - Total Count"
" is %d.\n",newPeer,
g_peerServentManager->getNumPeers());
newSock->flush();
}
}
else
{
eprintf("neShareClientThreads::processLoginMessage | "
"Cannot allocate new peer.\n");
}
}
else
{
/* drop the connection */
eprintf("neShareClientThreads::processLoginMessage | "
"Login Message not received.\n");
delete newSock;
}
}
return (void *)0;
}
void *listenForClients(void *ptr)
{
unsigned long clientControlPort = 0;
assert(g_config);
clientControlPort = g_config->getClientControlPort();
/*
create a ncSocketListener and register a callback that will
add a new user to the client peerManager (similar to the
userManager in the server).
*/
if (g_nsl)
{
eprintf("FIXME: neShareClientThreads::listenForClients "
"called with an already initialized socket "
"listener object -- terminating\n");
assert(0);
}
g_nsl = new ncSocketListener(clientControlPort,SOCKTYPE_TCPIP);
if (g_nsl &&
g_nsl->startListening(processLoginMessage, NC_NONTHREADED,
NC_REUSEADDR) != NC_OK)
{
eprintf("ERROR!!! NEshare client listener has mysteriously "
"stopped running.\nNo more incoming client "
"connections are allowed.\nClient listener "
"terminating.\n");
}
return (void *)0;
}
void *processClientPeers(void *ptr)
{
int numReady = 0;
std::vector<nePeer *> markedPeers;
std::vector<nePeer *>::iterator iter;
s_processClientPeersThreadStop = 1;
while(s_processClientPeersThreadStop)
{
assert(markedPeers.empty());
numReady = g_peerClientManager->pollPeerSockets(&markedPeers);
/* remove marked peers if any */
for(iter = markedPeers.begin(); iter != markedPeers.end();
iter++)
{
g_peerClientManager->removePeer((*iter),
g_peerUploadManager,
g_peerDownloadManager);
}
markedPeers.clear();
if (numReady == 0)
{
/*
if there are no peer sockets ready,
sleep and then try again.
*/
ncSleep(250);
continue;
}
else if (numReady == -1)
{
/* if an error occurred, report the error and continue */
eprintf("neShareClientThreads::processClientPeers | "
"peerManager::pollPeerSockets failed.\n");
continue;
}
/* handle ready peers, if any */
if (neClientUtils::handleReadyPeers(g_peerClientManager,
g_peerDownloadManager,
g_peerUploadManager))
{
eprintf("neShareClientThreads::processClientPeers | a"
" non-fatal peer error occured.\n");
}
/* check if a cancel request was issued */
ncThread::testCancel();
}
s_processClientPeersThreadStop = 1;
return (void *)0;
}
void *processServentPeers(void *ptr)
{
int numReady = 0;
std::vector<nePeer *> markedPeers;
std::vector<nePeer *>::iterator iter;
s_processServentPeersThreadStop = 1;
while(s_processServentPeersThreadStop)
{
assert(markedPeers.empty());
numReady = g_peerServentManager->pollPeerSockets(
&markedPeers);
/* remove marked peers if any */
for(iter = markedPeers.begin(); iter != markedPeers.end();
iter++)
{
g_peerServentManager->removePeer((*iter),
g_peerUploadManager,
g_peerDownloadManager);
}
markedPeers.clear();
if (numReady == 0)
{
/*
if there are no peer sockets ready,
sleep and then try again.
*/
ncSleep(250);
continue;
}
else if (numReady == -1)
{
/* if an error occurred, report the error and continue */
eprintf("neShareClientThreads::processServentPeers | "
"peerManager::pollPeerSockets failed.\n");
continue;
}
/* handle ready peers, if any */
if (neClientUtils::handleReadyPeers(g_peerServentManager,
g_peerDownloadManager,
g_peerUploadManager))
{
eprintf("neShareClientThreads::processServentPeers "
"| a non-fatal peer error occured.\n");
}
/* check if a cancel request was issued */
ncThread::testCancel();
}
s_processServentPeersThreadStop = 1;
return (void *)0;
}
void *processUploads(void *ptr)
{
s_processUploadsThreadStop = 1;
while(s_processUploadsThreadStop)
{
/* check if there are any current uploads */
if (g_peerUploadManager->getNumUploads() == 0)
{
/* if not, sleep for a while */
ncSleep(500);
}
else
{
/*
send another chunk to each peer
with an active download
*/
g_peerUploadManager->sendPeerData();
}
/* check if a cancel request was issued */
ncThread::testCancel();
}
s_processUploadsThreadStop = 1;
return (void *)0;
}
void startThreads(neConfig *config,
nePeerManager *peerClientManager,
nePeerManager *peerServentManager,
nePeerDownloadManager *peerDownloadManager,
nePeerUploadManager *peerUploadManager)
{
/* stash all incoming arguments for later use */
g_config = config;
g_peerClientManager = peerClientManager;
g_peerServentManager = peerServentManager;
g_peerDownloadManager = peerDownloadManager;
g_peerUploadManager = peerUploadManager;
/* set the config object on the download manager */
g_peerDownloadManager->setConfig(g_config);
/* start up client-to-client related threads */
if (s_processClientPeersThread.start(
processClientPeers,(void *)0) == NC_FAILED)
{
eprintf("Fatal error: Cannot start "
"processClientPeersThread.\n");
exit(1);
}
if (s_processServentPeersThread.start(
processServentPeers,(void *)0) == NC_FAILED)
{
eprintf("Fatal error: Cannot start "
"processServentPeersThread.\n");
exit(1);
}
if (s_clientListenerThread.start(
listenForClients,(void *)0) == NC_FAILED)
{
eprintf("Fatal error: Cannot start "
"clientListenerThread.\n");
exit(1);
}
if (s_processUploadsThread.start(
processUploads,(void *)0) == NC_FAILED)
{
eprintf("Error: Cannot start upload processing thread. "
"Skipping.\n");
}
/* detach threads (to spin off in background) */
if (s_processClientPeersThread.detach() == NC_FAILED)
{
eprintf("Fatal error: Cannot detach "
"processClientPeersThread.\n");
exit(1);
}
if (s_processServentPeersThread.detach() == NC_FAILED)
{
eprintf("Fatal error: Cannot detach "
"processServentPeersThread.\n");
exit(1);
}
if (s_clientListenerThread.detach() == NC_FAILED)
{
eprintf("Fatal error: Cannot detach clientListenerThread.\n");
stopThreads();
exit(1);
}
if (s_processUploadsThread.detach() == NC_FAILED)
{
eprintf("Error: Cannot detach processUploadsThread. "
"Skipping.\n");
}
}
void stopThreads()
{
/* stop all running client threads */
if (g_nsl)
{
g_nsl->stopListening();
}
s_processClientPeersThreadStop = 0;
s_processServentPeersThreadStop = 0;
s_processUploadsThreadStop = 0;
/*
sleep for half a second to allow
for proper thread cancellation
*/
ncSleep(500);
/* now cancel the threads, if they haven't stopped already */
if (!s_processClientPeersThreadStop)
{
s_processClientPeersThread.stop(0);
}
if (!s_processServentPeersThreadStop)
{
s_processServentPeersThread.stop(0);
}
if (!s_processUploadsThreadStop)
{
s_processUploadsThread.stop(0);
}
s_clientListenerThread.stop(0);
/* uninitialize our pointers to the objects we know about */
g_config = (neConfig *)0;
g_peerClientManager = (nePeerManager *)0;
g_peerServentManager = (nePeerManager *)0;
g_peerDownloadManager = (nePeerDownloadManager *)0;
g_peerUploadManager = (nePeerUploadManager *)0;
delete g_nsl;
g_nsl = (ncSocketListener *)0;
}
}
| thecodefactory/neshare | ne_client/neshareclientthreads.cpp | C++ | gpl-2.0 | 13,553 |
<?php // need to be separately enclosed like this
header("Content-Type: application/rss+xml; charset=".config_item("charset"));
echo '<?xml version="1.0" encoding="'.config_item("charset").'"?>'.PHP_EOL;
$this->load->helper('xml');
?>
<rss version="2.0"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:admin="http://webns.net/mvcb/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title><?php echo xml_convert($feed_name); ?></title>
<link><?php echo $feed_url; ?></link>
<atom:link href="<?php echo $feed_url ?>" rel="self" type="application/rss+xml" />
<description><?php echo xml_convert($page_description); ?></description>
<dc:language><?php echo $page_language; ?></dc:language>
<dc:creator><?php echo $creator_email; /*/Translators: In case we want to translate the copyright statement.. */ ?></dc:creator>
<dc:rights><?=t("Copyright !date !organization", array('!date'=>gmdate("Y"), '!organization'=>NULL)) ?></dc:rights>
<admin:generatorAgent/>
<?php foreach($clouds as $entry): ?>
<item>
<title><?php echo xml_safe(xml_convert($entry->title)); ?></title>
<link><?php echo site_url('cloud/view/'. $entry->cloud_id) ?></link>
<guid><?php echo site_url('cloud/view/'. $entry->cloud_id) ?></guid>
<description><![CDATA[<?= xml_feed_html_safe($entry->body) ?>]]></description>
<pubDate><?php
//Bug #183, 1970 date bug.
if (isset($entry->timestamp)) {
echo date('r', $entry->timestamp);
}
elseif (isset($entry->created)) {
echo date('r', $entry->created);
}
elseif (isset($entry->modified)) {
echo date('r', $entry->modified);
}
?></pubDate>
</item>
<?php endforeach; ?>
</channel>
</rss>
| IET-OU/cloudengine | system/application/views/rss/rss.php | PHP | gpl-2.0 | 1,985 |
final class Class3_Sub28_Sub2 extends Class3_Sub28 {
private static Class94 aClass94_3541 = Class3_Sub4.buildString("yellow:");
static int anInt3542;
private static Class94 aClass94_3543 = Class3_Sub4.buildString("Loading config )2 ");
static Class94 aClass94_3544 = aClass94_3541;
Class140_Sub2 aClass140_Sub2_3545;
static Class94 aClass94_3546 = aClass94_3543;
static Class94 aClass94_3547 = Class3_Sub4.buildString("Speicher wird zugewiesen)3");
static Class94 aClass94_3548 = aClass94_3541;
public static void method534(int var0) {
try {
aClass94_3546 = null;
aClass94_3548 = null;
aClass94_3543 = null;
int var1 = 101 % ((-29 - var0) / 45);
aClass94_3544 = null;
aClass94_3547 = null;
aClass94_3541 = null;
} catch (RuntimeException var2) {
throw Class44.method1067(var2, "bk.B(" + var0 + ')');
}
}
static final void method535(byte var0, int var1) {
try {
Class151.aFloatArray1934[0] = (float)Class3_Sub28_Sub15.method633(255, var1 >> 16) / 255.0F;
Class151.aFloatArray1934[1] = (float)Class3_Sub28_Sub15.method633(var1 >> 8, 255) / 255.0F;
Class151.aFloatArray1934[2] = (float)Class3_Sub28_Sub15.method633(255, var1) / 255.0F;
Class3_Sub18.method383(-32584, 3);
Class3_Sub18.method383(-32584, 4);
if(var0 != 56) {
method535((byte)127, 99);
}
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.A(" + var0 + ',' + var1 + ')');
}
}
static final Class75_Sub3 method536(byte var0, Class3_Sub30 var1) {
try {
if(var0 != 54) {
method534(117);
}
return new Class75_Sub3(var1.method787((byte)25), var1.method787((byte)73), var1.method787((byte)114), var1.method787((byte)33), var1.method787((byte)78), var1.method787((byte)91), var1.method787((byte)120), var1.method787((byte)113), var1.method794((byte)115), var1.method803((byte)-64));
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.C(" + var0 + ',' + (var1 != null?"{...}":"null") + ')');
}
}
Class3_Sub28_Sub2(Class140_Sub2 var1) {
try {
this.aClass140_Sub2_3545 = var1;
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.<init>(" + (var1 != null?"{...}":"null") + ')');
}
}
}
| Lmctruck30/RiotScape-Client | src/Class3_Sub28_Sub2.java | Java | gpl-2.0 | 2,501 |
<?php
defined('_JEXEC') or die;
JHtml::_('behavior.formvalidation');
JHtml::_('formbehavior.chosen', 'select');
?>
<form
action="<?php echo JRoute::_('index.php?option=com_bookpro&id=' . (int) $this->item->id); ?>"
method="post" id="adminForm" name="adminForm" class="form-validate">
<div class="row-fluid">
<div class="span10 form-horizontal">
<fieldset>
<div class="control-group">
<!--
<label class="control-label" for="title"><?php echo JText::_('COM_BOOKPRO_TOURS'); ?>
</label>
<div class="controls">
<?php echo $this->form->getInput('tour_id'); ?>
</div>
</div>
-->
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('title'); ?></div>
<div class="controls"><?php echo $this->form->getInput('title'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('type'); ?></div>
<div class="controls"><?php echo $this->form->getInput('type'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('obj_id'); ?></div>
<div class="controls"><?php echo $this->form->getInput('obj_id'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('desc'); ?></div>
<div class="controls"><?php echo $this->form->getInput('desc'); ?></div>
</div>
</fieldset>
</div>
<?php echo JLayoutHelper::render('joomla.edit.details', $this); ?>
</div>
<div>
<?php echo $this->form->getInput('tour_id',null,$this->tour_id); ?>
<input type="hidden" name="task" value="" />
<input type="hidden" name="return" value="<?php echo JRequest::getCmd('return');?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
| cuongnd/test_pro | administrator/components/com_bookpro/views/faq/tmpl/edit.php | PHP | gpl-2.0 | 1,925 |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogImportExport\Model\Import\Product;
use Magento\CatalogImportExport\Model\Import\Product;
use Magento\Framework\Validator\AbstractValidator;
use Magento\Catalog\Model\Product\Attribute\Backend\Sku;
/**
* Class Validator
*
* @api
* @since 100.0.2
*/
class Validator extends AbstractValidator implements RowValidatorInterface
{
/**
* @var RowValidatorInterface[]|AbstractValidator[]
*/
protected $validators = [];
/**
* @var \Magento\CatalogImportExport\Model\Import\Product
*/
protected $context;
/**
* @var \Magento\Framework\Stdlib\StringUtils
*/
protected $string;
/**
* @var array
*/
protected $_uniqueAttributes;
/**
* @var array
*/
protected $_rowData;
/**
* @var string|null
* @since 100.1.0
*/
protected $invalidAttribute;
/**
* @param \Magento\Framework\Stdlib\StringUtils $string
* @param RowValidatorInterface[] $validators
*/
public function __construct(
\Magento\Framework\Stdlib\StringUtils $string,
$validators = []
) {
$this->string = $string;
$this->validators = $validators;
}
/**
* Text validation
*
* @param mixed $attrCode
* @param string $type
* @return bool
*/
protected function textValidation($attrCode, $type)
{
$val = $this->string->cleanString($this->_rowData[$attrCode]);
if ($type == 'text') {
$valid = $this->string->strlen($val) < Product::DB_MAX_TEXT_LENGTH;
} else if ($attrCode == Product::COL_SKU) {
$valid = $this->string->strlen($val) <= SKU::SKU_MAX_LENGTH;
} else {
$valid = $this->string->strlen($val) < Product::DB_MAX_VARCHAR_LENGTH;
}
if (!$valid) {
$this->_addMessages([RowValidatorInterface::ERROR_EXCEEDED_MAX_LENGTH]);
}
return $valid;
}
/**
* Check if value is valid attribute option
*
* @param string $attrCode
* @param array $possibleOptions
* @param string $value
* @return bool
*/
private function validateOption($attrCode, $possibleOptions, $value)
{
if (!isset($possibleOptions[strtolower($value)])) {
$this->_addMessages(
[
sprintf(
$this->context->retrieveMessageTemplate(
RowValidatorInterface::ERROR_INVALID_ATTRIBUTE_OPTION
),
$attrCode
)
]
);
return false;
}
return true;
}
/**
* Numeric validation
*
* @param mixed $attrCode
* @param string $type
* @return bool
*/
protected function numericValidation($attrCode, $type)
{
$val = trim($this->_rowData[$attrCode]);
if ($type == 'int') {
$valid = (string)(int)$val === $val;
} else {
$valid = is_numeric($val);
}
if (!$valid) {
$this->_addMessages(
[
sprintf(
$this->context->retrieveMessageTemplate(RowValidatorInterface::ERROR_INVALID_ATTRIBUTE_TYPE),
$attrCode,
$type
)
]
);
}
return $valid;
}
/**
* Is required attribute valid
*
* @param string $attrCode
* @param array $attributeParams
* @param array $rowData
* @return bool
*/
public function isRequiredAttributeValid($attrCode, array $attributeParams, array $rowData)
{
$doCheck = false;
if ($attrCode == Product::COL_SKU) {
$doCheck = true;
} elseif ($attrCode == 'price') {
$doCheck = false;
} elseif ($attributeParams['is_required'] && $this->getRowScope($rowData) == Product::SCOPE_DEFAULT
&& $this->context->getBehavior() != \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE
) {
$doCheck = true;
}
if ($doCheck === true) {
return isset($rowData[$attrCode])
&& strlen(trim($rowData[$attrCode]))
&& trim($rowData[$attrCode]) !== $this->context->getEmptyAttributeValueConstant();
}
return true;
}
/**
* Is attribute valid
*
* @param string $attrCode
* @param array $attrParams
* @param array $rowData
* @return bool
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function isAttributeValid($attrCode, array $attrParams, array $rowData)
{
$this->_rowData = $rowData;
if (isset($rowData['product_type']) && !empty($attrParams['apply_to'])
&& !in_array($rowData['product_type'], $attrParams['apply_to'])
) {
return true;
}
if (!$this->isRequiredAttributeValid($attrCode, $attrParams, $rowData)) {
$valid = false;
$this->_addMessages(
[
sprintf(
$this->context->retrieveMessageTemplate(
RowValidatorInterface::ERROR_VALUE_IS_REQUIRED
),
$attrCode
)
]
);
return $valid;
}
if (!strlen(trim($rowData[$attrCode]))) {
return true;
}
if ($rowData[$attrCode] === $this->context->getEmptyAttributeValueConstant() && !$attrParams['is_required']) {
return true;
}
switch ($attrParams['type']) {
case 'varchar':
case 'text':
$valid = $this->textValidation($attrCode, $attrParams['type']);
break;
case 'decimal':
case 'int':
$valid = $this->numericValidation($attrCode, $attrParams['type']);
break;
case 'select':
case 'boolean':
$valid = $this->validateOption($attrCode, $attrParams['options'], $rowData[$attrCode]);
break;
case 'multiselect':
$values = $this->context->parseMultiselectValues($rowData[$attrCode]);
foreach ($values as $value) {
$valid = $this->validateOption($attrCode, $attrParams['options'], $value);
if (!$valid) {
break;
}
}
$uniqueValues = array_unique($values);
if (count($uniqueValues) != count($values)) {
$valid = false;
$this->_addMessages([RowValidatorInterface::ERROR_DUPLICATE_MULTISELECT_VALUES]);
}
break;
case 'datetime':
$val = trim($rowData[$attrCode]);
$valid = strtotime($val) !== false;
if (!$valid) {
$this->_addMessages([RowValidatorInterface::ERROR_INVALID_ATTRIBUTE_TYPE]);
}
break;
default:
$valid = true;
break;
}
if ($valid && !empty($attrParams['is_unique'])) {
if (isset($this->_uniqueAttributes[$attrCode][$rowData[$attrCode]])
&& ($this->_uniqueAttributes[$attrCode][$rowData[$attrCode]] != $rowData[Product::COL_SKU])) {
$this->_addMessages([RowValidatorInterface::ERROR_DUPLICATE_UNIQUE_ATTRIBUTE]);
return false;
}
$this->_uniqueAttributes[$attrCode][$rowData[$attrCode]] = $rowData[Product::COL_SKU];
}
if (!$valid) {
$this->setInvalidAttribute($attrCode);
}
return (bool)$valid;
}
/**
* Set invalid attribute
*
* @param string|null $attribute
* @return void
* @since 100.1.0
*/
protected function setInvalidAttribute($attribute)
{
$this->invalidAttribute = $attribute;
}
/**
* Get invalid attribute
*
* @return string
* @since 100.1.0
*/
public function getInvalidAttribute()
{
return $this->invalidAttribute;
}
/**
* Is valid attributes
*
* @return bool
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
protected function isValidAttributes()
{
$this->_clearMessages();
$this->setInvalidAttribute(null);
if (!isset($this->_rowData['product_type'])) {
return false;
}
$entityTypeModel = $this->context->retrieveProductTypeByName($this->_rowData['product_type']);
if ($entityTypeModel) {
foreach ($this->_rowData as $attrCode => $attrValue) {
$attrParams = $entityTypeModel->retrieveAttributeFromCache($attrCode);
if ($attrParams) {
$this->isAttributeValid($attrCode, $attrParams, $this->_rowData);
}
}
if ($this->getMessages()) {
return false;
}
}
return true;
}
/**
* @inheritdoc
*/
public function isValid($value)
{
$this->_rowData = $value;
$this->_clearMessages();
$returnValue = $this->isValidAttributes();
foreach ($this->validators as $validator) {
if (!$validator->isValid($value)) {
$returnValue = false;
$this->_addMessages($validator->getMessages());
}
}
return $returnValue;
}
/**
* Obtain scope of the row from row data.
*
* @param array $rowData
* @return int
*/
public function getRowScope(array $rowData)
{
if (empty($rowData[Product::COL_STORE])) {
return Product::SCOPE_DEFAULT;
}
return Product::SCOPE_STORE;
}
/**
* Init
*
* @param \Magento\CatalogImportExport\Model\Import\Product $context
* @return $this
*/
public function init($context)
{
$this->context = $context;
foreach ($this->validators as $validator) {
$validator->init($context);
}
}
}
| kunj1988/Magento2 | app/code/Magento/CatalogImportExport/Model/Import/Product/Validator.php | PHP | gpl-2.0 | 10,486 |
<?php
/**
* Humescores functions and definitions.
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
* @package Humescores
*/
if ( ! function_exists( 'humescores_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function humescores_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on Humescores, use a find and replace
* to change 'humescores' to the name of your theme in all the template files.
*/
load_theme_textdomain( 'humescores', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array(
'primary' => esc_html__( 'Header', 'humescores' ),
'social' => esc_html__( 'Social Media Menu', 'humescores' ),
) );
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
) );
// Set up the WordPress core custom background feature.
add_theme_support( 'custom-background', apply_filters( 'humescores_custom_background_args', array(
'default-color' => 'ffffff',
'default-image' => '',
) ) );
// Add theme support for Custom Logo
add_theme_support( 'custom-logo', array(
'width' => 90,
'height' => 90,
'flex-width' => true,
));
}
endif;
add_action( 'after_setup_theme', 'humescores_setup' );
/**
* Register custom fonts.
*/
function humescores_fonts_url() {
$fonts_url = '';
/**
* Translators: If there are characters in your language that are not
* supported by Source Sans Pro and PT Serif, translate this to 'off'. Do not translate
* into your own language.
*/
$source_sans_pro = _x( 'on', 'Source Sans Pro font: on or off', 'humescores' );
$pt_serif = _x( 'on', 'PT Serif font: on or off', 'humescores' );
$font_families = array();
if ( 'off' !== $source_sans_pro ) {
$font_families[] = 'Source Sans Pro:400,400i,700,900';
}
if ( 'off' !== $pt_serif ) {
$font_families[] = 'PT Serif:400,400i,700,700i';
}
if ( in_array( 'on', array($source_sans_pro, $pt_serif) ) ) {
$query_args = array(
'family' => urlencode( implode( '|', $font_families ) ),
'subset' => urlencode( 'latin,latin-ext' ),
);
$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
}
return esc_url_raw( $fonts_url );
}
/**
* Add preconnect for Google Fonts.
*
* @since Twenty Seventeen 1.0
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed.
* @return array $urls URLs to print for resource hints.
*/
function humescores_resource_hints( $urls, $relation_type ) {
if ( wp_style_is( 'humescores-fonts', 'queue' ) && 'preconnect' === $relation_type ) {
$urls[] = array(
'href' => 'https://fonts.gstatic.com',
'crossorigin',
);
}
return $urls;
}
add_filter( 'wp_resource_hints', 'humescores_resource_hints', 10, 2 );
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
*
* @global int $content_width
*/
function humescores_content_width() {
$GLOBALS['content_width'] = apply_filters( 'humescores_content_width', 640 );
}
add_action( 'after_setup_theme', 'humescores_content_width', 0 );
/**
* Register widget area.
*
* @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
*/
function humescores_widgets_init() {
register_sidebar( array(
'name' => esc_html__( 'Sidebar', 'humescores' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Add widgets here.', 'humescores' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'humescores_widgets_init' );
/**
* Enqueue scripts and styles.
*/
function humescores_scripts() {
// Enqueue Google Fonts: Source Sans Pro and PT Serif
wp_enqueue_style( 'humescores-fonts', humescores_fonts_url() );
wp_enqueue_style( 'humescores-style', get_stylesheet_uri() );
wp_enqueue_script( 'humescores-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );
wp_localize_script( 'humescores-navigation', 'humescoresScreenReaderText', array(
'expand' => __( 'Expand child menu', 'humescores'),
'collapse' => __( 'Collapse child menu', 'humescores'),
));
wp_enqueue_script( 'humescores-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'humescores_scripts' );
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/inc/custom-header.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/inc/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
*/
require get_template_directory() . '/inc/extras.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/inc/customizer.php';
/**
* Load Jetpack compatibility file.
*/
require get_template_directory() . '/inc/jetpack.php';
| spraveenitpro/humescores | functions.php | PHP | gpl-2.0 | 6,984 |
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* 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.
*/
package com.iucn.whp.dbservice.service.persistence;
import com.iucn.whp.dbservice.model.benefit_rating_lkp;
import com.liferay.portal.service.persistence.BasePersistence;
/**
* The persistence interface for the benefit_rating_lkp service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author alok.sen
* @see benefit_rating_lkpPersistenceImpl
* @see benefit_rating_lkpUtil
* @generated
*/
public interface benefit_rating_lkpPersistence extends BasePersistence<benefit_rating_lkp> {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. Always use {@link benefit_rating_lkpUtil} to access the benefit_rating_lkp persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this interface.
*/
/**
* Caches the benefit_rating_lkp in the entity cache if it is enabled.
*
* @param benefit_rating_lkp the benefit_rating_lkp
*/
public void cacheResult(
com.iucn.whp.dbservice.model.benefit_rating_lkp benefit_rating_lkp);
/**
* Caches the benefit_rating_lkps in the entity cache if it is enabled.
*
* @param benefit_rating_lkps the benefit_rating_lkps
*/
public void cacheResult(
java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> benefit_rating_lkps);
/**
* Creates a new benefit_rating_lkp with the primary key. Does not add the benefit_rating_lkp to the database.
*
* @param id the primary key for the new benefit_rating_lkp
* @return the new benefit_rating_lkp
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp create(long id);
/**
* Removes the benefit_rating_lkp with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp that was removed
* @throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp remove(long id)
throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException,
com.liferay.portal.kernel.exception.SystemException;
public com.iucn.whp.dbservice.model.benefit_rating_lkp updateImpl(
com.iucn.whp.dbservice.model.benefit_rating_lkp benefit_rating_lkp,
boolean merge)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the benefit_rating_lkp with the primary key or throws a {@link com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException} if it could not be found.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp
* @throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp findByPrimaryKey(
long id)
throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException,
com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the benefit_rating_lkp with the primary key or returns <code>null</code> if it could not be found.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp, or <code>null</code> if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp fetchByPrimaryKey(
long id) throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns all the benefit_rating_lkps.
*
* @return the benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll()
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns a range of all the benefit_rating_lkps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of benefit_rating_lkps
* @param end the upper bound of the range of benefit_rating_lkps (not inclusive)
* @return the range of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll(
int start, int end)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns an ordered range of all the benefit_rating_lkps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of benefit_rating_lkps
* @param end the upper bound of the range of benefit_rating_lkps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll(
int start, int end,
com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Removes all the benefit_rating_lkps from the database.
*
* @throws SystemException if a system exception occurred
*/
public void removeAll()
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the number of benefit_rating_lkps.
*
* @return the number of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public int countAll()
throws com.liferay.portal.kernel.exception.SystemException;
} | iucn-whp/world-heritage-outlook | portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/service/persistence/benefit_rating_lkpPersistence.java | Java | gpl-2.0 | 6,928 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* 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 com.android.contacts.model.dataitem;
import android.content.ContentValues;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.SipAddress;
import com.android.contacts.model.RawContact;
/**
* Represents a sip address data item, wrapping the columns in
* {@link ContactsContract.CommonDataKinds.SipAddress}.
*/
public class SipAddressDataItem extends DataItem {
/* package */ SipAddressDataItem(RawContact rawContact, ContentValues values) {
super(rawContact, values);
}
public String getSipAddress() {
return getContentValues().getAsString(SipAddress.SIP_ADDRESS);
}
/**
* Value is one of SipAddress.TYPE_*
*/
public int getType() {
return getContentValues().getAsInteger(SipAddress.TYPE);
}
public String getLabel() {
return getContentValues().getAsString(SipAddress.LABEL);
}
}
| rex-xxx/mt6572_x201 | packages/apps/Contacts/src/com/android/contacts/model/dataitem/SipAddressDataItem.java | Java | gpl-2.0 | 1,543 |
#include "stdafx.h"
#include "Emu/System.h"
#include "Emu/ARMv7/PSVFuncList.h"
#include "sceAppUtil.h"
s32 sceAppUtilInit(vm::psv::ptr<const SceAppUtilInitParam> initParam, vm::psv::ptr<SceAppUtilBootParam> bootParam)
{
throw __FUNCTION__;
}
s32 sceAppUtilShutdown()
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotCreate(u32 slotId, vm::psv::ptr<const SceAppUtilSaveDataSlotParam> param, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotDelete(u32 slotId, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotSetParam(u32 slotId, vm::psv::ptr<const SceAppUtilSaveDataSlotParam> param, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotGetParam(u32 slotId, vm::psv::ptr<SceAppUtilSaveDataSlotParam> param, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataFileSave(vm::psv::ptr<const SceAppUtilSaveDataFileSlot> slot, vm::psv::ptr<const SceAppUtilSaveDataFile> files, u32 fileNum, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint, vm::psv::ptr<u32> requiredSizeKB)
{
throw __FUNCTION__;
}
s32 sceAppUtilPhotoMount()
{
throw __FUNCTION__;
}
s32 sceAppUtilPhotoUmount()
{
throw __FUNCTION__;
}
s32 sceAppUtilSystemParamGetInt(u32 paramId, vm::psv::ptr<s32> value)
{
throw __FUNCTION__;
}
s32 sceAppUtilSystemParamGetString(u32 paramId, vm::psv::ptr<char> buf, u32 bufSize)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveSafeMemory(vm::psv::ptr<const void> buf, u32 bufSize, s64 offset)
{
throw __FUNCTION__;
}
s32 sceAppUtilLoadSafeMemory(vm::psv::ptr<void> buf, u32 bufSize, s64 offset)
{
throw __FUNCTION__;
}
#define REG_FUNC(nid, name) reg_psv_func(nid, &sceAppUtil, #name, name)
psv_log_base sceAppUtil("SceAppUtil", []()
{
sceAppUtil.on_load = nullptr;
sceAppUtil.on_unload = nullptr;
sceAppUtil.on_stop = nullptr;
REG_FUNC(0xDAFFE671, sceAppUtilInit);
REG_FUNC(0xB220B00B, sceAppUtilShutdown);
REG_FUNC(0x7E8FE96A, sceAppUtilSaveDataSlotCreate);
REG_FUNC(0x266A7646, sceAppUtilSaveDataSlotDelete);
REG_FUNC(0x98630136, sceAppUtilSaveDataSlotSetParam);
REG_FUNC(0x93F0D89F, sceAppUtilSaveDataSlotGetParam);
REG_FUNC(0x1E2A6158, sceAppUtilSaveDataFileSave);
REG_FUNC(0xEE85804D, sceAppUtilPhotoMount);
REG_FUNC(0x9651B941, sceAppUtilPhotoUmount);
REG_FUNC(0x5DFB9CA0, sceAppUtilSystemParamGetInt);
REG_FUNC(0x6E6AA267, sceAppUtilSystemParamGetString);
REG_FUNC(0x9D8AC677, sceAppUtilSaveSafeMemory);
REG_FUNC(0x3424D772, sceAppUtilLoadSafeMemory);
});
| Syphurith/rpcs3 | rpcs3/Emu/ARMv7/Modules/sceAppUtil.cpp | C++ | gpl-2.0 | 2,648 |
using System;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Security.Policy;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UserProfile : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request["User"] == null)
{
Response.Redirect("MainPage.aspx");
return;
}
Guid userId;
if (!Guid.TryParse(Request["User"], out userId))
{
Response.Redirect("MainPage.aspx");
return;
}
var membershipUser = Membership.GetUser(userId);
if (membershipUser == null)
{
Response.Redirect("MainPage.aspx");
return;
}
InitControlsVisibility(userId);
PopulateShowProfileControls(membershipUser);
PopulateEditProfileControls(membershipUser);
}
}
private void InitControlsVisibility(Guid userId)
{
pnlEditProfile.Visible = false;
pnlShowProfile.Visible = true;
lvShowChecker.Visible = UserInteraction.CheckIfIdIsLoggedUser(userId);
lvEditChecker.Visible = lvShowChecker.Visible;
}
private void PopulateShowProfileControls(MembershipUser membershipUser)
{
if (membershipUser == null)
{
return;
}
var userProfile = Profile.GetProfile(membershipUser.UserName);
lblUsernameShow.Text = membershipUser.UserName;
lblFirstNameShow.Text = userProfile.FirstName;
lblLastNameShow.Text = userProfile.LastName;
lblBirthDateShow.Text = userProfile.BirthDate.HasValue ? userProfile.BirthDate.Value.ToString("dd MMMMM yyyy", CultureInfo.CreateSpecificCulture("en-us")) : string.Empty;
lblAgeShow.Text = userProfile.BirthDate.HasValue
? ((DateTime.Now - userProfile.BirthDate.Value).Days / 365).ToString()
: string.Empty;
hlEmailShow.Text = membershipUser.Email;
hlEmailShow.NavigateUrl = string.Format("mailto:{0}", membershipUser.Email);
lblRoleShow.Text = Roles.GetRolesForUser(membershipUser.UserName)[0];
if (membershipUser.ProviderUserKey != null)
{
imgUserProfileImageShow.ImageUrl = UserInteraction.MakeProfileUrl((Guid)membershipUser.ProviderUserKey);
}
imgUserProfileImageShow.ImageAlign = ImageAlign.Middle;
}
private void PopulateEditProfileControls(MembershipUser membershipUser)
{
if (membershipUser == null)
{
return;
}
var userProfile = Profile.GetProfile(membershipUser.UserName);
lblUsernameEdit.Text = membershipUser.UserName;
tbFirstNameEdit.Text = userProfile.FirstName;
tbLastNameEdit.Text = userProfile.LastName;
tbBirthDateEdit.Text = userProfile.BirthDate.HasValue ? userProfile.BirthDate.Value.ToString("dd MMMMM yyyy", CultureInfo.CreateSpecificCulture("en-us")) : string.Empty;
lblAgeEdit.Text = userProfile.BirthDate.HasValue
? ((DateTime.Now - userProfile.BirthDate.Value).Days / 365).ToString()
: string.Empty;
tbEmailEdit.Text = membershipUser.Email;
lblRoleEdit.Text = Roles.GetRolesForUser(membershipUser.UserName)[0];
if (membershipUser.ProviderUserKey != null)
{
imgUserProfileImageEdit.ImageUrl = UserInteraction.MakeProfileUrl((Guid)membershipUser.ProviderUserKey);
}
imgUserProfileImageEdit.ImageAlign = ImageAlign.Middle;
}
protected void EditButtonClick(object sender, EventArgs e)
{
pnlEditProfile.Visible = true;
pnlShowProfile.Visible = false;
}
protected void CancelButtonClick(object sender, EventArgs e)
{
if (Request["User"] == null)
{
return;
}
Guid userId;
if (!Guid.TryParse(Request["User"], out userId))
{
return;
}
var membershipUser = Membership.GetUser(userId);
if (membershipUser == null)
{
return;
}
PopulateEditProfileControls(membershipUser);
pnlEditProfile.Visible = false;
pnlShowProfile.Visible = true;
}
protected void UpdateButtonClick(object sender, EventArgs e)
{
if (Request["User"] == null)
{
return;
}
Guid userId;
if (!Guid.TryParse(Request["User"], out userId))
{
return;
}
var membershipUser = Membership.GetUser(userId);
if (membershipUser == null)
{
return;
}
membershipUser.Email = tbEmailEdit.Text;
var userProfile = Profile.GetProfile(membershipUser.UserName);
userProfile.FirstName = tbFirstNameEdit.Text;
userProfile.LastName = tbLastNameEdit.Text;
if (!string.IsNullOrWhiteSpace(tbBirthDateEdit.Text))
{
userProfile.BirthDate = DateTime.Parse(tbBirthDateEdit.Text);
}
if (fuUserProfileImage.HasFile)
{
var filePath = Server.MapPath("ProfileImages") + Path.DirectorySeparatorChar + membershipUser.ProviderUserKey;
fuUserProfileImage.SaveAs(filePath);
userProfile.ProfilePicture = "/ForumWebsite" + "/" + "ProfileImages" + "/" + membershipUser.ProviderUserKey;
}
userProfile.Save();
PopulateEditProfileControls(membershipUser);
PopulateShowProfileControls(membershipUser);
pnlEditProfile.Visible = false;
pnlShowProfile.Visible = true;
}
} | botezatumihaicatalin/Asp.net-Forum | Profile.aspx.cs | C# | gpl-2.0 | 5,818 |