repo_id
stringlengths
4
98
size
int64
611
5.02M
file_path
stringlengths
1
276
content
stringlengths
611
5.02M
shard_id
int64
0
109
quality_score
float32
0.5
1
quality_prediction
int8
1
1
quality_confidence
float32
0.5
1
topic_primary
stringclasses
1 value
topic_group
stringclasses
1 value
topic_score
float32
0.05
1
topic_all
stringclasses
96 values
quality2_score
float32
0.5
1
quality2_prediction
int8
1
1
quality2_confidence
float32
0.5
1
ValveSoftware/halflife
12,773
dlls/ggrenade.cpp
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /* ===== generic grenade.cpp ======================================================== */ #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "weapons.h" #include "nodes.h" #include "soundent.h" #include "decals.h" //===================grenade LINK_ENTITY_TO_CLASS( grenade, CGrenade ); // Grenades flagged with this will be triggered when the owner calls detonateSatchelCharges #define SF_DETONATE 0x0001 // // Grenade Explode // void CGrenade::Explode( Vector vecSrc, Vector vecAim ) { TraceResult tr; UTIL_TraceLine ( pev->origin, pev->origin + Vector ( 0, 0, -32 ), ignore_monsters, ENT(pev), & tr); Explode( &tr, DMG_BLAST ); } // UNDONE: temporary scorching for PreAlpha - find a less sleazy permenant solution. void CGrenade::Explode( TraceResult *pTrace, int bitsDamageType ) { float flRndSound;// sound randomizer pev->model = iStringNull;//invisible pev->solid = SOLID_NOT;// intangible pev->takedamage = DAMAGE_NO; // Pull out of the wall a bit if ( pTrace->flFraction != 1.0 ) { pev->origin = pTrace->vecEndPos + (pTrace->vecPlaneNormal * (pev->dmg - 24) * 0.6); } int iContents = UTIL_PointContents ( pev->origin ); MESSAGE_BEGIN( MSG_PAS, SVC_TEMPENTITY, pev->origin ); WRITE_BYTE( TE_EXPLOSION ); // This makes a dynamic light and the explosion sprites/sound WRITE_COORD( pev->origin.x ); // Send to PAS because of the sound WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); if (iContents != CONTENTS_WATER) { WRITE_SHORT( g_sModelIndexFireball ); } else { WRITE_SHORT( g_sModelIndexWExplosion ); } WRITE_BYTE( (pev->dmg - 50) * .60 ); // scale * 10 WRITE_BYTE( 15 ); // framerate WRITE_BYTE( TE_EXPLFLAG_NONE ); MESSAGE_END(); CSoundEnt::InsertSound ( bits_SOUND_COMBAT, pev->origin, NORMAL_EXPLOSION_VOLUME, 3.0 ); entvars_t *pevOwner; if ( pev->owner ) pevOwner = VARS( pev->owner ); else pevOwner = NULL; pev->owner = NULL; // can't traceline attack owner if this is set RadiusDamage ( pev, pevOwner, pev->dmg, CLASS_NONE, bitsDamageType ); if ( RANDOM_FLOAT( 0 , 1 ) < 0.5 ) { UTIL_DecalTrace( pTrace, DECAL_SCORCH1 ); } else { UTIL_DecalTrace( pTrace, DECAL_SCORCH2 ); } flRndSound = RANDOM_FLOAT( 0 , 1 ); switch ( RANDOM_LONG( 0, 2 ) ) { case 0: EMIT_SOUND(ENT(pev), CHAN_VOICE, "weapons/debris1.wav", 0.55, ATTN_NORM); break; case 1: EMIT_SOUND(ENT(pev), CHAN_VOICE, "weapons/debris2.wav", 0.55, ATTN_NORM); break; case 2: EMIT_SOUND(ENT(pev), CHAN_VOICE, "weapons/debris3.wav", 0.55, ATTN_NORM); break; } pev->effects |= EF_NODRAW; SetThink( &CGrenade::Smoke ); pev->velocity = g_vecZero; pev->nextthink = gpGlobals->time + 0.3; if (iContents != CONTENTS_WATER) { int sparkCount = RANDOM_LONG(0,3); for ( int i = 0; i < sparkCount; i++ ) Create( "spark_shower", pev->origin, pTrace->vecPlaneNormal, NULL ); } } void CGrenade::Smoke( void ) { if (UTIL_PointContents ( pev->origin ) == CONTENTS_WATER) { UTIL_Bubbles( pev->origin - Vector( 64, 64, 64 ), pev->origin + Vector( 64, 64, 64 ), 100 ); } else { MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, pev->origin ); WRITE_BYTE( TE_SMOKE ); WRITE_COORD( pev->origin.x ); WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_SHORT( g_sModelIndexSmoke ); WRITE_BYTE( (pev->dmg - 50) * 0.80 ); // scale * 10 WRITE_BYTE( 12 ); // framerate MESSAGE_END(); } UTIL_Remove( this ); } void CGrenade::Killed( entvars_t *pevAttacker, int iGib ) { Detonate( ); } // Timed grenade, this think is called when time runs out. void CGrenade::DetonateUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { SetThink( &CGrenade::Detonate ); pev->nextthink = gpGlobals->time; } void CGrenade::PreDetonate( void ) { CSoundEnt::InsertSound ( bits_SOUND_DANGER, pev->origin, 400, 0.3 ); SetThink( &CGrenade::Detonate ); pev->nextthink = gpGlobals->time + 1; } void CGrenade::Detonate( void ) { TraceResult tr; Vector vecSpot;// trace starts here! vecSpot = pev->origin + Vector ( 0 , 0 , 8 ); UTIL_TraceLine ( vecSpot, vecSpot + Vector ( 0, 0, -40 ), ignore_monsters, ENT(pev), & tr); Explode( &tr, DMG_BLAST ); } // // Contact grenade, explode when it touches something // void CGrenade::ExplodeTouch( CBaseEntity *pOther ) { TraceResult tr; Vector vecSpot;// trace starts here! pev->enemy = pOther->edict(); vecSpot = pev->origin - pev->velocity.Normalize() * 32; UTIL_TraceLine( vecSpot, vecSpot + pev->velocity.Normalize() * 64, ignore_monsters, ENT(pev), &tr ); Explode( &tr, DMG_BLAST ); } void CGrenade::DangerSoundThink( void ) { if (!IsInWorld()) { UTIL_Remove( this ); return; } CSoundEnt::InsertSound ( bits_SOUND_DANGER, pev->origin + pev->velocity * 0.5, pev->velocity.Length( ), 0.2 ); pev->nextthink = gpGlobals->time + 0.2; if (pev->waterlevel != 0) { pev->velocity = pev->velocity * 0.5; } } void CGrenade::BounceTouch( CBaseEntity *pOther ) { // don't hit the guy that launched this grenade if ( pOther->edict() == pev->owner ) return; // only do damage if we're moving fairly fast if (m_flNextAttack < gpGlobals->time && pev->velocity.Length() > 100) { entvars_t *pevOwner = VARS( pev->owner ); if (pevOwner) { TraceResult tr = UTIL_GetGlobalTrace( ); ClearMultiDamage( ); pOther->TraceAttack(pevOwner, 1, gpGlobals->v_forward, &tr, DMG_CLUB ); ApplyMultiDamage( pev, pevOwner); } m_flNextAttack = gpGlobals->time + 1.0; // debounce } Vector vecTestVelocity; // pev->avelocity = Vector (300, 300, 300); // this is my heuristic for modulating the grenade velocity because grenades dropped purely vertical // or thrown very far tend to slow down too quickly for me to always catch just by testing velocity. // trimming the Z velocity a bit seems to help quite a bit. vecTestVelocity = pev->velocity; vecTestVelocity.z *= 0.45; if ( !m_fRegisteredSound && vecTestVelocity.Length() <= 60 ) { //ALERT( at_console, "Grenade Registered!: %f\n", vecTestVelocity.Length() ); // grenade is moving really slow. It's probably very close to where it will ultimately stop moving. // go ahead and emit the danger sound. // register a radius louder than the explosion, so we make sure everyone gets out of the way CSoundEnt::InsertSound ( bits_SOUND_DANGER, pev->origin, pev->dmg / 0.4, 0.3 ); m_fRegisteredSound = TRUE; } if (pev->flags & FL_ONGROUND) { // add a bit of static friction pev->velocity = pev->velocity * 0.8; pev->sequence = RANDOM_LONG( 1, 1 ); } else { // play bounce sound BounceSound(); } pev->framerate = pev->velocity.Length() / 200.0; if (pev->framerate > 1.0) pev->framerate = 1; else if (pev->framerate < 0.5) pev->framerate = 0; } void CGrenade::SlideTouch( CBaseEntity *pOther ) { // don't hit the guy that launched this grenade if ( pOther->edict() == pev->owner ) return; // pev->avelocity = Vector (300, 300, 300); if (pev->flags & FL_ONGROUND) { // add a bit of static friction pev->velocity = pev->velocity * 0.95; if (pev->velocity.x != 0 || pev->velocity.y != 0) { // maintain sliding sound } } else { BounceSound(); } } void CGrenade :: BounceSound( void ) { switch ( RANDOM_LONG( 0, 2 ) ) { case 0: EMIT_SOUND(ENT(pev), CHAN_VOICE, "weapons/grenade_hit1.wav", 0.25, ATTN_NORM); break; case 1: EMIT_SOUND(ENT(pev), CHAN_VOICE, "weapons/grenade_hit2.wav", 0.25, ATTN_NORM); break; case 2: EMIT_SOUND(ENT(pev), CHAN_VOICE, "weapons/grenade_hit3.wav", 0.25, ATTN_NORM); break; } } void CGrenade :: TumbleThink( void ) { if (!IsInWorld()) { UTIL_Remove( this ); return; } StudioFrameAdvance( ); pev->nextthink = gpGlobals->time + 0.1; if (pev->dmgtime - 1 < gpGlobals->time) { CSoundEnt::InsertSound ( bits_SOUND_DANGER, pev->origin + pev->velocity * (pev->dmgtime - gpGlobals->time), 400, 0.1 ); } if (pev->dmgtime <= gpGlobals->time) { SetThink( &CGrenade::Detonate ); } if (pev->waterlevel != 0) { pev->velocity = pev->velocity * 0.5; pev->framerate = 0.2; } } void CGrenade:: Spawn( void ) { pev->movetype = MOVETYPE_BOUNCE; pev->classname = MAKE_STRING( "grenade" ); pev->solid = SOLID_BBOX; SET_MODEL(ENT(pev), "models/grenade.mdl"); UTIL_SetSize(pev, Vector( 0, 0, 0), Vector(0, 0, 0)); pev->dmg = 100; m_fRegisteredSound = FALSE; } CGrenade *CGrenade::ShootContact( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity ) { CGrenade *pGrenade = GetClassPtr( (CGrenade *)NULL ); pGrenade->Spawn(); // contact grenades arc lower pGrenade->pev->gravity = 0.5;// lower gravity since grenade is aerodynamic and engine doesn't know it. UTIL_SetOrigin( pGrenade->pev, vecStart ); pGrenade->pev->velocity = vecVelocity; pGrenade->pev->angles = UTIL_VecToAngles (pGrenade->pev->velocity); pGrenade->pev->owner = ENT(pevOwner); // make monsters afaid of it while in the air pGrenade->SetThink( &CGrenade::DangerSoundThink ); pGrenade->pev->nextthink = gpGlobals->time; // Tumble in air pGrenade->pev->avelocity.x = RANDOM_FLOAT ( -100, -500 ); // Explode on contact pGrenade->SetTouch( &CGrenade::ExplodeTouch ); pGrenade->pev->dmg = gSkillData.plrDmgM203Grenade; return pGrenade; } CGrenade * CGrenade:: ShootTimed( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity, float time ) { CGrenade *pGrenade = GetClassPtr( (CGrenade *)NULL ); pGrenade->Spawn(); UTIL_SetOrigin( pGrenade->pev, vecStart ); pGrenade->pev->velocity = vecVelocity; pGrenade->pev->angles = UTIL_VecToAngles(pGrenade->pev->velocity); pGrenade->pev->owner = ENT(pevOwner); pGrenade->SetTouch( &CGrenade::BounceTouch ); // Bounce if touched // Take one second off of the desired detonation time and set the think to PreDetonate. PreDetonate // will insert a DANGER sound into the world sound list and delay detonation for one second so that // the grenade explodes after the exact amount of time specified in the call to ShootTimed(). pGrenade->pev->dmgtime = gpGlobals->time + time; pGrenade->SetThink( &CGrenade::TumbleThink ); pGrenade->pev->nextthink = gpGlobals->time + 0.1; if (time < 0.1) { pGrenade->pev->nextthink = gpGlobals->time; pGrenade->pev->velocity = Vector( 0, 0, 0 ); } pGrenade->pev->sequence = RANDOM_LONG( 3, 6 ); pGrenade->pev->framerate = 1.0; // Tumble through the air // pGrenade->pev->avelocity.x = -400; pGrenade->pev->gravity = 0.5; pGrenade->pev->friction = 0.8; SET_MODEL(ENT(pGrenade->pev), "models/w_grenade.mdl"); pGrenade->pev->dmg = 100; return pGrenade; } CGrenade * CGrenade :: ShootSatchelCharge( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity ) { CGrenade *pGrenade = GetClassPtr( (CGrenade *)NULL ); pGrenade->pev->movetype = MOVETYPE_BOUNCE; pGrenade->pev->classname = MAKE_STRING( "grenade" ); pGrenade->pev->solid = SOLID_BBOX; SET_MODEL(ENT(pGrenade->pev), "models/grenade.mdl"); // Change this to satchel charge model UTIL_SetSize(pGrenade->pev, Vector( 0, 0, 0), Vector(0, 0, 0)); pGrenade->pev->dmg = 200; UTIL_SetOrigin( pGrenade->pev, vecStart ); pGrenade->pev->velocity = vecVelocity; pGrenade->pev->angles = g_vecZero; pGrenade->pev->owner = ENT(pevOwner); // Detonate in "time" seconds pGrenade->SetThink( &CGrenade::SUB_DoNothing ); pGrenade->SetUse( &CGrenade::DetonateUse ); pGrenade->SetTouch( &CGrenade::SlideTouch ); pGrenade->pev->spawnflags = SF_DETONATE; pGrenade->pev->friction = 0.9; return pGrenade; } void CGrenade :: UseSatchelCharges( entvars_t *pevOwner, SATCHELCODE code ) { edict_t *pentFind; edict_t *pentOwner; if ( !pevOwner ) return; CBaseEntity *pOwner = CBaseEntity::Instance( pevOwner ); pentOwner = pOwner->edict(); pentFind = FIND_ENTITY_BY_CLASSNAME( NULL, "grenade" ); while ( !FNullEnt( pentFind ) ) { CBaseEntity *pEnt = Instance( pentFind ); if ( pEnt ) { if ( FBitSet( pEnt->pev->spawnflags, SF_DETONATE ) && pEnt->pev->owner == pentOwner ) { if ( code == SATCHEL_DETONATE ) pEnt->Use( pOwner, pOwner, USE_ON, 0 ); else // SATCHEL_RELEASE pEnt->pev->owner = NULL; } } pentFind = FIND_ENTITY_BY_CLASSNAME( pentFind, "grenade" ); } } //======================end grenade
412
0.850651
1
0.850651
game-dev
MEDIA
0.97342
game-dev
0.623267
1
0.623267
googlevr/gvr-unity-sdk
4,960
Assets/GoogleVR/Scripts/Keyboard/Internal/KeyboardProviders/EmulatorKeyboardProvider.cs
//----------------------------------------------------------------------- // <copyright file="EmulatorKeyboardProvider.cs" company="Google Inc."> // Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- // This is a version of the keyboard that runs directly in the Unity Editor. // It is meant to simply be a placeholder so developers can test their games // without having to use actual devices. using UnityEngine; using System; /// @cond namespace Gvr.Internal { /// Keyboard subclass to run in the Unity editor public class EmulatorKeyboardProvider : IKeyboardProvider { private GameObject stub; private bool showing; GvrKeyboard.KeyboardCallback keyboardCallback; private string editorText = string.Empty; private GvrKeyboardInputMode mode = GvrKeyboardInputMode.DEFAULT; private Matrix4x4 worldMatrix; private bool isValid = false; public string EditorText { get { return editorText; } set { editorText = value; } } public void SetInputMode(GvrKeyboardInputMode mode) { this.mode = mode; } public EmulatorKeyboardProvider() { Debug.Log("Creating stub keyboard"); // Set default data; showing = false; isValid = true; } public void OnPause() { } public void OnResume() { } public void ReadState(KeyboardState outState) { outState.mode = mode; outState.editorText = editorText; outState.worldMatrix = worldMatrix; outState.isValid = isValid; outState.isReady = true; } public bool Create(GvrKeyboard.KeyboardCallback keyboardEvent) { keyboardCallback = keyboardEvent; if (!isValid) { keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED); } return true; } public void Show(Matrix4x4 controllerMatrix, bool useRecommended, float distance, Matrix4x4 model) { if (!showing && isValid) { showing = true; worldMatrix = controllerMatrix; keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_SHOWN); } } public void UpdateData() { // Can skip if keyboard not available if (!showing) { return; } if (Input.GetKeyDown(KeyCode.KeypadEnter)) { keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_TEXT_COMMITTED); return; } if (Input.GetKeyDown(KeyCode.Backspace)) { if (editorText.Length > 0) { editorText = editorText.Substring(0, editorText.Length - 1); SendUpdateNotification(); } return; } if (Input.inputString.Length <= 0) { return; } switch (mode) { case GvrKeyboardInputMode.DEFAULT: editorText += Input.inputString; break; case GvrKeyboardInputMode.NUMERIC: foreach (char n in Input.inputString) { if (n >= '0' && n <= '9') { editorText += n; } } break; default: break; } SendUpdateNotification(); } public void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport) { } public void Hide() { if (showing) { showing = false; keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_HIDDEN); } } private void SendUpdateNotification() { keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_TEXT_UPDATED); } } }
412
0.708168
1
0.708168
game-dev
MEDIA
0.706453
game-dev
0.777041
1
0.777041
SuperNewRoles/SuperNewRoles
9,072
SuperNewRoles/Roles/Neutral/Spelunker.cs
using System; using System.Collections.Generic; using System.Linq; using AmongUs.GameOptions; using SuperNewRoles.CustomOptions; using SuperNewRoles.Modules; using SuperNewRoles.Roles.Ability; using SuperNewRoles.Events; using SuperNewRoles.Events.PCEvents; using SuperNewRoles.Modules.Events.Bases; using UnityEngine; using HarmonyLib; namespace SuperNewRoles.Roles.Neutral; class Spelunker : RoleBase<Spelunker> { public override RoleId Role { get; } = RoleId.Spelunker; public override Color32 RoleColor { get; } = new(255, 255, 0, byte.MaxValue); // 黄色 public override List<Func<AbilityBase>> Abilities { get; } = [ () => new SpelunkerAbility(new SpelunkerData( VentDeathChance: SpelunkerVentDeathChance, CommsDeathTime: SpelunkerIsDeathCommsOrPowerdown ? SpelunkerDeathCommsTime : -1f, PowerdownDeathTime: SpelunkerIsDeathCommsOrPowerdown ? SpelunkerDeathPowerdownTime : -1f, LiftDeathChance: SpelunkerLiftDeathChance, DoorOpenChance: SpelunkerDoorOpenChance, LadderDeathChance: SpelunkerLadderDeathChance )), () => new LadderDeathAbility(SpelunkerLadderDeathChance) ]; public override QuoteMod QuoteMod { get; } = QuoteMod.SuperNewRoles; public override RoleTypes IntroSoundType { get; } = RoleTypes.Shapeshifter; public override short IntroNum { get; } = 1; public override AssignedTeamType AssignedTeam { get; } = AssignedTeamType.Neutral; public override WinnerTeamType WinnerTeam { get; } = WinnerTeamType.Neutral; public override TeamTag TeamTag { get; } = TeamTag.Neutral; public override RoleTag[] RoleTags { get; } = []; public override RoleOptionMenuType OptionTeam { get; } = RoleOptionMenuType.Neutral; [CustomOptionBool("SpelunkerIsDeathCommsOrPowerdown", true, translationName: "SpelunkerIsDeathCommsOrPowerdown")] public static bool SpelunkerIsDeathCommsOrPowerdown; [CustomOptionFloat("SpelunkerDeathCommsTime", 5f, 120f, 2.5f, 20f, parentFieldName: nameof(SpelunkerIsDeathCommsOrPowerdown), suffix: "s")] public static float SpelunkerDeathCommsTime; [CustomOptionFloat("SpelunkerDeathPowerdownTime", 5f, 120f, 2.5f, 20f, parentFieldName: nameof(SpelunkerIsDeathCommsOrPowerdown), suffix: "s")] public static float SpelunkerDeathPowerdownTime; [CustomOptionInt("SpelunkerVentDeathChance", 0, 100, 5, 20, translationName: "SpelunkerVentDeathChance", suffix: "%")] public static int SpelunkerVentDeathChance; [CustomOptionInt("SpelunkerLiftDeathChance", 0, 100, 5, 20, translationName: "SpelunkerLiftDeathChance", suffix: "%")] public static int SpelunkerLiftDeathChance; [CustomOptionInt("SpelunkerDoorOpenChance", 0, 100, 5, 20, translationName: "SpelunkerDoorOpenChance", suffix: "%")] public static int SpelunkerDoorOpenChance; [CustomOptionInt("SpelunkerLadderDeathChance", 0, 100, 5, 20, translationName: "LadderDeadChance", suffix: "%")] public static int SpelunkerLadderDeathChance; [CustomOptionBool("SpelunkerIsAdditionalWin", false, translationName: "AdditionalWin")] public static bool SpelunkerIsAdditionalWin; } public record SpelunkerData( int VentDeathChance, float CommsDeathTime, float PowerdownDeathTime, int LiftDeathChance, int DoorOpenChance, int LadderDeathChance ); public class SpelunkerAbility : AbilityBase { public SpelunkerData Data { get; set; } private EventListener _fixedUpdateListener; private EventListener<ExileEventData> _exileListener; private EventListener<UsePlatformEventData> _usePlatformListener; private EventListener<DoorConsoleUseEventData> _doorConsoleUseListener; // Spelunker specific variables private bool _isVentChecked; private float _commsDeathTimer; private float _powerdownDeathTimer; private Vector2? _deathPosition; public SpelunkerAbility(SpelunkerData data) { Data = data; _commsDeathTimer = data.CommsDeathTime; _powerdownDeathTimer = data.PowerdownDeathTime; } public override void AttachToLocalPlayer() { base.AttachToLocalPlayer(); _fixedUpdateListener = FixedUpdateEvent.Instance.AddListener(OnFixedUpdate); _exileListener = ExileEvent.Instance.AddListener(OnExile); _usePlatformListener = UsePlatformEvent.Instance.AddListener(OnUsePlatform); _doorConsoleUseListener = DoorConsoleUseEvent.Instance.AddListener(OnDoorConsoleUse); } public override void DetachToLocalPlayer() { _fixedUpdateListener?.RemoveListener(); _exileListener?.RemoveListener(); _usePlatformListener?.RemoveListener(); _doorConsoleUseListener?.RemoveListener(); } private void OnFixedUpdate() { if (ExPlayerControl.LocalPlayer.IsDead()) return; if (FastDestroyableSingleton<HudManager>.Instance.IsIntroDisplayed || MeetingHud.Instance != null || ExileController.Instance != null) return; // ベント判定 if (Data.VentDeathChance > 0) { CheckVentDeath(); } // コミュと停電の不安死 if (Data.CommsDeathTime != -1) { CheckCommsDeath(); } if (Data.PowerdownDeathTime != -1) { CheckPowerdownDeath(); } // 転落死判定 if (_deathPosition != null && Vector2.Distance((Vector2)_deathPosition, ExPlayerControl.LocalPlayer.transform.position) < 0.5f) { ExPlayerControl.LocalPlayer.RpcCustomDeath(CustomDeathType.Suicide); FinalStatusManager.RpcSetFinalStatus(ExPlayerControl.LocalPlayer, FinalStatus.NunDeath); _deathPosition = null; } } private void CheckVentDeath() { Vent currentVent = null; bool nearVent = false; if (ShipStatus.Instance?.AllVents != null) { foreach (var vent in ShipStatus.Instance.AllVents) { if (Vector2.Distance(vent.transform.position, ExPlayerControl.LocalPlayer.transform.position) < vent.UsableDistance) { currentVent = vent; nearVent = true; break; } } } if (nearVent) { if (!_isVentChecked) { _isVentChecked = true; if (ModHelpers.IsSuccessChance(Data.VentDeathChance)) { ExPlayerControl.LocalPlayer.RpcCustomDeath(CustomDeathType.Suicide); FinalStatusManager.RpcSetFinalStatus(ExPlayerControl.LocalPlayer, FinalStatus.SpelunkerVentDeath); } } } else { _isVentChecked = false; } } private void CheckCommsDeath() { if (ModHelpers.IsComms()) { _commsDeathTimer -= Time.fixedDeltaTime; if (_commsDeathTimer <= 0) { ExPlayerControl.LocalPlayer.RpcCustomDeath(CustomDeathType.Suicide); FinalStatusManager.RpcSetFinalStatus(ExPlayerControl.LocalPlayer, FinalStatus.SpelunkerCommsElecDeath); } } else { _commsDeathTimer = Data.CommsDeathTime; } } private void CheckPowerdownDeath() { if (ModHelpers.IsElectrical()) { _powerdownDeathTimer -= Time.fixedDeltaTime; if (_powerdownDeathTimer <= 0) { ExPlayerControl.LocalPlayer.RpcCustomDeath(CustomDeathType.Suicide); FinalStatusManager.RpcSetFinalStatus(ExPlayerControl.LocalPlayer, FinalStatus.SpelunkerCommsElecDeath); } } else { _powerdownDeathTimer = Data.PowerdownDeathTime; } } private void OnExile(ExileEventData data) { // 会議終了時のリセット _deathPosition = null; } private void OnUsePlatform(UsePlatformEventData data) { if (data.player == ExPlayerControl.LocalPlayer) { OnMovingPlatformUsed(data.platform); } } private void OnDoorConsoleUse(DoorConsoleUseEventData data) { if (data.player == ExPlayerControl.LocalPlayer) { OnDoorOpen(); } } // MovingPlatformの使用時の転落死判定 public void OnMovingPlatformUsed(MovingPlatformBehaviour platform) { if (ModHelpers.IsSuccessChance(Data.LiftDeathChance)) { _deathPosition = platform.transform.parent.TransformPoint((!platform.IsLeft) ? platform.LeftUsePosition : platform.RightUsePosition); Logger.Info($"Spelunker lift death position set: {_deathPosition}"); } } // ドア開放時の指挟み死 public void OnDoorOpen() { if (ModHelpers.IsSuccessChance(Data.DoorOpenChance)) { ExPlayerControl.LocalPlayer.RpcCustomDeath(CustomDeathType.Suicide); FinalStatusManager.RpcSetFinalStatus(ExPlayerControl.LocalPlayer, FinalStatus.SpelunkerOpenDoor); } } }
412
0.866238
1
0.866238
game-dev
MEDIA
0.884059
game-dev
0.949204
1
0.949204
ProjectSkyfire/SkyFire.406a
290,991
src/server/game/Spells/Spell.cpp
/* * Copyright (C) 2011-2019 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2019 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2019 MaNGOS <https://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 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Opcodes.h" #include "Log.h" #include "UpdateMask.h" #include "World.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "Pet.h" #include "Unit.h" #include "Totem.h" #include "Spell.h" #include "DynamicObject.h" #include "Guild.h" #include "Group.h" #include "UpdateData.h" #include "MapManager.h" #include "ObjectAccessor.h" #include "CellImpl.h" #include "SharedDefines.h" #include "LootMgr.h" #include "VMapFactory.h" #include "Battleground.h" #include "BattlefieldMgr.h" #include "Util.h" #include "TemporarySummon.h" #include "Vehicle.h" #include "SpellAuraEffects.h" #include "ScriptMgr.h" #include "ConditionMgr.h" #include "DisableMgr.h" #include "SpellScript.h" #include "InstanceScript.h" #include "SpellInfo.h" #include "DB2Stores.h" extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS]; SpellDestination::SpellDestination() { _position.Relocate(0, 0, 0, 0); _transportGUID = 0; _transportOffset.Relocate(0, 0, 0, 0); } SpellDestination::SpellDestination(float x, float y, float z, float orientation, uint32 mapId) { _position.Relocate(x, y, z, orientation); _transportGUID = 0; _position.m_mapId = mapId; } SpellDestination::SpellDestination(Position const& pos) { _position.Relocate(pos); _transportGUID = 0; } SpellDestination::SpellDestination(WorldObject const& wObj) { _transportGUID = wObj.GetTransGUID(); _transportOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO()); _position.Relocate(wObj); _position.SetOrientation(wObj.GetOrientation()); } SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0) { m_objectTarget = NULL; m_itemTarget = NULL; m_objectTargetGUID = 0; m_itemTargetGUID = 0; m_itemTargetEntry = 0; m_strTarget = ""; m_targetMask = 0; } SpellCastTargets::~SpellCastTargets() { } void SpellCastTargets::Read(ByteBuffer& data, Unit* caster) { data >> m_targetMask; if (m_targetMask == TARGET_FLAG_NONE) return; if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_UNIT_MINIPET | TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_CORPSE_ALLY)) data.readPackGUID(m_objectTargetGUID); if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM)) data.readPackGUID(m_itemTargetGUID); if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) { data.readPackGUID(m_src._transportGUID); if (m_src._transportGUID) data >> m_src._transportOffset.PositionXYZStream(); else data >> m_src._position.PositionXYZStream(); } else { m_src._transportGUID = caster->GetTransGUID(); if (m_src._transportGUID) m_src._transportOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO()); else m_src._position.Relocate(caster); } if (m_targetMask & TARGET_FLAG_DEST_LOCATION) { data.readPackGUID(m_dst._transportGUID); if (m_dst._transportGUID) data >> m_dst._transportOffset.PositionXYZStream(); else data >> m_dst._position.PositionXYZStream(); } else { m_dst._transportGUID = caster->GetTransGUID(); if (m_dst._transportGUID) m_dst._transportOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO()); else m_dst._position.Relocate(caster); } if (m_targetMask & TARGET_FLAG_STRING) data >> m_strTarget; Update(caster); } void SpellCastTargets::Write(ByteBuffer& data) { data << uint32(m_targetMask); if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_CORPSE_ALLY | TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_UNIT_MINIPET)) data.appendPackGUID(m_objectTargetGUID); if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM)) { if (m_itemTarget) data.append(m_itemTarget->GetPackGUID()); else data << uint8(0); } if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) { data.appendPackGUID(m_src._transportGUID); // relative position guid here - transport for example if (m_src._transportGUID) data << m_src._transportOffset.PositionXYZStream(); else data << m_src._position.PositionXYZStream(); } if (m_targetMask & TARGET_FLAG_DEST_LOCATION) { data.appendPackGUID(m_dst._transportGUID); // relative position guid here - transport for example if (m_dst._transportGUID) data << m_dst._transportOffset.PositionXYZStream(); else data << m_dst._position.PositionXYZStream(); } if (m_targetMask & TARGET_FLAG_STRING) data << m_strTarget; } uint64 SpellCastTargets::GetUnitTargetGUID() const { switch (GUID_HIPART(m_objectTargetGUID)) { case HIGHGUID_PLAYER: case HIGHGUID_VEHICLE: case HIGHGUID_UNIT: case HIGHGUID_PET: return m_objectTargetGUID; default: return 0LL; } } Unit* SpellCastTargets::GetUnitTarget() const { if (m_objectTarget) return m_objectTarget->ToUnit(); return NULL; } void SpellCastTargets::SetUnitTarget(Unit* target) { if (!target) return; m_objectTarget = target; m_objectTargetGUID = target->GetGUID(); m_targetMask |= TARGET_FLAG_UNIT; } uint64 SpellCastTargets::GetGOTargetGUID() const { switch (GUID_HIPART(m_objectTargetGUID)) { case HIGHGUID_TRANSPORT: case HIGHGUID_MO_TRANSPORT: case HIGHGUID_GAMEOBJECT: return m_objectTargetGUID; default: return 0LL; } } GameObject* SpellCastTargets::GetGOTarget() const { if (m_objectTarget) return m_objectTarget->ToGameObject(); return NULL; } void SpellCastTargets::SetGOTarget(GameObject* target) { if (!target) return; m_objectTarget = target; m_objectTargetGUID = target->GetGUID(); m_targetMask |= TARGET_FLAG_GAMEOBJECT; } uint64 SpellCastTargets::GetCorpseTargetGUID() const { switch (GUID_HIPART(m_objectTargetGUID)) { case HIGHGUID_CORPSE: return m_objectTargetGUID; default: return 0LL; } } Corpse* SpellCastTargets::GetCorpseTarget() const { if (m_objectTarget) return m_objectTarget->ToCorpse(); return NULL; } WorldObject* SpellCastTargets::GetObjectTarget() const { return m_objectTarget; } uint64 SpellCastTargets::GetObjectTargetGUID() const { return m_objectTargetGUID; } void SpellCastTargets::RemoveObjectTarget() { m_objectTarget = NULL; m_objectTargetGUID = 0LL; m_targetMask &= ~(TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK); } void SpellCastTargets::SetItemTarget(Item* item) { if (!item) return; m_itemTarget = item; m_itemTargetGUID = item->GetGUID(); m_itemTargetEntry = item->GetEntry(); m_targetMask |= TARGET_FLAG_ITEM; } void SpellCastTargets::SetTradeItemTarget(Player* caster) { m_itemTargetGUID = uint64(TRADE_SLOT_NONTRADED); m_itemTargetEntry = 0; m_targetMask |= TARGET_FLAG_TRADE_ITEM; Update(caster); } void SpellCastTargets::UpdateTradeSlotItem() { if (m_itemTarget && (m_targetMask & TARGET_FLAG_TRADE_ITEM)) { m_itemTargetGUID = m_itemTarget->GetGUID(); m_itemTargetEntry = m_itemTarget->GetEntry(); } } SpellDestination const* SpellCastTargets::GetSrc() const { return &m_src; } Position const* SpellCastTargets::GetSrcPos() const { return &m_src._position; } void SpellCastTargets::SetSrc(float x, float y, float z) { m_src = SpellDestination(x, y, z); m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::SetSrc(Position const& pos) { m_src = SpellDestination(pos); m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::SetSrc(WorldObject const& wObj) { m_src = SpellDestination(wObj); m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::ModSrc(Position const& pos) { ASSERT(m_targetMask & TARGET_FLAG_SOURCE_LOCATION); if (m_src._transportGUID) { Position offset; m_src._position.GetPositionOffsetTo(pos, offset); m_src._transportOffset.RelocateOffset(offset); } m_src._position.Relocate(pos); } void SpellCastTargets::RemoveSrc() { m_targetMask &= ~(TARGET_FLAG_SOURCE_LOCATION); } SpellDestination const* SpellCastTargets::GetDst() const { return &m_dst; } WorldLocation const* SpellCastTargets::GetDstPos() const { return &m_dst._position; } void SpellCastTargets::SetDst(float x, float y, float z, float orientation, uint32 mapId) { m_dst = SpellDestination(x, y, z, orientation, mapId); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::SetDst(Position const& pos) { m_dst = SpellDestination(pos); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::SetDst(WorldObject const& wObj) { m_dst = SpellDestination(wObj); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::SetDst(SpellCastTargets const& spellTargets) { m_dst = spellTargets.m_dst; m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::ModDst(Position const& pos) { ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION); if (m_dst._transportGUID) { Position offset; m_dst._position.GetPositionOffsetTo(pos, offset); m_dst._transportOffset.RelocateOffset(offset); } m_dst._position.Relocate(pos); } void SpellCastTargets::RemoveDst() { m_targetMask &= ~(TARGET_FLAG_DEST_LOCATION); } void SpellCastTargets::Update(Unit* caster) { m_objectTarget = m_objectTargetGUID ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : NULL; m_itemTarget = NULL; if (caster->GetTypeId() == TYPEID_PLAYER) { Player* player = caster->ToPlayer(); if (m_targetMask & TARGET_FLAG_ITEM) m_itemTarget = player->GetItemByGuid(m_itemTargetGUID); else if (m_targetMask & TARGET_FLAG_TRADE_ITEM) if (m_itemTargetGUID == TRADE_SLOT_NONTRADED) // here it is not guid but slot. Also prevents hacking slots if (TradeData* pTrade = player->GetTradeData()) m_itemTarget = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED); if (m_itemTarget) m_itemTargetEntry = m_itemTarget->GetEntry(); } // update positions by transport move if (HasSrc() && m_src._transportGUID) { if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_src._transportGUID)) { m_src._position.Relocate(transport); m_src._position.RelocateOffset(m_src._transportOffset); } } if (HasDst() && m_dst._transportGUID) { if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_dst._transportGUID)) { m_dst._position.Relocate(transport); m_dst._position.RelocateOffset(m_dst._transportOffset); } } } void SpellCastTargets::OutDebug() const { if (!m_targetMask) sLog->outString("No targets"); sLog->outString("target mask: %u", m_targetMask); if (m_targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK)) sLog->outString("Object target: " UI64FMTD, m_objectTargetGUID); if (m_targetMask & TARGET_FLAG_ITEM) sLog->outString("Item target: " UI64FMTD, m_itemTargetGUID); if (m_targetMask & TARGET_FLAG_TRADE_ITEM) sLog->outString("Trade item target: " UI64FMTD, m_itemTargetGUID); if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) sLog->outString("Source location: transport guid:" UI64FMTD " trans offset: %s position: %s", m_src._transportGUID, m_src._transportOffset.ToString().c_str(), m_src._position.ToString().c_str()); if (m_targetMask & TARGET_FLAG_DEST_LOCATION) sLog->outString("Destination location: transport guid:" UI64FMTD " trans offset: %s position: %s", m_dst._transportGUID, m_dst._transportOffset.ToString().c_str(), m_dst._position.ToString().c_str()); if (m_targetMask & TARGET_FLAG_STRING) sLog->outString("String: %s", m_strTarget.c_str()); sLog->outString("speed: %f", m_speed); sLog->outString("elevation: %f", m_elevation); } SpellValue::SpellValue(SpellInfo const* proto) { for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) EffectBasePoints[i] = proto->Effects[i].BasePoints; MaxAffectedTargets = proto->MaxAffectedTargets; RadiusMod = 1.0f; AuraStackAmount = 1; } Spell::Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, uint64 originalCasterGUID, bool skipCheck) : m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, caster)), m_caster((info->AttributesEx6 & SPELL_ATTR6_CAST_BY_CHARMER && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster) , m_spellValue(new SpellValue(m_spellInfo)) { m_customError = SPELL_CUSTOM_ERROR_NONE; m_skipCheck = skipCheck; m_selfContainer = NULL; m_referencedFromCurrentSpell = false; m_executedCurrently = false; m_needComboPoints = m_spellInfo->NeedsComboPoints(); m_comboPointGain = 0; m_delayStart = 0; m_delayAtDamageCount = 0; m_applyMultiplierMask = 0; m_auraScaleMask = 0; // Get data for type of attack switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND) m_attackType = OFF_ATTACK; else m_attackType = BASE_ATTACK; break; case SPELL_DAMAGE_CLASS_RANGED: m_attackType = m_spellInfo->IsRangedWeaponSpell() ? RANGED_ATTACK : BASE_ATTACK; break; default: // Wands if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) m_attackType = RANGED_ATTACK; else m_attackType = BASE_ATTACK; break; } m_spellSchoolMask = info->GetSchoolMask(); // Can be override for some spell (wand shoot for example) if (m_attackType == RANGED_ATTACK) // wand case if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER) if (Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK)) m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetTemplate()->DamageType); if (originalCasterGUID) m_originalCasterGUID = originalCasterGUID; else m_originalCasterGUID = m_caster->GetGUID(); if (m_originalCasterGUID == m_caster->GetGUID()) m_originalCaster = m_caster; else { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL; } m_spellState = SPELL_STATE_NULL; _triggeredCastFlags = triggerFlags; if (info->AttributesEx4 & SPELL_ATTR4_TRIGGERED) _triggeredCastFlags = TRIGGERED_FULL_MASK; _CastItem = NULL; m_castItemGUID = 0; unitTarget = NULL; itemTarget = NULL; gameObjTarget = NULL; focusObject = NULL; _cast_count = 0; m_glyphIndex = 0; m_preCastSpell = 0; m_triggeredByAuraSpell = NULL; m_spellAura = NULL; //Auto Shot & Shoot (wand) m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell(); m_runesState = 0; m_powerCost = 0; // setup to correct value in Spell::prepare, must not be used before. m_casttime = 0; // setup to correct value in Spell::prepare, must not be used before. _timer = 0; // will set to castime in prepare m_channelTargetEffectMask = 0; // Determine if spell can be reflected back to the caster // Patch 1.2 notes: Spell Reflection no longer reflects abilities m_canReflect = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->Attributes & SPELL_ATTR0_ABILITY) && !(m_spellInfo->AttributesEx & SPELL_ATTR1_CANT_BE_REFLECTED) && !(m_spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) && !m_spellInfo->IsPassive() && !m_spellInfo->IsPositive(); CleanupTargetList(); CleanupEffectExecuteData(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) m_destTargets[i] = SpellDestination(*m_caster); } Spell::~Spell() { // unload scripts while (!m_loadedScripts.empty()) { std::list<SpellScript*>::iterator itr = m_loadedScripts.begin(); (*itr)->_Unload(); delete (*itr); m_loadedScripts.erase(itr); } if (m_referencedFromCurrentSpell && m_selfContainer && *m_selfContainer == this) { // Clean the reference to avoid later crash. // If this error is repeating, we may have to add an ASSERT to better track down how we get into this case. sLog->outError("SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id); *m_selfContainer = NULL; } if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER) ASSERT(m_caster->ToPlayer()->m_spellModTakingSpell != this); delete m_spellValue; CheckEffectExecuteData(); } void Spell::InitExplicitTargets(SpellCastTargets const& targets) { m_targets = targets; // this function tries to correct spell explicit targets for spell // client doesn't send explicit targets correctly sometimes - we need to fix such spells serverside // this also makes sure that we correctly send explicit targets to client (removes redundant data) uint32 neededTargets = m_spellInfo->GetExplicitTargetMask(); if (WorldObject* target = m_targets.GetObjectTarget()) { // check if object target is valid with needed target flags // for unit case allow corpse target mask because player with not released corpse is a unit target if ((target->ToUnit() && !(neededTargets & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK))) || (target->ToGameObject() && !(neededTargets & TARGET_FLAG_GAMEOBJECT_MASK)) || (target->ToCorpse() && !(neededTargets & TARGET_FLAG_CORPSE_MASK))) m_targets.RemoveObjectTarget(); } else { // try to select correct unit target if not provided by client or by serverside cast if (neededTargets & (TARGET_FLAG_UNIT_MASK)) { Unit* unit = NULL; // try to use player selection as a target if (Player* playerCaster = m_caster->ToPlayer()) { // selection has to be found and to be valid target for the spell if (Unit* selectedUnit = ObjectAccessor::GetUnit(*m_caster, playerCaster->GetSelection())) if (m_spellInfo->CheckExplicitTarget(m_caster, selectedUnit) == SPELL_CAST_OK) unit = selectedUnit; } // try to use attacked unit as a target else if ((m_caster->GetTypeId() == TYPEID_UNIT) && neededTargets & (TARGET_FLAG_UNIT_ENEMY | TARGET_FLAG_UNIT)) unit = m_caster->getVictim(); // didn't find anything - let's use self as target if (!unit && neededTargets & (TARGET_FLAG_UNIT_RAID | TARGET_FLAG_UNIT_PARTY | TARGET_FLAG_UNIT_ALLY)) unit = m_caster; m_targets.SetUnitTarget(unit); } } // check if spell needs dst target if (neededTargets & TARGET_FLAG_DEST_LOCATION) { // and target isn't set if (!m_targets.HasDst()) { // try to use unit target if provided if (WorldObject* target = targets.GetObjectTarget()) m_targets.SetDst(*target); // or use self if not available else m_targets.SetDst(*m_caster); } } else m_targets.RemoveDst(); if (neededTargets & TARGET_FLAG_SOURCE_LOCATION) { if (!targets.HasSrc()) m_targets.SetSrc(*m_caster); } else m_targets.RemoveSrc(); } void Spell::SelectExplicitTargets() { // here go all explicit target changes made to explicit targets after spell prepare phase is finished if (Unit* target = m_targets.GetUnitTarget()) { // check for explicit target redirection, for Grounding Totem for example if (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT_ENEMY || (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT && !m_spellInfo->IsPositive())) { Unit* redirect; switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: redirect = m_caster->GetMagicHitRedirectTarget(target, m_spellInfo); break; case SPELL_DAMAGE_CLASS_MELEE: case SPELL_DAMAGE_CLASS_RANGED: redirect = m_caster->GetMeleeHitRedirectTarget(target, m_spellInfo); break; default: redirect = NULL; break; } if (redirect && (redirect != target)) m_targets.SetUnitTarget(redirect); } } } void Spell::SelectSpellTargets() { // select targets for cast phase SelectExplicitTargets(); uint32 processedAreaEffectsMask = 0; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { // not call for empty effect. // Also some spells use not used effect targets for store targets for dummy effect in triggered spells if (!m_spellInfo->Effects[i].IsEffect()) continue; // set expected type of implicit targets to be sent to client uint32 implicitTargetMask = GetTargetFlagMask(m_spellInfo->Effects[i].TargetA.GetObjectType()) | GetTargetFlagMask(m_spellInfo->Effects[i].TargetB.GetObjectType()); if (implicitTargetMask & TARGET_FLAG_UNIT) m_targets.SetTargetFlag(TARGET_FLAG_UNIT); if (implicitTargetMask & (TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_GAMEOBJECT_ITEM)) m_targets.SetTargetFlag(TARGET_FLAG_GAMEOBJECT); SelectEffectImplicitTargets(SpellEffIndex(i), m_spellInfo->Effects[i].TargetA, processedAreaEffectsMask); SelectEffectImplicitTargets(SpellEffIndex(i), m_spellInfo->Effects[i].TargetB, processedAreaEffectsMask); // Select targets of effect based on effect type // those are used when no valid target could be added for spell effect based on spell target type // some spell effects use explicit target as a default target added to target map (like SPELL_EFFECT_LEARN_SPELL) // some spell effects add target to target map only when target type specified (like SPELL_EFFECT_WEAPON) // some spell effects don't add anything to target map (confirmed with sniffs) (like SPELL_EFFECT_DESTROY_ALL_TOTEMS) SelectEffectTypeImplicitTargets(i); if (m_targets.HasDst()) AddDestTarget(*m_targets.GetDst(), i); if (m_spellInfo->IsChanneled()) { uint8 mask = (1 << i); for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->effectMask & mask) { m_channelTargetEffectMask |= mask; break; } } } else if (m_auraScaleMask) { bool checkLvl = !m_UniqueTargetInfo.empty(); for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();) { // remove targets which did not pass min level check if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask) { // Do not check for selfcast if (!ihit->scaleAura && ihit->targetGUID != m_caster->GetGUID()) { m_UniqueTargetInfo.erase(ihit++); continue; } } ++ihit; } if (checkLvl && m_UniqueTargetInfo.empty()) { SendCastResult(SPELL_FAILED_LOWLEVEL); finish(false); } } } if (m_targets.HasDst()) { if (m_targets.HasTraj()) { float speed = m_targets.GetSpeedXY(); if (speed > 0.0f) m_delayMoment = (uint64)floor(m_targets.GetDist2d() / speed * 1000.0f); } else if (m_spellInfo->Speed > 0.0f) { float dist = m_caster->GetDistance(*m_targets.GetDstPos()); m_delayMoment = (uint64) floor(dist / m_spellInfo->Speed * 1000.0f); } } } void Spell::SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32& processedEffectMask) { if (!targetType.GetTarget()) return; uint32 effectMask = 1 << effIndex; // set the same target list for all effects // some spells appear to need this, however this requires more research switch (targetType.GetSelectionCategory()) { case TARGET_SELECT_CATEGORY_NEARBY: case TARGET_SELECT_CATEGORY_CONE: case TARGET_SELECT_CATEGORY_AREA: // targets for effect already selected if (effectMask & processedEffectMask) return; // choose which targets we can select at once for (uint32 j = effIndex + 1; j < MAX_SPELL_EFFECTS; ++j) if (GetSpellInfo()->Effects[effIndex].TargetA.GetTarget() == GetSpellInfo()->Effects[j].TargetA.GetTarget() && GetSpellInfo()->Effects[effIndex].TargetB.GetTarget() == GetSpellInfo()->Effects[j].TargetB.GetTarget() && GetSpellInfo()->Effects[effIndex].ImplicitTargetConditions == GetSpellInfo()->Effects[j].ImplicitTargetConditions && GetSpellInfo()->Effects[effIndex].CalcRadius(m_caster) == GetSpellInfo()->Effects[j].CalcRadius(m_caster)) effectMask |= 1 << j; processedEffectMask |= effectMask; break; default: break; } switch (targetType.GetSelectionCategory()) { case TARGET_SELECT_CATEGORY_CHANNEL: SelectImplicitChannelTargets(effIndex, targetType); break; case TARGET_SELECT_CATEGORY_NEARBY: SelectImplicitNearbyTargets(effIndex, targetType, effectMask); break; case TARGET_SELECT_CATEGORY_CONE: SelectImplicitConeTargets(effIndex, targetType, effectMask); break; case TARGET_SELECT_CATEGORY_AREA: SelectImplicitAreaTargets(effIndex, targetType, effectMask); break; case TARGET_SELECT_CATEGORY_DEFAULT: switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_SRC: switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_CASTER: m_targets.SetSrc(*m_caster); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_SRC"); break; } break; case TARGET_OBJECT_TYPE_DEST: switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_CASTER: SelectImplicitCasterDestTargets(effIndex, targetType); break; case TARGET_REFERENCE_TYPE_TARGET: SelectImplicitTargetDestTargets(effIndex, targetType); break; case TARGET_REFERENCE_TYPE_DEST: SelectImplicitDestDestTargets(effIndex, targetType); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_DEST"); break; } break; default: switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_CASTER: SelectImplicitCasterObjectTargets(effIndex, targetType); break; case TARGET_REFERENCE_TYPE_TARGET: SelectImplicitTargetObjectTargets(effIndex, targetType); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT"); break; } break; } break; case TARGET_SELECT_CATEGORY_NYI: sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: target type %u, found in spellID %u, effect %u is not implemented yet!", m_spellInfo->Id, effIndex, targetType.GetTarget()); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target category"); break; } } void Spell::SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) { ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target reference type"); return; } Spell* channeledSpell = m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL); if (!channeledSpell) { sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::SelectImplicitChannelTargets: cannot find channel spell for spell ID %u, effect %u", m_spellInfo->Id, effIndex); return; } switch (targetType.GetTarget()) { case TARGET_UNIT_CHANNEL_TARGET: { WorldObject* target = ObjectAccessor::GetUnit(*m_caster, channeledSpell->m_targets.GetUnitTargetGUID()); CallScriptObjectTargetSelectHandlers(target, effIndex); // unit target may be no longer available - teleported out of map for example if (target && target->ToUnit()) AddUnitTarget(target->ToUnit(), 1 << effIndex); else sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: cannot find channel spell target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); break; } case TARGET_DEST_CHANNEL_TARGET: if (channeledSpell->m_targets.HasDst()) m_targets.SetDst(channeledSpell->m_targets); else if (WorldObject* target = ObjectAccessor::GetWorldObject(*m_caster, channeledSpell->m_targets.GetObjectTargetGUID())) { CallScriptObjectTargetSelectHandlers(target, effIndex); m_targets.SetDst(*target); } else sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: cannot find channel spell destination for spell ID %u, effect %u", m_spellInfo->Id, effIndex); break; case TARGET_DEST_CHANNEL_CASTER: m_targets.SetDst(*channeledSpell->GetCaster()); break; default: ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target type"); break; } } void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) { ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target reference type"); return; } float range = 0.0f; switch (targetType.GetCheckType()) { case TARGET_CHECK_ENEMY: range = m_spellInfo->GetMaxRange(false, m_caster, this); break; case TARGET_CHECK_ALLY: case TARGET_CHECK_PARTY: case TARGET_CHECK_RAID: case TARGET_CHECK_RAID_CLASS: range = m_spellInfo->GetMaxRange(true, m_caster, this); break; case TARGET_CHECK_ENTRY: case TARGET_CHECK_DEFAULT: range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive(), m_caster, this); break; default: ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented selection check type"); break; } ConditionList* condList = m_spellInfo->Effects[effIndex].ImplicitTargetConditions; // handle emergency case - try to use other provided targets if no conditions provided if (targetType.GetCheckType() == TARGET_CHECK_ENTRY && (!condList || condList->empty())) { sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::SelectImplicitNearbyTargets: no conditions entry for target with TARGET_CHECK_ENTRY of spell ID %u, effect %u - selecting default targets", m_spellInfo->Id, effIndex); switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_GOBJ: if (m_spellInfo->RequiresSpellFocus) { if (focusObject) AddGOTarget(focusObject, effMask); return; } break; case TARGET_OBJECT_TYPE_DEST: if (m_spellInfo->RequiresSpellFocus) { if (focusObject) m_targets.SetDst(*focusObject); return; } break; default: break; } } WorldObject* target = SearchNearbyTarget(range, targetType.GetObjectType(), targetType.GetCheckType(), condList); if (!target) { sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::SelectImplicitNearbyTargets: cannot find nearby target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); return; } CallScriptObjectTargetSelectHandlers(target, effIndex); switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_UNIT: if (Unit* unitTarget = target->ToUnit()) AddUnitTarget(unitTarget, effMask, true, false); break; case TARGET_OBJECT_TYPE_GOBJ: if (GameObject* gobjTarget = target->ToGameObject()) AddGOTarget(gobjTarget, effMask); break; case TARGET_OBJECT_TYPE_DEST: m_targets.SetDst(*target); break; default: ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target object type"); break; } SelectImplicitChainTargets(effIndex, targetType, target, effMask); } void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) { ASSERT(false && "Spell::SelectImplicitConeTargets: received not implemented target reference type"); return; } std::list<WorldObject*> targets; SpellTargetObjectTypes objectType = targetType.GetObjectType(); SpellTargetCheckTypes selectionType = targetType.GetCheckType(); ConditionList* condList = m_spellInfo->Effects[effIndex].ImplicitTargetConditions; float coneAngle = M_PI/2; float radius = m_spellInfo->Effects[effIndex].CalcRadius(m_caster) * m_spellValue->RadiusMod; if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList)) { SkyFire::WorldObjectSpellConeTargetCheck check(coneAngle, radius, m_caster, m_spellInfo, selectionType, condList); SkyFire::WorldObjectListSearcher<SkyFire::WorldObjectSpellConeTargetCheck> searcher(m_caster, targets, check, containerTypeMask); SearchTargets<SkyFire::WorldObjectListSearcher<SkyFire::WorldObjectSpellConeTargetCheck> >(searcher, containerTypeMask, m_caster, m_caster, radius); CallScriptObjectAreaTargetSelectHandlers(targets, effIndex); if (!targets.empty()) { // Other special target selection goes here if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) { Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) if ((*j)->IsAffectedOnSpell(m_spellInfo)) maxTargets += (*j)->GetAmount(); SkyFire::Containers::RandomResizeList(targets, maxTargets); } // for compability with older code - add only unit and go targets // TODO: remove this std::list<Unit*> unitTargets; std::list<GameObject*> gObjTargets; for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) { if (Unit* unitTarget = (*itr)->ToUnit()) unitTargets.push_back(unitTarget); else if (GameObject* gObjTarget = (*itr)->ToGameObject()) gObjTargets.push_back(gObjTarget); } for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr) AddUnitTarget(*itr, effMask, false); for (std::list<GameObject*>::iterator itr = gObjTargets.begin(); itr != gObjTargets.end(); ++itr) AddGOTarget(*itr, effMask); } } } void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { Unit* referer = NULL; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: case TARGET_REFERENCE_TYPE_DEST: case TARGET_REFERENCE_TYPE_CASTER: referer = m_caster; break; case TARGET_REFERENCE_TYPE_TARGET: referer = m_targets.GetUnitTarget(); break; case TARGET_REFERENCE_TYPE_LAST: { // find last added target for this effect for (std::list<TargetInfo>::reverse_iterator ihit = m_UniqueTargetInfo.rbegin(); ihit != m_UniqueTargetInfo.rend(); ++ihit) { if (ihit->effectMask & (1<<effIndex)) { referer = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); break; } } break; } default: ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); return; } if (!referer) return; Position const* center = NULL; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: center = m_targets.GetSrcPos(); break; case TARGET_REFERENCE_TYPE_DEST: center = m_targets.GetDstPos(); break; case TARGET_REFERENCE_TYPE_CASTER: case TARGET_REFERENCE_TYPE_TARGET: case TARGET_REFERENCE_TYPE_LAST: center = referer; break; default: ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); return; } std::list<WorldObject*> targets; float radius = m_spellInfo->Effects[effIndex].CalcRadius(m_caster) * m_spellValue->RadiusMod; SearchAreaTargets(targets, radius, center, referer, targetType.GetObjectType(), targetType.GetCheckType(), m_spellInfo->Effects[effIndex].ImplicitTargetConditions); // Custom entries // TODO: remove those switch (m_spellInfo->Id) { case 46584: // Raise Dead { if (Player* playerCaster = m_caster->ToPlayer()) { for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) { switch ((*itr)->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: { Unit* unitTarget = (*itr)->ToUnit(); if (unitTarget->isAlive() || !playerCaster->isHonorOrXPTarget(unitTarget) || ((unitTarget->GetCreatureTypeMask() & (1 << (CREATURE_TYPE_HUMANOID-1))) == 0) || (unitTarget->GetDisplayId() != unitTarget->GetNativeDisplayId())) break; AddUnitTarget(unitTarget, effMask, false); // no break; } case TYPEID_CORPSE: // wont work until corpses are allowed in target lists, but at least will send dest in packet m_targets.SetDst(*(*itr)); return; // nothing more to do here default: break; } } } return; // don't add targets to target map } // Corpse Explosion case 49158: case 51325: case 51326: case 51327: case 51328: // check if our target is not valid (spell can target ghoul or dead unit) if (!(m_targets.GetUnitTarget() && m_targets.GetUnitTarget()->GetDisplayId() == m_targets.GetUnitTarget()->GetNativeDisplayId() && ((m_targets.GetUnitTarget()->GetEntry() == 26125 && m_targets.GetUnitTarget()->GetOwnerGUID() == m_caster->GetGUID()) || m_targets.GetUnitTarget()->isDead()))) { // remove existing targets CleanupTargetList(); for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) { switch ((*itr)->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: if (!(*itr)->ToUnit()->isDead()) break; AddUnitTarget((*itr)->ToUnit(), 1 << effIndex, false); return; default: break; } } if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true); SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW); finish(false); } return; default: break; } CallScriptObjectAreaTargetSelectHandlers(targets, effIndex); std::list<Unit*> unitTargets; std::list<GameObject*> gObjTargets; // for compability with older code - add only unit and go targets // TODO: remove this for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) { if (Unit* unitTarget = (*itr)->ToUnit()) unitTargets.push_back(unitTarget); else if (GameObject* gObjTarget = (*itr)->ToGameObject()) gObjTargets.push_back(gObjTarget); } if (!unitTargets.empty()) { // Special target selection for smart heals and energizes uint32 maxSize = 0; int32 power = -1; switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch (m_spellInfo->Id) { case 52759: // Ancestral Awakening case 71610: // Echoes of Light (Althor's Abacus normal version) case 71641: // Echoes of Light (Althor's Abacus heroic version) maxSize = 1; power = POWER_HEALTH; break; case 54968: // Glyph of Holy Light maxSize = m_spellInfo->MaxAffectedTargets; power = POWER_HEALTH; break; case 57669: // Replenishment // In arenas Replenishment may only affect the caster if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->InArena()) { unitTargets.clear(); unitTargets.push_back(m_caster); break; } maxSize = 10; power = POWER_MANA; break; default: break; } break; case SPELLFAMILY_PRIEST: if (m_spellInfo->SpellFamilyFlags[0] == 0x10000000) // Circle of Healing { maxSize = m_caster->HasAura(55675) ? 6 : 5; // Glyph of Circle of Healing power = POWER_HEALTH; } else if (m_spellInfo->Id == 64844) // Divine Hymn { maxSize = 3; power = POWER_HEALTH; } else if (m_spellInfo->Id == 64904) // Hymn of Hope { maxSize = 3; power = POWER_MANA; } else break; // Remove targets outside caster's raid for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end();) { if (!(*itr)->IsInRaidWith(m_caster)) itr = unitTargets.erase(itr); else ++itr; } break; case SPELLFAMILY_DRUID: if (m_spellInfo->SpellFamilyFlags[1] == 0x04000000) // Wild Growth { maxSize = m_caster->HasAura(62970) ? 6 : 5; // Glyph of Wild Growth power = POWER_HEALTH; } else if (m_spellInfo->SpellFamilyFlags[2] == 0x0100) // Starfall { // Remove targets not in LoS or in stealth that are not being detected for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end();) { if (((*itr)->HasStealthAura() && !m_caster->canSeeOrDetect(*itr)) || (*itr)->HasInvisibilityAura() || !(*itr)->IsWithinLOSInMap(m_caster)) itr = unitTargets.erase(itr); else ++itr; } break; } else break; // Remove targets outside caster's raid for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end();) if (!(*itr)->IsInRaidWith(m_caster)) itr = unitTargets.erase(itr); else ++itr; break; default: break; } if (maxSize && power != -1) { if (Powers(power) == POWER_HEALTH) { if (unitTargets.size() > maxSize) { unitTargets.sort(SkyFire::HealthPctOrderPred()); unitTargets.resize(maxSize); } } else { for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end();) if ((*itr)->getPowerType() != (Powers)power) itr = unitTargets.erase(itr); else ++itr; if (unitTargets.size() > maxSize) { unitTargets.sort(SkyFire::PowerPctOrderPred((Powers)power)); unitTargets.resize(maxSize); } } } // Other special target selection goes here if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) { Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) if ((*j)->IsAffectedOnSpell(m_spellInfo)) maxTargets += (*j)->GetAmount(); if (m_spellInfo->Id == 5246) //Intimidating Shout unitTargets.remove(m_targets.GetUnitTarget()); SkyFire::Containers::RandomResizeList(unitTargets, maxTargets); } for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr) AddUnitTarget(*itr, effMask, false); } if (!gObjTargets.empty()) { if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) { Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) if ((*j)->IsAffectedOnSpell(m_spellInfo)) maxTargets += (*j)->GetAmount(); SkyFire::Containers::RandomResizeList(gObjTargets, maxTargets); } for (std::list<GameObject*>::iterator itr = gObjTargets.begin(); itr != gObjTargets.end(); ++itr) AddGOTarget(*itr, effMask); } } void Spell::SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { switch (targetType.GetTarget()) { case TARGET_DEST_CASTER: m_targets.SetDst(*m_caster); return; case TARGET_DEST_HOME: if (Player* playerCaster = m_caster->ToPlayer()) m_targets.SetDst(playerCaster->_homebindX, playerCaster->_homebindY, playerCaster->_homebindZ, playerCaster->GetOrientation(), playerCaster->_homebindMapId); return; case TARGET_DEST_DB: if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id)) { // TODO: fix this check if (m_spellInfo->HasEffect(SPELL_EFFECT_TELEPORT_UNITS)) m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId); else if (st->target_mapId == m_caster->GetMapId()) m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation); } else { sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id); WorldObject* target = m_targets.GetObjectTarget(); m_targets.SetDst(target ? *target : *m_caster); } return; case TARGET_DEST_CASTER_FISHING: { float min_dis = m_spellInfo->GetMinRange(true); float max_dis = m_spellInfo->GetMaxRange(true); float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; float x, y, z, angle; angle = (float)rand_norm() * static_cast<float>(M_PI * 35.0f / 180.0f) - static_cast<float>(M_PI * 17.5f / 180.0f); m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, angle); m_targets.SetDst(x, y, z, m_caster->GetOrientation()); return; } default: break; } float dist; float angle = targetType.CalcDirectionAngle(); float objSize = m_caster->GetObjectSize(); if (targetType.GetTarget() == TARGET_DEST_CASTER_SUMMON) dist = PET_FOLLOW_DIST; else dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); if (dist < objSize) dist = objSize; else if (targetType.GetTarget() == TARGET_DEST_CASTER_RANDOM) dist = objSize + (dist - objSize) * (float)rand_norm(); Position pos; if (targetType.GetTarget() == TARGET_DEST_CASTER_FRONT_LEAP) m_caster->GetFirstCollisionPosition(pos, dist, angle); else m_caster->GetNearPosition(pos, dist, angle); m_targets.SetDst(*m_caster); m_targets.ModDst(pos); } void Spell::SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { WorldObject* target = m_targets.GetObjectTarget(); switch (targetType.GetTarget()) { case TARGET_DEST_TARGET_ENEMY: case TARGET_DEST_TARGET_ANY: m_targets.SetDst(*target); return; default: break; } float angle = targetType.CalcDirectionAngle(); float objSize = target->GetObjectSize(); float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); if (dist < objSize) dist = objSize; else if (targetType.GetTarget() == TARGET_DEST_TARGET_RANDOM) dist = objSize + (dist - objSize) * (float)rand_norm(); Position pos; target->GetNearPosition(pos, dist, angle); m_targets.SetDst(*target); m_targets.ModDst(pos); } void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { // set destination to caster if no dest provided // can only happen if previous destination target could not be set for some reason // (not found nearby target, or channel target for example // maybe we should abort the spell in such case? if (!m_targets.HasDst()) m_targets.SetDst(*m_caster); switch (targetType.GetTarget()) { case TARGET_DEST_DYNOBJ_ENEMY: case TARGET_DEST_DYNOBJ_ALLY: case TARGET_DEST_DYNOBJ_ALL_UNITS: case TARGET_DEST_DEST: return; case TARGET_DEST_TRAJ: SelectImplicitTrajTargets(); return; default: break; } float angle = targetType.CalcDirectionAngle(); float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); if (targetType.GetTarget() == TARGET_DEST_DEST_RANDOM) dist *= (float)rand_norm(); Position pos = *m_targets.GetDstPos(); m_caster->MovePosition(pos, dist, angle); m_targets.ModDst(pos); } void Spell::SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { WorldObject* target = NULL; bool checkIfValid = true; switch (targetType.GetTarget()) { case TARGET_UNIT_CASTER: target = m_caster; checkIfValid = false; break; case TARGET_UNIT_MASTER: target = m_caster->GetCharmerOrOwner(); break; case TARGET_UNIT_PET: target = m_caster->GetGuardianPet(); break; case TARGET_UNIT_SUMMONER: if (m_caster->isSummon()) target = m_caster->ToTempSummon()->GetSummoner(); break; case TARGET_UNIT_VEHICLE: target = m_caster->GetVehicleBase(); break; case TARGET_UNIT_PASSENGER_0: case TARGET_UNIT_PASSENGER_1: case TARGET_UNIT_PASSENGER_2: case TARGET_UNIT_PASSENGER_3: case TARGET_UNIT_PASSENGER_4: case TARGET_UNIT_PASSENGER_5: case TARGET_UNIT_PASSENGER_6: case TARGET_UNIT_PASSENGER_7: if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsVehicle()) target = m_caster->GetVehicleKit()->GetPassenger(targetType.GetTarget() - TARGET_UNIT_PASSENGER_0); break; default: break; } CallScriptObjectTargetSelectHandlers(target, effIndex); if (target && target->ToUnit()) AddUnitTarget(target->ToUnit(), 1 << effIndex, checkIfValid); } void Spell::SelectImplicitTargetObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { ASSERT((m_targets.GetObjectTarget() || m_targets.GetItemTarget()) && "Spell::SelectImplicitTargetObjectTargets - no explicit object or item target available!"); WorldObject* target = m_targets.GetObjectTarget(); CallScriptObjectTargetSelectHandlers(target, effIndex); if (target) { if (Unit* unit = target->ToUnit()) AddUnitTarget(unit, 1 << effIndex, true, false); else if (GameObject* gobj = target->ToGameObject()) AddGOTarget(gobj, 1 << effIndex); SelectImplicitChainTargets(effIndex, targetType, target, 1 << effIndex); } // Script hook can remove object target and we would wrongly land here else if (Item* item = m_targets.GetItemTarget()) AddItemTarget(item, 1 << effIndex); } void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, WorldObject* target, uint32 effMask) { uint32 maxTargets = m_spellInfo->Effects[effIndex].ChainTarget; if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this); if (maxTargets > 1) { // mark damage multipliers as used for (uint32 k = effIndex; k < MAX_SPELL_EFFECTS; ++k) if (effMask & (1 << k)) m_damageMultipliers[k] = 1.0f; m_applyMultiplierMask |= effMask; std::list<WorldObject*> targets; SearchChainTargets(targets, maxTargets - 1, target, targetType.GetObjectType(), targetType.GetCheckType(), m_spellInfo->Effects[effIndex].ImplicitTargetConditions, targetType.GetTarget() == TARGET_UNIT_TARGET_CHAINHEAL_ALLY); // Chain primary target is added earlier CallScriptObjectAreaTargetSelectHandlers(targets, effIndex); // for backward compability std::list<Unit*> unitTargets; for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) if (Unit* unitTarget = (*itr)->ToUnit()) unitTargets.push_back(unitTarget); for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr) AddUnitTarget(*itr, effMask, false); } } float tangent(float x) { x = tan(x); //if (x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x; //if (x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max(); //if (x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max(); if (x < 100000.0f && x > -100000.0f) return x; if (x >= 100000.0f) return 100000.0f; if (x <= 100000.0f) return -100000.0f; return 0.0f; } #define DEBUG_TRAJ(a) //a void Spell::SelectImplicitTrajTargets() { if (!m_targets.HasTraj()) return; float dist2d = m_targets.GetDist2d(); if (!dist2d) return; float srcToDestDelta = m_targets.GetDstPos()->m_positionZ - m_targets.GetSrcPos()->m_positionZ; std::list<WorldObject*> targets; SkyFire::WorldObjectSpellTrajTargetCheck check(dist2d, m_targets.GetSrcPos(), m_caster, m_spellInfo); SkyFire::WorldObjectListSearcher<SkyFire::WorldObjectSpellTrajTargetCheck> searcher(m_caster, targets, check, GRID_MAP_TYPE_MASK_ALL); SearchTargets<SkyFire::WorldObjectListSearcher<SkyFire::WorldObjectSpellTrajTargetCheck> > (searcher, GRID_MAP_TYPE_MASK_ALL, m_caster, m_targets.GetSrcPos(), dist2d); if (targets.empty()) return; targets.sort(SkyFire::ObjectDistanceOrderPred(m_caster)); float b = tangent(m_targets.GetElevation()); float a = (srcToDestDelta - dist2d * b) / (dist2d * dist2d); if (a > -0.0001f) a = 0; DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: a %f b %f", a, b);) float bestDist = m_spellInfo->GetMaxRange(false); std::list<WorldObject*>::const_iterator itr = targets.begin(); for (; itr != targets.end(); ++itr) { if (Unit* unitTarget = (*itr)->ToUnit()) if (m_caster == *itr || m_caster->IsOnVehicle(unitTarget) || (unitTarget)->GetVehicle())//(*itr)->IsOnVehicle(m_caster)) continue; const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3) // TODO: all calculation should be based on src instead of m_caster const float objDist2d = m_targets.GetSrcPos()->GetExactDist2d(*itr) * cos(m_targets.GetSrcPos()->GetRelativeAngle(*itr)); const float dz = (*itr)->GetPositionZ() - m_targets.GetSrcPos()->m_positionZ; DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);) float dist = objDist2d - size; float height = dist * (a * dist + b); DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);) if (dist < bestDist && height < dz + size && height > dz - size) { bestDist = dist > 0 ? dist : 0; break; } #define CHECK_DIST {\ DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\ if (dist > bestDist)\ continue;\ if (dist < objDist2d + size && dist > objDist2d - size)\ {\ bestDist = dist;\ break;\ }\ } if (!a) { height = dz - size; dist = height / b; CHECK_DIST; height = dz + size; dist = height / b; CHECK_DIST; continue; } height = dz - size; float sqrt1 = b * b + 4 * a * height; if (sqrt1 > 0) { sqrt1 = sqrt(sqrt1); dist = (sqrt1 - b) / (2 * a); CHECK_DIST; } height = dz + size; float sqrt2 = b * b + 4 * a * height; if (sqrt2 > 0) { sqrt2 = sqrt(sqrt2); dist = (sqrt2 - b) / (2 * a); CHECK_DIST; dist = (-sqrt2 - b) / (2 * a); CHECK_DIST; } if (sqrt1 > 0) { dist = (-sqrt1 - b) / (2 * a); CHECK_DIST; } } if (m_targets.GetSrcPos()->GetExactDist2d(m_targets.GetDstPos()) > bestDist) { float x = m_targets.GetSrcPos()->m_positionX + cos(m_caster->GetOrientation()) * bestDist; float y = m_targets.GetSrcPos()->m_positionY + sin(m_caster->GetOrientation()) * bestDist; float z = m_targets.GetSrcPos()->m_positionZ + bestDist * (a * bestDist + b); if (itr != targets.end()) { float distSq = (*itr)->GetExactDistSq(x, y, z); float sizeSq = (*itr)->GetObjectSize(); sizeSq *= sizeSq; DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) if (distSq > sizeSq) { float factor = 1 - sqrt(sizeSq / distSq); x += factor * ((*itr)->GetPositionX() - x); y += factor * ((*itr)->GetPositionY() - y); z += factor * ((*itr)->GetPositionZ() - z); distSq = (*itr)->GetExactDistSq(x, y, z); DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) } } Position trajDst; trajDst.Relocate(x, y, z, m_caster->GetOrientation()); m_targets.ModDst(trajDst); } } void Spell::SelectEffectTypeImplicitTargets(uint8 effIndex) { // special case for SPELL_EFFECT_SUMMON_RAF_FRIEND and SPELL_EFFECT_SUMMON_PLAYER // TODO: this is a workaround - target shouldn't be stored in target map for those spells switch (m_spellInfo->Effects[effIndex].Effect) { case SPELL_EFFECT_SUMMON_RAF_FRIEND: case SPELL_EFFECT_SUMMON_PLAYER: if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->GetSelection()) { WorldObject* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetSelection()); CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex)); if (target && target->ToPlayer()) AddUnitTarget(target->ToUnit(), 1 << effIndex, false); } return; default: break; } // select spell implicit targets based on effect type if (!m_spellInfo->Effects[effIndex].GetImplicitTargetType()) return; uint32 targetMask = m_spellInfo->Effects[effIndex].GetMissingTargetMask(); if (!targetMask) return; WorldObject* target = NULL; switch (m_spellInfo->Effects[effIndex].GetImplicitTargetType()) { // add explicit object target or self to the target map case EFFECT_IMPLICIT_TARGET_EXPLICIT: // player which not released his spirit is Unit, but target flag for it is TARGET_FLAG_CORPSE_MASK if (targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK)) { if (Unit* unitTarget = m_targets.GetUnitTarget()) target = unitTarget; else if (targetMask & TARGET_FLAG_CORPSE_MASK) { if (Corpse* corpseTarget = m_targets.GetCorpseTarget()) { // TODO: this is a workaround - corpses should be added to spell target map too, but we can't do that so we add owner instead if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) target = owner; } } else //if (targetMask & TARGET_FLAG_UNIT_MASK) target = m_caster; } if (targetMask & TARGET_FLAG_ITEM_MASK) { if (Item* itemTarget = m_targets.GetItemTarget()) AddItemTarget(itemTarget, 1 << effIndex); return; } if (targetMask & TARGET_FLAG_GAMEOBJECT_MASK) target = m_targets.GetGOTarget(); break; // add self to the target map case EFFECT_IMPLICIT_TARGET_CASTER: if (targetMask & TARGET_FLAG_UNIT_MASK) target = m_caster; break; default: break; } CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex)); if (target) { if (target->ToUnit()) AddUnitTarget(target->ToUnit(), 1 << effIndex, false); else if (target->ToGameObject()) AddGOTarget(target->ToGameObject(), 1 << effIndex); } } uint32 Spell::GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionList* condList) { // this function selects which containers need to be searched for spell target uint32 retMask = GRID_MAP_TYPE_MASK_ALL; // filter searchers based on searched object type switch (objType) { case TARGET_OBJECT_TYPE_UNIT: case TARGET_OBJECT_TYPE_UNIT_AND_DEST: case TARGET_OBJECT_TYPE_CORPSE: case TARGET_OBJECT_TYPE_CORPSE_ENEMY: case TARGET_OBJECT_TYPE_CORPSE_ALLY: retMask &= GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_CREATURE; break; case TARGET_OBJECT_TYPE_GOBJ: case TARGET_OBJECT_TYPE_GOBJ_ITEM: retMask &= GRID_MAP_TYPE_MASK_GAMEOBJECT; break; default: break; } if (!(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_DEAD)) retMask &= ~GRID_MAP_TYPE_MASK_CORPSE; if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_PLAYERS) retMask &= GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_PLAYER; if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_GHOSTS) retMask &= GRID_MAP_TYPE_MASK_PLAYER; if (condList) retMask &= sConditionMgr->GetSearcherTypeMaskForConditionList(*condList); return retMask; } template<class SEARCHER> void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius) { if (!containerMask) return; // search world and grid for possible targets bool searchInGrid = containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_GAMEOBJECT); bool searchInWorld = containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE); if (searchInGrid || searchInWorld) { float x, y; x = pos->GetPositionX(); y = pos->GetPositionY(); CellCoord p(SkyFire::ComputeCellCoord(x, y)); Cell cell(p); cell.SetNoCreate(); Map& map = *(referer->GetMap()); if (searchInWorld) { TypeContainerVisitor<SEARCHER, WorldTypeMapContainer> world_object_notifier(searcher); cell.Visit(p, world_object_notifier, map, radius, x, y); } if (searchInGrid) { TypeContainerVisitor<SEARCHER, GridTypeMapContainer > grid_object_notifier(searcher); cell.Visit(p, grid_object_notifier, map, radius, x, y); } } } WorldObject* Spell::SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList) { WorldObject* target = NULL; uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); if (!containerTypeMask) return NULL; SkyFire::WorldObjectSpellNearbyTargetCheck check(range, m_caster, m_spellInfo, selectionType, condList); SkyFire::WorldObjectLastSearcher<SkyFire::WorldObjectSpellNearbyTargetCheck> searcher(m_caster, target, check, containerTypeMask); SearchTargets<SkyFire::WorldObjectLastSearcher<SkyFire::WorldObjectSpellNearbyTargetCheck> > (searcher, containerTypeMask, m_caster, m_caster, range); return target; } void Spell::SearchAreaTargets(std::list<WorldObject*>& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList) { uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); if (!containerTypeMask) return; SkyFire::WorldObjectSpellAreaTargetCheck check(range, position, m_caster, referer, m_spellInfo, selectionType, condList); SkyFire::WorldObjectListSearcher<SkyFire::WorldObjectSpellAreaTargetCheck> searcher(m_caster, targets, check, containerTypeMask); SearchTargets<SkyFire::WorldObjectListSearcher<SkyFire::WorldObjectSpellAreaTargetCheck> > (searcher, containerTypeMask, m_caster, m_caster, range); } void Spell::SearchChainTargets(std::list<WorldObject*>& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, ConditionList* condList, bool isChainHeal) { // max dist for jump target selection float jumpRadius = 0.0f; switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_RANGED: // 7.5y for multi shot jumpRadius = 7.5f; break; case SPELL_DAMAGE_CLASS_MELEE: // 5y for swipe, cleave and similar jumpRadius = 5.0f; break; case SPELL_DAMAGE_CLASS_NONE: case SPELL_DAMAGE_CLASS_MAGIC: // 12.5y for chain heal spell since 3.2 patch if (isChainHeal) jumpRadius = 12.5f; // 10y as default for magic chain spells else jumpRadius = 10.0f; break; } // chain lightning/heal spells and similar - allow to jump at larger distance and go out of los bool isBouncingFar = (m_spellInfo->AttributesEx4 & SPELL_ATTR4_AREA_TARGET_CHAIN || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC); // max dist which spell can reach float searchRadius = jumpRadius; if (isBouncingFar) searchRadius *= chainTargets; std::list<WorldObject*> tempTargets; SearchAreaTargets(tempTargets, searchRadius, target, m_caster, objectType, selectType, condList); tempTargets.remove(target); // remove targets which are always invalid for chain spells // for some spells allow only chain targets in front of caster (swipe for example) if (!isBouncingFar) { for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end();) { std::list<WorldObject*>::iterator checkItr = itr++; if (!m_caster->HasInArc(static_cast<float>(M_PI), *checkItr)) tempTargets.erase(checkItr); } } while (chainTargets) { // try to get unit for next chain jump std::list<WorldObject*>::iterator foundItr = tempTargets.end(); // get unit with highest hp deficit in dist if (isChainHeal) { uint32 maxHPDeficit = 0; for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr) { if (Unit* unitTarget = (*itr)->ToUnit()) { uint32 deficit = unitTarget->GetMaxHealth() - unitTarget->GetHealth(); if ((deficit > maxHPDeficit || foundItr == tempTargets.end()) && target->IsWithinDist(unitTarget, jumpRadius) && target->IsWithinLOSInMap(unitTarget)) { foundItr = itr; maxHPDeficit = deficit; } } } } // get closest object else { for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr) { if (foundItr == tempTargets.end()) { if ((!isBouncingFar || target->IsWithinDist(*itr, jumpRadius)) && target->IsWithinLOSInMap(*itr)) foundItr = itr; } else if (target->GetDistanceOrder(*itr, *foundItr) && target->IsWithinLOSInMap(*itr)) foundItr = itr; } } // not found any valid target - chain ends if (foundItr == tempTargets.end()) break; target = *foundItr; tempTargets.erase(foundItr); targets.push_back(target); --chainTargets; } } void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/) { //========================================================================================== // Now fill data for trigger system, need know: // can spell trigger another or not (m_canTrigger) // Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_procEx) //========================================================================================== m_procVictim = m_procAttacker = 0; // Get data for type of attack and fill base info for trigger switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS; if (m_attackType == OFF_ATTACK) m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK; else m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK; m_procVictim = PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS; break; case SPELL_DAMAGE_CLASS_RANGED: // Auto attack if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) { m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; } else // Ranged spell attack { m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS; m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS; } break; default: if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && m_spellInfo->EquippedItemSubClassMask & (1<<ITEM_SUBCLASS_WEAPON_WAND) && m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) // Wands auto attack { m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; } // For other spells trigger procflags are set in Spell::DoAllEffectOnTarget // Because spell positivity is dependant on target } m_procEx = PROC_EX_NONE; // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION; /* Effects which are result of aura proc from triggered spell cannot proc to prevent chain proc of these spells */ // Hellfire Effect - trigger as DOT if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040) { m_procAttacker = PROC_FLAG_DONE_PERIODIC; m_procVictim = PROC_FLAG_TAKEN_PERIODIC; } // Ranged autorepeat attack is set as triggered spell - ignore it if (!(m_procAttacker & PROC_FLAG_DONE_RANGED_AUTO_ATTACK)) { if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS && (m_spellInfo->AttributesEx2 & SPELL_ATTR2_TRIGGERED_CAN_TRIGGER_PROC || m_spellInfo->AttributesEx3 & SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_PROC_2)) m_procEx |= PROC_EX_INTERNAL_CANT_PROC; else if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) m_procEx |= PROC_EX_INTERNAL_TRIGGERED; } // Totem casts require spellfamilymask defined in spell_proc_event to proc if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isTotem() && m_caster->IsControlledByPlayer()) m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY; } void Spell::CleanupTargetList() { m_UniqueTargetInfo.clear(); m_UniqueGOTargetInfo.clear(); m_UniqueItemInfo.clear(); m_delayMoment = 0; } void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= true*/, bool implicit /*= true*/) { for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) if (!m_spellInfo->Effects[effIndex].IsEffect() || !CheckEffectTarget(target, effIndex)) effectMask &= ~(1 << effIndex); // no effects left if (!effectMask) return; if (checkIfValid) if (m_spellInfo->CheckTarget(m_caster, target, implicit) != SPELL_CAST_OK) return; // Check for effect immune skip if immuned for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) if (target->IsImmunedToSpellEffect(m_spellInfo, effIndex)) effectMask &= ~(1 << effIndex); uint64 targetGUID = target->GetGUID(); // Lookup target in already in list for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (targetGUID == ihit->targetGUID) // Found in list { ihit->effectMask |= effectMask; // Immune effects removed from mask ihit->scaleAura = false; if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != target) { SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel) ihit->scaleAura = true; } return; } } // This is new target calculate data for him // Get spell hit result on target TargetInfo targetInfo; targetInfo.targetGUID = targetGUID; // Store target GUID targetInfo.effectMask = effectMask; // Store all effects not immune targetInfo.processed = false; // Effects not apply on target targetInfo.alive = target->isAlive(); targetInfo.damage = 0; targetInfo.crit = false; targetInfo.scaleAura = false; if (m_auraScaleMask && targetInfo.effectMask == m_auraScaleMask && m_caster != target) { SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel) targetInfo.scaleAura = true; } // Calculate hit result if (m_originalCaster) { targetInfo.missCondition = m_originalCaster->SpellHitResult(target, m_spellInfo, m_canReflect); if (m_skipCheck && targetInfo.missCondition != SPELL_MISS_IMMUNE) targetInfo.missCondition = SPELL_MISS_NONE; } else targetInfo.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE; // Spell have speed - need calculate incoming time // Incoming time is zero for self casts. At least I think so. if (m_spellInfo->Speed > 0.0f && m_caster != target) { // calculate spell incoming interval // TODO: this is a hack float dist = m_caster->GetDistance(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()); if (dist < 5.0f) dist = 5.0f; targetInfo.timeDelay = (uint64) floor(dist / m_spellInfo->Speed * 1000.0f); // Calculate minimum incoming time if (m_delayMoment == 0 || m_delayMoment > targetInfo.timeDelay) m_delayMoment = targetInfo.timeDelay; } else targetInfo.timeDelay = 0LL; // If target reflect spell back to caster if (targetInfo.missCondition == SPELL_MISS_REFLECT) { // Calculate reflected spell result on caster targetInfo.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect); if (targetInfo.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell targetInfo.reflectResult = SPELL_MISS_PARRY; // Increase time interval for reflected spells by 1.5 targetInfo.timeDelay += targetInfo.timeDelay >> 1; } else targetInfo.reflectResult = SPELL_MISS_NONE; // Add target to list m_UniqueTargetInfo.push_back(targetInfo); } void Spell::AddGOTarget(GameObject* go, uint32 effectMask) { for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { if (!m_spellInfo->Effects[effIndex].IsEffect()) effectMask &= ~(1 << effIndex); else { switch (m_spellInfo->Effects[effIndex].Effect) { case SPELL_EFFECT_GAMEOBJECT_DAMAGE: case SPELL_EFFECT_GAMEOBJECT_REPAIR: case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE: if (go->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) effectMask &= ~(1 << effIndex); break; default: break; } } } if (!effectMask) return; uint64 targetGUID = go->GetGUID(); // Lookup target in already in list for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) { if (targetGUID == ihit->targetGUID) // Found in list { ihit->effectMask |= effectMask; // Add only effect mask return; } } // This is new target calculate data for him GOTargetInfo target; target.targetGUID = targetGUID; target.effectMask = effectMask; target.processed = false; // Effects not apply on target // Spell have speed - need calculate incoming time if (m_spellInfo->Speed > 0.0f) { // calculate spell incoming interval float dist = m_caster->GetDistance(go->GetPositionX(), go->GetPositionY(), go->GetPositionZ()); if (dist < 5.0f) dist = 5.0f; target.timeDelay = uint64(floor(dist / m_spellInfo->Speed * 1000.0f)); if (m_delayMoment == 0 || m_delayMoment > target.timeDelay) m_delayMoment = target.timeDelay; } else target.timeDelay = 0LL; // Add target to list m_UniqueGOTargetInfo.push_back(target); } void Spell::AddItemTarget(Item* item, uint32 effectMask) { for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) if (!m_spellInfo->Effects[effIndex].IsEffect()) effectMask &= ~(1 << effIndex); // no effects left if (!effectMask) return; // Lookup target in already in list for (std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) { if (item == ihit->item) // Found in list { ihit->effectMask |= effectMask; // Add only effect mask return; } } // This is new target add data ItemTargetInfo target; target.item = item; target.effectMask = effectMask; m_UniqueItemInfo.push_back(target); } void Spell::AddDestTarget(SpellDestination const& dest, uint32 effIndex) { m_destTargets[effIndex] = dest; } void Spell::DoAllEffectOnTarget(TargetInfo* target) { if (!target || target->processed) return; target->processed = true; // Target checked in apply effects procedure // Get mask of effects for target uint8 mask = target->effectMask; Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID); if (!unit) { uint8 farMask = 0; // create far target mask for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_spellInfo->Effects[i].IsFarUnitTargetEffect()) if ((1 << i) & mask) farMask |= (1 << i); if (!farMask) return; // find unit in world unit = ObjectAccessor::FindUnit(target->targetGUID); if (!unit) return; // do far effects on the unit // can't use default call because of threading, do stuff as fast as possible for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (farMask & (1 << i)) HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_HIT_TARGET); return; } if (unit->isAlive() != target->alive) return; if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsPositive() && (getMSTime() - target->timeDelay) <= unit->m_lastSanctuaryTime) return; // No missinfo in that case // Get original caster (if exist) and calculate damage/healing from him data Unit* caster = m_originalCaster ? m_originalCaster : m_caster; // Skip if m_originalCaster not avaiable if (!caster) return; SpellMissInfo missInfo = target->missCondition; // Need init unitTarget by default unit (can changed in code on reflect) // Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem) unitTarget = unit; // Reset damage/healing counter m_damage = target->damage; m_healing = -target->damage; // Fill base trigger info uint32 procAttacker = m_procAttacker; uint32 procVictim = m_procVictim; uint32 procEx = m_procEx; m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied //Spells with this flag cannot trigger if effect is casted on self bool canEffectTrigger = !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && CanExecuteTriggersOnHit(mask); Unit* spellHitTarget = NULL; if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target spellHitTarget = unit; else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit) { if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster ->do all effect on him { spellHitTarget = m_caster; if (m_caster->GetTypeId() == TYPEID_UNIT) m_caster->ToCreature()->LowerPlayerDamageReq(target->damage); } } if (spellHitTarget) { SpellMissInfo missInfo2 = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura); if (missInfo2 != SPELL_MISS_NONE) { if (missInfo2 != SPELL_MISS_MISS) m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo2); m_damage = 0; spellHitTarget = NULL; } } // Do not take combo points on dodge and miss if (missInfo != SPELL_MISS_NONE && m_needComboPoints && m_targets.GetUnitTargetGUID() == target->targetGUID) { m_needComboPoints = false; // Restore spell mods for a miss/dodge/parry Cold Blood // TODO: check how broad this rule should be if (m_caster->GetTypeId() == TYPEID_PLAYER && (missInfo == SPELL_MISS_MISS || missInfo == SPELL_MISS_DODGE || missInfo == SPELL_MISS_PARRY)) m_caster->ToPlayer()->RestoreSpellMods(this, 14177); } // Trigger info was not filled in spell::preparedatafortriggersystem - we do it now if (canEffectTrigger && !procAttacker && !procVictim) { bool positive = true; if (m_damage > 0) positive = false; else if (!m_healing) { for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) // If at least one effect negative spell is negative hit if (mask & (1<<i) && !m_spellInfo->IsPositiveEffect(i)) { positive = false; break; } if (mask) { for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) // If at least one effect negative spell is negative hit if (mask & (1 << effIndex) && !m_spellInfo->IsPositiveEffect(effIndex)) { positive = false; break; } } else // If there is no effect mask determine from spell proto positive = m_spellInfo->_IsPositiveSpell(); } switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: if (positive) { procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS; procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS; } else { procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG; } break; case SPELL_DAMAGE_CLASS_NONE: if (positive) { procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS; procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS; } else { procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG; } break; } } CallScriptOnHitHandlers(); // All calculated do it! // Do healing and triggers if (m_healing > 0) { bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask); uint32 addhealth = m_healing; if (crit) { procEx |= PROC_EX_CRITICAL_HIT; addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL); } else procEx |= PROC_EX_NORMAL_HIT; // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell); int32 gain = caster->HealBySpell(unitTarget, m_spellInfo, addhealth, crit); unitTarget->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo); m_healing = gain; } // Do damage and triggers else if (m_damage > 0) { // Fill base damage struct (unitTarget - is real spell target) SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); // Add bonuses and fill damageInfo struct caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit); caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); // Send log damage message to client caster->SendSpellNonMeleeDamageLog(&damageInfo); procEx |= createProcExtendMask(&damageInfo, missInfo); procVictim |= PROC_FLAG_TAKEN_DAMAGE; // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) { caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell); if (caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx); } caster->DealSpellDamage(&damageInfo, true); } // Passive spell hits/misses or active spells only misses (only triggers) else { // Fill base damage struct (unitTarget - is real spell target) SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); procEx |= createProcExtendMask(&damageInfo, missInfo); // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell); // Failed Pickpocket, reveal rogue if (missInfo == SPELL_MISS_RESIST && m_spellInfo->AttributesCu & SPELL_ATTR0_CU_PICKPOCKET && unitTarget->GetTypeId() == TYPEID_UNIT) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); if (unitTarget->ToCreature()->IsAIEnabled) unitTarget->ToCreature()->AI()->AttackStart(m_caster); } } if (missInfo != SPELL_MISS_EVADE && m_caster && !m_caster->IsFriendlyTo(unit) && !m_spellInfo->IsPositive()) { m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)); if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) if (!unit->IsStandState()) unit->SetStandState(UNIT_STAND_STATE_STAND); } if (spellHitTarget) { //AI functions if (spellHitTarget->GetTypeId() == TYPEID_UNIT) { if (spellHitTarget->ToCreature()->IsAIEnabled) spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo); // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm...) if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !spellHitTarget->ToCreature()->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) p->CastedCreatureOrGO(spellHitTarget->GetEntry(), spellHitTarget->GetGUID(), m_spellInfo->Id); } if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled) m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo); // Needs to be called after dealing damage/healing to not remove breaking on damage auras DoTriggersOnSpellHit(spellHitTarget, mask); // if target is fallged for pvp also flag caster if a player if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->UpdatePvP(true); CallScriptAfterHitHandlers(); } } SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleAura) { if (!unit || !effectMask) return SPELL_MISS_EVADE; // For delayed spells immunity may be applied between missile launch and hit - check immunity for that case // disable effects to which unit is immune for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber) && unit->IsImmunedToSpellEffect(m_spellInfo, effectNumber)) effectMask &= ~(1 << effectNumber); if (!effectMask || (m_spellInfo->Speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo)))) return SPELL_MISS_IMMUNE; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(); if (unit->GetTypeId() == TYPEID_PLAYER) { unit->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id); unit->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, m_caster); unit->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id); } if (m_caster->GetTypeId() == TYPEID_PLAYER) { m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id); m_caster->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit); } if (m_caster != unit) { // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells if (m_spellInfo->Speed > 0.0f && unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID()) return SPELL_MISS_EVADE; if (m_caster->_IsValidAttackTarget(unit, m_spellInfo)) { unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL); //TODO: This is a hack. But we do not know what types of stealth should be interrupted by CC if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) && unit->IsControlledByPlayer()) unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); } else if (m_caster->IsFriendlyTo(unit)) { // for delayed spells ignore negative spells (after duel end) for friendly targets // TODO: this cause soul transfer bugged if (m_spellInfo->Speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->IsPositive()) return SPELL_MISS_EVADE; // assisting case, healing and resurrection if (unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER)) { m_caster->SetContestedPvP(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->UpdatePvP(true); } if (unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)) { m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit); unit->getHostileRefManager().threatAssist(m_caster, 0.0f); } } } // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo, m_triggeredByAuraSpell); if (m_diminishGroup) { m_diminishLevel = unit->GetDiminishing(m_diminishGroup); DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup); // Increase Diminishing on unit, current informations for actually casts will use values above if ((type == DRTYPE_PLAYER && unit->GetCharmerOrOwnerPlayerOrPlayerItself()) || type == DRTYPE_ALL) unit->IncrDiminishing(m_diminishGroup); } uint8 aura_effmask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (effectMask & (1 << i) && m_spellInfo->Effects[i].IsUnitOwnedAuraEffect()) aura_effmask |= 1 << i; if (aura_effmask) { // Select rank for aura with level requirements only in specific cases // Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target SpellInfo const* aurSpellInfo = m_spellInfo; int32 basePoints[3]; if (scaleAura) { aurSpellInfo = m_spellInfo->GetAuraRankForLevel(unitTarget->getLevel()); ASSERT(aurSpellInfo); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { basePoints[i] = aurSpellInfo->Effects[i].BasePoints; if (m_spellInfo->Effects[i].Effect != aurSpellInfo->Effects[i].Effect) { aurSpellInfo = m_spellInfo; break; } } } if (m_originalCaster) { bool refresh = false; m_spellAura = Aura::TryRefreshStackOrCreate(aurSpellInfo, effectMask, unit, m_originalCaster, (aurSpellInfo == m_spellInfo)? &m_spellValue->EffectBasePoints[0] : &basePoints[0], _CastItem, 0, &refresh); if (m_spellAura) { // Set aura stack amount to desired value if (m_spellValue->AuraStackAmount > 1) { if (!refresh) m_spellAura->SetStackAmount(m_spellValue->AuraStackAmount); else m_spellAura->ModStackAmount(m_spellValue->AuraStackAmount); } // Now Reduce spell duration using data received at spell hit int32 duration = m_spellAura->GetMaxDuration(); int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup, aurSpellInfo); float diminishMod = unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel, limitduration); // unit is immune to aura if it was diminished to 0 duration if (diminishMod == 0.0f) { m_spellAura->Remove(); bool found = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (effectMask & (1 << i) && m_spellInfo->Effects[i].Effect != SPELL_EFFECT_APPLY_AURA) found = true; if (!found) return SPELL_MISS_IMMUNE; } else { ((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup); bool positive = m_spellAura->GetSpellInfo()->IsPositive(); if (AuraApplication* aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID())) positive = aurApp->IsPositive(); duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive, effectMask); // Haste modifies duration of channeled spells if (m_spellInfo->IsChanneled()) { if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this); } // and duration of auras affected by SPELL_AURA_PERIODIC_HASTE else if (m_originalCaster->HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, aurSpellInfo) || m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) duration = int32(duration * m_originalCaster->GetFloatValue(UNIT_MOD_CAST_SPEED)); if (duration != m_spellAura->GetMaxDuration()) { m_spellAura->SetMaxDuration(duration); m_spellAura->SetDuration(duration); } m_spellAura->_RegisterForTargets(); } } } } for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) HandleEffects(unit, NULL, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); return SPELL_MISS_NONE; } void Spell::DoTriggersOnSpellHit(Unit* unit, uint8 effMask) { // Apply additional spell effects to target // TODO: move this code to scripts if (m_preCastSpell) { if (sSpellMgr->GetSpellInfo(m_preCastSpell)) // Blizz seems to just apply aura without bothering to cast m_caster->AddAura(m_preCastSpell, unit); } // handle SPELL_AURA_ADD_TARGET_TRIGGER auras // this is executed after spell proc spells on target hit // spells are triggered for each hit spell target // info confirmed with retail sniffs of permafrost and shadow weaving if (!m_hitTriggerSpells.empty()) { int _duration = 0; for (HitTriggerSpells::const_iterator i = m_hitTriggerSpells.begin(); i != m_hitTriggerSpells.end(); ++i) { if (CanExecuteTriggersOnHit(effMask, i->first) && roll_chance_i(i->second)) { m_caster->CastSpell(unit, i->first, true); sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->first->Id); // SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration // set duration of current aura to the triggered spell if (i->first->GetDuration() == -1) { if (Aura* triggeredAur = unit->GetAura(i->first->Id, m_caster->GetGUID())) { // get duration from aura-only once if (!_duration) { Aura* aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID()); _duration = aur ? aur->GetDuration() : -1; } triggeredAur->SetDuration(_duration); } } } } } // trigger linked auras remove/apply // TODO: remove/cleanup this, as this table is not documented and people are doing stupid things with it if (std::vector<int32> const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT)) for (std::vector<int32>::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i) if (*i < 0) unit->RemoveAurasDueToSpell(-(*i)); else unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID()); } void Spell::DoAllEffectOnTarget(GOTargetInfo* target) { if (target->processed) // Check target return; target->processed = true; // Target checked in apply effects procedure uint32 effectMask = target->effectMask; if (!effectMask) return; GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID); if (!go) return; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(); for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) HandleEffects(NULL, NULL, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); CallScriptOnHitHandlers(); // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) // ignore autorepeat/melee casts for speed (not exist quest for spells (hm...) if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id); CallScriptAfterHitHandlers(); } void Spell::DoAllEffectOnTarget(ItemTargetInfo* target) { uint32 effectMask = target->effectMask; if (!target->item || !effectMask) return; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(); for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) HandleEffects(NULL, target->item, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); CallScriptOnHitHandlers(); CallScriptAfterHitHandlers(); } bool Spell::UpdateChanneledTargetList() { // Not need check return true if (m_channelTargetEffectMask == 0) return true; uint8 channelTargetEffectMask = m_channelTargetEffectMask; uint8 channelAuraMask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA) channelAuraMask |= 1<<i; channelAuraMask &= channelTargetEffectMask; float range = 0; if (channelAuraMask) { range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive()); if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); } for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask)) { Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); if (!unit) continue; if (IsValidDeadOrAliveTarget(unit)) { if (channelAuraMask & ihit->effectMask) { if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) { if (m_caster != unit && !m_caster->IsWithinDistInMap(unit, range)) { ihit->effectMask &= ~aurApp->GetEffectMask(); unit->RemoveAura(aurApp); continue; } } else // aura is dispelled continue; } channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target } } } // is all effects from m_needAliveTargetMask have alive targets return channelTargetEffectMask == 0; } void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura) { if (_CastItem) m_castItemGUID = _CastItem->GetGUID(); else m_castItemGUID = 0; InitExplicitTargets(*targets); // Fill aura scaling information if (m_caster->IsControlledByPlayer() && !m_spellInfo->IsPassive() && m_spellInfo->SpellLevel && !m_spellInfo->IsChanneled() && !(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_SCALING)) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA) { // Change aura with ranks only if basepoints are taken from spellInfo and aura is positive if (m_spellInfo->IsPositiveEffect(i)) { m_auraScaleMask |= (1 << i); if (m_spellValue->EffectBasePoints[i] != m_spellInfo->Effects[i].BasePoints) { m_auraScaleMask = 0; break; } } } } } m_spellState = SPELL_STATE_PREPARING; if (triggeredByAura) m_triggeredByAuraSpell = triggeredByAura->GetSpellInfo(); // create and add update event for this spell SpellEvent* Event = new SpellEvent(this); m_caster->_Events.AddEvent(Event, m_caster->_Events.CalculateTime(1)); //Prevent casting at cast another spell (ServerSide check) if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS) && m_caster->IsNonMeleeSpellCasted(false, true, true) && _cast_count) { SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS); finish(false); return; } if (DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, m_caster)) { SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE); finish(false); return; } LoadScripts(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); // Fill cost data (not use power for item casts m_powerCost = _CastItem ? 0 : m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); // Set combo point requirement if ((_triggeredCastFlags & TRIGGERED_IGNORE_COMBO_POINTS) || _CastItem || !m_caster->_movedPlayer) m_needComboPoints = false; SpellCastResult result = CheckCast(true); if (result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering { // Periodic auras should be interrupted when aura triggers a spell which can't be cast // for example bladestorm aura should be removed on disarm as of patch 3.3.5 // channeled periodic spells should be affected by this (arcane missiles, penance, etc) // a possible alternative sollution for those would be validating aura target on unit state change if (triggeredByAura && triggeredByAura->IsPeriodic() && !triggeredByAura->GetBase()->IsPassive()) { SendChannelUpdate(0); triggeredByAura->GetBase()->SetDuration(0); } SendCastResult(result); finish(false); return; } // Prepare data for triggers prepareDataForTriggerSystem(triggeredByAura); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail) m_casttime = m_spellInfo->CalcCastTime(m_caster, this); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); // don't allow channeled spells / spells with cast time to be casted while moving // (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in) // also check if that spell can be casted while moving (e.g. Scorch /w Firestarter) if ((m_spellInfo->IsChanneled() || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->isMoving() && m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT && !m_caster->CanCastWhileWalking(m_spellInfo->Id)) { SendCastResult(SPELL_FAILED_MOVING); finish(false); return; } // set timer base at cast time ReSetTimer(); sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::prepare: spell id %u source %u caster %d customCastFlags %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, _triggeredCastFlags, m_targets.GetTargetMask()); //Containers for channeled spells have to be set //TODO:Apply this to all casted spells if needed // Why check duration? 29350: channelled triggers channelled if ((_triggeredCastFlags & TRIGGERED_CAST_DIRECTLY) && (!m_spellInfo->IsChanneled() || !m_spellInfo->GetMaxDuration())) cast(true); else { // stealth must be removed at cast starting (at show channel bar) // skip triggered spell (item equip spell casting and other not explicit character casts/item uses) if (!(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_INTERRUPT_FLAGS) && m_spellInfo->IsBreakingStealth()) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST); for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_spellInfo->Effects[i].GetUsedTargetObjectType() == TARGET_OBJECT_TYPE_UNIT) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK); break; } } m_caster->SetCurrentCastedSpell(this); SendSpellStart(); // set target for proper facing if (m_casttime && !(_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING)) if (uint64 target = m_targets.GetUnitTargetGUID()) if (m_caster->GetGUID() != target && m_caster->GetTypeId() == TYPEID_UNIT) m_caster->FocusTarget(this, target); if (!(_triggeredCastFlags & TRIGGERED_IGNORE_GCD)) TriggerGlobalCooldown(); //item: first cast may destroy item and second cast causes crash if (!m_casttime && !m_spellInfo->StartRecoveryTime && !m_castItemGUID && GetCurrentContainer() == CURRENT_GENERIC_SPELL) cast(true); } Unit::AuraEffectList const& AurasList = m_caster->GetAuraEffectsByType(SPELL_AURA_SWAP_SPELLS); for (Unit::AuraEffectList::const_iterator itr = AurasList.begin(); itr != AurasList.end(); ++itr) { if (!m_spellInfo->IsPositive() && m_spellInfo->CasterAuraSpell == (*itr)->GetId()) // Only remove negative spell { m_caster->RemoveAurasByType(SPELL_AURA_SWAP_SPELLS); break; } } } void Spell::cancel() { if (m_spellState == SPELL_STATE_FINISHED) return; uint32 oldState = m_spellState; m_spellState = SPELL_STATE_FINISHED; m_autoRepeat = false; switch (oldState) { case SPELL_STATE_PREPARING: CancelGlobalCooldown(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->RestoreSpellMods(this); case SPELL_STATE_DELAYED: SendInterrupted(0); SendCastResult(SPELL_FAILED_INTERRUPTED); break; case SPELL_STATE_CASTING: for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if ((*ihit).missCondition == SPELL_MISS_NONE) if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL); SendChannelUpdate(0); SendInterrupted(0); SendCastResult(SPELL_FAILED_INTERRUPTED); // spell is canceled-take mods and clear list if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->RemoveSpellMods(this); m_appliedMods.clear(); break; default: break; } SetReferencedFromCurrent(false); if (m_selfContainer && *m_selfContainer == this) *m_selfContainer = NULL; m_caster->RemoveDynObject(m_spellInfo->Id); if (m_spellInfo->IsChanneled()) // if not channeled then the object for the current cast wasn't summoned yet m_caster->RemoveGameObject(m_spellInfo->Id, true); //set state back so finish will be processed m_spellState = oldState; finish(false); } void Spell::cast(bool skipCheck) { // update pointers base at GUIDs to prevent access to non-existed already object UpdatePointers(); // cancel at lost explicit target during cast if (m_targets.GetObjectTargetGUID() && !m_targets.GetObjectTarget()) { cancel(); return; } // now that we've done the basic check, now run the scripts // should be done before the spell is actually executed if (Player* playerCaster = m_caster->ToPlayer()) sScriptMgr->OnPlayerSpellCast(playerCaster, this, skipCheck); SetExecutedCurrently(true); if (m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.GetUnitTarget() && m_targets.GetUnitTarget() != m_caster) m_caster->SetInFront(m_targets.GetUnitTarget()); // Should this be done for original caster? if (m_caster->GetTypeId() == TYPEID_PLAYER) { // Set spell which will drop charges for triggered cast spells // if not successfully casted, will be remove in finish(false) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); } CallScriptBeforeCastHandlers(); // skip check if done already (for instant cast spells for example) if (!skipCheck) { SpellCastResult castResult = CheckCast(false); if (castResult != SPELL_CAST_OK) { SendCastResult(castResult); SendInterrupted(0); //restore spell mods if (m_caster->GetTypeId() == TYPEID_PLAYER) { m_caster->ToPlayer()->RestoreSpellMods(this); // cleanup after mod system // triggered spell pointer can be not removed in some cases m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); } finish(false); SetExecutedCurrently(false); return; } // additional check after cast bar completes (must not be in CheckCast) // if trade not complete then remember it in trade data if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (TradeData* my_trade = m_caster->ToPlayer()->GetTradeData()) { if (!my_trade->IsInAcceptProcess()) { // Spell will be casted at completing the trade. Silently ignore at this place my_trade->SetSpell(m_spellInfo->Id, _CastItem); SendCastResult(SPELL_FAILED_DONT_REPORT); SendInterrupted(0); m_caster->ToPlayer()->RestoreSpellMods(this); // cleanup after mod system // triggered spell pointer can be not removed in some cases m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); finish(false); SetExecutedCurrently(false); return; } } } } } SelectSpellTargets(); // Spell may be finished after target map check if (m_spellState == SPELL_STATE_FINISHED) { SendInterrupted(0); //restore spell mods if (m_caster->GetTypeId() == TYPEID_PLAYER) { m_caster->ToPlayer()->RestoreSpellMods(this); // cleanup after mod system // triggered spell pointer can be not removed in some cases m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); } finish(false); SetExecutedCurrently(false); return; } PrepareTriggersExecutedOnHit(); CallScriptOnCastHandlers(); // traded items have trade slot instead of guid in m_itemTargetGUID // set to real guid to be sent later to the client m_targets.UpdateTradeSlotItem(); if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM) && _CastItem) { m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_ITEM, _CastItem->GetEntry()); m_caster->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, _CastItem->GetEntry()); } m_caster->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id); } if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)) { // Powers have to be taken before SendSpellGo TakePower(); TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot } else if (Item* targetItem = m_targets.GetItemTarget()) { /// Not own traded item (in trader trade slot) req. reagents including triggered spell case if (targetItem->GetOwnerGUID() != m_caster->GetGUID()) TakeReagents(); } // CAST SPELL SendSpellCooldown(); PrepareScriptHitHandlers(); HandleLaunchPhase(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()... SendSpellGo(); // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells if ((m_spellInfo->Speed > 0.0f && !m_spellInfo->IsChanneled()) || m_spellInfo->Id == 14157) { // Remove used for cast item if need (it can be already NULL after TakeReagents call // in case delayed spell remove item at cast delay start TakeCastItem(); // Okay, maps created, now prepare flags m_immediateHandled = false; m_spellState = SPELL_STATE_DELAYED; SetDelayStart(0); if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true)) m_caster->ClearUnitState(UNIT_STATE_CASTING); } else { // Immediate spell, no big deal handle_immediate(); } CallScriptAfterCastHandlers(); if (const std::vector<int32> *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id)) { for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i) if (*i < 0) m_caster->RemoveAurasDueToSpell(-(*i)); else m_caster->CastSpell(m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster, *i, true); } if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); SetExecutedCurrently(false); } void Spell::handle_immediate() { // start channeling if applicable if (m_spellInfo->IsChanneled()) { int32 duration = m_spellInfo->GetDuration(); if (duration) { // First mod_duration then haste - see Missile Barrage // Apply duration mod if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); // Apply haste mods if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) m_caster->ModSpellCastTime(m_spellInfo, duration, this); m_spellState = SPELL_STATE_CASTING; m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags); SendChannelStart(duration); } else if (duration == -1) { m_spellState = SPELL_STATE_CASTING; m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags); SendChannelStart(duration); } } PrepareTargetProcessing(); // process immediate effects (items, ground, etc.) also initialize some variables _handle_immediate_phase(); for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); for (std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); FinishTargetProcessing(); // spell is finished, perform some last features of the spell here _handle_finish_phase(); // Remove used for cast item if need (it can be already NULL after TakeReagents call TakeCastItem(); if (m_spellState != SPELL_STATE_CASTING) finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell) } uint64 Spell::handle_delayed(uint64 t_offset) { UpdatePointers(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); uint64 next_time = 0; PrepareTargetProcessing(); if (!m_immediateHandled) { _handle_immediate_phase(); m_immediateHandled = true; } bool single_missile = (m_targets.HasDst()); // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases) for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->processed == false) { if (single_missile || ihit->timeDelay <= t_offset) { ihit->timeDelay = t_offset; DoAllEffectOnTarget(&(*ihit)); } else if (next_time == 0 || ihit->timeDelay < next_time) next_time = ihit->timeDelay; } } // now recheck gameobject targeting correctness for (std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) { if (ighit->processed == false) { if (single_missile || ighit->timeDelay <= t_offset) DoAllEffectOnTarget(&(*ighit)); else if (next_time == 0 || ighit->timeDelay < next_time) next_time = ighit->timeDelay; } } FinishTargetProcessing(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); // All targets passed - need finish phase if (next_time == 0) { // spell is finished, perform some last features of the spell here _handle_finish_phase(); finish(true); // successfully finish spell cast // return zero, spell is finished now return 0; } else { // spell is unfinished, return next execution time return next_time; } } void Spell::_handle_immediate_phase() { m_spellAura = NULL; // initialize Diminishing Returns Data m_diminishLevel = DIMINISHING_LEVEL_1; m_diminishGroup = DIMINISHING_NONE; // handle some immediate features of the spell here HandleThreatSpells(); PrepareScriptHitHandlers(); // handle effects with SPELL_EFFECT_HANDLE_HIT mode for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { // don't do anything for empty effect if (!m_spellInfo->Effects[j].IsEffect()) continue; // call effect handlers to handle destination hit HandleEffects(NULL, NULL, NULL, j, SPELL_EFFECT_HANDLE_HIT); } // process items for (std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); if (!m_originalCaster) return; // Handle procs on cast // TODO: finish new proc system:P if (m_UniqueTargetInfo.empty()) { uint32 procAttacker = m_procAttacker; if (!procAttacker) { bool positive = m_spellInfo->IsPositive(); switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: if (positive) procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS; else procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; break; case SPELL_DAMAGE_CLASS_NONE: if (positive) procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS; else procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; break; } } // Proc damage for spells which have only dest targets (2484 should proc 51486 for example) m_originalCaster->ProcDamageAndSpell(NULL, procAttacker, 0, m_procEx | PROC_EX_NORMAL_HIT, 0, BASE_ATTACK, m_spellInfo, m_triggeredByAuraSpell); } } void Spell::_handle_finish_phase() { if (m_caster->_movedPlayer) { // Take for real after all targets are processed if (m_needComboPoints) m_caster->_movedPlayer->ClearComboPoints(); // Real add combo points from effects if (m_comboPointGain) m_caster->_movedPlayer->GainSpellComboPoints(m_comboPointGain); if (m_spellInfo->PowerType == POWER_HOLY_POWER && m_caster->_movedPlayer->getClass() == CLASS_PALADIN) HandleHolyPower(m_caster->_movedPlayer); } if (m_caster->_extraAttacks && GetSpellInfo()->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS)) m_caster->HandleProcExtraAttackFor(m_caster->getVictim()); // TODO: trigger proc phase finish here } void Spell::SendSpellCooldown() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* _player = (Player*)m_caster; // mana/health/etc potions, disabled by client (until combat out as declarate) if (_CastItem && _CastItem->IsPotion()) { // need in some way provided data for Spell::finish SendCooldownEvent _player->SetLastPotionId(_CastItem->GetEntry()); return; } // have infinity cooldown but set at aura apply // do not set cooldown for triggered spells (needed by reincarnation) if (m_spellInfo->Attributes & (SPELL_ATTR0_DISABLED_WHILE_ACTIVE | SPELL_ATTR0_PASSIVE) || (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD)) return; _player->AddSpellAndCategoryCooldowns(m_spellInfo, _CastItem ? _CastItem->GetEntry() : 0, this); } void Spell::update(uint32 difftime) { // update pointers based at it's GUIDs UpdatePointers(); if (m_targets.GetUnitTargetGUID() && !m_targets.GetUnitTarget()) { sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %u is cancelled due to removal of target.", m_spellInfo->Id); cancel(); return; } // check if the player caster has moved before the spell finished if ((m_caster->GetTypeId() == TYPEID_PLAYER && _timer != 0) && m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && (m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING))) { // don't cancel for melee, autorepeat, triggered and instant spells if (!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered() && !m_caster->CanCastWhileWalking(m_spellInfo->Id)) cancel(); } switch (m_spellState) { case SPELL_STATE_PREPARING: { if (_timer > 0) { // Cancel the cast if the target is not in line of sight if (m_targets.GetUnitTarget() && !m_caster->IsWithinLOSInMap(m_targets.GetUnitTarget())) { SendCastResult(SPELL_FAILED_LINE_OF_SIGHT); cancel(); return; } if (difftime >= (uint32)_timer) _timer = 0; else _timer -= difftime; } if (_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat()) // don't CheckCast for instant spells - done in spell::prepare, skip duplicate checks, needed for range checks for example cast(!m_casttime); break; } case SPELL_STATE_CASTING: { if (_timer) { // check if there are alive targets left if (!UpdateChanneledTargetList()) { sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Channeled spell %d is removed due to lack of targets", m_spellInfo->Id); SendChannelUpdate(0); finish(); } if (_timer > 0) { if (difftime >= (uint32)_timer) _timer = 0; else _timer -= difftime; } } if (_timer == 0) { SendChannelUpdate(0); // channeled spell processed independently for quest targeting // cast at creature (or GO) quest objectives update at successful cast channel finished // ignore autorepeat/melee casts for speed (not exist quest for spells (hm...) if (!IsAutoRepeat() && !IsNextMeleeSwingSpell()) { if (Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself()) { for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { TargetInfo* target = &*ihit; if (!IS_CRE_OR_VEH_GUID(target->targetGUID)) continue; Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID); if (unit == NULL) continue; p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id); } for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) { GOTargetInfo* target = &*ihit; GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID); if (!go) continue; p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id); } } } finish(); } break; } default: break; } } void Spell::finish(bool ok) { if (!m_caster) return; if (m_spellState == SPELL_STATE_FINISHED) return; m_spellState = SPELL_STATE_FINISHED; if (m_spellInfo->IsChanneled()) m_caster->UpdateInterruptMask(); if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true)) m_caster->ClearUnitState(UNIT_STATE_CASTING); // Unsummon summon as possessed creatures on spell cancel if (m_spellInfo->IsChanneled() && m_caster->GetTypeId() == TYPEID_PLAYER) { if (Unit* charm = m_caster->GetCharm()) if (charm->GetTypeId() == TYPEID_UNIT && charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET) && charm->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id) ((Puppet*)charm)->UnSummon(); } if (m_caster->GetTypeId() == TYPEID_UNIT) m_caster->ReleaseFocus(this); if (!ok) return; if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isSummon()) { // Unsummon statue uint32 spell = m_caster->GetUInt32Value(UNIT_CREATED_BY_SPELL); SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell); if (spellInfo && spellInfo->SpellIconID == 2056) { sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Statue %d is unsummoned in spell %d finish", m_caster->GetGUIDLow(), m_spellInfo->Id); m_caster->setDeathState(JUST_DIED); return; } } if (IsAutoActionResetSpell()) { bool found = false; Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET); for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i) { if ((*i)->IsAffectedOnSpell(m_spellInfo)) { found = true; break; } } if (!found && !(m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS)) { m_caster->resetAttackTimer(BASE_ATTACK); if (m_caster->haveOffhandWeapon()) m_caster->resetAttackTimer(OFF_ATTACK); m_caster->resetAttackTimer(RANGED_ATTACK); } } // potions disabled by client, send event "not in combat" if need if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (!m_triggeredByAuraSpell) m_caster->ToPlayer()->UpdatePotionCooldown(this); // triggered spell pointer can be not set in some cases // this is needed for proper apply of triggered spell mods m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); // Take mods after trigger spell (needed for 14177 to affect 48664) // mods are taken only on succesfull cast and independantly from targets of the spell m_caster->ToPlayer()->RemoveSpellMods(this); m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); } // Stop Attack for some spells if (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) m_caster->AttackStop(); } void Spell::SendCastResult(SpellCastResult result) { if (result == SPELL_CAST_OK) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (m_caster->ToPlayer()->GetSession()->PlayerLoading()) // don't send cast results at loading time return; SendCastResult(m_caster->ToPlayer(), m_spellInfo, _cast_count, result, m_customError); } void Spell::SendCastResult(Player* caster, SpellInfo const* spellInfo, uint8 cast_count, SpellCastResult result, SpellCustomErrors customError /*= SPELL_CUSTOM_ERROR_NONE*/) { if (result == SPELL_CAST_OK) return; WorldPacket data(SMSG_CAST_FAILED, (4+1+1)); data << uint8(cast_count); // single cast or multi 2.3 (0/1) data << uint32(spellInfo->Id); data << uint8(result); // problem switch (result) { case SPELL_FAILED_REQUIRES_SPELL_FOCUS: data << uint32(spellInfo->RequiresSpellFocus); // SpellFocusObject.dbc id break; case SPELL_FAILED_REQUIRES_AREA: // AreaTable.dbc id // hardcode areas limitation case switch (spellInfo->Id) { case 41617: // Cenarion Mana Salve case 41619: // Cenarion Healing Salve data << uint32(3905); break; case 41618: // Bottled Nethergon Energy case 41620: // Bottled Nethergon Vapor data << uint32(3842); break; case 45373: // Bloodberry Elixir data << uint32(4075); break; default: // default case (don't must be) data << uint32(0); break; } break; case SPELL_FAILED_TOTEMS: if (spellInfo->Totem[0]) data << uint32(spellInfo->Totem[0]); if (spellInfo->Totem[1]) data << uint32(spellInfo->Totem[1]); break; case SPELL_FAILED_TOTEM_CATEGORY: if (spellInfo->TotemCategory[0]) data << uint32(spellInfo->TotemCategory[0]); if (spellInfo->TotemCategory[1]) data << uint32(spellInfo->TotemCategory[1]); break; case SPELL_FAILED_EQUIPPED_ITEM_CLASS: case SPELL_FAILED_EQUIPPED_ITEM_CLASS_MAINHAND: case SPELL_FAILED_EQUIPPED_ITEM_CLASS_OFFHAND: data << uint32(spellInfo->EquippedItemClass); data << uint32(spellInfo->EquippedItemSubClassMask); break; case SPELL_FAILED_TOO_MANY_OF_ITEM: { uint32 item = 0; for (int8 x = 0; x < 3; x++) if (spellInfo->Effects[x].ItemType) item = spellInfo->Effects[x].ItemType; ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item); if (pProto && pProto->ItemLimitCategory) data << uint32(pProto->ItemLimitCategory); break; } case SPELL_FAILED_CUSTOM_ERROR: data << uint32(customError); break; case SPELL_FAILED_REAGENTS: { uint32 missingItem = 0; for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++) { if (spellInfo->Reagent[i] <= 0) continue; uint32 itemid = spellInfo->Reagent[i]; uint32 itemcount = spellInfo->ReagentCount[i]; if (!caster->HasItemCount(itemid, itemcount)) { missingItem = itemid; break; } } data << uint32(missingItem); // first missing item break; } default: break; } caster->GetSession()->SendPacket(&data); } void Spell::SendSpellStart() { if (!IsNeedSendToClient()) return; //sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Sending SMSG_SPELL_START id=%u", m_spellInfo->Id); uint32 castFlags = CAST_FLAG_UNKNOWN_2; if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) castFlags |= CAST_FLAG_PENDING; if ((m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet())) && m_spellInfo->PowerType != POWER_HEALTH) castFlags |= CAST_FLAG_POWER_LEFT_SELF; if (m_spellInfo->RuneCostID && m_spellInfo->PowerType == POWER_RUNE) castFlags |= CAST_FLAG_UNKNOWN_19; WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2)); if (_CastItem) data.append(_CastItem->GetPackGUID()); else data.append(m_caster->GetPackGUID()); data.append(m_caster->GetPackGUID()); data << uint8(_cast_count); // pending spell cast? data << uint32(m_spellInfo->Id); // spellId data << uint32(castFlags); // cast flags data << int32(_timer); // delay? m_targets.Write(data); if (castFlags & CAST_FLAG_POWER_LEFT_SELF) data << uint32(m_caster->GetPower((Powers)m_spellInfo->PowerType)); if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list { //TODO: There is a crash caused by a spell with CAST_FLAG_RUNE_LIST casted by a creature //The creature is the mover of a player, so HandleCastSpellOpcode uses it as the caster if (Player* player = m_caster->ToPlayer()) { data << uint8(m_runesState); // runes state before data << uint8(player->GetRunesState()); // runes state after for (uint8 i = 0; i < MAX_RUNES; ++i) { // float casts ensure the division is performed on floats as we need float result float baseCd = float(player->GetRuneBaseCooldown(i)); data << uint8((baseCd - float(player->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed } } else { data << uint8(0); data << uint8(0); for (uint8 i = 0; i < MAX_RUNES; ++i) data << uint8(0); } } if (castFlags & CAST_FLAG_UNKNOWN_23) { data << uint32(0); data << uint32(0); } m_caster->SendMessageToSet(&data, true); } void Spell::SendSpellGo() { // not send invisible spell casting if (!IsNeedSendToClient()) return; //sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id); uint32 castFlags = CAST_FLAG_UNKNOWN_9; // triggered spells with spell visual != 0 if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) castFlags |= CAST_FLAG_PENDING; if ((m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet())) && m_spellInfo->PowerType != POWER_HEALTH) castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible if ((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->RuneCostID && m_spellInfo->PowerType == POWER_RUNE) { castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list castFlags |= CAST_FLAG_UNKNOWN_9; // ?? } if (m_spellInfo->HasEffect(SPELL_EFFECT_ACTIVATE_RUNE)) { castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START } if (m_targets.HasTraj()) castFlags |= CAST_FLAG_ADJUST_MISSILE; WorldPacket data(SMSG_SPELL_GO, 50); // guess size if (_CastItem) data.append(_CastItem->GetPackGUID()); else data.append(m_caster->GetPackGUID()); data.append(m_caster->GetPackGUID()); data << uint8(_cast_count); // pending spell cast? data << uint32(m_spellInfo->Id); // spellId data << uint32(castFlags); // cast flags data << uint32(getMSTime()); // timestamp WriteSpellGoTargets(&data); m_targets.Write(data); if (castFlags & CAST_FLAG_POWER_LEFT_SELF) data << uint32(m_caster->GetPower((Powers)m_spellInfo->PowerType)); if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list { //TODO: There is a crash caused by a spell with CAST_FLAG_RUNE_LIST casted by a creature //The creature is the mover of a player, so HandleCastSpellOpcode uses it as the caster if (Player* player = m_caster->ToPlayer()) { data << uint8(m_runesState); // runes state before data << uint8(player->GetRunesState()); // runes state after for (uint8 i = 0; i < MAX_RUNES; ++i) { // float casts ensure the division is performed on floats as we need float result float baseCd = float(player->GetRuneBaseCooldown(i)); data << uint8((baseCd - float(player->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed } } else { data << uint8(0); data << uint8(0); for (uint8 i = 0; i < MAX_RUNES; ++i) data << uint8(0); } } if (castFlags & CAST_FLAG_ADJUST_MISSILE) { data << m_targets.GetElevation(); data << uint32(m_delayMoment); } if (castFlags & CAST_FLAG_UNKNOWN_20) { data << uint32(0); data << uint32(0); } if (m_targets.GetTargetMask() & TARGET_FLAG_DEST_LOCATION) { data << uint8(0); } m_caster->SendMessageToSet(&data, true); } void Spell::WriteSpellGoTargets(WorldPacket* data) { // This function also fill data for channeled spells: // m_needAliveTargetMask req for stop channeling if one target die uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO uint32 miss = 0; for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if ((*ihit).effectMask == 0) // No effect apply - all immuned add state { // possibly SPELL_MISS_IMMUNE2 for this?? ihit->missCondition = SPELL_MISS_IMMUNE2; ++miss; } else if ((*ihit).missCondition == SPELL_MISS_NONE) ++hit; else ++miss; } *data << (uint8)hit; for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits { *data << uint64(ihit->targetGUID); m_channelTargetEffectMask |=ihit->effectMask; } } for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) *data << uint64(ighit->targetGUID); // Always hits *data << (uint8)miss; for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition != SPELL_MISS_NONE) // Add only miss { *data << uint64(ihit->targetGUID); *data << uint8(ihit->missCondition); if (ihit->missCondition == SPELL_MISS_REFLECT) *data << uint8(ihit->reflectResult); } } // Reset m_needAliveTargetMask for non channeled spell if (!m_spellInfo->IsChanneled()) m_channelTargetEffectMask = 0; } void Spell::SendLogExecute() { WorldPacket data(SMSG_COMBAT_LOG_MULTIPLE, 4+4+4+4+8+4+4+4+4+8); data << uint32(1); // total number of log lines data << uint32(0); data << uint32(0); data << uint32(SPELL_LOG_EXECUTE); data.append(m_caster->GetPackGUID()); data << uint32(m_spellInfo->Id); uint8 effCount = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_effectExecuteData[i]) ++effCount; } if (!effCount) return; data << uint32(effCount); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (!m_effectExecuteData[i]) continue; data << uint32(m_spellInfo->Effects[i].Effect); // spell effect data.append(*m_effectExecuteData[i]); delete m_effectExecuteData[i]; m_effectExecuteData[i] = NULL; } m_caster->SendMessageToSet(&data, true); } void Spell::ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit* target, uint32 powerType, uint32 powerTaken, float gainMultiplier) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(target->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(powerTaken); *m_effectExecuteData[effIndex] << uint32(powerType); *m_effectExecuteData[effIndex] << float(gainMultiplier); } void Spell::ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit* victim, uint32 attCount) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(victim->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(attCount); } void Spell::ExecuteLogEffectInterruptCast(uint8 effIndex, Unit* victim, uint32 spellId) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(victim->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(spellId); } void Spell::ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit* victim, uint32 /*itemslot*/, uint32 damage) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(victim->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(m_spellInfo->Id); *m_effectExecuteData[effIndex] << uint32(damage); } void Spell::ExecuteLogEffectOpenLock(uint8 effIndex, Object* obj) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(obj->GetPackGUID()); } void Spell::ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry) { InitEffectExecuteData(effIndex); *m_effectExecuteData[effIndex] << uint32(entry); } void Spell::ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry) { InitEffectExecuteData(effIndex); *m_effectExecuteData[effIndex] << uint32(entry); } void Spell::ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject* obj) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(obj->GetPackGUID()); } void Spell::ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject* obj) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(obj->GetPackGUID()); } void Spell::ExecuteLogEffectResurrect(uint8 effIndex, Unit* target) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(target->GetPackGUID()); } void Spell::SendInterrupted(uint8 result) { WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1)); data.append(m_caster->GetPackGUID()); data << uint8(_cast_count); data << uint32(m_spellInfo->Id); data << uint8(result); m_caster->SendMessageToSet(&data, true); data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4)); data.append(m_caster->GetPackGUID()); data << uint8(_cast_count); data << uint32(m_spellInfo->Id); data << uint8(result); m_caster->SendMessageToSet(&data, true); } void Spell::SendChannelUpdate(uint32 time) { if (time == 0) { m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0); m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0); } WorldPacket data(MSG_CHANNEL_UPDATE, 8+4); data.append(m_caster->GetPackGUID()); data << uint32(time); m_caster->SendMessageToSet(&data, true); } void Spell::SendChannelStart(uint32 duration) { uint64 channelTarget = m_targets.GetObjectTargetGUID(); WorldPacket data(MSG_CHANNEL_START, (8+4+4)); data.append(m_caster->GetPackGUID()); data << uint32(m_spellInfo->Id); data << uint32(duration); m_caster->SendMessageToSet(&data, true); _timer = duration; if (channelTarget) m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, channelTarget); m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id); } void Spell::SendResurrectRequest(Player* target) { // get resurrector name for creature resurrections, otherwise packet will be not accepted // for player resurrections the name is looked up by guid char const* resurrectorName = m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex()); WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(resurrectorName)+1+1+1+4)); data << uint64(m_caster->GetGUID()); // resurrector guid data << uint32(strlen(resurrectorName) + 1); data << resurrectorName; data << uint8(0); // null terminator data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1); // "you'll be afflicted with resurrection sickness" // override delay sent with SMSG_CORPSE_RECLAIM_DELAY, set instant resurrection for spells with this attribute if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_IGNORE_RESURRECTION_TIMER) data << uint32(0); target->GetSession()->SendPacket(&data); } void Spell::TakeCastItem() { if (!_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER) return; // not remove cast item at triggered spell (equipping, weapon damage, etc) if (_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM) return; ItemTemplate const* proto = _CastItem->GetTemplate(); if (!proto) { // This code is to avoid a crash // I'm not sure, if this is really an error, but I guess every item needs a prototype sLog->outError("Cast item has no item prototype highId=%d, lowId=%d", _CastItem->GetGUIDHigh(), _CastItem->GetGUIDLow()); return; } bool expendable = false; bool withoutCharges = false; for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { if (proto->Spells[i].SpellId) { // item has limited charges if (proto->Spells[i].SpellCharges) { if (proto->Spells[i].SpellCharges < 0) expendable = true; int32 charges = _CastItem->GetSpellCharges(i); // item has charges left if (charges) { (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use if (proto->Stackable == 1) _CastItem->SetSpellCharges(i, charges); _CastItem->SetState(ITEM_CHANGED, (Player*)m_caster); } // all charges used withoutCharges = (charges == 0); } } } if (expendable && withoutCharges) { uint32 count = 1; m_caster->ToPlayer()->DestroyItemCount(_CastItem, count, true); // prevent crash at access to deleted m_targets.GetItemTarget if (_CastItem == m_targets.GetItemTarget()) m_targets.SetItemTarget(NULL); _CastItem = NULL; } } void Spell::TakePower() { if (_CastItem || m_triggeredByAuraSpell) return; Powers powerType = Powers(m_spellInfo->PowerType); bool hit = true; if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (powerType == POWER_RAGE || powerType == POWER_ENERGY || powerType == POWER_RUNE) if (uint64 targetGUID = m_targets.GetUnitTargetGUID()) for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetGUID) { if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS/* && ihit->targetGUID != m_caster->GetGUID()*/) hit = false; if (ihit->missCondition != SPELL_MISS_NONE) { //lower spell cost on fail (by talent aura) if (Player* modOwner = m_caster->ToPlayer()->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost); } break; } } if (powerType == POWER_RUNE) { TakeRunePower(hit); return; } if (!m_powerCost) return; // health as power used if (powerType == POWER_HEALTH) { m_caster->ModifyHealth(-(int32)m_powerCost); return; } if (powerType >= MAX_POWERS) { sLog->outError("Spell::TakePower: Unknown power type '%d'", powerType); return; } if (hit) m_caster->ModifyPower(powerType, -m_powerCost); else m_caster->ModifyPower(powerType, -irand(0, m_powerCost/4)); } SpellCastResult Spell::CheckRuneCost(uint32 runeCostID) { if (m_spellInfo->PowerType != POWER_RUNE || !runeCostID) return SPELL_CAST_OK; if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_CAST_OK; Player* player = (Player*)m_caster; if (player->getClass() != CLASS_DEATH_KNIGHT) return SPELL_CAST_OK; SpellRuneCostEntry const* src = sSpellRuneCostStore.LookupEntry(runeCostID); if (!src) return SPELL_CAST_OK; if (src->NoRuneCost()) return SPELL_CAST_OK; int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death for (uint32 i = 0; i < RUNE_DEATH; ++i) { runeCost[i] = src->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this); } runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later for (uint32 i = 0; i < MAX_RUNES; ++i) { RuneType rune = player->GetCurrentRune(i); if ((player->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0)) runeCost[rune]--; } for (uint32 i = 0; i < RUNE_DEATH; ++i) if (runeCost[i] > 0) runeCost[RUNE_DEATH] += runeCost[i]; if (runeCost[RUNE_DEATH] > MAX_RUNES) return SPELL_FAILED_NO_POWER; // not sure if result code is correct return SPELL_CAST_OK; } void Spell::TakeRunePower(bool didHit) { if (m_caster->GetTypeId() != TYPEID_PLAYER || m_caster->getClass() != CLASS_DEATH_KNIGHT) return; SpellRuneCostEntry const* runeCostData = sSpellRuneCostStore.LookupEntry(m_spellInfo->RuneCostID); if (!runeCostData || (runeCostData->NoRuneCost() && runeCostData->NoRunicPowerGain())) return; Player* player = m_caster->ToPlayer(); m_runesState = player->GetRunesState(); // store previous state int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death for (uint32 i = 0; i < RUNE_DEATH; ++i) { runeCost[i] = runeCostData->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this); } runeCost[RUNE_DEATH] = 0; // calculated later for (uint32 i = 0; i < MAX_RUNES; ++i) { RuneType rune = player->GetCurrentRune(i); if (!player->GetRuneCooldown(i) && runeCost[rune] > 0) { player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown(i) : uint32(RUNE_MISS_COOLDOWN)); player->SetLastUsedRune(rune); runeCost[rune]--; } } runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST]; if (runeCost[RUNE_DEATH] > 0) { for (uint32 i = 0; i < MAX_RUNES; ++i) { RuneType rune = player->GetCurrentRune(i); if (!player->GetRuneCooldown(i) && rune == RUNE_DEATH) { player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown(i) : uint32(RUNE_MISS_COOLDOWN)); player->SetLastUsedRune(rune); runeCost[rune]--; // keep Death Rune type if missed if (didHit) player->RestoreBaseRune(i); if (runeCost[RUNE_DEATH] == 0) break; } } } // you can gain some runic power when use runes if (didHit) if (int32 rp = int32(runeCostData->runePowerGain * sWorld->getRate(RATE_POWER_RUNICPOWER_INCOME))) player->ModifyPower(POWER_RUNIC_POWER, int32(rp)); } void Spell::TakeReagents() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; ItemTemplate const* castItemTemplate = _CastItem ? _CastItem->GetTemplate() : NULL; // do not take reagents for these item casts if (castItemTemplate && castItemTemplate->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST) return; Player* p_caster = m_caster->ToPlayer(); if (p_caster->CanNoReagentCast(m_spellInfo)) return; for (uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x) { if (m_spellInfo->Reagent[x] <= 0) continue; uint32 itemid = m_spellInfo->Reagent[x]; uint32 itemcount = m_spellInfo->ReagentCount[x]; // if CastItem is also spell reagent if (castItemTemplate && castItemTemplate->ItemId == itemid) { for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s) { // CastItem will be used up and does not count as reagent int32 charges = _CastItem->GetSpellCharges(s); if (castItemTemplate->Spells[s].SpellCharges < 0 && abs(charges) < 2) { ++itemcount; break; } } _CastItem = NULL; } // if GetItemTarget is also spell reagent if (m_targets.GetItemTargetEntry() == itemid) m_targets.SetItemTarget(NULL); p_caster->DestroyItemCount(itemid, itemcount, true); } } void Spell::HandleThreatSpells() { if (m_UniqueTargetInfo.empty()) return; if ((m_spellInfo->AttributesEx & SPELL_ATTR1_NO_THREAT) || (m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)) return; float threat = 0.0f; if (SpellThreatEntry const* threatEntry = sSpellMgr->GetSpellThreatEntry(m_spellInfo->Id)) { if (threatEntry->apPctMod != 0.0f) threat += threatEntry->apPctMod * m_caster->GetTotalAttackPowerValue(BASE_ATTACK); threat += threatEntry->flatMod; } else if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_NO_INITIAL_THREAT) == 0) threat += m_spellInfo->SpellLevel; // past this point only multiplicative effects occur if (threat == 0.0f) return; // since 2.0.1 threat from positive effects also is distributed among all targets, so the overall caused threat is at most the defined bonus threat /= m_UniqueTargetInfo.size(); for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition != SPELL_MISS_NONE) continue; Unit* target = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); if (!target) continue; // positive spells distribute threat among all units that are in combat with target, like healing if (m_spellInfo->_IsPositiveSpell()) target->getHostileRefManager().threatAssist(m_caster, threat, m_spellInfo); // for negative spells threat gets distributed among affected targets else { if (!target->CanHaveThreatList()) continue; target->AddThreat(m_caster, threat, m_spellInfo->GetSchoolMask(), m_spellInfo); } } sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %u, added an additional %f threat for %s %u target(s)", m_spellInfo->Id, threat, m_spellInfo->_IsPositiveSpell() ? "assisting" : "harming", uint32(m_UniqueTargetInfo.size())); } void Spell::HandleHolyPower(Player* caster) { if (!caster) return; bool hit = true; m_powerCost = caster->GetPower(POWER_HOLY_POWER); // Always use all the holy power we have Player *modOwner = caster->GetSpellModOwner(); if (!m_powerCost || !modOwner) return; if (m_spellInfo->PowerType == POWER_HOLY_POWER) { if (uint64 targetGUID = m_targets.GetUnitTargetGUID()) { for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->targetGUID == targetGUID) { if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS) { hit = false; } break; } } } // The spell did hit the target, apply aura cost mods if there are any. if (hit) { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, m_powerCost); m_caster->ModifyPower(POWER_HOLY_POWER, -m_powerCost); } else return; } } void Spell::HandleEffects(Unit* pUnitTarget, Item* pItemTarget, GameObject* pGOTarget, uint32 i, SpellEffectHandleMode mode) { effectHandleMode = mode; unitTarget = pUnitTarget; itemTarget = pItemTarget; gameObjTarget = pGOTarget; destTarget = &m_destTargets[i]._position; uint8 eff = m_spellInfo->Effects[i].Effect; sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell: %u Effect : %u", m_spellInfo->Id, eff); // we do not need DamageMultiplier here. damage = CalculateDamage(i, NULL); bool preventDefault = CallScriptEffectHandlers((SpellEffIndex)i, mode); if (!preventDefault && eff < TOTAL_SPELL_EFFECTS) { (this->*SpellEffects[eff])((SpellEffIndex)i); } } SpellCastResult Spell::CheckCast(bool strict) { // check death state if (!m_caster->isAlive() && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !((m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD) || (IsTriggered() && !m_triggeredByAuraSpell))) return SPELL_FAILED_CASTER_DEAD; // check cooldowns to prevent cheating if (m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE)) { //can cast triggered (by aura only?) spells while have this flag if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE) && m_caster->ToPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_ALLOW_ONLY_ABILITY)) return SPELL_FAILED_SPELL_IN_PROGRESS; if (m_caster->ToPlayer()->HasSpellCooldown(m_spellInfo->Id)) { if (m_triggeredByAuraSpell) return SPELL_FAILED_DONT_REPORT; else return SPELL_FAILED_NOT_READY; } } if (m_spellInfo->AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL && !m_caster->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_ALLOW_CHEAT_SPELLS)) { m_customError = SPELL_CUSTOM_ERROR_GM_ONLY; return SPELL_FAILED_CUSTOM_ERROR; } // Check global cooldown if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_GCD) && HasGlobalCooldown()) return SPELL_FAILED_NOT_READY; // only triggered spells can be processed an ended battleground if (!IsTriggered() && m_caster->GetTypeId() == TYPEID_PLAYER) if (Battleground* bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() == STATUS_WAIT_LEAVE) return SPELL_FAILED_DONT_REPORT; if (m_caster->GetTypeId() == TYPEID_PLAYER && VMAP::VMapFactory::createOrGetVMapManager()->isLineOfSightCalcEnabled()) { if (m_spellInfo->Attributes & SPELL_ATTR0_OUTDOORS_ONLY && !m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) return SPELL_FAILED_ONLY_OUTDOORS; if (m_spellInfo->Attributes & SPELL_ATTR0_INDOORS_ONLY && m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) return SPELL_FAILED_ONLY_INDOORS; } // only check at first call, Stealth auras are already removed at second call // for now, ignore triggered spells if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_SHAPESHIFT)) { bool checkForm = true; // Ignore form req aura Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT); for (Unit::AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i) { if (!(*i)->IsAffectedOnSpell(m_spellInfo)) continue; checkForm = false; break; } if (checkForm) { // Cannot be used in this stance/form SpellCastResult shapeError = m_spellInfo->CheckShapeshift(m_caster->GetShapeshiftForm()); if (shapeError != SPELL_CAST_OK) return shapeError; if ((m_spellInfo->Attributes & SPELL_ATTR0_ONLY_STEALTHED) && !(m_caster->HasStealthAura())) return SPELL_FAILED_ONLY_STEALTHED; } } Unit::AuraEffectList const& blockSpells = m_caster->GetAuraEffectsByType(SPELL_AURA_BLOCK_SPELL_FAMILY); for (Unit::AuraEffectList::const_iterator blockItr = blockSpells.begin(); blockItr != blockSpells.end(); ++blockItr) if (uint32((*blockItr)->GetMiscValue()) == m_spellInfo->SpellFamilyName) return SPELL_FAILED_SPELL_UNAVAILABLE; bool reqCombat = true; Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE); for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j) { if ((*j)->IsAffectedOnSpell(m_spellInfo)) { m_needComboPoints = false; if ((*j)->GetMiscValue() == 1) { reqCombat=false; break; } } } // caster state requirements // not for triggered spells (needed by execute) if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE)) { if (m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraState), m_spellInfo, m_caster)) return SPELL_FAILED_CASTER_AURASTATE; if (m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraStateNot), m_spellInfo, m_caster)) return SPELL_FAILED_CASTER_AURASTATE; // Note: spell 62473 requres casterAuraSpell = triggering spell if (m_spellInfo->CasterAuraSpell && !m_caster->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->CasterAuraSpell, m_caster))) return SPELL_FAILED_CASTER_AURASTATE; if (m_spellInfo->ExcludeCasterAuraSpell && m_caster->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->ExcludeCasterAuraSpell, m_caster))) return SPELL_FAILED_CASTER_AURASTATE; if (reqCombat && m_caster->isInCombat() && !m_spellInfo->CanBeUsedInCombat()) return SPELL_FAILED_AFFECTING_COMBAT; } // cancel autorepeat spells if cast start when moving // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code) if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving()) { // skip stuck spell to allow use it in falling case and apply spell limitations at movement if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK) && (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) && !m_caster->CanCastWhileWalking(m_spellInfo->Id)) return SPELL_FAILED_MOVING; } Vehicle* vehicle = m_caster->GetVehicle(); if (vehicle && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE)) { uint16 checkMask = 0; for (uint8 effIndex = EFFECT_0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { SpellEffectInfo const* effInfo = &m_spellInfo->Effects[effIndex]; if (effInfo->ApplyAuraName == SPELL_AURA_MOD_SHAPESHIFT) { SpellShapeshiftFormEntry const* shapeShiftEntry = sSpellShapeshiftFormStore.LookupEntry(effInfo->MiscValue); if (shapeShiftEntry && (shapeShiftEntry->flags1 & 1) == 0) // unk flag checkMask |= VEHICLE_SEAT_FLAG_UNCONTROLLED; break; } } if (m_spellInfo->HasAura(SPELL_AURA_MOUNTED)) checkMask |= VEHICLE_SEAT_FLAG_CAN_CAST_MOUNT_SPELL; if (!checkMask) checkMask = VEHICLE_SEAT_FLAG_CAN_ATTACK; VehicleSeatEntry const* vehicleSeat = vehicle->GetSeatForPassenger(m_caster); if (!(m_spellInfo->AttributesEx6 & SPELL_ATTR6_CASTABLE_WHILE_ON_VEHICLE) && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_MOUNTED) && (vehicleSeat->m_flags & checkMask) != checkMask) return SPELL_FAILED_DONT_REPORT; } // check spell cast conditions from database { ConditionSourceInfo condInfo = ConditionSourceInfo(m_caster); condInfo.mConditionTargets[1] = m_targets.GetObjectTarget(); ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL, m_spellInfo->Id); if (!conditions.empty() && !sConditionMgr->IsObjectMeetToConditions(condInfo, conditions)) { // send error msg to player if condition failed and text message available // TODO: using WorldSession::SendNotification is not blizzlike if (Player* playerCaster = m_caster->ToPlayer()) { // mLastFailedCondition can be NULL if there was an error processing the condition in Condition::Meets (i.e. wrong data for ConditionTarget or others) if (playerCaster->GetSession() && condInfo.mLastFailedCondition && condInfo.mLastFailedCondition->ErrorTextId) { playerCaster->GetSession()->SendNotification(condInfo.mLastFailedCondition->ErrorTextId); return SPELL_FAILED_DONT_REPORT; } } if (!condInfo.mLastFailedCondition || !condInfo.mLastFailedCondition->ConditionTarget) return SPELL_FAILED_CASTER_AURASTATE; return SPELL_FAILED_BAD_TARGETS; } } // Don't check explicit target for passive spells (workaround) (check should be skipped only for learn case) // those spells may have incorrect target entries or not filled at all (for example 15332) // such spells when learned are not targeting anyone using targeting system, they should apply directly to caster instead // also, such casts shouldn't be sent to client if (!((m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster))) { // Check explicit target for m_originalCaster - todo: get rid of such workarounds SpellCastResult castResult = m_spellInfo->CheckExplicitTarget(m_originalCaster ? m_originalCaster : m_caster, m_targets.GetObjectTarget(), m_targets.GetItemTarget()); if (castResult != SPELL_CAST_OK) return castResult; } if (Unit* target = m_targets.GetUnitTarget()) { SpellCastResult castResult = m_spellInfo->CheckTarget(m_caster, target, false); if (castResult != SPELL_CAST_OK) return castResult; if (target != m_caster) { // Must be behind the target if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET) && target->HasInArc(static_cast<float>(M_PI), m_caster)) return SPELL_FAILED_NOT_BEHIND; // Target must be facing you if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_REQ_TARGET_FACING_CASTER) && !target->HasInArc(static_cast<float>(M_PI), m_caster)) return SPELL_FAILED_NOT_INFRONT; if (m_caster->GetEntry() != WORLD_TRIGGER) // Ignore LOS for gameobjects casts (wrongly casted by a trigger) if (!(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target)) return SPELL_FAILED_LINE_OF_SIGHT; } } //Check for line of sight for spells with dest if (m_targets.HasDst()) { float x, y, z; m_targets.GetDstPos()->GetPosition(x, y, z); if (!(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOS(x, y, z)) return SPELL_FAILED_LINE_OF_SIGHT; } // check pet presence for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (m_spellInfo->Effects[j].TargetA.GetTarget() == TARGET_UNIT_PET) { if (!m_caster->GetGuardianPet()) { if (m_triggeredByAuraSpell) // not report pet not existence for triggered spells return SPELL_FAILED_DONT_REPORT; else return SPELL_FAILED_NO_PET; } break; } } // Spell casted only on battleground if ((m_spellInfo->AttributesEx3 & SPELL_ATTR3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER) if (!m_caster->ToPlayer()->InBattleground()) return SPELL_FAILED_ONLY_BATTLEGROUNDS; // do not allow spells to be cast in arenas // - with greater than 10 min CD without SPELL_ATTR4_USABLE_IN_ARENA flag // - with SPELL_ATTR4_NOT_USABLE_IN_ARENA flag if ((m_spellInfo->AttributesEx4 & SPELL_ATTR4_NOT_USABLE_IN_ARENA) || (m_spellInfo->GetRecoveryTime() > 10 * MINUTE * IN_MILLISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR4_USABLE_IN_ARENA))) if (MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId())) if (mapEntry->IsBattleArena()) return SPELL_FAILED_NOT_IN_ARENA; // zone check if (m_caster->GetTypeId() == TYPEID_UNIT || !m_caster->ToPlayer()->isGameMaster()) { uint32 zone, area; m_caster->GetZoneAndAreaId(zone, area); SpellCastResult locRes= m_spellInfo->CheckLocation(m_caster->GetMapId(), zone, area, m_caster->GetTypeId() == TYPEID_PLAYER ? m_caster->ToPlayer() : NULL); if (locRes != SPELL_CAST_OK) return locRes; } // not let players cast spells at mount (and let do it to creatures) if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE) && !m_spellInfo->IsPassive() && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_MOUNTED)) { if (m_caster->isInFlight()) return SPELL_FAILED_NOT_ON_TAXI; else return SPELL_FAILED_NOT_MOUNTED; } SpellCastResult castResult = SPELL_CAST_OK; // always (except passive spells) check items (focus object can be required for any type casts) if (!m_spellInfo->IsPassive()) { castResult = CheckItems(); if (castResult != SPELL_CAST_OK) return castResult; } // Triggered spells also have range check // TODO: determine if there is some flag to enable/disable the check castResult = CheckRange(strict); if (castResult != SPELL_CAST_OK) return castResult; if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)) { castResult = CheckPower(); if (castResult != SPELL_CAST_OK) return castResult; } if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURAS)) { castResult = CheckCasterAuras(); if (castResult != SPELL_CAST_OK) return castResult; } // script hook castResult = CallScriptCheckCastHandlers(); if (castResult != SPELL_CAST_OK) return castResult; for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { // for effects of spells that have only one target switch (m_spellInfo->Effects[i].Effect) { case SPELL_EFFECT_DUMMY: { if (m_spellInfo->Id == 51582) // Rocket Boots Engaged { if (m_caster->IsInWater()) return SPELL_FAILED_ONLY_ABOVEWATER; } else if (m_spellInfo->SpellIconID == 156) // Holy Shock { // spell different for friends and enemies // hurt version required facing if (m_targets.GetUnitTarget() && !m_caster->IsFriendlyTo(m_targets.GetUnitTarget()) && !m_caster->HasInArc(static_cast<float>(M_PI), m_targets.GetUnitTarget())) return SPELL_FAILED_UNIT_NOT_INFRONT; } else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] == 0x2000) // Death Coil (DeathKnight) { Unit* target = m_targets.GetUnitTarget(); if (!target || (target->IsFriendlyTo(m_caster) && target->GetCreatureType() != CREATURE_TYPE_UNDEAD)) return SPELL_FAILED_BAD_TARGETS; } else if (m_spellInfo->Id == 19938) // Awaken Peon { Unit* unit = m_targets.GetUnitTarget(); if (!unit || !unit->HasAura(17743)) return SPELL_FAILED_BAD_TARGETS; } else if (m_spellInfo->Id == 52264) // Deliver Stolen Horse { if (!m_caster->FindNearestCreature(28653, 5)) return SPELL_FAILED_OUT_OF_RANGE; } else if (m_spellInfo->Id == 31789) // Righteous Defense { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_DONT_REPORT; Unit* target = m_targets.GetUnitTarget(); if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty()) return SPELL_FAILED_BAD_TARGETS; } break; } case SPELL_EFFECT_HEAL_MAX_HEALTH: { Unit* target = m_targets.GetUnitTarget(); if (target) { // Cannot be cast on paladin with Forbearance if (m_spellInfo->Id == 633) // Lay on Hands if (target->HasAura(25771)) return SPELL_FAILED_TARGET_AURASTATE; } break; } case SPELL_EFFECT_LEARN_SPELL: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_PET) break; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell); if (!learn_spellproto) return SPELL_FAILED_NOT_KNOWN; if (m_spellInfo->SpellLevel > pet->getLevel()) return SPELL_FAILED_LOWLEVEL; break; } case SPELL_EFFECT_BUY_GUILD_TAB: // Perk: Guild Bank 7th Slot { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (Guild* guild = m_caster->ToPlayer()->GetGuild()) if (guild->GetLeaderGUID() != m_caster->ToPlayer()->GetGUID()) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; break; } case SPELL_EFFECT_LEARN_PET_SPELL: { // check target only for unit target case if (Unit* unitTarget = m_targets.GetUnitTarget()) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Pet* pet = unitTarget->ToPet(); if (!pet || pet->GetOwner() != m_caster) return SPELL_FAILED_BAD_TARGETS; SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell); if (!learn_spellproto) return SPELL_FAILED_NOT_KNOWN; if (m_spellInfo->SpellLevel > pet->getLevel()) return SPELL_FAILED_LOWLEVEL; } break; } case SPELL_EFFECT_APPLY_GLYPH: { uint32 glyphId = m_spellInfo->Effects[i].MiscValue; if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyphId)) if (m_caster->HasAura(gp->SpellId)) return SPELL_FAILED_UNIQUE_GLYPH; break; } case SPELL_EFFECT_FEED_PET: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Item* foodItem = m_targets.GetItemTarget(); if (!foodItem) return SPELL_FAILED_BAD_TARGETS; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; if (!pet->HaveInDiet(foodItem->GetTemplate())) return SPELL_FAILED_WRONG_PET_FOOD; if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->ItemLevel)) return SPELL_FAILED_FOOD_LOWLEVEL; if (m_caster->isInCombat() || pet->isInCombat()) return SPELL_FAILED_AFFECTING_COMBAT; break; } case SPELL_EFFECT_POWER_BURN: case SPELL_EFFECT_POWER_DRAIN: { // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects) if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Unit* target = m_targets.GetUnitTarget()) if (target != m_caster && target->getPowerType() != Powers(m_spellInfo->Effects[i].MiscValue)) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_CHARGE: { if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR) { // Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953)) m_caster->RemoveMovementImpairingAuras(); } if (m_caster->HasUnitState(UNIT_STATE_ROOT)) return SPELL_FAILED_ROOTED; break; } case SPELL_EFFECT_SKINNING: { if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() != TYPEID_UNIT) return SPELL_FAILED_BAD_TARGETS; if (!(m_targets.GetUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE)) return SPELL_FAILED_TARGET_UNSKINNABLE; Creature* creature = m_targets.GetUnitTarget()->ToCreature(); if (creature->GetCreatureType() != CREATURE_TYPE_CRITTER && !creature->loot.isLooted()) return SPELL_FAILED_TARGET_NOT_LOOTED; uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill(); int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill); int32 TargetLevel = m_targets.GetUnitTarget()->getLevel(); int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5); if (ReqValue > skillValue) return SPELL_FAILED_LOW_CASTLEVEL; // chance for fail at orange skinning attempt if ((m_selfContainer && (*m_selfContainer) == this) && skillValue < sWorld->GetConfigMaxSkillValue() && (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37)) return SPELL_FAILED_TRY_AGAIN; break; } case SPELL_EFFECT_OPEN_LOCK: { if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_TARGET && m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_ITEM_TARGET) break; if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc. // we need a go target in case of TARGET_GAMEOBJECT_TARGET || (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget())) return SPELL_FAILED_BAD_TARGETS; Item* pTempItem = NULL; if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData()) pTempItem = pTrade->GetTraderData()->GetItem(TradeSlots(m_targets.GetItemTargetGUID())); } else if (m_targets.GetTargetMask() & TARGET_FLAG_ITEM) pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.GetItemTargetGUID()); // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM_TARGET if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET && !m_targets.GetGOTarget() && (!pTempItem || !pTempItem->GetTemplate()->LockID || !pTempItem->IsLocked())) return SPELL_FAILED_BAD_TARGETS; if (m_spellInfo->Id != 1842 || (m_targets.GetGOTarget() && m_targets.GetGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP)) if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners !m_caster->ToPlayer()->CanUseBattlegroundObject()) return SPELL_FAILED_TRY_AGAIN; // get the lock entry uint32 lockId = 0; if (GameObject* go = m_targets.GetGOTarget()) { lockId = go->GetGOInfo()->GetLockId(); if (!lockId) return SPELL_FAILED_BAD_TARGETS; } else if (Item* itm = m_targets.GetItemTarget()) lockId = itm->GetTemplate()->LockID; SkillType skillId = SKILL_NONE; int32 reqSkillValue = 0; int32 skillValue = 0; // check lock compatibility SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue); if (res != SPELL_CAST_OK) return res; // chance for fail at orange mining/herb/LockPicking gathering attempt // second check prevent fail at rechecks if (skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this))) { bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING; // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill) if ((canFailAtMax || skillValue < sWorld->GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37)) return SPELL_FAILED_TRY_AGAIN; } break; } case SPELL_EFFECT_SUMMON_DEAD_PET: { Creature* pet = m_caster->GetGuardianPet(); if (pet && pet->isAlive()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; break; } // This is generic summon effect case SPELL_EFFECT_SUMMON: { SummonPropertiesEntry const* SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[i].MiscValueB); if (!SummonProperties) break; switch (SummonProperties->Category) { case SUMMON_CATEGORY_PET: if (m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; case SUMMON_CATEGORY_PUPPET: if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } break; } case SPELL_EFFECT_CREATE_TAMED_PET: { if (m_targets.GetUnitTarget()) { if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (m_targets.GetUnitTarget()->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; } break; } case SPELL_EFFECT_SUMMON_PET: { if (m_caster->GetPetGUID()) //let warlock do a replacement summon { if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK) { if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player) if (Pet* pet = m_caster->ToPlayer()->GetPet()) pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID()); } else return SPELL_FAILED_ALREADY_HAVE_SUMMON; } if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } case SPELL_EFFECT_SUMMON_PLAYER: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_caster->ToPlayer()->GetSelection()) return SPELL_FAILED_BAD_TARGETS; Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetSelection()); if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell return SPELL_FAILED_BAD_TARGETS; // check if our map is dungeon MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId()); if (map->IsDungeon()) { uint32 mapId = m_caster->GetMap()->GetId(); Difficulty difficulty = m_caster->GetMap()->GetDifficulty(); if (map->IsRaid()) if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty)) if (InstancePlayerBind* casterBind = m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty)) if (targetBind->perm && targetBind->save != casterBind->save) return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE; InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapId); if (!instance) return SPELL_FAILED_TARGET_NOT_IN_INSTANCE; if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId)) return SPELL_FAILED_BAD_TARGETS; } break; } // RETURN HERE case SPELL_EFFECT_SUMMON_RAF_FRIEND: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Player* playerCaster = m_caster->ToPlayer(); // if (!(playerCaster->GetSelection())) return SPELL_FAILED_BAD_TARGETS; Player* target = ObjectAccessor::FindPlayer(playerCaster->GetSelection()); if (!target || !(target->GetSession()->GetRecruiterId() == playerCaster->GetSession()->GetAccountId() || target->GetSession()->GetAccountId() == playerCaster->GetSession()->GetRecruiterId())) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_LEAP: case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER: { //Do not allow to cast it before BG starts. if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() != STATUS_IN_PROGRESS) return SPELL_FAILED_TRY_AGAIN; break; } case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF: { if (m_targets.GetUnitTarget() == m_caster) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_LEAP_BACK: { // Spell 781 (Disengage) requires player to be in combat if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Id == 781 && !m_caster->isInCombat()) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; Unit* target = m_targets.GetUnitTarget(); if (m_caster == target && m_caster->HasUnitState(UNIT_STATE_ROOT)) { if (m_caster->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_ROOTED; else return SPELL_FAILED_DONT_REPORT; } break; } case SPELL_EFFECT_TALENT_SPEC_SELECT: // can't change during already started arena/battleground if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() == STATUS_IN_PROGRESS) return SPELL_FAILED_NOT_IN_BATTLEGROUND; break; default: break; } } for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { switch (m_spellInfo->Effects[i].ApplyAuraName) { case SPELL_AURA_DUMMY: { //custom check switch (m_spellInfo->Id) { // Tag Murloc case 30877: { Unit* target = m_targets.GetUnitTarget(); if (!target || target->GetEntry() != 17326) return SPELL_FAILED_BAD_TARGETS; break; } case 61336: //this spellid= Survival Instincts this needs checked. if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_caster->ToPlayer()->IsInFeralForm()) return SPELL_FAILED_ONLY_SHAPESHIFT; break; case 1515: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; Creature* target = m_targets.GetUnitTarget()->ToCreature(); if (target->getLevel() > m_caster->getLevel()) return SPELL_FAILED_HIGHLEVEL; // use SMSG_PET_TAME_FAILURE? if (!target->GetCreatureTemplate()->isTameable (m_caster->ToPlayer()->CanTameExoticPets())) return SPELL_FAILED_BAD_TARGETS; if (m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } case 44795: // Parachute { float x, y, z; m_caster->GetPosition(x, y, z); float ground_Z = m_caster->GetMap()->GetHeight(m_caster->GetPhaseMask(), x, y, z); if (fabs(ground_Z - z) < 0.1f) return SPELL_FAILED_DONT_REPORT; break; } default: break; } break; } case SPELL_AURA_SCHOOL_IMMUNITY: { Unit* target = m_targets.GetUnitTarget(); if (target) { // Cannot be cast on paladin with Forbearance if (m_spellInfo->Id == 642 || m_spellInfo->Id == 1022) // Divine Shield - Hand of Protection if (target->HasAura(25771)) return SPELL_FAILED_TARGET_AURASTATE; } break; } case SPELL_AURA_MOD_POSSESS_PET: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_NO_PET; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; if (pet->GetCharmerGUID()) return SPELL_FAILED_CHARMED; break; } case SPELL_AURA_MOD_POSSESS: case SPELL_AURA_MOD_CHARM: case SPELL_AURA_AOE_CHARM: { if (m_caster->GetCharmerGUID()) return SPELL_FAILED_CHARMED; if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_CHARM || m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_POSSESS) { if (m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; } if (Unit* target = m_targets.GetUnitTarget()) { if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; if (target->IsMounted()) return SPELL_FAILED_CANT_BE_CHARMED; if (target->GetCharmerGUID()) return SPELL_FAILED_CHARMED; int32 damage = CalculateDamage(i, target); if (damage && int32(target->getLevel()) > damage) return SPELL_FAILED_HIGHLEVEL; } break; } case SPELL_AURA_MOUNTED: { if (m_caster->IsInWater()) return SPELL_FAILED_ONLY_ABOVEWATER; // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells bool allowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena(); InstanceTemplate const* it = sObjectMgr->GetInstanceTemplate(m_caster->GetMapId()); if (it) allowMount = it->AllowMount; if (m_caster->GetTypeId() == TYPEID_PLAYER && !allowMount && !m_spellInfo->AreaGroupId) return SPELL_FAILED_NO_MOUNTS_ALLOWED; if (m_caster->IsInDisallowedMountForm()) return SPELL_FAILED_NOT_SHAPESHIFT; break; } case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS: { if (!m_targets.GetUnitTarget()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; // can be casted at non-friendly unit or own pet/charm if (m_caster->IsFriendlyTo(m_targets.GetUnitTarget())) return SPELL_FAILED_TARGET_FRIENDLY; break; } case SPELL_AURA_FLY: case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED: { // not allow cast fly spells if not have req. skills (all spells is self target) // allow always ghost flight spells if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->isAlive()) { if (AreaTableEntry const* pArea = GetAreaEntryByAreaID(m_originalCaster->GetAreaId())) if (pArea->flags & AREA_FLAG_NO_FLY_ZONE) return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE; } break; } case SPELL_AURA_PERIODIC_MANA_LEECH: { if (m_spellInfo->Effects[i].IsTargetingArea()) break; if (!m_targets.GetUnitTarget()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; if (m_caster->GetTypeId() != TYPEID_PLAYER || _CastItem) break; if (m_targets.GetUnitTarget()->getPowerType() != POWER_MANA) return SPELL_FAILED_BAD_TARGETS; break; } default: break; } } // check trade slot case (last, for allow catch any another cast problems) if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (_CastItem) return SPELL_FAILED_ITEM_ENCHANT_TRADE_WINDOW; if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_NOT_TRADING; TradeData* my_trade = m_caster->ToPlayer()->GetTradeData(); if (!my_trade) return SPELL_FAILED_NOT_TRADING; TradeSlots slot = TradeSlots(m_targets.GetItemTargetGUID()); if (slot != TRADE_SLOT_NONTRADED) return SPELL_FAILED_BAD_TARGETS; if (!IsTriggered()) if (my_trade->GetSpell()) return SPELL_FAILED_ITEM_ALREADY_ENCHANTED; } // check if caster has at least 1 combo point for spells that require combo points if (m_needComboPoints) if (Player* plrCaster = m_caster->ToPlayer()) if (!plrCaster->GetComboPoints()) return SPELL_FAILED_NO_COMBO_POINTS; // all ok return SPELL_CAST_OK; } SpellCastResult Spell::CheckPetCast(Unit* target) { if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS)) //prevent spellcast interruption by another spellcast return SPELL_FAILED_SPELL_IN_PROGRESS; // dead owner (pets still alive when owners ressed?) if (Unit* owner = m_caster->GetCharmerOrOwner()) if (!owner->isAlive()) return SPELL_FAILED_CASTER_DEAD; if (!target && m_targets.GetUnitTarget()) target = m_targets.GetUnitTarget(); if (m_spellInfo->NeedsExplicitUnitTarget()) { if (!target) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; m_targets.SetUnitTarget(target); } // cooldown if (Creature const* creatureCaster = m_caster->ToCreature()) if (creatureCaster->HasSpellCooldown(m_spellInfo->Id)) return SPELL_FAILED_NOT_READY; return CheckCast(true); } SpellCastResult Spell::CheckCasterAuras() const { // spells totally immuned to caster auras (wsg flag drop, give marks etc) if (m_spellInfo->AttributesEx6 & SPELL_ATTR6_IGNORE_CASTER_AURAS) return SPELL_CAST_OK; uint8 school_immune = 0; uint32 mechanic_immune = 0; uint32 dispel_immune = 0; // Check if the spell grants school or mechanic immunity. // We use bitmasks so the loop is done only once and not on every aura check below. if (m_spellInfo->AttributesEx & SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY) { for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_SCHOOL_IMMUNITY) school_immune |= uint32(m_spellInfo->Effects[i].MiscValue); else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MECHANIC_IMMUNITY) mechanic_immune |= 1 << uint32(m_spellInfo->Effects[i].MiscValue); else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_DISPEL_IMMUNITY) dispel_immune |= SpellInfo::GetDispelMask(DispelType(m_spellInfo->Effects[i].MiscValue)); } // immune movement impairment and loss of control if (m_spellInfo->Id == 42292 || m_spellInfo->Id == 59752) mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK; } bool usableInStun = m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_STUNNED; // Glyph of Pain Suppression // there is no other way to handle it if (m_spellInfo->Id == 33206 && !m_caster->HasAura(63248)) usableInStun = false; // Check whether the cast should be prevented by any state you might have. SpellCastResult prevented_reason = SPELL_CAST_OK; // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state if (unitflag & UNIT_FLAG_STUNNED) { // spell is usable while stunned, check if caster has only mechanic stun auras, another stun types must prevent cast spell if (usableInStun) { bool foundNotStun = false; Unit::AuraEffectList const& stunAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_STUN); for (Unit::AuraEffectList::const_iterator i = stunAuras.begin(); i != stunAuras.end(); ++i) { if (!((*i)->GetSpellInfo()->GetAllEffectsMechanicMask() & (1<<MECHANIC_STUN))) { foundNotStun = true; break; } } if (foundNotStun) prevented_reason = SPELL_FAILED_STUNNED; } else prevented_reason = SPELL_FAILED_STUNNED; } else if (unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED)) prevented_reason = SPELL_FAILED_CONFUSED; else if (unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED)) prevented_reason = SPELL_FAILED_FLEEING; else if (unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) prevented_reason = SPELL_FAILED_SILENCED; else if (unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY) prevented_reason = SPELL_FAILED_PACIFIED; // Attr must make flag drop spell totally immune from all effects if (prevented_reason != SPELL_CAST_OK) { if (school_immune || mechanic_immune || dispel_immune) { //Checking auras is needed now, because you are prevented by some state but the spell grants immunity. Unit::AuraApplicationMap const& auras = m_caster->GetAppliedAuras(); for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura const* aura = itr->second->GetBase(); SpellInfo const* auraInfo = aura->GetSpellInfo(); if (auraInfo->GetAllEffectsMechanicMask() & mechanic_immune) continue; if (auraInfo->GetSchoolMask() & school_immune) continue; if (auraInfo->GetDispelMask() & dispel_immune) continue; //Make a second check for spell failed so the right SPELL_FAILED message is returned. //That is needed when your casting is prevented by multiple states and you are only immune to some of them. for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (AuraEffect* part = aura->GetEffect(i)) { switch (part->GetAuraType()) { case SPELL_AURA_MOD_STUN: if (!usableInStun || !(auraInfo->GetAllEffectsMechanicMask() & (1<<MECHANIC_STUN))) return SPELL_FAILED_STUNNED; break; case SPELL_AURA_MOD_CONFUSE: if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED)) return SPELL_FAILED_CONFUSED; break; case SPELL_AURA_MOD_FEAR: if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED)) return SPELL_FAILED_FLEEING; break; case SPELL_AURA_MOD_SILENCE: case SPELL_AURA_MOD_PACIFY: case SPELL_AURA_MOD_PACIFY_SILENCE: if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY) return SPELL_FAILED_PACIFIED; else if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) return SPELL_FAILED_SILENCED; break; default: break; } } } } } // You are prevented from casting and the spell casted does not grant immunity. Return a failed error. else return prevented_reason; } return SPELL_CAST_OK; } bool Spell::CanAutoCast(Unit* target) { uint64 targetguid = target->GetGUID(); for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (m_spellInfo->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA) { if (m_spellInfo->StackAmount <= 1) { if (target->HasAuraEffect(m_spellInfo->Id, j)) return false; } else { if (AuraEffect* aureff = target->GetAuraEffect(m_spellInfo->Id, j)) if (aureff->GetBase()->GetStackAmount() >= m_spellInfo->StackAmount) return false; } } else if (m_spellInfo->Effects[j].IsAreaAuraEffect()) { if (target->HasAuraEffect(m_spellInfo->Id, j)) return false; } } SpellCastResult result = CheckPetCast(target); if (result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT) { SelectSpellTargets(); //check if among target units, our WANTED target is as well (->only self cast spells return false) for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetguid) return true; } return false; //target invalid } SpellCastResult Spell::CheckRange(bool strict) { // Don't check for instant cast spells if (!strict && m_casttime == 0) return SPELL_CAST_OK; uint32 range_type = 0; if (m_spellInfo->RangeEntry) { // check needed by 68766 51693 - both spells are cast on enemies and have 0 max range // these are triggered by other spells - possibly we should omit range check in that case? if (m_spellInfo->RangeEntry->ID == 1) return SPELL_CAST_OK; range_type = m_spellInfo->RangeEntry->type; } Unit* target = m_targets.GetUnitTarget(); float max_range = m_caster->GetSpellMaxRangeForTarget(target, m_spellInfo); float min_range = m_caster->GetSpellMinRangeForTarget(target, m_spellInfo); if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this); if (target && target != m_caster) { if (range_type == SPELL_RANGE_MELEE) { // Because of lag, we can not check too strictly here. if (!m_caster->IsWithinMeleeRange(target, max_range)) return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; } else if (!m_caster->IsWithinCombatRange(target, max_range)) return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; //0x5A; if (range_type == SPELL_RANGE_RANGED) { if (m_caster->IsWithinMeleeRange(target)) return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT; } else if (min_range && m_caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0 return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT; if (m_caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc(static_cast<float>(M_PI), target)) return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_UNIT_NOT_INFRONT : SPELL_FAILED_DONT_REPORT; } if (m_targets.HasDst() && !m_targets.HasTraj()) { if (!m_caster->IsWithinDist3d(m_targets.GetDstPos(), max_range)) return SPELL_FAILED_OUT_OF_RANGE; if (min_range && m_caster->IsWithinDist3d(m_targets.GetDstPos(), min_range)) return SPELL_FAILED_TOO_CLOSE; } return SPELL_CAST_OK; } SpellCastResult Spell::CheckPower() { // item cast not used power if (_CastItem) return SPELL_CAST_OK; // health as power used - need check health amount if (m_spellInfo->PowerType == POWER_HEALTH) { if (int32(m_caster->GetHealth()) <= m_powerCost) return SPELL_FAILED_CASTER_AURASTATE; return SPELL_CAST_OK; } // Check valid power type if (m_spellInfo->PowerType >= MAX_POWERS) { sLog->outError("Spell::CheckPower: Unknown power type '%d'", m_spellInfo->PowerType); return SPELL_FAILED_UNKNOWN; } //check rune cost only if a spell has PowerType == POWER_RUNE if (m_spellInfo->PowerType == POWER_RUNE) { SpellCastResult failReason = CheckRuneCost(m_spellInfo->RuneCostID); if (failReason != SPELL_CAST_OK) return failReason; } // Check power amount Powers powerType = Powers(m_spellInfo->PowerType); if (int32(m_caster->GetPower(powerType)) < m_powerCost) return SPELL_FAILED_NO_POWER; else return SPELL_CAST_OK; } SpellCastResult Spell::CheckItems() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_CAST_OK; Player* p_caster = (Player*)m_caster; if (!_CastItem) { if (m_castItemGUID) return SPELL_FAILED_ITEM_NOT_READY; } else { uint32 itemid = _CastItem->GetEntry(); if (!p_caster->HasItemCount(itemid, 1)) return SPELL_FAILED_ITEM_NOT_READY; ItemTemplate const* proto = _CastItem->GetTemplate(); if (!proto) return SPELL_FAILED_ITEM_NOT_READY; for (int i = 0; i < MAX_ITEM_SPELLS; ++i) if (proto->Spells[i].SpellCharges) if (_CastItem->GetSpellCharges(i) == 0) return SPELL_FAILED_NO_CHARGES_REMAIN; // consumable cast item checks if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.GetUnitTarget()) { // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example SpellCastResult failReason = SPELL_CAST_OK; for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { // skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.GetUnitTarget() is not the real target but the caster if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_PET) continue; if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_HEAL) { if (m_targets.GetUnitTarget()->IsFullHealth()) { failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH; continue; } else { failReason = SPELL_CAST_OK; break; } } // Mana Potion, Rage Potion, Thistle Tea(Rogue), ... if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_ENERGIZE) { if (m_spellInfo->Effects[i].MiscValue < 0 || m_spellInfo->Effects[i].MiscValue >= int8(MAX_POWERS)) { failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER; continue; } Powers power = Powers(m_spellInfo->Effects[i].MiscValue); if (m_targets.GetUnitTarget()->GetPower(power) == m_targets.GetUnitTarget()->GetMaxPower(power)) { failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER; continue; } else { failReason = SPELL_CAST_OK; break; } } } if (failReason != SPELL_CAST_OK) return failReason; } } // check target item if (m_targets.GetItemTargetGUID()) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_targets.GetItemTarget()) return SPELL_FAILED_ITEM_GONE; if (!m_targets.GetItemTarget()->IsFitToSpellRequirements(m_spellInfo)) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // if not item target then required item must be equipped else { if (m_caster->GetTypeId() == TYPEID_PLAYER && !m_caster->ToPlayer()->HasItemFitToSpellRequirements(m_spellInfo)) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // check spell focus object if (m_spellInfo->RequiresSpellFocus) { CellCoord p(SkyFire::ComputeCellCoord(m_caster->GetPositionX(), m_caster->GetPositionY())); Cell cell(p); GameObject* ok = NULL; SkyFire::GameObjectFocusCheck go_check(m_caster, m_spellInfo->RequiresSpellFocus); SkyFire::GameObjectSearcher<SkyFire::GameObjectFocusCheck> checker(m_caster, ok, go_check); TypeContainerVisitor<SkyFire::GameObjectSearcher<SkyFire::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker); Map& map = *m_caster->GetMap(); cell.Visit(p, object_checker, map, *m_caster, m_caster->GetVisibilityRange()); if (!ok) return SPELL_FAILED_REQUIRES_SPELL_FOCUS; focusObject = ok; // game object found in range } // do not take reagents for these item casts if (!(_CastItem && _CastItem->GetTemplate()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST)) { bool checkReagents = !(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST) && !p_caster->CanNoReagentCast(m_spellInfo); // Not own traded item (in trader trade slot) requires reagents even if triggered spell if (!checkReagents) if (Item* targetItem = m_targets.GetItemTarget()) if (targetItem->GetOwnerGUID() != m_caster->GetGUID()) checkReagents = true; // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case. if (checkReagents) { for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++) { if (m_spellInfo->Reagent[i] <= 0) continue; uint32 itemid = m_spellInfo->Reagent[i]; uint32 itemcount = m_spellInfo->ReagentCount[i]; // if CastItem is also spell reagent if (_CastItem && _CastItem->GetEntry() == itemid) { ItemTemplate const* proto = _CastItem->GetTemplate(); if (!proto) return SPELL_FAILED_ITEM_NOT_READY; for (int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s) { // CastItem will be used up and does not count as reagent int32 charges = _CastItem->GetSpellCharges(s); if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2) { ++itemcount; break; } } } if (!p_caster->HasItemCount(itemid, itemcount)) return SPELL_FAILED_REAGENTS; } } // check totem-item requirements (items presence in inventory) uint32 totems = 2; for (int i = 0; i < 2; ++i) { if (m_spellInfo->Totem[i] != 0) { if (p_caster->HasItemCount(m_spellInfo->Totem[i], 1)) { totems -= 1; continue; } }else totems -= 1; } if (totems != 0) return SPELL_FAILED_TOTEMS; //0x7C } // special checks for spell effects for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { switch (m_spellInfo->Effects[i].Effect) { case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_CREATE_ITEM_2: { if (!IsTriggered() && m_spellInfo->Effects[i].ItemType) { ItemPosCountVec dest; InventoryResult msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1); if (msg != EQUIP_ERR_OK) { ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(m_spellInfo->Effects[i].ItemType); // TODO: Needs review if (pProto && !(pProto->ItemLimitCategory)) { p_caster->SendEquipError(msg, NULL, NULL, m_spellInfo->Effects[i].ItemType); return SPELL_FAILED_DONT_REPORT; } else { if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000))) return SPELL_FAILED_TOO_MANY_OF_ITEM; else if (!(p_caster->HasItemCount(m_spellInfo->Effects[i].ItemType, 1))) return SPELL_FAILED_TOO_MANY_OF_ITEM; else p_caster->CastSpell(m_caster, m_spellInfo->Effects[EFFECT_1].CalcValue(), false); // move this to anywhere return SPELL_FAILED_DONT_REPORT; } } } break; } case SPELL_EFFECT_ENCHANT_ITEM: if (m_spellInfo->Effects[i].ItemType && m_targets.GetItemTarget() && (m_targets.GetItemTarget()->IsArmorVellum())) { // cannot enchant vellum for other player if (m_targets.GetItemTarget()->GetOwner() != m_caster) return SPELL_FAILED_NOT_TRADEABLE; // do not allow to enchant vellum from scroll made by vellum-prevent exploit if (_CastItem && _CastItem->GetTemplate()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST) return SPELL_FAILED_TOTEM_CATEGORY; ItemPosCountVec dest; InventoryResult msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1); if (msg != EQUIP_ERR_OK) { p_caster->SendEquipError(msg, NULL, NULL, m_spellInfo->Effects[i].ItemType); return SPELL_FAILED_DONT_REPORT; } } case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC: { Item* targetItem = m_targets.GetItemTarget(); if (!targetItem) return SPELL_FAILED_ITEM_NOT_FOUND; if (targetItem->GetTemplate()->ItemLevel < m_spellInfo->BaseLevel) return SPELL_FAILED_LOWLEVEL; bool isItemUsable = false; for (uint8 e = 0; e < MAX_ITEM_PROTO_SPELLS; ++e) { ItemTemplate const* proto = targetItem->GetTemplate(); if (proto->Spells[e].SpellId && ( proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE || proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)) { isItemUsable = true; break; } } SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(m_spellInfo->Effects[i].MiscValue); // do not allow adding usable enchantments to items that have use effect already if (pEnchant && isItemUsable) for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s) if (pEnchant->type[s] == ITEM_ENCHANTMENT_TYPE_USE_SPELL) return SPELL_FAILED_ON_USE_ENCHANT; // Not allow enchant in trade slot for some enchant type if (targetItem->GetOwner() != m_caster) { if (!pEnchant) return SPELL_FAILED_ERROR; if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND) return SPELL_FAILED_NOT_TRADEABLE; } break; } case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY: { Item* item = m_targets.GetItemTarget(); if (!item) return SPELL_FAILED_ITEM_NOT_FOUND; // Not allow enchant in trade slot for some enchant type if (item->GetOwner() != m_caster) { uint32 enchant_id = m_spellInfo->Effects[i].MiscValue; SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return SPELL_FAILED_ERROR; if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND) return SPELL_FAILED_NOT_TRADEABLE; } break; } case SPELL_EFFECT_ENCHANT_HELD_ITEM: // check item existence in effect code (not output errors at offhand hold item effect to main hand for example break; case SPELL_EFFECT_DISENCHANT: { if (!m_targets.GetItemTarget()) return SPELL_FAILED_CANT_BE_DISENCHANTED; // prevent disenchanting in trade slot if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_DISENCHANTED; ItemTemplate const* itemProto = m_targets.GetItemTarget()->GetTemplate(); if (!itemProto) return SPELL_FAILED_CANT_BE_DISENCHANTED; uint32 item_quality = itemProto->Quality; // 2.0.x addon: Check player enchanting level against the item disenchanting requirements uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill; if (item_disenchantskilllevel == uint32(-1)) return SPELL_FAILED_CANT_BE_DISENCHANTED; if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING)) return SPELL_FAILED_LOW_CASTLEVEL; if (item_quality > 4 || item_quality < 2) return SPELL_FAILED_CANT_BE_DISENCHANTED; if (itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR) return SPELL_FAILED_CANT_BE_DISENCHANTED; if (!itemProto->DisenchantID) return SPELL_FAILED_CANT_BE_DISENCHANTED; break; } case SPELL_EFFECT_PROSPECTING: { if (!m_targets.GetItemTarget()) return SPELL_FAILED_CANT_BE_PROSPECTED; //ensure item is a prospectable ore if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_PROTO_FLAG_PROSPECTABLE)) return SPELL_FAILED_CANT_BE_PROSPECTED; //prevent prospecting in trade slot if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_PROSPECTED; //Check for enough skill in jewelcrafting uint32 item_prospectingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank; if (item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING)) return SPELL_FAILED_LOW_CASTLEVEL; //make sure the player has the required ores in inventory if (m_targets.GetItemTarget()->GetCount() < 5) return SPELL_FAILED_NEED_MORE_ITEMS; if (!LootTemplates_Prospecting.HaveLootFor(m_targets.GetItemTargetEntry())) return SPELL_FAILED_CANT_BE_PROSPECTED; break; } case SPELL_EFFECT_MILLING: { if (!m_targets.GetItemTarget()) return SPELL_FAILED_CANT_BE_MILLED; //ensure item is a millable herb if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_PROTO_FLAG_MILLABLE)) return SPELL_FAILED_CANT_BE_MILLED; //prevent milling in trade slot if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_MILLED; //Check for enough skill in inscription uint32 item_millingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank; if (item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION)) return SPELL_FAILED_LOW_CASTLEVEL; //make sure the player has the required herbs in inventory if (m_targets.GetItemTarget()->GetCount() < 5) return SPELL_FAILED_NEED_MORE_ITEMS; if (!LootTemplates_Milling.HaveLootFor(m_targets.GetItemTargetEntry())) return SPELL_FAILED_CANT_BE_MILLED; break; } case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER; if (m_attackType != RANGED_ATTACK) break; Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType); if (!pItem || pItem->IsBroken()) return SPELL_FAILED_EQUIPPED_ITEM; switch (pItem->GetTemplate()->SubClass) { case ITEM_SUBCLASS_WEAPON_THROWN: case ITEM_SUBCLASS_WEAPON_GUN: case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_CROSSBOW: case ITEM_SUBCLASS_WEAPON_WAND: break; default: break; } break; } case SPELL_EFFECT_CREATE_MANA_GEM: { uint32 item_id = m_spellInfo->Effects[i].ItemType; ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id); if (!pProto) return SPELL_FAILED_ITEM_AT_MAX_CHARGES; if (Item* pitem = p_caster->GetItemByEntry(item_id)) { for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges) return SPELL_FAILED_ITEM_AT_MAX_CHARGES; } break; } default: break; } } // check weapon presence in slots for main/offhand weapons if (m_spellInfo->EquippedItemClass >=0) { // main hand weapon required if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_MAIN_HAND) { Item* item = m_caster->ToPlayer()->GetWeaponForAttack(BASE_ATTACK); // skip spell if no weapon in slot or broken if (!item || item->IsBroken()) return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; // skip spell if weapon not fit to triggered spell if (!item->IsFitToSpellRequirements(m_spellInfo)) return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // offhand hand weapon required if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND) { Item* item = m_caster->ToPlayer()->GetWeaponForAttack(OFF_ATTACK); // skip spell if no weapon in slot or broken if (!item || item->IsBroken()) return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; // skip spell if weapon not fit to triggered spell if (!item->IsFitToSpellRequirements(m_spellInfo)) return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; } } return SPELL_CAST_OK; } void Spell::Delayed() // only called in DealDamage() { if (!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER) return; //if (m_spellState == SPELL_STATE_DELAYED) // return; // spell is active and can't be time-backed if (isDelayableNoMore()) // Spells may only be delayed twice return; // spells not loosing casting time (slam, dynamites, bombs..) //if (!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE)) // return; //check pushback reduce int32 delaytime = 500; // spellcasting delay is normally 500ms int32 delayReduce = 100; // must be initialized to 100 for percent modifiers m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; AddPctN(delaytime, -delayReduce); if (_timer + delaytime > m_casttime) { delaytime = m_casttime - _timer; _timer = m_casttime; } else _timer += delaytime; sLog->outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime); WorldPacket data(SMSG_SPELL_DELAYED, 8+4); data.append(m_caster->GetPackGUID()); data << uint32(delaytime); m_caster->SendMessageToSet(&data, true); } void Spell::DelayedChannel() { if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING) return; if (isDelayableNoMore()) // Spells may only be delayed twice return; //check pushback reduce int32 delaytime = CalculatePctN(m_spellInfo->GetDuration(), 25); // channeling delay is normally 25% of its time per hit int32 delayReduce = 100; // must be initialized to 100 for percent modifiers m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; AddPctN(delaytime, -delayReduce); if (_timer <= delaytime) { delaytime = _timer; _timer = 0; } else _timer -= delaytime; sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, _timer); for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if ((*ihit).missCondition == SPELL_MISS_NONE) if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime); // partially interrupt persistent area auras if (DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id)) dynObj->Delay(delaytime); SendChannelUpdate(_timer); } void Spell::UpdatePointers() { if (m_originalCasterGUID == m_caster->GetGUID()) m_originalCaster = m_caster; else { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL; } if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER) _CastItem = m_caster->ToPlayer()->GetItemByGuid(m_castItemGUID); m_targets.Update(m_caster); // further actions done only for dest targets if (!m_targets.HasDst()) return; // cache last transport WorldObject* transport = NULL; // update effect destinations (in case of moved transport dest target) for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { SpellDestination& dest = m_destTargets[effIndex]; if (!dest._transportGUID) continue; if (!transport || transport->GetGUID() != dest._transportGUID) transport = ObjectAccessor::GetWorldObject(*m_caster, dest._transportGUID); if (transport) { dest._position.Relocate(transport); dest._position.RelocateOffset(dest._transportOffset); } } } CurrentSpellTypes Spell::GetCurrentContainer() const { if (IsNextMeleeSwingSpell()) return(CURRENT_MELEE_SPELL); else if (IsAutoRepeat()) return(CURRENT_AUTOREPEAT_SPELL); else if (m_spellInfo->IsChanneled()) return(CURRENT_CHANNELED_SPELL); else return(CURRENT_GENERIC_SPELL); } bool Spell::CheckEffectTarget(Unit const* target, uint32 eff) const { switch (m_spellInfo->Effects[eff].ApplyAuraName) { case SPELL_AURA_MOD_POSSESS: case SPELL_AURA_MOD_CHARM: case SPELL_AURA_MOD_POSSESS_PET: case SPELL_AURA_AOE_CHARM: if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle()) return false; if (target->IsMounted()) return false; if (target->GetCharmerGUID()) return false; if (int32 damage = CalculateDamage(eff, target)) if ((int32)target->getLevel() > damage) return false; break; default: break; } if (IsTriggered() || m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) return true; // todo: shit below shouldn't be here, but it's temporary //Check targets for LOS visibility (except spells without range limitations) switch (m_spellInfo->Effects[eff].Effect) { case SPELL_EFFECT_RESURRECT_NEW: // player far away, maybe his corpse near? if (target != m_caster && !target->IsWithinLOSInMap(m_caster)) { if (!m_targets.GetCorpseTargetGUID()) return false; Corpse* corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.GetCorpseTargetGUID()); if (!corpse) return false; if (target->GetGUID() != corpse->GetOwnerGUID()) return false; if (!corpse->IsWithinLOSInMap(m_caster)) return false; } // all ok by some way or another, skip normal check break; default: // normal case // Get GO cast coordinates if original caster ->GO WorldObject* caster = NULL; if (IS_GAMEOBJECT_GUID(m_originalCasterGUID)) caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID); if (!caster) caster = m_caster; if (target != m_caster && !target->IsWithinLOSInMap(caster)) return false; break; } return true; } bool Spell::IsNextMeleeSwingSpell() const { return m_spellInfo->Attributes & SPELL_ATTR0_ON_NEXT_SWING; } bool Spell::IsAutoActionResetSpell() const { // TODO: changed SPELL_INTERRUPT_FLAG_AUTOATTACK ->SPELL_INTERRUPT_FLAG_INTERRUPT to fix compile - is this check correct at all? return !IsTriggered() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT); } bool Spell::IsNeedSendToClient() const { return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || m_spellInfo->IsChanneled() || m_spellInfo->Speed > 0.0f || (!m_triggeredByAuraSpell && !IsTriggered()); } bool Spell::HaveTargetsForEffect(uint8 effect) const { for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; for (std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; return false; } SpellEvent::SpellEvent(Spell* spell) : BasicEvent() { m_Spell = spell; } SpellEvent::~SpellEvent() { if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->cancel(); if (m_Spell->IsDeletable()) { delete m_Spell; } else { sLog->outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.", (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id); ASSERT(false); } } bool SpellEvent::Execute(uint64 e_time, uint32 p_time) { // update spell if it is not finished if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->update(p_time); // check spell state to process switch (m_Spell->getState()) { case SPELL_STATE_FINISHED: { // spell was finished, check deletable state if (m_Spell->IsDeletable()) { // check, if we do have unfinished triggered spells return true; // spell is deletable, finish event } // event will be re-added automatically at the end of routine) } break; case SPELL_STATE_DELAYED: { // first, check, if we have just started if (m_Spell->GetDelayStart() != 0) { // no, we aren't, do the typical update // check, if we have channeled spell on our hands /* if (IsChanneledSpell(m_Spell->m_spellInfo)) { // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish // check, if we have casting anything else except this channeled spell and autorepeat if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true)) { // another non-melee non-delayed spell is casted now, abort m_Spell->cancel(); } else { // Set last not triggered spell for apply spellmods ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true); // do the action (pass spell to channeling state) m_Spell->handle_immediate(); // And remove after effect handling ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false); } // event will be re-added automatically at the end of routine) } else */ { // run the spell handler and think about what we can do next uint64 t_offset = e_time - m_Spell->GetDelayStart(); uint64 n_offset = m_Spell->handle_delayed(t_offset); if (n_offset) { // re-add us to the queue m_Spell->GetCaster()->_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false); return false; // event not complete } // event complete // finish update event will be re-added automatically at the end of routine) } } else { // delaying had just started, record the moment m_Spell->SetDelayStart(e_time); // re-plan the event for the delay moment m_Spell->GetCaster()->_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false); return false; // event not complete } } break; default: { // all other states // event will be re-added automatically at the end of routine) } break; } // spell processing not complete, plan event on the next update interval m_Spell->GetCaster()->_Events.AddEvent(this, e_time + 1, false); return false; // event not complete } void SpellEvent::Abort(uint64 /*e_time*/) { // oops, the spell we try to do is aborted if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->cancel(); } bool SpellEvent::IsDeletable() const { return m_Spell->IsDeletable(); } bool Spell::IsValidDeadOrAliveTarget(Unit const* target) const { if (target->isAlive()) return !m_spellInfo->IsRequiringDeadTarget(); if (m_spellInfo->IsAllowingDeadTarget()) return true; return false; } void Spell::HandleLaunchPhase() { // handle effects with SPELL_EFFECT_HANDLE_LAUNCH mode for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { // don't do anything for empty effect if (!m_spellInfo->Effects[i].IsEffect()) continue; HandleEffects(NULL, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH); } float multiplier[MAX_SPELL_EFFECTS]; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_applyMultiplierMask & (1 << i)) multiplier[i] = m_spellInfo->Effects[i].CalcDamageMultiplier(m_originalCaster, this); bool usesAmmo = m_spellInfo->AttributesCu & SPELL_ATTR0_CU_DIRECT_DAMAGE; Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_CONSUME_NO_AMMO); for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) { if ((*j)->IsAffectedOnSpell(m_spellInfo)) usesAmmo=false; } for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { TargetInfo& target = *ihit; uint32 mask = target.effectMask; if (!mask) continue; DoAllEffectOnLaunchTarget(target, multiplier); } } void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier) { Unit* unit = NULL; // In case spell hit target, do all effect on that target if (targetInfo.missCondition == SPELL_MISS_NONE) unit = m_caster->GetGUID() == targetInfo.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, targetInfo.targetGUID); // In case spell reflect from target, do all effect on caster (if hit) else if (targetInfo.missCondition == SPELL_MISS_REFLECT && targetInfo.reflectResult == SPELL_MISS_NONE) unit = m_caster; if (!unit) return; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (targetInfo.effectMask & (1<<i)) { m_damage = 0; m_healing = 0; HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH_TARGET); if (m_damage > 0) { if (m_spellInfo->Effects[i].IsTargetingArea()) { m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask)); if (m_caster->GetTypeId() == TYPEID_UNIT) m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask)); if (m_caster->GetTypeId() == TYPEID_PLAYER) { uint32 targetAmount = m_UniqueTargetInfo.size(); if (targetAmount > 10) m_damage = m_damage * 10/targetAmount; } } } if (m_applyMultiplierMask & (1 << i)) { m_damage = int32(m_damage * m_damageMultipliers[i]); m_damageMultipliers[i] *= multiplier[i]; } targetInfo.damage += m_damage; } } targetInfo.crit = m_caster->isSpellCrit(unit, m_spellInfo, m_spellSchoolMask, m_attackType); } SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue) { if (!lockId) // possible case for GO and maybe for items. return SPELL_CAST_OK; // Get LockInfo LockEntry const* lockInfo = sLockStore.LookupEntry(lockId); if (!lockInfo) return SPELL_FAILED_BAD_TARGETS; bool reqKey = false; // some locks not have reqs for (int j = 0; j < MAX_LOCK_CASE; ++j) { switch (lockInfo->Type[j]) { // check key item (many fit cases can be) case LOCK_KEY_ITEM: if (lockInfo->Index[j] && _CastItem && _CastItem->GetEntry() == lockInfo->Index[j]) return SPELL_CAST_OK; reqKey = true; break; // check key skill (only single first fit case can be) case LOCK_KEY_SKILL: { reqKey = true; // wrong locktype, skip if (uint32(m_spellInfo->Effects[effIndex].MiscValue) != lockInfo->Index[j]) continue; skillId = SkillByLockType(LockType(lockInfo->Index[j])); if (skillId != SKILL_NONE) { reqSkillValue = lockInfo->Skill[j]; // castitem check: rogue using skeleton keys. the skill values should not be added in this case. skillValue = _CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ? 0 : m_caster->ToPlayer()->GetSkillValue(skillId); // skill bonus provided by casting spell (mostly item spells) // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) if (m_spellInfo->Effects[effIndex].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET || m_spellInfo->Effects[effIndex].TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET) skillValue += uint32(CalculateDamage(effIndex, NULL)); if (skillValue < reqSkillValue) return SPELL_FAILED_LOW_CASTLEVEL; } return SPELL_CAST_OK; } } } if (reqKey) return SPELL_FAILED_BAD_TARGETS; return SPELL_CAST_OK; } void Spell::SetSpellValue(SpellValueMod mod, int32 value) { switch (mod) { case SPELLVALUE_BASE_POINT0: m_spellValue->EffectBasePoints[0] = m_spellInfo->Effects[EFFECT_0].CalcBaseValue(value); break; case SPELLVALUE_BASE_POINT1: m_spellValue->EffectBasePoints[1] = m_spellInfo->Effects[EFFECT_1].CalcBaseValue(value); break; case SPELLVALUE_BASE_POINT2: m_spellValue->EffectBasePoints[2] = m_spellInfo->Effects[EFFECT_2].CalcBaseValue(value); break; case SPELLVALUE_RADIUS_MOD: m_spellValue->RadiusMod = (float)value / 10000; break; case SPELLVALUE_MAX_TARGETS: m_spellValue->MaxAffectedTargets = (uint32)value; break; case SPELLVALUE_AURA_STACK: m_spellValue->AuraStackAmount = uint8(value); break; } } void Spell::PrepareTargetProcessing() { CheckEffectExecuteData(); } void Spell::FinishTargetProcessing() { SendLogExecute(); } void Spell::InitEffectExecuteData(uint8 effIndex) { ASSERT(effIndex < MAX_SPELL_EFFECTS); if (!m_effectExecuteData[effIndex]) { m_effectExecuteData[effIndex] = new ByteBuffer(0x20); // first dword - target counter *m_effectExecuteData[effIndex] << uint32(1); } else { // increase target counter by one uint32 count = (*m_effectExecuteData[effIndex]).read<uint32>(0); (*m_effectExecuteData[effIndex]).put<uint32>(0, ++count); } } void Spell::CleanupEffectExecuteData() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) m_effectExecuteData[i] = NULL; } void Spell::CheckEffectExecuteData() { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) ASSERT(!m_effectExecuteData[i]); } void Spell::LoadScripts() { sScriptMgr->CreateSpellScripts(m_spellInfo->Id, m_loadedScripts); for (std::list<SpellScript*>::iterator itr = m_loadedScripts.begin(); itr != m_loadedScripts.end() ;) { if (!(*itr)->_Load(this)) { std::list<SpellScript*>::iterator bitr = itr; ++itr; m_loadedScripts.erase(bitr); continue; } sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::LoadScripts: Script `%s` for spell `%u` is loaded now", (*itr)->_GetScriptName()->c_str(), m_spellInfo->Id); (*itr)->Register(); ++itr; } } void Spell::CallScriptBeforeCastHandlers() { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_CAST); std::list<SpellScript::CastHandler>::iterator hookItrEnd = (*scritr)->BeforeCast.end(), hookItr = (*scritr)->BeforeCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnCastHandlers() { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_CAST); std::list<SpellScript::CastHandler>::iterator hookItrEnd = (*scritr)->OnCast.end(), hookItr = (*scritr)->OnCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptAfterCastHandlers() { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_CAST); std::list<SpellScript::CastHandler>::iterator hookItrEnd = (*scritr)->AfterCast.end(), hookItr = (*scritr)->AfterCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } SpellCastResult Spell::CallScriptCheckCastHandlers() { SpellCastResult retVal = SPELL_CAST_OK; for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CHECK_CAST); std::list<SpellScript::CheckCastHandler>::iterator hookItrEnd = (*scritr)->OnCheckCast.end(), hookItr = (*scritr)->OnCheckCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) { SpellCastResult tempResult = (*hookItr).Call(*scritr); if (retVal == SPELL_CAST_OK) retVal = tempResult; } (*scritr)->_FinishScriptCall(); } return retVal; } void Spell::PrepareScriptHitHandlers() { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) (*scritr)->_InitHit(); } bool Spell::CallScriptEffectHandlers(SpellEffIndex effIndex, SpellEffectHandleMode mode) { // execute script effect handler hooks and check if effects was prevented bool preventDefault = false; for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { std::list<SpellScript::EffectHandler>::iterator effItr, effEndItr; SpellScriptHookType hookType; switch (mode) { case SPELL_EFFECT_HANDLE_LAUNCH: effItr = (*scritr)->OnEffectLaunch.begin(); effEndItr = (*scritr)->OnEffectLaunch.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH; break; case SPELL_EFFECT_HANDLE_LAUNCH_TARGET: effItr = (*scritr)->OnEffectLaunchTarget.begin(); effEndItr = (*scritr)->OnEffectLaunchTarget.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH_TARGET; break; case SPELL_EFFECT_HANDLE_HIT: effItr = (*scritr)->OnEffectHit.begin(); effEndItr = (*scritr)->OnEffectHit.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT; break; case SPELL_EFFECT_HANDLE_HIT_TARGET: effItr = (*scritr)->OnEffectHitTarget.begin(); effEndItr = (*scritr)->OnEffectHitTarget.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT_TARGET; break; default: ASSERT(false); return false; } (*scritr)->_PrepareScriptCall(hookType); for (; effItr != effEndItr; ++effItr) // effect execution can be prevented if (!(*scritr)->_IsEffectPrevented(effIndex) && (*effItr).IsEffectAffected(m_spellInfo, effIndex)) (*effItr).Call(*scritr, effIndex); if (!preventDefault) preventDefault = (*scritr)->_IsDefaultEffectPrevented(effIndex); (*scritr)->_FinishScriptCall(); } return preventDefault; } void Spell::CallScriptBeforeHitHandlers() { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_HIT); std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->BeforeHit.end(), hookItr = (*scritr)->BeforeHit.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnHitHandlers() { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_HIT); std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->OnHit.end(), hookItr = (*scritr)->OnHit.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptAfterHitHandlers() { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_HIT); std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->AfterHit.end(), hookItr = (*scritr)->AfterHit.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptObjectAreaTargetSelectHandlers(std::list<WorldObject*>& targets, SpellEffIndex effIndex) { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_AREA_TARGET_SELECT); std::list<SpellScript::ObjectAreaTargetSelectHandler>::iterator hookItrEnd = (*scritr)->OnObjectAreaTargetSelect.end(), hookItr = (*scritr)->OnObjectAreaTargetSelect.begin(); for (; hookItr != hookItrEnd; ++hookItr) if ((*hookItr).IsEffectAffected(m_spellInfo, effIndex)) (*hookItr).Call(*scritr, targets); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptObjectTargetSelectHandlers(WorldObject*& target, SpellEffIndex effIndex) { for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_TARGET_SELECT); std::list<SpellScript::ObjectTargetSelectHandler>::iterator hookItrEnd = (*scritr)->OnObjectTargetSelect.end(), hookItr = (*scritr)->OnObjectTargetSelect.begin(); for (; hookItr != hookItrEnd; ++hookItr) if ((*hookItr).IsEffectAffected(m_spellInfo, effIndex)) (*hookItr).Call(*scritr, target); (*scritr)->_FinishScriptCall(); } } bool Spell::CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* spellInfo) const { bool only_on_dummy = (spellInfo && (spellInfo->AttributesEx4 & SPELL_ATTR4_PROC_ONLY_ON_DUMMY)); // If triggered spell has SPELL_ATTR4_PROC_ONLY_ON_DUMMY then it can only proc on a casted spell with SPELL_EFFECT_DUMMY // If triggered spell doesn't have SPELL_ATTR4_PROC_ONLY_ON_DUMMY then it can NOT proc on SPELL_EFFECT_DUMMY (needs confirmation) for (uint8 i = 0;i < MAX_SPELL_EFFECTS; ++i) { if ((effMask & (1 << i)) && (only_on_dummy == (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_DUMMY))) return true; } return false; } void Spell::PrepareTriggersExecutedOnHit() { // todo: move this to scripts if (m_spellInfo->SpellFamilyName) { SpellInfo const* excludeCasterSpellInfo = sSpellMgr->GetSpellInfo(m_spellInfo->ExcludeCasterAuraSpell); if (excludeCasterSpellInfo && !excludeCasterSpellInfo->IsPositive()) m_preCastSpell = m_spellInfo->ExcludeCasterAuraSpell; SpellInfo const* excludeTargetSpellInfo = sSpellMgr->GetSpellInfo(m_spellInfo->ExcludeTargetAuraSpell); if (excludeTargetSpellInfo && !excludeTargetSpellInfo->IsPositive()) m_preCastSpell = m_spellInfo->ExcludeTargetAuraSpell; } // todo: move this to scripts switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages m_preCastSpell = 11196; // Recently Bandaged break; } case SPELLFAMILY_MAGE: { // Permafrost if (m_spellInfo->SpellFamilyFlags[1] & 0x00001000 || m_spellInfo->SpellFamilyFlags[0] & 0x00100220) m_preCastSpell = 68391; break; } } // handle SPELL_AURA_ADD_TARGET_TRIGGER auras: // save auras which were present on spell caster on cast, to prevent triggered auras from affecting caster // and to correctly calculate proc chance when combopoints are present Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER); for (Unit::AuraEffectList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i) { if (!(*i)->IsAffectedOnSpell(m_spellInfo)) continue; SpellInfo const* auraSpellInfo = (*i)->GetSpellInfo(); uint32 auraSpellIdx = (*i)->GetEffIndex(); if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(auraSpellInfo->Effects[auraSpellIdx].TriggerSpell)) { // calculate the chance using spell base amount, because aura amount is not updated on combo-points change // this possibly needs fixing int32 auraBaseAmount = (*i)->GetBaseAmount(); int32 chance = m_caster->CalculateSpellDamage(NULL, auraSpellInfo, auraSpellIdx, &auraBaseAmount); // proc chance is stored in effect amount m_hitTriggerSpells.push_back(std::make_pair(spellInfo, chance * (*i)->GetBase()->GetStackAmount())); } } } // Global cooldowns management enum GCDLimits { MIN_GCD = 1000, MAX_GCD = 1500 }; bool Spell::HasGlobalCooldown() const { // Only player or controlled units have global cooldown if (m_caster->GetCharmInfo()) return m_caster->GetCharmInfo()->GetGlobalCooldownMgr().HasGlobalCooldown(m_spellInfo); else if (m_caster->GetTypeId() == TYPEID_PLAYER) return m_caster->ToPlayer()->GetGlobalCooldownMgr().HasGlobalCooldown(m_spellInfo); else return false; } void Spell::TriggerGlobalCooldown() { int32 gcd = m_spellInfo->StartRecoveryTime; if (!gcd) return; // Global cooldown can't leave range 1..1.5 secs // There are some spells (mostly not casted directly by player) that have < 1 sec and > 1.5 sec global cooldowns // but as tests show are not affected by any spell mods. if (m_spellInfo->StartRecoveryTime >= MIN_GCD && m_spellInfo->StartRecoveryTime <= MAX_GCD) { // gcd modifier auras are applied only to own spells and only players have such mods if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this); // Apply haste rating gcd = int32(float(gcd) * m_caster->GetFloatValue(UNIT_MOD_CAST_SPEED)); if (gcd < MIN_GCD) gcd = MIN_GCD; else if (gcd > MAX_GCD) gcd = MAX_GCD; } // Only players or controlled units have global cooldown if (m_caster->GetCharmInfo()) m_caster->GetCharmInfo()->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd); else if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd); } void Spell::CancelGlobalCooldown() { if (!m_spellInfo->StartRecoveryTime) return; // Cancel global cooldown when interrupting current cast if (m_caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) != this) return; // Only players or controlled units have global cooldown if (m_caster->GetCharmInfo()) m_caster->GetCharmInfo()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo); else if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo); } namespace SkyFire { WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) : _caster(caster), _referer(referer), _spellInfo(spellInfo), _targetSelectionType(selectionType), _condList(condList) { if (condList) _condSrcInfo = new ConditionSourceInfo(NULL, caster); else _condSrcInfo = NULL; } WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck() { if (_condSrcInfo) delete _condSrcInfo; } bool WorldObjectSpellTargetCheck::operator()(WorldObject* target) { if (_spellInfo->CheckTarget(_caster, target, true) != SPELL_CAST_OK) return false; Unit* unitTarget = target->ToUnit(); if (Corpse* corpseTarget = target->ToCorpse()) { // use ofter for party/assistance checks if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) unitTarget = owner; else return false; } if (unitTarget) { switch (_targetSelectionType) { case TARGET_CHECK_ENEMY: if (unitTarget->isTotem()) return false; if (!_caster->_IsValidAttackTarget(unitTarget, _spellInfo)) return false; break; case TARGET_CHECK_ALLY: if (unitTarget->isTotem()) return false; if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) return false; break; case TARGET_CHECK_PARTY: if (unitTarget->isTotem()) return false; if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) return false; if (!_referer->IsInPartyWith(unitTarget)) return false; break; case TARGET_CHECK_RAID_CLASS: if (_referer->getClass() != unitTarget->getClass()) return false; // nobreak; case TARGET_CHECK_RAID: if (unitTarget->isTotem()) return false; if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) return false; if (!_referer->IsInRaidWith(unitTarget)) return false; break; default: break; } } if (!_condSrcInfo) return true; _condSrcInfo->mConditionTargets[0] = target; return sConditionMgr->IsObjectMeetToConditions(*_condSrcInfo, *_condList); } WorldObjectSpellNearbyTargetCheck::WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) : WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(caster) { } bool WorldObjectSpellNearbyTargetCheck::operator()(WorldObject* target) { float dist = target->GetDistance(*_position); if (dist < _range && WorldObjectSpellTargetCheck::operator ()(target)) { _range = dist; return true; } return false; } WorldObjectSpellAreaTargetCheck::WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster, Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) : WorldObjectSpellTargetCheck(caster, referer, spellInfo, selectionType, condList), _range(range), _position(position) { } bool WorldObjectSpellAreaTargetCheck::operator()(WorldObject* target) { if (!target->IsWithinDist3d(_position, _range) && !(target->ToGameObject() && target->ToGameObject()->IsInRange(_position->GetPositionX(), _position->GetPositionY(), _position->GetPositionZ(), _range))) return false; return WorldObjectSpellTargetCheck::operator ()(target); } WorldObjectSpellConeTargetCheck::WorldObjectSpellConeTargetCheck(float coneAngle, float range, Unit* caster, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) : WorldObjectSpellAreaTargetCheck(range, caster, caster, caster, spellInfo, selectionType, condList), _coneAngle(coneAngle) { } bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target) { if (_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_BACK) { if (!_caster->isInBack(target, _coneAngle)) return false; } else if (_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_LINE) { if (!_caster->HasInLine(target, _caster->GetObjectSize())) return false; } else { if (!_caster->isInFront(target, _coneAngle)) return false; } return WorldObjectSpellAreaTargetCheck::operator ()(target); } WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, SpellInfo const* spellInfo) : WorldObjectSpellAreaTargetCheck(range, position, caster, caster, spellInfo, TARGET_CHECK_DEFAULT, NULL) { } bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target) { // return all targets on missile trajectory (0 - size of a missile) if (!_caster->HasInLine(target, 0)) return false; return WorldObjectSpellAreaTargetCheck::operator ()(target); } } //namespace SkyFire
412
0.949739
1
0.949739
game-dev
MEDIA
0.962919
game-dev
0.905628
1
0.905628
jwvhewitt/gearhead-caramel
18,933
game/content/ghplots/wmw_occupation.py
import random from game import content, services, teams, ghdialogue import gears import pbge from game.content import gharchitecture, plotutility, dungeonmaker, ghwaypoints, adventureseed, ghcutscene, ghterrain, \ ghchallenges, ghrooms from game.ghdialogue import context from pbge.dialogue import Offer, ContextTag from pbge.plots import Plot, Rumor, PlotState from pbge import stories, quests from pbge.memos import Memo from . import missionbuilder, rwme_objectives, campfeatures, ghquests from pbge.challenges import Challenge, AutoOffer from .shops_plus import get_building import collections # ***************************** # *** OCCUPATION PLOTS *** # ***************************** # Required Elements: # METRO, METROSCENE, WORLD_MAP_WAR # OCCUPIER: The faction that has occupied this metro area. # RIVAL_FACTIONS: A list of other factions that also want this metro area. May be falsy. # ORIGINAL_FACTION: The faction that originally controlled this area. May be "None". # RESISTANCE_FACTION: A faction that may attempt to oust the occupier. May be the same as ORIGINAL_FACTION. Optional. OCCUPIER = "OCCUPIER" RIVAL_FACTIONS = "RIVAL_FACTIONS" ORIGINAL_FACTION = "ORIGINAL_FACTION" RESISTANCE_FACTION = "RESISTANCE_FACTION" class OccupationPlot(Plot): # Subclassing an Occupation Plot. The only change from regular plots is a property confirming that this is an # OccupationPlot. Why? Because only one OccupationPlot can be active in a city at once; if there are any more, # they get deleted. IS_OCCUPATION_PLOT = True # During a world map war, different factions may have different effects on the territories they conquer. This may give # special opportunities to the player character, depending on which side of the conflict the PC is working for (if any). TEST_WAR_PLOT = "TEST_WAR_PLOT" WMWO_DEFENDER = "WMWO_DEFENDER" # The faction will attempt to defend this location. # Plots may involve shoring up defenses, evacuating civilians, and repairing damage done during the attack. # This plot type will usually be associated with the original owner of a given territory, but not necessarily. class OccupationFortify(Plot): LABEL = WMWO_DEFENDER scope = "METRO" active = True IS_OCCUPATION_PLOT = True def custom_init(self, nart): # The invading faction is going to fortify their position. self.expiration = plotutility.RulingFactionExpiration(self.elements["METROSCENE"], self.elements[OCCUPIER]) if RESISTANCE_FACTION not in self.elements: candidates = self.elements.get(RIVAL_FACTIONS) if candidates: rival = random.choice(candidates) else: rival = gears.factions.Circle( nart.camp, parent_faction=self.elements.get(ORIGINAL_FACTION) ) self.elements[RESISTANCE_FACTION] = rival oc1 = quests.QuestOutcome( ghquests.FortifyVerb, ghquests.default_player_can_do_outcome, win_effect=self._occupier_wins, loss_effect=self._occupier_loses, lore=[ quests.QuestLore( ghquests.LORECAT_OUTCOME, texts={ quests.TEXT_LORE_HINT: "{OCCUPIER} plans to hold onto {METROSCENE}".format(**self.elements), quests.TEXT_LORE_INFO: "{OCCUPIER} is working to improve {METROSCENE}'s defenses".format(**self.elements), quests.TEXT_LORE_TOPIC: "the state of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that {OCCUPIER} is working to consolidate its position in {METROSCENE}.".format(**self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{OCCUPIER}'s plans".format(**self.elements), quests.TEXT_LORE_MEMO: "{OCCUPIER} is fortifying their position in {METROSCENE}.".format(**self.elements), }, involvement=ghchallenges.InvolvedMetroNoEnemyToFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), priority=True ), ], prioritize_lore=True, o_elements={ ghquests.OE_ALLYFACTION: self.elements[OCCUPIER], ghquests.OE_ENEMYFACTION: self.elements[RESISTANCE_FACTION], ghquests.OE_OBJECT: self.elements["METROSCENE"], } ) oc2 = quests.QuestOutcome( ghquests.ExpelVerb, ghquests.default_player_can_do_outcome, win_effect=self._occupier_loses, loss_effect=self._occupier_wins, lore=[ quests.QuestLore( ghquests.LORECAT_OUTCOME, texts={ quests.TEXT_LORE_HINT: "{OCCUPIER} is not entirely welcome here".format(**self.elements), quests.TEXT_LORE_INFO: "{RESISTANCE_FACTION} seek to force {OCCUPIER} out of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_TOPIC: "{OCCUPIER}'s occupation of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that {RESISTANCE_FACTION} plans to drive {OCCUPIER} from {METROSCENE}.".format(**self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{OCCUPIER}'s occupation of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_MEMO: "{RESISTANCE_FACTION} opposes {OCCUPIER}'s occupation of {METROSCENE}.".format(**self.elements), }, involvement=ghchallenges.InvolvedMetroNoFriendToFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), priority=True ) ], prioritize_lore=False, o_elements={ ghquests.OE_ALLYFACTION: self.elements[RESISTANCE_FACTION], ghquests.OE_ENEMYFACTION: self.elements[OCCUPIER] } ) myquest = self.register_element(quests.QUEST_ELEMENT_ID, quests.Quest( "{OCCUPIER} is attempting to fortify its position in {METROSCENE}.".format(**self.elements), outcomes=(oc1, oc2), end_on_loss=True )) myquest.build(nart, self) self.add_sub_plot(nart, "ENSURE_LOCAL_OPERATIVES", elements={"FACTION": self.elements["OCCUPIER"]}) return True def _occupier_wins(self, camp: gears.GearHeadCampaign): pbge.alert("The occupier wins!") def _occupier_loses(self, camp: gears.GearHeadCampaign): pbge.alert("The resistance wins!") WMWO_IRON_FIST = "WMWO_IRON_FIST" # The faction will impose totalitarian rule on this location. # Plots may involve forced labor, rounding up dissidents, and propaganda campaigns. This plot type will usually be # associated with an invading dictatorship, but not necessarily. class OccupationCrushDissent(Plot): LABEL = WMWO_IRON_FIST scope = "METRO" active = True IS_OCCUPATION_PLOT = True def custom_init(self, nart): # The invading faction is going to try and crush dissent in this region. The locals are going to try to resist # this as well as they can. self.expiration = plotutility.RulingFactionExpiration(self.elements["METROSCENE"], self.elements["OCCUPIER"]) if RESISTANCE_FACTION not in self.elements: self.elements[RESISTANCE_FACTION] = gears.factions.Circle( nart.camp, parent_faction=self.elements.get(ORIGINAL_FACTION) ) oc1 = quests.QuestOutcome( ghquests.RepressVerb, ghquests.default_player_can_do_outcome, win_effect=self._occupier_wins, loss_effect=self._resistance_wins, lore=[ quests.QuestLore( ghquests.LORECAT_OUTCOME, texts={ quests.TEXT_LORE_HINT: "{OCCUPIER} will bring {METROSCENE} under our complete control".format(**self.elements), quests.TEXT_LORE_INFO: "{RESISTANCE_FACTION} are dissidents who resist {OCCUPIER} and must be crushed".format(**self.elements), quests.TEXT_LORE_TOPIC: "the state of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that {RESISTANCE_FACTION} is working against {OCCUPIER} in {METROSCENE}.".format(**self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{RESISTANCE_FACTION}'s rebellion".format(**self.elements), quests.TEXT_LORE_MEMO: "{OCCUPIER} is attempting to crush all dissent in {METROSCENE}.".format(**self.elements), }, involvement = ghchallenges.InvolvedMetroFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), priority=True ), quests.QuestLore( ghquests.LORECAT_MOTIVE, texts={ quests.TEXT_LORE_HINT: "{RESISTANCE_FACTION} is plotting a rebellion".format( **self.elements), quests.TEXT_LORE_INFO: "{OCCUPIER}'s control of {METROSCENE} will never be complete as long as {RESISTANCE_FACTION} exists".format( **self.elements), quests.TEXT_LORE_TOPIC: "the {RESISTANCE_FACTION} resistance".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that {RESISTANCE_FACTION} has been trying to drive {OCCUPIER} from {METROSCENE}.".format( **self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{OCCUPIER}'s control of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_MEMO: "{RESISTANCE_FACTION} is attempting to drive {OCCUPIER} out of {METROSCENE}.".format( **self.elements), ghquests.L_MOTIVE_CONFESSION: "{RESISTANCE_FACTION} will free {METROSCENE} from {OCCUPIER}".format( **self.elements), }, involvement=ghchallenges.InvolvedMetroFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), tags=(ghquests.LORETAG_ENEMY, ghquests.LORETAG_PRIMARY), ) ], prioritize_lore=True, o_elements={ ghquests.OE_ALLYFACTION: self.elements[OCCUPIER], ghquests.OE_ENEMYFACTION: self.elements[RESISTANCE_FACTION] } ) oc2 = quests.QuestOutcome( ghquests.ExpelVerb, ghquests.default_player_can_do_outcome, win_effect=self._resistance_wins, loss_effect=self._occupier_wins, lore=[ quests.QuestLore( ghquests.LORECAT_OUTCOME, texts={ quests.TEXT_LORE_HINT: "life under {OCCUPIER} has been unbearable".format(**self.elements), quests.TEXT_LORE_INFO: "a resistance has formed to get rid of {OCCUPIER}".format(**self.elements), quests.TEXT_LORE_TOPIC: "{OCCUPIER}'s occupation of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that the people of {METROSCENE} must unite to oust {OCCUPIER}.".format(**self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{OCCUPIER}'s occupation of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_MEMO: "There is a resistance opposing {OCCUPIER}'s occupation of {METROSCENE}.".format(**self.elements), }, involvement=ghchallenges.InvolvedMetroNoFriendToFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), priority=True ), quests.QuestLore( ghquests.LORECAT_MOTIVE, texts={ quests.TEXT_LORE_HINT: "{RESISTANCE_FACTION} is our only hope to stop {OCCUPIER}".format(**self.elements), quests.TEXT_LORE_INFO: "no-one is safe as long as {OCCUPIER} occupies {METROSCENE}; {RESISTANCE_FACTION} is leading the resistance".format( **self.elements), quests.TEXT_LORE_TOPIC: "the {OCCUPIER} occupation".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that {OCCUPIER} has been eliminating all resistance in {METROSCENE}.".format( **self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{RESISTANCE_FACTION}'s rebellion".format(**self.elements), quests.TEXT_LORE_MEMO: "{OCCUPIER} is attempting to crush all resistance to their occupation of {METROSCENE}.".format( **self.elements), ghquests.L_MOTIVE_CONFESSION: "{OCCUPIER} will destroy any who defy our rulership of {METROSCENE}".format( **self.elements), }, involvement=ghchallenges.InvolvedMetroNoFriendToFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), tags=(ghquests.LORETAG_ENEMY, ghquests.LORETAG_PRIMARY), ) ], prioritize_lore=False, o_elements={ ghquests.OE_ALLYFACTION: self.elements[RESISTANCE_FACTION], ghquests.OE_ENEMYFACTION: self.elements[OCCUPIER] } ) myquest = self.register_element(quests.QUEST_ELEMENT_ID, quests.Quest( "{OCCUPIER} is attempting to crush all dissent in {METROSCENE}.".format(**self.elements), outcomes=(oc1, oc2), end_on_loss=True )) myquest.build(nart, self) self.add_sub_plot(nart, "ENSURE_LOCAL_OPERATIVES", elements={"FACTION": self.elements["OCCUPIER"]}) return True def _occupier_wins(self, camp: gears.GearHeadCampaign): pbge.alert("The occupier wins!") def _resistance_wins(self, camp: gears.GearHeadCampaign): pbge.alert("The resistance wins!") WMWO_MARTIAL_LAW = "WMWO_MARTIAL_LAW" # The faction will attempt to impose law and order on the territory. # Plots may involve capturing fugitives, enforcing curfew, and dispersing riots. This plot will usually be associated # with either an invading force or a totalitarian force reasserting control over areas lost to rebellion or outside # influence. class OccupationRestoreOrder(Plot): LABEL = WMWO_MARTIAL_LAW scope = "METRO" active = True IS_OCCUPATION_PLOT = True def custom_init(self, nart): # The invading faction is going to fortify their position. self.expiration = plotutility.RulingFactionExpiration(self.elements["METROSCENE"], self.elements["OCCUPIER"]) if RESISTANCE_FACTION not in self.elements: candidates = self.elements.get(RIVAL_FACTIONS) if candidates: rival = random.choice(candidates) else: rival = gears.factions.Circle( nart.camp, parent_faction=self.elements.get(ORIGINAL_FACTION) ) self.elements[RESISTANCE_FACTION] = rival oc1 = quests.QuestOutcome( ghquests.FortifyVerb, ghquests.default_player_can_do_outcome, win_effect=self._occupier_wins, loss_effect=self._occupier_loses, lore=[ quests.QuestLore( ghquests.LORECAT_OUTCOME, texts={ quests.TEXT_LORE_HINT: "{OCCUPIER} must bring order to {METROSCENE}".format(**self.elements), quests.TEXT_LORE_INFO: "{RESISTANCE_FACTION} are dissidents who resist {OCCUPIER} and must be crushed".format(**self.elements), quests.TEXT_LORE_TOPIC: "the state of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that {RESISTANCE_FACTION} is working against {OCCUPIER} in {METROSCENE}.".format(**self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{RESISTANCE_FACTION}'s rebellion".format(**self.elements), quests.TEXT_LORE_MEMO: "{OCCUPIER} has placed {METROSCENE} under martial law.".format(**self.elements), }, involvement = ghchallenges.InvolvedMetroFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), priority=True ) ], prioritize_lore=True, o_elements={ ghquests.OE_ALLYFACTION: self.elements[OCCUPIER], ghquests.OE_ENEMYFACTION: self.elements[RESISTANCE_FACTION], } ) oc2 = quests.QuestOutcome( ghquests.ExpelVerb, ghquests.default_player_can_do_outcome, win_effect=self._occupier_loses, loss_effect=self._occupier_wins, lore=[ quests.QuestLore( ghquests.LORECAT_OUTCOME, texts={ quests.TEXT_LORE_HINT: "life under {OCCUPIER} has been unbearable".format(**self.elements), quests.TEXT_LORE_INFO: "a resistance has formed to get rid of {OCCUPIER}".format(**self.elements), quests.TEXT_LORE_TOPIC: "{OCCUPIER}'s occupation of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_SELFDISCOVERY: "You learned that there is a resistance dedicated to ousting {OCCUPIER} from {METROSCENE}.".format(**self.elements), quests.TEXT_LORE_TARGET_TOPIC: "{OCCUPIER}'s occupation of {METROSCENE}".format(**self.elements), quests.TEXT_LORE_MEMO: "There is a resistance opposing {OCCUPIER}'s occupation of {METROSCENE}.".format(**self.elements), }, involvement=ghchallenges.InvolvedMetroNoFriendToFactionNPCs( self.elements["METROSCENE"], self.elements["OCCUPIER"] ), priority=True ) ], prioritize_lore=False, o_elements={ ghquests.OE_ALLYFACTION: self.elements[RESISTANCE_FACTION], ghquests.OE_ENEMYFACTION: self.elements[OCCUPIER], } ) myquest = self.register_element(quests.QUEST_ELEMENT_ID, quests.Quest( "{OCCUPIER} has imposed martial law in {METROSCENE}.".format(**self.elements), outcomes=(oc1, oc2), end_on_loss=True )) myquest.build(nart, self) self.add_sub_plot(nart, "ENSURE_LOCAL_OPERATIVES", elements={"FACTION": self.elements["OCCUPIER"]}) return True def _occupier_wins(self, camp: gears.GearHeadCampaign): pbge.alert("The occupier wins!") def _occupier_loses(self, camp: gears.GearHeadCampaign): pbge.alert("The resistance wins!")
412
0.788013
1
0.788013
game-dev
MEDIA
0.969564
game-dev
0.910363
1
0.910363
MincraftEinstein/SubtleEffects
1,200
fabric/src/main/java/einstein/subtle_effects/mixin/client/FabricMultiPlayerGameModeMixin.java
package einstein.subtle_effects.mixin.client; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Local; import einstein.subtle_effects.util.ParticleSpawnUtil; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @Mixin(MultiPlayerGameMode.class) public class FabricMultiPlayerGameModeMixin { @WrapOperation(method = "destroyBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;I)Z")) private boolean destroyBlock(Level level, BlockPos pos, BlockState newState, int flags, Operation<Boolean> original, @Local BlockState state) { boolean success = original.call(level, pos, newState, flags); ParticleSpawnUtil.spawnUnderwaterBlockBreakBubbles(level, pos, state, success); return success; } }
412
0.881875
1
0.881875
game-dev
MEDIA
0.998453
game-dev
0.874056
1
0.874056
dtrajko/MoravaEngine
2,669
MoravaEngine/src/H2M/Hazel-ScriptCore/src/Hazel/Math/Matrix4.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Hazel { [StructLayout(LayoutKind.Explicit)] public struct Matrix4 { [FieldOffset( 0)] public float D00; [FieldOffset( 4)] public float D10; [FieldOffset( 8)] public float D20; [FieldOffset(12)] public float D30; [FieldOffset(16)] public float D01; [FieldOffset(20)] public float D11; [FieldOffset(24)] public float D21; [FieldOffset(28)] public float D31; [FieldOffset(32)] public float D02; [FieldOffset(36)] public float D12; [FieldOffset(40)] public float D22; [FieldOffset(44)] public float D32; [FieldOffset(48)] public float D03; [FieldOffset(52)] public float D13; [FieldOffset(56)] public float D23; [FieldOffset(60)] public float D33; public Matrix4(float value) { D00 = value; D10 = 0.0f; D20 = 0.0f; D30 = 0.0f; D01 = 0.0f; D11 = value; D21 = 0.0f; D31 = 0.0f; D02 = 0.0f; D12 = 0.0f; D22 = value; D32 = 0.0f; D03 = 0.0f; D13 = 0.0f; D23 = 0.0f; D33 = value; } public Vector3 Translation { get { return new Vector3(D03, D13, D23); } set { D03 = value.X; D13 = value.Y; D23 = value.Z; } } public static Matrix4 Translate(Vector3 translation) { Matrix4 result = new Matrix4(1.0f); result.D03 = translation.X; result.D13 = translation.Y; result.D23 = translation.Z; return result; } public static Matrix4 Scale(Vector3 scale) { Matrix4 result = new Matrix4(1.0f); result.D00 = scale.X; result.D11 = scale.Y; result.D22 = scale.Z; return result; } public static Matrix4 Scale(float scale) { Matrix4 result = new Matrix4(1.0f); result.D00 = scale; result.D11 = scale; result.D22 = scale; return result; } public void DebugPrint() { Console.WriteLine("{0:0.00} {1:0.00} {2:0.00} {3:0.00}", D00, D10, D20, D30); Console.WriteLine("{0:0.00} {1:0.00} {2:0.00} {3:0.00}", D01, D11, D21, D31); Console.WriteLine("{0:0.00} {1:0.00} {2:0.00} {3:0.00}", D02, D12, D22, D32); Console.WriteLine("{0:0.00} {1:0.00} {2:0.00} {3:0.00}", D03, D13, D23, D33); } } }
412
0.819954
1
0.819954
game-dev
MEDIA
0.847312
game-dev
0.761623
1
0.761623
rickomax/psxprev
215,952
Forms/PreviewForm.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Printing; using System.IO; using System.Reflection; using System.Timers; using System.Windows.Forms; using Manina.Windows.Forms; using OpenTK; using OpenTK.Graphics; using PSXPrev.Common; using PSXPrev.Common.Animator; using PSXPrev.Common.Exporters; using PSXPrev.Common.Renderer; using PSXPrev.Forms; using PSXPrev.Forms.Dialogs; using PSXPrev.Forms.Utils; using Timer = System.Timers.Timer; namespace PSXPrev.Forms { public partial class PreviewForm : Form { private const float MouseSensivity = 0.0035f; private const double AnimationProgressPrecision = 200d; private const int CheckAllNodesWarningCount = 100; private const double DefaultElapsedTime = 1d / 60d; // 1 frame (60FPS) private const double MaxElapsedTime = 10d / 60d; // 10 frames (60FPS) private const bool IncludeAnimationFrameTreeViewNodes = false; private const int ModelsTabIndex = 0; private const int TexturesTabIndex = 1; private const int VRAMTabIndex = 2; private const int AnimationsTabIndex = 3; private readonly List<RootEntity> _rootEntities = new List<RootEntity>(); private readonly List<Texture> _textures = new List<Texture>(); private readonly List<Texture> _packedTextures = new List<Texture>(); private readonly List<Animation> _animations = new List<Animation>(); private readonly Scene _scene; private readonly VRAM _vram; private readonly AnimationBatch _animationBatch; private GLControl _glControl; private int _currentMultisampling; // Form timers private Timer _mainTimer; // Main timer used by all timed events private Stopwatch _mainWatch; // Watch to track elapsed time between main timer events private Stopwatch _fpsWatch; private bool _fixedTimer = false; // If true, then timer always updates with the same time delta // Timers that are updated during main timer Elapsed event private RefreshDelayTimer _animationProgressBarRefreshDelayTimer; private RefreshDelayTimer _modelPropertyGridRefreshDelayTimer; private RefreshDelayTimer _fpsLabelRefreshDelayTimer; private RefreshDelayTimer _scanProgressRefreshDelayTimer; private RefreshDelayTimer _scanPopulateRefreshDelayTimer; private float _fps = (float)(1d / DefaultElapsedTime); private int _trianglesDrawn; private int _meshesDrawn; private int _skinsDrawn; private double _fpsCalcElapsedSeconds; private int _fpsCalcElapsedFrames; // Scanning private readonly object _scanProgressLock = new object(); private Program.ScanProgressReport _scanProgressReport; private string _scanProgressMessage; private bool _drawAllToVRAMAfterScan; private List<RootEntity> _addedRootEntities = new List<RootEntity>(); private List<Texture> _addedTextures = new List<Texture>(); private List<Animation> _addedAnimations = new List<Animation>(); // Swap lists are used so that we don't need to allocate new lists every time we call ScanPopulateItems. private List<RootEntity> _addedRootEntitiesSwap = new List<RootEntity>(); private List<Texture> _addedTexturesSwap = new List<Texture>(); private List<Animation> _addedAnimationsSwap = new List<Animation>(); // Form state private bool _closing; private bool _inDialog; // Prevent timers from performing updates while true private bool _resizeLayoutSuspended; // True if we need to ResumeLayout during ResizeEnd event private object _cancelMenuCloseItemClickedSender; // Prevent closing menus on certain click events (like separators) private bool _busyChecking; // Checking or unchecking multiple tree view items, and events need to be delayed private string _baseWindowTitle; private Animation _curAnimation; private AnimationObject _curAnimationObject; private AnimationFrame _curAnimationFrame; private float _animationSpeed = 1f; private bool _inAnimationTab; private bool _playing; private int _lastMouseX; private int _lastMouseY; private Tuple<ModelEntity, Triangle> _selectedTriangle; private ModelEntity _selectedModelEntity; private RootEntity _selectedRootEntity; private EntitySelectionSource _selectionSource; private int _vramSelectedPage = -1; // Used because combo box SelectedIndex can be -1 while typing. private TexturesListViewItemAdaptor _texturesListViewAdaptor; private Bitmap _maskColorBitmap; private Bitmap _ambientColorBitmap; private Bitmap _backgroundColorBitmap; private Bitmap _wireframeVerticesColorBitmap; private int _clutIndex; private bool _autoDrawModelTextures; private bool _autoPackModelTextures; private bool _autoSelectAnimationModel; private bool _autoPlayAnimations; private SubModelVisibility _subModelVisibility; private bool _autoFocusOnRootModel; private bool _autoFocusOnSubModel; private bool _autoFocusIncludeWholeModel; private bool _autoFocusIncludeCheckedModels; private bool _autoFocusResetCameraRotation; private EntitySelectionMode _modelSelectionMode; private bool _showSkeleton; private uint? _fallbackTextureID; private GizmoType _gizmoType; private GizmoId _hoveredGizmo; private GizmoId _selectedGizmo; private Vector3 _gizmoAxis; private Vector3 _gizmoOrigin; private Vector3 _gizmoInitialTranslation; private Quaternion _gizmoInitialRotation; private Vector3 _gizmoInitialScale; private float _gizmoRotateAngle; private Vector2 _gizmoRotateStartDirection; private float _gizmoScaleStartDistance; public PreviewForm() { _scene = new Scene(); _vram = new VRAM(_scene); _animationBatch = new AnimationBatch(); _texturesListViewAdaptor = new TexturesListViewItemAdaptor(this); // It's observed in GLControl's source that this is called with PreferNative in the // control's constructor. Changing this from PreferDefault is needed to prevent SDL2 // from creating the graphics context for certain users, which can throw an AccessViolationException. Toolkit.Init(new ToolkitOptions { Backend = PlatformBackend.PreferNative, }); InitializeComponent(); SetupControls(); } private bool Playing { get => _playing; set { if (_playing != value) { _playing = value; // Make sure we restart the animation if it was finished. if (!value && _animationBatch.IsFinished) { _animationBatch.Restart(); } // Refresh to make sure the button text updates quickly. animationPlayButton.Text = value ? "Pause Animation" : "Play Animation"; animationPlayButton.Refresh(); } } } private bool IsSceneTab { get { switch (menusTabControl.SelectedIndex) { case ModelsTabIndex: case AnimationsTabIndex: return true; default: return false; } } } private bool IsImageTab { get { switch (menusTabControl.SelectedIndex) { case TexturesTabIndex: case VRAMTabIndex: return true; default: return false; } } } private Control PrimaryControl { get { switch (menusTabControl.SelectedIndex) { case ModelsTabIndex: return scenePreviewer;//.GLControl; case TexturesTabIndex: return texturePreviewer; case VRAMTabIndex: return vramPreviewer; case AnimationsTabIndex: return animationPreviewer;//.GLControl; default: return null; } } } private bool IsControlDown => ModifierKeys.HasFlag(Keys.Control); private bool IsShiftDown => ModifierKeys.HasFlag(Keys.Shift); #region Scanning private void ScanPopulateItems() { // A-B swap between two lists, one used to populate items, and one used to hold items to be populated. lock (_scanProgressLock) { var rootEntitiesSwap = _addedRootEntities; _addedRootEntities = _addedRootEntitiesSwap; _addedRootEntitiesSwap = rootEntitiesSwap; var texturesSwap = _addedTextures; _addedTextures = _addedTexturesSwap; _addedTexturesSwap = texturesSwap; var animationsSwap = _addedAnimations; _addedAnimations = _addedAnimationsSwap; _addedAnimationsSwap = animationsSwap; } AddRootEntities(_addedRootEntitiesSwap); AddTextures(_addedTexturesSwap); AddAnimations(_addedAnimationsSwap); _addedRootEntitiesSwap.Clear(); _addedTexturesSwap.Clear(); _addedAnimationsSwap.Clear(); } private void ScanUpdated() { Program.ScanProgressReport p; string message; lock (_scanProgressLock) { p = _scanProgressReport; message = _scanProgressMessage; _scanProgressReport = null; _scanProgressMessage = null; } if (p == null) { return; } statusStrip1.SuspendLayout(); const int max = 100; // Avoid divide-by-zero when scanning 0 files, or a file that's 0 bytes in size. // Update major progress bar, default to 100% when zero files var totalFilesPercent = (p.TotalFiles > 0) ? ((double)p.CurrentFile / p.TotalFiles) : 1d; statusTotalFilesProgressBar.Maximum = max; statusTotalFilesProgressBar.SetValueSafe((int)(totalFilesPercent * max)); // Update minor progress bar, default to 0% when zero length var currentFilePercent = (p.CurrentLength > 0) ? ((double)p.CurrentPosition / p.CurrentLength) : 0d; statusCurrentFileProgressBar.Maximum = max; statusCurrentFileProgressBar.SetValueSafe((int)(currentFilePercent * max)); if (message != null) { statusMessageLabel.Text = message; } statusStrip1.ResumeLayout(); // Instantly update status bar at end of scan, since populating the rest of the views may be a little slow. if (p.State == Program.ScanProgressState.Finished) { // Vista introduced progress bar animation that slowly moves the bar. // We don't want that when finishing a scan, so force the value to instantly change. statusTotalFilesProgressBar.UpdateValueInstant(); statusCurrentFileProgressBar.UpdateValueInstant(); statusStrip1.Refresh(); } } private void ScanStarted() { pauseScanningToolStripMenuItem.Checked = false; pauseScanningToolStripMenuItem.Enabled = true; stopScanningToolStripMenuItem.Enabled = true; startScanToolStripMenuItem.Enabled = false; clearScanResultsToolStripMenuItem.Enabled = false; statusStrip1.SuspendLayout(); // Reset positions back to start, since they may not get updated right away. statusTotalFilesProgressBar.Maximum = 1; statusTotalFilesProgressBar.Value = 0; statusCurrentFileProgressBar.Maximum = 1; statusCurrentFileProgressBar.Value = 0; statusTotalFilesProgressBar.Visible = true; statusCurrentFileProgressBar.Visible = true; statusMessageLabel.Text = $"Scan Started"; statusStrip1.ResumeLayout(); statusStrip1.Refresh(); lock (_scanProgressLock) { _scanProgressReport = null; _scanProgressMessage = null; } _scanProgressRefreshDelayTimer.Restart(); _scanPopulateRefreshDelayTimer.Restart(); } private void ScanFinished() { _scanProgressRefreshDelayTimer.Reset(); _scanPopulateRefreshDelayTimer.Reset(); ScanUpdated(); lock (_scanProgressLock) { _scanProgressReport = null; _scanProgressMessage = null; } ScanPopulateItems(); SelectFirstEntity(); // Select something if the user hasn't already done so. if (_drawAllToVRAMAfterScan) { DrawTexturesToVRAM(_textures, _clutIndex); } pauseScanningToolStripMenuItem.Checked = false; pauseScanningToolStripMenuItem.Enabled = false; stopScanningToolStripMenuItem.Enabled = false; startScanToolStripMenuItem.Enabled = true; clearScanResultsToolStripMenuItem.Enabled = true; statusStrip1.SuspendLayout(); statusTotalFilesProgressBar.Visible = false; statusCurrentFileProgressBar.Visible = false; statusMessageLabel.Text = $"Models: {_rootEntities.Count}, Textures: {_textures.Count}, Animations: {_animations.Count}"; statusStrip1.ResumeLayout(); statusStrip1.Refresh(); if (_autoPackModelTextures) { // Ensure model is redrawn with packed textures applied. UpdateSelectedEntity(); } // Debugging: Quickly export models and animations on startup. /*if (_rootEntities.Count >= 1 && _animations.Count >= 1) { var options = new ExportModelOptions { Path = @"", Format = ExportModelOptions.GLTF2, SingleTexture = false, AttachLimbs = true, RedrawTextures = true, ExportAnimations = true, }; ExportModelsForm.Export(options, new[] { _rootEntities[0] }, new[] { _animations[0] }, _animationBatch); Close(); }*/ } private void OnScanProgressCallback(Program.ScanProgressReport p) { // WARNING: This function is not called on the UI thread! switch (p.State) { case Program.ScanProgressState.Started: // Instantly handle starting the scan. Invoke(new Action(ScanStarted)); break; case Program.ScanProgressState.Finished: // Instantly refresh the status bar while the scan finishes up. // Then instantly handle finishing the scan. lock (_scanProgressLock) { _scanProgressMessage = "Scan Finishing"; _scanProgressReport = p; } Invoke(new Action(ScanFinished)); break; case Program.ScanProgressState.Updated: // Prepare progress that will be updated in future main timer Elapsed events. lock (_scanProgressLock) { _scanProgressMessage = null; // Added items are reloaded infrequently. if (p.Result is RootEntity rootEntity) { _scanProgressMessage = $"Found {rootEntity.FormatName} Model with {rootEntity.ChildEntities.Length} objects"; _addedRootEntities.Add(rootEntity); } else if (p.Result is Texture texture) { _scanProgressMessage = $"Found {texture.FormatName} Texture {texture.Width}x{texture.Height} {texture.Bpp}bpp"; _addedTextures.Add(texture); } else if (p.Result is Animation animation) { _scanProgressMessage = $"Found {animation.FormatName} Animation with {animation.ObjectCount} objects and {animation.FrameCount} frames"; _addedAnimations.Add(animation); } // Progress bars and status message updates are handled frequently. _scanProgressReport = p; } break; } } #endregion #region Settings public void LoadDefaultSettings() { Settings.LoadDefaults(); ReadSettings(Settings.Instance); UpdateSelectedEntity(); } public void LoadSettings() { if (Settings.Load(false)) { ReadSettings(Settings.Instance); UpdateSelectedEntity(); } } public void SaveSettings() { WriteSettings(Settings.Instance); Settings.Instance.Save(); } public void ReadSettings(Settings settings) { if (!Program.IsScanning) { Program.Logger.ReadSettings(settings); } Program.ConsoleLogger.ReadSettings(settings); gridSnapUpDown.SetValueSafe((decimal)settings.GridSnap); angleSnapUpDown.SetValueSafe((decimal)settings.AngleSnap); scaleSnapUpDown.SetValueSafe((decimal)settings.ScaleSnap); cameraFOVUpDown.SetValueSafe((decimal)settings.CameraFOV); { // Prevent light rotation ray from showing up while reading settings. // This is re-assigned later in the function. _scene.ShowLightRotationRay = false; lightIntensityNumericUpDown.SetValueSafe((decimal)settings.LightIntensity); lightYawNumericUpDown.SetValueSafe((decimal)settings.LightYaw); lightPitchNumericUpDown.SetValueSafe((decimal)settings.LightPitch); enableLightToolStripMenuItem.Checked = settings.LightEnabled; } _scene.AmbientEnabled = settings.AmbientEnabled; enableTexturesToolStripMenuItem.Checked = settings.TexturesEnabled; enableVertexColorToolStripMenuItem.Checked = settings.VertexColorEnabled; enableSemiTransparencyToolStripMenuItem.Checked = settings.SemiTransparencyEnabled; forceDoubleSidedToolStripMenuItem.Checked = settings.ForceDoubleSided; autoAttachLimbsToolStripMenuItem.Checked = settings.AutoAttachLimbs; drawModeFacesToolStripMenuItem.Checked = settings.DrawFaces; drawModeWireframeToolStripMenuItem.Checked = settings.DrawWireframe; drawModeVerticesToolStripMenuItem.Checked = settings.DrawVertices; drawModeSolidWireframeVerticesToolStripMenuItem.Checked = settings.DrawSolidWireframeVertices; wireframeSizeUpDown.SetValueSafe((decimal)settings.WireframeSize); vertexSizeUpDown.SetValueSafe((decimal)settings.VertexSize); SetGizmoType(settings.GizmoType, force: true); SetModelSelectionMode(settings.ModelSelectionMode, force: true); SetSubModelVisibility(settings.SubModelVisibility, force: true); autoFocusOnRootModelToolStripMenuItem.Checked = settings.AutoFocusOnRootModel; autoFocusOnSubModelToolStripMenuItem.Checked = settings.AutoFocusOnSubModel; autoFocusIncludeWholeModelToolStripMenuItem.Checked = settings.AutoFocusIncludeWholeModel; autoFocusIncludeCheckedModelsToolStripMenuItem.Checked = settings.AutoFocusIncludeCheckedModels; autoFocusResetCameraRotationToolStripMenuItem.Checked = settings.AutoFocusResetCameraRotation; showBoundsToolStripMenuItem.Checked = settings.ShowBounds; showSkeletonToolStripMenuItem.Checked = settings.ShowSkeleton; _scene.ShowLightRotationRay = settings.ShowLightRotationRay; _scene.LightRotationRayDelayTime = settings.LightRotationRayDelayTime; _scene.ShowDebugVisuals = settings.ShowDebugVisuals; _scene.ShowDebugPickingRay = settings.ShowDebugPickingRay; _scene.ShowDebugIntersections = settings.ShowDebugIntersections; SetBackgroundColor(settings.BackgroundColor); SetAmbientColor(settings.AmbientColor); SetMaskColor(settings.MaskColor); SetSolidWireframeVerticesColor(settings.SolidWireframeVerticesColor); SetCurrentCLUTIndex(settings.CurrentCLUTIndex); showVRAMSemiTransparencyToolStripMenuItem.Checked = settings.ShowVRAMSemiTransparency; showVRAMUVsToolStripMenuItem.Checked = settings.ShowVRAMUVs; showTexturePaletteToolStripMenuItem.Checked = settings.ShowTexturePalette; showTextureSemiTransparencyToolStripMenuItem.Checked = settings.ShowTextureSemiTransparency; showTextureUVsToolStripMenuItem.Checked = settings.ShowTextureUVs; showMissingTexturesToolStripMenuItem.Checked = settings.ShowMissingTextures; autoDrawModelTexturesToolStripMenuItem.Checked = settings.AutoDrawModelTextures; autoPackModelTexturesToolStripMenuItem.Checked = settings.AutoPackModelTextures; autoPlayAnimationsToolStripMenuItem.Checked = settings.AutoPlayAnimation; autoSelectAnimationModelToolStripMenuItem.Checked = settings.AutoSelectAnimationModel; animationLoopModeComboBox.SelectedIndex = (int)settings.AnimationLoopMode; animationReverseCheckBox.Checked = settings.AnimationReverse; animationSpeedNumericUpDown.SetValueSafe((decimal)settings.AnimationSpeed); showFPSToolStripMenuItem.Checked = settings.ShowFPS; fastWindowResizeToolStripMenuItem.Checked = settings.FastWindowResize; _scanProgressRefreshDelayTimer.Interval = settings.ScanProgressFrequency; _scanPopulateRefreshDelayTimer.Interval = settings.ScanPopulateFrequency; } public void WriteSettings(Settings settings) { Program.Logger.WriteSettings(settings); settings.GridSnap = (float)gridSnapUpDown.Value; settings.AngleSnap = (float)angleSnapUpDown.Value; settings.ScaleSnap = (float)scaleSnapUpDown.Value; settings.CameraFOV = (float)cameraFOVUpDown.Value; settings.LightIntensity = (float)lightIntensityNumericUpDown.Value; settings.LightYaw = (float)lightYawNumericUpDown.Value; settings.LightPitch = (float)lightPitchNumericUpDown.Value; settings.LightEnabled = enableLightToolStripMenuItem.Checked; settings.AmbientEnabled = _scene.AmbientEnabled; settings.TexturesEnabled = enableTexturesToolStripMenuItem.Checked; settings.VertexColorEnabled = enableVertexColorToolStripMenuItem.Checked; settings.SemiTransparencyEnabled = enableSemiTransparencyToolStripMenuItem.Checked; settings.ForceDoubleSided = forceDoubleSidedToolStripMenuItem.Checked; settings.AutoAttachLimbs = autoAttachLimbsToolStripMenuItem.Checked; settings.DrawFaces = drawModeFacesToolStripMenuItem.Checked; settings.DrawWireframe = drawModeWireframeToolStripMenuItem.Checked; settings.DrawVertices = drawModeVerticesToolStripMenuItem.Checked; settings.DrawSolidWireframeVertices = drawModeSolidWireframeVerticesToolStripMenuItem.Checked; settings.WireframeSize = (float)wireframeSizeUpDown.Value; settings.VertexSize = (float)vertexSizeUpDown.Value; settings.GizmoType = _gizmoType; settings.ModelSelectionMode = _modelSelectionMode; settings.SubModelVisibility = _subModelVisibility; settings.AutoFocusOnRootModel = autoFocusOnRootModelToolStripMenuItem.Checked; settings.AutoFocusOnSubModel = autoFocusOnSubModelToolStripMenuItem.Checked; settings.AutoFocusIncludeWholeModel = autoFocusIncludeWholeModelToolStripMenuItem.Checked; settings.AutoFocusIncludeCheckedModels = autoFocusIncludeCheckedModelsToolStripMenuItem.Checked; settings.AutoFocusResetCameraRotation = autoFocusResetCameraRotationToolStripMenuItem.Checked; settings.ShowBounds = showBoundsToolStripMenuItem.Checked; settings.ShowSkeleton = showSkeletonToolStripMenuItem.Checked; settings.ShowLightRotationRay = _scene.ShowLightRotationRay; settings.LightRotationRayDelayTime = _scene.LightRotationRayDelayTime; settings.ShowDebugVisuals = _scene.ShowDebugVisuals; settings.ShowDebugPickingRay = _scene.ShowDebugPickingRay; settings.ShowDebugIntersections = _scene.ShowDebugIntersections; settings.BackgroundColor = _scene.ClearColor; settings.AmbientColor = _scene.AmbientColor; settings.MaskColor = _scene.MaskColor; settings.SolidWireframeVerticesColor = _scene.SolidWireframeVerticesColor; settings.CurrentCLUTIndex = _clutIndex; settings.ShowVRAMSemiTransparency = showVRAMSemiTransparencyToolStripMenuItem.Checked; settings.ShowVRAMUVs = showVRAMUVsToolStripMenuItem.Checked; settings.ShowTexturePalette = showTexturePaletteToolStripMenuItem.Checked; settings.ShowTextureSemiTransparency = showTextureSemiTransparencyToolStripMenuItem.Checked; settings.ShowTextureUVs = showTextureUVsToolStripMenuItem.Checked; settings.ShowMissingTextures = showMissingTexturesToolStripMenuItem.Checked; settings.AutoDrawModelTextures = autoDrawModelTexturesToolStripMenuItem.Checked; settings.AutoPackModelTextures = autoPackModelTexturesToolStripMenuItem.Checked; settings.AutoPlayAnimation = autoPlayAnimationsToolStripMenuItem.Checked; settings.AutoSelectAnimationModel = autoSelectAnimationModelToolStripMenuItem.Checked; settings.AnimationLoopMode = (AnimationLoopMode)animationLoopModeComboBox.SelectedIndex; settings.AnimationReverse = animationReverseCheckBox.Checked; settings.AnimationSpeed = (float)animationSpeedNumericUpDown.Value; settings.ShowFPS = showFPSToolStripMenuItem.Checked; settings.FastWindowResize = fastWindowResizeToolStripMenuItem.Checked; } #endregion #region Main/GLControl private void SetupControls() { // Set window title to format: PSXPrev #.#.#.# _baseWindowTitle = $"{Text} {GetVersionString()}"; Text = _baseWindowTitle; // Setup GLControl try { // 24-bit depth buffer fixes issues where lower-end laptops // with integrated graphics render larger models horribly. var samples = Settings.Instance.Multisampling; var graphicsMode = new GraphicsMode(color: 32, depth: 24, stencil: 0, samples: samples); _glControl = new GLControl(graphicsMode); _currentMultisampling = samples; } catch { // Don't know if an unsupported graphics mode can throw, but let's play it safe. _glControl = new GLControl(); _currentMultisampling = 0; } _glControl.Name = "glControl"; _glControl.TabIndex = 0; _glControl.BackColor = _scene.ClearColor; _glControl.Dock = DockStyle.Fill; _glControl.VSync = true; _glControl.MouseDown += (sender, e) => glControl_MouseEvent(e, MouseEventType.Down); _glControl.MouseUp += (sender, e) => glControl_MouseEvent(e, MouseEventType.Up); _glControl.MouseWheel += (sender, e) => glControl_MouseEvent(e, MouseEventType.Wheel); _glControl.MouseMove += (sender, e) => glControl_MouseEvent(e, MouseEventType.Move); _glControl.Paint += glControl_Paint; // Assign user control properties that need something from the main form scenePreviewer.GLControl = _glControl; animationPreviewer.GLControl = _glControl; scenePreviewer.Scene = _scene; animationPreviewer.Scene = _scene; texturePreviewer.GetUVEntities = EnumerateUVEntities; vramPreviewer.GetUVEntities = EnumerateUVEntities; // Setup Timers // Don't start watch until first Elapsed event (and use a default time for that first event) // Don't start timer until the Form is loaded _fpsWatch = new Stopwatch(); _mainWatch = new Stopwatch(); _mainTimer = new Timer(1d); // 1 millisecond, update as fast as possible (usually ~60FPS) _mainTimer.SynchronizingObject = this; _mainTimer.Elapsed += mainTimer_Elapsed; _animationProgressBarRefreshDelayTimer = new RefreshDelayTimer(1d / 60d); // 1 frame (60FPS) _animationProgressBarRefreshDelayTimer.Elapsed += () => UpdateAnimationProgressLabel(true); _modelPropertyGridRefreshDelayTimer = new RefreshDelayTimer(50d / 1000d); // 50 milliseconds _modelPropertyGridRefreshDelayTimer.Elapsed += () => UpdateModelPropertyGrid(true); _fpsLabelRefreshDelayTimer = new RefreshDelayTimer(1d); // 1 second _fpsLabelRefreshDelayTimer.Elapsed += () => UpdateFPSLabel(); _scanProgressRefreshDelayTimer = new RefreshDelayTimer(); // Interval assigned by settings _scanProgressRefreshDelayTimer.AutoReset = true; _scanProgressRefreshDelayTimer.Elapsed += () => ScanUpdated(); _scanPopulateRefreshDelayTimer = new RefreshDelayTimer(); // Interval assigned by settings _scanPopulateRefreshDelayTimer.AutoReset = true; _scanPopulateRefreshDelayTimer.Elapsed += () => ScanPopulateItems(); // Setup Events // Allow changing multiple checkboxes while holding shift down. drawModeToolStripMenuItem.DropDown.Closing += OnCancelMenuCloseWhileHoldingShift; autoFocusToolStripMenuItem.DropDown.Closing += OnCancelMenuCloseWhileHoldingShift; // Ensure numeric up downs display the same value that they store internally. SetupNumericUpDownValidateEvents(this); // Normally clicking a menu separator will close the menu, which doesn't follow standard UI patterns. SetupCancelMenuCloseOnSeparatorClick(mainMenuStrip); // Make it so that checkboxes without text will still show a focus rectangle. // NOTE: Padding for these should be set to: 2, 2, 0, 1 SetupFocusRectangleForCheckBoxesWithoutText(); // Setup Enabled/Visible // Hide certain controls by default (rather than hiding them in the designer and making them hard to edit). // Default scanning state for controls pauseScanningToolStripMenuItem.Enabled = false; stopScanningToolStripMenuItem.Enabled = false; statusTotalFilesProgressBar.Visible = false; statusCurrentFileProgressBar.Visible = false; // Default to invisible until we have a gizmo type set gizmoSnapFlowLayoutPanel.Visible = false; // Default to invisible unless wireframe and/or vertices draw modes are enabled wireframeVertexSizeFlowLayoutPanel.Visible = false; // Setup ImageListView for textures // Set renderer to use a sharp-cornered square box, and nameplate below the box. texturesListView.SetRenderer(new Manina.Windows.Forms.ImageListViewRenderers.XPRenderer()); // Use this cache mode so that thumbnails are already loaded when you scroll past them. texturesListView.CacheMode = CacheMode.Continuous; // Set handlers for "Found" and "Textures" groups. var grouper = new TexturesListViewGrouper(); var comparer = Comparer<ImageListViewItem>.Create(CompareTexturesListViewItems); // Set grouper and comparer for "Found" group. texturesListView.Columns[0].Grouper = grouper; texturesListView.Columns[0].Comparer = comparer; // Set grouper and comparer for "Textures" (everything else) group. texturesListView.Columns[1].Grouper = grouper; texturesListView.Columns[1].Comparer = comparer; } private void SetupScene() { if (!_scene.IsInitialized) { // Make sure GLControl's handle is created, so that its graphics context is prepared. // GLControl attempts to do this automatically when calling MakeCurrent, // but it will throw an exception if not visible... so we can't rely on it. if (!_glControl.IsHandleCreated) { // Calling the getter for Handle will force handle creation. // CreateControl() will not do so if the control is not visible. var dummyAssignToCreateHandle = _glControl.Handle; } // Setup classes that depend on OpenTK. // Make the GraphicsContext current before doing any OpenTK/GL stuff, // this only ever needs to be done once. _glControl.MakeCurrent(); _scene.Initialize(); _vram.Initialize(); } } private void ClearScanResults() { if (!Program.IsScanning) { Program.ClearResults(); // Clear selections //SelectEntity(null); UnselectTriangle(); _selectedTriangle = null; _selectedModelEntity = null; _selectedRootEntity = null; UpdateSelectedEntity(); _curAnimation = null; _curAnimationObject = null; _curAnimationFrame = null; UpdateSelectedAnimation(false); // Clear selected property grid objects modelPropertyGrid.SelectedObject = null; texturePropertyGrid.SelectedObject = null; animationPropertyGrid.SelectedObject = null; // Clear listed results entitiesTreeView.Nodes.Clear(); texturesListView.Items.Clear(); animationsTreeView.Nodes.Clear(); // Clear picture boxes texturePreviewer.Texture = null; // We don't need to clear this for VRAM, since VRAM isn't a scan result // Clear actual results _rootEntities.Clear(); foreach (var texture in _textures) { texture.Dispose(); } _textures.Clear(); _packedTextures.Clear(); _animations.Clear(); _vram.ClearAllPages(); vramPreviewer.InvalidateTexture(); // Invalidate to make sure we redraw. // Reset scene batches _scene.MeshBatch.Reset(0); _scene.BoundsBatch.Reset(1); _scene.TriangleOutlineBatch.Reset(2); _scene.DebugIntersectionsBatch.Reset(1); _scene.SetDebugPickingRay(false); // Update display information statusMessageLabel.Text = "Waiting"; UpdateVRAMComboBoxPageItems(); UpdateAnimationProgressLabel(); _scene.ClearUnderMouseCycleLists(); TMDBindingsForm.CloseTool(); GC.Collect(); // It's my memory and I need it now! } } private void Redraw() { _glControl.Invalidate(); /*if (menusTabControl.SelectedIndex == ModelsTabIndex) { scenePreviewer.InvalidateScene(); } else if (menusTabControl.SelectedIndex == AnimationsTabIndex) { animationPreviewer.InvalidateScene(); }*/ } private static string GetVersionString() { var assembly = Assembly.GetExecutingAssembly(); var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); return fileVersionInfo.FileVersion; } private void UpdateFPSLabel() { _fpsLabelRefreshDelayTimer.Reset(); if (showFPSToolStripMenuItem.Checked && IsSceneTab) { var skinsStr = string.Empty;// _skinsDrawn > 0 ? $", Skins: {_skinsDrawn}" : string.Empty; Text = $"{_baseWindowTitle} (FPS: {_fps:0.0}, Triangles: {_trianglesDrawn}, Meshes: {_meshesDrawn}{skinsStr})"; } else { Text = _baseWindowTitle; } } private void UpdatePreviewerParents() { var hideUI = !showUIToolStripMenuItem.Checked; var tabIndex = menusTabControl.SelectedIndex; if (hideUI && tabIndex == ModelsTabIndex) { scenePreviewer.Parent = this; } else { // Change back to default parent while not in use scenePreviewer.Parent = modelsPreviewSplitContainer.Panel2; } if (hideUI && tabIndex == AnimationsTabIndex) { animationPreviewer.Parent = this; } else { // Change back to default parent while not in use animationPreviewer.Parent = animationPreviewPanel; animationPreviewer.BringToFront(); } /*if (hideUI && (tabIndex == ModelsTabIndex || tabIndex == AnimationsTabIndex)) { scenePreviewer.Parent = this; } else if (tabIndex == ModelsTabIndex) { scenePreviewer.Parent = modelsPreviewSplitContainer.Panel2; } else if (tabIndex == AnimationsTabIndex) { scenePreviewer.Parent = animationPreviewPanel; } else if (scenePreviewer.Parent == this) { // Assign back to default parent when not in use scenePreviewer.Parent = modelsPreviewSplitContainer.Panel2; }*/ if (hideUI && tabIndex == TexturesTabIndex) { texturePreviewer.Parent = this; } else { texturePreviewer.Parent = texturesPreviewSplitContainer.Panel2; } if (hideUI && tabIndex == VRAMTabIndex) { vramPreviewer.Parent = this; } else { vramPreviewer.Parent = vramPreviewSplitContainer.Panel2; } // Update the previewer status bars while we're at it, since we only change visibilty when changing parents var showModelsStatusBar = showModelsStatusBarToolStripMenuItem.Checked; scenePreviewer.ShowStatusBar = !hideUI && showModelsStatusBar; texturePreviewer.ShowStatusBar = !hideUI; vramPreviewer.ShowStatusBar = !hideUI; //animationPreviewer.ShowStatusBar = false; // Always false } private void UpdateShowUIVisibility(bool changeShowUI) { PrimaryControl.SuspendLayout(); SuspendLayout(); var hideUI = !showUIToolStripMenuItem.Checked; mainMenuStrip.Visible = !hideUI; // WinForms tries to select the contents of a nested tree view when hiding the parent tab control. // So we want to hide the containers nested inside the tab control first to prevent this from happening. // WinForms moment... modelsPreviewSplitContainer.Visible = !hideUI; texturesPreviewSplitContainer.Visible = !hideUI; vramPreviewSplitContainer.Visible = !hideUI; animationsPreviewSplitContainer.Visible = !hideUI; menusTabControl.Visible = !hideUI; sceneControlsFlowLayoutPanel.Visible = !hideUI; statusStrip1.Visible = !hideUI; var showSideBar = showSideBarToolStripMenuItem.Checked; modelsPreviewSplitContainer.Panel1Collapsed = !showSideBar; texturesPreviewSplitContainer.Panel1Collapsed = !showSideBar; vramPreviewSplitContainer.Panel1Collapsed = !showSideBar; animationsPreviewSplitContainer.Panel1Collapsed = !showSideBar; var borderStyle = (hideUI ? BorderStyle.None : BorderStyle.FixedSingle); scenePreviewer.BorderStyle = borderStyle; texturePreviewer.BorderStyle = borderStyle; vramPreviewer.BorderStyle = borderStyle; animationPreviewer.BorderStyle = borderStyle; UpdatePreviewerParents(); ResumeLayout(); PrimaryControl.ResumeLayout(); if (changeShowUI) { Refresh(); } } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.Enter) { // Take focus away from numeric up/downs, // and give it the primary control of this tab. var numericUpDown = this.GetFocusedControlOfType<NumericUpDown>(); if (numericUpDown != null) { switch (menusTabControl.SelectedIndex) { case ModelsTabIndex: // Models scenePreviewer.Focus(); break; case TexturesTabIndex: // Textures texturePreviewer.Focus(); break; case VRAMTabIndex: // VRAM vramPreviewer.Focus(); break; case AnimationsTabIndex: // Animations animationPreviewer.Focus(); break; } return true; // Enter key handled } } else if (keyData == Keys.Escape) { if (!showUIToolStripMenuItem.Checked) { showUIToolStripMenuItem.Checked = true; return true; // Escape key handled } } #if ENABLE_CLIPBOARD if (keyData == (Keys.Control | Keys.C)) { var copied = false; var tabIndex = menusTabControl.SelectedIndex; if (scenePreviewer.Focused || animationPreviewer.Focused || entitiesTreeView.Focused || animationsTreeView.Focused) { var currentScenePreviewer = tabIndex != AnimationsTabIndex ? scenePreviewer : animationPreviewer; using (var bitmap = currentScenePreviewer.CreateBitmap()) { if (bitmap != null) { // Supporting transparency in the copied image means that some programs // like Paint won't use the fallback opaque image background color. :\ //ClipboardUtils.SetImageWithTransparency(bitmap, _scene.ClearColor); Clipboard.SetImage(bitmap); copied = true; } } } else if (texturePreviewer.Focused || vramPreviewer.Focused || texturesListView.Focused || vramListBox.Focused) { var currentTexturePreviewer = tabIndex != VRAMTabIndex ? texturePreviewer : vramPreviewer; using (var bitmap = currentTexturePreviewer.CreateBitmap()) { if (bitmap != null) { ClipboardUtils.SetImageWithTransparency(bitmap); //Clipboard.SetImage(bitmap); copied = true; } } } if (copied) { Program.ConsoleLogger.WriteLine("Copied to clipboard"); return true; // Ctrl+C hotkey handled } } #endif return base.ProcessCmdKey(ref msg, keyData); } private void previewForm_Load(object sender, EventArgs e) { // SetupScene needs to be called before ReadSettings SetupScene(); // Read and apply settings or default settings ReadSettings(Settings.Instance); // Start timers that should always be running _mainTimer.Start(); #if DEBUG SetupTestModels(); #endif } private void previewForm_Shown(object sender, EventArgs e) { if (Program.HasCommandLineArguments) { _drawAllToVRAMAfterScan = Program.CommandLineOptions.DrawAllToVRAM; Program.ScanCommandLineAsync(OnScanProgressCallback); } else { PromptScan(); } } private void previewForm_FormClosing(object sender, FormClosingEventArgs e) { _closing = true; // Automatically save settings when closing the program. // The user can still manually save settings with a menu item. SaveSettings(); _mainTimer?.Stop(); Program.CancelScan(); // Cancel the scan if one is active. } private void previewForm_ResizeBegin(object sender, EventArgs e) { if (fastWindowResizeToolStripMenuItem.Checked) { SuspendLayout(); _resizeLayoutSuspended = true; } } private void previewForm_ResizeEnd(object sender, EventArgs e) { if (_resizeLayoutSuspended) { ResumeLayout(); _resizeLayoutSuspended = false; } } private void menusTabControl_SelectedIndexChanged(object sender, EventArgs e) { var tabIndex = menusTabControl.SelectedIndex; // Handle leaving the animation tab. if (_inAnimationTab && tabIndex != AnimationsTabIndex) { _inAnimationTab = false; // Restart to force animation state update next time we're in the animation tab. // Reset animation when leaving the tab. _animationBatch.Restart(); Playing = false; UpdateAnimationProgressLabel(); // Update selected entity to invalidate the animation changes to the model. UpdateSelectedEntity(updateTextures: false); } // Force-hide all visuals when in animation tab. _scene.ShowVisuals = tabIndex != AnimationsTabIndex; UpdatePreviewerParents(); switch (tabIndex) { case ModelsTabIndex: // Models animationsTreeView.SelectedNode = null; _fpsWatch.Reset(); break; case TexturesTabIndex: // Textures break; case VRAMTabIndex: // VRAM UpdateVRAMComboBoxPageItems(); break; case AnimationsTabIndex: // Animations _inAnimationTab = true; _fpsWatch.Reset(); UpdateSelectedAnimation(); break; } menusTabControl.Refresh(); // Refresh so that controls don't take an undetermined amount of time to render UpdateFPSLabel(); } private void previewForm_KeyDown(object sender, KeyEventArgs e) { previewForm_KeyEvent(e, KeyEventType.Down); } private void previewForm_KeyUp(object sender, KeyEventArgs e) { previewForm_KeyEvent(e, KeyEventType.Up); } private void previewForm_KeyEvent(KeyEventArgs e, KeyEventType eventType) { if (eventType == KeyEventType.Down || eventType == KeyEventType.Up) { var state = eventType == KeyEventType.Down; var sceneFocused = (scenePreviewer.Focused || animationPreviewer.Focused); var textureFocused = (texturePreviewer.Focused || texturesListView.Focused); var vramFocused = (vramPreviewer.Focused || vramListBox.Focused); switch (e.KeyCode) { // Press space to focus on the currently-selected model case Keys.Space when state && sceneFocused: if (_selectedRootEntity != null || _selectedModelEntity != null) { _scene.FocusOnBounds(GetFocusBounds(GetCheckedEntities()), resetRotation: _autoFocusResetCameraRotation); e.Handled = true; } break; // Gizmo tools // We can't set these shortcut keys in the designer because it // considers them "invalid" for not having modifier keys. case Keys.W when state && sceneFocused: if (!IsControlDown) { if (_gizmoType != GizmoType.Translate) { SetGizmoType(GizmoType.Translate); //Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"GizmoType: {_gizmoType}"); } e.Handled = true; } break; case Keys.E when state && sceneFocused: if (!IsControlDown) { if (_gizmoType != GizmoType.Rotate) { SetGizmoType(GizmoType.Rotate); //Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"GizmoType: {_gizmoType}"); } e.Handled = true; } break; case Keys.R when state && sceneFocused: if (!IsControlDown) { if (_gizmoType != GizmoType.Scale) { SetGizmoType(GizmoType.Scale); //Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"GizmoType: {_gizmoType}"); } e.Handled = true; } break; case Keys.Oemplus when state && textureFocused: if (_clutIndex < 255) { SetCurrentCLUTIndex(_clutIndex + 1); e.Handled = true; } break; case Keys.OemMinus when state && textureFocused: if (_clutIndex > 0) { SetCurrentCLUTIndex(_clutIndex - 1); e.Handled = true; } break; case Keys.P when state && textureFocused: if (!IsControlDown) { showTexturePaletteToolStripMenuItem.Checked = !showTexturePaletteToolStripMenuItem.Checked; Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"ShowTexturePalette: {showTexturePaletteToolStripMenuItem.Checked}"); e.Handled = true; } break; case Keys.T when state && (textureFocused || vramFocused): if (!IsControlDown) { if (textureFocused) { showTextureSemiTransparencyToolStripMenuItem.Checked = !showTextureSemiTransparencyToolStripMenuItem.Checked; Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"ShowTextureSemiTransparency: {showTextureSemiTransparencyToolStripMenuItem.Checked}"); } else { showVRAMSemiTransparencyToolStripMenuItem.Checked = !showVRAMSemiTransparencyToolStripMenuItem.Checked; Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"ShowVRAMSemiTransparency: {showVRAMSemiTransparencyToolStripMenuItem.Checked}"); } e.Handled = true; } break; // Debugging keys for testing picking rays. #if true case Keys.D when state && sceneFocused: if (IsControlDown) // Ctrl+D: Toggle debug visuals) { _scene.ShowDebugVisuals = !_scene.ShowDebugVisuals; Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"ShowDebugVisuals: {_scene.ShowDebugVisuals}"); e.Handled = true; } break; case Keys.P when state && sceneFocused: if (_scene.ShowDebugVisuals) { if (IsControlDown) // Ctrl+P (Toggle debug picking ray) { _scene.ShowDebugPickingRay = !_scene.ShowDebugPickingRay; Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"ShowDebugPickingRay: {_scene.ShowDebugPickingRay}"); e.Handled = true; } else if (_scene.ShowDebugPickingRay) // P (Set debug picking ray) { _scene.SetDebugPickingRay(); e.Handled = true; } } break; case Keys.I when state && sceneFocused: if (_scene.ShowDebugVisuals) { if (IsControlDown) // Ctrl+I (Toggle debug intersections) { _scene.ShowDebugIntersections = !_scene.ShowDebugIntersections; Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"ShowDebugIntersections: {_scene.ShowDebugIntersections}"); e.Handled = true; } else if (_scene.ShowDebugIntersections) // Hold I/Hold Shift+I (Update debug intersections) { var checkedEntities = GetCheckedEntities(); var rootEntity = GetSelectedRootEntity(); if (IsTriangleSelectMode()) { _scene.GetTriangleUnderMouse(checkedEntities, rootEntity, _lastMouseX, _lastMouseY); } else { _scene.GetEntityUnderMouse(checkedEntities, rootEntity, _lastMouseX, _lastMouseY, selectionMode: _modelSelectionMode); } e.Handled = true; } } break; #endif // Debugging: Print information to help hardcode scene setup when taking screenshots of models. #if DEBUG case Keys.C when state && sceneFocused: if (_scene.ShowDebugVisuals && !IsControlDown) { Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"CameraFOV = {_scene.CameraFOV:R};"); Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"CameraDistance = {_scene.CameraDistance:R};"); Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"_cameraX = {_scene.CameraX:R};"); Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"_cameraY = {_scene.CameraY:R};"); Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"_cameraPitch = {_scene.CameraPitch:R};"); Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"_cameraYaw = {_scene.CameraYaw:R};"); Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"LightIntensity = {_scene.LightIntensity:R};"); Program.ConsoleLogger.WriteColorLine(ConsoleColor.Magenta, $"LightPitchYaw = new Vector2({_scene.LightPitch:R}, {_scene.LightYaw:R});"); e.Handled = true; } break; #endif // Debugging keys for testing AnimationBatch settings while they still don't have UI controls. #if false case Keys.F when state: _animationBatch.LoopDelayTime += 0.5; Program.ConsoleLogger.WriteLine($"LoopDelayTime={_animationBatch.LoopDelayTime}"); break; case Keys.G when state: _animationBatch.LoopDelayTime -= 0.5; Program.ConsoleLogger.WriteLine($"LoopDelayTime={_animationBatch.LoopDelayTime}"); break; #endif } } } private void glControl_Paint(object sender, PaintEventArgs e) { // Get elapsed time var deltaSeconds = _fpsWatch.IsRunning ? _fpsWatch.Elapsed.TotalSeconds : DefaultElapsedTime; _fpsWatch.Restart(); // Start or restart timer, use default time if timer wasn't running. // Update FPS tracker // Source: <http://www.david-amador.com/2009/11/how-to-do-a-xna-fps-counter/> _fpsCalcElapsedSeconds += deltaSeconds; if (_fpsCalcElapsedSeconds >= 1d) // Update FPS every one second { _fps = (float)(_fpsCalcElapsedFrames / _fpsCalcElapsedSeconds); _fpsCalcElapsedSeconds = 0d; _fpsCalcElapsedFrames = 0; if (showFPSToolStripMenuItem.Checked) { // We don't want to be updating other controls in a paint event _fpsLabelRefreshDelayTimer.Start(); } } _fpsCalcElapsedFrames++; if (_inAnimationTab && _curAnimation != null) { var rootEntity = GetSelectedRootEntity(); if (_animationBatch.SetupAnimationFrame(rootEntity) && rootEntity != null) { var updateMeshData = _curAnimation.AnimationType.IsVertexBased(); //_scene.MeshBatch.UpdateMultipleEntityBatch(_selectedRootEntity, _selectedModelEntity, updateMeshData, fastSetup: true); _scene.MeshBatch.SetupMultipleEntityBatch(GetCheckedEntities(), _selectedRootEntity, _selectedModelEntity, updateMeshData, fastSetup: true); // Animation has been processed. Update attached limbs while animating. if (_scene.AttachJointsMode == AttachJointsMode.Attach) { rootEntity.FixConnections(); } else { rootEntity.UnfixConnections(); } if (_showSkeleton) { _scene.SkeletonBatch.SetupEntitySkeleton(rootEntity, updateMeshData: false); } } } _scene.Draw(out _trianglesDrawn, out _meshesDrawn, out _skinsDrawn); _glControl.SwapBuffers(); } private void glControl_MouseEvent(MouseEventArgs e, MouseEventType eventType) { if (_inAnimationTab) { _selectedGizmo = GizmoId.None; } if (eventType == MouseEventType.Wheel) { _scene.CameraDistance -= e.Delta * MouseSensivity * _scene.CameraDistanceIncrement; return; } var deltaX = e.X - _lastMouseX; var deltaY = e.Y - _lastMouseY; var mouseLeft = e.Button == MouseButtons.Left; var mouseMiddle = e.Button == MouseButtons.Middle; var mouseRight = e.Button == MouseButtons.Right; var selectedEntityBase = GetSelectedEntityBase(); _scene.UpdatePicking(e.X, e.Y); var hoveredGizmo = _scene.GetGizmoUnderPosition(selectedEntityBase, _gizmoType); switch (_selectedGizmo) { case GizmoId.None: if (!_inAnimationTab && mouseLeft && eventType == MouseEventType.Down) { if (hoveredGizmo == GizmoId.None) { var checkedEntities = GetCheckedEntities(); var rootEntity = GetSelectedRootEntity(); if (IsTriangleSelectMode()) { var newSelectedTriangle = _scene.GetTriangleUnderMouse(checkedEntities, rootEntity, e.X, e.Y); if (newSelectedTriangle != null) { SelectTriangle(newSelectedTriangle); } else { UnselectTriangle(); } } else { var newSelectedEntity = _scene.GetEntityUnderMouse(checkedEntities, rootEntity, e.X, e.Y, selectionMode: _modelSelectionMode); if (newSelectedEntity != null) { SelectEntity(newSelectedEntity, false); } else { UnselectTriangle(); } } } else { StartGizmoAction(hoveredGizmo, e.X, e.Y); _scene.ResetIntersection(); } } else { if (mouseRight && eventType == MouseEventType.Move) { _scene.CameraPitchYaw += new Vector2(deltaY * MouseSensivity, -deltaX * MouseSensivity); } if (mouseMiddle && eventType == MouseEventType.Move) { _scene.CameraPosition += new Vector2(deltaX * MouseSensivity * _scene.CameraPanIncrement, deltaY * MouseSensivity * _scene.CameraPanIncrement); } } // Gizmos are already updated by Action methods when selected. if (_selectedGizmo == GizmoId.None && hoveredGizmo != _hoveredGizmo) { UpdateGizmoVisualAndState(_selectedGizmo, hoveredGizmo); } break; case GizmoId.AxisX when !_inAnimationTab: case GizmoId.AxisY when !_inAnimationTab: case GizmoId.AxisZ when !_inAnimationTab: case GizmoId.Uniform when !_inAnimationTab: if (mouseLeft && eventType == MouseEventType.Move && selectedEntityBase != null) { UpdateGizmoAction(e.X, e.Y); } else if (mouseRight && eventType == MouseEventType.Down) { CancelGizmoAction(); } else { FinishGizmoAction(); } break; } _lastMouseX = e.X; _lastMouseY = e.Y; } private void SetupNumericUpDownValidateEvents(Control parent) { // When a user manually enters in a value in a NumericUpDown, // the value will be shown with the specified number of decimal places, // BUT VALUE WILL NOT BE ROUNDED TO THE SPECIFIED NUMBER OF DECIMAL PLACES! // Anyways, this fixes that by rounding the value during the validating event. // We need to find all NumericUpDowns in the form, and register the event for those. var queue = new Queue<Control>(); queue.Enqueue(parent); while (queue.Count > 0) { var container = queue.Dequeue(); foreach (Control control in container.Controls) { if (control is NumericUpDown numericUpDown) { // Use the ValueChanged event (instead of Validating) // so that values assigned from settings are also enforced. numericUpDown.ValueChanged += OnNumericUpDownValidateValueChanged; } if (control.Controls.Count > 0) { queue.Enqueue(control); } } } } private void OnNumericUpDownValidateValueChanged(object sender, EventArgs e) { if (sender is NumericUpDown numericUpDown) { numericUpDown.Value = Math.Round(numericUpDown.Value, numericUpDown.DecimalPlaces, MidpointRounding.AwayFromZero); } } private void SetupCancelMenuCloseOnSeparatorClick(object parent, bool setupChildren = true) { var queue = new Queue<object>(); if (parent is ToolStrip toolStrip) // Parent is ToolStrip { // Ignore setupChildren here and treat toolStrip's items as the parents. foreach (var child in toolStrip.Items) { queue.Enqueue(child); } } else { queue.Enqueue(parent); } while (queue.Count > 0) { var container = queue.Dequeue(); if (container is ToolStripDropDownItem dropDownItem) { dropDownItem.DropDown.Closing += OnCancelMenuCloseOnSeparatorClickClosing; dropDownItem.DropDown.ItemClicked += OnCancelMenuCloseOnSeparatorClickItemClicked; if (setupChildren) { foreach (var child in dropDownItem.DropDownItems) { queue.Enqueue(child); } } } } } private void OnCancelMenuCloseOnSeparatorClickClosing(object sender, ToolStripDropDownClosingEventArgs e) { if (_cancelMenuCloseItemClickedSender == sender) { if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) { // We're closing because a separator item was clicked, so cancel it. e.Cancel = true; } // Always clear the clicked separator sender for the sender's Closing event. _cancelMenuCloseItemClickedSender = null; } } private void OnCancelMenuCloseOnSeparatorClickItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem is ToolStripSeparator) { // Store the sender of the clicked separator, we'll need it // to make sure we cancel during the correct Closing event. _cancelMenuCloseItemClickedSender = sender; } else { // Always reset this if a new item is clicked that isn't a separator. // In the scenario that Closing never happened after a separator was clicked. _cancelMenuCloseItemClickedSender = null; } } private void OnCancelMenuCloseWhileHoldingShift(object sender, ToolStripDropDownClosingEventArgs e) { if (IsShiftDown && e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) { // Allow changing multiple draw modes without re-opening the menu. // A hacky solution until we have draw modes somewhere else like a toolbar. e.Cancel = true; } } private void SetupFocusRectangleForCheckBoxesWithoutText() { foreach (var checkBox in this.EnumerateAllControlsOfType<CheckBox>()) { if (checkBox.Text.Length == 0) { checkBox.Paint += OnPaintCheckBoxWithoutTextFocusRectangle; } } } private void OnPaintCheckBoxWithoutTextFocusRectangle(object sender, PaintEventArgs e) { // source: <https://stackoverflow.com/a/6025759/7517185> if (sender is CheckBox checkBox && checkBox.Focused) { ControlPaint.DrawFocusRectangle(e.Graphics, e.ClipRectangle, checkBox.ForeColor, checkBox.BackColor); } } private void mainTimer_Elapsed(object sender, ElapsedEventArgs e) { if (IsDisposed || _closing) { return; } if (_inDialog) { // Instantly finish delayed control refreshes _animationProgressBarRefreshDelayTimer.Finish(); _modelPropertyGridRefreshDelayTimer.Finish(); _fpsLabelRefreshDelayTimer.Finish(); } else { // Get elapsed time var deltaSeconds = _mainWatch.IsRunning ? _mainWatch.Elapsed.TotalSeconds : DefaultElapsedTime; _mainWatch.Restart(); // Start or restart timer, use default time if timer wasn't running. // Don't skip too much time if we've fallen too far behind. var renderSeconds = _fixedTimer ? DefaultElapsedTime : Math.Min(deltaSeconds, MaxElapsedTime); // Update delayed control refreshes _animationProgressBarRefreshDelayTimer.AddTime(deltaSeconds); _modelPropertyGridRefreshDelayTimer.AddTime(deltaSeconds); _fpsLabelRefreshDelayTimer.AddTime(deltaSeconds); _scanProgressRefreshDelayTimer.AddTime(deltaSeconds); _scanPopulateRefreshDelayTimer.AddTime(deltaSeconds); // Update animation // Don't animate if we're not in the animation tab, or not currently playing. // todo: Or allow animations to play in other tabs, in-which case other checks for _inAnimationTab need to be removed. if (_inAnimationTab && Playing) { if (Playing && _animationBatch.IsFinished) { Playing = false; // LoopMode is a Once type, and the animation has finished. Stop playing. } else { _animationBatch.AddTime(renderSeconds * _animationSpeed); } UpdateAnimationProgressLabel(false); // Delay update to avoid excessive control refresh } // Update scene timer and then mark for redraw (but only if visible) if (IsSceneTab) { _scene.AddTime(renderSeconds); Redraw(); } } } #endregion #region GetChecked/AddResults private RootEntity GetSelectedRootEntity() { return _selectedRootEntity ?? _selectedModelEntity?.GetRootEntity(); } private EntityBase GetSelectedEntityBase() { return (EntityBase)_selectedRootEntity ?? _selectedModelEntity; } private RootEntity[] GetCheckedEntities(bool defaultToSelected = false) { var selectedEntities = new List<RootEntity>(); for (var i = 0; i < entitiesTreeView.Nodes.Count; i++) { var node = entitiesTreeView.Nodes[i]; if (node.Checked) { var tagInfo = (EntitiesTreeViewTagInfo)node.Tag; if (tagInfo.Entity is RootEntity rootEntity) { selectedEntities.Add(rootEntity); } } } if (selectedEntities.Count == 0 && defaultToSelected) { var selectedRootEntity = GetSelectedRootEntity(); if (selectedRootEntity != null) { selectedEntities.Add(selectedRootEntity); } } return selectedEntities.Count == 0 ? null : selectedEntities.ToArray(); } private IEnumerable<EntityBase> EnumerateUVEntities() { var selectedEntityBase = GetSelectedEntityBase(); var selectedRootEntity = GetSelectedRootEntity(); for (var i = 0; i < entitiesTreeView.Nodes.Count; i++) { var node = entitiesTreeView.Nodes[i]; if (node.Checked) { var tagInfo = (EntitiesTreeViewTagInfo)node.Tag; if (tagInfo.Entity is RootEntity rootEntity && rootEntity != selectedRootEntity) { yield return rootEntity; } } } if (selectedEntityBase != null) { yield return selectedEntityBase; } } private Animation[] GetCheckedAnimations(bool defaultToSelected = false) { var selectedAnimations = new List<Animation>(); for (var i = 0; i < animationsTreeView.Nodes.Count; i++) { var node = animationsTreeView.Nodes[i]; if (node.Checked) { var tagInfo = (AnimationsTreeViewTagInfo)node.Tag; if (tagInfo.Animation != null) { selectedAnimations.Add(tagInfo.Animation); } } } if (selectedAnimations.Count == 0 && defaultToSelected) { if (_curAnimation != null) { selectedAnimations.Add(_curAnimation); } } return selectedAnimations.Count == 0 ? null : selectedAnimations.ToArray(); } private Texture[] GetSelectedTextures() { // Use enumerator instead of SelectedItems.Count and array, since: // * Count enumerates over all items for each call // * Indexer enumerates over items up until index for each call var textures = new List<Texture>(); foreach (var selectedItem in texturesListView.SelectedItems) { var tagInfo = (TexturesListViewTagInfo)selectedItem.Tag; textures.Add(_textures[tagInfo.Index]); } return textures.ToArray(); } private Texture GetSelectedTexture() { // Don't use SelectedItems.Count since it enumerates over all items. But... // We can't use most Linq functions with SelectedItems because key IList interface methods are not supported. var selectedItems = texturesListView.SelectedItems; if (selectedItems.Count == 0) { return null; } var tagInfo = (TexturesListViewTagInfo)selectedItems[0].Tag; return _textures[tagInfo.Index]; } private TreeNode CreateRootEntityNode(RootEntity rootEntity, int rootIndex) { var loaded = rootEntity.ChildEntities.Length == 0; var rootEntityNode = new TreeNode(rootEntity.Name) { Tag = new EntitiesTreeViewTagInfo { Entity = rootEntity, RootIndex = rootIndex, LazyLoaded = loaded, }, }; if (!loaded) { rootEntityNode.Nodes.Add(string.Empty); // Show plus sign before we've lazy-loaded } return rootEntityNode; } private TreeNode CreateModelEntityNode(EntityBase modelEntity, int rootIndex, int childIndex) { var modelNode = new TreeNode(modelEntity.Name) { Tag = new EntitiesTreeViewTagInfo { Entity = modelEntity, RootIndex = rootIndex, ChildIndex = childIndex, LazyLoaded = true, }, }; return modelNode; } private void LoadEntityChildNodes(TreeNode entityNode) { //entitiesTreeView.BeginUpdate(); var tagInfo = (EntitiesTreeViewTagInfo)entityNode.Tag; var entity = tagInfo.Entity; var modelNodes = new TreeNode[entity.ChildEntities.Length]; for (var i = 0; i < entity.ChildEntities.Length; i++) { modelNodes[i] = CreateModelEntityNode(entity.ChildEntities[i], tagInfo.RootIndex, i); } entityNode.Nodes.Clear(); // Clear dummy node used to show plus sign entityNode.Nodes.AddRange(modelNodes); // We can't hide checkboxes until we've been added to the tree view structure. foreach (var modelNode in modelNodes) { modelNode.HideCheckBox(); } tagInfo.LazyLoaded = true; //entitiesTreeView.EndUpdate(); } private void EntitiesAdded(IReadOnlyList<RootEntity> rootEntities, int startIndex) { //entitiesTreeView.BeginUpdate(); var rootEntityNodes = new TreeNode[rootEntities.Count]; for (var i = 0; i < rootEntities.Count; i++) { rootEntityNodes[i] = CreateRootEntityNode(rootEntities[i], startIndex + i); } entitiesTreeView.Nodes.AddRange(rootEntityNodes); //entitiesTreeView.EndUpdate(); // Assign textures to models foreach (var rootEntity in rootEntities) { _vram.AssignModelTextures(rootEntity); } } private void EntityAdded(RootEntity rootEntity, int index) { entitiesTreeView.Nodes.Add(CreateRootEntityNode(rootEntity, index)); // Assign texture to model _vram.AssignModelTextures(rootEntity); } private TreeNode FindEntityNode(EntityBase entityBase, bool lazyLoad = true) { // First check if the selected node is the node we're looking for var selectedNode = entitiesTreeView.SelectedNode; var tagInfo = (EntitiesTreeViewTagInfo)selectedNode?.Tag; if (selectedNode == null || tagInfo.Entity != entityBase) { var modelEntity = entityBase as ModelEntity; var rootEntity = entityBase.GetRootEntity(); // If the selected node is the root node of our child node, then skip enumerating through all other root nodes var startIndex = selectedNode != null && tagInfo.Entity == rootEntity ? selectedNode.Index : 0; // The selected node differs, find the associated node selectedNode = null; for (var i = startIndex; i < entitiesTreeView.Nodes.Count; i++) { var rootNode = entitiesTreeView.Nodes[i]; tagInfo = (EntitiesTreeViewTagInfo)rootNode.Tag; if (tagInfo.Entity == rootEntity) { if (modelEntity == null) { // Root entity is selected, use this node selectedNode = rootNode; } else if (tagInfo.LazyLoaded || lazyLoad) { // Child of root entity is selected, find that node if (!tagInfo.LazyLoaded) { // We can't search for this node if we haven't lazy-loaded yet LoadEntityChildNodes(rootNode); } for (var j = 0; j < rootNode.Nodes.Count; j++) { var modelNode = rootNode.Nodes[j]; tagInfo = (EntitiesTreeViewTagInfo)rootNode.Tag; if (tagInfo.Entity == modelEntity) { selectedNode = modelNode; break; } } } break; } } } return selectedNode; } private ImageListViewItem CreateTextureItem(Texture texture, int index) { object key = index; var textureItem = new ImageListViewItem(key) { //Text = index.ToString(), //debug Text = texture.Name, Tag = new TexturesListViewTagInfo { //Texture = texture, Index = index, Found = false, }, }; return textureItem; } private void TexturesAdded(IReadOnlyList<Texture> textures, int startIndex) { var textureItems = new ImageListViewItem[textures.Count]; for (var i = 0; i < textures.Count; i++) { textureItems[i] = CreateTextureItem(textures[i], startIndex + i); } texturesListView.Items.AddRange(textureItems, _texturesListViewAdaptor); // Change CLUT index to current index foreach (var texture in textures) { texture.SetCLUTIndex(_clutIndex); } } private void TextureAdded(Texture texture, int index) { texturesListView.Items.Add(CreateTextureItem(texture, index), _texturesListViewAdaptor); // Change CLUT index to current index texture.SetCLUTIndex(_clutIndex); } private TreeNode CreateAnimationNode(Animation animation, int rootIndex) { var loaded = animation.RootAnimationObject.Children.Count == 0; var animationNode = new TreeNode(animation.Name) { Tag = new AnimationsTreeViewTagInfo { Animation = animation, LazyLoaded = loaded, RootIndex = rootIndex, }, }; if (!loaded) { animationNode.Nodes.Add(string.Empty); // Show plus sign before we've lazy-loaded } return animationNode; } private TreeNode CreateAnimationObjectNode(AnimationObject animationObject, int rootIndex, int childIndex) { var loaded = animationObject.Children.Count == 0; if (IncludeAnimationFrameTreeViewNodes) { loaded &= animationObject.AnimationFrames.Count == 0; } var namePostfix = string.Empty; if (!string.IsNullOrEmpty(animationObject.ObjectName)) { namePostfix = $" {animationObject.ObjectName}"; } var animationObjectNode = new TreeNode($"Animation-Object {childIndex}{namePostfix}") // 0-indexed like Sub-Models { Tag = new AnimationsTreeViewTagInfo { AnimationObject = animationObject, LazyLoaded = loaded, RootIndex = rootIndex, ChildIndex = childIndex, }, }; if (!loaded) { animationObjectNode.Nodes.Add(string.Empty); // Show plus sign before we've lazy-loaded } return animationObjectNode; } private TreeNode CreateAnimationFrameNode(AnimationFrame animationFrame, int rootIndex, int childIndex) { var frameNumber = animationFrame.FrameTime; //childIndex; var animationFrameNode = new TreeNode("Animation-Frame " + frameNumber) { Tag = new AnimationsTreeViewTagInfo { AnimationFrame = animationFrame, LazyLoaded = true, RootIndex = rootIndex, ChildIndex = childIndex, }, }; return animationFrameNode; } private void LoadAnimationChildNodes(TreeNode animationNode) { //animationsTreeView.BeginUpdate(); var tagInfo = (AnimationsTreeViewTagInfo)animationNode.Tag; var animationObject = tagInfo.AnimationObject ?? tagInfo.Animation?.RootAnimationObject; var frameCount = IncludeAnimationFrameTreeViewNodes ? animationObject.AnimationFrames.Count : 0; var animationChildNodes = new TreeNode[animationObject.Children.Count + frameCount]; for (var i = 0; i < animationObject.Children.Count; i++) { animationChildNodes[i] = CreateAnimationObjectNode(animationObject.Children[i], tagInfo.RootIndex, i); } if (frameCount > 0) { var frameStart = animationObject.Children.Count; // Sort frames by order of appearance var animationFrames = new List<AnimationFrame>(animationObject.AnimationFrames.Values); animationFrames.Sort((a, b) => a.FrameTime.CompareTo(b.FrameTime)); for (var i = 0; i < animationFrames.Count; i++) { animationChildNodes[frameStart + i] = CreateAnimationFrameNode(animationFrames[i], tagInfo.RootIndex, i); } } animationNode.Nodes.Clear(); // Clear dummy node used to show plus sign animationNode.Nodes.AddRange(animationChildNodes); // We can't hide checkboxes until we've been added to the tree view structure. foreach (var animationChildNode in animationChildNodes) { animationChildNode.HideCheckBox(); } tagInfo.LazyLoaded = true; //animationsTreeView.EndUpdate(); } private void AnimationsAdded(IReadOnlyList<Animation> animations, int startIndex) { //animationsTreeView.BeginUpdate(); var animationNodes = new TreeNode[animations.Count]; for (var i = 0; i < animations.Count; i++) { animationNodes[i] = CreateAnimationNode(animations[i], startIndex + i); } animationsTreeView.Nodes.AddRange(animationNodes); //animationsTreeView.EndUpdate(); } private void AnimationAdded(Animation animation, int index) { animationsTreeView.Nodes.Add(CreateAnimationNode(animation, index)); } private TreeNode FindAnimationNode(Animation animation, bool lazyLoad = true) { // First check if the selected node is the node we're looking for var selectedNode = animationsTreeView.SelectedNode; var tagInfo = (AnimationsTreeViewTagInfo)selectedNode?.Tag; if (selectedNode == null || tagInfo.Animation != animation) { // The selected node differs, find the associated node selectedNode = null; for (var i = 0; i < animationsTreeView.Nodes.Count; i++) { var animationNode = animationsTreeView.Nodes[i]; tagInfo = (AnimationsTreeViewTagInfo)animationNode.Tag; if (tagInfo.Animation == animation) { selectedNode = animationNode; break; } } } return selectedNode; } private TreeNode FindAnimationNode(AnimationObject animationObject, AnimationFrame animationFrame, bool lazyLoad = true) { // First check if the selected node is the node we're looking for var selectedNode = animationsTreeView.SelectedNode; var tagInfo = (AnimationsTreeViewTagInfo)selectedNode?.Tag; var objectMatches = (animationObject != null && tagInfo?.AnimationObject == animationObject); var frameMatches = (animationFrame != null && tagInfo?.AnimationFrame == animationFrame); if (selectedNode == null || (!objectMatches && !frameMatches)) { var animation = animationObject.Animation; if (animation.RootAnimationObject == animationObject) { return null; // We don't show nodes for root animation objects, unless we want to return the animation node... } // If the selected node is the root node of our child node, then skip enumerating through all other root nodes var startIndex = selectedNode != null && tagInfo.Animation == animation ? selectedNode.Index : 0; // The selected node differs, find the associated node selectedNode = null; for (var i = startIndex; i < animationsTreeView.Nodes.Count; i++) { var animationNode = animationsTreeView.Nodes[i]; tagInfo = (AnimationsTreeViewTagInfo)animationNode.Tag; if (tagInfo.Animation == animation) { var parentAnimationObject = animationObject?.Parent ?? animationFrame.AnimationObject; var parentNode = FindAnimationParentNode(animationNode, parentAnimationObject, lazyLoad); if (parentNode == null) { break; // Parent not found, or not loaded } for (var j = 0; j < parentNode.Nodes.Count; j++) { var childNode = parentNode.Nodes[j]; tagInfo = (AnimationsTreeViewTagInfo)childNode.Tag; if (animationObject != null && tagInfo.AnimationObject == animationObject) { selectedNode = childNode; break; } else if (animationFrame != null && tagInfo.AnimationFrame == animationFrame) { selectedNode = childNode; break; } } break; } } } return selectedNode; } private TreeNode FindAnimationParentNode(TreeNode animationNode, AnimationObject parentObject, bool lazyLoad) { var tagInfo = (AnimationsTreeViewTagInfo)animationNode.Tag; if (!tagInfo.LazyLoaded) { if (!lazyLoad) { return null; // We can't continue } // We can't search for this node if we haven't lazy-loaded yet LoadAnimationChildNodes(animationNode); } if (parentObject.Parent == null) { return animationNode; // This is the parent node } var stack = new Stack<AnimationObject>(); while (parentObject != null && parentObject.Parent != null) // Don't include RootAnimationObject { stack.Push(parentObject); parentObject = parentObject.Parent; } var nextParentNode = animationNode; while (stack.Count > 0 && nextParentNode != null) { parentObject = stack.Pop(); var parentNode = nextParentNode; nextParentNode = null; for (var j = 0; j < parentNode.Nodes.Count; j++) { var childNode = parentNode.Nodes[j]; tagInfo = (AnimationsTreeViewTagInfo)childNode.Tag; if (tagInfo.AnimationObject == parentObject) { if (!tagInfo.LazyLoaded) { if (!lazyLoad) { break; // We can't continue } // We can't search for this node if we haven't lazy-loaded yet LoadAnimationChildNodes(parentNode); } nextParentNode = childNode; break; } } } return nextParentNode; } // Helper functions primarily intended for debugging models made by MeshBuilders. private void AddRootEntities(params RootEntity[] rootEntities) { AddRootEntities((IReadOnlyList<RootEntity>)rootEntities); // Cast required to avoid calling this same function } private void AddRootEntities(IReadOnlyList<RootEntity> rootEntities) { var startIndex = _rootEntities.Count; _rootEntities.AddRange(rootEntities); EntitiesAdded(rootEntities, startIndex); } private void AddRootEntity(RootEntity rootEntity) { _rootEntities.Add(rootEntity); EntityAdded(rootEntity, _rootEntities.Count - 1); } private void AddTextures(params Texture[] textures) { AddTextures((IReadOnlyList<Texture>)textures); // Cast required to avoid calling this same function } private void AddTextures(IReadOnlyList<Texture> textures) { var startIndex = _textures.Count; _textures.AddRange(textures); TexturesAdded(textures, startIndex); } private void AddTexture(Texture texture) { _textures.Add(texture); TextureAdded(texture, _textures.Count - 1); } private void AddAnimations(params Animation[] animations) { AddAnimations((IReadOnlyList<Animation>)animations); // Cast required to avoid calling this same function } private void AddAnimations(IReadOnlyList<Animation> animations) { var startIndex = _animations.Count; _animations.AddRange(animations); AnimationsAdded(animations, startIndex); } private void AddAnimation(Animation animation) { _animations.Add(animation); AnimationAdded(animation, _animations.Count - 1); } #endregion #region Gizmos private void SetGizmoType(GizmoType gizmoType, bool force = false) { if (_gizmoType != gizmoType || force) { FinishGizmoAction(); // Make sure to finish action before changing _gizmoType _gizmoType = gizmoType; gizmoToolNoneToolStripMenuItem.Checked = _gizmoType == GizmoType.None; gizmoToolTranslateToolStripMenuItem.Checked = _gizmoType == GizmoType.Translate; gizmoToolRotateToolStripMenuItem.Checked = _gizmoType == GizmoType.Rotate; gizmoToolScaleToolStripMenuItem.Checked = _gizmoType == GizmoType.Scale; // Suspend layout while changing visibility and text to avoid jittery movement of controls. sceneControlsFlowLayoutPanel.SuspendLayout(); gizmoSnapFlowLayoutPanel.Visible = _gizmoType != GizmoType.None; gridSnapUpDown.Visible = _gizmoType == GizmoType.Translate; angleSnapUpDown.Visible = _gizmoType == GizmoType.Rotate; scaleSnapUpDown.Visible = _gizmoType == GizmoType.Scale; switch (_gizmoType) { case GizmoType.Translate: gizmoSnapLabel.Text = "Grid Snap:"; break; case GizmoType.Rotate: gizmoSnapLabel.Text = "Angle Snap:"; break; case GizmoType.Scale: gizmoSnapLabel.Text = "Scale Snap:"; break; } sceneControlsFlowLayoutPanel.ResumeLayout(); // Gizmo shape has changed, recalculate hovered. var selectedEntityBase = GetSelectedEntityBase(); _scene.UpdatePicking(_lastMouseX, _lastMouseY); var hoveredGizmo = _scene.GetGizmoUnderPosition(selectedEntityBase, _gizmoType); UpdateGizmoVisualAndState(_selectedGizmo, hoveredGizmo); } } private void UpdateGizmoVisualAndState(GizmoId selectedGizmo, GizmoId hoveredGizmo) { var selectedEntityBase = GetSelectedEntityBase(); // Don't highlight hovered gizmo while selecting var highlightGizmo = selectedGizmo != GizmoId.None ? selectedGizmo : hoveredGizmo; _scene.UpdateGizmoVisual(selectedEntityBase, _gizmoType, highlightGizmo); if (selectedEntityBase != null) { _selectedGizmo = selectedGizmo; _hoveredGizmo = hoveredGizmo; } } private void StartGizmoAction(GizmoId hoveredGizmo, int x, int y) { if (_selectedGizmo != GizmoId.None || _gizmoType == GizmoType.None) { return; } var selectedEntityBase = GetSelectedEntityBase(); switch (hoveredGizmo) { case GizmoId.AxisX: _gizmoAxis = Vector3.UnitX; break; case GizmoId.AxisY: _gizmoAxis = Vector3.UnitY; break; case GizmoId.AxisZ: _gizmoAxis = Vector3.UnitZ; break; case GizmoId.Uniform: _gizmoAxis = Vector3.One; break; } switch (_gizmoType) { case GizmoType.Translate: _gizmoOrigin = _scene.GetPickedPosition(); _gizmoInitialTranslation = selectedEntityBase.Translation; break; case GizmoType.Rotate: _gizmoOrigin = selectedEntityBase.WorldOrigin; // Must assign _gizmoOrigin before calling CalculateGizmoRotationDirection. _gizmoRotateStartDirection = CalculateGizmoRotateDirection(x, y); _gizmoInitialRotation = selectedEntityBase.Rotation; break; case GizmoType.Scale: _gizmoOrigin = selectedEntityBase.WorldOrigin; // Must assign _gizmoOrigin before calling CalculateGizmoScaleDistance. _gizmoScaleStartDistance = Math.Max(CalculateGizmoScaleDistance(x, y), 1f); _gizmoInitialScale = selectedEntityBase.Scale; break; } UpdateGizmoVisualAndState(hoveredGizmo, hoveredGizmo); } private void UpdateGizmoAction(int x, int y) { if (_selectedGizmo == GizmoId.None) { return; } var selectedEntityBase = GetSelectedEntityBase(); switch (_gizmoType) { case GizmoType.Translate: UpdateGizmoTranslate(selectedEntityBase); break; case GizmoType.Rotate: UpdateGizmoRotate(selectedEntityBase, x, y); break; case GizmoType.Scale: UpdateGizmoScale(selectedEntityBase, x, y); break; } UpdateSelectedEntity(false, noDelayUpdatePropertyGrid: false, fastSetup: true, selectedOnly: true, updateTextures: false); // Delay updating property grid to reduce lag } private void FinishGizmoAction() { if (_selectedGizmo == GizmoId.None) { return; } var selectedEntityBase = GetSelectedEntityBase(); switch (_gizmoType) { case GizmoType.Translate: AlignSelectedEntityToGrid(selectedEntityBase); break; case GizmoType.Rotate: AlignSelectedEntityGizmoRotation(selectedEntityBase); break; case GizmoType.Scale: AlignSelectedEntityScale(selectedEntityBase); break; } // UpdateSelectedEntity is already called by align functions. // Recalculate hovered gizmo, since the gizmo position/rotation may have changed after alignment. var hoveredGizmo = _scene.GetGizmoUnderPosition(selectedEntityBase, _gizmoType); UpdateGizmoVisualAndState(GizmoId.None, hoveredGizmo); } private void CancelGizmoAction() { if (_selectedGizmo == GizmoId.None) { return; } var selectedEntityBase = GetSelectedEntityBase(); switch (_gizmoType) { case GizmoType.Translate: selectedEntityBase.Translation = _gizmoInitialTranslation; break; case GizmoType.Rotate: selectedEntityBase.Rotation = _gizmoInitialRotation; break; case GizmoType.Scale: selectedEntityBase.Scale = _gizmoInitialScale; break; } UpdateSelectedEntity(false, selectedOnly: true, updateTextures: false); // Recalculate hovered gizmo, since the gizmo position/rotation may have changed after alignment. var hoveredGizmo = _scene.GetGizmoUnderPosition(selectedEntityBase, _gizmoType); UpdateGizmoVisualAndState(GizmoId.None, hoveredGizmo); } private void UpdateGizmoTranslate(EntityBase selectedEntityBase) { // Make sure to scale translation by that of parent entity. var scale = Vector3.One; if (selectedEntityBase.ParentEntity != null) { var parentWorldMatrix = selectedEntityBase.ParentEntity.WorldMatrix; scale = parentWorldMatrix.ExtractScale(); // The larger the scale, the less we want to move to preserve the same world translation. // No division operator with RHS Vector3, so we need to inverse here. scale.X = scale.X != 0f ? (1f / scale.X) : 0f; scale.Y = scale.Y != 0f ? (1f / scale.Y) : 0f; scale.Z = scale.Z != 0f ? (1f / scale.Z) : 0f; } var pickedPosition = _scene.GetPickedPosition(); var projectedOffset = (pickedPosition - _gizmoOrigin).ProjectOnNormal(_gizmoAxis); if (selectedEntityBase.ParentEntity != null) { var parentWorldRotation = selectedEntityBase.ParentEntity.WorldMatrix.ExtractRotationSafe();//.Inverted(); if (Vector3.Dot(parentWorldRotation * _gizmoAxis, _gizmoAxis) < 0f) { // Axis is not "forward", reverse offset so that we move in the same direction as the mouse. projectedOffset = -projectedOffset; } } selectedEntityBase.Translation = _gizmoInitialTranslation + projectedOffset * scale; } private void UpdateGizmoRotate(EntityBase selectedEntityBase, int x, int y) { var direction = CalculateGizmoRotateDirection(x, y); //var z = Vector3.Cross(new Vector3(direction), new Vector3(_gizmoRotateStartDirection)).Z; var z = direction.X * _gizmoRotateStartDirection.Y - direction.Y * _gizmoRotateStartDirection.X; var angle = (float)Math.Asin(GeomMath.Clamp(z, -1f, 1f)); // Math.Asin only returns angles in the range 90deg to -90deg. For angles beyond // that, we need to check if direction is opposite of _gizmoRotateStartDirection. if (Vector2.Dot(direction, _gizmoRotateStartDirection) < 0f) { angle = (float)Math.PI - angle; } var worldRotation = selectedEntityBase.WorldMatrix.ExtractRotationSafe(); if (Vector3.Dot(worldRotation * _gizmoAxis, _scene.CameraDirection) < 0f) { angle = -angle; // Camera view of axis is not "forward", reverse angle } // This isn't necessary, since angle isn't going to be compounded and end up as multiples of 360deg. //angle = GeomMath.PositiveModulus(angle, (float)(Math.PI * 2d)); // Add axis rotation based on the current axis rotations. // Basically, if you rotate one axis, then that will change // the angle of rotation applied when using other axes. _gizmoRotateAngle = angle; var newRotation = _gizmoInitialRotation * Quaternion.FromAxisAngle(_gizmoAxis, _gizmoRotateAngle); selectedEntityBase.Rotation = newRotation; } private void UpdateGizmoScale(EntityBase selectedEntityBase, int x, int y) { var distance = CalculateGizmoScaleDistance(x, y); var amount = distance / _gizmoScaleStartDistance; if (_selectedGizmo == GizmoId.Uniform) { selectedEntityBase.Scale = _gizmoInitialScale * amount; } else { var newScaleMult = Vector3.One + _gizmoAxis * (amount - 1f); selectedEntityBase.Scale = _gizmoInitialScale * newScaleMult; } } private Vector2 CalculateGizmoRotateDirection(int x, int y) { // Get the center of the gizmo as seen on the screen. var screen = _scene.WorldToScreenPoint(_gizmoOrigin).Xy; var diff = new Vector2(x - screen.X, y - screen.Y); if (diff.IsZero()) { // Choose some arbitrary default 2D unit vector in-case the user selected the // rotation gizmo right on the same world coordinates as the model's origin. return Vector2.UnitX; } return diff.Normalized(); } private float CalculateGizmoScaleDistance(int x, int y) { var screen = _scene.WorldToScreenPoint(_gizmoOrigin).Xy; var diff = new Vector2(x - screen.X, y - screen.Y); return diff.Length; } private void AlignSelectedEntityToGrid(EntityBase selectedEntityBase) { if (selectedEntityBase != null) { selectedEntityBase.Translation = SnapToGrid(selectedEntityBase.Translation); UpdateSelectedEntity(false, selectedOnly: true, updateTextures: false); } } private void AlignSelectedEntityGizmoRotation(EntityBase selectedEntityBase) { if (selectedEntityBase != null) { var angle = SnapAngle(_gizmoRotateAngle); // Grid size is in units of 1 degree. var newRotation = _gizmoInitialRotation * Quaternion.FromAxisAngle(_gizmoAxis, angle); selectedEntityBase.Rotation = newRotation; UpdateSelectedEntity(false, selectedOnly: true, updateTextures: false); } } private void AlignSelectedEntityScale(EntityBase selectedEntityBase) { if (selectedEntityBase != null) { selectedEntityBase.Scale = SnapScale(selectedEntityBase.Scale); UpdateSelectedEntity(false, selectedOnly: true, updateTextures: false); } } private float SnapToGrid(float value) { var step = (double)gridSnapUpDown.Value; // Grid size of zero should not align at all. Also we want to avoid divide-by-zero. return step == 0 ? value : GeomMath.Snap(value, step); } private Vector3 SnapToGrid(Vector3 vector) { var step = (double)gridSnapUpDown.Value; // Grid size of zero should not align at all. Also we want to avoid divide-by-zero. return step == 0 ? vector : GeomMath.Snap(vector, step); } private float SnapAngle(float value) { var step = (double)angleSnapUpDown.Value * ((Math.PI * 2d) / 360d); // In units of 1 degree. // Snap of zero should not align at all. Also we want to avoid divide-by-zero. return step == 0 ? value : GeomMath.Snap(value, step); } private Vector3 SnapScale(Vector3 vector) { var step = (double)scaleSnapUpDown.Value; // Scale snap of zero should not align at all. Also we want to avoid divide-by-zero. return step == 0 ? vector : GeomMath.Snap(vector, step); } #endregion #region Prompts/SetColor private void PromptScan() { if (!Program.IsScanning) { EnterDialog(); try { // Write unsaved changes to the settings so that we don't lose them when writing scanner options to file. WriteSettings(Settings.Instance); var options = ScannerForm.Show(this); if (options != null) { _drawAllToVRAMAfterScan = options.DrawAllToVRAM; if (!Program.ScanAsync(options, OnScanProgressCallback)) { ShowMessageBox($"Directory/File not found: {options.Path}", "Scan Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } finally { LeaveDialog(); } } } private void PromptAdvancedSettings() { EnterDialog(); try { bool Validate(object obj, PropertyValueChangedEventArgs args) { var settings = (Settings)obj; settings.Validate(); return true; } // Write unsaved changes to the settings so that we don't lose them when reading them back. WriteSettings(Settings.Instance); // Use a clone of the settings so that changes can be cancelled. var clonedSettings = Settings.Instance.Clone(); if (AdvancedSettingsForm.Show(this, "Advanced Program Settings", clonedSettings, out var modified, validate: Validate)) { // User pressed Accept, and at least one property was modified if (modified) { Settings.Instance = clonedSettings; ReadSettings(Settings.Instance); UpdateSelectedEntity(); } // Always save changes to settings if user presses accept (similarly to how we do so with the scanner/export forms) if (Settings.ImplicitSave) { Settings.Instance.Save(); } } } finally { LeaveDialog(); } } private void PromptOutputFolder(Action<string> pathCallback) { // Use BeginInvoke so that dialog doesn't show up behind menu items... BeginInvoke((Action)(() => { EnterDialog(); try { // Don't use FolderBrowserDialog because it has the usability of a brick. using (var folderBrowserDialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog()) { folderBrowserDialog.IsFolderPicker = true; folderBrowserDialog.Title = "Select the output folder"; // Parameter name used to avoid overload resolution with WPF Window, which we don't have a reference to. if (folderBrowserDialog.ShowDialog(ownerWindowHandle: Handle) == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok) { pathCallback(folderBrowserDialog.FileName); return; } } pathCallback(null); //var fbd = new FolderBrowserDialog { Description = "Select the output folder" }; //var result = fbd.ShowDialog(this) == DialogResult.OK; //path = fbd.SelectedPath; //return result; } finally { LeaveDialog(); } })); } private bool PromptVRAMPage(string title, int? initialPage, out int pageIndex) { EnterDialog(); try { pageIndex = 0; var defaultText = (initialPage.HasValue && initialPage.Value != -1) ? initialPage.ToString() : null; var pageStr = InputDialog.Show(this, $"Please type in a VRAM Page index (0-{VRAM.PageCount-1})", title, defaultText); if (pageStr != null) { if (int.TryParse(pageStr, out pageIndex) && pageIndex >= 0 && pageIndex < VRAM.PageCount) { return true; // OK (valid page) } ShowMessageBox($"Please type in a valid VRAM Page index between 0 and {VRAM.PageCount-1}", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return false; // Canceled / OK (invalid page) } finally { LeaveDialog(); } } private bool PromptCLUTIndex(string title, int? initialIndex, out int clutIndex) { EnterDialog(); try { clutIndex = 0; var defaultText = (initialIndex.HasValue && initialIndex.Value != -1) ? initialIndex.ToString() : null; var pageStr = InputDialog.Show(this, $"Please type in a Palette index (0-255)", title, defaultText); if (pageStr != null) { if (int.TryParse(pageStr, out clutIndex) && clutIndex >= 0 && clutIndex < VRAM.PageCount) { return true; // OK (valid page) } ShowMessageBox($"Please type in a valid Palette index between 0 and 255", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return false; // Canceled / OK (invalid page) } finally { LeaveDialog(); } } private bool PromptColor(Color? initialColor, Color? defaultColor, out Color color) { EnterDialog(); try { using (var colorDialog = new ColorDialog()) { colorDialog.FullOpen = true; // Use dialog custom colors chosen by the user colorDialog.CustomColors = Settings.Instance.GetColorDialogCustomColors(defaultColor); if (initialColor.HasValue) { colorDialog.Color = initialColor.Value; } if (colorDialog.ShowDialog(this) == DialogResult.OK) { // Remember dialog custom colors chosen by the user Settings.Instance.SetColorDialogCustomColors(colorDialog.CustomColors); color = colorDialog.Color; return true; } // todo: Should we still update custom colors when cancelled? Settings.Instance.SetColorDialogCustomColors(colorDialog.CustomColors); } color = Color.Black; return false; } finally { LeaveDialog(); } } private void PromptExportModels(bool all) { // Get all models, checked models, or selected model if nothing is checked. var entities = all ? _rootEntities.ToArray() : GetCheckedEntities(true); #if DEBUG // Allow testing of export models form without needing to scan if (entities == null) { entities = new RootEntity[0]; } #else if (entities == null || entities.Length == 0) { var message = all ? "No models to export" : "No models checked or selected to export"; ShowMessageBox(message, "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } #endif var animations = GetCheckedAnimations(true); EnterDialog(); try { // Write unsaved changes to the settings so that we don't lose them when writing export options to file. WriteSettings(Settings.Instance); var options = ExportModelsForm.Show(this, entities, animations); if (options != null) { var exportedCount = ExportModelsForm.Export(options, entities, animations); ShowMessageBox($"{exportedCount} models exported", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Information); } } finally { LeaveDialog(); } } private void PromptExportTextures(bool all, bool vram, bool vramDrawnTo = false) { Texture[] textures; if (vram) { if (all && vramDrawnTo) { var drawnToTextures = new List<Texture>(); for (var i = 0; i < _vram.Count; i++) { if (_vram.IsPageUsed(i)) { drawnToTextures.Add(_vram[i]); } } textures = drawnToTextures.ToArray(); } else if (all) { textures = _vram.ToArray(); } else { textures = _vramSelectedPage != -1 ? new[] { _vram[_vramSelectedPage] } : null; } } else { if (all) { textures = _textures.ToArray(); } else { textures = GetSelectedTextures(); } } if (textures == null || textures.Length == 0) { string message; if (vram) { message = all ? "No drawn-to VRAM pages to export" : "No VRAM page selected to export"; } else { message = all ? "No textures to export" : "No textures selected to export"; } ShowMessageBox(message, "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } PromptOutputFolder(path => { if (path != null) { var pngExporter = new PNGExporter(); if (vram) { // Always number exported VRAM pages by their page number, not export index. foreach (var texture in textures) { pngExporter.Export(texture, $"vram{texture.TexturePage}", path); } ShowMessageBox($"{textures.Length} VRAM pages exported", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { pngExporter.Export(textures, path); ShowMessageBox($"{textures.Length} textures exported", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }); } private DialogResult ShowMessageBox(string text) { return ShowMessageBox(text, "PSXPrev"); } private DialogResult ShowMessageBox(string text, string title) { EnterDialog(); try { return MessageBox.Show(this, text, title); } finally { LeaveDialog(); } } private DialogResult ShowMessageBox(string text, string title, MessageBoxButtons buttons) { EnterDialog(); try { return MessageBox.Show(this, text, title, buttons); } finally { LeaveDialog(); } } private DialogResult ShowMessageBox(string text, string title, MessageBoxButtons buttons, MessageBoxIcon icon) { EnterDialog(); try { return MessageBox.Show(this, text, title, buttons, icon); } finally { LeaveDialog(); } } private DialogResult ShowMessageBox(string text, string title, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { EnterDialog(); try { return MessageBox.Show(this, text, title, buttons, icon, defaultButton); } finally { LeaveDialog(); } } private DialogResult ShowMessageBox(string text, string title, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { EnterDialog(); try { return MessageBox.Show(this, text, title, buttons, icon, defaultButton, options); } finally { LeaveDialog(); } } private void EnterDialog() { if (!_inDialog) { _inDialog = true; _mainWatch.Reset(); // Stop watch and use default time during the next Elapsed event } } private void LeaveDialog() { if (_inDialog) { _inDialog = false; } } private Bitmap DrawColorIcon(ref Bitmap bitmap, Color color) { if (bitmap == null) { bitmap = new Bitmap(16, 16); } using (var graphics = Graphics.FromImage(bitmap)) { #if false // Simple method just draws a solid 16x16 rectangle with color. graphics.Clear(color); #else // Fancy method uses a bitmap with a shadow, and draws a 14x14 rectangle // with a darkened outline, and the solid color within a 12x12 rectangle. graphics.CompositingMode = CompositingMode.SourceCopy; graphics.SmoothingMode = SmoothingMode.None; graphics.Clear(Color.Transparent); // Draw the background image that casts a shadow graphics.DrawImage(Properties.Resources.ColorBackground, 0, 0); // Draw the solid color box using (var brush = new SolidBrush(color)) { graphics.FillRectangle(brush, 2, 2, 12, 12); } // Draw the darkened color border (color is brightened if maximum channel is less than threshold) const float inc = 80f; const int threshold = 40; var brighten = Math.Max(color.R, Math.Max(color.G, color.B)) <= threshold; int BorderChannel(byte channel) { var c = channel + (brighten ? (inc * 1.25f) : -inc); return GeomMath.Clamp((int)c, 0, 255); } var borderColor = Color.FromArgb(BorderChannel(color.R), BorderChannel(color.G), BorderChannel(color.B)); using (var borderPen = new Pen(borderColor, 1f)) { graphics.DrawRectangle(borderPen, 1, 1, 14 - 1, 14 - 1); // -1 because size is inclusive for outlines } #endif } return bitmap; } private void SetAmbientColor(Color color) { _scene.AmbientColor = color; setAmbientColorToolStripMenuItem.Image = DrawColorIcon(ref _ambientColorBitmap, color); } private void SetBackgroundColor(Color color) { // Match background color for panels containing the GLControl to reduce flicker when switching tabs // Also helps for when hiding/showing side bar scenePreviewer.BackColor = color; animationPreviewer.BackColor = color; modelsPreviewSplitContainer.Panel2.BackColor = color; animationsPreviewSplitContainer.Panel2.BackColor = color; animationPreviewPanel.BackColor = color; //_glControl.BackColor = color; // Handled by ScenePreviewer controls _scene.ClearColor = color; setBackgroundColorToolStripMenuItem.Image = DrawColorIcon(ref _backgroundColorBitmap, color); } private void SetSolidWireframeVerticesColor(Color color) { _scene.SolidWireframeVerticesColor = color; setWireframeVerticesColorToolStripMenuItem.Image = DrawColorIcon(ref _wireframeVerticesColorBitmap, color); } private void SetMaskColor(Color color) { _scene.MaskColor = color; setMaskColorToolStripMenuItem.Image = DrawColorIcon(ref _maskColorBitmap, color); } private void setAmbientColorToolStripMenuItem_Click(object sender, EventArgs e) { if (PromptColor(_scene.AmbientColor, Settings.Defaults.AmbientColor, out var color)) { SetAmbientColor(color); } } private void setBackgroundColorToolStripMenuItem_Click(object sender, EventArgs e) { if (PromptColor(_scene.ClearColor, Settings.Defaults.BackgroundColor, out var color)) { SetBackgroundColor(color); } } private void setSolidWireframeVerticesColorToolStripMenuItem_Click(object sender, EventArgs e) { if (PromptColor(_scene.SolidWireframeVerticesColor, Settings.Defaults.SolidWireframeVerticesColor, out var color)) { SetSolidWireframeVerticesColor(color); } } private void setMaskColorToolStripMenuItem_Click(object sender, EventArgs e) { if (PromptColor(_scene.MaskColor, Settings.Defaults.MaskColor, out var color)) { SetMaskColor(color); } } private void exportSelectedModels_Click(object sender, EventArgs e) { PromptExportModels(false); } private void exportAllModels_Click(object sender, EventArgs e) { PromptExportModels(true); } private void exportSelectedTextures_Click(object sender, EventArgs e) { PromptExportTextures(false, false); } private void exportAllTextures_Click(object sender, EventArgs e) { PromptExportTextures(true, false); } private void exportSelectedVRAMPage_Click(object sender, EventArgs e) { PromptExportTextures(false, true); } private void exportDrawnToVRAMPages_Click(object sender, EventArgs e) { PromptExportTextures(true, true, vramDrawnTo: true); } private void exportAllVRAMPages_Click(object sender, EventArgs e) { PromptExportTextures(true, true); } #endregion #region Models private void SelectFirstEntity() { // Don't select the first model if we already have a selection. // Doing that would interrupt the user. if (entitiesTreeView.SelectedNode == null && _rootEntities.Count > 0) { SelectEntity(_rootEntities[0], true); // Select and focus } } private void SelectEntity(EntityBase entity, bool focus = false) { if (!focus) { _selectionSource = EntitySelectionSource.Click; } TreeNode newNode = null; if (entity is RootEntity rootEntity) { var rootIndex = _rootEntities.IndexOf(rootEntity); newNode = entitiesTreeView.Nodes[rootIndex]; } else if (entity != null) { if (entity.ParentEntity is RootEntity rootEntityFromSub) { var rootIndex = _rootEntities.IndexOf(rootEntityFromSub); var rootNode = entitiesTreeView.Nodes[rootIndex]; var subIndex = Array.IndexOf(rootEntityFromSub.ChildEntities, entity); var tagInfo = (EntitiesTreeViewTagInfo)rootNode.Tag; if (!tagInfo.LazyLoaded) { LoadEntityChildNodes(rootNode); } newNode = rootNode.Nodes[subIndex]; } } if (newNode != null && newNode == entitiesTreeView.SelectedNode) { // entitiesTreeView_AfterSelect won't be called. Reset the selection source. _selectionSource = EntitySelectionSource.None; if (entity != null) { UnselectTriangle(); } } else { entitiesTreeView.SelectedNode = newNode; } } private void SelectTriangle(Tuple<ModelEntity, Triangle> triangle) { if (_selectedTriangle?.Item2 != triangle?.Item2) { _selectedTriangle = triangle; UpdateSelectedTriangle(); UpdateModelPropertyGrid(); } } private void UnselectTriangle() { SelectTriangle(null); } private bool IsTriangleSelectMode() { return IsShiftDown; } private void UpdateSelectedEntity(bool updateMeshData = true, bool noDelayUpdatePropertyGrid = true, bool focus = false, bool fastSetup = false, bool selectedOnly = false, bool updateTextures = true) { _scene.BoundsBatch.Reset(1); var selectedEntityBase = GetSelectedEntityBase(); var rootEntity = GetSelectedRootEntity(); if (rootEntity != null) { rootEntity.ResetAnimationData(); if (_scene.AttachJointsMode == AttachJointsMode.Attach) { rootEntity.FixConnections(); } else { rootEntity.UnfixConnections(); } rootEntity.ComputeBounds(_scene.AttachJointsMode); } if (_showSkeleton) { _scene.SkeletonBatch.SetupEntitySkeleton(rootEntity, updateMeshData: updateMeshData); } if (selectedEntityBase != null) { _scene.BoundsBatch.BindEntityBounds(selectedEntityBase); var needsCheckedEntities = true; // (updateMeshData && updateTextures) || !selectedOnly || focus; var checkedEntities = needsCheckedEntities ? GetCheckedEntities() : null; if (updateMeshData && updateTextures) { if (_autoDrawModelTextures || _autoPackModelTextures) { if (_autoPackModelTextures) { // Check if the models being drawn have packed textures. If they do, // then we'll removed all current packed textures from VRAM to ensure we // have room for new ones. This is an ugly way to do it, but it's simple. var hasPacking = false; if (checkedEntities != null) { foreach (var checkedEntity in checkedEntities) { foreach (ModelEntity model in checkedEntity.ChildEntities) { if (model.NeedsTextureLookup) { hasPacking = true; break; } } if (hasPacking) { break; } } } if (rootEntity != null && !hasPacking) { foreach (ModelEntity model in rootEntity.ChildEntities) { if (model.NeedsTextureLookup) { hasPacking = true; break; } } } if (hasPacking) { // Packed textures found, clear existing ones from VRAM. RemoveAllPackedTexturesFromVRAM(updateSelectedEntity: false); } } if (_autoDrawModelTextures) { if (checkedEntities != null) { foreach (var checkedEntity in checkedEntities) { DrawModelTexturesToVRAM(rootEntity, _clutIndex, updateSelectedEntity: false); } } if (rootEntity != null) { // Selected entity gets drawing priority over checked entities. DrawModelTexturesToVRAM(rootEntity, _clutIndex, updateSelectedEntity: false); } } if (_autoPackModelTextures) { if (rootEntity != null) { // Selected entity gets packing priority over checked entities. AssignModelLookupTexturesAndPackInVRAM(rootEntity, true); } if (checkedEntities != null) { foreach (var checkedEntity in checkedEntities) { AssignModelLookupTexturesAndPackInVRAM(checkedEntity, true); } } _vram.UpdateAllPages(); } } if (checkedEntities != null) { foreach (var checkedEntity in checkedEntities) { AssignModelLookupTextures(checkedEntity); } } if (rootEntity != null) { AssignModelLookupTextures(rootEntity); } } // SubModelVisibility setting is not supported in the Animations tab. var subModelVisibility = _inAnimationTab ? SubModelVisibility.All : _subModelVisibility; /*if (selectedOnly) { _scene.MeshBatch.UpdateMultipleEntityBatch(_selectedRootEntity, _selectedModelEntity, updateMeshData, subModelVisibility: subModelVisibility, fastSetup: fastSetup); } else*/ { _scene.MeshBatch.SetupMultipleEntityBatch(checkedEntities, _selectedRootEntity, _selectedModelEntity, updateMeshData, subModelVisibility: subModelVisibility, fastSetup: fastSetup); } // todo: Ensure we focus when switching to a different root entity, even if the selected entity is a sub-model. if (focus) { if (_selectedModelEntity == null) { focus = _autoFocusOnRootModel; } else if (_selectedModelEntity != null) { focus = _autoFocusOnSubModel; } if (focus) { _scene.FocusOnBounds(GetFocusBounds(checkedEntities), resetRotation: _autoFocusResetCameraRotation); } } } else { _scene.ClearUnderMouseCycleLists(); _scene.MeshBatch.Reset(0); _selectedGizmo = GizmoId.None; _hoveredGizmo = GizmoId.None; } if (_selectionSource != EntitySelectionSource.Click) { _scene.DebugIntersectionsBatch.Reset(1); } UpdateSelectedTriangle(); UpdateModelPropertyGrid(noDelayUpdatePropertyGrid); UpdateGizmoVisualAndState(_selectedGizmo, _hoveredGizmo); _selectionSource = EntitySelectionSource.None; } private void UpdateSelectedTriangle(bool updateMeshData = true) { _scene.TriangleOutlineBatch.Reset(2); if (_selectedTriangle != null) { _scene.TriangleOutlineBatch.BindTriangleOutline(_selectedTriangle.Item1, _selectedTriangle.Item2); } else { // Fix it so that when a triangle is unselected, the cached list // (for selecting each triangle under the mouse) is reset. // Otherwise we end up picking the next triangle when the user isn't expecting it. _scene.ClearTriangleUnderMouseCycleList(); } } private void UpdateModelPropertyGrid(bool noDelay = true) { var propertyObject = _selectedTriangle?.Item2 ?? _selectedRootEntity ?? (object)_selectedModelEntity; if (noDelay || modelPropertyGrid.SelectedObject != propertyObject) { _modelPropertyGridRefreshDelayTimer.Reset(); modelPropertyGrid.SelectedObject = propertyObject; } else { // Delay updating the property grid to reduce lag. _modelPropertyGridRefreshDelayTimer.Start(); } } private void SetModelSelectionMode(EntitySelectionMode selectionMode, bool force = false) { if (force || _modelSelectionMode != selectionMode) { _modelSelectionMode = selectionMode; selectionModeNoneToolStripMenuItem.Checked = _modelSelectionMode == EntitySelectionMode.None; selectionModeBoundsToolStripMenuItem.Checked = _modelSelectionMode == EntitySelectionMode.Bounds; selectionModeTriangleToolStripMenuItem.Checked = _modelSelectionMode == EntitySelectionMode.Triangle; } } private void SetSubModelVisibility(SubModelVisibility visibility, bool force = false) { if (force || _subModelVisibility != visibility) { _subModelVisibility = visibility; subModelVisibilityAllToolStripMenuItem.Checked = _subModelVisibility == SubModelVisibility.All; subModelVisibilitySelectedToolStripMenuItem.Checked = _subModelVisibility == SubModelVisibility.Selected; subModelVisibilityWithSameTMDIDToolStripMenuItem.Checked = _subModelVisibility == SubModelVisibility.WithSameTMDID; UpdateSelectedEntity(selectedOnly: true, updateTextures: false); } } private BoundingBox GetFocusBounds(RootEntity[] checkedEntities) { var bounds = new BoundingBox(); var selectedRootEntity = GetSelectedRootEntity(); if (_autoFocusIncludeCheckedModels && checkedEntities != null) { foreach (var checkedEntity in checkedEntities) { if (checkedEntity == selectedRootEntity) { continue; // We'll add bounds for selectedRootEntity later on in the function. } bounds.AddBounds(checkedEntity.Bounds3D); } } if (selectedRootEntity != null) { if (_selectedModelEntity != null && (!_autoFocusIncludeWholeModel || _subModelVisibility != SubModelVisibility.All)) { IReadOnlyList<ModelEntity> models; if (!_autoFocusIncludeWholeModel || _subModelVisibility == SubModelVisibility.Selected) { models = new ModelEntity[] { _selectedModelEntity }; } else if (_subModelVisibility == SubModelVisibility.WithSameTMDID) { models = selectedRootEntity.GetModelsWithTMDID(_selectedModelEntity.TMDID); } else { models = new ModelEntity[0]; } foreach (var model in models) { if (model.Triangles.Length > 0 && (!model.AttachedOnly || _scene.AttachJointsMode != AttachJointsMode.Hide)) { bounds.AddBounds(model.Bounds3D); } } } else { bounds.AddBounds(selectedRootEntity.Bounds3D); } } if (!bounds.IsSet) { bounds.AddPoint(Vector3.Zero); } return bounds; } private void FixConnectionsForCheckedNode(TreeNode checkedNode) { // Fix connections for entities when checked // (but not if it's the selected entity, since that's handled by UpdateSelectedEntity) var tagInfo = (EntitiesTreeViewTagInfo)checkedNode.Tag; // todo: If we support checking things other than root entities, then we need to handle it here var rootEntity = tagInfo.Entity as RootEntity; var selectedRootEntity = GetSelectedRootEntity(); if (rootEntity != null && rootEntity != selectedRootEntity) { if (_scene.AttachJointsMode == AttachJointsMode.Attach) { rootEntity.FixConnections(); } else { rootEntity.UnfixConnections(); } } } private void entitiesTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) { var tagInfo = (EntitiesTreeViewTagInfo)e.Node.Tag; if (!tagInfo.LazyLoaded) { LoadEntityChildNodes(e.Node); } } private void entitiesTreeView_AfterSelect(object sender, TreeViewEventArgs e) { if (_selectionSource == EntitySelectionSource.None) { _selectionSource = EntitySelectionSource.TreeView; } var selectedNode = entitiesTreeView.SelectedNode; if (selectedNode != null) { var tagInfo = (EntitiesTreeViewTagInfo)selectedNode.Tag; _selectedRootEntity = tagInfo.Entity as RootEntity; _selectedModelEntity = tagInfo.Entity as ModelEntity; UnselectTriangle(); } var rootEntity = GetSelectedRootEntity(); UpdateSelectedEntity(focus: _selectionSource == EntitySelectionSource.TreeView); } private void entitiesTreeView_AfterCheck(object sender, TreeViewEventArgs e) { var checkedNode = e.Node; if (checkedNode != null) { FixConnectionsForCheckedNode(checkedNode); } if (!_busyChecking) { UpdateSelectedEntity(focus: _autoFocusIncludeCheckedModels); } } private void modelPropertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { var updateEntity = true; var updateMeshData = false; var updateTextures = false; var selectedOnly = true; var propertyName = e.ChangedItem.PropertyDescriptor.Name; var parentPropertyName = e.ChangedItem.Parent?.PropertyDescriptor?.Name; var parentParentPropertyName = e.ChangedItem.Parent?.Parent?.PropertyDescriptor?.Name; if (modelPropertyGrid.SelectedObject is EntityBase entityBase) { var modelEntity = entityBase as ModelEntity; var rootEntity = entityBase.GetRootEntity(); if (propertyName == nameof(ModelEntity.RenderFlags)) { var oldRenderFlags = (RenderFlags)e.OldValue; var newRenderFlags = (RenderFlags)e.ChangedItem.Value; // Check if any render flags have changed that require changes to mesh data var changedRenderFlags = (oldRenderFlags ^ newRenderFlags); if ((changedRenderFlags & (RenderFlags.Line | RenderFlags.Sprite | RenderFlags.SpriteNoPitch)) != 0) { updateMeshData = true; } } else if (propertyName == nameof(ModelEntity.PositionX)) { // We shouldn't be snapping when the change is made by the user //entityBase.PositionX = SnapToGrid(entityBase.PositionX); } else if (propertyName == nameof(ModelEntity.PositionY)) { // We shouldn't be snapping when the change is made by the user //entityBase.PositionY = SnapToGrid(entityBase.PositionY); } else if (propertyName == nameof(ModelEntity.PositionZ)) { // We shouldn't be snapping when the change is made by the user //entityBase.PositionZ = SnapToGrid(entityBase.PositionZ); } else if (propertyName == nameof(ModelEntity.TexturePage)) { // Update the texture associated with this model if (modelEntity != null) { _vram.AssignModelTextures(modelEntity); } updateMeshData = true; updateTextures = true; } else if (parentPropertyName == nameof(ModelEntity.TextureLookup) || parentParentPropertyName == nameof(ModelEntity.TextureLookup)) { updateMeshData = true; updateTextures = true; } else if (parentPropertyName == nameof(ModelEntity.Texture) || parentPropertyName == nameof(TextureLookup.Texture)) { updateMeshData = true; updateTextures = true; selectedOnly = false; // We modified a texture, and may need to modify the UVs in the mesh data } else if (propertyName == nameof(EntityBase.Name)) { updateEntity = false; // Updating TreeNodes can be extremely slow (before we fixed that), // and the property setter doesn't check if the value is the same. // So do the work ourselves and reduce some lag... WinForms moment. var entityNode = FindEntityNode(entityBase); if (entityNode != null && entityNode.Text != entityBase.Name) { entityNode.Text = entityBase.Name; } } else if (parentPropertyName == nameof(EntityBase.DebugData)) { updateEntity = false; } } else if (modelPropertyGrid.SelectedObject is Triangle triangle) { if (parentPropertyName == nameof(Triangle.DebugData)) { updateEntity = false; } } if (updateEntity) { // If updating textures, then we may need to update the UV coordinates of meshes UpdateSelectedEntity(updateMeshData, selectedOnly: selectedOnly, updateTextures: updateTextures, fastSetup: true); } } private void checkAllModelsToolStripMenuItem_Click(object sender, EventArgs e) { if (entitiesTreeView.Nodes.Count > CheckAllNodesWarningCount) { var result = ShowMessageBox($"You are about to check over {CheckAllNodesWarningCount} models. Displaying too many models may cause problems. Do you want to continue?", "Check All", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result != DialogResult.Yes) { return; } } entitiesTreeView.BeginUpdate(); _busyChecking = true; try { for (var i = 0; i < entitiesTreeView.Nodes.Count; i++) { var node = entitiesTreeView.Nodes[i]; node.Checked = true; } } finally { _busyChecking = false; entitiesTreeView.EndUpdate(); } UpdateSelectedEntity(focus: _autoFocusIncludeCheckedModels); // Checked entities have changed, which are included in UV drawing texturePreviewer.InvalidateUVs(); vramPreviewer.InvalidateUVs(); } private void uncheckAllModelsToolStripMenuItem_Click(object sender, EventArgs e) { entitiesTreeView.BeginUpdate(); _busyChecking = true; try { for (var i = 0; i < entitiesTreeView.Nodes.Count; i++) { var node = entitiesTreeView.Nodes[i]; node.Checked = false; } } finally { _busyChecking = false; entitiesTreeView.EndUpdate(); } UpdateSelectedEntity(focus: _autoFocusIncludeCheckedModels); // Checked entities have changed, which are included in UV drawing texturePreviewer.InvalidateUVs(); vramPreviewer.InvalidateUVs(); } private void resetWholeModelToolStripMenuItem_Click(object sender, EventArgs e) { var selectedRootEntity = GetSelectedRootEntity(); if (selectedRootEntity != null) { // This could be changed to only reset the selected model and its children. // But that's only necessary if sub-sub-model support is ever added. selectedRootEntity.ResetTransform(true); UpdateSelectedEntity(false, selectedOnly: true, updateTextures: false); } } private void resetSelectedModelToolStripMenuItem_Click(object sender, EventArgs e) { var selectedEntityBase = GetSelectedEntityBase(); if (selectedEntityBase != null) { selectedEntityBase.ResetTransform(false); UpdateSelectedEntity(false, selectedOnly: true, updateTextures: false); } } private void gizmoToolNoneToolStripMenuItem_Click(object sender, EventArgs e) { SetGizmoType(GizmoType.None); } private void gizmoToolTranslateToolStripMenuItem_Click(object sender, EventArgs e) { SetGizmoType(GizmoType.Translate); } private void gizmoToolRotateToolStripMenuItem_Click(object sender, EventArgs e) { SetGizmoType(GizmoType.Rotate); } private void gizmoToolScaleToolStripMenuItem_Click(object sender, EventArgs e) { SetGizmoType(GizmoType.Scale); } private void selectionModeNoneToolStripMenuItem_Click(object sender, EventArgs e) { SetModelSelectionMode(EntitySelectionMode.None); } private void selectionModeBoundsToolStripMenuItem_Click(object sender, EventArgs e) { SetModelSelectionMode(EntitySelectionMode.Bounds); } private void selectionModeTriangleToolStripMenuItem_Click(object sender, EventArgs e) { SetModelSelectionMode(EntitySelectionMode.Triangle); } private void drawModeFacesToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.DrawFaces = drawModeFacesToolStripMenuItem.Checked; } private void drawModeWireframeToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.DrawWireframe = drawModeWireframeToolStripMenuItem.Checked; UpdateDrawModeWireframeVertices(); } private void drawModeVerticesToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.DrawVertices = drawModeVerticesToolStripMenuItem.Checked; UpdateDrawModeWireframeVertices(); } private void drawModeSolidWireframeVerticesToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.DrawSolidWireframeVertices = drawModeSolidWireframeVerticesToolStripMenuItem.Checked; } private void UpdateDrawModeWireframeVertices() { // Suspend layout while changing visibility and text to avoid jittery movement of controls. sceneControlsFlowLayoutPanel.SuspendLayout(); wireframeVertexSizeFlowLayoutPanel.Visible = _scene.DrawWireframe || _scene.DrawVertices; wireframeSizeUpDown.Visible = _scene.DrawWireframe; vertexSizeUpDown.Visible = _scene.DrawVertices; if (_scene.DrawWireframe && _scene.DrawVertices) { wireframeVertexSizeLabel.Text = "Wireframe/Vertex Size:"; } else if (_scene.DrawWireframe) { wireframeVertexSizeLabel.Text = "Wireframe Size:"; } else if (_scene.DrawVertices) { wireframeVertexSizeLabel.Text = "Vertex Size:"; } sceneControlsFlowLayoutPanel.ResumeLayout(); sceneControlsFlowLayoutPanel.Refresh(); // Force controls to show/hide if the renderer is taking too long to paint } private void showBoundsToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.ShowBounds = showBoundsToolStripMenuItem.Checked; Redraw(); } private void showSkeletonToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _showSkeleton = showSkeletonToolStripMenuItem.Checked; if (!_showSkeleton) { _scene.SkeletonBatch.Reset(0); } else { var rootEntity = GetSelectedRootEntity(); _scene.SkeletonBatch.SetupEntitySkeleton(rootEntity, updateMeshData: true); } } private void enableLightToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.LightEnabled = enableLightToolStripMenuItem.Checked; Redraw(); } private void enableTexturesToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.TexturesEnabled = enableTexturesToolStripMenuItem.Checked; Redraw(); } private void enableVertexColorToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.VertexColorEnabled = enableVertexColorToolStripMenuItem.Checked; Redraw(); } private void enableSemiTransparencyToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.SemiTransparencyEnabled = enableSemiTransparencyToolStripMenuItem.Checked; Redraw(); } private void forceDoubleSidedToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.ForceDoubleSided = forceDoubleSidedToolStripMenuItem.Checked; Redraw(); } private void autoAttachLimbsToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { var oldHide = _scene.AttachJointsMode == AttachJointsMode.Hide; if (autoAttachLimbsToolStripMenuItem.Checked) { _scene.AttachJointsMode = AttachJointsMode.Attach; } else { _scene.AttachJointsMode = AttachJointsMode.Hide; } var newHide = _scene.AttachJointsMode == AttachJointsMode.Hide; var updateMeshData = (oldHide != newHide); // Update mesh data, since limb vertices may have changed UpdateSelectedEntity(updateMeshData: updateMeshData, updateTextures: false); } // These two events are for testing AttachJointsMode.DontAttach. We don't have a proper UI selection for it yet. private void autoAttachLimbsToolStripMenuItem_CheckStateChanged(object sender, EventArgs e) { /*var oldHide = _scene.AttachJointsMode == AttachJointsMode.Hide; switch (autoAttachLimbsToolStripMenuItem.CheckState) { case CheckState.Unchecked: _scene.AttachJointsMode = AttachJointsMode.Hide; break; case CheckState.Indeterminate: _scene.AttachJointsMode = AttachJointsMode.DontAttach; break; case CheckState.Checked: _scene.AttachJointsMode = AttachJointsMode.Attach; break; } var newHide = _scene.AttachJointsMode == AttachJointsMode.Hide; var updateMeshData = (oldHide != newHide); // Update mesh data, since limb vertices may have changed UpdateSelectedEntity(updateMeshData: updateMeshData, updateTextures: false);*/ } private void autoAttachLimbsToolStripMenuItem_Click(object sender, EventArgs e) { /*// Lazy solution to turn off CheckOnClick since this is just for debugging autoAttachLimbsToolStripMenuItem.CheckOnClick = false; switch (autoAttachLimbsToolStripMenuItem.CheckState) { case CheckState.Unchecked: autoAttachLimbsToolStripMenuItem.CheckState = CheckState.Indeterminate; break; case CheckState.Indeterminate: autoAttachLimbsToolStripMenuItem.CheckState = CheckState.Checked; break; case CheckState.Checked: autoAttachLimbsToolStripMenuItem.CheckState = CheckState.Unchecked; break; }*/ } private void subModelVisibilityAllToolStripMenuItem_Click(object sender, EventArgs e) { SetSubModelVisibility(SubModelVisibility.All); } private void subModelVisibilitySelectedToolStripMenuItem_Click(object sender, EventArgs e) { SetSubModelVisibility(SubModelVisibility.Selected); } private void subModelVisibilityWithSameTMDIDToolStripMenuItem_Click(object sender, EventArgs e) { SetSubModelVisibility(SubModelVisibility.WithSameTMDID); } private void autoFocusOnRootModelToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoFocusOnRootModel = autoFocusOnRootModelToolStripMenuItem.Checked; } private void autoFocusOnSubModelToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoFocusOnSubModel = autoFocusOnSubModelToolStripMenuItem.Checked; } private void autoFocusIncludeWholeModelToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoFocusIncludeWholeModel = autoFocusIncludeWholeModelToolStripMenuItem.Checked; } private void autoFocusIncludeCheckedModelsToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoFocusIncludeCheckedModels = autoFocusIncludeCheckedModelsToolStripMenuItem.Checked; } private void autoFocusResetCameraRotationToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoFocusResetCameraRotation = autoFocusResetCameraRotationToolStripMenuItem.Checked; } private void lineRendererToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.VibRibbonWireframe = lineRendererToolStripMenuItem.Checked; UpdateSelectedEntity(updateTextures: false); // Update mesh data, since vib ribbon redefines how mesh data is built. } private void UpdateLightDirection() { _scene.LightPitchYaw = new Vector2((float)lightPitchNumericUpDown.Value * GeomMath.Deg2Rad, (float)lightYawNumericUpDown.Value * GeomMath.Deg2Rad); } private void lightPitchNumericUpDown_ValueChanged(object sender, EventArgs e) { lightPitchNumericUpDown.Value = GeomMath.PositiveModulus(lightPitchNumericUpDown.Value, 360m); UpdateLightDirection(); lightPitchNumericUpDown.Refresh(); // Too slow to refresh number normally if using the arrow keys } private void lightYawNumericUpDown_ValueChanged(object sender, EventArgs e) { lightYawNumericUpDown.Value = GeomMath.PositiveModulus(lightYawNumericUpDown.Value, 360m); UpdateLightDirection(); lightYawNumericUpDown.Refresh(); // Too slow to refresh number normally if using the arrow keys } private void lightIntensityNumericUpDown_ValueChanged(object sender, EventArgs e) { _scene.LightIntensity = (float)lightIntensityNumericUpDown.Value; lightIntensityNumericUpDown.Refresh(); // Too slow to refresh number normally if using the arrow keys } private void gridSnapUpDown_ValueChanged(object sender, EventArgs e) { gridSnapUpDown.Refresh(); } private void angleSnapUpDown_ValueChanged(object sender, EventArgs e) { angleSnapUpDown.Refresh(); } private void scaleSnapUpDown_ValueChanged(object sender, EventArgs e) { scaleSnapUpDown.Refresh(); } private void vertexSizeUpDown_ValueChanged(object sender, EventArgs e) { _scene.VertexSize = (float)vertexSizeUpDown.Value; vertexSizeUpDown.Refresh(); // Too slow to refresh number normally if using the arrow keys } private void wireframeSizeUpDown_ValueChanged(object sender, EventArgs e) { _scene.WireframeSize = (float)wireframeSizeUpDown.Value; wireframeSizeUpDown.Refresh(); // Too slow to refresh number normally if using the arrow keys } private void cameraFOVUpDown_ValueChanged(object sender, EventArgs e) { _scene.CameraFOV = (float)cameraFOVUpDown.Value;// * GeomMath.Deg2Rad; cameraFOVUpDown.Refresh(); // Too slow to refresh number normally if using the arrow keys } #endregion #region Textures/VRAM private int AssignModelLookupTextures(RootEntity rootEntity) { var locateFailedCount = 0; foreach (ModelEntity model in rootEntity.ChildEntities) { if (!AssignModelLookupTextures(model)) { locateFailedCount++; } } return locateFailedCount; } private bool AssignModelLookupTextures(ModelEntity model) { if (!model.NeedsTextureLookup) { return true; } model.TexturePage = 0; model.TextureLookup.Texture = null; _vram.AssignModelTextures(model); var expectedFormat = model.TextureLookup.ExpectedFormat; var id = model.TextureLookup.ID; if (!id.HasValue) { return false; } Texture found = null; foreach (var texture in _packedTextures) { if (!texture.LookupID.HasValue) { continue; // This could be changed by the user in the property grid } if (!string.IsNullOrEmpty(expectedFormat)) { if (texture.FormatName == null || texture.FormatName != expectedFormat) { continue; } } if (texture.LookupID.Value == id) { found = texture; break; } else if (_fallbackTextureID.HasValue && texture.LookupID.Value == _fallbackTextureID.Value) { found = texture; // Keep looking for the real texture } } if (found != null) { var texture = found; model.TexturePage = (uint)texture.TexturePage; model.TextureLookup.Texture = texture; _vram.AssignModelTextures(model); return true; } return false; } private int AssignModelLookupTexturesAndPackInVRAM(RootEntity rootEntity, bool suppressUpdate = false) { var locateOrPackFailedCount = 0; foreach (ModelEntity model in rootEntity.ChildEntities) { if (!AssignModelLookupTexturesAndPackInVRAM(model, suppressUpdate)) { locateOrPackFailedCount++; } } return locateOrPackFailedCount; } private bool AssignModelLookupTexturesAndPackInVRAM(ModelEntity model, bool suppressUpdate = false) { if (!model.NeedsTextureLookup) { return true; } model.TexturePage = 0; model.TextureLookup.Texture = null; _vram.AssignModelTextures(model); var expectedFormat = model.TextureLookup.ExpectedFormat; var id = model.TextureLookup.ID; if (!id.HasValue) { return false; } Texture found = null; foreach (var texture in _textures) { if (!texture.NeedsPacking) { continue; // This isn't a locatable texture } if (!string.IsNullOrEmpty(expectedFormat)) { if (texture.FormatName == null || texture.FormatName != expectedFormat) { continue; } } if (texture.LookupID.Value == id) { found = texture; break; } else if (_fallbackTextureID.HasValue && texture.LookupID.Value == _fallbackTextureID.Value) { found = texture; // Keep looking for the real texture } } if (found != null) { var texture = found; if (texture.IsPacked) { model.TexturePage = (uint)texture.TexturePage; model.TextureLookup.Texture = texture; _vram.AssignModelTextures(model); return true; } else if (PackTextureInVRAM(texture)) { _vram.DrawTexture(texture, suppressUpdate); model.TexturePage = (uint)texture.TexturePage; model.TextureLookup.Texture = texture; _vram.AssignModelTextures(model); return true; } // Failed to pack texture } return false; } // Returns number of textures that could not be packed private int DrawTexturesToVRAM(IEnumerable<Texture> textures, int? clutIndex, bool updateSelectedEntity = true) { var packedChanged = false; var packFailedCount = 0; foreach (var texture in textures) { // Textures that need packing must find a location to pack first if (texture.NeedsPacking) { if (texture.IsPacked) { continue; // Texture is already drawn } if (!PackTextureInVRAM(texture)) { packFailedCount++; continue; // No place to pack this texture, can't draw } packedChanged = true; } var oldClutIndex = texture.CLUTIndex; if (clutIndex.HasValue && texture.CLUTCount > 1) { texture.SetCLUTIndex(clutIndex.Value); } _vram.DrawTexture(texture, true); // Suppress updates to scene until all textures are drawn. if (clutIndex.HasValue && texture.CLUTCount > 1) { texture.SetCLUTIndex(oldClutIndex); } } if (_vram.UpdateAllPages()) // True if any pages needed to be updated (aka textures wasn't empty) { vramPreviewer.InvalidateTexture(); // Invalidate to make sure we redraw. UpdateVRAMComboBoxPageItems(); } if (packedChanged && updateSelectedEntity) { UpdateSelectedEntity(); } return packFailedCount; } private int DrawModelTexturesToVRAM(RootEntity rootEntity, int? clutIndex, bool updateSelectedEntity = true) { // Note: We can't just use ModelEntity.Texture, since that just points to the VRAM page. return DrawTexturesToVRAM(rootEntity.OwnedTextures, clutIndex, updateSelectedEntity); } private bool PackTextureInVRAM(Texture texture) { if (!texture.NeedsPacking || texture.IsPacked) { return true; } if (_vram.FindPackLocation(texture, out var packPage, out var packX, out var packY)) { texture.IsPacked = true; texture.TexturePage = packPage; texture.X = packX; texture.Y = packY; _packedTextures.Add(texture); return true; } return false; } private void ClearVRAMPage(int index, bool updateSelectedEntity = true) { var packedChanged = false; _vram.ClearPage(index); for (var i = 0; i < _packedTextures.Count; i++) { var texture = _packedTextures[i]; if (texture.TexturePage == index) { packedChanged = true; texture.IsPacked = false; texture.TexturePage = 0; texture.X = 0; texture.Y = 0; _packedTextures.RemoveAt(i); i--; } } vramPreviewer.InvalidateTexture(); // Invalidate to make sure we redraw. UpdateVRAMComboBoxPageItems(); if (packedChanged && updateSelectedEntity) { UpdateSelectedEntity(); } } private void ClearAllVRAMPages(bool updateSelectedEntity = true) { var packedChanged = _packedTextures.Count > 0; _vram.ClearAllPages(); foreach (var texture in _packedTextures) { texture.IsPacked = false; texture.TexturePage = 0; texture.X = 0; texture.Y = 0; } _packedTextures.Clear(); vramPreviewer.InvalidateTexture(); // Invalidate to make sure we redraw. UpdateVRAMComboBoxPageItems(); if (packedChanged && updateSelectedEntity) { UpdateSelectedEntity(); } } private void RemoveAllPackedTexturesFromVRAM(bool updateSelectedEntity = true) { var packedChanged = _packedTextures.Count > 0; foreach (var texture in _packedTextures) { _vram.RemoveTexturePacking(texture); texture.IsPacked = false; texture.TexturePage = 0; texture.X = 0; texture.Y = 0; } _packedTextures.Clear(); vramPreviewer.InvalidateTexture(); // Invalidate to make sure we redraw. UpdateVRAMComboBoxPageItems(); if (packedChanged && updateSelectedEntity) { UpdateSelectedEntity(); } } private void SetCurrentCLUTIndex(int clutIndex) { _clutIndex = GeomMath.Clamp(clutIndex, 0, 255); foreach (var texture in _textures) { texture.SetCLUTIndex(_clutIndex); } setPaletteIndexToolStripMenuItem.Text = $"Set CLUT Index: {_clutIndex}"; // Refresh texture thumbnails, texture preview, and property grid texturesListView.Invalidate(); texturePreviewer.InvalidateTexture(); // Invalidate to make sure we redraw. texturePropertyGrid.SelectedObject = texturePropertyGrid.SelectedObject; } private static int CompareTexturesListViewItems(ImageListViewItem a, ImageListViewItem b) { var tagInfoA = (TexturesListViewTagInfo)a.Tag; var tagInfoB = (TexturesListViewTagInfo)b.Tag; return tagInfoA.Index.CompareTo(tagInfoB.Index); } private void UpdateVRAMComboBoxPageItems() { // Mark page numbers that have had textures drawn to them. // note: This assumes the combo box items are strings, which they currently are. for (var i = 0; i < _vram.Count; i++) { var used = _vram.IsPageUsed(i); vramListBox.Items[i] = $"{i}" + (used ? " (drawn to)" : string.Empty); } } private void texturesListView_SelectedIndexChanged(object sender, EventArgs e) { // Don't use SelectedItems.Count since it enumerates over all items. But... // We can't use most Linq functions with SelectedItems because key IList interface methods are not supported. if (texturesListView.SelectedItems.Count != 1) { // Only show a texture in the property grid if exactly one item is selected. texturePropertyGrid.SelectedObject = null; return; } var texture = GetSelectedTexture(); if (texture == null) { return; } texturePreviewer.Texture = texture; texturePropertyGrid.SelectedObject = texture; } private void texturePropertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { var updateEntities = false; var updateMeshData = false; var updateTextures = false; var propertyName = e.ChangedItem.PropertyDescriptor.Name; var parentPropertyName = e.ChangedItem.Parent?.PropertyDescriptor?.Name; //var parentParentPropertyName = e.ChangedItem.Parent?.Parent?.PropertyDescriptor?.Name; // Validate changes to texture properties. if (texturePropertyGrid.SelectedObject is Texture texture) { if (propertyName == nameof(Texture.X)) { if (!texture.IsPacked) { texture.X = VRAM.ClampTextureX(texture.X); texturePreviewer.InvalidateUVs(); // Offset of UV lines has changed } else { texture.X = (int)e.OldValue; // Can't changed value used to determine packing } } else if (propertyName == nameof(Texture.Y)) { if (!texture.IsPacked) { texture.Y = VRAM.ClampTextureY(texture.Y); texturePreviewer.InvalidateUVs(); // Offset of UV lines has changed } else { texture.Y = (int)e.OldValue; // Can't changed value used to determine packing } } else if (propertyName == nameof(Texture.TexturePage)) { if (!texture.IsPacked) { texture.TexturePage = VRAM.ClampTexturePage(texture.TexturePage); texturePreviewer.InvalidateUVs(); // Set of UV lines has changed } else { texture.TexturePage = (int)e.OldValue; // Can't changed value used to determine packing } } else if (propertyName == nameof(Texture.CLUTIndex)) { texture.CLUTIndex = GeomMath.Clamp(texture.CLUTIndex, 0, Math.Max(0, texture.CLUTCount - 1)); texture.SetCLUTIndex(texture.CLUTIndex, force: true); texturePreviewer.InvalidateTexture(); // Invalidate to make sure we redraw. } else if (propertyName == nameof(Texture.Name)) { // Update changes to Name property in ListViewItem. // Don't use SelectedItems.Count since it enumerates over all items. But... // We can't use most Linq functions with SelectedItems because key IList interface methods are not supported. var selectedItems = texturesListView.SelectedItems; var selectedItem = selectedItems.Count > 0 ? selectedItems[0] : null; var tagInfo = (TexturesListViewTagInfo)selectedItem?.Tag; if (selectedItem == null || _textures[tagInfo.Index] != texture) { // The selected item differs from the property grid's selected object, find the associated item selectedItem = null; foreach (var item in texturesListView.Items) { tagInfo = (TexturesListViewTagInfo)item.Tag; if (_textures[tagInfo.Index] == texture) { selectedItem = item; break; } } } if (selectedItem != null && selectedItem.Text != texture.Name) { selectedItem.Text = texture.Name; } } } } private void drawSelectedToVRAM_Click(object sender, EventArgs e) { // Don't use SelectedItems.Count since it enumerates over all items. var selectedTextures = GetSelectedTextures(); if (selectedTextures == null || selectedTextures.Length == 0) { ShowMessageBox("Select textures to draw to VRAM first", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var packFailedCount = DrawTexturesToVRAM(selectedTextures, null); // Null to draw selected textures of any clut index WarnPackFailedCount(packFailedCount); } private void drawAllToVRAM_Click(object sender, EventArgs e) { var packFailedCount = DrawTexturesToVRAM(_textures, _clutIndex); WarnPackFailedCount(packFailedCount); } private void WarnPackFailedCount(int packFailedCount) { if (packFailedCount > 0) { ShowMessageBox($"Not enough room to pack remaining {packFailedCount} textures.\nTry clearing VRAM pages first.", "Packing Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void findTextureByVRAMPage_Click(object sender, EventArgs e) { if (PromptVRAMPage("Find by Page", null, out var pageIndex)) { var found = 0; foreach (var item in texturesListView.Items) { var tagInfo = (TexturesListViewTagInfo)item.Tag; tagInfo.Found = false; var texture = _textures[tagInfo.Index]; if (texture.TexturePage == pageIndex) { tagInfo.Found = true; // Mark as found so the grouper will add it to the "Found" group found++; } } texturesListView.GroupColumn = found > 0 ? 0 : 1; // Set primary group to "Found" (only if any items were found) texturesListView.Sort(); // Sort items added to "Found" group (is this necessary?) ShowMessageBox(found > 0 ? $"Found {found} items" : "Nothing found", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void clearTextureFindResults_Click(object sender, EventArgs e) { foreach (var item in texturesListView.Items) { var tagInfo = (TexturesListViewTagInfo)item.Tag; tagInfo.Found = false; // Unmark found so the grouper will return it to the "Textures" group } texturesListView.GroupColumn = 1; // Set primary group back to "Textures" texturesListView.Sort(); // Re-sort now that "Found" group has been merged back with "Textures" group ShowMessageBox("Results cleared", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void setPaletteIndexToolStripMenuItem_Click(object sender, EventArgs e) { if (PromptCLUTIndex("Change CLUT Index", _clutIndex, out var newCLUTIndex)) { if (_clutIndex != newCLUTIndex) { SetCurrentCLUTIndex(newCLUTIndex); } } } private void vramComboBox_SelectedIndexChanged(object sender, EventArgs e) { var index = vramListBox.SelectedIndex; if (index >= 0 && index != _vramSelectedPage) { _vramSelectedPage = index; vramPreviewer.Texture = _vram[_vramSelectedPage]; } } private void gotoVRAMPageButton_Click(object sender, EventArgs e) { if (PromptVRAMPage("Go to VRAM Page", _vramSelectedPage, out var pageIndex)) { vramListBox.SelectedIndex = pageIndex; } } private void clearVRAMPage_Click(object sender, EventArgs e) { if (_vramSelectedPage < 0) { ShowMessageBox("Select a page first", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } ClearVRAMPage(_vramSelectedPage); } private void clearAllVRAMPages_Click(object sender, EventArgs e) { ClearAllVRAMPages(); } private void showTexturePaletteToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { texturePreviewer.ShowPalette = showTexturePaletteToolStripMenuItem.Checked; } private void showTextureSemiTransparencyToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { texturePreviewer.ShowSemiTransparency = showTextureSemiTransparencyToolStripMenuItem.Checked; } private void showTextureUVsToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { texturePreviewer.ShowUVs = showTextureUVsToolStripMenuItem.Checked; } private void showMissingTexturesToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _scene.ShowMissingTextures = showMissingTexturesToolStripMenuItem.Checked; } private void autoDrawModelTexturesToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoDrawModelTextures = autoDrawModelTexturesToolStripMenuItem.Checked; } private void autoPackModelTexturesToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoPackModelTextures = autoPackModelTexturesToolStripMenuItem.Checked; } private void showVRAMSemiTransparencyToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { vramPreviewer.ShowSemiTransparency = showVRAMSemiTransparencyToolStripMenuItem.Checked; } private void showVRAMUVsToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { vramPreviewer.ShowUVs = showVRAMUVsToolStripMenuItem.Checked; } #endregion #region Animations private void UpdateSelectedAnimation(bool play = false) { var propertyObject = _curAnimationFrame ?? _curAnimationObject ?? (object)_curAnimation; // Change Playing after Enabled, so that the call to Refresh in Playing will affect the enabled visual style too. animationPlayButton.Enabled = (_curAnimation != null); Playing = play; var rootEntity = GetSelectedRootEntity(); animationPropertyGrid.SelectedObject = propertyObject; _animationBatch.SetupAnimationBatch(_curAnimation); if (_curAnimation != null) { _animationBatch.SetupAnimationFrame(rootEntity, force: true); } //_scene.MeshBatch.UpdateMultipleEntityBatch(_selectedRootEntity, _selectedModelEntity, true, fastSetup: false); _scene.MeshBatch.SetupMultipleEntityBatch(GetCheckedEntities(), _selectedRootEntity, _selectedModelEntity, true, fastSetup: false); if (_showSkeleton) { if (rootEntity != null) { _scene.SkeletonBatch.SetupEntitySkeleton(rootEntity, updateMeshData: true); } } UpdateAnimationProgressLabel(); } private void UpdateAnimationProgressLabel(bool noDelay = true) { if (noDelay) { _animationProgressBarRefreshDelayTimer.Reset(); // Display max can be shown as 0, even if we require a minimum of 1 internally. var displayMax = (int)GeomMath.Clamp(_animationBatch.FrameCount, 0, int.MaxValue); var displayValue = (int)GeomMath.Clamp(_animationBatch.CurrentFrameTime, 0, int.MaxValue); var newMax = (int)GeomMath.Clamp(_animationBatch.FrameCount * AnimationProgressPrecision, 1, int.MaxValue); var newValue = (int)GeomMath.Clamp(_animationBatch.CurrentFrameTime * AnimationProgressPrecision, 0, int.MaxValue); animationProgressLabel.Text = $"{displayValue}/{displayMax}"; if (newMax != animationFrameTrackBar.Maximum || newValue != animationFrameTrackBar.Value) { animationFrameTrackBar.Maximum = newMax; animationFrameTrackBar.SetValueSafe(newValue); animationFrameTrackBar.Refresh(); animationProgressLabel.Refresh(); } } else { _animationProgressBarRefreshDelayTimer.Start(); } } private void animationsTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) { var tagInfo = (AnimationsTreeViewTagInfo)e.Node.Tag; if (!tagInfo.LazyLoaded) { LoadAnimationChildNodes(e.Node); } } private void animationsTreeView_AfterSelect(object sender, TreeViewEventArgs e) { var selectedNode = animationsTreeView.SelectedNode; if (selectedNode == null) { UpdateSelectedEntity(); return; } var tagInfo = (AnimationsTreeViewTagInfo)selectedNode.Tag; if (tagInfo.Animation != null) { _curAnimation = tagInfo.Animation; _curAnimationObject = null; _curAnimationFrame = null; } else if (tagInfo.AnimationObject != null) { _curAnimation = tagInfo.AnimationObject.Animation; _curAnimationObject = tagInfo.AnimationObject; _curAnimationFrame = null; } else if (tagInfo.AnimationFrame != null) { _curAnimation = tagInfo.AnimationFrame.AnimationObject.Animation; _curAnimationObject = tagInfo.AnimationFrame.AnimationObject; _curAnimationFrame = tagInfo.AnimationFrame; } if (_autoSelectAnimationModel && _curAnimation.OwnerEntity != null) { SelectEntity(_curAnimation.OwnerEntity, true); } else { UpdateSelectedEntity(); } UpdateSelectedAnimation(_autoPlayAnimations); if (_curAnimationFrame != null) { _animationBatch.SetTimeToFrame(_curAnimationFrame); UpdateAnimationProgressLabel(); } if (TMDBindingsForm.IsVisible && _curAnimation != null) { TMDBindingsForm.ShowTool(this, _curAnimation); } } private void animationPropertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { var propertyName = e.ChangedItem.PropertyDescriptor.Name; var parentPropertyName = e.ChangedItem.Parent?.PropertyDescriptor?.Name; var parentParentPropertyName = e.ChangedItem.Parent?.Parent?.PropertyDescriptor?.Name; if (animationPropertyGrid.SelectedObject is Animation animation) { if (propertyName == nameof(Animation.Name)) { var animationNode = FindAnimationNode(animation); if (animationNode != null && animationNode.Text != animation.Name) { animationNode.Text = animation.Name; } } } else if (animationPropertyGrid.SelectedObject is AnimationObject animationObject) { } else if (animationPropertyGrid.SelectedObject is AnimationFrame animationFrame) { } // Restart animation to force invalidate. _animationBatch.Restart(); // todo: Can we remove this? UpdateSelectedEntity(updateTextures: false); UpdateSelectedAnimation(); } private void animationPlayButton_Click(object sender, EventArgs e) { Playing = !Playing; } private void animationFrameTrackBar_Scroll(object sender, EventArgs e) { if (_inAnimationTab && !Playing) { var value = (double)animationFrameTrackBar.Value; // Sanity check that max is less than intmax, if it isn't, then we aren't using progress precision. if (IsShiftDown && animationFrameTrackBar.Maximum < int.MaxValue) { // Hold shift down to reduce precision to individual frames value = GeomMath.Snap(value, AnimationProgressPrecision); } var delta = value / animationFrameTrackBar.Maximum; _animationBatch.FrameTime = delta * _animationBatch.FrameCount; UpdateAnimationProgressLabel(); } } private void animationSpeedNumericUpDown_ValueChanged(object sender, EventArgs e) { _animationSpeed = (float)animationSpeedNumericUpDown.Value; } private void animationLoopModeComboBox_SelectedIndexChanged(object sender, EventArgs e) { var index = animationLoopModeComboBox.SelectedIndex; if (index >= 0) { _animationBatch.LoopMode = (AnimationLoopMode)index; } } private void animationReverseCheckBox_CheckedChanged(object sender, EventArgs e) { _animationBatch.Reverse = animationReverseCheckBox.Checked; } private void checkAllAnimationsToolStripMenuItem_Click(object sender, EventArgs e) { animationsTreeView.BeginUpdate(); _busyChecking = true; try { for (var i = 0; i < animationsTreeView.Nodes.Count; i++) { var node = animationsTreeView.Nodes[i]; node.Checked = true; } } finally { _busyChecking = false; animationsTreeView.EndUpdate(); } } private void uncheckAllAnimationsToolStripMenuItem_Click(object sender, EventArgs e) { animationsTreeView.BeginUpdate(); _busyChecking = true; try { for (var i = 0; i < animationsTreeView.Nodes.Count; i++) { var node = animationsTreeView.Nodes[i]; node.Checked = false; } } finally { _busyChecking = false; animationsTreeView.EndUpdate(); } } private void autoPlayAnimationsToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoPlayAnimations = autoPlayAnimationsToolStripMenuItem.Checked; } private void autoSelectAnimationModelToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { _autoSelectAnimationModel = autoSelectAnimationModelToolStripMenuItem.Checked; } private void showTMDBindingsToolStripMenuItem_Click(object sender, EventArgs e) { if (_curAnimation == null) { ShowMessageBox("Please select an Animation first", "PSXPrev", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { TMDBindingsForm.ShowTool(this, _curAnimation); } } #endregion #region File/Help private void startScanToolStripMenuItem_Click(object sender, EventArgs e) { PromptScan(); } private void clearScanResultsToolStripMenuItem_Click(object sender, EventArgs e) { if (!Program.IsScanning && (_rootEntities.Count > 0 || _textures.Count > 0 || _animations.Count > 0)) { var result = ShowMessageBox("Are you sure you want to clear scan results?", "Clear Scan Results", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.Yes) { ClearScanResults(); } } } private void pauseScanningToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { if (Program.IsScanning && !Program.IsScanCanceling) { var paused = Program.PauseScan(pauseScanningToolStripMenuItem.Checked); statusMessageLabel.Text = "Scan " + (paused ? "Paused" : "Resumed"); } } private void stopScanningToolStripMenuItem_Click(object sender, EventArgs e) { if (Program.IsScanning && !Program.IsScanCanceling) { var result = ShowMessageBox("Are you sure you want to cancel the current scan?", "Stop Scanning", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { var canceled = Program.CancelScan(); if (canceled) { pauseScanningToolStripMenuItem.Checked = false; pauseScanningToolStripMenuItem.Enabled = false; stopScanningToolStripMenuItem.Enabled = false; } } } } private void showFPSToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { UpdateFPSLabel(); } private void showModelsStatusBarToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { UpdatePreviewerParents(); // This method also updates status bar visibility } private void showSideBarToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { // No need to update side-bar if UI is hidden, since it won't be shown regardless if (showUIToolStripMenuItem.Checked) { UpdateShowUIVisibility(false); } } private void showUIToolStripMenuItem_CheckedChanged(object sender, EventArgs e) { UpdateShowUIVisibility(true); } private void defaultSettingsToolStripMenuItem_Click(object sender, EventArgs e) { var result = ShowMessageBox("Are you sure you want to reset settings to their default values?", "Reset Settings", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { LoadDefaultSettings(); } } private void loadSettingsToolStripMenuItem_Click(object sender, EventArgs e) { var result = ShowMessageBox("Are you sure you want to reload settings from file?", "Reload Settings", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { LoadSettings(); } } private void saveSettingsToolStripMenuItem_Click(object sender, EventArgs e) { SaveSettings(); } private void advancedSettingsToolStripMenuItem_Click(object sender, EventArgs e) { PromptAdvancedSettings(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { var result = ShowMessageBox("Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { Application.Exit(); } } private void videoTutorialToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start("https://www.youtube.com/watch?v=hPDa8l3ZE6U"); } private void compatibilityListToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start("https://docs.google.com/spreadsheets/d/155pUzwl7CC14ssT0PJkaEA53CS1ijpOV04VitQCVBC4/edit?pli=1#gid=22642205"); } private void viewOnGitHubToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start("https://github.com/rickomax/psxprev"); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { // Don't bother showing joints limit if it's high enough to never be a problem var maxJointsStr = Shader.MaxJoints <= 2048 ? $", max: {Shader.MaxJoints}" : string.Empty; var jointsSupportStr = Shader.JointsSupported ? $"Shader-time joints{maxJointsStr}" : "Pre-computed joints"; var message = "PSXPrev - PlayStation (PSX) Files Previewer/Extractor\n" + "\u00a9 PSXPrev Contributors - 2020-2023\n" + $"Program Version {GetVersionString()}\n" + $"GLSL Version {Shader.GLSLVersion} ({jointsSupportStr})\n" + #if ENABLE_CLIPBOARD "Clipboard Support Enabled" #else "Clipboard Support Disabled" #endif ; ShowMessageBox(message, "About", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion #region Testing // Create models that are used to test renderer/builder functionality. // Uncomment return; before committing. private void SetupTestModels() { return; SetupTestSpriteTransformModels(); SelectFirstEntity(); } // Testing for sprites that have model transforms applied, along with confirming normal transforms are correct. private void SetupTestSpriteTransformModels() { var size = 40; var center = new Vector3(size * 3, 0f, 0f); var triBuilder = new TriangleMeshBuilder { RenderFlags = /*RenderFlags.Unlit |*/ RenderFlags.Sprite,// | RenderFlags.DoubleSided, SpriteCenter = center, }; /*var vertex0 = center + new Vector3(-size, size, 0f); var vertex1 = center + new Vector3( size, size, 0f); var vertex2 = center + new Vector3(-size, -size, 0f); var vertex3 = center + new Vector3( size, -size, 0f);*/ //triBuilder.AddQuad(vertex0, vertex1, vertex2, vertex3, // Color3.Red, Color3.Green, Color3.Blue, Color3.Yellow); triBuilder.AddSprite(center, new Vector2(size), Color3.Red, Color3.Green, Color3.Blue, Color3.Yellow); var model0 = triBuilder.CreateModelEntity(Matrix4.CreateTranslation(center * -2)); triBuilder.Clear(); triBuilder.RenderFlags &= ~(RenderFlags.Sprite | RenderFlags.SpriteNoPitch); triBuilder.AddOctaSphere(Vector3.Zero, size / 5, 4, true, Color3.Purple); //triBuilder.AddSphere(Vector3.Zero, size / 5, 16, 8, true, Color3.Purple); var model1 = triBuilder.CreateModelEntity(); AddRootEntity(new RootEntity { Name = "Sprite", ChildEntities = new[] { model0, model1 }, OriginalLocalMatrix = Matrix4.CreateRotationY(45f * GeomMath.Deg2Rad) * Matrix4.CreateTranslation(0f, 70f, -30f), }); } #endregion #region Helper Types private enum MouseEventType { Down, Up, Move, Wheel, } private enum KeyEventType { Down, Up, } private enum EntitySelectionSource { None, TreeView, Click, } private class EntitiesTreeViewTagInfo { public EntityBase Entity { get; set; } public int RootIndex { get; set; } public int ChildIndex { get; set; } = -1; public bool IsRoot => ChildIndex == -1; public bool LazyLoaded { get; set; } // True if child nodes have been added } private class AnimationsTreeViewTagInfo { public Animation Animation { get; set; } public AnimationObject AnimationObject { get; set; } public AnimationFrame AnimationFrame { get; set; } public int RootIndex { get; set; } public int ChildIndex { get; set; } = -1; public bool IsRoot => ChildIndex == -1; public bool LazyLoaded { get; set; } // True if child nodes have been added } private class TexturesListViewTagInfo { //public Texture Texture { get; set; } // We need to store index because ImageListViewItem.Index does not represent the original index. public int Index { get; set; } public bool Found { get; set; } // Search results flag } private class TexturesListViewGrouper : ImageListView.IGrouper { public ImageListView.GroupInfo GetGroupInfo(ImageListViewItem item) { var tagInfo = (TexturesListViewTagInfo)item.Tag; var name = tagInfo.Found ? "Found" : "Textures"; // Name ID of group var order = tagInfo.Found ? 0 : 1; // Index of group return new ImageListView.GroupInfo(name, order); } } // We need a custom adaptor to assign the image associated with the ImageListViewItem. // The default adaptor assumes the image is in the filesystem (which it's not), // and there's no way to refresh the image thumbnail if we don't use this class. private class TexturesListViewItemAdaptor : ImageListView.ImageListViewItemAdaptor { private static readonly Utility.Tuple<ColumnType, string, object>[] EmptyDetails = new Utility.Tuple<ColumnType, string, object>[0]; private PreviewForm _previewForm; public TexturesListViewItemAdaptor(PreviewForm previewForm) { _previewForm = previewForm; } public override void Dispose() { _previewForm = null; } public override Image GetThumbnail(object key, Size size, UseEmbeddedThumbnails useEmbeddedThumbnails, bool useExifOrientation) { var index = (int)key; return _previewForm._textures[index].Bitmap; } public override string GetUniqueIdentifier(object key, Size size, UseEmbeddedThumbnails useEmbeddedThumbnails, bool useExifOrientation) { var index = (int)key; return index.ToString(); } public override string GetSourceImage(object key) { // This is just asking for the source filename, we don't have anything like that, but we can safely return null. return null; } public override Utility.Tuple<ColumnType, string, object>[] GetDetails(object key) { /*var index = (int)key; var texture = _previewForm._textures[index]; var details = new Utility.Tuple<ColumnType, string, object>[] { new Utility.Tuple<ColumnType, string, object>(ColumnType.Dimensions, string.Empty, new Size(texture.Width, texture.Height)), new Utility.Tuple<ColumnType, string, object>(ColumnType.Custom, "TexturePage", texture.TexturePage), }; return details;*/ return EmptyDetails; // We're not displaying details columns } } #endregion } }
412
0.989596
1
0.989596
game-dev
MEDIA
0.548373
game-dev
0.909241
1
0.909241
MinLL/SkyrimNet-GamePlugin
3,846
SKSE/Plugins/SkyrimNet/original_prompts/characters/coco_generic.prompt
{% block summary %}Coco is a charismatic Khajiit adventurer who frequents Dead Man's Drink in Falkreath, entertaining patrons with tales of her daring escape from highwaymen and subsequent forest exploits. Her quick wit and acrobatic talents make her a memorable presence in the tavern.{% endblock %} {% block interject_summary %}Coco interjects when conversations turn to: bandit encounters, Falkreath's forests, acrobatic feats, escape stories, Khajiit discrimination, or when patrons underestimate others based on appearance.{% endblock %} {% block background %}Born to a trading caravan that frequented the border between Cyrodiil and Skyrim, Coco developed independence early. When highwaymen ambushed her small trading party near Falkreath, they captured her for ransom or slavery. Underestimating her agility and cunning, they were unprepared when she escaped during the night, using her claws to free herself from bindings. After surviving alone in Falkreath's dense forests for weeks, she emerged with newfound confidence and made Dead Man's Drink her regular haunt, finding safety and purpose in the community there.{% endblock %} {% block personality %}Boisterous and self-assured, Coco projects confidence to mask lingering trauma from her captivity. She values freedom above all else and detests those who prey on travelers. Her humor serves as both entertainment and defense mechanism. She's naturally suspicious of armed strangers but warms quickly to those who treat her as an equal. She demonstrates fierce loyalty to those who earn her trust and holds grudges against those who dismiss Khajiit as mere thieves.{% endblock %} {% block appearance %}Coco has sleek tawny fur with distinctive black markings around her eyes that give her a perpetually alert expression. A notched ear and small scar on her right forearm remain from her escape. Her movements are fluid and deliberate, showcasing her natural agility even when simply crossing the tavern.{% endblock %} {% block aspirations %} - Track down and bring justice to the highwaymen who captured her - Establish a reputation as a guide through Falkreath's forests - Earn enough coin to purchase a small cabin outside town - Prove that Khajiit deserve the same respect as other races in Skyrim {% endblock %} {% block relationships %} - Valga Vinicia (Dead Man's Drink owner): Mutual respect; Valga appreciates Coco's ability to entertain customers and Coco values the safe haven Valga provides - Narri (Barmaid): Friendly rivalry; they compete for patrons' attention and tips - Mathies (Farmer): Cautious friendship; he brings news from outside town and occasionally trades fresh produce for Coco's forest finds - Falkreath Guards: Tense tolerance; they watch her closely due to anti-Khajiit prejudice but have no cause to act against her {% endblock %} {% block occupation %}Unofficial entertainer at Dead Man's Drink who supplements her income by gathering and selling rare herbs and fungi from Falkreath's forests.{% endblock %} {% block skills %} - Expert acrobatics and climbing abilities - Skilled in unarmed combat, particularly quick strikes and evasion - Proficient at identifying edible and alchemical plants in Falkreath Hold - Adept at tracking both animals and people through forest terrain - Talented storyteller who can captivate an audience - Nimble pickpocketing (though rarely practiced now) {% endblock %} {% block speech_style %}Speaks with a traditional Khajiit third-person speech pattern, referring to herself as "this one" or "Coco." Her voice is melodic with a purring undertone when pleased. She emphasizes dramatic moments in stories with theatrical pauses and animated gestures. When excited, her speech quickens and includes more Khajiit expressions. She punctuates important points by tapping her claws on nearby surfaces.{% endblock %}
412
0.661587
1
0.661587
game-dev
MEDIA
0.997908
game-dev
0.556482
1
0.556482
EasyRPG/Player
3,658
src/game_enemyparty.cpp
/* * This file is part of EasyRPG Player. * * EasyRPG Player is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. */ // Headers #include <cassert> #include <algorithm> #include "game_interpreter.h" #include "game_enemyparty.h" #include "game_runtime_patches.h" #include "main_data.h" #include <lcf/reader_util.h> #include "utils.h" #include "output.h" #include "rand.h" Game_EnemyParty::Game_EnemyParty() { } Game_Enemy* Game_EnemyParty::GetEnemy(int idx) { if (idx >= 0 && idx < static_cast<int>(enemies.size())) { return &enemies[idx]; } return nullptr; } Game_Enemy& Game_EnemyParty::operator[] (const int index) { if (index < 0 || index >= (int)enemies.size()) { assert(false && "Subscript out of range"); } return enemies[index]; } int Game_EnemyParty::GetBattlerCount() const { return static_cast<int>(enemies.size()); } int Game_EnemyParty::GetVisibleBattlerCount() const { int visible = 0; for (const auto& enemy: enemies) { visible += !enemy.IsHidden(); } return visible; } void Game_EnemyParty::ResetBattle(int battle_troop_id) { enemies.clear(); const auto* troop = lcf::ReaderUtil::GetElement(lcf::Data::troops, battle_troop_id); if (!troop) { // Valid case when battle quits return; } int non_hidden = static_cast<int>(troop->members.size()); for (const auto& mem : troop->members) { enemies.emplace_back(&mem); non_hidden -= enemies.back().IsHidden(); } if (troop->appear_randomly) { for (auto& enemy: enemies) { if (non_hidden <= 1) { // At least one party member must be visible break; } if (enemy.IsHidden()) { continue; } if (Rand::PercentChance(40)) { enemy.SetHidden(true); --non_hidden; } } } } std::vector<Game_Enemy*> Game_EnemyParty::GetEnemies() { std::vector<Game_Enemy*> party; party.reserve(enemies.size()); for (auto& e: enemies) { party.push_back(&e); } return party; } int Game_EnemyParty::GetExp() const { int sum = 0; for (auto& enemy: enemies) { if (enemy.IsDead()) { auto exp = enemy.GetExp(); RuntimePatches::MonSca::ModifyExpGained(enemy, exp); sum += exp; } } return sum; } int Game_EnemyParty::GetMoney() const { int sum = 0; for (auto& enemy: enemies) { if (enemy.IsDead()) { auto money = enemy.GetMoney(); RuntimePatches::MonSca::ModifyMoneyGained(enemy, money); sum += money; } } return sum; } void Game_EnemyParty::GenerateDrops(std::vector<int>& out) const { for (auto& enemy: enemies) { if (enemy.IsDead()) { auto drop_id = enemy.GetDropId(); RuntimePatches::MonSca::ModifyItemGained(enemy, drop_id); // Only roll if the enemy has something to drop if (drop_id > 0) { auto drop_rate = enemy.GetDropProbability(); RuntimePatches::MonSca::ModifyItemDropRate(enemy, drop_rate); if (Rand::ChanceOf(drop_rate, 100)) { out.push_back(drop_id); } } } } } int Game_EnemyParty::GetEnemyPositionInParty(const Game_Enemy* enemy) const { if (enemy >= enemies.data() && enemy < enemies.data() + enemies.size()) { return enemy - enemies.data(); } return -1; }
412
0.915334
1
0.915334
game-dev
MEDIA
0.985028
game-dev
0.896064
1
0.896064
loathers/autoscend
6,074
RELEASE/scripts/autoscend/auto_adventure.ash
// autoAdv is used to automate adventuring *once* in adventure.php zones // it will (should?) handle the complete adventure from start to finish regardless of // how many choices or combats it encounters (this is mafia's adv1 behaviour) // TODO: seems to return false even if it adventures successfully but doesn't cost an adventure (mafia issue?) boolean autoAdv(int num, location loc, string option) { if(!zone_isAvailable(loc, true)){ auto_log_warning("Can't get to " + loc + " right now.", "red"); return false; } remove_property("_auto_combatState"); set_property("auto_diag_round", 0); set_property("nextAdventure", loc); if(option == "") { if (isActuallyEd()) { option = "auto_edCombatHandler"; } else { option = "auto_combatHandler"; } } // adv1 can erroneously return false for "choiceless" non-combats // see https://kolmafia.us/showthread.php?25370-adv1-returns-false-for-quot-choiceless-quot-choice-adventures // undo all this when (if?) that ever gets fixed string previousEncounter = get_property("lastEncounter"); int turncount = my_turncount(); boolean advReturn = adv1(loc, -1, option); if (!advReturn) { auto_log_debug("adv1 returned false for some reason. Did we actually adventure though?", "blue"); if (get_property("lastEncounter") != previousEncounter) { auto_log_debug(`Looks like we may have adventured, lastEncounter was {previousEncounter}, now {get_property("lastEncounter")}`, "blue"); advReturn = true; } if (my_turncount() > turncount) { auto_log_debug(`Looks like we may have adventured, turncount was {turncount}, now {my_turncount()}`, "blue"); advReturn = true; } } return advReturn; } boolean autoAdv(int num, location loc) { return autoAdv(num, loc, ""); } boolean autoAdv(location loc) { return autoAdv(1, loc, ""); } boolean autoAdv(location loc, string option) { return autoAdv(1, loc, option); } boolean autoLuckyAdv(location loc, boolean override) { boolean gotLucky = false; if (cloversAvailable(override) > 0) { cloverUsageInit(override); gotLucky = autoAdv(loc); if (cloverUsageRestart()) { gotLucky = autoAdv(loc); } cloverUsageFinish(); } return gotLucky; } boolean autoLuckyAdv(location loc) { // overload to not override clover usage by default as this is the general case return autoLuckyAdv(loc, false); } // autoAdvBypass is used to automate adventuring *once* in non-adventure.php zones // it will (should?) handle the complete adventure from start to finish regardless of // how many choices or combats it encounters boolean autoAdvBypass(int urlGetFlags, string[int] url, location loc, string option) { if(!zone_isAvailable(loc, true)) { // reinstate this check for now. Didn't fix the War boss fight outside of Ed & KoE, // will work around that by passing Noob Cave as location until this is refactored. auto_log_warning("Can't get to " + loc + " right now.", "red"); return false; } set_property("nextAdventure", loc); cli_execute("auto_pre_adv"); remove_property("_auto_combatState"); set_property("auto_diag_round", 0); if(option == "") { if (isActuallyEd()) { option = "auto_edCombatHandler"; } else { option = "auto_combatHandler"; } } if (isActuallyEd()) { ed_handleAdventureServant(loc); } auto_log_info("About to start a combat indirectly at " + loc + "... (" + count(url) + ") accesses required.", "blue"); string page; foreach idx, it in url { if((urlGetFlags & 1) == 1) { page = visit_url(it, false); } else { page = visit_url(it); } urlGetFlags /= 2; } // handle the initial combat or choice the easy way. string combatPage = ">Combat"; if(in_pokefam()) { combatPage = ">Fight!"; } if (contains_text(page, combatPage)) { auto_log_info("autoAdvBypass has encountered a combat! (param: '" + option + "')", "green"); run_combat(option); } else { int choice_id = last_choice(); auto_log_info("autoAdvBypass has encountered a choice: "+choice_id, "green"); run_choice(-1); } // this should handle stuff like Ed's resurrect/fight loop // and anything else that chains combats & choices in any order while (fight_follows_choice() || choice_follows_fight() || in_multi_fight() || handling_choice()) { if ((fight_follows_choice() || in_multi_fight()) && (!choice_follows_fight() && !handling_choice())) { auto_log_info("autoAdvBypass has encountered a combat! (param: '" + option + "')", "green"); run_combat(option); } if (choice_follows_fight() || handling_choice()) { int choice_id = last_choice(); auto_log_info("autoAdvBypass has encountered a choice: "+choice_id, "green"); run_choice(-1); } } cli_execute("auto_post_adv"); // Encounters that need to generate a false so we handle them manually should go here. if(get_property("lastEncounter") == "Travel to a Recent Fight") { return false; } if(get_property("lastEncounter") == "Rationing out Destruction") { return false; } if(get_property("lastEncounter") == "Rainy Fax Dreams on your Wedding Day") { return false; } return true; } boolean autoAdvBypass(string url, location loc) { return autoAdvBypass(url, loc, ""); } boolean autoAdvBypass(string url, location loc, string option) { string[int] urlConvert; urlConvert[0] = url; return autoAdvBypass(0, urlConvert, loc, option); } boolean autoAdvBypass(int snarfblat, location loc) { string page = "adventure.php?snarfblat=" + snarfblat; return autoAdvBypass(page, loc); } boolean autoAdvBypass(int snarfblat, location loc, string option) { string page = "adventure.php?snarfblat=" + snarfblat; return autoAdvBypass(page, loc, option); } boolean autoAdvBypass(int snarfblat) { return autoAdvBypass(snarfblat, $location[Noob Cave]); } boolean autoAdvBypass(string url) { return autoAdvBypass(url, $location[Noob Cave]); } boolean autoAdvBypass(int snarfblat, string option) { return autoAdvBypass(snarfblat, $location[Noob Cave], option); } boolean autoAdvBypass(string url, string option) { return autoAdvBypass(url, $location[Noob Cave], option); }
412
0.935178
1
0.935178
game-dev
MEDIA
0.56446
game-dev
0.997248
1
0.997248
saturnflyer/casting
1,833
lib/casting/client.rb
require "casting/delegation" require "casting/missing_method_client" require "casting/missing_method_client_class" module Casting module Client def self.included(base) def base.delegate_missing_methods(*which) Casting::Client.set_delegation_strategy(self, *which.reverse) end unless base.method_defined?(:delegate) add_delegate_method_to(base) end end def self.extended(base) unless base.respond_to?(:delegate) add_delegate_method_to(base.singleton_class) end end def delegation(delegated_method_name) Casting::Delegation.prepare(delegated_method_name, self) end def cast(delegated_method_name, attendant, ...) validate_attendant(attendant) delegation(delegated_method_name).to(attendant).call(...) end def delegate_missing_methods(*which) Casting::Client.set_delegation_strategy(singleton_class, *which.reverse) end private def validate_attendant(attendant) if attendant == self raise Casting::InvalidAttendant.new("client can not delegate to itself") end end def self.set_delegation_strategy(base, *which) which = [:instance] if which.empty? which.map! { |selection| selection == :instance && selection = method(:set_method_missing_client) selection == :class && selection = method(:set_method_missing_client_class) selection }.map { |meth| meth.call(base) } end def self.add_delegate_method_to(base) base.class_eval { alias_method :delegate, :cast } end def self.set_method_missing_client(base) base.send(:include, ::Casting::MissingMethodClient) end def self.set_method_missing_client_class(base) base.send(:extend, ::Casting::MissingMethodClientClass) end end end
412
0.719578
1
0.719578
game-dev
MEDIA
0.294933
game-dev
0.520266
1
0.520266
Tareq-Khalil/Pixy-Wheel
3,946
core/src/com/agateau/ui/menu/MenuInputHandler.java
/* * Copyright 2017 Aurélien Gâteau <mail@agateau.com> * * This file is part of Pixel Wheels. * * 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.agateau.ui.menu; import com.agateau.ui.InputMapper; import com.agateau.ui.UiInputMapper; import com.agateau.ui.VirtualKey; /** * Monitor input events for the menu * * <p>Provides an API similar to Gdx.input but works with {@link VirtualKey}. Handles key repeat. */ public class MenuInputHandler { private static final float REPEAT_DELAY = 0.6f; private static final float REPEAT_RATE = 0.025f; private enum State { STARTING, NORMAL, KEY_DOWN, REPEATING } private InputMapper mInputMapper = UiInputMapper.getInstance(); private State mState = State.STARTING; private VirtualKey mPressedVirtualKey = null; private VirtualKey mJustPressedVirtualKey = null; private float mRepeatDelay = 0; /** * Returns true if the key is being pressed. If the key is held down, this will return true at * regular intervals, like an auto-repeat keyboard * * @param vkey the key to check * @return True if the key is being pressed */ public boolean isPressed(VirtualKey vkey) { return mPressedVirtualKey == vkey && mRepeatDelay < 0; } /** * Returns true if the key has been pressed, then released * * @param vkey the key to check * @return True if the key has been pressed, then released */ public boolean isJustPressed(VirtualKey vkey) { return mJustPressedVirtualKey == vkey; } public void act(float delta) { if (mState == State.STARTING) { // If a key is already down at startup, ignore it. If no key is down, go to NORMAL state if (findPressedKey() == null) { mState = State.NORMAL; } } else if (mState == State.NORMAL) { // Not repeating yet mJustPressedVirtualKey = null; VirtualKey virtualKey = findPressedKey(); if (virtualKey != null) { mPressedVirtualKey = virtualKey; // Set delay to -1 so that next call to isPressed() returns true mRepeatDelay = -1; mState = State.KEY_DOWN; } } else { // Repeating if (mInputMapper.isKeyPressed(mPressedVirtualKey)) { if (mRepeatDelay > 0) { mRepeatDelay -= delta; } else { if (mState == State.KEY_DOWN) { mRepeatDelay = REPEAT_DELAY; mState = State.REPEATING; } else { mRepeatDelay = REPEAT_RATE; } } } else { // Key has been released, not repeating anymore mState = State.NORMAL; mJustPressedVirtualKey = mPressedVirtualKey; } } } public InputMapper getInputMapper() { return mInputMapper; } public void setInputMapper(InputMapper inputMapper) { mInputMapper = inputMapper; } private VirtualKey findPressedKey() { for (VirtualKey virtualKey : VirtualKey.values()) { if (mInputMapper.isKeyPressed(virtualKey)) { return virtualKey; } } return null; } }
412
0.854272
1
0.854272
game-dev
MEDIA
0.202876
game-dev
0.974021
1
0.974021
PentestSS13/Pentest
2,690
code/datums/weather/weather_types/ash_storm.dm
//Ash storms happen frequently on lavaland. They heavily obscure vision, and cause high fire damage to anyone caught outside. /datum/weather/ash_storm name = "ash storm" desc = "An intense atmospheric storm lifts ash off of the planet's surface and billows it down across the area, dealing intense fire damage to the unprotected." telegraph_message = span_boldwarning("An eerie moan rises on the wind. Sheets of burning ash blacken the horizon. Seek shelter.") telegraph_duration = 300 telegraph_overlay = "light_ash" weather_message = span_userdanger("<i>Smoldering clouds of scorching ash billow down around you! Get inside!</i>") weather_duration_lower = 600 weather_duration_upper = 1200 weather_overlay = "ash_storm" end_message = span_boldannounce("The shrieking wind whips away the last of the ash and falls to its usual murmur. It should be safe to go outside now.") end_duration = 300 end_overlay = "light_ash" area_type = /area protect_indoors = TRUE immunity_type = "ash" barometer_predictable = TRUE sound_active_outside = /datum/looping_sound/active_outside_ashstorm sound_active_inside = /datum/looping_sound/active_inside_ashstorm sound_weak_outside = /datum/looping_sound/weak_outside_ashstorm sound_weak_inside = /datum/looping_sound/weak_inside_ashstorm multiply_blend_on_main_stage = TRUE /datum/weather/ash_storm/proc/is_ash_immune(atom/L) while (L && !isturf(L)) if(ismecha(L)) //Mechs are immune return TRUE if(ishuman(L)) //Are you immune? var/mob/living/carbon/human/H = L var/thermal_protection = H.get_thermal_protection() if(thermal_protection >= FIRE_IMMUNITY_MAX_TEMP_PROTECT) return TRUE if(isliving(L))// if we're a non immune mob inside an immune mob we have to reconsider if that mob is immune to protect ourselves var/mob/living/the_mob = L if("ash" in the_mob.weather_immunities) return TRUE L = L.loc //Check parent items immunities (recurses up to the turf) return FALSE //RIP you /datum/weather/ash_storm/weather_act(mob/living/L) if(is_ash_immune(L)) return L.adjustFireLoss(4) //Emberfalls are the result of an ash storm passing by close to the playable area of lavaland. They have a 10% chance to trigger in place of an ash storm. /datum/weather/ash_storm/emberfall name = "emberfall" desc = "A passing ash storm blankets the area in harmless embers." weather_message = span_notice("Gentle embers waft down around you like grotesque snow. The storm seems to have passed you by...") weather_overlay = "light_ash" end_message = span_notice("The emberfall slows, stops. Another layer of hardened soot to the basalt beneath your feet.") end_sound = null aesthetic = TRUE
412
0.922621
1
0.922621
game-dev
MEDIA
0.784353
game-dev
0.932647
1
0.932647
Logicalshift/flo_draw
12,846
draw/examples/vectoroids.rs
use flo_draw::*; use flo_canvas::*; use flo_stream::*; use rand::*; use futures::prelude::*; use futures::stream; use futures::executor; use futures_timer::*; use std::f64; use std::time::*; /// /// Demonstration of `flo_draw` that illustrates a way to implement a simple game /// pub fn main() { with_2d_graphics(|| { executor::block_on(async { // Set up let (canvas, events) = create_drawing_window_with_events("Vectoroids"); // Create a tick generator let tick_stream = tick_stream(); // Combine the tick generator into the events stream let events = events.map(|evt| VectorEvent::DrawEvent(evt)); let mut events = stream::select(events, tick_stream); // Set up the canvas by declaring the sprites and the background let ship_sprite = SpriteId(0); let bullet_sprite = SpriteId(1); let roid_sprite = SpriteId(2); canvas.draw(|gc| { gc.clear_canvas(Color::Rgba(0.1, 0.1, 0.1, 1.0)); // Game area is a 1000x1000 square gc.canvas_height(1000.0); gc.center_region(0.0, 0.0, 1000.0, 1000.0); // Ship is just a triangle gc.sprite(ship_sprite); gc.clear_sprite(); gc.new_path(); gc.move_to(-10.0, -8.0); gc.line_to(0.0, 12.0); gc.line_to(10.0, -8.0); gc.line_to(8.0, -6.0); gc.line_to(-8.0, -6.0); gc.line_to(-10.0, -8.0); gc.line_width(2.0); gc.stroke_color(Color::Rgba(0.8, 0.7, 0.0, 1.0)); gc.stroke(); // Bullet is a square gc.sprite(bullet_sprite); gc.clear_sprite(); gc.new_path(); gc.rect(-1.0, -1.0, 1.0, 1.0); gc.fill_color(Color::Rgba(1.0, 0.8, 0.0, 1.0)); gc.fill(); // 'roids are an irregular shape gc.sprite(roid_sprite); gc.clear_sprite(); gc.new_path(); gc.move_to(0.0, -15.0); gc.line_to(-15.0, -25.0); gc.line_to(-35.0, -15.0); gc.line_to(-20.0, 0.0); gc.line_to(-25.0, 5.0); gc.line_to(-10.0, 20.0); gc.line_to(5.0, 25.0); gc.line_to(30.0, 5.0); gc.line_to(20.0, -15.0); gc.line_to(10.0, -25.0); gc.line_to(0.0, -15.0); gc.line_width(3.0); gc.stroke_color(Color::Rgba(0.6, 0.5, 0.0, 1.0)); gc.stroke(); // Background is a random starscape made of squares gc.layer(LayerId(0)); gc.clear_layer(); gc.fill_color(Color::Rgba(0.7, 0.7, 0.8, 1.0)); for _star in 0..200 { let x = random::<f32>() * 1000.0; let y = random::<f32>() * 1000.0; gc.rect(x-1.0, y-1.0, x+1.0, y+1.0); gc.fill(); } }); // Run the main game loop let mut game_state = GameState::new(ship_sprite, roid_sprite); while let Some(event) = events.next().await { match event { VectorEvent::Tick => { // Update the game state game_state.tick(); // Draw the game on layer 1 canvas.draw(|gc| { gc.layer(LayerId(1)); gc.clear_layer(); game_state.draw(gc); }); } VectorEvent::DrawEvent(DrawEvent::KeyDown(_, Some(Key::KeyLeft))) => { game_state.ship.rotation = (360.0) / 60.0; } VectorEvent::DrawEvent(DrawEvent::KeyDown(_, Some(Key::KeyRight))) => { game_state.ship.rotation = -(360.0) / 60.0; } VectorEvent::DrawEvent(DrawEvent::KeyUp(_, Some(Key::KeyLeft))) | VectorEvent::DrawEvent(DrawEvent::KeyUp(_, Some(Key::KeyRight))) => { game_state.ship.rotation = 0.0; } VectorEvent::DrawEvent(DrawEvent::KeyDown(_, Some(Key::KeyUp))) => { game_state.ship.thrust = 0.3; } VectorEvent::DrawEvent(DrawEvent::KeyUp(_, Some(Key::KeyUp))) => { game_state.ship.thrust = 0.0; } VectorEvent::DrawEvent(DrawEvent::KeyDown(_, Some(Key::KeySpace))) => { game_state.bullets.push(Bullet::new(bullet_sprite, game_state.ship.x, game_state.ship.y, game_state.ship.vel_x, game_state.ship.vel_y, game_state.ship.angle)); } _ => { /* Other events are ignored */ } } } }); }); } /// /// Events processed by the game /// enum VectorEvent { Tick, DrawEvent(DrawEvent) } /// /// Represents the state of a game /// struct GameState { ship: Ship, roids: Vec<Roid>, bullets: Vec<Bullet> } /// /// Represents the state of the player's ship /// struct Ship { sprite: SpriteId, x: f64, y: f64, angle: f64, vel_x: f64, vel_y: f64, rotation: f64, thrust: f64 } /// /// Represents the state of a 'roid /// struct Roid { sprite: SpriteId, x: f64, y: f64, angle: f64, rotation: f64, vel_x: f64, vel_y: f64, } /// /// Represents the state of a bullet /// struct Bullet { sprite: SpriteId, x: f64, y: f64, vel_x: f64, vel_y: f64, time_left: usize } impl GameState { /// /// Creates a new game state /// pub fn new(ship_sprite: SpriteId, roid_sprite: SpriteId) -> GameState { GameState { ship: Ship::new(ship_sprite), roids: (0..20).into_iter().map(|_| Roid::new(roid_sprite)).collect(), bullets: vec![] } } /// /// Updates the game state after a tick /// pub fn tick(&mut self) { self.ship.tick(); self.roids.iter_mut().for_each(|roid| roid.tick()); self.bullets.iter_mut().for_each(|bullet| bullet.tick()); self.bullets.retain(|bullet| bullet.time_left > 0); } pub fn draw(&self, gc: &mut dyn GraphicsContext) { self.roids.iter().for_each(|roid| roid.draw(gc)); self.ship.draw(gc); self.bullets.iter().for_each(|bullet| bullet.draw(gc)); } } impl Ship { /// /// Creates a new ship state /// pub fn new(sprite: SpriteId) -> Ship { Ship { sprite: sprite, x: 500.0, y: 500.0, vel_x: 0.0, vel_y: 0.0, angle: 0.0, rotation: 0.0, thrust: 0.0 } } /// /// Updates the ship state after a tick /// pub fn tick(&mut self) { // Move the ship self.x += self.vel_x; self.y += self.vel_y; self.angle += self.rotation; self.angle = self.angle % 360.0; // Clip to the play area if self.x < 0.0 { self.x = 1000.0 }; if self.y < 0.0 { self.y = 1000.0 }; if self.x > 1000.0 { self.x = 0.0 }; if self.y > 1000.0 { self.y = 0.0 }; // Apply thrust let (acc_x, acc_y) = Transform2D::rotate_degrees(self.angle as _).transform_point(0.0, self.thrust as _); self.vel_x += acc_x as f64; self.vel_y += acc_y as f64; // Friction self.vel_x *= 0.99; self.vel_y *= 0.99; } pub fn draw(&self, gc: &mut dyn GraphicsContext) { gc.sprite_transform(SpriteTransform::Identity); gc.sprite_transform(SpriteTransform::Rotate(self.angle as _)); gc.sprite_transform(SpriteTransform::Translate(self.x as _, self.y as _)); gc.draw_sprite(self.sprite); } } impl Roid { /// /// Creates a new 'roid state /// pub fn new(sprite: SpriteId) -> Roid { Roid { sprite: sprite, x: random::<f64>() * 1000.0, y: random::<f64>() * 1000.0, vel_x: random::<f64>() * 3.0 - 1.5, vel_y: random::<f64>() * 3.0 - 1.5, angle: random::<f64>() * 360.0, rotation: random::<f64>() * 8.0 - 4.0 } } /// /// Updates the 'roid state after a tick /// pub fn tick(&mut self) { // Move the 'roid self.x += self.vel_x; self.y += self.vel_y; self.angle += self.rotation; self.angle = self.angle % 360.0; // Clip to the play area if self.x < 0.0 { self.x = 1000.0 }; if self.y < 0.0 { self.y = 1000.0 }; if self.x > 1000.0 { self.x = 0.0 }; if self.y > 1000.0 { self.y = 0.0 }; } pub fn draw(&self, gc: &mut dyn GraphicsContext) { gc.sprite_transform(SpriteTransform::Identity); gc.sprite_transform(SpriteTransform::Rotate(self.angle as _)); gc.sprite_transform(SpriteTransform::Translate(self.x as _, self.y as _)); gc.draw_sprite(self.sprite); } } impl Bullet { /// /// Creates a new bullet state /// pub fn new(sprite: SpriteId, x: f64, y: f64, ship_vel_x: f64, ship_vel_y: f64, ship_angle: f64) -> Bullet { let transform = Transform2D::rotate_degrees(ship_angle as _); let (offset_x, offset_y) = transform.transform_point(0.0, 11.0); let (x, y) = (x+offset_x as f64, y+offset_y as f64); let (vel_x, vel_y) = transform.transform_point(0.0, 4.0); let (vel_x, vel_y) = (ship_vel_x+vel_x as f64, ship_vel_y+vel_y as f64); Bullet { sprite: sprite, x: x, y: y, vel_x: vel_x, vel_y: vel_y, time_left: 90 } } /// /// Updates the bullet state after a tick /// pub fn tick(&mut self) { // Move the bullet self.x += self.vel_x; self.y += self.vel_y; self.time_left -= 1; // Clip to the play area if self.x < 0.0 { self.x = 1000.0 }; if self.y < 0.0 { self.y = 1000.0 }; if self.x > 1000.0 { self.x = 0.0 }; if self.y > 1000.0 { self.y = 0.0 }; } pub fn draw(&self, gc: &mut dyn GraphicsContext) { gc.sprite_transform(SpriteTransform::Identity); gc.sprite_transform(SpriteTransform::Translate(self.x as _, self.y as _)); gc.draw_sprite(self.sprite); } } /// /// A stream that generates a 'tick' event every time the game state should update /// fn tick_stream() -> impl Send+Unpin+Stream<Item=VectorEvent> { generator_stream(|yield_value| async move { // Set up the clock let start_time = Instant::now(); let mut last_time = Duration::from_millis(0); // We limit to a certain number of ticks per callback (in case the task is suspended or stuck for a prolonged period of time) let max_ticks_per_call = 5; // Ticks are generated 60 times a second let tick_length = Duration::from_nanos(1_000_000_000 / 60); loop { // Time that has elapsed since the last tick let elapsed = start_time.elapsed() - last_time; // Time remaining let mut remaining = elapsed; let mut num_ticks = 0; while remaining >= tick_length { if num_ticks < max_ticks_per_call { // Generate the tick yield_value(VectorEvent::Tick).await; num_ticks += 1; } // Remove from the remaining time, and update the last tick time remaining -= tick_length; last_time += tick_length; } // Wait for half a tick before generating more ticks let next_time = tick_length - remaining; let wait_time = Duration::min(tick_length / 2, next_time); Delay::new(wait_time).await; } }.boxed()) }
412
0.711091
1
0.711091
game-dev
MEDIA
0.788027
game-dev,graphics-rendering
0.912772
1
0.912772
TheProjectLumina/LuminaClient
16,786
app/src/main/java/com/project/lumina/client/constructors/NetBound.kt
package com.project.lumina.client.constructors import android.util.Log import com.project.lumina.client.application.AppContext import com.project.lumina.client.game.InterceptablePacket import com.project.lumina.client.game.entity.LocalPlayer import com.project.lumina.client.game.event.EventManager import com.project.lumina.client.game.event.EventPacketInbound import com.project.lumina.client.game.registry.BlockMapping import com.project.lumina.client.game.registry.BlockMappingProvider import com.project.lumina.client.game.world.Level import com.project.lumina.client.game.world.World import com.project.lumina.client.overlay.mods.MiniMapOverlay import com.project.lumina.client.overlay.mods.OverlayModuleList import com.project.lumina.client.overlay.mods.PacketNotificationOverlay import com.project.lumina.client.overlay.mods.Position import com.project.lumina.client.overlay.mods.SessionStatsOverlay import com.project.lumina.client.overlay.mods.SpeedometerOverlay import com.project.lumina.relay.LuminaRelaySession import com.project.lumina.client.game.registry.ItemMapping import com.project.lumina.client.game.registry.ItemMappingProvider import com.project.lumina.client.game.registry.LegacyBlockMapping import com.project.lumina.client.game.registry.LegacyBlockMappingProvider import com.project.lumina.client.overlay.mods.KeystrokesOverlay import com.project.lumina.client.overlay.mods.TargetHudOverlay import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import net.kyori.adventure.text.Component import org.cloudburstmc.math.vector.Vector3f import org.cloudburstmc.protocol.bedrock.data.definitions.ItemDefinition import org.cloudburstmc.protocol.bedrock.packet.BedrockPacket import org.cloudburstmc.protocol.bedrock.packet.StartGamePacket import org.cloudburstmc.protocol.bedrock.packet.ItemComponentPacket import org.cloudburstmc.protocol.bedrock.packet.TextPacket import org.cloudburstmc.protocol.bedrock.packet.PlayerListPacket import org.cloudburstmc.protocol.bedrock.packet.LevelEventPacket import org.cloudburstmc.protocol.bedrock.packet.SetTimePacket import org.cloudburstmc.protocol.bedrock.packet.BookEditPacket import org.cloudburstmc.protocol.bedrock.packet.CommandRequestPacket import org.cloudburstmc.protocol.common.SimpleDefinitionRegistry import java.util.Collections import java.util.UUID @Suppress("MemberVisibilityCanBePrivate") class NetBound(val luminaRelaySession: LuminaRelaySession) : ComposedPacketHandler, com.project.lumina.client.game.event.Listenable { override val eventManager = EventManager() val world = World(this) val level = Level(this) val localPlayer = LocalPlayer(this) private val proxyPlayerNames: MutableSet<String> = Collections.synchronizedSet(mutableSetOf()) val gameDataManager = GameDataManager() val protocolVersion: Int get() = luminaRelaySession.server.codec.protocolVersion private val mappingProviderContext = AppContext.instance private val blockMappingProvider = BlockMappingProvider(mappingProviderContext) private val itemMappingProvider = ItemMappingProvider(mappingProviderContext) private val legacyBlockMappingProvider = LegacyBlockMappingProvider(mappingProviderContext) lateinit var blockMapping: BlockMapping lateinit var itemMapping: ItemMapping lateinit var legacyBlockMapping: LegacyBlockMapping private var startGameReceived = false private val pendingPackets = mutableListOf<BedrockPacket>() private val mainScope = CoroutineScope(Dispatchers.Main) private var playerPosition = Position(0f, 0f) private var playerRotation = 0f private val entityPositions = mutableMapOf<Long, Position>() private var minimapEnabled = false private var minimapUpdateScheduled = false private var minimapSize = 100f private var minimapZoom = 1.0f private var minimapDotSize = 5 private var tracersEnabled = false private val versionName by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { AppContext.instance.packageManager.getPackageInfo( AppContext.instance.packageName, 0 ).versionName } fun clientBound(packet: BedrockPacket) { luminaRelaySession.clientBound(packet) } fun serverBound(packet: BedrockPacket) { luminaRelaySession.serverBound(packet) } override fun beforePacketBound(packet: BedrockPacket): Boolean { GameManager.setNetBound(this) if (packet is TextPacket) { if (packet.type == TextPacket.Type.CHAT) { proxyPlayerNames.add(packet.sourceName) } } if (packet is BookEditPacket) { if (packet.text.toString().length > 5000) { return true } } if (packet is CommandRequestPacket) { if (packet.command.length > 1000) { return true } } when (packet) { is StartGamePacket -> { gameDataManager.storeStartGamePacket(packet) try { val itemDefinitions = SimpleDefinitionRegistry.builder<ItemDefinition>() .addAll(packet.itemDefinitions) .build() luminaRelaySession.server.peer.codecHelper.itemDefinitions = itemDefinitions luminaRelaySession.client?.peer?.codecHelper?.itemDefinitions = itemDefinitions Log.i("NetBound", "Successfully set up codecHelper itemDefinitions: ${packet.itemDefinitions.size} items") } catch (e: Exception) { Log.e("NetBound", "Failed to set up codecHelper itemDefinitions", e) } if (!startGameReceived) { startGameReceived = true Log.e("StartGamePacket", packet.toString()) Log.i("GameSession", "Seed: ${gameDataManager.getSeed()}") Log.i("GameSession", "Game Mode: ${gameDataManager.getGameMode()}") Log.i("GameSession", "LevelName: ${gameDataManager.getLevelName()}") /** try { blockMapping = blockMappingProvider.craftMapping(protocolVersion) itemMapping = itemMappingProvider.craftMapping(protocolVersion) legacyBlockMapping = legacyBlockMappingProvider.craftMapping(protocolVersion) Log.i("GameSession", "Loaded mappings for protocol $protocolVersion") } catch (e: Exception) { Log.e("GameSession", "Failed to load mappings for protocol $protocolVersion", e) } */ } } is ItemComponentPacket -> { try { val itemDefinitions = SimpleDefinitionRegistry.builder<ItemDefinition>() .addAll(packet.items) .build() luminaRelaySession.server.peer.codecHelper.itemDefinitions = itemDefinitions luminaRelaySession.client?.peer?.codecHelper?.itemDefinitions = itemDefinitions Log.i("NetBound", "Successfully updated codecHelper from ItemComponentPacket: ${packet.items.size} items") } catch (e: Exception) { Log.e("NetBound", "Failed to update codecHelper from ItemComponentPacket", e) } } is PlayerListPacket -> { gameDataManager.handlePlayerListPacket(packet) } } localPlayer.onPacketBound(packet) world.onPacket(packet) level.onPacketBound(packet) val event = EventPacketInbound(this, packet) eventManager.emit(event) if (event.isCanceled()) return true val interceptablePacket = InterceptablePacket(packet) for (module in GameManager.elements) { module.beforePacketBound(interceptablePacket) if (interceptablePacket.isIntercepted) return true } displayClientMessage("[Lumina V4]", TextPacket.Type.TIP) return false } override fun afterPacketBound(packet: BedrockPacket) { for (module in GameManager.elements) { module.afterPacketBound(packet) } } override fun onDisconnect(reason: String) { localPlayer.onDisconnect() level.onDisconnect() proxyPlayerNames.clear() GameManager.clearNetBound() gameDataManager.clearAllData() startGameReceived = false for (module in GameManager.elements) { module.onDisconnect(reason) } } fun getStartGameData(): Map<String, Any?> = gameDataManager.getStartGameData() fun getStartGameField(fieldName: String): Any? = gameDataManager.getStartGameField(fieldName) fun hasStartGameData(): Boolean = gameDataManager.hasStartGameData() fun getWorldName(): String? = gameDataManager.getWorldName() fun getPlayerSpawnPosition(): Vector3f? = gameDataManager.getPlayerPosition() fun getWorldSeed(): Long? = gameDataManager.getSeed() fun getLevelId(): String? = gameDataManager.getLevelId() fun getPacketData(packetType: String): Map<String, Any?> = gameDataManager.getPacketData(packetType) fun getPacketField(packetType: String, fieldName: String): Any? = gameDataManager.getPacketField(packetType, fieldName) fun getGameDataStats(): String = gameDataManager.getDataStats() fun getCurrentPlayers(): List<GameDataManager.PlayerInfo> = gameDataManager.getCurrentPlayerList() fun getPlayerByName(name: String): GameDataManager.PlayerInfo? = gameDataManager.getPlayerByName(name) fun getPlayerByUUID(uuid: UUID): GameDataManager.PlayerInfo? = gameDataManager.getPlayerByUUID(uuid) fun getPlayerByEntityId(entityId: Long): GameDataManager.PlayerInfo? = gameDataManager.getPlayerByEntityId(entityId) fun getPlayerCount(): Int = gameDataManager.getPlayerCount() fun getPlayerListStats(): String = gameDataManager.getPlayerListStats() fun getPlayersWithRole(): Map<String, List<GameDataManager.PlayerInfo>> = gameDataManager.getPlayersWithRole() fun isPlayerOnline(playerName: String): Boolean = getPlayerByName(playerName) != null fun isPlayerOnlineByUUID(uuid: UUID): Boolean = getPlayerByUUID(uuid) != null fun getHosts(): List<GameDataManager.PlayerInfo> = getPlayersWithRole()["hosts"] ?: emptyList() fun getTeachers(): List<GameDataManager.PlayerInfo> = getPlayersWithRole()["teachers"] ?: emptyList() fun logCurrentPlayerList() { Log.i("NetBound", "=== Current Player List ===") Log.i("NetBound", getPlayerListStats()) Log.i("NetBound", "========================") } fun displayClientMessage(message: String, type: TextPacket.Type = TextPacket.Type.RAW) { val textPacket = TextPacket() textPacket.type = type textPacket.sourceName = "" textPacket.message = message textPacket.xuid = "" textPacket.platformChatId = "" textPacket.filteredMessage = "" clientBound(textPacket) } fun launchOnMain(block: suspend CoroutineScope.() -> Unit) { mainScope.launch { block() } } suspend fun showSessionStatsOverlay(initialStats: List<String>): SessionStatsOverlay = withContext(Dispatchers.Main) { try { val overlay = SessionStatsOverlay.showSessionStats(initialStats) overlay } catch (e: Exception) { e.printStackTrace() throw e } } fun showNotification(title: String, subtitle: String, ResId: Int) { mainScope.launch { try { PacketNotificationOverlay.showNotification( title = title, subtitle = subtitle, iconRes = ResId, duration = 1000L ) } catch (e: Exception) { e.printStackTrace() } } } fun showSpeedometer(position: Vector3f) { mainScope.launch { try { SpeedometerOverlay.showOverlay() SpeedometerOverlay.updatePosition(position) } catch (e: Exception) { } } } fun updatePlayerPosition(x: Float, z: Float) { playerPosition = Position(x, z) if (minimapEnabled) { scheduleMinimapUpdate() } } fun updatePlayerRotation(yaw: Float) { playerRotation = yaw if (minimapEnabled) { scheduleMinimapUpdate() } } fun updateEntityPosition(entityId: Long, x: Float, z: Float) { entityPositions[entityId] = Position(x, z) if (minimapEnabled && !minimapUpdateScheduled) { scheduleMinimapUpdate() } } fun updateMinimapSize(size: Float) { minimapSize = size if (minimapEnabled) { mainScope.launch { MiniMapOverlay.setMinimapSize(size) updateMinimap() } } } fun updateMinimapZoom(zoom: Float) { minimapZoom = zoom if (minimapEnabled) { mainScope.launch { MiniMapOverlay.overlayInstance.minimapZoom = zoom updateMinimap() } } } fun updateDotSize(dotSize: Int) { minimapDotSize = dotSize if (minimapEnabled) { mainScope.launch { MiniMapOverlay.overlayInstance.minimapDotSize = dotSize updateMinimap() } } } private fun scheduleMinimapUpdate() { if (!minimapUpdateScheduled) { minimapUpdateScheduled = true mainScope.launch { updateMinimap() minimapUpdateScheduled = false } } } fun enableMinimap(enable: Boolean) { if (enable != minimapEnabled) { minimapEnabled = enable if (enable) { mainScope.launch { MiniMapOverlay.setOverlayEnabled(true) MiniMapOverlay.setMinimapSize(minimapSize) updateMinimap() } } else { mainScope.launch { MiniMapOverlay.setOverlayEnabled(false) } } } } private fun updateMinimap() { try { MiniMapOverlay.setCenter(playerPosition.x, playerPosition.y) MiniMapOverlay.setPlayerRotation(playerRotation) MiniMapOverlay.overlayInstance.minimapZoom = minimapZoom MiniMapOverlay.overlayInstance.minimapDotSize = minimapDotSize val targets = entityPositions.values.toList() val finalTargets = if (targets.isEmpty()) { targets } else { targets } MiniMapOverlay.setTargets(finalTargets) MiniMapOverlay.showOverlay() } catch (e: Exception) { e.printStackTrace() } } fun clearEntityPositions() { entityPositions.clear() if (minimapEnabled) { scheduleMinimapUpdate() } } fun showMinimap(centerX: Float, centerZ: Float, targets: List<Position>) { mainScope.launch { MiniMapOverlay.setOverlayEnabled(true) MiniMapOverlay.setMinimapSize(minimapSize) MiniMapOverlay.setCenter(centerX, centerZ) MiniMapOverlay.setTargets(targets) MiniMapOverlay.showOverlay() minimapEnabled = true playerPosition = Position(centerX, centerZ) } } fun enableArrayList(boolean: Boolean) { OverlayModuleList.setOverlayEnabled(enabled = boolean) } fun setArrayListMode(boolean: Boolean) { } fun arrayListUi(string: String) { } fun isProxyPlayer(playerName: String): Boolean { return proxyPlayerNames.contains(playerName) } fun toggleSounds(bool: Boolean) { ArrayListManager.setSoundEnabled(bool) } fun soundList(set: ArrayListManager.SoundSet) { ArrayListManager.setCurrentSoundSet(set) } fun keyPress(key: String, pressed: Boolean) { KeystrokesOverlay.setKeyState(key, pressed) } fun targetHud(user: String, distance: Float, maxdistance: Float, hurtTime: Float) { mainScope.launch { TargetHudOverlay.showTargetHud(user, null, distance, maxdistance, hurtTime) } } }
412
0.939542
1
0.939542
game-dev
MEDIA
0.708952
game-dev,networking
0.860503
1
0.860503
gta-reversed/gta-reversed
7,263
source/game_sa/Tasks/TaskTypes/TaskComplexPolicePursuit.cpp
#include "StdInc.h" #include "TaskComplexPolicePursuit.h" #include "TaskComplexArrestPed.h" #include "TaskComplexSeekEntity.h" #include "SeekEntity/PosCalculators/EntitySeekPosCalculatorStandard.h" #include "TaskSimpleStandStill.h" #include "TaskSimpleScratchHead.h" void CTaskComplexPolicePursuit::InjectHooks() { RH_ScopedVirtualClass(CTaskComplexPolicePursuit, 0x8709d4, 11); RH_ScopedCategory("Tasks/TaskTypes"); RH_ScopedInstall(Constructor, 0x68BA70); RH_ScopedInstall(Destructor, 0x68D880); RH_ScopedInstall(SetWeapon, 0x68BAD0); RH_ScopedInstall(ClearPursuit, 0x68BD90); RH_ScopedInstall(SetPursuit, 0x68BBD0); RH_ScopedInstall(PersistPursuit, 0x68BDC0); RH_ScopedInstall(CreateSubTask, 0x68D910); RH_ScopedVMTInstall(Clone, 0x68CDD0); RH_ScopedVMTInstall(GetTaskType, 0x68BAA0); RH_ScopedVMTInstall(MakeAbortable, 0x68BAB0); RH_ScopedVMTInstall(CreateNextSubTask, 0x68BAC0); RH_ScopedVMTInstall(CreateFirstSubTask, 0x6908E0); RH_ScopedVMTInstall(ControlSubTask, 0x690920); } CTaskComplexPolicePursuit::CTaskComplexPolicePursuit(const CTaskComplexPolicePursuit& o) : CTaskComplexPolicePursuit{} { } // 0x68D880 CTaskComplexPolicePursuit::~CTaskComplexPolicePursuit() { if (m_Pursuer) { ClearPursuit(m_Pursuer); } } // 0x68BAD0 // Make sure cop has a weapon on them void CTaskComplexPolicePursuit::SetWeapon(CPed* ped) { // `ped` is the pursuer const auto wantedLevel = FindPlayerWanted()->GetWantedLevel(); // At level 0 we don't do anything (I don't think this is possible anyways) if (wantedLevel == 0) { return; } if (wantedLevel > 1) { if (ped->GetActiveWeapon().GetType() != WEAPON_UNARMED) { // Already has a weapon return; } } else /*wantedLevel == 1*/ { const auto player = FindPlayerPed(); if (player->m_standingOnEntity || ped->m_nPedState == PEDSTATE_ARREST_PLAYER) { return; } if (ped->DoWeHaveWeaponAvailable(WEAPON_NIGHTSTICK)) { switch (player->GetActiveWeapon().GetWeaponInfo(player).m_nWeaponFire) { case WEAPON_FIRE_INSTANT_HIT: case WEAPON_FIRE_PROJECTILE: break; default: ped->SetCurrentWeapon(WEAPON_NIGHTSTICK); return; } } } ped->SetCurrentWeapon(ped->DoWeHaveWeaponAvailable(WEAPON_SHOTGUN) ? WEAPON_SHOTGUN : WEAPON_PISTOL); } // 0x68BD90 void CTaskComplexPolicePursuit::ClearPursuit(CCopPed* pursuer) { if (FindPlayerPed()) { FindPlayerWanted()->RemovePursuitCop(pursuer); } } // 0x68BBD0 bool CTaskComplexPolicePursuit::SetPursuit(CPed* ped) { // Find closest player float minDistSq = FLT_MAX; CPlayerPed* closestPlayer{}; for (const auto& v : CWorld::Players) { const auto plyr = v.m_pPed; if (!plyr) { continue; } const auto distSq = (plyr->GetPosition() - ped->GetPosition()).SquaredMagnitude(); if (distSq >= minDistSq) { continue; } if (plyr->bInVehicle) { if (distSq * plyr->m_pVehicle->GetMoveSpeed().SquaredMagnitude() >= sq(4.f)) { // TODO/BUG: Why `*`? continue; } } closestPlayer = plyr; minDistSq = distSq; } m_Pursued = closestPlayer; return closestPlayer && FindPlayerWanted()->SetPursuitCop(ped->AsCop()); } // 0x68BDC0 bool CTaskComplexPolicePursuit::PersistPursuit(CCopPed* pursuer) { const auto wanted = FindPlayerWanted(); if (pursuer->m_fHealth <= 0.f) { // 0x68BDD0 ClearPursuit(pursuer); } else if (CCullZones::NoPolice() && !m_IsRoadBlockCop) { // 0x68BDF1 if (pursuer->bHitSomethingLastFrame) { // 0x68BE01 m_IsPlayerInCullZone = m_IsRoadBlockCop = true; ClearPursuit(pursuer); } } else if (!CCullZones::NoPolice() && m_IsPlayerInCullZone) { // 0x68BE16 m_IsPlayerInCullZone = m_IsRoadBlockCop = false; ClearPursuit(pursuer); } else if (wanted->GetWantedLevel() == 0) { // 0x68BE43 if (m_IsRoadBlockCop && !m_IsPlayerInCullZone) { m_IsPlayerInCullZone = m_IsRoadBlockCop = false; ClearPursuit(pursuer); } } wanted->RemoveExcessPursuitCops(); // 0x68BE5D return wanted->IsInPursuit(pursuer); } // 0x68D910 CTask* CTaskComplexPolicePursuit::CreateSubTask(eTaskType taskType, CPed* ped) { switch (taskType) { case TASK_COMPLEX_ARREST_PED: return new CTaskComplexArrestPed{m_Pursued}; case TASK_COMPLEX_SEEK_ENTITY: return new CTaskComplexSeekEntity<CEntitySeekPosCalculatorStandard>{ ped->m_pVehicle, 50'000, 1'000, ped->m_pVehicle->GetColModel()->GetBoundRadius() + 1.f, 2.f, 2.f, true, true }; case TASK_SIMPLE_STAND_STILL: return new CTaskSimpleStandStill{}; case TASK_SIMPLE_SCRATCH_HEAD: return new CTaskSimpleScratchHead{}; case TASK_FINISHED: return nullptr; default: NOTSA_UNREACHABLE("Invalid TaskType({})", taskType); } } // 0x6908E0 CTask* CTaskComplexPolicePursuit::CreateFirstSubTask(CPed* ped) { if (SetPursuit(ped->AsCop())) { return CreateSubTask(TASK_COMPLEX_ARREST_PED, ped); } m_CouldJoinPursuit = false; return CreateSubTask(TASK_FINISHED, ped); } // 0x690920 CTask* CTaskComplexPolicePursuit::ControlSubTask(CPed* ped) { const auto nextSubTaskType = GetNextSubTaskType(ped->AsCop()); if (m_pSubTask->GetTaskType() == TASK_COMPLEX_ARREST_PED || nextSubTaskType == TASK_COMPLEX_ARREST_PED) { // 0x690A3D SetWeapon(ped); } if (nextSubTaskType == TASK_NONE || !m_pSubTask->MakeAbortable(ped)) { // 0x690A56 return m_pSubTask; } if (nextSubTaskType != TASK_COMPLEX_ENTER_CAR_AS_DRIVER) { // 0x690A6C return CreateSubTask(nextSubTaskType, ped); } ped->GetEventGroup().Add(CEventVehicleToSteal{ ped->m_pVehicle }); return new CTaskSimpleScratchHead{}; } // 0x690956 (not a function originally) eTaskType CTaskComplexPolicePursuit::GetNextSubTaskType(CCopPed* pursuer) { // ped is the pursuer const auto plyrWanted = FindPlayerWanted(); if (PersistPursuit(pursuer)) { // 0x690956 return TASK_NONE; } if (m_IsRoadBlockCop && (!pursuer->bStayInSamePlace || pursuer->GetActiveWeapon().GetType() != WEAPON_PISTOL)) { // 0x690991 (Inverted) pursuer->SetCurrentWeapon(WEAPON_PISTOL); pursuer->bStayInSamePlace = true; return TASK_COMPLEX_ARREST_PED; } if (m_pSubTask->GetTaskType() == TASK_COMPLEX_ARREST_PED) { // 0x6909BB if (pursuer->bInVehicle) { return TASK_FINISHED; } if (!pursuer->m_pVehicle) { return TASK_SIMPLE_STAND_STILL; } if (plyrWanted->GetWantedLevel() == 0) { // 0x6909D7 return TASK_COMPLEX_ENTER_CAR_AS_DRIVER; } if ((pursuer->m_pVehicle->GetPosition() - pursuer->GetPosition()).SquaredMagnitude() <= sq(5.f)) { return TASK_COMPLEX_SEEK_ENTITY; } } return TASK_NONE; }
412
0.909787
1
0.909787
game-dev
MEDIA
0.977298
game-dev
0.96894
1
0.96894
DimensionalDevelopment/DimDoors
1,829
common/src/main/java/org/dimdev/dimdoors/world/decay/DecayCondition.java
package org.dimdev.dimdoors.world.decay; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Function; public interface DecayCondition { Codec<DecayCondition> CODEC = DecayConditionType.CODEC.dispatch("type", DecayCondition::getType, DecayConditionType::codec); Codec<List<DecayCondition>> LIST_CODEC = Codec.either(CODEC, CODEC.listOf()).xmap(either -> either.map(List::of, Function.identity()), conditions -> conditions.size() > 1 ? Either.right(conditions) : Either.left(conditions.get(0))); DecayCondition NONE = new DecayCondition() { private static final String ID = "none"; @Override public DecayConditionType<? extends DecayCondition> getType() { return DecayConditionType.NONE_CONDITION_TYPE.get(); } @Override public boolean test(Level world, BlockPos pos, BlockState origin, BlockState targetBlock, FluidState targetFluid, DecaySource source) { return false; } }; DecayConditionType<? extends DecayCondition> getType(); boolean test(Level world, BlockPos pos, BlockState origin, BlockState targetBlock, FluidState targetFluid, DecaySource source); default Set<ResourceKey<Fluid>> constructApplicableFluids() { return Collections.emptySet(); } default Set<ResourceKey<Block>> constructApplicableBlocks() { return Collections.emptySet(); } }
412
0.623406
1
0.623406
game-dev
MEDIA
0.997405
game-dev
0.723453
1
0.723453
Dimbreath/AzurLaneData
3,493
en-US/view/guild/subpages/member/guildappiontpage.lua
slot0 = class("GuildAppiontPage", import(".GuildMemberBasePage")) function slot0.getUIName(slot0) return "GuildAppiontPage" end slot1 = { "commander", "deputyCommander", "picked", "normal" } function slot0.OnLoaded(slot0) uv0.super.OnLoaded(slot0) slot0.dutyContainer = slot0:findTF("frame/duty") slot0.print = slot0:findTF("frame/prints/print"):GetComponent(typeof(Image)) slot0.confirmBtn = slot0:findTF("frame/confirm_btn") slot0.nameTF = slot0:findTF("frame/info/name/Text", slot0._tf):GetComponent(typeof(Text)) slot0.iconTF = slot0:findTF("frame/info/shipicon/icon", slot0._tf):GetComponent(typeof(Image)) slot0.starsTF = slot0:findTF("frame/info/shipicon/stars", slot0._tf) slot0.starTF = slot0:findTF("frame/info/shipicon/stars/star", slot0._tf) slot0.levelTF = slot0:findTF("frame/info/level/Text", slot0._tf):GetComponent(typeof(Text)) slot0.circle = slot0:findTF("frame/info/shipicon/frame", slot0._tf) end function slot0.OnInit(slot0) onButton(slot0, slot0._tf, function () uv0:Hide() end, SFX_PANEL) end function slot0.ShouldShow(slot0) return slot0.memberVO.id ~= slot0.playerVO.id end function slot0.OnShow(slot0) slot3 = slot0.guildVO slot5 = slot3:getEnableDuty(slot3:getDutyByMemberId(slot0.playerVO.id), slot0.memberVO.duty) slot6 = nil for slot10, slot11 in ipairs(uv0) do if slot2.duty == slot10 then setText(slot0.dutyContainer:Find(slot11):Find("Text"), i18n("guild_duty_tip_1")) elseif not table.contains(slot5, slot10) then setText(slot13, i18n("guild_duty_tip_2")) end setActive(slot13, not table.contains(slot5, slot10)) setToggleEnabled(slot12, table.contains(slot5, slot10)) onToggle(slot0, slot12, function (slot0) if slot0 then uv0 = uv1 uv2.selectedToggle = uv3 end end, SFX_PANEL) end if slot3:getFaction() == GuildConst.FACTION_TYPE_BLHX then slot0.print.color = Color.New(0.4235294117647059, 0.6313725490196078, 0.9568627450980393) elseif slot7 == GuildConst.FACTION_TYPE_CSZZ then slot0.print.color = Color.New(0.9568627450980393, 0.44313725490196076, 0.42745098039215684) end slot0.nameTF.text = slot2.name slot8 = AttireFrame.attireFrameRes(slot2, isSelf, AttireConst.TYPE_ICON_FRAME, slot2.propose) PoolMgr.GetInstance():GetPrefab("IconFrame/" .. slot8, slot8, true, function (slot0) if IsNil(uv0._tf) then return end if uv0.circle then slot0.name = uv1 findTF(slot0.transform, "icon"):GetComponent(typeof(Image)).raycastTarget = false setParent(slot0, uv0.circle, false) else PoolMgr.GetInstance():ReturnPrefab("IconFrame/" .. uv1, uv1, slot0) end end) LoadSpriteAsync("qicon/" .. Ship.New({ configId = slot2.icon, skin_id = slot2.skinId }):getPainting(), function (slot0) if not IsNil(uv0.iconTF) then uv0.iconTF.sprite = slot0 end end) for slot15 = slot0.starsTF.childCount, pg.ship_data_statistics[slot2.icon].star - 1 do cloneTplTo(slot0.starTF, slot0.starsTF) end for slot15 = 1, slot11 do setActive(slot0.starsTF:GetChild(slot15 - 1), slot15 <= slot9.star) end slot0.levelTF.text = "Lv." .. slot2.level onButton(slot0, slot0.confirmBtn, function () if uv3 == GuildConst.DUTY_COMMANDER and uv2 == GuildConst.DUTY_COMMANDER then pg.MsgboxMgr.GetInstance():ShowMsgBox({ content = i18n("guild_transfer_president_confirm", uv1.name), onYes = function () uv0:emit(GuildMemberMediator.SET_DUTY, uv1.id, uv2) uv0:Hide() end }) else slot0() end end, SFX_CONFIRM) end return slot0
412
0.688432
1
0.688432
game-dev
MEDIA
0.898618
game-dev
0.892467
1
0.892467
dingxiaowei/Aladdin_XLua
1,982
AladdinLuaFrameWork/Assets/AladdinLuaFramework/NGUI/Scripts/Interaction/UIButtonMessage.cs
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2015 Tasharen Entertainment //---------------------------------------------- using UnityEngine; /// <summary> /// Sends a message to the remote object when something happens. /// </summary> [AddComponentMenu("NGUI/Interaction/Button Message (Legacy)")] public class UIButtonMessage : MonoBehaviour { public enum Trigger { OnClick, OnMouseOver, OnMouseOut, OnPress, OnRelease, OnDoubleClick, } public GameObject target; public string functionName; public Trigger trigger = Trigger.OnClick; public bool includeChildren = false; bool mStarted = false; void Start () { mStarted = true; } void OnEnable () { if (mStarted) OnHover(UICamera.IsHighlighted(gameObject)); } void OnHover (bool isOver) { if (enabled) { if (((isOver && trigger == Trigger.OnMouseOver) || (!isOver && trigger == Trigger.OnMouseOut))) Send(); } } void OnPress (bool isPressed) { if (enabled) { if (((isPressed && trigger == Trigger.OnPress) || (!isPressed && trigger == Trigger.OnRelease))) Send(); } } void OnSelect (bool isSelected) { if (enabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller)) OnHover(isSelected); } void OnClick () { if (enabled && trigger == Trigger.OnClick) Send(); } void OnDoubleClick () { if (enabled && trigger == Trigger.OnDoubleClick) Send(); } void Send () { if (string.IsNullOrEmpty(functionName)) return; if (target == null) target = gameObject; if (includeChildren) { Transform[] transforms = target.GetComponentsInChildren<Transform>(); for (int i = 0, imax = transforms.Length; i < imax; ++i) { Transform t = transforms[i]; t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver); } } else { target.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver); } } }
412
0.965393
1
0.965393
game-dev
MEDIA
0.853916
game-dev
0.906932
1
0.906932
OrionFive/Hospitality
1,548
Source/Source/JobGiver_GotoGuestArea.cs
using System.Linq; using Hospitality.Utilities; using RimWorld; using Verse; using Verse.AI; namespace Hospitality { public class JobGiver_GotoGuestArea : ThinkNode { public override float GetPriority(Pawn pawn) { var area = pawn.GetGuestArea(); if (area == null) return 0; if (area.TrueCount == 0) return 0; var result = area[pawn.PositionHeld] ? 0 : 10; return result; } public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { var area = pawn.GetGuestArea(); if (area == null) return ThinkResult.NoJob; if (area.TrueCount == 0) return ThinkResult.NoJob; // Find nearby bool found = CellFinder.TryFindRandomReachableNearbyCell(pawn.Position, pawn.MapHeld, 20, TraverseParms.For(pawn, Danger.Some, TraverseMode.PassDoors), c => area[c], null, out var closeSpot); if (!found) { // Find any closeSpot = area.ActiveCells.InRandomOrder().Where(cell => cell.Walkable(area.Map)).Take(20) .FirstOrDefault(cell => pawn.CanReach(cell, PathEndMode.OnCell, Danger.Some, false, false, TraverseMode.PassDoors)); found = closeSpot.IsValid; } var job = found ? new ThinkResult(new Job(JobDefOf.Goto, closeSpot) {locomotionUrgency = LocomotionUrgency.Jog}, this) : ThinkResult.NoJob; return job; } } }
412
0.993479
1
0.993479
game-dev
MEDIA
0.928777
game-dev
0.959083
1
0.959083
mindstorm38/mc173
17,134
mc173-server/src/command.rs
//! Module for command handlers. use std::mem; use glam::IVec3; use mc173::entity::{BaseKind, Entity, EntityCategory, EntityKind}; use mc173::world::{Event, Weather}; use mc173::item::{self, ItemStack}; use mc173::block; use crate::world::{ServerWorld, TickMode}; use crate::proto::{OutPacket, self}; use crate::player::ServerPlayer; /// Describe all the context when a command is executed by something. pub struct CommandContext<'a> { /// The command parts. pub parts: &'a [&'a str], /// The world to run the command in. pub world: &'a mut ServerWorld, /// The dynamic reference to the command sender. pub player: &'a mut ServerPlayer, } /// Handle a command and execute it. pub fn handle_command(ctx: CommandContext) { let Some(&cmd_name) = ctx.parts.first() else { ctx.player.send_chat(format!("§eNo command, type help!")); return; }; for cmd in COMMANDS { if cmd.name == cmd_name { let res = (cmd.handler)(CommandContext { parts: &ctx.parts[1..], world: ctx.world, player: ctx.player, }); match res { Err(Some(message)) => ctx.player.send_chat(message), Err(None) => ctx.player.send_chat(format!("§eUsage:§r /{} {}", cmd.name, cmd.usage)), _ => {} } return; } } ctx.player.send_chat(format!("§eUnknown command, type help!")); } /// The result of a command, if the result is ok, nothing is done, if the result is an /// error, the optional message is printed, if no message is given the command usage /// is displayed to the player. type CommandResult = Result<(), Option<String>>; /// Describe a command. struct Command { /// The command name. name: &'static str, /// The command usage. usage: &'static str, /// The command description for help message. description: &'static str, /// The command handler to call when executing it. handler: fn(CommandContext) -> CommandResult, } /// Internal array of commands. const COMMANDS: &'static [Command] = &[ Command { name: "help", usage: "", description: "Print all available commands", handler: cmd_help }, Command { name: "give", usage: "<item>[:<damage>] [<size>]", description: "Give item to a player", handler: cmd_give }, Command { name: "spawn", usage: "<entity_kind> [<params>...]", description: "Spawn an entity", handler: cmd_spawn }, Command { name: "time", usage: "", description: "Display world and server time", handler: cmd_time }, Command { name: "weather", usage: "[clear|rain|thunder]", description: "Display world weather", handler: cmd_weather }, Command { name: "pos", usage: "", description: "Display many information about current position", handler: cmd_pos }, Command { name: "effect", usage: "<id> [<data>]", description: "Make some effect in the world", handler: cmd_effect }, Command { name: "path", usage: "<x> <y> <z>", description: "Try to path find to a given position", handler: cmd_path }, Command { name: "tick", usage: "freeze|auto|{step [n]}", description: "Control how the world is being ticked", handler: cmd_tick }, Command { name: "clean", usage: "", description: "Remove all entity in the world except the player", handler: cmd_clean }, Command { name: "explode", usage: "", description: "Make an explosion on the player position", handler: cmd_explode }, Command { name: "perf", usage: "", description: "Display performance indicators for the current world", handler: cmd_perf, }, Command { name: "entity", usage: "<id>", description: "Display debug information of an entity", handler: cmd_entity, }, Command { name: "ib", usage: "", description: "Enable or disable instant breaking", handler: cmd_ib, } ]; fn cmd_help(ctx: CommandContext) -> CommandResult { ctx.player.send_chat(format!("§8=====================================================")); for cmd in COMMANDS { if cmd.usage.is_empty() { ctx.player.send_chat(format!("§a/{}:§r {}", cmd.name, cmd.description)); } else { ctx.player.send_chat(format!("§a/{} {}:§r {}", cmd.name, cmd.usage, cmd.description)); } } Ok(()) } fn cmd_give(ctx: CommandContext) -> CommandResult { if ctx.parts.len() != 1 && ctx.parts.len() != 2 { return Err(None); } let item_raw = ctx.parts[0]; let ( id_raw, metadata_raw ) = item_raw.split_once(':').unwrap_or((item_raw, "")); let id; if let Ok(direct_id) = id_raw.parse::<u16>() { id = direct_id; } else if let Some(name_id) = item::from_name(id_raw) { id = name_id; } else { return Err(Some(format!("§cError: unknown item name or id:§r {id_raw}"))); } let item = item::from_id(id); if item.name.is_empty() { return Err(Some(format!("§cError: unknown item id:§r {id_raw}"))); } let mut stack = ItemStack::new_sized(id, 0, item.max_stack_size); if !metadata_raw.is_empty() { stack.damage = metadata_raw.parse::<u16>() .map_err(|_| format!("§cError: invalid item damage:§r {metadata_raw}"))?; } if let Some(size_raw) = ctx.parts.get(1) { stack.size = size_raw.parse::<u16>() .map_err(|_| format!("§cError: invalid stack size:§r {size_raw}"))?; } ctx.player.send_chat(format!("§aGiving §r{}§a (§r{}:{}§a) x§r{}§a to §r{}", item.name, stack.id, stack.damage, stack.size, ctx.player.username)); ctx.player.pickup_stack(&mut stack); Ok(()) } fn cmd_spawn(ctx: CommandContext) -> CommandResult { let [entity_kind_raw] = *ctx.parts else { return Err(None); }; let entity_kind = match entity_kind_raw { "item" => EntityKind::Item, "boat" => EntityKind::Boat, "minecart" => EntityKind::Minecart, "pig" => EntityKind::Pig, "chicken" => EntityKind::Chicken, "cow" => EntityKind::Cow, "sheep" => EntityKind::Sheep, "zombie" => EntityKind::Zombie, "skeleton" => EntityKind::Skeleton, "ghast" => EntityKind::Ghast, "slime" => EntityKind::Slime, "creeper" => EntityKind::Creeper, "squid" => EntityKind::Squid, "lightning_bolt" => EntityKind::LightningBolt, _ => return Err(Some(format!("§cError: invalid or unsupported entity kind:§r {entity_kind_raw}"))) }; let mut entity = entity_kind.new_default(ctx.player.pos); entity.0.persistent = true; entity.init_natural_spawn(&mut ctx.world.world); let entity_id = ctx.world.world.spawn_entity(entity); ctx.player.send_chat(format!("§aEntity spawned:§r {entity_id}")); Ok(()) } fn cmd_time(ctx: CommandContext) -> CommandResult { ctx.player.send_chat(format!("§aWorld time:§r {}", ctx.world.world.get_time())); ctx.player.send_chat(format!("§aServer time:§r {}", ctx.world.time)); Ok(()) } fn cmd_weather(ctx: CommandContext) -> CommandResult { if ctx.parts.len() == 1 { let weather = match ctx.parts[0] { "clear" => Weather::Clear, "rain" => Weather::Rain, "thunder" => Weather::Thunder, _ => return Err(None) }; ctx.world.world.set_weather(weather); ctx.player.send_chat(format!("§aWeather set to:§r {:?}", weather)); Ok(()) } else if ctx.parts.is_empty() { ctx.player.send_chat(format!("§aWeather:§r {:?}", ctx.world.world.get_weather())); Ok(()) } else { Err(None) } } fn cmd_pos(ctx: CommandContext) -> CommandResult { ctx.player.send_chat(format!("§8=====================================================")); let block_pos = ctx.player.pos.floor().as_ivec3(); ctx.player.send_chat(format!("§aReal:§r {}", ctx.player.pos)); ctx.player.send_chat(format!("§aBlock:§r {}", block_pos)); if let Some(height) = ctx.world.world.get_height(block_pos) { ctx.player.send_chat(format!("§aHeight:§r {}", height)); } let light = ctx.world.world.get_light(block_pos); ctx.player.send_chat(format!("§aBlock light:§r {}", light.block)); ctx.player.send_chat(format!("§aSky light:§r {}", light.sky)); ctx.player.send_chat(format!("§aSky real light:§r {}", light.sky_real)); ctx.player.send_chat(format!("§aBrightness:§r {}", light.brightness())); if let Some(biome) = ctx.world.world.get_biome(block_pos) { ctx.player.send_chat(format!("§aBiome:§r {biome:?}")); } Ok(()) } fn cmd_effect(ctx: CommandContext) -> CommandResult { if ctx.parts.len() != 1 && ctx.parts.len() != 2 { return Err(None); } let effect_raw = ctx.parts[0]; let (effect_id, mut effect_data) = match effect_raw { "click" => (1000, 0), "click2" => (1001, 0), "bow" => (1002, 0), "door" => (1003, 0), "fizz" => (1004, 0), "record_13" => (1005, 2000), "record_cat" => (1005, 2001), "smoke" => (2000, 0), "break" => (2001, 0), _ => { let id = effect_raw.parse::<u32>() .map_err(|_| format!("§cError: invalid effect id:§r {effect_raw}"))?; (id, 0) } }; if let Some(effect_data_raw) = ctx.parts.get(1) { effect_data = effect_data_raw.parse::<u32>() .map_err(|_| format!("§cError: invalid effect data:§r {effect_data_raw}"))?; } let pos = ctx.player.pos.floor().as_ivec3(); ctx.player.send(OutPacket::EffectPlay(proto::EffectPlayPacket { x: pos.x, y: pos.y as i8, z: pos.z, effect_id, effect_data, })); ctx.player.send_chat(format!("§aPlayed effect:§r {effect_id}/{effect_data}")); Ok(()) } fn cmd_path(ctx: CommandContext) -> CommandResult { let [x_raw, y_raw, z_raw] = *ctx.parts else { return Err(None); }; let from = ctx.player.pos.floor().as_ivec3(); let to = IVec3 { x: x_raw.parse::<i32>().map_err(|_| format!("§cError: invalid x:§r {x_raw}"))?, y: y_raw.parse::<i32>().map_err(|_| format!("§cError: invalid y:§r {y_raw}"))?, z: z_raw.parse::<i32>().map_err(|_| format!("§cError: invalid z:§r {z_raw}"))?, }; if let Some(path) = ctx.world.world.find_path(from, to, IVec3::ONE, 20.0) { for pos in path { ctx.world.world.set_block(pos, block::DEAD_BUSH, 0); } Ok(()) } else { Err(Some(format!("§cError: path not found"))) } } fn cmd_tick(ctx: CommandContext) -> CommandResult { match ctx.parts { ["freeze"] => { ctx.player.send_chat(format!("§aWorld ticking:§r freeze")); ctx.world.tick_mode = TickMode::Manual(0); Ok(()) } ["auto"] => { ctx.player.send_chat(format!("§aWorld ticking:§r auto")); ctx.world.tick_mode = TickMode::Auto; Ok(()) } ["step"] => { ctx.player.send_chat(format!("§aWorld ticking:§r step")); ctx.world.tick_mode = TickMode::Manual(1); Ok(()) } ["step", step_count] => { let step_count = step_count.parse::<u32>() .map_err(|_| format!("§cError: invalid step count:§r {step_count}"))?; ctx.player.send_chat(format!("§aWorld ticking:§r {step_count} steps")); ctx.world.tick_mode = TickMode::Manual(step_count); Ok(()) } _ => return Err(None) } } fn cmd_clean(ctx: CommandContext) -> CommandResult { let ids = ctx.world.world.iter_entities().map(|(id, _)| id).collect::<Vec<_>>(); let mut removed_count = 0; for id in ids { if !ctx.world.world.is_player_entity(id) { assert!(ctx.world.world.remove_entity(id, "server clean command")); removed_count += 1; } } ctx.player.send_chat(format!("§aCleaned entities:§r {removed_count}")); Ok(()) } fn cmd_explode(ctx: CommandContext) -> CommandResult { ctx.world.world.explode(ctx.player.pos, 4.0, false, Some(ctx.player.entity_id)); ctx.player.send_chat(format!("§aExplode at:§r {}", ctx.player.pos)); Ok(()) } fn cmd_perf(ctx: CommandContext) -> CommandResult { ctx.player.send_chat(format!("§8=====================================================")); ctx.player.send_chat(format!("§aTick duration:§r {:.1} ms", ctx.world.tick_duration.get() * 1000.0)); ctx.player.send_chat(format!("§aTick interval:§r {:.1} ms", ctx.world.tick_interval.get() * 1000.0)); ctx.player.send_chat(format!("§aEvents:§r {:.1} ({:.1} kB)", ctx.world.events_count.get(), ctx.world.events_count.get() * mem::size_of::<Event>() as f32 / 1000.0)); ctx.player.send_chat(format!("§aEntities:§r {} ({} players)", ctx.world.world.get_entity_count(), ctx.world.world.get_player_entity_count())); let mut categories_count = [0usize; EntityCategory::ALL.len()]; for (_, entity) in ctx.world.world.iter_entities() { categories_count[entity.category() as usize] += 1; } for category in EntityCategory::ALL { ctx.player.send_chat(format!(" §a{category:?}s:§r {}", categories_count[category as usize])); } ctx.player.send_chat(format!("§aBlock ticks:§r {}", ctx.world.world.get_block_tick_count())); ctx.player.send_chat(format!("§aLight updates:§r {}", ctx.world.world.get_light_update_count())); Ok(()) } fn cmd_entity(ctx: CommandContext) -> CommandResult { if ctx.parts.len() != 1 { return Err(None); } let id_raw = ctx.parts[0]; let id = id_raw.parse::<u32>() .map_err(|_| format!("§cError: invalid entity id:§r {id_raw}"))?; let Some(Entity(base, base_kind)) = ctx.world.world.get_entity(id) else { return Err(Some(format!("§cError: unknown entity"))); }; ctx.player.send_chat(format!("§8=====================================================")); ctx.player.send_chat(format!("§aKind:§r {:?} §8| §aPersistent:§r {} §8| §aLifetime:§r {}", base_kind.entity_kind(), base.persistent, base.lifetime)); let bb_size = base.bb.size(); ctx.player.send_chat(format!("§aBound:§r {:.2}/{:.2}/{:.2}:{:.2}/{:.2}/{:.2} ({:.2}/{:.2}/{:.2})", base.bb.min.x, base.bb.min.y, base.bb.min.z, base.bb.max.x, base.bb.max.y, base.bb.max.z, bb_size.x, bb_size.y, bb_size.z)); ctx.player.send_chat(format!("§aPos:§r {:.2}/{:.2}/{:.2} §8| §aVel:§r {:.2}/{:.2}/{:.2}", base.pos.x, base.pos.y, base.pos.z, base.vel.x, base.vel.y, base.vel.z)); ctx.player.send_chat(format!("§aLook:§r {:.2}/{:.2} §8| §aCan Pickup:§r {} §8| §aNo Clip:§r {}", base.look.x, base.look.y, base.can_pickup, base.no_clip)); ctx.player.send_chat(format!("§aOn Ground:§r {} §aIn Water:§r {} §8| §aIn Lava:§r {}", base.on_ground, base.in_water, base.in_lava)); ctx.player.send_chat(format!("§aFall Distance:§r {} §8| §aFire Time:§r {} §8| §aAir Time:§r {}", base.fall_distance, base.fire_time, base.air_time)); ctx.player.send_chat(format!("§aRider Id:§r {:?} §8| §aBobber Id:§r {:?}", base.rider_id, base.bobber_id)); match base_kind { BaseKind::Item(item) => { ctx.player.send_chat(format!("§aItem:§r {} §8| §aDamage:§r {} §8| §aSize:§r {}", item::from_id(item.stack.id).name, item.stack.damage, item.stack.size)); ctx.player.send_chat(format!("§aHealth:§r {} §8| §aFrozen Time:§r {}", item.health, item.frozen_time)); } BaseKind::Painting(painting) => { ctx.player.send_chat(format!("§aBlock Pos:§r {}/{}/{} §8| §aFace:§r {:?} §8| §aArt:§r {:?}", painting.block_pos.x, painting.block_pos.y, painting.block_pos.z, painting.face, painting.art)); } BaseKind::Boat(_) => todo!(), BaseKind::Minecart(_) => todo!(), BaseKind::LightningBolt(_) => todo!(), BaseKind::FallingBlock(_) => todo!(), BaseKind::Tnt(_) => todo!(), BaseKind::Projectile(_, _) => todo!(), BaseKind::Living(_, _) => todo!(), } Ok(()) } fn cmd_ib(ctx: CommandContext) -> CommandResult { if ctx.parts.len() != 0 { return Err(None); } ctx.player.instant_break ^= true; ctx.player.send_chat(format!("§aInstant breaking:§r {}", if ctx.player.instant_break {"enabled"} else {"disabled"})); Ok(()) }
412
0.875914
1
0.875914
game-dev
MEDIA
0.882923
game-dev
0.738432
1
0.738432
Drommedhar/DlssUpdater
3,076
DlssUpdater/GameLibrary/Steam/VdfParser.cs
using System.IO; namespace DlssUpdater.GameLibrary.Steam; public class VdfParser { private readonly string _path; private string? _data; public VdfParser(string path) { _path = path; } public async Task<bool> Load() { if (!File.Exists(_path)) { return false; } _data = await File.ReadAllTextAsync(_path); return true; } public List<T> GetValuesForKey<T>(string key) { var genericType = typeof(T); List<T> values = []; var indices = findKeyIndices(key); foreach (var item in indices) { if (genericType == typeof(string)) { // Only parse the next string we can find var value = getString(item + key.Length); if (value is null) { continue; } if (value is T convertedValue) { values.Add(convertedValue); } } if (genericType == typeof(List<string>)) { // We know there needs to be some kind of object here var objectValues = getObject(item + key.Length); if (objectValues is T convertedValue) { values.Add(convertedValue); } } } return values; } private string? getString(int start) { var startIndex = _data!.IndexOf('\"', start + 1); var endIndex = _data!.IndexOf('\"', startIndex + 1); if (startIndex == -1 || endIndex == -1) { return null; } return _data!.Substring(startIndex + 1, endIndex - startIndex - 1); } private List<string> getObject(int start) { List<string> objects = []; var objectStart = _data!.IndexOf('{', start + 1); var objectEnd = _data!.IndexOf('}', start + 1); if (objectStart == -1 || objectEnd == -1) { return objects; } var startIndex = objectStart; int index; while ((index = _data!.IndexOf('\"', startIndex)) != -1 && index <= objectEnd) { // index now contains the start of the value, find the end var valueEndIndex = _data!.IndexOf('\"', index + 1); if (valueEndIndex == -1) // Should not happen, but better be safe { break; } var value = _data!.Substring(index + 1, valueEndIndex - index - 1); objects.Add(value.Trim()); startIndex = valueEndIndex + 1; } return objects; } private List<int> findKeyIndices(string key) { List<int> keyIndidices = new(); var startIndex = 0; int index; while ((index = _data!.IndexOf(key, startIndex)) != -1) { keyIndidices.Add(index); startIndex = index + 1; } return keyIndidices; } }
412
0.82004
1
0.82004
game-dev
MEDIA
0.366457
game-dev
0.932488
1
0.932488
GarageGames/Qt
2,190
qt-5/qtwebengine/src/3rdparty/chromium/ui/gfx/animation/throb_animation.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/animation/throb_animation.h" #include <limits> namespace gfx { static const int kDefaultThrobDurationMS = 400; ThrobAnimation::ThrobAnimation(AnimationDelegate* target) : SlideAnimation(target), slide_duration_(GetSlideDuration()), throb_duration_(kDefaultThrobDurationMS), cycles_remaining_(0), throbbing_(false) { } void ThrobAnimation::StartThrobbing(int cycles_til_stop) { cycles_til_stop = cycles_til_stop >= 0 ? cycles_til_stop : std::numeric_limits<int>::max(); cycles_remaining_ = cycles_til_stop; throbbing_ = true; SlideAnimation::SetSlideDuration(throb_duration_); if (is_animating()) return; // We're already running, we'll cycle when current loop finishes. if (IsShowing()) SlideAnimation::Hide(); else SlideAnimation::Show(); cycles_remaining_ = cycles_til_stop; } void ThrobAnimation::Reset() { Reset(0); } void ThrobAnimation::Reset(double value) { ResetForSlide(); SlideAnimation::Reset(value); } void ThrobAnimation::Show() { ResetForSlide(); SlideAnimation::Show(); } void ThrobAnimation::Hide() { ResetForSlide(); SlideAnimation::Hide(); } void ThrobAnimation::SetSlideDuration(int duration) { slide_duration_ = duration; } void ThrobAnimation::Step(base::TimeTicks time_now) { LinearAnimation::Step(time_now); if (!is_animating() && throbbing_) { // Were throbbing a finished a cycle. Start the next cycle unless we're at // the end of the cycles, in which case we stop. cycles_remaining_--; if (IsShowing()) { // We want to stop hidden, hence this doesn't check cycles_remaining_. SlideAnimation::Hide(); } else if (cycles_remaining_ > 0) { SlideAnimation::Show(); } else { // We're done throbbing. throbbing_ = false; } } } void ThrobAnimation::ResetForSlide() { SlideAnimation::SetSlideDuration(slide_duration_); cycles_remaining_ = 0; throbbing_ = false; } } // namespace gfx
412
0.900902
1
0.900902
game-dev
MEDIA
0.393601
game-dev
0.925267
1
0.925267
OneUptime/oneuptime
7,750
Scripts/TerraformProvider/GenerateProvider.ts
import { generateOpenAPISpec } from "../OpenAPI/GenerateSpec"; import path from "path"; import fs from "fs"; import Logger from "Common/Server/Utils/Logger"; import { TerraformProviderGenerator } from "./Core/TerraformProviderGenerator"; import { OpenAPIParser } from "./Core/OpenAPIParser"; import { GoModuleGenerator } from "./Core/GoModuleGenerator"; import { ResourceGenerator } from "./Core/ResourceGenerator"; import { DataSourceGenerator } from "./Core/DataSourceGenerator"; import { ProviderGenerator } from "./Core/ProviderGenerator"; import { DocumentationGenerator } from "./Core/DocumentationGenerator"; import { exec } from "child_process"; import { promisify } from "util"; const execAsync: ( command: string, ) => Promise<{ stdout: string; stderr: string }> = promisify(exec); async function main(): Promise<void> { Logger.info("🚀 Starting Terraform Provider Generation Process..."); // Define paths const terraformDir: string = path.resolve(__dirname, "../../Terraform"); const openApiSpecPath: string = path.resolve(terraformDir, "openapi.json"); const providerDir: string = path.resolve( terraformDir, "terraform-provider-oneuptime", ); try { // Step 1: Clean up existing Terraform directory if (fs.existsSync(terraformDir)) { Logger.info("🗑️ Removing existing Terraform directory..."); fs.rmSync(terraformDir, { recursive: true, force: true }); } // Step 2: Generate OpenAPI spec Logger.info("📄 Step 1: Generating OpenAPI specification..."); await generateOpenAPISpec(openApiSpecPath); // Step 3: Parse OpenAPI spec Logger.info("🔍 Step 2: Parsing OpenAPI specification..."); const parser: OpenAPIParser = new OpenAPIParser(); const apiSpec: any = await parser.parseOpenAPISpec(openApiSpecPath); // Step 4: Initialize Terraform provider generator Logger.info("⚙️ Step 3: Initializing Terraform provider generator..."); const generator: TerraformProviderGenerator = new TerraformProviderGenerator({ outputDir: providerDir, providerName: "oneuptime", providerVersion: "1.0.0", goModuleName: "github.com/oneuptime/terraform-provider-oneuptime", }); // Step 5: Generate Go module files Logger.info("📦 Step 4: Generating Go module files..."); const goModuleGen: GoModuleGenerator = new GoModuleGenerator( generator.config, ); await goModuleGen.generateModule(); // Step 6: Generate provider main file Logger.info("🏗️ Step 5: Generating provider main file..."); const providerGen: ProviderGenerator = new ProviderGenerator( generator.config, apiSpec, ); await providerGen.generateProvider(); // Step 7: Generate resources Logger.info("📋 Step 6: Generating Terraform resources..."); const resourceGen: ResourceGenerator = new ResourceGenerator( generator.config, apiSpec, ); await resourceGen.generateResources(); // Step 8: Generate data sources Logger.info("🔍 Step 7: Generating Terraform data sources..."); const dataSourceGen: DataSourceGenerator = new DataSourceGenerator( generator.config, apiSpec, ); await dataSourceGen.generateDataSources(); // Step 9: Generate documentation Logger.info("📚 Step 8: Generating documentation..."); const docGen: DocumentationGenerator = new DocumentationGenerator( generator.config, apiSpec, ); await docGen.generateDocumentation(); // Step 10: Generate build scripts Logger.info("🔨 Step 9: Generating build and installation scripts..."); await generator.generateBuildScripts(); // Step 11: Run go mod tidy Logger.info("📦 Step 10: Running go mod tidy..."); try { const originalCwd: string = process.cwd(); process.chdir(providerDir); await execAsync("go mod tidy"); process.chdir(originalCwd); Logger.info("✅ go mod tidy completed successfully"); } catch (error) { Logger.warn( `⚠️ go mod tidy failed: ${error instanceof Error ? error.message : "Unknown error"}`, ); } // Step 12: Build the provider for multiple platforms Logger.info("🔨 Step 11: Building the provider for multiple platforms..."); try { const originalCwd: string = process.cwd(); process.chdir(providerDir); // First build for current platform await execAsync("go build"); Logger.info("✅ go build completed successfully"); // Check if make is available for multi-platform build try { await execAsync("which make"); // Then build for all platforms (this creates the builds directory) await execAsync("make release"); Logger.info("✅ Multi-platform build completed successfully"); } catch { Logger.warn( "⚠️ 'make' command not available, building platforms manually...", ); // Create builds directory manually await execAsync("mkdir -p ./builds"); // Build for each platform manually const platforms: Array<{ os: string; arch: string; ext?: string; }> = [ { os: "darwin", arch: "amd64" }, { os: "darwin", arch: "arm" }, { os: "darwin", arch: "arm64" }, { os: "linux", arch: "amd64" }, { os: "linux", arch: "386" }, { os: "linux", arch: "arm" }, { os: "linux", arch: "arm64" }, { os: "windows", arch: "amd64", ext: ".exe" }, { os: "windows", arch: "386", ext: ".exe" }, { os: "windows", arch: "arm", ext: ".exe" }, { os: "windows", arch: "arm64", ext: ".exe" }, { os: "freebsd", arch: "amd64" }, { os: "freebsd", arch: "386" }, { os: "freebsd", arch: "arm" }, { os: "freebsd", arch: "arm64" }, { os: "openbsd", arch: "amd64" }, { os: "openbsd", arch: "386" }, { os: "openbsd", arch: "arm" }, { os: "openbsd", arch: "arm64" }, { os: "solaris", arch: "amd64" }, ]; for (const platform of platforms) { const ext: string = platform.ext || ""; const binaryName: string = `terraform-provider-oneuptime_${platform.os}_${platform.arch}${ext}`; const buildCmd: string = `GOOS=${platform.os} GOARCH=${platform.arch} go build -o ./builds/${binaryName}`; try { await execAsync(buildCmd); Logger.info(`✅ Built ${binaryName}`); } catch (platformError) { Logger.warn( `⚠️ Failed to build ${binaryName}: ${platformError instanceof Error ? platformError.message : "Unknown error"}`, ); } } Logger.info("✅ Manual multi-platform build completed"); } process.chdir(originalCwd); } catch (error) { Logger.warn( `⚠️ Build failed: ${error instanceof Error ? error.message : "Unknown error"}`, ); } Logger.info("✅ Terraform provider generation completed successfully!"); Logger.info(`📁 Provider generated at: ${providerDir}`); Logger.info("🎯 Next steps:"); Logger.info(" 1. cd Terraform/terraform-provider-oneuptime"); Logger.info(" 2. Run tests with: go test ./..."); Logger.info(" 3. Install locally with: ./install.sh"); } catch (error) { Logger.error( `❌ Error during Terraform provider generation: ${error instanceof Error ? error.message : "Unknown error"}`, ); throw new Error( `Failed to generate Terraform provider: ${ error instanceof Error ? error.message : "Unknown error" }`, ); } } main().catch((err: Error) => { Logger.error(`💥 Unexpected error: ${err.message}`); process.exit(1); });
412
0.951223
1
0.951223
game-dev
MEDIA
0.32993
game-dev
0.926484
1
0.926484
magefree/mage
2,588
Mage.Sets/src/mage/cards/r/Reprocess.java
package mage.cards.r; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.effects.OneShotEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.filter.common.FilterControlledPermanent; import mage.filter.predicate.Predicates; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.common.TargetControlledPermanent; import mage.target.common.TargetSacrifice; /** * * @author LoneFox */ public final class Reprocess extends CardImpl { public Reprocess(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{2}{B}{B}"); // Sacrifice any number of artifacts, creatures, and/or lands. Draw a card for each permanent sacrificed this way. this.getSpellAbility().addEffect(new ReprocessEffect()); } private Reprocess(final Reprocess card) { super(card); } @Override public Reprocess copy() { return new Reprocess(this); } } class ReprocessEffect extends OneShotEffect { private static final FilterControlledPermanent filter = new FilterControlledPermanent("artifacts, creatures, and/or lands"); static { filter.add(Predicates.or(CardType.ARTIFACT.getPredicate(), CardType.CREATURE.getPredicate(), CardType.LAND.getPredicate())); } public ReprocessEffect() { super(Outcome.Neutral); staticText = "Sacrifice any number of artifacts, creatures, and/or lands. Draw a card for each permanent sacrificed this way."; } private ReprocessEffect(final ReprocessEffect effect) { super(effect); } @Override public ReprocessEffect copy() { return new ReprocessEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); if (player == null){ return false; } int amount = 0; TargetSacrifice toSacrifice = new TargetSacrifice(0, Integer.MAX_VALUE, filter); if(player.choose(Outcome.Sacrifice, toSacrifice, source, game)) { for(UUID uuid : toSacrifice.getTargets()){ Permanent permanent = game.getPermanent(uuid); if(permanent != null){ permanent.sacrifice(source, game); amount++; } } player.drawCards(amount, source, game); } return true; } }
412
0.970531
1
0.970531
game-dev
MEDIA
0.985572
game-dev
0.991778
1
0.991778
autoresbot/resbot-md
2,125
plugins/OWNER/del sewa.js
const { deleteSewa } = require("@lib/sewa"); async function handle(sock, messageInfo) { const { remoteJid, message, content, prefix, command } = messageInfo; // Validasi input if (!content || !content.trim()) { return await sock.sendMessage( remoteJid, { text: `_⚠️ Format Penggunaan:_\n\n_💬 Contoh:_ _*${prefix + command} 123xxxxx@g.us*_\n\n_Untuk mendapatkan ID grup, silakan ketik *.listsewa*_` }, { quoted: message } ); } // Validasi format ID grup if (!content.includes("@g.us")) { return await sock.sendMessage( remoteJid, { text: `_⚠️ Format tidak valid!_\n\n_Pastikan ID grup mengandung '@g.us'._\n\n_💬 Contoh penggunaan:_ _*${prefix + command} 123xxxxx@g.us*_` }, { quoted: message } ); } try { // Hapus data sewa berdasarkan ID grup const result = await deleteSewa(content.trim()); if (result) { // Pesan berhasil return await sock.sendMessage( remoteJid, { text: `✅ _Berhasil menghapus data sewa untuk ID grup:_ *${content}*` }, { quoted: message } ); } else { // Pesan jika ID tidak ditemukan return await sock.sendMessage( remoteJid, { text: `⚠️ _ID grup tidak ditemukan:_ *${content}*\n\n_Pastikan ID grup benar atau tersedia di daftar sewa._` }, { quoted: message } ); } } catch (error) { console.error("Gagal menghapus ID grup:", error); // Pesan error return await sock.sendMessage( remoteJid, { text: `⚠️ _Terjadi kesalahan saat menghapus data sewa._\n\n_Error:_ ${error.message}` }, { quoted: message } ); } } module.exports = { handle, Commands : ["delsewa"], OnlyPremium : false, OnlyOwner : true };
412
0.760744
1
0.760744
game-dev
MEDIA
0.508681
game-dev,web-backend
0.861789
1
0.861789
soldat/soldat
19,019
shared/network/NetworkServerSprite.pas
unit NetworkServerSprite; interface uses // delphi and system units SysUtils, Classes, // helper units Vector, {$IFDEF SCRIPT} ScriptDispatcher, {$ENDIF} // soldat units Steam, Net, Sprites, Weapons, Constants, PolyMap; procedure ServerSpriteSnapshot(r: Byte); procedure ServerSpriteSnapshotMajor(r: Byte); procedure ServerSpriteSnapshotMajorSingle(Who: Byte; r: Byte); procedure ServerSkeletonSnapshot(r: Byte); procedure ServerSpriteDeltas(i: Byte); procedure ServerSpriteDeltasMouse(i: Byte); procedure ServerSpriteDeath(Who, Killer, BulletNum, Where: Integer); procedure ServerHandleClientSpriteSnapshot_Dead(NetMessage: PSteamNetworkingMessage_t); procedure ServerHandleClientSpriteSnapshot_Mov(NetMessage: PSteamNetworkingMessage_t); procedure ServerHandleClientSpriteSnapshot(NetMessage: PSteamNetworkingMessage_t); var OldMovementMsg: array[1..MAX_SPRITES, 1..MAX_SPRITES] of TMsg_ServerSpriteDelta_Movement; OldMouseAimMsg: array[1..MAX_SPRITES, 1..MAX_SPRITES] of TMsg_ServerSpriteDelta_MouseAim; OldWeaponsMsg: array[1..MAX_SPRITES, 1..MAX_SPRITES] of TMsg_ServerSpriteDelta_Weapons; OldHelmetMsg: array[1..MAX_SPRITES, 1..MAX_SPRITES] of TMsg_ServerSpriteDelta_Helmet; OldSpriteSnapshotMsg: array[1..MAX_SPRITES] of TMsg_ServerSpriteSnapshot; Time_SpriteSnapshot: array[1..MAX_SPRITES] of Integer; Time_SpriteSnapshot_Mov: array[1..MAX_SPRITES] of Integer; implementation uses Server, NetworkUtils, Game, Demo; // SERVER SNAPSHOT procedure ServerSpriteSnapshot(r: Byte); var ServerMsg: TMsg_ServerSpriteSnapshot; i, j: Integer; b: TVector2; begin // SERVER SPRITES SNAPSHOT for i := 1 to MAX_SPRITES do if Sprite[i].Active and not Sprite[i].DeadMeat and Sprite[i].IsNotSpectator() then begin // active player/sprite ServerMsg.Header.ID := MsgID_ServerSpriteSnapshot; // assign sprite values to ServerMsg ServerMsg.Pos := SpriteParts.Pos[i]; ServerMsg.Velocity := SpriteParts.Velocity[i]; ServerMsg.Num := Sprite[i].Num; ServerMsg.Health := Sprite[i].Health; ServerMsg.Position := Sprite[i].Position; ServerMsg.ServerTicks := ServerTickCounter; EncodeKeys(Sprite[i], ServerMsg.Keys16); ServerMsg.MouseAimY := Sprite[i].Control.MouseAimY; ServerMsg.MouseAimX := Sprite[i].Control.MouseAimX; ServerMsg.Look := 0; if Sprite[i].WearHelmet = 0 then ServerMsg.Look := ServerMsg.Look or B1; if Sprite[i].HasCigar = 5 then ServerMsg.Look := ServerMsg.Look or B2; if Sprite[i].HasCigar = 10 then ServerMsg.Look := ServerMsg.Look or B3; if Sprite[i].WearHelmet = 2 then ServerMsg.Look := ServerMsg.Look or B4; ServerMsg.WeaponNum := Sprite[i].Weapon.Num; ServerMsg.SecondaryWeaponNum := Sprite[i].SecondaryWeapon.Num; ServerMsg.AmmoCount := Sprite[i].Weapon.AmmoCount; ServerMsg.GrenadeCount := Sprite[i].TertiaryWeapon.AmmoCount; if Sprite[i].Vest < 0 then Sprite[i].Vest := 0; if Sprite[i].Vest > DEFAULTVEST then Sprite[i].Vest := DEFAULTVEST; ServerMsg.Vest := Sprite[i].Vest; b := Vec2Subtract(ServerMsg.Velocity, OldSpriteSnapshotMsg[i].Velocity); if ((Vec2Length(b) > VELDELTA)) or (MainTickCounter - Time_SpriteSnapshot_Mov[i] > 30) or (MainTickCounter - Time_SpriteSnapshot[i] > 30) or (ServerMsg.Health <> OldSpriteSnapshotMsg[i].Health) or (ServerMsg.Position <> OldSpriteSnapshotMsg[i].Position) or (ServerMsg.Keys16 <> OldSpriteSnapshotMsg[i].Keys16) or (ServerMsg.WeaponNum <> OldSpriteSnapshotMsg[i].WeaponNum) or (ServerMsg.SecondaryWeaponNum <> OldSpriteSnapshotMsg[i].SecondaryWeaponNum) or (ServerMsg.AmmoCount <> OldSpriteSnapshotMsg[i].AmmoCount) or (ServerMsg.GrenadeCount <> OldSpriteSnapshotMsg[i].GrenadeCount) or (ServerMsg.Vest <> OldSpriteSnapshotMsg[i].Vest) then begin // send to all if r = NETW then for j := 1 to MAX_PLAYERS do if (Sprite[j].Active) and (Sprite[j].Player.ControlMethod = HUMAN) then UDP.SendData(ServerMsg, sizeof(ServerMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); end; if r = NETW then OldSpriteSnapshotMsg[i] := ServerMsg; end; // sprite[i] end; // SERVER SNAPSHOT MAJOR procedure ServerSpriteSnapshotMajor(r: Byte); var ServerMsg: TMsg_ServerSpriteSnapshot_Major; i, j: Integer; b: TVector2; begin // SERVER SPRITES SNAPSHOT for i := 1 to MAX_SPRITES do if Sprite[i].Active and not Sprite[i].DeadMeat and Sprite[i].IsNotSpectator() then begin // active player/sprite ServerMsg.Header.ID := MsgID_ServerSpriteSnapshot_Major; // assign sprite values to ServerMsg ServerMsg.Pos := SpriteParts.Pos[i]; ServerMsg.Velocity := SpriteParts.Velocity[i]; ServerMsg.Num := Sprite[i].Num; ServerMsg.Health := Sprite[i].Health; ServerMsg.Position := Sprite[i].Position; ServerMsg.ServerTicks := ServerTickCounter; EncodeKeys(Sprite[i], ServerMsg.Keys16); ServerMsg.MouseAimY := Sprite[i].Control.MouseAimY; ServerMsg.MouseAimX := Sprite[i].Control.MouseAimX; b := Vec2Subtract(ServerMsg.Velocity, OldSpriteSnapshotMsg[i].Velocity); if ((Vec2Length(b) > VELDELTA)) or ((MainTickCounter - Time_SpriteSnapshot_Mov[i]) > 30) or (ServerMsg.Position <> OldSpriteSnapshotMsg[i].Position) or (ServerMsg.Health <> OldSpriteSnapshotMsg[i].Health) or (ServerMsg.Keys16 <> OldSpriteSnapshotMsg[i].Keys16) then begin // send to all if r = NETW then for j := 1 to MAX_PLAYERS do if (Sprite[j].Active) and (Sprite[j].Player.ControlMethod = HUMAN) then UDP.SendData(ServerMsg, sizeof(ServerMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); end; if r = NETW then begin OldSpriteSnapshotMsg[i].Keys16 := ServerMsg.Keys16; OldSpriteSnapshotMsg[i].Position := ServerMsg.Position; OldSpriteSnapshotMsg[i].Pos := ServerMsg.Pos; OldSpriteSnapshotMsg[i].Velocity := ServerMsg.Velocity; end; end; // sprite[i] end; procedure ServerSpriteSnapshotMajorSingle(Who: Byte; r: Byte); var ServerMsg: TMsg_ServerSpriteSnapshot_Major; i: Integer; begin ServerMsg.Header.ID := MsgID_ServerSpriteSnapshot_Major; // assign sprite values to ServerMsg ServerMsg.Pos := SpriteParts.Pos[who]; ServerMsg.Velocity := SpriteParts.Velocity[who]; ServerMsg.Num := Sprite[who].Num; ServerMsg.Health := Sprite[who].Health; ServerMsg.Position := Sprite[who].Position; ServerMsg.ServerTicks := ServerTickCounter; EncodeKeys(Sprite[who], ServerMsg.Keys16); ServerMsg.MouseAimY := Sprite[who].Control.MouseAimY; ServerMsg.MouseAimX := Sprite[who].Control.MouseAimX; // send to all if r = NETW then for i := 1 to MAX_PLAYERS do if (Sprite[i].Active) and (Sprite[i].Player.ControlMethod = HUMAN) then begin UDP.SendData(ServerMsg, sizeof(ServerMsg), Sprite[i].Player.peer, k_nSteamNetworkingSend_Unreliable); end; if r = NETW then begin OldSpriteSnapshotMsg[who].Keys16 := ServerMsg.Keys16; OldSpriteSnapshotMsg[who].Position := ServerMsg.Position; OldSpriteSnapshotMsg[who].Pos := ServerMsg.Pos; OldSpriteSnapshotMsg[who].Velocity := ServerMsg.Velocity; end; end; // SERVER SKELETON SNAPSHOT procedure ServerSkeletonSnapshot(r: Byte); var SkeletonMsg: TMsg_ServerSkeletonSnapshot; i, j: Integer; begin for i := 1 to MAX_SPRITES do if Sprite[i].Active and Sprite[i].DeadMeat and Sprite[i].IsNotSpectator() then begin // active player/sprite SkeletonMsg.Header.ID := MsgID_ServerSkeletonSnapshot; // assign sprite values to SkeletonMsg SkeletonMsg.Num := Sprite[i].Num; if Sprite[i].RespawnCounter > 0 then SkeletonMsg.RespawnCounter := Sprite[i].RespawnCounter else SkeletonMsg.RespawnCounter := 0; // send to all if r = NETW then for j := 1 to MAX_PLAYERS do if (Sprite[j].Active) and (Sprite[j].Player.ControlMethod = HUMAN) then UDP.SendData(SkeletonMsg, sizeof(SkeletonMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); end; end; procedure ServerSpriteDeath(Who, Killer, BulletNum, Where: Integer); var SpriteDeathMsg: TMsg_SpriteDeath; j: Integer; begin SpriteDeathMsg.Header.ID := MsgID_SpriteDeath; // assign sprite values to SpriteDeathMsg SpriteDeathMsg.Num := Who; SpriteDeathMsg.Killer := Killer; SpriteDeathMsg.Where := Where; SpriteDeathMsg.RespawnCounter := Sprite[Who].RespawnCounter; SpriteDeathMsg.Health := Sprite[Who].Health; SpriteDeathMsg.OnFire := Sprite[Who].OnFire; SpriteDeathMsg.ShotDistance := ShotDistance; SpriteDeathMsg.ShotLife := ShotLife; SpriteDeathMsg.ShotRicochet := ShotRicochet; if (BulletNum = -1) then SpriteDeathMsg.KillBullet := 250 else begin // if Bullet[BulletNum].OwnerWeapon = 0 then // SpriteDeathMsg.KillBullet := 250; SpriteDeathMsg.KillBullet := Bullet[BulletNum].OwnerWeapon; if Bullet[BulletNum].Style = 2 then SpriteDeathMsg.KillBullet := 222; if Bullet[BulletNum].Style = 10 then SpriteDeathMsg.KillBullet := 210; if Bullet[BulletNum].Style = 5 then SpriteDeathMsg.KillBullet := 205; if Bullet[BulletNum].Style = 7 then SpriteDeathMsg.KillBullet := 207; if Bullet[BulletNum].Style = 8 then SpriteDeathMsg.KillBullet := 208; if Bullet[BulletNum].Style = 6 then SpriteDeathMsg.KillBullet := 206; if Bullet[BulletNum].OwnerWeapon = Guns[KNIFE].Num then SpriteDeathMsg.KillBullet := 211; if Bullet[BulletNum].OwnerWeapon = Guns[CHAINSAW].Num then SpriteDeathMsg.KillBullet := 212; if Bullet[BulletNum].Style = 12 then SpriteDeathMsg.KillBullet := 224; if Bullet[BulletNum].Style = 13 then SpriteDeathMsg.KillBullet := 211; if Bullet[BulletNum].Style = 14 then SpriteDeathMsg.KillBullet := 225; end; for j := 1 to 16 do begin SpriteDeathMsg.Pos[j].X := Sprite[Who].Skeleton.Pos[j].X; SpriteDeathMsg.Pos[j].Y := Sprite[Who].Skeleton.Pos[j].Y; SpriteDeathMsg.OldPos[j].X := Sprite[Who].Skeleton.OldPos[j].X; SpriteDeathMsg.OldPos[j].Y := Sprite[Who].Skeleton.OldPos[j].Y; end; SpriteDeathMsg.Constraints := 0; if not Sprite[Who].Skeleton.Constraints[2].Active then SpriteDeathMsg.Constraints := SpriteDeathMsg.Constraints or B1; if not Sprite[Who].Skeleton.Constraints[4].Active then SpriteDeathMsg.Constraints := SpriteDeathMsg.Constraints or B2; if not Sprite[Who].Skeleton.Constraints[20].Active then SpriteDeathMsg.Constraints := SpriteDeathMsg.Constraints or B3; if not Sprite[Who].Skeleton.Constraints[21].Active then SpriteDeathMsg.Constraints := SpriteDeathMsg.Constraints or B4; if not Sprite[Who].Skeleton.Constraints[23].Active then SpriteDeathMsg.Constraints := SpriteDeathMsg.Constraints or B5; for j := 1 to MAX_PLAYERS do if (Sprite[j].Active) and (Sprite[j].Player.ControlMethod = HUMAN) then UDP.SendData(SpriteDeathMsg, sizeof(SpriteDeathMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); end; // SEND DELTAS OF SPRITE procedure ServerSpriteDeltas(i: Byte); var MovementMsg: TMsg_ServerSpriteDelta_Movement; WeaponsMsg: TMsg_ServerSpriteDelta_Weapons; HelmetMsg: TMsg_ServerSpriteDelta_Helmet; j: Integer; a, b: TVector2; begin HelmetMsg.Header.ID := MsgID_Delta_Helmet; HelmetMsg.Num := i; HelmetMsg.WearHelmet := Sprite[i].WearHelmet; MovementMsg.Header.ID := MsgID_Delta_Movement; MovementMsg.Num := i; MovementMsg.Velocity := SpriteParts.Velocity[i]; MovementMsg.Pos := SpriteParts.Pos[i]; MovementMsg.ServerTick := ServerTickCounter; EncodeKeys(Sprite[i], MovementMsg.Keys16); MovementMsg.MouseAimY := Sprite[i].Control.MouseAimY; MovementMsg.MouseAimX := Sprite[i].Control.MouseAimX; WeaponsMsg.Header.ID := MsgID_Delta_Weapons; WeaponsMsg.Num := i; WeaponsMsg.WeaponNum := Sprite[i].Weapon.Num; WeaponsMsg.SecondaryWeaponNum := Sprite[i].SecondaryWeapon.Num; WeaponsMsg.AmmoCount := Sprite[i].Weapon.AmmoCount; for j := 1 to MAX_SPRITES do if Sprite[j].Active and (Sprite[j].Player.ControlMethod = HUMAN) and (j <> i) then if PointVisible(SpriteParts.Pos[i].X, SpriteParts.Pos[i].Y, Sprite[j].Player.Camera) or (Sprite[j].IsSpectator() and (Sprite[j].Player.Port = 0)) then // visible to sprite begin a := Vec2Subtract(MovementMsg.Pos, OldMovementMsg[j, i].Pos); b := Vec2Subtract(MovementMsg.Velocity, OldMovementMsg[j, i].Velocity); if (Sprite[i].Player.ControlMethod = HUMAN) or (((Vec2Length(a) > POSDELTA) or (Vec2Length(b) > VELDELTA)) and (MovementMsg.Keys16 <> OldMovementMsg[j, i].Keys16)) then begin UDP.SendData(MovementMsg, sizeof(MovementMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); OldMovementMsg[j, i] := MovementMsg; end; end; for j := 1 to MAX_SPRITES do if Sprite[j].Active and (Sprite[j].Player.ControlMethod = HUMAN) and (j <> i) then if (WeaponsMsg.WeaponNum <> OldWeaponsMsg[j, i].WeaponNum) or (WeaponsMsg.SecondaryWeaponNum <> OldWeaponsMsg[j, i].SecondaryWeaponNum) then if PointVisible(SpriteParts.Pos[i].X, SpriteParts.Pos[i].Y, Sprite[j].Player.Camera) or (Sprite[j].IsSpectator() and (Sprite[j].Player.Port = 0)) then // visible to sprite begin UDP.SendData(WeaponsMsg, sizeof(WeaponsMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); OldWeaponsMsg[j, i] := WeaponsMsg; end; for j := 1 to MAX_SPRITES do if (Sprite[j].Active) and (Sprite[j].Player.ControlMethod = HUMAN) and (j <> i) then if HelmetMsg.WearHelmet <> OldHelmetMsg[j, i].WearHelmet then begin UDP.SendData(HelmetMsg, sizeof(HelmetMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); OldHelmetMsg[j, i] := HelmetMsg; end; end; procedure ServerSpriteDeltasMouse(i: Byte); var MouseAimMsg: TMsg_ServerSpriteDelta_MouseAim; j: Integer; begin MouseAimMsg.Header.ID := MsgID_Delta_MouseAim; MouseAimMsg.Num := i; MouseAimMsg.MouseAimY := Sprite[i].Control.MouseAimY; MouseAimMsg.MouseAimX := Sprite[i].Control.MouseAimX; for j := 1 to MAX_SPRITES do if (Sprite[j].Active) and (Sprite[j].Player.ControlMethod = HUMAN) and (j <> i) then begin UDP.SendData(MouseAimMsg, sizeof(MouseAimMsg), Sprite[j].Player.peer, k_nSteamNetworkingSend_Unreliable); OldMouseAimMsg[j, i] := MouseAimMsg; end; end; procedure ServerHandleClientSpriteSnapshot(NetMessage: PSteamNetworkingMessage_t); var ClientMsg: TMsg_ClientSpriteSnapshot; Player: TPlayer; i: Integer; begin if not VerifyPacket(sizeof(TMsg_ClientSpriteSnapshot), NetMessage^.m_cbSize, MsgID_ClientSpriteSnapshot) then Exit; ClientMsg := PMsg_ClientSpriteSnapshot(NetMessage^.m_pData)^; Player := TPlayer(NetMessage^.m_nConnUserData); i := Player.SpriteNum; Inc(MessagesASecNum[i]); if Sprite[i].DeadMeat then Exit; Sprite[i].Player.Camera := i; {$IFDEF SCRIPT} ForceWeaponCalled := False; if (Sprite[i].Weapon.Num <> ClientMsg.WeaponNum) or (Sprite[i].SecondaryWeapon.Num <> ClientMsg.SecondaryWeaponNum) then begin // event must be before actual weapon apply. // script might've called ForceWeapon, which we should check. // if it did, we don't apply snapshot weapon's as they were already applied // by force weapon. ScrptDispatcher.OnWeaponChange(i, ClientMsg.WeaponNum, ClientMsg.SecondaryWeaponNum, ClientMsg.AmmoCount, ClientMsg.SecondaryAmmoCount); end; if not ForceWeaponCalled then begin {$ENDIF} if Sprite[i].Weapon.Num <> ClientMsg.WeaponNum then begin Sprite[i].ApplyWeaponByNum(ClientMsg.WeaponNum, 1, ClientMsg.AmmoCount); end; if Sprite[i].SecondaryWeapon.Num <> ClientMsg.SecondaryWeaponNum then begin Sprite[i].ApplyWeaponByNum(ClientMsg.SecondaryWeaponNum, 2, ClientMsg.SecondaryAmmoCount); end; {$IFDEF SCRIPT} end; {$ENDIF} if Sprite[i].Weapon.Num = Guns[COLT].Num then Sprite[i].Player.SecWep := 0; if Sprite[i].Weapon.Num = Guns[KNIFE].Num then Sprite[i].Player.SecWep := 1; if Sprite[i].Weapon.Num = Guns[CHAINSAW].Num then Sprite[i].Player.SecWep := 2; if Sprite[i].Weapon.Num = Guns[LAW].Num then Sprite[i].Player.SecWep := 3; Sprite[i].Weapon.AmmoCount := ClientMsg.AmmoCount; Sprite[i].SecondaryWeapon.AmmoCount := ClientMsg.SecondaryAmmoCount; // Toggle prone if it was activated or deactivated Sprite[i].Control.Prone := (ClientMsg.Position = POS_PRONE) xor (Sprite[i].Position = POS_PRONE); if CheckWeaponNotAllowed(i) then begin KickPlayer(i, True, KICK_CHEAT, DAY, 'Not allowed weapon'); Exit; end; ServerSpriteDeltas(i); Time_SpriteSnapshot[i] := MainTickCounter; end; procedure ServerHandleClientSpriteSnapshot_Mov(NetMessage: PSteamNetworkingMessage_t); var ClientMovMsg: TMsg_ClientSpriteSnapshot_Mov; Player: TPlayer; i: Integer; begin if not VerifyPacket(sizeof(TMsg_ClientSpriteSnapshot_Mov), NetMessage^.m_cbSize, MsgID_ClientSpriteSnapshot_Mov) then Exit; ClientMovMsg := PMsg_ClientSpriteSnapshot_Mov(NetMessage^.m_pData)^; Player := TPlayer(NetMessage^.m_nConnUserData); i := Player.SpriteNum; Inc(MessagesASecNum[i]); if Sprite[i].DeadMeat then Exit; CheckOutOfBounds(ClientMovMsg.Pos.X, ClientMovMsg.Pos.Y); CheckOutOfBounds(ClientMovMsg.Velocity.X, ClientMovMsg.Velocity.Y); Sprite[i].Player.Camera := i; SpriteParts.Pos[i] := ClientMovMsg.Pos; SpriteParts.Velocity[i] := ClientMovMsg.Velocity; CheckOutOfBounds(ClientMovMsg.MouseAimX, ClientMovMsg.MouseAimY); Sprite[i].Control.MouseAimX := ClientMovMsg.MouseAimX; Sprite[i].Control.MouseAimY := ClientMovMsg.MouseAimY; DecodeKeys(Sprite[i], ClientMovMsg.Keys16); if Sprite[i].Control.ThrowWeapon = False then Sprite[i].Player.KnifeWarnings := 0; ServerSpriteDeltas(i); Time_SpriteSnapshot_Mov[i] := MainTickCounter; end; procedure ServerHandleClientSpriteSnapshot_Dead(NetMessage: PSteamNetworkingMessage_t); var ClientDeadMsg: TMsg_ClientSpriteSnapshot_Dead; Player: TPlayer; i: Integer; begin if not VerifyPacket(sizeof(TMsg_ClientSpriteSnapshot_Dead), NetMessage^.m_cbSize, MsgID_ClientSpriteSnapshot_Dead) then Exit; ClientDeadMsg := PMsg_ClientSpriteSnapshot_Dead(NetMessage^.m_pData)^; Player := TPlayer(NetMessage^.m_nConnUserData); i := Player.SpriteNum; Inc(MessagesASecNum[i]); if not Sprite[i].DeadMeat then Exit; // assign received sprite info to sprite if ClientDeadMsg.CameraFocus < MAX_SPRITES + 1 then Sprite[i].Player.Camera := ClientDeadMsg.CameraFocus; end; end.
412
0.710695
1
0.710695
game-dev
MEDIA
0.795745
game-dev
0.719226
1
0.719226
rbfx/rbfx
6,756
Source/Samples/49_Urho2DIsometricDemo/Character2D.cpp
// // Copyright (c) 2008-2022 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <Urho3D/Core/Context.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Physics2D/RigidBody2D.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Scene/SceneEvents.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/UI.h> #include <Urho3D/Urho2D/AnimatedSprite2D.h> #include <Urho3D/Urho2D/AnimationSet2D.h> #include "Character2D.h" #include <Urho3D/DebugNew.h> // CharacterIsometric logic component CharacterIsometric::CharacterIsometric(Context* context) : LogicComponent(context), wounded_(false), killed_(false), timer_(0.0f), maxCoins_(0), remainingCoins_(0), remainingLifes_(3), moveSpeedScale_(1.0f), zoom_(0.0f) { } void CharacterIsometric::RegisterObject(Context* context) { context->AddFactoryReflection<CharacterIsometric>(); // These macros register the class attributes to the Context for automatic load / save handling. // We specify the 'Default' attribute mode which means it will be used both for saving into file, and network replication. URHO3D_ATTRIBUTE("Move Speed Scale", float, moveSpeedScale_, 1.0f, AM_DEFAULT); URHO3D_ATTRIBUTE("Camera Zoom", float, zoom_, 0.0f, AM_DEFAULT); URHO3D_ATTRIBUTE("Coins In Level", int, maxCoins_, 0, AM_DEFAULT); URHO3D_ATTRIBUTE("Remaining Coins", int, remainingCoins_, 0, AM_DEFAULT); URHO3D_ATTRIBUTE("Remaining Lifes", int, remainingLifes_, 3, AM_DEFAULT); } void CharacterIsometric::Update(float timeStep) { // Handle wounded/killed states if (killed_) return; if (wounded_) { HandleWoundedState(timeStep); return; } auto* animatedSprite = GetComponent<AnimatedSprite2D>(); auto* input = GetSubsystem<Input>(); // Set direction Vector3 moveDir = Vector3::ZERO; // Reset float speedX = Clamp(MOVE_SPEED_X / zoom_, 0.4f, 1.0f); float speedY = speedX; if (input->GetKeyDown(KEY_A) || input->GetKeyDown(KEY_LEFT)) { moveDir = moveDir + Vector3::LEFT * speedX; animatedSprite->SetFlipX(false); // Flip sprite (reset to default play on the X axis) } if (input->GetKeyDown(KEY_D) || input->GetKeyDown(KEY_RIGHT)) { moveDir = moveDir + Vector3::RIGHT * speedX; animatedSprite->SetFlipX(true); // Flip sprite (flip animation on the X axis) } if (!moveDir.Equals(Vector3::ZERO)) speedY = speedX * moveSpeedScale_; if (input->GetKeyDown(KEY_W) || input->GetKeyDown(KEY_UP)) moveDir = moveDir + Vector3::UP * speedY; if (input->GetKeyDown(KEY_S) || input->GetKeyDown(KEY_DOWN)) moveDir = moveDir + Vector3::DOWN * speedY; // Move if (!moveDir.Equals(Vector3::ZERO)) node_->Translate(moveDir * timeStep); // Animate if (input->GetKeyDown(KEY_SPACE)) { if (animatedSprite->GetAnimation() != "attack") animatedSprite->SetAnimation("attack", LM_FORCE_LOOPED); } else if (!moveDir.Equals(Vector3::ZERO)) { if (animatedSprite->GetAnimation() != "run") animatedSprite->SetAnimation("run"); } else if (animatedSprite->GetAnimation() != "idle") { animatedSprite->SetAnimation("idle"); } } void CharacterIsometric::HandleWoundedState(float timeStep) { auto* body = GetComponent<RigidBody2D>(); auto* animatedSprite = GetComponent<AnimatedSprite2D>(); // Play "hit" animation in loop if (animatedSprite->GetAnimation() != "hit") animatedSprite->SetAnimation("hit", LM_FORCE_LOOPED); // Update timer timer_ += timeStep; if (timer_ > 2.0f) { // Reset timer timer_ = 0.0f; // Clear forces (should be performed by setting linear velocity to zero, but currently doesn't work) body->SetLinearVelocity(Vector2::ZERO); body->SetAwake(false); body->SetAwake(true); // Remove particle emitter node_->GetChild("Emitter", true)->Remove(); // Update lifes UI and counter remainingLifes_ -= 1; auto* ui = GetSubsystem<UI>(); Text* lifeText = static_cast<Text*>(GetSubsystem<UI>()->GetRoot()->GetChild("LifeText", true)); lifeText->SetText(ea::to_string(remainingLifes_)); // Update lifes UI counter // Reset wounded state wounded_ = false; // Handle death if (remainingLifes_ == 0) { HandleDeath(); return; } // Re-position the character to the nearest point if (node_->GetPosition().x_ < 15.0f) node_->SetPosition(Vector3(-5.0f, 11.0f, 0.0f)); else node_->SetPosition(Vector3(18.8f, 9.2f, 0.0f)); } } void CharacterIsometric::HandleDeath() { auto* body = GetComponent<RigidBody2D>(); auto* animatedSprite = GetComponent<AnimatedSprite2D>(); // Set state to 'killed' killed_ = true; // Update UI elements auto* ui = GetSubsystem<UI>(); Text* instructions = static_cast<Text*>(ui->GetRoot()->GetChild("Instructions", true)); instructions->SetText("!!! GAME OVER !!!"); static_cast<Text*>(ui->GetRoot()->GetChild("ExitButton", true))->SetVisible(true); static_cast<Text*>(ui->GetRoot()->GetChild("PlayButton", true))->SetVisible(true); // Show mouse cursor so that we can click auto* input = GetSubsystem<Input>(); input->SetMouseVisible(true); // Put character outside of the scene and magnify him node_->SetPosition(Vector3(-20.0f, 0.0f, 0.0f)); node_->SetScale(1.2f); // Play death animation once if (animatedSprite->GetAnimation() != "dead") animatedSprite->SetAnimation("dead"); }
412
0.932666
1
0.932666
game-dev
MEDIA
0.982438
game-dev
0.951658
1
0.951658
shit-ware/IW4
17,966
ui/popmenu_act2.menu
{ menuDef { name "popmenu_act2" rect 0 0 640 480 0 0 style 1 forecolor 1 1 1 1 focuscolor 1 1 1 1 fullscreen 1 fadeCycle 1 fadeClamp 1 fadeAmount 0.1 onOpen { focusfirst; setLocalVarInt "ui_hide_act_button" ( 1 ); } onClose { setLocalVarInt "ui_hide_act_button" ( 0 ); } onEsc { close self; } itemDef { rect 0 0 640 480 4 4 decoration visible 1 style 3 forecolor 1 1 1 1 background "mw2_main_background" textscale 0.55 } itemDef { rect 0 0 1708 480 0 0 decoration visible 1 style 3 forecolor 1 1 1 0.5 background "mw2_main_cloud_overlay" textscale 0.55 exp rect x ( ( 0 - 107 ) - ( ( float( milliseconds( ) % 60000 ) / 60000 ) * ( 854 ) ) ) } itemDef { rect 0 0 -1708 -480 0 0 decoration visible 1 style 3 forecolor 1 1 1 0.5 background "mw2_main_cloud_overlay" textscale 0.55 exp rect x ( ( - 107 + 854 ) + ( ( float( milliseconds( ) % 50000 ) / 50000 ) * ( 854 ) ) ) } itemDef { rect 0 0 640 480 4 4 decoration visible 1 style 3 forecolor 1 1 1 0 background "mockup_bg_glow" textscale 0.55 exp forecolor a ( ( ( sin( milliseconds( ) / 1500 ) + 1 ) * 0.25 ) + 0.25 ) } itemDef { rect 0 0 640 480 4 4 decoration visible 1 style 3 forecolor 1 1 1 0 background "mockup_bg_glow" textscale 0.55 exp forecolor a ( ( ( sin( milliseconds( ) / 480 ) + 1 ) * 0.25 ) + 0.25 ) } itemDef { rect 0 0 272 28 1 1 decoration visible 1 forecolor 1 1 1 1 textfont 9 textalign 6 textalignx -60 textscale 0.5 text "@MENU_MISSIONS_CAP" } itemDef { rect 0 0 272 28 1 1 decoration visible 1 forecolor 1 1 1 1 textfont 9 textalign 4 textalignx 226 textaligny 4.5 textscale 0.375 text "@MENU_SP_ACT_II_CAPS" } itemDef { rect 222 0 272 28 1 1 decoration autowrapped visible 1 forecolor 1 1 1 1 textfont 9 textalign 4 textscale 0.5 visible when ( 0 ) exp text ( ":" ) } itemDef { rect 0 28 640 356 4 1 decoration visible 1 style 3 forecolor 1 1 1 0.15 background "white" textscale 0.55 } itemDef { rect -126 28 633.383 356 1 1 decoration visible 1 style 3 forecolor 1 1 1 0.2 background "mw2_main_sp_image" textscale 0.55 visible when ( 1 ) } itemDef { rect -32 -4 32 32 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_tl" textscale 0.55 visible when ( 1 ) } itemDef { rect 0 -4 640 32 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_t" textscale 0.55 visible when ( 1 ) } itemDef { rect 640 -4 32 32 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_tr" textscale 0.55 visible when ( 1 ) } itemDef { rect 640 28 32 356 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_r" textscale 0.55 visible when ( 1 ) } itemDef { rect 640 384 32 32 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_br" textscale 0.55 visible when ( 1 ) } itemDef { rect 0 384 640 32 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_b" textscale 0.55 visible when ( 1 ) } itemDef { rect -32 384 32 32 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_bl" textscale 0.55 visible when ( 1 ) } itemDef { rect -32 28 32 356 4 1 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_l" textscale 0.55 visible when ( 1 ) } itemDef { rect -292 28 292 356 3 1 decoration visible 1 style 3 forecolor 0.7 0.7 0.7 1 background "black" textscale 0.55 } itemDef { name "mapimage" rect -282 38 272 272 3 1 decoration visible 1 style 3 forecolor 1 1 1 1 textscale 0.55 exp material ( localvarstring( "ui_level_levelshot" ) ) } itemDef { name "mapimage_gradient" rect -282 316 272 16 3 1 decoration visible 1 style 3 forecolor 0 0 0 0.65 textscale 0.55 visible when ( 0 ) exp material ( "gradient" ) } itemDef { name "description" rect -282 310 272 20 3 1 decoration autowrapped visible 1 forecolor 1 1 1 0.75 textfont 3 textalign 4 textscale 0.375 exp text ( localvarstring( "ui_level_desc" ) ) } itemDef { name "name" rect -282 28 272 272 3 1 decoration visible 1 forecolor 1 1 1 0.75 textfont 9 textalign 12 textalignx 2 textaligny 32 textscale 0.375 visible when ( 0 ) exp text ( localvarstring( "ui_level_name" ) ) } itemDef { rect -282 310 272 20 3 1 decoration autowrapped visible 1 forecolor 1 0.8 0.4 1 textfont 3 textalign 4 textaligny 52 textscale 0.375 visible when ( ( int( getcharbyindex( getprofiledata( "missionHighestDifficulty" ) , localvarint( "ui_highlighted_level_number" ) ) ) == 1 ) ) exp text ( locstring( "@MENU_DIFFICULTY_COMPLETED" ) + " " + locstring( "@MENU_RECRUIT" ) ) } itemDef { rect -282 310 272 20 3 1 decoration autowrapped visible 1 forecolor 1 0.8 0.4 1 textfont 3 textalign 4 textaligny 52 textscale 0.375 visible when ( ( int( getcharbyindex( getprofiledata( "missionHighestDifficulty" ) , localvarint( "ui_highlighted_level_number" ) ) ) == 2 ) ) exp text ( locstring( "@MENU_DIFFICULTY_COMPLETED" ) + " " + locstring( "@MENU_REGULAR" ) ) } itemDef { rect -282 310 272 20 3 1 decoration autowrapped visible 1 forecolor 1 0.8 0.4 1 textfont 3 textalign 4 textaligny 52 textscale 0.375 visible when ( ( int( getcharbyindex( getprofiledata( "missionHighestDifficulty" ) , localvarint( "ui_highlighted_level_number" ) ) ) == 3 ) ) exp text ( locstring( "@MENU_DIFFICULTY_COMPLETED" ) + " " + locstring( "@MENU_HARDENED" ) ) } itemDef { rect -282 310 272 20 3 1 decoration autowrapped visible 1 forecolor 1 0.8 0.4 1 textfont 3 textalign 4 textaligny 52 textscale 0.375 visible when ( ( int( getcharbyindex( getprofiledata( "missionHighestDifficulty" ) , localvarint( "ui_highlighted_level_number" ) ) ) == 4 ) ) exp text ( locstring( "@MENU_DIFFICULTY_COMPLETED" ) + " " + locstring( "@MENU_VETERAN" ) ) } itemDef { name "cheat_indicator" rect -64 -44 336 24 1 3 decoration visible 1 forecolor 1 0.8 0.4 1 textfont 9 textalign 6 textalignx -30 textscale 0.375 text "@MENU_CHEAT_ENABLED" visible when ( dvarbool( "mis_cheat" ) ) } itemDef { name "@MENU_SP_SP_INVASION" rect -64 28 336 20 1 1 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@MENU_SP_SP_INVASION" visible when ( ( ( ( 5 == 0 && getprofiledata( "highestMission" ) == 0 ) || ( getprofiledata( "highestMission" ) >= ( 5 ) || dvarbool( "mis_cheat" ) ) ) && 1 ) || dvarbool( "developer" ) ) action { play "mouse_click"; setdvar "credits" 0; setdvar "credits_active" 0; if ( "invasion" == "trainer" ) { exec "devmap trainer"; } else { setdvar "ui_load_level" "invasion"; open "popmenu_difficulty"; } } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); setLocalVarFloat "ui_popupYPos" ( getfocuseditemy( ) ); ;; setLocalVarString "ui_level_name" ( "@MENU_SP_SP_INVASION" ); setLocalVarString "ui_level_levelshot" ( "levelshot_mw2_invasion" ); setLocalVarString "ui_level_desc" ( "@MENU_SP_SP_INVASION_DESC" ); setLocalVarString "ui_choicegroup" ( "CHOICE_GROUP" ); setLocalVarInt "ui_highlighted_level_number" ( 5 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } itemDef { name "@MENU_SP_SP_FAVELA_ESCAPE" rect -64 48 336 20 1 1 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@MENU_SP_SP_FAVELA_ESCAPE" visible when ( ( ( ( 6 == 0 && getprofiledata( "highestMission" ) == 0 ) || ( getprofiledata( "highestMission" ) >= ( 6 ) || dvarbool( "mis_cheat" ) ) ) && 1 ) || dvarbool( "developer" ) ) action { play "mouse_click"; setdvar "credits" 0; setdvar "credits_active" 0; if ( "favela_escape" == "trainer" ) { exec "devmap trainer"; } else { setdvar "ui_load_level" "favela_escape"; open "popmenu_difficulty"; } } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); setLocalVarFloat "ui_popupYPos" ( getfocuseditemy( ) ); ;; setLocalVarString "ui_level_name" ( "@MENU_SP_SP_FAVELA_ESCAPE" ); setLocalVarString "ui_level_levelshot" ( "levelshot_mw2_favela_escape" ); setLocalVarString "ui_level_desc" ( "@MENU_SP_SP_FAVELA_ESCAPE_DESC" ); setLocalVarString "ui_choicegroup" ( "CHOICE_GROUP" ); setLocalVarInt "ui_highlighted_level_number" ( 6 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } itemDef { name "@MENU_SP_SP_ARCADIA" rect -64 68 336 20 1 1 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@MENU_SP_SP_ARCADIA" visible when ( ( ( ( 7 == 0 && getprofiledata( "highestMission" ) == 0 ) || ( getprofiledata( "highestMission" ) >= ( 7 ) || dvarbool( "mis_cheat" ) ) ) && 1 ) || dvarbool( "developer" ) ) action { play "mouse_click"; setdvar "credits" 0; setdvar "credits_active" 0; if ( "arcadia" == "trainer" ) { exec "devmap trainer"; } else { setdvar "ui_load_level" "arcadia"; open "popmenu_difficulty"; } } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); setLocalVarFloat "ui_popupYPos" ( getfocuseditemy( ) ); ;; setLocalVarString "ui_level_name" ( "@MENU_SP_SP_ARCADIA" ); setLocalVarString "ui_level_levelshot" ( "levelshot_mw2_arcadia" ); setLocalVarString "ui_level_desc" ( "@MENU_SP_SP_ARCADIA_DESC" ); setLocalVarString "ui_choicegroup" ( "CHOICE_GROUP" ); setLocalVarInt "ui_highlighted_level_number" ( 7 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } itemDef { name "@MENU_SP_SP_OILRIG" rect -64 88 336 20 1 1 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@MENU_SP_SP_OILRIG" visible when ( ( ( ( 8 == 0 && getprofiledata( "highestMission" ) == 0 ) || ( getprofiledata( "highestMission" ) >= ( 8 ) || dvarbool( "mis_cheat" ) ) ) && 1 ) || dvarbool( "developer" ) ) action { play "mouse_click"; setdvar "credits" 0; setdvar "credits_active" 0; if ( "oilrig" == "trainer" ) { exec "devmap trainer"; } else { setdvar "ui_load_level" "oilrig"; open "popmenu_difficulty"; } } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); setLocalVarFloat "ui_popupYPos" ( getfocuseditemy( ) ); ;; setLocalVarString "ui_level_name" ( "@MENU_SP_SP_OILRIG" ); setLocalVarString "ui_level_levelshot" ( "levelshot_mw2_oilrig" ); setLocalVarString "ui_level_desc" ( "@MENU_SP_SP_OILRIG_DESC" ); setLocalVarString "ui_choicegroup" ( "CHOICE_GROUP" ); setLocalVarInt "ui_highlighted_level_number" ( 8 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } itemDef { name "@MENU_SP_SP_GULAG" rect -64 108 336 20 1 1 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@MENU_SP_SP_GULAG" visible when ( ( ( ( 9 == 0 && getprofiledata( "highestMission" ) == 0 ) || ( getprofiledata( "highestMission" ) >= ( 9 ) || dvarbool( "mis_cheat" ) ) ) && 1 ) || dvarbool( "developer" ) ) action { play "mouse_click"; setdvar "credits" 0; setdvar "credits_active" 0; if ( "gulag" == "trainer" ) { exec "devmap trainer"; } else { setdvar "ui_load_level" "gulag"; open "popmenu_difficulty"; } } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); setLocalVarFloat "ui_popupYPos" ( getfocuseditemy( ) ); ;; setLocalVarString "ui_level_name" ( "@MENU_SP_SP_GULAG" ); setLocalVarString "ui_level_levelshot" ( "levelshot_mw2_gulag" ); setLocalVarString "ui_level_desc" ( "@MENU_SP_SP_GULAG_DESC" ); setLocalVarString "ui_choicegroup" ( "CHOICE_GROUP" ); setLocalVarInt "ui_highlighted_level_number" ( 9 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } itemDef { name "@MENU_SP_SP_DCBURNING" rect -64 128 336 20 1 1 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@MENU_SP_SP_DCBURNING" visible when ( ( ( ( 10 == 0 && getprofiledata( "highestMission" ) == 0 ) || ( getprofiledata( "highestMission" ) >= ( 10 ) || dvarbool( "mis_cheat" ) ) ) && 1 ) || dvarbool( "developer" ) ) action { play "mouse_click"; setdvar "credits" 0; setdvar "credits_active" 0; if ( "dcburning" == "trainer" ) { exec "devmap trainer"; } else { setdvar "ui_load_level" "dcburning"; open "popmenu_difficulty"; } } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); setLocalVarFloat "ui_popupYPos" ( getfocuseditemy( ) ); ;; setLocalVarString "ui_level_name" ( "@MENU_SP_SP_DCBURNING" ); setLocalVarString "ui_level_levelshot" ( "levelshot_mw2_dcburning" ); setLocalVarString "ui_level_desc" ( "@MENU_SP_SP_DCBURNING_DESC" ); setLocalVarString "ui_choicegroup" ( "CHOICE_GROUP" ); setLocalVarInt "ui_highlighted_level_number" ( 10 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } itemDef { rect -64 -20 336 20 1 3 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@PLATFORM_BACK_CAPS" visible when ( "@PLATFORM_BACK_CAPS" == "@PLATFORM_BACK_CAPS" ) action { play "mouse_click"; play "mouse_click"; "escape" self; } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } itemDef { rect -64 -20 336 20 1 3 visible 1 group "mw2_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "menu_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -60 textscale 0.375 text "@PLATFORM_BACK_CAPS" visible when ( "@PLATFORM_BACK_CAPS" == "@PLATFORM_GAME_SUMMARY_CAPS" ) action { play "mouse_click"; play "mouse_click"; open "popup_summary"; } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_menuAButton" ( 1 ); } leaveFocus { setItemColor self backcolor 0 0 0 "0.0"; setLocalVarString "ui_hint_text" ( "@NULL_EMPTY" ); setLocalVarBool "ui_menuAButton" ( 0 ); } } } }
412
0.899072
1
0.899072
game-dev
MEDIA
0.600882
game-dev,desktop-app
0.94556
1
0.94556
chris81605/DOL-BJXExtende_for_ML_Project
28,219
DATA/原版 0.4.5.3/DoLModExportData_20240117_021134/passage/Widgets Canvas Model Main.twee
:: Widgets Canvas Model Main [widget] <!-- <<canvasimg [CSSCLASSES]>> Render full player image. --> <<widget "canvasimg">> <<selectmodel "main" "sidebar">> <<modelprepare-player-body>> <<modelprepare-player-clothes>> <<if $options.sidebarAnimations isnot false>> <<animatemodel _args[0]>> <<else>> <<rendermodel _args[0]>> <</if>> <<if playerHasStrapon()>> <<set _modeloptions.crotch_visible to false>> <<set _modeloptions.crotch_exposed to false>> <<if $worn.lower.exposed lte 1 and $lowerwetstage lte 0>> <<set _modeloptions.worn_under_lower to 0>> <</if>> <</if>> <</widget>> <!-- Set model options & filters from player body Requires prior <<selectmodel "main">> --> <<widget "modelprepare-player-body">> /*Prep for image checks*/ <<set _disabled to ["disabled","hidden"]>> <!-- unwrap tanLoc/tanValues array --> <<twinescript>> let tanValByName = { body: 0, breasts: -0.01, penis: -0.01, swimshorts: -0.01, swimsuitTop: -0.01, swimsuitBottom: -0.01, bikiniTop: -0.01, bikiniBottom: -0.01, tshirt: -0.01 /* No sprites yet? */ }; for (let i = 0; i < setup.skinColor.tanLoc.length; i++) { tanValByName[setup.skinColor.tanLoc[i]] = $skinColor.tanValues[i] / 100; } _modeloptions.skin_type = $skinColor.natural || "light"; _modeloptions.skin_tone = tanValByName["body"]; if ($options.tanningEnabled is true){ for (let loc in tanValByName) { if (loc !== 'body') { _modeloptions['skin_tone_'+loc] = tanValByName[loc]; } } } else { _modeloptions.show_tanlines = false; } <</twinescript>> <<if $makeup.eyeshadow != 0>> <<set _modeloptions.eyeshadow_colour to $makeup.eyeshadow>> <</if>> <<if $makeup.mascara != 0>> <<set _modeloptions.mascara_colour to $makeup.mascara>> <</if>> <<if $makeup.mascara_running != 0>> <<set _modeloptions.mascara_running to $makeup.mascara_running>> <</if>> <<if $makeup.lipstick != 0>> <<set _modeloptions.lipstick_colour to $makeup.lipstick>> <</if>> <<if $possessed>> <<set _modeloptions.left_eye = (["haunt", "despair"].includes($wraith.state) ? "red possessed" : "blue possessed")>> <<set _modeloptions.right_eye = (["haunt", "despair"].includes($wraith.state) ? "red possessed" : "blue possessed")>> <<else>> <<set _modeloptions.left_eye = $makeup.eyelenses.left != 0 ? $makeup.eyelenses.left : $leftEyeColour>> <<set _modeloptions.right_eye = $makeup.eyelenses.right != 0 ? $makeup.eyelenses.right : $rightEyeColour>> <</if>> <<set _modeloptions.hair_colour = $haircolour>> <<set _modeloptions.hair_fringe_colour = $hairfringecolour>> <<set _modeloptions.hair_colour_gradient = $hairColourGradient>> <<set _modeloptions.hair_fringe_colour_gradient = $hairFringeColourGradient>> <<set _modeloptions.hair_colour_style to $hairColourStyle>> <<set _modeloptions.hair_fringe_colour_style to $hairFringeColourStyle>> <<set _modeloptions.brows_colour = ($makeup.browscolour != 0 ? $makeup.browscolour : $naturalhaircolour)>> <<set _modeloptions.pbhair_colour = ($makeup.pbcolour != 0 ? $makeup.pbcolour : $naturalhaircolour)>> <!-- ██████ █████ ███████ ███████ ██ ██ ██ ██ ██ ██ ██████ ███████ ███████ █████ ██ ██ ██ ██ ██ ██ ██████ ██ ██ ███████ ███████ --> <<set _modeloptions.body_type to !$options.genderBody || $options.genderBody === "default" ? $player.gender_body : $options.genderBody>> <<run apparentbreastsizecheck()>> <<switch $player.perceived_breastsize>> <<case 12>> <<set _modeloptions.breast_size to 6>> <<case 8 9 10 11>> <<set _modeloptions.breast_size to 5>> <<case 6 7>> <<set _modeloptions.breast_size to 4>> <<case 4 5>> <<set _modeloptions.breast_size to 3>> <<case 3>> <<set _modeloptions.breast_size to 2>> <<case 1 2>> <<set _modeloptions.breast_size to 1>> <<default>> <<set _modeloptions.breast_size to 0>> <</switch>> <<set _modeloptions.breasts to "default">> <<if $sexStats>> <<set _modeloptions.belly to playerBellySize() || $bellySizeDebug>> <<set _bellySize to playerBellySize() || $bellySizeDebug>> <</if>> <<if $wraithSkin>> <<set _modeloptions.mannequin to true>> <<set _modeloptions.skin_type to 'custom'>> <<set _modeloptions.filters.body to {blend:'#ffffff',blendMode:'multiply',desaturate:true}>> <<set _modeloptions.filters.breasts to _modeloptions.filters.body>> <<set _modeloptions.filters.penis to _modeloptions.filters.body>> <<set _modeloptions.show_tanlines to false>> <</if>> <!-- - ██ ██ █████ ██ ██████ - ██ ██ ██ ██ ██ ██ ██ - ███████ ███████ ██ ██████ - ██ ██ ██ ██ ██ ██ ██ - ██ ██ ██ ██ ██ ██ ██ - - --> <<set _modeloptions.hair_sides_length to $hairlengthstage>> <<set _modeloptions.hair_sides_type to $hairtype>> <<set _modeloptions.hair_sides_position to $hairposition>> <<set _modeloptions.hair_fringe_length to $fringelengthstage>> <<set _modeloptions.hair_fringe_type to $fringetype>> <!-- - █████ ██████ ███ ███ ███████ - ██ ██ ██ ██ ████ ████ ██ - ███████ ██████ ██ ████ ██ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ - ██ ██ ██ ██ ██ ██ ███████ - --> <<set _coverBreastsWithArm to false>> <<if $leftarm isnot "bound" and $leftarm isnot "grappled">> <<if $dontHide is false and $worn.over_upper.exposed gte 1 and ($worn.upper.exposed gte 1 or $upperwetstage gte 3) and ($worn.lower.covers_top isnot 1) and (($uncomfortable.underwear is true and !$worn.under_upper.type.includes("naked")) or ($uncomfortable.nude is true and ($worn.under_upper.exposed gte 1 or $underupperwetstage gte 3)))>> <<set _coverBreasts to true>> <<set _modeloptions.arm_left to "cover">> <!-- might be changed back to "idle" if covering with wings --> <<else>> <<set _coverBreasts to false>> <<set _modeloptions.arm_left to "idle">> <</if>> <<else>> <<set _modeloptions.arm_left to "none">> <</if>> <<if $rightarm isnot "bound" and $rightarm isnot "grappled">> <<if $dontHide is false and $worn.over_lower.exposed gte 1 and ($worn.lower.exposed gte 1 or $lowerwetstage gte 3) and (($uncomfortable.underwear is true and !$worn.under_lower.type.includes("naked")) or ($uncomfortable.nude is true and ($worn.under_lower.exposed gte 1 or $underlowerwetstage gte 3)))>> <<set _coverCrotch to true>> <<set _modeloptions.arm_right to "cover">> <!-- might be changed back to "idle" if covering with wings/tail --> <<else>> <<set _coverCrotch to false>> <<set _modeloptions.arm_right to $worn.handheld.name isnot "naked" ? "hold" : "idle">> <</if>> <<else>> <<set _modeloptions.arm_right to "none">> <</if>> <<if $leftarm isnot "bound" and $leftarm isnot "grappled">> <<if _coverBreasts is false>> <<if $exposed gte 2 and $dontHide is false and $transformationParts.traits.flaunting is "default">> <<set _modeloptions.demon_wings_state to "flaunt">> <<else>> <<set _modeloptions.demon_wings_state to "idle">> <</if>> <<set _modeloptions.angel_wing_right to "idle">> <<set _modeloptions.fallen_wing_right to "idle">> <<set _modeloptions.bird_wing_right to "idle">> <<elseif _coverBreasts is true>> <<if !_disabled.includes($transformationParts.demon.wings)>> <<set _modeloptions.demon_wings_state to ($transformationParts.traits.flaunting is "default" ? "flaunt" : "cover")>> <<set _modeloptions.arm_left to "idle">> <<elseif !_disabled.includes($transformationParts.angel.wings)>> <<set _modeloptions.angel_wing_right to "cover">> <<set _modeloptions.arm_left to "idle">> <<elseif !_disabled.includes($transformationParts.fallenAngel.wings)>> <<set _modeloptions.fallen_wing_right to "cover">> <<set _modeloptions.arm_left to "idle">> <<elseif !_disabled.includes($transformationParts.bird.wings)>> <<set _modeloptions.bird_wing_right to "cover">> <<set _modeloptions.arm_left to "idle">> <<else>> <<set _coverBreastsWithArm to true>> <</if>> <</if>> <</if>> <<if $rightarm isnot "bound" and $rightarm isnot "grappled">> <<if _coverCrotch is false>> <<if !_disabled.includes($transformationParts.demon.tail)>> <<if $exposed gte 2 and $dontHide is false and $transformationParts.traits.flaunting is "default">> <<set _modeloptions.demon_tail_state to "flaunt">> <<set _modeloptions.cat_tail_state to "flaunt">> <<else>> <<set _modeloptions.demon_tail_state to "idle">> <<set _modeloptions.cat_tail_state to "idle">> <</if>> <</if>> <<set _modeloptions.angel_wing_left to "idle">> <<set _modeloptions.fallen_wing_left to "idle">> <<set _modeloptions.bird_wing_left to "idle">> <<elseif _coverCrotch is true>> <<if !_disabled.includes($transformationParts.demon.tail)>> <<set _modeloptions.demon_tail_state to ($transformationParts.traits.flaunting is "default" ? "flaunt" : "cover")>> <<set _modeloptions.cat_tail_state to "cover">> <<set _modeloptions.arm_right to $worn.handheld.name isnot "naked" ? "hold" : "idle">> <<elseif !_disabled.includes($transformationParts.angel.wings)>> <<set _modeloptions.angel_wing_left to "cover">> <<set _modeloptions.arm_right to $worn.handheld.name isnot "naked" ? "hold" : "idle">> <<elseif !_disabled.includes($transformationParts.fallenAngel.wings)>> <<set _modeloptions.fallen_wing_left to "cover">> <<set _modeloptions.arm_right to $worn.handheld.name isnot "naked" ? "hold" : "idle">> <<elseif !_disabled.includes($transformationParts.bird.wings)>> <<set _modeloptions.bird_wing_left to "cover">> <<set _modeloptions.arm_right to $worn.handheld.name isnot "naked" ? "hold" : "idle">> <</if>> <</if>> <</if>> <!-- - ██ ██ ██████ ██ ████████ ██ ███ ██ ██████ ███████ - ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██ - ██ █ ██ ██████ ██ ██ ██ ██ ██ ██ ██ ███ ███████ - ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ███ ███ ██ ██ ██ ██ ██ ██ ████ ██████ ███████ --> <<if $options.bodywritingImages is true>> <<for _label, _value range $skin>> <<if _value.writing>> <<set _modeloptions["writing_"+_label] to setup.bodywriting_namebyindex[_value.index]>> <</if>> <</for>> <</if>> <!-- - ███████ █████ ██████ ███████ - ██ ██ ██ ██ ██ - █████ ███████ ██ █████ - ██ ██ ██ ██ ██ - ██ ██ ██ ██████ ███████ --> <<set _modeloptions.facestyle to $facestyle>> <<set _modeloptions.freckles = $player.freckles == true and $makeup.concealer != 1>> <<set _modeloptions.ears_position to $earsposition>> <<set _modeloptions.toast = _toast == true>> <!-- Eyes --> <<if $possessed>> <<set _modeloptions.trauma to $possessed>> <<else>> <<set _modeloptions.trauma to $trauma gte ($traumamax * 0.9)>> <</if>> <<set _modeloptions.blink to $options.blinkingEnabled>> <<set _modeloptions.eyes_bloodshot to $pain gte 100 and $willpowerpain is 0 or $tiredness >= C.tiredness.max>> <<set _modeloptions.eyes_half to $options.halfClosedEnabled and ($arousal gte ($arousalmax / 5) * 4 or $orgasmdown gte 1) and $trauma lt ($traumamax * 0.9) and $pain lt 60 and $eyelidTEST is true or ($possessed or $tiredness >= C.tiredness.max * 0.75)>> <!-- Brows --> <<if $trauma gte $traumamax or $possessed>> <<set _modeloptions.brows = "top">> <<elseif $pain gte 60>> <<set _modeloptions.brows = "low">> <<elseif $arousal gte ($arousalmax / 5) * 4 or $orgasmdown gte 1>> <<set _modeloptions.brows = "orgasm">> <<elseif $pain gte 20>> <<set _modeloptions.brows = "mid">> <<else>> <<set _modeloptions.brows = "top">> <</if>> <<set _modeloptions.brows_position to $browsposition>> <!-- Mouth --> <<if $trauma gte $traumamax>> <<set _modeloptions.mouth = "neutral">> <<elseif $pain gte 60 or $orgasmdown gte 1 or ($possessed)>> <<set _modeloptions.mouth = "cry">> <<elseif $exposed is 2 and $uncomfortable.nude is true and $dontHide is false or $pain gte 20>> <<set _modeloptions.mouth = "frown">> <<elseif $pain gte 1 or ($exposed is 1 and $uncomfortable.underwear is true) or ($combat is 1 and $consensual isnot 1)>> <<set _modeloptions.mouth = "neutral">> <<elseif $stress >= ($stressmax / 5) * 3 or !($control >= ($controlmax / 5) * 1)>> <!-- $stress == You are strained. or $control == You are scared.--> <<set _modeloptions.mouth = "neutral">> <<else>> <<set _modeloptions.mouth = "smile">> <</if>> <!-- Blush --> <<set _modeloptions.blush = Math.min(5, Math.floor($arousal / 2000) + 1)>> <<if _modeloptions.blush lt 2 and $exposed gte 2>> <<set _modeloptions.blush = 2>> <<elseif $arousal lt 100 and $exposed lt 1>> <<set _modeloptions.blush = 0>> <</if>> <<if !$worn.over_upper.type.includes("naked") and !$worn.over_lower.type.includes("naked") and $worn.upper.type.includes("naked") and $worn.lower.type.includes("naked") and $worn.under_upper.type.includes("naked") and $worn.under_lower.type.includes("naked")>> <<set _modeloptions.blush = 2>> <</if>> <!-- Tears --> <<set _modeloptions.tears = painToTearsLvl($pain)>> <!-- - ████████ ███████ ███████ - ██ ██ ██ - ██ █████ ███████ - ██ ██ ██ - ██ ██ ███████ --> <!-- Transformation filters here --> <<set $_filterBase to { blendMode: "hard-light", brightness: 0, contrast: 1, desaturate: false }>> <!-- wing and tail idle/cover/flaunt state is configured in the arms section above --> <<set _modeloptions.angel_wings_type to $transformationParts.angel.wings>> <<set _modeloptions.angel_wings_layer to $wingslayer>> <<set _modeloptions.angel_halo_type to $transformationParts.angel.halo>> <<set _modeloptions.fallen_wings_type to $transformationParts.fallenAngel.wings>> <<set _modeloptions.fallen_wings_layer to $wingslayer>> <<set _modeloptions.fallen_halo_type to $transformationParts.fallenAngel.halo>> <<set _modeloptions.demon_wings_type to $transformationParts.demon.wings>> <<set _modeloptions.demon_wings_layer to $wingslayer>> <<set _modeloptions.demon_tail_type to $transformationParts.demon.tail>> <<set _modeloptions.demon_tail_layer to $taillayer>> <<set _modeloptions.demon_horns_type to $transformationParts.demon.horns>> <<set _modeloptions.demon_horns_layer to $hornslayer>> <!-- Calculate blend pattern for demon TF here. --> <<set $_demonHsl to ColourUtils.toHslString(Transformations.defaults.demon.colour)>> <<set _modeloptions.filters.demon_wings to clone(Object.assign($_filterBase, { blend: ColourUtils.toHslString($transformationParts.demon.wings_colour, $_demonHsl) }))>> <<set _modeloptions.filters.demon_tail to clone(Object.assign($_filterBase, { blend: ColourUtils.toHslString($transformationParts.demon.tail_colour, $_demonHsl) }))>> <<set _modeloptions.filters.demon_horns to clone(Object.assign($_filterBase, { blend: ColourUtils.toHslString($transformationParts.demon.horns_colour, $_demonHsl) }))>> <<set _modeloptions.wolf_tail_type to $transformationParts.wolf.tail>> <<set _modeloptions.wolf_tail_layer to $taillayer>> <<set _modeloptions.wolf_ears_type to $transformationParts.wolf.ears>> <<set _modeloptions.wolf_pits_type to $transformationParts.wolf.pits>> <<set _modeloptions.wolf_pubes_type to $transformationParts.wolf.pubes>> <<set _modeloptions.wolf_cheeks_type to $transformationParts.wolf.cheeks>> <<set _modeloptions.cat_tail_type to $transformationParts.cat.tail>> <<set _modeloptions.cat_tail_layer to $taillayer>> <<set _modeloptions.cat_ears_type to $transformationParts.cat.ears>> <<set _modeloptions.cow_horns_type to $transformationParts.cow.horns>> <<set _modeloptions.cow_horns_layer to $hornslayer>> <<set _modeloptions.cow_tail_type to $transformationParts.cow.tail>> <<set _modeloptions.cow_tail_layer to $taillayer>> <<set _modeloptions.cow_ears_type to $transformationParts.cow.ears>> <<set _modeloptions.bird_wings_type to $transformationParts.bird.wings>> <<set _modeloptions.bird_wings_layer to $wingslayer>> <<set _modeloptions.bird_tail_type to $transformationParts.bird.tail>> <<set _modeloptions.bird_tail_layer to $taillayer>> <<set _modeloptions.bird_eyes_type to $transformationParts.bird.eyes>> <<set _modeloptions.bird_malar_type to $transformationParts.bird.malar>> <<set _modeloptions.bird_plumage_type to $transformationParts.bird.plumage>> <<set _modeloptions.bird_pubes_type to $transformationParts.bird.pubes>> <<set _modeloptions.fox_tail_type to $transformationParts.fox.tail>> <<set _modeloptions.fox_tail_layer to $taillayer>> <<set _modeloptions.fox_ears_type to $transformationParts.fox.ears>> <<set _modeloptions.fox_cheeks_type to $transformationParts.fox.cheeks>> <!-- - ██████ ██ ██ ██ ███ ███ ███████ ██████ █████ - ██ ██ ██ ██ ████ ████ ██ ██ ██ ██ ██ - ██ ███████ ██ ██ ████ ██ █████ ██████ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██████ ██ ██ ██ ██ ██ ███████ ██ ██ ██ ██ --> <!-- Demon-cat tail --> <<if isPartEnabled(_modeloptions.cat_tail_type) and isPartEnabled(_modeloptions.demon_tail_type) and isChimeraEnabled("demoncat", "tail")>> <<set _modeloptions.demon_tail_type to 'default-cat'>> <<set _modeloptions.demon_tail_layer to "cover">> <</if>> <!-- Demon-harpy wings --> <<if isPartEnabled(_modeloptions.demon_wings_type) and isPartEnabled(_modeloptions.bird_wings_type) and isChimeraEnabled("demonharpy", "wings")>> <<set _modeloptions.bird_wings_type to 'default-demon'>> <<set _modeloptions.demon_wings_type to 'hidden'>> <</if>> <!-- Demon-cow horns --> <<if isPartEnabled(_modeloptions.cow_horns_type) and isPartEnabled(_modeloptions.demon_horns_type) and isChimeraEnabled("demoncow", "horns")>> <<if !['default', 'succubus'].includes(_modeloptions.demon_horns_type)>> <!-- Force default horns if the PC has unsupported horn styles (E.G. Classic) --> <<set _modeloptions.demon_horns_type to 'default'>> <</if>> <<set _modeloptions.cow_horns_type to 'default-demon'>> <</if>> <!-- - ██████ ██████ ██████ ████████ ██████ ██ ██ - ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██ ██████ ██ ██ ██ ██ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██████ ██ ██ ██████ ██ ██████ ██ ██ --> <<set _modeloptions.crotch_visible to true>> <<if $pbdisable is "f">> <<set _modeloptions.pbhair_level = $pblevel>> <<set _modeloptions.pbhair_strip = $pbstrip>> <<set _modeloptions.pbhair_balls = $pblevelballs>> <</if>> <<if $player.penisExist>> <<set _modeloptions.penis_size to Math.clamp($player.penissize, -2, 4)>> <<set _modeloptions.penis to ($player.virginity.penile === true ? "virgin" : "default") >> <<set _modeloptions.balls to $player.ballsExist>> <<set _modeloptions.penis_parasite to $parasite.penis.name>> <<set _modeloptions.penis_condom to $player.condom.type>> <<set _modeloptions.condom_colour to $player.condom.colour>> <</if>> <<if $player.vaginaExist>> <<set _modeloptions.clit_parasite to $parasite.clit.name>> <</if>> <<if _modeloptions.penis_parasite is "parasite" or _modeloptions.clit_parasite is "parasite">> /* Always uses the clit image as a base */ <<if $earSlime.focus is "impregnation">> <<set _modeloptions.clit_parasite to "parasitem">> <<else>> <<set _modeloptions.clit_parasite to "parasite">> <</if>> <<if $player.penisExist and $player.ballsExist and $player.penissize gte -1>> <<set _modeloptions.penis_parasite to "parasite">> <<else>> <<set _modeloptions.penis_parasite to "">> <</if>> /* Ensure its always displayed */ <<if $worn.genitals.name is "chastity parasite">> <<set _modeloptions['worn_genitals'] = clothesIndex("genitals", $worn.genitals)>> <<set _modeloptions['worn_genitals_integrity'] = integrityKeyword($worn.genitals, "genitals")>> <<set _modeloptions['worn_genitals_colour'] = $worn.genitals.colour>> <</if>> <</if>> <!-- Dripping Speeds --> <<set $_dripspeeds to ["", "Start", "VerySlow", "Slow", "Fast", "VeryFast"]>> <!-- Vagina --> <<set $_liquidamt to Math.clamp(setup.bodyliquid.combined("vagina"), 0, 5)>> <<set _modeloptions.drip_vaginal to $_dripspeeds.select($_liquidamt)>> <!-- Anus --> <<set $_liquidamt to Math.clamp(setup.bodyliquid.combined("anus"), 0, 5)>> <<set _modeloptions.drip_anal to $_dripspeeds.select($_liquidamt)>> <!-- Mouth --> <<set $_liquidamt to Math.clamp(setup.bodyliquid.combined("mouth"), 0, 5)>> <<set _modeloptions.drip_mouth to $_dripspeeds.select($_liquidamt)>> <<if $worn.upper.exposed gte 2 and $worn.under_upper.exposed gte 1>> <<set _chestVisible to true>> <<elseif ($upperwetstage gt 0 or $worn.upper.type.includes("naked")) and ($underupperwetstage gt 0 or $worn.under_upper.type.includes("naked"))>> <<set _chestVisible to true>> <</if>> <<if _chestVisible>> <<set _modeloptions.nipples_parasite to $parasite.nipples.name>> <<set _modeloptions.breasts_parasite to $parasite.breasts.name>> <</if>> <!-- - ███████ ██ ██ ██ ██ ██████ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ - █████ ██ ██ ██ ██ ██ ██ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ - ██ ███████ ██████ ██ ██████ ███████ --> <<script>> let cumsprite = { "chest": [null, "1", "2", "3", "4,5", "4,5"], "face": [null, "1,2", "1,2", "3,4", "3,4", "5"], "feet": [null, null, "2,3", "2,3", "4,5", "4,5"], "leftarm": [null, "1,2,3", "1,2,3", "1,2,3", "4,5", "4,5"], "rightarm": [null, "1,2,3", "1,2,3", "1,2,3", "4,5", "4,5"], "neck": [null, "1,2", "1,2", "3,4", "3,4", "5"], "thigh": [null, "1", "2", "3", "4", "5"], "tummy": [null, "1", "2", "3", "4", "5"] }; let bodyparts = ["chest", "face", "feet", "leftarm", "rightarm", "neck", "thigh", "tummy"]; bodyparts.forEach(bodypart => { let liquidamt = Math.clamp(setup.bodyliquid.combined(bodypart), 0, 5); T.modeloptions["cum_" + bodypart] = cumsprite[bodypart].select(liquidamt); }); <</script>> <</widget>> <!-- - ██████ ██ ██████ ████████ ██ ██ ███████ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██ ██ ██ ██ ██ ███████ █████ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██████ ███████ ██████ ██ ██ ██ ███████ ███████ --> <!-- Set model options & filters for player clothes --> <<widget "modelprepare-player-clothes">> <<if !$worn.upper.type.includes("naked") || !$worn.under_upper.type.includes("naked") || _coverBreastsWithArm>> <<set _modeloptions.breasts to "cleavage">> <<else>> <<set _modeloptions.breasts to "default">> <</if>> <<if $worn.under_upper.type.includes("chest_bind")>> <<set _modeloptions.breast_size to 1>> <</if>> <<if $worn.lower.exposed gte 2 and $worn.under_lower.exposed gte 1 and !$worn.legs.name.includes("tights")>> <<set _modeloptions.crotch_visible to true>> <<set _modeloptions.crotch_exposed to true>> <<elseif ($lowerwetstage gt 0 or $worn.lower.type.includes("naked")) and ($underlowerwetstage gt 0 or $worn.under_lower.type.includes("naked"))>> <<set _modeloptions.crotch_visible to true>> <<set _modeloptions.crotch_exposed to false>> <<else>> <<set _modeloptions.crotch_visible to false>> <</if>> <<set _modeloptions.hood_down to $worn.upper.hoodposition is "down">> <<if ((($worn.over_head.hood is 1 and $worn.over_head.mask_img isnot 1) or ($worn.head.hood is 1 and $worn.head.mask_img isnot 1))) and $worn.upper.hoodposition is "down">> <<set _modeloptions.hair_sides_length to "short">> <<set _modeloptions.hair_fringe_length to "short">> <</if>> <<set _modeloptions.alt_position to $worn.upper.altposition is "alt">> <<set _modeloptions.alt_position_neck to $worn.neck.altposition is "alt">> <<set _modeloptions.alt_sleeve to $worn.upper.altsleeve is "alt">> <<set _modeloptions.facewear_layer to $facelayer>> <<set _modeloptions.upper_tucked to $upperTucked and !setup.clothes.upper[clothesIndex('upper', $worn.upper)].notuck and $worn.upper.outfitPrimary is undefined>> <<twinescript>> let slots = [ ["upper", $upperwetstage], ["over_upper"], ["genitals"], ["lower", $lowerwetstage], ["over_lower"], ["under_lower", $underlowerwetstage], ["under_upper", $underupperwetstage], ["hands"], ["handheld"], ["head"], ["over_head"], ["face"], ["neck"], ["legs"], ["feet"], ]; for (let slotobj of slots) { let slot = slotobj[0]; let worn = $worn[slot]; switch (slotobj[1]) { case 1: _modeloptions['worn_'+slot+'_alpha'] = 0.9; break; case 2: _modeloptions['worn_'+slot+'_alpha'] = 0.7; break; case 3: _modeloptions['worn_'+slot+'_alpha'] = 0.5; break; default: _modeloptions['worn_'+slot+'_alpha'] = 1.0; break; } _modeloptions['worn_'+slot] = clothesIndex(slot,worn); _modeloptions['worn_'+slot+'_integrity'] = integrityKeyword(worn,slot); _modeloptions['worn_'+slot+'_colour'] = worn.colour; if (worn.colour === 'custom') { /* TODO @aimozg We recalculate custom colour RGB here; in future versions, we should store custom colours in canvasfilter-friendly way */ _modeloptions.filters['worn_'+slot+'_custom'] = worn.colourCanvasFilter || getCustomClothesColourCanvasFilter(worn.colourCustom); } _modeloptions['worn_'+slot+'_acc_colour'] = worn.accessory_colour; if (worn.accessory_colour === 'custom') { _modeloptions.filters['worn_'+slot+'_acc_custom'] = worn.accessory_colourCanvasFilter || getCustomClothesColourCanvasFilter(worn.accessory_colourCustom); } if (worn.accessory_layer_under) { _modeloptions.acc_layer_under = worn.accessory_layer_under; } } <</twinescript>> <<if Object.keys($modeloptionsOverride).length gte 1>> <<for _m to 0; _m lt Object.keys($modeloptionsOverride).length; _m++>> <<set _modeloptions[Object.keys($modeloptionsOverride)[_m]] to Object.values($modeloptionsOverride)[_m]>> <</for>> <</if>> <</widget>> <<widget "canvas-player-base-body">> <<selectmodel "main">> <<set _chestVisible to !$options.neverNudeMenus>> <<modelprepare-player-body>> <!-- Reset covering --> <<set _modeloptions.arm_left to "idle">> <<set _modeloptions.arm_right to "idle">> <<set _modeloptions.angel_wing_left to "idle">> <<set _modeloptions.angel_wing_right to "idle">> <<set _modeloptions.fallen_wing_left to "idle">> <<set _modeloptions.fallen_wing_right to "idle">> <<set _modeloptions.demon_wing_left to "idle">> <<set _modeloptions.demon_wing_right to "idle">> <<set _modeloptions.bird_wing_left to "idle">> <<set _modeloptions.bird_wing_right to "idle">> <!-- Reset face --> <<set _modeloptions.blink to false>> <<set _modeloptions.eyes_half to false>> <<set _modeloptions.brows to "top">> <<set _modeloptions.mouth to "neutral">> <<set _modeloptions.tears to 0>> <<set _modeloptions.blush to 0>> <!-- Reset effects --> <<set _modeloptions.drip_vaginal to "">> <<set _modeloptions.drip_anal to "">> <<set _modeloptions.drip_mouth to "">> <<if $options.neverNudeMenus>> <<set _modeloptions.crotch_visible to false>> <<set _modeloptions.penis to "">> <<if $player.gender_appearance neq "m" or $player.perceived_breastsize gte 3>> <<set _modeloptions.worn_under_upper to 12>> <<set _modeloptions.worn_under_upper_colour to "pale white">> <</if>> <<set _modeloptions.worn_under_lower_colour to "pale white">> <<if $player.gender_appearance is "m">> <<set _modeloptions.worn_under_lower to 4>> <<else>> <<set _modeloptions.worn_under_lower to 1>> <</if>> <</if>> <<if playerHasStrapon()>> <<set _modeloptions.worn_under_lower to $worn.under_lower.index>> <<set _modeloptions.worn_under_lower_colour to ($worn.under_lower.colourCustom ? $worn.under_lower.colourCustom : $worn.under_lower.colour)>> <</if>> <<if $options.sidebarRenderer is 'both'>> <<rendermodel 'canvasimg-both'>> <<else>> <<rendermodel>> <</if>> <</widget>> <<widget "canvas-model-override">> <<if _args[0] is "clear">> <<set $modeloptionsOverride to {}>> <<else>> <<set $modeloptionsOverride[_args[0]] to _args[1]>> <</if>> <</widget>>
412
0.734293
1
0.734293
game-dev
MEDIA
0.581545
game-dev,graphics-rendering
0.768334
1
0.768334
followingthefasciaplane/source-engine-diff-check
1,250
misc/game/server/hl1/hl1_ai_basenpc.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Base combat character with no AI // // $Workfile: $ // $Date: $ // $NoKeywords: $ //=============================================================================// #ifndef HL1_AI_BASENPC_H #define HL1_AI_BASENPC_H #ifdef _WIN32 #pragma once #endif #include "ai_basenpc.h" #include "ai_motor.h" //============================================================================= // >> CHL1NPCTalker //============================================================================= class CHL1BaseNPC : public CAI_BaseNPC { DECLARE_CLASS( CHL1BaseNPC, CAI_BaseNPC ); public: CHL1BaseNPC( void ) { } void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator ); bool ShouldGib( const CTakeDamageInfo &info ); bool CorpseGib( const CTakeDamageInfo &info ); bool HasAlienGibs( void ); bool HasHumanGibs( void ); void Precache( void ); int IRelationPriority( CBaseEntity *pTarget ); bool NoFriendlyFire( void ); void EjectShell( const Vector &vecOrigin, const Vector &vecVelocity, float rotation, int iType ); virtual int SelectDeadSchedule(); }; #endif //HL1_AI_BASENPC_H
412
0.917252
1
0.917252
game-dev
MEDIA
0.913592
game-dev
0.836601
1
0.836601
ppy/osu
10,899
osu.Game/Online/Leaderboards/LeaderboardManager.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Development; using osu.Framework.Graphics; using osu.Framework.Logging; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Extensions; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Scoring; using osu.Game.Screens.Select.Leaderboards; using Realms; namespace osu.Game.Online.Leaderboards { public partial class LeaderboardManager : Component { /// <summary> /// The latest leaderboard scores fetched by the criteria in <see cref="CurrentCriteria"/>. /// </summary> public IBindable<LeaderboardScores?> Scores => scores; private readonly Bindable<LeaderboardScores?> scores = new Bindable<LeaderboardScores?>(); public LeaderboardCriteria? CurrentCriteria { get; private set; } private IDisposable? localScoreSubscription; private GetScoresRequest? inFlightOnlineRequest; [Resolved] private IAPIProvider api { get; set; } = null!; [Resolved] private RealmAccess realm { get; set; } = null!; [Resolved] private RulesetStore rulesets { get; set; } = null!; /// <summary> /// Fetch leaderboard content with the new criteria specified in the background. /// On completion, <see cref="Scores"/> will be updated with the results from this call (unless a more recent call with a different criteria has completed). /// </summary> public void FetchWithCriteria(LeaderboardCriteria newCriteria, bool forceRefresh = false) { if (!ThreadSafety.IsUpdateThread) throw new InvalidOperationException(@$"{nameof(FetchWithCriteria)} must be called from the update thread."); if (!forceRefresh && CurrentCriteria?.Equals(newCriteria) == true && scores.Value?.FailState == null) return; CurrentCriteria = newCriteria; localScoreSubscription?.Dispose(); inFlightOnlineRequest?.Cancel(); scores.Value = null; if (newCriteria.Beatmap == null || newCriteria.Ruleset == null) { scores.Value = LeaderboardScores.Failure(LeaderboardFailState.NoneSelected); return; } switch (newCriteria.Scope) { case BeatmapLeaderboardScope.Local: { localScoreSubscription = realm.RegisterForNotifications(r => r.All<ScoreInfo>().Filter($"{nameof(ScoreInfo.BeatmapInfo)}.{nameof(BeatmapInfo.ID)} == $0" + $" AND {nameof(ScoreInfo.BeatmapInfo)}.{nameof(BeatmapInfo.Hash)} == {nameof(ScoreInfo.BeatmapHash)}" + $" AND {nameof(ScoreInfo.Ruleset)}.{nameof(RulesetInfo.ShortName)} == $1" + $" AND {nameof(ScoreInfo.DeletePending)} == false" , newCriteria.Beatmap.ID, newCriteria.Ruleset.ShortName), localScoresChanged); return; } default: { if (newCriteria.Sorting != LeaderboardSortMode.Score) throw new NotSupportedException($@"Requesting online scores with a {nameof(LeaderboardSortMode)} other than {nameof(LeaderboardSortMode.Score)} is not supported"); if (!api.IsLoggedIn) { scores.Value = LeaderboardScores.Failure(LeaderboardFailState.NotLoggedIn); return; } if (!newCriteria.Ruleset.IsLegacyRuleset()) { scores.Value = LeaderboardScores.Failure(LeaderboardFailState.RulesetUnavailable); return; } if (newCriteria.Beatmap.OnlineID <= 0 || newCriteria.Beatmap.Status <= BeatmapOnlineStatus.Pending) { scores.Value = LeaderboardScores.Failure(LeaderboardFailState.BeatmapUnavailable); return; } if ((newCriteria.Scope.RequiresSupporter(newCriteria.ExactMods != null)) && !api.LocalUser.Value.IsSupporter) { scores.Value = LeaderboardScores.Failure(LeaderboardFailState.NotSupporter); return; } if (newCriteria.Scope == BeatmapLeaderboardScope.Team && api.LocalUser.Value.Team == null) { scores.Value = LeaderboardScores.Failure(LeaderboardFailState.NoTeam); return; } IReadOnlyList<Mod>? requestMods = null; if (newCriteria.ExactMods != null) { if (!newCriteria.ExactMods.Any()) // add nomod for the request requestMods = new Mod[] { new ModNoMod() }; else requestMods = newCriteria.ExactMods; } var newRequest = new GetScoresRequest(newCriteria.Beatmap, newCriteria.Ruleset, newCriteria.Scope, requestMods); newRequest.Success += response => { if (inFlightOnlineRequest != null && !newRequest.Equals(inFlightOnlineRequest)) return; var result = LeaderboardScores.Success ( response.Scores.Select(s => s.ToScoreInfo(rulesets, newCriteria.Beatmap)) .OrderByTotalScore() .Select((s, idx) => { s.Position = idx + 1; return s; }) .ToArray(), response.ScoresCount, response.UserScore?.CreateScoreInfo(rulesets, newCriteria.Beatmap) ); inFlightOnlineRequest = null; scores.Value = result; }; newRequest.Failure += ex => { Logger.Log($@"Failed to fetch leaderboards when displaying results: {ex}", LoggingTarget.Network); if (ex is not OperationCanceledException) scores.Value = LeaderboardScores.Failure(LeaderboardFailState.NetworkFailure); }; api.Queue(inFlightOnlineRequest = newRequest); break; } } } private void localScoresChanged(IRealmCollection<ScoreInfo> sender, ChangeSet? changes) { Debug.Assert(CurrentCriteria != null); // This subscription may fire from changes to linked beatmaps, which we don't care about. // It's currently not possible for a score to be modified after insertion, so we can safely ignore callbacks with only modifications. if (changes?.HasCollectionChanges() == false) return; var newScores = sender.AsEnumerable(); if (CurrentCriteria.ExactMods != null) { if (!CurrentCriteria.ExactMods.Any()) { // we need to filter out all scores that have any mods to get all local nomod scores newScores = newScores.Where(s => !s.Mods.Any()); } else { // otherwise find all the scores that have all of the currently selected mods (similar to how web applies mod filters) // we're creating and using a string HashSet representation of selected mods so that it can be translated into the DB query itself var selectedMods = CurrentCriteria.ExactMods.Select(m => m.Acronym).ToHashSet(); newScores = newScores.Where(s => selectedMods.SetEquals(s.Mods.Select(m => m.Acronym))); } } newScores = newScores.Detach().OrderByCriteria(CurrentCriteria.Sorting); var newScoresArray = newScores.ToArray(); scores.Value = LeaderboardScores.Success(newScoresArray, newScoresArray.Length, null); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); localScoreSubscription?.Dispose(); } } public record LeaderboardCriteria( BeatmapInfo? Beatmap, RulesetInfo? Ruleset, BeatmapLeaderboardScope Scope, Mod[]? ExactMods, LeaderboardSortMode Sorting = LeaderboardSortMode.Score ); public record LeaderboardScores { public ICollection<ScoreInfo> TopScores { get; } public int TotalScores { get; } public ScoreInfo? UserScore { get; } public LeaderboardFailState? FailState { get; } public IEnumerable<ScoreInfo> AllScores { get { foreach (var score in TopScores) yield return score; if (UserScore != null && TopScores.All(topScore => !topScore.Equals(UserScore) && !topScore.MatchesOnlineID(UserScore))) yield return UserScore; } } private LeaderboardScores(ICollection<ScoreInfo> topScores, int totalScores, ScoreInfo? userScore, LeaderboardFailState? failState) { TopScores = topScores; TotalScores = totalScores; UserScore = userScore; FailState = failState; } public static LeaderboardScores Success(ICollection<ScoreInfo> topScores, int totalScores, ScoreInfo? userScore) => new LeaderboardScores(topScores, totalScores, userScore, null); public static LeaderboardScores Failure(LeaderboardFailState failState) => new LeaderboardScores([], 0, null, failState); } public enum LeaderboardFailState { NetworkFailure = -1, BeatmapUnavailable = -2, RulesetUnavailable = -3, NoneSelected = -4, NotLoggedIn = -5, NotSupporter = -6, NoTeam = -7 } }
412
0.900089
1
0.900089
game-dev
MEDIA
0.525614
game-dev
0.973685
1
0.973685
Poobslag/turbofat
8,124
project/src/main/puzzle/critter/spear.gd
class_name Spear extends Node2D ## A puzzle critter which adds veggie blocks from the sides. ## ## Sharks pop out onto the playfield, destroying any blocks they collide with. Depending on the level configuration, ## they might retreat eventually. If they retreat, they leave behind empty cells which is annoying as well. ## Which playfield side the spear appears from. enum Side { LEFT, RIGHT, } ## States the spear goes through when appearing/disappearing. enum State { NONE, WAITING, WAITING_END, POPPED_IN, POPPED_OUT, } const UNPOPPED_SPEAR_SPRITE_X := -450 const LEFT := Side.LEFT const RIGHT := Side.RIGHT const NONE := State.NONE const WAITING := State.WAITING const WAITING_END := State.WAITING_END const POPPED_IN := State.POPPED_IN const POPPED_OUT := State.POPPED_OUT ## Enum from State for the spear's current animation state. var state: int = NONE setget set_state ## Which playfield side the spear appears from. var side: int = Side.LEFT setget set_side ## The duration in seconds of the spear's pop in/pop out animation. var pop_anim_duration := 0.6 ## The length in pixels of the visible portion of the spear, after it's popped out. This can be a small number for ## short spears, or a large number for longer spears. var pop_length := 450 ## 'true' if a state has already been popped from the _next_states queue this frame. We monitor this to avoid ## accidentally popping two states from the queue when the spear first spawns. var _already_popped_state := false ## 'true' if the Spear will be queued for deletion after the 'poof' animation completes. var _free_after_poof := false ## Queue of enums from State for the spear's upcoming animation states. var _next_states := [] ## Schedules events for the spear's pop in/pop out animations. var _pop_tween: SceneTreeTween onready var poof: Sprite = $Poof onready var sfx: SpearSfx = $SpearSfx onready var spear_holder: Control = $SpearHolder onready var spear_sprite: Sprite = $SpearHolder/Spear onready var wait: SpearWaitSprite = $Wait onready var _crumb_holder := $CrumbHolder onready var _dirt_particles_burst: Particles2D = $SoilFront/DirtParticlesBurst onready var _dirt_particles_continuous: Particles2D = $SoilFront/DirtParticlesContinuous onready var _face: Sprite = $SpearHolder/Spear/Face onready var _soil_back: Sprite = $SoilFront onready var _soil_front: Sprite = $SoilBack onready var _states: StateMachine = $States ## key: (int) Enum from State ## value: (Node) State node from the _states StateMachine onready var _state_nodes_by_enum := { NONE: $States/None, WAITING: $States/Waiting, WAITING_END: $States/WaitingEnd, POPPED_IN: $States/PoppedIn, POPPED_OUT: $States/PoppedOut, } func _ready() -> void: # The state machine defaults to the 'none' state and not the 'null' state to avoid edge cases _states.set_state(_state_nodes_by_enum[NONE]) spear_sprite.position.x = -450 # avoid a case where we initialize a spear and it's immediately advanced _already_popped_state = true _refresh_side() _refresh_state() func _process(_delta: float) -> void: _already_popped_state = false ## Cancels any events for the spear's pop in/pop out animations. func kill_pop_tween() -> void: Utils.kill_tween(_pop_tween) _dirt_particles_burst.emitting = false _dirt_particles_continuous.emitting = false func set_side(new_side: int) -> void: side = new_side _refresh_side() ## Enqueues an enums from State to the spear's upcoming animation states. ## ## Parameters: ## 'next_state': Enum from State ## ## 'count': (Optional) Number of instances of the state to enqueue. func append_next_state(next_state: int, count: int = 1) -> void: for _i in range(count): _next_states.append(next_state) ## Clears the spear's queue of upcoming animation states. func clear_next_states() -> void: _next_states.clear() ## Returns 'true' if there are states remaining in the spear's queue of upcoming animation states. func has_next_state() -> bool: return not _next_states.empty() ## Dequeues the next state from the spear's queue of upcoming animation states. ## ## Returns: ## Enum from State for the spear's new state. func pop_next_state() -> int: if _next_states.empty(): return NONE if _already_popped_state: pass else: var next_state: int = _next_states.pop_front() set_state(next_state) _already_popped_state = true return state func pop_in_immediately() -> void: kill_pop_tween() spear_sprite.position.x = -450 + pop_length _dirt_particles_burst.restart() _dirt_particles_burst.emitting = true ## Parameters: ## 'new_state': enum from State for the spear's new animation state. func set_state(new_state: int) -> void: state = new_state # avoid a case where we set a spear's state, and it's immediately advanced _already_popped_state = true _refresh_state() ## Plays a 'poof' animation and queues the spear for deletion. func poof_and_free() -> void: set_state(NONE) if poof.is_poof_animation_playing(): _free_after_poof = true else: queue_free() ## Tweens the spear into view, or out of view. func tween_and_pop(target_x: float, squint_duration: float) -> void: sfx.play_pop_sound() _dirt_particles_burst.restart() _dirt_particles_burst.emitting = true _dirt_particles_continuous.emitting = true _pop_tween = Utils.recreate_tween(self, _pop_tween) _pop_tween.set_parallel() _ruffle_soil() _face.squint(squint_duration) _pop_tween.tween_property(spear_sprite, "position:x", target_x, pop_anim_duration) \ .set_trans(Tween.TRANS_QUINT).set_ease(Tween.EASE_OUT) _pop_tween.tween_callback(_dirt_particles_burst, "set", ["emitting", false]) \ .set_delay(pop_anim_duration) _pop_tween.tween_callback(_dirt_particles_continuous, "set", ["emitting", false]) \ .set_delay(pop_anim_duration * 0.5) if target_x > UNPOPPED_SPEAR_SPRITE_X: # if the spear is popping into view, we play a 'hello' sound effect _pop_tween.tween_callback(sfx, "play_hello_voice").set_delay(0.1) ## Emits particle properties based on the speared blocks. ## ## Parameters: ## 'crumb_colors': An array of Color instances corresponding to crumb colors for destroyed blocks. ## ## 'width': The width in pixels which should be covered in crumbs. func emit_crumbs(crumb_colors: Array, row: int) -> void: _crumb_holder.get_child(row).emit_crumbs(crumb_colors, pop_length) ## Schedules the soil to cycle between frames as the spear pops in or out. func _ruffle_soil() -> void: for soil_sprite in [_soil_back, _soil_front]: # make the soil visible soil_sprite.visible = true soil_sprite.frame = 0 _pop_tween.tween_callback(soil_sprite, "set", ["frame", 1]).set_delay(pop_anim_duration * 0.050) _pop_tween.tween_callback(soil_sprite, "set", ["frame", 2]).set_delay(pop_anim_duration * 0.080) _pop_tween.tween_callback(soil_sprite, "set", ["frame", 0]).set_delay(pop_anim_duration * 0.130) _pop_tween.tween_callback(soil_sprite, "set", ["frame", 1]).set_delay(pop_anim_duration * 0.210) _pop_tween.tween_callback(soil_sprite, "set", ["frame", 2]).set_delay(pop_anim_duration * 0.340) _pop_tween.tween_callback(soil_sprite, "set", ["frame", 0]).set_delay(pop_anim_duration * 0.550) ## Refreshes our visuals based on the 'side' property. ## ## Most of our visual elements flip or change position if we're appearing on the left or right side. func _refresh_side() -> void: if not is_inside_tree(): return var new_child_scale := -1 if side == Side.RIGHT else 1 _soil_back.scale.x = new_child_scale spear_holder.rect_scale.x = new_child_scale _soil_front.scale.x = new_child_scale _crumb_holder.rect_scale.x = new_child_scale wait.position.x = abs(wait.position.x) * new_child_scale poof.position.x = abs(poof.position.x) * new_child_scale ## Updates the state machine's state to match the value of the 'state' enum. func _refresh_state() -> void: if not is_inside_tree(): return _states.set_state(_state_nodes_by_enum[state]) ## When the 'poof' animation finishes, if poof_and_free() was called then we queue the spear for deletion. func _on_Poof_animation_finished() -> void: if _free_after_poof: queue_free()
412
0.887886
1
0.887886
game-dev
MEDIA
0.973564
game-dev
0.987433
1
0.987433
lintstar/SharpHunter
3,433
SharpHunter/Program.cs
using System; using System.Diagnostics; using SharpHunter.Commands; using SharpHunter.Utils; namespace SharpHunter { class Program { static void RegistrationCommands() { CommandRegistry.RegisterCommand("all", () => new HuntingAllCommand()); CommandRegistry.RegisterCommand("sys", () => new SystemInfoCommand()); CommandRegistry.RegisterCommand("pid", () => new ProcessCommand()); CommandRegistry.RegisterCommand("net", () => new NetworkInfoCommand()); CommandRegistry.RegisterCommand("rdp", () => new RDPInfoCommand()); CommandRegistry.RegisterCommand("soft", () => new SoftwareInfoCommand()); CommandRegistry.RegisterCommand("file", () => new UserFileInfoCommand()); CommandRegistry.RegisterCommand("domain", () => new DomainInfoCommand()); CommandRegistry.RegisterCommand("chrome", () => new ChromiumCredCommand()); CommandRegistry.RegisterCommand("fshell", () => new FinalShellCredCommand()); CommandRegistry.RegisterCommand("moba", () => new MobaXtermCredCommand()); CommandRegistry.RegisterCommand("todesk", () => new ToDeskCredCommand()); CommandRegistry.RegisterCommand("sunlogin", () => new SunLoginCredCommand()); CommandRegistry.RegisterCommand("wechat", () => new WeChatCredCommand()); CommandRegistry.RegisterCommand("wifi", () => new WifiCredCommand()); CommandRegistry.RegisterCommand("run", () => new ExecuteCmdCommand()); CommandRegistry.RegisterCommand("screen", () => new ScreenShotPostCommand()); CommandRegistry.RegisterCommand("adduser", () => new AddUserCommand()); CommandRegistry.RegisterCommand("enrdp", () => new EnableRDPCommand()); CommandRegistry.RegisterCommand("down", () => new DownloadFileCommand()); } static void Main(string[] args) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var commandParsedArgs = CommandLineParser.Parse(args); CommonUtils.Banner(); RegistrationCommands(); if (args.Length == 0) { Logger.WriteLine("\n[-] No command provided. Please try again."); CommonUtils.DisplayHelp(); return; } try { var command = CommandRegistry.GetCommand(commandParsedArgs.CommandName); string commandName = command.GetType().Name; Logger.Initialize(commandParsedArgs.LogEnabled, commandParsedArgs.ZipEnabled, commandName); command.Execute(commandParsedArgs.CommandArgs); } catch (ArgumentException ex) { Logger.WriteLine($"\n{ex.Message}"); CommonUtils.DisplayHelp(); } catch (Exception ex) { Logger.WriteLine($"\n{ex.Message}"); } if (commandParsedArgs.LogEnabled) { Logger.WriteLine("[+] LogFilePath: " + Logger.LogFilePath); } stopwatch.Stop(); Logger.WriteLine("\n[*] Hunt End: {0} s", stopwatch.Elapsed.TotalSeconds); if (commandParsedArgs.ZipEnabled) { Logger.SetLogToFile(); } } } }
412
0.709414
1
0.709414
game-dev
MEDIA
0.341546
game-dev
0.673849
1
0.673849
joergoster/Stockfish-NNUE
2,440
src/eval/nnue/features/castling_right.cpp
//Definition of input feature quantity K of NNUE evaluation function #if defined(EVAL_NNUE) #include "castling_right.h" #include "index_list.h" namespace Eval { namespace NNUE { namespace Features { // Get a list of indices with a value of 1 among the features void CastlingRight::AppendActiveIndices( const Position& pos, Color perspective, IndexList* active) { // do nothing if array size is small to avoid compiler warning if (RawFeatures::kMaxActiveDimensions < kMaxActiveDimensions) return; int castling_rights = pos.state()->castlingRights; int relative_castling_rights; if (perspective == WHITE) { relative_castling_rights = castling_rights; } else { // Invert the perspective. relative_castling_rights = ((castling_rights & 3) << 2) & ((castling_rights >> 2) & 3); } for (int i = 0; i <kDimensions; ++i) { if (relative_castling_rights & (i << 1)) { active->push_back(i); } } } // Get a list of indices whose values ​​have changed from the previous one in the feature quantity void CastlingRight::AppendChangedIndices( const Position& pos, Color perspective, IndexList* removed, IndexList* added) { int previous_castling_rights = pos.state()->previous->castlingRights; int current_castling_rights = pos.state()->castlingRights; int relative_previous_castling_rights; int relative_current_castling_rights; if (perspective == WHITE) { relative_previous_castling_rights = previous_castling_rights; relative_current_castling_rights = current_castling_rights; } else { // Invert the perspective. relative_previous_castling_rights = ((previous_castling_rights & 3) << 2) & ((previous_castling_rights >> 2) & 3); relative_current_castling_rights = ((current_castling_rights & 3) << 2) & ((current_castling_rights >> 2) & 3); } for (int i = 0; i < kDimensions; ++i) { if ((relative_previous_castling_rights & (i << 1)) && (relative_current_castling_rights & (i << 1)) == 0) { removed->push_back(i); } } } } // namespace Features } // namespace NNUE } // namespace Eval #endif // defined(EVAL_NNUE)
412
0.907244
1
0.907244
game-dev
MEDIA
0.346941
game-dev
0.941783
1
0.941783
Dreamtowards/Ethertia
2,042
lib/jolt-3.0.1/Jolt/Physics/Constraints/PathConstraintPathHermite.h
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) // SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #pragma once #include <Jolt/Physics/Constraints/PathConstraintPath.h> JPH_NAMESPACE_BEGIN /// A path that follows a Hermite spline class PathConstraintPathHermite final : public PathConstraintPath { public: JPH_DECLARE_SERIALIZABLE_VIRTUAL(PathConstraintPathHermite) // See PathConstraintPath::GetPathMaxFraction virtual float GetPathMaxFraction() const override { return float(IsLooping()? mPoints.size() : mPoints.size() - 1); } // See PathConstraintPath::GetClosestPoint virtual float GetClosestPoint(Vec3Arg inPosition) const override; // See PathConstraintPath::GetPointOnPath virtual void GetPointOnPath(float inFraction, Vec3 &outPathPosition, Vec3 &outPathTangent, Vec3 &outPathNormal, Vec3 &outPathBinormal) const override; /// Adds a point to the path void AddPoint(Vec3Arg inPosition, Vec3Arg inTangent, Vec3Arg inNormal) { mPoints.push_back({ inPosition, inTangent, inNormal}); } // See: PathConstraintPath::SaveBinaryState virtual void SaveBinaryState(StreamOut &inStream) const override; struct Point { JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(Point) Vec3 mPosition; ///< Position on the path Vec3 mTangent; ///< Tangent of the path, does not need to be normalized (in the direction of the path) Vec3 mNormal; ///< Normal of the path (together with the tangent along the curve this forms a basis for the constraint) }; protected: // See: PathConstraintPath::RestoreBinaryState virtual void RestoreBinaryState(StreamIn &inStream) override; private: /// Helper function that returns the index of the path segment and the fraction t on the path segment based on the full path fraction inline void GetIndexAndT(float inFraction, int &outIndex, float &outT) const; using Points = Array<Point>; Points mPoints; ///< Points on the Hermite spline }; JPH_NAMESPACE_END
412
0.91326
1
0.91326
game-dev
MEDIA
0.921857
game-dev
0.942603
1
0.942603
freeciv/freeciv
50,883
server/scripting/api_server_edit.c
/***************************************************************************** Freeciv - Copyright (C) 2005 - The Freeciv Project 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H #include <fc_config.h> #endif /* utility */ #include "rand.h" /* common */ #include "citizens.h" #include "map.h" #include "movement.h" #include "research.h" #include "unittype.h" /* common/scriptcore */ #include "api_game_find.h" #include "luascript.h" /* server */ #include "aiiface.h" #include "barbarian.h" #include "citytools.h" #include "cityturn.h" /* city_refresh() auto_arrange_workers() */ #include "console.h" /* enum rfc_status */ #include "gamehand.h" #include "maphand.h" #include "notify.h" #include "plrhand.h" #include "srv_main.h" /* game_was_started() */ #include "stdinhand.h" #include "techtools.h" #include "unithand.h" #include "unittools.h" /* server/scripting */ #include "script_server.h" /* server/generator */ #include "mapgen_utils.h" #include "api_server_edit.h" /**********************************************************************//** Unleash barbarians on a tile, for example from a hut **************************************************************************/ bool api_edit_unleash_barbarians(lua_State *L, Tile *ptile) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 2, Tile, FALSE); return unleash_barbarians(ptile); } /**********************************************************************//** A wrapper around transform_unit() that correctly processes some unsafe requests. punit and to_unit must not be NULL. **************************************************************************/ static bool ur_transform_unit(struct unit *punit, const struct unit_type *to_unit, int vet_loss) { if (UU_OK == unit_transform_result(&(wld.map), punit, to_unit)) { /* Avoid getting overt veteranship if a user requests increasing it */ if (vet_loss < 0) { int vl = utype_veteran_levels(to_unit); vl = punit->veteran - vl + 1; if (vl >= 0) { vet_loss = 0; } else { vet_loss = MAX(vet_loss, vl); } } transform_unit(punit, to_unit, vet_loss); return TRUE; } else { return FALSE; } } /**********************************************************************//** Place partisans for a player around a tile (normally around a city). **************************************************************************/ void api_edit_place_partisans(lua_State *L, Tile *ptile, Player *pplayer, int count, int sq_radius) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 2, Tile); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 3, Player); LUASCRIPT_CHECK_ARG(L, 0 <= sq_radius, 5, "radius must be positive"); LUASCRIPT_CHECK(L, 0 < num_role_units(L_PARTISAN), "no partisans in ruleset"); return place_partisans(ptile, pplayer, count, sq_radius); } /**********************************************************************//** Create a new unit. **************************************************************************/ Unit *api_edit_create_unit(lua_State *L, Player *pplayer, Tile *ptile, Unit_Type *ptype, int veteran_level, City *homecity, int moves_left) { return api_edit_create_unit_full(L, pplayer, ptile, ptype, veteran_level, homecity, moves_left, -1, NULL); } /**********************************************************************//** Create a new unit. **************************************************************************/ Unit *api_edit_create_unit_full(lua_State *L, Player *pplayer, Tile *ptile, Unit_Type *ptype, int veteran_level, City *homecity, int moves_left, int hp_left, Unit *ptransport) { struct fc_lua *fcl; struct city *pcity; struct unit *punit; #ifndef FREECIV_NDEBUG bool placed; #endif LUASCRIPT_CHECK_STATE(L, NULL); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 2, Player, NULL); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 3, Tile, NULL); fcl = luascript_get_fcl(L); LUASCRIPT_CHECK(L, fcl != NULL, "Undefined Freeciv lua state!", NULL); if (ptype == NULL || ptype < unit_type_array_first() || ptype > unit_type_array_last()) { return NULL; } if (is_non_allied_unit_tile(ptile, pplayer, utype_has_flag(ptype, UTYF_FLAGLESS))) { luascript_log(fcl, LOG_ERROR, "create_unit_full: tile is occupied by " "enemy unit"); return NULL; } pcity = tile_city(ptile); if (pcity != NULL && !pplayers_allied(pplayer, city_owner(pcity))) { luascript_log(fcl, LOG_ERROR, "create_unit_full: tile is occupied by " "enemy city"); return NULL; } if (utype_player_already_has_this_unique(pplayer, ptype)) { luascript_log(fcl, LOG_ERROR, "create_unit_full: player already has unique unit"); return NULL; } punit = unit_virtual_prepare(pplayer, ptile, ptype, veteran_level, homecity ? homecity->id : 0, moves_left, hp_left); if (ptransport) { /* The unit maybe can't freely load into the transport * but must be able to be in it, see can_unit_load() */ int ret = same_pos(ptile, unit_tile(ptransport)) && could_unit_be_in_transport(punit, ptransport); if (!ret) { unit_virtual_destroy(punit); luascript_log(fcl, LOG_ERROR, "create_unit_full: '%s' cannot transport " "'%s' here", utype_rule_name(unit_type_get(ptransport)), utype_rule_name(ptype)); return NULL; } } else if (!can_exist_at_tile(&(wld.map), ptype, ptile)) { unit_virtual_destroy(punit); luascript_log(fcl, LOG_ERROR, "create_unit_full: '%s' cannot exist at " "tile", utype_rule_name(ptype)); return NULL; } #ifndef FREECIV_NDEBUG placed = #endif place_unit(punit, pplayer, homecity, ptransport, TRUE); fc_assert_action(placed, unit_virtual_destroy(punit); punit = NULL); return punit; } /**********************************************************************//** Teleport unit to destination tile **************************************************************************/ bool api_edit_unit_teleport(lua_State *L, Unit *punit, Tile *dest, Unit *embark_to, bool allow_disembark, bool conquer_city, bool conquer_extra, bool enter_hut, bool frighten_hut) { bool alive; LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, dest, 3, Tile, FALSE); LUASCRIPT_CHECK(L, !(enter_hut && frighten_hut), "Can't both enter and frighten a hut at the same time", TRUE); if (!allow_disembark && unit_transported(punit)) { /* Can't leave the transport. */ return TRUE; } if (unit_teleport_to_tile_test(&(wld.map), punit, ACTIVITY_IDLE, unit_tile(punit), dest, FALSE, embark_to, TRUE) != MR_OK) { /* Can't teleport to target. Return that unit is still alive. */ return TRUE; } /* Teleport first so destination is revealed even if unit dies */ alive = unit_move(punit, dest, 0, embark_to, embark_to != NULL, conquer_city, conquer_extra, enter_hut, frighten_hut); if (alive) { struct player *owner = unit_owner(punit); struct city *pcity = tile_city(dest); if (!can_unit_exist_at_tile(&(wld.map), punit, dest) && !unit_transported(punit)) { wipe_unit(punit, ULR_NONNATIVE_TERR, NULL); return FALSE; } if (is_non_allied_unit_tile(dest, owner, unit_has_type_flag(punit, UTYF_FLAGLESS)) || (pcity != NULL && !pplayers_allied(city_owner(pcity), owner))) { wipe_unit(punit, ULR_STACK_CONFLICT, NULL); return FALSE; } } return alive; } /***********************************************************************//** Force a unit to perform an action against a city. ***************************************************************************/ bool api_edit_perform_action_unit_vs_city(lua_State *L, Unit *punit, Action *paction, City *tgt) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, paction, 3, Action, FALSE); LUASCRIPT_CHECK_ARG(L, action_get_actor_kind(paction) == AAK_UNIT, 3, "Not a unit-performed action", FALSE); LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) == ATK_CITY, 3, "Not a city-targeted action", FALSE); LUASCRIPT_CHECK_ARG_NIL(L, tgt, 4, City, FALSE); fc_assert_ret_val(!action_has_result(paction, ACTRES_FOUND_CITY), FALSE); if (is_action_enabled_unit_on_city(&(wld.map), paction->id, punit, tgt)) { return unit_perform_action(unit_owner(punit), punit->id, tgt->id, IDENTITY_NUMBER_ZERO, "", paction->id, ACT_REQ_RULES); } else { /* Action not enabled */ return FALSE; } } /***********************************************************************//** Force a unit to perform an action against a city and a building. ***************************************************************************/ bool api_edit_perform_action_unit_vs_city_impr(lua_State *L, Unit *punit, Action *paction, City *tgt, Building_Type *sub_tgt) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, paction, 3, Action, FALSE); LUASCRIPT_CHECK_ARG(L, action_get_actor_kind(paction) == AAK_UNIT, 3, "Not a unit-performed action", FALSE); LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) == ATK_CITY, 3, "Not a city-targeted action", FALSE); LUASCRIPT_CHECK_ARG_NIL(L, tgt, 4, City, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, sub_tgt, 5, Building_Type, FALSE); fc_assert_ret_val(!action_has_result(paction, ACTRES_FOUND_CITY), FALSE); if (is_action_enabled_unit_on_city(&(wld.map), paction->id, punit, tgt)) { return unit_perform_action(unit_owner(punit), punit->id, tgt->id, sub_tgt->item_number, "", paction->id, ACT_REQ_RULES); } else { /* Action not enabled */ return FALSE; } } /***********************************************************************//** Force a unit to perform an action against a city and a tech. ***************************************************************************/ bool api_edit_perform_action_unit_vs_city_tech(lua_State *L, Unit *punit, Action *paction, City *tgt, Tech_Type *sub_tgt) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, paction, 3, Action, FALSE); LUASCRIPT_CHECK_ARG(L, action_get_actor_kind(paction) == AAK_UNIT, 3, "Not a unit-performed action", FALSE); LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) == ATK_CITY, 3, "Not a city-targeted action", FALSE); LUASCRIPT_CHECK_ARG_NIL(L, tgt, 4, City, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, sub_tgt, 5, Tech_Type, FALSE); fc_assert_ret_val(!action_has_result(paction, ACTRES_FOUND_CITY), FALSE); if (is_action_enabled_unit_on_city(&(wld.map), paction->id, punit, tgt)) { return unit_perform_action(unit_owner(punit), punit->id, tgt->id, sub_tgt->item_number, "", paction->id, ACT_REQ_RULES); } else { /* Action not enabled */ return FALSE; } } /***********************************************************************//** Force a unit to perform an action against a unit. ***************************************************************************/ bool api_edit_perform_action_unit_vs_unit(lua_State *L, Unit *punit, Action *paction, Unit *tgt) { const struct civ_map *nmap = &(wld.map); LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, paction, 3, Action, FALSE); LUASCRIPT_CHECK_ARG(L, action_get_actor_kind(paction) == AAK_UNIT, 3, "Not a unit-performed action", FALSE); LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) == ATK_UNIT, 3, "Not a unit-targeted action", FALSE); LUASCRIPT_CHECK_ARG_NIL(L, tgt, 4, Unit, FALSE); fc_assert_ret_val(!action_has_result(paction, ACTRES_FOUND_CITY), FALSE); if (is_action_enabled_unit_on_unit(nmap, paction->id, punit, tgt)) { return unit_perform_action(unit_owner(punit), punit->id, tgt->id, IDENTITY_NUMBER_ZERO, "", paction->id, ACT_REQ_RULES); } else { /* Action not enabled */ return FALSE; } } /***********************************************************************//** Force a unit to perform an action against a tile. ***************************************************************************/ bool api_edit_perform_action_unit_vs_tile(lua_State *L, Unit *punit, Action *paction, Tile *tgt) { bool enabled = FALSE; const struct civ_map *nmap = &(wld.map); LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, paction, 3, Action, FALSE); LUASCRIPT_CHECK_ARG(L, action_get_actor_kind(paction) == AAK_UNIT, 3, "Not a unit-performed action", FALSE); LUASCRIPT_CHECK_ARG_NIL(L, tgt, 4, Tile, FALSE); switch (action_get_target_kind(paction)) { case ATK_STACK: enabled = is_action_enabled_unit_on_stack(nmap, paction->id, punit, tgt); break; case ATK_TILE: enabled = is_action_enabled_unit_on_tile(nmap, paction->id, punit, tgt, NULL); break; case ATK_EXTRAS: enabled = is_action_enabled_unit_on_extras(nmap, paction->id, punit, tgt, NULL); break; case ATK_CITY: /* Not handled here. */ LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) != ATK_CITY, 3, "City-targeted action applied to tile", FALSE); break; case ATK_UNIT: /* Not handled here. */ LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) != ATK_UNIT, 3, "Unit-targeted action applied to tile", FALSE); break; case ATK_SELF: /* Not handled here. */ LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) != ATK_SELF, 3, "Self-targeted action applied to tile", FALSE); break; case ATK_COUNT: /* Should not exist */ fc_assert(action_get_target_kind(paction) != ATK_COUNT); break; } if (enabled) { return unit_perform_action(unit_owner(punit), punit->id, tile_index(tgt), IDENTITY_NUMBER_ZERO, city_name_suggestion(unit_owner(punit), tgt), paction->id, ACT_REQ_RULES); } else { /* Action not enabled */ return FALSE; } } /***********************************************************************//** Force a unit to perform an action against a tile and an extra. ***************************************************************************/ bool api_edit_perform_action_unit_vs_tile_extra(lua_State *L, Unit *punit, Action *paction, Tile *tgt, const char *sub_tgt) { struct extra_type *sub_target; bool enabled = FALSE; const struct civ_map *nmap = &(wld.map); LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, paction, 3, Action, FALSE); LUASCRIPT_CHECK_ARG(L, action_get_actor_kind(paction) == AAK_UNIT, 3, "Not a unit-performed action", FALSE); LUASCRIPT_CHECK_ARG_NIL(L, tgt, 4, Tile, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, sub_tgt, 5, string, FALSE); sub_target = extra_type_by_rule_name(sub_tgt); LUASCRIPT_CHECK_ARG(L, sub_target != NULL, 5, "No such extra", FALSE); switch (action_get_target_kind(paction)) { case ATK_STACK: enabled = is_action_enabled_unit_on_stack(nmap, paction->id, punit, tgt); break; case ATK_TILE: enabled = is_action_enabled_unit_on_tile(nmap, paction->id, punit, tgt, sub_target); break; case ATK_EXTRAS: enabled = is_action_enabled_unit_on_extras(nmap, paction->id, punit, tgt, sub_target); break; case ATK_CITY: /* Not handled here. */ LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) != ATK_CITY, 3, "City-targeted action applied to tile", FALSE); break; case ATK_UNIT: /* Not handled here. */ LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) != ATK_UNIT, 3, "Unit-targeted action applied to tile", FALSE); break; case ATK_SELF: /* Not handled here. */ LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) != ATK_SELF, 3, "Self-targeted action applied to tile", FALSE); break; case ATK_COUNT: /* Should not exist */ fc_assert(action_get_target_kind(paction) != ATK_COUNT); break; } if (enabled) { return unit_perform_action(unit_owner(punit), punit->id, tile_index(tgt), sub_target->id, city_name_suggestion(unit_owner(punit), tgt), paction->id, ACT_REQ_RULES); } else { /* Action not enabled */ return FALSE; } } /***********************************************************************//** Force a unit to perform an action against it self. ***************************************************************************/ bool api_edit_perform_action_unit_vs_self(lua_State *L, Unit *punit, Action *paction) { const struct civ_map *nmap = &(wld.map); LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, paction, 3, Action, FALSE); LUASCRIPT_CHECK_ARG(L, action_get_actor_kind(paction) == AAK_UNIT, 3, "Not a unit-performed action", FALSE); LUASCRIPT_CHECK_ARG(L, action_get_target_kind(paction) == ATK_SELF, 3, "Not a self-targeted action", FALSE); fc_assert_ret_val(!action_has_result(paction, ACTRES_FOUND_CITY), FALSE); if (is_action_enabled_unit_on_self(nmap, paction->id, punit)) { return unit_perform_action(unit_owner(punit), punit->id, IDENTITY_NUMBER_ZERO, IDENTITY_NUMBER_ZERO, "", paction->id, ACT_REQ_RULES); } else { /* Action not enabled */ return FALSE; } } /**********************************************************************//** Change unit orientation **************************************************************************/ void api_edit_unit_turn(lua_State *L, Unit *punit, Direction dir) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit); if (direction8_is_valid(dir)) { punit->facing = dir; send_unit_info(NULL, punit); } else { log_error("Illegal direction %d for unit from lua script", dir); } } /**********************************************************************//** Upgrade punit for free in the default manner, lose vet_loss vet levels. Returns if the upgrade was possible. **************************************************************************/ bool api_edit_unit_upgrade(lua_State *L, Unit *punit, int vet_loss) { const struct unit_type *ptype; LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_SELF(L, punit, FALSE); ptype = can_upgrade_unittype(unit_owner(punit), unit_type_get(punit)); if (!ptype) { return FALSE; } return ur_transform_unit(punit, ptype, vet_loss); } /**********************************************************************//** Transform punit to ptype, decreasing vet_loss veteranship levels. Returns if the transformation was possible. **************************************************************************/ bool api_edit_unit_transform(lua_State *L, Unit *punit, Unit_Type *ptype, int vet_loss) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_SELF(L, punit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, ptype, 3, Unit_Type, FALSE); return ur_transform_unit(punit, ptype, vet_loss); } /**********************************************************************//** Kill the unit. **************************************************************************/ void api_edit_unit_kill(lua_State *L, Unit *punit, const char *reason, Player *killer) { enum unit_loss_reason loss_reason; LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, punit, 2, Unit); LUASCRIPT_CHECK_ARG_NIL(L, reason, 3, string); loss_reason = unit_loss_reason_by_name(reason, fc_strcasecmp); LUASCRIPT_CHECK_ARG(L, unit_loss_reason_is_valid(loss_reason), 3, "Invalid unit loss reason"); wipe_unit(punit, loss_reason, killer); } /**********************************************************************//** Change unit hitpoints. Reason and killer are used if unit dies. **************************************************************************/ bool api_edit_unit_hitpoints(lua_State *L, Unit *self, int change, const char *reason, Player *killer) { LUASCRIPT_CHECK_STATE(L, TRUE); LUASCRIPT_CHECK_ARG_NIL(L, self, 2, Unit, TRUE); self->hp += change; if (self->hp <= 0) { enum unit_loss_reason loss_reason = unit_loss_reason_by_name(reason, fc_strcasecmp); wipe_unit(self, loss_reason, killer); /* Intentionally only after wiping, so that unit is never left with * zero or less hit points. */ LUASCRIPT_CHECK_ARG(L, unit_loss_reason_is_valid(loss_reason), 4, "Invalid unit loss reason", FALSE); return FALSE; } else { int max = unit_type_get(self)->hp; if (self->hp > max) { self->hp = max; } } send_unit_info(NULL, self); return TRUE; } /**********************************************************************//** Change unit move points. **************************************************************************/ void api_edit_unit_movepoints(lua_State *L, Unit *self, int change) { bool was_exhausted = FALSE; LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, self, 2, Unit); if (self->moves_left == 0 && self->done_moving) { was_exhausted = TRUE; } self->moves_left += change; if (self->moves_left <= 0) { self->moves_left = 0; } else if (was_exhausted && !unit_has_orders(self)) { /* Unit has regained ability to move. */ self->done_moving = FALSE; } send_unit_info(NULL, self); } /**********************************************************************//** Change terrain on tile **************************************************************************/ bool api_edit_change_terrain(lua_State *L, Tile *ptile, Terrain *pterr) { struct terrain *old_terrain; LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 2, Tile, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, pterr, 3, Terrain, FALSE); old_terrain = tile_terrain(ptile); if (old_terrain == pterr || (terrain_has_flag(pterr, TER_NO_CITIES) && tile_city(ptile) != NULL)) { return FALSE; } tile_change_terrain(ptile, pterr); fix_tile_on_terrain_change(ptile, old_terrain, FALSE); if (need_to_reassign_continents(old_terrain, pterr)) { assign_continent_numbers(); /* FIXME: adv / ai phase handling like in check_terrain_change() */ send_all_known_tiles(NULL); } update_tile_knowledge(ptile); tile_change_side_effects(ptile, TRUE); return TRUE; } /**********************************************************************//** Create a new city. **************************************************************************/ bool api_edit_create_city(lua_State *L, Player *pplayer, Tile *ptile, const char *name, Player *nationality) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 2, Player, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 3, Tile, FALSE); return create_city_for_player(pplayer, ptile, name, nationality); } /**********************************************************************//** Destroy a city **************************************************************************/ void api_edit_remove_city(lua_State *L, City *pcity) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, pcity, 2, City); remove_city(pcity); } /**********************************************************************//** Transfer city from player to another. **************************************************************************/ bool api_edit_transfer_city(lua_State *L, City *pcity, Player *new_owner) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, pcity, 2, City, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, new_owner, 3, Player, FALSE); return transfer_city(new_owner, pcity, FALSE, FALSE, FALSE, FALSE, FALSE); } /**********************************************************************//** Create a building to a city **************************************************************************/ void api_edit_create_building(lua_State *L, City *pcity, Building_Type *impr) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, pcity, 2, City); LUASCRIPT_CHECK_ARG_NIL(L, impr, 3, Building_Type); /* FIXME: may "Special" impr be buildable? */ LUASCRIPT_CHECK_ARG(L, !is_special_improvement(impr), 3, "It is a special item, not a city building"); if (!city_has_building(pcity, impr)) { bool need_game_info = FALSE; bool need_plr_info = FALSE; struct player *old_owner = NULL, *pplayer = city_owner(pcity); struct city *oldcity; oldcity = build_or_move_building(pcity, impr, &old_owner); if (oldcity) { need_plr_info = TRUE; } if (old_owner && old_owner != pplayer) { /* Great wonders make more changes. */ need_game_info = TRUE; } if (oldcity) { if (city_refresh(oldcity)) { auto_arrange_workers(oldcity); } send_city_info(NULL, oldcity); } if (city_refresh(pcity)) { auto_arrange_workers(pcity); } send_city_info(NULL, pcity); if (need_game_info) { send_game_info(NULL); send_player_info_c(old_owner, NULL); } if (need_plr_info) { send_player_info_c(pplayer, NULL); } } } /**********************************************************************//** Remove a building from a city **************************************************************************/ void api_edit_remove_building(lua_State *L, City *pcity, Building_Type *impr) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, pcity, 2, City); LUASCRIPT_CHECK_ARG_NIL(L, impr, 3, Building_Type); if (city_has_building(pcity, impr)) { city_remove_improvement(pcity, impr); send_city_info(NULL, pcity); if (is_wonder(impr)) { if (is_great_wonder(impr)) { send_game_info(NULL); } send_player_info_c(city_owner(pcity), NULL); } } } /**********************************************************************//** Reduce specialists of given type s. Superspecialists are just reduced, normal specialists are toggled in a way like toggling in the client. Does not place workers on map, just switches to another specialist. Does nothing if there is less than amount specialists s in pcity. Return if given number could be removed/repurposed. **************************************************************************/ bool api_edit_city_reduce_specialists(lua_State *L, City *pcity, Specialist *s, int amount) { Specialist_type_id from; LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_SELF(L, pcity, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, s, 2, Specialist, FALSE); LUASCRIPT_CHECK_ARG(L, amount >= 0, 3, "must be non-negative", FALSE); from = specialist_index(s); if (pcity->specialists[from] < amount) { return FALSE; } if (is_super_specialist_id(from)) { /* Just reduce superspecialists */ pcity->specialists[from] -= amount; } else { /* Toggle normal specialist */ Specialist_type_id to = from; do { to = (to + 1) % normal_specialist_count(); } while (to != from && !city_can_use_specialist(pcity, to)); if (to == from) { /* We can use only the default specialist */ return FALSE; } else { /* City population must be correct */ fc_assert_ret_val_msg(pcity->specialists[to] <= amount - MAX_CITY_SIZE, FALSE, "Wrong specialist number in %s", city_name_get(pcity)); pcity->specialists[from] -= amount; pcity->specialists[to] += amount; } } city_refresh(pcity); /* sanity_check_city(pcity); -- hopefully we don't break things here? */ send_city_info(city_owner(pcity), pcity); return TRUE; } /**********************************************************************//** Add amount specialists of given type s to pcity, return true iff done. For normal specialists, also increases city size at amount. Fails if either pcity does not fulfill s->reqs or it does not have enough space for given specialists or citizens number. **************************************************************************/ bool api_edit_city_add_specialist(lua_State *L, City *pcity, Specialist *s, int amount) { Specialist_type_id sid; int csize = 0; LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_SELF(L, pcity, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, s, 2, Specialist, FALSE); LUASCRIPT_CHECK_ARG(L, amount >= 0, 3, "must be non-negative", FALSE); sid = specialist_index(s); if (!city_can_use_specialist(pcity, sid)) { /* Can't employ this one */ return FALSE; } if (is_super_specialist(s)) { if (pcity->specialists[sid] > MAX_CITY_SIZE - amount) { /* No place for the specialist */ return FALSE; } pcity->specialists[sid] += amount; city_refresh(pcity); send_city_info(city_owner(pcity), pcity); } else { csize = city_size_get(pcity); if (csize > MAX_CITY_SIZE - amount) { /* No place for the specialist */ return FALSE; } city_change_size(pcity, csize + amount, city_owner(pcity), sid, "script"); city_refresh(pcity); send_city_info(nullptr, pcity); } return TRUE; } /**********************************************************************//** Create a new player. **************************************************************************/ Player *api_edit_create_player(lua_State *L, const char *username, Nation_Type *pnation, const char *ai) { struct player *pplayer = NULL; char buf[128] = ""; struct fc_lua *fcl; LUASCRIPT_CHECK_STATE(L, NULL); LUASCRIPT_CHECK_ARG_NIL(L, username, 2, string, NULL); if (!ai) { ai = default_ai_type_name(); } fcl = luascript_get_fcl(L); LUASCRIPT_CHECK(L, fcl != NULL, "Undefined Freeciv lua state!", NULL); if (game_was_started()) { create_command_newcomer(username, ai, FALSE, pnation, &pplayer, buf, sizeof(buf)); } else { create_command_pregame(username, ai, FALSE, &pplayer, buf, sizeof(buf)); } if (strlen(buf) > 0) { luascript_log(fcl, LOG_NORMAL, "%s", buf); } return pplayer; } /**********************************************************************//** Change pplayer's gold by amount. **************************************************************************/ void api_edit_change_gold(lua_State *L, Player *pplayer, int amount) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 2, Player); pplayer->economic.gold = MAX(0, pplayer->economic.gold + amount); send_player_info_c(pplayer, NULL); } /**********************************************************************//** Change pplayer's infrapoints by amount. **************************************************************************/ void api_edit_change_infrapoints(lua_State *L, Player *pplayer, int amount) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 2, Player); pplayer->economic.infra_points = MAX(0, pplayer->economic.infra_points + amount); send_player_info_c(pplayer, NULL); } /**********************************************************************//** Give pplayer technology ptech. Quietly returns NULL if player already has this tech; otherwise returns the tech granted. Use NULL for ptech to grant a random tech. sends script signal "tech_researched" with the given reason **************************************************************************/ Tech_Type *api_edit_give_technology(lua_State *L, Player *pplayer, Tech_Type *ptech, int cost, bool notify, const char *reason) { struct research *presearch; Tech_type_id id; Tech_Type *result; LUASCRIPT_CHECK_STATE(L, NULL); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 2, Player, NULL); LUASCRIPT_CHECK_ARG(L, cost >= -3, 4, "Unknown give_tech() cost value", NULL); presearch = research_get(pplayer); if (ptech) { id = advance_number(ptech); } else { id = pick_free_tech(presearch); } if (is_future_tech(id) || research_invention_state(presearch, id) != TECH_KNOWN) { if (cost < 0) { if (cost == -1) { cost = game.server.freecost; } else if (cost == -2) { cost = game.server.conquercost; } else if (cost == -3) { cost = game.server.diplbulbcost; } else { cost = 0; } } research_apply_penalty(presearch, id, cost); found_new_tech(presearch, id, FALSE, TRUE); result = advance_by_number(id); script_tech_learned(presearch, pplayer, result, reason); if (notify && result != NULL) { const char *adv_name = research_advance_name_translation(presearch, id); char research_name[MAX_LEN_NAME * 2]; research_pretty_name(presearch, research_name, sizeof(research_name)); notify_player(pplayer, NULL, E_TECH_GAIN, ftc_server, Q_("?fromscript:You acquire %s."), adv_name); notify_research(presearch, pplayer, E_TECH_GAIN, ftc_server, /* TRANS: "The Greeks ..." or "The members of * team Red ..." */ Q_("?fromscript:The %s acquire %s and share this " "advance with you."), nation_plural_for_player(pplayer), adv_name); notify_research_embassies(presearch, NULL, E_TECH_EMBASSY, ftc_server, /* TRANS: "The Greeks ..." or "The members of * team Red ..." */ Q_("?fromscript:The %s acquire %s."), research_name, adv_name); } return result; } else { return NULL; } } /**********************************************************************//** Modify player's trait value. **************************************************************************/ bool api_edit_trait_mod_set(lua_State *L, Player *pplayer, const char *tname, const int mod) { enum trait tr; LUASCRIPT_CHECK_STATE(L, -1); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 2, Player, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, tname, 3, string, FALSE); tr = trait_by_name(tname, fc_strcasecmp); LUASCRIPT_CHECK_ARG(L, trait_is_valid(tr), 3, "no such trait", 0); pplayer->ai_common.traits[tr].mod += mod; return TRUE; } /**********************************************************************//** Create a new owned extra. **************************************************************************/ void api_edit_create_owned_extra(lua_State *L, Tile *ptile, const char *name, Player *pplayer) { struct extra_type *pextra; LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 2, Tile); if (name == NULL) { return; } pextra = extra_type_by_rule_name(name); if (pextra != NULL) { create_extra(ptile, pextra, pplayer); update_tile_knowledge(ptile); tile_change_side_effects(ptile, TRUE); } } /**********************************************************************//** Create a new extra. **************************************************************************/ void api_edit_create_extra(lua_State *L, Tile *ptile, const char *name) { api_edit_create_owned_extra(L, ptile, name, NULL); } /**********************************************************************//** Create a new base. **************************************************************************/ void api_edit_create_base(lua_State *L, Tile *ptile, const char *name, Player *pplayer) { api_edit_create_owned_extra(L, ptile, name, pplayer); } /**********************************************************************//** Add a new road. **************************************************************************/ void api_edit_create_road(lua_State *L, Tile *ptile, const char *name) { api_edit_create_owned_extra(L, ptile, name, NULL); } /**********************************************************************//** Remove extra from tile, if present **************************************************************************/ void api_edit_remove_extra(lua_State *L, Tile *ptile, const char *name) { struct extra_type *pextra; LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 2, Tile); if (name == NULL) { return; } pextra = extra_type_by_rule_name(name); if (pextra != NULL && tile_has_extra(ptile, pextra)) { tile_extra_rm_apply(ptile, pextra); update_tile_knowledge(ptile); tile_change_side_effects(ptile, TRUE); } } /**********************************************************************//** Set tile label text. **************************************************************************/ void api_edit_tile_set_label(lua_State *L, Tile *ptile, const char *label) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, ptile); LUASCRIPT_CHECK_ARG_NIL(L, label, 3, string); tile_set_label(ptile, label); if (server_state() >= S_S_RUNNING) { send_tile_info(NULL, ptile, FALSE); } } /**********************************************************************//** Reveal tile as it is currently to the player. **************************************************************************/ void api_edit_tile_show(lua_State *L, Tile *ptile, Player *pplayer) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, ptile); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 3, Player); map_show_tile(pplayer, ptile); } /**********************************************************************//** Try to hide tile from player. **************************************************************************/ bool api_edit_tile_hide(lua_State *L, Tile *ptile, Player *pplayer) { struct city *pcity; LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_SELF(L, ptile, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 3, Player, FALSE); if (map_is_known_and_seen(ptile, pplayer, V_MAIN)) { /* Can't hide currently seen tile */ return FALSE; } pcity = tile_city(ptile); if (pcity != NULL) { trade_partners_iterate(pcity, partner) { if (really_gives_vision(pplayer, city_owner(partner))) { /* Can't remove vision about trade partner */ return FALSE; } } trade_partners_iterate_end; } dbv_clr(&pplayer->tile_known, tile_index(ptile)); send_tile_info(pplayer->connections, ptile, TRUE); return TRUE; } /**********************************************************************//** Global climate change. **************************************************************************/ void api_edit_climate_change(lua_State *L, enum climate_change_type type, int effect) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG(L, type == CLIMATE_CHANGE_GLOBAL_WARMING || type == CLIMATE_CHANGE_NUCLEAR_WINTER, 2, "invalid climate change type"); LUASCRIPT_CHECK_ARG(L, effect > 0, 3, "effect must be greater than zero"); climate_change(type == CLIMATE_CHANGE_GLOBAL_WARMING, effect); } /**********************************************************************//** Provoke a civil war. **************************************************************************/ Player *api_edit_civil_war(lua_State *L, Player *pplayer, int probability) { LUASCRIPT_CHECK_STATE(L, NULL); LUASCRIPT_CHECK_ARG_NIL(L, pplayer, 2, Player, NULL); LUASCRIPT_CHECK_ARG(L, probability >= 0 && probability <= 100, 3, "must be a percentage", NULL); if (!civil_war_possible(pplayer, FALSE, FALSE)) { return NULL; } if (probability == 0) { /* Calculate chance with normal rules */ if (!civil_war_triggered(pplayer)) { return NULL; } } else { /* Fixed chance specified by script */ if (fc_rand(100) >= probability) { return NULL; } } return civil_war(pplayer); } /**********************************************************************//** Make player winner of the scenario **************************************************************************/ void api_edit_player_victory(lua_State *L, Player *pplayer) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, pplayer); player_status_add(pplayer, PSTATUS_WINNER); } /**********************************************************************//** Move a unit. **************************************************************************/ bool api_edit_unit_move(lua_State *L, Unit *punit, Tile *ptile, int movecost, Unit *embark_to, bool disembark, bool conquer_city, bool conquer_extra, bool enter_hut, bool frighten_hut) { LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_SELF(L, punit, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, ptile, 3, Tile, FALSE); LUASCRIPT_CHECK_ARG(L, movecost >= 0, 4, "Negative move cost!", FALSE); LUASCRIPT_CHECK(L, !(enter_hut && frighten_hut), "Can't both enter and frighten a hut at the same time", TRUE); if (!disembark && unit_transported(punit)) { /* Can't leave the transport. */ return TRUE; } if (unit_move_to_tile_test(&(wld.map), punit, ACTIVITY_IDLE, unit_tile(punit), ptile, TRUE, FALSE, embark_to, TRUE) != MR_OK) { /* Can't move to target. Return that unit is still alive. */ return TRUE; } return unit_move(punit, ptile, movecost, embark_to, embark_to != NULL, conquer_city, conquer_extra, enter_hut, frighten_hut); } /**********************************************************************//** Prohibit unit from moving **************************************************************************/ void api_edit_unit_moving_disallow(lua_State *L, Unit *punit) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, punit); if (punit != NULL) { punit->stay = TRUE; } } /**********************************************************************//** Allow unit to move **************************************************************************/ void api_edit_unit_moving_allow(lua_State *L, Unit *punit) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, punit); if (punit != NULL) { punit->stay = FALSE; } } /**********************************************************************//** Add history to a city **************************************************************************/ void api_edit_city_add_history(lua_State *L, City *pcity, int amount) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, pcity); pcity->history += amount; } /**********************************************************************//** Add history to a player **************************************************************************/ void api_edit_player_add_history(lua_State *L, Player *pplayer, int amount) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, pplayer); pplayer->history += amount; } /**********************************************************************//** Give bulbs to a player, optionally towards a specific tech. If a tech that is not currently in research is specified, tech known state will not immediately change. Out of multiresearch mode, when tech is not NULL, this function sets the "previous" tech (or clears it if the current one is specified); in the case if a new "previous" tech is set, all non-free bulbs of the old "previous" tech are cleared, and if necessary the bulbs on stock are adjusted (for clear switching) as like amount was the previously researched value. **************************************************************************/ void api_edit_player_give_bulbs(lua_State *L, Player *pplayer, int amount, Tech_Type *tech) { struct research *presearch; LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_SELF(L, pplayer); presearch = research_get(pplayer); fc_assert_ret(presearch); if (!tech) { update_bulbs(pplayer, amount, TRUE, TRUE); send_research_info(presearch, NULL); } else if (advance_number(tech) == presearch->researching) { update_bulbs(pplayer, amount, TRUE, FALSE); /* Clean the saved tech to get no surprizes switching */ presearch->researching_saved = A_UNKNOWN; send_research_info(presearch, NULL); } else { /* Sometimes we may set negative bulbs, it's normal though lurking */ if (game.server.multiresearch) { presearch->inventions[advance_number(tech)].bulbs_researched_saved += amount; /* Currently, multiresearch data are not sent to clients */ } else { int oldb = presearch->bulbs_researched; /* NOTE: We can set a tech we already know / can't research here. * Probably it's safe as we can't switch into it any way. */ if (presearch->researching_saved != advance_number(tech)) { presearch->researching_saved = advance_number(tech); presearch->bulbs_researching_saved = amount + presearch->free_bulbs; } else { presearch->bulbs_researching_saved += amount + presearch->free_bulbs; } /* For consistency, modify current bulbs alongside * (sometimes getting into "overresearch" situation, but ok) */ presearch->bulbs_researched = amount - amount * game.server.techpenalty / 100 + presearch->free_bulbs; if (oldb != presearch->bulbs_researched) { send_research_info(presearch, NULL); } } } } /**********************************************************************//** Create a trade route between two cities. **************************************************************************/ bool api_edit_create_trade_route(lua_State *L, City *from, City *to) { struct player *pplayer, *partner_player; LUASCRIPT_CHECK_STATE(L, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, from, 2, City, FALSE); LUASCRIPT_CHECK_ARG_NIL(L, to, 3, City, FALSE); /* Priority zero -> never replace old routes. */ if (!can_establish_trade_route(from, to, 0)) { return FALSE; } create_trade_route(from, to, goods_from_city_to_unit(from, NULL)); /* Refresh the cities. */ city_refresh(from); city_refresh(to); pplayer = city_owner(from); partner_player = city_owner(to); send_city_info(pplayer, from); send_city_info(partner_player, to); /* Notify each player about the other's cities. */ if (pplayer != partner_player && game.info.reveal_trade_partner) { map_show_tile(partner_player, city_tile(from)); send_city_info(partner_player, from); map_show_tile(pplayer, city_tile(to)); send_city_info(pplayer, to); } return TRUE; } /**********************************************************************//** Change city size. **************************************************************************/ void api_edit_change_city_size(lua_State *L, City *pcity, int change, Player *nationality) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, pcity, 2, City); if (nationality == nullptr) { nationality = city_owner(pcity); } city_change_size(pcity, city_size_get(pcity) + change, nationality, -1, "script"); } /**********************************************************************//** Change nationality of the city citizens. **************************************************************************/ void api_edit_change_citizen_nationality(lua_State *L, City *pcity, Player *from, Player *to, int amount) { LUASCRIPT_CHECK_STATE(L); LUASCRIPT_CHECK_ARG_NIL(L, pcity, 2, City); LUASCRIPT_CHECK_ARG_NIL(L, from, 3, Player); LUASCRIPT_CHECK_ARG_NIL(L, to, 4, Player); citizens_nation_move(pcity, from->slot, to->slot, amount); }
412
0.841224
1
0.841224
game-dev
MEDIA
0.903865
game-dev
0.933871
1
0.933871
electronicarts/CnC_Generals_Zero_Hour
15,469
Generals/Code/Tools/WorldBuilder/src/TerrainMaterial.cpp
/* ** Command & Conquer Generals(tm) ** Copyright 2025 Electronic Arts 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 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ // TerrainMaterial.cpp : implementation file // #define DEFINE_TERRAIN_TYPE_NAMES #include "stdafx.h" #include "resource.h" #include "Lib\BaseType.h" #include "terrainmaterial.h" #include "WHeightMapEdit.h" #include "WorldBuilderDoc.h" #include "TileTool.h" #include "WBView3D.h" #include "Common/TerrainTypes.h" #include "W3DDevice/GameClient/TerrainTex.h" #include "W3DDevice/GameClient/HeightMap.h" TerrainMaterial *TerrainMaterial::m_staticThis = NULL; static Int defaultMaterialIndex = 0; ///////////////////////////////////////////////////////////////////////////// // TerrainMaterial dialog Int TerrainMaterial::m_currentFgTexture(3); Int TerrainMaterial::m_currentBgTexture(6); Bool TerrainMaterial::m_paintingPathingInfo; Bool TerrainMaterial::m_paintingPassable; TerrainMaterial::TerrainMaterial(CWnd* pParent /*=NULL*/) : m_updating(false), m_currentWidth(3) { //{{AFX_DATA_INIT(TerrainMaterial) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void TerrainMaterial::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(TerrainMaterial) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(TerrainMaterial, COptionsPanel) //{{AFX_MSG_MAP(TerrainMaterial) ON_BN_CLICKED(IDC_SWAP_TEXTURES, OnSwapTextures) ON_EN_CHANGE(IDC_SIZE_EDIT, OnChangeSizeEdit) ON_BN_CLICKED(IDC_IMPASSABLE, OnImpassable) ON_BN_CLICKED(IDC_PASSABLE_CHECK, OnPassableCheck) ON_BN_CLICKED(IDC_PASSABLE, OnPassable) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // TerrainMaterial data access method. /// Set foreground texture and invalidate swatches. void TerrainMaterial::setFgTexClass(Int texClass) { if (m_staticThis) { m_staticThis->m_currentFgTexture=texClass; m_staticThis->m_terrainSwatches.Invalidate(); updateTextureSelection(); } } /// Set backgroundground texture and invalidate swatches. void TerrainMaterial::setBgTexClass(Int texClass) { if (m_staticThis) { m_staticThis->m_currentBgTexture=texClass; m_staticThis->m_terrainSwatches.Invalidate(); } } /// Sets the setWidth value in the dialog. /** Update the value in the edit control and the slider. */ void TerrainMaterial::setWidth(Int width) { CString buf; buf.Format("%d", width); if (m_staticThis && !m_staticThis->m_updating) { m_staticThis->m_currentWidth = width; CWnd *pEdit = m_staticThis->GetDlgItem(IDC_SIZE_EDIT); if (pEdit) pEdit->SetWindowText(buf); } } /// Sets the tool option - single & multi tile use this panel, // and only multi tile uses the width. /** Update the ui for the tool. */ void TerrainMaterial::setToolOptions(Bool singleCell) { CString buf; if (m_staticThis ) { m_staticThis->m_updating = true; CWnd *pEdit = m_staticThis->GetDlgItem(IDC_SIZE_EDIT); if (pEdit) { pEdit->EnableWindow(!singleCell); if (singleCell) { pEdit->SetWindowText("1"); } } pEdit = m_staticThis->GetDlgItem(IDC_SIZE_POPUP); if (pEdit) { pEdit->EnableWindow(!singleCell); } m_staticThis->m_updating = false; } } void TerrainMaterial::updateLabel(void) { CWorldBuilderDoc *pDoc = CWorldBuilderDoc::GetActiveDoc(); if (!pDoc) return; AsciiString name = pDoc->GetHeightMap()->getTexClassUiName(m_currentFgTexture); const char *tName = name.str(); if (tName == NULL || tName[0] == 0) { tName = pDoc->GetHeightMap()->getTexClassUiName(m_currentFgTexture).str(); } if (tName == NULL) { return; } const char *leaf = tName; while (*tName) { if ((tName[0] == '\\' || tName[0] == '/')&& tName[1]) { leaf = tName+1; } tName++; } CWnd *pLabel = GetDlgItem(IDC_TERRAIN_NAME); if (pLabel) { pLabel->SetWindowText(leaf); } } void TerrainMaterial::updateTextureSelection(void) { if (m_staticThis) { m_staticThis->setTerrainTreeViewSelection(TVI_ROOT, m_staticThis->m_currentFgTexture); m_staticThis->updateLabel(); } } /// Set the selected texture in the tree view. Bool TerrainMaterial::setTerrainTreeViewSelection(HTREEITEM parent, Int selection) { TVITEM item; char buffer[_MAX_PATH]; ::memset(&item, 0, sizeof(item)); HTREEITEM child = m_terrainTreeView.GetChildItem(parent); while (child != NULL) { item.mask = TVIF_HANDLE|TVIF_PARAM; item.hItem = child; item.pszText = buffer; item.cchTextMax = sizeof(buffer)-2; m_terrainTreeView.GetItem(&item); if (item.lParam == selection) { m_terrainTreeView.SelectItem(child); return(true); } if (setTerrainTreeViewSelection(child, selection)) { return(true); } child = m_terrainTreeView.GetNextSiblingItem(child); } return(false); } ///////////////////////////////////////////////////////////////////////////// // TerrainMaterial message handlers /// Setup the controls in the dialog. BOOL TerrainMaterial::OnInitDialog() { CDialog::OnInitDialog(); m_updating = true; CWnd *pWnd = GetDlgItem(IDC_TERRAIN_TREEVIEW); CRect rect; pWnd->GetWindowRect(&rect); ScreenToClient(&rect); rect.DeflateRect(2,2,2,2); m_terrainTreeView.Create(TVS_HASLINES|TVS_LINESATROOT|TVS_HASBUTTONS| TVS_SHOWSELALWAYS|TVS_DISABLEDRAGDROP, rect, this, IDC_TERRAIN_TREEVIEW); m_terrainTreeView.ShowWindow(SW_SHOW); pWnd = GetDlgItem(IDC_TERRAIN_SWATCHES); pWnd->GetWindowRect(&rect); ScreenToClient(&rect); rect.DeflateRect(2,2,2,2); m_terrainSwatches.Create(NULL, "", WS_CHILD, rect, this, IDC_TERRAIN_SWATCHES); m_terrainSwatches.ShowWindow(SW_SHOW); m_paintingPathingInfo = false; m_paintingPassable = false; CButton *button = (CButton *)GetDlgItem(IDC_PASSABLE_CHECK); button->SetCheck(false); button = (CButton *)GetDlgItem(IDC_PASSABLE); button->SetCheck(false); button->EnableWindow(false); button = (CButton *)GetDlgItem(IDC_IMPASSABLE); button->SetCheck(true); button->EnableWindow(false); m_widthPopup.SetupPopSliderButton(this, IDC_SIZE_POPUP, this); m_staticThis = this; m_updating = false; setWidth(m_currentWidth); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } /** Locate the child item in tree item parent with name pLabel. If not found, add it. Either way, return child. */ HTREEITEM TerrainMaterial::findOrAdd(HTREEITEM parent, char *pLabel) { TVINSERTSTRUCT ins; char buffer[_MAX_PATH]; ::memset(&ins, 0, sizeof(ins)); HTREEITEM child = m_terrainTreeView.GetChildItem(parent); while (child != NULL) { ins.item.mask = TVIF_HANDLE|TVIF_TEXT; ins.item.hItem = child; ins.item.pszText = buffer; ins.item.cchTextMax = sizeof(buffer)-2; m_terrainTreeView.GetItem(&ins.item); if (strcmp(buffer, pLabel) == 0) { return(child); } child = m_terrainTreeView.GetNextSiblingItem(child); } // not found, so add it. ::memset(&ins, 0, sizeof(ins)); ins.hParent = parent; ins.hInsertAfter = TVI_LAST; ins.item.mask = TVIF_PARAM|TVIF_TEXT; ins.item.lParam = -1; ins.item.pszText = pLabel; ins.item.cchTextMax = strlen(pLabel); child = m_terrainTreeView.InsertItem(&ins); return(child); } /** Add the terrain path to the tree view. */ void TerrainMaterial::addTerrain(char *pPath, Int terrainNdx, HTREEITEM parent) { TerrainType *terrain = TheTerrainTypes->findTerrain( WorldHeightMapEdit::getTexClassName( terrainNdx ) ); Bool doAdd = FALSE; char buffer[_MAX_PATH]; // // if we have a 'terrain' entry, it means that our terrain index was properly defined // in an INI file, otherwise it was from eval textures. We will sort all of // the eval texture entries in a tree leaf all their own while the others are // sorted according to a field specified in INI // if( terrain ) { if (terrain->isBlendEdge()) { return; // Don't add blend edges to the materials list. } for( TerrainClass i = TERRAIN_NONE; i < TERRAIN_NUM_CLASSES; i = (TerrainClass)(i + 1) ) { if( terrain->getClass() == i ) { parent = findOrAdd( parent, terrainTypeNames[ i ] ); break; // exit for } // end if } // end for i // set the name in the tree view to that of the entry strcpy( buffer, terrain->getName().str() ); doAdd = TRUE; } // end if else if (!WorldHeightMapEdit::getTexClassIsBlendEdge(terrainNdx)) { // all these old entries we will put in a tree for eval textures parent = findOrAdd( parent, "**Eval" ); Int i=0; while (pPath[i] && i<sizeof(buffer)) { if (pPath[i] == 0) { return; } if (pPath[i] == '\\' || pPath[i] == '/') { if (i>0 && (i>1 || buffer[0]!='.') ) { // skip the "." directory. buffer[i] = 0; parent = findOrAdd(parent, buffer); } pPath+= i+1; i = 0; } buffer[i] = pPath[i]; buffer[i+1] = 0; // terminate at next character doAdd = TRUE; i++; } } // end else Int tilesPerRow = TEXTURE_WIDTH/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); Int availableTiles = 4 * tilesPerRow * tilesPerRow; Int percent = (WorldHeightMapEdit::getTexClassNumTiles(terrainNdx)*100 + availableTiles/2) / availableTiles; char label[_MAX_PATH]; sprintf(label, "%d%% %s", percent, buffer); if( doAdd ) { if (percent<3 && defaultMaterialIndex==0) { defaultMaterialIndex = terrainNdx; } TVINSERTSTRUCT ins; ::memset(&ins, 0, sizeof(ins)); ins.hParent = parent; ins.hInsertAfter = TVI_LAST; ins.item.mask = TVIF_PARAM|TVIF_TEXT; ins.item.lParam = terrainNdx; ins.item.pszText = label; ins.item.cchTextMax = strlen(label)+2; m_terrainTreeView.InsertItem(&ins); } } //* Create the tree view of textures from the textures in pMap. */ void TerrainMaterial::updateTextures(WorldHeightMapEdit *pMap) { #if 1 if (m_staticThis) { m_staticThis->m_updating = true; m_staticThis->m_terrainTreeView.DeleteAllItems(); Int i; for (i=0; i<pMap->getNumTexClasses(); i++) { char path[_MAX_PATH]; AsciiString uiName = pMap->getTexClassUiName(i); strncpy(path, uiName.str(), _MAX_PATH-2); m_staticThis->addTerrain(path, i, TVI_ROOT); } m_staticThis->m_updating = false; m_staticThis->m_currentFgTexture = defaultMaterialIndex; updateTextureSelection(); } #endif } /** Swap the foreground and background textures. */ void TerrainMaterial::OnSwapTextures() { Int tmp = m_currentFgTexture; m_currentFgTexture = m_currentBgTexture; m_currentBgTexture = tmp; m_terrainSwatches.Invalidate(); updateTextureSelection(); } /// Handles width edit ui messages. /** Gets the new edit control text, converts it to an int, then updates the slider and brush tool. */ void TerrainMaterial::OnChangeSizeEdit() { if (m_updating) return; CWnd *pEdit = m_staticThis->GetDlgItem(IDC_SIZE_EDIT); char buffer[_MAX_PATH]; if (pEdit) { pEdit->GetWindowText(buffer, sizeof(buffer)); Int width; m_updating = true; if (1==sscanf(buffer, "%d", &width)) { m_currentWidth = width; BigTileTool::setWidth(m_currentWidth); sprintf(buffer, "%.1f FEET.", m_currentWidth*MAP_XY_FACTOR); pEdit = m_staticThis->GetDlgItem(IDC_WIDTH_LABEL); if (pEdit) pEdit->SetWindowText(buffer); } m_updating = false; } } void TerrainMaterial::GetPopSliderInfo(const long sliderID, long *pMin, long *pMax, long *pLineSize, long *pInitial) { switch (sliderID) { case IDC_SIZE_POPUP: *pMin = MIN_TILE_SIZE; *pMax = MAX_TILE_SIZE; *pInitial = m_currentWidth; *pLineSize = 1; break; default: break; } // switch } void TerrainMaterial::PopSliderChanged(const long sliderID, long theVal) { CString str; CWnd *pEdit; switch (sliderID) { case IDC_SIZE_POPUP: m_currentWidth = theVal; str.Format("%d",m_currentWidth); pEdit = m_staticThis->GetDlgItem(IDC_SIZE_EDIT); if (pEdit) pEdit->SetWindowText(str); BigTileTool::setWidth(m_currentWidth); break; default: break; } // switch } void TerrainMaterial::PopSliderFinished(const long sliderID, long theVal) { switch (sliderID) { case IDC_SIZE_POPUP: break; default: break; } // switch } BOOL TerrainMaterial::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { NMTREEVIEW *pHdr = (NMTREEVIEW *)lParam; if (pHdr->hdr.hwndFrom == m_terrainTreeView.m_hWnd) { if (pHdr->hdr.code == TVN_SELCHANGED) { HTREEITEM hItem = m_terrainTreeView.GetSelectedItem(); TVITEM item; ::memset(&item, 0, sizeof(item)); item.mask = TVIF_HANDLE|TVIF_PARAM; item.hItem = hItem; m_terrainTreeView.GetItem(&item); if (item.lParam >= 0) { Int texClass = item.lParam; CWorldBuilderDoc *pDoc = CWorldBuilderDoc::GetActiveDoc(); if (!pDoc) return 0; WorldHeightMapEdit *pMap = pDoc->GetHeightMap(); if (!pMap) return 0; if (m_updating) return 0; if (pMap->canFitTexture(texClass)) { m_currentFgTexture = texClass; updateLabel(); m_terrainSwatches.Invalidate(); } else { if (m_currentFgTexture != texClass) { // Tried to switch to a too large texture. ::AfxMessageBox(IDS_TEXTURE_TOO_LARGE); ::AfxGetMainWnd()->SetFocus(); } m_currentFgTexture = texClass; updateLabel(); m_terrainSwatches.Invalidate(); } } else if (!(item.state & TVIS_EXPANDEDONCE) ) { HTREEITEM child = m_terrainTreeView.GetChildItem(hItem); while (child != NULL) { hItem = child; child = m_terrainTreeView.GetChildItem(hItem); } if (hItem != m_terrainTreeView.GetSelectedItem()) { m_terrainTreeView.SelectItem(hItem); } } } } return CDialog::OnNotify(wParam, lParam, pResult); } void TerrainMaterial::OnImpassable() { m_paintingPassable = false; CButton *button = (CButton *)GetDlgItem(IDC_PASSABLE); button->SetCheck(0); } void TerrainMaterial::OnPassableCheck() { CButton *owner = (CButton*) GetDlgItem(IDC_PASSABLE_CHECK); Bool isChecked = (owner->GetCheck() != 0); CButton *button = (CButton *)GetDlgItem(IDC_PASSABLE); button->EnableWindow(isChecked); button = (CButton *)GetDlgItem(IDC_IMPASSABLE); button->EnableWindow(isChecked); Bool showImpassable = false; if (TheTerrainRenderObject) { showImpassable = TheTerrainRenderObject->getShowImpassableAreas(); } m_terrainSwatches.EnableWindow(!isChecked); m_terrainTreeView.EnableWindow(!isChecked); m_paintingPathingInfo = isChecked; if (showImpassable != isChecked) { TheTerrainRenderObject->setShowImpassableAreas(isChecked); // Force the entire terrain mesh to be rerendered. IRegion2D range = {0,0,0,0}; CWorldBuilderDoc *pDoc = CWorldBuilderDoc::GetActiveDoc(); if (pDoc) { WbView3d *p3View = pDoc->GetActive3DView(); if (p3View) { p3View->updateHeightMapInView(pDoc->GetHeightMap(), false, range); } } } } void TerrainMaterial::OnPassable() { m_paintingPassable = true; CButton *button = (CButton *)GetDlgItem(IDC_IMPASSABLE); button->SetCheck(0); }
412
0.996527
1
0.996527
game-dev
MEDIA
0.744061
game-dev
0.993227
1
0.993227
markniu/PandaPi
1,554
Marlin2.x/standalone/Marlin-2.0.9.3/Marlin/src/feature/cancel_object.h
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include <stdint.h> class CancelObject { public: static bool skipping; static int8_t object_count, active_object; static uint32_t canceled; static void set_active_object(const int8_t obj); static void cancel_object(const int8_t obj); static void uncancel_object(const int8_t obj); static void report(); static inline bool is_canceled(const int8_t obj) { return TEST(canceled, obj); } static inline void clear_active_object() { set_active_object(-1); } static inline void cancel_active_object() { cancel_object(active_object); } static inline void reset() { canceled = 0x0000; object_count = 0; clear_active_object(); } }; extern CancelObject cancelable;
412
0.805565
1
0.805565
game-dev
MEDIA
0.685254
game-dev
0.608714
1
0.608714
christophhart/HISE
27,233
hi_scripting/scripting/scriptnode/dynamic_elements/DynamicSmootherNode.h
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * =========================================================================== */ #pragma once namespace scriptnode { using namespace juce; using namespace hise; namespace control { struct logic_op_editor : public ScriptnodeExtraComponent<pimpl::combined_parameter_base<multilogic::logic_op>> { using LogicBase = pimpl::combined_parameter_base<multilogic::logic_op>; logic_op_editor(LogicBase* b, PooledUIUpdater* u); void paint(Graphics& g) override; void timerCallback() override; void resized() override; static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto typed = static_cast<mothernode*>(obj); return new logic_op_editor(dynamic_cast<LogicBase*>(typed), updater); } ModulationSourceBaseComponent dragger; control::multilogic::logic_op lastData; }; struct compare_editor : public ScriptnodeExtraComponent<pimpl::combined_parameter_base<multilogic::compare>> { using CompareBase = pimpl::combined_parameter_base<multilogic::compare>; compare_editor(CompareBase* b, PooledUIUpdater* u); void paint (Graphics& g) override; void timerCallback () override; void resized () override; static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto typed = static_cast<mothernode*>(obj); return new compare_editor(dynamic_cast<CompareBase*>(typed), updater); } ModulationSourceBaseComponent dragger; control::multilogic::compare lastData; }; struct blend_editor : public ScriptnodeExtraComponent<pimpl::combined_parameter_base<multilogic::blend>> { using LogicBase = pimpl::combined_parameter_base<multilogic::blend>; blend_editor(LogicBase* b, PooledUIUpdater* u): ScriptnodeExtraComponent<LogicBase>(b, u), dragger(u) { addAndMakeVisible(dragger); setSize(256, 50); }; void paint(Graphics& g) override { auto alpha = (float)lastData.alpha * 2.0f - 1.0f; auto b = getLocalBounds().removeFromRight((getWidth() * 2) / 3).toFloat(); auto area = b.reduced(JUCE_LIVE_CONSTANT(40), 15).toFloat(); ScriptnodeComboBoxLookAndFeel::drawScriptnodeDarkBackground(g, area, true); area = area.reduced(4); auto w = (area.getWidth() - area.getHeight()) * 0.5f; auto tb = area.translated(0, 20); area = area.withSizeKeepingCentre(area.getHeight(), area.getHeight()); area = area.translated(alpha * w, 0); g.setColour(getHeaderColour()); g.fillEllipse(area); g.setFont(GLOBAL_BOLD_FONT()); g.drawText(String(lastData.getValue(), 2), tb, Justification::centred); } void timerCallback() override { auto thisData = getObject()->getUIData(); if (!(thisData == lastData)) { lastData = thisData; repaint(); } } void resized() override { auto b = getLocalBounds(); dragger.setBounds(b.removeFromLeft(getWidth()/3).withSizeKeepingCentre(32, 32)); } static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto typed = static_cast<mothernode*>(obj); return new blend_editor(dynamic_cast<LogicBase*>(typed), updater); } ModulationSourceBaseComponent dragger; control::multilogic::blend lastData; }; struct intensity_editor : public ScriptnodeExtraComponent<pimpl::combined_parameter_base<multilogic::intensity>> { using IntensityBase = pimpl::combined_parameter_base<multilogic::intensity>; intensity_editor(IntensityBase* b, PooledUIUpdater* u); void paint(Graphics& g) override; void rebuildPaths(); void timerCallback() override; void resized() override; static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto typed = static_cast<mothernode*>(obj); return new intensity_editor(dynamic_cast<IntensityBase*>(typed), updater); } Rectangle<float> pathArea; Path fullPath, valuePath; multilogic::intensity lastData; ModulationSourceBaseComponent dragger; }; struct minmax_editor : public ScriptnodeExtraComponent<pimpl::combined_parameter_base<multilogic::minmax>> { using MinMaxBase = pimpl::combined_parameter_base<multilogic::minmax>; minmax_editor(MinMaxBase* b, PooledUIUpdater* u); void paint(Graphics& g) override; void timerCallback() override; static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto typed = static_cast<mothernode*>(obj); return new minmax_editor(dynamic_cast<MinMaxBase*>(typed), updater); } void setRange(InvertableParameterRange newRange); void rebuildPaths(); void resized() override; multilogic::minmax lastData; Path fullPath, valuePath; ComboBox rangePresets; ModulationSourceBaseComponent dragger; Rectangle<float> pathArea; ScriptnodeComboBoxLookAndFeel slaf; RangePresets presets; }; struct midi_cc_editor : public ScriptnodeExtraComponent<midi_cc<parameter::dynamic_base_holder>> { using ObjectType = midi_cc<parameter::dynamic_base_holder>; midi_cc_editor(ObjectType* obj, PooledUIUpdater* u) : ScriptnodeExtraComponent<ObjectType>(obj, u), dragger(u) { addAndMakeVisible(dragger); setSize(256, 32); }; void checkValidContext() { if (contextChecked) return; if (auto nc = findParentComponentOfClass<NodeComponent>()) { NodeBase* n = nc->node.get(); try { ScriptnodeExceptionHandler::validateMidiProcessingContext(n); n->getRootNetwork()->getExceptionHandler().removeError(n); } catch (Error& e) { n->getRootNetwork()->getExceptionHandler().addError(n, e); } contextChecked = true; } } void paint(Graphics& g) override { auto b = getLocalBounds().toFloat(); b.removeFromBottom((float)dragger.getHeight()); g.setColour(Colours::white.withAlpha(alpha)); g.drawRoundedRectangle(b, b.getHeight() / 2.0f, 1.0f); b = b.reduced(2.0f); b.setWidth(jmax<float>(b.getHeight(), lastValue.getModValue() * b.getWidth())); g.fillRoundedRectangle(b, b.getHeight() / 2.0f); } void resized() override { dragger.setBounds(getLocalBounds().removeFromBottom(24)); } void timerCallback() override { checkValidContext(); if (ObjectType* o = getObject()) { auto lv = o->getParameter().getDisplayValue(); if (lastValue.setModValueIfChanged(lv)) alpha = 1.0f; else alpha = jmax(0.5f, alpha * 0.9f); repaint(); } } static Component* createExtraComponent(void* o, PooledUIUpdater* u) { auto mn = static_cast<mothernode*>(o); auto typed = dynamic_cast<ObjectType*>(mn); return new midi_cc_editor(typed, u); } float alpha = 0.5f; ModValue lastValue; ModulationSourceBaseComponent dragger; bool contextChecked = false; }; struct bipolar_editor : public ScriptnodeExtraComponent<pimpl::combined_parameter_base<multilogic::bipolar>> { using BipolarBase = pimpl::combined_parameter_base<multilogic::bipolar>; bipolar_editor(BipolarBase* b, PooledUIUpdater* u) : ScriptnodeExtraComponent<BipolarBase>(b, u), dragger(u) { setSize(256, 256); addAndMakeVisible(dragger); }; void timerCallback() override { auto obj = getObject(); if (obj == nullptr) return; auto thisData = getObject()->getUIData(); if (!(thisData == lastData)) { lastData = thisData; rebuild(); } } void rebuild() { outlinePath.clear(); valuePath.clear(); outlinePath.startNewSubPath(0.0f, 0.0f); outlinePath.startNewSubPath(1.0f, 1.0f); valuePath.startNewSubPath(0.0f, 0.0f); valuePath.startNewSubPath(1.0f, 1.0f); auto copy = lastData; auto numPixels = pathArea.getWidth(); bool outlineEmpty = true; bool valueEmpty = true; bool valueBiggerThanHalf = copy.value > 0.5; auto v = lastData.value; for (float i = 0.0; i < numPixels; i++) { float x = i / numPixels; copy.value = x; float y = 1.0f - copy.getValue(); if (outlineEmpty) { outlinePath.startNewSubPath(x, y); outlineEmpty = false; } else outlinePath.lineTo(x, y); bool drawBiggerValue = valueBiggerThanHalf && x > 0.5f && x < v; bool drawSmallerValue = !valueBiggerThanHalf && x < 0.5f && x > v; if (drawBiggerValue || drawSmallerValue) { if (valueEmpty) { valuePath.startNewSubPath(x, y); valueEmpty = false; } else valuePath.lineTo(x, y); } } PathFactory::scalePath(outlinePath, pathArea.reduced(UIValues::NodeMargin)); PathFactory::scalePath(valuePath, pathArea.reduced(UIValues::NodeMargin)); repaint(); } void paint(Graphics& g) override; void resized() override { auto b = getLocalBounds(); dragger.setBounds(b.removeFromBottom(28)); b.removeFromBottom(UIValues::NodeMargin); auto bSize = jmin(b.getWidth(), b.getHeight()); pathArea = b.withSizeKeepingCentre(bSize, bSize).toFloat(); } static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto typed = static_cast<mothernode*>(obj); return new bipolar_editor(dynamic_cast<BipolarBase*>(typed), updater); } Path outlinePath; Path valuePath; multilogic::bipolar lastData; Rectangle<float> pathArea; ModulationSourceBaseComponent dragger; }; template <typename pma_type> struct pma_editor : public ModulationSourceBaseComponent { using PmaBase = control::pimpl::combined_parameter_base<pma_type>; using ParameterBase = control::pimpl::parameter_node_base<parameter::dynamic_base_holder>; pma_editor(mothernode* b, PooledUIUpdater* u) : ModulationSourceBaseComponent(u), obj(dynamic_cast<PmaBase*>(b)) { setSize(100 * 3, 120); }; void resized() override { setRepaintsOnMouseActivity(true); dragPath.loadPathFromData(ColumnIcons::targetIcon, SIZE_OF_PATH(ColumnIcons::targetIcon)); auto b = getLocalBounds().toFloat(); b = b.withSizeKeepingCentre(28.0f, 28.0f); b = b.translated(0.0f, JUCE_LIVE_CONSTANT_OFF(5.0f)); getProperties().set("circleOffsetY", -0.5f * (float)getHeight() + 2.0f); PathFactory::scalePath(dragPath, b); } void timerCallback() override { repaint(); } static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto typed = static_cast<mothernode*>(obj); return new pma_editor(typed, updater); } void paint(Graphics& g) override { g.setFont(GLOBAL_BOLD_FONT()); auto r = obj->currentRange; if (auto n = findParentComponentOfClass<NodeComponent>()->node) { r = RangeHelpers::getDoubleRange(n->getParameterFromName("Value")->data).rng; } String start, mid, end; int numDigits = jmax<int>(1, -1 * roundToInt(log10(r.interval))); start = String(r.start, numDigits); mid = String(r.convertFrom0to1(0.5), numDigits); end = String(r.end, numDigits); auto b = getLocalBounds().toFloat(); float w = JUCE_LIVE_CONSTANT_OFF(85.0f); auto midCircle = b.withSizeKeepingCentre(w, w).translated(0.0f, 5.0f); float r1 = JUCE_LIVE_CONSTANT_OFF(3.0f); float r2 = JUCE_LIVE_CONSTANT_OFF(5.0f); float startArc = JUCE_LIVE_CONSTANT_OFF(-2.5f); float endArc = JUCE_LIVE_CONSTANT_OFF(2.5f); Colour trackColour = JUCE_LIVE_CONSTANT_OFF(Colour(0xff4f4f4f)); auto createArc = [startArc, endArc](Rectangle<float> b, float startNormalised, float endNormalised) { Path p; auto s = startArc + jmin(startNormalised, endNormalised) * (endArc - startArc); auto e = startArc + jmax(startNormalised, endNormalised) * (endArc - startArc); s = jlimit(startArc, endArc, s); e = jlimit(startArc, endArc, e); p.addArc(b.getX(), b.getY(), b.getWidth(), b.getHeight(), s, e, true); return p; }; auto oc = midCircle; auto mc = midCircle.reduced(5.0f); auto ic = midCircle.reduced(10.0f); auto outerTrack = createArc(oc, 0.0f, 1.0f); auto midTrack = createArc(mc, 0.0f, 1.0f); auto innerTrack = createArc(ic, 0.0f, 1.0f); if (isMouseOver()) trackColour = trackColour.withMultipliedBrightness(1.1f); if (isMouseButtonDown()) trackColour = trackColour.withMultipliedBrightness(1.1f); g.setColour(trackColour); g.strokePath(outerTrack, PathStrokeType(r1)); g.strokePath(midTrack, PathStrokeType(r2)); g.strokePath(innerTrack, PathStrokeType(r1)); g.fillPath(dragPath); auto data = obj->getUIData(); auto nrm = [r](double v) { return r.convertTo0to1(v); }; auto mulValue = nrm(data.value * data.mulValue); auto totalValue = nrm(data.getValue()); auto outerRing = createArc(oc, mulValue, totalValue); auto midRing = createArc(mc, 0.0f, totalValue); auto innerRing = createArc(ic, 0.0f, mulValue); auto valueRing = createArc(ic, 0.0f, nrm(data.value)); auto c1 = MultiOutputDragSource::getFadeColour(0, 2).withAlpha(0.8f); auto c2 = MultiOutputDragSource::getFadeColour(1, 2).withAlpha(0.8f); auto ab = getLocalBounds().removeFromBottom(5).toFloat(); ab.removeFromLeft(ab.getWidth() / 3.0f); auto ar2 = ab.removeFromLeft(ab.getWidth() / 2.0f).withSizeKeepingCentre(5.0f, 5.0f); auto ar1 = ab.withSizeKeepingCentre(5.0f, 5.0f); g.setColour(Colour(c1)); g.strokePath(outerRing, PathStrokeType(r1 - 1.0f)); g.setColour(c1.withMultipliedAlpha(data.addValue == 0.0 ? 0.2f : 1.0f)); g.fillEllipse(ar1); g.setColour(JUCE_LIVE_CONSTANT_OFF(Colour(0xffd7d7d7))); g.strokePath(midRing, PathStrokeType(r2 - 1.0f)); g.setColour(c2.withMultipliedAlpha(JUCE_LIVE_CONSTANT_OFF(0.4f))); g.strokePath(valueRing, PathStrokeType(r1 - 1.0f)); g.setColour(c2.withMultipliedAlpha(data.mulValue == 1.0 ? 0.2f : 1.0f)); g.fillEllipse(ar2); g.setColour(c2); g.strokePath(innerRing, PathStrokeType(r1)); b.removeFromTop(18.0f); g.setColour(Colours::white.withAlpha(0.3f)); Rectangle<float> t((float)getWidth() / 2.0f - 35.0f, 0.0f, 70.0f, 15.0f); g.drawText(start, t.translated(-70.0f, 80.0f), Justification::centred); g.drawText(mid, t, Justification::centred); g.drawText(end, t.translated(70.0f, 80.0f), Justification::centred); } WeakReference<PmaBase> obj; bool colourOk = false; Path dragPath; }; struct sliderbank_pack : public data::dynamic::sliderpack { sliderbank_pack(data::base& t, int index=0) : data::dynamic::sliderpack(t, index) {}; void initialise(NodeBase* n) override { sliderpack::initialise(n); outputListener.setCallback(n->getValueTree().getChildWithName(PropertyIds::SwitchTargets), valuetree::AsyncMode::Synchronously, BIND_MEMBER_FUNCTION_2(sliderbank_pack::updateNumSliders)); updateNumSliders({}, false); } void updateNumSliders(ValueTree v, bool wasAdded) { if (auto sp = dynamic_cast<SliderPackData*>(currentlyUsedData)) sp->setNumSliders((int)outputListener.getParentTree().getNumChildren()); } valuetree::ChildListener outputListener; }; using dynamic_sliderbank = wrap::data<sliderbank<parameter::dynamic_list>, sliderbank_pack>; struct sliderbank_editor : public ScriptnodeExtraComponent<dynamic_sliderbank> { using NodeType = dynamic_sliderbank; sliderbank_editor(ObjectType* b, PooledUIUpdater* updater) : ScriptnodeExtraComponent<ObjectType>(b, updater), p(updater, &b->i), r(&b->getWrappedObject().p, updater) { addAndMakeVisible(p); addAndMakeVisible(r); setSize(256, 200); stop(); }; void resized() override { auto b = getLocalBounds(); p.setBounds(b.removeFromTop(130)); r.setBounds(b); } void timerCallback() override { jassertfalse; } static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto v = static_cast<NodeType*>(obj); return new sliderbank_editor(v, updater); } scriptnode::data::ui::sliderpack_editor p; parameter::ui::dynamic_list_editor r; }; } namespace conversion_logic { struct dynamic { using NodeType = control::converter<parameter::dynamic_base_holder, dynamic>; enum class Mode { Ms2Freq, Freq2Ms, Freq2Samples, Ms2Samples, Samples2Ms, Ms2BPM, Pitch2St, St2Pitch, Pitch2Cent, Cent2Pitch, Midi2Freq, Freq2Norm, Gain2dB, dB2Gain, numModes }; dynamic() : mode(PropertyIds::Mode, getConverterNames()[0]) { } static StringArray getConverterNames() { return { "Ms2Freq", "Freq2Ms", "Freq2Samples", "Ms2Samples", "Samples2Ms", "Ms2BPM", "Pitch2St", "St2Pitch", "Pitch2Cent", "Cent2Pitch", "Midi2Freq", "Freq2Norm", "Gain2dB", "db2Gain" }; } void initialise(NodeBase* n) { mode.initialise(n); mode.setAdditionalCallback(BIND_MEMBER_FUNCTION_2(dynamic::setMode), true); } void prepare(PrepareSpecs ps) { m.prepare(ps); s.prepare(ps); fs.prepare(ps); } double getValue(double input) { switch(currentMode) { case Mode::Ms2Freq: return ms2freq().getValue(input); case Mode::Freq2Ms: return freq2ms().getValue(input); case Mode::Ms2Samples: return m.getValue(input); case Mode::Samples2Ms: return s.getValue(input); case Mode::Freq2Samples: return fs.getValue(input); case Mode::Ms2BPM: return ms2bpm().getValue(input); case Mode::Pitch2St: return pitch2st().getValue(input); case Mode::St2Pitch: return st2pitch().getValue(input); case Mode::Pitch2Cent: return pitch2cent().getValue(input); case Mode::Cent2Pitch: return cent2pitch().getValue(input); case Mode::Midi2Freq: return midi2freq().getValue(input); case Mode::Freq2Norm: return freq2norm().getValue(input); case Mode::Gain2dB: return gain2db().getValue(input); case Mode::dB2Gain: return db2gain().getValue(input); default: return input; } } void setMode(Identifier id, var newValue) { currentMode = (Mode)getConverterNames().indexOf(newValue.toString()); } struct editor : public ScriptnodeExtraComponent<dynamic>, public ComboBox::Listener { editor(dynamic* p, PooledUIUpdater* updater): ScriptnodeExtraComponent<dynamic>(p, updater), plotter(updater), modeSelector(getConverterNames()[0]) { addAndMakeVisible(modeSelector); addAndMakeVisible(plotter); setSize(128, 24 + 28 + 30); modeSelector.addListener(this); } void setRange(NormalisableRange<double> nr, double center = -90.0) { auto n = findParentComponentOfClass<NodeComponent>()->node; auto p = n->getParameterFromIndex(0); if(center != -90.0) nr.setSkewForCentre(center); InvertableParameterRange r; r.rng = nr; RangeHelpers::storeDoubleRange(p->data, r, n->getUndoManager()); } void paint(Graphics& g) override { g.setColour(Colours::white.withAlpha(0.5f)); g.setFont(GLOBAL_BOLD_FONT()); auto n = findParentComponentOfClass<NodeComponent>()->node; auto v = n->getParameterFromIndex(0)->getValue(); auto output = getObject()->getValue(v); auto m = (Mode)getConverterNames().indexOf(modeSelector.getText()); String inputDomain, outputDomain; switch(m) { case Mode::Ms2Freq: inputDomain = "ms"; outputDomain = "Hz"; break; case Mode::Freq2Ms: inputDomain = "Hz"; outputDomain = "ms"; break; case Mode::Freq2Samples: inputDomain = "Hz"; outputDomain = "smp"; break; case Mode::Ms2Samples: inputDomain = "ms"; outputDomain = " smp"; break; case Mode::Samples2Ms: inputDomain = "smp"; outputDomain = "ms"; break; case Mode::Ms2BPM: inputDomain = "ms"; outputDomain = "BPM"; break; case Mode::Pitch2St: inputDomain = ""; outputDomain = "st"; break; case Mode::St2Pitch: inputDomain = "st"; outputDomain = ""; break; case Mode::Cent2Pitch: inputDomain = "ct"; outputDomain = ""; break; case Mode::Pitch2Cent: inputDomain = ""; outputDomain = "ct"; break; case Mode::Midi2Freq: inputDomain = ""; outputDomain = "Hz"; break; case Mode::Freq2Norm: inputDomain = "Hz"; outputDomain = ""; break; case Mode::Gain2dB: inputDomain = ""; outputDomain = "dB"; break; case Mode::dB2Gain: inputDomain = "dB"; outputDomain = ""; break; default: break; } String s; s << snex::Types::Helpers::getCppValueString(v); s << inputDomain << " -> "; s << snex::Types::Helpers::getCppValueString(output) << outputDomain; g.drawText(s, textArea, Justification::centred); } void comboBoxChanged(ComboBox* b) { auto m = (Mode)getConverterNames().indexOf(b->getText()); switch(m) { case Mode::Ms2Freq: setRange({0.0, 1000.0, 1.0}); break; case Mode::Freq2Ms: setRange({20.0, 20000.0, 0.1}, 1000.0); break; case Mode::Freq2Samples: setRange({20.0, 20000.0, 0.1}, 1000.0); break; case Mode::Ms2Samples: setRange({0.0, 1000.0, 1.0}); break; case Mode::Samples2Ms: setRange({0.0, 44100.0, 1.0}); break; case Mode::Pitch2St: setRange({0.5, 2.0}, 1.0); break; case Mode::Ms2BPM: setRange({0.0, 2000.0, 1.0}); break; case Mode::St2Pitch: setRange({-12.0, 12.0, 1.0}); break; case Mode::Pitch2Cent: setRange({ 0.5, 2.0 }, 1.0); break; case Mode::Cent2Pitch: setRange({ -100.0, 100.0, 0.0 }); break; case Mode::Midi2Freq: setRange({0, 127.0, 1.0}); break; case Mode::Freq2Norm: setRange({0.0, 20000.0}); break; case Mode::Gain2dB: setRange({0.0, 1.0, 0.0}); break; case Mode::dB2Gain: setRange({-100.0, 0.0, 0.1}, -12.0); break; default: break; } } void timerCallback() override { modeSelector.initModes(getConverterNames(), plotter.getSourceNodeFromParent()); repaint(); }; static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto v = static_cast<NodeType*>(obj); return new editor(&v->obj, updater); } void resized() override { auto b = getLocalBounds(); modeSelector.setBounds(b.removeFromTop(24)); plotter.setBounds(b.removeFromBottom(28)); textArea = b.toFloat(); } Rectangle<float> textArea; ModulationSourceBaseComponent plotter; ComboBoxWithModeProperty modeSelector; Colour currentColour; }; NodePropertyT<String> mode; Mode currentMode = Mode::Ms2Freq; conversion_logic::ms2samples m; conversion_logic::samples2ms s; conversion_logic::freq2samples fs; JUCE_DECLARE_WEAK_REFERENCEABLE(dynamic); }; } namespace smoothers { struct dynamic_base : public base { using NodeType = control::smoothed_parameter_base; enum class SmoothingType { NoSmoothing, LinearRamp, LowPass, numSmoothingTypes }; static StringArray getSmoothNames() { return { "NoSmoothing", "Linear Ramp", "Low Pass" }; } dynamic_base() : mode(PropertyIds::Mode, "Linear Ramp") {}; void initialise(NodeBase* n) override { mode.initialise(n); mode.setAdditionalCallback(BIND_MEMBER_FUNCTION_2(dynamic_base::setMode), true); } virtual void setMode(Identifier id, var newValue) {}; virtual ~dynamic_base() {}; struct editor : public ScriptnodeExtraComponent<dynamic_base> { editor(dynamic_base* p, PooledUIUpdater* updater); void paint(Graphics& g) override; void timerCallback(); static Component* createExtraComponent(void* obj, PooledUIUpdater* updater) { auto v = static_cast<NodeType*>(obj); auto o = v->getSmootherObject(); return new editor(dynamic_cast<dynamic_base*>(o), updater); } void resized() override { auto b = getLocalBounds(); modeSelector.setBounds(b.removeFromTop(24)); b.removeFromTop(UIValues::NodeMargin); plotter.setBounds(b); } ModulationSourceBaseComponent plotter; ComboBoxWithModeProperty modeSelector; Colour currentColour; }; float get() const final override { return (float)lastValue.getModValue(); } protected: double value = 0.0; NodePropertyT<String> mode; ModValue lastValue; smoothers::base* b = nullptr; JUCE_DECLARE_WEAK_REFERENCEABLE(dynamic_base); }; template <int NV> struct dynamic : public dynamic_base { static constexpr int NumVoices = NV; dynamic() { b = &r; } void reset() final override { b->reset(); }; void set(double nv) final override { value = nv; b->set(nv); } float advance() final override { if (enabled) lastValue.setModValueIfChanged(b->advance()); return get(); } void prepare(PrepareSpecs ps) final override { l.prepare(ps); r.prepare(ps); n.prepare(ps); } void refreshSmoothingTime() final override { b->setSmoothingTime(smoothingTimeMs); }; float v = 0.0f; void setMode(Identifier id, var newValue) override { auto m = (SmoothingType)getSmoothNames().indexOf(newValue.toString()); switch (m) { case SmoothingType::NoSmoothing: b = &n; break; case SmoothingType::LinearRamp: b = &r; break; case SmoothingType::LowPass: b = &l; break; default: b = &r; break; } refreshSmoothingTime(); b->set(value); b->reset(); } smoothers::no<NumVoices> n; smoothers::linear_ramp<NumVoices> r; smoothers::low_pass<NumVoices> l; }; } }
412
0.971702
1
0.971702
game-dev
MEDIA
0.483728
game-dev,graphics-rendering
0.969968
1
0.969968
julianperrott/SimCityBuildItBot
3,150
SimCityBuildItBot/Bot/ResourceReader.cs
namespace SimCityBuildItBot.Bot { using Common.Logging; using SimplePaletteQuantizer; using System.Collections.Generic; using System.Drawing; using System.Linq; public class CommerceResourceReader { private CaptureScreen captureScreen; private ILog log; private readonly Touch touch; private TwoColourPallette palleteReader = new TwoColourPallette(); public CommerceResourceReader(ILog log, Touch touch) { this.log = log; this.touch = touch; captureScreen = new CaptureScreen(log); } public List<Bot.FactoryResource> GetRequiredResources(Bot.Location clickAt, List<Bot.FactoryResource> resources) { List<Location> resourceLocations = GetResourceLocations(resources); var images = GetResourceImages(clickAt, resourceLocations); var requiredResources = new List<Bot.FactoryResource>(); for (int i = 0; i < resourceLocations.Count; i++) { if (palleteReader.GetClosest2Colours(images[i]).Contains("Red")) { requiredResources.Add(resources[i]); } } return requiredResources; } private static List<Location> GetResourceLocations(List<FactoryResource> resources) { List<Bot.Location> resourceLocations = null; switch (resources.Count()) { case 1: resourceLocations = new List<Bot.Location>() { Bot.Location.Resources1_Position1, }; ; break; case 2: resourceLocations = new List<Bot.Location>() { Bot.Location.Resources2_Position1, Bot.Location.Resources2_Position2, }; break; default: resourceLocations = new List<Bot.Location>() { Bot.Location.Resources3_Position1, Bot.Location.Resources3_Position2, Bot.Location.Resources3_Position3 }; break; } return resourceLocations; } public List<Bitmap> GetResourceImages(Bot.Location clickAt, List<Bot.Location> resourceLocations) { var resourceLocationOffset = Constants.GetOffset(clickAt); touch.TouchDown(); touch.MoveTo(Constants.GetPoint(clickAt)); BotApplication.Wait(300); var images = resourceLocations.Select(resourceLocation => { var capturePoint = Constants.GetPoint(resourceLocation); return captureScreen.SnapShot(capturePoint.X + resourceLocationOffset.X, capturePoint.Y + resourceLocationOffset.Y, new Size(70, 35)); }).ToList(); touch.TouchUp(); touch.EndTouchData(); return images; } } }
412
0.820332
1
0.820332
game-dev
MEDIA
0.501948
game-dev
0.805078
1
0.805078
justinleewells/pogo-optimizer
11,463
src/app/components/spreadsheet/spreadsheet.jade
#spreadsheet-view .ui.container .buttons button.ui.icon.button.black(ng-click="openSettingsModal()") i.icon.settings .ui.search input(class="prompt" placeholder="Search" ng-model="search") select.ui.fluid.dropdown(name='skills', multiple='' ng-model="sort" ng-change="sortChange()") option(value='') Sort option(value='+metadata.id') Number (Asc) option(value='-metadata.id') Number (Dsc) option(value='+data.pokemon_id') Name (Asc) option(value='-data.pokemon_id') Name (Dsc) option(value='+metadata.piv') IV% (Asc) option(value='-metadata.piv') IV% (Dsc) option(value='+metadata.pcp') CP% (Asc) option(value='-metadata.pcp') CP% (Dsc) option(value='+metadata.level') Level (Asc) option(value='-metadata.level') Level (Dsc) option(value='+data.cp') CP (Asc) option(value='-data.cp') CP (Dsc) option(value='+data.stamina_max') HP (Asc) option(value='-data.stamina_max') HP (Dsc) option(value='+metadata.atk') ATK (Asc) option(value='-metadata.atk') ATK (Dsc) option(value='+metadata.def') DEF (Asc) option(value='-metadata.def') DEF (Dsc) option(value='+metadata.dps') DPS (Asc) option(value='-metadata.dps') DPS (Dsc) option(value='+metadata.max_dps') Max DPS (Asc) option(value='-metadata.max_dps') Max DPS (Dsc) option(value='+data.creation_time_ms') Recent (Asc) option(value='-data.creation_time_ms') Recent (Dsc) table#spreadsheet.ui.celled.table.inverted(class="{{moveColorClass() + ' ' + ivColorClass()}}") thead tr th Pokemon th.move(ng-show="isVisible('move_1')") span Fast span.dps(ng-show="isVisible('move_dps')") [DPS] th.stat(ng-show="isVisible('move_1') && isVisible('move_energy')") Energy th.move(ng-show="isVisible('move_2')") span Special span.dps(ng-show="isVisible('move_dps')") [DPS] th.stat(ng-show="isVisible('move_2') && isVisible('move_energy')") Energy th.stat(ng-show="isVisible('level')") Level th.stat(ng-show="isVisible('cp')") CP th.stat(ng-show="isVisible('hp')") HP th.stat(ng-show="isVisible('atk')") ATK th.stat(ng-show="isVisible('def')") DEF th.stat.atk(ng-show="isVisible('iva')") IVA th.stat.def(ng-show="isVisible('ivd')") IVD th.stat.sta(ng-show="isVisible('ivs')") IVS th.stat(ng-show="isVisible('dps')") DPS th.stat(ng-show="isVisible('max_dps')") MDPS th.stat(ng-show="isVisible('piv')") IV% th.stat(ng-show="isVisible('pcp')") CP% tbody tr(ng-repeat="pokemon in $root.inventory.pokemon | orderBy: getSortArray() | filter: getSearchFilter() track by pokemon.data.id") td.selectable(ng-class="favoriteClass(pokemon)" ng-click="openPokemonModal(pokemon)") h4.ui.image.header img.ui.mini.rounded.image(ng-src="{{'assets/img/icons/' + pokemon.metadata.id + '.png'}}") .content.name {{pokemon.data.nickname || pokemon.data.pokemon_id.toLowerCase() || ''}} td.move(class="{{pokemon.metadata.move_1.Type}}" ng-show="isVisible('move_1')") span {{formatMoveName(pokemon.data.move_1)}} span.dps(ng-show="isVisible('move_dps')") [{{getMoveDPS(pokemon.metadata.move_1)}}] td.stat(ng-bind="pokemon.metadata.move_1.EnergyDelta" ng-show="isVisible('move_1') && isVisible('move_energy')") td.move(class="{{pokemon.metadata.move_2.Type}}" ng-show="isVisible('move_2')") span {{formatMoveName(pokemon.data.move_2)}} span.dps(ng-show="isVisible('move_dps')") [{{getMoveDPS(pokemon.metadata.move_2)}}] td.stat(ng-bind="pokemon.metadata.move_2.EnergyDelta" ng-show="isVisible('move_2') && isVisible('move_energy')") td.stat(ng-bind="pokemon.metadata.level" ng-show="isVisible('level')") td.stat(ng-bind="pokemon.data.cp" ng-show="isVisible('cp')") td.stat(ng-bind="pokemon.data.stamina_max" ng-show="isVisible('hp')") td.stat(ng-show="isVisible('atk')") {{formatDecimal(pokemon.metadata.atk)}} td.stat(ng-show="isVisible('def')") {{formatDecimal(pokemon.metadata.def)}} td.stat.atk(ng-bind="pokemon.data.individual_attack" ng-show="isVisible('iva')") td.stat.def(ng-bind="pokemon.data.individual_defense" ng-show="isVisible('ivd')") td.stat.sta(ng-bind="pokemon.data.individual_stamina" ng-show="isVisible('ivs')") td.stat(ng-show="isVisible('dps')") {{formatDecimal(pokemon.metadata.dps)}} td.stat(ng-show="isVisible('max_dps')") {{formatDecimal(pokemon.metadata.max_dps)}} td.stat(ng-show="isVisible('piv')") img(src="assets/img/icons/star.png" ng-show="pokemon.metadata.piv > .99") span(ng-bind="formatPercentage(pokemon.metadata.piv)" ng-show="pokemon.metadata.piv < .99") td.stat(ng-show="isVisible('pcp')") img(src="assets/img/icons/star.png" ng-show="pokemon.metadata.piv > .99") span(ng-bind="formatPercentage(pokemon.metadata.pcp)" ng-show="pokemon.metadata.piv < .99") #pokemon-modal.ui.basic.modal .content img(ng-src="assets/img/sprites/{{selected.metadata.id}}.png") .info label Height: span {{formatDecimal(selectedPokemon.data.height_m)}} .info label Weight: span {{formatDecimal(selectedPokemon.data.weight_kg)}} #spreadsheet-settings-modal.ui.modal.settings .header Settings .content .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.color.move" ng-change="updateSettings()") label label Enable Move Colors .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.color.iv" ng-change="updateSettings()") label label Enable IV Colors .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.move_1" ng-change="updateSettings()") label label Display Move 1 .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.move_2" ng-change="updateSettings()") label label Display Move 2 .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.move_energy" ng-change="updateSettings()") label label Display Move Energy .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.move_dps" ng-change="updateSettings()") label label Display Move DPS .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.level" ng-change="updateSettings()") label label Display Level .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.cp" ng-change="updateSettings()") label label Display CP .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.hp" ng-change="updateSettings()") label label Display HP .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.atk" ng-change="updateSettings()") label label Display Attack .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.def" ng-change="updateSettings()") label label Display Defense .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.iva" ng-change="updateSettings()") label label Display Attack IV .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.ivd" ng-change="updateSettings()") label label Display Defense IV .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.ivs" ng-change="updateSettings()") label label Display Stamina IV .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.dps" ng-change="updateSettings()") label label Display DPS .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.max_dps" ng-change="updateSettings()") label label Display Max DPS .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.piv" ng-change="updateSettings()") label label Display IV% .checkbox-container .ui.toggle.checkbox input(type="checkbox" name="public" ng-model="$root.player.settings.spreadsheet.display.pcp" ng-change="updateSettings()") label label Display CP% button.ui.button(ng-click="closeSettingsModal()") Close
412
0.909539
1
0.909539
game-dev
MEDIA
0.640764
game-dev
0.927232
1
0.927232
philipbuuck/Quake-VS2015
37,343
WinQuake/sv_phys.c
/* Copyright (C) 1996-1997 Id Software, 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. */ // sv_phys.c #include "quakedef.h" /* pushmove objects do not obey gravity, and do not interact with each other or trigger fields, but block normal movement and push normal objects when they move. onground is set for toss objects when they come to a complete rest. it is set for steping or walking objects doors, plats, etc are SOLID_BSP, and MOVETYPE_PUSH bonus items are SOLID_TRIGGER touch, and MOVETYPE_TOSS corpses are SOLID_NOT and MOVETYPE_TOSS crates are SOLID_BBOX and MOVETYPE_TOSS walking monsters are SOLID_SLIDEBOX and MOVETYPE_STEP flying/floating monsters are SOLID_SLIDEBOX and MOVETYPE_FLY solid_edge items only clip against bsp models. */ cvar_t sv_friction = {"sv_friction","4",false,true}; cvar_t sv_stopspeed = {"sv_stopspeed","100"}; cvar_t sv_gravity = {"sv_gravity","800",false,true}; cvar_t sv_maxvelocity = {"sv_maxvelocity","2000"}; cvar_t sv_nostep = {"sv_nostep","0"}; #ifdef QUAKE2 static vec3_t vec_origin = {0.0, 0.0, 0.0}; #endif #define MOVE_EPSILON 0.01 void SV_Physics_Toss (edict_t *ent); /* ================ SV_CheckAllEnts ================ */ void SV_CheckAllEnts (void) { int e; edict_t *check; // see if any solid entities are inside the final position check = NEXT_EDICT(sv.edicts); for (e=1 ; e<sv.num_edicts ; e++, check = NEXT_EDICT(check)) { if (check->free) continue; if (check->v.movetype == MOVETYPE_PUSH || check->v.movetype == MOVETYPE_NONE #ifdef QUAKE2 || check->v.movetype == MOVETYPE_FOLLOW #endif || check->v.movetype == MOVETYPE_NOCLIP) continue; if (SV_TestEntityPosition (check)) Con_Printf ("entity in invalid position\n"); } } /* ================ SV_CheckVelocity ================ */ void SV_CheckVelocity (edict_t *ent) { int i; // // bound velocity // for (i=0 ; i<3 ; i++) { if (IS_NAN(ent->v.velocity[i])) { Con_Printf ("Got a NaN velocity on %s\n", pr_strings + ent->v.classname); ent->v.velocity[i] = 0; } if (IS_NAN(ent->v.origin[i])) { Con_Printf ("Got a NaN origin on %s\n", pr_strings + ent->v.classname); ent->v.origin[i] = 0; } if (ent->v.velocity[i] > sv_maxvelocity.value) ent->v.velocity[i] = sv_maxvelocity.value; else if (ent->v.velocity[i] < -sv_maxvelocity.value) ent->v.velocity[i] = -sv_maxvelocity.value; } } /* ============= SV_RunThink Runs thinking code if time. There is some play in the exact time the think function will be called, because it is called before any movement is done in a frame. Not used for pushmove objects, because they must be exact. Returns false if the entity removed itself. ============= */ qboolean SV_RunThink (edict_t *ent) { float thinktime; thinktime = ent->v.nextthink; if (thinktime <= 0 || thinktime > sv.time + host_frametime) return true; if (thinktime < sv.time) thinktime = sv.time; // don't let things stay in the past. // it is possible to start that way // by a trigger with a local time. ent->v.nextthink = 0; pr_global_struct->time = thinktime; pr_global_struct->self = EDICT_TO_PROG(ent); pr_global_struct->other = EDICT_TO_PROG(sv.edicts); PR_ExecuteProgram (ent->v.think); return !ent->free; } /* ================== SV_Impact Two entities have touched, so run their touch functions ================== */ void SV_Impact (edict_t *e1, edict_t *e2) { int old_self, old_other; old_self = pr_global_struct->self; old_other = pr_global_struct->other; pr_global_struct->time = sv.time; if (e1->v.touch && e1->v.solid != SOLID_NOT) { pr_global_struct->self = EDICT_TO_PROG(e1); pr_global_struct->other = EDICT_TO_PROG(e2); PR_ExecuteProgram (e1->v.touch); } if (e2->v.touch && e2->v.solid != SOLID_NOT) { pr_global_struct->self = EDICT_TO_PROG(e2); pr_global_struct->other = EDICT_TO_PROG(e1); PR_ExecuteProgram (e2->v.touch); } pr_global_struct->self = old_self; pr_global_struct->other = old_other; } /* ================== ClipVelocity Slide off of the impacting object returns the blocked flags (1 = floor, 2 = step / wall) ================== */ #define STOP_EPSILON 0.1 int ClipVelocity (vec3_t in, vec3_t normal, vec3_t out, float overbounce) { float backoff; float change; int i, blocked; blocked = 0; if (normal[2] > 0) blocked |= 1; // floor if (!normal[2]) blocked |= 2; // step backoff = DotProduct (in, normal) * overbounce; for (i=0 ; i<3 ; i++) { change = normal[i]*backoff; out[i] = in[i] - change; if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; } return blocked; } /* ============ SV_FlyMove The basic solid body movement clip that slides along multiple planes Returns the clipflags if the velocity was modified (hit something solid) 1 = floor 2 = wall / step 4 = dead stop If steptrace is not NULL, the trace of any vertical wall hit will be stored ============ */ #define MAX_CLIP_PLANES 5 int SV_FlyMove (edict_t *ent, float time, trace_t *steptrace) { int bumpcount, numbumps; vec3_t dir; float d; int numplanes; vec3_t planes[MAX_CLIP_PLANES]; vec3_t primal_velocity, original_velocity, new_velocity; int i, j; trace_t trace; vec3_t end; float time_left; int blocked; numbumps = 4; blocked = 0; VectorCopy (ent->v.velocity, original_velocity); VectorCopy (ent->v.velocity, primal_velocity); numplanes = 0; time_left = time; for (bumpcount=0 ; bumpcount<numbumps ; bumpcount++) { if (!ent->v.velocity[0] && !ent->v.velocity[1] && !ent->v.velocity[2]) break; for (i=0 ; i<3 ; i++) end[i] = ent->v.origin[i] + time_left * ent->v.velocity[i]; trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid) { // entity is trapped in another solid VectorCopy (vec3_origin, ent->v.velocity); return 3; } if (trace.fraction > 0) { // actually covered some distance VectorCopy (trace.endpos, ent->v.origin); VectorCopy (ent->v.velocity, original_velocity); numplanes = 0; } if (trace.fraction == 1) break; // moved the entire distance if (!trace.ent) Sys_Error ("SV_FlyMove: !trace.ent"); if (trace.plane.normal[2] > 0.7) { blocked |= 1; // floor if (trace.ent->v.solid == SOLID_BSP) { ent->v.flags = (int)ent->v.flags | FL_ONGROUND; ent->v.groundentity = EDICT_TO_PROG(trace.ent); } } if (!trace.plane.normal[2]) { blocked |= 2; // step if (steptrace) *steptrace = trace; // save for player extrafriction } // // run the impact function // SV_Impact (ent, trace.ent); if (ent->free) break; // removed by the impact function time_left -= time_left * trace.fraction; // cliped to another plane if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen VectorCopy (vec3_origin, ent->v.velocity); return 3; } VectorCopy (trace.plane.normal, planes[numplanes]); numplanes++; // // modify original_velocity so it parallels all of the clip planes // for (i=0 ; i<numplanes ; i++) { ClipVelocity (original_velocity, planes[i], new_velocity, 1); for (j=0 ; j<numplanes ; j++) if (j != i) { if (DotProduct (new_velocity, planes[j]) < 0) break; // not ok } if (j == numplanes) break; } if (i != numplanes) { // go along this plane VectorCopy (new_velocity, ent->v.velocity); } else { // go along the crease if (numplanes != 2) { // Con_Printf ("clip velocity, numplanes == %i\n",numplanes); VectorCopy (vec3_origin, ent->v.velocity); return 7; } CrossProduct (planes[0], planes[1], dir); d = DotProduct (dir, ent->v.velocity); VectorScale (dir, d, ent->v.velocity); } // // if original velocity is against the original velocity, stop dead // to avoid tiny occilations in sloping corners // if (DotProduct (ent->v.velocity, primal_velocity) <= 0) { VectorCopy (vec3_origin, ent->v.velocity); return blocked; } } return blocked; } /* ============ SV_AddGravity ============ */ void SV_AddGravity (edict_t *ent) { float ent_gravity; #ifdef QUAKE2 if (ent->v.gravity) ent_gravity = ent->v.gravity; else ent_gravity = 1.0; #else eval_t *val; val = GetEdictFieldValue(ent, "gravity"); if (val && val->_float) ent_gravity = val->_float; else ent_gravity = 1.0; #endif ent->v.velocity[2] -= ent_gravity * sv_gravity.value * host_frametime; } /* =============================================================================== PUSHMOVE =============================================================================== */ /* ============ SV_PushEntity Does not change the entities velocity at all ============ */ trace_t SV_PushEntity (edict_t *ent, vec3_t push) { trace_t trace; vec3_t end; VectorAdd (ent->v.origin, push, end); if (ent->v.movetype == MOVETYPE_FLYMISSILE) trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_MISSILE, ent); else if (ent->v.solid == SOLID_TRIGGER || ent->v.solid == SOLID_NOT) // only clip against bmodels trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NOMONSTERS, ent); else trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NORMAL, ent); VectorCopy (trace.endpos, ent->v.origin); SV_LinkEdict (ent, true); if (trace.ent) SV_Impact (ent, trace.ent); return trace; } /* ============ SV_PushMove ============ */ void SV_PushMove (edict_t *pusher, float movetime) { int i, e; edict_t *check, *block; vec3_t mins, maxs, move; vec3_t entorig, pushorig; int num_moved; edict_t *moved_edict[MAX_EDICTS]; vec3_t moved_from[MAX_EDICTS]; if (!pusher->v.velocity[0] && !pusher->v.velocity[1] && !pusher->v.velocity[2]) { pusher->v.ltime += movetime; return; } for (i=0 ; i<3 ; i++) { move[i] = pusher->v.velocity[i] * movetime; mins[i] = pusher->v.absmin[i] + move[i]; maxs[i] = pusher->v.absmax[i] + move[i]; } VectorCopy (pusher->v.origin, pushorig); // move the pusher to it's final position VectorAdd (pusher->v.origin, move, pusher->v.origin); pusher->v.ltime += movetime; SV_LinkEdict (pusher, false); // see if any solid entities are inside the final position num_moved = 0; check = NEXT_EDICT(sv.edicts); for (e=1 ; e<sv.num_edicts ; e++, check = NEXT_EDICT(check)) { if (check->free) continue; if (check->v.movetype == MOVETYPE_PUSH || check->v.movetype == MOVETYPE_NONE #ifdef QUAKE2 || check->v.movetype == MOVETYPE_FOLLOW #endif || check->v.movetype == MOVETYPE_NOCLIP) continue; // if the entity is standing on the pusher, it will definately be moved if ( ! ( ((int)check->v.flags & FL_ONGROUND) && PROG_TO_EDICT(check->v.groundentity) == pusher) ) { if ( check->v.absmin[0] >= maxs[0] || check->v.absmin[1] >= maxs[1] || check->v.absmin[2] >= maxs[2] || check->v.absmax[0] <= mins[0] || check->v.absmax[1] <= mins[1] || check->v.absmax[2] <= mins[2] ) continue; // see if the ent's bbox is inside the pusher's final position if (!SV_TestEntityPosition (check)) continue; } // remove the onground flag for non-players if (check->v.movetype != MOVETYPE_WALK) check->v.flags = (int)check->v.flags & ~FL_ONGROUND; VectorCopy (check->v.origin, entorig); VectorCopy (check->v.origin, moved_from[num_moved]); moved_edict[num_moved] = check; num_moved++; // try moving the contacted entity pusher->v.solid = SOLID_NOT; SV_PushEntity (check, move); pusher->v.solid = SOLID_BSP; // if it is still inside the pusher, block block = SV_TestEntityPosition (check); if (block) { // fail the move if (check->v.mins[0] == check->v.maxs[0]) continue; if (check->v.solid == SOLID_NOT || check->v.solid == SOLID_TRIGGER) { // corpse check->v.mins[0] = check->v.mins[1] = 0; VectorCopy (check->v.mins, check->v.maxs); continue; } VectorCopy (entorig, check->v.origin); SV_LinkEdict (check, true); VectorCopy (pushorig, pusher->v.origin); SV_LinkEdict (pusher, false); pusher->v.ltime -= movetime; // if the pusher has a "blocked" function, call it // otherwise, just stay in place until the obstacle is gone if (pusher->v.blocked) { pr_global_struct->self = EDICT_TO_PROG(pusher); pr_global_struct->other = EDICT_TO_PROG(check); PR_ExecuteProgram (pusher->v.blocked); } // move back any entities we already moved for (i=0 ; i<num_moved ; i++) { VectorCopy (moved_from[i], moved_edict[i]->v.origin); SV_LinkEdict (moved_edict[i], false); } return; } } } #ifdef QUAKE2 /* ============ SV_PushRotate ============ */ void SV_PushRotate (edict_t *pusher, float movetime) { int i, e; edict_t *check, *block; vec3_t move, a, amove; vec3_t entorig, pushorig; int num_moved; edict_t *moved_edict[MAX_EDICTS]; vec3_t moved_from[MAX_EDICTS]; vec3_t org, org2; vec3_t forward, right, up; if (!pusher->v.avelocity[0] && !pusher->v.avelocity[1] && !pusher->v.avelocity[2]) { pusher->v.ltime += movetime; return; } for (i=0 ; i<3 ; i++) amove[i] = pusher->v.avelocity[i] * movetime; VectorSubtract (vec3_origin, amove, a); AngleVectors (a, forward, right, up); VectorCopy (pusher->v.angles, pushorig); // move the pusher to it's final position VectorAdd (pusher->v.angles, amove, pusher->v.angles); pusher->v.ltime += movetime; SV_LinkEdict (pusher, false); // see if any solid entities are inside the final position num_moved = 0; check = NEXT_EDICT(sv.edicts); for (e=1 ; e<sv.num_edicts ; e++, check = NEXT_EDICT(check)) { if (check->free) continue; if (check->v.movetype == MOVETYPE_PUSH || check->v.movetype == MOVETYPE_NONE || check->v.movetype == MOVETYPE_FOLLOW || check->v.movetype == MOVETYPE_NOCLIP) continue; // if the entity is standing on the pusher, it will definately be moved if ( ! ( ((int)check->v.flags & FL_ONGROUND) && PROG_TO_EDICT(check->v.groundentity) == pusher) ) { if ( check->v.absmin[0] >= pusher->v.absmax[0] || check->v.absmin[1] >= pusher->v.absmax[1] || check->v.absmin[2] >= pusher->v.absmax[2] || check->v.absmax[0] <= pusher->v.absmin[0] || check->v.absmax[1] <= pusher->v.absmin[1] || check->v.absmax[2] <= pusher->v.absmin[2] ) continue; // see if the ent's bbox is inside the pusher's final position if (!SV_TestEntityPosition (check)) continue; } // remove the onground flag for non-players if (check->v.movetype != MOVETYPE_WALK) check->v.flags = (int)check->v.flags & ~FL_ONGROUND; VectorCopy (check->v.origin, entorig); VectorCopy (check->v.origin, moved_from[num_moved]); moved_edict[num_moved] = check; num_moved++; // calculate destination position VectorSubtract (check->v.origin, pusher->v.origin, org); org2[0] = DotProduct (org, forward); org2[1] = -DotProduct (org, right); org2[2] = DotProduct (org, up); VectorSubtract (org2, org, move); // try moving the contacted entity pusher->v.solid = SOLID_NOT; SV_PushEntity (check, move); pusher->v.solid = SOLID_BSP; // if it is still inside the pusher, block block = SV_TestEntityPosition (check); if (block) { // fail the move if (check->v.mins[0] == check->v.maxs[0]) continue; if (check->v.solid == SOLID_NOT || check->v.solid == SOLID_TRIGGER) { // corpse check->v.mins[0] = check->v.mins[1] = 0; VectorCopy (check->v.mins, check->v.maxs); continue; } VectorCopy (entorig, check->v.origin); SV_LinkEdict (check, true); VectorCopy (pushorig, pusher->v.angles); SV_LinkEdict (pusher, false); pusher->v.ltime -= movetime; // if the pusher has a "blocked" function, call it // otherwise, just stay in place until the obstacle is gone if (pusher->v.blocked) { pr_global_struct->self = EDICT_TO_PROG(pusher); pr_global_struct->other = EDICT_TO_PROG(check); PR_ExecuteProgram (pusher->v.blocked); } // move back any entities we already moved for (i=0 ; i<num_moved ; i++) { VectorCopy (moved_from[i], moved_edict[i]->v.origin); VectorSubtract (moved_edict[i]->v.angles, amove, moved_edict[i]->v.angles); SV_LinkEdict (moved_edict[i], false); } return; } else { VectorAdd (check->v.angles, amove, check->v.angles); } } } #endif /* ================ SV_Physics_Pusher ================ */ void SV_Physics_Pusher (edict_t *ent) { float thinktime; float oldltime; float movetime; oldltime = ent->v.ltime; thinktime = ent->v.nextthink; if (thinktime < ent->v.ltime + host_frametime) { movetime = thinktime - ent->v.ltime; if (movetime < 0) movetime = 0; } else movetime = host_frametime; if (movetime) { #ifdef QUAKE2 if (ent->v.avelocity[0] || ent->v.avelocity[1] || ent->v.avelocity[2]) SV_PushRotate (ent, movetime); else #endif SV_PushMove (ent, movetime); // advances ent->v.ltime if not blocked } if (thinktime > oldltime && thinktime <= ent->v.ltime) { ent->v.nextthink = 0; pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(ent); pr_global_struct->other = EDICT_TO_PROG(sv.edicts); PR_ExecuteProgram (ent->v.think); if (ent->free) return; } } /* =============================================================================== CLIENT MOVEMENT =============================================================================== */ /* ============= SV_CheckStuck This is a big hack to try and fix the rare case of getting stuck in the world clipping hull. ============= */ void SV_CheckStuck (edict_t *ent) { int i, j; int z; vec3_t org; if (!SV_TestEntityPosition(ent)) { VectorCopy (ent->v.origin, ent->v.oldorigin); return; } VectorCopy (ent->v.origin, org); VectorCopy (ent->v.oldorigin, ent->v.origin); if (!SV_TestEntityPosition(ent)) { Con_DPrintf ("Unstuck.\n"); SV_LinkEdict (ent, true); return; } for (z=0 ; z< 18 ; z++) for (i=-1 ; i <= 1 ; i++) for (j=-1 ; j <= 1 ; j++) { ent->v.origin[0] = org[0] + i; ent->v.origin[1] = org[1] + j; ent->v.origin[2] = org[2] + z; if (!SV_TestEntityPosition(ent)) { Con_DPrintf ("Unstuck.\n"); SV_LinkEdict (ent, true); return; } } VectorCopy (org, ent->v.origin); Con_DPrintf ("player is stuck.\n"); } /* ============= SV_CheckWater ============= */ qboolean SV_CheckWater (edict_t *ent) { vec3_t point; int cont; #ifdef QUAKE2 int truecont; #endif point[0] = ent->v.origin[0]; point[1] = ent->v.origin[1]; point[2] = ent->v.origin[2] + ent->v.mins[2] + 1; ent->v.waterlevel = 0; ent->v.watertype = CONTENTS_EMPTY; cont = SV_PointContents (point); if (cont <= CONTENTS_WATER) { #ifdef QUAKE2 truecont = SV_TruePointContents (point); #endif ent->v.watertype = cont; ent->v.waterlevel = 1; point[2] = ent->v.origin[2] + (ent->v.mins[2] + ent->v.maxs[2])*0.5; cont = SV_PointContents (point); if (cont <= CONTENTS_WATER) { ent->v.waterlevel = 2; point[2] = ent->v.origin[2] + ent->v.view_ofs[2]; cont = SV_PointContents (point); if (cont <= CONTENTS_WATER) ent->v.waterlevel = 3; } #ifdef QUAKE2 if (truecont <= CONTENTS_CURRENT_0 && truecont >= CONTENTS_CURRENT_DOWN) { static vec3_t current_table[] = { {1, 0, 0}, {0, 1, 0}, {-1, 0, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1} }; VectorMA (ent->v.basevelocity, 150.0*ent->v.waterlevel/3.0, current_table[CONTENTS_CURRENT_0 - truecont], ent->v.basevelocity); } #endif } return ent->v.waterlevel > 1; } /* ============ SV_WallFriction ============ */ void SV_WallFriction (edict_t *ent, trace_t *trace) { vec3_t forward, right, up; float d, i; vec3_t into, side; AngleVectors (ent->v.v_angle, forward, right, up); d = DotProduct (trace->plane.normal, forward); d += 0.5; if (d >= 0) return; // cut the tangential velocity i = DotProduct (trace->plane.normal, ent->v.velocity); VectorScale (trace->plane.normal, i, into); VectorSubtract (ent->v.velocity, into, side); ent->v.velocity[0] = side[0] * (1 + d); ent->v.velocity[1] = side[1] * (1 + d); } /* ===================== SV_TryUnstick Player has come to a dead stop, possibly due to the problem with limited float precision at some angle joins in the BSP hull. Try fixing by pushing one pixel in each direction. This is a hack, but in the interest of good gameplay... ====================== */ int SV_TryUnstick (edict_t *ent, vec3_t oldvel) { int i; vec3_t oldorg; vec3_t dir; int clip; trace_t steptrace; VectorCopy (ent->v.origin, oldorg); VectorCopy (vec3_origin, dir); for (i=0 ; i<8 ; i++) { // try pushing a little in an axial direction switch (i) { case 0: dir[0] = 2; dir[1] = 0; break; case 1: dir[0] = 0; dir[1] = 2; break; case 2: dir[0] = -2; dir[1] = 0; break; case 3: dir[0] = 0; dir[1] = -2; break; case 4: dir[0] = 2; dir[1] = 2; break; case 5: dir[0] = -2; dir[1] = 2; break; case 6: dir[0] = 2; dir[1] = -2; break; case 7: dir[0] = -2; dir[1] = -2; break; } SV_PushEntity (ent, dir); // retry the original move ent->v.velocity[0] = oldvel[0]; ent->v. velocity[1] = oldvel[1]; ent->v. velocity[2] = 0; clip = SV_FlyMove (ent, 0.1f, &steptrace); if ( fabs(oldorg[1] - ent->v.origin[1]) > 4 || fabs(oldorg[0] - ent->v.origin[0]) > 4 ) { //Con_DPrintf ("unstuck!\n"); return clip; } // go back to the original pos and try again VectorCopy (oldorg, ent->v.origin); } VectorCopy (vec3_origin, ent->v.velocity); return 7; // still not moving } /* ===================== SV_WalkMove Only used by players ====================== */ #define STEPSIZE 18 void SV_WalkMove (edict_t *ent) { vec3_t upmove, downmove; vec3_t oldorg, oldvel; vec3_t nosteporg, nostepvel; int clip; int oldonground; trace_t steptrace, downtrace; // // do a regular slide move unless it looks like you ran into a step // oldonground = (int)ent->v.flags & FL_ONGROUND; ent->v.flags = (int)ent->v.flags & ~FL_ONGROUND; VectorCopy (ent->v.origin, oldorg); VectorCopy (ent->v.velocity, oldvel); clip = SV_FlyMove (ent, host_frametime, &steptrace); if ( !(clip & 2) ) return; // move didn't block on a step if (!oldonground && ent->v.waterlevel == 0) return; // don't stair up while jumping if (ent->v.movetype != MOVETYPE_WALK) return; // gibbed by a trigger if (sv_nostep.value) return; if ( (int)sv_player->v.flags & FL_WATERJUMP ) return; VectorCopy (ent->v.origin, nosteporg); VectorCopy (ent->v.velocity, nostepvel); // // try moving up and forward to go up a step // VectorCopy (oldorg, ent->v.origin); // back to start pos VectorCopy (vec3_origin, upmove); VectorCopy (vec3_origin, downmove); upmove[2] = STEPSIZE; downmove[2] = -STEPSIZE + oldvel[2]*host_frametime; // move up SV_PushEntity (ent, upmove); // FIXME: don't link? // move forward ent->v.velocity[0] = oldvel[0]; ent->v. velocity[1] = oldvel[1]; ent->v. velocity[2] = 0; clip = SV_FlyMove (ent, host_frametime, &steptrace); // check for stuckness, possibly due to the limited precision of floats // in the clipping hulls if (clip) { if ( fabs(oldorg[1] - ent->v.origin[1]) < 0.03125 && fabs(oldorg[0] - ent->v.origin[0]) < 0.03125 ) { // stepping up didn't make any progress clip = SV_TryUnstick (ent, oldvel); } } // extra friction based on view angle if ( clip & 2 ) SV_WallFriction (ent, &steptrace); // move down downtrace = SV_PushEntity (ent, downmove); // FIXME: don't link? if (downtrace.plane.normal[2] > 0.7) { if (ent->v.solid == SOLID_BSP) { ent->v.flags = (int)ent->v.flags | FL_ONGROUND; ent->v.groundentity = EDICT_TO_PROG(downtrace.ent); } } else { // if the push down didn't end up on good ground, use the move without // the step up. This happens near wall / slope combinations, and can // cause the player to hop up higher on a slope too steep to climb VectorCopy (nosteporg, ent->v.origin); VectorCopy (nostepvel, ent->v.velocity); } } /* ================ SV_Physics_Client Player character actions ================ */ void SV_Physics_Client (edict_t *ent, int num) { if ( ! svs.clients[num-1].active ) return; // unconnected slot // // call standard client pre-think // pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(ent); PR_ExecuteProgram (pr_global_struct->PlayerPreThink); // // do a move // SV_CheckVelocity (ent); // // decide which move function to call // switch ((int)ent->v.movetype) { case MOVETYPE_NONE: if (!SV_RunThink (ent)) return; break; case MOVETYPE_WALK: if (!SV_RunThink (ent)) return; if (!SV_CheckWater (ent) && ! ((int)ent->v.flags & FL_WATERJUMP) ) SV_AddGravity (ent); SV_CheckStuck (ent); #ifdef QUAKE2 VectorAdd (ent->v.velocity, ent->v.basevelocity, ent->v.velocity); #endif SV_WalkMove (ent); #ifdef QUAKE2 VectorSubtract (ent->v.velocity, ent->v.basevelocity, ent->v.velocity); #endif break; case MOVETYPE_TOSS: case MOVETYPE_BOUNCE: SV_Physics_Toss (ent); break; case MOVETYPE_FLY: if (!SV_RunThink (ent)) return; SV_FlyMove (ent, host_frametime, NULL); break; case MOVETYPE_NOCLIP: if (!SV_RunThink (ent)) return; VectorMA (ent->v.origin, host_frametime, ent->v.velocity, ent->v.origin); break; default: Sys_Error ("SV_Physics_client: bad movetype %i", (int)ent->v.movetype); } // // call standard player post-think // SV_LinkEdict (ent, true); pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(ent); PR_ExecuteProgram (pr_global_struct->PlayerPostThink); } //============================================================================ /* ============= SV_Physics_None Non moving objects can only think ============= */ void SV_Physics_None (edict_t *ent) { // regular thinking SV_RunThink (ent); } #ifdef QUAKE2 /* ============= SV_Physics_Follow Entities that are "stuck" to another entity ============= */ void SV_Physics_Follow (edict_t *ent) { // regular thinking SV_RunThink (ent); VectorAdd (PROG_TO_EDICT(ent->v.aiment)->v.origin, ent->v.v_angle, ent->v.origin); SV_LinkEdict (ent, true); } #endif /* ============= SV_Physics_Noclip A moving object that doesn't obey physics ============= */ void SV_Physics_Noclip (edict_t *ent) { // regular thinking if (!SV_RunThink (ent)) return; VectorMA (ent->v.angles, host_frametime, ent->v.avelocity, ent->v.angles); VectorMA (ent->v.origin, host_frametime, ent->v.velocity, ent->v.origin); SV_LinkEdict (ent, false); } /* ============================================================================== TOSS / BOUNCE ============================================================================== */ /* ============= SV_CheckWaterTransition ============= */ void SV_CheckWaterTransition (edict_t *ent) { int cont; #ifdef QUAKE2 vec3_t point; point[0] = ent->v.origin[0]; point[1] = ent->v.origin[1]; point[2] = ent->v.origin[2] + ent->v.mins[2] + 1; cont = SV_PointContents (point); #else cont = SV_PointContents (ent->v.origin); #endif if (!ent->v.watertype) { // just spawned here ent->v.watertype = cont; ent->v.waterlevel = 1; return; } if (cont <= CONTENTS_WATER) { if (ent->v.watertype == CONTENTS_EMPTY) { // just crossed into water SV_StartSound (ent, 0, "misc/h2ohit1.wav", 255, 1); } ent->v.watertype = cont; ent->v.waterlevel = 1; } else { if (ent->v.watertype != CONTENTS_EMPTY) { // just crossed into water SV_StartSound (ent, 0, "misc/h2ohit1.wav", 255, 1); } ent->v.watertype = CONTENTS_EMPTY; ent->v.waterlevel = cont; } } /* ============= SV_Physics_Toss Toss, bounce, and fly movement. When onground, do nothing. ============= */ void SV_Physics_Toss (edict_t *ent) { trace_t trace; vec3_t move; float backoff; #ifdef QUAKE2 edict_t *groundentity; groundentity = PROG_TO_EDICT(ent->v.groundentity); if ((int)groundentity->v.flags & FL_CONVEYOR) VectorScale(groundentity->v.movedir, groundentity->v.speed, ent->v.basevelocity); else VectorCopy(vec_origin, ent->v.basevelocity); SV_CheckWater (ent); #endif // regular thinking if (!SV_RunThink (ent)) return; #ifdef QUAKE2 if (ent->v.velocity[2] > 0) ent->v.flags = (int)ent->v.flags & ~FL_ONGROUND; if ( ((int)ent->v.flags & FL_ONGROUND) ) //@@ if (VectorCompare(ent->v.basevelocity, vec_origin)) return; SV_CheckVelocity (ent); // add gravity if (! ((int)ent->v.flags & FL_ONGROUND) && ent->v.movetype != MOVETYPE_FLY && ent->v.movetype != MOVETYPE_BOUNCEMISSILE && ent->v.movetype != MOVETYPE_FLYMISSILE) SV_AddGravity (ent); #else // if onground, return without moving if ( ((int)ent->v.flags & FL_ONGROUND) ) return; SV_CheckVelocity (ent); // add gravity if (ent->v.movetype != MOVETYPE_FLY && ent->v.movetype != MOVETYPE_FLYMISSILE) SV_AddGravity (ent); #endif // move angles VectorMA (ent->v.angles, host_frametime, ent->v.avelocity, ent->v.angles); // move origin #ifdef QUAKE2 VectorAdd (ent->v.velocity, ent->v.basevelocity, ent->v.velocity); #endif VectorScale (ent->v.velocity, host_frametime, move); trace = SV_PushEntity (ent, move); #ifdef QUAKE2 VectorSubtract (ent->v.velocity, ent->v.basevelocity, ent->v.velocity); #endif if (trace.fraction == 1) return; if (ent->free) return; if (ent->v.movetype == MOVETYPE_BOUNCE) backoff = 1.5; #ifdef QUAKE2 else if (ent->v.movetype == MOVETYPE_BOUNCEMISSILE) backoff = 2.0; #endif else backoff = 1; ClipVelocity (ent->v.velocity, trace.plane.normal, ent->v.velocity, backoff); // stop if on ground if (trace.plane.normal[2] > 0.7) { #ifdef QUAKE2 if (ent->v.velocity[2] < 60 || (ent->v.movetype != MOVETYPE_BOUNCE && ent->v.movetype != MOVETYPE_BOUNCEMISSILE)) #else if (ent->v.velocity[2] < 60 || ent->v.movetype != MOVETYPE_BOUNCE) #endif { ent->v.flags = (int)ent->v.flags | FL_ONGROUND; ent->v.groundentity = EDICT_TO_PROG(trace.ent); VectorCopy (vec3_origin, ent->v.velocity); VectorCopy (vec3_origin, ent->v.avelocity); } } // check for in water SV_CheckWaterTransition (ent); } /* =============================================================================== STEPPING MOVEMENT =============================================================================== */ /* ============= SV_Physics_Step Monsters freefall when they don't have a ground entity, otherwise all movement is done with discrete steps. This is also used for objects that have become still on the ground, but will fall if the floor is pulled out from under them. ============= */ #ifdef QUAKE2 void SV_Physics_Step (edict_t *ent) { qboolean wasonground; qboolean inwater; qboolean hitsound = false; float *vel; float speed, newspeed, control; float friction; edict_t *groundentity; groundentity = PROG_TO_EDICT(ent->v.groundentity); if ((int)groundentity->v.flags & FL_CONVEYOR) VectorScale(groundentity->v.movedir, groundentity->v.speed, ent->v.basevelocity); else VectorCopy(vec_origin, ent->v.basevelocity); //@@ pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(ent); PF_WaterMove(); SV_CheckVelocity (ent); wasonground = (int)ent->v.flags & FL_ONGROUND; // ent->v.flags = (int)ent->v.flags & ~FL_ONGROUND; // add gravity except: // flying monsters // swimming monsters who are in the water inwater = SV_CheckWater(ent); if (! wasonground) if (!((int)ent->v.flags & FL_FLY)) if (!(((int)ent->v.flags & FL_SWIM) && (ent->v.waterlevel > 0))) { if (ent->v.velocity[2] < sv_gravity.value*-0.1) hitsound = true; if (!inwater) SV_AddGravity (ent); } if (!VectorCompare(ent->v.velocity, vec_origin) || !VectorCompare(ent->v.basevelocity, vec_origin)) { ent->v.flags = (int)ent->v.flags & ~FL_ONGROUND; // apply friction // let dead monsters who aren't completely onground slide if (wasonground) if (!(ent->v.health <= 0.0 && !SV_CheckBottom(ent))) { vel = ent->v.velocity; speed = sqrt(vel[0]*vel[0] +vel[1]*vel[1]); if (speed) { friction = sv_friction.value; control = speed < sv_stopspeed.value ? sv_stopspeed.value : speed; newspeed = speed - host_frametime*control*friction; if (newspeed < 0) newspeed = 0; newspeed /= speed; vel[0] = vel[0] * newspeed; vel[1] = vel[1] * newspeed; } } VectorAdd (ent->v.velocity, ent->v.basevelocity, ent->v.velocity); SV_FlyMove (ent, host_frametime, NULL); VectorSubtract (ent->v.velocity, ent->v.basevelocity, ent->v.velocity); // determine if it's on solid ground at all { vec3_t mins, maxs, point; int x, y; VectorAdd (ent->v.origin, ent->v.mins, mins); VectorAdd (ent->v.origin, ent->v.maxs, maxs); point[2] = mins[2] - 1; for (x=0 ; x<=1 ; x++) for (y=0 ; y<=1 ; y++) { point[0] = x ? maxs[0] : mins[0]; point[1] = y ? maxs[1] : mins[1]; if (SV_PointContents (point) == CONTENTS_SOLID) { ent->v.flags = (int)ent->v.flags | FL_ONGROUND; break; } } } SV_LinkEdict (ent, true); if ((int)ent->v.flags & FL_ONGROUND) if (!wasonground) if (hitsound) SV_StartSound (ent, 0, "demon/dland2.wav", 255, 1); } // regular thinking SV_RunThink (ent); SV_CheckWaterTransition (ent); } #else void SV_Physics_Step (edict_t *ent) { qboolean hitsound; // freefall if not onground if ( ! ((int)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM) ) ) { if (ent->v.velocity[2] < sv_gravity.value*-0.1) hitsound = true; else hitsound = false; SV_AddGravity (ent); SV_CheckVelocity (ent); SV_FlyMove (ent, host_frametime, NULL); SV_LinkEdict (ent, true); if ( (int)ent->v.flags & FL_ONGROUND ) // just hit ground { if (hitsound) SV_StartSound (ent, 0, "demon/dland2.wav", 255, 1); } } // regular thinking SV_RunThink (ent); SV_CheckWaterTransition (ent); } #endif //============================================================================ /* ================ SV_Physics ================ */ void SV_Physics (void) { int i; edict_t *ent; // let the progs know that a new frame has started pr_global_struct->self = EDICT_TO_PROG(sv.edicts); pr_global_struct->other = EDICT_TO_PROG(sv.edicts); pr_global_struct->time = sv.time; PR_ExecuteProgram (pr_global_struct->StartFrame); //SV_CheckAllEnts (); // // treat each object in turn // ent = sv.edicts; for (i=0 ; i<sv.num_edicts ; i++, ent = NEXT_EDICT(ent)) { if (ent->free) continue; if (pr_global_struct->force_retouch) { SV_LinkEdict (ent, true); // force retouch even for stationary } if (i > 0 && i <= svs.maxclients) SV_Physics_Client (ent, i); else if (ent->v.movetype == MOVETYPE_PUSH) SV_Physics_Pusher (ent); else if (ent->v.movetype == MOVETYPE_NONE) SV_Physics_None (ent); #ifdef QUAKE2 else if (ent->v.movetype == MOVETYPE_FOLLOW) SV_Physics_Follow (ent); #endif else if (ent->v.movetype == MOVETYPE_NOCLIP) SV_Physics_Noclip (ent); else if (ent->v.movetype == MOVETYPE_STEP) SV_Physics_Step (ent); else if (ent->v.movetype == MOVETYPE_TOSS || ent->v.movetype == MOVETYPE_BOUNCE #ifdef QUAKE2 || ent->v.movetype == MOVETYPE_BOUNCEMISSILE #endif || ent->v.movetype == MOVETYPE_FLY || ent->v.movetype == MOVETYPE_FLYMISSILE) SV_Physics_Toss (ent); else Sys_Error ("SV_Physics: bad movetype %i", (int)ent->v.movetype); } if (pr_global_struct->force_retouch) pr_global_struct->force_retouch--; sv.time += host_frametime; } #ifdef QUAKE2 trace_t SV_Trace_Toss (edict_t *ent, edict_t *ignore) { edict_t tempent, *tent; trace_t trace; vec3_t move; vec3_t end; double save_frametime; // extern particle_t *active_particles, *free_particles; // particle_t *p; save_frametime = host_frametime; host_frametime = 0.05; memcpy(&tempent, ent, sizeof(edict_t)); tent = &tempent; while (1) { SV_CheckVelocity (tent); SV_AddGravity (tent); VectorMA (tent->v.angles, host_frametime, tent->v.avelocity, tent->v.angles); VectorScale (tent->v.velocity, host_frametime, move); VectorAdd (tent->v.origin, move, end); trace = SV_Move (tent->v.origin, tent->v.mins, tent->v.maxs, end, MOVE_NORMAL, tent); VectorCopy (trace.endpos, tent->v.origin); // p = free_particles; // if (p) // { // free_particles = p->next; // p->next = active_particles; // active_particles = p; // // p->die = 256; // p->color = 15; // p->type = pt_static; // VectorCopy (vec3_origin, p->vel); // VectorCopy (tent->v.origin, p->org); // } if (trace.ent) if (trace.ent != ignore) break; } // p->color = 224; host_frametime = save_frametime; return trace; } #endif
412
0.841632
1
0.841632
game-dev
MEDIA
0.613702
game-dev
0.974074
1
0.974074
Cataclysm-TLG/Cataclysm-TLG
22,400
src/gates.cpp
#include "gates.h" #include <algorithm> #include <array> #include <memory> #include <optional> #include <set> #include <vector> #include "activity_actor_definitions.h" #include "avatar.h" #include "character.h" #include "colony.h" #include "creature.h" #include "creature_tracker.h" #include "debug.h" #include "enums.h" #include "game.h" // TODO: This is a circular dependency #include "generic_factory.h" #include "iexamine.h" #include "item.h" #include "json.h" #include "map.h" #include "mapdata.h" #include "messages.h" #include "player_activity.h" #include "point.h" #include "translations.h" #include "units.h" #include "vehicle.h" #include "viewer.h" #include "vpart_position.h" static const furn_str_id furn_f_crate_o( "f_crate_o" ); static const furn_str_id furn_f_safe_o( "f_safe_o" ); static const material_id material_glass( "glass" ); // Gates namespace namespace { struct gate_data; using gate_id = string_id<gate_data>; struct gate_data { gate_data() : moves( 0 ), bash_dmg( 0 ), was_loaded( false ) {} gate_id id; std::vector<std::pair<gate_id, mod_id>> src; ter_str_id door; ter_str_id floor; std::vector<ter_str_id> walls; translation pull_message; translation open_message; translation close_message; translation fail_message; int moves; int bash_dmg; bool was_loaded; void load( const JsonObject &jo, std::string_view src ); void check() const; bool is_suitable_wall( const tripoint_bub_ms &pos ) const; }; gate_id get_gate_id( const tripoint_bub_ms &pos ) { return gate_id( get_map().ter( pos ).id().str() ); } generic_factory<gate_data> gates_data( "gate type" ); } // namespace void gate_data::load( const JsonObject &jo, const std::string_view ) { mandatory( jo, was_loaded, "door", door ); mandatory( jo, was_loaded, "floor", floor ); mandatory( jo, was_loaded, "walls", walls, string_id_reader<ter_t> {} ); if( !was_loaded || jo.has_member( "messages" ) ) { JsonObject messages_obj = jo.get_object( "messages" ); optional( messages_obj, was_loaded, "pull", pull_message ); optional( messages_obj, was_loaded, "open", open_message ); optional( messages_obj, was_loaded, "close", close_message ); optional( messages_obj, was_loaded, "fail", fail_message ); } optional( jo, was_loaded, "moves", moves, 0 ); optional( jo, was_loaded, "bashing_damage", bash_dmg, 0 ); } void gate_data::check() const { const ter_str_id winch_tid( id.str() ); if( !winch_tid.is_valid() ) { debugmsg( "Gates \"%s\" have no terrain of the same name, working as a winch.", id.c_str() ); } else if( !winch_tid->has_examine( iexamine::controls_gate ) ) { debugmsg( "Terrain \"%s\" can't control gates, but gates \"%s\" depend on it.", winch_tid.c_str(), id.c_str() ); } if( !door.is_valid() ) { debugmsg( "Invalid door \"%s\" in \"%s\".", door.c_str(), id.c_str() ); } if( !floor.is_valid() ) { debugmsg( "Invalid floor \"%s\" in \"%s\".", floor.c_str(), id.c_str() ); } for( const auto &elem : walls ) { if( !elem.is_valid() ) { debugmsg( "Invalid wall \"%s\" in \"%s\".", elem.c_str(), id.c_str() ); } } if( moves < 0 ) { debugmsg( "Gates \"%s\" grant moves.", id.c_str() ); } } bool gate_data::is_suitable_wall( const tripoint_bub_ms &pos ) const { const ter_id &wid = get_map().ter( pos ); if( walls.empty() ) { return wid->has_flag( "WALL" ); } const auto iter = std::find_if( walls.begin(), walls.end(), [ wid ]( const ter_str_id & wall ) { return wall.id() == wid; } ); return iter != walls.end(); } void gates::load( const JsonObject &jo, const std::string &src ) { gates_data.load( jo, src ); } void gates::check() { gates_data.check(); } void gates::reset() { gates_data.reset(); } // A gate handle is adjacent to a wall section, and next to that wall section on one side or // another is the gate. There may be a handle on the other side, but this is optional. // The gate continues until it reaches a non-floor tile, so they can be arbitrary length. // // | !|! -++-++- !|++++- // + + ! + // + + -++-++- + // + + + // + + !|++++- + // !| |! ! | // void gates::open_gate( const tripoint_bub_ms &pos ) { const gate_id gid = get_gate_id( pos ); if( !gates_data.is_valid( gid ) ) { return; } const gate_data &gate = gates_data.obj( gid ); bool open = false; bool close = false; bool fail = false; map &here = get_map(); for( const point &wall_offset : four_adjacent_offsets ) { const tripoint_bub_ms wall_pos = pos + wall_offset; if( !gate.is_suitable_wall( wall_pos ) ) { continue; } for( const point &gate_offset : four_adjacent_offsets ) { const tripoint_bub_ms gate_pos = wall_pos + gate_offset; if( gate_pos == pos ) { continue; // Never comes back } if( !open ) { // Closing the gate... tripoint_bub_ms cur_pos = gate_pos; std::vector<tripoint_bub_ms> all_gate_tiles; while( here.ter( cur_pos ) == gate.floor.id() ) { all_gate_tiles.emplace_back( cur_pos ); cur_pos += gate_offset; } cur_pos = gate_pos; while( here.ter( cur_pos ) == gate.floor.id() ) { fail = !doors::forced_door_closing( cur_pos, all_gate_tiles, gate.door.id(), gate.bash_dmg ) || fail; close = !fail; cur_pos += gate_offset; } } if( !close ) { // Opening the gate... tripoint_bub_ms cur_pos = gate_pos; while( true ) { const ter_id &ter = here.ter( cur_pos ); if( ter == gate.door.id() ) { here.ter_set( cur_pos, gate.floor.id() ); open = !fail; } else if( ter != gate.floor.id() ) { break; } cur_pos += gate_offset; } } } } if( get_player_view().sees( here, pos ) ) { if( open ) { add_msg( gate.open_message ); } else if( close ) { add_msg( gate.close_message ); } else if( fail ) { add_msg( gate.fail_message ); } else { add_msg( _( "Nothing happens." ) ); } } } void gates::open_gate( const tripoint_bub_ms &pos, Character &p ) { const gate_id gid = get_gate_id( pos ); if( !gates_data.is_valid( gid ) ) { p.add_msg_if_player( _( "Nothing happens." ) ); return; } const gate_data &gate = gates_data.obj( gid ); p.add_msg_if_player( gate.pull_message ); p.assign_activity( open_gate_activity_actor( gate.moves, pos ) ); } // Doors namespace // TODO: move door functions from maps namespace here, or vice versa. void doors::close_door( map &m, Creature &who, const tripoint_bub_ms &closep ) { bool didit = false; const bool inside = !m.is_outside( who.pos_bub() ); const Creature *const mon = get_creature_tracker().creature_at( closep ); if( mon ) { if( mon->is_avatar() ) { who.add_msg_if_player( m_info, _( "There's some buffoon in the way!" ) ); } else if( mon->is_monster() ) { // TODO: Houseflies, mosquitoes, etc shouldn't count who.add_msg_if_player( m_info, _( "The %s is in the way!" ), mon->get_name() ); } else { who.add_msg_if_player( m_info, _( "%s is in the way!" ), mon->disp_name() ); } return; } if( optional_vpart_position vp = m.veh_at( closep ) ) { // There is a vehicle part here; see if it has anything that can be closed vehicle *const veh = &vp->vehicle(); const int vpart = vp->part_index(); const int closable = veh->next_part_to_close( vpart, veh_pointer_or_null( m.veh_at( who.pos_bub() ) ) != veh ); const int inside_closable = veh->next_part_to_close( vpart ); const int openable = veh->next_part_to_open( vpart ); if( closable >= 0 ) { if( !veh->handle_potential_theft( get_avatar() ) ) { return; } Character *ch = who.as_character(); if( ch && veh->can_close( closable, *ch ) ) { veh->close( m, closable ); //~ %1$s - vehicle name, %2$s - part name who.add_msg_if_player( _( "You close the %1$s's %2$s." ), veh->name, veh->part( closable ).name() ); didit = true; } } else if( inside_closable >= 0 ) { who.add_msg_if_player( m_info, _( "That %s can only be closed from the inside." ), veh->part( inside_closable ).name() ); } else if( openable >= 0 ) { who.add_msg_if_player( m_info, _( "That %s is already closed." ), veh->part( openable ).name() ); } else { who.add_msg_if_player( m_info, _( "You cannot close the %s." ), veh->part( vpart ).name() ); } } else if( m.furn( closep ) == furn_f_crate_o ) { who.add_msg_if_player( m_info, _( "You'll need to construct a seal to close the crate!" ) ); } else if( !m.close_door( closep, inside, true ) ) { if( m.close_door( closep, true, true ) ) { who.add_msg_if_player( m_info, _( "You cannot close the %s from outside. You must be inside the building." ), m.name( closep ) ); } else { who.add_msg_if_player( m_info, _( "You cannot close the %s." ), m.name( closep ) ); } } else { map_stack items_in_way = m.i_at( closep ); // Scoot up to 25 liters of items out of the way if( m.furn( closep ) != furn_f_safe_o && !items_in_way.empty() ) { const units::volume max_nudge = 25_liter; const auto toobig = std::find_if( items_in_way.begin(), items_in_way.end(), [&max_nudge]( const item & it ) { return it.volume() > max_nudge; } ); if( toobig != items_in_way.end() ) { who.add_msg_if_player( m_info, _( "The %s is too big to just nudge out of the way." ), toobig->tname() ); } else if( items_in_way.stored_volume() > max_nudge ) { who.add_msg_if_player( m_info, _( "There is too much stuff in the way." ) ); } else { m.close_door( closep, inside, false ); didit = true; who.add_msg_if_player( m_info, _( "You push the %s out of the way." ), items_in_way.size() == 1 ? items_in_way.only_item().tname() : _( "stuff" ) ); who.mod_moves( -std::min( items_in_way.stored_volume() / ( max_nudge / 50 ), 100 ) ); if( m.has_flag( ter_furn_flag::TFLAG_NOITEM, closep ) ) { // Just plopping items back on their origin square will displace them to adjacent squares // since the door is closed now. for( item &elem : items_in_way ) { m.add_item_or_charges( closep, elem ); } m.i_clear( closep ); } } } else { const std::string door_name = m.obstacle_name( closep ); m.close_door( closep, inside, false ); who.add_msg_if_player( _( "You close the %s." ), door_name ); didit = true; } } if( didit ) { // TODO: Vary this? Based on strength, broken legs, and so on. who.mod_moves( -90 ); } } bool doors::forced_door_closing( const tripoint_bub_ms &p, std::vector<tripoint_bub_ms> affected_tiles, const ter_id &door_type, int bash_dmg ) { map &m = get_map(); avatar &u = get_avatar(); const int &x = p.x(); const int &y = p.y(); const std::string &door_name = door_type.obj().name(); const auto valid_location = [&]( const tripoint_bub_ms & pvl ) { return ( g->is_empty( pvl ) && pvl != p && std::find( affected_tiles.cbegin(), affected_tiles.cend(), pvl ) == std::end( affected_tiles ) ); }; const std::optional<tripoint_bub_ms> pos = random_point( m.points_in_radius( p, 2 ), valid_location ); if( !pos.has_value() ) { // can't pushback any creatures anywhere, that means the door can't close. return false; } const tripoint_bub_ms displace = pos.value(); //knockback trajectory requires the line be flipped const tripoint_bub_ms kbp( -displace.x() + x * 2, -displace.y() + y * 2, displace.z() ); const bool can_see = u.sees( m, kbp ); creature_tracker &creatures = get_creature_tracker(); Character *npc_or_player = creatures.creature_at<Character>( p, false ); if( npc_or_player != nullptr ) { if( bash_dmg <= 0 ) { return false; } if( npc_or_player->is_npc() && can_see ) { add_msg( _( "The %1$s hits the %2$s." ), door_name, npc_or_player->get_name() ); } else if( npc_or_player->is_avatar() ) { add_msg( m_bad, _( "The %s hits you." ), door_name ); } if( npc_or_player->activity ) { npc_or_player->cancel_activity(); } // TODO: make the npc angry? npc_or_player->hitall( bash_dmg, 0, nullptr ); g->knockback( kbp, p, std::max( 1, bash_dmg / 10 ), -1, 1 ); // TODO: perhaps damage/destroy the gate // if the npc was really big? if( creatures.creature_at<Character>( p, false ) != nullptr ) { return false; } } if( monster *const mon_ptr = creatures.creature_at<monster>( p ) ) { monster &critter = *mon_ptr; if( bash_dmg <= 0 ) { return false; } if( can_see ) { add_msg( _( "The %1$s hits the %2$s." ), door_name, critter.name() ); } if( critter.get_size() <= creature_size::small ) { critter.die_in_explosion( nullptr ); } else { critter.apply_damage( nullptr, bodypart_id( "torso" ), bash_dmg ); critter.check_dead_state( &m ); } if( !critter.is_dead() && critter.get_size() >= creature_size::huge ) { // big critters simply prevent the gate from closing // TODO: perhaps damage/destroy the gate // if the critter was really big? return false; } if( !critter.is_dead() ) { // Still alive? Move the critter away so the door can close g->knockback( kbp, p, std::max( 1, bash_dmg / 10 ), -1, 1 ); if( creatures.creature_at( p ) ) { return false; } } } if( const optional_vpart_position vp = m.veh_at( p ) ) { if( bash_dmg <= 0 ) { return false; } vp->vehicle().damage( m, vp->part_index(), bash_dmg ); if( m.veh_at( p ) ) { // Check again in case all parts at the door tile // have been destroyed, if there is still a vehicle // there, the door can not be closed return false; } } if( bash_dmg < 0 && !m.i_at( point_bub_ms( x, y ) ).empty() ) { return false; } if( bash_dmg == 0 ) { for( item &elem : m.i_at( point_bub_ms( x, y ) ) ) { if( elem.made_of( phase_id::LIQUID ) ) { // Liquids are OK, will be destroyed later continue; } if( elem.volume() < 250_ml ) { // Dito for small items, will be moved away continue; } // Everything else prevents the door from closing return false; } } m.ter_set( point_bub_ms( x, y ), door_type ); if( m.has_flag( ter_furn_flag::TFLAG_NOITEM, point_bub_ms( x, y ) ) ) { map_stack items = m.i_at( point_bub_ms( x, y ) ); for( map_stack::iterator it = items.begin(); it != items.end(); ) { if( it->made_of( phase_id::LIQUID ) ) { it = items.erase( it ); continue; } const int glass_portion = it->made_of( material_glass ); const float glass_fraction = glass_portion / static_cast<float>( it->type->mat_portion_total ); if( glass_portion && rng_float( 0.0f, 1.0f ) < glass_fraction * 0.5f ) { if( can_see ) { add_msg( m_warning, _( "A %s shatters!" ), it->tname() ); } else { add_msg( m_warning, _( "Something shatters!" ) ); } it = items.erase( it ); continue; } m.add_item_or_charges( kbp, *it ); it = items.erase( it ); } } return true; } // If you update this, look at doors::can_lock_door too. bool doors::lock_door( map &m, Creature &who, const tripoint_bub_ms &lockp ) { bool didit = false; if( const optional_vpart_position &vp = m.veh_at( lockp ) ) { vehicle *const veh = &vp->vehicle(); const int vpart = vp->part_index(); const optional_vpart_position &veh_here = m.veh_at( who.pos_bub() ); const bool inside_vehicle = veh_here && &vp->vehicle() == &veh_here->vehicle(); const int lockable = veh->next_part_to_lock( vpart, !inside_vehicle ); const int inside_lockable = veh->next_part_to_lock( vpart ); const int already_locked_part = veh->next_part_to_unlock( vpart ); if( lockable >= 0 ) { if( const Character *const ch = who.as_character() ) { if( !veh->handle_potential_theft( *ch ) ) { return false; } veh->lock( lockable ); who.add_msg_if_player( _( "You lock the %1$s's %2$s." ), veh->name, veh->part( lockable ).name() ); didit = true; } } else if( inside_lockable >= 0 ) { who.add_msg_if_player( m_info, _( "That %s can only be locked from the inside." ), veh->part( inside_lockable ).name() ); } else if( already_locked_part >= 0 ) { who.add_msg_if_player( m_info, _( "That %s is already locked." ), veh->part( already_locked_part ).name() ); } else { who.add_msg_if_player( m_info, _( "You cannot lock the %s." ), veh->part( vpart ).name() ); } } if( didit ) { sounds::sound( lockp, 1, sounds::sound_t::activity, _( "a soft chk." ) ); who.mod_moves( -90 ); } return didit; } bool doors::can_lock_door( const map &m, const Creature &who, const tripoint_bub_ms &lockp ) { int lockable = -1; if( const optional_vpart_position vp = m.veh_at( lockp ) ) { const vehicle *const veh = &vp->vehicle(); const optional_vpart_position &vp_here = m.veh_at( who.pos_bub() ); const bool inside_vehicle = vp_here && &vp->vehicle() == &vp_here->vehicle(); const int vpart = vp->part_index(); lockable = veh->next_part_to_lock( vpart, !inside_vehicle ); } return lockable >= 0; } // If you update this, look at doors::can_unlock_door too. bool doors::unlock_door( map &m, Creature &who, const tripoint_bub_ms &lockp ) { bool didit = false; if( const optional_vpart_position &vp = m.veh_at( lockp ) ) { vehicle *const veh = &vp->vehicle(); const int vpart = vp->part_index(); const optional_vpart_position &vp_here = m.veh_at( who.pos_bub() ); const bool inside_vehicle = vp_here && &vp->vehicle() == &vp_here->vehicle(); const int already_unlocked_part = veh->next_part_to_lock( vpart ); const int inside_unlockable = veh->next_part_to_unlock( vpart ); const int unlockable = veh->next_part_to_unlock( vpart, !inside_vehicle ); if( unlockable >= 0 ) { if( const Character *const ch = who.as_character() ) { if( !veh->handle_potential_theft( *ch ) ) { return false; } veh->unlock( unlockable ); who.add_msg_if_player( _( "You unlock the %1$s's %2$s." ), veh->name, veh->part( unlockable ).name() ); didit = true; } } else if( inside_unlockable >= 0 ) { who.add_msg_if_player( m_info, _( "That %s can only be unlocked from the inside." ), veh->part( inside_unlockable ).name() ); } else if( already_unlocked_part >= 0 ) { who.add_msg_if_player( m_info, _( "That %s is already unlocked." ), veh->part( already_unlocked_part ).name() ); } else { who.add_msg_if_player( m_info, _( "You cannot unlock the %s." ), veh->part( vpart ).name() ); } } if( didit ) { sounds::sound( lockp, 1, sounds::sound_t::activity, _( "a soft click." ) ); who.mod_moves( -90 ); } return didit; } bool doors::can_unlock_door( const map &m, const Creature &who, const tripoint_bub_ms &lockp ) { int unlockable = -1; if( const optional_vpart_position vp = m.veh_at( lockp ) ) { const vehicle *const veh = &vp->vehicle(); const optional_vpart_position &vp_here = m.veh_at( who.pos_bub() ); const bool inside_vehicle = vp_here && &vp->vehicle() == &vp_here->vehicle(); const int vpart = vp->part_index(); unlockable = veh->next_part_to_unlock( vpart, !inside_vehicle ); } return unlockable >= 0; }
412
0.972121
1
0.972121
game-dev
MEDIA
0.558487
game-dev
0.837411
1
0.837411
Fluorohydride/ygopro-scripts
2,755
c46425662.lua
--エレメントセイバー・ナル function c46425662.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(46425662,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1) e1:SetCost(c46425662.thcost) e1:SetTarget(c46425662.thtg) e1:SetOperation(c46425662.thop) c:RegisterEffect(e1) --att change local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(46425662,1)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_GRAVE) e2:SetCountLimit(1) e2:SetTarget(c46425662.atttg) e2:SetOperation(c46425662.attop) c:RegisterEffect(e2) end function c46425662.costfilter(c) return c:IsSetCard(0x400d) and c:IsType(TYPE_MONSTER) and c:IsAbleToGraveAsCost() end function c46425662.thcost(e,tp,eg,ep,ev,re,r,rp,chk) local fe=Duel.IsPlayerAffectedByEffect(tp,61557074) local loc=LOCATION_HAND if fe then loc=LOCATION_HAND+LOCATION_DECK end if chk==0 then return Duel.IsExistingMatchingCard(c46425662.costfilter,tp,loc,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local tc=Duel.SelectMatchingCard(tp,c46425662.costfilter,tp,loc,0,1,1,nil):GetFirst() if tc:IsLocation(LOCATION_DECK) then Duel.Hint(HINT_CARD,0,61557074) fe:UseCountLimit(tp) end Duel.SendtoGrave(tc,REASON_COST) end function c46425662.thfilter(c) return c:IsSetCard(0x400d,0x113) and c:IsType(TYPE_MONSTER) and not c:IsCode(46425662) and c:IsAbleToHand() end function c46425662.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c46425662.thfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c46425662.thfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c46425662.thfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c46425662.thop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end function c46425662.atttg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATTRIBUTE) local att=Duel.AnnounceAttribute(tp,1,ATTRIBUTE_ALL&~e:GetHandler():GetAttribute()) e:SetLabel(att) Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,e:GetHandler(),1,tp,LOCATION_GRAVE) end function c46425662.attop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CHANGE_ATTRIBUTE) e1:SetValue(e:GetLabel()) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) end end
412
0.942744
1
0.942744
game-dev
MEDIA
0.956671
game-dev
0.961839
1
0.961839
MATTYOneInc/AionEncomBase_Java8
4,812
AL-Game_SoloPlay_patches/data/scripts/system/handlers/quest/reshanta/_3736Glory_Against_The_8th.java
/* * =====================================================================================* * This file is part of Aion-Unique (Aion-Unique Home Software Development) * * Aion-Unique Development is a closed Aion Project that use Old Aion Project Base * * Like Aion-Lightning, Aion-Engine, Aion-Core, Aion-Extreme, Aion-NextGen, ArchSoft, * * Aion-Ger, U3J, Encom And other Aion project, All Credit Content * * That they make is belong to them/Copyright is belong to them. And All new Content * * that Aion-Unique make the copyright is belong to Aion-Unique * * You may have agreement with Aion-Unique Development, before use this Engine/Source * * You have agree with all of Term of Services agreement with Aion-Unique Development * * =====================================================================================* */ package quest.reshanta; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestDialog; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.utils.stats.AbyssRankEnum; /****/ /** MATTYOne DainAvenger Ptich /****/ public class _3736Glory_Against_The_8th extends QuestHandler { private final static int questId = 3736; private final static int REQUIRED_KILLS = 1; // summ of NPC needed to kill // NPC ID, that needs to kill private final static int[] mobs = {205395, 205396, 205397, 205398, 205399, 205400, 205401, 205402, 217476, 217477, 217478, 217479, 217480, 217481, 217482, 217483, 205404, 205405, 205406, 205407, 205408, 205409, 205410, 205411, 217485, 217486, 217487, 217488, 217489, 217490, 217491, 217492}; public _3736Glory_Against_The_8th() { super(questId); } @Override public void register() { qe.registerQuestNpc(278535).addOnQuestStart(questId); //Maius. qe.registerQuestNpc(278535).addOnTalkEvent(questId); //Maius. // register NPC in case to kill for (int mobId : mobs) { qe.registerQuestNpc(mobId).addOnKillEvent(questId); } } @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() != QuestStatus.START) { return false; } int targetId = env.getTargetId(); int killCount = qs.getQuestVarById(1); // Killed NPC boolean killCounted = false; // If we kill the opposite faction, then: if (env.getVisibleObject() instanceof Player && player.getWorldId() == 400010000) { Player target = (Player) env.getVisibleObject(); if ((env.getPlayer().getLevel() >= (target.getLevel() - 5)) && (env.getPlayer().getLevel() <= (target.getLevel() + 9))) { killCounted = true; } } // Check NPC ID from list in top for (int mobId : mobs) { if (targetId == mobId) { killCounted = true; break; } } if (killCounted) { killCount++; // Kill counter ++ if (killCount >= REQUIRED_KILLS) { killCount = REQUIRED_KILLS; // TODO qs.setQuestVarById(0, 1); qs.setStatus(QuestStatus.REWARD); // If we made MOBS_KILLS = 1 of NPC, then make status REWARD } qs.setQuestVarById(1, killCount); // Update variable updateQuestStatus(env); return true; } return false; } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); final QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (env.getTargetId() == 278535) { //Maius. switch (env.getDialog()) { case START_DIALOG: { return sendQuestDialog(env, 4762); } case ACCEPT_QUEST_SIMPLE: { return sendQuestStartDialog(env); } case REFUSE_QUEST_SIMPLE: { return closeDialogWindow(env); } } } if (qs == null || qs.getStatus() == QuestStatus.REWARD) { if (env.getTargetId() == 278535) { //Maius. if (env.getDialog() == QuestDialog.START_DIALOG) { return sendQuestDialog(env, 10002); } else if (env.getDialog() == QuestDialog.SELECT_REWARD) { return sendQuestDialog(env, 5); } else { return sendQuestEndDialog(env); } } } } return false; } }
412
0.951351
1
0.951351
game-dev
MEDIA
0.990979
game-dev
0.977602
1
0.977602
kiwec/neosu
4,366
src/App/Osu/UIRankingScreenInfoLabel.cpp
// Copyright (c) 2016, PG, All rights reserved. #include "UIRankingScreenInfoLabel.h" #include <algorithm> #include <chrono> #include <utility> #include "BeatmapInterface.h" #include "DatabaseBeatmap.h" #include "Engine.h" #include "Osu.h" #include "SString.h" #include "Font.h" UIRankingScreenInfoLabel::UIRankingScreenInfoLabel(float xPos, float yPos, float xSize, float ySize, UString name) : CBaseUIElement(xPos, yPos, xSize, ySize, std::move(name)) { this->font = osu->getSubTitleFont(); this->iMargin = 10; float globalScaler = 1.3f; this->fSubTitleScale = 0.6f * globalScaler; this->sArtist = "Artist"; this->sTitle = "Title"; this->sDiff = "Difficulty"; this->sMapper = "Mapper"; this->sPlayer = "Guest"; this->sDate = "?"; } void UIRankingScreenInfoLabel::draw() { // build strings UString titleText{this->sArtist}; titleText.append({" - "}); titleText.append(UString{this->sTitle}); titleText.append({" ["}); titleText.append(UString{this->sDiff}); titleText.append({"]"}); titleText = titleText.trim(); UString subTitleText{"Beatmap by "}; subTitleText.append(UString{this->sMapper}); subTitleText = subTitleText.trim(); const UString playerText{this->buildPlayerString()}; const float globalScale = std::max((this->vSize.y / this->getMinimumHeight()) * 0.741f, 1.0f); // draw title g->setColor(0xffffffff); g->pushTransform(); { const float scale = globalScale; g->scale(scale, scale); g->translate(this->vPos.x, this->vPos.y + this->font->getHeight() * scale); g->drawString(this->font, titleText); } g->popTransform(); // draw subtitle g->setColor(0xffffffff); g->pushTransform(); { const float scale = this->fSubTitleScale * globalScale; const float subTitleStringWidth = this->font->getStringWidth(subTitleText); g->translate((int)(-subTitleStringWidth / 2), (int)(this->font->getHeight() / 2)); g->scale(scale, scale); g->translate( (int)(this->vPos.x + (subTitleStringWidth / 2) * scale), (int)(this->vPos.y + this->font->getHeight() * globalScale + (this->font->getHeight() / 2) * scale + this->iMargin)); g->drawString(this->font, subTitleText); } g->popTransform(); // draw subsubtitle (player text + datetime) g->setColor(0xffffffff); g->pushTransform(); { const float scale = this->fSubTitleScale * globalScale; const float playerStringWidth = this->font->getStringWidth(playerText); g->translate((int)(-playerStringWidth / 2), (int)(this->font->getHeight() / 2)); g->scale(scale, scale); g->translate((int)(this->vPos.x + (playerStringWidth / 2) * scale), (int)(this->vPos.y + this->font->getHeight() * globalScale + this->font->getHeight() * scale + (this->font->getHeight() / 2) * scale + this->iMargin * 2)); g->drawString(this->font, playerText); } g->popTransform(); } void UIRankingScreenInfoLabel::setFromBeatmap(const DatabaseBeatmap *map) { this->setArtist(map->getArtist()); this->setTitle(map->getTitle()); this->setDiff(map->getDifficultyName()); this->setMapper(map->getCreator()); std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); this->sDate = std::ctime(&now_c); SString::trim_inplace(this->sDate); } UString UIRankingScreenInfoLabel::buildPlayerString() { UString playerString{"Played by "}; playerString.append(UString{this->sPlayer}); playerString.append({" on "}); playerString.append(UString{this->sDate}); return playerString.trim(); } float UIRankingScreenInfoLabel::getMinimumWidth() { float titleWidth = 0; float subTitleWidth = 0; float playerWidth = this->font->getStringWidth(this->buildPlayerString()) * this->fSubTitleScale; return std::max({titleWidth, subTitleWidth, playerWidth}); } float UIRankingScreenInfoLabel::getMinimumHeight() { float titleHeight = this->font->getHeight(); float subTitleHeight = this->font->getHeight() * this->fSubTitleScale; float playerHeight = this->font->getHeight() * this->fSubTitleScale; return titleHeight + subTitleHeight + playerHeight + this->iMargin * 2; }
412
0.542071
1
0.542071
game-dev
MEDIA
0.388804
game-dev
0.879356
1
0.879356
Squalr/Squally
2,673
Source/Entities/Platformer/Squally/Squally.cpp
#include "Squally.h" #include "cocos/base/CCEventCustom.h" #include "cocos/base/CCEventListenerCustom.h" #include "Engine/Events/SceneEvents.h" #include "Engine/Input/Input.h" #include "Engine/Save/SaveManager.h" #include "Events/PlatformerEvents.h" #include "Scenes/Platformer/Components/Entities/Inventory/EntityInventoryBehavior.h" #include "Scenes/Platformer/Inventory/EquipmentInventory.h" #include "Resources/EntityResources.h" #include "Resources/SoundResources.h" #include "Strings/Strings.h" using namespace cocos2d; const float Squally::SquallyScale = 0.92f; const std::string Squally::MapKey = "squally"; const std::string Squally::TeamTag = "squally-team"; const float Squally::HoverHeight = 112.0f; Squally* Squally::create() { ValueMap emptyProperties = ValueMap(); Squally* instance = new Squally(emptyProperties); instance->autorelease(); return instance; } Squally* Squally::deserialize(ValueMap& properties) { Squally* instance = new Squally(properties); instance->autorelease(); return instance; } Squally::Squally(ValueMap& properties) : super(properties, Squally::MapKey, EntityResources::Squally_Animations, EntityResources::Squally_Emblem, CSize(128.0f, 128.0f), Squally::SquallyScale, Squally::HoverHeight) { } Squally::~Squally() { } void Squally::onEnter() { super::onEnter(); } void Squally::onEnterTransitionDidFinish() { super::onEnterTransitionDidFinish(); } void Squally::initializePositions() { super::initializePositions(); } void Squally::initializeListeners() { super::initializeListeners(); this->addEventListenerIgnorePause(EventListenerCustom::create(SceneEvents::EventBeforeSceneChange, [=](EventCustom* eventCustom) { PlatformerEvents::TriggerHudUntrackEntity(PlatformerEvents::HudTrackEntityArgs(this)); })); } void Squally::update(float dt) { super::update(dt); } Vec2 Squally::getButtonOffset() { return Vec2(0, 72.0f); } cocos2d::Vec2 Squally::getDialogueOffset() { return Vec2(0.0f, 32.0f); } LocalizedString* Squally::getEntityName() { return Strings::Platformer_Entities_Names_Squally::create(); } std::string Squally::getSwimAnimation() { std::string swimAnimation = super::getSwimAnimation(); this->getComponent<EntityInventoryBehavior>([&](EntityInventoryBehavior* entityInventoryBehavior) { if (entityInventoryBehavior->getEquipmentInventory()->getWeapon() != nullptr) { swimAnimation = "SwimWithWeapon"; } else { swimAnimation = "Swim"; } }); return swimAnimation; } std::string Squally::getJumpSound() { return SoundResources::Platformer_Entities_Generic_Movement_Jump3; } std::vector<std::string> Squally::getWalkSounds() { return { }; }
412
0.79834
1
0.79834
game-dev
MEDIA
0.87997
game-dev
0.717322
1
0.717322
reinforcement-learning-kr/Unity_ML_Agents_2.0
2,189
unity_project/GridWorld/Packages/com.unity.ml-agents/Runtime/Sensors/OneHotGridSensor.cs
using UnityEngine; namespace Unity.MLAgents.Sensors { /// <summary> /// Grid-based sensor with one-hot observations. /// </summary> public class OneHotGridSensor : GridSensorBase { /// <summary> /// Create a OneHotGridSensor with the specified configuration. /// </summary> /// <param name="name">The sensor name</param> /// <param name="cellScale">The scale of each cell in the grid</param> /// <param name="gridSize">Number of cells on each side of the grid</param> /// <param name="detectableTags">Tags to be detected by the sensor</param> /// <param name="compression">Compression type</param> public OneHotGridSensor( string name, Vector3 cellScale, Vector3Int gridSize, string[] detectableTags, SensorCompressionType compression ) : base(name, cellScale, gridSize, detectableTags, compression) { } /// <inheritdoc/> protected override int GetCellObservationSize() { return DetectableTags == null ? 0 : DetectableTags.Length; } /// <inheritdoc/> protected override bool IsDataNormalized() { return true; } /// <inheritdoc/> protected internal override ProcessCollidersMethod GetProcessCollidersMethod() { return ProcessCollidersMethod.ProcessClosestColliders; } /// <summary> /// Get the one-hot representation of the detected game object's tag. /// </summary> /// <param name="detectedObject">The game object that was detected within a certain cell</param> /// <param name="tagIndex">The index of the detectedObject's tag in the DetectableObjects list</param> /// <param name="dataBuffer">The buffer to write the observation values. /// The buffer size is configured by <seealso cref="GetCellObservationSize"/>. /// </param> protected override void GetObjectData(GameObject detectedObject, int tagIndex, float[] dataBuffer) { dataBuffer[tagIndex] = 1; } } }
412
0.879811
1
0.879811
game-dev
MEDIA
0.710568
game-dev
0.784346
1
0.784346
11011010/BFA-Frankenstein-Core
19,023
src/server/scripts/Zandalar/TempleOfSethraliss/boss_adderis_and_aspix.cpp
#include "ScriptMgr.h" #include "GameObject.h" #include "GameObjectAI.h" #include "temple_of_sethraliss.h" enum Spells { SPELL_LIGHTNING_SHIELD_AURA = 263246, SPELL_STATIC_SHOCK = 263257, SPELL_JOLT = 263318, SPELL_CONDUCTION = 263371, SPELL_GUST = 263775, SPELL_CYCLONE_STRIKE_CAST = 261773, SPELL_CYCLONE_STRIKE_DMG = 263573, SPELL_CYCLONE_STRIKE_AT = 263325, SPELL_ARC_DASH = 263425, SPELL_ARCING_BLADE = 263234, SPELL_A_PEAR_OF_THUNDER = 263365 }; enum Events { EVENT_CHECK_ENERGY = 1, EVENT_JOLT, EVENT_CONDUCTION, EVENT_STATIC_SHOCK, EVENT_CYCLONE_STRIKE, EVENT_A_PEAL_OF_THUNDER, EVENT_ARC_DASH, EVENT_GUST, EVENT_ARCING_BLADE, EVENT_GALE_FORCE, }; enum Timers { TIMER_CHECK_ENERGY = 3 * IN_MILLISECONDS, TIMER_GUST = 10 * IN_MILLISECONDS, TIMER_JOLT = 5 * IN_MILLISECONDS, TIMER_CONDUCTION = 15 * IN_MILLISECONDS, TIMER_CYCLONE_STRIKE = 25 * IN_MILLISECONDS, TIMER_A_PEAL_OF_THUNDER = 10 * IN_MILLISECONDS, TIMER_ARCING_BLADE = 12 * IN_MILLISECONDS, TIMER_GALE_FORCE = 22 * IN_MILLISECONDS, }; enum Actions { ACTION_SHIELDED = 1, ACTION_FINISH_OTHER, }; enum Creatures { BOSS_ADDERIS = 133379, BOSS_ASPIX = 133944, }; const Position centerPos = { 3344.53f, 3148.79f, 88.43f }; //45y uint8 AdderisAndAspix(InstanceScript* instance, Creature* me) { uint8 count = 0; if (!instance || !me) return count; Creature* adderis = instance->GetCreature(BOSS_ADDERIS); if (adderis && adderis->IsAlive()) ++count; Creature* aspix = instance->GetCreature(BOSS_ASPIX); if (aspix && aspix->IsAlive()) ++count; return count; } // gale force forcemovement #define AGGRO_ASPIX "None can stand against our empire!" #define SHIELD_ADDERIS "Severed!" #define SHIELD_ASPIX "Break them, Adderis!" #define ARCING_SLASH_ADDERIS "Arcing slash!" #define ASPIX_DEATH "What will become... of the empire..." #define ADDERIS_DEATH "The sands...take me..." class bfa_boss_adderis : public CreatureScript { public: bfa_boss_adderis() : CreatureScript("bfa_boss_adderis") { } struct bfa_boss_adderis_AI : public BossAI { bfa_boss_adderis_AI(Creature* creature) : BossAI(creature, DATA_ADDERIS_AND_ASPIX) { } private: bool shielded; bool castSpecial; void Reset() override { events.Reset(); castSpecial = false; shielded = false; me->SetPowerType(POWER_ENERGY); me->SetMaxPower(POWER_ENERGY, 100); me->SetPower(POWER_ENERGY, 0); RespawnAspixAtWipe(); me->RemoveUnitFlag2(UNIT_FLAG2_REGENERATE_POWER); } void SelectSoundAndText(Creature* me, uint32 selectedTextSound = 0) { if (!me) return; if (me) { switch (selectedTextSound) { case 1: me->Yell(SHIELD_ADDERIS, LANG_UNIVERSAL, NULL); break; case 2: me->Yell(ADDERIS_DEATH, LANG_UNIVERSAL, NULL); break; case 3: me->Yell(ARCING_SLASH_ADDERIS, LANG_UNIVERSAL, NULL); break; } } } Creature* GetAspix() { return me->FindNearestCreature(BOSS_ASPIX, 200.0f, true); } Creature* GetAdderisDead() { return me->FindNearestCreature(BOSS_ADDERIS, 200.0f, false); } Creature* GetAspixDead() { return me->FindNearestCreature(BOSS_ASPIX, 200.0f, false); } void RespawnAspixAtWipe() { if (Creature* aspix = GetAspix()) aspix->Respawn(); } void DoAction(int32 action) override { switch (action) { case ACTION_FINISH_OTHER: instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); if (GameObject* adderisAspixDoor = me->FindNearestGameObject(GO_ADDERIS_ASPIX_EXIT, 100.0f)) adderisAspixDoor->SetGoState(GO_STATE_ACTIVE); break; case ACTION_SHIELDED: { SelectSoundAndText(me, 1); std::ostringstream str; str << "Adderis gains a |cFFF00000|h[Lightning Shield]|h|r !"; me->TextEmote(str.str().c_str()); me->AddAura(SPELL_LIGHTNING_SHIELD_AURA, me); break; } } } void JustDied(Unit*) override { SelectSoundAndText(me, 2); if (instance) { switch (AdderisAndAspix(instance, me)) { case 1: me->AddLootRecipient(nullptr); break; case 0: if (Creature* aspix = GetAspixDead()) aspix->AI()->DoAction(ACTION_FINISH_OTHER); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); break; } } } void EnterEvadeMode(EvadeReason why) override { _DespawnAtEvade(15); } void DamageTaken(Unit* at, uint32& damage) override { if (me->HasAura(SPELL_LIGHTNING_SHIELD_AURA)) damage = 0; } void EnterCombat(Unit*) override { if (Creature* aspix = GetAspix()) aspix->SetInCombatWithZone(); me->SetPower(POWER_ENERGY, 0); _EnterCombat(); events.ScheduleEvent(EVENT_CHECK_ENERGY, TIMER_CHECK_ENERGY); events.ScheduleEvent(EVENT_GUST, TIMER_GUST); if (IsHeroic() || IsMythic()) events.ScheduleEvent(EVENT_ARCING_BLADE, TIMER_ARCING_BLADE); } void HandleArcDash() { std::ostringstream str; str << "Adderis begins his |cFFF00000|h[Arc Dash]|h|r !"; me->TextEmote(str.str().c_str()); SelectSoundAndText(me, 3); std::list<Player*> playerList; me->GetPlayerListInGrid(playerList, 100.0f); if (playerList.size()) { if (playerList.size() > 1) playerList.resize(1); for (auto player : playerList) { me->GetMotionMaster()->MoveCharge(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), 40.0f); me->CastSpell(player, SPELL_ARC_DASH, true); } } } void UpdateAI(uint32 diff) override { events.Update(diff); if (!UpdateVictim()) return; if (me->HasAura(SPELL_LIGHTNING_SHIELD_AURA)) { shielded = true; me->AddUnitState(UNIT_STATE_ROOT); } else { shielded = false; me->ClearUnitState(UNIT_STATE_ROOT); } if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CHECK_ENERGY: { if (shielded) { if (me->GetPower(POWER_ENERGY) == 100) { if (Creature* aspix = GetAspix()) { aspix->AI()->DoAction(ACTION_SHIELDED); me->RemoveAura(SPELL_LIGHTNING_SHIELD_AURA); } for (uint8 i = 0; i < 3; ++i) HandleArcDash(); me->SetPower(POWER_ENERGY, 0); castSpecial = false; } if (me->GetPower(POWER_ENERGY) >= 50 && !castSpecial) { castSpecial = true; events.ScheduleEvent(EVENT_A_PEAL_OF_THUNDER, TIMER_A_PEAL_OF_THUNDER); } me->SetPower(POWER_ENERGY, me->GetPower(POWER_ENERGY) + urand(1, 5)); } events.ScheduleEvent(EVENT_CHECK_ENERGY, TIMER_CHECK_ENERGY); break; } case EVENT_A_PEAL_OF_THUNDER: { if (shielded) { std::list<Player*> playerList; me->GetPlayerListInGrid(playerList, 100.0f); if (playerList.size()) { if (playerList.size() > 1) playerList.resize(1); for (auto player : playerList) { me->NearTeleportTo(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), me->GetOrientation(), false); me->CastSpell(player, SPELL_A_PEAR_OF_THUNDER); } } } events.ScheduleEvent(EVENT_A_PEAL_OF_THUNDER, TIMER_A_PEAL_OF_THUNDER); break; } case EVENT_GUST: if (!shielded) if (Unit* target = me->GetVictim()) me->CastSpell(target, SPELL_GUST); events.ScheduleEvent(EVENT_GUST, TIMER_GUST); break; case EVENT_ARCING_BLADE: if (Unit* target = me->GetVictim()) me->CastSpell(target, SPELL_ARCING_BLADE); events.ScheduleEvent(EVENT_ARCING_BLADE, TIMER_ARCING_BLADE); break; } } } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_boss_adderis_AI(creature); } }; class bfa_boss_aspix : public CreatureScript { public: bfa_boss_aspix() : CreatureScript("bfa_boss_aspix") { } struct bfa_boss_aspix_AI : public BossAI { bfa_boss_aspix_AI(Creature* creature) : BossAI(creature, DATA_ADDERIS_AND_ASPIX) { } private: bool shielded; bool castSpecial; void Reset() override { shielded = false; castSpecial = false; events.Reset(); me->SetPowerType(POWER_ENERGY); RespawnAdderisAtWipe(); me->SetMaxPower(POWER_ENERGY, 100); me->SetPower(POWER_ENERGY, 0); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); me->RemoveUnitFlag2(UNIT_FLAG2_REGENERATE_POWER); } void SelectSoundAndText(Creature* me, uint32 selectedTextSound = 0) { if (!me) return; if (me) { switch (selectedTextSound) { case 1: me->Yell(SHIELD_ASPIX, LANG_UNIVERSAL, NULL); break; case 2: me->Yell(ASPIX_DEATH, LANG_UNIVERSAL, NULL); break; case 3: me->Yell(AGGRO_ASPIX, LANG_UNIVERSAL, NULL); break; } } } Creature* GetAdderis() { return me->FindNearestCreature(BOSS_ADDERIS, 200.0f, true); } Creature* GetAdderisDead() { return me->FindNearestCreature(BOSS_ADDERIS, 200.0f, false); } Creature* GetAspixDead() { return me->FindNearestCreature(BOSS_ASPIX, 200.0f, false); } void RespawnAdderisAtWipe() { if (Creature* adderis = GetAdderisDead()) adderis->Respawn(); } void DoAction(int32 action) override { switch (action) { case ACTION_FINISH_OTHER: instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); if (GameObject* adderisAspixDoor = me->FindNearestGameObject(GO_ADDERIS_ASPIX_EXIT, 100.0f)) adderisAspixDoor->SetGoState(GO_STATE_ACTIVE); break; case ACTION_SHIELDED: { std::ostringstream str; str << "Aspix gains a |cFFF00000|h[Lightning Shield]|h|r !"; me->TextEmote(str.str().c_str()); SelectSoundAndText(me, 1); me->AddAura(SPELL_LIGHTNING_SHIELD_AURA, me); break; } } } void JustDied(Unit*) override { SelectSoundAndText(me, 2); if (instance) { switch (AdderisAndAspix(instance, me)) { case 1: me->AddLootRecipient(nullptr); break; case 0: if (Creature* adderis = GetAdderisDead()) adderis->AI()->DoAction(ACTION_FINISH_OTHER); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); break; } } } void EnterEvadeMode(EvadeReason w) override { _DespawnAtEvade(15); } void DamageTaken(Unit* attacker, uint32& damage) override { if (me->HasAura(SPELL_LIGHTNING_SHIELD_AURA)) damage = 0; } void EnterCombat(Unit*) override { SelectSoundAndText(me, 3); if (Creature* adderis = GetAdderis()) adderis->SetInCombatWithZone(); me->CastSpell(me, SPELL_LIGHTNING_SHIELD_AURA, true); me->SetPower(POWER_ENERGY, 0); _EnterCombat(); events.ScheduleEvent(EVENT_CHECK_ENERGY, TIMER_CHECK_ENERGY); events.ScheduleEvent(EVENT_CYCLONE_STRIKE, TIMER_CYCLONE_STRIKE); events.ScheduleEvent(EVENT_JOLT, TIMER_JOLT); if (IsHeroic() || IsMythic()) events.ScheduleEvent(EVENT_GALE_FORCE, TIMER_GALE_FORCE); } void UpdateAI(uint32 diff) override { events.Update(diff); if (!UpdateVictim()) return; if (me->HasAura(SPELL_LIGHTNING_SHIELD_AURA)) { shielded = true; me->AddUnitState(UNIT_STATE_ROOT); } else { shielded = false; me->ClearUnitState(UNIT_STATE_ROOT); } if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_GALE_FORCE: events.ScheduleEvent(EVENT_GALE_FORCE, TIMER_GALE_FORCE); break; case EVENT_CHECK_ENERGY: { if (shielded) { if (me->GetPower(POWER_ENERGY) == 100) { if (Creature* adderis = GetAdderis()) { adderis->AI()->DoAction(ACTION_SHIELDED); me->RemoveAura(SPELL_LIGHTNING_SHIELD_AURA); } me->CastSpell(me, SPELL_STATIC_SHOCK); me->SetPower(POWER_ENERGY, 0); castSpecial = false; } if (me->GetPower(POWER_ENERGY) >= 50 && !castSpecial) { castSpecial = true; events.ScheduleEvent(EVENT_CONDUCTION, TIMER_CONDUCTION); } me->SetPower(POWER_ENERGY, me->GetPower(POWER_ENERGY) + urand(1, 5)); } events.ScheduleEvent(EVENT_CHECK_ENERGY, TIMER_CHECK_ENERGY); break; } case EVENT_CONDUCTION: if (shielded) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) me->CastSpell(target, SPELL_CONDUCTION); events.ScheduleEvent(EVENT_CONDUCTION, TIMER_CONDUCTION); break; case EVENT_CYCLONE_STRIKE: if (!shielded) me->CastSpell(me, SPELL_CYCLONE_STRIKE_CAST); events.ScheduleEvent(EVENT_CYCLONE_STRIKE, TIMER_CYCLONE_STRIKE); break; case EVENT_JOLT: if (shielded) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) me->CastSpell(target, SPELL_JOLT); events.ScheduleEvent(EVENT_JOLT, TIMER_JOLT); break; } } } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_boss_aspix_AI(creature); } }; // 263234 class bfa_spell_arcing_blade : public SpellScriptLoader { public: bfa_spell_arcing_blade() : SpellScriptLoader("bfa_spell_arcing_blade") { } class bfa_spell_arcing_blade_SpellScript : public SpellScript { PrepareSpellScript(bfa_spell_arcing_blade_SpellScript); uint8 targetsPlayers; bool Load() { targetsPlayers = 1; return true; } void CheckTargets(std::list<WorldObject*>& targets) { targetsPlayers = targets.size(); } void RecalculateDamage(SpellEffIndex effIndex) { SetHitDamage(GetHitDamage() / targetsPlayers); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(bfa_spell_arcing_blade_SpellScript::CheckTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(bfa_spell_arcing_blade_SpellScript::RecalculateDamage, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); } }; SpellScript* GetSpellScript() const { return new bfa_spell_arcing_blade_SpellScript(); } }; void AddSC_boss_adderis_and_aspix() { new bfa_boss_adderis(); new bfa_boss_aspix(); new bfa_spell_arcing_blade(); }
412
0.991307
1
0.991307
game-dev
MEDIA
0.982067
game-dev
0.998448
1
0.998448
magefree/mage
4,296
Mage.Sets/src/mage/cards/f/FrodoSauronsBane.java
package mage.cards.f; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.DealsCombatDamageToAPlayerTriggeredAbility; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.condition.Condition; import mage.abilities.condition.common.SourceHasSubtypeCondition; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.decorator.ConditionalOneShotEffect; import mage.abilities.effects.common.AddContinuousEffectToGame; import mage.abilities.effects.common.LoseGameTargetPlayerEffect; import mage.abilities.effects.common.continuous.AddCardSubTypeSourceEffect; import mage.abilities.effects.common.continuous.GainAbilitySourceEffect; import mage.abilities.effects.common.continuous.SetBasePowerToughnessSourceEffect; import mage.abilities.effects.keyword.TheRingTemptsYouEffect; import mage.abilities.keyword.LifelinkAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.game.Game; import mage.watchers.common.TemptedByTheRingWatcher; import java.util.UUID; /** * @author TheElk801 */ public final class FrodoSauronsBane extends CardImpl { private static final Condition condition1 = new SourceHasSubtypeCondition(SubType.CITIZEN); private static final Condition condition2 = new SourceHasSubtypeCondition(SubType.SCOUT); public FrodoSauronsBane(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{W}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.HALFLING); this.subtype.add(SubType.CITIZEN); this.power = new MageInt(1); this.toughness = new MageInt(2); // {W/B}{W/B}: If Frodo, Sauron's Bane is a Citizen, it becomes a Halfling Scout with base power and toughness 2/3 and lifelink. this.addAbility(new SimpleActivatedAbility( new ConditionalOneShotEffect(new AddContinuousEffectToGame( new AddCardSubTypeSourceEffect(Duration.Custom, SubType.HALFLING, SubType.SCOUT), new SetBasePowerToughnessSourceEffect(2, 3, Duration.Custom), new GainAbilitySourceEffect(LifelinkAbility.getInstance(), Duration.Custom) ), condition1, "if {this} is a Citizen, it becomes a Halfling Scout with base power and toughness 2/3 and lifelink"), new ManaCostsImpl<>("{W/B}{W/B}") )); // {B}{B}{B}: If Frodo is a Scout, it becomes a Halfling Rogue with "Whenever this creature deals combat damage to a player, that player loses the game if the Ring has tempted you four or more times this game. Otherwise, the Ring tempts you." this.addAbility(new SimpleActivatedAbility(new ConditionalOneShotEffect( new AddContinuousEffectToGame( new AddCardSubTypeSourceEffect(Duration.Custom, SubType.HALFLING, SubType.ROGUE), new GainAbilitySourceEffect(new DealsCombatDamageToAPlayerTriggeredAbility( new ConditionalOneShotEffect( new LoseGameTargetPlayerEffect(), new TheRingTemptsYouEffect(), FrodoSauronsBaneCondition.instance, "that player loses the game " + "if the Ring has tempted you four or more times this game. Otherwise, the Ring tempts you" ), false, true), Duration.Custom) ), condition2, "if {this} is a Scout, it becomes a Halfling Rogue with " + "\"Whenever this creature deals combat damage to a player, that player loses the game " + "if the Ring has tempted you four or more times this game. Otherwise, the Ring tempts you.\"" ), new ManaCostsImpl<>("{B}{B}{B}"))); } private FrodoSauronsBane(final FrodoSauronsBane card) { super(card); } @Override public FrodoSauronsBane copy() { return new FrodoSauronsBane(this); } } enum FrodoSauronsBaneCondition implements Condition { instance; @Override public boolean apply(Game game, Ability source) { return TemptedByTheRingWatcher.getCount(source.getControllerId(), game) >= 4; } }
412
0.969374
1
0.969374
game-dev
MEDIA
0.8501
game-dev
0.998361
1
0.998361
CypherCore/CypherCore
14,394
Source/Game/Weather/WeatherManager.cs
// Copyright (c) CypherCore <http://github.com/CypherCore> All rights reserved. // Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE file in the project root for full license information. using Framework.Database; using Game.Entities; using Game.Networking.Packets; using System.Collections.Generic; namespace Game { public class WeatherManager : Singleton<WeatherManager> { WeatherManager() { } public void LoadWeatherData() { uint oldMSTime = Time.GetMSTime(); uint count = 0; SQLResult result = DB.World.Query("SELECT zone, spring_rain_chance, spring_snow_chance, spring_storm_chance," + "summer_rain_chance, summer_snow_chance, summer_storm_chance, fall_rain_chance, fall_snow_chance, fall_storm_chance," + "winter_rain_chance, winter_snow_chance, winter_storm_chance, ScriptName FROM game_weather"); if (result.IsEmpty()) { Log.outInfo(LogFilter.ServerLoading, "Loaded 0 weather definitions. DB table `game_weather` is empty."); return; } do { uint zone_id = result.Read<uint>(0); WeatherData wzc = new(); for (byte season = 0; season < 4; ++season) { wzc.data[season].rainChance = result.Read<byte>(season * (4 - 1) + 1); wzc.data[season].snowChance = result.Read<byte>(season * (4 - 1) + 2); wzc.data[season].stormChance = result.Read<byte>(season * (4 - 1) + 3); if (wzc.data[season].rainChance > 100) { wzc.data[season].rainChance = 25; Log.outError(LogFilter.Sql, "Weather for zone {0} season {1} has wrong rain chance > 100%", zone_id, season); } if (wzc.data[season].snowChance > 100) { wzc.data[season].snowChance = 25; Log.outError(LogFilter.Sql, "Weather for zone {0} season {1} has wrong snow chance > 100%", zone_id, season); } if (wzc.data[season].stormChance > 100) { wzc.data[season].stormChance = 25; Log.outError(LogFilter.Sql, "Weather for zone {0} season {1} has wrong storm chance > 100%", zone_id, season); } } wzc.ScriptId = Global.ObjectMgr.GetScriptId(result.Read<string>(13)); _weatherData[zone_id] = wzc; ++count; } while (result.NextRow()); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} weather definitions in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime)); } public WeatherData GetWeatherData(uint zone_id) { return _weatherData.LookupByKey(zone_id); } Dictionary<uint, WeatherData> _weatherData = new(); } public class Weather { public Weather(uint zoneId, WeatherData weatherChances) { m_zone = zoneId; m_weatherChances = weatherChances; m_timer.SetInterval(10 * Time.Minute * Time.InMilliseconds); m_type = WeatherType.Fine; m_intensity = 0; //Log.outInfo(LogFilter.General, "WORLD: Starting weather system for zone {0} (change every {1} minutes).", m_zone, (m_timer.GetInterval() / (Time.Minute * Time.InMilliseconds))); } public bool Update(uint diff) { if (m_timer.GetCurrent() >= 0) m_timer.Update(diff); else m_timer.SetCurrent(0); // If the timer has passed, ReGenerate the weather if (m_timer.Passed()) { m_timer.Reset(); // update only if Regenerate has changed the weather if (ReGenerate()) { // Weather will be removed if not updated (no players in zone anymore) if (!UpdateWeather()) return false; } } Global.ScriptMgr.OnWeatherUpdate(this, diff); return true; } public bool ReGenerate() { if (m_weatherChances == null) { m_type = WeatherType.Fine; m_intensity = 0.0f; return false; } // Weather statistics: // 30% - no change // 30% - weather gets better (if not fine) or change weather type // 30% - weather worsens (if not fine) // 10% - radical change (if not fine) uint u = RandomHelper.URand(0, 99); if (u < 30) return false; // remember old values WeatherType old_type = m_type; float old_intensity = m_intensity; long gtime = GameTime.GetGameTime(); var ltime = Time.UnixTimeToDateTime(gtime).ToLocalTime(); uint season = (uint)((ltime.DayOfYear - 78 + 365) / 91) % 4; string[] seasonName = { "spring", "summer", "fall", "winter" }; Log.outInfo(LogFilter.Server, "Generating a change in {0} weather for zone {1}.", seasonName[season], m_zone); if ((u < 60) && (m_intensity < 0.33333334f)) // Get fair { m_type = WeatherType.Fine; m_intensity = 0.0f; } if ((u < 60) && (m_type != WeatherType.Fine)) // Get better { m_intensity -= 0.33333334f; return true; } if ((u < 90) && (m_type != WeatherType.Fine)) // Get worse { m_intensity += 0.33333334f; return true; } if (m_type != WeatherType.Fine) { // Radical change: // if light . heavy // if medium . change weather type // if heavy . 50% light, 50% change weather type if (m_intensity < 0.33333334f) { m_intensity = 0.9999f; // go nuts return true; } else { if (m_intensity > 0.6666667f) { // Severe change, but how severe? uint rnd = RandomHelper.URand(0, 99); if (rnd < 50) { m_intensity -= 0.6666667f; return true; } } m_type = WeatherType.Fine; // clear up m_intensity = 0; } } // At this point, only weather that isn't doing anything remains but that have weather data uint chance1 = m_weatherChances.data[season].rainChance; uint chance2 = chance1 + m_weatherChances.data[season].snowChance; uint chance3 = chance2 + m_weatherChances.data[season].stormChance; uint rn = RandomHelper.URand(1, 100); if (rn <= chance1) m_type = WeatherType.Rain; else if (rn <= chance2) m_type = WeatherType.Snow; else if (rn <= chance3) m_type = WeatherType.Storm; else m_type = WeatherType.Fine; // New weather statistics (if not fine): // 85% light // 7% medium // 7% heavy // If fine 100% sun (no fog) if (m_type == WeatherType.Fine) { m_intensity = 0.0f; } else if (u < 90) { m_intensity = RandomHelper.NextSingle() * 0.3333f; } else { // Severe change, but how severe? rn = RandomHelper.URand(0, 99); if (rn < 50) m_intensity = RandomHelper.NextSingle() * 0.3333f + 0.3334f; else m_intensity = RandomHelper.NextSingle() * 0.3333f + 0.6667f; } // return true only in case weather changes return m_type != old_type || m_intensity != old_intensity; } public void SendWeatherUpdateToPlayer(Player player) { WeatherPkt weather = new(GetWeatherState(), m_intensity); player.SendPacket(weather); } public static void SendFineWeatherUpdateToPlayer(Player player) { player.SendPacket(new WeatherPkt(WeatherState.Fine)); } public bool UpdateWeather() { Player player = Global.WorldMgr.FindPlayerInZone(m_zone); if (player == null) return false; // Send the weather packet to all players in this zone if (m_intensity >= 1) m_intensity = 0.9999f; else if (m_intensity < 0) m_intensity = 0.0001f; WeatherState state = GetWeatherState(); WeatherPkt weather = new(state, m_intensity); //- Returns false if there were no players found to update if (!Global.WorldMgr.SendZoneMessage(m_zone, weather)) return false; // Log the event string wthstr; switch (state) { case WeatherState.Fog: wthstr = "fog"; break; case WeatherState.LightRain: wthstr = "light rain"; break; case WeatherState.MediumRain: wthstr = "medium rain"; break; case WeatherState.HeavyRain: wthstr = "heavy rain"; break; case WeatherState.LightSnow: wthstr = "light snow"; break; case WeatherState.MediumSnow: wthstr = "medium snow"; break; case WeatherState.HeavySnow: wthstr = "heavy snow"; break; case WeatherState.LightSandstorm: wthstr = "light sandstorm"; break; case WeatherState.MediumSandstorm: wthstr = "medium sandstorm"; break; case WeatherState.HeavySandstorm: wthstr = "heavy sandstorm"; break; case WeatherState.Thunders: wthstr = "thunders"; break; case WeatherState.BlackRain: wthstr = "blackrain"; break; case WeatherState.Fine: default: wthstr = "fine"; break; } Log.outInfo(LogFilter.Server, "Change the weather of zone {0} to {1}.", m_zone, wthstr); Global.ScriptMgr.OnWeatherChange(this, state, m_intensity); return true; } public void SetWeather(WeatherType type, float grade) { if (m_type == type && m_intensity == grade) return; m_type = type; m_intensity = grade; UpdateWeather(); } public WeatherState GetWeatherState() { if (m_intensity < 0.27f) return WeatherState.Fine; switch (m_type) { case WeatherType.Rain: if (m_intensity < 0.40f) return WeatherState.LightRain; else if (m_intensity < 0.70f) return WeatherState.MediumRain; else return WeatherState.HeavyRain; case WeatherType.Snow: if (m_intensity < 0.40f) return WeatherState.LightSnow; else if (m_intensity < 0.70f) return WeatherState.MediumSnow; else return WeatherState.HeavySnow; case WeatherType.Storm: if (m_intensity < 0.40f) return WeatherState.LightSandstorm; else if (m_intensity < 0.70f) return WeatherState.MediumSandstorm; else return WeatherState.HeavySandstorm; case WeatherType.BlackRain: return WeatherState.BlackRain; case WeatherType.Thunders: return WeatherState.Thunders; case WeatherType.Fine: default: return WeatherState.Fine; } } public uint GetZone() { return m_zone; } public uint GetScriptId() { return m_weatherChances.ScriptId; } uint m_zone; WeatherType m_type; float m_intensity; IntervalTimer m_timer = new(); WeatherData m_weatherChances; } public class WeatherData { public WeatherSeasonChances[] data = new WeatherSeasonChances[4]; public uint ScriptId; } public struct WeatherSeasonChances { public uint rainChance; public uint snowChance; public uint stormChance; } public enum WeatherState { Fine = 0, Fog = 1, // Used in some instance encounters. Drizzle = 2, LightRain = 3, MediumRain = 4, HeavyRain = 5, LightSnow = 6, MediumSnow = 7, HeavySnow = 8, LightSandstorm = 22, MediumSandstorm = 41, HeavySandstorm = 42, Thunders = 86, BlackRain = 90, BlackSnow = 106 } public enum WeatherType { Fine = 0, Rain = 1, Snow = 2, Storm = 3, Thunders = 86, BlackRain = 90 } }
412
0.539868
1
0.539868
game-dev
MEDIA
0.524016
game-dev,networking
0.993225
1
0.993225
codergautam/swordbattle.io
4,504
server/src/game/components/LevelSystem.js
const Types = require('../Types'); const { swingDurationIncrease, maxSwingDuration } = require('../../config').sword; var levels = [ {'coins': 0, 'scale': 0}, {'coins': 5, 'scale': 1}, {'coins': 15, 'scale': 2}, {'coins': 25, 'scale': 4}, {'coins': 50, 'scale': 8}, {'coins': 75, 'scale': 10}, {'coins': 100, 'scale': 11}, {'coins': 200, 'scale': 12}, {'coins': 300, 'scale': 13}, {'coins': 400, 'scale': 15}, {'coins': 500, 'scale': 20}, {'coins': 700, 'scale': 21}, {'coins': 900, 'scale': 23}, {'coins': 1000, 'scale': 24}, {'coins': 1500, 'scale': 27}, {'coins': 2000, 'scale': 30}, {'coins': 2500, 'scale': 31}, {'coins': 3000, 'scale': 32}, {'coins': 3500, 'scale': 34}, {'coins': 4000, 'scale': 36}, {'coins': 4500, 'scale': 36}, {'coins': 5000, 'scale': 38}, {'coins': 7500, 'scale': 40}, {'coins': 9000, 'scale': 41}, {'coins': 10000, 'scale': 42}, {'coins': 15000, 'scale': 43}, {'coins': 20000, 'scale': 44}, {'coins': 30000, 'scale': 45}, {'coins': 50000, 'scale': 46}, {'coins': 75000, 'scale': 47}, {'coins': 100000, 'scale': 48}, {'coins': 150000, 'scale': 49}, {'coins': 200000, 'scale': 49}, {'coins': 300000, 'scale': 50}, {'coins': 400000, 'scale': 51}, {'coins': 500000, 'scale': 51}, {'coins': 650000, 'scale': 52}, {'coins': 800000, 'scale': 53}, {'coins': 1000000, 'scale': 54}, {'coins': 1500000, 'scale': 55}, {'coins': 2000000, 'scale': 55} ]; class LevelSystem { constructor(player) { this.player = player; this.level = 1; this.maxLevel = levels.length-1; this.coins = 0; this.previousLevelCoins = 0; this.nextLevelCoins = levels[this.level].coins; this.upgradePoints = 0; this.buffs = { [Types.Buff.Speed]: { level: 0, max: 10, step: 0.03, buyable: true, }, [Types.Buff.Size]: { level: 0, max: levels[this.maxLevel].scale, step: 0.04, buyable: false, }, [Types.Buff.Health]: { level: 0, step: 0.06, max: 10, buyable: true, }, [Types.Buff.Regeneration]: { level: 0, step: 0.075, max: 10, buyable: true, }, [Types.Buff.Damage]: { level: 0, step: 0.04, max: 10, buyable: true, }, } } addCoins(coins) { this.coins += coins; while (this.coins >= this.nextLevelCoins) { if (this.level === this.maxLevel) break; this.levelUp(); } } canBuff(type) { const buff = this.buffs[type]; return this.upgradePoints > 0 && buff && buff.level < buff.max; } addBuff(type, buy=true, cnt=1) { for(let i=0; i<cnt; i++) { if (!this.canBuff(type)) return; if (buy && !this.buffs[type].buyable) return; this.buffs[type].level += 1; if(buy) this.upgradePoints -= 1; // if health buff, increase current health if (type === Types.Buff.Health) { this.player.health.percent *= 1.25; this.player.health.percent = Math.min(1, this.player.health.percent); } } } applyBuffs() { for (const [type, buff] of Object.entries(this.buffs)) { if (buff.level === 0) continue; const multiplier = 1 + buff.level * buff.step; switch (Number(type)) { case Types.Buff.Speed: this.player.speed.multiplier *= multiplier; break; case Types.Buff.Size: this.player.shape.setScale(multiplier); break; case Types.Buff.Health: this.player.health.max.multiplier *= multiplier; break; case Types.Buff.Regeneration: this.player.health.regen.multiplier *= multiplier; break; case Types.Buff.Damage: this.player.sword.damage.multiplier *= multiplier; break; } } this.player.sword.swingDuration.multiplier['level'] = Math.min(maxSwingDuration, Math.max(1, swingDurationIncrease * (this.level-1))); this.player.sword.knockback.multiplier['level'] = 1 + (this.buffs[Types.Buff.Size].level * 0.015); } levelUp() { this.level += 1; this.previousLevelCoins = this.nextLevelCoins; this.nextLevelCoins = levels[this.level] ? levels[this.level].coins : this.nextLevelCoins * 2.2; this.upgradePoints += 1; this.player.evolutions.checkForEvolutions(); let sizeBuffsNeeded = levels[this.level].scale - levels[this.level-1].scale; if(!sizeBuffsNeeded) sizeBuffsNeeded = 0; this.addBuff(Types.Buff.Size, false, sizeBuffsNeeded); } } module.exports = LevelSystem;
412
0.859465
1
0.859465
game-dev
MEDIA
0.694617
game-dev
0.804005
1
0.804005
rambler-digital-solutions/rambler-it-ios
1,801
Pods/Typhoon/Source/Utils/NSArray+TyphoonManualEnumeration.m
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// #import "NSArray+TyphoonManualEnumeration.h" @interface TyphoonNextSignal : NSObject <TyphoonIterator> - (void)next; - (void)setNextBlock:(dispatch_block_t)block; @end @implementation TyphoonNextSignal { dispatch_block_t _block; } - (void)next { if (_block) { _block(); } } - (void)setNextBlock:(dispatch_block_t)block { _block = block; } @end @implementation NSArray (TyphoonSignalEnumerator) - (void)typhoon_enumerateObjectsWithManualIteration:(TyphoonManualIterationBlock)block completion:(dispatch_block_t)completion { TyphoonNextSignal *signal = [[TyphoonNextSignal alloc] init]; NSEnumerator *objectsEnumerator = [self objectEnumerator]; __weak __typeof (self) weakSelf = self; __weak __typeof (signal) weakSignal = signal; [signal setNextBlock:^{ [weakSelf typhoon_doStepWithEnumerator:objectsEnumerator signal:weakSignal block:block completion:completion]; }]; [self typhoon_doStepWithEnumerator:objectsEnumerator signal:signal block:block completion:completion]; } - (void)typhoon_doStepWithEnumerator:(NSEnumerator *)enumerator signal:(id<TyphoonIterator>)iterator block:(TyphoonManualIterationBlock)block completion:(dispatch_block_t)completion { id object = [enumerator nextObject]; if (object) { block(object, iterator); } else { completion(); } } @end
412
0.859315
1
0.859315
game-dev
MEDIA
0.429825
game-dev
0.778894
1
0.778894
TeamTwilight/twilightforest-fabric
7,337
src/main/java/twilightforest/block/HollowLogClimbable.java
package twilightforest.block; import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; import net.fabricmc.fabric.api.tag.convention.v1.ConventionalItemTags; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ShearsItem; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import io.github.fabricators_of_create.porting_lib.util.RegistryObject; import twilightforest.enums.HollowLogVariants; public class HollowLogClimbable extends HorizontalDirectionalBlock implements WaterloggedBlock { public static final EnumProperty<HollowLogVariants.Climbable> VARIANT = EnumProperty.create("variant", HollowLogVariants.Climbable.class); private static final VoxelShape LADDER_EAST = Block.box(0, 0, 0, 3, 16, 16); private static final VoxelShape LADDER_WEST = Block.box(13, 0, 0, 16, 16, 16); private static final VoxelShape LADDER_SOUTH = Block.box(0, 0, 0, 16, 16, 3); private static final VoxelShape LADDER_NORTH = Block.box(0, 0, 13, 16, 16, 16); private static final VoxelShape HOLLOW_SHAPE = Shapes.join(Shapes.block(), Block.box(2, 0, 2, 14, 16, 14), BooleanOp.ONLY_FIRST); private static final VoxelShape HOLLOW_SHAPE_SOUTH = Shapes.or(HOLLOW_SHAPE, LADDER_SOUTH); private static final VoxelShape HOLLOW_SHAPE_NORTH = Shapes.or(HOLLOW_SHAPE, LADDER_NORTH); private static final VoxelShape HOLLOW_SHAPE_EAST = Shapes.or(HOLLOW_SHAPE, LADDER_EAST); private static final VoxelShape HOLLOW_SHAPE_WEST = Shapes.or(HOLLOW_SHAPE, LADDER_WEST); private static final VoxelShape COLLISION_SHAPE = Shapes.join(Shapes.block(), Block.box(1, 0, 1, 15, 16, 15), BooleanOp.ONLY_FIRST); private static final VoxelShape COLLISION_SHAPE_SOUTH = Shapes.or(COLLISION_SHAPE, LADDER_SOUTH); private static final VoxelShape COLLISION_SHAPE_NORTH = Shapes.or(COLLISION_SHAPE, LADDER_NORTH); private static final VoxelShape COLLISION_SHAPE_EAST = Shapes.or(COLLISION_SHAPE, LADDER_EAST); private static final VoxelShape COLLISION_SHAPE_WEST = Shapes.or(COLLISION_SHAPE, LADDER_WEST); private final RegistryObject<HollowLogVertical> vertical; public HollowLogClimbable(Properties properties, RegistryObject<HollowLogVertical> vertical) { super(properties); this.vertical = vertical; this.registerDefaultState(this.getStateDefinition().any().setValue(VARIANT, HollowLogVariants.Climbable.VINE).setValue(FACING, Direction.NORTH)); FlammableBlockRegistry.getDefaultInstance().add(this, getFireSpreadSpeed(), getFlammability()); } @Override public VoxelShape getShape(BlockState state, BlockGetter getter, BlockPos pos, CollisionContext context) { return state.getValue(VARIANT) == HollowLogVariants.Climbable.VINE ? HOLLOW_SHAPE : switch (state.getValue(FACING)) { case SOUTH -> HOLLOW_SHAPE_SOUTH; case WEST -> HOLLOW_SHAPE_WEST; case EAST -> HOLLOW_SHAPE_EAST; default -> HOLLOW_SHAPE_NORTH; }; } @Override public VoxelShape getCollisionShape(BlockState state, BlockGetter getter, BlockPos pos, CollisionContext context) { return state.getValue(VARIANT) == HollowLogVariants.Climbable.VINE ? COLLISION_SHAPE : switch (state.getValue(FACING)) { case SOUTH -> COLLISION_SHAPE_SOUTH; case WEST -> COLLISION_SHAPE_WEST; case EAST -> COLLISION_SHAPE_EAST; default -> COLLISION_SHAPE_NORTH; }; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { super.createBlockStateDefinition(builder.add(VARIANT, FACING)); } @Override public boolean isStateWaterlogged(BlockState state) { return state.getValue(VARIANT) == HollowLogVariants.Climbable.LADDER_WATERLOGGED; } @Override public BlockState setWaterlog(BlockState prior, boolean doWater) { return switch (prior.getValue(VARIANT)) { case VINE -> doWater ? this.vertical.get().defaultBlockState().setValue(HollowLogVertical.WATERLOGGED, true) : prior; case LADDER -> prior.setValue(VARIANT, HollowLogVariants.Climbable.LADDER_WATERLOGGED); case LADDER_WATERLOGGED -> prior.setValue(VARIANT, HollowLogVariants.Climbable.LADDER); }; } @Override public FluidState getFluidState(BlockState state) { return state.getValue(VARIANT) == HollowLogVariants.Climbable.LADDER_WATERLOGGED ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor accessor, BlockPos pos, BlockPos neighborPos) { if (this.isStateWaterlogged(state)) { accessor.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(accessor)); } return super.updateShape(state, facing, neighborState, accessor, pos, neighborPos); } @Override public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { if (!isInside(hit, pos)) return super.use(state, level, pos, player, hand, hit); ItemStack stack = player.getItemInHand(hand); if (stack.getItem() instanceof ShearsItem || stack.is(ConventionalItemTags.SHEARS)) { HollowLogVariants.Climbable variant = state.getValue(VARIANT); level.setBlock(pos, this.vertical.get().defaultBlockState().setValue(HollowLogVertical.WATERLOGGED, variant == HollowLogVariants.Climbable.LADDER_WATERLOGGED), 3); level.playSound(null, pos, SoundEvents.SHEEP_SHEAR, SoundSource.BLOCKS, 1.0F, 1.0F); if (!player.isCreative()) { stack.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(hand)); level.addFreshEntity(new ItemEntity(level, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(variant == HollowLogVariants.Climbable.VINE ? Blocks.VINE : Blocks.LADDER))); } return InteractionResult.sidedSuccess(level.isClientSide()); } return super.use(state, level, pos, player, hand, hit); } private static boolean isInside(HitResult result, BlockPos pos) { Vec3 vec = result.getLocation().subtract(pos.getX(), pos.getY(), pos.getZ()); return (0.124 <= vec.x() && vec.x() <= 0.876) && (0.124 <= vec.z() && vec.z() <= 0.876); } public int getFlammability() { return 5; } public int getFireSpreadSpeed() { return 5; } }
412
0.892552
1
0.892552
game-dev
MEDIA
0.994925
game-dev
0.973683
1
0.973683
FirelandsProject/firelands-cata
3,129
src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp
/* * This file is part of the FirelandsCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero 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 Affero General Public License for * more details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: The_Eye SD%Complete: 100 SDComment: SDCategory: Tempest Keep, The Eye EndScriptData */ /* ContentData npc_crystalcore_devastator EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "the_eye.h" enum Spells { SPELL_COUNTERCHARGE = 35035, SPELL_KNOCKAWAY = 22893, }; class npc_crystalcore_devastator : public CreatureScript { public: npc_crystalcore_devastator() : CreatureScript("npc_crystalcore_devastator") { } struct npc_crystalcore_devastatorAI : public ScriptedAI { npc_crystalcore_devastatorAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { Countercharge_Timer = 9000; Knockaway_Timer = 25000; } uint32 Knockaway_Timer; uint32 Countercharge_Timer; void Reset() override { Initialize(); } void JustEngagedWith(Unit* /*who*/) override { } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; //Check if we have a current target //Knockaway_Timer if (Knockaway_Timer <= diff) { if (Unit* victim = me->GetVictim()) { DoCastVictim(SPELL_KNOCKAWAY, true); me->GetThreatManager().ResetThreat(victim); } Knockaway_Timer = 23000; } else Knockaway_Timer -= diff; //Countercharge_Timer if (Countercharge_Timer <= diff) { DoCast(me, SPELL_COUNTERCHARGE); Countercharge_Timer = 45000; } else Countercharge_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetTheEyeAI<npc_crystalcore_devastatorAI>(creature); } }; void AddSC_the_eye() { new npc_crystalcore_devastator(); }
412
0.878356
1
0.878356
game-dev
MEDIA
0.995754
game-dev
0.913525
1
0.913525
lua9520/source-engine-2018-hl2_src
29,108
game/server/hl2/npc_assassin.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "ammodef.h" #include "AI_Hint.h" #include "AI_Navigator.h" #include "npc_Assassin.h" #include "game.h" #include "npcevent.h" #include "engine/IEngineSound.h" #include "ai_squad.h" #include "AI_SquadSlot.h" #include "ai_moveprobe.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar sk_assassin_health( "sk_assassin_health","150"); ConVar g_debug_assassin( "g_debug_assassin", "0" ); //========================================================= // Anim Events //========================================================= #define ASSASSIN_AE_FIRE_PISTOL_RIGHT 1 #define ASSASSIN_AE_FIRE_PISTOL_LEFT 2 #define ASSASSIN_AE_KICK_HIT 3 int AE_ASSASIN_FIRE_PISTOL_RIGHT; int AE_ASSASIN_FIRE_PISTOL_LEFT; int AE_ASSASIN_KICK_HIT; //========================================================= // Assassin activities //========================================================= int ACT_ASSASSIN_FLIP_LEFT; int ACT_ASSASSIN_FLIP_RIGHT; int ACT_ASSASSIN_FLIP_BACK; int ACT_ASSASSIN_FLIP_FORWARD; int ACT_ASSASSIN_PERCH; //========================================================= // Flip types //========================================================= enum { FLIP_LEFT, FLIP_RIGHT, FLIP_FORWARD, FLIP_BACKWARD, NUM_FLIP_TYPES, }; //========================================================= // Private conditions //========================================================= enum Assassin_Conds { COND_ASSASSIN_ENEMY_TARGETTING_ME = LAST_SHARED_CONDITION, }; //========================================================= // Assassin schedules //========================================================= enum { SCHED_ASSASSIN_FIND_VANTAGE_POINT = LAST_SHARED_SCHEDULE, SCHED_ASSASSIN_EVADE, SCHED_ASSASSIN_STALK_ENEMY, SCHED_ASSASSIN_LUNGE, }; //========================================================= // Assassin tasks //========================================================= enum { TASK_ASSASSIN_GET_PATH_TO_VANTAGE_POINT = LAST_SHARED_TASK, TASK_ASSASSIN_EVADE, TASK_ASSASSIN_SET_EYE_STATE, TASK_ASSASSIN_LUNGE, }; //----------------------------------------------------------------------------- // Purpose: Class Constructor //----------------------------------------------------------------------------- CNPC_Assassin::CNPC_Assassin( void ) { } //----------------------------------------------------------------------------- LINK_ENTITY_TO_CLASS( npc_assassin, CNPC_Assassin ); #if 0 //--------------------------------------------------------- // Custom Client entity //--------------------------------------------------------- IMPLEMENT_SERVERCLASS_ST(CNPC_Assassin, DT_NPC_Assassin) END_SEND_TABLE() #endif //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CNPC_Assassin ) DEFINE_FIELD( m_nNumFlips, FIELD_INTEGER ), DEFINE_FIELD( m_nLastFlipType, FIELD_INTEGER ), DEFINE_FIELD( m_flNextFlipTime, FIELD_TIME ), DEFINE_FIELD( m_flNextLungeTime, FIELD_TIME ), DEFINE_FIELD( m_flNextShotTime, FIELD_TIME ), DEFINE_FIELD( m_bEvade, FIELD_BOOLEAN ), DEFINE_FIELD( m_bAggressive, FIELD_BOOLEAN ), DEFINE_FIELD( m_bBlinkState, FIELD_BOOLEAN ), DEFINE_FIELD( m_pEyeSprite, FIELD_CLASSPTR ), DEFINE_FIELD( m_pEyeTrail, FIELD_CLASSPTR ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: // // //----------------------------------------------------------------------------- void CNPC_Assassin::Precache( void ) { PrecacheModel( "models/fassassin.mdl" ); PrecacheScriptSound( "NPC_Assassin.ShootPistol" ); PrecacheScriptSound( "Zombie.AttackHit" ); PrecacheScriptSound( "Assassin.AttackMiss" ); PrecacheScriptSound( "NPC_Assassin.Footstep" ); PrecacheModel( "sprites/redglow1.vmt" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: // // //----------------------------------------------------------------------------- void CNPC_Assassin::Spawn( void ) { Precache(); SetModel( "models/fassassin.mdl" ); SetHullType(HULL_HUMAN); SetHullSizeNormal(); SetSolid( SOLID_BBOX ); AddSolidFlags( FSOLID_NOT_STANDABLE ); SetMoveType( MOVETYPE_STEP ); SetBloodColor( BLOOD_COLOR_RED ); m_iHealth = sk_assassin_health.GetFloat(); m_flFieldOfView = 0.1; m_NPCState = NPC_STATE_NONE; CapabilitiesClear(); CapabilitiesAdd( bits_CAP_MOVE_CLIMB | bits_CAP_MOVE_GROUND | bits_CAP_MOVE_JUMP ); CapabilitiesAdd( bits_CAP_SQUAD | bits_CAP_USE_WEAPONS | bits_CAP_AIM_GUN | bits_CAP_INNATE_RANGE_ATTACK1 | bits_CAP_INNATE_RANGE_ATTACK2 | bits_CAP_INNATE_MELEE_ATTACK1 ); //Turn on our guns SetBodygroup( 1, 1 ); int attachment = LookupAttachment( "Eye" ); // Start up the eye glow m_pEyeSprite = CSprite::SpriteCreate( "sprites/redglow1.vmt", GetLocalOrigin(), false ); if ( m_pEyeSprite != NULL ) { m_pEyeSprite->SetAttachment( this, attachment ); m_pEyeSprite->SetTransparency( kRenderTransAdd, 255, 255, 255, 200, kRenderFxNone ); m_pEyeSprite->SetScale( 0.25f ); } // Start up the eye trail m_pEyeTrail = CSpriteTrail::SpriteTrailCreate( "sprites/bluelaser1.vmt", GetLocalOrigin(), false ); if ( m_pEyeTrail != NULL ) { m_pEyeTrail->SetAttachment( this, attachment ); m_pEyeTrail->SetTransparency( kRenderTransAdd, 255, 0, 0, 200, kRenderFxNone ); m_pEyeTrail->SetStartWidth( 8.0f ); m_pEyeTrail->SetLifeTime( 0.75f ); } NPCInit(); m_bEvade = false; m_bAggressive = false; } //----------------------------------------------------------------------------- // Purpose: Returns true if a reasonable jumping distance // Input : // Output : //----------------------------------------------------------------------------- bool CNPC_Assassin::IsJumpLegal(const Vector &startPos, const Vector &apex, const Vector &endPos) const { const float MAX_JUMP_RISE = 256.0f; const float MAX_JUMP_DISTANCE = 256.0f; const float MAX_JUMP_DROP = 512.0f; return BaseClass::IsJumpLegal( startPos, apex, endPos, MAX_JUMP_RISE, MAX_JUMP_DROP, MAX_JUMP_DISTANCE ); } //----------------------------------------------------------------------------- // Purpose: // Input : flDot - // flDist - // Output : int CNPC_Assassin::MeleeAttack1Conditions //----------------------------------------------------------------------------- int CNPC_Assassin::MeleeAttack1Conditions ( float flDot, float flDist ) { if ( flDist > 84 ) return COND_TOO_FAR_TO_ATTACK; if ( flDot < 0.7f ) return 0; if ( GetEnemy() == NULL ) return 0; return COND_CAN_MELEE_ATTACK1; } //----------------------------------------------------------------------------- // Purpose: // Input : flDot - // flDist - // Output : int CNPC_Assassin::RangeAttack1Conditions //----------------------------------------------------------------------------- int CNPC_Assassin::RangeAttack1Conditions ( float flDot, float flDist ) { if ( flDist < 84 ) return COND_TOO_CLOSE_TO_ATTACK; if ( flDist > 1024 ) return COND_TOO_FAR_TO_ATTACK; if ( flDot < 0.5f ) return COND_NOT_FACING_ATTACK; return COND_CAN_RANGE_ATTACK1; } //----------------------------------------------------------------------------- // Purpose: // Input : flDot - // flDist - // Output : int CNPC_Assassin::RangeAttack1Conditions //----------------------------------------------------------------------------- int CNPC_Assassin::RangeAttack2Conditions ( float flDot, float flDist ) { if ( m_flNextLungeTime > gpGlobals->curtime ) return 0; float lungeRange = GetSequenceMoveDist( SelectWeightedSequence( (Activity) ACT_ASSASSIN_FLIP_FORWARD ) ); if ( flDist < lungeRange * 0.25f ) return COND_TOO_CLOSE_TO_ATTACK; if ( flDist > lungeRange * 1.5f ) return COND_TOO_FAR_TO_ATTACK; if ( flDot < 0.75f ) return COND_NOT_FACING_ATTACK; if ( GetEnemy() == NULL ) return 0; // Check for a clear path trace_t tr; UTIL_TraceHull( GetAbsOrigin(), GetEnemy()->GetAbsOrigin(), GetHullMins(), GetHullMaxs(), MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction == 1.0f || tr.m_pEnt == GetEnemy() ) return COND_CAN_RANGE_ATTACK2; return 0; } //----------------------------------------------------------------------------- // Purpose: // Input : hand - //----------------------------------------------------------------------------- void CNPC_Assassin::FirePistol( int hand ) { if ( m_flNextShotTime > gpGlobals->curtime ) return; m_flNextShotTime = gpGlobals->curtime + random->RandomFloat( 0.05f, 0.15f ); Vector muzzlePos; QAngle muzzleAngle; const char *handName = ( hand ) ? "LeftMuzzle" : "RightMuzzle"; GetAttachment( handName, muzzlePos, muzzleAngle ); Vector muzzleDir; if ( GetEnemy() == NULL ) { AngleVectors( muzzleAngle, &muzzleDir ); } else { muzzleDir = GetEnemy()->BodyTarget( muzzlePos ) - muzzlePos; VectorNormalize( muzzleDir ); } int bulletType = GetAmmoDef()->Index( "Pistol" ); FireBullets( 1, muzzlePos, muzzleDir, VECTOR_CONE_5DEGREES, 1024, bulletType, 2 ); UTIL_MuzzleFlash( muzzlePos, muzzleAngle, 0.5f, 1 ); CPASAttenuationFilter filter( this ); EmitSound( filter, entindex(), "NPC_Assassin.ShootPistol" ); } //--------------------------------------------------------- //--------------------------------------------------------- void CNPC_Assassin::HandleAnimEvent( animevent_t *pEvent ) { if ( pEvent->event == AE_ASSASIN_FIRE_PISTOL_RIGHT ) { FirePistol( 0 ); return; } if ( pEvent->event == AE_ASSASIN_FIRE_PISTOL_LEFT ) { FirePistol( 1 ); return; } if ( pEvent->event == AE_ASSASIN_KICK_HIT ) { Vector attackDir = BodyDirection2D(); Vector attackPos = WorldSpaceCenter() + ( attackDir * 64.0f ); trace_t tr; UTIL_TraceHull( WorldSpaceCenter(), attackPos, -Vector(8,8,8), Vector(8,8,8), MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr ); if ( ( tr.m_pEnt != NULL ) && ( tr.DidHitWorld() == false ) ) { if ( tr.m_pEnt->m_takedamage != DAMAGE_NO ) { CTakeDamageInfo info( this, this, 5, DMG_CLUB ); CalculateMeleeDamageForce( &info, (tr.endpos - tr.startpos), tr.endpos ); tr.m_pEnt->TakeDamage( info ); CBasePlayer *pPlayer = ToBasePlayer( tr.m_pEnt ); if ( pPlayer != NULL ) { //Kick the player angles pPlayer->ViewPunch( QAngle( -30, 40, 10 ) ); } EmitSound( "Zombie.AttackHit" ); //EmitSound( "Assassin.AttackHit" ); } } else { EmitSound( "Assassin.AttackMiss" ); //EmitSound( "Assassin.AttackMiss" ); } return; } BaseClass::HandleAnimEvent( pEvent ); } //----------------------------------------------------------------------------- // Purpose: Causes the assassin to prefer to run away, rather than towards her target //----------------------------------------------------------------------------- bool CNPC_Assassin::MovementCost( int moveType, const Vector &vecStart, const Vector &vecEnd, float *pCost ) { if ( GetEnemy() == NULL ) return true; float multiplier = 1.0f; Vector moveDir = ( vecEnd - vecStart ); VectorNormalize( moveDir ); Vector enemyDir = ( GetEnemy()->GetAbsOrigin() - vecStart ); VectorNormalize( enemyDir ); // If we're moving towards our enemy, then the cost is much higher than normal if ( DotProduct( enemyDir, moveDir ) > 0.5f ) { multiplier = 16.0f; } *pCost *= multiplier; return ( multiplier != 1 ); } //--------------------------------------------------------- //--------------------------------------------------------- int CNPC_Assassin::SelectSchedule ( void ) { switch ( m_NPCState ) { case NPC_STATE_IDLE: case NPC_STATE_ALERT: { if ( HasCondition ( COND_HEAR_DANGER ) ) return SCHED_TAKE_COVER_FROM_BEST_SOUND; if ( HasCondition ( COND_HEAR_COMBAT ) ) return SCHED_INVESTIGATE_SOUND; } break; case NPC_STATE_COMBAT: { // dead enemy if ( HasCondition( COND_ENEMY_DEAD ) ) { // call base class, all code to handle dead enemies is centralized there. return BaseClass::SelectSchedule(); } // Need to move if ( /*( HasCondition( COND_SEE_ENEMY ) && HasCondition( COND_ASSASSIN_ENEMY_TARGETTING_ME ) && random->RandomInt( 0, 32 ) == 0 && m_flNextFlipTime < gpGlobals->curtime ) )*/ ( m_nNumFlips > 0 ) || ( ( HasCondition ( COND_LIGHT_DAMAGE ) && random->RandomInt( 0, 2 ) == 0 ) ) || ( HasCondition ( COND_HEAVY_DAMAGE ) ) ) { if ( m_nNumFlips <= 0 ) { m_nNumFlips = random->RandomInt( 1, 2 ); } return SCHED_ASSASSIN_EVADE; } // Can kick if ( HasCondition( COND_CAN_MELEE_ATTACK1 ) ) return SCHED_MELEE_ATTACK1; // Can shoot if ( HasCondition( COND_CAN_RANGE_ATTACK2 ) ) { m_flNextLungeTime = gpGlobals->curtime + 2.0f; m_nLastFlipType = FLIP_FORWARD; return SCHED_ASSASSIN_LUNGE; } // Can shoot if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) ) return SCHED_RANGE_ATTACK1; // Face our enemy if ( HasCondition( COND_SEE_ENEMY ) ) return SCHED_COMBAT_FACE; // new enemy if ( HasCondition( COND_NEW_ENEMY ) ) return SCHED_TAKE_COVER_FROM_ENEMY; // ALERT( at_console, "stand\n"); return SCHED_ASSASSIN_FIND_VANTAGE_POINT; } break; } return BaseClass::SelectSchedule(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Assassin::PrescheduleThink( void ) { if ( GetActivity() == ACT_RUN || GetActivity() == ACT_WALK) { CPASAttenuationFilter filter( this ); static int iStep = 0; iStep = ! iStep; if (iStep) { EmitSound( filter, entindex(), "NPC_Assassin.Footstep" ); } } } //----------------------------------------------------------------------------- // Purpose: // Input : right - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_Assassin::CanFlip( int flipType, Activity &activity, const Vector *avoidPosition ) { Vector testDir; Activity act = ACT_INVALID; switch( flipType ) { case FLIP_RIGHT: GetVectors( NULL, &testDir, NULL ); act = NPC_TranslateActivity( (Activity) ACT_ASSASSIN_FLIP_RIGHT ); break; case FLIP_LEFT: GetVectors( NULL, &testDir, NULL ); testDir.Negate(); act = NPC_TranslateActivity( (Activity) ACT_ASSASSIN_FLIP_LEFT ); break; case FLIP_FORWARD: GetVectors( &testDir, NULL, NULL ); act = NPC_TranslateActivity( (Activity) ACT_ASSASSIN_FLIP_FORWARD ); break; case FLIP_BACKWARD: GetVectors( &testDir, NULL, NULL ); testDir.Negate(); act = NPC_TranslateActivity( (Activity) ACT_ASSASSIN_FLIP_BACK ); break; default: assert(0); //NOTENOTE: Invalid flip type activity = ACT_INVALID; return false; break; } // Make sure we don't flip towards our avoidance position/ if ( avoidPosition != NULL ) { Vector avoidDir = (*avoidPosition) - GetAbsOrigin(); VectorNormalize( avoidDir ); if ( DotProduct( avoidDir, testDir ) > 0.0f ) return false; } int seq = SelectWeightedSequence( act ); // Find out the length of this sequence float testDist = GetSequenceMoveDist( seq ); // Find the resulting end position from the sequence's movement Vector endPos = GetAbsOrigin() + ( testDir * testDist ); trace_t tr; if ( ( flipType != FLIP_BACKWARD ) && ( avoidPosition != NULL ) ) { UTIL_TraceLine( (*avoidPosition), endPos, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction == 1.0f ) return false; } /* UTIL_TraceHull( GetAbsOrigin(), endPos, NAI_Hull::Mins(m_eHull) + Vector( 0, 0, StepHeight() ), NAI_Hull::Maxs(m_eHull), MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr ); // See if we're hit an obstruction in that direction if ( tr.fraction < 1.0f ) { if ( g_debug_assassin.GetBool() ) { NDebugOverlay::BoxDirection( GetAbsOrigin(), NAI_Hull::Mins(m_eHull) + Vector( 0, 0, StepHeight() ), NAI_Hull::Maxs(m_eHull) + Vector( testDist, 0, StepHeight() ), testDir, 255, 0, 0, true, 2.0f ); } return false; } #define NUM_STEPS 2 float stepLength = testDist / NUM_STEPS; for ( int i = 1; i <= NUM_STEPS; i++ ) { endPos = GetAbsOrigin() + ( testDir * (stepLength*i) ); // Also check for a cliff edge UTIL_TraceHull( endPos, endPos - Vector( 0, 0, StepHeight() * 4.0f ), NAI_Hull::Mins(m_eHull) + Vector( 0, 0, StepHeight() ), NAI_Hull::Maxs(m_eHull), MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction == 1.0f ) { if ( g_debug_assassin.GetBool() ) { NDebugOverlay::BoxDirection( endPos, NAI_Hull::Mins(m_eHull) + Vector( 0, 0, StepHeight() ), NAI_Hull::Maxs(m_eHull) + Vector( StepHeight() * 4.0f, 0, StepHeight() ), Vector(0,0,-1), 255, 0, 0, true, 2.0f ); } return false; } } if ( g_debug_assassin.GetBool() ) { NDebugOverlay::BoxDirection( GetAbsOrigin(), NAI_Hull::Mins(m_eHull) + Vector( 0, 0, StepHeight() ), NAI_Hull::Maxs(m_eHull) + Vector( testDist, 0, StepHeight() ), testDir, 0, 255, 0, true, 2.0f ); } */ AIMoveTrace_t moveTrace; GetMoveProbe()->TestGroundMove( GetAbsOrigin(), endPos, MASK_NPCSOLID, AITGM_DEFAULT, &moveTrace ); if ( moveTrace.fStatus != AIMR_OK ) return false; // Return the activity to use activity = (Activity) act; return true; } //--------------------------------------------------------- // Purpose: //--------------------------------------------------------- void CNPC_Assassin::StartTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_ASSASSIN_SET_EYE_STATE: { SetEyeState( (eyeState_t) ( (int) pTask->flTaskData ) ); TaskComplete(); } break; case TASK_ASSASSIN_EVADE: { Activity flipAct = ACT_INVALID; const Vector *avoidPos = ( GetEnemy() != NULL ) ? &(GetEnemy()->GetAbsOrigin()) : NULL; for ( int i = FLIP_LEFT; i < NUM_FLIP_TYPES; i++ ) { if ( CanFlip( i, flipAct, avoidPos ) ) { // Don't flip back to where we just were if ( ( ( i == FLIP_LEFT ) && ( m_nLastFlipType == FLIP_RIGHT ) ) || ( ( i == FLIP_RIGHT ) && ( m_nLastFlipType == FLIP_LEFT ) ) || ( ( i == FLIP_FORWARD ) && ( m_nLastFlipType == FLIP_BACKWARD ) ) || ( ( i == FLIP_BACKWARD ) && ( m_nLastFlipType == FLIP_FORWARD ) ) ) { flipAct = ACT_INVALID; continue; } m_nNumFlips--; ResetIdealActivity( flipAct ); m_flNextFlipTime = gpGlobals->curtime + 2.0f; m_nLastFlipType = i; break; } } if ( flipAct == ACT_INVALID ) { m_nNumFlips = 0; m_nLastFlipType = -1; m_flNextFlipTime = gpGlobals->curtime + 2.0f; TaskFail( "Unable to find flip evasion direction!\n" ); } } break; case TASK_ASSASSIN_GET_PATH_TO_VANTAGE_POINT: { assert( GetEnemy() != NULL ); if ( GetEnemy() == NULL ) break; Vector goalPos; CHintCriteria hint; // Find a disadvantage node near the player, but away from ourselves hint.SetHintType( HINT_TACTICAL_ENEMY_DISADVANTAGED ); hint.AddExcludePosition( GetAbsOrigin(), 256 ); hint.AddExcludePosition( GetEnemy()->GetAbsOrigin(), 256 ); if ( ( m_pSquad != NULL ) && ( m_pSquad->NumMembers() > 1 ) ) { AISquadIter_t iter; for ( CAI_BaseNPC *pSquadMember = m_pSquad->GetFirstMember( &iter ); pSquadMember; pSquadMember = m_pSquad->GetNextMember( &iter ) ) { if ( pSquadMember == NULL ) continue; hint.AddExcludePosition( pSquadMember->GetAbsOrigin(), 128 ); } } hint.SetFlag( bits_HINT_NODE_NEAREST ); CAI_Hint *pHint = CAI_HintManager::FindHint( this, GetEnemy()->GetAbsOrigin(), &hint ); if ( pHint == NULL ) { TaskFail( "Unable to find vantage point!\n" ); break; } pHint->GetPosition( this, &goalPos ); AI_NavGoal_t goal( goalPos ); //Try to run directly there if ( GetNavigator()->SetGoal( goal ) == false ) { TaskFail( "Unable to find path to vantage point!\n" ); break; } TaskComplete(); } break; default: BaseClass::StartTask( pTask ); break; } } //----------------------------------------------------------------------------- // Purpose: // // //----------------------------------------------------------------------------- float CNPC_Assassin::MaxYawSpeed( void ) { switch( GetActivity() ) { case ACT_TURN_LEFT: case ACT_TURN_RIGHT: return 160; break; case ACT_RUN: return 900; break; case ACT_RANGE_ATTACK1: return 0; break; default: return 60; break; } } //--------------------------------------------------------- //--------------------------------------------------------- void CNPC_Assassin::RunTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_ASSASSIN_EVADE: AutoMovement(); if ( IsActivityFinished() ) { TaskComplete(); } break; default: BaseClass::RunTask( pTask ); break; } } //--------------------------------------------------------- //--------------------------------------------------------- bool CNPC_Assassin::FValidateHintType ( CAI_Hint *pHint ) { switch( pHint->HintType() ) { case HINT_TACTICAL_ENEMY_DISADVANTAGED: { Vector hintPos; pHint->GetPosition( this, &hintPos ); // Verify that we can see the target from that position hintPos += GetViewOffset(); trace_t tr; UTIL_TraceLine( hintPos, GetEnemy()->BodyTarget( hintPos, true ), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); // Check for seeing our target at the new location if ( ( tr.fraction == 1.0f ) || ( tr.m_pEnt == GetEnemy() ) ) return false; return true; break; } default: return false; break; } return FALSE; } //----------------------------------------------------------------------------- // Purpose: // Output : const Vector //----------------------------------------------------------------------------- const Vector &CNPC_Assassin::GetViewOffset( void ) { static Vector eyeOffset; //FIXME: Use eye attachment? // If we're crouching, offset appropriately if ( ( GetActivity() == ACT_ASSASSIN_PERCH ) || ( GetActivity() == ACT_RANGE_ATTACK1 ) ) { eyeOffset = Vector( 0, 0, 24.0f ); } else { eyeOffset = BaseClass::GetViewOffset(); } return eyeOffset; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Assassin::OnScheduleChange( void ) { //TODO: Change eye state? BaseClass::OnScheduleChange(); } //----------------------------------------------------------------------------- // Purpose: // Input : state - //----------------------------------------------------------------------------- void CNPC_Assassin::SetEyeState( eyeState_t state ) { //Must have a valid eye to affect if ( ( m_pEyeSprite == NULL ) || ( m_pEyeTrail == NULL ) ) return; //Set the state switch( state ) { default: case ASSASSIN_EYE_SEE_TARGET: //Fade in and scale up m_pEyeSprite->SetColor( 255, 0, 0 ); m_pEyeSprite->SetBrightness( 164, 0.1f ); m_pEyeSprite->SetScale( 0.4f, 0.1f ); m_pEyeTrail->SetColor( 255, 0, 0 ); m_pEyeTrail->SetScale( 8.0f ); m_pEyeTrail->SetBrightness( 164 ); break; case ASSASSIN_EYE_SEEKING_TARGET: //Ping-pongs //Toggle our state m_bBlinkState = !m_bBlinkState; m_pEyeSprite->SetColor( 255, 128, 0 ); if ( m_bBlinkState ) { //Fade up and scale up m_pEyeSprite->SetScale( 0.25f, 0.1f ); m_pEyeSprite->SetBrightness( 164, 0.1f ); } else { //Fade down and scale down m_pEyeSprite->SetScale( 0.2f, 0.1f ); m_pEyeSprite->SetBrightness( 64, 0.1f ); } break; case ASSASSIN_EYE_DORMANT: //Fade out and scale down m_pEyeSprite->SetScale( 0.5f, 0.5f ); m_pEyeSprite->SetBrightness( 64, 0.5f ); m_pEyeTrail->SetScale( 2.0f ); m_pEyeTrail->SetBrightness( 64 ); break; case ASSASSIN_EYE_DEAD: //Fade out slowly m_pEyeSprite->SetColor( 255, 0, 0 ); m_pEyeSprite->SetScale( 0.1f, 5.0f ); m_pEyeSprite->SetBrightness( 0, 5.0f ); m_pEyeTrail->SetColor( 255, 0, 0 ); m_pEyeTrail->SetScale( 0.1f ); m_pEyeTrail->SetBrightness( 0 ); break; case ASSASSIN_EYE_ACTIVE: m_pEyeSprite->SetColor( 255, 0, 0 ); m_pEyeSprite->SetScale( 0.1f ); m_pEyeSprite->SetBrightness( 0 ); break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Assassin::GatherEnemyConditions( CBaseEntity *pEnemy ) { ClearCondition( COND_ASSASSIN_ENEMY_TARGETTING_ME ); BaseClass::GatherEnemyConditions( pEnemy ); // See if we're being targetted specifically if ( HasCondition( COND_ENEMY_FACING_ME ) ) { Vector enemyDir = GetAbsOrigin() - pEnemy->GetAbsOrigin(); VectorNormalize( enemyDir ); Vector enemyBodyDir; CBasePlayer *pPlayer = ToBasePlayer( pEnemy ); if ( pPlayer != NULL ) { enemyBodyDir = pPlayer->BodyDirection3D(); } else { AngleVectors( pEnemy->GetAbsAngles(), &enemyBodyDir ); } float enemyDot = DotProduct( enemyBodyDir, enemyDir ); //FIXME: Need to refine this a bit if ( enemyDot > 0.97f ) { SetCondition( COND_ASSASSIN_ENEMY_TARGETTING_ME ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Assassin::BuildScheduleTestBits( void ) { SetNextThink( gpGlobals->curtime + 0.05 ); //Don't allow any modifications when scripted if ( m_NPCState == NPC_STATE_SCRIPT ) return; //Become interrupted if we're targetted when shooting an enemy if ( IsCurSchedule( SCHED_RANGE_ATTACK1 ) ) { SetCustomInterruptCondition( COND_ASSASSIN_ENEMY_TARGETTING_ME ); } } //----------------------------------------------------------------------------- // Purpose: // Input : &info - //----------------------------------------------------------------------------- void CNPC_Assassin::Event_Killed( const CTakeDamageInfo &info ) { BaseClass::Event_Killed( info ); // Turn off the eye SetEyeState( ASSASSIN_EYE_DEAD ); // Turn off the pistols SetBodygroup( 1, 0 ); // Spawn her guns } //----------------------------------------------------------------------------- // // Schedules // //----------------------------------------------------------------------------- AI_BEGIN_CUSTOM_NPC( npc_assassin, CNPC_Assassin ) DECLARE_ACTIVITY(ACT_ASSASSIN_FLIP_LEFT) DECLARE_ACTIVITY(ACT_ASSASSIN_FLIP_RIGHT) DECLARE_ACTIVITY(ACT_ASSASSIN_FLIP_BACK) DECLARE_ACTIVITY(ACT_ASSASSIN_FLIP_FORWARD) DECLARE_ACTIVITY(ACT_ASSASSIN_PERCH) //Adrian: events go here DECLARE_ANIMEVENT( AE_ASSASIN_FIRE_PISTOL_RIGHT ) DECLARE_ANIMEVENT( AE_ASSASIN_FIRE_PISTOL_LEFT ) DECLARE_ANIMEVENT( AE_ASSASIN_KICK_HIT ) DECLARE_TASK(TASK_ASSASSIN_GET_PATH_TO_VANTAGE_POINT) DECLARE_TASK(TASK_ASSASSIN_EVADE) DECLARE_TASK(TASK_ASSASSIN_SET_EYE_STATE) DECLARE_TASK(TASK_ASSASSIN_LUNGE) DECLARE_CONDITION(COND_ASSASSIN_ENEMY_TARGETTING_ME) //========================================================= // ASSASSIN_STALK_ENEMY //========================================================= DEFINE_SCHEDULE ( SCHED_ASSASSIN_STALK_ENEMY, " Tasks" " TASK_STOP_MOVING 0" " TASK_PLAY_SEQUENCE_FACE_ENEMY ACTIVITY:ACT_ASSASSIN_PERCH" " " " Interrupts" " COND_ASSASSIN_ENEMY_TARGETTING_ME" " COND_SEE_ENEMY" " COND_LIGHT_DAMAGE" " COND_HEAVY_DAMAGE" ) //========================================================= // > ASSASSIN_FIND_VANTAGE_POINT //========================================================= DEFINE_SCHEDULE ( SCHED_ASSASSIN_FIND_VANTAGE_POINT, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_TAKE_COVER_FROM_ENEMY" " TASK_STOP_MOVING 0" " TASK_ASSASSIN_GET_PATH_TO_VANTAGE_POINT 0" " TASK_RUN_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" " TASK_SET_SCHEDULE SCHEDULE:SCHED_ASSASSIN_STALK_ENEMY" " " " Interrupts" " COND_LIGHT_DAMAGE" " COND_HEAVY_DAMAGE" " COND_TASK_FAILED" ) //========================================================= // Assassin needs to avoid the player //========================================================= DEFINE_SCHEDULE ( SCHED_ASSASSIN_EVADE, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSASSIN_FIND_VANTAGE_POINT" " TASK_STOP_MOVING 0" " TASK_ASSASSIN_EVADE 0" " " " Interrupts" " COND_TASK_FAILED" ) //========================================================= // Assassin needs to avoid the player //========================================================= DEFINE_SCHEDULE ( SCHED_ASSASSIN_LUNGE, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSASSIN_FIND_VANTAGE_POINT" " TASK_STOP_MOVING 0" " TASK_FACE_ENEMY 0" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_ASSASSIN_FLIP_FORWARD" " " " Interrupts" " COND_TASK_FAILED" ) AI_END_CUSTOM_NPC()
412
0.958482
1
0.958482
game-dev
MEDIA
0.997569
game-dev
0.97273
1
0.97273
systemsomicslab/MsdialWorkbench
6,860
src/Common/ChartDrawing/AxisManager/Generic/LogScaleAxisManager.cs
using CompMs.Graphics.Core.Base; using System; using System.Collections.Generic; using System.Linq; namespace CompMs.Graphics.AxisManager.Generic { public class LogScaleAxisManager<T> : BaseAxisManager<T> where T : IConvertible { internal LogScaleAxisManager(AxisRange range) : base(range) { _labelGenerator = new LogScaleLabelGenerator(); Base = 10; } internal LogScaleAxisManager(AxisRange range, AxisRange bounds) : base(range, bounds) { _labelGenerator = new LogScaleLabelGenerator(); Base = 10; } internal LogScaleAxisManager(AxisRange range, IChartMargin margin) : base(range, margin) { _labelGenerator = new LogScaleLabelGenerator(); Base = 10; } internal LogScaleAxisManager(AxisRange range, IChartMargin margin, int base_) : base(range, margin) { _labelGenerator = new BaseSelectableLogScaleLabelGenerator(base_); Base = base_; } internal LogScaleAxisManager(AxisRange range, IChartMargin margin, AxisRange bounds) : base(range, margin, bounds) { _labelGenerator = new LogScaleLabelGenerator(); Base = 10; } internal LogScaleAxisManager(AxisRange range, IChartMargin margin, T lowBound, T highBound) : this(range, margin, new AxisRange(ConvertToAxisValue(lowBound, 10), ConvertToAxisValue(highBound, 10))) { } internal LogScaleAxisManager(AxisRange range, T lowBound, T highBound) : this(range, new AxisRange(ConvertToAxisValue(lowBound, 10), ConvertToAxisValue(highBound, 10))) { } public LogScaleAxisManager(T low, T high) : this(new AxisRange(ConvertToAxisValue(low, 10), ConvertToAxisValue(high, 10))) { } public LogScaleAxisManager(T low, T high, IChartMargin margin) : this(new AxisRange(ConvertToAxisValue(low, 10), ConvertToAxisValue(high, 10)), margin) { } public LogScaleAxisManager(T low, T high, IChartMargin margin, int base_) : this(new AxisRange(ConvertToAxisValue(low, base_), ConvertToAxisValue(high, base_)), margin, base_) { } public LogScaleAxisManager(T low, T high, T lowBound, T highBound) : this(new AxisRange(ConvertToAxisValue(low, 10), ConvertToAxisValue(high, 10)), new AxisRange(ConvertToAxisValue(lowBound, 10), ConvertToAxisValue(highBound, 10))) { } public LogScaleAxisManager(T low, T high, IChartMargin margin, T lowBound, T highBound) : this(new AxisRange(ConvertToAxisValue(low, 10), ConvertToAxisValue(high, 10)), margin, new AxisRange(ConvertToAxisValue(lowBound, 10), ConvertToAxisValue(highBound, 10))) { } public LogScaleAxisManager(ICollection<T> source) : this(source.DefaultIfEmpty().Min(), source.DefaultIfEmpty().Max()) { } public LogScaleAxisManager(ICollection<T> source, IChartMargin margin) : this(source.DefaultIfEmpty().Min(), source.DefaultIfEmpty().Max(), margin) { } public LogScaleAxisManager(ICollection<T> source, IChartMargin margin, int base_) : this(source.DefaultIfEmpty().Min(), source.DefaultIfEmpty().Max(), margin, base_) { } public LogScaleAxisManager(ICollection<T> source, T low, T high) : this(source.DefaultIfEmpty().Min(), source.DefaultIfEmpty().Max(), low, high) { } public LogScaleAxisManager(ICollection<T> source, IChartMargin margin, T low, T high) : this(source.DefaultIfEmpty().Min(), source.DefaultIfEmpty().Max(), margin, low, high) { } public int Base { get; } public LabelType LabelType { get => _labelType; set => SetProperty(ref _labelType, value); } private LabelType _labelType = LabelType.Standard; public void UpdateInitialRange(T low, T high) { UpdateInitialRange(new AxisRange(ConvertToAxisValue(low, Base), ConvertToAxisValue(high, Base))); } public void UpdateInitialRange(ICollection<T> source) { UpdateInitialRange(new AxisRange(ConvertToAxisValue(source.DefaultIfEmpty().Min(), Base), ConvertToAxisValue(source.DefaultIfEmpty().Max(), Base))); } protected override void OnRangeChanged() { labelTicks = null; base.OnRangeChanged(); } private ILabelGenerator LabelGenerator { get { switch (LabelType) { case LabelType.Relative: return _labelGenerator is RelativeLabelGenerator ? _labelGenerator : _labelGenerator = new RelativeLabelGenerator(); case LabelType.Percent: return _labelGenerator is PercentLabelGenerator ? _labelGenerator : _labelGenerator = new PercentLabelGenerator(); case LabelType.Standard: case LabelType.Order: default: return _labelGenerator is LogScaleLabelGenerator || _labelGenerator is BaseSelectableLogScaleLabelGenerator ? _labelGenerator : _labelGenerator = new LogScaleLabelGenerator(); } } } private ILabelGenerator _labelGenerator = new LogScaleLabelGenerator(); public override List<LabelTickData> GetLabelTicks() { var initialRangeCore = CoerceRange(InitialRangeCore, Bounds); List<LabelTickData> ticks; (ticks, UnitLabel) = LabelGenerator.Generate(Range.Minimum.Value, Range.Maximum.Value, initialRangeCore.Minimum.Value, initialRangeCore.Maximum.Value); return ticks; } public override AxisValue TranslateToAxisValue(T value) { return ConvertToAxisValue(value, Base); } private static AxisValue ConvertToAxisValue(T value, int base_) { return new AxisValue(Math.Log(Convert.ToDouble(value), base_)); } public static LogScaleAxisManager<T> Build<U>(IEnumerable<U> source, Func<U, T> map) { return new LogScaleAxisManager<T>(source.Select(map).ToList()); } public static LogScaleAxisManager<T> Build<U>(IEnumerable<U> source, Func<U, T> map, T lowBound, T highBound) { return new LogScaleAxisManager<T>(source.Select(map).ToList(), lowBound, highBound); } public static LogScaleAxisManager<T> BuildDefault<U>(IEnumerable<U> source, Func<U, T> map) { return new LogScaleAxisManager<T>(source.Select(map).ToList()); } public static LogScaleAxisManager<T> BuildDefault<U>(IEnumerable<U> source, Func<U, T> map, T lowBound, T highBound) { return new LogScaleAxisManager<T>(source.Select(map).ToList(), lowBound, highBound); } } }
412
0.809477
1
0.809477
game-dev
MEDIA
0.17337
game-dev
0.94787
1
0.94787
magefree/mage
2,586
Mage.Sets/src/mage/cards/s/Scrapheap.java
package mage.cards.s; import mage.MageObject; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.common.GainLifeEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Zone; import mage.filter.StaticFilters; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.ZoneChangeEvent; import mage.game.permanent.Permanent; import java.util.UUID; /** * * @author Plopman */ public final class Scrapheap extends CardImpl { public Scrapheap(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{3}"); // Whenever an artifact or enchantment is put into your graveyard from the battlefield, you gain 1 life. this.addAbility(new ScrapheapTriggeredAbility()); } private Scrapheap(final Scrapheap card) { super(card); } @Override public Scrapheap copy() { return new Scrapheap(this); } } class ScrapheapTriggeredAbility extends TriggeredAbilityImpl { @Override public ScrapheapTriggeredAbility copy() { return new ScrapheapTriggeredAbility(this); } public ScrapheapTriggeredAbility(){ super(Zone.BATTLEFIELD, new GainLifeEffect(1)); setLeavesTheBattlefieldTrigger(true); } private ScrapheapTriggeredAbility(final ScrapheapTriggeredAbility ability){ super(ability); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.ZONE_CHANGE; } @Override public boolean checkTrigger(GameEvent event, Game game) { ZoneChangeEvent zEvent = (ZoneChangeEvent) event; if (zEvent.isDiesEvent()) { Permanent permanent = (Permanent) game.getLastKnownInformation(event.getTargetId(), Zone.BATTLEFIELD); if (permanent != null && permanent.isOwnedBy(this.getControllerId())) { if (StaticFilters.FILTER_PERMANENT_ARTIFACT_OR_ENCHANTMENT.match(permanent, controllerId, this, game)) { return true; } } } return false; } @Override public String getRule() { return "Whenever an artifact or enchantment is put into your graveyard from the battlefield, you gain 1 life."; } @Override public boolean isInUseableZone(Game game, MageObject sourceObject, GameEvent event) { return TriggeredAbilityImpl.isInUseableZoneDiesTrigger(this, sourceObject, event, game); } }
412
0.980525
1
0.980525
game-dev
MEDIA
0.95916
game-dev
0.992003
1
0.992003
tgstation/tgstation
3,148
code/modules/antagonists/changeling/cellular_emporium.dm
// Cellular Emporium - // The place where Changelings go to purchase biological weaponry. /datum/cellular_emporium /// The name of the emporium - why does it need a name? Dunno var/name = "cellular emporium" /// The changeling who owns this emporium var/datum/antagonist/changeling/changeling /datum/cellular_emporium/New(my_changeling) . = ..() changeling = my_changeling /datum/cellular_emporium/Destroy() changeling = null return ..() /datum/cellular_emporium/ui_state(mob/user) return GLOB.always_state /datum/cellular_emporium/ui_status(mob/user, datum/ui_state/state) if(!changeling) return UI_CLOSE return UI_INTERACTIVE /datum/cellular_emporium/ui_interact(mob/user, datum/tgui/ui) ui = SStgui.try_update_ui(user, src, ui) if(!ui) ui = new(user, src, "CellularEmporium", name) ui.open() /datum/cellular_emporium/ui_static_data(mob/user) var/list/data = list() var/static/list/abilities if(isnull(abilities)) abilities = list() for(var/datum/action/changeling/ability_path as anything in changeling.all_powers) var/dna_cost = initial(ability_path.dna_cost) if(dna_cost < 0) // 0 = free, but negatives are invalid continue var/list/ability_data = list() ability_data["name"] = initial(ability_path.name) ability_data["desc"] = initial(ability_path.desc) ability_data["path"] = ability_path ability_data["helptext"] = initial(ability_path.helptext) ability_data["genetic_point_required"] = dna_cost ability_data["absorbs_required"] = initial(ability_path.req_absorbs) // compares against changeling true_absorbs ability_data["dna_required"] = initial(ability_path.req_dna) // compares against changeling absorbed_count abilities += list(ability_data) // Sorts abilities alphabetically by default sortTim(abilities, /proc/cmp_assoc_list_name) data["abilities"] = abilities return data /datum/cellular_emporium/ui_data(mob/user) var/list/data = list() data["can_readapt"] = changeling.can_respec data["owned_abilities"] = assoc_to_keys(changeling.purchased_powers) data["genetic_points_count"] = changeling.genetic_points data["absorb_count"] = changeling.true_absorbs data["dna_count"] = changeling.absorbed_count return data /datum/cellular_emporium/ui_act(action, list/params, datum/tgui/ui, datum/ui_state/state) . = ..() if(.) return switch(action) if("readapt") if(changeling.can_respec) changeling.readapt() if("evolve") // purchase_power sanity checks stuff like typepath, DNA, and absorbs for us. changeling.purchase_power(text2path(params["path"])) return TRUE /datum/action/cellular_emporium name = "Cellular Emporium" button_icon = 'icons/obj/drinks/soda.dmi' button_icon_state = "changelingsting" background_icon_state = "bg_changeling" overlay_icon_state = "bg_changeling_border" check_flags = NONE /datum/action/cellular_emporium/New(Target) . = ..() if(!istype(Target, /datum/cellular_emporium)) stack_trace("cellular_emporium action created with non-emporium.") qdel(src) /datum/action/cellular_emporium/Trigger(mob/clicker, trigger_flags) . = ..() if(!.) return target.ui_interact(owner)
412
0.914554
1
0.914554
game-dev
MEDIA
0.587251
game-dev
0.933904
1
0.933904
Hazrat-Ali9/Computer-Science-and-Engineering
1,423
09. Computer Architecture/Lectures/06-Day_07/main.cpp
#include <iostream> #include <string> using namespace std; class Point { float x; float y; public: void Move(float dx, float dy) { x += dx; y += dy; } void Jump(float dx, float dy) { x = dx; y = dy; } }; class Line { Point A; Point B; void Move(float adx, float ady, float bdx, float bdy) { A.Move(adx, ady); B.Move(bdx, bdy); } void Jump() {} }; class Character { private: string fname; string lname; string email; string charName; protected: int intelligence; // int strength; // int manna; public: void setFname(string f) { fname = f; } string getFname() { return fname; } void setCharname(string c) { charName = c; } string getCharname() { return charName; } Character(string f,string l,string c){ fname =f ; lname = l; charName = c; } }; class Magician : public Character { private: int manna; public: Magician(string f,string l, string c) : Character(f,l,c){ manna = (rand() % 90) + 10; intelligence = (rand() % 90) + 10; } void setManna(int m) { manna = m; } int getManna() { return manna; } void setIntelligence(int i) { intelligence = i; } int getIntelligence() { return intelligence; } }; class Warrior : public Character { string weapon; }; int main() { Magician M1("Joe","Smith","joemomma"); cout<<M1.getFname()<<endl; cout<<M1.getManna()<<endl; cout<<M1.getIntelligence()<<endl; }
412
0.62086
1
0.62086
game-dev
MEDIA
0.711277
game-dev
0.578356
1
0.578356
mangosone/server
36,641
src/game/WorldHandlers/PetitionsHandler.cpp
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu> * * 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 * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include "Common.h" #include "Language.h" #include "WorldPacket.h" #include "WorldSession.h" #include "World.h" #include "ObjectMgr.h" #include "Log.h" #include "Opcodes.h" #include "Guild.h" #include "GuildMgr.h" #include "ArenaTeam.h" #include "GossipDef.h" #include "SocialMgr.h" // Charters ID in item_template #define GUILD_CHARTER 5863 #define GUILD_CHARTER_COST 1000 // 10 S #define ARENA_TEAM_CHARTER_2v2 23560 #define ARENA_TEAM_CHARTER_2v2_COST 800000 // 80 G #define ARENA_TEAM_CHARTER_3v3 23561 #define ARENA_TEAM_CHARTER_3v3_COST 1200000 // 120 G #define ARENA_TEAM_CHARTER_5v5 23562 #define ARENA_TEAM_CHARTER_5v5_COST 2000000 // 200 G #define CHARTER_DISPLAY_ID 16161 void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode CMSG_PETITION_BUY"); recv_data.hexlike(); ObjectGuid guidNPC; uint32 clientIndex; // 1 for guild and arenaslot+1 for arenas in client std::string name; recv_data >> guidNPC; // NPC GUID recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint64>(); // 0 recv_data >> name; // name recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint16>(); // 0 recv_data.read_skip<uint8>(); // 0 recv_data >> clientIndex; // index recv_data.read_skip<uint32>(); // 0 DEBUG_LOG("Petitioner %s tried sell petition: name %s", guidNPC.GetString().c_str(), name.c_str()); // prevent cheating Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(guidNPC, UNIT_NPC_FLAG_PETITIONER); if (!pCreature) { DEBUG_LOG("WORLD: HandlePetitionBuyOpcode - %s not found or you can't interact with him.", guidNPC.GetString().c_str()); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) { GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); } uint32 charterid = 0; uint32 cost = 0; uint32 type = 0; if (pCreature->IsTabardDesigner()) { // if tabard designer, then trying to buy a guild charter. // do not let if already in guild. if (_player->GetGuildId()) { return; } charterid = GUILD_CHARTER; cost = GUILD_CHARTER_COST; type = 9; } else { // TODO: find correct opcode if (_player->getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { SendNotification(LANG_ARENA_ONE_TOOLOW, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)); return; } switch (clientIndex) // arenaSlot+1 as received from client (1 from 3 case) { case 1: charterid = ARENA_TEAM_CHARTER_2v2; cost = ARENA_TEAM_CHARTER_2v2_COST; type = 2; // 2v2 break; case 2: charterid = ARENA_TEAM_CHARTER_3v3; cost = ARENA_TEAM_CHARTER_3v3_COST; type = 3; // 3v3 break; case 3: charterid = ARENA_TEAM_CHARTER_5v5; cost = ARENA_TEAM_CHARTER_5v5_COST; type = 5; // 5v5 break; default: DEBUG_LOG("unknown selection at buy arena petition: %u", clientIndex); return; } if (_player->GetArenaTeamId(clientIndex - 1)) // arenaSlot+1 as received from client { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM); return; } } if (type == 9) { if (sGuildMgr.GetGuildByName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, ERR_GUILD_NAME_EXISTS_S); return; } if (sObjectMgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, ERR_GUILD_NAME_INVALID); return; } } else { if (sObjectMgr.GetArenaTeamByName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S); return; } if (sObjectMgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_INVALID); return; } } ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(charterid); if (!pProto) { _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, charterid, 0); return; } if (_player->GetMoney() < sWorld.getConfig(CONFIG_UNIT32_GUILD_PETITION_COST)) { // player hasn't got enough money _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, charterid, 0); return; } ItemPosCountVec dest; InventoryResult msg = _player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, charterid, pProto->BuyCount); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, NULL, NULL, charterid); return; } _player->ModifyMoney(-int64(sWorld.getConfig(CONFIG_UNIT32_GUILD_PETITION_COST))); Item* charter = _player->StoreNewItem(dest, GUILD_CHARTER, true); if (!charter) { return; } charter->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1, charter->GetGUIDLow()); // ITEM_FIELD_ENCHANTMENT_1_1 is guild/arenateam id // ITEM_FIELD_ENCHANTMENT_1_1+1 is current signatures count (showed on item) charter->SetState(ITEM_CHANGED, _player); _player->SendNewItem(charter, 1, true, false); // a petition is invalid, if both the owner and the type matches // we checked above, if this player is in an arenateam, so this must be data corruption QueryResult* result = CharacterDatabase.PQuery("SELECT `petitionguid` FROM `petition` WHERE `ownerguid` = '%u' AND `type` = '%u'", _player->GetGUIDLow(), type); std::ostringstream ssInvalidPetitionGUIDs; if (result) { do { Field* fields = result->Fetch(); ssInvalidPetitionGUIDs << "'" << fields[0].GetUInt32() << "' , "; } while (result->NextRow()); delete result; } // delete petitions with the same guid as this one ssInvalidPetitionGUIDs << "'" << charter->GetGUIDLow() << "'"; DEBUG_LOG("Invalid petition GUIDs: %s", ssInvalidPetitionGUIDs.str().c_str()); CharacterDatabase.escape_string(name); CharacterDatabase.BeginTransaction(); CharacterDatabase.PExecute("DELETE FROM `petition` WHERE `petitionguid` IN ( %s )", ssInvalidPetitionGUIDs.str().c_str()); CharacterDatabase.PExecute("DELETE FROM `petition_sign` WHERE `petitionguid` IN ( %s )", ssInvalidPetitionGUIDs.str().c_str()); CharacterDatabase.PExecute("INSERT INTO `petition` (`ownerguid`, `petitionguid`, `name`, `type`) VALUES ('%u', '%u', '%s', '%u')", _player->GetGUIDLow(), charter->GetGUIDLow(), name.c_str(), type); CharacterDatabase.CommitTransaction(); } void WorldSession::HandlePetitionShowSignOpcode(WorldPacket& recv_data) { // ok DEBUG_LOG("Received opcode CMSG_PETITION_SHOW_SIGNATURES"); // recv_data.hexlike(); uint8 signs = 0; ObjectGuid petitionguid; recv_data >> petitionguid; // petition guid // solve (possible) some strange compile problems with explicit use GUID_LOPART(petitionguid) at some GCC versions (wrong code optimization in compiler?) uint32 petitionguid_low = petitionguid.GetCounter(); QueryResult* result = CharacterDatabase.PQuery("SELECT `type` FROM `petition` WHERE `petitionguid` = '%u'", petitionguid_low); if (!result) { sLog.outError("any petition on server..."); return; } Field* fields = result->Fetch(); uint32 type = fields[0].GetUInt32(); delete result; // if guild petition and has guild => error, return; if (type == 9 && _player->GetGuildId()) { return; } result = CharacterDatabase.PQuery("SELECT `playerguid` FROM `petition_sign` WHERE `petitionguid` = '%u'", petitionguid_low); // result==NULL also correct in case no sign yet if (result) { signs = (uint8)result->GetRowCount(); } DEBUG_LOG("CMSG_PETITION_SHOW_SIGNATURES petition: %s", petitionguid.GetString().c_str()); WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8 + 8 + 4 + 1 + signs * 12)); data << ObjectGuid(petitionguid); // petition guid data << _player->GetObjectGuid(); // owner guid data << uint32(petitionguid_low); // guild guid (in mangos always same as GUID_LOPART(petitionguid) data << uint8(signs); // sign's count for (uint8 i = 1; i <= signs; ++i) { Field* fields2 = result->Fetch(); ObjectGuid signerGuid = ObjectGuid(HIGHGUID_PLAYER, fields2[0].GetUInt32()); data << ObjectGuid(signerGuid); // Player GUID data << uint32(0); // there 0 ... result->NextRow(); } delete result; SendPacket(&data); } void WorldSession::HandlePetitionQueryOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode CMSG_PETITION_QUERY"); // recv_data.hexlike(); uint32 guildguid; ObjectGuid petitionguid; recv_data >> guildguid; // in mangos always same as GUID_LOPART(petitionguid) recv_data >> petitionguid; // petition guid DEBUG_LOG("CMSG_PETITION_QUERY Petition %s Guild GUID %u", petitionguid.GetString().c_str(), guildguid); SendPetitionQueryOpcode(petitionguid); } void WorldSession::SendPetitionQueryOpcode(ObjectGuid petitionguid) { uint32 petitionLowGuid = petitionguid.GetCounter(); ObjectGuid ownerGuid; uint32 type; std::string name = "NO_NAME_FOR_GUID"; uint8 signs = 0; QueryResult* result = CharacterDatabase.PQuery( "SELECT `ownerguid`, `name`, " " (SELECT COUNT(`playerguid`) FROM `petition_sign` WHERE `petition_sign`.`petitionguid` = '%u') AS `signs`, " " `type` " "FROM `petition` WHERE `petitionguid` = '%u'", petitionLowGuid, petitionLowGuid); if (result) { Field* fields = result->Fetch(); ownerGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); name = fields[1].GetCppString(); signs = fields[2].GetUInt8(); type = fields[3].GetUInt32(); delete result; } else { DEBUG_LOG("CMSG_PETITION_QUERY failed for petition (GUID: %u)", petitionLowGuid); return; } WorldPacket data(SMSG_PETITION_QUERY_RESPONSE, (4 + 8 + name.size() + 1 + 1 + 4 * 13 + 2)); data << uint32(petitionLowGuid); // guild/team guid (in mangos always same as GUID_LOPART(petition guid) data << ObjectGuid(ownerGuid); // charter owner guid data << name; // name (guild/arena team) data << uint8(0); // 1 if (type == 9) { data << uint32(9); data << uint32(9); data << uint32(0); // bypass client - side limitation, a different value is needed here for each petition } else { data << uint32(type - 1); data << uint32(type - 1); data << uint32(type); // bypass client - side limitation, a different value is needed here for each petition } data << uint32(0); // 5 data << uint32(0); // 6 data << uint32(0); // 7 data << uint32(0); // 8 data << uint16(0); // 9 2 bytes field data << uint32(0); // 10 data << uint32(0); // 11 data << uint32(0); // 13 count of next strings? data << uint32(0); // 14 if (type == 9) { data << uint32(0); // 15 0 - guild, 1 - arena team } else { data << uint32(1); } SendPacket(&data); } void WorldSession::HandlePetitionRenameOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode MSG_PETITION_RENAME"); // ok // recv_data.hexlike(); ObjectGuid petitionGuid; uint32 type; std::string newname; recv_data >> petitionGuid; // guid recv_data >> newname; // new name Item* item = _player->GetItemByGuid(petitionGuid); if (!item) { return; } QueryResult* result = CharacterDatabase.PQuery("SELECT `type` FROM `petition` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); if (result) { Field* fields = result->Fetch(); type = fields[0].GetUInt32(); delete result; } else { DEBUG_LOG("CMSG_PETITION_QUERY failed for petition: %s", petitionGuid.GetString().c_str()); return; } if (type == 9) { if (sGuildMgr.GetGuildByName(newname)) { SendGuildCommandResult(GUILD_CREATE_S, newname, ERR_GUILD_NAME_EXISTS_S); return; } if (sObjectMgr.IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname)) { SendGuildCommandResult(GUILD_CREATE_S, newname, ERR_GUILD_NAME_INVALID); return; } } else { if (sObjectMgr.GetArenaTeamByName(newname)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_EXISTS_S); return; } if (sObjectMgr.IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_INVALID); return; } } std::string db_newname = newname; CharacterDatabase.escape_string(db_newname); CharacterDatabase.PExecute("UPDATE `petition` SET `name` = '%s' WHERE `petitionguid` = '%u'", db_newname.c_str(), petitionGuid.GetCounter()); DEBUG_LOG("Petition %s renamed to '%s'", petitionGuid.GetString().c_str(), newname.c_str()); WorldPacket data(MSG_PETITION_RENAME, (8 + newname.size() + 1)); data << ObjectGuid(petitionGuid); data << newname; SendPacket(&data); } void WorldSession::HandlePetitionSignOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode CMSG_PETITION_SIGN"); // ok // recv_data.hexlike(); Field* fields; ObjectGuid petitionGuid; uint8 unk; recv_data >> petitionGuid; // petition guid recv_data >> unk; uint32 petitionLowGuid = petitionGuid.GetCounter(); QueryResult* result = CharacterDatabase.PQuery( "SELECT `ownerguid`, " " (SELECT COUNT(`playerguid`) FROM `petition_sign` WHERE `petition_sign`.`petitionguid` = '%u') AS `signs`, " " `type` " "FROM `petition` WHERE `petitionguid` = '%u'", petitionLowGuid, petitionLowGuid); if (!result) { sLog.outError("any petition on server..."); return; } fields = result->Fetch(); uint32 ownerLowGuid = fields[0].GetUInt32(); ObjectGuid ownerGuid = ObjectGuid(HIGHGUID_PLAYER, ownerLowGuid); uint8 signs = fields[1].GetUInt8(); uint32 type = fields[2].GetUInt32(); delete result; if (ownerGuid == _player->GetObjectGuid()) { return; } // not let enemies sign guild charter if (!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != sObjectMgr.GetPlayerTeamByGUID(ownerGuid)) { if (type != 9) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED); } else { SendGuildCommandResult(GUILD_CREATE_S, "", ERR_GUILD_NOT_ALLIED); } return; } if (type != 9) { if (_player->getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", _player->GetName(), ERR_ARENA_TEAM_TARGET_TOO_LOW_S); return; } if (!IsArenaTypeValid(ArenaType(type))) { return; } uint8 slot = ArenaTeam::GetSlotByType(ArenaType(type)); if (slot >= MAX_ARENA_SLOT) { return; } if (_player->GetArenaTeamId(slot)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_IN_ARENA_TEAM_S); return; } if (_player->GetArenaTeamIdInvited()) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S); return; } } else { if (_player->GetGuildId()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_IN_GUILD_S); return; } if (_player->GetGuildIdInvited()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_INVITED_TO_GUILD_S); return; } } if (++signs > type) // client signs maximum { return; } // client doesn't allow to sign petition two times by one character, but not check sign by another character from same account // not allow sign another player from already sign player account result = CharacterDatabase.PQuery("SELECT `playerguid` FROM `petition_sign` WHERE `player_account` = '%u' AND `petitionguid` = '%u'", GetAccountId(), petitionLowGuid); if (result) { delete result; WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8 + 8 + 4)); data << ObjectGuid(petitionGuid); data << ObjectGuid(_player->GetObjectGuid()); data << uint32(PETITION_SIGN_ALREADY_SIGNED); // close at signer side SendPacket(&data); // update for owner if online if (Player* owner = sObjectMgr.GetPlayer(ownerGuid)) { owner->GetSession()->SendPacket(&data); } return; } CharacterDatabase.PExecute("INSERT INTO `petition_sign` (`ownerguid`,`petitionguid`, `playerguid`, `player_account`) VALUES ('%u', '%u', '%u','%u')", ownerLowGuid, petitionLowGuid, _player->GetGUIDLow(), GetAccountId()); DEBUG_LOG("PETITION SIGN: %s by %s", petitionGuid.GetString().c_str(), _player->GetGuidStr().c_str()); WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8 + 8 + 4)); data << ObjectGuid(petitionGuid); data << ObjectGuid(_player->GetObjectGuid()); data << uint32(PETITION_SIGN_OK); // close at signer side SendPacket(&data); // update signs count on charter, required testing... // Item *item = _player->GetItemByGuid(petitionguid)); // if (item) // item->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1+1, signs); // update for owner if online if (Player* owner = sObjectMgr.GetPlayer(ownerGuid)) { owner->GetSession()->SendPacket(&data); } } void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode MSG_PETITION_DECLINE"); // ok // recv_data.hexlike(); ObjectGuid petitionGuid; recv_data >> petitionGuid; // petition guid DEBUG_LOG("Petition %s declined by %s", petitionGuid.GetString().c_str(), _player->GetGuidStr().c_str()); uint32 petitionLowGuid = petitionGuid.GetCounter(); QueryResult* result = CharacterDatabase.PQuery("SELECT `ownerguid` FROM `petition` WHERE `petitionguid` = '%u'", petitionLowGuid); if (!result) { return; } Field* fields = result->Fetch(); ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); delete result; Player* owner = sObjectMgr.GetPlayer(ownerguid); if (owner) // petition owner online { WorldPacket data(MSG_PETITION_DECLINE, 8); data << _player->GetObjectGuid(); owner->GetSession()->SendPacket(&data); } } void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode CMSG_OFFER_PETITION"); // ok // recv_data.hexlike(); ObjectGuid petitionGuid; ObjectGuid playerGuid; uint32 junk; recv_data >> junk; // this is not petition type! recv_data >> petitionGuid; // petition guid recv_data >> playerGuid; // player guid Player* player = sObjectAccessor.FindPlayer(playerGuid); if (!player) { return; } /// Get petition type and check QueryResult* result = CharacterDatabase.PQuery("SELECT `type` FROM `petition` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); if (!result) { return; } Field* fields = result->Fetch(); uint32 type = fields[0].GetUInt32(); delete result; DEBUG_LOG("OFFER PETITION: type %u petition %s to %s", type, petitionGuid.GetString().c_str(), playerGuid.GetString().c_str()); if (!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != player->GetTeam()) { if (type != 9) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED); } else { SendGuildCommandResult(GUILD_CREATE_S, "", ERR_GUILD_NOT_ALLIED); } return; } if (type != 9) { if (player->getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { // player is too low level to join an arena team SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", player->GetName(), ERR_ARENA_TEAM_TARGET_TOO_LOW_S); return; } if (!IsArenaTypeValid(ArenaType(type))) { return; } uint8 slot = ArenaTeam::GetSlotByType(ArenaType(type)); if (slot >= MAX_ARENA_SLOT) { return; } if (player->GetArenaTeamId(slot)) { // player is already in an arena team SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", player->GetName(), ERR_ALREADY_IN_ARENA_TEAM_S); return; } if (player->GetArenaTeamIdInvited()) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S); return; } } else { if (player->GetGuildId()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_IN_GUILD_S); return; } if (player->GetGuildIdInvited()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_INVITED_TO_GUILD_S); return; } } /// Get petition signs count uint8 signs = 0; result = CharacterDatabase.PQuery("SELECT `playerguid` FROM `petition_sign` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); // result==NULL also correct charter without signs if (result) { signs = (uint8)result->GetRowCount(); } /// Send response WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8 + 8 + 4 + signs + signs * 12)); data << ObjectGuid(petitionGuid); // petition guid data << ObjectGuid(_player->GetObjectGuid()); // owner guid data << uint32(petitionGuid.GetCounter()); // guild guid (in mangos always same as low part of petition guid) data << uint8(signs); // sign's count for (uint8 i = 1; i <= signs; ++i) { Field* fields2 = result->Fetch(); ObjectGuid signerGuid = ObjectGuid(HIGHGUID_PLAYER, fields2[0].GetUInt32()); data << ObjectGuid(signerGuid); // Player GUID data << uint32(0); // there 0 ... result->NextRow(); } delete result; player->GetSession()->SendPacket(&data); } void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode CMSG_TURN_IN_PETITION"); // ok // recv_data.hexlike(); ObjectGuid petitionGuid; recv_data >> petitionGuid; DEBUG_LOG("Petition %s turned in by %s", petitionGuid.GetString().c_str(), _player->GetGuidStr().c_str()); /// Collect petition info data ObjectGuid ownerGuid; uint32 type; std::string name; // data QueryResult* result = CharacterDatabase.PQuery("SELECT `ownerguid`, `name`, `type` FROM `petition` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); if (result) { Field* fields = result->Fetch(); ownerGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); name = fields[1].GetCppString(); type = fields[2].GetUInt32(); delete result; } else { sLog.outError("CMSG_TURN_IN_PETITION: petition table not have data for guid %u!", petitionGuid.GetCounter()); return; } if (type == 9) { if (_player->GetGuildId()) { WorldPacket data(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_ALREADY_IN_GUILD); // already in guild _player->GetSession()->SendPacket(&data); return; } } else { if (!IsArenaTypeValid(ArenaType(type))) { return; } uint8 slot = ArenaTeam::GetSlotByType(ArenaType(type)); if (slot >= MAX_ARENA_SLOT) { return; } if (_player->GetArenaTeamId(slot)) { // data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); // data << (uint32)PETITION_TURN_ALREADY_IN_GUILD; // already in guild //_player->GetSession()->SendPacket(&data); SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM); return; } } if (_player->GetObjectGuid() != ownerGuid) { return; } // signs result = CharacterDatabase.PQuery("SELECT `playerguid` FROM `petition_sign` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); uint8 signs = result ? (uint8)result->GetRowCount() : 0; uint32 count = type == 9 ? sWorld.getConfig(CONFIG_UINT32_MIN_PETITION_SIGNS) : type - 1; if (signs < count) { WorldPacket data(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_NEED_MORE_SIGNATURES); // need more signatures... SendPacket(&data); delete result; return; } if (type == 9) { if (sGuildMgr.GetGuildByName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, ERR_GUILD_NAME_EXISTS_S); delete result; return; } } else { if (sObjectMgr.GetArenaTeamByName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S); delete result; return; } } // and at last charter item check Item* item = _player->GetItemByGuid(petitionGuid); if (!item) { delete result; return; } // OK! // delete charter item _player->DestroyItem(item->GetBagSlot(), item->GetSlot(), true); if (type == 9) // create guild { Guild* guild = new Guild; if (!guild->Create(_player, name)) { delete guild; delete result; return; } // register guild and add guildmaster sGuildMgr.AddGuild(guild); // add members for (uint8 i = 0; i < signs; ++i) { Field* fields = result->Fetch(); ObjectGuid signGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); if (signGuid.IsEmpty()) { continue; } guild->AddMember(signGuid, guild->GetLowestRank()); result->NextRow(); } } else // or arena team { ArenaTeam* at = new ArenaTeam; if (!at->Create(_player->GetObjectGuid(), ArenaType(type), name)) { sLog.outError("PetitionsHandler: arena team create failed."); delete at; delete result; return; } uint32 icon, iconcolor, border, bordercolor, backgroud; recv_data >> backgroud >> icon >> iconcolor >> border >> bordercolor; at->SetEmblem(backgroud, icon, iconcolor, border, bordercolor); // register team and add captain sObjectMgr.AddArenaTeam(at); DEBUG_LOG("PetitonsHandler: arena team added to objmrg"); // add members for (uint8 i = 0; i < signs; ++i) { Field* fields = result->Fetch(); ObjectGuid memberGUID = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); if (!memberGUID) { continue; } DEBUG_LOG("PetitionsHandler: adding arena member %s", memberGUID.GetString().c_str()); at->AddMember(memberGUID); result->NextRow(); } } delete result; CharacterDatabase.BeginTransaction(); CharacterDatabase.PExecute("DELETE FROM `petition` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); CharacterDatabase.PExecute("DELETE FROM `petition_sign` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); CharacterDatabase.CommitTransaction(); // created DEBUG_LOG("TURN IN PETITION %s", petitionGuid.GetString().c_str()); WorldPacket data(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_OK); SendPacket(&data); } void WorldSession::HandlePetitionShowListOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received CMSG_PETITION_SHOWLIST"); // recv_data.hexlike(); ObjectGuid guid; recv_data >> guid; SendPetitionShowList(guid); } void WorldSession::SendPetitionShowList(ObjectGuid guid) { Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_PETITIONER); if (!pCreature) { DEBUG_LOG("WORLD: HandlePetitionShowListOpcode - %s not found or you can't interact with him.", guid.GetString().c_str()); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) { GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); } uint8 count = 0; if (pCreature->IsTabardDesigner()) { count = 1; } else { count = 3; } WorldPacket data(SMSG_PETITION_SHOWLIST, 8 + 1 + 4 * 6); data << guid; // npc guid if (pCreature->IsTabardDesigner()) { data << uint8(1); // count data << uint32(1); // index data << uint32(GUILD_CHARTER); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(sWorld.getConfig(CONFIG_UNIT32_GUILD_PETITION_COST)); // charter cost data << uint32(0); // unknown data << uint32(4); // required signs } else { data << uint8(count); // count if (count == 1) { data << uint32(1); // index data << uint32(GUILD_CHARTER); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(GUILD_CHARTER_COST); // charter cost data << uint32(0); // unknown data << uint32(9); // required signs? } else { // 2v2 data << uint32(1); // index data << uint32(ARENA_TEAM_CHARTER_2v2); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(ARENA_TEAM_CHARTER_2v2_COST); // charter cost data << uint32(2); // unknown data << uint32(2); // required signs? // 3v3 data << uint32(2); // index data << uint32(ARENA_TEAM_CHARTER_3v3); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(ARENA_TEAM_CHARTER_3v3_COST); // charter cost data << uint32(3); // unknown data << uint32(3); // required signs? // 5v5 data << uint32(3); // index data << uint32(ARENA_TEAM_CHARTER_5v5); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(ARENA_TEAM_CHARTER_5v5_COST); // charter cost data << uint32(5); // unknown data << uint32(5); // required signs? } } SendPacket(&data); DEBUG_LOG("Sent SMSG_PETITION_SHOWLIST"); }
412
0.930422
1
0.930422
game-dev
MEDIA
0.5663
game-dev
0.936725
1
0.936725
fxgenstudio/MGShaderEditor
3,135
Src/MonoGame.Framework/Graphics/PackedVector/HalfTypeHelper.cs
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Runtime.InteropServices; namespace Microsoft.Xna.Framework.Graphics.PackedVector { internal class HalfTypeHelper { [StructLayout(LayoutKind.Explicit)] private struct uif { [FieldOffset(0)] public float f; [FieldOffset(0)] public int i; [FieldOffset(0)] public uint u; } internal static UInt16 Convert(float f) { uif uif = new uif(); uif.f = f; return Convert(uif.i); } internal static UInt16 Convert(int i) { int s = (i >> 16) & 0x00008000; int e = ((i >> 23) & 0x000000ff) - (127 - 15); int m = i & 0x007fffff; if (e <= 0) { if (e < -10) { return (UInt16)s; } m = m | 0x00800000; int t = 14 - e; int a = (1 << (t - 1)) - 1; int b = (m >> t) & 1; m = (m + a + b) >> t; return (UInt16)(s | m); } else if (e == 0xff - (127 - 15)) { if (m == 0) { return (UInt16)(s | 0x7c00); } else { m >>= 13; return (UInt16)(s | 0x7c00 | m | ((m == 0) ? 1 : 0)); } } else { m = m + 0x00000fff + ((m >> 13) & 1); if ((m & 0x00800000) != 0) { m = 0; e += 1; } if (e > 30) { return (UInt16)(s | 0x7c00); } return (UInt16)(s | (e << 10) | (m >> 13)); } } internal static float Convert(ushort value) { uint rst; uint mantissa = (uint)(value & 1023); uint exp = 0xfffffff2; if ((value & -33792) == 0) { if (mantissa != 0) { while ((mantissa & 1024) == 0) { exp--; mantissa = mantissa << 1; } mantissa &= 0xfffffbff; rst = ((uint)((((uint)value & 0x8000) << 16) | ((exp + 127) << 23))) | (mantissa << 13); } else { rst = (uint)((value & 0x8000) << 16); } } else { rst = (uint)(((((uint)value & 0x8000) << 16) | ((((((uint)value >> 10) & 0x1f) - 15) + 127) << 23)) | (mantissa << 13)); } var uif = new uif(); uif.u = rst; return uif.f; } } }
412
0.93174
1
0.93174
game-dev
MEDIA
0.704162
game-dev
0.995043
1
0.995043
osoykan-archive/ProductContext-EventSourcing
4,047
lib/Value/Value/DictionaryByValue.cs
// // -------------------------------------------------------------------------------------------------------------------- // // <copyright file="EquatableByValue.cs"> // // Copyright 2017 // // Thomas PIERRAIN (@tpierrain) // // 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.b // // </copyright> // // -------------------------------------------------------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Linq; namespace Value { /// <summary> /// A dictionary with equality based on its content and not on the dictionary's reference /// (i.e.: 2 different instances containing the same entries will be equals). /// </summary> /// <remarks>This type is not thread-safe (for hashcode updates).</remarks> /// <typeparam name="K">The type of keys in the dictionary.</typeparam> /// <typeparam name="V">The type of values in the dictionary.</typeparam> public class DictionaryByValue<K, V> : EquatableByValueWithoutOrder<DictionaryByValue<K, V>>, IDictionary<K, V> { private readonly IDictionary<K, V> dictionary; public DictionaryByValue(IDictionary<K, V> dictionary) { this.dictionary = dictionary; } IEnumerator IEnumerable.GetEnumerator() => dictionary.GetEnumerator(); public IEnumerator<KeyValuePair<K, V>> GetEnumerator() => dictionary.GetEnumerator(); public void Add(KeyValuePair<K, V> item) { ResetHashCode(); dictionary.Add(item); } public void Clear() { ResetHashCode(); dictionary.Clear(); } public bool Contains(KeyValuePair<K, V> item) => dictionary.Contains(item); public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) { dictionary.CopyTo(array, arrayIndex); } public bool Remove(KeyValuePair<K, V> item) { ResetHashCode(); return dictionary.Remove(item); } public int Count => dictionary.Count; public bool IsReadOnly => dictionary.IsReadOnly; public bool ContainsKey(K key) => dictionary.ContainsKey(key); public void Add(K key, V value) { ResetHashCode(); dictionary.Add(key, value); } public bool Remove(K key) { ResetHashCode(); return dictionary.Remove(key); } public bool TryGetValue(K key, out V value) => dictionary.TryGetValue(key, out value); public V this[K key] { get => dictionary[key]; set { ResetHashCode(); dictionary[key] = value; } } public ICollection<K> Keys => dictionary.Keys; public ICollection<V> Values => dictionary.Values; protected override IEnumerable<object> GetAllAttributesToBeUsedForEquality() { foreach (var kv in dictionary) { yield return kv; } } protected override bool EqualsWithoutOrderImpl(EquatableByValueWithoutOrder<DictionaryByValue<K, V>> obj) { var other = obj as DictionaryByValue<K, V>; if (other == null) { return false; } return !dictionary.Except(other).Any(); } } }
412
0.794886
1
0.794886
game-dev
MEDIA
0.459871
game-dev
0.654783
1
0.654783
gameplay3d/gameplay
3,011
gameplay/src/AIState.h
#ifndef AISTATE_H_ #define AISTATE_H_ #include "Ref.h" namespace gameplay { class AIAgent; class AIStateMachine; /** * Defines a single state in an AIStateMachine. * * An AIState encapsulates a state and unit of work within an AI * state machine. Events can be programmed or scripted when the * state is entered, exited and each frame/tick in its update event. */ class AIState : public Ref { friend class AIStateMachine; public: /** * Interface for listening to AIState events. */ class Listener { public: /** * Virtual destructor. */ virtual ~Listener(); /** * Called when a state is entered. * * @param agent The AIAgent this state event is for. * @param state The state that was entered. */ virtual void stateEnter(AIAgent* agent, AIState* state); /** * Called when a state is exited. * * @param agent The AIAgent this state event is for. * @param state The state that was exited. */ virtual void stateExit(AIAgent* agent, AIState* state); /** * Called once per frame when for a state when it is active. * * This method is normally where the logic for a state is implemented. * * @param agent The AIAgent this state event is for. * @param state The active AIState. * @param elapsedTime The elapsed time, in milliseconds. */ virtual void stateUpdate(AIAgent* agent, AIState* state, float elapsedTime); }; /** * Creates a new AISTate. * * @param id The ID of the new AIState. * * @return The new AIState. * @script{create} */ static AIState* create(const char* id); /** * Returns the ID of this state. * * @return The state ID. */ const char* getId() const; /** * Sets a listener to dispatch state events to. * * @param listener Listener to dispatch state events to, or NULL to disable event dispatching. */ void setListener(Listener* listener); private: /** * Constructs a new AIState. */ AIState(const char* id); /** * Destructor. */ ~AIState(); /** * Hidden copy constructor. */ AIState(const AIState&); /** * Hidden copy assignment operator. */ AIState& operator=(const AIState&); /** * Called by AIStateMachine when this state is being entered. */ void enter(AIStateMachine* stateMachine); /** * Called by AIStateMachine when this state is being exited. */ void exit(AIStateMachine* stateMachine); /** * Called by AIStateMachine once per frame to update this state when it is active. */ void update(AIStateMachine* stateMachine, float elapsedTime); std::string _id; Listener* _listener; // The default/empty state. static AIState* _empty; }; } #endif
412
0.709134
1
0.709134
game-dev
MEDIA
0.32512
game-dev
0.525405
1
0.525405
lgi-devs/lgi
9,664
lgi/override/GObject-Closure.lua
------------------------------------------------------------------------------ -- -- LGI GClosure handling and marshalling of callables in GValues -- arrays as arguments. -- -- Copyright (c) 2010, 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local type, pairs, ipairs, unpack = type, pairs, ipairs, unpack or table.unpack local core = require 'lgi.core' local gi = core.gi local repo = core.repo local Type, Value = repo.GObject.Type, repo.GObject.Value -- Implementation of closure support, together with marshalling. local Closure = repo.GObject.Closure local closure_info = gi.GObject.Closure -- CallInfo is object based on GICallable, allowing marshalling -- from/to GValue arrays. local CallInfo = {} CallInfo.__index = CallInfo -- Compile callable_info into table which allows fast marshalling function CallInfo.new(callable_info, to_lua) local self = setmetatable( { has_self = (callable_info.is_signal or callable_info.is_virtual) }, CallInfo) local argc, gtype = 0 -- If this is a C array with explicit length argument, mark it. local function mark_array_length(cell, ti) local len = ti.array_length if len then cell.len_index = 1 + len + (self.has_self and 1 or 0) if not self[cell.len_index] then self[cell.len_index] = {} end self[cell.len_index].internal = true end end -- Fill in 'self' argument. if self.has_self then argc = 1 gtype = callable_info.container.gtype self[1] = { dir = 'in', gtype = gtype, [to_lua and 'to_lua' or 'to_value'] = Value.find_marshaller(gtype) } end -- Go through arguments. local phantom_return for i = 1, #callable_info.args do local ai = callable_info.args[i] local ti = ai.typeinfo -- Prepare parameter cell in self array. argc = argc + 1 if not self[argc] then self[argc] = {} end local cell = self[argc] -- Fill in marshaller(s) for the cell. cell.dir = ai.direction if cell.dir == 'in' then -- Direct marshalling into value. cell.gtype = Type.from_typeinfo(ti) local marshaller = Value.find_marshaller(cell.gtype, ti, ti.transfer) cell[to_lua and 'to_lua' or 'to_value'] = marshaller else -- Indirect marshalling, value contains just pointer to the -- real storage pointer. Used for inout and out arguments. cell.gtype = Type.POINTER local marshaller = Value.find_marshaller(cell.gtype) if to_lua then if cell.dir == 'inout' then function cell.to_lua(value, params) local arg = marshaller(value, nil) return core.marshal.argument(arg, ti, ti.transfer) end end function cell.to_value(value, params, val) local arg = marshaller(value, nil) core.marshal.argument(arg, ti, ti.transfer, val) end else function cell.to_value(value, params, val) local arg, ptr = core.marshal.argument() params[cell] = arg marshaller(value, nil, ptr) if cell.dir == 'inout' then -- Marshal input to the argument. core.marshal.argument(arg, ti, ti.transfer, val) else -- Returning true indicates that input argument should -- actually not be consumed, because we are just -- preparing slot for the output value. return true end end function cell.to_lua(value, params) local arg = params[cell] return core.marshal.argument(arg, ti, ti.transfer) end end end mark_array_length(cell, ti) -- Check for output parameters; if present, enable -- phantom-return heuristics. phantom_return = phantom_return or cell.dir == 'out' end -- Prepare retval marshalling. local ti = callable_info.return_type if ti.tag ~= 'void' or ti.is_pointer then gtype = Type.from_typeinfo(ti) local ret = { dir = 'out', gtype = gtype, to_value = Value.find_marshaller( gtype, ti, callable_info.return_transfer) } mark_array_length(ret, ti) if phantom_return and ti.tag == 'gboolean' then self.phantom = ret else self.ret = ret end end return self end -- Marshal single call_info cell (either input or output). local function marshal_cell( call_info, cell, direction, args, argc, marshalling_params, value, params, retval) local marshaller = cell[direction] if not marshaller or cell.internal then return argc end argc = argc + 1 local length_marshaller if cell.len_index then -- Prepare length argument marshaller. length_marshaller = call_info[cell.len_index][direction] if direction == 'to_lua' then marshalling_params.length = length_marshaller( params[cell.len_index], {}) end end if direction == 'to_lua' then -- Marshal from GValue to Lua args[argc] = marshaller(value, marshalling_params) else -- Marshal from Lua to GValue if marshaller(value, marshalling_params, args[argc]) then -- When true is returned, we were just preparing slot for the -- output value, so do not consume the argument. argc = argc - 1 end -- Marshal array length output, if applicable. if length_marshaller then length_marshaller(params[cell.len_index], {}, marshalling_params.length) end -- Marshal phantom return, if applicable. if retval and call_info.phantom and args[argc] == nil then call_info.phantom.to_value(retval, marshalling_params, false) end end return argc end -- Creates GClosure marshaller based on compiled CallInfo. function CallInfo:get_closure_marshaller(target) return function(closure, retval, params) local marshalling_params = { keepalive = {} } local args, argc = {}, 0 -- Marshal input arguments. for i = 1, #self do argc = marshal_cell( self, self[i], 'to_lua', args, argc, marshalling_params, params[i], params) end -- Do the call. args = { target(unpack(args, 1, argc)) } argc = 0 marshalling_params.keepalive = {} -- Marshall the return value. if self.ret and retval then argc = marshal_cell( self, self.ret, 'to_value', args, argc, marshalling_params, retval, params) end -- Prepare 'true' into phantom return, will be reset to 'false' -- when some output argument is returned as 'nil'. if self.phantom and retval then self.phantom.to_value(retval, marshalling_params, true) end -- Marshal output arguments. for i = 1, #self do argc = marshal_cell( self, self[i], 'to_value', args, argc, marshalling_params, params[i], params, retval) end end end -- Marshalls Lua arguments into Values suitable for invoking closures -- and signals. Returns Value (for retval), array of Value (for -- params) and keepalive value (which must be kept alive during the -- call) function CallInfo:pre_call(...) -- Prepare array of param values and initialize them with correct type. local params = {} for i = 1, #self do params[#params + 1] = Value(self[i].gtype) end local marshalling_params = { keepalive = {} } -- Marshal input values. local args, argc = { ... }, 0 for i = 1, #self do argc = marshal_cell( self, self[i], 'to_value', args, argc, marshalling_params, params[i], params) end -- Prepare return value. local retval = Value() if self.ret then retval.type = self.ret.gtype end if self.phantom then retval.type = self.phantom.gtype end return retval, params, marshalling_params end -- Unmarshalls Lua restuls from Values after invoking closure or -- signal. Returns all unmarshalled Lua values. function CallInfo:post_call(params, retval, marshalling_params) marshalling_params.keepalive = {} local args, argc = {}, 0 -- Check, whether phantom return exists and returned 'false'. If -- yes, return just nil. if (self.phantom and not self.phantom.to_lua(retval, marshalling_params)) then return nil end -- Unmarshal return value. if self.ret and retval then argc = marshal_cell( self, self.ret, 'to_lua', args, argc, marshalling_params, retval, params) end -- Unmarshal output arguments. for i = 1, #self do argc = marshal_cell( self, self[i], 'to_lua', args, argc, marshalling_params, params[i], params) end -- Return all created Lua values. return unpack(args, 1, argc) end -- Create new closure invoking Lua target function (or anything else -- that can be called). Optionally callback_info specifies detailed -- information about how to marshal signals. function Closure:_new(target, callback_info) local closure = Closure._method.new_simple(closure_info.size, nil) if target then local marshaller if callback_info then -- Create marshaller based on callinfo. local call_info = CallInfo.new(callback_info, true) marshaller = call_info:get_closure_marshaller(target) else -- Create marshaller based only on Value types. function marshaller(closure, retval, params) local args = {} for i, val in ipairs(params) do args[i] = val.value end local ret = target(unpack(args, 1, #params)) if retval then retval.value = ret end end end core.marshal.closure_set_marshal(closure, marshaller) end Closure.ref(closure) Closure.sink(closure) return closure end -- Use native marshalling for g_closure_invoke Closure.invoke = core.marshal.closure_invoke -- Export CallInfo as field of Closure. Closure.CallInfo = CallInfo
412
0.911309
1
0.911309
game-dev
MEDIA
0.794746
game-dev
0.927941
1
0.927941
openmultiplayer/web
2,186
frontend/docs/scripting/functions/GameTextForAll.md
--- title: GameTextForAll sidebar_label: GameTextForAll description: Shows 'game text' (on-screen text) for a certain length of time for all players. tags: ["gametext"] --- ## Description Shows 'game text' (on-screen text) for a certain length of time for all players. | Name | Description | |------------------|-------------------------------------------------------------------| | const format[] | The text to be displayed. | | time | The duration of the text being shown in milliseconds. | | style | The [style](../resources/gametextstyles) of text to be displayed. | | OPEN_MP_TAGS:... | Indefinite number of arguments of any tag. | ## Returns This function always returns 1. ## Examples ```c public OnPlayerDeath(playerid, killerid, WEAPON:reason) { // This example shows a large, white text saying "[playerName] has // passed away" on everyone's screen, after a player has died or // has been killed. It shows in text-type 3, for 5 seconds (5000 ms) new name[MAX_PLAYER_NAME]; GetPlayerName(playerid, name, sizeof(name)); // Format the passed-away message properly, and show it to everyone: new string[64]; format(string, sizeof(string), "~w~%s has passed away", name); GameTextForAll(string, 5000, 3); // PRO TIP: You don't need `format` in open.mp GameTextForAll("~w~%s has passed away", 5000, 3, name); return 1; } ``` ## Notes :::warning Do note that the players may crash because of odd number of tilde (~) symbols used in the game text. Using color codes (e.g. ~r~) beyond the 255th character may crash the client. ::: ## Related Functions - [HideGameTextForAll](HideGameTextForAll): Stop showing a gametext style for all players. - [GameTextForPlayer](GameTextForPlayer): Display gametext to a player. - [HideGameTextForPlayer](HideGameTextForPlayer): Stop showing a gametext style to a player. - [TextDrawShowForAll](TextDrawShowForAll): Show a textdraw for all players. ## Related Resources - [GameText Styles](../resources/gametextstyles)
412
0.824107
1
0.824107
game-dev
MEDIA
0.816256
game-dev
0.942004
1
0.942004
LayTec-AG/Plotly.Blazor
3,272
Plotly.Blazor/Traces/ScatterMapBoxLib/Legendgrouptitle.cs
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text.Json.Serialization; namespace Plotly.Blazor.Traces.ScatterMapBoxLib { /// <summary> /// The LegendGroupTitle class. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", null)] [Serializable] public class LegendGroupTitle : IEquatable<LegendGroupTitle> { /// <summary> /// Sets this legend group&#39;s title font. /// </summary> [JsonPropertyName(@"font")] public Plotly.Blazor.Traces.ScatterMapBoxLib.LegendGroupTitleLib.Font Font { get; set;} /// <summary> /// Sets the title of the legend group. /// </summary> [JsonPropertyName(@"text")] public string Text { get; set;} /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is LegendGroupTitle other)) return false; return ReferenceEquals(this, obj) || Equals(other); } /// <inheritdoc /> public bool Equals([AllowNull] LegendGroupTitle other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return ( Font == other.Font || Font != null && Font.Equals(other.Font) ) && ( Text == other.Text || Text != null && Text.Equals(other.Text) ); } /// <inheritdoc /> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; if (Font != null) hashCode = hashCode * 59 + Font.GetHashCode(); if (Text != null) hashCode = hashCode * 59 + Text.GetHashCode(); return hashCode; } } /// <summary> /// Checks for equality of the left LegendGroupTitle and the right LegendGroupTitle. /// </summary> /// <param name="left">Left LegendGroupTitle.</param> /// <param name="right">Right LegendGroupTitle.</param> /// <returns>Boolean</returns> public static bool operator == (LegendGroupTitle left, LegendGroupTitle right) { return Equals(left, right); } /// <summary> /// Checks for inequality of the left LegendGroupTitle and the right LegendGroupTitle. /// </summary> /// <param name="left">Left LegendGroupTitle.</param> /// <param name="right">Right LegendGroupTitle.</param> /// <returns>Boolean</returns> public static bool operator != (LegendGroupTitle left, LegendGroupTitle right) { return !Equals(left, right); } /// <summary> /// Gets a deep copy of this instance. /// </summary> /// <returns>LegendGroupTitle</returns> public LegendGroupTitle DeepClone() { return this.Copy(); } } }
412
0.692694
1
0.692694
game-dev
MEDIA
0.497109
game-dev
0.80208
1
0.80208
ImLegiitXD/Dream-Advanced
4,279
dll/back/1.12/net/minecraft/src/ReflectorForge.java
package net.minecraft.src; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Map; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; public class ReflectorForge { public static void FMLClientHandler_trackBrokenTexture(ResourceLocation p_FMLClientHandler_trackBrokenTexture_0_, String p_FMLClientHandler_trackBrokenTexture_1_) { if (!Reflector.FMLClientHandler_trackBrokenTexture.exists()) { Object object = Reflector.call(Reflector.FMLClientHandler_instance); Reflector.call(object, Reflector.FMLClientHandler_trackBrokenTexture, p_FMLClientHandler_trackBrokenTexture_0_, p_FMLClientHandler_trackBrokenTexture_1_); } } public static void FMLClientHandler_trackMissingTexture(ResourceLocation p_FMLClientHandler_trackMissingTexture_0_) { if (!Reflector.FMLClientHandler_trackMissingTexture.exists()) { Object object = Reflector.call(Reflector.FMLClientHandler_instance); Reflector.call(object, Reflector.FMLClientHandler_trackMissingTexture, p_FMLClientHandler_trackMissingTexture_0_); } } public static void putLaunchBlackboard(String p_putLaunchBlackboard_0_, Object p_putLaunchBlackboard_1_) { Map map = (Map)Reflector.getFieldValue(Reflector.Launch_blackboard); if (map != null) { map.put(p_putLaunchBlackboard_0_, p_putLaunchBlackboard_1_); } } public static boolean renderFirstPersonHand(RenderGlobal p_renderFirstPersonHand_0_, float p_renderFirstPersonHand_1_, int p_renderFirstPersonHand_2_) { return !Reflector.ForgeHooksClient_renderFirstPersonHand.exists() ? false : Reflector.callBoolean(Reflector.ForgeHooksClient_renderFirstPersonHand, p_renderFirstPersonHand_0_, p_renderFirstPersonHand_1_, p_renderFirstPersonHand_2_); } public static InputStream getOptiFineResourceStream(String p_getOptiFineResourceStream_0_) { if (!Reflector.OptiFineClassTransformer_instance.exists()) { return null; } else { Object object = Reflector.getFieldValue(Reflector.OptiFineClassTransformer_instance); if (object == null) { return null; } else { if (p_getOptiFineResourceStream_0_.startsWith("/")) { p_getOptiFineResourceStream_0_ = p_getOptiFineResourceStream_0_.substring(1); } byte[] abyte = (byte[])Reflector.call(object, Reflector.OptiFineClassTransformer_getOptiFineResource, p_getOptiFineResourceStream_0_); if (abyte == null) { return null; } else { InputStream inputstream = new ByteArrayInputStream(abyte); return inputstream; } } } } public static boolean blockHasTileEntity(IBlockState p_blockHasTileEntity_0_) { Block block = p_blockHasTileEntity_0_.getBlock(); return !Reflector.ForgeBlock_hasTileEntity.exists() ? block.hasTileEntity() : Reflector.callBoolean(block, Reflector.ForgeBlock_hasTileEntity, p_blockHasTileEntity_0_); } public static boolean isItemDamaged(ItemStack p_isItemDamaged_0_) { return !Reflector.ForgeItem_showDurabilityBar.exists() ? p_isItemDamaged_0_.isItemDamaged() : Reflector.callBoolean(p_isItemDamaged_0_.getItem(), Reflector.ForgeItem_showDurabilityBar, p_isItemDamaged_0_); } public static boolean armorHasOverlay(ItemArmor p_armorHasOverlay_0_, ItemStack p_armorHasOverlay_1_) { if (Reflector.ForgeItemArmor_hasOverlay.exists()) { return Reflector.callBoolean(p_armorHasOverlay_0_, Reflector.ForgeItemArmor_hasOverlay, p_armorHasOverlay_1_); } else { int i = p_armorHasOverlay_0_.getColor(p_armorHasOverlay_1_); return i != 16777215; } } }
412
0.74801
1
0.74801
game-dev
MEDIA
0.903133
game-dev
0.938145
1
0.938145
keijiro/OscKlak
2,090
Assets/Klak Imported/Wiring/Output/FloatOut.cs
// // Klak - Utilities for creative coding with Unity // // Copyright (C) 2016 Keijiro Takahashi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using UnityEngine; using System.Reflection; namespace Klak.Wiring { [AddComponentMenu("Klak/Wiring/Output/Generic/Float Out")] public class FloatOut : NodeBase { #region Editable properties [SerializeField] Component _target; [SerializeField] string _propertyName; #endregion #region Node I/O [Inlet] public float input { set { if (!enabled || _target == null || _propertyInfo == null) return; _propertyInfo.SetValue(_target, value, null); } } #endregion #region Private members PropertyInfo _propertyInfo; void OnEnable() { if (_target == null || string.IsNullOrEmpty(_propertyName)) return; _propertyInfo = _target.GetType().GetProperty(_propertyName); } #endregion } }
412
0.831365
1
0.831365
game-dev
MEDIA
0.909119
game-dev
0.751529
1
0.751529
arkeus/Axel
2,215
src/org/axgl/particle/AxParticleSystem.as
package org.axgl.particle { import flash.utils.Dictionary; import org.axgl.AxEntity; import org.axgl.AxGroup; /** * A generic particle system to keep track of your particle effects, and allow you to create your effects * from anywhere within the game. */ public class AxParticleSystem { /** * A mapping of all your particle effects by name. */ private static var effects:Dictionary = new Dictionary; /** * An internal counter used to "randomize" which instance of a particle effect is shown. */ private static var counter:Number = 0; /** * Registers a new particle effect. After creating an effect, you must register it before you can * use it in your game. * * @param effect The effect to register. * * @return The group containing all the created instances of your effect. */ public static function register(effect:AxParticleEffect):AxGroup { var set:AxGroup = new AxGroup; var particleCloud:AxParticleCloud = new AxParticleCloud(effect).build(); for (var i:uint = 0; i < effect.max - 1; i++) { set.add(particleCloud.clone()); } set.add(particleCloud); effects[effect.name] = set; return set; } /** * Creates an instance of your particle effect on screen at the location provided. Note that to use this * you must have first registered the particle effect. If you already have more instances of this effect * showing on screen than you allocated, it will destroy one and reuse it for this new effect. If you use * the name of an effect that doesn't exist, nothing will happen. * * @param name The name of the particle effect to show. * @param x The x-position in world coordinates. * @param y The y-position in world coordinates. * * @return The instance of the particle effect that was placed on screen, null if the effect doesn't exist. */ public static function emit(name:String, x:Number, y:Number):AxParticleCloud { counter++; if (effects[name] == null) { return null; } var members:Vector.<AxEntity> = effects[name].members; var cloud:AxParticleCloud = members[counter % members.length] as AxParticleCloud; cloud.reset(x, y); return cloud; } } }
412
0.82173
1
0.82173
game-dev
MEDIA
0.935285
game-dev
0.949213
1
0.949213
stubma/cocos2dx-classical
9,585
external/chipmunk/src/chipmunk.c
/* Copyright (c) 2007 Scott Lembcke * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include "chipmunk_private.h" void cpMessage(const char *condition, const char *file, int line, cpBool isError, cpBool isHardError, const char *message, ...) { fprintf(stderr, (isError ? "Aborting due to Chipmunk error: " : "Chipmunk warning: ")); va_list vargs; va_start(vargs, message); { vfprintf(stderr, message, vargs); fprintf(stderr, "\n"); } va_end(vargs); fprintf(stderr, "\tFailed condition: %s\n", condition); fprintf(stderr, "\tSource:%s:%d\n", file, line); if(isError) abort(); } #define STR(s) #s #define XSTR(s) STR(s) const char *cpVersionString = XSTR(CP_VERSION_MAJOR)"."XSTR(CP_VERSION_MINOR)"."XSTR(CP_VERSION_RELEASE); void cpInitChipmunk(void) { cpAssertWarn(cpFalse, "cpInitChipmunk is deprecated and no longer required. It will be removed in the future."); } //MARK: Misc Functions cpFloat cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset) { return m*(0.5f*(r1*r1 + r2*r2) + cpvlengthsq(offset)); } cpFloat cpAreaForCircle(cpFloat r1, cpFloat r2) { return (cpFloat)M_PI*cpfabs(r1*r1 - r2*r2); } cpFloat cpMomentForSegment(cpFloat m, cpVect a, cpVect b) { cpVect offset = cpvmult(cpvadd(a, b), 0.5f); return m*(cpvdistsq(b, a)/12.0f + cpvlengthsq(offset)); } cpFloat cpAreaForSegment(cpVect a, cpVect b, cpFloat r) { return r*((cpFloat)M_PI*r + 2.0f*cpvdist(a, b)); } cpFloat cpMomentForPoly(cpFloat m, const int numVerts, const cpVect *verts, cpVect offset) { cpFloat sum1 = 0.0f; cpFloat sum2 = 0.0f; for(int i=0; i<numVerts; i++){ cpVect v1 = cpvadd(verts[i], offset); cpVect v2 = cpvadd(verts[(i+1)%numVerts], offset); cpFloat a = cpvcross(v2, v1); cpFloat b = cpvdot(v1, v1) + cpvdot(v1, v2) + cpvdot(v2, v2); sum1 += a*b; sum2 += a; } return (m*sum1)/(6.0f*sum2); } cpFloat cpAreaForPoly(const int numVerts, const cpVect *verts) { cpFloat area = 0.0f; for(int i=0; i<numVerts; i++){ area += cpvcross(verts[i], verts[(i+1)%numVerts]); } return -area/2.0f; } cpVect cpCentroidForPoly(const int numVerts, const cpVect *verts) { cpFloat sum = 0.0f; cpVect vsum = cpvzero; for(int i=0; i<numVerts; i++){ cpVect v1 = verts[i]; cpVect v2 = verts[(i+1)%numVerts]; cpFloat cross = cpvcross(v1, v2); sum += cross; vsum = cpvadd(vsum, cpvmult(cpvadd(v1, v2), cross)); } return cpvmult(vsum, 1.0f/(3.0f*sum)); } void cpRecenterPoly(const int numVerts, cpVect *verts){ cpVect centroid = cpCentroidForPoly(numVerts, verts); for(int i=0; i<numVerts; i++){ verts[i] = cpvsub(verts[i], centroid); } } cpFloat cpMomentForBox(cpFloat m, cpFloat width, cpFloat height) { return m*(width*width + height*height)/12.0f; } cpFloat cpMomentForBox2(cpFloat m, cpBB box) { cpFloat width = box.r - box.l; cpFloat height = box.t - box.b; cpVect offset = cpvmult(cpv(box.l + box.r, box.b + box.t), 0.5f); // TODO NaN when offset is 0 and m is INFINITY return cpMomentForBox(m, width, height) + m*cpvlengthsq(offset); } //MARK: Quick Hull void cpLoopIndexes(cpVect *verts, int count, int *start, int *end) { (*start) = (*end) = 0; cpVect min = verts[0]; cpVect max = min; for(int i=1; i<count; i++){ cpVect v = verts[i]; if(v.x < min.x || (v.x == min.x && v.y < min.y)){ min = v; (*start) = i; } else if(v.x > max.x || (v.x == max.x && v.y > max.y)){ max = v; (*end) = i; } } } #define SWAP(__A__, __B__) {cpVect __TMP__ = __A__; __A__ = __B__; __B__ = __TMP__;} static int QHullPartition(cpVect *verts, int count, cpVect a, cpVect b, cpFloat tol) { if(count == 0) return 0; cpFloat max = 0; int pivot = 0; cpVect delta = cpvsub(b, a); cpFloat valueTol = tol*cpvlength(delta); int head = 0; for(int tail = count-1; head <= tail;){ cpFloat value = cpvcross(delta, cpvsub(verts[head], a)); if(value > valueTol){ if(value > max){ max = value; pivot = head; } head++; } else { SWAP(verts[head], verts[tail]); tail--; } } // move the new pivot to the front if it's not already there. if(pivot != 0) SWAP(verts[0], verts[pivot]); return head; } static int QHullReduce(cpFloat tol, cpVect *verts, int count, cpVect a, cpVect pivot, cpVect b, cpVect *result) { if(count < 0){ return 0; } else if(count == 0) { result[0] = pivot; return 1; } else { int left_count = QHullPartition(verts, count, a, pivot, tol); int index = QHullReduce(tol, verts + 1, left_count - 1, a, verts[0], pivot, result); result[index++] = pivot; int right_count = QHullPartition(verts + left_count, count - left_count, pivot, b, tol); return index + QHullReduce(tol, verts + left_count + 1, right_count - 1, pivot, verts[left_count], b, result + index); } } // QuickHull seemed like a neat algorithm, and efficient-ish for large input sets. // My implementation performs an in place reduction using the result array as scratch space. int cpConvexHull(int count, cpVect *verts, cpVect *result, int *first, cpFloat tol) { if(result){ // Copy the line vertexes into the empty part of the result polyline to use as a scratch buffer. memcpy(result, verts, count*sizeof(cpVect)); } else { // If a result array was not specified, reduce the input instead. result = verts; } // Degenerate case, all poins are the same. int start, end; cpLoopIndexes(verts, count, &start, &end); if(start == end){ if(first) (*first) = 0; return 1; } SWAP(result[0], result[start]); SWAP(result[1], result[end == 0 ? start : end]); cpVect a = result[0]; cpVect b = result[1]; if(first) (*first) = start; int resultCount = QHullReduce(tol, result + 2, count - 2, a, b, a, result + 1) + 1; cpAssertSoft(cpPolyValidate(result, resultCount), "Internal error: cpConvexHull() and cpPolyValidate() did not agree." "Please report this error with as much info as you can."); return resultCount; } //MARK: Alternate Block Iterators #if defined(__has_extension) #if __has_extension(blocks) static void IteratorFunc(void *ptr, void (^block)(void *ptr)){block(ptr);} void cpSpaceEachBody_b(cpSpace *space, void (^block)(cpBody *body)){ cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)IteratorFunc, block); } void cpSpaceEachShape_b(cpSpace *space, void (^block)(cpShape *shape)){ cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)IteratorFunc, block); } void cpSpaceEachConstraint_b(cpSpace *space, void (^block)(cpConstraint *constraint)){ cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)IteratorFunc, block); } static void BodyIteratorFunc(cpBody *body, void *ptr, void (^block)(void *ptr)){block(ptr);} void cpBodyEachShape_b(cpBody *body, void (^block)(cpShape *shape)){ cpBodyEachShape(body, (cpBodyShapeIteratorFunc)BodyIteratorFunc, block); } void cpBodyEachConstraint_b(cpBody *body, void (^block)(cpConstraint *constraint)){ cpBodyEachConstraint(body, (cpBodyConstraintIteratorFunc)BodyIteratorFunc, block); } void cpBodyEachArbiter_b(cpBody *body, void (^block)(cpArbiter *arbiter)){ cpBodyEachArbiter(body, (cpBodyArbiterIteratorFunc)BodyIteratorFunc, block); } static void NearestPointQueryIteratorFunc(cpShape *shape, cpFloat distance, cpVect point, cpSpaceNearestPointQueryBlock block){block(shape, distance, point);} void cpSpaceNearestPointQuery_b(cpSpace *space, cpVect point, cpFloat maxDistance, cpLayers layers, cpGroup group, cpSpaceNearestPointQueryBlock block){ cpSpaceNearestPointQuery(space, point, maxDistance, layers, group, (cpSpaceNearestPointQueryFunc)NearestPointQueryIteratorFunc, block); } static void SegmentQueryIteratorFunc(cpShape *shape, cpFloat t, cpVect n, cpSpaceSegmentQueryBlock block){block(shape, t, n);} void cpSpaceSegmentQuery_b(cpSpace *space, cpVect start, cpVect end, cpLayers layers, cpGroup group, cpSpaceSegmentQueryBlock block){ cpSpaceSegmentQuery(space, start, end, layers, group, (cpSpaceSegmentQueryFunc)SegmentQueryIteratorFunc, block); } void cpSpaceBBQuery_b(cpSpace *space, cpBB bb, cpLayers layers, cpGroup group, cpSpaceBBQueryBlock block){ cpSpaceBBQuery(space, bb, layers, group, (cpSpaceBBQueryFunc)IteratorFunc, block); } static void ShapeQueryIteratorFunc(cpShape *shape, cpContactPointSet *points, cpSpaceShapeQueryBlock block){block(shape, points);} cpBool cpSpaceShapeQuery_b(cpSpace *space, cpShape *shape, cpSpaceShapeQueryBlock block){ return cpSpaceShapeQuery(space, shape, (cpSpaceShapeQueryFunc)ShapeQueryIteratorFunc, block); } #endif #endif #include "chipmunk_ffi.h"
412
0.931253
1
0.931253
game-dev
MEDIA
0.454577
game-dev
0.965837
1
0.965837
Arius-Cr/wire_ext_blender_fix_ime
3,249
src/native/offset/uiBlock/3.X/3.5.1.h
struct uiBlock { uiBlock *next, *prev; ListBase buttons; Panel *panel; uiBlock *oldblock; /** Used for `UI_butstore_*` runtime function. */ ListBase butstore; blender::Vector<uiButtonGroup> button_groups; ListBase layouts; uiLayout *curlayout; ListBase contexts; /** A block can store "views" on data-sets. Currently tree-views (#AbstractTreeView) only. * Others are imaginable, e.g. table-views, grid-views, etc. These are stored here to support * state that is persistent over redraws (e.g. collapsed tree-view items). */ ListBase views; ListBase dynamic_listeners; /* #uiBlockDynamicListener */ char name[UI_MAX_NAME_STR]; float winmat[4][4]; rctf rect; float aspect; /** Unique hash used to implement popup menu memory. */ uint puphash; uiButHandleFunc func; void *func_arg1; void *func_arg2; uiButHandleNFunc funcN; void *func_argN; uiMenuHandleFunc butm_func; void *butm_func_arg; uiBlockHandleFunc handle_func; void *handle_func_arg; /** Custom interaction data. */ uiBlockInteraction_CallbackData custom_interaction_callbacks; /** Custom extra event handling. */ int (*block_event_func)(const bContext *C, uiBlock *, const wmEvent *); /** Custom extra draw function for custom blocks. */ void (*drawextra)(const bContext *C, void *idv, void *arg1, void *arg2, rcti *rect); void *drawextra_arg1; void *drawextra_arg2; int flag; short alignnr; /** Hints about the buttons of this block. Used to avoid iterating over * buttons to find out if some criteria is met by any. Instead, check this * criteria when adding the button and set a flag here if it's met. */ short content_hints; /* #eBlockContentHints */ char direction; /** UI_BLOCK_THEME_STYLE_* */ char theme_style; /** Copied to #uiBut.emboss */ eUIEmbossType emboss; bool auto_open; char _pad[5]; double auto_open_last; const char *lockstr; bool lock; /** To keep blocks while drawing and free them afterwards. */ bool active; /** To avoid tool-tip after click. */ bool tooltipdisabled; /** True when #UI_block_end has been called. */ bool endblock; /** for doing delayed */ eBlockBoundsCalc bounds_type; /** Offset to use when calculating bounds (in pixels). */ int bounds_offset[2]; /** for doing delayed */ int bounds, minbounds; /** Pull-downs, to detect outside, can differ per case how it is created. */ rctf safety; /** #uiSafetyRct list */ ListBase saferct; uiPopupBlockHandle *handle; /** use so presets can find the operator, * across menus and from nested popups which fail for operator context. */ wmOperator *ui_operator; /** XXX hack for dynamic operator enums */ void *evil_C; /** unit system, used a lot for numeric buttons so include here * rather than fetching through the scene every time. */ UnitSettings *unit; /** \note only accessed by color picker templates. */ ColorPickerData color_pickers; /** Block for color picker with gamma baked in. */ bool is_color_gamma_picker; /** * Display device name used to display this block, * used by color widgets to transform colors from/to scene linear. */ char display_device[64]; PieMenuData pie_data; };
412
0.909752
1
0.909752
game-dev
MEDIA
0.736052
game-dev
0.67
1
0.67
opentibiabr/canary
1,302
data-otservbr-global/npc/elbert.lua
local internalNpcName = "Elbert" local npcType = Game.createNpcType(internalNpcName) local npcConfig = {} npcConfig.name = internalNpcName npcConfig.description = internalNpcName npcConfig.health = 100 npcConfig.maxHealth = npcConfig.health npcConfig.walkInterval = 2000 npcConfig.walkRadius = 2 npcConfig.outfit = { lookType = 153, lookHead = 58, lookBody = 119, lookLegs = 120, lookFeet = 121, lookAddons = 3, } npcConfig.flags = { floorchange = false, } local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) npcType.onThink = function(npc, interval) npcHandler:onThink(npc, interval) end npcType.onAppear = function(npc, creature) npcHandler:onAppear(npc, creature) end npcType.onDisappear = function(npc, creature) npcHandler:onDisappear(npc, creature) end npcType.onMove = function(npc, creature, fromPosition, toPosition) npcHandler:onMove(npc, creature, fromPosition, toPosition) end npcType.onSay = function(npc, creature, type, message) npcHandler:onSay(npc, creature, type, message) end npcType.onCloseChannel = function(npc, creature) npcHandler:onCloseChannel(npc, creature) end npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) -- npcType registering the npcConfig table npcType:register(npcConfig)
412
0.824241
1
0.824241
game-dev
MEDIA
0.907116
game-dev
0.560239
1
0.560239
CatImmortal/Trinity
8,639
Assets/Scripts/GameMain/Procedure/Builtin/ProcedureUpdateResource.cs
using GameFramework; using GameFramework.Event; using GameFramework.Procedure; using System; using System.Collections.Generic; using UnityEngine; using UnityGameFramework.Runtime; using ProcedureOwner = GameFramework.Fsm.IFsm<GameFramework.Procedure.IProcedureManager>; namespace Trinity { /// <summary> /// 更新资源流程 /// </summary> public class ProcedureUpdateResource : ProcedureBase { private bool m_UpdateAllComplete = false; private int m_UpdateCount = 0; private long m_UpdateTotalZipLength = 0; private int m_UpdateSuccessCount = 0; private List<UpdateLengthData> m_UpdateLengthData = new List<UpdateLengthData>(); protected override void OnEnter(ProcedureOwner procedureOwner) { base.OnEnter(procedureOwner); m_UpdateAllComplete = false; m_UpdateCount = 0; m_UpdateTotalZipLength = 0; m_UpdateSuccessCount = 0; m_UpdateLengthData.Clear(); GameEntry.Event.Subscribe(ResourceUpdateStartEventArgs.EventId, OnResourceUpdateStart); GameEntry.Event.Subscribe(ResourceUpdateChangedEventArgs.EventId, OnResourceUpdateChanged); GameEntry.Event.Subscribe(ResourceUpdateSuccessEventArgs.EventId, OnResourceUpdateSuccess); GameEntry.Event.Subscribe(ResourceUpdateFailureEventArgs.EventId, OnResourceUpdateFailure); GameEntry.Resource.CheckResources(OnCheckResourcesComplete); } protected override void OnLeave(ProcedureOwner procedureOwner, bool isShutdown) { GameEntry.Event.Unsubscribe(ResourceUpdateStartEventArgs.EventId, OnResourceUpdateStart); GameEntry.Event.Unsubscribe(ResourceUpdateChangedEventArgs.EventId, OnResourceUpdateChanged); GameEntry.Event.Unsubscribe(ResourceUpdateSuccessEventArgs.EventId, OnResourceUpdateSuccess); GameEntry.Event.Unsubscribe(ResourceUpdateFailureEventArgs.EventId, OnResourceUpdateFailure); base.OnLeave(procedureOwner, isShutdown); } protected override void OnUpdate(ProcedureOwner procedureOwner, float elapseSeconds, float realElapseSeconds) { base.OnUpdate(procedureOwner, elapseSeconds, realElapseSeconds); if (!m_UpdateAllComplete) { return; } ChangeState<ProcedurePreload>(procedureOwner); } private void OnCheckResourcesComplete(bool needUpdateResources, int removedCount, int updateCount, long updateTotalLength, long updateTotalZipLength) { Log.Info("Check resources complete, '{0}' resources need to update, zip length is '{1}', unzip length is '{2}'.", updateCount.ToString(), updateTotalZipLength.ToString(), updateTotalLength.ToString()); m_UpdateCount = updateCount; m_UpdateTotalZipLength = updateTotalZipLength; if (!needUpdateResources) { //不需要更新资源 ProcessUpdateResourcesComplete(); return; } //开始更新资源 StartUpdateResources(null); } private void ProcessUpdateResourcesComplete() { m_UpdateAllComplete = true; } private void StartUpdateResources(object userData) { GameEntry.Resource.UpdateResources(OnUpdateResourcesComplete); Log.Info("Start update resources..."); } private void OnUpdateResourcesComplete() { Log.Info("Update resources complete."); ProcessUpdateResourcesComplete(); } private void OnResourceUpdateStart(object sender, GameEventArgs e) { ResourceUpdateStartEventArgs ne = (ResourceUpdateStartEventArgs)e; for (int i = 0; i < m_UpdateLengthData.Count; i++) { if (m_UpdateLengthData[i].Name == ne.Name) { Log.Warning("Update resource '{0}' is invalid.", ne.Name); m_UpdateLengthData[i].Length = 0; RefreshProgress(); return; } } //记录下要更新的这个资源的长度数据 m_UpdateLengthData.Add(new UpdateLengthData(ne.Name)); } private void OnResourceUpdateChanged(object sender, GameEventArgs e) { ResourceUpdateChangedEventArgs ne = (ResourceUpdateChangedEventArgs)e; for (int i = 0; i < m_UpdateLengthData.Count; i++) { if (m_UpdateLengthData[i].Name == ne.Name) { m_UpdateLengthData[i].Length = ne.CurrentLength; RefreshProgress(); return; } } Log.Warning("Update resource '{0}' is invalid.", ne.Name); } private void OnResourceUpdateSuccess(object sender, GameEventArgs e) { ResourceUpdateSuccessEventArgs ne = (ResourceUpdateSuccessEventArgs)e; Log.Info("Update resource '{0}' success.", ne.Name); for (int i = 0; i < m_UpdateLengthData.Count; i++) { if (m_UpdateLengthData[i].Name == ne.Name) { m_UpdateLengthData[i].Length = ne.ZipLength; m_UpdateSuccessCount++; RefreshProgress(); return; } } Log.Warning("Update resource '{0}' is invalid.", ne.Name); } private void OnResourceUpdateFailure(object sender, GameEventArgs e) { ResourceUpdateFailureEventArgs ne = (ResourceUpdateFailureEventArgs)e; if (ne.RetryCount >= ne.TotalRetryCount) { Log.Error("Update resource '{0}' failure from '{1}' with error message '{2}', retry count '{3}'.", ne.Name, ne.DownloadUri, ne.ErrorMessage, ne.RetryCount.ToString()); return; } else { Log.Info("Update resource '{0}' failure from '{1}' with error message '{2}', retry count '{3}'.", ne.Name, ne.DownloadUri, ne.ErrorMessage, ne.RetryCount.ToString()); } for (int i = 0; i < m_UpdateLengthData.Count; i++) { if (m_UpdateLengthData[i].Name == ne.Name) { m_UpdateLengthData.Remove(m_UpdateLengthData[i]); RefreshProgress(); return; } } Log.Warning("Update resource '{0}' is invalid.", ne.Name); } /// <summary> /// 刷新进度 /// </summary> private void RefreshProgress() { int currentTotalUpdateLength = 0; for (int i = 0; i < m_UpdateLengthData.Count; i++) { currentTotalUpdateLength += m_UpdateLengthData[i].Length; } //计算更新进度 float progressTotal = (float)currentTotalUpdateLength / m_UpdateTotalZipLength; //获取更新描述文本 string descriptionText = GameEntry.Localization.GetString("UpdateResource.Tips", m_UpdateSuccessCount.ToString(), m_UpdateCount.ToString(), GetLengthString(currentTotalUpdateLength), GetLengthString(m_UpdateTotalZipLength), progressTotal, GetLengthString((int)GameEntry.Download.CurrentSpeed)); } /// <summary> /// 获取长度字符串 /// </summary> private string GetLengthString(long length) { if (length < 1024) { return Utility.Text.Format("{0} Bytes", length.ToString()); } if (length < 1024 * 1024) { return Utility.Text.Format("{0} KB", (length / 1024f).ToString("F2")); } if (length < 1024 * 1024 * 1024) { return Utility.Text.Format("{0} MB", (length / 1024f / 1024f).ToString("F2")); } return Utility.Text.Format("{0} GB", (length / 1024f / 1024f / 1024f).ToString("F2")); } private class UpdateLengthData { private readonly string m_Name; public UpdateLengthData(string name) { m_Name = name; } public string Name { get { return m_Name; } } public int Length { get; set; } } } }
412
0.55595
1
0.55595
game-dev
MEDIA
0.809463
game-dev,desktop-app
0.929715
1
0.929715
Stewmath/oracles-disasm
1,533
data/ages/tile_properties/seaEffectTiles2.s
; This is a list of tiles which have some special effect when PART_SEA_EFFECTS has been spawned in ; the current room. ; ; This is a bit of a weird system. First, in seaEffectTiles1.s, the PART_SEA_EFFECTS object is ; automatically spawned in if any of the tiles in that file exist. ; ; Then, so long as that object exists, it checks the data in this file to apply pollution, ; whirlpool, and water current effects. ; ; Not sure why an object needs to be spawned at all, but hey, it works. ; Data format for this table: ; b0: Tile index ($00 to end the list) ; b1: $00 for pollution tile, $01 for whirlpool tile, $02 for underwater whirlpool tile harmfulWaterTilesCollisionTable: .dw @overworld .dw @stub .dw @dungeon .dw @stub .dw @underwater .dw @dungeon @overworld: .db TILEINDEX_POLLUTION $00 .db TILEINDEX_WHIRLPOOL $01 @stub: .db $00 @underwater: .db TILEINDEX_POLLUTION $00 .db TILEINDEX_WHIRLPOOL $02 .db $00 @dungeon: ; 4 different variants of the currents pits in underwater dungeons .db $3c $02 .db $3d $02 .db $3e $02 .db $3f $02 .db $00 ; Data format for this table: ; b0: Tile index ($00 to end the list) ; b1: Angle towards which Link should be moved while on this tile currentsCollisionTable: .dw @overworld .dw @stub .dw @dungeon .dw @stub .dw @stub .dw @dungeon @dungeon: .db $54, ANGLE_UP .db $55, ANGLE_RIGHT .db $56, ANGLE_DOWN .db $57, ANGLE_LEFT .db $00 @overworld: .db $e0, ANGLE_UP .db $e1, ANGLE_DOWN .db $e2, ANGLE_LEFT .db $e3, ANGLE_RIGHT @stub: .db $00
412
0.794813
1
0.794813
game-dev
MEDIA
0.295694
game-dev
0.570597
1
0.570597
provencher/OpenXR_XRI_Sample
22,597
Assets/Samples/XR Hands/1.3.0/HandVisualizer/Scripts/HandVisualizer.cs
using System; using System.Collections.Generic; namespace UnityEngine.XR.Hands.Samples.VisualizerSample { /// <summary> /// This component visualizes the hand joints and mesh for the left and right hands. /// </summary> public class HandVisualizer : MonoBehaviour { /// <summary> /// The type of velocity to visualize. /// </summary> public enum VelocityType { /// <summary> /// Visualize the linear velocity of the joint. /// </summary> Linear, /// <summary> /// Visualize the angular velocity of the joint. /// </summary> Angular, /// <summary> /// Do not visualize velocity. /// </summary> None, } [SerializeField] [Tooltip("If this is enabled, this component will enable the Input System internal feature flag 'USE_OPTIMIZED_CONTROLS'. You must have at least version 1.5.0 of the Input System and have its backend enabled for this to take effect.")] bool m_UseOptimizedControls; [SerializeField] [Tooltip("References either a prefab or a GameObject in the scene that will be used to visualize the left hand.")] GameObject m_LeftHandMesh; [SerializeField] [Tooltip("References either a prefab or a GameObject in the scene that will be used to visualize the right hand.")] GameObject m_RightHandMesh; [SerializeField] [Tooltip("(Optional) If this is set, the hand meshes will be assigned this material.")] Material m_HandMeshMaterial; [SerializeField] [Tooltip("Tells the Hand Visualizer to draw the meshes for the hands.")] bool m_DrawMeshes; bool m_PreviousDrawMeshes; /// <summary> /// Tells the Hand Visualizer to draw the meshes for the hands. /// </summary> public bool drawMeshes { get => m_DrawMeshes; set => m_DrawMeshes = value; } [SerializeField] [Tooltip("The prefab that will be used to visualize the joints for debugging.")] GameObject m_DebugDrawPrefab; [SerializeField] [Tooltip("Tells the Hand Visualizer to draw the debug joints for the hands.")] bool m_DebugDrawJoints; bool m_PreviousDebugDrawJoints; /// <summary> /// Tells the Hand Visualizer to draw the debug joints for the hands. /// </summary> public bool debugDrawJoints { get => m_DebugDrawJoints; set => m_DebugDrawJoints = value; } [SerializeField] [Tooltip("Prefab to use for visualizing the velocity.")] GameObject m_VelocityPrefab; [SerializeField] [Tooltip("The type of velocity to visualize.")] VelocityType m_VelocityType; VelocityType m_PreviousVelocityType; /// <summary> /// The type of velocity to visualize. /// </summary> public VelocityType velocityType { get => m_VelocityType; set => m_VelocityType = value; } XRHandSubsystem m_Subsystem; HandGameObjects m_LeftHandGameObjects; HandGameObjects m_RightHandGameObjects; static readonly List<XRHandSubsystem> s_SubsystemsReuse = new List<XRHandSubsystem>(); /// <summary> /// See <see cref="MonoBehaviour"/>. /// </summary> protected void Awake() { #if ENABLE_INPUT_SYSTEM if (m_UseOptimizedControls) InputSystem.InputSystem.settings.SetInternalFeatureFlag("USE_OPTIMIZED_CONTROLS", true); #endif // ENABLE_INPUT_SYSTEM } /// <summary> /// See <see cref="MonoBehaviour"/>. /// </summary> protected void OnEnable() { if (m_Subsystem == null) return; UpdateRenderingVisibility(m_LeftHandGameObjects, m_Subsystem.leftHand.isTracked); UpdateRenderingVisibility(m_RightHandGameObjects, m_Subsystem.rightHand.isTracked); } /// <summary> /// See <see cref="MonoBehaviour"/>. /// </summary> protected void OnDisable() { if (m_Subsystem != null) { m_Subsystem.trackingAcquired -= OnTrackingAcquired; m_Subsystem.trackingLost -= OnTrackingLost; m_Subsystem.updatedHands -= OnUpdatedHands; m_Subsystem = null; } UpdateRenderingVisibility(m_LeftHandGameObjects, false); UpdateRenderingVisibility(m_RightHandGameObjects, false); } /// <summary> /// See <see cref="MonoBehaviour"/>. /// </summary> protected void OnDestroy() { if (m_LeftHandGameObjects != null) { m_LeftHandGameObjects.OnDestroy(); m_LeftHandGameObjects = null; } if (m_RightHandGameObjects != null) { m_RightHandGameObjects.OnDestroy(); m_RightHandGameObjects = null; } } /// <summary> /// See <see cref="MonoBehaviour"/>. /// </summary> protected void Update() { if (m_Subsystem != null && m_Subsystem.running) return; SubsystemManager.GetSubsystems(s_SubsystemsReuse); var foundRunningHandSubsystem = false; for (var i = 0; i < s_SubsystemsReuse.Count; ++i) { var handSubsystem = s_SubsystemsReuse[i]; if (handSubsystem.running) { UnsubscribeHandSubsystem(); m_Subsystem = handSubsystem; foundRunningHandSubsystem = true; break; } } if (!foundRunningHandSubsystem) return; if (m_LeftHandGameObjects == null) { m_LeftHandGameObjects = new HandGameObjects( Handedness.Left, transform, m_LeftHandMesh, m_HandMeshMaterial, m_DebugDrawPrefab, m_VelocityPrefab); } if (m_RightHandGameObjects == null) { m_RightHandGameObjects = new HandGameObjects( Handedness.Right, transform, m_RightHandMesh, m_HandMeshMaterial, m_DebugDrawPrefab, m_VelocityPrefab); } UpdateRenderingVisibility(m_LeftHandGameObjects, m_Subsystem.leftHand.isTracked); UpdateRenderingVisibility(m_RightHandGameObjects, m_Subsystem.rightHand.isTracked); m_PreviousDrawMeshes = m_DrawMeshes; m_PreviousDebugDrawJoints = m_DebugDrawJoints; m_PreviousVelocityType = m_VelocityType; SubscribeHandSubsystem(); } void SubscribeHandSubsystem() { if (m_Subsystem == null) return; m_Subsystem.trackingAcquired += OnTrackingAcquired; m_Subsystem.trackingLost += OnTrackingLost; m_Subsystem.updatedHands += OnUpdatedHands; } void UnsubscribeHandSubsystem() { if (m_Subsystem == null) return; m_Subsystem.trackingAcquired -= OnTrackingAcquired; m_Subsystem.trackingLost -= OnTrackingLost; m_Subsystem.updatedHands -= OnUpdatedHands; } void UpdateRenderingVisibility(HandGameObjects handGameObjects, bool isTracked) { if (handGameObjects == null) return; handGameObjects.ToggleDrawMesh(m_DrawMeshes); handGameObjects.ToggleDebugDrawJoints(m_DebugDrawJoints && isTracked); handGameObjects.SetVelocityType(isTracked ? m_VelocityType : VelocityType.None); } void OnTrackingAcquired(XRHand hand) { switch (hand.handedness) { case Handedness.Left: UpdateRenderingVisibility(m_LeftHandGameObjects, true); break; case Handedness.Right: UpdateRenderingVisibility(m_RightHandGameObjects, true); break; } } void OnTrackingLost(XRHand hand) { switch (hand.handedness) { case Handedness.Left: UpdateRenderingVisibility(m_LeftHandGameObjects, false); break; case Handedness.Right: UpdateRenderingVisibility(m_RightHandGameObjects, false); break; } } void OnUpdatedHands(XRHandSubsystem subsystem, XRHandSubsystem.UpdateSuccessFlags updateSuccessFlags, XRHandSubsystem.UpdateType updateType) { // We have no game logic depending on the Transforms, so early out here // (add game logic before this return here, directly querying from // subsystem.leftHand and subsystem.rightHand using GetJoint on each hand) if (updateType == XRHandSubsystem.UpdateType.Dynamic) return; bool leftHandTracked = subsystem.leftHand.isTracked; bool rightHandTracked = subsystem.rightHand.isTracked; if (m_PreviousDrawMeshes != m_DrawMeshes) { m_LeftHandGameObjects.ToggleDrawMesh(m_DrawMeshes); m_RightHandGameObjects.ToggleDrawMesh(m_DrawMeshes); m_PreviousDrawMeshes = m_DrawMeshes; } if (m_PreviousDebugDrawJoints != m_DebugDrawJoints) { m_LeftHandGameObjects.ToggleDebugDrawJoints(m_DebugDrawJoints && leftHandTracked); m_RightHandGameObjects.ToggleDebugDrawJoints(m_DebugDrawJoints && rightHandTracked); m_PreviousDebugDrawJoints = m_DebugDrawJoints; } if (m_PreviousVelocityType != m_VelocityType) { m_LeftHandGameObjects.SetVelocityType(leftHandTracked ? m_VelocityType : VelocityType.None); m_RightHandGameObjects.SetVelocityType(rightHandTracked ? m_VelocityType : VelocityType.None); m_PreviousVelocityType = m_VelocityType; } m_LeftHandGameObjects.UpdateJoints( subsystem.leftHand, (updateSuccessFlags & XRHandSubsystem.UpdateSuccessFlags.LeftHandJoints) != 0, m_DebugDrawJoints, m_VelocityType); m_RightHandGameObjects.UpdateJoints( subsystem.rightHand, (updateSuccessFlags & XRHandSubsystem.UpdateSuccessFlags.RightHandJoints) != 0, m_DebugDrawJoints, m_VelocityType); } class HandGameObjects { GameObject m_HandRoot; GameObject m_DrawJointsParent; GameObject[] m_DrawJoints = new GameObject[XRHandJointID.EndMarker.ToIndex()]; GameObject[] m_VelocityParents = new GameObject[XRHandJointID.EndMarker.ToIndex()]; LineRenderer[] m_Lines = new LineRenderer[XRHandJointID.EndMarker.ToIndex()]; static Vector3[] s_LinePointsReuse = new Vector3[2]; XRHandMeshController m_MeshController; const float k_LineWidth = 0.005f; public HandGameObjects( Handedness handedness, Transform parent, GameObject meshPrefab, Material meshMaterial, GameObject debugDrawPrefab, GameObject velocityPrefab) { void AssignJoint( XRHandJointID jointId, Transform jointDrivenTransform, Transform drawJointsParent) { var jointIndex = jointId.ToIndex(); m_DrawJoints[jointIndex] = Instantiate(debugDrawPrefab); m_DrawJoints[jointIndex].transform.parent = drawJointsParent; m_DrawJoints[jointIndex].name = jointId.ToString(); m_VelocityParents[jointIndex] = Instantiate(velocityPrefab); m_VelocityParents[jointIndex].transform.parent = jointDrivenTransform; m_Lines[jointIndex] = m_DrawJoints[jointIndex].GetComponent<LineRenderer>(); m_Lines[jointIndex].startWidth = m_Lines[jointIndex].endWidth = k_LineWidth; s_LinePointsReuse[0] = s_LinePointsReuse[1] = jointDrivenTransform.position; m_Lines[jointIndex].SetPositions(s_LinePointsReuse); } var isSceneObject = meshPrefab.scene.IsValid(); m_HandRoot = isSceneObject ? meshPrefab : Instantiate(meshPrefab, parent); m_HandRoot.SetActive(false); // Deactivate so that added components do not run OnEnable before they are finished being set up m_HandRoot.transform.localPosition = Vector3.zero; m_HandRoot.transform.localRotation = Quaternion.identity; var handEvents = m_HandRoot.GetComponent<XRHandTrackingEvents>(); if (handEvents == null) { handEvents = m_HandRoot.AddComponent<XRHandTrackingEvents>(); handEvents.updateType = XRHandTrackingEvents.UpdateTypes.Dynamic; handEvents.handedness = handedness; } m_MeshController = m_HandRoot.GetComponent<XRHandMeshController>(); if (m_MeshController == null) { m_MeshController = m_HandRoot.AddComponent<XRHandMeshController>(); for (var childIndex = 0; childIndex < m_HandRoot.transform.childCount; ++childIndex) { var childTransform = m_HandRoot.transform.GetChild(childIndex); if (childTransform.TryGetComponent<SkinnedMeshRenderer>(out var renderer)) m_MeshController.handMeshRenderer = renderer; } m_MeshController.handTrackingEvents = handEvents; } if (meshMaterial != null) { m_MeshController.handMeshRenderer.sharedMaterial = meshMaterial; } var skeletonDriver = m_HandRoot.GetComponent<XRHandSkeletonDriver>(); if (skeletonDriver == null) { skeletonDriver = m_HandRoot.AddComponent<XRHandSkeletonDriver>(); skeletonDriver.jointTransformReferences = new List<JointToTransformReference>(); Transform root = null; for (var childIndex = 0; childIndex < m_HandRoot.transform.childCount; ++childIndex) { var child = m_HandRoot.transform.GetChild(childIndex); if (child.gameObject.name.EndsWith(XRHandJointID.Wrist.ToString())) root = child; } skeletonDriver.rootTransform = root; XRHandSkeletonDriverUtility.FindJointsFromRoot(skeletonDriver); skeletonDriver.InitializeFromSerializedReferences(); skeletonDriver.handTrackingEvents = handEvents; } m_DrawJointsParent = new GameObject(); m_DrawJointsParent.transform.parent = parent; m_DrawJointsParent.transform.localPosition = Vector3.zero; m_DrawJointsParent.transform.localRotation = Quaternion.identity; m_DrawJointsParent.name = handedness + "HandDebugDrawJoints"; for (var i = 0; i < skeletonDriver.jointTransformReferences.Count; i++) { var jointTransformReference = skeletonDriver.jointTransformReferences[i]; var jointTransform = jointTransformReference.jointTransform; var jointID = jointTransformReference.xrHandJointID; AssignJoint(jointID, jointTransform, m_DrawJointsParent.transform); } m_HandRoot.SetActive(true); } public void OnDestroy() { Destroy(m_HandRoot); m_HandRoot = null; for (var jointIndex = 0; jointIndex < m_DrawJoints.Length; ++jointIndex) { Destroy(m_DrawJoints[jointIndex]); m_DrawJoints[jointIndex] = null; } for (var jointIndex = 0; jointIndex < m_VelocityParents.Length; ++jointIndex) { Destroy(m_VelocityParents[jointIndex]); m_VelocityParents[jointIndex] = null; } Destroy(m_DrawJointsParent); m_DrawJointsParent = null; } public void ToggleDrawMesh(bool drawMesh) { m_MeshController.enabled = drawMesh; if (!drawMesh) m_MeshController.handMeshRenderer.enabled = false; } public void ToggleDebugDrawJoints(bool debugDrawJoints) { for (int jointIndex = 0; jointIndex < m_DrawJoints.Length; ++jointIndex) { ToggleRenderers<MeshRenderer>(debugDrawJoints, m_DrawJoints[jointIndex].transform); m_Lines[jointIndex].enabled = debugDrawJoints; } m_Lines[0].enabled = false; } public void SetVelocityType(VelocityType velocityType) { for (int jointIndex = 0; jointIndex < m_VelocityParents.Length; ++jointIndex) ToggleRenderers<LineRenderer>(velocityType != VelocityType.None, m_VelocityParents[jointIndex].transform); } public void UpdateJoints( XRHand hand, bool areJointsTracked, bool debugDrawJoints, VelocityType velocityType) { if (!areJointsTracked) return; var wristPose = Pose.identity; var parentIndex = XRHandJointID.Wrist.ToIndex(); UpdateJoint(debugDrawJoints, velocityType, hand.GetJoint(XRHandJointID.Wrist), ref wristPose, ref parentIndex); UpdateJoint(debugDrawJoints, velocityType, hand.GetJoint(XRHandJointID.Palm), ref wristPose, ref parentIndex, false); for (var fingerIndex = (int)XRHandFingerID.Thumb; fingerIndex <= (int)XRHandFingerID.Little; ++fingerIndex) { var parentPose = wristPose; var fingerId = (XRHandFingerID)fingerIndex; parentIndex = XRHandJointID.Wrist.ToIndex(); var jointIndexBack = fingerId.GetBackJointID().ToIndex(); for (var jointIndex = fingerId.GetFrontJointID().ToIndex(); jointIndex <= jointIndexBack; ++jointIndex) { UpdateJoint(debugDrawJoints, velocityType, hand.GetJoint(XRHandJointIDUtility.FromIndex(jointIndex)), ref parentPose, ref parentIndex); } } } void UpdateJoint( bool debugDrawJoints, VelocityType velocityType, XRHandJoint joint, ref Pose parentPose, ref int parentIndex, bool cacheParentPose = true) { if (joint.id == XRHandJointID.Invalid) return; var jointIndex = joint.id.ToIndex(); if (!joint.TryGetPose(out var pose)) return; m_DrawJoints[jointIndex].transform.localPosition = pose.position; m_DrawJoints[jointIndex].transform.localRotation = pose.rotation; if (debugDrawJoints && joint.id != XRHandJointID.Wrist) { s_LinePointsReuse[0] = m_DrawJoints[parentIndex].transform.position; s_LinePointsReuse[1] = m_DrawJoints[jointIndex].transform.position; m_Lines[jointIndex].SetPositions(s_LinePointsReuse); } if (cacheParentPose) { parentPose = pose; parentIndex = jointIndex; } if (velocityType != VelocityType.None && m_VelocityParents[jointIndex].TryGetComponent<LineRenderer>(out var renderer)) { m_VelocityParents[jointIndex].transform.localPosition = Vector3.zero; m_VelocityParents[jointIndex].transform.localRotation = Quaternion.identity; s_LinePointsReuse[0] = s_LinePointsReuse[1] = m_VelocityParents[jointIndex].transform.position; if (velocityType == VelocityType.Linear) { if (joint.TryGetLinearVelocity(out var velocity)) s_LinePointsReuse[1] += velocity; } else if (velocityType == VelocityType.Angular) { if (joint.TryGetAngularVelocity(out var velocity)) s_LinePointsReuse[1] += 0.05f * velocity.normalized; } renderer.SetPositions(s_LinePointsReuse); } } static void ToggleRenderers<TRenderer>(bool toggle, Transform rendererTransform) where TRenderer : Renderer { if (rendererTransform.TryGetComponent<TRenderer>(out var renderer)) renderer.enabled = toggle; for (var childIndex = 0; childIndex < rendererTransform.childCount; ++childIndex) ToggleRenderers<TRenderer>(toggle, rendererTransform.GetChild(childIndex)); } } } }
412
0.974715
1
0.974715
game-dev
MEDIA
0.71235
game-dev
0.945685
1
0.945685
runuo/runuo
2,890
Scripts/Mobiles/Vendors/SBInfo/SBAlchemist.cs
using System; using System.Collections.Generic; using Server.Items; namespace Server.Mobiles { public class SBAlchemist : SBInfo { private List<GenericBuyInfo> m_BuyInfo = new InternalBuyInfo(); private IShopSellInfo m_SellInfo = new InternalSellInfo(); public SBAlchemist() { } public override IShopSellInfo SellInfo { get { return m_SellInfo; } } public override List<GenericBuyInfo> BuyInfo { get { return m_BuyInfo; } } public class InternalBuyInfo : List<GenericBuyInfo> { public InternalBuyInfo() { Add( new GenericBuyInfo( typeof( RefreshPotion ), 15, 10, 0xF0B, 0 ) ); Add( new GenericBuyInfo( typeof( AgilityPotion ), 15, 10, 0xF08, 0 ) ); Add( new GenericBuyInfo( typeof( NightSightPotion ), 15, 10, 0xF06, 0 ) ); Add( new GenericBuyInfo( typeof( LesserHealPotion ), 15, 10, 0xF0C, 0 ) ); Add( new GenericBuyInfo( typeof( StrengthPotion ), 15, 10, 0xF09, 0 ) ); Add( new GenericBuyInfo( typeof( LesserPoisonPotion ), 15, 10, 0xF0A, 0 ) ); Add( new GenericBuyInfo( typeof( LesserCurePotion ), 15, 10, 0xF07, 0 ) ); Add( new GenericBuyInfo( typeof( LesserExplosionPotion ), 21, 10, 0xF0D, 0 ) ); Add( new GenericBuyInfo( typeof( MortarPestle ), 8, 10, 0xE9B, 0 ) ); Add( new GenericBuyInfo( typeof( BlackPearl ), 5, 20, 0xF7A, 0 ) ); Add( new GenericBuyInfo( typeof( Bloodmoss ), 5, 20, 0xF7B, 0 ) ); Add( new GenericBuyInfo( typeof( Garlic ), 3, 20, 0xF84, 0 ) ); Add( new GenericBuyInfo( typeof( Ginseng ), 3, 20, 0xF85, 0 ) ); Add( new GenericBuyInfo( typeof( MandrakeRoot ), 3, 20, 0xF86, 0 ) ); Add( new GenericBuyInfo( typeof( Nightshade ), 3, 20, 0xF88, 0 ) ); Add( new GenericBuyInfo( typeof( SpidersSilk ), 3, 20, 0xF8D, 0 ) ); Add( new GenericBuyInfo( typeof( SulfurousAsh ), 3, 20, 0xF8C, 0 ) ); Add( new GenericBuyInfo( typeof( Bottle ), 5, 100, 0xF0E, 0 ) ); Add( new GenericBuyInfo( typeof( HeatingStand ), 2, 100, 0x1849, 0 ) ); Add( new GenericBuyInfo( "1041060", typeof( HairDye ), 37, 10, 0xEFF, 0 ) ); } } public class InternalSellInfo : GenericSellInfo { public InternalSellInfo() { Add( typeof( BlackPearl ), 3 ); Add( typeof( Bloodmoss ), 3 ); Add( typeof( MandrakeRoot ), 2 ); Add( typeof( Garlic ), 2 ); Add( typeof( Ginseng ), 2 ); Add( typeof( Nightshade ), 2 ); Add( typeof( SpidersSilk ), 2 ); Add( typeof( SulfurousAsh ), 2 ); Add( typeof( Bottle ), 3 ); Add( typeof( MortarPestle ), 4 ); Add( typeof( HairDye ), 19 ); Add( typeof( NightSightPotion ), 7 ); Add( typeof( AgilityPotion ), 7 ); Add( typeof( StrengthPotion ), 7 ); Add( typeof( RefreshPotion ), 7 ); Add( typeof( LesserCurePotion ), 7 ); Add( typeof( LesserHealPotion ), 7 ); Add( typeof( LesserPoisonPotion ), 7 ); Add( typeof( LesserExplosionPotion ), 10 ); } } } }
412
0.632321
1
0.632321
game-dev
MEDIA
0.225779
game-dev
0.650353
1
0.650353
LmeSzinc/AzurLaneAutoScript
4,532
module/event_hospital/combat.py
from module.base.decorator import run_once from module.base.timer import Timer from module.campaign.campaign_event import CampaignEvent from module.combat.combat import BATTLE_PREPARATION, Combat from module.event_hospital.assets import HOSPITAL_BATTLE_PREPARE from module.event_hospital.ui import HospitalUI from module.exception import OilExhausted, RequestHumanTakeover from module.logger import logger from module.map.assets import * from module.map.map_fleet_preparation import FleetOperator from module.raid.assets import RAID_FLEET_PREPARATION class HospitalCombat(Combat, HospitalUI, CampaignEvent): def handle_fleet_recommend(self, recommend=True): """ Args: recommend: Returns: bool: If clicked """ fleet_1 = FleetOperator( choose=FLEET_1_CHOOSE, advice=FLEET_1_ADVICE, bar=FLEET_1_BAR, clear=FLEET_1_CLEAR, in_use=FLEET_1_IN_USE, hard_satisfied=FLEET_1_HARD_SATIESFIED, main=self) if fleet_1.in_use(): return False if recommend: logger.info('Recommend fleet') fleet_1.recommend() return True else: logger.error('Fleet not prepared and fleet recommend is not enabled, ' 'please prepare fleets manually before running') raise RequestHumanTakeover def combat_preparation(self, balance_hp=False, emotion_reduce=False, auto='combat_auto', fleet_index=1): """ Args: balance_hp (bool): emotion_reduce (bool): auto (bool): fleet_index (int): """ logger.info('Combat preparation.') skip_first_screenshot = True # No need, already waited in `raid_execute_once()` # if emotion_reduce: # self.emotion.wait(fleet_index) @run_once def check_oil(): if self.get_oil() < max(500, self.config.StopCondition_OilLimit): logger.hr('Triggered oil limit') raise OilExhausted @run_once def check_coin(): if self.config.TaskBalancer_Enable and self.triggered_task_balancer(): logger.hr('Triggered stop condition: Coin limit') self.handle_task_balancer() return True while 1: if skip_first_screenshot: skip_first_screenshot = False else: self.device.screenshot() if self.appear(BATTLE_PREPARATION, offset=(30, 20)): if self.handle_combat_automation_set(auto=auto == 'combat_auto'): continue check_oil() check_coin() if self.handle_retirement(): continue if self.handle_combat_low_emotion(): continue if self.appear_then_click(BATTLE_PREPARATION, offset=(30, 20), interval=2): continue if self.handle_combat_automation_confirm(): continue if self.handle_story_skip(): continue # Handle fleet preparation if self.appear(RAID_FLEET_PREPARATION, offset=(30, 30), interval=2): if self.handle_fleet_recommend(recommend=self.config.Hospital_UseRecommendFleet): self.interval_clear(RAID_FLEET_PREPARATION) continue self.device.click(RAID_FLEET_PREPARATION) continue if self.appear_then_click(HOSPITAL_BATTLE_PREPARE, offset=(20, 20), interval=2): continue # End pause = self.is_combat_executing() if pause: logger.attr('BattleUI', pause) if emotion_reduce: self.emotion.reduce(fleet_index) break in_clue_confirm = Timer(0.5, count=2) def hospital_expected_end(self): """ Returns: bool: If combat ended """ if self.handle_clue_exit(): return False if self.is_in_clue(): self.in_clue_confirm.start() if self.in_clue_confirm.reached(): return True else: self.in_clue_confirm.reset() return False def hospital_combat(self): """ Pages: in: FLEET_PREPARATION out: is_in_clue """ self.combat(balance_hp=False, expected_end=self.hospital_expected_end)
412
0.946876
1
0.946876
game-dev
MEDIA
0.50624
game-dev
0.978277
1
0.978277
Secrets-of-Sosaria/World
4,511
Data/Scripts/Mobiles/Elementals/Elementals/WaterElemental.cs
using System; using Server; using Server.Items; using Server.Mobiles; using Server.Misc; using Server.Network; namespace Server.Mobiles { [CorpseName( "an elemental corpse" )] public class WaterElemental : BaseCreature { public override double DispelDifficulty{ get{ return 117.5; } } public override double DispelFocus{ get{ return 45.0; } } public override int BreathPhysicalDamage{ get{ return 50; } } public override int BreathFireDamage{ get{ return 0; } } public override int BreathColdDamage{ get{ return 50; } } public override int BreathPoisonDamage{ get{ return 0; } } public override int BreathEnergyDamage{ get{ return 0; } } public override int BreathEffectHue{ get{ return 0; } } public override int BreathEffectSound{ get{ return 0x012; } } public override int BreathEffectItemID{ get{ return 0x1A85; } } public override bool ReacquireOnMovement{ get{ return !Controlled; } } public override bool HasBreath{ get{ return true; } } public override double BreathEffectDelay{ get{ return 0.1; } } public override void BreathDealDamage( Mobile target, int form ){ base.BreathDealDamage( target, 30 ); } [Constructable] public WaterElemental () : base( AIType.AI_Mage, FightMode.Closest, 10, 1, 0.2, 0.4 ) { Name = "a water elemental"; Body = 16; BaseSoundID = 278; CanSwim = true; if ( Utility.RandomMinMax(1,5) == 1 ) { Body = 224; Hue = 0xB3E; SetStr( 226, 255 ); SetDex( 166, 185 ); SetInt( 201, 225 ); SetHits( 176, 193 ); SetDamage( 12, 16 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 45, 55 ); SetResistance( ResistanceType.Fire, 20, 35 ); SetResistance( ResistanceType.Cold, 20, 35 ); SetResistance( ResistanceType.Poison, 70, 80 ); SetResistance( ResistanceType.Energy, 15, 20 ); SetSkill( SkillName.Psychology, 70.1, 85.0 ); SetSkill( SkillName.Magery, 70.1, 85.0 ); SetSkill( SkillName.MagicResist, 100.1, 115.0 ); SetSkill( SkillName.Tactics, 60.1, 80.0 ); SetSkill( SkillName.FistFighting, 60.1, 80.0 ); Fame = 7500; Karma = -7500; VirtualArmor = 50; ControlSlots = 3; PackItem( new SeaSalt( Utility.RandomMinMax(5,15) ) ); PackItem( new WaterBottle() ); if ( Utility.RandomBool() ) PackItem( new WaterBottle() ); } else { if ( Utility.RandomBool() ) { Body = 977; Hue = Utility.RandomList( 0xBA7, 0xB3F, 0xB3D ); } SetStr( 126, 155 ); SetDex( 66, 85 ); SetInt( 101, 125 ); SetHits( 76, 93 ); SetDamage( 7, 9 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 35, 45 ); SetResistance( ResistanceType.Fire, 10, 25 ); SetResistance( ResistanceType.Cold, 10, 25 ); SetResistance( ResistanceType.Poison, 60, 70 ); SetResistance( ResistanceType.Energy, 5, 10 ); SetSkill( SkillName.Psychology, 60.1, 75.0 ); SetSkill( SkillName.Magery, 60.1, 75.0 ); SetSkill( SkillName.MagicResist, 100.1, 115.0 ); SetSkill( SkillName.Tactics, 50.1, 70.0 ); SetSkill( SkillName.FistFighting, 50.1, 70.0 ); Fame = 4500; Karma = -4500; VirtualArmor = 40; ControlSlots = 3; PackItem( new SeaSalt( Utility.RandomMinMax(3,9) ) ); PackItem( new WaterBottle() ); } } public override void GenerateLoot() { AddLoot( LootPack.Average ); AddLoot( LootPack.Meager ); AddLoot( LootPack.MedPotions ); if ( Body == 224 ){ AddLoot( LootPack.Rich ); } } public override bool BleedImmune{ get{ return true; } } public override int TreasureMapLevel{ get{ return 2; } } public override void OnGotMeleeAttack( Mobile attacker ) { base.OnGotMeleeAttack( attacker ); if ( Utility.RandomMinMax( 1, 4 ) == 1 && ( this.Fame > 4500 || this.WhisperHue == 999 ) ) { int goo = 0; foreach ( Item splash in this.GetItemsInRange( 10 ) ){ if ( splash is MonsterSplatter && splash.Name == "freezing water" ){ goo++; } } if ( goo == 0 ) { MonsterSplatter.AddSplatter( this.X, this.Y, this.Z, this.Map, this.Location, this, "freezing water", 296, 0 ); } } } public WaterElemental( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
412
0.967316
1
0.967316
game-dev
MEDIA
0.993625
game-dev
0.981933
1
0.981933
fxgenstudio/MGShaderEditor
3,447
Src/MonoGame.Framework/Content/ContentReaders/SpriteFontReader.cs
#region License /* MIT License Copyright © 2006 The Mono.Xna Team All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion License using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Microsoft.Xna.Framework.Content { internal class SpriteFontReader : ContentTypeReader<SpriteFont> { internal SpriteFontReader() { } static string[] supportedExtensions = new string[] { ".spritefont" }; internal static string Normalize(string fileName) { return Normalize(fileName, supportedExtensions); } protected internal override SpriteFont Read(ContentReader input, SpriteFont existingInstance) { if (existingInstance != null) { // Read the texture into the existing texture instance input.ReadObject<Texture2D>(existingInstance.Texture); // discard the rest of the SpriteFont data as we are only reloading GPU resources for now input.ReadObject<List<Rectangle>>(); input.ReadObject<List<Rectangle>>(); input.ReadObject<List<char>>(); input.ReadInt32(); input.ReadSingle(); input.ReadObject<List<Vector3>>(); if (input.ReadBoolean()) { input.ReadChar(); } return existingInstance; } else { // Create a fresh SpriteFont instance Texture2D texture = input.ReadObject<Texture2D>(); List<Rectangle> glyphs = input.ReadObject<List<Rectangle>>(); List<Rectangle> cropping = input.ReadObject<List<Rectangle>>(); List<char> charMap = input.ReadObject<List<char>>(); int lineSpacing = input.ReadInt32(); float spacing = input.ReadSingle(); List<Vector3> kerning = input.ReadObject<List<Vector3>>(); char? defaultCharacter = null; if (input.ReadBoolean()) { defaultCharacter = new char?(input.ReadChar()); } return new SpriteFont(texture, glyphs, cropping, charMap, lineSpacing, spacing, kerning, defaultCharacter); } } } }
412
0.838019
1
0.838019
game-dev
MEDIA
0.783782
game-dev
0.79079
1
0.79079
Ravaelles/Atlantis
3,131
src/atlantis/combat/missions/contain/TerranMissionChangerWhenContain.java
package atlantis.combat.missions.contain; import atlantis.combat.retreating.RetreatManager; import atlantis.game.A; import atlantis.game.AGame; import atlantis.information.enemy.EnemyInfo; import atlantis.information.enemy.EnemyUnits; import atlantis.information.generic.ArmyStrength; import atlantis.information.strategy.GamePhase; import atlantis.units.AUnitType; import atlantis.units.select.Count; import atlantis.game.player.Enemy; public class TerranMissionChangerWhenContain extends MissionChangerWhenContain { // public static void changeMissionIfNeeded() { // if (shouldChangeMissionToDefend() && !TerranMissionChangerWhenDefend.shouldChangeMissionToContain()) { // Missions.forceGlobalMissionDefend(reason); // } // // else if (shouldChangeMissionToAttack() && !TerranMissionChangerWhenAttack.shouldChangeMissionToContain()) { // Missions.forceGlobalMissionAttack(reason); // } // } // ========================================================= @Override public boolean shouldChangeMissionToDefend() { if (GamePhase.isEarlyGame()) { if (Enemy.protoss() && EnemyUnits.discovered().ofType(AUnitType.Protoss_Zealot).atLeast(4)) { if (Count.medics() <= 4) { if (DEBUG) reason = "Enemy rush (" + ArmyStrength.ourArmyRelativeStrength() + "%)"; return true; } } } if (ArmyStrength.ourArmyRelativeStrength() < 200) { if (DEBUG) reason = "Let us not risk (" + ArmyStrength.ourArmyRelativeStrength() + "%)"; return true; } if (EnemyInfo.isEnemyNearAnyOurBase() && A.supplyUsed() <= 70) { if (DEBUG) reason = "Enemy near our building"; return true; } if (ArmyStrength.weAreWeaker() && RetreatManager.GLOBAL_RETREAT_COUNTER >= 2 && A.resourcesBalance() <= 300) { if (DEBUG) reason = "We are weaker (" + ArmyStrength.ourArmyRelativeStrength() + "%)"; return true; } if (A.resourcesBalance() <= -400 && A.supplyUsed() <= 130 && !GamePhase.isLateGame()) { if (DEBUG) reason = "Too many resources lost"; return true; } // if (EnemyInfo.hiddenUnitsCount() >= 2 && Count.ofType(AUnitType.Terran_Science_Vessel) == 0) { // if (DEBUG) reason = "Hidden units"; // return true; // } return false; } @Override public boolean shouldChangeMissionToAttack() { if (A.supplyUsed() >= 190) { if (DEBUG) reason = "Supply blocked"; return true; } if (A.supplyUsed() >= 80 && ArmyStrength.ourArmyRelativeStrength() >= 300) { if (DEBUG) reason = "Resources balance good"; return true; } return false; } protected static boolean killsBalanceSaysSo() { if (AGame.timeSeconds() <= 400 && AGame.killsLossesResourceBalance() >= 900) return true; return AGame.timeSeconds() <= 700 && AGame.killsLossesResourceBalance() >= 1600; } }
412
0.880444
1
0.880444
game-dev
MEDIA
0.971673
game-dev
0.950921
1
0.950921
flammpfeil/SlashBlade
1,754
src/main/java/mods/flammpfeil/slashblade/gui/config/ConfigGuiFactory.java
package mods.flammpfeil.slashblade.gui.config; import mods.flammpfeil.slashblade.SlashBlade; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.IModGuiFactory; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Created by Furia on 2017/01/22. */ public class ConfigGuiFactory implements IModGuiFactory { public static class ConfigGui extends GuiConfig { public ConfigGui(GuiScreen parentScreen) { super(parentScreen,getConfigElements(), SlashBlade.modid, false, false, "SlashBlade config", SlashBlade.mainConfigurationFile.getAbsolutePath()); } private static List<IConfigElement> getConfigElements(){ List<IConfigElement> list = new ArrayList<IConfigElement>(); for(String categoryName : SlashBlade.mainConfiguration.getCategoryNames()){ list.add( new ConfigElement(SlashBlade.mainConfiguration.getCategory(categoryName)) ); } return list; } } @Override public void initialize(Minecraft minecraftInstance) { } @Override public boolean hasConfigGui() { return true; } @Override public GuiScreen createConfigGui(GuiScreen parentScreen) { return new ConfigGui(parentScreen); } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } }
412
0.830003
1
0.830003
game-dev
MEDIA
0.981727
game-dev
0.561531
1
0.561531
Fewnity/Xenity-Engine
15,348
Xenity_Engine/Source/editor/ui/menus/debug/profiler_menu.cpp
// SPDX-License-Identifier: MIT // // Copyright (c) 2022-2025 Gregory Machefer (Fewnity) // // This file is part of Xenity Engine #include "profiler_menu.h" #include <imgui/imgui.h> #include <implot/implot.h> #include <implot/implot_internal.h> #include <engine/file_system/file_reference.h> #include <engine/time/time.h> #include <engine/engine_settings.h> #include <engine/debug/performance.h> #include <engine/debug/memory_tracker.h> #include <engine/asset_management/asset_manager.h> #include <engine/file_system/file.h> #include <engine/debug/memory_info.h> #include <editor/ui/editor_ui.h> void ProfilerMenu::Init() { } void ProfilerMenu::Draw() { UpdateFpsCounter(); UpdateMemoryCounter(); const std::string windowName = "Profiling###Profiling" + std::to_string(id); const bool visible = ImGui::Begin(windowName.c_str(), &m_isActive, ImGuiWindowFlags_NoCollapse); if (visible) { OnStartDrawing(); const std::string fpsText = "FPS: " + std::to_string(m_lastFps) + "###FPS_COUNTER"; ImGui::PlotLines(fpsText.c_str(), m_fpsHistory, FPS_HISTORY_SIZE, 0, "", 0); ImGui::Text("FPS average: %0.2f, average frame time %0.2fms", m_fpsAVG, (1 / m_fpsAVG) * 1000); ImGui::Text("DrawCalls Count: %d", Performance::GetDrawCallCount()); ImGui::Text("Triangles Count: %d", Performance::GetDrawTrianglesCount()); ImGui::Text("Materials update count: %d", Performance::GetUpdatedMaterialCount()); DrawMemoryStats(); DrawProfilerGraph(); CalculateWindowValues(); } else { ResetWindowValues(); } ImGui::End(); } void ProfilerMenu::UpdateFpsCounter() { const ImGuiIO& io = ImGui::GetIO(); //Update timer to slowly update framerate m_nextFpsUpdate += Time::GetUnscaledDeltaTime(); if (m_nextFpsUpdate >= 0.06f) { m_nextFpsUpdate = 0; m_lastFps = io.Framerate; } // If the counter history is empty, fill the counter with the current frame rate if (!m_counterInitialised) { m_counterInitialised = true; for (int i = 0; i < FPS_HISTORY_SIZE; i++) { m_fpsHistory[i] = io.Framerate; } } // Move history and make an average m_fpsAVG = 0; for (int i = 0; i < FPS_HISTORY_SIZE - 1; i++) { m_fpsAVG += m_fpsHistory[i]; m_fpsHistory[i] = m_fpsHistory[i + 1]; } m_fpsAVG /= FPS_HISTORY_SIZE - 1; m_fpsHistory[FPS_HISTORY_SIZE - 1] = m_lastFps; } void ProfilerMenu::UpdateMemoryCounter() { for (int i = 0; i < USED_MEMORY_HISTORY_SIZE - 1; i++) { m_usedMemoryHistory[i] = m_usedMemoryHistory[i + 1]; } m_usedMemoryHistory[USED_MEMORY_HISTORY_SIZE - 1] = static_cast<float>(MemoryInfo::GetUsedMemory() / 1000); for (int i = 0; i < USED_VIDE_MEMORY_HISTORY_SIZE - 1; i++) { m_usedVideoMemoryHistory[i] = m_usedVideoMemoryHistory[i + 1]; } m_usedVideoMemoryHistory[USED_VIDE_MEMORY_HISTORY_SIZE - 1] = static_cast<float>(MemoryInfo::GetUsedVideoMemory() / 1000); } void ProfilerMenu::DrawMemoryStats() { if (ImGui::CollapsingHeader("Memory stats", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed)) { ImGui::Text("Used memory:"); const std::string usedMemoryText = std::to_string((size_t)m_usedMemoryHistory[USED_MEMORY_HISTORY_SIZE - 1]) + " KiloBytes" + "###USED_MEMORY_COUNTER"; ImGui::PlotLines(usedMemoryText.c_str(), m_usedMemoryHistory, USED_MEMORY_HISTORY_SIZE, 0, "", 0); ImGui::Separator(); ImGui::Text("Used video memory:"); const std::string usedVideoMemoryText = std::to_string((size_t)m_usedVideoMemoryHistory[USED_VIDE_MEMORY_HISTORY_SIZE - 1]) + " KiloBytes" + "###USED_MEMORY_COUNTER"; ImGui::PlotLines(usedVideoMemoryText.c_str(), m_usedVideoMemoryHistory, USED_VIDE_MEMORY_HISTORY_SIZE, 0, "", 0); #if defined(DEBUG) ImGui::Separator(); const MemoryTracker* goMem = Performance::s_gameObjectMemoryTracker; ImGui::Text("%s:", goMem->m_name.c_str()); ImGui::Text("Current allocation: %zu Bytes, Total: %zu Bytes", goMem->m_allocatedMemory - goMem->m_deallocatedMemory, goMem->m_allocatedMemory); ImGui::Text("Current allocation: %f MegaBytes, Total: %f MegaBytes,", (goMem->m_allocatedMemory - goMem->m_deallocatedMemory) / 1000000.0f, goMem->m_allocatedMemory / 1000000.0f); ImGui::Text("Alloc count: %zu, Delete count: %zu", goMem->m_allocCount, goMem->m_deallocCount); const MemoryTracker* meshDataMem = Performance::s_meshDataMemoryTracker; ImGui::Separator(); ImGui::Text("%s:", meshDataMem->m_name.c_str()); ImGui::Text("Current allocation: %zu Bytes, Total: %zu Bytes", meshDataMem->m_allocatedMemory - meshDataMem->m_deallocatedMemory, meshDataMem->m_allocatedMemory); ImGui::Text("Current allocation: %f MegaBytes, Total: %f MegaBytes,", (meshDataMem->m_allocatedMemory - meshDataMem->m_deallocatedMemory) / 1000000.0f, meshDataMem->m_allocatedMemory / 1000000.0f); ImGui::Text("Alloc count: %zu, Delete count: %zu", meshDataMem->m_allocCount, meshDataMem->m_deallocCount); const MemoryTracker* textureMem = Performance::s_textureMemoryTracker; ImGui::Separator(); ImGui::Text("%s:", textureMem->m_name.c_str()); ImGui::Text("Current allocation: %zu Bytes, Total: %zu Bytes", textureMem->m_allocatedMemory - textureMem->m_deallocatedMemory, textureMem->m_allocatedMemory); ImGui::Text("Current allocation: %f MegaBytes, Total: %f MegaBytes,", (textureMem->m_allocatedMemory - textureMem->m_deallocatedMemory) / 1000000.0f, textureMem->m_allocatedMemory / 1000000.0f); ImGui::Text("Alloc count: %zu, Delete count: %zu", textureMem->m_allocCount, textureMem->m_deallocCount); #endif } } void ProfilerMenu::DrawProfilerGraph() { if (ImGui::CollapsingHeader("Profiler", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed)) { const std::string pauseText = m_isPaused ? "Resume Profilers" : "Pause Profilers"; if (ImGui::Button(pauseText.c_str())) { m_isPaused = !m_isPaused; Performance::s_isPaused = m_isPaused; } uint64_t offsetTime = m_lastStartTime; uint64_t endTime = m_lastEndTime; bool needUpdate = true; if (m_isPaused) { Performance::s_currentProfilerFrame = m_selectedProfilingRow; } else { m_selectedProfilingRow = Performance::s_currentProfilerFrame; m_lastFrame = Performance::s_currentFrame; } auto UpdateProfilers = [this, &offsetTime, &endTime, &needUpdate]() { if (needUpdate) { needUpdate = false; uint64_t engineLoopKey = 0; for (const auto& profilerNamesKV : Performance::s_scopProfilerNames) { if (profilerNamesKV.second == "Engine::Loop") { engineLoopKey = profilerNamesKV.first; break; } } offsetTime = Performance::s_scopProfilerList[Performance::s_currentProfilerFrame].timerResults[engineLoopKey][0].start; endTime = Performance::s_scopProfilerList[Performance::s_currentProfilerFrame].timerResults[engineLoopKey][0].end; CreateTimelineItems(); m_lastStartTime = offsetTime; m_lastEndTime = endTime; } }; if (ImGui::Button("Load profiler record file")) { std::string filePath = EditorUI::OpenFileDialog("Select record file", ""); if (!filePath.empty()) { m_selectedProfilingRow = Performance::s_currentProfilerFrame; m_lastFrame = Performance::s_currentFrame; m_isPaused = true; Performance::s_isPaused = true; Performance::LoadFromBinary(filePath); UpdateProfilers(); } } if (Performance::s_scopProfilerList[Performance::s_currentProfilerFrame].timerResults.empty()) { ImGui::Text("No profiler data available"); } else { //if (!isPaused) { UpdateProfilers(); } static ImGuiTableFlags profilerDumpListTableflags = ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersH | ImGuiTableFlags_ScrollY; if (ImGui::BeginTable("ProfilerDumpTable", 2, profilerDumpListTableflags, ImVec2(0, 200))) { ImGui::TableSetupColumn("id", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("duration", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); uint32_t i = 0; for (const auto& profilerLine : Performance::s_scopProfilerList) { ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); std::string idStr = std::to_string(profilerLine.frameId); if (profilerLine.frameId == m_lastFrame) { idStr += " (last frame)"; } if (ImGui::Selectable(idStr.c_str(), m_selectedProfilingRow == i)) { m_selectedProfilingRow = i; m_isPaused = true; } ImGui::TableSetColumnIndex(1); const std::string frameDurationStr = std::to_string(profilerLine.frameDuration); if (ImGui::Selectable(frameDurationStr.c_str(), m_selectedProfilingRow == i)) { m_selectedProfilingRow = i; m_isPaused = true; } i++; } ImGui::EndTable(); } if (ImGui::CollapsingHeader("Basic Profiler", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed)) { static ImGuiTableFlags basicProfilerTableflags = ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersH | ImGuiTableFlags_ScrollY; if (ImGui::BeginTable("BasicProfilerTable", 4, basicProfilerTableflags, ImVec2(0, 300))) { ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("Total time", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("Engine time", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("Call count in frame", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); for (const auto& profilerLine : m_classicProfilerItems) { ImGui::TableNextRow(); const uint64_t totalEngineTime = endTime - offsetTime; ImGui::TableSetColumnIndex(0); ImGui::Text("%s", profilerLine.name.c_str()); ImGui::TableSetColumnIndex(1); ImGui::Text("%d microseconds", profilerLine.totalTime); ImGui::TableSetColumnIndex(2); ImGui::Text("%.2f%%", ((double)profilerLine.totalTime / (double)totalEngineTime) * 100); ImGui::TableSetColumnIndex(3); ImGui::Text("%d", profilerLine.callCountInFrame); } ImGui::EndTable(); } } } if (ImGui::CollapsingHeader("Profiler Graph", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed)) { // If the profiler is not running, display a message if (Performance::s_scopProfilerList[Performance::s_currentProfilerFrame].timerResults.empty()) { ImGui::Text("No profiler data available"); } else { float lineHeigh = 1; // If the profiler not paused, update the timeline items //if (!isPaused) { UpdateProfilers(); } // Draw graph ImDrawList* draw_list = ImPlot::GetPlotDrawList(); if (ImPlot::BeginPlot("Profiler", ImVec2(-1, 500))) { ImPlot::SetupLegend(ImPlotLocation_West, ImPlotLegendFlags_Outside); // Set the axis limits ImPlot::SetupAxisLimitsConstraints(ImAxis_X1, 0, static_cast<float>(endTime - offsetTime)); ImPlot::SetupAxisLimitsConstraints(ImAxis_Y1, 0, m_lastMaxLevel + 1); const ImPlotPoint mousePoint = ImPlot::GetPlotMousePos(); ImVec2 mousePixelPos = ImPlot::PlotToPixels(mousePoint.x, mousePoint.y); size_t hoveredItemIndex = -1; const size_t timelineItemsCount = m_timelineItems.size(); for (size_t i = 0; i < timelineItemsCount; i++) { const TimelineItem& item = m_timelineItems[i]; if (ImPlot::BeginItem(item.name.c_str())) { // Get the item position in pixels and draw it const ImVec2 open_pos = ImPlot::PlotToPixels(static_cast<float>(item.start - offsetTime), item.level * lineHeigh); const ImVec2 close_pos = ImPlot::PlotToPixels(static_cast<float>(item.end - offsetTime), item.level * lineHeigh + lineHeigh); draw_list->AddRectFilled(open_pos, close_pos, ImGui::GetColorU32(ImPlot::GetCurrentItem()->Color)); // Check if the mouse is over the item if (mousePixelPos.x >= open_pos.x && mousePixelPos.x <= close_pos.x) { if (mousePixelPos.y >= close_pos.y && mousePixelPos.y <= open_pos.y) { hoveredItemIndex = i; } } ImPlot::EndItem(); } } if (hoveredItemIndex != -1) { const TimelineItem hoveredItem = m_timelineItems[hoveredItemIndex]; uint64_t itemTime = hoveredItem.end - hoveredItem.start; const float oldMouseX = mousePixelPos.x; const float oldMouseY = mousePixelPos.y; // Draw hovered item name { const std::string& mouseText = hoveredItem.name; ImVec2 textSize = ImGui::CalcTextSize(mouseText.c_str()); mousePixelPos.y -= textSize.y * 3; mousePixelPos.x -= textSize.x / 2.0f; draw_list->AddRectFilled(ImVec2(mousePixelPos.x, mousePixelPos.y), ImVec2(mousePixelPos.x + textSize.x, mousePixelPos.y + textSize.y), ImGui::GetColorU32(ImVec4(0, 0, 0, 0.6f))); draw_list->AddText(mousePixelPos, ImGui::GetColorU32(ImVec4(1, 1, 1, 1)), mouseText.c_str()); mousePixelPos.x = oldMouseX; mousePixelPos.y = oldMouseY; mousePixelPos.y -= textSize.y * 2; } // Draw time text { std::string mouseText = std::to_string(itemTime) + " microseconds"; ImVec2 textSize = ImGui::CalcTextSize(mouseText.c_str()); mousePixelPos.x -= textSize.x / 2.0f; draw_list->AddRectFilled(ImVec2(mousePixelPos.x, mousePixelPos.y), ImVec2(mousePixelPos.x + textSize.x, mousePixelPos.y + textSize.y), ImGui::GetColorU32(ImVec4(0, 0, 0, 0.6f))); draw_list->AddText(mousePixelPos, ImGui::GetColorU32(ImVec4(1, 1, 1, 1)), mouseText.c_str()); mousePixelPos.x = oldMouseX; mousePixelPos.y = oldMouseY; mousePixelPos.y -= textSize.y * 1; } // Draw percentage text { std::string mouseText = std::to_string((static_cast<float>(hoveredItem.end - hoveredItem.start) / static_cast<float>(endTime - offsetTime)) * 100); mouseText = mouseText.substr(0, mouseText.find('.') + 3) + "%"; ImVec2 textSize = ImGui::CalcTextSize(mouseText.c_str()); mousePixelPos.x -= textSize.x / 2.0f; draw_list->AddRectFilled(ImVec2(mousePixelPos.x, mousePixelPos.y), ImVec2(mousePixelPos.x + textSize.x, mousePixelPos.y + textSize.y), ImGui::GetColorU32(ImVec4(0, 0, 0, 0.6f))); draw_list->AddText(mousePixelPos, ImGui::GetColorU32(ImVec4(1, 1, 1, 1)), mouseText.c_str()); } } ImPlot::EndPlot(); } } } } } void ProfilerMenu::CreateTimelineItems() { m_timelineItems.clear(); m_classicProfilerItems.clear(); m_lastMaxLevel = 0; for (const auto& valCategory : Performance::s_scopProfilerList[Performance::s_currentProfilerFrame].timerResults) { ClassicProfilerItem& classicProfilerItem = m_classicProfilerItems.emplace_back(Performance::s_scopProfilerNames[valCategory.first]); for (const auto& value : valCategory.second) { classicProfilerItem.totalTime += static_cast<uint32_t>(value.end - value.start); classicProfilerItem.callCountInFrame++; TimelineItem item(Performance::s_scopProfilerNames[valCategory.first]); item.start = value.start; item.end = value.end; item.level = value.level; if (m_lastMaxLevel < value.level) { m_lastMaxLevel = value.level; } m_timelineItems.push_back(item); } } }
412
0.867979
1
0.867979
game-dev
MEDIA
0.24545
game-dev
0.909613
1
0.909613
Sigma-Skidder-Team/SigmaRebase
2,309
src/main/java/net/minecraft/item/WritableBookItem.java
package net.minecraft.item; import javax.annotation.Nullable; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.LecternBlock; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.ListNBT; import net.minecraft.stats.Stats; import net.minecraft.util.ActionResult; import net.minecraft.util.ActionResultType; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class WritableBookItem extends Item { public WritableBookItem(Item.Properties builder) { super(builder); } /** * Called when this item is used when targetting a Block */ public ActionResultType onItemUse(ItemUseContext context) { World world = context.getWorld(); BlockPos blockpos = context.getPos(); BlockState blockstate = world.getBlockState(blockpos); if (blockstate.isIn(Blocks.LECTERN)) { return LecternBlock.tryPlaceBook(world, blockpos, blockstate, context.getItem()) ? ActionResultType.func_233537_a_(world.isRemote) : ActionResultType.PASS; } else { return ActionResultType.PASS; } } public ActionResult<ItemStack> onItemRightClick(World worldIn, PlayerEntity playerIn, Hand handIn) { ItemStack itemstack = playerIn.getHeldItem(handIn); playerIn.openBook(itemstack, handIn); playerIn.addStat(Stats.ITEM_USED.get(this)); return ActionResult.func_233538_a_(itemstack, worldIn.isRemote()); } /** * this method returns true if the book's NBT Tag List "pages" is valid */ public static boolean isNBTValid(@Nullable CompoundNBT nbt) { if (nbt == null) { return false; } else if (!nbt.contains("pages", 9)) { return false; } else { ListNBT listnbt = nbt.getList("pages", 8); for (int i = 0; i < listnbt.size(); ++i) { String s = listnbt.getString(i); if (s.length() > 32767) { return false; } } return true; } } }
412
0.712784
1
0.712784
game-dev
MEDIA
0.999427
game-dev
0.975082
1
0.975082
splhack/Hello-LWF-Cocos2d-x
2,556
cocos2d/extensions/Particle3D/PU/CCPUOnRandomObserver.h
/**************************************************************************** Copyright (C) 2013 Henry van Merode. All rights reserved. Copyright (c) 2015 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __CC_PU_PARTICLE_3D_ON_RANDOM_OBSERVER_H__ #define __CC_PU_PARTICLE_3D_ON_RANDOM_OBSERVER_H__ #include "base/CCRef.h" #include "math/CCMath.h" #include "extensions/Particle3D/PU/CCPUObserver.h" #include <vector> #include <string> NS_CC_BEGIN struct PUParticle3D; class PUParticleSystem3D; class CC_DLL PUOnRandomObserver : public PUObserver { public: // Constants static const float DEFAULT_THRESHOLD; static PUOnRandomObserver* create(); /** See ParticleObserver::_preProcessParticles() */ virtual void preUpdateObserver(float deltaTime) override; /** See ParticleObserver::_processParticle() */ virtual void updateObserver(PUParticle3D *particle, float deltaTime, bool firstParticle) override; /** */ virtual bool observe (PUParticle3D* particle, float timeElapsed) override; /** */ float getThreshold(void) const {return _threshold;}; void setThreshold(float threshold){_threshold = threshold;}; virtual void copyAttributesTo (PUObserver* observer) override; CC_CONSTRUCTOR_ACCESS: PUOnRandomObserver(void); virtual ~PUOnRandomObserver(void) {}; protected: float _threshold; // Value between 0..1 }; NS_CC_END #endif
412
0.925702
1
0.925702
game-dev
MEDIA
0.594285
game-dev,graphics-rendering
0.753677
1
0.753677
magefree/mage
4,114
Mage.Sets/src/mage/cards/c/CrowdControlWarden.java
package mage.cards.c; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; import mage.abilities.effects.ReplacementEffectImpl; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.hint.Hint; import mage.abilities.hint.ValueHint; import mage.constants.*; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.keyword.DisguiseAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.counters.CounterType; import mage.filter.StaticFilters; import mage.game.Game; import mage.game.events.EntersTheBattlefieldEvent; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; /** * @author Cguy7777 */ public final class CrowdControlWarden extends CardImpl { private static final Hint hint = new ValueHint( "Other creatures you control", new PermanentsOnBattlefieldCount(StaticFilters.FILTER_CONTROLLED_ANOTHER_CREATURE)); public CrowdControlWarden(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}{W}"); this.subtype.add(SubType.CENTAUR); this.subtype.add(SubType.SOLDIER); this.power = new MageInt(4); this.toughness = new MageInt(4); // As Crowd-Control Warden enters the battlefield or is turned face up, put X +1/+1 counters on it, where X is the number of other creatures you control. Ability ability = new SimpleStaticAbility(Zone.ALL, new CrowdControlWardenReplacementEffect()); ability.setWorksFaceDown(true); ability.addHint(hint); this.addAbility(ability); // Disguise {3}{G/W}{G/W} this.addAbility(new DisguiseAbility(this, new ManaCostsImpl<>("{3}{G/W}{G/W}"))); } private CrowdControlWarden(final CrowdControlWarden card) { super(card); } @Override public CrowdControlWarden copy() { return new CrowdControlWarden(this); } } class CrowdControlWardenReplacementEffect extends ReplacementEffectImpl { private static final DynamicValue xValue = new PermanentsOnBattlefieldCount(StaticFilters.FILTER_CONTROLLED_ANOTHER_CREATURE); CrowdControlWardenReplacementEffect() { super(Duration.WhileOnBattlefield, Outcome.BoostCreature); staticText = "as {this} enters or is turned face up, " + "put X +1/+1 counters on it, where X is the number of other creatures you control"; } private CrowdControlWardenReplacementEffect(final CrowdControlWardenReplacementEffect effect) { super(effect); } @Override public boolean checksEventType(GameEvent event, Game game) { switch (event.getType()) { case ENTERS_THE_BATTLEFIELD: case TURN_FACE_UP: return true; default: return false; } } @Override public boolean applies(GameEvent event, Ability source, Game game) { if (event.getType() == GameEvent.EventType.ENTERS_THE_BATTLEFIELD) { if (event.getTargetId().equals(source.getSourceId())) { Permanent sourcePermanent = ((EntersTheBattlefieldEvent) event).getTarget(); if (sourcePermanent != null && !sourcePermanent.isFaceDown(game)) { return true; } } } if (event.getType() == GameEvent.EventType.TURN_FACE_UP) { return event.getTargetId().equals(source.getSourceId()); } return false; } @Override public boolean replaceEvent(GameEvent event, Ability source, Game game) { new AddCountersSourceEffect(CounterType.P1P1.createInstance(0), xValue, false) .apply(game, source); return false; } @Override public CrowdControlWardenReplacementEffect copy() { return new CrowdControlWardenReplacementEffect(this); } }
412
0.969736
1
0.969736
game-dev
MEDIA
0.990833
game-dev
0.991561
1
0.991561
corporateshark/Mastering-Android-NDK
14,847
Chapter6/1_GLES3/jni/SDL/include/SDL_keycode.h
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * \file SDL_keycode.h * * Defines constants which identify keyboard keys and modifiers. */ #ifndef _SDL_keycode_h #define _SDL_keycode_h #include "SDL_stdinc.h" #include "SDL_scancode.h" /** * \brief The SDL virtual key representation. * * Values of this type are used to represent keyboard keys using the current * layout of the keyboard. These values include Unicode values representing * the unmodified character that would be generated by pressing the key, or * an SDLK_* constant for those keys that do not generate characters. */ typedef Sint32 SDL_Keycode; #define SDLK_SCANCODE_MASK (1<<30) #define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK) enum { SDLK_UNKNOWN = 0, SDLK_RETURN = '\r', SDLK_ESCAPE = '\033', SDLK_BACKSPACE = '\b', SDLK_TAB = '\t', SDLK_SPACE = ' ', SDLK_EXCLAIM = '!', SDLK_QUOTEDBL = '"', SDLK_HASH = '#', SDLK_PERCENT = '%', SDLK_DOLLAR = '$', SDLK_AMPERSAND = '&', SDLK_QUOTE = '\'', SDLK_LEFTPAREN = '(', SDLK_RIGHTPAREN = ')', SDLK_ASTERISK = '*', SDLK_PLUS = '+', SDLK_COMMA = ',', SDLK_MINUS = '-', SDLK_PERIOD = '.', SDLK_SLASH = '/', SDLK_0 = '0', SDLK_1 = '1', SDLK_2 = '2', SDLK_3 = '3', SDLK_4 = '4', SDLK_5 = '5', SDLK_6 = '6', SDLK_7 = '7', SDLK_8 = '8', SDLK_9 = '9', SDLK_COLON = ':', SDLK_SEMICOLON = ';', SDLK_LESS = '<', SDLK_EQUALS = '=', SDLK_GREATER = '>', SDLK_QUESTION = '?', SDLK_AT = '@', /* Skip uppercase letters */ SDLK_LEFTBRACKET = '[', SDLK_BACKSLASH = '\\', SDLK_RIGHTBRACKET = ']', SDLK_CARET = '^', SDLK_UNDERSCORE = '_', SDLK_BACKQUOTE = '`', SDLK_a = 'a', SDLK_b = 'b', SDLK_c = 'c', SDLK_d = 'd', SDLK_e = 'e', SDLK_f = 'f', SDLK_g = 'g', SDLK_h = 'h', SDLK_i = 'i', SDLK_j = 'j', SDLK_k = 'k', SDLK_l = 'l', SDLK_m = 'm', SDLK_n = 'n', SDLK_o = 'o', SDLK_p = 'p', SDLK_q = 'q', SDLK_r = 'r', SDLK_s = 's', SDLK_t = 't', SDLK_u = 'u', SDLK_v = 'v', SDLK_w = 'w', SDLK_x = 'x', SDLK_y = 'y', SDLK_z = 'z', SDLK_CAPSLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CAPSLOCK), SDLK_F1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F1), SDLK_F2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F2), SDLK_F3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F3), SDLK_F4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F4), SDLK_F5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F5), SDLK_F6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F6), SDLK_F7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F7), SDLK_F8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F8), SDLK_F9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F9), SDLK_F10 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F10), SDLK_F11 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F11), SDLK_F12 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F12), SDLK_PRINTSCREEN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRINTSCREEN), SDLK_SCROLLLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SCROLLLOCK), SDLK_PAUSE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAUSE), SDLK_INSERT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INSERT), SDLK_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HOME), SDLK_PAGEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEUP), SDLK_DELETE = '\177', SDLK_END = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_END), SDLK_PAGEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEDOWN), SDLK_RIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RIGHT), SDLK_LEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LEFT), SDLK_DOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DOWN), SDLK_UP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UP), SDLK_NUMLOCKCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_NUMLOCKCLEAR), SDLK_KP_DIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DIVIDE), SDLK_KP_MULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MULTIPLY), SDLK_KP_MINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MINUS), SDLK_KP_PLUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUS), SDLK_KP_ENTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_ENTER), SDLK_KP_1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_1), SDLK_KP_2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_2), SDLK_KP_3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_3), SDLK_KP_4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_4), SDLK_KP_5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_5), SDLK_KP_6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_6), SDLK_KP_7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_7), SDLK_KP_8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_8), SDLK_KP_9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_9), SDLK_KP_0 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_0), SDLK_KP_PERIOD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERIOD), SDLK_APPLICATION = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APPLICATION), SDLK_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_POWER), SDLK_KP_EQUALS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALS), SDLK_F13 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F13), SDLK_F14 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F14), SDLK_F15 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F15), SDLK_F16 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F16), SDLK_F17 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F17), SDLK_F18 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F18), SDLK_F19 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F19), SDLK_F20 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F20), SDLK_F21 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F21), SDLK_F22 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F22), SDLK_F23 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F23), SDLK_F24 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F24), SDLK_EXECUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXECUTE), SDLK_HELP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HELP), SDLK_MENU = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MENU), SDLK_SELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SELECT), SDLK_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_STOP), SDLK_AGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AGAIN), SDLK_UNDO = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UNDO), SDLK_CUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CUT), SDLK_COPY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COPY), SDLK_PASTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PASTE), SDLK_FIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_FIND), SDLK_MUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MUTE), SDLK_VOLUMEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEUP), SDLK_VOLUMEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEDOWN), SDLK_KP_COMMA = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COMMA), SDLK_KP_EQUALSAS400 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALSAS400), SDLK_ALTERASE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ALTERASE), SDLK_SYSREQ = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SYSREQ), SDLK_CANCEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CANCEL), SDLK_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEAR), SDLK_PRIOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRIOR), SDLK_RETURN2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RETURN2), SDLK_SEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SEPARATOR), SDLK_OUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OUT), SDLK_OPER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OPER), SDLK_CLEARAGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEARAGAIN), SDLK_CRSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CRSEL), SDLK_EXSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXSEL), SDLK_KP_00 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_00), SDLK_KP_000 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_000), SDLK_THOUSANDSSEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_THOUSANDSSEPARATOR), SDLK_DECIMALSEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DECIMALSEPARATOR), SDLK_CURRENCYUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYUNIT), SDLK_CURRENCYSUBUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYSUBUNIT), SDLK_KP_LEFTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTPAREN), SDLK_KP_RIGHTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTPAREN), SDLK_KP_LEFTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTBRACE), SDLK_KP_RIGHTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTBRACE), SDLK_KP_TAB = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_TAB), SDLK_KP_BACKSPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BACKSPACE), SDLK_KP_A = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_A), SDLK_KP_B = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_B), SDLK_KP_C = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_C), SDLK_KP_D = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_D), SDLK_KP_E = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_E), SDLK_KP_F = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_F), SDLK_KP_XOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_XOR), SDLK_KP_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_POWER), SDLK_KP_PERCENT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERCENT), SDLK_KP_LESS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LESS), SDLK_KP_GREATER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_GREATER), SDLK_KP_AMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AMPERSAND), SDLK_KP_DBLAMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLAMPERSAND), SDLK_KP_VERTICALBAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_VERTICALBAR), SDLK_KP_DBLVERTICALBAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLVERTICALBAR), SDLK_KP_COLON = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COLON), SDLK_KP_HASH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HASH), SDLK_KP_SPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_SPACE), SDLK_KP_AT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AT), SDLK_KP_EXCLAM = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EXCLAM), SDLK_KP_MEMSTORE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSTORE), SDLK_KP_MEMRECALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMRECALL), SDLK_KP_MEMCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMCLEAR), SDLK_KP_MEMADD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMADD), SDLK_KP_MEMSUBTRACT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSUBTRACT), SDLK_KP_MEMMULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMMULTIPLY), SDLK_KP_MEMDIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMDIVIDE), SDLK_KP_PLUSMINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUSMINUS), SDLK_KP_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEAR), SDLK_KP_CLEARENTRY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEARENTRY), SDLK_KP_BINARY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BINARY), SDLK_KP_OCTAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_OCTAL), SDLK_KP_DECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DECIMAL), SDLK_KP_HEXADECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HEXADECIMAL), SDLK_LCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LCTRL), SDLK_LSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LSHIFT), SDLK_LALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LALT), SDLK_LGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LGUI), SDLK_RCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RCTRL), SDLK_RSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RSHIFT), SDLK_RALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RALT), SDLK_RGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RGUI), SDLK_MODE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MODE), SDLK_AUDIONEXT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIONEXT), SDLK_AUDIOPREV = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPREV), SDLK_AUDIOSTOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOSTOP), SDLK_AUDIOPLAY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPLAY), SDLK_AUDIOMUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOMUTE), SDLK_MEDIASELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIASELECT), SDLK_WWW = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_WWW), SDLK_MAIL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MAIL), SDLK_CALCULATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALCULATOR), SDLK_COMPUTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COMPUTER), SDLK_AC_SEARCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SEARCH), SDLK_AC_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_HOME), SDLK_AC_BACK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BACK), SDLK_AC_FORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_FORWARD), SDLK_AC_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_STOP), SDLK_AC_REFRESH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_REFRESH), SDLK_AC_BOOKMARKS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BOOKMARKS), SDLK_BRIGHTNESSDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSDOWN), SDLK_BRIGHTNESSUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSUP), SDLK_DISPLAYSWITCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DISPLAYSWITCH), SDLK_KBDILLUMTOGGLE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMTOGGLE), SDLK_KBDILLUMDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMDOWN), SDLK_KBDILLUMUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMUP), SDLK_EJECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EJECT), SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP) }; /** * \brief Enumeration of valid key mods (possibly OR'd together). */ typedef enum { KMOD_NONE = 0x0000, KMOD_LSHIFT = 0x0001, KMOD_RSHIFT = 0x0002, KMOD_LCTRL = 0x0040, KMOD_RCTRL = 0x0080, KMOD_LALT = 0x0100, KMOD_RALT = 0x0200, KMOD_LGUI = 0x0400, KMOD_RGUI = 0x0800, KMOD_NUM = 0x1000, KMOD_CAPS = 0x2000, KMOD_MODE = 0x4000, KMOD_RESERVED = 0x8000 } SDL_Keymod; #define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) #define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT) #define KMOD_ALT (KMOD_LALT|KMOD_RALT) #define KMOD_GUI (KMOD_LGUI|KMOD_RGUI) #endif /* _SDL_keycode_h */ /* vi: set ts=4 sw=4 expandtab: */
412
0.841491
1
0.841491
game-dev
MEDIA
0.744276
game-dev
0.699797
1
0.699797
AlessioDP/Parties
1,115
bungeecord/src/main/java/com/alessiodp/parties/bungeecord/addons/external/BungeePremiumVanishHandler.java
package com.alessiodp.parties.bungeecord.addons.external; import com.alessiodp.core.common.configuration.Constants; import com.alessiodp.parties.common.PartiesPlugin; import de.myzelyam.api.vanish.BungeeVanishAPI; import lombok.RequiredArgsConstructor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import org.jetbrains.annotations.NotNull; import java.util.UUID; @RequiredArgsConstructor public class BungeePremiumVanishHandler { @NotNull private final PartiesPlugin plugin; private static final String ADDON_NAME = "PremiumVanish"; private static boolean active = false; public void init() { active = false; if (ProxyServer.getInstance().getPluginManager().getPlugin(ADDON_NAME) != null) { active = true; plugin.getLoggerManager().log(String.format(Constants.DEBUG_ADDON_HOOKED, ADDON_NAME), true); } } public static boolean isPlayerVanished(UUID uuid) { if (active) { ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); if (player != null) return BungeeVanishAPI.isInvisible(player); } return false; } }
412
0.887776
1
0.887776
game-dev
MEDIA
0.751067
game-dev
0.770412
1
0.770412
mehah/otclient
5,530
mods/game_bot/default_configs/vBot_4.8/cavebot/tasker.lua
CaveBot.Extensions.Tasker = {} local dataValidationFailed = function() print("CaveBot[Tasker]: data validation failed! incorrect data, check cavebot/tasker for more info") return false end -- miniconfig local talkDelay = storage.extras.talkDelay if not storage.caveBotTasker then storage.caveBotTasker = { inProgress = false, monster = "", taskName = "", count = 0, max = 0 } end local resetTaskData = function() storage.caveBotTasker.inProgress = false storage.caveBotTasker.monster = "" storage.caveBotTasker.monster2 = "" storage.caveBotTasker.taskName = "" storage.caveBotTasker.count = 0 storage.caveBotTasker.max = 0 end CaveBot.Extensions.Tasker.setup = function() CaveBot.registerAction("Tasker", "#FF0090", function(value, retries) local taskName = "" local monster = "" local monster2 = "" local count = 0 local label1 = "" local label2 = "" local task local data = string.split(value, ",") if not data or #data < 1 then dataValidationFailed() end local marker = tonumber(data[1]) if not marker then dataValidationFailed() resetTaskData() elseif marker == 1 then if getNpcs(3) == 0 then print("CaveBot[Tasker]: no NPC found in range! skipping") return false end if #data ~= 4 and #data ~= 5 then dataValidationFailed() resetTaskData() else taskName = data[2]:lower():trim() count = tonumber(data[3]:trim()) monster = data[4]:lower():trim() if #data == 5 then monster2 = data[5]:lower():trim() end end elseif marker == 2 then if #data ~= 3 then dataValidationFailed() else label1 = data[2]:lower():trim() label2 = data[3]:lower():trim() end elseif marker == 3 then if getNpcs(3) == 0 then print("CaveBot[Tasker]: no NPC found in range! skipping") return false end if #data ~= 1 then dataValidationFailed() end end -- let's cover markers now if marker == 1 then -- starting task CaveBot.Conversation("hi", "task", taskName, "yes") delay(talkDelay*4) storage.caveBotTasker.monster = monster if monster2 then storage.caveBotTasker.monster2 = monster2 end storage.caveBotTasker.taskName = taskName storage.caveBotTasker.inProgress = true storage.caveBotTasker.max = count storage.caveBotTasker.count = 0 print("CaveBot[Tasker]: taken task for: " .. monster .. " x" .. count) return true elseif marker == 2 then -- only checking if not storage.caveBotTasker.inProgress then CaveBot.gotoLabel(label2) print("CaveBot[Tasker]: there is no task in progress so going to take one.") return true end local max = storage.caveBotTasker.max local count = storage.caveBotTasker.count if count >= max then CaveBot.gotoLabel(label2) print("CaveBot[Tasker]: task completed: " .. storage.caveBotTasker.taskName) return true else CaveBot.gotoLabel(label1) print("CaveBot[Tasker]: task in progress, left: " .. max - count .. " " .. storage.caveBotTasker.taskName) return true end elseif marker == 3 then -- reporting task CaveBot.Conversation("hi", "report", "task") delay(talkDelay*3) resetTaskData() print("CaveBot[Tasker]: task reported, done") return true end end) CaveBot.Editor.registerAction("tasker", "tasker", { value=[[ There is 3 scenarios for this extension, as example we will use medusa: 1. start task, parameters: - scenario for extension: 1 - task name in gryzzly adams: medusae - monster count: 500 - monster name to track: medusa - optional, monster name 2: 2. check status, to be used on refill to decide whether to go back or spawn or go give task back parameters: - scenario for extension: 2 - label if task in progress: skipTask - label if task done: taskDone 3. report task, parameters: - scenario for extension: 3 Strong suggestion, almost mandatory - USE POS CHECK to verify position! this module will only check if there is ANY npc in range! when begin remove all the text and leave just a single string of parameters some examples: 2, skipReport, goReport 3 1, drakens, 500, draken warmaster, draken spellweaver 1, medusae, 500, medusa]], title="Tasker", multiline = true }) end local regex = "Loot of ([a-z])* ([a-z A-Z]*):" local regex2 = "Loot of ([a-z A-Z]*):" onTextMessage(function(mode, text) -- if CaveBot.isOff() then return end if not text:lower():find("loot of") then return end if #regexMatch(text, regex) == 1 and #regexMatch(text, regex)[1] == 3 then monster = regexMatch(text, regex)[1][3] elseif #regexMatch(text, regex2) == 1 and #regexMatch(text, regex2)[1] == 2 then monster = regexMatch(text, regex2)[1][2] end local m1 = storage.caveBotTasker.monster local m2 = storage.caveBotTasker.monster2 if monster == m1 or monster == m2 and storage.caveBotTasker.count then storage.caveBotTasker.count = storage.caveBotTasker.count + 1 end end)
412
0.716511
1
0.716511
game-dev
MEDIA
0.872246
game-dev
0.935263
1
0.935263
PlayFab/UnrealMarketplacePlugin
48,657
4.25/ExampleProject/Plugins/PlayFab/Source/PlayFabCpp/Private/Core/PlayFabProfilesDataModels.cpp
////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// // This is automatically generated by PlayFab SDKGenerator. DO NOT modify this manually! #include "Core/PlayFabProfilesDataModels.h" #include "Core/PlayFabJsonHelpers.h" using namespace PlayFab; using namespace PlayFab::ProfilesModels; void PlayFab::ProfilesModels::writeEffectTypeEnumJSON(EffectType enumVal, JsonWriter& writer) { switch (enumVal) { case EffectTypeAllow: writer->WriteValue(TEXT("Allow")); break; case EffectTypeDeny: writer->WriteValue(TEXT("Deny")); break; } } ProfilesModels::EffectType PlayFab::ProfilesModels::readEffectTypeFromValue(const TSharedPtr<FJsonValue>& value) { return readEffectTypeFromValue(value.IsValid() ? value->AsString() : ""); } ProfilesModels::EffectType PlayFab::ProfilesModels::readEffectTypeFromValue(const FString& value) { static TMap<FString, EffectType> _EffectTypeMap; if (_EffectTypeMap.Num() == 0) { // Auto-generate the map on the first use _EffectTypeMap.Add(TEXT("Allow"), EffectTypeAllow); _EffectTypeMap.Add(TEXT("Deny"), EffectTypeDeny); } if (!value.IsEmpty()) { auto output = _EffectTypeMap.Find(value); if (output != nullptr) return *output; } return EffectTypeAllow; // Basically critical fail } PlayFab::ProfilesModels::FEntityDataObject::~FEntityDataObject() { } void PlayFab::ProfilesModels::FEntityDataObject::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (DataObject.notNull()) { writer->WriteIdentifierPrefix(TEXT("DataObject")); DataObject.writeJSON(writer); } if (EscapedDataObject.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("EscapedDataObject")); writer->WriteValue(EscapedDataObject); } if (ObjectName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ObjectName")); writer->WriteValue(ObjectName); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FEntityDataObject::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> DataObjectValue = obj->TryGetField(TEXT("DataObject")); if (DataObjectValue.IsValid() && !DataObjectValue->IsNull()) { DataObject = FJsonKeeper(DataObjectValue); } const TSharedPtr<FJsonValue> EscapedDataObjectValue = obj->TryGetField(TEXT("EscapedDataObject")); if (EscapedDataObjectValue.IsValid() && !EscapedDataObjectValue->IsNull()) { FString TmpValue; if (EscapedDataObjectValue->TryGetString(TmpValue)) { EscapedDataObject = TmpValue; } } const TSharedPtr<FJsonValue> ObjectNameValue = obj->TryGetField(TEXT("ObjectName")); if (ObjectNameValue.IsValid() && !ObjectNameValue->IsNull()) { FString TmpValue; if (ObjectNameValue->TryGetString(TmpValue)) { ObjectName = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FEntityKey::~FEntityKey() { } void PlayFab::ProfilesModels::FEntityKey::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (!Id.IsEmpty() == false) { UE_LOG(LogTemp, Error, TEXT("This field is required: EntityKey::Id, PlayFab calls may not work if it remains empty.")); } else { writer->WriteIdentifierPrefix(TEXT("Id")); writer->WriteValue(Id); } if (Type.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Type")); writer->WriteValue(Type); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FEntityKey::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IdValue = obj->TryGetField(TEXT("Id")); if (IdValue.IsValid() && !IdValue->IsNull()) { FString TmpValue; if (IdValue->TryGetString(TmpValue)) { Id = TmpValue; } } const TSharedPtr<FJsonValue> TypeValue = obj->TryGetField(TEXT("Type")); if (TypeValue.IsValid() && !TypeValue->IsNull()) { FString TmpValue; if (TypeValue->TryGetString(TmpValue)) { Type = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FEntityLineage::~FEntityLineage() { } void PlayFab::ProfilesModels::FEntityLineage::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (GroupId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("GroupId")); writer->WriteValue(GroupId); } if (MasterPlayerAccountId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("MasterPlayerAccountId")); writer->WriteValue(MasterPlayerAccountId); } if (NamespaceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("NamespaceId")); writer->WriteValue(NamespaceId); } if (TitleId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitleId")); writer->WriteValue(TitleId); } if (TitlePlayerAccountId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitlePlayerAccountId")); writer->WriteValue(TitlePlayerAccountId); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FEntityLineage::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> GroupIdValue = obj->TryGetField(TEXT("GroupId")); if (GroupIdValue.IsValid() && !GroupIdValue->IsNull()) { FString TmpValue; if (GroupIdValue->TryGetString(TmpValue)) { GroupId = TmpValue; } } const TSharedPtr<FJsonValue> MasterPlayerAccountIdValue = obj->TryGetField(TEXT("MasterPlayerAccountId")); if (MasterPlayerAccountIdValue.IsValid() && !MasterPlayerAccountIdValue->IsNull()) { FString TmpValue; if (MasterPlayerAccountIdValue->TryGetString(TmpValue)) { MasterPlayerAccountId = TmpValue; } } const TSharedPtr<FJsonValue> NamespaceIdValue = obj->TryGetField(TEXT("NamespaceId")); if (NamespaceIdValue.IsValid() && !NamespaceIdValue->IsNull()) { FString TmpValue; if (NamespaceIdValue->TryGetString(TmpValue)) { NamespaceId = TmpValue; } } const TSharedPtr<FJsonValue> TitleIdValue = obj->TryGetField(TEXT("TitleId")); if (TitleIdValue.IsValid() && !TitleIdValue->IsNull()) { FString TmpValue; if (TitleIdValue->TryGetString(TmpValue)) { TitleId = TmpValue; } } const TSharedPtr<FJsonValue> TitlePlayerAccountIdValue = obj->TryGetField(TEXT("TitlePlayerAccountId")); if (TitlePlayerAccountIdValue.IsValid() && !TitlePlayerAccountIdValue->IsNull()) { FString TmpValue; if (TitlePlayerAccountIdValue->TryGetString(TmpValue)) { TitlePlayerAccountId = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FEntityPermissionStatement::~FEntityPermissionStatement() { } void PlayFab::ProfilesModels::FEntityPermissionStatement::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (!Action.IsEmpty() == false) { UE_LOG(LogTemp, Error, TEXT("This field is required: EntityPermissionStatement::Action, PlayFab calls may not work if it remains empty.")); } else { writer->WriteIdentifierPrefix(TEXT("Action")); writer->WriteValue(Action); } if (Comment.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Comment")); writer->WriteValue(Comment); } if (Condition.notNull()) { writer->WriteIdentifierPrefix(TEXT("Condition")); Condition.writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("Effect")); writeEffectTypeEnumJSON(Effect, writer); writer->WriteIdentifierPrefix(TEXT("Principal")); Principal.writeJSON(writer); if (!Resource.IsEmpty() == false) { UE_LOG(LogTemp, Error, TEXT("This field is required: EntityPermissionStatement::Resource, PlayFab calls may not work if it remains empty.")); } else { writer->WriteIdentifierPrefix(TEXT("Resource")); writer->WriteValue(Resource); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FEntityPermissionStatement::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ActionValue = obj->TryGetField(TEXT("Action")); if (ActionValue.IsValid() && !ActionValue->IsNull()) { FString TmpValue; if (ActionValue->TryGetString(TmpValue)) { Action = TmpValue; } } const TSharedPtr<FJsonValue> CommentValue = obj->TryGetField(TEXT("Comment")); if (CommentValue.IsValid() && !CommentValue->IsNull()) { FString TmpValue; if (CommentValue->TryGetString(TmpValue)) { Comment = TmpValue; } } const TSharedPtr<FJsonValue> ConditionValue = obj->TryGetField(TEXT("Condition")); if (ConditionValue.IsValid() && !ConditionValue->IsNull()) { Condition = FJsonKeeper(ConditionValue); } Effect = readEffectTypeFromValue(obj->TryGetField(TEXT("Effect"))); const TSharedPtr<FJsonValue> PrincipalValue = obj->TryGetField(TEXT("Principal")); if (PrincipalValue.IsValid() && !PrincipalValue->IsNull()) { Principal = FJsonKeeper(PrincipalValue); } const TSharedPtr<FJsonValue> ResourceValue = obj->TryGetField(TEXT("Resource")); if (ResourceValue.IsValid() && !ResourceValue->IsNull()) { FString TmpValue; if (ResourceValue->TryGetString(TmpValue)) { Resource = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FEntityProfileFileMetadata::~FEntityProfileFileMetadata() { } void PlayFab::ProfilesModels::FEntityProfileFileMetadata::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Checksum.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Checksum")); writer->WriteValue(Checksum); } if (FileName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FileName")); writer->WriteValue(FileName); } writer->WriteIdentifierPrefix(TEXT("LastModified")); writeDatetime(LastModified, writer); writer->WriteIdentifierPrefix(TEXT("Size")); writer->WriteValue(Size); writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FEntityProfileFileMetadata::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ChecksumValue = obj->TryGetField(TEXT("Checksum")); if (ChecksumValue.IsValid() && !ChecksumValue->IsNull()) { FString TmpValue; if (ChecksumValue->TryGetString(TmpValue)) { Checksum = TmpValue; } } const TSharedPtr<FJsonValue> FileNameValue = obj->TryGetField(TEXT("FileName")); if (FileNameValue.IsValid() && !FileNameValue->IsNull()) { FString TmpValue; if (FileNameValue->TryGetString(TmpValue)) { FileName = TmpValue; } } const TSharedPtr<FJsonValue> LastModifiedValue = obj->TryGetField(TEXT("LastModified")); if (LastModifiedValue.IsValid()) LastModified = readDatetime(LastModifiedValue); const TSharedPtr<FJsonValue> SizeValue = obj->TryGetField(TEXT("Size")); if (SizeValue.IsValid() && !SizeValue->IsNull()) { int32 TmpValue; if (SizeValue->TryGetNumber(TmpValue)) { Size = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FEntityStatisticValue::~FEntityStatisticValue() { } void PlayFab::ProfilesModels::FEntityStatisticValue::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Metadata.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Metadata")); writer->WriteValue(Metadata); } if (Name.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Name")); writer->WriteValue(Name); } if (Scores.Num() != 0) { writer->WriteArrayStart(TEXT("Scores")); for (const FString& item : Scores) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(Version); writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FEntityStatisticValue::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> MetadataValue = obj->TryGetField(TEXT("Metadata")); if (MetadataValue.IsValid() && !MetadataValue->IsNull()) { FString TmpValue; if (MetadataValue->TryGetString(TmpValue)) { Metadata = TmpValue; } } const TSharedPtr<FJsonValue> NameValue = obj->TryGetField(TEXT("Name")); if (NameValue.IsValid() && !NameValue->IsNull()) { FString TmpValue; if (NameValue->TryGetString(TmpValue)) { Name = TmpValue; } } obj->TryGetStringArrayField(TEXT("Scores"), Scores); const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { int32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FEntityProfileBody::~FEntityProfileBody() { //if (Entity != nullptr) delete Entity; //if (Lineage != nullptr) delete Lineage; } void PlayFab::ProfilesModels::FEntityProfileBody::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AvatarUrl.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("AvatarUrl")); writer->WriteValue(AvatarUrl); } writer->WriteIdentifierPrefix(TEXT("Created")); writeDatetime(Created, writer); if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (Entity.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Entity")); Entity->writeJSON(writer); } if (EntityChain.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("EntityChain")); writer->WriteValue(EntityChain); } if (ExperimentVariants.Num() != 0) { writer->WriteArrayStart(TEXT("ExperimentVariants")); for (const FString& item : ExperimentVariants) writer->WriteValue(item); writer->WriteArrayEnd(); } if (Files.Num() != 0) { writer->WriteObjectStart(TEXT("Files")); for (TMap<FString, FEntityProfileFileMetadata>::TConstIterator It(Files); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } if (Language.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Language")); writer->WriteValue(Language); } if (Lineage.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Lineage")); Lineage->writeJSON(writer); } if (Objects.Num() != 0) { writer->WriteObjectStart(TEXT("Objects")); for (TMap<FString, FEntityDataObject>::TConstIterator It(Objects); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } if (Permissions.Num() != 0) { writer->WriteArrayStart(TEXT("Permissions")); for (const FEntityPermissionStatement& item : Permissions) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Statistics.Num() != 0) { writer->WriteObjectStart(TEXT("Statistics")); for (TMap<FString, FEntityStatisticValue>::TConstIterator It(Statistics); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("VersionNumber")); writer->WriteValue(VersionNumber); writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FEntityProfileBody::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AvatarUrlValue = obj->TryGetField(TEXT("AvatarUrl")); if (AvatarUrlValue.IsValid() && !AvatarUrlValue->IsNull()) { FString TmpValue; if (AvatarUrlValue->TryGetString(TmpValue)) { AvatarUrl = TmpValue; } } const TSharedPtr<FJsonValue> CreatedValue = obj->TryGetField(TEXT("Created")); if (CreatedValue.IsValid()) Created = readDatetime(CreatedValue); const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> EntityValue = obj->TryGetField(TEXT("Entity")); if (EntityValue.IsValid() && !EntityValue->IsNull()) { Entity = MakeShareable(new FEntityKey(EntityValue->AsObject())); } const TSharedPtr<FJsonValue> EntityChainValue = obj->TryGetField(TEXT("EntityChain")); if (EntityChainValue.IsValid() && !EntityChainValue->IsNull()) { FString TmpValue; if (EntityChainValue->TryGetString(TmpValue)) { EntityChain = TmpValue; } } obj->TryGetStringArrayField(TEXT("ExperimentVariants"), ExperimentVariants); const TSharedPtr<FJsonObject>* FilesObject; if (obj->TryGetObjectField(TEXT("Files"), FilesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*FilesObject)->Values); It; ++It) { Files.Add(It.Key(), FEntityProfileFileMetadata(It.Value()->AsObject())); } } const TSharedPtr<FJsonValue> LanguageValue = obj->TryGetField(TEXT("Language")); if (LanguageValue.IsValid() && !LanguageValue->IsNull()) { FString TmpValue; if (LanguageValue->TryGetString(TmpValue)) { Language = TmpValue; } } const TSharedPtr<FJsonValue> LineageValue = obj->TryGetField(TEXT("Lineage")); if (LineageValue.IsValid() && !LineageValue->IsNull()) { Lineage = MakeShareable(new FEntityLineage(LineageValue->AsObject())); } const TSharedPtr<FJsonObject>* ObjectsObject; if (obj->TryGetObjectField(TEXT("Objects"), ObjectsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*ObjectsObject)->Values); It; ++It) { Objects.Add(It.Key(), FEntityDataObject(It.Value()->AsObject())); } } const TArray<TSharedPtr<FJsonValue>>&PermissionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Permissions")); for (int32 Idx = 0; Idx < PermissionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PermissionsArray[Idx]; Permissions.Add(FEntityPermissionStatement(CurrentItem->AsObject())); } const TSharedPtr<FJsonObject>* StatisticsObject; if (obj->TryGetObjectField(TEXT("Statistics"), StatisticsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*StatisticsObject)->Values); It; ++It) { Statistics.Add(It.Key(), FEntityStatisticValue(It.Value()->AsObject())); } } const TSharedPtr<FJsonValue> VersionNumberValue = obj->TryGetField(TEXT("VersionNumber")); if (VersionNumberValue.IsValid() && !VersionNumberValue->IsNull()) { int32 TmpValue; if (VersionNumberValue->TryGetNumber(TmpValue)) { VersionNumber = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FGetEntityProfileRequest::~FGetEntityProfileRequest() { //if (Entity != nullptr) delete Entity; } void PlayFab::ProfilesModels::FGetEntityProfileRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (DataAsObject.notNull()) { writer->WriteIdentifierPrefix(TEXT("DataAsObject")); writer->WriteValue(DataAsObject); } if (Entity.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Entity")); Entity->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetEntityProfileRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> DataAsObjectValue = obj->TryGetField(TEXT("DataAsObject")); if (DataAsObjectValue.IsValid() && !DataAsObjectValue->IsNull()) { bool TmpValue; if (DataAsObjectValue->TryGetBool(TmpValue)) { DataAsObject = TmpValue; } } const TSharedPtr<FJsonValue> EntityValue = obj->TryGetField(TEXT("Entity")); if (EntityValue.IsValid() && !EntityValue->IsNull()) { Entity = MakeShareable(new FEntityKey(EntityValue->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FGetEntityProfileResponse::~FGetEntityProfileResponse() { //if (Profile != nullptr) delete Profile; } void PlayFab::ProfilesModels::FGetEntityProfileResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Profile.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Profile")); Profile->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetEntityProfileResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ProfileValue = obj->TryGetField(TEXT("Profile")); if (ProfileValue.IsValid() && !ProfileValue->IsNull()) { Profile = MakeShareable(new FEntityProfileBody(ProfileValue->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FGetEntityProfilesRequest::~FGetEntityProfilesRequest() { } void PlayFab::ProfilesModels::FGetEntityProfilesRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (DataAsObject.notNull()) { writer->WriteIdentifierPrefix(TEXT("DataAsObject")); writer->WriteValue(DataAsObject); } writer->WriteArrayStart(TEXT("Entities")); for (const FEntityKey& item : Entities) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetEntityProfilesRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> DataAsObjectValue = obj->TryGetField(TEXT("DataAsObject")); if (DataAsObjectValue.IsValid() && !DataAsObjectValue->IsNull()) { bool TmpValue; if (DataAsObjectValue->TryGetBool(TmpValue)) { DataAsObject = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&EntitiesArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Entities")); for (int32 Idx = 0; Idx < EntitiesArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = EntitiesArray[Idx]; Entities.Add(FEntityKey(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FGetEntityProfilesResponse::~FGetEntityProfilesResponse() { } void PlayFab::ProfilesModels::FGetEntityProfilesResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Profiles.Num() != 0) { writer->WriteArrayStart(TEXT("Profiles")); for (const FEntityProfileBody& item : Profiles) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetEntityProfilesResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&ProfilesArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Profiles")); for (int32 Idx = 0; Idx < ProfilesArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ProfilesArray[Idx]; Profiles.Add(FEntityProfileBody(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FGetGlobalPolicyRequest::~FGetGlobalPolicyRequest() { //if (Entity != nullptr) delete Entity; } void PlayFab::ProfilesModels::FGetGlobalPolicyRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (Entity.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Entity")); Entity->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetGlobalPolicyRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> EntityValue = obj->TryGetField(TEXT("Entity")); if (EntityValue.IsValid() && !EntityValue->IsNull()) { Entity = MakeShareable(new FEntityKey(EntityValue->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FGetGlobalPolicyResponse::~FGetGlobalPolicyResponse() { } void PlayFab::ProfilesModels::FGetGlobalPolicyResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Permissions.Num() != 0) { writer->WriteArrayStart(TEXT("Permissions")); for (const FEntityPermissionStatement& item : Permissions) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetGlobalPolicyResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&PermissionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Permissions")); for (int32 Idx = 0; Idx < PermissionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PermissionsArray[Idx]; Permissions.Add(FEntityPermissionStatement(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FGetTitlePlayersFromMasterPlayerAccountIdsRequest::~FGetTitlePlayersFromMasterPlayerAccountIdsRequest() { } void PlayFab::ProfilesModels::FGetTitlePlayersFromMasterPlayerAccountIdsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteArrayStart(TEXT("MasterPlayerAccountIds")); for (const FString& item : MasterPlayerAccountIds) writer->WriteValue(item); writer->WriteArrayEnd(); if (TitleId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitleId")); writer->WriteValue(TitleId); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetTitlePlayersFromMasterPlayerAccountIdsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } obj->TryGetStringArrayField(TEXT("MasterPlayerAccountIds"), MasterPlayerAccountIds); const TSharedPtr<FJsonValue> TitleIdValue = obj->TryGetField(TEXT("TitleId")); if (TitleIdValue.IsValid() && !TitleIdValue->IsNull()) { FString TmpValue; if (TitleIdValue->TryGetString(TmpValue)) { TitleId = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FGetTitlePlayersFromMasterPlayerAccountIdsResponse::~FGetTitlePlayersFromMasterPlayerAccountIdsResponse() { } void PlayFab::ProfilesModels::FGetTitlePlayersFromMasterPlayerAccountIdsResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (TitleId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitleId")); writer->WriteValue(TitleId); } if (TitlePlayerAccounts.Num() != 0) { writer->WriteObjectStart(TEXT("TitlePlayerAccounts")); for (TMap<FString, FEntityKey>::TConstIterator It(TitlePlayerAccounts); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetTitlePlayersFromMasterPlayerAccountIdsResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> TitleIdValue = obj->TryGetField(TEXT("TitleId")); if (TitleIdValue.IsValid() && !TitleIdValue->IsNull()) { FString TmpValue; if (TitleIdValue->TryGetString(TmpValue)) { TitleId = TmpValue; } } const TSharedPtr<FJsonObject>* TitlePlayerAccountsObject; if (obj->TryGetObjectField(TEXT("TitlePlayerAccounts"), TitlePlayerAccountsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*TitlePlayerAccountsObject)->Values); It; ++It) { TitlePlayerAccounts.Add(It.Key(), FEntityKey(It.Value()->AsObject())); } } return HasSucceeded; } PlayFab::ProfilesModels::FGetTitlePlayersFromProviderIDsResponse::~FGetTitlePlayersFromProviderIDsResponse() { } void PlayFab::ProfilesModels::FGetTitlePlayersFromProviderIDsResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (TitlePlayerAccounts.Num() != 0) { writer->WriteObjectStart(TEXT("TitlePlayerAccounts")); for (TMap<FString, FEntityLineage>::TConstIterator It(TitlePlayerAccounts); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetTitlePlayersFromProviderIDsResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* TitlePlayerAccountsObject; if (obj->TryGetObjectField(TEXT("TitlePlayerAccounts"), TitlePlayerAccountsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*TitlePlayerAccountsObject)->Values); It; ++It) { TitlePlayerAccounts.Add(It.Key(), FEntityLineage(It.Value()->AsObject())); } } return HasSucceeded; } PlayFab::ProfilesModels::FGetTitlePlayersFromXboxLiveIDsRequest::~FGetTitlePlayersFromXboxLiveIDsRequest() { } void PlayFab::ProfilesModels::FGetTitlePlayersFromXboxLiveIDsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (!Sandbox.IsEmpty() == false) { UE_LOG(LogTemp, Error, TEXT("This field is required: GetTitlePlayersFromXboxLiveIDsRequest::Sandbox, PlayFab calls may not work if it remains empty.")); } else { writer->WriteIdentifierPrefix(TEXT("Sandbox")); writer->WriteValue(Sandbox); } if (TitleId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitleId")); writer->WriteValue(TitleId); } writer->WriteArrayStart(TEXT("XboxLiveIds")); for (const FString& item : XboxLiveIds) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FGetTitlePlayersFromXboxLiveIDsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> SandboxValue = obj->TryGetField(TEXT("Sandbox")); if (SandboxValue.IsValid() && !SandboxValue->IsNull()) { FString TmpValue; if (SandboxValue->TryGetString(TmpValue)) { Sandbox = TmpValue; } } const TSharedPtr<FJsonValue> TitleIdValue = obj->TryGetField(TEXT("TitleId")); if (TitleIdValue.IsValid() && !TitleIdValue->IsNull()) { FString TmpValue; if (TitleIdValue->TryGetString(TmpValue)) { TitleId = TmpValue; } } obj->TryGetStringArrayField(TEXT("XboxLiveIds"), XboxLiveIds); return HasSucceeded; } void PlayFab::ProfilesModels::writeOperationTypesEnumJSON(OperationTypes enumVal, JsonWriter& writer) { switch (enumVal) { case OperationTypesCreated: writer->WriteValue(TEXT("Created")); break; case OperationTypesUpdated: writer->WriteValue(TEXT("Updated")); break; case OperationTypesDeleted: writer->WriteValue(TEXT("Deleted")); break; case OperationTypesNone: writer->WriteValue(TEXT("None")); break; } } ProfilesModels::OperationTypes PlayFab::ProfilesModels::readOperationTypesFromValue(const TSharedPtr<FJsonValue>& value) { return readOperationTypesFromValue(value.IsValid() ? value->AsString() : ""); } ProfilesModels::OperationTypes PlayFab::ProfilesModels::readOperationTypesFromValue(const FString& value) { static TMap<FString, OperationTypes> _OperationTypesMap; if (_OperationTypesMap.Num() == 0) { // Auto-generate the map on the first use _OperationTypesMap.Add(TEXT("Created"), OperationTypesCreated); _OperationTypesMap.Add(TEXT("Updated"), OperationTypesUpdated); _OperationTypesMap.Add(TEXT("Deleted"), OperationTypesDeleted); _OperationTypesMap.Add(TEXT("None"), OperationTypesNone); } if (!value.IsEmpty()) { auto output = _OperationTypesMap.Find(value); if (output != nullptr) return *output; } return OperationTypesCreated; // Basically critical fail } PlayFab::ProfilesModels::FSetDisplayNameRequest::~FSetDisplayNameRequest() { //if (Entity != nullptr) delete Entity; } void PlayFab::ProfilesModels::FSetDisplayNameRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (Entity.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Entity")); Entity->writeJSON(writer); } if (ExpectedVersion.notNull()) { writer->WriteIdentifierPrefix(TEXT("ExpectedVersion")); writer->WriteValue(ExpectedVersion); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetDisplayNameRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> EntityValue = obj->TryGetField(TEXT("Entity")); if (EntityValue.IsValid() && !EntityValue->IsNull()) { Entity = MakeShareable(new FEntityKey(EntityValue->AsObject())); } const TSharedPtr<FJsonValue> ExpectedVersionValue = obj->TryGetField(TEXT("ExpectedVersion")); if (ExpectedVersionValue.IsValid() && !ExpectedVersionValue->IsNull()) { int32 TmpValue; if (ExpectedVersionValue->TryGetNumber(TmpValue)) { ExpectedVersion = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FSetDisplayNameResponse::~FSetDisplayNameResponse() { } void PlayFab::ProfilesModels::FSetDisplayNameResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (OperationResult.notNull()) { writer->WriteIdentifierPrefix(TEXT("OperationResult")); writeOperationTypesEnumJSON(OperationResult, writer); } if (VersionNumber.notNull()) { writer->WriteIdentifierPrefix(TEXT("VersionNumber")); writer->WriteValue(VersionNumber); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetDisplayNameResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; OperationResult = readOperationTypesFromValue(obj->TryGetField(TEXT("OperationResult"))); const TSharedPtr<FJsonValue> VersionNumberValue = obj->TryGetField(TEXT("VersionNumber")); if (VersionNumberValue.IsValid() && !VersionNumberValue->IsNull()) { int32 TmpValue; if (VersionNumberValue->TryGetNumber(TmpValue)) { VersionNumber = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FSetEntityProfilePolicyRequest::~FSetEntityProfilePolicyRequest() { } void PlayFab::ProfilesModels::FSetEntityProfilePolicyRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("Entity")); Entity.writeJSON(writer); writer->WriteArrayStart(TEXT("Statements")); for (const FEntityPermissionStatement& item : Statements) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetEntityProfilePolicyRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> EntityValue = obj->TryGetField(TEXT("Entity")); if (EntityValue.IsValid() && !EntityValue->IsNull()) { Entity = FEntityKey(EntityValue->AsObject()); } const TArray<TSharedPtr<FJsonValue>>&StatementsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Statements")); for (int32 Idx = 0; Idx < StatementsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = StatementsArray[Idx]; Statements.Add(FEntityPermissionStatement(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FSetEntityProfilePolicyResponse::~FSetEntityProfilePolicyResponse() { } void PlayFab::ProfilesModels::FSetEntityProfilePolicyResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Permissions.Num() != 0) { writer->WriteArrayStart(TEXT("Permissions")); for (const FEntityPermissionStatement& item : Permissions) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetEntityProfilePolicyResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&PermissionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Permissions")); for (int32 Idx = 0; Idx < PermissionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PermissionsArray[Idx]; Permissions.Add(FEntityPermissionStatement(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FSetGlobalPolicyRequest::~FSetGlobalPolicyRequest() { } void PlayFab::ProfilesModels::FSetGlobalPolicyRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (Permissions.Num() != 0) { writer->WriteArrayStart(TEXT("Permissions")); for (const FEntityPermissionStatement& item : Permissions) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetGlobalPolicyRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TArray<TSharedPtr<FJsonValue>>&PermissionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Permissions")); for (int32 Idx = 0; Idx < PermissionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PermissionsArray[Idx]; Permissions.Add(FEntityPermissionStatement(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ProfilesModels::FSetGlobalPolicyResponse::~FSetGlobalPolicyResponse() { } void PlayFab::ProfilesModels::FSetGlobalPolicyResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetGlobalPolicyResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ProfilesModels::FSetProfileLanguageRequest::~FSetProfileLanguageRequest() { //if (Entity != nullptr) delete Entity; } void PlayFab::ProfilesModels::FSetProfileLanguageRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomTags.Num() != 0) { writer->WriteObjectStart(TEXT("CustomTags")); for (TMap<FString, FString>::TConstIterator It(CustomTags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (Entity.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Entity")); Entity->writeJSON(writer); } if (ExpectedVersion.notNull()) { writer->WriteIdentifierPrefix(TEXT("ExpectedVersion")); writer->WriteValue(ExpectedVersion); } if (Language.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Language")); writer->WriteValue(Language); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetProfileLanguageRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* CustomTagsObject; if (obj->TryGetObjectField(TEXT("CustomTags"), CustomTagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomTagsObject)->Values); It; ++It) { CustomTags.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> EntityValue = obj->TryGetField(TEXT("Entity")); if (EntityValue.IsValid() && !EntityValue->IsNull()) { Entity = MakeShareable(new FEntityKey(EntityValue->AsObject())); } const TSharedPtr<FJsonValue> ExpectedVersionValue = obj->TryGetField(TEXT("ExpectedVersion")); if (ExpectedVersionValue.IsValid() && !ExpectedVersionValue->IsNull()) { int32 TmpValue; if (ExpectedVersionValue->TryGetNumber(TmpValue)) { ExpectedVersion = TmpValue; } } const TSharedPtr<FJsonValue> LanguageValue = obj->TryGetField(TEXT("Language")); if (LanguageValue.IsValid() && !LanguageValue->IsNull()) { FString TmpValue; if (LanguageValue->TryGetString(TmpValue)) { Language = TmpValue; } } return HasSucceeded; } PlayFab::ProfilesModels::FSetProfileLanguageResponse::~FSetProfileLanguageResponse() { } void PlayFab::ProfilesModels::FSetProfileLanguageResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (OperationResult.notNull()) { writer->WriteIdentifierPrefix(TEXT("OperationResult")); writeOperationTypesEnumJSON(OperationResult, writer); } if (VersionNumber.notNull()) { writer->WriteIdentifierPrefix(TEXT("VersionNumber")); writer->WriteValue(VersionNumber); } writer->WriteObjectEnd(); } bool PlayFab::ProfilesModels::FSetProfileLanguageResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; OperationResult = readOperationTypesFromValue(obj->TryGetField(TEXT("OperationResult"))); const TSharedPtr<FJsonValue> VersionNumberValue = obj->TryGetField(TEXT("VersionNumber")); if (VersionNumberValue.IsValid() && !VersionNumberValue->IsNull()) { int32 TmpValue; if (VersionNumberValue->TryGetNumber(TmpValue)) { VersionNumber = TmpValue; } } return HasSucceeded; }
412
0.898728
1
0.898728
game-dev
MEDIA
0.814238
game-dev
0.91443
1
0.91443
leanprover-community/mathlib3
8,572
src/order/game_add.lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import data.sym.sym2 import logic.relation /-! # Game addition relation > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines, given relations `rα : α → α → Prop` and `rβ : β → β → Prop`, a relation `prod.game_add` on pairs, such that `game_add rα rβ x y` iff `x` can be reached from `y` by decreasing either entry (with respect to `rα` and `rβ`). It is so called since it models the subsequency relation on the addition of combinatorial games. We also define `sym2.game_add`, which is the unordered pair analog of `prod.game_add`. ## Main definitions and results - `prod.game_add`: the game addition relation on ordered pairs. - `well_founded.prod_game_add`: formalizes induction on ordered pairs, where exactly one entry decreases at a time. - `sym2.game_add`: the game addition relation on unordered pairs. - `well_founded.sym2_game_add`: formalizes induction on unordered pairs, where exactly one entry decreases at a time. -/ variables {α β : Type*} {rα : α → α → Prop} {rβ : β → β → Prop} /-! ### `prod.game_add` -/ namespace prod variables (rα rβ) /-- `prod.game_add rα rβ x y` means that `x` can be reached from `y` by decreasing either entry with respect to the relations `rα` and `rβ`. It is so called, as it models game addition within combinatorial game theory. If `rα a₁ a₂` means that `a₂ ⟶ a₁` is a valid move in game `α`, and `rβ b₁ b₂` means that `b₂ ⟶ b₁` is a valid move in game `β`, then `game_add rα rβ` specifies the valid moves in the juxtaposition of `α` and `β`: the player is free to choose one of the games and make a move in it, while leaving the other game unchanged. See `sym2.game_add` for the unordered pair analog. -/ inductive game_add : α × β → α × β → Prop | fst {a₁ a₂ b} : rα a₁ a₂ → game_add (a₁, b) (a₂, b) | snd {a b₁ b₂} : rβ b₁ b₂ → game_add (a, b₁) (a, b₂) lemma game_add_iff {rα rβ} {x y : α × β} : game_add rα rβ x y ↔ rα x.1 y.1 ∧ x.2 = y.2 ∨ rβ x.2 y.2 ∧ x.1 = y.1 := begin split, { rintro (@⟨a₁, a₂, b, h⟩ | @⟨a, b₁, b₂, h⟩), exacts [or.inl ⟨h, rfl⟩, or.inr ⟨h, rfl⟩] }, { revert x y, rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨h, rfl : b₁ = b₂⟩ | ⟨h, rfl : a₁ = a₂⟩), exacts [game_add.fst h, game_add.snd h] } end lemma game_add_mk_iff {rα rβ} {a₁ a₂ : α} {b₁ b₂ : β} : game_add rα rβ (a₁, b₁) (a₂, b₂) ↔ rα a₁ a₂ ∧ b₁ = b₂ ∨ rβ b₁ b₂ ∧ a₁ = a₂ := game_add_iff @[simp] lemma game_add_swap_swap : ∀ a b : α × β, game_add rβ rα a.swap b.swap ↔ game_add rα rβ a b := λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, by rw [prod.swap, game_add_mk_iff, game_add_mk_iff, or_comm] lemma game_add_swap_swap_mk (a₁ a₂ : α) (b₁ b₂ : β) : game_add rα rβ (a₁, b₁) (a₂, b₂) ↔ game_add rβ rα (b₁, a₁) (b₂, a₂) := game_add_swap_swap rβ rα (b₁, a₁) (b₂, a₂) /-- `prod.game_add` is a `subrelation` of `prod.lex`. -/ lemma game_add_le_lex : game_add rα rβ ≤ prod.lex rα rβ := λ _ _ h, h.rec (λ _ _ b, prod.lex.left b b) (λ a _ _, prod.lex.right a) /-- `prod.rprod` is a subrelation of the transitive closure of `prod.game_add`. -/ lemma rprod_le_trans_gen_game_add : rprod rα rβ ≤ relation.trans_gen (game_add rα rβ) := λ _ _ h, h.rec begin intros _ _ _ _ hα hβ, exact relation.trans_gen.tail (relation.trans_gen.single $ game_add.fst hα) (game_add.snd hβ), end end prod /-- If `a` is accessible under `rα` and `b` is accessible under `rβ`, then `(a, b)` is accessible under `prod.game_add rα rβ`. Notice that `prod.lex_accessible` requires the stronger condition `∀ b, acc rβ b`. -/ lemma acc.prod_game_add {a b} (ha : acc rα a) (hb : acc rβ b) : acc (prod.game_add rα rβ) (a, b) := begin induction ha with a ha iha generalizing b, induction hb with b hb ihb, refine acc.intro _ (λ h, _), rintro (⟨ra⟩ | ⟨rb⟩), exacts [iha _ ra (acc.intro b hb), ihb _ rb], end /-- The `prod.game_add` relation on well-founded inputs is well-founded. In particular, the sum of two well-founded games is well-founded. -/ lemma well_founded.prod_game_add (hα : well_founded rα) (hβ : well_founded rβ) : well_founded (prod.game_add rα rβ) := ⟨λ ⟨a, b⟩, (hα.apply a).prod_game_add (hβ.apply b)⟩ namespace prod /-- Recursion on the well-founded `prod.game_add` relation. Note that it's strictly more general to recurse on the lexicographic order instead. -/ def game_add.fix {C : α → β → Sort*} (hα : well_founded rα) (hβ : well_founded rβ) (IH : Π a₁ b₁, (Π a₂ b₂, game_add rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a : α) (b : β) : C a b := @well_founded.fix (α × β) (λ x, C x.1 x.2) _ (hα.prod_game_add hβ) (λ ⟨x₁, x₂⟩ IH', IH x₁ x₂ $ λ a' b', IH' ⟨a', b'⟩) ⟨a, b⟩ lemma game_add.fix_eq {C : α → β → Sort*} (hα : well_founded rα) (hβ : well_founded rβ) (IH : Π a₁ b₁, (Π a₂ b₂, game_add rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a : α) (b : β) : game_add.fix hα hβ IH a b = IH a b (λ a' b' h, game_add.fix hα hβ IH a' b') := well_founded.fix_eq _ _ _ /-- Induction on the well-founded `prod.game_add` relation. Note that it's strictly more general to induct on the lexicographic order instead. -/ lemma game_add.induction {C : α → β → Prop} : well_founded rα → well_founded rβ → (∀ a₁ b₁, (∀ a₂ b₂, game_add rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) → ∀ a b, C a b := game_add.fix end prod /-! ### `sym2.game_add` -/ namespace sym2 /-- `sym2.game_add rα x y` means that `x` can be reached from `y` by decreasing either entry with respect to the relation `rα`. See `prod.game_add` for the ordered pair analog. -/ def game_add (rα : α → α → Prop): sym2 α → sym2 α → Prop := sym2.lift₂ ⟨λ a₁ b₁ a₂ b₂, prod.game_add rα rα (a₁, b₁) (a₂, b₂) ∨ prod.game_add rα rα (b₁, a₁) (a₂, b₂), λ a₁ b₁ a₂ b₂, begin rw [prod.game_add_swap_swap_mk _ _ b₁ b₂ a₁ a₂, prod.game_add_swap_swap_mk _ _ a₁ b₂ b₁ a₂], simp [or_comm] end⟩ variable {rα} lemma game_add_iff : ∀ {x y : α × α}, game_add rα ⟦x⟧ ⟦y⟧ ↔ prod.game_add rα rα x y ∨ prod.game_add rα rα x.swap y := by { rintros ⟨_, _⟩ ⟨_, _⟩, refl } lemma game_add_mk_iff {a₁ a₂ b₁ b₂ : α} : game_add rα ⟦(a₁, b₁)⟧ ⟦(a₂, b₂)⟧ ↔ prod.game_add rα rα (a₁, b₁) (a₂, b₂) ∨ prod.game_add rα rα (b₁, a₁) (a₂, b₂) := iff.rfl lemma _root_.prod.game_add.to_sym2 {a₁ a₂ b₁ b₂ : α} (h : prod.game_add rα rα (a₁, b₁) (a₂, b₂)) : sym2.game_add rα ⟦(a₁, b₁)⟧ ⟦(a₂, b₂)⟧ := game_add_mk_iff.2 $ or.inl $ h lemma game_add.fst {a₁ a₂ b : α} (h : rα a₁ a₂) : game_add rα ⟦(a₁, b)⟧ ⟦(a₂, b)⟧ := (prod.game_add.fst h).to_sym2 lemma game_add.snd {a b₁ b₂ : α} (h : rα b₁ b₂) : game_add rα ⟦(a, b₁)⟧ ⟦(a, b₂)⟧ := (prod.game_add.snd h).to_sym2 lemma game_add.fst_snd {a₁ a₂ b : α} (h : rα a₁ a₂) : game_add rα ⟦(a₁, b)⟧ ⟦(b, a₂)⟧ := by { rw sym2.eq_swap, exact game_add.snd h } lemma game_add.snd_fst {a₁ a₂ b : α} (h : rα a₁ a₂) : game_add rα ⟦(b, a₁)⟧ ⟦(a₂, b)⟧ := by { rw sym2.eq_swap, exact game_add.fst h } end sym2 lemma acc.sym2_game_add {a b} (ha : acc rα a) (hb : acc rα b) : acc (sym2.game_add rα) ⟦(a, b)⟧ := begin induction ha with a ha iha generalizing b, induction hb with b hb ihb, refine acc.intro _ (λ s, _), induction s using sym2.induction_on with c d, rintros ((rc | rd) | (rd | rc)), { exact iha c rc ⟨b, hb⟩ }, { exact ihb d rd }, { rw sym2.eq_swap, exact iha d rd ⟨b, hb⟩ }, { rw sym2.eq_swap, exact ihb c rc } end /-- The `sym2.game_add` relation on well-founded inputs is well-founded. -/ lemma well_founded.sym2_game_add (h : well_founded rα) : well_founded (sym2.game_add rα) := ⟨λ i, sym2.induction_on i $ λ x y, (h.apply x).sym2_game_add (h.apply y)⟩ namespace sym2 /-- Recursion on the well-founded `sym2.game_add` relation. -/ def game_add.fix {C : α → α → Sort*} (hr : well_founded rα) (IH : Π a₁ b₁, (Π a₂ b₂, sym2.game_add rα ⟦(a₂, b₂)⟧ ⟦(a₁, b₁)⟧ → C a₂ b₂) → C a₁ b₁) (a b : α) : C a b := @well_founded.fix (α × α) (λ x, C x.1 x.2) _ hr.sym2_game_add.of_quotient_lift₂ (λ ⟨x₁, x₂⟩ IH', IH x₁ x₂ $ λ a' b', IH' ⟨a', b'⟩) (a, b) lemma game_add.fix_eq {C : α → α → Sort*} (hr : well_founded rα) (IH : Π a₁ b₁, (Π a₂ b₂, sym2.game_add rα ⟦(a₂, b₂)⟧ ⟦(a₁, b₁)⟧ → C a₂ b₂) → C a₁ b₁) (a b : α) : game_add.fix hr IH a b = IH a b (λ a' b' h, game_add.fix hr IH a' b') := well_founded.fix_eq _ _ _ /-- Induction on the well-founded `sym2.game_add` relation. -/ lemma game_add.induction {C : α → α → Prop} : well_founded rα → (∀ a₁ b₁, (∀ a₂ b₂, sym2.game_add rα ⟦(a₂, b₂)⟧ ⟦(a₁, b₁)⟧ → C a₂ b₂) → C a₁ b₁) → ∀ a b, C a b := game_add.fix end sym2
412
0.51174
1
0.51174
game-dev
MEDIA
0.544755
game-dev
0.759601
1
0.759601
mono/gtk-sharp
11,446
generator/Signal.cs
// GtkSharp.Generation.Signal.cs - The Signal Generatable. // // Author: Mike Kestner <mkestner@speakeasy.net> // // Copyright (c) 2001-2003 Mike Kestner // Copyright (c) 2003-2005 Novell, Inc. // Copyright (c) 2007 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // 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. namespace GtkSharp.Generation { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; public class Signal { bool marshaled; string name; XmlElement elem; ReturnValue retval; Parameters parms; ObjectBase container_type; public Signal (XmlElement elem, ObjectBase container_type) { this.elem = elem; name = elem.GetAttribute ("name"); marshaled = elem.GetAttribute ("manual") == "true"; retval = new ReturnValue (elem ["return-type"]); parms = new Parameters (elem["parameters"], container_type.ParserVersion == 1 ? true : false); this.container_type = container_type; } bool Marshaled { get { return marshaled; } } public string Name { get { return name; } set { name = value; } } public bool Validate (LogWriter log) { log.Member = Name; if (Name == "") { log.Warn ("Nameless signal found. Add name attribute with fixup."); Statistics.ThrottledCount++; return false; } else if (!parms.Validate (log) || !retval.Validate (log)) { Statistics.ThrottledCount++; return false; } return true; } public void GenerateDecl (StreamWriter sw) { if (elem.GetAttributeAsBoolean ("new_flag") || (container_type != null && container_type.GetSignalRecursively (Name) != null)) sw.Write("new "); sw.WriteLine ("\t\tevent " + EventHandlerQualifiedName + " " + Name + ";"); } public string CName { get { return "\"" + elem.GetAttribute("cname") + "\""; } } string CallbackSig { get { string result = ""; for (int i = 0; i < parms.Count; i++) { if (i > 0) result += ", "; Parameter p = parms [i]; if (p.PassAs != "" && !(p.Generatable is StructBase)) result += p.PassAs + " "; result += (p.MarshalType + " arg" + i); } return result; } } string CallbackName { get { return Name + "SignalCallback"; } } string DelegateName { get { return Name + "SignalDelegate"; } } private string EventArgsName { get { if (IsEventHandler) return "EventArgs"; else return Name + "Args"; } } private string EventArgsQualifiedName { get { if (IsEventHandler) return "System.EventArgs"; else return container_type.NS + "." + Name + "Args"; } } private string EventHandlerName { get { if (IsEventHandler) return "EventHandler"; else if (SymbolTable.Table [container_type.NS + Name + "Handler"] != null) return Name + "EventHandler"; else return Name + "Handler"; } } private string EventHandlerQualifiedName { get { if (IsEventHandler) return "System.EventHandler"; else return container_type.NS + "." + EventHandlerName; } } private bool IsEventHandler { get { return retval.CSType == "void" && parms.Count == 0; } } private string GenArgsInitialization (StreamWriter sw, IList<Parameter> dispose_params) { if (parms.Count > 0) sw.WriteLine("\t\t\t\targs.Args = new object[" + parms.Count + "];"); string finish = ""; for (int idx = 0; idx < parms.Count; idx++) { Parameter p = parms [idx]; IGeneratable igen = p.Generatable; if (p.PassAs != "out") { if (igen is ManualGen) { sw.WriteLine("\t\t\t\tif (arg{0} == IntPtr.Zero)", idx); sw.WriteLine("\t\t\t\t\targs.Args[{0}] = null;", idx); sw.WriteLine("\t\t\t\telse {"); sw.WriteLine("\t\t\t\t\targs.Args[" + idx + "] = " + p.FromNative ("arg" + idx) + ";"); sw.WriteLine("\t\t\t\t}"); } else if (dispose_params.Contains (p)) { sw.WriteLine("\t\t\t\t" + p.Name + " = " + p.FromNative ("arg" + idx) + ";"); sw.WriteLine("\t\t\t\targs.Args[" + idx + "] = " + p.Name + ";"); } else { sw.WriteLine("\t\t\t\targs.Args[" + idx + "] = " + p.FromNative ("arg" + idx) + ";"); } } if ((igen is StructBase || igen is ByRefGen) && p.PassAs != "") finish += "\t\t\t\tif (arg" + idx + " != IntPtr.Zero) System.Runtime.InteropServices.Marshal.StructureToPtr (args.Args[" + idx + "], arg" + idx + ", false);\n"; else if (igen is IManualMarshaler && p.PassAs != "") finish += String.Format ("\t\t\t\targ{0} = {1};\n", idx, (igen as IManualMarshaler).AllocNative ("args.Args[" + idx + "]")); else if (p.PassAs != "") finish += "\t\t\t\targ" + idx + " = " + igen.CallByName ("((" + p.CSType + ")args.Args[" + idx + "])") + ";\n"; } return finish; } private void GenArgsCleanup (StreamWriter sw, string finish) { if (retval.IsVoid && finish.Length == 0) return; sw.WriteLine("\n\t\t\ttry {"); sw.Write (finish); if (!retval.IsVoid) { if (retval.CSType == "bool") { sw.WriteLine ("\t\t\t\tif (args.RetVal == null)"); sw.WriteLine ("\t\t\t\t\treturn false;"); } sw.WriteLine ("\t\t\t\treturn {0};", retval.ToNative (String.Format ("(({0}) args.RetVal)", retval.CSType))); } sw.WriteLine("\t\t\t} catch (Exception) {"); sw.WriteLine ("\t\t\t\tException ex = new Exception (\"args.RetVal or 'out' property unset or set to incorrect type in " + EventHandlerQualifiedName + " callback\");"); sw.WriteLine("\t\t\t\tGLib.ExceptionManager.RaiseUnhandledException (ex, true);"); sw.WriteLine ("\t\t\t\t// NOTREACHED: above call doesn't return."); sw.WriteLine ("\t\t\t\tthrow ex;"); sw.WriteLine("\t\t\t}"); } public void GenCallback (StreamWriter sw) { if (IsEventHandler) return; IList<Parameter> dispose_params = new List<Parameter> (); foreach (Parameter p in parms) { if (p.IsOwnable) { dispose_params.Add (p); } } string native_signature = "IntPtr inst"; if (parms.Count > 0) native_signature += ", " + CallbackSig; native_signature += ", IntPtr gch"; sw.WriteLine ("\t\t[UnmanagedFunctionPointer (CallingConvention.Cdecl)]"); sw.WriteLine ("\t\tdelegate {0} {1} ({2});", retval.ToNativeType, DelegateName, native_signature); sw.WriteLine (); sw.WriteLine ("\t\tstatic {0} {1} ({2})", retval.ToNativeType, CallbackName, native_signature); sw.WriteLine("\t\t{"); sw.WriteLine("\t\t\t{0} args = new {0} ();", EventArgsQualifiedName); foreach (Parameter p in dispose_params) { sw.WriteLine("\t\t\t{0} {1} = null;", p.CSType, p.Name); } sw.WriteLine("\t\t\ttry {"); sw.WriteLine("\t\t\t\tGLib.Signal sig = ((GCHandle) gch).Target as GLib.Signal;"); sw.WriteLine("\t\t\t\tif (sig == null)"); sw.WriteLine("\t\t\t\t\tthrow new Exception(\"Unknown signal GC handle received \" + gch);"); sw.WriteLine(); string finish = GenArgsInitialization (sw, dispose_params); sw.WriteLine("\t\t\t\t{0} handler = ({0}) sig.Handler;", EventHandlerQualifiedName); sw.WriteLine("\t\t\t\thandler (GLib.Object.GetObject (inst), args);"); sw.WriteLine("\t\t\t} catch (Exception e) {"); sw.WriteLine("\t\t\t\tGLib.ExceptionManager.RaiseUnhandledException (e, false);"); if (dispose_params.Count > 0) { sw.WriteLine ("\t\t\t} finally {"); foreach (Parameter p in dispose_params) { string disp_name = "disposable_" + p.Name; sw.WriteLine ("\t\t\t\tvar " + disp_name + " = " + p.Name + " as IDisposable;"); sw.WriteLine ("\t\t\t\tif (" + disp_name + " != null)"); sw.WriteLine ("\t\t\t\t\t" + disp_name + ".Dispose ();"); } } sw.WriteLine ("\t\t\t}"); GenArgsCleanup (sw, finish); sw.WriteLine("\t\t}"); sw.WriteLine(); } private bool NeedNew (ObjectBase implementor) { return elem.GetAttributeAsBoolean ("new_flag") || (container_type != null && container_type.GetSignalRecursively (Name) != null) || (implementor != null && implementor.GetSignalRecursively (Name) != null); } public void GenEventHandler (GenerationInfo gen_info) { if (IsEventHandler) return; string ns = container_type.NS; StreamWriter sw = gen_info.OpenStream (EventHandlerName, container_type.NS); sw.WriteLine ("namespace " + ns + " {"); sw.WriteLine (); sw.WriteLine ("\tusing System;"); sw.WriteLine (); sw.WriteLine ("\tpublic delegate void " + EventHandlerName + "(object o, " + EventArgsName + " args);"); sw.WriteLine (); sw.WriteLine ("\tpublic class " + EventArgsName + " : GLib.SignalArgs {"); for (int i = 0; i < parms.Count; i++) { sw.WriteLine ("\t\tpublic " + parms[i].CSType + " " + parms[i].StudlyName + "{"); if (parms[i].PassAs != "out") { sw.WriteLine ("\t\t\tget {"); if (SymbolTable.Table.IsInterface (parms [i].CType)) { var igen = SymbolTable.Table.GetInterfaceGen (parms [i].CType); sw.WriteLine ("\t\t\t\treturn {0}.GetObject (Args [{1}] as GLib.Object);", igen.QualifiedAdapterName, i); } else { sw.WriteLine ("\t\t\t\treturn ({0}) Args [{1}];", parms [i].CSType, i); } sw.WriteLine ("\t\t\t}"); } if (parms[i].PassAs != "") { sw.WriteLine ("\t\t\tset {"); if (SymbolTable.Table.IsInterface (parms [i].CType)) { var igen = SymbolTable.Table.GetInterfaceGen (parms [i].CType); sw.WriteLine ("\t\t\t\tArgs [{0}] = value is {1} ? (value as {1}).Implementor : value;", i, igen.AdapterName); } else { sw.WriteLine ("\t\t\t\tArgs[" + i + "] = (" + parms [i].CSType + ")value;"); } sw.WriteLine ("\t\t\t}"); } sw.WriteLine ("\t\t}"); sw.WriteLine (); } sw.WriteLine ("\t}"); sw.WriteLine ("}"); sw.Close (); } public void GenEvent (StreamWriter sw, ObjectBase implementor, string target) { string args_type = IsEventHandler ? "" : ", typeof (" + EventArgsQualifiedName + ")"; if (Marshaled) { GenCallback (sw); args_type = ", new " + DelegateName + "(" + CallbackName + ")"; } sw.WriteLine("\t\t[GLib.Signal("+ CName + ")]"); sw.Write("\t\tpublic "); if (NeedNew (implementor)) sw.Write("new "); sw.WriteLine("event " + EventHandlerQualifiedName + " " + Name + " {"); sw.WriteLine("\t\t\tadd {"); sw.WriteLine("\t\t\t\t{0}.AddSignalHandler ({1}, value{2});", target, CName, args_type); sw.WriteLine("\t\t\t}"); sw.WriteLine("\t\t\tremove {"); sw.WriteLine("\t\t\t\t{0}.RemoveSignalHandler ({1}, value);", target, CName); sw.WriteLine("\t\t\t}"); sw.WriteLine("\t\t}"); sw.WriteLine(); } public void Generate (GenerationInfo gen_info, ObjectBase implementor) { StreamWriter sw = gen_info.Writer; if (implementor == null) GenEventHandler (gen_info); GenEvent (sw, implementor, "this"); Statistics.SignalCount++; } } }
412
0.935141
1
0.935141
game-dev
MEDIA
0.21244
game-dev
0.978335
1
0.978335
FlowShield/flowshield
5,154
ca/pkg/memorycacher/sharded.go
/* * @Author: patrickmn,gitsrc * @Date: 2020-07-09 13:17:30 * @LastEditors: gitsrc * @LastEditTime: 2020-07-09 13:22:41 * @FilePath: /ServiceCar/utils/memorycache/sharded.go */ package memorycacher import ( "crypto/rand" "math" "math/big" insecurerand "math/rand" "os" "runtime" "time" ) // This is an experimental and unexported (for now) attempt at making a cache // with better algorithmic complexity than the standard one, namely by // preventing write locks of the entire cache when an item is added. As of the // time of writing, the overhead of selecting buckets results in cache // operations being about twice as slow as for the standard cache with small // total cache sizes, and faster for larger ones. // // See cache_test.go for a few benchmarks. type unexportedShardedCache struct { *shardedCache } type shardedCache struct { seed uint32 m uint32 cs []*cache lastCleanTime time.Time //Last cleanup time janitor *shardedJanitor } // djb2 with better shuffling. 5x faster than FNV with the hash.Hash overhead. func djb33(seed uint32, k string) uint32 { var ( l = uint32(len(k)) d = 5381 + seed + l i = uint32(0) ) // Why is all this 5x faster than a for loop? if l >= 4 { for i < l-4 { d = (d * 33) ^ uint32(k[i]) d = (d * 33) ^ uint32(k[i+1]) d = (d * 33) ^ uint32(k[i+2]) d = (d * 33) ^ uint32(k[i+3]) i += 4 } } switch l - i { case 1: case 2: d = (d * 33) ^ uint32(k[i]) case 3: d = (d * 33) ^ uint32(k[i]) d = (d * 33) ^ uint32(k[i+1]) case 4: d = (d * 33) ^ uint32(k[i]) d = (d * 33) ^ uint32(k[i+1]) d = (d * 33) ^ uint32(k[i+2]) } return d ^ (d >> 16) } func (sc *shardedCache) bucket(k string) *cache { return sc.cs[djb33(sc.seed, k)%sc.m] } func (sc *shardedCache) Set(k string, x interface{}, d time.Duration) { sc.bucket(k).Set(k, x, d) } func (sc *shardedCache) Add(k string, x interface{}, d time.Duration) error { return sc.bucket(k).Add(k, x, d) } func (sc *shardedCache) Replace(k string, x interface{}, d time.Duration) error { return sc.bucket(k).Replace(k, x, d) } func (sc *shardedCache) Get(k string) (interface{}, bool) { return sc.bucket(k).Get(k) } func (sc *shardedCache) Increment(k string, n int64) error { return sc.bucket(k).Increment(k, n) } func (sc *shardedCache) IncrementFloat(k string, n float64) error { return sc.bucket(k).IncrementFloat(k, n) } func (sc *shardedCache) Decrement(k string, n int64) error { return sc.bucket(k).Decrement(k, n) } func (sc *shardedCache) Delete(k string) { sc.bucket(k).Delete(k) } func (sc *shardedCache) DeleteExpired() { for _, v := range sc.cs { v.DeleteExpired() } } // Returns the items in the cache. This may include items that have expired, // but have not yet been cleaned up. If this is significant, the Expiration // fields of the items should be checked. Note that explicit synchronization // is needed to use a cache and its corresponding Items() return values at // the same time, as the maps are shared. func (sc *shardedCache) Items() []map[string]Item { res := make([]map[string]Item, len(sc.cs)) for i, v := range sc.cs { res[i] = v.Items() } return res } func (sc *shardedCache) Flush() { for _, v := range sc.cs { v.Flush() } } type shardedJanitor struct { Interval time.Duration shoudClean chan bool //Signal should be cleaned up stop chan bool } func (j *shardedJanitor) Run(sc *shardedCache) { j.stop = make(chan bool) tick := time.Tick(j.Interval) for { select { case <-tick: sc.DeleteExpired() case <-j.shoudClean: //If received should Clean signal sc.DeleteExpired() case <-j.stop: return } } } func stopShardedJanitor(sc *unexportedShardedCache) { sc.janitor.stop <- true } func runShardedJanitor(sc *shardedCache, ci time.Duration) { j := &shardedJanitor{ Interval: ci, shoudClean: make(chan bool), } sc.janitor = j go j.Run(sc) } func newShardedCache(n int, de time.Duration, maxItemsCount int) *shardedCache { max := big.NewInt(0).SetUint64(uint64(math.MaxUint32)) rnd, err := rand.Int(rand.Reader, max) var seed uint32 if err != nil { os.Stderr.Write([]byte("WARNING: go-cache's newShardedCache failed to read from the system CSPRNG (/dev/urandom or equivalent.) Your system's security may be compromised. Continuing with an insecure seed.\n")) seed = insecurerand.Uint32() } else { seed = uint32(rnd.Uint64()) } sc := &shardedCache{ seed: seed, m: uint32(n), cs: make([]*cache, n), } for i := 0; i < n; i++ { c := &cache{ defaultExpiration: de, items: map[string]Item{}, maxItemsCount: maxItemsCount, lastCleanTime: time.Now(), } sc.cs[i] = c } return sc } func unexportedNewSharded(defaultExpiration, cleanupInterval time.Duration, shards int, maxItemsCount int) *unexportedShardedCache { if defaultExpiration == 0 { defaultExpiration = -1 } sc := newShardedCache(shards, defaultExpiration, maxItemsCount) SC := &unexportedShardedCache{sc} if cleanupInterval > 0 { runShardedJanitor(sc, cleanupInterval) runtime.SetFinalizer(SC, stopShardedJanitor) } return SC }
412
0.85868
1
0.85868
game-dev
MEDIA
0.146745
game-dev
0.918587
1
0.918587
swgemu/Core3
2,577
MMOCoreORB/src/server/zone/objects/creature/commands/NameStructureCommand.h
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #ifndef NAMESTRUCTURECOMMAND_H_ #define NAMESTRUCTURECOMMAND_H_ #include "server/zone/objects/scene/SceneObject.h" class NameStructureCommand : public QueueCommand { public: NameStructureCommand(const String& name, ZoneProcessServer* server) : QueueCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const { if (!checkStateMask(creature)) return INVALIDSTATE; if (!checkInvalidLocomotions(creature)) return INVALIDLOCOMOTION; /*creature->sendSystemMessage("Temporarily disabled while being worked on."); return GENERALERROR;*/ ManagedReference<PlayerManager*> playerManager = server->getPlayerManager(); uint64 targetid = creature->getTargetID(); ManagedReference<SceneObject*> obj = playerManager->getInRangeStructureWithAdminRights(creature, targetid); if (obj == nullptr || !obj->isStructureObject()) { creature->sendSystemMessage("@player_structure:command_no_building"); //You must be in a building or near an installation to use that command. return INVALIDTARGET; } StructureObject* structure = cast<StructureObject*>(obj.get()); Locker _lock(structure, creature); if (!structure->isOwnerOf(creature)) { creature->sendSystemMessage("@player_structure:rename_must_be_owner"); //You must be the owner to rename a structure. return GENERALERROR; } if (structure->isGCWBase()) { creature->sendSystemMessage("@player_structure:no_rename_hq"); //You may not rename a factional headquarters. return INVALIDTARGET; } if (structure->isTurret() || structure->isMinefield()) { return INVALIDTARGET; } //Validate the name. NameManager* nameManager = server->getNameManager(); String name = arguments.toString(); if (name.isEmpty() || nameManager->isProfane(name) || name.length() > 128) { creature->sendSystemMessage("@player_structure:obscene"); //That name was rejected by the name filter. Try a different name. return INVALIDPARAMETERS; } structure->setCustomObjectName(name, true); if (structure->isBuildingObject() && (cast<BuildingObject*>(structure))->getSignObject() != nullptr) { StringIdChatParameter params("@player_structure:prose_sign_name_updated"); //Sign name successfully updated to '%TO'. params.setTO(name); creature->sendSystemMessage(params); } creature->sendSystemMessage("@player_structure:structure_renamed"); //Structure renamed. return SUCCESS; } }; #endif //NAMESTRUCTURECOMMAND_H_
412
0.908995
1
0.908995
game-dev
MEDIA
0.848605
game-dev
0.881352
1
0.881352
stride3d/stride
5,934
sources/engine/Stride.Input/Gestures/GestureRecognizer.cs
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Stride.Core.Collections; using Stride.Core.Mathematics; namespace Stride.Input { internal abstract class GestureRecognizer { private static readonly ThreadLocal<List<int>> FingerIdsCache = new ThreadLocal<List<int>>(() => new List<int>()); protected readonly Dictionary<int, Vector2> FingerIdToBeginPositions = new Dictionary<int, Vector2>(); protected readonly Dictionary<int, Vector2> FingerIdsToLastPos = new Dictionary<int, Vector2>(); protected PoolListStruct<GestureEvent> CurrentGestureEvents; protected TimeSpan ElapsedSinceBeginning; protected TimeSpan ElapsedSinceLast; // avoid reallocation of the dictionary at each update call private readonly Dictionary<int, Vector2> fingerIdsToLastMovePos = new Dictionary<int, Vector2>(); private bool hasGestureStarted; protected GestureRecognizer(GestureConfig config, float screenRatio) { CurrentGestureEvents = new PoolListStruct<GestureEvent>(8, NewEventFactory); Config = config; ScreenRatio = screenRatio; } internal float ScreenRatio { get; set; } protected virtual GestureConfig Config { get; } protected bool HasGestureStarted { get { return hasGestureStarted; } set { if (value && !hasGestureStarted) { ElapsedSinceBeginning = TimeSpan.Zero; ElapsedSinceLast = TimeSpan.Zero; } hasGestureStarted = value; } } protected virtual int NbOfFingerOnScreen => FingerIdsToLastPos.Count; public void ProcessPointerEvents(TimeSpan deltaTime, List<PointerEvent> events, List<GestureEvent> outputEvents) { ElapsedSinceBeginning += deltaTime; ElapsedSinceLast += deltaTime; CurrentGestureEvents.Clear(); ProcessPointerEventsImpl(deltaTime, events); for (int i = 0; i < CurrentGestureEvents.Count; i++) { outputEvents.Add(CurrentGestureEvents[i]); } } protected abstract GestureEvent NewEventFactory(); protected virtual void ProcessPointerEventsImpl(TimeSpan deltaTime, List<PointerEvent> events) { AnalysePointerEvents(events); } protected Vector2 ComputeMeanPosition(IEnumerable<Vector2> positions) { var count = 0; var accuPos = Vector2.Zero; foreach (var position in positions) { accuPos += position; ++count; } return accuPos / count; } protected void AnalysePointerEvents(List<PointerEvent> events) { foreach (var pointerEvent in events) { var eventType = pointerEvent.EventType; var id = pointerEvent.PointerId; var pos = pointerEvent.Position; switch (eventType) { case PointerEventType.Pressed: ProcessDownEventPointer(id, UnnormalizeVector(pos)); break; case PointerEventType.Moved: // just memorize the last position to avoid useless processing on move events if (FingerIdToBeginPositions.ContainsKey(id)) fingerIdsToLastMovePos[id] = pos; break; case PointerEventType.Released: case PointerEventType.Canceled: // process previous move events ProcessAndClearMovePointerEvents(); // process the up event ProcessUpEventPointer(id, UnnormalizeVector(pos)); break; default: throw new ArgumentOutOfRangeException(); } } // process move events not followed by an 'up' event ProcessAndClearMovePointerEvents(); } protected Vector2 NormalizeVector(Vector2 inputVector) { return ScreenRatio > 1 ? new Vector2(inputVector.X, inputVector.Y * ScreenRatio) : new Vector2(inputVector.X / ScreenRatio, inputVector.Y); } protected Vector2 UnnormalizeVector(Vector2 inputVector) { return ScreenRatio > 1 ? new Vector2(inputVector.X, inputVector.Y / ScreenRatio) : new Vector2(inputVector.X * ScreenRatio, inputVector.Y); } private void ProcessAndClearMovePointerEvents() { if (fingerIdsToLastMovePos.Count > 0) { FingerIdsCache.Value.Clear(); FingerIdsCache.Value.AddRange(fingerIdsToLastMovePos.Keys); // Unnormalizes vectors here before utilization foreach (var id in FingerIdsCache.Value) fingerIdsToLastMovePos[id] = UnnormalizeVector(fingerIdsToLastMovePos[id]); ProcessMoveEventPointers(fingerIdsToLastMovePos); fingerIdsToLastMovePos.Clear(); } } protected abstract void ProcessDownEventPointer(int id, Vector2 pos); protected abstract void ProcessMoveEventPointers(Dictionary<int, Vector2> fingerIdsToMovePos); protected abstract void ProcessUpEventPointer(int id, Vector2 pos); } }
412
0.960521
1
0.960521
game-dev
MEDIA
0.607309
game-dev
0.918018
1
0.918018
DeformedSAS/Counter-Strike2-Global-Offensive
6,545
scripts/common/characteranims_loadout_grid.js
'use strict'; var CharacterAnims = ( function() { function _AddModifiersFromWeaponItemId ( itemId, arrModifiers ) { var weaponName = ItemInfo.GetItemDefinitionName( itemId ); arrModifiers.push( weaponName ); var weaponType = InventoryAPI.GetWeaponTypeString( itemId ); arrModifiers.push( weaponType ); } function _NormalizeTeamName ( team, bShort = false ) { team = String(team).toLowerCase(); switch ( team ) { case '2': case 't': case 'terrorist': case 'team_t': return bShort? 't' : 'terrorist'; case '3': case 'ct': case 'counter-terrorist': case 'team_ct': return 'ct'; default: return ''; } } function _TeamForEquip ( team ) { team = team.toLowerCase(); switch ( team ) { case '2': case 't': case 'terrorist': case 'team_t': return 't'; case '3': case 'ct': case 'counter-terrorist': case 'team_ct': return 'ct'; default: return ''; } } var _PlayAnimsOnPanel = function ( importedSettings, bDontStompModel = false, makeDeepCopy = true ) { if ( importedSettings === null ) { return; } var settings = makeDeepCopy ? ItemInfo.DeepCopyVanityCharacterSettings( importedSettings ) : importedSettings; if ( !settings.team || settings.team == "" ) settings.team = 'ct'; settings.team = _NormalizeTeamName( settings.team ); if ( settings.modelOverride ) { settings.model = settings.modelOverride; } else { settings.model = ItemInfo.GetModelPlayer( settings.charItemId ); if ( !settings.model ) { if ( settings.team == 'ct' ) settings.model = "models/player/custom_player/legacy/ctm_sas.mdl"; else settings.model = "models/player/custom_player/legacy/tm_phoenix.mdl"; } } var wid = settings.weaponItemId; var playerPanel = settings.panel; _CancelScheduledAnim( playerPanel ); _ResetLastRandomAnimHandle( playerPanel ); playerPanel.ResetAnimation( true ); playerPanel.SetSceneAngles( 0, 0, 0, false ); if ( settings.manifest ) playerPanel.SetScene( settings.manifest, settings.model, false ); if ( !bDontStompModel ) { playerPanel.SetPlayerCharacterItemID( settings.charItemId ); playerPanel.SetPlayerModel( settings.model ); } playerPanel.EquipPlayerWithItem( wid ); playerPanel.EquipPlayerWithItem( settings.glovesItemId ); playerPanel.ResetActivityModifiers(); playerPanel.ApplyActivityModifier( settings.team ); if ( !( 'arrModifiers' in settings ) ) { settings.arrModifiers = []; } _AddModifiersFromWeaponItemId( wid, settings.arrModifiers ); settings.arrModifiers.forEach( mod => playerPanel.ApplyActivityModifier( mod ) ); if ( !('activity' in settings ) || settings.activity == "" ) { settings.activity = 'ACT_CSGO_UIPLAYER_BUYMENU'; } if ( !( 'immediate' in settings ) || settings.immediate == "" ) { settings.immediate = true; } playerPanel.PlayActivity( settings.activity, settings.immediate ); var cam = 1; if ( 'cameraPreset' in settings ) { cam = settings.cameraPreset; } playerPanel.SetCameraPreset( Number( cam ), false ); if ( 'flashlightAmount' in settings && settings.flashlightAmount !== '' ) { playerPanel.SetFlashlightAmount( settings.flashlightAmount ); } if ( 'flashlightColor' in settings && settings.flashlightColor !== '' ) { playerPanel.SetFlashlightColor( settings.flashlightColor[ 0 ], settings.flashlightColor[ 1 ], settings.flashlightColor[ 2 ] ); } if ( 'ambientLightColor' in settings && settings.ambientLightColor !== '' ) { playerPanel.SetAmbientLightColor( settings.ambientLightColor[ 0 ], settings.ambientLightColor[ 1 ], settings.ambientLightColor[ 2 ] ); } }; var _CancelScheduledAnim = function ( playerPanel ) { if ( playerPanel.Data().handle ) { $.CancelScheduled( playerPanel.Data().handle ); playerPanel.Data().handle = null; } }; var _ResetLastRandomAnimHandle = function ( playerPanel) { if ( playerPanel.Data().lastRandomAnim !== 0 ) { playerPanel.Data().lastRandomAnim = 0; } }; var _GetValidCharacterModels = function( bUniquePerTeamModelsOnly ) { InventoryAPI.SetInventorySortAndFilters ( 'inv_sort_rarity', false, 'customplayer', '', '' ); var count = InventoryAPI.GetInventoryCount(); var itemsList = []; var uniqueTracker = {}; for( var i = 0 ; i < count ; i++ ) { var itemId = InventoryAPI.GetInventoryItemIDByIndex( i ); var modelplayer = ItemInfo.GetModelPlayer( itemId ); if ( !modelplayer ) continue; var team = ( ItemInfo.GetTeam( itemId ).search( 'Team_T' ) === -1 ) ? 'ct' : 't'; if ( bUniquePerTeamModelsOnly ) { if ( uniqueTracker.hasOwnProperty( team + modelplayer ) ) continue; uniqueTracker[ team + modelplayer ] = 1; } var label = ItemInfo.GetName( itemId ); var entry = { label: label, team: team, itemId: itemId }; itemsList.push( entry ); } return itemsList; }; return { PlayAnimsOnPanel : _PlayAnimsOnPanel, CancelScheduledAnim : _CancelScheduledAnim, GetValidCharacterModels : _GetValidCharacterModels, NormalizeTeamName : _NormalizeTeamName }; })();
412
0.923048
1
0.923048
game-dev
MEDIA
0.715319
game-dev,web-frontend
0.992168
1
0.992168
gro-ove/actools
10,521
AcTools.Render/Base/Objects/MoveableHelper.cs
using System; using System.Collections.Generic; using AcTools.Render.Base.Cameras; using AcTools.Render.Base.Utils; using AcTools.Utils.Helpers; using JetBrains.Annotations; using SlimDX; namespace AcTools.Render.Base.Objects { public interface IMoveable { void Move(Vector3 delta); void Rotate(Quaternion delta); void Scale(Vector3 scale); [CanBeNull] IMoveable Clone(); } public interface IMousePositionProvider { Vector2 GetRelative(); } [Flags] public enum MoveableRotationAxis : uint { None = 0, X = 1, Y = 2, Z = 4, All = 7 } public class MoveableHelper : IRenderableObject { private DebugLinesObject _arrowX, _arrowY, _arrowZ; [CanBeNull] private DebugLinesObject _circleX, _circleY, _circleZ, _scale; private Vector3 _arrowHighlighted, _circleHighlighted; private bool _scaleHighlighted, _keepHighlight; private readonly IMoveable _parent; private readonly MoveableRotationAxis _rotationAxis; private readonly bool _allowScaling; private static bool _justCloned = true; public MoveableHelper(IMoveable parent, MoveableRotationAxis rotationAxis = MoveableRotationAxis.Y, bool allowScaling = false) { _parent = parent; _rotationAxis = rotationAxis; _allowScaling = allowScaling; } public bool MoveObject(Vector2 relativeFrom, Vector2 relativeDelta, CameraBase camera, bool tryToClone, [CanBeNull] out IMoveable cloned) { if (_keepHighlight) { tryToClone = false; } else { _keepHighlight = true; } if (_justCloned) { tryToClone = false; } cloned = null; if (_arrowHighlighted != default(Vector3)) { var plane = new Plane(ParentMatrix.GetTranslationVector(), -camera.Look); var rayFrom = camera.GetPickingRay(relativeFrom, new Vector2(1f, 1f)); var rayTo = camera.GetPickingRay(relativeFrom + relativeDelta, new Vector2(1f, 1f)); if (!Ray.Intersects(rayFrom, plane, out var distanceFrom) || !Ray.Intersects(rayTo, plane, out var distanceTo)) return false; var pointDelta = rayTo.Direction * distanceTo - rayFrom.Direction * distanceFrom; if (tryToClone) { cloned = _parent.Clone(); _justCloned = true; } var totalDistance = pointDelta.Length(); var resultMovement = new Vector3( pointDelta.X * _arrowHighlighted.X, pointDelta.Y * _arrowHighlighted.Y, pointDelta.Z * _arrowHighlighted.Z); resultMovement.Normalize(); resultMovement *= totalDistance; _parent.Move(resultMovement); UpdateBoundingBox(); return true; } if (_circleHighlighted != default(Vector3)) { var rotationAxis = _circleHighlighted.X * _circleHighlighted.Y * _circleHighlighted.Z != 0f ? camera.Look : _circleHighlighted; if (tryToClone) { cloned = _parent.Clone(); _justCloned = true; } _parent.Rotate(Quaternion.RotationAxis(rotationAxis, relativeDelta.X * 10f)); UpdateBoundingBox(); return true; } if (_scaleHighlighted) { var v = relativeDelta.X + relativeDelta.Y; _parent.Scale(new Vector3(v > 0f ? 1.01f : 1f / 1.01f)); UpdateBoundingBox(); return true; } return false; } public void StopMovement() { _keepHighlight = false; _justCloned = false; } public void Draw(IDeviceContextHolder holder, ICamera camera, SpecialRenderMode mode, Func<IRenderableObject, bool> filter = null) { const float arrowSize = 0.08f; const float circleSize = 0.06f; const float boxSize = 0.14f; if (_arrowX == null) { _arrowX = DebugLinesObject.GetLinesArrow(Matrix.Identity, Vector3.UnitX, new Color4(0f, 1f, 0f, 0f), arrowSize); _arrowY = DebugLinesObject.GetLinesArrow(Matrix.Identity, Vector3.UnitY, new Color4(0f, 0f, 1f, 0f), arrowSize); _arrowZ = DebugLinesObject.GetLinesArrow(Matrix.Identity, Vector3.UnitZ, new Color4(0f, 0f, 0f, 1f), arrowSize); if (_rotationAxis.HasFlag(MoveableRotationAxis.X)) { _circleX = DebugLinesObject.GetLinesCircle(Matrix.Identity, Vector3.UnitX, new Color4(0f, 1f, 0f, 0f), radius: circleSize); } if (_rotationAxis.HasFlag(MoveableRotationAxis.Y)) { _circleY = DebugLinesObject.GetLinesCircle(Matrix.Identity, Vector3.UnitY, new Color4(0f, 0f, 1f, 0f), radius: circleSize); } if (_rotationAxis.HasFlag(MoveableRotationAxis.Z)) { _circleZ = DebugLinesObject.GetLinesCircle(Matrix.Identity, Vector3.UnitZ, new Color4(0f, 0f, 0f, 1f), radius: circleSize); } if (_allowScaling) { _scale = DebugLinesObject.GetLinesBox(Matrix.Identity, new Vector3(boxSize), new Color4(0f, 1f, 1f, 0f)); } } var matrix = ParentMatrix.GetTranslationVector().ToFixedSizeMatrix(camera); if (_arrowX.ParentMatrix != matrix) { _arrowX.ParentMatrix = matrix; _arrowY.ParentMatrix = matrix; _arrowZ.ParentMatrix = matrix; _arrowX.UpdateBoundingBox(); _arrowY.UpdateBoundingBox(); _arrowZ.UpdateBoundingBox(); if (_circleX != null) { _circleX.ParentMatrix = matrix; _circleX.UpdateBoundingBox(); } if (_circleY != null) { _circleY.ParentMatrix = matrix; _circleY.UpdateBoundingBox(); } if (_circleZ != null) { _circleZ.ParentMatrix = matrix; _circleZ.UpdateBoundingBox(); } if (_scale != null) { _scale.ParentMatrix = matrix; _scale.UpdateBoundingBox(); } } if (_keepHighlight) { _arrowX.Draw(holder, camera, _arrowHighlighted.X == 0f ? SpecialRenderMode.Simple : SpecialRenderMode.Outline); _arrowY.Draw(holder, camera, _arrowHighlighted.Y == 0f ? SpecialRenderMode.Simple : SpecialRenderMode.Outline); _arrowZ.Draw(holder, camera, _arrowHighlighted.Z == 0f ? SpecialRenderMode.Simple : SpecialRenderMode.Outline); _circleX?.Draw(holder, camera, _circleHighlighted.X == 0f ? SpecialRenderMode.Simple : SpecialRenderMode.Outline); _circleY?.Draw(holder, camera, _circleHighlighted.Y == 0f ? SpecialRenderMode.Simple : SpecialRenderMode.Outline); _circleZ?.Draw(holder, camera, _circleHighlighted.Z == 0f ? SpecialRenderMode.Simple : SpecialRenderMode.Outline); _scale?.Draw(holder, camera, _scaleHighlighted ? SpecialRenderMode.Outline : SpecialRenderMode.Simple); } else { var mousePosition = holder.TryToGet<IMousePositionProvider>()?.GetRelative(); var rayN = mousePosition == null ? null : (camera as CameraBase)?.GetPickingRay(mousePosition.Value, new Vector2(1f, 1f)); if (!rayN.HasValue) return; var ray = rayN.Value; _arrowHighlighted = new Vector3( _arrowX.DrawHighlighted(ray, holder, camera) ? 1f : 0f, _arrowY.DrawHighlighted(ray, holder, camera) ? 1f : 0f, _arrowZ.DrawHighlighted(ray, holder, camera) ? 1f : 0f); if (_arrowHighlighted == Vector3.Zero) { _circleHighlighted = new Vector3( _circleX?.DrawHighlighted(ray, holder, camera) ?? false ? 1f : 0f, _circleY?.DrawHighlighted(ray, holder, camera) ?? false ? 1f : 0f, _circleZ?.DrawHighlighted(ray, holder, camera) ?? false ? 1f : 0f); } else { _circleHighlighted = Vector3.Zero; _circleX?.Draw(holder, camera, SpecialRenderMode.Simple); _circleY?.Draw(holder, camera, SpecialRenderMode.Simple); _circleZ?.Draw(holder, camera, SpecialRenderMode.Simple); } if (_arrowHighlighted == Vector3.Zero && _circleHighlighted == Vector3.Zero) { _scaleHighlighted = _scale?.DrawHighlighted(ray, holder, camera) ?? false; } else { _scaleHighlighted = false; _scale?.Draw(holder, camera, SpecialRenderMode.Simple); } } } public void Dispose() { DisposeHelper.Dispose(ref _arrowX); DisposeHelper.Dispose(ref _arrowY); DisposeHelper.Dispose(ref _arrowZ); DisposeHelper.Dispose(ref _circleX); DisposeHelper.Dispose(ref _circleY); DisposeHelper.Dispose(ref _circleZ); DisposeHelper.Dispose(ref _scale); } public string Name => "__movable"; public Matrix ParentMatrix { get; set; } public bool IsEnabled { get; set; } = true; public bool IsReflectable { get; set; } = false; public int GetTrianglesCount() { return 0; } public int GetObjectsCount() { return 0; } public IEnumerable<int> GetMaterialIds() { return new int[0]; } public BoundingBox? BoundingBox => default(BoundingBox); public void UpdateBoundingBox() { } public IRenderableObject Clone() { return new MoveableHelper(_parent, _rotationAxis, _allowScaling); } public float? CheckIntersection(Ray ray) { return null; } } }
412
0.953289
1
0.953289
game-dev
MEDIA
0.732859
game-dev,graphics-rendering
0.993994
1
0.993994
ProjectIgnis/CardScripts
1,143
goat/c504700094.lua
--弱体化の仮面 --Mask of Weakness (Goat) local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_CAL) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated() end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local tc=Duel.GetAttacker() if chkc then return chkc==tc end if chk==0 then return tc and tc:IsOnField() and tc:IsCanBeEffectTarget(e) end Duel.SetTargetCard(tc) end function s.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(-700) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end end
412
0.942919
1
0.942919
game-dev
MEDIA
0.98531
game-dev
0.910428
1
0.910428