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
shitake2333/IceKori
1,726
Assets/Plugins/IceKori/Syntax/Std/Math/Pow.cs
using System; using Assets.Plugins.IceKori.Common; using Assets.Plugins.IceKori.Syntax.BaseType; using Assets.Plugins.IceKori.Syntax.Error; using Assets.Plugins.IceKori.Syntax.Expression; using UnityEngine; namespace Assets.Plugins.IceKori.Syntax.Std.Math { [PageSlider, Serializable] public class Pow : BaseExpression { public BaseExpression Floor; public BaseExpression Power; public Pow(BaseExpression f, BaseExpression p) { Floor = f; Power = p; } public override BaseExpression Reduce(Enviroment env) { if (Floor.Reducible) return new Pow(Floor.Reduce(env), Power); if (Floor.ID == BaseError.Error) { return Floor; } if (Power.Reducible) return new Pow(Floor, Power.Reduce(env)); if (Power.ID == BaseError.Error) { return Power; } if (Floor.ID != IceKoriBaseType.Float && Floor.ID != IceKoriBaseType.Int) { return new TypeError($"Argument of type '{Floor}' is not assignable to parameter of type 'IceKoriFloat || IceKoriInt'."); } if (Power.ID != IceKoriBaseType.Float && Power.ID != IceKoriBaseType.Int) { return new TypeError($"Argument of type '{Power}' is not assignable to parameter of type 'IceKoriFloat || IceKoriInt'."); } return new IceKoriFloat(Mathf.Pow((float)((IceKoriBaseType)Floor).Unbox(), (float)((IceKoriBaseType)Power).Unbox())); } public override string ToString() { return $"Math.pow({Floor}, {Power})"; } } }
0
0.793845
1
0.793845
game-dev
MEDIA
0.818542
game-dev
0.937635
1
0.937635
r1delta/CORE
219,763
scripts/vscripts/mp/mp_npe.nut
const FX_LIGHT_ORANGE = "runway_light_orange" const FX_LIGHT_GREEN = "runway_light_green" const FX_POD_LASER = "P_pod_scan_laser_FP" const FX_POD_GLOWLIGHT = "P_pod_door_glow_FP" const FX_POD_SCREEN_IN = "P_pod_screen_lasers_IN" const FX_POD_SCREEN_OUT = "P_pod_screen_lasers_OUT" const FX_POD_DLIGHT_CONSOLE1 = "P_pod_Dlight_console1" const FX_POD_DLIGHT_CONSOLE2 = "P_pod_Dlight_console2" const FX_POD_DLIGHT_BACKLIGHT_SIDE = "P_pod_Dlight_backlight_side" const FX_POD_DLIGHT_BACKLIGHT_TOP = "P_pod_Dlight_backlight_top" const FX_SWAPDOOR_CLOSED = "P_npe_door_closed_sml" const FX_SWAPDOOR_OPEN = "P_npe_door_open_sml" const FX_SWAPDOOR_CLOSED_TITAN = "P_npe_door_closed_titan" const FX_SWAPDOOR_OPEN_TITAN = "P_npe_door_open_titan" const FX_SWAPDOOR_CLOSED_ARCH = "P_npe_door_closed_arch" const FX_SWAPDOOR_OPEN_ARCH = "P_npe_door_open_arch" PrecacheParticleSystem( FX_LIGHT_ORANGE ) PrecacheParticleSystem( FX_LIGHT_GREEN ) PrecacheParticleSystem( FX_POD_LASER ) PrecacheParticleSystem( FX_POD_GLOWLIGHT ) PrecacheParticleSystem( FX_POD_SCREEN_IN ) PrecacheParticleSystem( FX_POD_SCREEN_OUT ) PrecacheParticleSystem( FX_POD_DLIGHT_CONSOLE1 ) PrecacheParticleSystem( FX_POD_DLIGHT_CONSOLE2 ) PrecacheParticleSystem( FX_POD_DLIGHT_BACKLIGHT_SIDE ) PrecacheParticleSystem( FX_POD_DLIGHT_BACKLIGHT_TOP ) PrecacheParticleSystem( FX_SWAPDOOR_CLOSED ) PrecacheParticleSystem( FX_SWAPDOOR_OPEN ) PrecacheParticleSystem( FX_SWAPDOOR_CLOSED_TITAN ) PrecacheParticleSystem( FX_SWAPDOOR_OPEN_TITAN ) PrecacheParticleSystem( FX_SWAPDOOR_CLOSED_ARCH ) PrecacheParticleSystem( FX_SWAPDOOR_OPEN_ARCH ) PrecacheWeapon( "mp_projectile_orbital_strike" ) const PILOT_WEAPON_1 = "mp_weapon_semipistol" const PILOT_WEAPON_2 = "mp_weapon_smart_pistol" const PILOT_WEAPON_3 = "mp_weapon_rspn101" const PILOT_WEAPON_OFFHAND_OFFENSIVE = "mp_weapon_frag_grenade" const PILOT_WEAPON_AT = "mp_weapon_smr" const GRENADE_SLOT = 0 const TITAN_WEAPON_1 = "mp_titanweapon_xo16" const TITAN_WEAPON_OFFHAND_DEFENSIVE = "mp_titanweapon_vortex_shield" const TITAN_WEAPON_OFFHAND_OFFENSIVE = "mp_titanweapon_salvo_rockets" const FX_DEREZ = "env_training_derez" const FX_DEREZ_BLACK = "env_training_derez_blackout" const LEVEL_START_MODULE = -1 // set the default module to run at start (NOT dev) TITAN_CORE_ENABLED = false function main() { IncludeScript( "mp_npe_shared" ) if ( reloadingScripts ) return Riff_ForceSetSpawnAsTitan( eSpawnAsTitan.Never ) AddCallback_OnClientConnected( NPE_PlayerConnected ) AddClientCommandCallback( "topTarget", ClientCommand_LookTarget_Top ) AddClientCommandCallback( "bottomTarget", ClientCommand_LookTarget_Bottom ) AddClientCommandCallback( "lookInverted", ClientCommand_NPE_LookWasInverted ) AddClientCommandCallback( "noButtonClicked", ClientCommand_NPE_NoButtonClicked ) AddClientCommandCallback( "confirmInvertSettings", ClientCommand_NPE_ConfirmInvertYes ) AddClientCommandCallback( "startBedEndModule", ClientCommand_NPE_StartBedEndModule ) AddClientCommandCallback( "startTitanMoshPitModule", ClientCommand_NPE_StartTitanMoshPitModule ) AddClientCommandCallback( "NPE_WeaponSwitch", ClientCommand_NPE_PressedWeaponSwitch ) AddClientCommandCallback( "NPE_DashMeterLow", ClientCommand_NPE_DashMeterLow ) AddClientCommandCallback( "NPE_DashMeterReady", ClientCommand_NPE_DashMeterReady ) AddClientCommandCallback( "NPE_PlayerReloaded", ClientCommand_NPE_PlayerReloaded ) AddClientCommandCallback( "NPE_PlayerDashed", ClientCommand_NPE_PlayerDashed ) AddClientCommandCallback( "NPE_PlayerPressedUse", ClientCommand_NPE_PlayerPressedUse ) AddClientCommandCallback( "NPE_PlayerPressedPrimaryWeapon", ClientCommand_NPE_PlayerPressedPrimaryWeapon) AddClientCommandCallback( "NPE_FiredOffhandOffensive", ClientCommand_NPE_FiredOffhandOffensive ) AddClientCommandCallback( "NPE_PlayerPressedJump", ClientCommand_NPE_PlayerPressedJump ) AddClientCommandCallback( "leaveTraining", ClientCommand_LeaveTraining ) // for the pause menu AddClientCommandCallback( "callConversationOverSignal", ClientCommand_CallConversationOverSignal ) // for the pause menu AddClientCommandCallback( "callConversationOverEndSignal", ClientCommand_CallConversationOverEndSignal ) // for the pause menu AddClientCommandCallback( "trainingFinished", ClientCommand_SetTrainingHasEverFinished ) AddClientCommandCallback( "trainingStarted", ClientCommand_SetTrainingHasEverBeenStarted ) AddClientCommandCallback( "resumeChoice", ClientCommand_ResumeChoice ) AddDeathCallback( "npc_soldier", NPE_GroundTroopsDeathCallback ) AddDeathCallback( "npc_spectre", NPE_GroundTroopsDeathCallback ) AddDeathCallback( "npc_marvin", NPE_GroundTroopsDeathCallback ) level.grenadesThrown <- 0 AddSpawnCallback( "npc_grenade_frag", NPE_GrenadeCreatedCallback ) level.trainingRocketEffectTable <- PrecacheImpactEffectTable( GetWeaponInfoFileKeyField_Global( "mp_projectile_orbital_strike", "impact_effect_table" ) ) level.resumeChoice <- null level.training_hasEverBeenStarted <- null level.training_hasEverFinished <- null level.doQuickIntro <- false level.doQuickOutro <- false level.pilotTrainingOnly <- false level.titanTrainingOnly <- false level.currentTrainingModule <- null level.trainingModuleInfos <- null level.player <- null level.trainingPod <- null level.lastTrainingPrompt <- null level.skyboxCamDefault <- null level.skyboxCamSpace <- null level.skyboxModelSpace <- null level.titanPetControlPanel <- null level.titanDisembarkDisabled <- true level.dashMoves <- null level.moshpitStartAreaTrig <- null level.vortexDamage <- 0 level.wallrunPlayerPos <- -1 level.previousWallrunPlayerPos <- -1 level.wallrunPlatformTrigs <- [] level.lastSmartPistolTargs <- [] level.trainingModules <- [] level.lightSwitchTrigs <- [] level.grenadeTrigs <- [] level.lookTargets <- [] level.walkDoors <- [] level.sprintDoors <- [] level.dashRockets <- [] level.cabinWindowShutters <- [] level.trainingPodGlowLightRows <- [] RegisterSignal( "ConversationOver" ) RegisterSignal( "ModuleChanging" ) RegisterSignal( "Teleported" ) RegisterSignal( "TeleportedPlayer" ) RegisterSignal( "ModuleChangeDone" ) RegisterSignal( "DoorResetting" ) RegisterSignal( "PlayerInvertedLook" ) RegisterSignal( "PlayerClickedNoButton" ) RegisterSignal( "InvertSettingsConfirmed" ) RegisterSignal( "Cloak_PlayerFound" ) RegisterSignal( "Cloak_RanIntoPlayer" ) RegisterSignal( "PlayerKilledAllSentries" ) RegisterSignal( "CloakModuleResetting" ) RegisterSignal( "DetectPlayerFailedMultiTarget_Stop" ) RegisterSignal( "DetectTargetWasMeleed_Stop" ) RegisterSignal( "SetPlayerRocketDamageFlag" ) RegisterSignal( "StopSkyRotation" ) RegisterSignal( "PodInteriorSequenceDone" ) RegisterSignal( "TrainingPod_BeginInteriorShutdown" ) RegisterSignal( "StopFiringRockets" ) RegisterSignal( "StopRechargingVortex" ) RegisterSignal( "PlayTitanAnimSafe_Start" ) RegisterSignal( "NPC_FightPlayer" ) RegisterSignal( "StandDown_Change" ) RegisterSignal( "StopRefillingPlayerAmmo" ) RegisterSignal( "StopRefillingOffhandWeapons" ) RegisterSignal( "TeleportingPlayer" ) PrecacheParticleSystem( FX_DEREZ ) PrecacheParticleSystem( FX_DEREZ_BLACK ) FlagInit( "HealthSuperRegenEnd" ) FlagInit( "ModuleChangeInProgress" ) FlagInit( "FirstSpawnDone" ) FlagInit( "PlayerIsTeleporting" ) FlagInit( "PlayerPressedUse" ) FlagInit( "PlayerPressedPrimaryWeapon" ) FlagInit( "PlayerPressedJump" ) FlagInit( "PlayerLookedAtTopTarget" ) FlagInit( "PlayerLookedAtBottomTarget" ) FlagInit( "NagFlag" ) FlagInit( "DoorsImpassable" ) FlagInit( "PlayerNotSprintingThroughTrigger" ) FlagInit( "DoingBasicWallrunVO" ) FlagInit( "DoingWallrunHelperVO" ) FlagInit( "ShortWallrunDetected" ) FlagInit( "PlayerPastCloakArea" ) FlagInit( "NotKilledUsingSmartPistol" ) FlagInit( "PlayerReloaded" ) FlagInit( "PlayerPressedWeaponSwitchButton" ) FlagInit( "PlayerFailedMultiTarget" ) FlagInit( "SmartPistolMultiTargetsDead" ) FlagInit( "PlayerFailedMultiLock" ) FlagInit( "PlayerPassedMultiLock" ) FlagInit( "MultiLock_TargetWasMeleed" ) FlagInit( "FiringRangeWeaponSwapped" ) FlagInit( "PlayerADSed" ) FlagInit( "NonHeadshot" ) FlagInit( "PlayerThrewGrenade" ) FlagInit( "GrenadeThrowingDone" ) FlagInit( "PilotMoshPit_AllSquadsSpawned" ) FlagInit( "TrainingPilotHealth" ) FlagInit( "PilotHealthTrainingStarted" ) FlagInit( "MoshPit_GroundTroops_Done" ) FlagInit( "PlayerCalledInTitan" ) FlagInit( "TitanDropped" ) FlagInit( "PlayerEnteredTitan" ) FlagInit( "TitanDash_StartDirectionalVO" ) FlagInit( "PlayerDashMeterLow" ) FlagInit( "PlayerDashed" ) FlagInit( "PlayerDashed_Left" ) FlagInit( "PlayerDashed_Right" ) FlagInit( "PlayerDashed_Forward" ) FlagInit( "PlayerDashed_Back" ) FlagInit( "TeachingDashDirection" ) FlagInit( "TeachingDashMeter" ) FlagInit( "DashThreat_PlayerPastAlcove1" ) FlagInit( "PlayerTookRocketDamage" ) FlagInit( "PlayerVortexed" ) FlagInit( "PlayerVortex_CanRefire" ) FlagInit( "TitanVortex_NPCTitanDead" ) FlagInit( "TitanVortex_PlayerDamaged" ) FlagInit( "PlayerDisembarked" ) FlagInit( "PlayerInsideControlRoom" ) FlagInit( "TitanFollowModeEngaged" ) FlagInit( "FiredOffhandOffensive" ) FlagInit( "TitanMoshPitCombatStarted" ) FlagInit( "TitanShieldTrainingStarted" ) FlagInit( "TrainingTitanShields") FlagInit( "TitanHealthTrainingStarted" ) FlagInit( "TrainingTitanHealth") FlagInit( "CombatTestDone" ) FlagInit( "PlayerEjected" ) FlagInit( "Moshpit_Grenade" ) FlagInit( "Moshpit_Melee" ) FlagInit( "ConversationOver" ) FlagSet( "ForceStartSpawn" ) // always spawn as though the match just started FlagSet( "DisableTimeLimit" ) // won't end the game from time limit SetTitanEmbarkFailsafeOverrideFunc( NPE_TitanEmbarkFailsafeOverrideFunc ) } function EntitiesDidLoad() { NPE_EntitySetup() SetupTrainingModules() thread TrainerStart() } function NPE_PlayerConnected( player ) { printt( "NPE_PlayerConnected" ) thread NPE_PlayerConnected_Threaded( player ) } function NPE_PlayerConnected_Threaded( player ) { printt( "NPE_PlayerConnected_Threaded" ) if ( IsValid( level.player ) ) { printt( "WARNING multiple players connected to training level! Forcing return to lobby..." ) ReturnToLobby() } level.player = player level.player.EnableDemigod() level.player.SetTeam( TEAM_IMC ) //level.player.SetNextTitanRespawnAvailable( -1 ) if (GAMETYPE != "battle_practice") InitTitanBuildRule( level.player ) CreatePlayerAssaultEnt() printt( "invoke ServerCallback_PilotTrainingStart" ) Remote.CallFunction_Replay( level.player, "ServerCallback_PilotTrainingStart" ) } function TrainerStart() { printt( "TrainerStart" ) disable_npcs() SetGlobalForcedDialogueOnly( true ) printt( "NPE waiting for resume choice" ) //while ( level.resumeChoice == null ) // wait 0 printt( "NPE waiting for player" ) while ( !IsValidPlayer( level.player ) ) wait 0 printt( "NPE player found!" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) // default start if(level.resumeChoice != -1 && level.resumeChoice > -1) { // we are starting into a custom module level.doQuickIntro = true if(level.training_hasEverFinished) level.doQuickOutro = true } if(level.resumeChoice == -3) // user chose pilot training only { level.pilotTrainingOnly = true level.doQuickIntro = true level.doQuickOutro = true } if(level.resumeChoice == -4) // user chose titan training only { level.titanTrainingOnly = true level.doQuickIntro = true level.doQuickOutro = true } if(level.resumeChoice == null) { // in the uneventful case the resumechoice is null (a.k.a as invalid, thanks to the callbacks for catching it up) // we just reset to the bedroom intro level.resumeChoice = -1 Remote.CallFunction_Replay(level.player, "ServerCallback_SetTrainingResumeChoice", -1) } // technically we should always warp to the bedroom intro, then check where to go next level.currentTrainingModule = -1 /*if (true) level.currentTrainingModule = level.resumeChoice else if (GAMETYPE == "titan_tutorial") level.currentTrainingModule = eTrainingModules.TITAN_MOSH_PIT else if (GAMETYPE == "battle_practice") { level.currentTrainingModule = TRAINING_BATTLE_PRACTICE Remote.CallFunction_Replay(level.player, "ServerCallback_EnableTitanModeChange") }*/ // first time playing the level start -- OR -- dev test start thread StartTrainingModule( level.currentTrainingModule ) wait 0.5 level.player.s.rodeoEnabled = false // HACK shouldn't have to wait this long! (Related to player load time) wait 5 ModuleAdvanceTriggers_StartLoopedSFX() } // =========================== MODULE SETUP & FUNCTIONS =========================== function SetupTrainingModules() { level.trainingModuleInfos = [] local module = CreateTrainingModuleInfo() module.id = eTrainingModules.BEDROOM module.startPos = Vector( -13536, -6643, 0 ) module.startAng = Vector( 0, 100, 0 ) module.runFunc = Module_Bedroom module.resetFlags = [ "PlayerLookedAtTopTarget", "PlayerLookedAtBottomTarget" ] module.showLoading = true module.resumePoint = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.BEDROOM_END module.startPos = Vector( -13536, -6643, 0 ) module.startAng = Vector( 0, 100, 0 ) module.runFunc = Module_Bedroom_End module.showLoading = true module.resumePoint = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.JUMP module.startEnt = "destination_run_and_jump_training" module.runFunc = Module_RunAndJump module.playerMods = [ "disable_doublejump", "disable_wallrun" ] module.resetTrigs = [ "trigger_lightswitch3", "trigger_lightswitch2", "trigger_lightswitch", "trigger_lightswitch1", "trigger_lightswitch4" ] module.resetFlags = [ "DoorsImpassable", "PlayerStartWalkSection", "PlayerPassedWalkDoors", "SafeToCloseWalkDoors", "SprintDoorsStartClosing", "PlayerNotSprintingThroughTrigger", "PlayerPassedSprintDoors", "SafeToCloseSprintDoors", "PlayerNearJump", "PlayerPastJump", "PlayerPastRunAndJump", "PlayerNearMantle", "PlayerPastMantle" ] module.showLoading = true module.resumePoint = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.WALLRUN module.startEnt = "destination_wallrun_training" module.runFunc = Module_Wallrun module.playerMods = [ "disable_doublejump" ] module.resetTrigs = [ "trigger_lightswitch8", "trigger_lightswitch9", "trigger_lightswitch10", "trigger_lightswitch11" ] module.resetFlags = [ "PlayerEnteredWallrunArea", "DoingBasicWallrunVO", "DoingWallrunHelperVO", "PlayerReachedWallrunPlatform2", "PlayerReachedWallrunPlatform3", "PlayerReachedWallrunPlatform4", "PlayerReachedWallrunEnd" ] module.showLoading = true module.resumePoint = false module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.WALLRUN_PLAYGROUND module.startEnt = "destination_wallrun_playground" module.runFunc = Module_Wallrun_Playground // ??????????? module.resetFlags = [ "WallrunPlayground_HighRoad_1", "WallrunPlayground_HighRoad_2", "WallrunPlayground_BonusEval", "WallrunPlayground_HighRoad_Fail", "WallrunPlayground_LowRoad_1", "WallrunPlayground_LowRoad_2" ] module.playerMods = [ "disable_doublejump" ] module.showLoading = true module.resumePoint = false module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.DOUBLEJUMP module.startEnt = "destination_doublejump_training" module.runFunc = Module_Doublejump module.resetTrigs = [ "trigger_lightswitch12", "trigger_lightswitch13", "trigger_lightswitch14" ] module.resetFlags = [ "PlayerReachedDoublejumpPlatform2", "PlayerPastDoubleJump2", "PlayerPassedDoubleJumpCeiling" ] module.showLoading = true module.resumePoint = false module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.DOUBLEJUMP_PLAYGROUND module.startEnt = "destination_doublejump_playground" module.runFunc = Module_Doublejump_Playground // ??????????? module.resetFlags = [ "DoublejumpPlayground_PlayerEval" ] module.showLoading = true module.resumePoint = false module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.CLOAK module.startEnt = "destination_cloak_training" module.runFunc = Module_Cloak module.showLoading = true module.resumePoint = false module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.BASIC_COMBAT module.startEnt = "destination_smart_pistol_training" module.runFunc = Module_BasicCombat // ???????????? module.resetFlags = [ "PlayerNearMultikillSpot", "PlayerNearMultiLockSpot" ] module.showLoading = true module.resumePoint = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.FIRINGRANGE module.startEnt = "destination_weapons_training" module.runFunc = Module_FiringRange // I THINK THIS IS SPOT ON module.resetFlags = [ "FiringRangeWeaponSwapped", "PlayerADSed", "PlayerReloaded" ] module.showLoading = true module.resumePoint = false module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.FIRINGRANGE_GRENADES module.startEnt = "destination_grenade_training" module.runFunc = Module_FiringRange_Grenades module.resetFlags = [ "PlayerThrewGrenade", "GrenadeThrowingDone" ] module.showLoading = true module.resumePoint = false module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.MOSH_PIT module.startEnt = "destination_mosh_pit_playground" module.runFunc = Module_MoshPit module.resetFlags = [ "PlayerPressedWeaponSwitchButton", "PlayerReloaded", "PilotMoshPit_AllSquadsSpawned", "TrainingPilotHealth", "PilotHealthTrainingStarted", "MoshPit_GroundTroops_Done", "FiringRangeWeaponSwapped", "PlayerCalledInTitan", "TitanDropped", "PlayerEnteredTitan" ] module.showLoading = true module.resumePoint = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.TITAN_DASH module.startEnt = "teleport_titan_dash" module.runFunc = Module_TitanDash module.playerMods = [ "disable_sprint" ] module.resetFlags = [ "TitanDashFinishLine", "PlayerPastDashThreat", "PlayerStartDashThreat", "PlayerDashThreat_Alcove2", "PlayerDashThreat_Alcove1" ] module.showLoading = true module.resumePoint = true module.startAsTitan = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.TITAN_VORTEX module.startEnt = "teleport_titan_train_vortex" module.runFunc = Module_TitanVortex module.playerMods = [ "disable_sprint" ] module.resetFlags = [ "TitanPetPassedGate","PlayerInsideControlRoom" ] module.showLoading = true module.resumePoint = true module.startAsTitan = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.TITAN_PET module.startEnt = "teleport_titan_train_pet" module.runFunc = Module_TitanPet module.resetFlags = [ "TitanPetPassedGate","PlayerInsideControlRoom" ] module.showLoading = true module.resumePoint = true module.startAsTitan = true module.showEndEMP = false AddTrainingModuleInfo( module ) local module = CreateTrainingModuleInfo() module.id = eTrainingModules.TITAN_MOSH_PIT module.startEnt = "teleport_titan_mosh_pit" module.runFunc = Module_TitanMoshPit module.resetFlags = [ "TitanMoshPitCombatStarted", "TitanShieldTrainingStarted", "TrainingTitanShields", "TitanHealthTrainingStarted", "TrainingTitanHealth", "CombatTestDone" ] module.showLoading = true module.resumePoint = true module.startAsTitan = true module.showEndEMP = false AddTrainingModuleInfo( module ) if (GAMETYPE == "battle_practice") { local module = CreateTrainingModuleInfo() module.id = TRAINING_BATTLE_PRACTICE module.startEnt = "destination_mosh_pit_playground" module.runFunc = Module_BattlePractice module.resetFlags = [ "TitanMoshPitCombatStarted", "TitanShieldTrainingStarted", "TrainingTitanShields", "TitanHealthTrainingStarted", "TrainingTitanHealth", "CombatTestDone" ] module.showLoading = true module.resumePoint = true module.showEndEMP = false AddTrainingModuleInfo( module ) } } function CreateTrainingModuleInfo() { local info = {} info.id <- null info.startPos <- null info.startAng <- null info.startEnt <- null info.runFunc <- null info.runFuncVar <- null info.playerMods <- null info.startAsTitan <- null info.resetTrigs <- null info.resetFlags <- null info.showLoading <- null info.resumePoint <- null info.showEndEMP <- null return info } function AddTrainingModuleInfo( table ) { if ( table.startEnt != null ) { local entArray = GetEntArrayByName_Expensive( table.startEnt ) Assert( entArray.len(), "Couldn't find ent called " + table.startEnt ) Assert( entArray.len() == 1, "Found " + entArray.len() + " ent(s) with name " + startEnt + ", expected just one." ) local startEnt = entArray[ 0 ] table.startPos = startEnt.GetOrigin() table.startAng = startEnt.GetAngles() } if ( table.playerMods != null ) Assert( type( table.playerMods ) == "array", "Need to set player mods up as an array for module ID " + table.id ) level.trainingModuleInfos.append( table ) } function GetTrainingModuleInfo( moduleID ) { local moduleInfos = null foreach ( module in level.trainingModuleInfos ) { if ( module.id == moduleID ) { moduleInfos = module break } } Assert( moduleInfos, "Couldn't find training module info for moduleID " + moduleID ) return moduleInfos } function StartTrainingModule_FromDevMenu( moduleID ) { if ( !Flag( "FirstSpawnDone" ) ) { printt( "WARNING: Can't use dev menu until first spawn is finished." ) return } StartTrainingModule( moduleID ) } // If this function is called it means the player got stuck in a bad state while embarking/disembarking. function NPE_TitanEmbarkFailsafeOverrideFunc( player ) { printt( "NPE: Player titan embark failsafe override!" ) if ( Flag( "ModuleChangeInProgress" ) ) return // if player got stuck, restart the current training module thread StartTrainingModule( level.currentTrainingModule ) } function StartTrainingModule( moduleID ) { // we change resumechoice accordingly if we haven't finished training yet if(moduleID > -1) Remote.CallFunction_Replay(level.player, "ServerCallback_SetTrainingResumeChoice", moduleID) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.player.EndSignal( "OnDeath" ) level.ent.Signal( "ModuleChanging" ) level.ent.EndSignal( "ModuleChanging" ) FlagSet( "ModuleChangeInProgress" ) OnThreadEnd( function() : () { FlagClear( "ModuleChangeInProgress" ) } ) printt( "starting module", moduleID ) Remote.CallFunction_Replay( level.player, "ScriptCallback_NPE_ModuleChanging" ) local moduleInfo = GetTrainingModuleInfo( moduleID ) if (moduleInfo.showEndEMP) { Remote.CallFunction_Replay( level.player, "ServerCallback_TrainingTeleport" ) wait 0.5 } // sets the module we're about to execute as the current module so that advancing the module can increment the variable // EXCEPTION: intro cabin module doesn't set it because we might want to go to a module other than the very next one afterward (for continuing training after start) if (moduleID != TRAINING_BEDROOM/*eTrainingModules.BEDROOM*/) { level.currentTrainingModule = moduleID // server script } level.ui.trainingModule = moduleID // UI script needs to know when we are in BEDROOM or BEDROOM_END, so we always set it HideTrainingPrompt() level.player.HolsterWeapon() MuteAll( level.player, 2.5 ) // fix for moduleInfo being null sometimes in the wild if ( !IsValid( moduleInfo ) ) { local printstr = "$$$$ StartTrainingModule aborting because moduleInfo was invalid for ID " + moduleID printtodiag( printstr + "\n" ) printt( printstr ) return } if (GAMETYPE != "battle_practice") TakeAllWeapons( level.player ) TrainingModule_ResetTriggers( moduleInfo ) TrainingModule_ResetFlags( moduleInfo ) TrainingModule_SetPlayerSettings( moduleInfo ) HideMinimap() if ( moduleInfo.runFunc != null ) { if ( moduleInfo.runFuncVar != null ) thread moduleInfo.runFunc( moduleInfo.runFuncVar ) else thread moduleInfo.runFunc() } // INTROSCREEN TEXT if (ShouldDoIntroscreens() && moduleInfo.showLoading) { Remote.CallFunction_Replay( level.player, "ServerCallback_ShowIntroScreen", moduleID ) // let the intro screen start before we teleport, this is set up to work with the timing of the introscreen fade from black local waitTime = 5.3 if ( moduleID == TRAINING_BEDROOM/*eTrainingModules.BEDROOM*/ ) waitTime = 1 // SimpleBlackscreen wait wait waitTime } EnablePilotHud() //level.player.SetNextTitanRespawnAvailable( -1 ) if (GAMETYPE != "battle_practice") InitTitanBuildRule( level.player ) // teleport player before introscreen wait, so the module can set things up under blackscreen if necessary TeleportPlayer( moduleInfo.startPos, moduleInfo.startAng, false ) Remote.CallFunction_Replay( level.player, "ServerCallback_EnableFog" ) level.player.SetSkyCamera( level.skyboxCamDefault ) CleanupCorpses() local totalWait = 0 local waitBeforeTeleportFX = 0 local waitBeforeWeaponDeploy = 0 if (ShouldDoIntroscreens() && moduleInfo.showLoading) { totalWait = 1.5 waitBeforeTeleportFX = 0.6 waitBeforeWeaponDeploy = totalWait - waitBeforeTeleportFX } if ( !Flag( "FirstSpawnDone" ) ) FlagSet( "FirstSpawnDone" ) if (moduleInfo.showLoading) { wait waitBeforeTeleportFX if (moduleID != TRAINING_BEDROOM/*eTrainingModules.BEDROOM*/) // don't do the audio when players first spawn in Remote.CallFunction_Replay( level.player, "ServerCallback_TrainingTeleport" ) } UnMuteAll( level.player, 1.0 ) wait waitBeforeWeaponDeploy TrainingModule_GiveDefaultWeapons() level.ent.Signal( "ModuleChangeDone" ) } function TrainingModule_SetPlayerSettings( moduleInfo ) { local cancelDoomedState = moduleInfo.startAsTitan && level.player.IsTitan() && level.player.GetDoomedState() // Handle player embarking/disembarking local playerEmbarking = false local playerTitan = GetPlayerTitanInMap( level.player ) if ( playerTitan ) if ( "disembarkingPlayer" in playerTitan.s || "embarkingPlayer" in playerTitan.s ) playerEmbarking = true printt( "Player embarking?", playerEmbarking ) if ( playerEmbarking ) level.player.ClearParent() // trying to kill the titan while the player is attached causes an engine error // Kill player's pet titan in the world. If embarking/disembarking this also kills that scripting. if ( playerTitan && !playerTitan.IsPlayer() ) playerTitan.Kill() // if module is for pilots and we're a Titan, OR if we're already a Titan and need to cancel doomed state, turn player into a pilot if ( ( moduleInfo.startAsTitan == null && level.player.IsTitan() ) || cancelDoomedState ) { local dummyTitan = CreateTitanFromPlayer( level.player ) TitanBecomesPilot( level.player, dummyTitan ) dummyTitan.Kill() // HACK this forces the cockpit HUD to redraw, clearing the health bar hazard lines and the eject button prompt if ( cancelDoomedState ) Remote.CallFunction_NonReplay( level.player, "ScriptCallback_DestroyPlayerCockpit" ) } if ( moduleInfo.startAsTitan && !level.player.IsTitan() ) { local titan = CreateNPCTitanForPlayer( level.player, level.player.GetOrigin(), level.player.GetAngles() ) PilotBecomesTitan( level.player, titan ) titan.Kill() DisableTitanDisembark() } local playerSetFile = "pilot_training" if ( moduleInfo.startAsTitan != null ) playerSetFile = "titan_atlas_training" if ( moduleInfo.playerMods != null ) level.player.SetPlayerSettingsWithMods( playerSetFile, moduleInfo.playerMods ) else level.player.SetPlayerSettings( playerSetFile ) } function TrainingModule_GiveDefaultWeapons() { if (GAMETYPE == "battle_practice") return TakeAllWeapons( level.player ) if ( level.player.IsTitan() ) { level.player.GiveWeapon( TITAN_WEAPON_1 ) //level.player.GiveOffhandWeapon( TITAN_WEAPON_OFFHAND_OFFENSIVE, 0 ) //level.player.GiveOffhandWeapon( TITAN_WEAPON_OFFHAND_DEFENSIVE, 1 ) level.player.DeployWeapon() } else { level.player.GiveWeapon( PILOT_WEAPON_1 ) level.player.DeployWeapon() } thread TakeAmmoFromPlayerASAP() } function AdvanceToNextTrainingModule() { //printt( "AdvanceToNextTrainingModule: level.currentTrainingModule: " + level.currentTrainingModule ) AdvanceCurrentTrainingModuleIdx() if ( level.currentTrainingModule > 0 ) EmitSoundOnEntity( level.player, "NPE_Module_Finish" ) if(level.resumeChoice > 0 && level.currentTrainingModule < level.resumeChoice) level.currentTrainingModule = level.resumeChoice if(level.pilotTrainingOnly && level.currentTrainingModule > 9) level.currentTrainingModule = -2 // warp to bedroom end if(level.titanTrainingOnly && level.currentTrainingModule < 11) level.currentTrainingModule = 10 thread StartTrainingModule( level.currentTrainingModule ) } // sets the next module ID to use function AdvanceCurrentTrainingModuleIdx() { local table = getconsttable().eTrainingModules local lastIdx = 0 foreach ( val in table ) { if ( val > lastIdx ) lastIdx = val } local nextModuleID = level.currentTrainingModule + 1 nextModuleID = FindValidModuleID(nextModuleID) if ( nextModuleID == -1 ) { local printstr = "No training modules set up past index " + level.currentTrainingModule + ", setting to zero." printt( printstr ) printtodiag( printstr + "\n" ) nextModuleID = 0 } level.currentTrainingModule = nextModuleID } function FindValidModuleID( moduleID ) { local table = getconsttable().eTrainingModules local lastIdx = 0 foreach ( val in table ) { if ( val > lastIdx ) lastIdx = val } while ( 1 ) { if ( moduleID > lastIdx ) break foreach ( module in level.trainingModuleInfos ) { if ( module.id == moduleID ) { return module.id } } moduleID = moduleID + 1 } return -1 } // =========================== ENTITY SETUP =========================== function NPE_EntitySetup() { SetupLightSwitchTriggers() SetupModuleAdvanceTriggers() SetupPlayerResetTriggers() SetupGrenadeTriggers() SetupDoors() SetupCabinWindowShutters() SetupSkyboxEnts() local arr = GetEntArrayByName_Expensive( "control_panel_titan_pet" ) Assert( arr.len() == 1 ) level.titanPetControlPanel = arr[ 0 ] SetupTrainingPod() TrainingPod_GlowLightsArraySetup() // the order of these should match the order of the gapInfo indices level.wallrunPlatformTrigs.append( GetEnt( "trig_wallrun_start" ) ) level.wallrunPlatformTrigs.append( GetEnt( "trig_wallrun_platform2" ) ) level.wallrunPlatformTrigs.append( GetEnt( "trig_wallrun_platform3" ) ) level.wallrunPlatformTrigs.append( GetEnt( "trig_wallrun_platform4" ) ) level.wallrunPlatformTrigs.append( GetEnt( "trigger_lightswitch11" ) ) level.moshpitStartAreaTrig = GetEnt( "trig_moshpit_start_building" ) } function SetupLightSwitchTriggers() { local lightTrigs = GetEntArrayByNameWildCard_Expensive( "trigger_lightswitch*" ) foreach ( trig in lightTrigs ) { trig.s.triggered <- null trig.s.lights <- [] local targs = GetEntArrayByName_Expensive( trig.GetTarget() ) Assert( targs.len(), "Couldn't find lightswitch trigger target named " + trig.GetTarget() + " from trigger " + trig.GetName() ) Assert( targs.len() == 1 ) local targetEnt = targs[ 0 ] while ( IsValid( targetEnt ) ) { trig.s.lights.append( targetEnt ) local targs = GetEntArrayByName_Expensive( targetEnt.GetTarget() ) if ( !targs.len() ) break Assert( targs.len() == 1 ) targetEnt = targs[ 0 ] } foreach ( fxSpot in trig.s.lights ) ChangeFXOnRef( fxSpot, FX_LIGHT_ORANGE ) level.lightSwitchTrigs.append( trig ) // HACK want to disable the auto triggering on this one without recompiling the map if ( trig.GetName() == "trigger_lightswitch6" ) continue trig.ConnectOutput( "OnStartTouch", PlayerTouchedLightSwitchTrigger ) } } function TrainingModule_ResetTriggers( moduleInfo ) { if ( moduleInfo.resetTrigs == null ) return LightTriggers_Reset( moduleInfo.resetTrigs ) } function LightTriggers_Reset( lightTrigArray ) { foreach ( name in lightTrigArray ) { local trig = GetLightTrigger( name ) Assert( IsValid( trig ), "Couldn't find valid trigger named " + name ) trig.s.triggered = null foreach ( fxSpot in trig.s.lights ) ChangeFXOnRef( fxSpot, FX_LIGHT_ORANGE ) } } function LightTrigger_On( trigTN, fxAlias = FX_LIGHT_ORANGE ) { local lightTrig = GetLightTrigger( trigTN) Assert( lightTrig ) foreach ( fxSpot in lightTrig.s.lights ) ChangeFXOnRef( fxSpot, fxAlias ) } function LightTrigger_Off( trigTN ) { local lightTrig = GetLightTrigger( trigTN) Assert( lightTrig ) foreach ( fxSpot in lightTrig.s.lights ) KillFX( fxSpot.s.fxHandle ) } function GetLightTrigger( trigTN ) { foreach ( trig in level.lightSwitchTrigs ) if ( trig.GetName() == trigTN ) return trig return null } function TriggerSetRequireSprint( trigTN ) { local trig = GetLightTrigger( trigTN ) Assert( IsValid( trig ), "Can't set requireSprint on trigger named " + trigTN + " because it wasn't found." ) if ( !( "requireSprint" in trig.s ) ) trig.s.requireSprint <- 1 } function TrainingModule_ResetFlags( moduleInfo ) { if ( moduleInfo.resetFlags == null ) return foreach ( flagname in moduleInfo.resetFlags ) { FlagClear( flagname ) } } function PlayerTouchedLightSwitchTrigger( trig, entity, caller, value ) { if ( entity != level.player ) return if ( trig.s.triggered != null ) return trig.s.triggered = 1 local lightColorFX = FX_LIGHT_GREEN local soundAlias = "NPE_Player_Succeed" if ( "requireSprint" in trig.s && !entity.IsSprinting() ) { lightColorFX = null soundAlias = null FlagSet( "PlayerNotSprintingThroughTrigger" ) } Assert( trig.s.lights.len() ) if ( soundAlias != null ) EmitSoundOnEntity( level.player, soundAlias ) if ( lightColorFX != null ) foreach ( fxSpot in trig.s.lights ) ChangeFXOnRef( fxSpot, lightColorFX ) } function ChangeFXOnRef( fxSpot, fxAlias, endcapPlayTime = null ) { if ( "fxHandle" in fxSpot.s ) { if ( endcapPlayTime != null ) thread KillFXWithEndcap( fxSpot.s.fxHandle, endcapPlayTime ) else KillFX( fxSpot.s.fxHandle ) fxSpot.s.fxHandle = null } else { fxSpot.s.fxHandle <- null } fxSpot.s.fxHandle = PlayLoopFX( fxAlias, fxSpot.GetOrigin(), fxSpot.GetAngles() ) } function KillFX( fxHandle, doDestroyImmediately = false ) { if ( !IsValid_ThisFrame( fxHandle ) ) return fxHandle.Fire( "DestroyImmediately" ) fxHandle.ClearParent() fxHandle.Destroy() } function KillFXWithEndcap( fxHandle, killDelay = 1.0 ) { if ( !IsValid_ThisFrame( fxHandle ) ) return fxHandle.Fire( "StopPlayEndCap" ) wait killDelay if ( !IsValid_ThisFrame( fxHandle ) ) return fxHandle.ClearParent() fxHandle.Destroy() } function KillFXWithEndlessEndcap( fxHandle ) { if ( !IsValid_ThisFrame( fxHandle ) ) return fxHandle.Fire( "StopPlayEndCap" ) } function SetupModuleAdvanceTriggers() { local moduleChangeTrigs = GetEntArrayByNameWildCard_Expensive( "module_advance_trigger*" ) level.moduleChangeTrigs <- [] foreach ( trig in moduleChangeTrigs ) { trig.ConnectOutput( "OnStartTouch", PlayerTouchedModuleAdvanceTrigger ) level.moduleChangeTrigs.append( trig ) } } function ModuleAdvanceTriggers_StartLoopedSFX() { Assert( level.moduleChangeTrigs && level.moduleChangeTrigs.len() ) foreach ( trig in level.moduleChangeTrigs ) { local ref = CreateScriptMover( trig, trig.GetOrigin(), Vector( 0, 0, 0 ) ) ref.Show() trig.s.sfxEmitter <- ref //printt( "trying to play successdeck sound on", ref, "isvalid?", IsValid( ref ) ) EmitSoundOnEntity( trig.s.sfxEmitter, "NPE_Emit_SuccessDeck" ) } } function PlayerTouchedModuleAdvanceTrigger( trig, entity, caller, value ) { trig.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) if ( entity != level.player ) return //printt( "touched module advance trigger" ) if ( IsValid( trig.s.sfxEmitter ) ) FadeOutSoundOnEntity( trig.s.sfxEmitter, "NPE_Emit_SuccessDeck", 1 ) thread AdvanceToNextTrainingModule() // wait for teleport away, then play sound again level.player.WaitSignal( "Teleported" ) EmitSoundOnEntity( trig.s.sfxEmitter, "NPE_Emit_SuccessDeck" ) } function SetupPlayerResetTriggers() { local resetTrigs = GetEntArrayByNameWildCard_Expensive( "player_reset_trigger*" ) foreach ( trig in resetTrigs ) { local targs = GetEntArrayByName_Expensive( trig.GetTarget() ) Assert( targs.len(), "Couldn't find player reset trigger target named " + trig.GetTarget() + " from trigger " + trig.GetName() ) Assert( targs.len() == 1 ) local targetEnt = targs[ 0 ] trig.s.targetOrg <- targetEnt.GetOrigin() trig.s.targetAng <- targetEnt.GetAngles() trig.ConnectOutput( "OnStartTouch", PlayerTouchedPlayerResetTrigger ) } } function PlayerTouchedPlayerResetTrigger( trig, entity, caller, value ) { if ( entity != level.player ) return Assert( trig.s.targetOrg && trig.s.targetAng ) if ( Flag( "PlayerIsTeleporting" ) ) { printt( "canceled teleport from trig", trig, "because a teleport is already happening." ) return } EmitSoundOnEntity( level.player, "NPE_Player_Fail" ) thread TeleportPlayer( trig.s.targetOrg, trig.s.targetAng, true, true ) } function SetupGrenadeTriggers() { local grenadeTrigs = GetEntArrayByNameWildCard_Expensive( "trig_grenade_target*" ) foreach ( trig in grenadeTrigs ) { local targs = GetEntArrayByName_Expensive( trig.GetTarget() ) Assert( targs.len(), "Couldn't find light named " + trig.GetTarget() + " from trigger " + trig.GetName() ) Assert( targs.len() == 1 ) local targetEnt = targs[ 0 ] trig.s.fxSpot <- targetEnt trig.s.wasTriggered <- false trig.ConnectOutput( "OnStartTouch", GrenadeTriggerTouched ) } level.grenadeTrigs = grenadeTrigs } function GrenadeTriggerTouched( trig, entity, caller, value ) { Assert( "wasTriggered" in trig.s ) Assert( "fxSpot" in trig.s ) if ( entity.GetClassname() != "npc_grenade_frag" ) return trig.EndSignal( "OnDestroy" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) // let the grenade explode before it's registered trig.DisconnectOutput( "OnStartTouch", "GrenadeTriggerTouched" ) wait 0.25 EmitSoundOnEntity( level.player, "NPE_Player_Succeed" ) // just turn the light off KillFX( trig.s.fxSpot.s.fxHandle ) trig.s.wasTriggered = true } function ResetGrenadeTriggers() { foreach ( trig in level.grenadeTrigs ) { ChangeFXOnRef( trig.s.fxSpot, FX_LIGHT_ORANGE ) trig.s.wasTriggered = false } } function SetupCabinWindowShutters() { local shutterNames = [ "cabin_shutter_1", "cabin_shutter_2", "cabin_shutter_3", "cabin_shutter_4", "cabin_shutter_5", "cabin_shutter_6" ] foreach ( name in shutterNames ) { local arr = GetEntArrayByName_Expensive( name ) Assert( arr.len() == 1, "Couldn't find cabin window shutter named " + name ) local shutter = arr[ 0 ] shutter.s.ogPos <- shutter.GetOrigin() shutter.s.ogAng <- shutter.GetAngles() level.cabinWindowShutters.append( shutter ) } } function SetupSkyboxEnts() { local arr = GetEntArrayByName_Expensive( "skybox_cam_level" ) Assert( arr.len() == 1 ) level.skyboxCamDefault = arr[ 0 ] local arr = GetEntArrayByName_Expensive( "skybox_cam_intro" ) Assert( arr.len() == 1 ) level.skyboxCamSpace = arr[ 0 ] local arr = GetEntArrayByName_Expensive( "skybox_model_space" ) Assert( arr.len() == 1 ) level.skyboxModelSpace = arr[ 0 ] level.skyboxModelSpace.s.ogAng <- level.skyboxModelSpace.GetAngles() } function SetupDoors() { level.walkDoors = GetEntArrayByNameWildCard_Expensive( "walk_door*" ) Assert( level.walkDoors.len() == 2 ) level.sprintDoors = GetEntArrayByNameWildCard_Expensive( "sprint_door*" ) Assert( level.sprintDoors.len() == 2 ) local allDoors = clone level.walkDoors allDoors.extend( clone level.sprintDoors ) foreach ( door in allDoors ) door.s.ogPos <- door.GetOrigin() level.swapDoors <- {} AddSwapDoors( "door_walk_enter", "arch" ) AddSwapDoors( "door_sprint_enter", "arch" ) AddSwapDoors( "door_cloak_exit", "small" ) AddSwapDoors( "door_cloak_secondexit", "small" ) AddSwapDoors( "door_melee_enter", "small" ) AddSwapDoors( "door_melee_exit", "small" ) AddSwapDoors( "door_smartpistol_enter", "small" ) AddSwapDoors( "door_smartpistol_exit", "small" ) AddSwapDoors( "door_smartpistolpilots_enter", "small" ) AddSwapDoors( "door_smartpistolpilots_exit", "small" ) AddSwapDoors( "door_titan_dash_threat_enter", "titan" ) AddSwapDoors( "door_titan_dash_threat_start", "titan" ) AddSwapDoors( "door_titan_vortex_enter", "titan" ) AddSwapDoors( "door_titan_vortex_exit", "titan" ) AddSwapDoors( "door_titan_pet_gate", "titan" ) AddSwapDoors( "door_titan_pet_exit_gate", "titan" ) AddSwapDoors( "door_controlpanel_exit", "small" ) AddSwapDoors( "door_controlpanel_enter", "small" ) } // door pairs that slide open function GetDoorPair( doorArray ) { local doorL local doorR foreach ( door in doorArray ) { local doorName = door.GetName() local suffix = doorName.slice( doorName.len() - 2 ) Assert( suffix == "_L" || suffix == "_R" ) if ( suffix == "_L" ) doorL = door else doorR = door } Assert( IsValid( doorL ) && IsValid( doorR ) ) return { doorL = doorL, doorR = doorR } } function DoorPair_SnapOpen( doorArray, moveDist ) { DoorPair_Reset( doorArray ) wait 0.05 // make sure the doors are done resetting before moving them local doors = GetDoorPair( doorArray ) local doorL = doors.doorL local doorR = doors.doorR local doorL_org = doorL.GetOrigin() local doorL_movePos = Vector( doorL_org.x - moveDist, doorL_org.y, doorL_org.z ) local doorR_org = doorR.GetOrigin() local doorR_movePos = Vector( doorR_org.x + moveDist, doorR_org.y, doorR_org.z ) doorL.MoveTo( doorL_movePos, 0.05 ) doorR.MoveTo( doorR_movePos, 0.05 ) } function DoorPair_SnapClosed( doorArray ) { DoorPair_Reset( doorArray ) local doors = GetDoorPair( doorArray ) local doorL = doors.doorL local doorR = doors.doorR doorL.MoveTo( doorL.s.ogPos, 0.05 ) doorR.MoveTo( doorR.s.ogPos, 0.05 ) } /* DEPRECATED we don't use this anymore function DoorPair_SlideOpen( doorArray, moveDist, moveTime, secondDoorDelay = 0.0 ) { local doors = GetDoorPair( doorArray ) local doorL = doors.doorL local doorR = doors.doorR local doorL_org = doorL.GetOrigin() local doorL_movePos = Vector( doorL_org.x - moveDist, doorL_org.y, doorL_org.z ) local doorR_org = doorR.GetOrigin() local doorR_movePos = Vector( doorR_org.x + moveDist, doorR_org.y, doorR_org.z ) local accel = moveTime * 0.2 local decel = moveTime * 0.2 thread LoopSoundOnDoor_ForTime( doorL, "NPE_Scr_SprintDoor_Loop", moveTime, null, "NPE_Scr_SprintDoor_Shut", "NPE_Scr_SprintDoor_Stop" ) doorL.MoveTo( doorL_movePos, moveTime, accel, decel ) delaythread( secondDoorDelay ) doorR.MoveTo( doorR_movePos, moveTime, accel, decel ) } */ function DoorPair_SlideClosed( doorArray, moveTime, secondDoorDelay = 0, endFlag = null ) { local doors = GetDoorPair( doorArray ) local doorL = doors.doorL local doorR = doors.doorR local accel = moveTime * 0.2 local decel = moveTime * 0.2 EmitSoundOnEntity( doorL, "NPE_Scr_SprintDoor_Start" ) thread LoopSoundOnDoor_ForTime( doorL, "NPE_Scr_SprintDoor_Loop", moveTime, endFlag, "NPE_Scr_SprintDoor_Shut", "NPE_Scr_SprintDoor_Stop" ) doorL.MoveTo( doorL.s.ogPos, moveTime, accel, decel ) thread MoveTo_Delayed( secondDoorDelay, doorR, doorR.s.ogPos, moveTime, accel, decel ) } function SetFlagWhenDoorsImpossibleToPass( doorArray, setFlag, stopSignal ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( stopSignal ) // min dist the doors need to be apart for players to pass local minDistApart = 66 // player width is 64 local doors = GetDoorPair( doorArray ) local doorL = doors.doorL local doorR = doors.doorR Assert( Distance( doorL.GetOrigin(), doorL.s.ogPos ) + Distance( doorR.GetOrigin(), doorR.s.ogPos ) > minDistApart ) doorL.EndSignal( "OnDestroy" ) doorR.EndSignal( "OnDestroy" ) local totalDist = 0 while ( 1 ) { local doorL_dist = Distance( doorL.GetOrigin(), doorL.s.ogPos ) local doorR_dist = Distance( doorR.GetOrigin(), doorR.s.ogPos ) totalDist = doorL_dist + doorR_dist //printt( "doorL_dist", doorL_dist, "doorR_dist", doorR_dist, "totalDist", totalDist ) if ( totalDist <= minDistApart ) break wait 0 } //printt( "doors impossible to pass at dist", totalDist, "setting flag", setFlag ) FlagSet( setFlag ) } function LoopSoundOnDoor_ForTime( ent, alias, time, endFlag = null, endAlias = null, earlyEndAlias = null ) { ent.EndSignal( "OnDeath" ) ent.EndSignal( "DoorResetting" ) //printt( "looping sound") local expectedEndTime = Time() + time if ( endFlag ) level.ent.EndSignal( endFlag ) OnThreadEnd( function() : ( ent, alias, expectedEndTime, endAlias, earlyEndAlias ) { //printt( "ending loop sound" ) if ( IsValid( ent ) ) { StopSoundOnEntity( ent, alias ) if ( Time() < expectedEndTime && earlyEndAlias ) EmitSoundOnEntity( ent, earlyEndAlias ) else if ( Time() >= expectedEndTime && endAlias ) EmitSoundOnEntity( ent, endAlias ) } } ) EmitSoundOnEntity( ent, alias ) wait time } function DoorPair_Reset( doorArray ) { local doors = GetDoorPair( doorArray ) foreach ( door in doors ) door.Signal( "DoorResetting" ) local didMoveTo = false foreach ( door in doors ) { // doing a moveto if ( "_internalMover" in door.s ) { door.MoveTo( door.s.ogPos, 0.05 ) didMoveTo = true continue } door.SetOrigin( door.s.ogPos ) } if ( didMoveTo ) wait 0.05 } function DoorPair_Freeze( doorPair ) { local doors = GetDoorPair( doorPair ) foreach( door in doors ) door.MoveTo( door.GetOrigin(), 0.05 ) wait 0.05 } function AddSwapDoors( tnPrefix, doorSize = null ) { Assert( !( tnPrefix in level.swapDoors ), "Tried to set up swap doors twice: " + tnPrefix ) level.swapDoors[ tnPrefix ] <- SetupSwapDoors( tnPrefix, doorSize ) } // grid style doors that swap function SetupSwapDoors( tnPrefix, doorSize = null ) { local doorClosed local doorOpen local doors = GetEntArrayByNameWildCard_Expensive( tnPrefix + "*" ) foreach ( door in doors ) { local doorName = door.GetName() if ( doorName.find( "_red" ) ) doorClosed = door else if ( doorName.find( "_green" ) ) doorOpen = door else printt( "Couldn't find red/green door using prefix", tnPrefix ) } Assert( IsValid( doorClosed ) && IsValid( doorOpen ) ) doorClosed.s.ogPos <- doorClosed.GetOrigin() doorOpen.s.doorSize <- doorSize doorOpen.s.fxSpot <- null local targs = GetEntArrayByName_Expensive( doorOpen.GetTarget() ) if ( targs.len() ) { Assert( targs.len() == 1 ) local targetEnt = targs[ 0 ] printt( doorOpen.GetName(), "found target ent" ) doorOpen.s.fxSpot = targetEnt } else { local centerpoint = OriginToGround( doorOpen.GetOrigin() ) local centerang = doorOpen.GetAngles() + Vector( 0, 90, 0 ) // HACK doorOpen.s.fxSpot = CreateScriptRef( centerpoint, centerang ) } return { doorClosed = doorClosed, doorOpen = doorOpen } } function GetSwapDoors( tnPrefix ) { Assert( tnPrefix in level.swapDoors, "No swap doors found with prefix name " + tnPrefix ) return level.swapDoors[ tnPrefix ] } function OpenSwapDoors( tnPrefix ) { local doors = GetSwapDoors( tnPrefix ) local doorClosed = doors.doorClosed local doorOpen = doors.doorOpen doorClosed.Hide() doorClosed.MoveTo( doorClosed.GetOrigin() + Vector( 0, 0, 256 ), 0.05 ) doorOpen.Show() StopSwapDoorLoopSFX( doorOpen ) EmitSoundAtPosition( doorOpen.GetOrigin(), "NPE_Scr_DigitalDoor_Open" ) // doors replaced with FX if ( doorOpen.s.doorSize ) { SwapDoorOpenFX( doorOpen ) doorOpen.Hide() } } function CloseSwapDoors( tnPrefix ) { local doors = GetSwapDoors( tnPrefix ) local doorClosed = doors.doorClosed local doorOpen = doors.doorOpen Assert( "ogPos" in doorClosed.s, "Couldn't find ogPos for door " + doorClosed ) doorClosed.MoveTo( doorClosed.s.ogPos, 0.05 ) doorClosed.Show() doorOpen.Hide() StartSwapDoorLoopSFX( doorOpen ) // doors replaced with FX if ( doorOpen.s.doorSize ) { SwapDoorCloseFX( doorOpen ) doorClosed.Hide() } } function SwapDoorOpenFX( swapDoor ) { Assert( "fxSpot" in swapDoor.s ) local doorSize = swapDoor.s.doorSize local doorFX = FX_SWAPDOOR_OPEN if ( doorSize == "titan" ) doorFX = FX_SWAPDOOR_OPEN_TITAN else if ( doorSize == "arch" ) doorFX = FX_SWAPDOOR_OPEN_ARCH ChangeFXOnRef( swapDoor.s.fxSpot, doorFX, 2 ) } function SwapDoorCloseFX( swapDoor ) { Assert( "fxSpot" in swapDoor.s ) local doorSize = swapDoor.s.doorSize local doorFX = FX_SWAPDOOR_CLOSED if ( doorSize == "titan" ) doorFX = FX_SWAPDOOR_CLOSED_TITAN else if ( doorSize == "arch" ) doorFX = FX_SWAPDOOR_CLOSED_ARCH ChangeFXOnRef( swapDoor.s.fxSpot, doorFX, 2 ) } function StartSwapDoorLoopSFX( swapDoor ) { if ( !( "loopSFX" in swapDoor.s ) ) swapDoor.s.loopSFX <- null else if ( swapDoor.s.loopSFX ) { // already playing return } EmitSoundOnEntity( swapDoor, "NPE_Emit_DigitalDoor_Presence" ) swapDoor.s.loopSFX = "NPE_Emit_DigitalDoor_Presence" } function StopSwapDoorLoopSFX( swapDoor ) { if ( !( "loopSFX" in swapDoor.s ) || !swapDoor.s.loopSFX ) return StopSoundOnEntity( swapDoor, "NPE_Emit_DigitalDoor_Presence" ) swapDoor.s.loopSFX = null } function SetupTrainingPod() { local arr = GetEntArrayByName_Expensive( "training_pod" ) Assert( arr.len() == 1 ) level.trainingPod = arr[ 0 ] level.trainingPod.s.laserEmitters <- [] level.trainingPod.s.glowLightFXHandles <- [] level.trainingPod.s.dLights <- [] TrainingPod_SetupInteriorDLights() local laserAttachNames = [ "fx_laser_L", "fx_laser_R" ] foreach ( attachName in laserAttachNames ) { local emitter = CreateScriptMover( level.trainingPod ) local attachID = level.trainingPod.LookupAttachment( attachName ) local attachAng = level.trainingPod.GetAttachmentAngles( attachID ) emitter.s.attachName <- attachName emitter.s.ogAng <- attachAng emitter.s.sweepDone <- false emitter.s.fxHandle <- null level.trainingPod.s.laserEmitters.append( emitter ) } // HACK we do this later as well to reset the emitter positions, so it's a separate function TrainingPod_SnapLaserEmittersToAttachPoints() level.trainingPod.SetAngles( Vector( 0, 109, 0 ) ) // these angles are a little better for seeing the room } function TrainingPod_SetupInteriorDLights() { local pod = level.trainingPod local map = [] map.append( { scriptAlias = "console1", fxName = FX_POD_DLIGHT_CONSOLE1, attachName = "light_console1" } ) map.append( { scriptAlias = "console2", fxName = FX_POD_DLIGHT_CONSOLE2, attachName = "light_console2" } ) map.append( { scriptAlias = "backlight_side_L", fxName = FX_POD_DLIGHT_BACKLIGHT_SIDE, attachName = "light_back1" } ) map.append( { scriptAlias = "backlight_side_R", fxName = FX_POD_DLIGHT_BACKLIGHT_SIDE, attachName = "light_back2" } ) map.append( { scriptAlias = "backlight_top", fxName = FX_POD_DLIGHT_BACKLIGHT_TOP, attachName = "light_backtop" } ) level.trainingPod.s.dLightMappings <- map } function TrainingPod_TurnOnInteriorDLights_Delayed( delay ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) wait delay TrainingPod_TurnOnInteriorDLight( "console1" ) TrainingPod_TurnOnInteriorDLight( "console2" ) } function TrainingPod_TurnOnInteriorDLight( scriptAlias ) { local pod = level.trainingPod local fxName local attachName foreach ( mapping in pod.s.dLightMappings ) { if ( mapping.scriptAlias == scriptAlias ) { fxName = mapping.fxName attachName = mapping.attachName break } } Assert( fxName && attachName ) local fxHandle = PlayLoopFXOnEntity( fxName, pod, attachName ) level.trainingPod.s.dLights.append( fxHandle ) } function TrainingPod_KillInteriorDLights_Delayed( delay ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) wait delay TrainingPod_KillInteriorDLights() } function TrainingPod_KillInteriorDLights() { foreach ( fxHandle in level.trainingPod.s.dLights ) { if ( !IsValid_ThisFrame( fxHandle ) ) continue KillFX( fxHandle ) } level.trainingPod.s.dLights = [] } function TrainingPod_SnapLaserEmittersToAttachPoints() { foreach ( emitter in level.trainingPod.s.laserEmitters ) { local attachID = level.trainingPod.LookupAttachment( emitter.s.attachName ) local attachOrg = level.trainingPod.GetAttachmentOrigin( attachID ) local attachAng = level.trainingPod.GetAttachmentAngles( attachID ) emitter.ClearParent() emitter.SetOrigin( attachOrg ) // HACK set this to ANYTHING (even 0, 0, 0) and the position is correct, otherwise it's offset from the attachpoint when parented emitter.SetParent( level.trainingPod, emitter.s.attachName ) } } function DrawEmitterArrows() { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) while ( 1 ) { foreach ( e in level.trainingPod.s.laserEmitters ) DrawArrow( e.GetOrigin(), e.GetAngles(), 1, 10 ) wait 1 } } function TrainingPod_GlowLightsArraySetup() { local rows = [] // rows are set up bottom to top // lights are set up outside to in (in = door close seam; opposite for each side) // process two rows per loop (one for each door side) local row = [] row.append( [ "fx_glow_L_door012", "fx_glow_L_door013" ] ) row.append( [ "fx_glow_R_door014", "fx_glow_R_door013" ] ) rows.append( row ) local row = [] row.append( [ "fx_glow_L_door014", "fx_glow_L_door011" ] ) row.append( [ "fx_glow_R_door012", "fx_glow_R_door011" ] ) rows.append( row ) local row = [] row.append( [ "fx_glow_L_door09", "fx_glow_L_door010" ] ) row.append( [ "fx_glow_R_door09", "fx_glow_R_door010" ] ) rows.append( row ) local row = [] row.append( [ "fx_glow_L_door07", "fx_glow_L_door08" ] ) row.append( [ "fx_glow_R_door07", "fx_glow_R_door08" ] ) rows.append( row ) local row = [] row.append( [ "fx_glow_L_door05", "fx_glow_L_door06" ] ) row.append( [ "fx_glow_R_door05", "fx_glow_R_door06" ] ) rows.append( row ) local row = [] row.append( [ "fx_glow_L_door03", "fx_glow_L_door04" ] ) row.append( [ "fx_glow_R_door03", "fx_glow_R_door04" ] ) rows.append( row ) local row = [] row.append( [ "fx_glow_L_door01", "fx_glow_L_door02" ] ) row.append( [ "fx_glow_R_door01", "fx_glow_R_door02" ] ) rows.append( row ) level.trainingPodGlowLightRows = rows } // =========================== MODULE THINK FUNCTIONS =========================== function Module_Bedroom() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) ResetCabinHoloscreen() DisablePilotHud() local player = level.player local pod = level.trainingPod OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { level.player.Anim_Stop() level.player.ClearAnimViewEntity() level.player.ClearParent() level.player.UnforceStand() StopSoundOnEntity( level.player, "Amb_NPE_Cabin_Intro" ) } if ( IsValid ( level.trainingPod ) ) { level.trainingPod.Anim_Stop() thread TrainingPod_ResetLaserEmitterRotation( level.trainingPod ) thread TrainingPod_KillLasers( level.trainingPod ) thread TrainingPod_KillGlowFX( level.trainingPod ) TrainingPod_KillInteriorDLights() } if ( IsValid( level.player ) && IsValid( level.trainingPod ) ) Remote.CallFunction_Replay( level.player, "ScriptCallback_LookTargets_KillLights" ) } ) // Have to do this first so the anim starts centered on the ref attachment angles local podAttach = "REF" local attachID = pod.LookupAttachment( podAttach ) local podRefOrg = pod.GetAttachmentOrigin( attachID ) local podRefAng = pod.GetAttachmentAngles( attachID ) player.SetOrigin( podRefOrg ) player.SetAngles( podRefAng ) player.ForceStand() // default start anim starts open local viewConeFunction_start = TrainingPod_ViewConeLock_PodOpen local podAnim_start = "trainingpod_doors_open_idle" if ( level.doQuickIntro ) { // quick start anim starts closed viewConeFunction_start = TrainingPod_ViewConeLock_PodClosed podAnim_start = "trainingpod_doors_close_idle" } // start open idle local playerSequence = CreateFirstPersonSequence() playerSequence.blendTime = 0.0 playerSequence.attachment = podAttach playerSequence.firstPersonAnimIdle = "ptpov_trainingpod_idle" playerSequence.thirdPersonAnimIdle = "pt_trainingpod_idle" playerSequence.viewConeFunction = viewConeFunction_start playerSequence.renderWithViewModels = true local podSequence = CreateFirstPersonSequence() podSequence.blendTime = 0.0 podSequence.thirdPersonAnimIdle = podAnim_start podSequence.renderWithViewModels = true thread FirstPersonSequence( podSequence, pod ) thread FirstPersonSequence( playerSequence, player, pod ) if ( !level.doQuickIntro ) { TrainingPod_TurnOnInteriorDLight( "console1" ) TrainingPod_TurnOnInteriorDLight( "console2" ) //TrainingPod_TurnOnInteriorDLight( "backlight_side_L" ) //TrainingPod_TurnOnInteriorDLight( "backlight_side_R" ) } local startTime = Time() level.ent.WaitSignal( "ModuleChangeDone" ) EmitSoundOnEntity( level.player, "Amb_NPE_Cabin_Intro" ) TakeAllWeapons( player ) local minWaitEnd = -1 if ( !level.doQuickIntro ) { wait 3 local warningVOEmitterPos = level.trainingPod.GetAttachmentOrigin( level.trainingPod.LookupAttachment( "fx_lookat_top" ) ) // This unit is authorized for: military use only. EmitSoundAtPosition( warningVOEmitterPos, "diag_npeLevelmsg_pickup_01" ) wait 3.2 // line time // extra time wait 1 // Possession by an individual is a Class One felony. EmitSoundAtPosition( warningVOEmitterPos, "diag_npeLevelmsg_pickup_02" ) wait 3.2 // --- WAIT FOR BUTTON PRESS TO CLOSE --- FlagClear( "PlayerPressedUse" ) thread IntroPod_HandlePrompt() FlagWait( "PlayerPressedUse" ) minWaitEnd = 11 + Time() ForcePlayConversationToPlayer( "intro", level.player ) wait 3.25 // timed so that the "key accepted" happens after viewhand pushes buttons } if ( !level.doQuickIntro ) { // normal intro sequence local playerSequence = CreateFirstPersonSequence() playerSequence.blendTime = 0.25 playerSequence.attachment = podAttach playerSequence.firstPersonAnim = "ptpov_trainingpod_doors_close" playerSequence.firstPersonAnimIdle = "ptpov_trainingpod_idle" playerSequence.thirdPersonAnim = "pt_trainingpod_doors_close" playerSequence.thirdPersonAnimIdle = "pt_trainingpod_idle" playerSequence.viewConeFunction = TrainingPod_ViewConeLock_SemiStrict playerSequence.renderWithViewModels = true local podSequence = CreateFirstPersonSequence() podSequence.blendTime = 0.25 podSequence.thirdPersonAnim = "trainingpod_doors_close" podSequence.thirdPersonAnimIdle = "trainingpod_doors_close_idle" podSequence.renderWithViewModels = true // HACK this should be based on an anim event thread TrainingPod_KillInteriorDLights_Delayed( 2.65 ) thread FirstPersonSequence( podSequence, pod ) waitthread FirstPersonSequence( playerSequence, player, pod ) } waitthread WaittillTime( minWaitEnd ) TrainingPod_ViewConeLock_PodClosed( level.player ) // resumeChoice will have been set up before this runs based on how we are starting the level (first run, dev, or continuing) if(level.doQuickIntro) { // for *some* reason conversation isn't over at this point and i'm not 100% why, so, reset. FlagToggle("ConversationOver") if(level.titanTrainingOnly || level.resumeChoice > 9) { // Welcome back, Pilot. // Now beginning Titan training. ForcePlayConversationToPlayer( "intro_quickstart_titan", level.player ) } else { // Welcome back to Pilot certification. ForcePlayConversationToPlayer( "intro_quickstart_pilot", level.player ) } } FlagWait("ConversationOver") FlagClear("ConversationOver") if(!level.doQuickIntro) // Welcome, Pilot. ForcePlayConversationToPlayer( "intro_welcome", level.player ) FlagWait("ConversationOver") FlagClear("ConversationOver") if(level.doQuickIntro) { // Simulator initializing. ForcePlayConversationToPlayer( "intro_simulator_initializing", level.player ) } else { //wait 1.5 waitthread LookTraining() } thread TrainingPod_Interior_BootSequence() level.ent.WaitSignal( "PodInteriorSequenceDone" ) //printt( "POD SEQUENCE DONE" ) wait 1 local printstr = "bedroom intro about to increment and advance module, level.currentTrainingModule is " + level.currentTrainingModule //printt( printstr ) printtodiag( printstr + "\n" ) AdvanceToNextTrainingModule() } function IntroPod_HandlePrompt() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) OnThreadEnd( function() : () { if ( IsValid ( level.player ) ) { HideTrainingPrompt() } } ) DisplayTrainingPrompt( eTrainingButtonPrompts.START_SIM ) level.ent.WaitSignal( "PlayerPressedUse" ) EmitSoundOnEntity( level.player, "NPE_Player_Succeed" ) } function LookTraining() { // LOOKAT SECTION ForcePlayConversationToPlayer( "train_lookat", level.player ) wait 3.5 // TrainingPod_ViewConeLock_PodClosed( level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.LOOK ) // 마우스 회전축 연습만 남기고, Remote.CallFunction_Replay( level.player, "ScriptCallback_SetupLookTargets" ) wait 0.5 Remote.CallFunction_Replay( level.player, "ScriptCallback_LookTargets_WaitForLookat" ) FlagWait( "PlayerLookedAtTopTarget" ) FlagWait( "PlayerLookedAtBottomTarget" ) // 회전축 변경 팝업은 삭제 local numInverts = 0 local doConfirmMenu = false local doConfirmAudio = false while ( 1 ) { doConfirmMenu = ( numInverts > 0 ) doConfirmAudio = ( numInverts < 2 ) // Would you like to reverse the vertical look input? local askAlias = "train_lookat_askIfInvertSettingIsGood" local askWait = 2 // Y/N question is swapped on confirmation menu if ( doConfirmMenu ) { // If these look input settings are to your liking, choose 'Yes.' Otherwise, choose 'No' to reverse the look input and try again. askAlias = "train_lookat_askIfInvertSettingIsGood_verbose" askWait = 4.5 } if ( doConfirmAudio ) { ForcePlayConversationToPlayer( askAlias, level.player ) wait askWait } Remote.CallFunction_UI( level.player, "ServerCallback_ShowInvertLookMenu", doConfirmMenu ) // wait for menu input local doneSig = "PlayerClickedNoButton" local tryAgainSig = "PlayerInvertedLook" if ( doConfirmMenu ) { doneSig = "InvertSettingsConfirmed" tryAgainSig = "PlayerClickedNoButton" } local resultTable = WaitSignal( level.ent, doneSig, tryAgainSig ) local sig = resultTable.signal if ( sig == doneSig ) break numInverts++ Remote.CallFunction_Replay( level.player, "ScriptCallback_LookTargets_KillLights" ) // Please confirm your selection by looking at each of the lights again. ForcePlayConversationToPlayer( "train_lookat_confirmInvertSetting", level.player ) wait 2 TrainingPod_ViewConeLock_PodClosed( level.player ) FlagClear( "PlayerLookedAtTopTarget" ) FlagClear( "PlayerLookedAtBottomTarget" ) // I think it might be adequate to put these in here. Remote.CallFunction_Replay( level.player, "ScriptCallback_SetupLookTargets" ) wait 0.5 Remote.CallFunction_Replay( level.player, "ScriptCallback_LookTargets_WaitForLookat" ) FlagWait( "PlayerLookedAtTopTarget" ) FlagWait( "PlayerLookedAtBottomTarget" ) } // 여기까지 회전축 변경 팝업삭제. HideTrainingPrompt() TrainingPod_ViewConeLock_PodClosed( level.player ) ForcePlayConversationToPlayer( "train_lookat_pt2", level.player ) wait 2 TrainingPod_ViewConeLock_SemiStrict( level.player ) // recenter player view Remote.CallFunction_Replay( level.player, "ScriptCallback_LookTargets_KillLights" ) } function TrainingPod_InteriorFX_CommonSetup() { local pod = level.trainingPod if ( pod.s.laserEmitters.len() ) { TrainingPod_KillLasers( pod ) TrainingPod_ResetLaserEmitterRotation( pod ) } TrainingPod_KillGlowFX( pod ) //wait 1 // pause for iteration, to catch the sequence starting again } function TrainingPod_KillLasers( pod, doEndCap = false ) { foreach ( emitter in pod.s.laserEmitters ) { if ( IsValid_ThisFrame( emitter.s.fxHandle ) ) { if ( !doEndCap ) { //printt( "killing laser FX", emitter.s.fxHandle ) KillFX( emitter.s.fxHandle ) } else { //printt( "killing laser FX with endcap", emitter.s.fxHandle ) KillFXWithEndcap( emitter.s.fxHandle ) } } emitter.s.fxHandle = null } } function TrainingPod_ResetLaserEmitterRotation( pod ) { if ( !( "laserEmitters" in pod.s ) ) return foreach ( emitter in pod.s.laserEmitters ) { //reset to start position emitter.RotateTo( emitter.s.ogAng, 0.05 ) } } function TrainingPod_KillGlowFX( pod ) { foreach ( fxHandle in pod.s.glowLightFXHandles ) { if ( !IsValid_ThisFrame( fxHandle ) ) continue KillFX( fxHandle ) } pod.s.glowLightFXHandles = [] } function TrainingPod_Interior_BootSequence() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) TrainingPod_InteriorFX_CommonSetup() local pod = level.trainingPod EmitSoundOnEntity( level.player, "NPE_Scr_SimPod_PowerUp" ) // Transition screen FX thread PlayFXOnEntity_Delayed( FX_POD_SCREEN_IN, level.player, 2.35 ) // GLOW LIGHTS local lightWait = 0.015 local rowWait = 0.05 TrainingPod_GlowLightsTurnOn( lightWait, rowWait ) // LASERS local longestSweepTime = -1 foreach ( emitter in pod.s.laserEmitters ) { local sweepTime = RandomFloat( 2.9, 3.15 ) if ( sweepTime > longestSweepTime ) longestSweepTime = sweepTime thread LaserSweep( sweepTime, emitter, pod, "top" ) } wait longestSweepTime level.ent.Signal( "PodInteriorSequenceDone" ) } function TrainingPod_GlowLightsTurnOn( lightWait, rowWait ) { //local startTime = Time() local pod = level.trainingPod // light up one light on each side at a time foreach ( row in level.trainingPodGlowLightRows ) { local loopTime = Time() // assume both sides have same number of lights local numLights = row[ 0 ].len() for ( local i = 0; i < numLights; i++ ) { foreach ( side in row ) { local attachName = side[ i ] local fxHandle = PlayLoopFXOnEntity( FX_POD_GLOWLIGHT, pod, attachName ) pod.s.glowLightFXHandles.append( fxHandle ) } if ( lightWait > 0 ) wait lightWait } if ( rowWait > 0) wait rowWait } //printt( "glow lights turn on took", Time() - startTime, "secs" ) } // NOTE startPosition is actually inverted from what I think it should be. Tag orientation issue, maybe? function LaserSweep( totalTime, emitter, pod, startPosition = "bottom" ) { //local startTime = Time() level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) emitter.EndSignal( "OnDeath" ) level.ent.EndSignal( "ModuleChanging" ) emitter.s.sweepDone = false //printt( "emitter og angles:", emitter.GetAngles() ) local vecToPlayerEye = ( level.player.EyePosition() + Vector( 0, 0, 7 ) ) - emitter.GetOrigin() // eye position offset is a HACK, not sure why I need to do that here. local centerAng = VectorToAngles( vecToPlayerEye ) local topAng = centerAng + Vector( 90, 0, 0 ) local bottomAng = centerAng + Vector( -90, 0, 0 ) //local topAng = emitter.GetAngles() + Vector( 90, -8, 0 ) //local bottomAng = emitter.GetAngles() + Vector( -90, 8, 0 ) //printt( "==== starting at:", startPosition ) //printt( "topAng:", topAng ) //printt( "bottomAng:", bottomAng ) //printt( "centerAng:", centerAng ) local lastBigSweepAng if ( startPosition == "bottom") { emitter.SetAbsAngles( bottomAng ) lastBigSweepAng = bottomAng } else { emitter.SetAbsAngles( topAng ) lastBigSweepAng = topAng } //printt( "setting start angles to:", lastBigSweepAng ) local fxHandle = PlayLoopFXOnEntity( FX_POD_LASER, emitter ) emitter.s.fxHandle = fxHandle local numBigSweeps = 2 local finalCenterTime = totalTime * 0.15 local bigSweepTime = ( totalTime - finalCenterTime ) / numBigSweeps local bigSweep_AccelTime = 0 local bigSweep_DecelTime = bigSweepTime * 0.2 // do the big sweeps local nextBigSweepAng for ( local i = 0; i < numBigSweeps; i++ ) { nextBigSweepAng = topAng if ( lastBigSweepAng == topAng ) nextBigSweepAng = bottomAng //printt( "rotating to", nextBigSweepAng ) emitter.RotateTo( nextBigSweepAng, bigSweepTime, bigSweep_AccelTime, bigSweep_DecelTime ) local waitTime = bigSweepTime if ( i < numBigSweeps - 1 ) waitTime = bigSweepTime - 0.1 wait waitTime lastBigSweepAng = nextBigSweepAng } // finish with centering move //printt( "centering to", centerAng ) local finalCenter_AccelTime = 0 local finalCenter_DecelTime = finalCenterTime * 0.2 emitter.RotateTo( centerAng, finalCenterTime, finalCenter_AccelTime, finalCenter_DecelTime ) wait finalCenterTime emitter.s.sweepDone = true //printt( "laser sweep done, total time", Time() - startTime, "should have been", totalTime ) } function TrainingPod_Interior_ShutdownSequence( shutdownTime ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) TrainingPod_InteriorFX_CommonSetup() local pod = level.trainingPod // TURN ON GLOW LIGHTS TrainingPod_GlowLightsTurnOn( 0, 0 ) // TURN ON LASERS thread TrainingPod_LasersInstantOn( pod ) level.ent.WaitSignal( "TrainingPod_BeginInteriorShutdown" ) thread TrainingPod_LasersShutDown( pod, shutdownTime * 0.7 ) thread TrainingPod_GlowLightsShutDown( pod, shutdownTime ) wait shutdownTime printt( "interior shutdown done" ) } function TrainingPod_LasersInstantOn( pod ) { foreach ( emitter in pod.s.laserEmitters ) { local vecToPlayerEye = ( level.player.EyePosition() + Vector( 0, 0, 7 ) ) - emitter.GetOrigin() // eye position offset is a HACK, not sure why I need to do that here. local centerAng = VectorToAngles( vecToPlayerEye ) emitter.RotateTo( centerAng, 0.05 ) // SETANGLES DOES NOT WORK! You have to rotate it for the FX to follow. local fxHandle = PlayLoopFXOnEntity( FX_POD_LASER, emitter ) emitter.s.fxHandle = fxHandle } } function TrainingPod_LasersShutDown( pod, shutdownTime ) { level.player.EndSignal( "Teleported" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) local accelTime = shutdownTime * 0.25 local decelTime = shutdownTime * 0.1 foreach ( emitter in pod.s.laserEmitters ) { local finalAng = emitter.GetAngles() + Vector( 30, 0, 0 ) // not sure why adding pitch makes them appear to drop down. emitter.RotateTo( finalAng, shutdownTime, accelTime, decelTime ) } wait shutdownTime TrainingPod_KillLasers( pod, true ) } function TrainingPod_GlowLightsShutDown( pod, shutdownTime ) { level.player.EndSignal( "Teleported" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) // reverse the array order /* local fxHandles = [] for ( local i = ( pod.s.glowLightFXHandles.len() - 1 ); i > -1; i-- ) fxHandles.append( pod.s.glowLightFXHandles[ i ] ) */ local fxHandles = pod.s.glowLightFXHandles local timePerLight = shutdownTime / fxHandles.len() foreach ( fxHandle in fxHandles ) { if ( !IsValid_ThisFrame( fxHandle ) ) continue thread KillFXWithEndcap( fxHandle ) wait timePerLight } } function Module_Bedroom_End() { thread EmitSoundOnEntity_Delayed( level.player, "NPE_Scr_SimPod_End", 2.9 ) level.player.WaitSignal( "Teleported" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) //thread DrawEmitterArrows() Remote.CallFunction_Replay( level.player, "ServerCallback_DisableFog" ) ResetCabinHoloscreen() DisablePilotHud() local player = level.player local pod = level.trainingPod OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { level.player.Anim_Stop() level.player.ClearAnimViewEntity() level.player.ClearParent() level.player.UnforceStand() StopSoundOnEntity( level.player, "Amb_NPE_Cabin_Reveal" ) StopSoundOnEntity( level.player, "Music_NPE_Cabin_Reveal" ) StopSoundOnEntity( level.player, "NPE_Scr_SimPod_End" ) StopSoundOnEntity( level.player, "NPE_Scr_EngineSlow" ) StopSoundOnEntity( level.player, "NPE_Scr_ScreenFlickerOff" ) StopSoundOnEntity( level.player, "NPE_Scr_BlastDoorOpen" ) } if ( IsValid ( level.trainingPod ) ) { level.trainingPod.Anim_Stop() TrainingPod_KillInteriorDLights() } if ( IsValid( level.skyboxModelSpace ) ) level.skyboxModelSpace.RotateTo( level.skyboxModelSpace.s.ogAng, 0.05 ) thread ResetCabinWindowShutters() } ) EmitSoundOnEntity( level.player, "Amb_NPE_Cabin_Reveal" ) thread PlayFXOnEntity_Delayed( FX_POD_SCREEN_OUT, level.player, 0.2 ) // play screenFX here so it shows up as we exit the blackscreen local podAttach = "REF" local attachID = pod.LookupAttachment( podAttach ) local podRefOrg = pod.GetAttachmentOrigin( attachID ) local podRefAng = pod.GetAttachmentAngles( attachID ) player.SetOrigin( podRefOrg ) player.SetAngles( podRefAng ) player.ForceStand() thread TrainingPod_Interior_ShutdownSequence( 4.35 ) level.skyboxCamSpace.SetAngles( Vector( 0, 88, -30 ) ) player.SetSkyCamera( level.skyboxCamSpace ) // start closed idle local playerSequence = CreateFirstPersonSequence() playerSequence.blendTime = 0.0 playerSequence.attachment = podAttach playerSequence.firstPersonAnimIdle = "ptpov_trainingpod_idle" playerSequence.thirdPersonAnimIdle = "pt_trainingpod_idle" playerSequence.viewConeFunction = TrainingPod_ViewConeLock_PodClosed playerSequence.renderWithViewModels = true local podSequence = CreateFirstPersonSequence() podSequence.blendTime = 0.0 podSequence.thirdPersonAnimIdle = "trainingpod_doors_close_idle" podSequence.renderWithViewModels = true thread FirstPersonSequence( playerSequence, player, pod ) thread FirstPersonSequence( podSequence, pod ) // HACK reparent the emitters so they look correct, I didn't expect to have to do this TrainingPod_SnapLaserEmittersToAttachPoints() local startTime = Time() level.ent.WaitSignal( "ModuleChangeDone" ) TakeAllWeapons( player ) // time staring at inside of pod wait 1.5 ForcePlayConversationToPlayer( "outro_simulator_finished", level.player ) if ( level.doQuickOutro ) { // stage the outside of the pod to have the cabin window already open FadeCabinHoloscreen( 0 ) thread OpenCabinWindowShutters( 2, false ) thread RotateSkyboxModel() } level.ent.Signal( "TrainingPod_BeginInteriorShutdown" ) wait 2 local playerSequence = CreateFirstPersonSequence() playerSequence.blendTime = 0.25 playerSequence.attachment = podAttach playerSequence.firstPersonAnim = "ptpov_trainingpod_doors_open" playerSequence.firstPersonAnimIdle = "ptpov_trainingpod_idle" playerSequence.thirdPersonAnim = "pt_trainingpod_doors_open" playerSequence.thirdPersonAnimIdle = "pt_trainingpod_idle" playerSequence.viewConeFunction = TrainingPod_ViewConeLock_SemiStrict playerSequence.renderWithViewModels = true local podSequence = CreateFirstPersonSequence() podSequence.blendTime = 0.25 podSequence.thirdPersonAnim = "trainingpod_doors_open" podSequence.thirdPersonAnimIdle = "trainingpod_doors_open_idle" podSequence.renderWithViewModels = true thread TrainingPod_TurnOnInteriorDLights_Delayed( 1.5 ) thread FirstPersonSequence( podSequence, pod ) waitthread FirstPersonSequence( playerSequence, player, pod ) TrainingPod_ViewConeLock_PodOpen( level.player ) if ( !level.doQuickOutro ) { wait 0.5 //printt( "ENGINE START SPINNING DOWN" ) EmitSoundOnEntity( level.player, "NPE_Scr_EngineSlow" ) wait 0.2 //printt( "TURBULENCE START" ) Remote.CallFunction_Replay( level.player, "ServerCallback_Turbulence" ) wait 3 EmitSoundOnEntity( level.player, "NPE_Scr_ScreenFlickerOff" ) FadeCabinHoloscreen( 4 ) wait 1 //printt( "PA ANNOUNCE START" ) // All hands, listen up. We're 5 minutes out from Horizon Station. // Pilots, this is your stop. You got 10 minutes to collect your gear and get off my boat. ForcePlayConversationToPlayer( "cabin_PA", level.player ) wait 2 thread RotateSkyboxModel() wait 2 //printt( "MUSIC START" ) EmitSoundOnEntity( level.player, "Music_NPE_Cabin_Reveal" ) wait 1 //printt( "OPEN SHUTTERS" ) thread OpenCabinWindowShutters( 6 ) wait 7 // Welcome to the Frontier. ForcePlayConversationToPlayer( "cabin_PA_welcome", level.player ) wait 5 // Now that we've heard the money line, remember that we've seen the cinematic ending of the level Remote.CallFunction_NonReplay( level.player, "ServerCallback_SetPlayerHasFinishedTraining" ) wait 1 } else { // time to look at the cabin before fading out wait 0.5 } ScreenFadeToBlack( level.player, 2.5, 60.0 ) wait 2 MuteAll( level.player, 2 ) wait 2 if ( !NPE_DEV_TEST || ( NPE_DEV_TEST && NPE_DEV_RETURN_TO_LOBBY ) ) ReturnToLobby() else level.ent.WaitSignal( "ModuleChanging" ) } function ResetCabinHoloscreen() { Remote.CallFunction_Replay( level.player, "ServerCallback_ResetHoloscreen" ) } function FadeCabinHoloscreen( fadeTime ) { Remote.CallFunction_Replay( level.player, "ServerCallback_FadeHoloscreen", fadeTime ) } function RotateSkyboxModel( yawRotateDist = -45, rotateTime = 30 ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.Signal( "StopSkyRotation" ) level.ent.EndSignal( "StopSkyRotation" ) OnThreadEnd( function() : () { if ( IsValid( level.skyboxModelSpace ) ) level.skyboxModelSpace.RotateTo( level.skyboxModelSpace.s.ogAng, 0.05 ) } ) local currAng = level.skyboxModelSpace.GetAngles() local newAng = currAng + Vector( 0, yawRotateDist, 0 ) level.skyboxModelSpace.RotateTo( newAng, rotateTime, 0, 0 ) wait rotateTime } function OpenCabinWindowShutters( totalMoveTime, doSound = true ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) local timePerMove = totalMoveTime.tofloat() / level.cabinWindowShutters.len().tofloat() local accelTime = timePerMove * 0.2 local decelTime = timePerMove * 0.1 local moveY = -6 local moveZ = 26 if ( doSound ) thread EmitSoundOnEntity_Delayed( level.player, "NPE_Scr_BlastDoorOpen", 0.25 ) foreach ( idx, shutter in level.cabinWindowShutters ) { if ( idx == level.cabinWindowShutters.len() - 1 ) moveZ = 12 local movePos = shutter.GetOrigin() + Vector( 0, moveY, moveZ ) shutter.MoveTo( movePos, timePerMove, accelTime, decelTime ) wait timePerMove if ( idx < ( level.cabinWindowShutters.len() - 1 ) ) shutter.SetParent( level.cabinWindowShutters[ idx + 1 ] ) } printt( "cabin window shutters opened" ) } function ResetCabinWindowShutters() { foreach ( shutter in level.cabinWindowShutters ) { shutter.MoveTo( shutter.GetOrigin(), 0.05 ) shutter.RotateTo( shutter.GetAngles(), 0.05 ) wait 0.05 shutter.SetOrigin( shutter.s.ogPos ) shutter.SetAngles( shutter.s.ogAng ) } } function TrainingPod_ViewConeLock_Shared( player ) { player.PlayerCone_FromAnim() player.PlayerCone_SetMinYaw( -25 ) player.PlayerCone_SetMaxYaw( 25 ) player.PlayerCone_SetMinPitch( -30 ) } function TrainingPod_ViewConeLock_PodOpen( player ) { TrainingPod_ViewConeLock_Shared( player ) player.PlayerCone_SetMaxPitch( 35 ) } function TrainingPod_ViewConeLock_PodClosed( player ) { TrainingPod_ViewConeLock_Shared( player ) player.PlayerCone_SetMaxPitch( 30 ) } function TrainingPod_ViewConeLock_SemiStrict( player ) { player.PlayerCone_FromAnim() player.PlayerCone_SetMinYaw( -10 ) player.PlayerCone_SetMaxYaw( 10 ) player.PlayerCone_SetMinPitch( -10 ) player.PlayerCone_SetMaxPitch( 10 ) } function TrainingPod_ViewConeLock_Strict( player ) { player.PlayerCone_FromAnim() player.PlayerCone_SetMinYaw( 0 ) player.PlayerCone_SetMaxYaw( 0 ) player.PlayerCone_SetMinPitch( 0 ) player.PlayerCone_SetMaxPitch( 0 ) } function Module_RunAndJump() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) CloseSwapDoors( "door_walk_enter" ) CloseSwapDoors( "door_sprint_enter" ) wait 0.1 local walkDoorsSnapOpenDist = 80 local sprintDoorsSnapOpenDist = 80 DoorPair_SnapOpen( level.walkDoors, walkDoorsSnapOpenDist ) DoorPair_SnapOpen( level.sprintDoors, sprintDoorsSnapOpenDist ) local sprintLightTrigs = [ "trigger_lightswitch3", "trigger_lightswitch2", "trigger_lightswitch" ] // gotta sprint through these triggers to make the sprint lights go foreach ( trigTN in sprintLightTrigs ) { LightTrigger_Off( trigTN ) TriggerSetRequireSprint( trigTN ) } local walkLightTrigs = [ "trigger_lightswitch5", "trigger_lightswitch7", "trigger_lightswitch" ] foreach ( trigTN in walkLightTrigs ) LightTrigger_Off( trigTN ) level.ent.WaitSignal( "ModuleChangeDone" ) DisablePilotHud() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { EnablePilotHud() } } ) EnablePilotHud() waitthread MoveTraining( walkDoorsSnapOpenDist, walkLightTrigs ) wait 1 waitthread SprintTraining( sprintDoorsSnapOpenDist, sprintLightTrigs ) thread JumpTrainingVO() FlagWait( "PlayerNearJump" ) DisplayTrainingPrompt( eTrainingButtonPrompts.JUMP ) FlagWait( "PlayerPastJump" ) DisplayTrainingPrompt( eTrainingButtonPrompts.LONGJUMP ) // sprint-and-jump combo- help them out if they already forgot how to sprint local sig local numResets = 0 while ( 1 ) { sig = "" local result = WaitSignal( level.ent, "PlayerPastRunAndJump", "TeleportedPlayer" ) sig = result.signal if ( sig == "PlayerPastRunAndJump" ) { StopControllerImageHint() break } numResets++ if ( numResets % 2 == 0 ) { ForcePlayConversationToPlayer( "train_sprint_and_jump_help", level.player ) ControllerImageHint_Sprint() } } FlagWait( "PlayerPastRunAndJump" ) HideTrainingPrompt() FlagWait( "PlayerNearMantle" ) DisplayTrainingPrompt( eTrainingButtonPrompts.MANTLE ) FlagWait( "PlayerPastMantle" ) HideTrainingPrompt() level.ent.WaitSignal( "ModuleChanging" ) HideTrainingPrompt() } function JumpTrainingVO() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) // trigger flag FlagWait( "PlayerNearJump" ) ForcePlayConversationToPlayer( "train_jump", level.player ) local minWait = 2 local startTime = Time() // trigger flag FlagWait( "PlayerPastJump" ) while ( Time() < startTime + minWait ) wait 0.1 ForcePlayConversationToPlayer( "train_sprint_and_jump", level.player ) local minWaitEnd = 3 // trigger flag FlagWait( "PlayerNearMantle" ) if ( Time() < minWaitEnd ) wait ( minWaitEnd - Time() ) ForcePlayConversationToPlayer( "train_mantle", level.player ) wait 3.6 FlagWait( "PlayerPastMantle" ) ForcePlayConversationToPlayer( "nicelydone", level.player ) } function MoveTraining( walkDoorsSnapOpenDist, lightTrigs ) { local ogPos = level.player.GetOrigin() DisplayTrainingPrompt( eTrainingButtonPrompts.MOVE ) local minWaitTimeout = 2.75 + Time() ForcePlayConversationToPlayer( "train_move", level.player ) level.player.ResetIdleTimer() waitthread NagPlayerUntilPlayerMove2D( 48, "train_move_nag" ) level.player.ResetIdleTimer() if ( minWaitTimeout > Time() ) wait ( minWaitTimeout - Time() ) OpenSwapDoors( "door_walk_enter" ) DisplayTrainingPrompt( eTrainingButtonPrompts.MOVEFORWARD ) ForcePlayConversationToPlayer( "walk_through_tunnel", level.player ) local doorsCloseTime = 8 local teleOrg = Vector( -12285, -4106, 0 ) local teleAng = Vector( 0, 90, 0 ) local numResets = 0 local sig = "" local lastHelpAlias = "" while ( 1 ) { FlagClear( "PlayerPassedWalkDoors" ) FlagClear( "DoorsImpassable" ) OpenSwapDoors( "door_walk_enter" ) thread NagPlayerUntilFlag( "PlayerStartWalkSection", "walk_through_tunnel_nag", 15 ) FlagWait( "PlayerStartWalkSection" ) DoorPair_SlideClosed( level.walkDoors, doorsCloseTime, 0, "PlayerPassedWalkDoors" ) thread SetFlagWhenDoorsImpossibleToPass( level.walkDoors, "DoorsImpassable", "PlayerPassedWalkDoors" ) sig = "" // reset local result = WaitSignal( level.ent, "PlayerPassedWalkDoors", "DoorsImpassable" ) sig = result.signal if ( sig == "PlayerPassedWalkDoors" ) break numResets++ // otherwise reset so they can try again thread TeleportPlayer( teleOrg, teleAng ) wait 0.2 CloseSwapDoors( "door_walk_enter" ) thread DoorPair_SnapOpen( level.walkDoors, walkDoorsSnapOpenDist ) thread LightTriggers_Reset( lightTrigs ) foreach ( trig in lightTrigs ) LightTrigger_Off( trig ) level.player.WaitSignal( "Teleported" ) FlagClear( "PlayerStartWalkSection") if ( numResets % 2 == 0 ) { local alias if ( lastHelpAlias == "walk_through_tunnel_help1" ) alias = "walk_through_tunnel_help2" else alias = "walk_through_tunnel_help1" lastHelpAlias = alias ForcePlayConversationToPlayer( alias, level.player ) } wait 0.5 } thread DoorPair_Freeze( level.walkDoors ) Assert( !Flag( "SafeToCloseWalkDoors" ), "Expect to wait for this flag." ) // close the doors behind the player FlagWait( "SafeToCloseWalkDoors" ) DoorPair_SnapClosed( level.walkDoors ) level.player.ResetIdleTimer() HideTrainingPrompt() } function SprintTraining( sprintDoorsSnapOpenDist, lightTrigs ) { ForcePlayConversationToPlayer( "train_sprint", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.SPRINT ) wait 1.5 local doorsCloseTime = 6.5 local teleOrg = Vector( -12289, -3111, 0 ) local teleAng = Vector( 0, 90, 0 ) OnThreadEnd( function() : () { if ( IsValid( level.player ) ) StopControllerImageHint() } ) local notSprintingNagIdx = 0 local notSprintingNags = [] // To make it past this set of closing doors, you must SPRINT as you move. notSprintingNags.append( { alias = "train_sprint_verbose", aliasWait = 3 } ) // If the lights in the tunnel do not turn green, you are not sprinting. notSprintingNags.append( { alias = "train_sprint_lights_mean_sprinting", aliasWait = 4 } ) // Pilot, you are not sprinting! // Please refer to the onscreen instructions to learn how to SPRINT. notSprintingNags.append( { alias = "train_sprint_pilot_not_sprinting", aliasWait = 6 } ) local generalNagIdx = 0 local generalNags = [] // Beat the closing doors by sprinting. generalNags.append( { alias = "train_sprint_tryagain", aliasWait = 2 } ) // You must SPRINT all the way through the tunnel, from start to finish. generalNags.append( { alias = "train_sprint_fully_through_tunnel", aliasWait = 3.5 } ) // Start moving first, then start sprinting a moment later. generalNags.append( { alias = "train_sprint_help_timing", aliasWait = 3.5 } ) local numResets = 0 local sig = "" while ( 1 ) { FlagClear( "PlayerPassedSprintDoors" ) FlagClear( "PlayerNotSprintingThroughTrigger" ) FlagClear( "DoorsImpassable" ) OpenSwapDoors( "door_sprint_enter" ) // To proceed, please sprint through the tunnel. thread NagPlayerUntilFlag( "SprintDoorsStartClosing", "train_sprint_nag", 15 ) FlagWait( "SprintDoorsStartClosing" ) DoorPair_SlideClosed( level.sprintDoors, doorsCloseTime, 0, "PlayerPassedSprintDoors" ) thread SetFlagWhenDoorsImpossibleToPass( level.sprintDoors, "DoorsImpassable", "PlayerPassedSprintDoors" ) sig = "" // reset local result = WaitSignal( level.ent, "PlayerPassedSprintDoors", "PlayerNotSprintingThroughTrigger", "DoorsImpassable" ) sig = result.signal if ( sig == "PlayerPassedSprintDoors" ) break numResets++ // otherwise reset so they can try again thread TeleportPlayer( teleOrg, teleAng ) wait 0.1 CloseSwapDoors( "door_sprint_enter" ) thread DoorPair_SnapOpen( level.sprintDoors, sprintDoorsSnapOpenDist ) thread LightTriggers_Reset( lightTrigs ) foreach ( trig in lightTrigs ) LightTrigger_Off( trig ) level.player.WaitSignal( "Teleported" ) FlagClear( "SprintDoorsStartClosing") if ( numResets > 2 ) ControllerImageHint_Sprint() if ( sig == "PlayerNotSprintingThroughTrigger" ) { local alias = notSprintingNags[ notSprintingNagIdx ].alias local aliasWait = notSprintingNags[ notSprintingNagIdx ].aliasWait ForcePlayConversationToPlayer( alias, level.player ) wait aliasWait notSprintingNagIdx++ if ( notSprintingNagIdx >= notSprintingNags.len() ) notSprintingNagIdx = 0 } else { local alias = generalNags[ generalNagIdx ].alias local aliasWait = generalNags[ generalNagIdx ].aliasWait ForcePlayConversationToPlayer( alias, level.player ) wait aliasWait generalNagIdx++ if ( generalNagIdx >= generalNags.len() ) generalNagIdx = 0 } } StopControllerImageHint() DoorPair_Freeze( level.sprintDoors ) FlagWait( "SafeToCloseSprintDoors" ) DoorPair_SnapClosed( level.sprintDoors ) HideTrainingPrompt() } function Module_Wallrun() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.WaitSignal( "ModuleChangeDone" ) thread Wallrun_TrackPlayerPos() thread Wallrun_BasicVO() FlagWait ( "PlayerEnteredWallrunArea" ) thread WallrunTraining_ManagePrompts() DisplayTrainingPrompt( eTrainingButtonPrompts.WALLRUN ) local lastEarlyJumpOffVOTime = -1 local earlyJumpOffVODebounceTime = 30 local numResetsToTriggerHelperVO = 4 local gapInfo = {} gapInfo[ 0 ] <- { nagIdx = 0, numResets = 0, nags = null, firstNagPlayed = false, nagRightAway = true } gapInfo[ 1 ] <- { nagIdx = 0, numResets = 0, nags = null, firstNagPlayed = false, nagRightAway = false } gapInfo[ 2 ] <- { nagIdx = 0, numResets = 0, nags = null, firstNagPlayed = false, nagRightAway = false } gapInfo[ 3 ] <- { nagIdx = 0, numResets = 0, nags = null, firstNagPlayed = false, nagRightAway = true } gapInfo[ 0 ].nags = [] gapInfo[ 0 ].nags.append( { alias = "train_wallrun_instructions", aliasTime = 4.5 } ) //gapInfo[ 0 ].nags.append( { alias = "train_wallrun_jump1_help1", aliasTime = 2.7 } ) //gapInfo[ 0 ].nags.append( { alias = "train_wallrun_jump1_help2", aliasTime = 3 } ) //gapInfo[ 0 ].nags.append( { alias = "train_wallrun_instructions", aliasTime = 4.5 } ) gapInfo[ 1 ].nags = [] gapInfo[ 1 ].nags.append( { alias = "train_wallrun_jump2_help1", aliasTime = 5.2 } ) gapInfo[ 1 ].nags.append( { alias = "train_wallrun_jump2_help2", aliasTime = 3.0 } ) gapInfo[ 1 ].nags.append( { alias = "train_wallrun_jump2_help3", aliasTime = 8.5 } ) gapInfo[ 1 ].nags.append( { alias = "train_wallrun_jump2_help4", aliasTime = 4.5 } ) gapInfo[ 1 ].nags.append( { alias = "train_wallrun_instructions_withjump", aliasTime = 7.7 } ) gapInfo[ 2 ].nags = [] gapInfo[ 2 ].nags.append( { alias = "train_wallrun_jump3_help1", aliasTime = 5.0 } ) gapInfo[ 2 ].nags.append( { alias = "train_wallrun_jump3_help2", aliasTime = 7.0 } ) gapInfo[ 2 ].nags.append( { alias = "train_wallrun_instructions_withjump", aliasTime = 7.7 } ) gapInfo[ 3 ].nags = [] gapInfo[ 3 ].nags.append( { alias = "train_wallrun_mantle", aliasTime = 7 } ) gapInfo[ 3 ].nags.append( { alias = "train_wallrun_instructions_withjump", aliasTime = 7.7 } ) while ( 1 ) { FlagClear( "ShortWallrunDetected" ) level.player.WaitSignal( "Teleported" ) wait 0.1 // make sure the player position refreshes if ( Flag( "DoingBasicWallrunVO" ) ) continue local wallrunPlayerPos = level.wallrunPlayerPos printt( "player position is:", wallrunPlayerPos ) local infoIdx = wallrunPlayerPos local wentBackwards = level.wallrunPlayerPos < level.previousWallrunPlayerPos if ( wentBackwards ) { printt( "player went backwards" ) gapInfo[ infoIdx ].numResets = 0 // player went backwards- set the reset counter back to zero for this spot // set previous to current after the teleport so the next teleport will trigger a nag level.previousWallrunPlayerPos = level.wallrunPlayerPos continue // don't ever want to nag right away after the player is teleported backwards } if ( !( infoIdx in gapInfo ) ) { printt( "no gap info set up for idx", infoIdx ) continue } gapInfo[ infoIdx ].numResets++ local numResets = gapInfo[ infoIdx ].numResets local nags = gapInfo[ infoIdx ].nags if ( Flag( "ShortWallrunDetected" ) && Time() - lastEarlyJumpOffVOTime >= earlyJumpOffVODebounceTime ) { FlagSet( "DoingWallrunHelperVO" ) ForcePlayConversationToPlayer( "train_wallrun_hint_jumpingOffTooEarly", level.player ) wait 8.5 FlagClear( "DoingWallrunHelperVO" ) lastEarlyJumpOffVOTime = Time() } else if ( nags != null ) { local nagRightAway = gapInfo[ infoIdx ].nagRightAway local doNag = numResets >= numResetsToTriggerHelperVO if ( nagRightAway && !gapInfo[ infoIdx ].firstNagPlayed ) { doNag = true gapInfo[ infoIdx ].firstNagPlayed = true } if ( doNag ) { local nagIdx = gapInfo[ infoIdx ].nagIdx local alias = nags[ nagIdx ].alias local aliasTime = nags[ nagIdx ].aliasTime FlagSet( "DoingWallrunHelperVO" ) ForcePlayConversationToPlayer( alias, level.player ) wait aliasTime FlagClear( "DoingWallrunHelperVO" ) nagIdx++ if ( nagIdx == nags.len() ) nagIdx = 0 gapInfo[ infoIdx ].nagIdx = nagIdx gapInfo[ infoIdx ].numResets = 0 } } } HideTrainingPrompt() } function Wallrun_BasicVO() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) waitthread Wallrun_BasicVOLine( "train_wallrun", 6 ) FlagWait ( "PlayerEnteredWallrunArea" ) //waitthread Wallrun_BasicVOLine( "train_wallrun_instructions", 4 ) waitthread Wallrun_BasicVOLine( "train_wallrun_jump1_help1", 2.7 ) FlagWait( "PlayerReachedWallrunPlatform3" ) waitthread Wallrun_BasicVOLine( "train_wallrun_3", 7.5 ) FlagWait( "PlayerReachedWallrunEnd" ) waitthread Wallrun_BasicVOLine( "welldone", 2.0 ) } function Wallrun_BasicVOLine( alias, aliasTime ) { FlagWaitClear( "DoingWallrunHelperVO" ) FlagSet( "DoingBasicWallrunVO" ) OnThreadEnd( function() : () { if ( IsValid( level.player ) ) FlagClear( "DoingBasicWallrunVO" ) } ) ForcePlayConversationToPlayer( alias, level.player ) wait aliasTime } function Wallrun_TrackPlayerPos() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) // reset to base values level.wallrunPlayerPos = -1 level.previousWallrunPlayerPos = -1 local refreshTime = 0 local playerPos = -1 while ( 1 ) { wait refreshTime playerPos = -1 foreach ( idx, trig in level.wallrunPlatformTrigs ) { if ( trig.IsTouching( level.player ) ) { playerPos = idx break } } if ( playerPos == -1 ) continue if ( level.wallrunPlayerPos != playerPos ) { level.previousWallrunPlayerPos = level.wallrunPlayerPos level.wallrunPlayerPos = playerPos //printt( "playerpos:", level.wallrunPlayerPos, "previousPos:", level.previousWallrunPlayerPos ) } } } function WallrunTraining_ManagePrompts( endFlag = null ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) if ( endFlag ) level.ent.EndSignal( endFlag ) OnThreadEnd( function() : () { HideTrainingPrompt() } ) local wallrunTooShortTime = 0.25 local wallTimeBeforeJumpPrompt = 1.1 local currentPrompt = null local wallrunStartTime = -1 local wallrunDone = true while ( 1 ) { wait 0 if ( !level.player.IsWallRunning() && wallrunStartTime != -1 && !wallrunDone ) { local wallrunTime = Time() - wallrunStartTime printt( "wallrun time:", wallrunTime ) wallrunDone = true if ( wallrunTime <= wallrunTooShortTime && !Flag( "PlayerPressedJump" ) ) printt( "no player jump input detected during very short wallrun- false positive" ) if ( wallrunTime <= wallrunTooShortTime && Flag( "PlayerPressedJump" ) ) { printt( "very short wallrun" ) FlagSet( "ShortWallrunDetected" ) } } // if player is near the exit room, hide the prompt if ( ( level.wallrunPlayerPos > 3 ) ) { if ( currentPrompt != null ) { currentPrompt = null HideTrainingPrompt() } } else { if ( level.player.IsOnGround() && !level.player.IsWallRunning() && currentPrompt != eTrainingButtonPrompts.WALLRUN ) { FlagClear( "PlayerPressedJump" ) wallrunStartTime = -1 wallrunDone = false currentPrompt = eTrainingButtonPrompts.WALLRUN DisplayTrainingPrompt( currentPrompt ) } else if ( level.player.IsWallRunning() ) { // just started if ( wallrunStartTime == -1 ) { wallrunStartTime = Time() printt( "started wallrun at", wallrunStartTime ) } // now running along wall before jump off point else if ( Time() - wallrunStartTime < wallTimeBeforeJumpPrompt && currentPrompt != eTrainingButtonPrompts.WALLRUN_EXTEND ) { currentPrompt = eTrainingButtonPrompts.WALLRUN_EXTEND DisplayTrainingPrompt( currentPrompt ) } // time to think about jumping off else if ( Time() - wallrunStartTime >= wallTimeBeforeJumpPrompt && currentPrompt != eTrainingButtonPrompts.WALLRUN_DETACH ) { currentPrompt = eTrainingButtonPrompts.WALLRUN_DETACH DisplayTrainingPrompt( currentPrompt ) } // player detached from wall after jump prompt appeared else if ( !level.player.IsWallRunning() && Time() - wallrunStartTime >= wallTimeBeforeJumpPrompt && currentPrompt != null ) { printt( "detached from wall" ) currentPrompt = null HideTrainingPrompt() } } } } } function Module_Wallrun_Playground() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.WaitSignal( "ModuleChangeDone" ) ForcePlayConversationToPlayer( "train_wallrun_playground", level.player ) //"WallrunPlayground_BonusEval", "WallrunPlayground_HighRoad_1", "WallrunPlayground_HighRoad_2", "WallrunPlayground_HighRoad_Fail" // "WallrunPlayground_LowRoad_1", "WallrunPlayground_LowRoad_2" // bonus line eval local numResets = 0 while ( 1 ) { FlagClear( "WallrunPlayground_BonusEval" ) FlagClear( "WallrunPlayground_LowRoad_1" ) FlagClear( "WallrunPlayground_LowRoad_2" ) local result = WaitSignal( level.ent, "WallrunPlayground_BonusEval", "TeleportedPlayer" ) local sig = result.signal if ( sig == "WallrunPlayground_BonusEval" ) break if ( sig == "TeleportedPlayer" ) numResets++ } // Completion requirements met. local alias = "requirements_met" if ( Flag( "WallrunPlayground_LowRoad_1" ) && Flag( "WallrunPlayground_LowRoad_2" ) ) { // Only a few Pilots can wallrun in tight spaces. // Your exceptional navigational abilities have been noted. alias = "bonus_wallrun_lowroad" } else if ( numResets == 0 && Flag( "WallrunPlayground_HighRoad_1" ) && Flag( "WallrunPlayground_HighRoad_2" ) && !Flag( "WallrunPlayground_HighRoad_Fail" ) ) { // Your chosen route indicates above-average navigational skills. // Excellent route, Pilot. alias = "bonus_wallrun_highroad" } ForcePlayConversationToPlayer( alias, level.player ) } function Module_Doublejump() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.WaitSignal( "ModuleChangeDone" ) wait 0.5 ForcePlayConversationToPlayer( "train_doublejump", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.DOUBLEJUMP ) wait 6.5 FlagWait( "PlayerReachedDoublejumpPlatform2" ) DisplayTrainingPrompt( eTrainingButtonPrompts.DOUBLEJUMP_FAR ) local minWaitEnd = 5.2 + Time() ForcePlayConversationToPlayer( "train_doublejump_2", level.player ) local nags = [ "train_doublejump_help_1", "train_doublejump_help_2", "train_doublejump_help_3" ] local nagIdx = 0 local sig local numResets = 0 while ( 1 ) { sig = "" local result = WaitSignal( level.ent, "PlayerPastDoubleJump2", "TeleportedPlayer" ) sig = result.signal if ( sig == "PlayerPastDoubleJump2" ) { break } numResets++ if ( numResets > 1 && numResets % 2 == 0 ) { local convAlias = nags[ nagIdx ] ForcePlayConversationToPlayer( nags[ nagIdx ], level.player ) minWaitEnd = 5 + Time() nagIdx++ if ( nagIdx == nags.len() ) nagIdx = 0 } } HideTrainingPrompt() // if player is slamming through it, don't let VO stomp if ( numResets == 0 && Time() < minWaitEnd ) wait ( minWaitEnd - Time() ) if ( !Flag( "PlayerPassedDoubleJumpCeiling" ) ) { // Double jump and mantle into the hole above to proceed. ForcePlayConversationToPlayer( "train_doublejump_ceiling", level.player ) } } function Module_Doublejump_Playground() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) local ogOrg = level.player.GetOrigin() while ( Distance( level.player.GetOrigin(), ogOrg ) <= 32 ) wait 0 local timeForBonusLine = 12 printt( "timer started" ) local startTime = Time() ForcePlayConversationToPlayer( "train_doublejump_playground", level.player ) FlagWait( "DoublejumpPlayground_PlayerEval" ) local finishTime = Time() - startTime printt( "finish time:", finishTime ) // Excellent navigational skills, Pilot. local alias = "bonus_nav_excellent" if ( finishTime <= timeForBonusLine ) { // You made very good time. // You appear quite adept at rapid environment navigation. alias = "bonus_doublejump_playground_fasttime" } ForcePlayConversationToPlayer( alias, level.player ) } function Module_Cloak() { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) local playerResetOrg = Vector( -3847, -4592, 0 ) local playerResetAng = Vector( 0, 90, 0 ) local squadIdx = 0 thread CloakArea_SpawnSentries( squadIdx ) level.player.WaitSignal( "Teleported" ) OnThreadEnd( function() : () { foreach ( sentry in level.cloakSentries ) { if ( IsAlive( sentry ) ) { ClearInvincible( sentry ) sentry.Kill() } } } ) CloseSwapDoors( "door_cloak_secondexit" ) OpenSwapDoors( "door_cloak_exit" ) level.ent.WaitSignal( "ModuleChangeDone" ) local cloakSlot = 1 level.player.GiveOffhandWeapon( "mp_ability_cloak", cloakSlot, [ "bc_long_cloak1" ] ) thread Cloak_IntroVO() thread Cloak_ManagePrompt( 3 ) local timesFailed = 0 local sig = "" while ( 1 ) { if ( timesFailed > 0 && sig != "" ) { if ( sig == "Cloak_RanIntoPlayer" ) ForcePlayConversationToPlayer( "train_cloak_ranIntoPlayer", level.player ) else if ( timesFailed % 2 == 0 ) ForcePlayConversationToPlayer( "train_cloak_failed", level.player ) } FlagClear( "CloseCloakSwapDoors" ) // in edge cases players can be seen, then quickly run into the end trigger before being reset back to the start sig = "" // reset local result = WaitSignal( level.ent, "Cloak_PlayerFound", "Cloak_RanIntoPlayer", "CloseCloakSwapDoors", "PlayerKilledAllSentries" ) sig = result.signal if ( sig == "CloseCloakSwapDoors" || sig == "PlayerKilledAllSentries" ) { // player made it clean break } else { // Help with fuzzy edge case of being spotted by last guy as player is melee killing him local stillAlive = 0 local aliveGuy = null foreach ( guy in level.cloakSentries ) { if ( !IsAlive( guy ) ) continue stillAlive++ if ( stillAlive > 1 ) break aliveGuy = guy } // if only one is still alive, that's the edge case if ( stillAlive == 1 ) { waitthread WaitForPlayerMeleeFinished() // If last guy is alive after melee, they didn't pass if ( !IsAlive( aliveGuy ) ) { break } else { printt( "single guy still alive, health is", aliveGuy.GetHealth(), "player melee state is", level.player.PlayerMelee_GetState() ) } } } // make the remaining guys invincible so a melee doesn't seem to kill them when the player really got caught foreach ( guy in level.cloakSentries ) { if ( !IsAlive( guy ) ) continue MakeInvincible( guy ) } // little break to hear guys chatter, etc. Realize what happened. local endTime = 1.5 + Time() // don't wait if I start a melee while ( Time() < endTime && level.player.PlayerMelee_GetState() == PLAYER_MELEE_STATE_NONE ) wait 0.1 waitthread WaitForPlayerMeleeFinished() // otherwise player failed, try again timesFailed++ level.ent.Signal( "CloakModuleResetting" ) DisableCloak( level.player ) EmitSoundOnEntity( level.player, "NPE_Player_Fail" ) thread TeleportPlayer( playerResetOrg, playerResetAng, true, true ) wait 0.1 thread CleanupCorpses() // respawn the guys after incrementing squad index squadIdx++ if ( squadIdx >= 10 ) squadIdx = 0 // reset it eventually, jiesang says we don't want too many unique squads thread CloakArea_SpawnSentries( squadIdx ) level.player.GetOffhandWeapon( cloakSlot ).SetNextAttackAllowedTime( Time() ) } // eval if anyone's alive here, instead of by using the signal, because time has passed since the signal that killed the loop was sent local killedAllSentries = true foreach ( guy in level.cloakSentries ) { if ( IsAlive( guy ) ) { killedAllSentries = false break } } FlagSet( "PlayerPastCloakArea" ) thread Cloak_CloseSwapDoorsWhenFinished() local reactAlias = "welldone" local reactTime = 2 if ( killedAllSentries ) { reactAlias = "train_cloak_killedSentries" reactTime = 6.5 } local minWaitEnd = reactTime + Time() HideTrainingPrompt() ForcePlayConversationToPlayer( reactAlias, level.player ) EmitSoundOnEntity( level.player, "NPE_Player_Succeed" ) foreach ( sentry in level.cloakSentries ) { if ( IsAlive( sentry ) ) { ClearInvincible( sentry ) sentry.Kill() } } level.cloakSentries = [] if ( killedAllSentries && !Flag( "CloseCloakSwapDoors" ) ) { if ( Time() < minWaitEnd ) wait minWaitEnd - Time() if ( !Flag( "CloseCloakSwapDoors" ) ) { ForcePlayConversationToPlayer( "train_cloak_proceedtoExit", level.player ) minWaitEnd = 3 + Time() } } FlagWait( "CloseCloakSwapDoors" ) if ( Time() < minWaitEnd ) wait( minWaitEnd - Time() ) // pulse the hint again since we're talking about the meter CloakHintPulse() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) StopHintPulse() } ) ForcePlayConversationToPlayer( "train_cloak_limitedtime", level.player ) wait 6 OpenSwapDoors( "door_cloak_secondexit" ) // wait til module change to clean up level.ent.WaitSignal( "ModuleChanging" ) level.player.TakeOffhandWeapon( cloakSlot ) DisableCloak( level.player ) } function Cloak_CloseSwapDoorsWhenFinished() { FlagWait( "CloseCloakSwapDoors" ) CloseSwapDoors( "door_cloak_exit" ) } function Cloak_ManagePrompt( waitTime ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( "PlayerPastCloakArea" ) wait waitTime CloakHintPulse() ControllerImageHint_OffhandDefensive() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { HideTrainingPrompt() StopHintPulse() StopControllerImageHint() } } ) local promptShowing = false while ( 1 ) { if ( IsCloaked( level.player ) && promptShowing ) { HideTrainingPrompt() StopControllerImageHint() promptShowing = false break } else if ( !IsCloaked( level.player ) && !promptShowing ) { DisplayTrainingPrompt( eTrainingButtonPrompts.CLOAK ) CloakHintPulse() ControllerImageHint_OffhandDefensive() promptShowing = true } wait 0.1 } } function Cloak_MoshPit_ManagePrompt( waitTime ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( "PlayerPastCloakArea" ) wait waitTime CloakHintPulse() ControllerImageHint_OffhandDefensive() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { HideTrainingPrompt() StopHintPulse() StopControllerImageHint() } } ) local promptShowing = false while ( 1 ) { if ( IsCloaked( level.player ) && promptShowing ) { HideTrainingPrompt() StopControllerImageHint() promptShowing = false } else if ( !IsCloaked( level.player ) && !promptShowing ) { DisplayTrainingPrompt( eTrainingButtonPrompts.CLOAK ) CloakHintPulse() ControllerImageHint_OffhandDefensive() promptShowing = true } if (Flag("MoshPit_GroundTroops_Done")) { local foundOne = false foreach ( squad in level.moshPitSquads ) { if ( squad == null ) { foundOne = true break } } if ( !foundOne ) break } wait 0.1 } } function Cloak_IntroVO() { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) ForcePlayConversationToPlayer( "train_cloak", level.player ) wait 5.5 ForcePlayConversationToPlayer( "train_cloak_pt2", level.player ) } // if we teleport players during a synced melee it won't work function WaitForPlayerMeleeFinished() { local player = level.player player.EndSignal( "OnDestroy" ) player.EndSignal( "Disconnected" ) player.EndSignal( "OnDeath" ) local meleeState = player.PlayerMelee_GetState() if ( meleeState == PLAYER_MELEE_STATE_NONE ) return Remote.CallFunction_Replay( level.player, "ServerCallback_SetFreezePlayerControls", true ) OnThreadEnd( function() : () { if ( IsValid( level.player ) ) Remote.CallFunction_Replay( level.player, "ServerCallback_SetFreezePlayerControls", false ) } ) while ( meleeState != PLAYER_MELEE_STATE_NONE ) { wait 0 meleeState = player.PlayerMelee_GetState() } } function CloakArea_SpawnSentries( squadIdx ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( "CloakModuleResetting" ) level.ent.EndSignal( "Cloak_PlayerFound" ) level.ent.EndSignal( "Cloak_RanIntoPlayer" ) level.ent.EndSignal( "PlayerPastCloakArea" ) if ( !( "cloakSentries" in level ) ) { level.cloakSentries <- [] } else { foreach ( guy in level.cloakSentries ) { if ( IsValid( guy ) ) { ClearInvincible( guy ) guy.Kill() } level.cloakSentries = [] } } local spawns = [] spawns.append( { origin = Vector( -3550, -3368, 208 ), angles = Vector( 0, -90, 0 ), anim = "pt_bored_stand_talker_A" } ) spawns.append( { origin = Vector( -3840, -3360, 208 ), angles = Vector( 0, -90, 0 ), anim = "CQB_Idle_Casual" } ) spawns.append( { origin = Vector( -4156, -3368, 208 ), angles = Vector( 0, -90, 0 ), anim = "pt_bored_stand_talker_B" } ) foreach ( spawn in spawns ) { local squadName = "cloak_squad_" + squadIdx // dudes need a new squad name because AIs being put into a squad will inherit that squad's enemy (for a certain amount of time anyway) local sentry = SpawnDumbNPC( "grunt", spawn.origin, spawn.angles, false, squadName ) sentry.StayPut( true ) sentry.SetEfficientMode( false ) sentry.Minimap_AlwaysShow( level.player.GetTeam(), level.player ) sentry.AllowHandSignals( false ) sentry.SetAISettings( "training_sentry_soldier" ) // custom AI settings so they have slightly wider vertical field of view thread PlayAnimGravity( sentry, spawn.anim, sentry ) level.cloakSentries.append( sentry ) thread CloakArea_SentryThink( sentry ) } while( 1 ) { local foundOne = false foreach ( sentry in level.cloakSentries ) { if ( IsAlive( sentry ) ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } level.ent.Signal( "PlayerKilledAllSentries" ) } function CloakArea_SentryThink( sentry ) { sentry.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( "CloakModuleResetting" ) level.ent.EndSignal( "Cloak_RanIntoPlayer" ) level.ent.EndSignal( "PlayerPastCloakArea" ) sentry.WaitSignal( "OnSeeEnemy" ) // if he's in the middle of a death anim let him keep doing it if ( IsAlive( sentry ) ) sentry.Anim_Stop() local ranIntoPlayer = false if ( Distance( level.player.GetOrigin(), sentry.GetOrigin() ) <= 72 ) { ranIntoPlayer = true //printt( "Sentry ran into player!" ) level.ent.Signal( "Cloak_RanIntoPlayer" ) } else { //printt( "Sentry found player!", sentry ) level.ent.Signal( "Cloak_PlayerFound" ) } } function Module_BasicCombat() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) OnThreadEnd( function() : () { if ( IsValid( level.player ) ) Remote.CallFunction_NonReplay( level.player, "ServerCallback_SetMeleePromptEnabled", true ) } ) // setup guys we're going to use if ( !( "meleeGuy" in level ) ) { level.meleeGuy <- null } else { if ( IsValid( level.meleeGuy ) ) level.meleeGuy.Kill() level.meleeGuy = null } CloseSwapDoors( "door_melee_enter" ) CloseSwapDoors( "door_melee_exit" ) CloseSwapDoors( "door_smartpistol_enter" ) CloseSwapDoors( "door_smartpistol_exit" ) CloseSwapDoors( "door_smartpistolpilots_enter" ) CloseSwapDoors( "door_smartpistolpilots_exit" ) level.ent.WaitSignal( "ModuleChangeDone" ) waitthread TrainMelee() waitthread TrainWeaponSwitch() Remote.CallFunction_NonReplay( level.player, "ServerCallback_SetMeleePromptEnabled", false ) wait 1 OpenSwapDoors( "door_melee_exit" ) waitthread TrainSmartPistol_Grunt() /* TEMP FOR TESTING OpenSwapDoors( "door_melee_enter" ) OpenSwapDoors( "door_melee_exit" ) OpenSwapDoors( "door_smartpistol_enter" ) OpenSwapDoors( "door_smartpistol_exit" ) TakeAllWeapons( level.player ) level.player.GiveWeapon( PILOT_WEAPON_2 ) local weapon = WaitForPlayerActiveWeapon() level.player.SetActiveWeaponPrimaryAmmoTotal( 48 ) delaythread( 1 ) RefillPlayerAmmo( level.player ) // before multitarget: Vector( -754, -3093, 390 ) // before multilock: Vector( -764.937, -1741.57, 4.68284 ) thread TeleportPlayer( Vector( -764.937, -1741.57, 4.68284 ), Vector( 0, 90, 0 ) ) */ //END TEMP waitthread TrainSmartPistol_MultiTarget() waitthread TrainSmartPistol_MultiLock() ForcePlayConversationToPlayer( "train_smart_pistol_multilock_done", level.player ) wait 2 OpenSwapDoors( "door_smartpistolpilots_exit" ) } function TrainMelee() { OnThreadEnd( function() : () { if ( IsValid( level.player ) ) StopControllerImageHint() } ) TakeAllWeapons( level.player ) level.player.GiveWeapon( PILOT_WEAPON_1 ) WaitForPlayerActiveWeapon() level.player.SetActiveWeaponPrimaryAmmoTotal( 0 ) level.player.SetActiveWeaponPrimaryAmmoLoaded( 0 ) local spawnOrg = Vector( -765.9, -3777.02, 384 ) local spawnAng = Vector( 0, 90, 0 ) level.meleeGuy = SpawnDumbNPC( "grunt", spawnOrg, spawnAng ) level.meleeGuy.SetModel( TEAM_MILITIA_ROCKET_GRUNT_MDL ) // guy with a face mask = less brutal feeling necksnap ForcePlayConversationToPlayer( "train_melee", level.player ) wait 5.5 OpenSwapDoors( "door_melee_enter" ) DisplayTrainingPrompt( eTrainingButtonPrompts.MELEE ) ForcePlayConversationToPlayer( "train_melee_nag", level.player ) ControllerImageHint_Melee() waitthread NagPlayerUntilGuysAreDead( [ level.meleeGuy ], "train_melee_nag" ) CloseSwapDoors( "door_melee_enter" ) wait 0.5 StopControllerImageHint() HideTrainingPrompt() ForcePlayConversationToPlayer( "train_melee_behind_is_safer", level.player ) wait 9.5 } function TrainWeaponSwitch() { // WEAPON SWITCH AND RELOAD TakeAllWeapons( level.player ) ForcePlayConversationToPlayer( "train_pull_weapon", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.WEAPONSWITCH ) local minWaitEnd = 3 + Time() FlagClear( "PlayerPressedWeaponSwitchButton" ) waitthread NagPlayerUntilFlag( "PlayerPressedWeaponSwitchButton", "train_pull_weapon" ) HideTrainingPrompt() level.player.GiveWeapon( PILOT_WEAPON_2 ) local weapon = WaitForPlayerActiveWeapon() SmartAmmo_Stop( weapon ) level.player.SetActiveWeaponPrimaryAmmoLoaded( 0 ) level.player.SetActiveWeaponPrimaryAmmoTotal( 0 ) FlagClear( "PlayerReloaded" ) thread GiveAmmoOnFlag( "PlayerReloaded" ) wait 0.9 // let pro players reload before prompting if ( !Flag( "PlayerReloaded" ) ) { waitthread WaittillTime( minWaitEnd ) minWaitEnd = 3 + Time() ForcePlayConversationToPlayer( "train_reload", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.RELOAD ) waitthread NagPlayerUntilFlag( "PlayerReloaded", "train_reload" ) HideTrainingPrompt() } thread RefillPlayerAmmo( level.player ) waitthread WaittillTime( minWaitEnd ) } function GiveAmmoOnFlag( flag ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) FlagWait( flag ) level.player.SetActiveWeaponPrimaryAmmoTotal( 48 ) } function TrainSmartPistol_Grunt() { local weapon = WaitForPlayerActiveWeapon() SmartAmmo_Stop( weapon ) waitthread SpawnSmartPistolGrunt() // don't target this guy with smart ammo until we say so level.smartPistolGuy.SetNoTarget( true ) level.smartPistolGuy.SetNoTargetSmartAmmo( true ) ForcePlayConversationToPlayer( "train_smart_pistol", level.player ) wait 4 ForcePlayConversationToPlayer( "train_smart_pistol_2", level.player ) wait 8.5 ForcePlayConversationToPlayer( "train_smart_pistol_reminder", level.player ) wait 2 DisplayTrainingPrompt( eTrainingButtonPrompts.FIREPRIMARY ) local teleOrg = Vector( -768, -3479, 390 ) local teleAng = Vector( 0, 90, 0 ) while ( 1 ) { thread MultiLock_DetectPlayerResult( weapon, level.smartPistolGuy, 1 ) thread MultiLock_DetectTargetWasMeleed( level.smartPistolGuy ) OpenSwapDoors( "door_smartpistol_enter" ) level.smartPistolGuy.SetNoTarget( false ) level.smartPistolGuy.SetNoTargetSmartAmmo( false ) wait 0.35 SmartAmmo_Start( weapon ) FlagClear( "PlayerPassedMultiLock" ) FlagClear( "PlayerFailedMultiLock" ) FlagClear( "MultiLock_TargetWasMeleed" ) local sig = "" local result = WaitSignal( level.ent, "PlayerPassedMultiLock", "PlayerFailedMultiLock", "MultiLock_TargetWasMeleed" ) sig = result.signal if ( Flag( "PlayerPassedMultiLock" ) ) break CloseSwapDoors( "door_smartpistol_enter" ) waitthread WaitForPlayerMeleeFinished() SmartAmmo_Stop( weapon ) thread TeleportPlayer( teleOrg, teleAng, true, true ) wait 0.1 CleanupCorpses() // do this manually here before threading the spawn, it takes longer on cloud servers to spawn the guy sometimes if ( IsAlive( level.smartPistolGuy ) ) level.smartPistolGuy.Kill() thread SpawnSmartPistolGrunt() local minWaitEnd = 0.2 + Time() while ( !IsAlive( level.smartPistolGuy ) ) wait 0 if ( Time() < minWaitEnd ) wait minWaitEnd - Time() local nagAlias = "train_smart_pistol_multilock_reminder_2" local lineWait = 4 if ( Flag( "MultiLock_TargetWasMeleed" ) ) { nagAlias = "train_smart_pistol_reminder" lineWait = 2 } ForcePlayConversationToPlayer( nagAlias, level.player ) wait lineWait } HideTrainingPrompt() ForcePlayConversationToPlayer( "train_smart_pistol_done", level.player ) wait 2.5 } function SpawnSmartPistolGrunt() { if ( !( "smartPistolGuy" in level ) ) { level.smartPistolGuy <- null } else { if ( IsValid( level.smartPistolGuy ) ) level.smartPistolGuy.Kill() level.smartPistolGuy = null } local spawnOrg = Vector( -765.9, -3105.02, 384 ) local spawnAng = Vector( 0, 90, 0 ) level.smartPistolGuy = SpawnDumbNPC( "grunt", spawnOrg, spawnAng ) level.smartPistolGuy.StayPut( true ) } function TrainSmartPistol_MultiTarget() { ForcePlayConversationToPlayer( "train_smart_pistol_multitarget", level.player ) wait 3 local swapDoors = "door_smartpistol_exit" local teleOrg = Vector( -766, -3065, 400 ) local teleAng = Vector( 0, 90, 0 ) local numResets = 0 while ( 1 ) { waitthread Spawn_SmartPistolMultiTargets() OpenSwapDoors( swapDoors ) // trigger flag wait FlagWait( "PlayerNearMultikillSpot" ) CloseSwapDoors( "door_melee_exit" ) CloseSwapDoors( "door_smartpistol_enter" ) if ( numResets == 0 ) ForcePlayConversationToPlayer( "train_smart_pistol_multitarget_nag", level.player ) FlagClear( "NotKilledUsingSmartPistol" ) thread MultiTarget_DetectPlayerResult() local sig = "" local result = WaitSignal( level.ent, "SmartPistolMultiTargetsDead", "PlayerFailedMultiTarget", "NotKilledUsingSmartPistol" ) sig = result.signal if ( sig == "SmartPistolMultiTargetsDead" ) break numResets++ waitthread WaitForPlayerMeleeFinished() thread TeleportPlayer( teleOrg, teleAng, true, true ) CloseSwapDoors( swapDoors ) level.player.WaitSignal( "Teleported" ) if ( Flag( "NotKilledUsingSmartPistol" ) ) { ForcePlayConversationToPlayer( "train_smart_pistol_reminder", level.player ) wait 2.25 } else if ( ( numResets == 1 || ( numResets > 2 && numResets % 2 == 0 ) ) ) { local alias = "train_smart_pistol_multitarget_nag" local waittime = 3 if ( Flag( "PlayerFailedMultiTarget" ) ) { alias = "train_smart_pistol_multitarget_2" waittime = 3 } ForcePlayConversationToPlayer( alias, level.player ) wait waittime } else { wait 1 } FlagClear( "PlayerNearMultikillSpot" ) FlagClear( "PlayerFailedMultiTarget" ) } HideTrainingPrompt() ForcePlayConversationToPlayer( "train_smart_pistol_multitarget_done", level.player ) wait 2.5 } function Spawn_SmartPistolMultiTargets() { if ( !( "smartPistolMultiGuys" in level ) ) { level.smartPistolMultiGuys <- [] } else { foreach ( guy in level.smartPistolMultiGuys ) if ( IsValid( guy ) ) guy.Kill() level.smartPistolMultiGuys = [] } local spawns = [] spawns.append( { origin = Vector( -766, -2180, 0 ), angles = Vector( 0, 90, 0 ) } ) // closest spawns.append( { origin = Vector( -896, -2040, 0 ), angles = Vector( 0, 90, 0 ) } ) // leftmost spawns.append( { origin = Vector( -640, -2040, 0 ), angles = Vector( 0, 90, 0 ) } ) // rightmost spawns.append( { origin = Vector( -768, -1912, 0 ), angles = Vector( 0, 90, 0 ) } ) // farthest foreach ( spot in spawns ) level.smartPistolMultiGuys.append( SpawnDumbNPC( "grunt", spot.origin, spot.angles ) ) } function MultiTarget_DetectPlayerResult() { level.ent.Signal( "DetectPlayerFailedMultiTarget_Stop") level.ent.EndSignal( "DetectPlayerFailedMultiTarget_Stop" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) Assert( level.smartPistolMultiGuys.len() == 4 ) local weapon = level.player.GetActiveWeapon() Assert( weapon ) local lockedAllTargets = false local numDead while ( 1 ) { level.player.WaitSignal( "OnPrimaryAttack" ) local targs = weapon.SmartAmmo_GetTargets() if ( targs.len() == level.smartPistolMultiGuys.len() ) lockedAllTargets = true numDead = 0 foreach ( guy in level.smartPistolMultiGuys ) { if ( !IsAlive( guy ) ) { numDead++ } } if ( numDead > 0 ) break } // time for the pistol to fire four shots wait 1.0 // re-evaluate numDead = 0 foreach ( guy in level.smartPistolMultiGuys ) { if ( !IsAlive( guy ) ) numDead++ } if ( numDead < 4 || !lockedAllTargets ) { //printt( "Multitarget failed") FlagSet( "PlayerFailedMultiTarget" ) } else { //printt( "Multitarget success") FlagSet( "SmartPistolMultiTargetsDead" ) } } function TrainSmartPistol_MultiLock() { local swapDoors = "door_smartpistolpilots_enter" local teleOrg = Vector( -766, -1742, 0 ) local teleAng = Vector( 0, 90, 0 ) local t = {} t.weapon <- null OnThreadEnd( function() : ( t ) { if ( ( "multilockTargetGuy" in level ) && IsAlive( level.multilockTargetGuy ) ) { printt( "level.multilockTargetGuy is still alive, killing him" ) level.multilockTargetGuy.Kill() } if ( IsValid( t.weapon ) ) thread TrainSmartPistol_MultiLock_Cleanup( t.weapon ) } ) // trigger flag wait FlagWait( "PlayerNearMultiLockSpot" ) waitthread SmartPistol_SpawnMultiLockTarget() // Time can pass after a waitthread if ( !( "multilockTargetGuy" in level ) ) return if ( !IsAlive( level.multilockTargetGuy ) ) return level.multilockTargetGuy.SetNoTarget( true ) level.multilockTargetGuy.SetNoTargetSmartAmmo( true ) CloseSwapDoors( "door_smartpistol_exit" ) local weapon = WaitForPlayerActiveWeapon() weapon.SetMods( [ "grunts_emulate_pilot_multilock" ] ) SmartAmmo_Stop( weapon ) weapon.EndSignal( "OnDestroy" ) t.weapon = weapon local numResets = 0 while ( 1 ) { FlagClear( "PlayerPassedMultiLock" ) FlagClear( "PlayerFailedMultiLock" ) FlagClear( "MultiLock_TargetWasMeleed" ) if ( numResets == 0 ) { ForcePlayConversationToPlayer( "train_smart_pistol_multilock", level.player ) wait 6 ForcePlayConversationToPlayer( "train_smart_pistol_multilock_nag", level.player ) } OpenSwapDoors( swapDoors ) // defensive fix against phone_home errors if ( !IsAlive( level.multilockTargetGuy ) ) return level.multilockTargetGuy.SetNoTarget( false ) level.multilockTargetGuy.SetNoTargetSmartAmmo( false ) wait 0.35 SmartAmmo_Start( weapon ) // defensive fix against phone_home errors if ( !IsAlive( level.multilockTargetGuy ) ) return thread MultiLock_DetectPlayerResult( weapon, level.multilockTargetGuy, 3 ) thread MultiLock_DetectTargetWasMeleed( level.multilockTargetGuy ) local sig = "" local result = WaitSignal( level.ent, "PlayerPassedMultiLock", "PlayerFailedMultiLock", "MultiLock_TargetWasMeleed" ) sig = result.signal if ( Flag( "PlayerPassedMultiLock" ) ) break numResets++ waitthread WaitForPlayerMeleeFinished() SmartAmmo_Stop( weapon ) thread TeleportPlayer( teleOrg, teleAng, true, true ) wait 0.2 CloseSwapDoors( swapDoors ) CleanupCorpses() waitthread SmartPistol_SpawnMultiLockTarget() // Wait for the weapon to finish the lockon process before pulling the trigger. //"train_smart_pistol_multilock_reminder_2" // Kill the Pilot with one trigger pull by waiting for multiple locks. local alias = "train_smart_pistol_multilock_reminder_1" local waitTime = 3.5 if ( sig == "MultiLock_TargetWasMeleed" ) { alias = "train_smart_pistol_reminder" waitTime = 2.5 } ForcePlayConversationToPlayer( alias, level.player ) wait waitTime } } function TrainSmartPistol_MultiLock_Cleanup( weapon ) { weapon.EndSignal( "OnDestroy" ) // don't take the mod until the multilock burstfire is done while ( weapon.IsBurstFireInProgress() ) wait 0 weapon.SetMods( [] ) } function SmartPistol_SpawnMultiLockTarget() { if ( !( "multilockTargetGuy" in level ) ) { level.multilockTargetGuy <- null } else { if ( IsAlive( level.multilockTargetGuy ) ) level.multilockTargetGuy.Kill() level.multilockTargetGuy = null } local spawnOrg = Vector( -766, -1402, 0 ) local spawnAng = Vector( 0, 90, 0 ) if ( !( "multiLockAssaultPoint" in level ) ) level.multiLockAssaultPoint <- CreateStrictAssaultEnt( spawnOrg, spawnAng, 64 ) level.multilockTargetGuy = SpawnDumbNPC( "grunt", spawnOrg, spawnAng ) level.multilockTargetGuy.SetModel( TEAM_MILITIA_GRUNT_MDL ) level.multilockTargetGuy.StayPut( true ) level.multilockTargetGuy.AssaultPointEnt( level.multiLockAssaultPoint ) level.multilockTargetGuy.SetTitle( "#NPC_SIMULATED_PILOT" ) level.multilockTargetGuy.SetShortTitle( "#NPC_SIMULATED_PILOT" ) // TODO uncomment after StevenW looks at multilock firing bug //level.multilockTargetGuy.SetHealth( 300 ) //level.multilockTargetGuy.SetMaxHealth( 300 ) } function MultiLock_DetectTargetWasMeleed( target ) { level.ent.Signal( "DetectTargetWasMeleed_Stop") level.ent.EndSignal( "DetectTargetWasMeleed_Stop" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) Assert( IsAlive( target ) ) target.WaitSignal( "OnDeath" ) wait 0.1 // let the other result detect thread do its thing first if ( Flag( "PlayerPassedMultiLock" ) || Flag( "PlayerFailedMultiLock" ) ) return FlagSet( "MultiLock_TargetWasMeleed" ) } function MultiLock_DetectPlayerResult( weapon, target, numReqLocks ) { level.ent.Signal( "DetectPlayerFailedMultiTarget_Stop") level.ent.EndSignal( "DetectPlayerFailedMultiTarget_Stop" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) target.EndSignal( "OnDestroy" ) weapon.EndSignal( "OnDestroy" ) Assert( IsAlive( target ) ) local ogHealth = target.GetHealth() local numDead level.lastSmartPistolTargs = [] local t = {} t.success <- false OnThreadEnd( function() : ( t, target ) { local setFlag = "PlayerFailedMultiLock" if ( t.success || !IsValid( target ) ) // defensive- always pass if target is invalid by now setFlag = "PlayerPassedMultiLock" //printt( "setting flag:", setFlag ) FlagSet( setFlag ) } ) while ( 1 ) { level.player.WaitSignal( "OnPrimaryAttack" ) // make sure player hit the guy before checking smart ammo status if ( target.GetHealth() < ogHealth ) { local targs // for more than one lock required, we can get targets here because OnPrimaryAttack happens after first shot if ( numReqLocks > 1 ) targs = weapon.SmartAmmo_GetTargets() // otherwise we use the array that the death callback populates, because server tick rate is slow, and the weapon clears its targets before we get here else targs = level.lastSmartPistolTargs if ( !targs || !targs.len() ) { //printt( "FAILED - no smart ammo targets" ) break } else { foreach ( targ in targs ) { if ( targ.entity == target && targ.fraction >= numReqLocks ) { t.success = true break } } if ( t.success ) break } } } } function Module_FiringRange() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) if ( !( "firingRangeTargets" in level ) ) { level.firingRangeTargets <- [] } else { foreach ( targ in level.firingRangeTargets ) if ( IsValid( targ ) ) targ.Kill() level.firingRangeTargets = [] } level.ent.WaitSignal( "ModuleChangeDone" ) ForcePlayConversationToPlayer( "train_firingrange_rifleswap", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.WEAPONSWITCH ) thread NagPlayerUntilFlag( "FiringRangeWeaponSwapped", "train_firingrange_rifleswap_nag" ) level.player.GiveWeapon( PILOT_WEAPON_3 ) local weapon while ( 1 ) { weapon = WaitForPlayerActiveWeapon() if ( weapon.GetClassname() == PILOT_WEAPON_3 ) { FlagSet( "FiringRangeWeaponSwapped" ) break } wait 0.5 } thread FiringRange_ReloadChecker( weapon ) HideTrainingPrompt() thread RefillPlayerAmmo( level.player, weapon.GetClassname() ) thread FlagSetWhenPlayerADS( "PlayerADSed" ) wait 2 if ( !Flag( "PlayerADSed" ) ) { DisplayTrainingPrompt( eTrainingButtonPrompts.ADS ) ForcePlayConversationToPlayer( "train_ads", level.player ) wait 5 waitthread NagPlayerUntilFlag( "PlayerADSed", "train_ads_nag", 15 ) HideTrainingPrompt() } FlagClear( "NonHeadshot" ) FiringRange_SpawnMarvins() DisplayTrainingPrompt( eTrainingButtonPrompts.FIREPRIMARY ) thread FiringRange_HidePromptWhenMarvinDies() ForcePlayConversationToPlayer( "train_firingrange_killtargets", level.player ) waitthread NagPlayerUntilGuysAreDead( level.firingRangeTargets, "train_firingrange_killtargets", 30 ) // Targets neutralized. local alias = "train_smart_pistol_multitarget_done" local aliasTime = 2.5 /* Marvins don't have normal headshot detection (no HITGROUP_HEAD maybe?) if ( !Flag( "NonHeadshot" ) ) { // All headshots. You appear quite ready for ranged combat. alias = "bonus_firingrange_headshots" aliasTime = 5.2 } else */ if ( !Flag( "PlayerReloaded" ) ) { // All targets eliminated without a magazine swap. Your ammunition conservation has been noted. alias = "bonus_firingrange_noreload" aliasTime = 5.5 } ForcePlayConversationToPlayer( alias, level.player ) wait aliasTime AdvanceToNextTrainingModule() } function FiringRange_HidePromptWhenMarvinDies() { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) while ( 1 ) { wait 0.2 local foundOne = false foreach ( target in level.firingRangeTargets ) { if ( !IsAlive( target ) ) { foundOne = true break } } if ( foundOne ) break } HideTrainingPrompt() } function FiringRange_ReloadChecker( weapon ) { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) local weaponName = weapon.GetClassname() local lastAmmo = level.player.GetActiveWeaponPrimaryAmmoLoaded() local newWeapon local newAmmo while ( 1 ) { newWeapon = WaitForPlayerActiveWeapon() if ( newWeapon.GetClassname() != weaponName ) return newAmmo = level.player.GetActiveWeaponPrimaryAmmoLoaded() if ( newAmmo > lastAmmo ) break lastAmmo = newAmmo } FlagSet( "PlayerReloaded" ) } function FiringRange_SpawnMarvins() { local spots = [] spots.append( { origin = Vector( 1478, -2130, 0 ), angles = Vector( 0, 130, 0 ) } ) spots.append( { origin = Vector( 1624, -2095, 0 ), angles = Vector( 0, 25, 0 ) } ) spots.append( { origin = Vector( 1460, -1849, 0 ), angles = Vector( 0, 165, 0 ) } ) spots.append( { origin = Vector( 1616, -1732, 0 ), angles = Vector( 0, -35, 0 ) } ) spots.append( { origin = Vector( 1441, -1411, 0 ), angles = Vector( 0, 140, 0 ) } ) spots.append( { origin = Vector( 1586, -1320, 0 ), angles = Vector( 0, 45, 0 ) } ) foreach ( spot in spots ) { local marvin = FiringRange_SpawnMarvin( spot.origin, spot.angles ) level.firingRangeTargets.append( marvin ) } } function FlagSetWhenPlayerADS( setFlag ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) while ( level.player.GetZoomFrac() < 0.9 ) wait 0.1 FlagSet( setFlag ) } function FiringRange_SpawnMarvin( org, ang ) { local marvin = CreateEntity( "npc_marvin" ) marvin.SetOrigin( org ) marvin.SetAngles( ang ) marvin.kv.health = -1 marvin.kv.max_health = -1 marvin.kv.spawnflags = 516 // Fall to ground, Fade Corpse marvin.kv.additionalequipment = "Nothing" marvin.SetModel( MARVIN_MODEL ) DispatchSpawn( marvin, true ) marvin.SetTeam( TEAM_UNASSIGNED ) marvin.SetAimAssistAllowed( true ) marvin.SetMoveSpeedScale( 0.6 ) TakeAllJobs( marvin ) thread MarvinMeandersAround( marvin ) return marvin } function MarvinMeandersAround( marvin ) { marvin.EndSignal( "OnDeath" ) local ogPos = marvin.GetOrigin() local ogX = ogPos.x local ogY = ogPos.y local ogZ = ogPos.z local randRange = 100 local moveWaitMin = 2 local moveWaitMax = 4 local numLoops = 0 while ( 1 ) { local newX local newY newX = RandomIntRange( ogX - randRange, ogX + randRange ) newY = RandomIntRange( ogY - randRange, ogY + randRange ) local newPos = Vector( newX, newY, ogZ ) local startWait = Time() waitthread GotoOrigin( marvin, newPos ) // if they didn't move far let them loop again sooner if ( Time() - startWait >= 1.0 ) wait ( RandomFloat( moveWaitMin, moveWaitMax ) ) else if ( Time() - startWait < 0.1 ) wait 0.1 numLoops++ } } function Module_FiringRange_Grenades() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) ResetGrenadeTriggers() level.ent.WaitSignal( "ModuleChangeDone" ) AddSpawnCallback( "npc_grenade_frag", FragCanTouchTriggers ) level.player.GiveOffhandWeapon( PILOT_WEAPON_OFFHAND_OFFENSIVE, GRENADE_SLOT ) local grenadeWeapon = level.player.GetOffhandWeapon( GRENADE_SLOT ) level.grenadesThrown = 0 thread RefillOffhandAmmoUntilSignal( grenadeWeapon, "GrenadeThrowingDone", 1.0 ) ForcePlayConversationToPlayer( "train_firingrange_grenades", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.FIREGRENADE ) ControllerImageHint_OffhandOffensive() OffhandOffensiveHintPulse() thread NagPlayerUntilFlag( "PlayerThrewGrenade", "train_firingrange_grenades", 15 ) while ( 1 ) { local foundOne = false foreach ( trig in level.grenadeTrigs ) { // stop the nagging after one grenade is thrown if ( !Flag( "PlayerThrewGrenade" ) && trig.s.wasTriggered ) { StopControllerImageHint() FlagSet( "PlayerThrewGrenade" ) } if ( !trig.s.wasTriggered ) { foundOne = true break } } if ( !foundOne ) break wait 0 } FlagSet( "GrenadeThrowingDone" ) StopHintPulse() HideTrainingPrompt() local alias = "welldone" local aliasTime = 3.5 if ( level.grenadesThrown < 5 ) { // Four out of four. Nicely done. alias = "bonus_firingrange_no_grenade_misses" aliasTime = 4 } ForcePlayConversationToPlayer( alias, level.player ) wait aliasTime // Four out of four. Nicely done. //convRef = AddConversation( "bonus_firingrange_no_grenade_misses", TEAM_IMC ) level.player.TakeOffhandWeapon( GRENADE_SLOT ) AdvanceToNextTrainingModule() } function FragCanTouchTriggers( frag ) { frag.SetTouchTriggers( true ) } function Module_MoshPit() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.WaitSignal( "ModuleChangeDone" ) // ozyoon changed 4 - weapon switch and reload TakeAllWeapons( level.player ) ForcePlayConversationToPlayer( "moshpit_combat_start", level.player ) thread MoshPit_Minimap_VO() level.player.GiveWeapon(PILOT_WEAPON_2) level.player.GiveWeapon(PILOT_WEAPON_1) level.player.GiveWeapon(PILOT_WEAPON_AT) level.player.GiveOffhandWeapon( PILOT_WEAPON_OFFHAND_OFFENSIVE, GRENADE_SLOT ) if ( !( "moshPitSquads" in level ) ) level.moshPitSquads <- {} else if ( level.moshPitSquads ) { foreach ( squad in level.moshPitSquads ) { if ( !squad ) continue foreach( guy in squad ) { if ( IsAlive( guy ) ) guy.Kill() } } } ShowMinimap() if ( !( "pilotMoshPlayerDamage" in level ) ) level.pilotMoshPlayerDamage <- 0 level.moshPitSquads = {} if ( !( "moshPitTitan" in level ) ) level.moshPitTitan <- null if ( IsAlive( level.moshPitTitan ) ) level.moshPitTitan.Kill() level.moshPitTitan = null level.pilotMoshPlayerDamage = 0 AddDamageCallback( "player", ScriptCallback_PilotMoshPit_PlayerDamaged ) OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { StopControllerImageHint() if ( DamageCallbackExists( "player", ScriptCallback_PilotMoshPit_PlayerDamaged ) ) RemoveDamageCallback( "player", ScriptCallback_PilotMoshPit_PlayerDamaged ) } } ) thread RefillPlayerAmmo( level.player ) local spots = [] thread HealthSuperRegen() // 기본 전투 // P7: this is based on absolutely nothing and i fucking hate it. // hit me up if you know how to extract the exact coordinates necessary to match vanilla spots.append( CreateScriptRef( Vector( 112, 3883, 6400 ), Vector( 0, 50, 0 ) ) ) // this is probably alright spots.append( CreateScriptRef( Vector( 112, 1858, 6400 ), Vector( 0, 50, 0 ) ) ) spots.append( CreateScriptRef( Vector( 1218, 2686, 6400 ), Vector( 0, 50, 0 ) ) ) waitthread PilotMoshPit_GroundTroops(spots) // 수류탄을 이용한 전투 훈련 FlagClear("MoshPit_GroundTroops_Done") /*waitthread PilotMoshPit_Grenade() // 근접공격을 이용한 전투 훈련 spots.clear() spots.append( CreateScriptRef( Vector( 318, 2686, 6400 ), Vector( 0, 50, 0 ) ) ) FlagClear("MoshPit_GroundTroops_Done") waitthread PilotMoshPit_Melee(spots)*/ FlagSet("HealthSuperRegenEnd") waitthread PilotMoshPit_KillTitanWithAT() waitthread PilotMoshPit_TitanTraining() // wtf: ClientCommand(level.player, "startTitanMoshPitModule") FlagClear("ConversationOver") // it bugged itself somehow, what a surprise // Excellent. Combat scenario complete. ForcePlayConversationToPlayer( "moshpit_done", level.player ) FlagWait("ConversationOver") FlagClear("ConversationOver") wait 1 // not really sure if its necessary AdvanceToNextTrainingModule() } function HealthSuperRegen() { while (1) { if (Flag("HealthSuperRegenEnd")) break; level.player.SetHealth(1000) wait 0 } } function OffHintPulse() { wait 10 StopHintPulse() HideTrainingPrompt() } function ScriptCallback_PilotMoshPit_PlayerDamaged( player, damageInfo ) { local dmg = damageInfo.GetDamage() if ( dmg > 0 ) level.pilotMoshPlayerDamage += dmg // wait for all squads to spawn before training health if ( !Flag( "PilotMoshPit_AllSquadsSpawned" ) ) return local healthFrac = GetHealthFrac( level.player ) //printt( "player health frac:", healthFrac ) if ( healthFrac <= 0.49 && !Flag( "PilotHealthTrainingStarted" ) ) { thread PilotMoshPit_TrainPilotHealth() } } function PilotMoshPit_TrainPilotHealth() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) FlagSet( "TrainingPilotHealth" ) FlagSet( "PilotHealthTrainingStarted" ) // take weapons away level.ent.Signal( "StopRefillingOffhandWeapons" ) if ( "storedPilotLoadout" in level.player.s ) delete level.player.s.storedPilotLoadout StorePilotWeapons( level.player ) level.player.SetNoTarget( true ) level.player.SetNoTargetSmartAmmo( true ) thread PilotMoshPit_NPCsStandDown() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { level.player.SetNoTarget( false ) level.player.SetNoTargetSmartAmmo( false ) } } ) // in case the AT weapon hint is on screen StopControllerImageHint() local ogPrompt = level.lastTrainingPrompt DisplayTrainingPrompt( eTrainingButtonPrompts.PILOT_HEALTH ) ForcePlayConversationToPlayer( "pilot_health_training", level.player ) wait 18 RetrievePilotWeapons( level.player ) // if still in the pilot section, turn grenade weapon refills back on again if ( !Flag( "MoshPit_GroundTroops_Done" ) ) { local grenadeWeapon = level.player.GetOffhandWeapon( GRENADE_SLOT ) thread RefillOffhandAmmoUntilSignal( grenadeWeapon, "MoshPit_GroundTroops_Done" ) } if ( ogPrompt != null ) { DisplayTrainingPrompt( ogPrompt ) if ( ogPrompt == eTrainingButtonPrompts.WEAPONSWITCH_AT ) ControllerImageHint_DPad_Left() } wait 2 thread PilotMoshPit_NPCsResumeFightingPlayer() level.player.SetNoTarget( false ) level.player.SetNoTargetSmartAmmo( false ) FlagClear( "TrainingPilotHealth" ) } function PilotMoshPit_GroundTroops(spots) { printt( "waiting for squads to spawn" ) local delayIncrement = 5 foreach ( idx, spot in spots ) { spot.s.inUse <- false // needed to spawn the guys local squadName = "moshpit_squad_" + idx level.moshPitSquads[ squadName ] <- null local delay = idx * delayIncrement wait delay thread MoshPit_SpawnZiplineSquad( spot, squadName ) } OnThreadEnd( function() : () { foreach ( squad in level.moshPitSquads ) { if ( !squad ) continue foreach( guy in squad ) { if ( IsAlive( guy ) ) guy.Kill() } } } ) // wait for squads to all finish spawning while ( 1 ) { local foundOne = false foreach ( squad in level.moshPitSquads ) { if ( squad == null ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } printt( "squads spawned" ) FlagSet( "PilotMoshPit_AllSquadsSpawned" ) DisplayTrainingPrompt( eTrainingButtonPrompts.MOSHPIT_KILLGUYS ) // I don't think this nag is necessary // thread NagPlayerUntilFlag( "MoshPit_GroundTroops_Done", "train_minimap_findgrunts", 35 ) // now that everyone is spawned, get the guys and wait for death local allGuys = [] foreach (squad in level.moshPitSquads) { foreach (guy in squad) allGuys.append(guy) } local combatTimeout = 90 local combatTimeoutTime = combatTimeout + Time() while (Time() < combatTimeoutTime) { local foundOne = false foreach (guy in allGuys) { if (IsAlive(guy)) { foundOne = true break } } if (!foundOne) break wait 0.1 } if (Time() >= combatTimeoutTime) { printt( "squad killing timed out" ) foreach (guy in allGuys) { if (IsAlive(guy)) guy.Die() // do this instead of Kill so he hits the death callback and dissolves } } else printt( "player killed all squads" ) FlagSet( "MoshPit_GroundTroops_Done" ) // if we're talking about pilot health at this point don't continue til that's done FlagWaitClear( "TrainingPilotHealth" ) HideTrainingPrompt() // put this after health training is done so in that case we will clear the health training prompt // Objective complete. local alias = "objective_complete" local aliasTime = 3 if ( level.pilotMoshPlayerDamage <= 300 ) { // Minimal damage sustained during live fire exercise. Well done. alias = "bonus_moshpit_lowdamage" aliasTime = 5.5 } ForcePlayConversationToPlayer( alias, level.player ) wait aliasTime } function PilotMoshPit_Melee(spots) { FlagSet("Moshpit_Melee") printt( "waiting for squads to spawn" ) level.moshPitSquads = {} local podSpawns = [] podSpawns.append( { origin = Vector( 325, 2945, 6390 ), angles = Vector( 0, 135, 0 ) } ) foreach (idx, spawnpoint in podSpawns) { local squadName = "moshpit_droppod_squad_" + idx level.moshPitSquads[ squadName ] <- null thread MoshPit_LaunchGruntDropPod( squadName, spawnpoint ) } OnThreadEnd( function() : () { foreach ( squad in level.moshPitSquads ) { if ( !squad ) continue foreach( guy in squad ) { if ( IsAlive( guy ) ) guy.Kill() } } } ) // wait for squads to all finish spawning while ( 1 ) { local foundOne = false foreach ( squad in level.moshPitSquads ) { if ( squad == null ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } printt( "squads spawned" ) FlagSet( "PilotMoshPit_AllSquadsSpawned" ) // now that everyone is spawned, get the guys and wait for death local allGuys = [] foreach (squad in level.moshPitSquads) { foreach (guy in squad) allGuys.append(guy) } wait 3 foreach (guy in allGuys) { if (guy) guy.StopAllAction(true) } local combatTimeout = 90 local combatTimeoutTime = combatTimeout + Time() while (Time() < combatTimeoutTime) { local foundOne = false foreach (guy in allGuys) { if (IsAlive(guy)) { foundOne = true break } } if (!foundOne) break wait 0.1 } if (Time() >= combatTimeoutTime) { printt( "squad killing timed out" ) foreach (guy in allGuys) { if (IsAlive(guy)) guy.Die() // do this instead of Kill so he hits the death callback and dissolves } } else printt( "player killed all squads" ) FlagClear("Moshpit_Melee") FlagSet( "MoshPit_GroundTroops_Done" ) // if we're talking about pilot health at this point don't continue til that's done FlagWaitClear( "TrainingPilotHealth" ) HideTrainingPrompt() // put this after health training is done so in that case we will clear the health training prompt // Objective complete. local alias = "objective_complete" local aliasTime = 3 if ( level.pilotMoshPlayerDamage <= 300 ) { // Minimal damage sustained during live fire exercise. Well done. alias = "bonus_moshpit_lowdamage" aliasTime = 5.5 } ForcePlayConversationToPlayer( alias, level.player ) wait aliasTime } function PilotMoshPit_Grenade() { FlagSet("Moshpit_Grenade") printt( "waiting for squads to spawn" ) local podSpawns = [] podSpawns.append( { origin = Vector( 926, 3442, 6550 ), angles = Vector( 0, -50, 0 ) } ) podSpawns.append( { origin = Vector( 894, 2930, 6550 ), angles = Vector( 0, -90, 0 ) } ) podSpawns.append( { origin = Vector( 1406, 2930, 6400 ), angles = Vector( 0, -160, 0 ) } ) podSpawns.append( { origin = Vector( 1534, 3442, 6400 ), angles = Vector( 0, 125, 0 ) } ) podSpawns.append( { origin = Vector( 382, 3266, 6400 ), angles = Vector( 0, 30, 0 ) } ) podSpawns.append( { origin = Vector( 574, 2946, 6450 ), angles = Vector( 0, 45, 0 ) } ) podSpawns.append( { origin = Vector( 2046, 3698, 6400 ), angles = Vector( 0, 60, 0 ) } ) podSpawns.append( { origin = Vector( 1982, 3122, 6400 ), angles = Vector( 0, 75, 0 ) } ) foreach ( idx, spawnpoint in podSpawns ) { local squadName = "moshpit_droppod_squad_" + idx level.moshPitSquads[ squadName ] <- null thread MoshPit_LaunchGruntDropPod( squadName, spawnpoint ) } // wait for squads to all finish spawning while ( 1 ) { local foundOne = false foreach ( squad in level.moshPitSquads ) { if ( squad == null ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } printt( "squads spawned" ) FlagSet( "PilotMoshPit_AllSquadsSpawned" ) local allGuys = [] foreach (squad in level.moshPitSquads) { foreach( guy in squad ) allGuys.append( guy ) } local combatTimeout = 90 local combatTimeoutTime = combatTimeout + Time() while (Time() < combatTimeoutTime) { local foundOne = false local deathCount = 0 foreach (guy in allGuys) { if (!IsAlive(guy)) ++deathCount } if (deathCount >= 16) break wait 0.1 } foreach (squad in level.moshPitSquads) { if (!squad) continue foreach (guy in squad) { if (IsAlive(guy)) guy.Die() } } FlagClear("Moshpit_Grenade") FlagSet( "MoshPit_GroundTroops_Done" ) // if we're talking about pilot health at this point don't continue til that's done FlagWaitClear( "TrainingPilotHealth" ) HideTrainingPrompt() // put this after health training is done so in that case we will clear the health training prompt // Objective complete. local alias = "objective_complete" local aliasTime = 5 if (level.pilotMoshPlayerDamage <= 300) { // Minimal damage sustained during live fire exercise. Well done. alias = "bonus_moshpit_lowdamage" aliasTime = 5.5 } ForcePlayConversationToPlayer( alias, level.player ) wait aliasTime } function MoshPit_Grenade_VO() { wait 18 if (!Flag("Moshpit_Grenade")) return ForcePlayConversationToPlayer( "train_firingrange_grenades", level.player ) } function MoshPit_Melee_VO() { wait 18 if (!Flag("Moshpit_Melee")) return ForcePlayConversationToPlayer( "train_melee_nag", level.player ) } function MoshPit_TitanRodeo_VO() { while ( 1 ) { local rodeoedSoul = level.player.GetTitanSoulBeingRodeoed() if (level.player.GetTitanSoulBeingRodeoed()) { //ForcePlayConversationToPlayer("train_rodeo", level.player) break } wait 0.1 } } function MoshPit_TitanAttack_VO() { //ForcePlayConversationToPlayer( "titan_kill_drop_pod_grunts", level.player ) //wait 5 //ForcePlayConversationToPlayer( "train_titan_attack", level.player ) } function MoshPit_Minimap_VO() { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) wait 7 HighlightMinimap() // idk why it bugged here lol FlagClear("ConversationOver") ForcePlayConversationToPlayer( "train_minimap", level.player ) FlagWait("ConversationOver") FlagClear("ConversationOver") ForcePlayConversationToPlayer( "train_minimap_findgrunts", level.player ) FlagWait("ConversationOver") FlagClear("ConversationOver") StopHighlightMinimap() } function MoshPit_SpawnZiplineSquad( spot, squadName ) { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) Assert( squadName in level.moshPitSquads ) local oppTeam = GetOppositeTeam( level.player ) // time passes before the squad spawns //have to do it like this because Flag( "disable_npcs" ) is true... so we must force it... //normally we'd use Spawn_ScriptedTrackedZipLineGruntSquad, but that wants the origin and angles of the animation, which is a different position than the spawn point. local ai_type = "npc_soldier" local forced = true local dropTable = CreateZipLineSquadDropTable( oppTeam, 4, spot, squadName ) local squad = Spawn_TrackedZipLineSquad( ai_type, spot, dropTable, forced ) level.moshPitSquads[ squadName ] = squad foreach ( guy in squad ) thread MoshPit_NPC_FightPlayer( guy ) } function MoshPit_NPC_FightPlayer( guy ) { guy.Signal( "NPC_FightPlayer" ) guy.EndSignal( "NPC_FightPlayer" ) guy.EndSignal( "StandDown_Change" ) guy.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) guy.Minimap_AlwaysShow( level.player.GetTeam(), level.player ) guy.SetEnemy( level.player ) if (guy.IsSoldier()) { guy.SetEngagementDistVsWeak( 400, 1024 ) guy.SetEngagementDistVsStrong( 400, 1024 ) } local memoryRefreshTime = 5 if (guy.IsTitan()) memoryRefreshTime = 10 if (!("backupAssaultEnt" in guy.s)) { local ambushSpots = [] ambushSpots.append( { origin = Vector( -778.451, 2458.06, 6383.9 ), angles = Vector( 0, 116.989, 0 ) } ) ambushSpots.append( { origin = Vector( -1277.68, 3694.24, 6389.53 ), angles = Vector( 0, -58.9187, 0 ) } ) ambushSpots.append( { origin = Vector( -333.503, 3687.86, 6368.16 ), angles = Vector( 0, -134.101, 0 ) } ) local ambushSpot = Random( ambushSpots ) guy.s.backupAssaultEnt <- CreateStrictAssaultEnt( ambushSpot.origin, ambushSpot.angles, 450 ) } local playerIsTarget = true local lastTarget = null while (1) { if (level.moshpitStartAreaTrig.IsTouching(level.player)) playerIsTarget = false if (playerIsTarget && lastTarget != level.player) { guy.AssaultPointEnt(level.player.s.playerAssaultEnt) lastTarget = level.player } else if (!playerIsTarget && lastTarget != guy.s.backupAssaultEnt) { guy.AssaultPointEnt( guy.s.backupAssaultEnt ) lastTarget = guy.s.backupAssaultEnt } UpdateEnemyMemory(guy, level.player) wait memoryRefreshTime } } function PilotMoshPit_KillTitanWithAT() { local weapon = WaitForPlayerActiveWeapon() if ( weapon.GetClassname() != PILOT_WEAPON_AT ) { FlagClear( "FiringRangeWeaponSwapped" ) thread MoshPit_TitanCombatStartVO( "FiringRangeWeaponSwapped" ) thread NagPlayerUntilFlag( "FiringRangeWeaponSwapped", "train_firingrange_at_swap_nag" ) while ( 1 ) { local weapon = WaitForPlayerActiveWeapon() if ( weapon.GetClassname() == PILOT_WEAPON_AT ) { FlagSet( "FiringRangeWeaponSwapped" ) break } wait 0.1 } HideTrainingPrompt() StopControllerImageHint() } MoshPit_SpawnDroneTitan({ origin = Vector( 905, 3446, 6540 ), angles = Vector( 0, -130, 0 ) }) // if we started training the player on pilot health, wait for that to finish FlagWaitClear( "TrainingPilotHealth" ) ForcePlayConversationToPlayer( "train_firingrange_at_killTitan", level.player ) //ForcePlayConversationToPlayer( "moshpit_titan_at_reminder", level.player ) // CUT? thread MoshPit_TitanCombat_ManageVO( level.moshPitTitan ) thread MoshPit_TitanCombat_ManagePrompts( level.moshPitTitan ) waitthread WaitUntilGuysAreDead( [ level.moshPitTitan ] ) // if currently training player on pilot health, wait for that to finish if ( Flag( "TrainingPilotHealth" ) ) { FlagWaitClear( "TrainingPilotHealth" ) HideTrainingPrompt() } else { ForcePlayConversationToPlayer( "goodjob", level.player ) wait 1.5 } ForcePlayConversationToPlayer( "train_firingrange_at_killTitan_done", level.player ) wait 6 } function SpawnStandDownTitan(spot, team, disableShield = true) { local spawnOrg = spot.origin local spawnAng = spot.angles local oppTeam = team local alert = 0 local titan = NPE_SpawnTitan( oppTeam, spawnOrg, spawnAng, alert ) level.moshPitTitans.append( titan ) titan.s.isHotDropping <- true titan.SetTitle( "#NPC_TITAN_TRAINING" ) titan.TakeOffhandWeapon( 1 ) if (disableShield) DisableTitanShield( titan ) titan.Minimap_AlwaysShow( level.player.GetTeam(), level.player ) waitthread SuperHotDropGenericTitan( titan, spawnOrg, spawnAng ) titan.s.isHotDropping = false NPC_StandDown( titan ) } function PilotMoshPit_TitanTraining() { // it bugged again, who knows why FlagClear("ConversationOver") ForcePlayConversationToPlayer( "train_titanfall", level.player ) local minWaitEnd = 3.75 + Time() FlagWait("ConversationOver") FlagClear("ConversationOver") ForcePlayConversationToPlayer( "train_call_in_titan", level.player ) //level.player.SetNextTitanRespawnAvailable( Time() ) ForceTitanBuildComplete( level.player ) Remote.CallFunction_Replay( level.player, "ServerCallback_EnableTitanModeHUD" ) // 타이탄 호출 한번만 할수있게.. level.nv.titanAvailability = eTitanAvailability.Once DisplayTrainingPrompt( eTrainingButtonPrompts.CALL_TITAN ) ControllerImageHint_DPad_Down() thread SetFlagWhenPlayerTitanInMap( "PlayerCalledInTitan" ) waitthread NagPlayerUntilFlag( "PlayerCalledInTitan", "train_call_in_titan_nag", 15 ) HideTrainingPrompt() StopControllerImageHint() WaittillTime( minWaitEnd ) ForcePlayConversationToPlayer( "train_titanfall_lookup", level.player ) local playerTitan = GetPlayerTitanInMap( level.player ) TakeAllWeapons( playerTitan ) playerTitan.GiveWeapon( "mp_titanweapon_rocket_launcher" ) thread SetFlagWhenTitanHitsGround( playerTitan, "TitanDropped" ) FlagWait( "TitanDropped" ) DisplayTrainingPrompt( eTrainingButtonPrompts.ENTER_TITAN ) thread SetFlagWhenPlayerEntersTitan( playerTitan, "PlayerEnteredTitan" ) waitthread NagPlayerUntilFlag( "PlayerEnteredTitan", "train_titan_mountup", 20 ) // useless: thread MoshPit_TitanAttack_VO() waitthread MoshPit_PlayerMopsUpAsTitan() } function PilotMoshPit_TitanBasicCombat() { DisplayTrainingPrompt(eTrainingButtonPrompts.TITAN_OFFHAND_OFFENSIVE) local podSpawns = [] podSpawns.append( { origin = Vector( 926, 3442, 6550 ), angles = Vector( 0, -50, 0 ) } ) podSpawns.append( { origin = Vector( 894, 2930, 6550 ), angles = Vector( 0, -90, 0 ) } ) podSpawns.append( { origin = Vector( 1406, 2930, 6400 ), angles = Vector( 0, -160, 0 ) } ) podSpawns.append( { origin = Vector( 1534, 3442, 6400 ), angles = Vector( 0, 125, 0 ) } ) podSpawns.append( { origin = Vector( 382, 3266, 6400 ), angles = Vector( 0, 30, 0 ) } ) podSpawns.append( { origin = Vector( 574, 2946, 6450 ), angles = Vector( 0, 45, 0 ) } ) if ( !( "moshPitSquads" in level ) ) level.moshPitSquads <- {} foreach (idx, spawnpoint in podSpawns) { local squadName = "moshpit_droppod_squad_" + idx level.moshPitSquads[squadName] <- null thread MoshPit_LaunchGruntDropPod(squadName, spawnpoint) } OnThreadEnd( function() : () { foreach (squad in level.moshPitSquads) { if (!squad) continue foreach (guy in squad) { if (IsAlive(guy)) guy.Die() } } } ) while (1) { local foundOne = false foreach (squad in level.moshPitSquads) { if (squad == null) { foundOne = true break } } if (!foundOne) break wait 0.1 } local allGuys = [] foreach (squad in level.moshPitSquads) { foreach (guy in squad) allGuys.append(guy) } while (1) { local foundOne = false local deathCount = 0 foreach (guy in allGuys) { if (!IsAlive(guy)) ++deathCount } if (deathCount >= 16) break wait 0.1 } HideTrainingPrompt() } function MoshPit_TitanCombatStartVO( endFlag ) { level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( endFlag ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) ForcePlayConversationToPlayer( "moshpit_titan_combat_start", level.player ) wait 5 ForcePlayConversationToPlayer( "train_firingrange_at_swap", level.player ) wait 4 DisplayTrainingPrompt( eTrainingButtonPrompts.WEAPONSWITCH_AT ) ControllerImageHint_DPad_Left() } function MoshPit_TitanCombat_ManageVO( titan ) { if ( Flag( "PilotHealthTrainingStarted" ) ) { if ( !Flag( "TrainingPilotHealth" ) ) { // health training is done return } else { // wait for health training to finish FlagWaitClear( "TrainingPilotHealth" ) } } else { thread NagPlayerUntilGuysAreDead( [ titan ], "train_firingrange_at_killTitan", 40 ) FlagWait( "PilotHealthTrainingStarted" ) // wait for health training to start FlagSet( "NagFlag" ) // manually stop the nag and wait for health training to finish FlagWaitClear( "TrainingPilotHealth" ) } // turn the nags back on for AT training now that health training is done if ( IsAlive( titan ) ) thread NagPlayerUntilGuysAreDead( [ titan ], "train_firingrange_at_killTitan", 40 ) } // function MoshPit_TitanRodeo_ManagePrompts( enemyTitan ) // { // level.ent.EndSignal( "ModuleChanging" ) // level.player.EndSignal( "OnDestroy" ) // level.player.EndSignal( "Disconnected" ) // enemyTitan.EndSignal( "OnDeath" ) // OnThreadEnd( // function() : () // { // StopControllerImageHint() // // don't hide the prompt if the Titan dies while player is learning about health // if ( !Flag( "TrainingPilotHealth" ) ) // HideTrainingPrompt() // } // ) // local currentPrompt = null // while ( 1 ) // { // wait 0.2 // // don't change the prompt while talking about pilot health // if ( Flag( "TrainingPilotHealth" ) ) // continue // local rodeoedSoul = level.player.GetTitanSoulBeingRodeoed() // if ( rodeoedSoul == null ) // { // if ( currentPrompt != eTrainingButtonPrompts.TITAN_RODEO ) // { // currentPrompt = eTrainingButtonPrompts.TITAN_RODEO // DisplayTrainingPrompt( currentPrompt ) // ControllerImageHint_DPad_Left() // level.player.FreezeFireControlsOnServer() // } // } // else // { // if ( currentPrompt != eTrainingButtonPrompts.TITAN_RODEO_COMBAT ) // { // currentPrompt = eTrainingButtonPrompts.TITAN_RODEO_COMBAT // DisplayTrainingPrompt( currentPrompt ) // StopControllerImageHint() // level.player.UnfreezeFireControlsOnServer() // } // } // } // } function MoshPit_TitanCombat_ManagePrompts( enemyTitan ) { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) enemyTitan.EndSignal( "OnDeath" ) OnThreadEnd( function() : () { StopControllerImageHint() // don't hide the prompt if the Titan dies while player is learning about health if ( !Flag( "TrainingPilotHealth" ) ) HideTrainingPrompt() } ) local weapon local currentPrompt = null while ( 1 ) { wait 0.2 // don't change the prompt while talking about pilot health if ( Flag( "TrainingPilotHealth" ) ) continue weapon = level.player.GetActiveWeapon() if ( !weapon ) continue local weaponClass = weapon.GetClassname() if ( weaponClass != PILOT_WEAPON_AT && currentPrompt != eTrainingButtonPrompts.WEAPONSWITCH_AT ) { currentPrompt = eTrainingButtonPrompts.WEAPONSWITCH_AT DisplayTrainingPrompt( currentPrompt ) ControllerImageHint_DPad_Left() } else if ( weaponClass == PILOT_WEAPON_AT && currentPrompt != eTrainingButtonPrompts.ADS ) { currentPrompt = eTrainingButtonPrompts.ADS DisplayTrainingPrompt( currentPrompt ) StopControllerImageHint() } } } function SetFlagWhenPlayerTitanInMap( flag ) { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) while ( !GetPlayerTitanInMap( level.player ) ) wait 0.1 FlagSet( flag ) } function SetFlagWhenTitanHitsGround( playerTitan, setFlag ) { playerTitan.EndSignal( "OnDeath" ) // titan is killed when player becomes the titan, this can happen before the impact signal OnThreadEnd( function() : ( setFlag ) { FlagSet( setFlag ) } ) level.player.WaitSignal( "titan_impact" ) } function SetFlagWhenPlayerEntersTitan( titan, flag ) { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) while ( !level.player.IsTitan() ) wait 1 FlagSet( flag ) } function MoshPit_SpawnDroneTitan(spot, defaultWeapon = "mp_titanweapon_xo16") { local spawnOrg = spot.origin local spawnAng = spot.angles local oppTeam = GetOppositeTeam( level.player ) local alert = 0 local titan = NPE_SpawnTitan(oppTeam, spawnOrg, spawnAng, alert, false, defaultWeapon) titan.s.isHotDropping <- true level.moshPitTitan = titan titan.SetTitle( "#NPC_TITAN_TRAINING" ) titan.TakeOffhandWeapon( 1 ) DisableRodeo( titan ) DisableTitanShield( titan ) titan.Minimap_AlwaysShow( level.player.GetTeam(), level.player ) FlagSet( "DisableTitanKneelingEmbark" ) OnThreadEnd( function() : () { if ( IsValid ( level.player ) ) FlagClear( "DisableTitanKneelingEmbark" ) } ) waitthread SuperHotDropGenericTitan( titan, spawnOrg, spawnAng ) titan.s.isHotDropping = false } function PilotMoshPit_GetAllEnemies() { // not reliable to get all enemies unless the zipline squad spawning has finished Assert( Flag( "PilotMoshPit_AllSquadsSpawned" ) ) local allGuys = [] foreach ( squad in level.moshPitSquads ) { if ( !squad ) continue foreach( guy in squad ) { if ( !IsAlive( guy ) ) continue allGuys.append( guy ) } } if ( IsAlive( level.moshPitTitan ) ) allGuys.append( level.moshPitTitan ) return allGuys } function TitanMoshPit_NPCsStandDown() { foreach ( titan in level.moshPitTitans ) thread NPC_StandDown( titan ) } function TitanMoshPit_NPCsResumeFightingPlayer() { foreach ( titan in level.moshPitTitans ) { if (!titan) continue if (titan.s.isHotDropping) continue thread NPC_StandDown_Stop( titan ) } } function PilotMoshPit_NPCsStandDown() { local allGuys = PilotMoshPit_GetAllEnemies() foreach ( guy in allGuys ) thread NPC_StandDown( guy ) } function PilotMoshPit_NPCsResumeFightingPlayer() { local allGuys = PilotMoshPit_GetAllEnemies() foreach ( guy in allGuys ) { if ( !IsAlive( guy ) ) continue NPC_StandDown_Stop( guy ) if ( guy.IsTitan() ) { // AT training target Titan should still stay in place after stand down // TODO JIESANG! Titan thinks he needs to do the stance to a stand activity here which puts him in a weird looking loop thread NPE_NPCStayPut( guy ) } else if ( guy.IsSoldier() ) { thread MoshPit_NPC_FightPlayer( guy ) } } } function MoshPit_PlayerMopsUpAsTitan() { ForcePlayConversationToPlayer( "titan_controls_like_pilot", level.player ) wait 4.25 DisplayTrainingPrompt( eTrainingButtonPrompts.FIREPRIMARY ) ForcePlayConversationToPlayer( "titan_primary_fire_like_pilot", level.player ) wait 5 level.moshPitSquads = {} // reset so squads are null local podSpawns = [] podSpawns.append( { origin = Vector( -9.97231, 3632.03, 6366.88 ), angles = Vector( 0, -52.5624, 0 ) } ) podSpawns.append( { origin = Vector( 956.635, 3451.81, 6544.03 ), angles = Vector( 0, -96.4783, 0 ) } ) podSpawns.append( { origin = Vector( 1721.89, 2756.19, 6400.51 ), angles = Vector( 0, -159.951, 0 ) } ) podSpawns.append( { origin = Vector( 2114.33, 1099, 6372.17 ), angles = Vector( 0, 121.815, 0 ) } ) podSpawns.append( { origin = Vector( -431.435, 725.337, 6400.03 ), angles = Vector( 0, 28.3477, 0 ) } ) foreach ( idx, spawnpoint in podSpawns ) { local squadName = "moshpit_droppod_squad_" + idx level.moshPitSquads[ squadName ] <- null thread MoshPit_LaunchGruntDropPod( squadName, spawnpoint ) } HideTrainingPrompt() ForcePlayConversationToPlayer( "titan_kill_drop_pod_grunts", level.player ) printt( "waiting for drop pod squads to spawn" ) // wait for squads to all finish spawning while ( 1 ) { local foundOneEmpty = false foreach ( squad in level.moshPitSquads ) { if ( squad == null ) { foundOneEmpty = true break } } if ( !foundOneEmpty ) break wait 0.1 } printt( "drop pod squads spawned" ) FlagClear( "MoshPit_GroundTroops_Done" ) DisplayTrainingPrompt( eTrainingButtonPrompts.MOSHPIT_KILLGUYS ) // I don't think we need this nag //thread NagPlayerUntilFlag( "MoshPit_GroundTroops_Done", "train_minimap_findgrunts", 35 ) // now that everyone is spawned, get the guys and wait for death local allGuys = [] foreach ( squad in level.moshPitSquads ) foreach( guy in squad ) allGuys.append( guy ) local combatTimeout = 60 local combatTimeoutTime = combatTimeout + Time() while( Time() < combatTimeoutTime ) { local foundOne = false foreach ( guy in allGuys ) { if ( IsAlive( guy ) ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } if ( Time() >= combatTimeoutTime ) { printt( "squad killing timed out" ) foreach ( guy in allGuys ) if ( IsAlive( guy ) ) guy.Die() // do this instead of Kill so he hits the death callback and dissolves } else { printt( "player killed all squads" ) } HideTrainingPrompt() } function MoshPit_LaunchGruntDropPod( squadName, spawnpoint ) { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) local oppTeam = GetOppositeTeam( level.player ) Assert( squadName in level.moshPitSquads ) local squad = GruntPod_LaunchToPoint( oppTeam, squadName, spawnpoint.origin, spawnpoint.angles, SpawnGrunt ) level.moshPitSquads[ squadName ] = squad foreach ( guy in squad ) thread MoshPit_NPC_FightPlayer( guy ) } function InitMoshPitTitans() { if ( !( "moshPitTitans" in level ) ) level.moshPitTitans <- [] else { foreach ( titan in level.moshPitTitans ) { if ( !IsValid( titan ) ) continue titan.Kill() } level.moshPitTitans = [] } } function Module_BattlePractice() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) level.ent.WaitSignal( "ModuleChangeDone" ) while (level.player.s.usedLoadoutCrate == true) wait 0.1 level.player.DeployWeapon() ShowMinimap() wait 3 while (1) { waitthread BattlePractice_Step_B() waitthread BattlePractice_Step_C() waitthread BattlePractice_Step_D() waitthread BattlePractice_Step_E() } GameRules_EndMatch() } function BattlePractice_Step_B() { if ( !( "moshPitSquads" in level ) ) level.moshPitSquads <- {} else level.moshPitSquads = {} local podSpawns = [] podSpawns.append( { origin = Vector( 926, 3442, 6550 ), angles = Vector( 0, -50, 0 ) } ) foreach (idx, spawnpoint in podSpawns) { local squadName = "moshpit_droppod_squad_" + idx level.moshPitSquads[ squadName ] <- null waitthread MoshPit_LaunchGruntDropPod( squadName, spawnpoint ) } while ( 1 ) { local foundOne = false foreach ( squad in level.moshPitSquads ) { if ( squad == null ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } // 스폰완료. local allGuys = [] foreach (squad in level.moshPitSquads) { foreach (guy in squad) allGuys.append(guy) } while (1) { local foundOne = false foreach (guy in allGuys) { if (IsAlive(guy)) { foundOne = true break } } if (!foundOne) break wait 0.1 } wait 3 } function BattlePractice_Step_C() { if ( !( "moshPitTitans" in level ) ) level.moshPitTitans <- [] else level.moshPitTitans = [] local spawns = [] spawns.append({origin = Vector(876.222, 3413.73, 6590.57), angles = Vector(0, -142.022, 0)}) waitthread SpawnBattlePracticeTitans(spawns) waitthread WaitUntilGuysAreDead(level.moshPitTitans) wait 3 } function BattlePractice_Step_D() { if ( !( "moshPitSquads" in level ) ) level.moshPitSquads <- {} else level.moshPitSquads = {} local podSpawns = [] podSpawns.append( { origin = Vector( 926, 3442, 6550 ), angles = Vector( 0, -50, 0 ) } ) podSpawns.append( { origin = Vector( 894, 2930, 6550 ), angles = Vector( 0, -90, 0 ) } ) foreach (idx, spawnpoint in podSpawns) { local squadName = "moshpit_droppod_squad_" + idx level.moshPitSquads[ squadName ] <- null waitthread MoshPit_LaunchGruntDropPod( squadName, spawnpoint ) } while ( 1 ) { local foundOne = false foreach ( squad in level.moshPitSquads ) { if ( squad == null ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } // 스폰완료. local allGuys = [] foreach (squad in level.moshPitSquads) { foreach (guy in squad) allGuys.append(guy) } while (1) { local foundOne = false foreach (guy in allGuys) { if (IsAlive(guy)) { foundOne = true break } } if (!foundOne) break wait 0.1 } wait 3 } function BattlePractice_Step_E() { if ( !( "moshPitTitans" in level ) ) level.moshPitTitans <- [] else level.moshPitTitans = [] local spawns = [] spawns.append({origin = Vector(876.222, 3413.73, 6590.57), angles = Vector(0, -142.022, 0)}) spawns.append({origin = Vector(2048, 3584, 6400), angles = Vector(0, 0, 0)}) waitthread SpawnBattlePracticeTitans(spawns) waitthread WaitUntilGuysAreDead(level.moshPitTitans) wait 3 } function SpawnBattlePracticeTitan(spot) { local spawnOrg = spot.origin local spawnAng = spot.angles local oppTeam = GetOppositeTeam( level.player ) local alert = 0 local titan = NPE_SpawnTitan(oppTeam, spawnOrg, spawnAng, alert, false, "mp_titanweapon_xo16") titan.s.isHotDropping <- true titan.SetTitle( "#NPC_TITAN_TRAINING" ) titan.TakeOffhandWeapon( 1 ) titan.Minimap_AlwaysShow( level.player.GetTeam(), level.player ) FlagSet( "DisableTitanKneelingEmbark" ) waitthread SuperHotDropGenericTitan( titan, spawnOrg, spawnAng ) titan.s.isHotDropping = false FlagClear( "DisableTitanKneelingEmbark" ) level.moshPitTitans.append(titan) } function SpawnBattlePracticeTitans(spawns) { foreach (spot in spawns) thread SpawnBattlePracticeTitan(spot) while (1) { if (level.moshPitTitans.len() == spawns.len()) break wait 0.1 } } function Module_TitanDash() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) local initialDash = -1 local table = level.player.playerClassData[ "titan" ] table.liverycode <- null table.liverycolor0 <- null table.liverycolor1 <- null table.liverycolor2 <- null CloseSwapDoors("door_titan_dash_threat_start") CloseSwapDoors("door_titan_dash_threat_enter") ForcePlayConversationToPlayer( "titan_dash_speed_intro", level.player ) wait 5 ForcePlayConversationToPlayer( "titandash_dash_anydirection", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_DASH ) waitthread NagPlayerUntilFlag( "PlayerDashed", "titandash_dash_anydirection_nag", 15 ) if (!Flag( "PlayerDashed_Left" )) { ForcePlayConversationToPlayer( "titandash_left", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.DASH_LEFT ) wait 2 waitthread NagPlayerUntilFlag( "PlayerDashed_Left", "titandash_left_nag", 15 ) } HideTrainingPrompt() DashMeterHintPulse() ForcePlayConversationToPlayer( "titan_dash_meter", level.player ) wait 9 StopHintPulse() if (!Flag( "PlayerDashed_Right" )) { ForcePlayConversationToPlayer( "titandash_right", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.DASH_RIGHT ) wait 2 waitthread NagPlayerUntilFlag( "PlayerDashed_Right", "titandash_right_nag", 15 ) } if (!Flag( "PlayerDashed_Forward" )) { ForcePlayConversationToPlayer( "titandash_forward", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.DASH_FORWARD ) wait 2 waitthread NagPlayerUntilFlag( "PlayerDashed_Forward", "titandash_forward_nag", 15 ) } if (!Flag( "PlayerDashed_Back" )) { ForcePlayConversationToPlayer( "titandash_back", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.DASH_BACK ) wait 2 waitthread NagPlayerUntilFlag( "PlayerDashed_Back", "titandash_back_nag", 15 ) } ForcePlayConversationToPlayer( "goodjob", level.player ) HideTrainingPrompt() wait 2 ForcePlayConversationToPlayer( "titandash_move_forward", level.player ) OpenSwapDoors("door_titan_dash_threat_start") OpenSwapDoors("door_titan_dash_threat_enter") wait 1 CloseSwapDoors("door_titan_dash_threat_start") wait 2 ForcePlayConversationToPlayer("titan_dash_threat", level.player) wait 5 OpenSwapDoors("door_titan_dash_threat_start") local spots = [] spots.append({ origin = Vector(6650,2870,192), angles = Vector(0,-90,0) }) spots.append({ origin = Vector(6742,2870,192), angles = Vector(0,-90,0) }) spots.append({ origin = Vector(6655,2870,108), angles = Vector(0,-90,0) }) spots.append({ origin = Vector(6650,2870,108), angles = Vector(0,-90,0) }) FireRocketsUntilSignal(spots, 1000, 1, "PlayerDashThreat_Alcove1") } function Module_TitanVortex() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) ForcePlayConversationToPlayer( "titan_vortex", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_VORTEX) CloseSwapDoors("door_titan_vortex_enter") CloseSwapDoors("door_titan_vortex_exit") wait 2 level.player.GiveOffhandWeapon( TITAN_WEAPON_OFFHAND_DEFENSIVE, 1 ) DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_VORTEX_NAG) // wait for player to use the vortex shield // poll the IsVortexing function until the player is no longer vortexing while ( IsVortexing(level.player) ) wait 0.1 DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_VORTEX_STARTINGLINE) OpenSwapDoors("door_titan_vortex_enter") // spawn a titan local spawnOrg = Vector( 8428, -2345 ,124) local spawnAng = Vector( 0, 0, 0 ) local oppTeam = GetOppositeTeam( level.player ) local alert = 1 local titan = NPE_SpawnTitan( oppTeam, spawnOrg, spawnAng, alert ) titan.SetTitle( "#NPC_TITAN_TRAINING" ) DisableRodeo( titan ) // set the titan health to 0 titan.SetHealth( 1 ) while (1) { local foundOne = false if (IsAlive(titan)) { foundOne = true break } if (!foundOne) break wait 0.1 } // open the rest of the doors OpenSwapDoors("door_titan_vortex_exit") } function Module_TitanPet() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) local table = {} table.useFunc <- UseTitanPetControlPanel table.useEnt <- GetEntArrayByName_Expensive("controlpanel_target")[0] table.scope <- this AddControlPanelUseFuncTable(level.titanPetControlPanel, table) local table = level.player.playerClassData[ "titan" ] table.liverycode <- null table.liverycolor0 <- null table.liverycolor1 <- null table.liverycolor2 <- null CloseSwapDoors("door_controlpanel_enter") CloseSwapDoors("door_controlpanel_exit") CloseSwapDoors("door_titan_pet_gate") CloseSwapDoors("door_titan_pet_exit_gate") ForcePlayConversationToPlayer( "titan_pet_intro", level.player ) wait 5 EnableTitanDisembark() ForcePlayConversationToPlayer("titan_pet_disembark", level.player) DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_DISEMBARK ) level.player.WaitSignal("DisembarkingTitan") TrainingModule_GiveDefaultWeapons() OpenSwapDoors("door_controlpanel_enter") Remote.CallFunction_Replay( level.player, "ServerCallback_EnableTitanModeHUD" ) local titan = GetPlayerTitanInMap(level.player) NPCTitanNextMode(titan, level.player) ForcePlayConversationToPlayer("titan_pet_go_hack", level.player) DisplayTrainingPrompt( eTrainingButtonPrompts.MOVE_TO_CONTROL_ROOM ) // FlagWait("PlayerInsideControlRoom") DisplayTrainingPrompt( eTrainingButtonPrompts.DATA_KNIFE ) // P7: Just allow the players to advance to the next training module until i refactor these modules OpenSwapDoors("door_titan_pet_gate") OpenSwapDoors("door_controlpanel_exit") OpenSwapDoors("door_titan_pet_exit_gate") level.titanPetControlPanel.WaitSignal( "PanelReprogram_Success" ) HideTrainingPrompt() ForcePlayConversationToPlayer("titan_aimode_intro", level.player) wait 8 ForcePlayConversationToPlayer("titan_aimode_hud", level.player) TitanAIControlHintPulse() wait 5 DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_AI_MODE) ForcePlayConversationToPlayer("titan_pet_toggle_follow", level.player) titan.WaitSignal("ChangedTitanMode") //OpenSwapDoors("door_titan_pet_gate") ForcePlayConversationToPlayer("titan_pet_follow_info", level.player) FlagWait("TitanPetPassedGate") CloseSwapDoors("door_titan_pet_gate") //OpenSwapDoors("door_controlpanel_exit") ForcePlayConversationToPlayer("titan_pet_reembark", level.player) DisplayTrainingPrompt( eTrainingButtonPrompts.ENTER_TITAN ) StopHintPulse() level.player.WaitSignal("player_embarks_titan") //OpenSwapDoors("door_titan_pet_exit_gate") ForcePlayConversationToPlayer("titan_pet_exit", level.player) HideTrainingPrompt() } function UseTitanPetControlPanel(panel,ent,target) { printt("hello") // titan_aimode_intro ForcePlayConversationToPlayer("titan_aimode_intro", level.player) Remote.CallFunction_Replay( level.player, "ServerCallback_EnableTitanModeChange_Once" ) CloseSwapDoors("door_controlpanel_enter") } function Module_TitanMoshPit() { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.player.WaitSignal( "Teleported" ) local table = level.player.playerClassData[ "titan" ] table.liverycode <- null table.liverycolor0 <- null table.liverycolor1 <- null table.liverycolor2 <- null TakePassive(level.player,PAS_AUTO_EJECT) InitMoshPitTitans() level.ent.WaitSignal( "ModuleChangeDone" ) waitthread Titan_OffensiveOffhandTraining() FlagSet( "TitanMoshPitCombatStarted" ) ShowMinimap() waitthread TitanMoshPit_Combat() waitthread Titan_TrainEject() wait 1.2 printt( "TITAN MOSH PIT ALL DONE" ) // Excellent. Your Pilot combat certification is complete. ForcePlayConversationToPlayer( "pilot_cert_done", level.player ) // ======== SEND TO END MODULE ======== wait 5 EmitSoundOnEntity( level.player, "NPE_Module_Finish" ) if (GAMETYPE == "titan_tutorial") { GameRules_EndMatch() } else { level.player.SetTutorialStatus( TR_RESULT_COMPLETE ); thread StartTrainingModule( TRAINING_BEDROOM_END/*eTrainingModules.BEDROOM_END*/ ) } } function PlayerDamageCallback_TitanMoshPit( player, damageInfo ) { if ( !IsValid( player ) ) return if ( !player.IsTitan() ) return // no titanfall damage - usually causes instadeath if ( damageInfo.GetDamageSourceIdentifier() == eDamageSourceId.titan_fall ) { printt( "Titanfall damage detected, zeroing out" ) damageInfo.SetDamage( 0 ) return } // only train these concepts after mosh pit combat section starts if ( Flag( "TitanMoshPitCombatStarted" ) ) { // SHIELD TRAINING FIRST if ( !Flag( "TitanShieldTrainingStarted" ) ) { local soul = level.player.GetTitanSoul() // defensive if ( !IsValid( soul ) ) return local shieldHealth = soul.GetShieldHealth().tofloat() local shieldHealthMax = soul.GetShieldHealthMax().tofloat() local shieldFrac = shieldHealth / shieldHealthMax if ( shieldFrac <= 0.2 ) thread TitanMoshPit_TrainTitanConcept( "shields" ) } // HEALTH TRAINING ONLY HAPPENS AFTER SHIELD TRAINING else if ( Flag( "TitanShieldTrainingStarted" ) && !Flag( "TrainingTitanShields" ) && !Flag( "TitanHealthTrainingStarted" ) ) { local healthFrac = GetHealthFrac( level.player ) if ( healthFrac <= 0.75 ) thread TitanMoshPit_TrainTitanConcept( "health" ) } } if ( !level.player.GetDoomedState() ) return // no doomed state death, but we want to let the doomed state bar drain to a sliver if ( player.GetHealth() - damageInfo.GetDamage() <= 0 ) damageInfo.SetDamage( 0 ) } // type = "shields" or "health" function TitanMoshPit_TrainTitanConcept( type ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) local startFlag local busyFlag local promptID local convAlias local convWait Assert( type == "shields" || type == "health" ) if ( type == "shields" ) { startFlag = "TitanShieldTrainingStarted" busyFlag = "TrainingTitanShields" promptID = eTrainingButtonPrompts.TITAN_SHIELDS convAlias = "titan_shields_training" convWait = 19 } else if ( type == "health" ) { startFlag = "TitanHealthTrainingStarted" busyFlag = "TrainingTitanHealth" promptID = eTrainingButtonPrompts.TITAN_HEALTH convAlias = "titan_health_training" convWait = 13 } FlagSet( startFlag ) FlagSet( busyFlag ) // take weapons and infinite ammo level.ent.Signal( "StopRefillingPlayerAmmo" ) local offhands = level.player.GetOffhandWeapons() local storedOffhands = {} StoreWeaponsToTable( storedOffhands, offhands, "offhandWeapons" ) foreach ( index, offhand in clone offhands ) level.player.TakeOffhandWeapon( index ) thread TakeAmmoFromPlayerASAP() level.player.EnableDemigod() level.player.SetNoTarget( true ) level.player.SetNoTargetSmartAmmo( true ) thread TitanMoshPit_NPCsStandDown() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { level.player.SetNoTarget( false ) level.player.SetNoTargetSmartAmmo( false ) level.player.DisableDemigod() } } ) local ogPrompt = level.lastTrainingPrompt DisplayTrainingPrompt( promptID ) ForcePlayConversationToPlayer( convAlias, level.player ) wait convWait printt( "conv done" ) if ( ogPrompt != null ) DisplayTrainingPrompt( ogPrompt ) else HideTrainingPrompt() // give back weapons and infinite ammo foreach ( idx, offhand in storedOffhands.offhandWeapons ) level.player.GiveOffhandWeapon( offhand.name, idx ) thread RefillPlayerAmmo( level.player ) // let player reload finish wait 2 thread TitanMoshPit_NPCsResumeFightingPlayer() FlagClear( busyFlag ) } function Titan_OffensiveOffhandTraining() { FlagClear( "FiredOffhandOffensive" ) level.player.GiveOffhandWeapon( TITAN_WEAPON_OFFHAND_OFFENSIVE, 0 ) OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { StopHintPulse() StopControllerImageHint() } } ) FlagClear("ConversationOver") ForcePlayConversationToPlayer( "offhand_rocket_intro", level.player ) if ( !Flag( "FiredOffhandOffensive" ) ) { OffhandOffensiveHintPulse() ControllerImageHint_OffhandOffensive() FlagWait("ConversationOver") FlagClear("ConversationOver") ForcePlayConversationToPlayer( "offhand_rocket_fire_name", level.player ) } if ( !Flag( "FiredOffhandOffensive" ) ) { FlagWait("ConversationOver") FlagClear("ConversationOver") ForcePlayConversationToPlayer( "offhand_rocket_fire_direction", level.player ) DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_OFFHAND_OFFENSIVE ) waitthread NagPlayerUntilFlag( "FiredOffhandOffensive", "offhand_rocket_fire_direction", 20 ) HideTrainingPrompt() StopHintPulse() StopControllerImageHint() } FlagWait("ConversationOver") FlagClear("ConversationOver") ForcePlayConversationToPlayer( "offhand_rocket_fire_finish", level.player ) wait 5 } function TitanMoshPit_Combat() { FlagSet( "DisableTitanKneelingEmbark" ) OnThreadEnd( function() : () { FlagClear( "DisableTitanKneelingEmbark" ) } ) ForcePlayConversationToPlayer( "titan_mosh_intro", level.player ) wait 2 // refill player health level.player.SetHealth( level.player.GetMaxHealth() ) // remove auto eject passive // give loadout and infinite ammo local offensiveOffhand = level.player.GetOffhandWeapon( 0 ) if ( !offensiveOffhand ) level.player.GiveOffhandWeapon( TITAN_WEAPON_OFFHAND_OFFENSIVE, 0 ) level.player.GiveOffhandWeapon( TITAN_WEAPON_OFFHAND_DEFENSIVE, 1 ) thread RefillPlayerAmmo( level.player ) wait 4 ForcePlayConversationToPlayer( "titan_mosh_start", level.player ) // 기존의 메세지 팝업창(생존, 최대한 버티세요.)을 아래 스레드 안으로 가져가기 위해 주석처리 // DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_MOSH_PIT_SURVIVE ) AddDamageCallback( "player", PlayerDamageCallback_TitanMoshPit ) thread TitanMoshPit_SpawnTitans_OrForceStandDown( "CombatTestDone" ) // wait until player is in doomed state while ( !level.player.GetDoomedState() ) wait 0 HideTrainingPrompt() thread TitanMoshPit_NPCsStandDown() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { // turn demigod back on before removing the callback, in case Titan is currently at end of doomed state and one more hit would kill the player level.player.EnableDemigod() RemoveDamageCallback( "player", PlayerDamageCallback_TitanMoshPit ) } } ) } function TitanMoshPit_SpawnTitans_OrForceStandDown( endSig ) { level.ent.EndSignal( endSig ) level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) DisplayTrainingPrompt( eTrainingButtonPrompts.TITAN_MOSH_PIT_SURVIVE ) ForcePlayConversationToPlayer( "titan_mosh_wave_start", level.player ) wait 2 ForcePlayConversationToPlayer("titan_mosh_wave_shields_disabled", level.player) for (local i = 0; i < 1; i++) thread TitanMoshPit_SpawnEnemyTitan(endSig, i, false, false, false, false, ATLAS_MODEL) while (1) { local foundOne = false foreach (titan in level.moshPitTitans) { if (IsAlive(titan)) { foundOne = true break } } if (!foundOne) break wait 2 } level.moshPitTitans = []; local soul = level.player.GetTitanSoul() soul.SetShieldHealth(soul.GetShieldHealthMax()) ForcePlayConversationToPlayer( "titan_mosh_wave_survived", level.player ) wait 8 ForcePlayConversationToPlayer( "titan_mosh_wave_start", level.player ) wait 2 ForcePlayConversationToPlayer("titan_mosh_wave_advanced_weapons", level.player) wait 2 for (local i = 0; i < 2; i++) thread TitanMoshPit_SpawnEnemyTitan(endSig, i, false, false, true,false, ATLAS_MODEL) while (1) { local foundOne = false foreach (titan in level.moshPitTitans) { if (IsAlive(titan)) { foundOne = true break } } if (!foundOne) break wait 2 } level.moshPitTitans = []; local soul = level.player.GetTitanSoul() soul.SetShieldHealth(soul.GetShieldHealthMax()) ForcePlayConversationToPlayer( "titan_mosh_wave_survived", level.player ) wait 8 ForcePlayConversationToPlayer( "titan_mosh_wave_start", level.player ) wait 2 ForcePlayConversationToPlayer("titan_mosh_wave_shields_enabled", level.player) wait 2 for (local i = 0; i < 3; i++) thread TitanMoshPit_SpawnEnemyTitan(endSig, i, true, false, true, false,ATLAS_MODEL) while (1) { local foundOne = false foreach (titan in level.moshPitTitans) { if (IsAlive(titan)) { foundOne = true break } } if (!foundOne) break wait 2 } level.moshPitTitans = []; local soul = level.player.GetTitanSoul() soul.SetShieldHealth(soul.GetShieldHealthMax()) ForcePlayConversationToPlayer( "titan_mosh_wave_survived", level.player ) wait 8 ForcePlayConversationToPlayer( "titan_mosh_wave_start", level.player ) wait 2 ForcePlayConversationToPlayer("titan_mosh_wave_vortex", level.player) wait 2 for (local i = 0; i < 4; i++) thread TitanMoshPit_SpawnEnemyTitan(endSig, i, true, true, true, false,ATLAS_MODEL) while (1) { local foundOne = false foreach (titan in level.moshPitTitans) { if (IsAlive(titan)) { foundOne = true break } } if (!foundOne) break wait 2 } ForcePlayConversationToPlayer("titan_mosh_wave_all_survived", level.player) wait 8 if(level.player.GetDoomedState()) return ForcePlayConversationToPlayer("titan_mosh_wave_forced_standdown", level.player) wait 2 ForceDoomedState() } function ForceDoomedState() { Assert( level.player.IsTitan() ) level.player.DisableDemigod() local soul = level.player.GetTitanSoul() Assert( IsValid( soul ) ) soul.SetShieldHealth( 0 ) level.player.TakeDamage( level.player.GetHealth() + 1, null, null, { damageSourceId=eDamageSourceId.suicide } ) } function InvincibleTitan(titan) { while(1) { titan.SetHealth(titan.GetMaxHealth()) wait 0 } } function TitanMoshPit_SpawnEnemyTitan(endSig, idxInSpawnGroup, giveShield, giveVortex, doRandWeapons, invincible, model) { level.ent.EndSignal( endSig ) level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) local startTime = Time() local spawnpoint = TitanMoshPit_GetBestTitanSpawn(idxInSpawnGroup) local spawnOrg = spawnpoint.origin local spawnAng = spawnpoint.angles local oppTeam = GetOppositeTeam( level.player ) local alert = 1 local titan = NPE_SpawnTitan(oppTeam, spawnOrg, spawnAng, alert, doRandWeapons, "mp_titanweapon_xo16", model) titan.s.isHotDropping <- true level.moshPitTitans.append( titan ) titan.SetTitle( "#NPC_TITAN_TRAINING" ) DisableRodeo( titan ) if ( !giveShield ) DisableTitanShield( titan ) if ( !giveVortex ) titan.TakeOffhandWeapon( 1 ) titan.Minimap_AlwaysShow( level.player.GetTeam(), level.player ) waitthread SuperHotDropGenericTitan( titan, spawnOrg, spawnAng ) titan.s.isHotDropping = false if (invincible) thread InvincibleTitan(titan) thread MoshPit_NPC_FightPlayer( titan ) } function TitanMoshPit_GetBestTitanSpawn(idx) { if ( !( "moshPitTitanSpawns" in level ) ) { level.moshPitTitanSpawns <- [] level.moshPitTitanSpawns.append( { origin = OriginToGround( Vector( 876.222, 3413.73, 6590.57 ) ), angles = Vector( 0, -142.022, 0 ) } ) level.moshPitTitanSpawns.append( { origin = OriginToGround( Vector( 2204.86, 3212.06, 6496.67 ) ), angles = Vector( 0, 167.431, 0 ) } ) level.moshPitTitanSpawns.append( { origin = OriginToGround( Vector( 2355.67, 1046.02, 6478.31 ) ), angles = Vector( 0, 134.641, 0 ) } ) level.moshPitTitanSpawns.append( { origin = OriginToGround( Vector( 886.44, 687.81, 6492.99 ) ), angles = Vector( 0, 162.233, 0 ) } ) level.moshPitTitanSpawns.append( { origin = OriginToGround( Vector( -1325.17, 1287.77, 6470.94 ) ), angles = Vector( 0, 41.3458, 0 ) } ) level.moshPitTitanSpawns.append( { origin = OriginToGround( Vector( -29.9723, 3779.67, 6458.22 ) ), angles = Vector( 0, -95.2431, 0 ) } ) } return level.moshPitTitanSpawns[idx] } function Titan_TrainEject() { FlagClear( "PlayerEjected" ) local playertitan = GetPlayerTitanInMap( level.player ) GivePassive( playertitan, PAS_NUCLEAR_CORE ) thread CatchPlayerEject() // set player invincible again level.player.EnableDemigod() if ( level.player.IsTitan() ) { ForcePlayConversationToPlayer( "titan_doomed_info", level.player ) wait 9 } if ( level.player.IsTitan() ) { ForcePlayConversationToPlayer( "titan_infinite_doomed_info", level.player ) } if ( level.player.IsTitan() ) { FlagClear("ConversationOver") DisplayTrainingPrompt( eTrainingButtonPrompts.EJECT_CONFIRM ) ForcePlayConversationToPlayer( "titan_doomed_eject", level.player ) wait 5 } if ( level.player.IsTitan() ) { waitthread NagPlayerUntilFlag( "PlayerEjected", "titan_eject_nag", 15 ) } // -- PLAYER PUNCHED OUT -- HideTrainingPrompt() local minWaitEnd = 5 + Time() ForcePlayConversationToPlayer( "titan_eject_in_air", level.player ) while ( !level.player.IsOnGround() ) wait 0.2 // let the VO finish playing if ( Time() < minWaitEnd ) wait minWaitEnd - Time() } function CatchPlayerEject() { level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) while ( level.player.IsTitan() ) wait 0.1 printt("Set PlayerEjected") FlagSet( "PlayerEjected" ) } // =========================== CALLBACKS & MISC FUNCTIONS =========================== function ControllerImageHint_Sprint() { Remote.CallFunction_Replay( level.player, "ControllerImageHint_Sprint" ) } function ControllerImageHint_Melee() { Remote.CallFunction_Replay( level.player, "ControllerImageHint_Melee" ) } function ControllerImageHint_OffhandDefensive() { Remote.CallFunction_Replay( level.player, "ControllerImageHint_OffhandDefensive" ) } function ControllerImageHint_OffhandOffensive() { Remote.CallFunction_Replay( level.player, "ControllerImageHint_OffhandOffensive" ) } function ControllerImageHint_DPad_Left() { Remote.CallFunction_Replay( level.player, "ControllerImageHint_DPad", 0 ) } function ControllerImageHint_DPad_Down() { Remote.CallFunction_Replay( level.player, "ControllerImageHint_DPad", 1 ) } function StopControllerImageHint() { Remote.CallFunction_Replay( level.player, "StopControllerImageHint" ) } function CloakHintPulse() { Remote.CallFunction_Replay( level.player, "HUDHintPulse", 0 ) } function OffhandOffensiveHintPulse() { Remote.CallFunction_Replay( level.player, "HUDHintPulse", 1 ) } function DashMeterHintPulse() { Remote.CallFunction_Replay( level.player, "HUDHintPulse", 2 ) } function TitanAIControlHintPulse() { Remote.CallFunction_Replay( level.player, "HUDHintPulse", 3 ) } function StopHintPulse() { Remote.CallFunction_Replay( level.player, "StopHintPulse" ) } function HighlightMinimap() { Remote.CallFunction_Replay( level.player, "HighlightMinimap" ) } function StopHighlightMinimap() { Remote.CallFunction_Replay( level.player, "StopHighlightMinimap" ) } function CleanupCorpses( delay = 0 ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) if ( delay > 0 ) wait delay Remote.CallFunction_Replay( level.player, "ServerCallback_CleanupCorpses" ) } function WaittillTime( minWaitEnd ) { if ( Time() < minWaitEnd ) wait ( minWaitEnd - Time() ) } function EmitSoundOnEntity_Delayed( ent, alias, delay ) { ent.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) if ( delay > 0 ) wait delay EmitSoundOnEntity( ent, alias ) } function PlayFXOnEntity_Delayed( alias, entity, delay ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) entity.EndSignal( "OnDeath" ) wait delay PlayFXOnEntity( alias, entity ) } function MoveTo_Delayed( delay, moveEnt, movePos, moveTime, accel, decel ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) moveEnt.EndSignal( "OnDeath" ) wait delay moveEnt.MoveTo( movePos, moveTime, accel, decel ) } function FireRocketsUntilSignal( rocketSpots, rocketSpeed, volleyWait, endSig, lightTrigTN = null ) { level.player.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( endSig ) local oppTeam = GetOppositeTeam( level.player ) if ( lightTrigTN ) LightTrigger_On( lightTrigTN, FX_LIGHT_GREEN ) OnThreadEnd( function() : ( lightTrigTN ) { if ( lightTrigTN && IsValid( lightTrigTN ) ) { LightTrigger_Off( lightTrigTN ) } } ) while ( 1 ) { foreach ( idx, spot in rocketSpots ) { local rocket = NPE_SpawnRocket( spot.origin, spot.angles, level, oppTeam, rocketSpeed ) // thread RocketSeekPlayer( rocket, rocketSpeed ) level.dashRockets.append( rocket ) } wait volleyWait } } function NPE_SpawnRocket( spawnPos, spawnAng, owner, team, rocketSpeed ) { local rocket = CreateEntity( "rpg_missile" ) rocket.SetOrigin( spawnPos ) rocket.SetAngles( spawnAng ) rocket.SetOwner( owner ) rocket.SetTeam( team ) rocket.SetModel( "models/weapons/bullets/projectile_rocket.mdl" ) rocket.SetImpactEffectTable( level.trainingRocketEffectTable ) rocket.SetWeaponClassName( "mp_projectile_orbital_strike" ) // rocket.SetSpeed( rocketSpeed ) rocket.kv.damageSourceId = eDamageSourceId.mp_titanweapon_orbital_strike DispatchSpawn( rocket ) EmitSoundAtPosition( spawnPos, "Weapon_Archer.Fire" ) return rocket } function GetScriptPos( player = null ) { if ( !player ) player = level.player local pos = player.GetOrigin() local ang = player.GetAngles() local returnStr = "Vector( " + pos.x + ", " + pos.y + ", " + pos.z + " ), Vector( 0, " + ang.y + ", 0 )" return returnStr } function TakeAmmoFromPlayerASAP() { level.player.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) local weapon = null while ( !weapon ) { weapon = level.player.GetActiveWeapon() if ( !weapon ) wait 0.1 } level.player.SetActiveWeaponPrimaryAmmoTotal( 0 ) level.player.SetActiveWeaponPrimaryAmmoLoaded( 0 ) } function DisplayTrainingPrompt( promptID ) { level.lastTrainingPrompt = promptID Remote.CallFunction_Replay( level.player, "ServerCallback_DisplayTrainingPrompt", promptID ) } function HideTrainingPrompt() { Remote.CallFunction_Replay( level.player, "ServerCallback_HideTrainingPrompt" ) } function NPE_GrenadeCreatedCallback( ent ) { if ( ent.GetOwner() != level.player ) return level.grenadesThrown++ } function NPE_GroundTroopsDeathCallback( guy, damageInfo ) { TryTakeWeaponOnDeath( guy ) local dmgSourceID = damageInfo.GetDamageSourceIdentifier() if ( dmgSourceID != eDamageSourceId.mp_weapon_smart_pistol ) FlagSet( "NotKilledUsingSmartPistol" ) else { local weapon = damageInfo.GetWeapon() if ( IsValid( weapon ) ) level.lastSmartPistolTargs = weapon.SmartAmmo_GetTargets() } /* if ( !( damageInfo.GetDamageType() & DF_HEADSHOT ) ) { printt( "Not a headshot!") FlagSet( "NonHeadshot" ) } else { printt( "Headshot!") } */ EmitSoundAtPosition( guy.GetOrigin(), "Object_Dissolve" ) guy.Dissolve( ENTITY_DISSOLVE_CHAR, Vector( 0, 0, 0 ), 0 ) } function TryTakeWeaponOnDeath( guy ) { if ( !( "dontDropWeapon" in guy.s ) ) return local activeWeapon = guy.GetActiveWeapon() if ( activeWeapon ) guy.TakeWeapon( activeWeapon.GetClassname() ) } function ClientCommand_LookTarget_Top( player, ... ) { level.player.ResetIdleTimer() FlagSet( "PlayerLookedAtTopTarget" ) return true } function ClientCommand_LookTarget_Bottom( player, ... ) { level.player.ResetIdleTimer() FlagSet( "PlayerLookedAtBottomTarget" ) return true } function ClientCommand_NPE_LookWasInverted( player, ... ) { level.player.ResetIdleTimer() level.ent.Signal( "PlayerInvertedLook" ) return true } function ClientCommand_NPE_NoButtonClicked( player, ... ) { level.player.ResetIdleTimer() //printt( "clicked no button" ) level.ent.Signal( "PlayerClickedNoButton" ) return true } function ClientCommand_NPE_StartBedEndModule( player, ... ) { if (true) thread StartTrainingModule( TRAINING_BEDROOM_END/*eTrainingModules.BEDROOM_END*/ ) else GameRules_EndMatch() } function ClientCommand_NPE_StartTitanMoshPitModule( player, ... ) { thread StartTrainingModule( eTrainingModules.TITAN_MOSH_PIT ) } function ClientCommand_NPE_ConfirmInvertYes( player, ... ) { level.player.ResetIdleTimer() level.ent.Signal( "InvertSettingsConfirmed" ) return true } function ClientCommand_NPE_PlayerReloaded( player, ... ) { FlagSet( "PlayerReloaded" ) return true } function ClientCommand_NPE_PlayerPressedPrimaryWeapon( player, ... ) { FlagSet("PlayerPressedPrimaryWeapon"); return true; } function ClientCommand_NPE_PlayerPressedUse( player, ... ) { FlagSet( "PlayerPressedUse" ) return true } function ClientCommand_NPE_FiredOffhandOffensive( player, ... ) { FlagSet( "FiredOffhandOffensive" ) return true } function ClientCommand_NPE_PlayerPressedJump( player, ... ) { FlagSet( "PlayerPressedJump" ) return true } function ClientCommand_NPE_PressedWeaponSwitch( player, ... ) { FlagSet( "PlayerPressedWeaponSwitchButton" ) return true } function ClientCommand_NPE_DashMeterLow( player, ... ) { FlagSet( "PlayerDashMeterLow" ) return true } function ClientCommand_NPE_DashMeterReady( player, ... ) { FlagClear( "PlayerDashMeterLow" ) return true } function ClientCommand_NPE_PlayerDashed( player, ... ) { //printt( "SERVER Setting PlayerDashed" ) FlagSet( "PlayerDashed" ) if (level.currentTrainingModule == eTrainingModules.TITAN_DASH) { thread SetAdditionalDashFlags() } thread ClearDashFlagAfterTime( player ) return true } function SetAdditionalDashFlags() { wait 0.25 // to let titan gain enough velocity local vec = level.player.GetVelocity() if (vec.x > 280) { LightTrigger_On("trigger_lightswitch_dash_R", FX_LIGHT_GREEN) FlagSet("PlayerDashed_Right") } else if (vec.x < -280) { LightTrigger_On("trigger_lightswitch_dash_L", FX_LIGHT_GREEN) FlagSet("PlayerDashed_Left") } else if (vec.y > 280) { LightTrigger_On("trigger_lightswitch_dash_T", FX_LIGHT_GREEN) FlagSet("PlayerDashed_Forward") } else if (vec.y < -280) { LightTrigger_On("trigger_lightswitch_dash_B", FX_LIGHT_GREEN) FlagSet("PlayerDashed_Back") } } function ClearDashFlagAfterTime( player ) { player.EndSignal( "OnDestroy" ) player.EndSignal( "Disconnected" ) level.ent.EndSignal( "PlayerDashed" ) wait 1 //printt( "SERVER Clearing PlayerDashed" ) FlagClear( "PlayerDashed" ) } function ClientCommand_CallConversationOverSignal( player, ... ) { FlagSet("ConversationOver") } function ClientCommand_CallConversationOverEndSignal( player, ... ) { FlagClear("ConversationOver") } // when players select "Skip Training" from the menu function ClientCommand_LeaveTraining( player, ... ) { // if in cabin start or end, go right to lobby if ( level.currentTrainingModule == TRAINING_BEDROOM/*eTrainingModules.BEDROOM*/ || level.currentTrainingModule == TRAINING_BEDROOM_END/*eTrainingModules.BEDROOM_END*/ ) { if ( IsValid( level.player ) ) // defensive MuteAll( level.player, 1.0 ) ReturnToLobby() return true } // otherwise go to end cabin to see end scripting if (true) thread StartTrainingModule( TRAINING_BEDROOM_END/*eTrainingModules.BEDROOM_END*/ ) else GameRules_EndMatch() return true } function ShowMinimap() { level.nv.minimapState = eMinimapState.Default } function HideMinimap() { level.nv.minimapState = eMinimapState.Hidden } function ReturnToLobby() { printt( "returning to lobby" ) Remote.CallFunction_UI( level.player, "ServerCallback_EndTraining" ) } function NagPlayerUntilFlag( flagName, nagAlias, nagInterval = 20, trainingPromptID = null, useTempConversation = null ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) local nextNagTime = Time() + nagInterval while ( !Flag( flagName ) ) { if ( Time() > nextNagTime ) { if ( trainingPromptID != null ) DisplayTrainingPrompt( trainingPromptID ) if ( useTempConversation ) PlayTempConversationToPlayer( nagAlias, level.player ) else ForcePlayConversationToPlayer( nagAlias, level.player ) nextNagTime = Time() + nagInterval } wait 0.1 } } function NagPlayerUntilGuysAreDead( guys, nagAlias, nagInterval = 20, trainingPromptID = null ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) if ( !guys.len() ) { printt( "NagPlayerUntilGuysAreDead: everyone is dead at the start, returning" ) return } FlagClear( "NagFlag" ) thread NagPlayerUntilFlag( "NagFlag", nagAlias, nagInterval, trainingPromptID ) waitthread( WaitUntilGuysAreDead( guys ) ) FlagSet( "NagFlag" ) } function WaitUntilGuysAreDead( guys ) { if ( !guys.len() ) { printt( "WaitUntilGuysAreDead: everyone is dead at the start, returning" ) return } while( 1 ) { local foundOne = false foreach ( guy in guys ) { if ( IsAlive( guy ) ) { foundOne = true break } } if ( !foundOne ) break wait 0.1 } } function NagPlayerUntilPlayerMove2D( distToMove, nagAlias, nagInterval = 20, trainingPromptID = null ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) local ogPos = level.player.GetOrigin() FlagClear( "NagFlag" ) thread NagPlayerUntilFlag( "NagFlag", nagAlias, nagInterval, trainingPromptID ) while ( Distance2D( ogPos, level.player.GetOrigin() ) < distToMove ) wait 0.1 FlagSet( "NagFlag" ) } function WaitForPlayerActiveWeapon( className = null ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) local weapon = null while ( 1 ) { wait 0 weapon = level.player.GetActiveWeapon() if( weapon ) { if( className ) { if ( weapon.GetClassname() == className ) break; } else break; } } return weapon } function SpawnDumbNPC( npcType, spawnOrg, spawnAng, shouldDropWeapon = false, squadName = null ) { Assert( npcType == "grunt" || npcType == "spectre" || npcType == "titan" ) local spawnTeam = GetOppositeTeam( level.player ) local alert = false if ( squadName == null ) squadName = "training_guys" local npc = null if ( npcType == "grunt" ) npc = SpawnGrunt( spawnTeam, squadName, spawnOrg, spawnAng, alert ) else if ( npcType == "spectre" ) npc = SpawnSpectre( spawnTeam, squadName, spawnOrg, spawnAng, alert ) else npc = NPE_SpawnTitan( spawnTeam, spawnOrg, spawnAng, alert ) if ( npcType == "spectre" ) DisableLeeching( npc ) npc.kv.reactChance = 0 npc.kv.reactFriendlyChance = 0 npc.SetEfficientMode( true ) if ( !shouldDropWeapon ) npc.s.dontDropWeapon <- 1 return npc } function NPE_SpawnTitan(spawnTeam, org, ang, alert, doRandWeapons = false, defaultWeapon = "mp_titanweapon_xo16", model = null) { local weapon = defaultWeapon if (doRandWeapons) { local randWeaps = [] randWeaps.append( "mp_titanweapon_xo16" ) randWeaps.append( "mp_titanweapon_40mm" ) randWeaps.append( "mp_titanweapon_rocket_launcher" ) weapon = Random( randWeaps ) } local table = CreateDefaultNPCTitanTemplate( spawnTeam ) table.title = "#NPC_TITAN_TRAINING" table.weapon = weapon table.origin = org table.angles = ang if (model) table.model = model local titan = SpawnNPCTitan( table ) local alertVal = alert ? 1 : 0 titan.kv.alwaysalert = alertVal return titan } function NPC_StandDown( npc ) { if ( !IsAlive( npc ) ) return if ( npc.IsTitan() && ( "isHotDropping" in npc.s ) && npc.s.isHotDropping ) while ( npc.s.isHotDropping ) wait 0 thread NPE_NPCStayPut( npc ) if ( !( "ogLookDist" in npc.s ) ) npc.s.ogLookDist <- null npc.s.ogLookDist = npc.GetLookDist() npc.SetLookDist( 0 ) // Titans play kneel anim if ( npc.IsTitan() ) thread PlayTitanAnimSafe( npc, "at_MP_embark_idle_blended" ) } function NPC_StandDown_Stop( npc, waitForAnimDone = false ) { if ( !IsAlive( npc ) ) return npc.Signal( "StandDown_Change" ) npc.DisableBehavior( "Assault" ) npc.StayPut( false ) if ( "ogLookDist" in npc.s ) npc.SetLookDist( npc.s.ogLookDist ) // Titan get back up if ( npc.IsTitan() ) thread PlayTitanAnimSafe( npc, "at_MP_embark_fast" ) } function PlayTitanAnimSafe( titan, anim ) { titan.Signal( "PlayTitanAnimSafe_Start" ) titan.EndSignal( "PlayTitanAnimSafe_Start" ) titan.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) while ( titan.ContextAction_IsActive() ) wait 0 thread PlayAnim( titan, anim ) } function NPE_NPCStayPut( npc, origin = null, angles = null ) { npc.EndSignal( "OnDeath" ) npc.EndSignal( "StandDown_Change" ) while ( !npc.IsOnGround() ) wait 0 npc.DisableBehavior( "Assault" ) if ( !( "ap" in npc.s ) ) npc.s.ap <- CreateStrictAssaultEnt( npc.GetOrigin(), npc.GetAngles() ) local stayOrg = npc.GetOrigin() local stayAng = npc.GetAngles() if ( origin ) stayOrg = origin if ( angles ) stayAng = angles npc.s.ap.SetOrigin( stayOrg ) npc.s.ap.SetAngles( stayAng ) npc.AssaultPointEnt( npc.s.ap ) if ( npc.IsSoldier() ) npc.s.ap.kv.forcecrouch = 1 npc.WaitSignal( "OnFinishedAssault" ) npc.StayPut( true ) } function CreatePlayerAssaultEnt() { level.player.s.playerAssaultEnt <- CreateStrictAssaultEnt( level.player.GetOrigin(), level.player.GetAngles(), 250 ) level.player.s.playerAssaultEnt.kv.forcecrouch = 0 thread UpdatePlayerAssaultEnt() } function UpdatePlayerAssaultEnt() { level.player.s.playerAssaultEnt.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDeath" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) local newPos local lastPos = level.player.s.playerAssaultEnt.GetOrigin() while( 1 ) { newPos = level.player.GetOrigin() if ( Distance( newPos, lastPos ) > 64 ) { //printt( "moving player assault ent" ) level.player.s.playerAssaultEnt.SetOrigin( newPos ) lastPos = newPos } wait 2.0 } } function GetOppositeTeam( ent ) { local oppTeam = TEAM_IMC if ( ent.GetTeam() == TEAM_IMC ) oppTeam = TEAM_MILITIA return oppTeam } function TeleportPlayer( targetOrg, targetAng, doTeleportFX = true, doInstantTeleport = false ) { level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) level.ent.Signal( "TeleportingPlayer" ) level.ent.EndSignal( "TeleportingPlayer" ) level.ent.EndSignal( "ModuleChanging" ) FlagSet( "PlayerIsTeleporting" ) if ( doTeleportFX ) Remote.CallFunction_Replay( level.player, "ServerCallback_TrainingTeleport" ) level.player.ResetIdleTimer() OnThreadEnd( function() : () { if ( IsValid( level.player ) ) { Remote.CallFunction_Replay( level.player, "ServerCallback_SetFreezePlayerControls", false ) FlagClear( "PlayerIsTeleporting" ) } } ) if ( !doInstantTeleport ) wait 0.25 // small wait before freezing feels good level.player.FreezeControlsOnServer( false ) Remote.CallFunction_Replay( level.player, "ServerCallback_SetFreezePlayerControls", true ) wait 0.1 level.player.SetOrigin( targetOrg ) level.player.SetAngles( targetAng ) level.player.ForceStand() wait 0.1 level.player.UnforceStand() level.player.UnfreezeControlsOnServer() level.player.Signal( "Teleported" ) level.ent.Signal( "TeleportedPlayer" ) // so we can do combo waitsignals on the level.ent } function LockPlayerMovement( player ) { if ( "movementLocked" in player.s ) return local sequence = CreateFirstPersonSequence() sequence.thirdPersonAnim = "UseTurretIdle" //"ref" sequence.attachment = "ref" sequence.blendTime = 0.0 sequence.viewConeFunction = PlayerLockViewCone player.s.movementLocked <- 1 thread FirstPersonSequence( sequence, player ) } function UnlockPlayerMovement( player ) { if ( !( "movementLocked" in player.s ) ) return delete player.s.movementLocked player.Anim_Stop() } function PlayerLockViewCone( player ) { player.PlayerCone_FromAnim() player.PlayerCone_SetMinYaw( -70 ) player.PlayerCone_SetMaxYaw( 60 ) player.PlayerCone_SetMinPitch( -80 ) player.PlayerCone_SetMaxPitch( 30 ) } function RefillOffhandAmmoUntilSignal( weapon, endSig, loopTime = 0.1 ) { level.ent.EndSignal( "StopRefillingOffhandWeapons" ) level.ent.EndSignal( "ModuleChanging" ) level.player.EndSignal( "OnDestroy" ) level.player.EndSignal( "Disconnected" ) weapon.EndSignal( "OnDestroy" ) level.ent.EndSignal( endSig ) local maxAmmoClip = weapon.GetWeaponPrimaryClipCount() while ( 1 ) { local currAmmo = level.player.GetWeaponAmmoLoaded( weapon ) if ( currAmmo <= 0 ) { weapon.SetWeaponPrimaryClipCount( maxAmmoClip ) } wait loopTime } } function RefillPlayerAmmo( player, classnameFilter = null ) { player.EndSignal( "OnDeath" ) player.EndSignal( "OnDestroy" ) player.EndSignal( "Disconnected" ) level.ent.EndSignal( "ModuleChanging" ) level.ent.EndSignal( "StopRefillingPlayerAmmo" ) local refillThreshold = 0.98 local weapon local maxAmmoMag while ( 1 ) { wait 0.5 weapon = level.player.GetActiveWeapon() if ( !weapon ) continue if ( classnameFilter && weapon.GetClassname() != classnameFilter ) continue maxAmmoMag = level.player.GetWeaponAmmoMaxLoaded( weapon ) if ( player.GetWeaponAmmoStockpile( weapon ) == 0 ) // doesn't count ammo in the mag weapon.SetWeaponPrimaryAmmoCount( maxAmmoMag * 2 ) // give him 2 mags worth } } function DisablePilotHud() { AddCinematicFlag( level.player, CE_FLAG_INTRO ) } function EnablePilotHud() { RemoveCinematicFlag( level.player, CE_FLAG_INTRO ) } function EnableTitanDisembark() { if ( !level.titanDisembarkDisabled ) return Remote.CallFunction_Replay( level.player, "ServerCallback_EnableTitanDisembark" ) level.titanDisembarkDisabled = null } //check function DisableTitanDisembark() { if ( level.titanDisembarkDisabled ) return Remote.CallFunction_Replay( level.player, "ServerCallback_DisableTitanDisembark" ) level.titanDisembarkDisabled = true } //check function ClientCommand_SetTrainingHasEverFinished( player, training_hasEverFinished ) { local intVal = SanitizeClientCommandInput( training_hasEverFinished ) if ( intVal == null ) return false level.training_hasEverFinished = intVal return true } //check function ClientCommand_SetTrainingHasEverBeenStarted( player, training_hasEverBeenStarted ) { local intVal = SanitizeClientCommandInput( training_hasEverBeenStarted ) if ( intVal == null ) return false level.training_hasEverBeenStarted = intVal return true } //check function ClientCommand_ResumeChoice( player, resumeChoice ) { local intVal = SanitizeClientCommandInput( resumeChoice ) if ( intVal == null ) return false level.resumeChoice = intVal return true } //check function SanitizeClientCommandInput( inputStr ) { // Need to do this so people can't use our client commands for evil if ( inputStr == null ) return inputStr // tointeger returns null if it's operating on a string local intVal = inputStr.tointeger() return intVal } main()
0
0.96954
1
0.96954
game-dev
MEDIA
0.927618
game-dev
0.916335
1
0.916335
shxzu/Simp
12,879
src/main/java/cc/simp/modules/impl/combat/KillAuraModule.java
package cc.simp.modules.impl.combat; import cc.simp.api.events.impl.game.PreUpdateEvent; import cc.simp.api.events.impl.player.HitSlowDownEvent; import cc.simp.api.events.impl.player.MotionEvent; import cc.simp.api.events.impl.world.WorldLoadEvent; import cc.simp.api.properties.Property; import cc.simp.api.properties.impl.ModeProperty; import cc.simp.api.properties.impl.NumberProperty; import cc.simp.modules.Module; import cc.simp.modules.ModuleCategory; import cc.simp.modules.ModuleInfo; import cc.simp.processes.RotationProcess; import cc.simp.utils.client.MathUtils; import cc.simp.utils.client.Timer; import cc.simp.utils.mc.*; import cc.simp.utils.misc.MovementFix; import io.github.nevalackin.homoBus.Listener; import io.github.nevalackin.homoBus.annotations.EventLink; import lombok.NonNull; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.network.play.client.C09PacketHeldItemChange; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MovingObjectPosition; import org.lwjgl.util.vector.Vector2f; import java.util.Comparator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static cc.simp.utils.Util.mc; @ModuleInfo(label = "Kill Aura", category = ModuleCategory.COMBAT) public final class KillAuraModule extends Module { public static ModeProperty<Mode> mode = new ModeProperty<>("Mode", Mode.Adaptive); public static ModeProperty<Entities> entities = new ModeProperty<>("Entities", Entities.Optimal); public static NumberProperty seekRange = new NumberProperty("Seek Range", 4.2, 3, 6, 0.1); public static NumberProperty killRange = new NumberProperty("Kill Range", 3, 3, 6, 0.1); public static NumberProperty blockingRange = new NumberProperty("Blocking Range", 4.2, 3, 6, 0.1); private static final NumberProperty max = new NumberProperty("Max CPS", 13.0, 0.0, 20.0, 0.5); private static final NumberProperty min = new NumberProperty("Min CPS", 9.0, 0.0, 20.0, 0.5); public static ModeProperty<AutoBlock> ab = new ModeProperty<>("Auto Block", AutoBlock.Fake); public static ModeProperty<Rotations> rotations = new ModeProperty<>("Rotations", Rotations.Regular); private final NumberProperty speed = new NumberProperty("Rotation Speed", 5, 0, 10, 1); public static final Property<Boolean> jitter = new Property<>("Jitter Rotations", false); public static final Property<Boolean> fix = new Property<>("Move Fix", true); public static final Property<Boolean> sprint = new Property<>("Keep Sprint", false); public static final Property<Boolean> legit = new Property<>("Legit", true); public static final Property<Boolean> raycast = new Property<>("Ray Cast", true); private final Property<Boolean> teams = new Property<>("Teams", false); public enum Mode { Adaptive, Single, Switch } public enum Entities { Optimal, Players, All } public enum Rotations { Regular, Snap, None } public enum AutoBlock { None, Fake, Switch, Legit, Predictive, Vanilla } public static EntityLivingBase target; public static boolean autoBlocking = false; public static boolean canAttack = true; private List<Entity> targetList = new CopyOnWriteArrayList<>(); private static final Timer attackTimer = new Timer(); private static final Timer switchTimer = new Timer(); private int targetIndex; static long delay = 0; @EventLink public final Listener<PreUpdateEvent> onPreUpdate = event -> { setSuffix(mode.getValue().toString()); targetList = getTargets(); if (targetList.isEmpty()) { target = null; unblock(); return; } selectTarget(); if (target == null) { unblock(); return; } calculateRotations(); attack(); }; @EventLink public final Listener<HitSlowDownEvent> hitSlowDownEventListener = e -> { if (sprint.getValue()) { e.setSprint(true); e.setSlowDown(1.0); } }; @EventLink public final Listener<WorldLoadEvent> worldLoadEventListener = e -> { if (autoBlocking) { if (ab.getValue() == AutoBlock.Legit || ab.getValue() == AutoBlock.Predictive) { mc.gameSettings.keyBindUseItem.setPressed(false); } else if (InventoryUtils.isHoldingSword()) { PacketUtils.sendPacket(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN)); } autoBlocking = false; } canAttack = true; target = null; targetList.clear(); }; private void selectTarget() { switch (mode.getValue()) { case Single: target = (EntityLivingBase) targetList.stream().findFirst().orElse(null); break; case Switch: if (switchTimer.hasTimeElapsed(1000)) { targetIndex = (targetIndex + 1) % targetList.size(); switchTimer.reset(); } target = (EntityLivingBase) targetList.get(targetIndex); break; case Adaptive: target = (EntityLivingBase) targetList.stream() .min(Comparator.comparingDouble(e -> mc.thePlayer.getDistanceToEntity(e))) .orElse(null); break; } } private void calculateRotations() { if (target == null || rotations.getValue() == Rotations.None) return; Vector2f rotation = RotationUtils.calculate(target, mode.getValue() == Mode.Adaptive, seekRange.getValue()); if (jitter.getValue()) { rotation.x += (float) ((Math.random() - 0.5) * 2); rotation.y += (float) ((Math.random() - 0.5) * 2); } float targetYaw = rotation.x; float targetPitch = rotation.y; switch (rotations.getValue()) { case Regular: /* Smoothing rotations */ final double minRotationSpeed = this.speed.getValue(); final double maxRotationSpeed = this.speed.getValue() * Math.random(); float rotSpeed = (float) MathUtils.getRandom(minRotationSpeed, maxRotationSpeed); RotationProcess.setRotations(new Vector2f(targetYaw, targetPitch), rotSpeed, fix.getValue() ? MovementFix.NORMAL : MovementFix.OFF); break; case Snap: RotationProcess.setRotations(new Vector2f(targetYaw, targetPitch), 10, fix.getValue() ? MovementFix.NORMAL : MovementFix.OFF); break; } } private void autoblock() { if (target == null || !InventoryUtils.isHoldingSword()) { autoBlocking = false; return; } switch (ab.getValue()) { case Legit: if (mc.thePlayer.ticksExisted % 4 == 0) { mc.gameSettings.keyBindUseItem.setPressed(true); autoBlocking = true; } else { mc.gameSettings.keyBindUseItem.setPressed(false); autoBlocking = false; } canAttack = !autoBlocking; break; case Predictive: if (mc.thePlayer.hurtTime >= 4 && mc.thePlayer.hurtTime != 10) { mc.gameSettings.keyBindUseItem.setPressed(true); autoBlocking = true; } else { mc.gameSettings.keyBindUseItem.setPressed(false); autoBlocking = false; } canAttack = !autoBlocking; break; case Vanilla: PacketUtils.sendPacket(new C08PacketPlayerBlockPlacement(mc.thePlayer.getHeldItem())); autoBlocking = true; break; case Switch: if (mc.thePlayer.ticksExisted % 4 == 0) { PacketUtils.sendPacket(new C08PacketPlayerBlockPlacement(mc.thePlayer.getHeldItem())); autoBlocking = true; PacketUtils.sendPacket(new C09PacketHeldItemChange((mc.thePlayer.inventory.currentItem + 1) % 8)); if (mc.thePlayer.isBlocking()) { PacketUtils.sendPacket(new C09PacketHeldItemChange((mc.thePlayer.inventory.currentItem))); autoBlocking = false; } } break; } } private void unblock() { if (!autoBlocking) return; if (ab.getValue() == AutoBlock.Legit || ab.getValue() == AutoBlock.Predictive) { mc.gameSettings.keyBindUseItem.setPressed(false); } else if (InventoryUtils.isHoldingSword()) { PacketUtils.sendPacket(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN)); } autoBlocking = false; } private void attack() { if (target == null || !canAttack) return; if (!hitTimerDone()) return; if (mc.thePlayer.getDistanceToEntity(target) > killRange.getValue()) return; if (raycast.getValue()) { MovingObjectPosition mop = RayCastUtils.rayCast(RotationProcess.rotations, killRange.getValue()); if (mop == null || mop.entityHit != target) return; } if (target.getDistanceToEntity(mc.thePlayer) > killRange.getValue()) return; if (!legit.getValue()) { if (!canAttack) return; mc.thePlayer.swingItem(); mc.playerController.attackEntity(mc.thePlayer, target); } else { mc.clickMouse(); } if (ab.getValue() != AutoBlock.None) { if (mc.thePlayer.getDistanceToEntity(target) <= blockingRange.getValue() && InventoryUtils.isHoldingSword()) { autoblock(); } } } private static boolean hitTimerDone() { boolean returnVal = false; if (attackTimer.hasTimeElapsed(delay, false)) { returnVal = true; attackTimer.reset(); delay = (long) (1000 / MathUtils.getRandom(max.getValue().floatValue(), Math.min(min.getValue().floatValue(), max.getValue().floatValue() - 1))); } return returnVal; } private List<Entity> getTargets() { return mc.theWorld.loadedEntityList.stream() .filter(entity -> entity instanceof EntityLivingBase) .filter(entity -> entity != mc.thePlayer) .filter(entity -> !entity.isDead) .filter(entity -> ((EntityLivingBase) entity).getHealth() > 0) .filter(entity -> mc.thePlayer.getDistanceToEntity(entity) <= seekRange.getValue()) .filter(this::isValidEntity) .collect(Collectors.toList()); } private boolean isValidEntity(Entity entity) { if (teams.getValue() && inTeam(mc.thePlayer, entity)) return false; return switch (entities.getValue()) { case Optimal -> entity instanceof EntityPlayer || entity instanceof EntityMob; case Players -> entity instanceof EntityPlayer; case All -> true; }; } public static boolean inTeam(@NonNull ICommandSender entity0, @NonNull ICommandSender entity1) { String s = "\u00a7" + teamColor(entity0); return entity0.getDisplayName().getFormattedText().contains(s) && entity1.getDisplayName().getFormattedText().contains(s); } public static @NonNull String teamColor(@NonNull ICommandSender player) { Matcher matcher = Pattern.compile("\u00a7(.).*\u00a7r").matcher(player.getDisplayName().getFormattedText()); return matcher.find() ? matcher.group(1) : "f"; } @Override public void onEnable() { delay = (long) (1000 / MathUtils.getRandom(max.getValue().floatValue(), Math.max(min.getValue().floatValue(), max.getValue().floatValue() - 1))); super.onEnable(); } @Override public void onDisable() { canAttack = true; target = null; targetList.clear(); unblock(); super.onDisable(); } }
0
0.944242
1
0.944242
game-dev
MEDIA
0.825482
game-dev
0.987804
1
0.987804
Dimbreath/AzurLaneData
6,263
ko-KR/view/main/navalacademymediator.lua
slot0 = class("NavalAcademyMediator", import("..base.ContextMediator")) slot0.OPEN_DOCK = "NavalAcademyMediator:OPEN_DOCK" slot0.START_TO_LEARN = "NavalAcademyMediator:START_TO_LEARN" slot0.GET_REWARD = "NavalAcademyMediator:GET_REWARD" slot0.TRUANT = "NavalAcademyMediator:TRUANT" slot0.TIMES_UP = "NavalAcademyMediator:TIMES_UP" slot0.GET_RES = "NavalAcademyMediator:GET_RES" slot0.UPGRADE_FIELD = "NavalAcademyMediator:UPGRADE_FIELD" slot0.UPGRADE_TIMES_UP = "NavalAcademyMediator:UPGRADE_TIMES_UP" slot0.OPEN_TACTIC = "NavalAcademyMediator:OPEN_TACTIC" slot0.GO_SHOP = "NavalAcademyMediator:GO_SHOP" slot0.ACTIVITY_OP = "NavalAcademyMediator:ACTIVITY_OP" slot0.TASK_GO = "NavalAcademyMediator:TASK_GO" slot0.GO_TASK_SCENE = "NavalAcademyMediator:GO_TASK_SCENE" slot0.OPEN_CLASS = "NavalAcademyMediator:OPEN_CLASS" slot0.GO_SCENE = "NavalAcademyMediator:GO_SCENE" slot0.OPEN_ACTIVITY_PANEL = "NavalAcademyMediator:OPEN_ACTIVITY_PANEL" slot0.OPEN_ACTIVITY_SHOP = "NavalAcademyMediator:OPEN_ACTIVITY_SHOP" slot0.OPEN_SCROLL = "NavalAcademyMediator:OPEN_SCROLL" slot0.OPEN_COMMANDER = "NavalAcademyMediator:OPEN_COMMANDER" slot0.OPEN_TROPHY_GALLERY = "NavalAcademyMediator:OPEN_TROPHY_GALLERY" function slot0.register(slot0) slot1 = getProxy(NavalAcademyProxy) slot0.viewComponent:SetCourseInfo(slot1:getCourse()) slot0.player = getProxy(PlayerProxy):getData() slot0.viewComponent:SetPlayerInfo(slot0.player, slot1:GetOilVO(), slot1:GetGoldVO(), slot1:GetClassVO()) if getProxy(ShopsProxy):getShopStreet() then slot0.viewComponent:SetMerchantInfo(slot7) end slot0.viewComponent:SetUnclaimTrophyCount(getProxy(CollectionProxy):unclaimTrophyCount()) slot0.viewComponent:SetTacticInfo(slot1:getStudents()) slot0:bind(uv0.OPEN_TACTIC, function (slot0, slot1) uv0:addSubLayers(Context.New({ mediator = NavalTacticsMediator, viewComponent = NavalTacticsLayer, data = { shipToLesson = uv0.contextData.shipToLesson }, onRemoved = slot1 })) uv0.contextData.shipToLesson = nil end) slot0:bind(uv0.OPEN_TROPHY_GALLERY, function (slot0, slot1) uv0:addSubLayers(Context.New({ mediator = TrophyGalleryMediator, viewComponent = TrophyGalleryLayer, onRemoved = slot1 })) end) slot0:bind(uv0.GO_SHOP, function (slot0) uv0:sendNotification(GAME.GO_SCENE, SCENE.SHOP, { warp = NewShopsScene.TYPE_SHOP_STREET }) end) slot0:bind(uv0.GET_RES, function (slot0, slot1) uv0:sendNotification(GAME.HARVEST_RES, slot1) end) slot0:bind(uv0.UPGRADE_FIELD, function (slot0, slot1) if uv0:getData().level < slot1:bindConfigTable()[slot1:GetLevel()].user_level then pg.TipsMgr.GetInstance():ShowTips(i18n("common_limit_level", slot4)) return end if slot5.gold < slot3.use[2] then GoShoppingMsgBox(i18n("switch_to_shop_tip_2", i18n("word_gold")), ChargeScene.TYPE_ITEM, { { 59001, slot3.use[2] - slot5.gold, slot3.use[2] } }) return end uv1:sendNotification(GAME.SHOPPING, { count = 1, id = slot1:GetUpgradeType() }) uv0:setFlag("blockResourceUpgrade", false) end) slot0:bind(uv0.UPGRADE_TIMES_UP, function (slot0, slot1) uv0:UpgradeFinish() uv1.viewComponent:SetPlayerInfo(uv2:getData(), uv0:GetOilVO(), uv0:GetGoldVO(), uv0:GetClassVO()) if slot1 then uv1.viewComponent:OpenResourcePanel(slot1) end end) slot0:bind(uv0.ACTIVITY_OP, function (slot0, slot1) uv0:sendNotification(GAME.ACTIVITY_OPERATION, slot1) end) slot0:bind(uv0.TASK_GO, function (slot0, slot1) uv0:sendNotification(GAME.TASK_GO, slot1) end) slot0:bind(uv0.GO_TASK_SCENE, function (slot0, slot1) uv0:sendNotification(GAME.GO_SCENE, SCENE.TASK, slot1) end) slot0:bind(uv0.OPEN_CLASS, function (slot0) uv0:sendNotification(GAME.GO_SCENE, SCENE.CLASS) end) slot0:bind(uv0.GO_SCENE, function (slot0, slot1) uv0:sendNotification(GAME.GO_SCENE, slot1[1], slot1[2]) end) slot0:bind(uv0.OPEN_ACTIVITY_PANEL, function (slot0, slot1) uv0:sendNotification(GAME.GO_SCENE, SCENE.ACTIVITY, { id = slot1 }) end) slot0:bind(uv0.OPEN_ACTIVITY_SHOP, function (slot0) uv0:sendNotification(GAME.GO_SCENE, SCENE.SHOP, { warp = NewShopsScene.TYPE_ACTIVITY }) end) slot0:bind(uv0.OPEN_SCROLL, function (slot0, slot1) end) slot0:bind(uv0.OPEN_COMMANDER, function (slot0) uv0:sendNotification(GAME.GO_SCENE, SCENE.COMMANDROOM, { fleetType = CommandRoomScene.FLEET_TYPE_COMMON }) end) slot1:UpgradeFinish() slot6:setFlag("blockResourceUpgrade", true) end function slot0.listNotificationInterests(slot0) return { NavalAcademyProxy.RESOURCE_UPGRADE, NavalAcademyProxy.START_LEARN_TACTICS, NavalAcademyProxy.CANCEL_LEARN_TACTICS, GAME.HARVEST_RES_DONE, PlayerProxy.UPDATED, GAME.REMOVE_LAYERS, ActivityProxy.ACTIVITY_OPERATION_DONE, GAME.BEGIN_STAGE_DONE, CollectionProxy.TROPHY_UPDATE } end function slot0.handleNotification(slot0, slot1) slot3 = slot1:getBody() if slot1:getName() == GAME.HARVEST_RES_DONE then slot0.viewComponent:GetResourceDone(slot3.type, slot3.outPut) pg.TipsMgr.GetInstance():ShowTips(i18n("battle_levelMediator_ok_takeResource")) elseif slot2 == PlayerProxy.UPDATED then slot4 = getProxy(NavalAcademyProxy) slot0.viewComponent:SetPlayerInfo(getProxy(PlayerProxy):getData(), slot4:GetOilVO(), slot4:GetGoldVO(), slot4:GetClassVO()) elseif slot2 == NavalAcademyProxy.RESOURCE_UPGRADE then slot4 = getProxy(NavalAcademyProxy) slot0.viewComponent:SetPlayerInfo(getProxy(PlayerProxy):getData(), slot4:GetOilVO(), slot4:GetGoldVO(), slot4:GetClassVO()) slot0.viewComponent:OpenResourcePanel(slot3.resVO) elseif slot2 ~= NavalAcademyProxy.START_LEARN_TACTICS then if slot2 == NavalAcademyProxy.CANCEL_LEARN_TACTICS then -- Nothing elseif slot2 == ActivityProxy.ACTIVITY_OPERATION_DONE then if getProxy(ActivityProxy):getActivityById(slot3):getConfig("type") == ActivityConst.ACTIVITY_TYPE_TASK_LIST then slot0.viewComponent:updateStudents() end elseif slot2 == GAME.BEGIN_STAGE_DONE then slot0:sendNotification(GAME.GO_SCENE, SCENE.COMBATLOAD, slot3) elseif slot2 == CollectionProxy.TROPHY_UPDATE then slot0.viewComponent:SetUnclaimTrophyCount(getProxy(CollectionProxy):unclaimTrophyCount()) slot0.viewComponent:updateTrophyReminder() end end end return slot0
0
0.693858
1
0.693858
game-dev
MEDIA
0.889442
game-dev
0.881626
1
0.881626
Consti10/FPV_VR_OS
3,413
app/src/main/cpp/Scene/OSD/Text/TEWarning.cpp
// // Created by Constantin on 8/10/2018. // #include "TEWarning.h" #include <SettingsOSDStyle.h> #define TAG "TEWarning" TEWarning::TEWarning(const TEWarning::Options& options,const BasicGLPrograms &basicGLPrograms,BatchingManager& batchingManager,TelemetryReceiver &telemetryReceiver): IUpdateable(TAG), IDrawable(TAG), mTelemetryReceiver(telemetryReceiver), mOptions(options), mGLTextObjIndices(OSDTextObj::createAll(N_CHARS_PER_TEXT_OBJ,MAX_N_TEXT_OBJ,true, TrueColor(glm::vec4(0.0f, 0, 0, 0.3f)),false, TrueColor2::WHITE,batchingManager)) { } void TEWarning::setupPosition() { float width=mWidth; float height=mHeight/3.0f; for(int i=0;i<MAX_N_TEXT_OBJ;i++){ auto& obj=mGLTextObjIndices.at((unsigned long)i); obj->setPosition(mX,mY+mHeight-(i+1)*height,width,height); obj->setBounds(OSDTextObj::MIDDLE); obj->recalculateDataIfNeeded(); } } static TrueColor getColorForWarning(int warningLevel){ if(warningLevel==1){ return TrueColor2::ORANGE; }else{ return TrueColor2::RED; } } void TEWarning::updateGL() { //every x ms, disable all elements for blinking int64_t timeMS=std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); bool blinkCounter=std::sin(timeMS/100)>0.5f; if(blinkCounter){ for(auto& i:mGLTextObjIndices){ i->setTextSafe(L""); i->recalculateDataIfNeeded(); } return; } //Batt % auto obj=mGLTextObjIndices.at(0).get(); const auto batteryPercentage=mTelemetryReceiver.getTelemetryValue(TelemetryReceiver::BATT_PERCENTAGE); const auto batteryVoltage=mTelemetryReceiver.getTelemetryValue(TelemetryReceiver::BATT_VOLTAGE); const auto batteryUsedCapacity=mTelemetryReceiver.getTelemetryValue(TelemetryReceiver::BATT_USED_CAPACITY); if(mOptions.batteryPercentage && batteryPercentage.warning>0){ obj->setTextSafe(L"BATT "+batteryPercentage.value+L"%",getColorForWarning(batteryPercentage.warning)); }else{ obj->setTextSafe(L""); } obj->recalculateDataIfNeeded(); //Batt V obj=mGLTextObjIndices.at(1).get(); if(mOptions.batteryVoltage && batteryVoltage.warning>0){ obj->setTextSafe(L"BATT V",getColorForWarning(batteryVoltage.warning)); }else{ obj->setTextSafe(L""); } obj->recalculateDataIfNeeded(); //Batt mAh used obj=mGLTextObjIndices.at(2).get(); if(mOptions.batteryMAHUsed && batteryUsedCapacity.warning>0){ obj->setTextSafe(L"BATT mAh",getColorForWarning(batteryUsedCapacity.warning)); }else{ obj->setTextSafe(L""); } obj->recalculateDataIfNeeded(); } void TEWarning::drawGL(const glm::mat4& ViewM,const glm::mat4& ProjM) { // nothing, everything is drawn by the Batching Manager } IPositionable::Rect2D TEWarning::calculatePosition(const IPositionable::Rect2D &osdOverlay) { float width=GLProgramText::getStringLength(MAX_TEXT_LENGTH_REFERENCE,mTextHeight); float height=mTextHeight*MAX_N_TEXT_OBJ; float clHeight=mTextHeight*3; float x=osdOverlay.mX+osdOverlay.mWidth/2.0f-width*0.5f; float y=osdOverlay.mY+osdOverlay.mHeight-height-clHeight; return {x,y,width,height}; }
0
0.94483
1
0.94483
game-dev
MEDIA
0.620417
game-dev
0.990276
1
0.990276
JordanTHarris/VAStateVariableFilter
19,641
JuceLibraryCode/modules/juce_gui_extra/code_editor/juce_CPlusPlusCodeTokeniserFunctions.h
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ #ifndef JUCE_CPLUSPLUSCODETOKENISERFUNCTIONS_H_INCLUDED #define JUCE_CPLUSPLUSCODETOKENISERFUNCTIONS_H_INCLUDED //============================================================================== /** Class containing some basic functions for simple tokenising of C++ code. */ struct CppTokeniserFunctions { static bool isIdentifierStart (const juce_wchar c) noexcept { return CharacterFunctions::isLetter (c) || c == '_' || c == '@'; } static bool isIdentifierBody (const juce_wchar c) noexcept { return CharacterFunctions::isLetterOrDigit (c) || c == '_' || c == '@'; } static bool isReservedKeyword (String::CharPointerType token, const int tokenLength) noexcept { static const char* const keywords2Char[] = { "if", "do", "or", nullptr }; static const char* const keywords3Char[] = { "for", "int", "new", "try", "xor", "and", "asm", "not", nullptr }; static const char* const keywords4Char[] = { "bool", "void", "this", "true", "long", "else", "char", "enum", "case", "goto", "auto", nullptr }; static const char* const keywords5Char[] = { "float", "const", "while", "break", "false", "catch", "class", "bitor", "compl", "or_eq", "short", "throw", "union", "using", "final", nullptr }; static const char* const keywords6Char[] = { "return", "and_eq", "bitand", "delete", "double", "export", "extern", "friend", "inline", "not_eq", "public", "signed", "sizeof", "static", "struct", "switch", "typeid", "xor_eq", nullptr }; static const char* const keywords7Char[] = { "nullptr", "alignas", "alignof", "default", "mutable", "private", "typedef", "virtual", "wchar_t", nullptr }; static const char* const keywordsOther[] = { "char16_t", "char32_t", "const_cast", "constexpr", "continue", "decltype", "dynamic_cast", "explicit", "namespace", "noexcept", "operator", "protected", "register", "reinterpret_cast", "static_assert", "static_cast", "template", "thread_local", "typename", "unsigned", "volatile", "@class", "@dynamic", "@end", "@implementation", "@interface", "@public", "@private", "@protected", "@property", "@synthesize", nullptr }; const char* const* k; switch (tokenLength) { case 2: k = keywords2Char; break; case 3: k = keywords3Char; break; case 4: k = keywords4Char; break; case 5: k = keywords5Char; break; case 6: k = keywords6Char; break; case 7: k = keywords7Char; break; default: if (tokenLength < 2 || tokenLength > 16) return false; k = keywordsOther; break; } for (int i = 0; k[i] != 0; ++i) if (token.compare (CharPointer_ASCII (k[i])) == 0) return true; return false; } template <typename Iterator> static int parseIdentifier (Iterator& source) noexcept { int tokenLength = 0; String::CharPointerType::CharType possibleIdentifier [100]; String::CharPointerType possible (possibleIdentifier); while (isIdentifierBody (source.peekNextChar())) { const juce_wchar c = source.nextChar(); if (tokenLength < 20) possible.write (c); ++tokenLength; } if (tokenLength > 1 && tokenLength <= 16) { possible.writeNull(); if (isReservedKeyword (String::CharPointerType (possibleIdentifier), tokenLength)) return CPlusPlusCodeTokeniser::tokenType_keyword; } return CPlusPlusCodeTokeniser::tokenType_identifier; } template <typename Iterator> static bool skipNumberSuffix (Iterator& source) { const juce_wchar c = source.peekNextChar(); if (c == 'l' || c == 'L' || c == 'u' || c == 'U') source.skip(); if (CharacterFunctions::isLetterOrDigit (source.peekNextChar())) return false; return true; } static bool isHexDigit (const juce_wchar c) noexcept { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } template <typename Iterator> static bool parseHexLiteral (Iterator& source) noexcept { if (source.peekNextChar() == '-') source.skip(); if (source.nextChar() != '0') return false; juce_wchar c = source.nextChar(); if (c != 'x' && c != 'X') return false; int numDigits = 0; while (isHexDigit (source.peekNextChar())) { ++numDigits; source.skip(); } if (numDigits == 0) return false; return skipNumberSuffix (source); } static bool isOctalDigit (const juce_wchar c) noexcept { return c >= '0' && c <= '7'; } template <typename Iterator> static bool parseOctalLiteral (Iterator& source) noexcept { if (source.peekNextChar() == '-') source.skip(); if (source.nextChar() != '0') return false; if (! isOctalDigit (source.nextChar())) return false; while (isOctalDigit (source.peekNextChar())) source.skip(); return skipNumberSuffix (source); } static bool isDecimalDigit (const juce_wchar c) noexcept { return c >= '0' && c <= '9'; } template <typename Iterator> static bool parseDecimalLiteral (Iterator& source) noexcept { if (source.peekNextChar() == '-') source.skip(); int numChars = 0; while (isDecimalDigit (source.peekNextChar())) { ++numChars; source.skip(); } if (numChars == 0) return false; return skipNumberSuffix (source); } template <typename Iterator> static bool parseFloatLiteral (Iterator& source) noexcept { if (source.peekNextChar() == '-') source.skip(); int numDigits = 0; while (isDecimalDigit (source.peekNextChar())) { source.skip(); ++numDigits; } const bool hasPoint = (source.peekNextChar() == '.'); if (hasPoint) { source.skip(); while (isDecimalDigit (source.peekNextChar())) { source.skip(); ++numDigits; } } if (numDigits == 0) return false; juce_wchar c = source.peekNextChar(); const bool hasExponent = (c == 'e' || c == 'E'); if (hasExponent) { source.skip(); c = source.peekNextChar(); if (c == '+' || c == '-') source.skip(); int numExpDigits = 0; while (isDecimalDigit (source.peekNextChar())) { source.skip(); ++numExpDigits; } if (numExpDigits == 0) return false; } c = source.peekNextChar(); if (c == 'f' || c == 'F') source.skip(); else if (! (hasExponent || hasPoint)) return false; return true; } template <typename Iterator> static int parseNumber (Iterator& source) { const Iterator original (source); if (parseFloatLiteral (source)) return CPlusPlusCodeTokeniser::tokenType_float; source = original; if (parseHexLiteral (source)) return CPlusPlusCodeTokeniser::tokenType_integer; source = original; if (parseOctalLiteral (source)) return CPlusPlusCodeTokeniser::tokenType_integer; source = original; if (parseDecimalLiteral (source)) return CPlusPlusCodeTokeniser::tokenType_integer; source = original; return CPlusPlusCodeTokeniser::tokenType_error; } template <typename Iterator> static void skipQuotedString (Iterator& source) noexcept { const juce_wchar quote = source.nextChar(); for (;;) { const juce_wchar c = source.nextChar(); if (c == quote || c == 0) break; if (c == '\\') source.skip(); } } template <typename Iterator> static void skipComment (Iterator& source) noexcept { bool lastWasStar = false; for (;;) { const juce_wchar c = source.nextChar(); if (c == 0 || (c == '/' && lastWasStar)) break; lastWasStar = (c == '*'); } } template <typename Iterator> static void skipPreprocessorLine (Iterator& source) noexcept { bool lastWasBackslash = false; for (;;) { const juce_wchar c = source.peekNextChar(); if (c == '"') { skipQuotedString (source); continue; } if (c == '/') { Iterator next (source); next.skip(); const juce_wchar c2 = next.peekNextChar(); if (c2 == '/' || c2 == '*') return; } if (c == 0) break; if (c == '\n' || c == '\r') { source.skipToEndOfLine(); if (lastWasBackslash) skipPreprocessorLine (source); break; } lastWasBackslash = (c == '\\'); source.skip(); } } template <typename Iterator> static void skipIfNextCharMatches (Iterator& source, const juce_wchar c) noexcept { if (source.peekNextChar() == c) source.skip(); } template <typename Iterator> static void skipIfNextCharMatches (Iterator& source, const juce_wchar c1, const juce_wchar c2) noexcept { const juce_wchar c = source.peekNextChar(); if (c == c1 || c == c2) source.skip(); } template <typename Iterator> static int readNextToken (Iterator& source) { source.skipWhitespace(); const juce_wchar firstChar = source.peekNextChar(); switch (firstChar) { case 0: break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': { int result = parseNumber (source); if (result == CPlusPlusCodeTokeniser::tokenType_error) { source.skip(); if (firstChar == '.') return CPlusPlusCodeTokeniser::tokenType_punctuation; } return result; } case ',': case ';': case ':': source.skip(); return CPlusPlusCodeTokeniser::tokenType_punctuation; case '(': case ')': case '{': case '}': case '[': case ']': source.skip(); return CPlusPlusCodeTokeniser::tokenType_bracket; case '"': case '\'': skipQuotedString (source); return CPlusPlusCodeTokeniser::tokenType_string; case '+': source.skip(); skipIfNextCharMatches (source, '+', '='); return CPlusPlusCodeTokeniser::tokenType_operator; case '-': { source.skip(); int result = parseNumber (source); if (result == CPlusPlusCodeTokeniser::tokenType_error) { skipIfNextCharMatches (source, '-', '='); return CPlusPlusCodeTokeniser::tokenType_operator; } return result; } case '*': case '%': case '=': case '!': source.skip(); skipIfNextCharMatches (source, '='); return CPlusPlusCodeTokeniser::tokenType_operator; case '/': { source.skip(); juce_wchar nextChar = source.peekNextChar(); if (nextChar == '/') { source.skipToEndOfLine(); return CPlusPlusCodeTokeniser::tokenType_comment; } if (nextChar == '*') { source.skip(); skipComment (source); return CPlusPlusCodeTokeniser::tokenType_comment; } if (nextChar == '=') source.skip(); return CPlusPlusCodeTokeniser::tokenType_operator; } case '?': case '~': source.skip(); return CPlusPlusCodeTokeniser::tokenType_operator; case '<': case '>': case '|': case '&': case '^': source.skip(); skipIfNextCharMatches (source, firstChar); skipIfNextCharMatches (source, '='); return CPlusPlusCodeTokeniser::tokenType_operator; case '#': skipPreprocessorLine (source); return CPlusPlusCodeTokeniser::tokenType_preprocessor; default: if (isIdentifierStart (firstChar)) return parseIdentifier (source); source.skip(); break; } return CPlusPlusCodeTokeniser::tokenType_error; } /** A class that can be passed to the CppTokeniserFunctions functions in order to parse a String. */ struct StringIterator { StringIterator (const String& s) noexcept : t (s.getCharPointer()), numChars (0) {} StringIterator (String::CharPointerType s) noexcept : t (s), numChars (0) {} juce_wchar nextChar() noexcept { if (isEOF()) return 0; ++numChars; return t.getAndAdvance(); } juce_wchar peekNextChar()noexcept { return *t; } void skip() noexcept { if (! isEOF()) { ++t; ++numChars; } } void skipWhitespace() noexcept { while (t.isWhitespace()) skip(); } void skipToEndOfLine() noexcept { while (*t != '\r' && *t != '\n' && *t != 0) skip(); } bool isEOF() const noexcept { return t.isEmpty(); } String::CharPointerType t; int numChars; }; //============================================================================== /** Takes a UTF8 string and writes it to a stream using standard C++ escape sequences for any non-ascii bytes. Although not strictly a tokenising function, this is still a function that often comes in handy when working with C++ code! Note that addEscapeChars() is easier to use than this function if you're working with Strings. @see addEscapeChars */ static void writeEscapeChars (OutputStream& out, const char* utf8, const int numBytesToRead, const int maxCharsOnLine, const bool breakAtNewLines, const bool replaceSingleQuotes, const bool allowStringBreaks) { int charsOnLine = 0; bool lastWasHexEscapeCode = false; for (int i = 0; i < numBytesToRead || numBytesToRead < 0; ++i) { const unsigned char c = (unsigned char) utf8[i]; bool startNewLine = false; switch (c) { case '\t': out << "\\t"; lastWasHexEscapeCode = false; charsOnLine += 2; break; case '\r': out << "\\r"; lastWasHexEscapeCode = false; charsOnLine += 2; break; case '\n': out << "\\n"; lastWasHexEscapeCode = false; charsOnLine += 2; startNewLine = breakAtNewLines; break; case '\\': out << "\\\\"; lastWasHexEscapeCode = false; charsOnLine += 2; break; case '\"': out << "\\\""; lastWasHexEscapeCode = false; charsOnLine += 2; break; case 0: if (numBytesToRead < 0) return; out << "\\0"; lastWasHexEscapeCode = true; charsOnLine += 2; break; case '\'': if (replaceSingleQuotes) { out << "\\\'"; lastWasHexEscapeCode = false; charsOnLine += 2; break; } // deliberate fall-through... default: if (c >= 32 && c < 127 && ! (lastWasHexEscapeCode // (have to avoid following a hex escape sequence with a valid hex digit) && CharacterFunctions::getHexDigitValue (c) >= 0)) { out << (char) c; lastWasHexEscapeCode = false; ++charsOnLine; } else if (allowStringBreaks && lastWasHexEscapeCode && c >= 32 && c < 127) { out << "\"\"" << (char) c; lastWasHexEscapeCode = false; charsOnLine += 3; } else { out << (c < 16 ? "\\x0" : "\\x") << String::toHexString ((int) c); lastWasHexEscapeCode = true; charsOnLine += 4; } break; } if ((startNewLine || (maxCharsOnLine > 0 && charsOnLine >= maxCharsOnLine)) && (numBytesToRead < 0 || i < numBytesToRead - 1)) { charsOnLine = 0; out << "\"" << newLine << "\""; lastWasHexEscapeCode = false; } } } /** Takes a string and returns a version of it where standard C++ escape sequences have been used to replace any non-ascii bytes. Although not strictly a tokenising function, this is still a function that often comes in handy when working with C++ code! @see writeEscapeChars */ static String addEscapeChars (const String& s) { MemoryOutputStream mo; writeEscapeChars (mo, s.toRawUTF8(), -1, -1, false, true, true); return mo.toString(); } }; #endif // JUCE_CPLUSPLUSCODETOKENISERFUNCTIONS_H_INCLUDED
0
0.977598
1
0.977598
game-dev
MEDIA
0.148377
game-dev
0.981518
1
0.981518
monxa/GodotIK
4,962
src/editor/godot_ik_editor_plugin.cpp
#include "godot_ik_editor_plugin.h" #include "godot_ik.h" #include <godot_cpp/classes/button.hpp> #include <godot_cpp/classes/editor_inspector_plugin.hpp> #include <godot_cpp/classes/editor_interface.hpp> #include <godot_cpp/classes/editor_settings.hpp> #include <godot_cpp/classes/editor_undo_redo_manager.hpp> #include <godot_cpp/classes/margin_container.hpp> #include <godot_cpp/classes/object.hpp> #include <godot_cpp/classes/undo_redo.hpp> #include <godot_cpp/core/error_macros.hpp> #include <godot_cpp/core/memory.hpp> #include <godot_cpp/core/object.hpp> #include <godot_cpp/variant/callable.hpp> #include <godot_cpp/variant/callable_method_pointer.hpp> #include <godot_cpp/variant/string_name.hpp> #include <godot_cpp/variant/typed_array.hpp> using namespace godot; GodotIKEditorPlugin::GodotIKEditorPlugin() { inspector_plugin = Ref(memnew(GodotIKEditorInspectorPlugin)); add_inspector_plugin(inspector_plugin); inspector_plugin->connect("request_reset_effector", callable_mp(this, &GodotIKEditorPlugin::reset_single_effector)); inspector_plugin->connect("request_reset_all_effectors", callable_mp(this, &GodotIKEditorPlugin::reset_all_effectors)); } void GodotIKEditorPlugin::_bind_methods() { } void GodotIKEditorPlugin::reset_single_effector(Object *p_effector) { GodotIKEffector *effector = Object::cast_to<GodotIKEffector>(p_effector); ERR_FAIL_NULL_MSG(effector, "[GodotIK] reset_single_effector: Effector is null or of the wrong type."); get_undo_redo()->create_action("Reset Single Effector Transform"); get_undo_redo()->add_do_method(p_effector, "set_transform_to_bone"); get_undo_redo()->add_undo_property(p_effector, "transform", effector->get_transform()); get_undo_redo()->commit_action(); } void GodotIKEditorPlugin::reset_all_effectors(Object *p_ik_controller) { GodotIK *ik_controller = Object::cast_to<GodotIK>(p_ik_controller); ERR_FAIL_NULL_MSG(ik_controller, "[GodotIK] reset_all_effectors: IK controller is null or of the wrong type."); get_undo_redo()->create_action("Reset All GodotIK Effector Transforms"); get_undo_redo()->add_do_method(ik_controller, "set_effector_transforms_to_bones"); TypedArray<GodotIKEffector> all_effectors = ik_controller->get_effectors(); for (int i = 0; i < all_effectors.size(); i++) { GodotIKEffector *effector = cast_to<GodotIKEffector>(all_effectors[i]); get_undo_redo()->add_undo_property(effector, "transform", effector->get_transform()); } get_undo_redo()->commit_action(); } // -------------------------------------------------- GodotIKEditorInspectorPlugin::GodotIKEditorInspectorPlugin() { } void GodotIKEditorInspectorPlugin::_bind_methods() { ADD_SIGNAL(MethodInfo("request_reset_effector", PropertyInfo(Variant::OBJECT, "effector"))); ADD_SIGNAL(MethodInfo("request_reset_all_effectors", PropertyInfo(Variant::OBJECT, "ik_controller"))); } bool GodotIKEditorInspectorPlugin::_can_handle(Object *p_object) const { const StringName obj_name = p_object->get_class(); if (obj_name == GodotIK::get_class_static()) { return true; } if (obj_name == GodotIKEffector::get_class_static()) { return true; } return false; } void GodotIKEditorInspectorPlugin::_parse_end(Object *p_object) { const StringName obj_name = p_object->get_class(); const float scale = EditorInterface::get_singleton()->get_editor_scale(); const float margin = EditorInterface::get_singleton()->get_editor_settings()->get_setting("interface/theme/base_margin"); const int margin_scaled = Math::round(margin * scale); MarginContainer *container = memnew(MarginContainer); container->add_theme_constant_override("margin_top", 6 * EditorInterface::get_singleton()->get_editor_scale()); container->add_theme_constant_override("margin_bottom", 6 * EditorInterface::get_singleton()->get_editor_scale()); container->add_theme_constant_override("margin_left", 4 * EditorInterface::get_singleton()->get_editor_scale()); container->add_theme_constant_override("margin_right", 4 * EditorInterface::get_singleton()->get_editor_scale()); Button *reset_button = memnew(Button); reset_button->set_h_size_flags(Control::SizeFlags::SIZE_EXPAND_FILL); if (obj_name == GodotIK::get_class_static()) { reset_button->set_text("Reset Effectors"); reset_button->set_tooltip_text("Resets all Effectors to the current [Skeleton3D] pose transform before IK is applied."); Callable c_emit_signal = Callable(this, "emit_signal").bind("request_reset_all_effectors", p_object); reset_button->connect("pressed", c_emit_signal); } if (obj_name == GodotIKEffector::get_class_static()) { reset_button->set_text("Reset Effector"); reset_button->set_tooltip_text("Resets current IKEffector to the current [Skeleton3D] pose transform before IK is applied."); Callable c_emit_signal = Callable(this, "emit_signal").bind("request_reset_effector", p_object); reset_button->connect("pressed", c_emit_signal); } container->add_child(reset_button); add_custom_control(container); }
0
0.87323
1
0.87323
game-dev
MEDIA
0.910164
game-dev
0.855876
1
0.855876
War3Source/War3Source
6,824
addons/sourcemod/scripting/War3Source_Engine_XPGoldCS.sp
#include <sourcemod> #include "W3SIncs/War3Source_Interface" public Plugin:myinfo = { name = "War3Source - Engine - XP Gold (CS)", author = "War3Source Team", description = "Give XP and Gold specific to Counter Strike to those who deserve it" }; public LoadCheck(){ return (GameCS() || GameCSGO()); } // cs new Handle:DefuseXPCvar; new Handle:PlantXPCvar; new Handle:RescueHostageXPCvar; //10 hostages? new Handle:touchedHostage[MAXPLAYERSCUSTOM]; public OnPluginStart() { LoadTranslations("w3s.engine.xpgold.txt"); for(new i=0;i<MAXPLAYERSCUSTOM;i++){ touchedHostage[i]=CreateArray(); } DefuseXPCvar=CreateConVar("war3_percent_cs_defusexp","200","Percent of kill XP awarded for defusing the bomb"); PlantXPCvar=CreateConVar("war3_percent_cs_plantxp","200","Percent of kill XP awarded for planting the bomb"); RescueHostageXPCvar=CreateConVar("war3_percent_cs_hostagerescuexp","100","Percent of kill XP awarded for rescuing a hostage"); if(GAMECSANY){ if(!HookEventEx("bomb_defused",War3Source_BombDefusedEvent)) { PrintToServer("[War3Source] Could not hook the bomb_defused event."); } if(!HookEventEx("bomb_planted",War3Source_BombPlantedEvent)) { PrintToServer("[War3Source] Could not hook the bomb_planted event."); } if(!HookEventEx("hostage_follows",War3Source_HostageFollow)) { PrintToServer("[War3Source] Could not hook the hostage_rescued event."); } if(!HookEventEx("hostage_rescued",War3Source_HostageRescuedEvent)) { PrintToServer("[War3Source] Could not hook the hostage_rescued event."); } if(!HookEventEx("hostage_killed",War3Source_HostageKilled)) { PrintToServer("[War3Source] Could not hook the hostage_rescued event."); } //for clearing hostage touch if(!HookEventEx("round_start",War3Source_RoundOverEvent)) { PrintToServer("[War3Source] Could not hook the round_end event."); } } } public War3Source_RoundOverEvent(Handle:event,const String:name[],bool:dontBroadcast) { for(new i=1;i<=MaxClients;i++){ ClearArray(touchedHostage[i]); } } public War3Source_BombDefusedEvent(Handle:event,const String:name[],bool:dontBroadcast) { if(GetEventInt(event,"userid")>0) { new client=GetClientOfUserId(GetEventInt(event,"userid")); new Float:origin[3]; GetClientAbsOrigin(client,origin); new team=GetClientTeam(client); new Float:otherorigin[3]; for(new i=1;i<=MaxClients;i++){ if(ValidPlayer(i,true)&&GetClientTeam(i)==team){ GetClientAbsOrigin(i,otherorigin); if(GetVectorDistance(origin,otherorigin)<1000.0&&War3_GetRace(i)>0){ // Called when a player defuses the bomb //new race=War3_GetRace(i); new addxp=(W3GetKillXP(i)*GetConVarInt(DefuseXPCvar))/100; new String:defusaward[64]; new String:helpdefusaward[64]; Format(defusaward,sizeof(defusaward),"%T","defusing the bomb",i); Format(helpdefusaward,sizeof(helpdefusaward),"%T","being near bomb defuse",i); W3GiveXPGold(i,XPAwardByBomb,addxp,0,i==client?defusaward:helpdefusaward); } } } } } public War3Source_BombPlantedEvent(Handle:event,const String:name[],bool:dontBroadcast) { if(GetEventInt(event,"userid")>0) { new client=GetClientOfUserId(GetEventInt(event,"userid")); new Float:origin[3]; GetClientAbsOrigin(client,origin); new team=GetClientTeam(client); new Float:otherorigin[3]; for(new i=1;i<=MaxClients;i++){ if(ValidPlayer(i,true)&&GetClientTeam(i)==team){ GetClientAbsOrigin(i,otherorigin); if(GetVectorDistance(origin,otherorigin)<1000.0&&War3_GetRace(i)>0){ // Called when a player plants the bomb //new race=War3_GetRace(i); new addxp=(W3GetKillXP(i)*GetConVarInt(PlantXPCvar))/100; new String:plantaward[64]; new String:helpplantaward[64]; Format(plantaward,sizeof(plantaward),"%T","planting the bomb",i); Format(helpplantaward,sizeof(helpplantaward),"%T","being near bomb plant",i); W3GiveXPGold(i,XPAwardByBomb,addxp,0,i==client?plantaward:helpplantaward); } } } } } public War3Source_HostageFollow(Handle:event,const String:name[],bool:dontBroadcast) { if(GetEventInt(event,"userid")>0) { new client=GetClientOfUserId(GetEventInt(event,"userid")); new hostage=GetEventInt(event,"hostage"); if(FindValueInArray(touchedHostage[client],hostage)==-1){ PushArrayCell(touchedHostage[client],hostage); //new race=War3_GetRace(client); new addxp=(W3GetKillXP(client)*GetConVarInt(RescueHostageXPCvar))/100; new String:hostageaward[64]; Format(hostageaward,sizeof(hostageaward),"%T","touching a hostage",client); W3GiveXPGold(client,XPAwardByHostage,addxp,0,hostageaward); } } } public War3Source_HostageRescuedEvent(Handle:event,const String:name[],bool:dontBroadcast) { if(GetEventInt(event,"userid")>0) { new client=GetClientOfUserId(GetEventInt(event,"userid")); // Called when a player rescues a hostage //new race=War3_GetRace(client); new addxp=(W3GetKillXP(client)*GetConVarInt(RescueHostageXPCvar))/100; new String:hostageaward[64]; Format(hostageaward,sizeof(hostageaward),"%T","rescuing a hostage",client); W3GiveXPGold(client,XPAwardByHostage,addxp,0,hostageaward); } } public War3Source_HostageKilled(Handle:event,const String:name[],bool:dontBroadcast) { if(GetEventInt(event,"userid")>0) { new client=GetClientOfUserId(GetEventInt(event,"userid")); // Called when a player rescues a hostage //new race=War3_GetRace(client); new addxp=-2*(W3GetKillXP(client)*GetConVarInt(RescueHostageXPCvar))/100; new String:hostageaward[64]; Format(hostageaward,sizeof(hostageaward),"%T","killing a hostage",client); W3GiveXPGold(client,XPAwardByHostage,addxp,0,hostageaward); } }
0
0.931373
1
0.931373
game-dev
MEDIA
0.922942
game-dev
0.809058
1
0.809058
deepnight/deepnightLibs
25,840
src/dn/heaps/HParticle.hx
package dn.heaps; #if !heaps #error "heaps is required for HParticle" #end import dn.M; import h2d.Tile; import h2d.SpriteBatch; import dn.Lib; import hxd.impl.AllocPos; import dn.TinyTween; class HParticle extends BatchElement { public static var DEFAULT_BOUNDS : h2d.col.Bounds = null; var pool : ParticlePool; public var poolIdx(default,null) : Int; var stamp : Float; public var dx : Float; public var dy : Float; public var da : Float; // alpha public var ds : Float; // scale public var dsX : Float; // scale public var dsY : Float; // scale public var dsFrict : Float; public var scaleMul : Float; public var scaleXMul : Float; public var scaleYMul : Float; public var dr : Float; public var drFrict : Float; public var frict(get,set) : Float; public var frictX : Float; public var frictY : Float; public var gx : Float; public var gy : Float; public var bounceMul : Float; public var bounds : Null<h2d.col.Bounds>; public var groundY : Null<Float>; public var groupId : Null<String>; public var fadeOutSpeed : Float; public var maxAlpha(default,set): Float; public var alphaFlicker : Float; public var customTmod : Void->Float; var x_tween(default,null) : TinyTween; var y_tween(default,null) : TinyTween; var scaleX_tween(default,null) : TinyTween; var scaleY_tween(default,null) : TinyTween; var delayedCb : Null< HParticle->Void >; var delayedCbTimeS : Float; public var lifeS(never,set) : Float; public var lifeF(never,set) : Float; var rLifeF : Float; var maxLifeF : Float; public var elapsedLifeS(get,never) : Float; public var remainingLifeS(get,never) : Float; /** From 0 (start) to 1 (death) **/ public var curLifeRatio(get,never) : Float; public var delayS(get, set) : Float; public var delayF(default, set) : Float; public var onStart : Null<Void->Void>; public var onBounce : Null<Void->Void>; public var onTouchGround : Null<HParticle->Void>; public var onUpdate : Null<HParticle->Void>; public var onFadeOutStart : Null<HParticle->Void>; public var onKill : Null<Void->Void>; public var onKillP : Null<HParticle->Void>; public var onLeaveBounds : Null<HParticle->Void>; public var killOnLifeOut : Bool; public var killed : Bool; /** If greater than 0, particle will keep its rotation aligned with movement. 1 means always strictly equal to current direction, below 1 means slower rotation tracking. **/ public var autoRotateSpeed(default,set) : Float; inline function set_autoRotateSpeed(v) return autoRotateSpeed = M.fclamp(v,0,1); public var userData : Dynamic; var fromColor : Col; var toColor : Col; var dColor : Float; var rColor : Float; public var data0 : Float; public var data1 : Float; public var data2 : Float; public var data3 : Float; public var data4 : Float; public var data5 : Float; public var data6 : Float; public var data7 : Float; var fps : Int; #if debug @:allow(dn.heaps.ParticlePool) var allocPos : AllocPos; #end private function new(p:ParticlePool, tile:Tile, fps:Int, x:Float=0., y:Float=0.) { super(tile); this.fps = fps; pool = p; poolIdx = -1; x_tween = new TinyTween(fps); y_tween = new TinyTween(fps); scaleX_tween = new TinyTween(fps); scaleY_tween = new TinyTween(fps); reset(null, x,y); } var animLib : Null<dn.heaps.slib.SpriteLib>; var animId : Null<String>; var animCursor : Float; var animXr : Float; var animYr : Float; var animLoop : Bool; var animStop : Bool; public var animSpd : Float; public inline function playAnimAndKill(lib:dn.heaps.slib.SpriteLib, k:String, spd=1.0) { animLib = lib; animId = k; animCursor = 0; animLoop = false; animSpd = spd; applyAnimFrame(); } public inline function playAnimLoop(lib:dn.heaps.slib.SpriteLib, k:String, spd=1.0) { animLib = lib; animId = k; animCursor = 0; animLoop = true; animSpd = spd; applyAnimFrame(); } public inline function playAnimAndStop(lib:dn.heaps.slib.SpriteLib, k:String, spd=1.0) { animLib = lib; animId = k; animCursor = 0; animLoop = false; animSpd = spd; animStop = true; applyAnimFrame(); } public inline function randomizeAnimCursor() { animCursor = irnd(0, animLib.getAnim(animId).length-1); applyAnimFrame(); } public inline function setScale(v:Float) scale = v; public inline function setPosition(x:Float, y:Float) { this.x = x; this.y = y; } public inline function tweenX(to:Float, durationS:Float, interp:TinyTweenInterpolation=Linear) { x_tween.start(x, to, durationS, interp); } public inline function tweenY(to:Float, durationS:Float, interp:TinyTweenInterpolation=Linear) { y_tween.start(y, to, durationS, interp); } public inline function tweenXY(toX:Float, toY:Float, durationS:Float, interp:TinyTweenInterpolation=Linear) { x_tween.start(x, toX, durationS, interp); y_tween.start(y, toY, durationS, interp); } public inline function tweenBothScales(from:Float, to:Float, durationS:Float, interp:TinyTweenInterpolation=Linear) { scaleX_tween.start(from, to, durationS, interp); scaleX = from; scaleY_tween.start(from, to, durationS, interp); scaleY = from; } public inline function tweenScaleX(from:Float, to:Float, durationS:Float, interp:TinyTweenInterpolation=Linear) { scaleX_tween.start(from, to, durationS, interp); scaleX = from; } public inline function tweenScaleY(from:Float, to:Float, durationS:Float, interp:TinyTweenInterpolation=Linear) { scaleY_tween.start(from, to, durationS, interp); scaleY = from; } public inline function squashX(s:Float, durationS=0.06) { scaleX_tween.start(scaleX*s, scaleX, durationS, Linear); scaleY_tween.start(scaleX*(2-s), scaleY, durationS, Linear); } public inline function squashY(s:Float, durationS=0.06) { scaleX_tween.start(scaleX*(2-s), scaleX, durationS, Linear); scaleY_tween.start(scaleY*s, scaleY, durationS, Linear); } @:deprecated("Use resizeTo (note: second arg is now optional)") @:noCompletion public inline function scaleTo(w:Float, h:Float) resizeTo(w,h); public inline function resizeTo(w:Float, h=-1.) { resizeXTo(w); resizeYTo(h>=0 ? h : w); } @:deprecated("Use resizeXTo") @:noCompletion public inline function scaleXTo(len:Float) resizeXTo(len); public inline function resizeXTo(len:Float) { scaleX = len/t.width; } @:deprecated("Use resizeYTo") @:noCompletion public inline function scaleYTo(len:Float) resizeYTo(len); public inline function resizeYTo(len:Float) { scaleY = len/t.height; } @:access(h2d.Tile) public inline function setTile(tile:Tile) { this.t.setPosition(tile.x, tile.y); this.t.setSize(tile.width, tile.height); this.t.dx = tile.dx; this.t.dy = tile.dy; this.t.switchTexture(tile); } public inline function mulRGB(v:Float) { r*=v; g*=v; b*=v; } public inline function isSet0() return !Math.isNaN(data0); public inline function isSet1() return !Math.isNaN(data1); public inline function isSet2() return !Math.isNaN(data2); public inline function isSet3() return !Math.isNaN(data3); public inline function isSet4() return !Math.isNaN(data4); public inline function isSet5() return !Math.isNaN(data5); public inline function isSet6() return !Math.isNaN(data6); public inline function isSet7() return !Math.isNaN(data7); public inline function initIfNull0(v:Float) if( Math.isNaN(data0) ) data0 = v; public inline function initIfNull1(v:Float) if( Math.isNaN(data1) ) data1 = v; public inline function initIfNull2(v:Float) if( Math.isNaN(data2) ) data2 = v; public inline function initIfNull3(v:Float) if( Math.isNaN(data3) ) data3 = v; public inline function initIfNull4(v:Float) if( Math.isNaN(data4) ) data4 = v; public inline function initIfNull5(v:Float) if( Math.isNaN(data5) ) data5 = v; public inline function initIfNull6(v:Float) if( Math.isNaN(data6) ) data6 = v; public inline function initIfNull7(v:Float) if( Math.isNaN(data7) ) data7 = v; public inline function inc0() return Math.isNaN(data0) ? data0=1 : ++data0; public inline function inc1() return Math.isNaN(data1) ? data1=1 : ++data1; public inline function inc2() return Math.isNaN(data2) ? data2=1 : ++data2; public inline function inc3() return Math.isNaN(data3) ? data3=1 : ++data3; public inline function inc4() return Math.isNaN(data4) ? data4=1 : ++data4; public inline function inc5() return Math.isNaN(data5) ? data5=1 : ++data5; public inline function inc6() return Math.isNaN(data6) ? data6=1 : ++data6; public inline function inc7() return Math.isNaN(data7) ? data7=1 : ++data7; inline function reset(sb:Null<SpriteBatch>, ?tile:Tile, x:Float=0., y:Float=0.) { if( tile!=null ) setTile(tile); if( batch!=sb ) { if( batch!=null ) remove(); if( sb!=null ) sb.add(this); } // Batch-element base fields setPosition(x,y); scaleX = 1; scaleY = 1; rotation = 0; r = g = b = a = 1; alpha = 1; visible = true; // Hparticle fields data0 = data1 = data2 = data3 = data4 = data5 = data6 = data7 = Math.NaN; customTmod = null; animId = null; animLib = null; scaleMul = 1; scaleXMul = scaleYMul = 1; dsFrict = 1; alphaFlicker = 0; fromColor = 0x0; dColor = rColor = Math.NaN; stamp = haxe.Timer.stamp(); setCenterRatio(0.5, 0.5); killed = false; maxAlpha = 1; dx = dy = 0; da = 0; dr = 0; ds = dsX = dsY = 0; gx = gy = 0; frictX = frictY = 1; drFrict = 1; fadeOutSpeed = 0.1; bounceMul = 0.85; delayS = 0; lifeS = 1; bounds = DEFAULT_BOUNDS; killOnLifeOut = false; groundY = null; groupId = null; autoRotateSpeed = 0; delayedCbTimeS = 0; // Tweens x_tween.reset(); y_tween.reset(); scaleX_tween.reset(); scaleY_tween.reset(); // Callbacks onStart = null; onKillP = null; onKill = null; onBounce = null; onUpdate = null; onFadeOutStart = null; onTouchGround = null; onLeaveBounds = null; delayedCb = null; } public inline function colorAnimS(from:Col, to:Col, t:Float) { fromColor = from; toColor = to; dColor = 1/(t*fps); rColor = 0; } public inline function rnd(min,max,?sign) return Lib.rnd(min,max,sign); public inline function irnd(min,max,?sign) return Lib.irnd(min,max,sign); inline function set_maxAlpha(v) { if( alpha>v ) alpha = v; maxAlpha = v; return v; } /** Set pivot ratios. If `pixelPerfect` is true (default), then pivots will snap to closest pixel. **/ public inline function setCenterRatio(xr:Float, yr:Float, pixelPerfect=false) { if( pixelPerfect ) { xr = M.round(t.width*xr) / t.width; yr = M.round(t.height*yr) / t.height; } t.setCenterRatio(xr,yr); animXr = xr; animYr = yr; } inline function set_frict(v) return frictX = frictY = v; inline function get_frict() return ( frictX + frictY ) * 0.5; public inline function uncolorize() r = g = b = 1; public inline function colorize(c:Col, ratio=1.0) { c.colorizeH2dBatchElement(this, ratio); } public inline function colorizeRandomDarker(c:Col, range:Float) { colorize( c.toBlack( rnd(0,range) ) ); } public inline function colorizeRandomLighter(c:Col, range:Float) { colorize( c.toWhite( rnd(0,range) ) ); } public inline function randScale(min:Float, max:Float, sign=false) { setScale( rnd(min, max, sign) ); } public inline function colorizeRandom(min:Col, max:Col) { min.interpolate( max, rnd(0,1) ).colorizeH2dBatchElement(this, 1); } public inline function randFlipXY() { scaleX *= RandomTools.sign(); scaleY *= RandomTools.sign(); } public inline function randFlipX() scaleX *= RandomTools.sign(); public inline function randFlipY() scaleY *= RandomTools.sign(); public inline function randRotation() rotation = RandomTools.fullCircle(); public inline function randRotationAndFlips() { randFlipXY(); randRotation(); } public inline function delayCallback(cb:HParticle->Void, sec:Float) { delayedCb = cb; delayedCbTimeS = sec; } public inline function fade(targetAlpha:Float, fadeInSpd=1.0, fadeOutSpd=1.0) { this.alpha = 0; maxAlpha = targetAlpha; da = targetAlpha*0.1*fadeInSpd; fadeOutSpeed = targetAlpha*0.1*fadeOutSpd; } public inline function setFadeS(targetAlpha:Float, fadeInDurationS:Float, fadeOutDurationS:Float) : Void { this.alpha = 0; maxAlpha = targetAlpha; if( fadeInDurationS<=0 ) alpha = maxAlpha; else da = targetAlpha / (fadeInDurationS*fps); if( fadeOutDurationS<=0 ) fadeOutSpeed = 99; else fadeOutSpeed = targetAlpha / (fadeOutDurationS*fps); } public inline function fadeIn(alpha:Float, spd:Float) { this.alpha = 0; maxAlpha = alpha; da = spd; } public inline function autoRotate(spd=1.0) { autoRotateSpeed = spd; rotation = getMoveAng(); } public inline function disableAutoRotate() { autoRotateSpeed = 0; } @:keep public function toString() { return 'HPart@$x,$y (lifeS=$remainingLifeS)'; } public inline function clone() : HParticle { var s = new haxe.Serializer(); s.useCache = true; s.serialize(this); return haxe.Unserializer.run( s.toString() ); } inline function set_delayS(d:Float):Float { delayF = d*fps; return d; } inline function get_delayS() return delayF/fps; inline function set_delayF(d:Float):Float { d = M.fmax(0,d); visible = !killed && d <= 0; return delayF = d; } inline function set_lifeS(v:Float) { rLifeF = maxLifeF = M.fmax(fps*v,0); return v; } inline function set_lifeF(v:Float) { rLifeF = maxLifeF = M.fmax(v,0); return v; } public inline function mulLife(f:Float) { rLifeF*=f; } inline function get_elapsedLifeS() return (maxLifeF-rLifeF)/fps; inline function get_remainingLifeS() return rLifeF/fps; inline function get_curLifeRatio() return 1-rLifeF/maxLifeF; // 0(start) -> 1(end) inline function onKillCallbacks() { var any = false; if( onKillP!=null ) { var cb = onKillP; onKillP = null; cb(this); any = true; } if( onKill!=null ) { var cb = onKill; onKill = null; cb(); any = true; } return any; } /** Remove particle immediately without fading out **/ public inline function kill() { if( !killed ) { onKillCallbacks(); alpha = 0; lifeS = 0; delayS = 0; killed = true; visible = false; @:privateAccess pool.free(this); } } public inline function fadeOutAndKill(fadeOutDurationS:Float) { if( fadeOutDurationS<=0 ) kill(); else { lifeS = 0; fadeOutSpeed = M.fmax( alpha / (fadeOutDurationS*fps), fadeOutSpeed ); } } /** Lower life to 0 and start fading out **/ public inline function timeoutNow() { rLifeF = 0; } function dispose() { reset(null); pool = null; bounds = null; x_tween = null; y_tween = null; scaleX_tween = null; scaleY_tween = null; } public inline function isAlive() { return rLifeF>0; } public inline function getSpeed() { return Math.sqrt( dx*dx + dy*dy ); } public inline function sign() { return Std.random(2)*2-1; } public inline function randFloat(f:Float) { return Std.random( Std.int(f*10000) ) / 10000; } public inline function setGravityAng(a:Float, spd:Float) { gx = Math.cos(a)*spd; gy = Math.sin(a)*spd; } public inline function cancelVelocities() { dx = dy = gx = gy = 0; } public inline function moveAng(a:Float, spd:Float) { dx = Math.cos(a)*spd; dy = Math.sin(a)*spd; } public inline function moveTo(x:Float,y:Float, spd:Float) { var a = Math.atan2(y-this.y, x-this.x); dx = Math.cos(a)*spd; dy = Math.sin(a)*spd; } public inline function moveAwayFrom(x:Float,y:Float, spd:Float) { var a = Math.atan2(y-this.y, x-this.x); dx = -Math.cos(a)*spd; dy = -Math.sin(a)*spd; } public inline function getMoveAng() { return Math.atan2(dy,dx); } public inline function stretchTo(tx:Float, ty:Float) { scaleX = M.dist(x,y, tx,ty) / t.width; rotation = Math.atan2(ty-y, tx-x); } inline function applyAnimFrame() { var f = animLib.getAnim(animId)[Std.int(animCursor)]; var fd = animLib.getFrameData(animId, f); var tile = animLib.getTile( animId, f ); t.setPosition(tile.x, tile.y); t.setSize(tile.width, tile.height); t.dx = -Std.int(fd.realWid * animXr + fd.realX); t.dy = -Std.int(fd.realHei * animYr + fd.realY); } public inline function optimPow(v:Float, p:Float) { return ( p==1 || v==0 || v==1 ) ? v : Math.pow(v,p); } inline function updatePart(tmod:Float) { if( customTmod!=null ) tmod = customTmod(); delayF -= tmod; if( delayF<=0 && !killed ) { // Start callback if( onStart!=null ) { var cb = onStart; onStart = null; cb(); } // Anim if( animId!=null ) { applyAnimFrame(); animCursor+=animSpd*tmod; if( animCursor>=animLib.getAnim(animId).length ) { if( animLoop ) animCursor-=animLib.getAnim(animId).length; else if (animStop) { animId = null; animLib = null; } else { animId = null; animLib = null; animCursor = 0; kill(); } } } if( !killed ) { // Custom movement tweens if( x_tween.update(tmod) ) x = x_tween.curValue; if( y_tween.update(tmod) ) y = y_tween.curValue; // Gravity dx += gx * tmod; dy += gy * tmod; // Velocities x += dx * tmod; y += dy * tmod; // Frictions if( frictX==frictY ){ var frictTmod = optimPow(frictX, tmod); dx *= frictTmod; dy *= frictTmod; } else { dx *= optimPow(frictX, tmod); dy *= optimPow(frictY, tmod); } // Ground if( groundY!=null && dy>0 && y>=groundY ) { if( bounceMul==0 ) gy = 0; dy = -dy*bounceMul; y = groundY-1; if( onBounce!=null ) onBounce(); if( onTouchGround!=null ) onTouchGround(this); } if( !killed ) { // Could have been killed in onBounce rotation += dr * tmod; dr *= optimPow(drFrict, tmod); var scaleMulTmod = optimPow(scaleMul, tmod); // X scale if( scaleX_tween.isCurrentlyRunning() ) { scaleX_tween.update(tmod); scaleX = scaleX_tween.curValue; } else { scaleX += (ds+dsX) * tmod; scaleX *= scaleMulTmod; scaleX *= optimPow(scaleXMul, tmod); } // Y scale if( scaleY_tween.isCurrentlyRunning() ) { scaleY_tween.update(tmod); scaleY = scaleY_tween.curValue; } else { scaleY += (ds+dsY) * tmod; scaleY *= scaleMulTmod; scaleY *= optimPow(scaleYMul, tmod); } ds *= optimPow(dsFrict, tmod); dsX *= optimPow(dsFrict, tmod); dsY *= optimPow(dsFrict, tmod); if( autoRotateSpeed!=0 ) rotation += M.radSubstract( getMoveAng(), rotation ) * M.fmin(1,autoRotateSpeed*tmod); // Color animation if( !Math.isNaN(rColor) ) { rColor = M.fclamp(rColor+dColor*tmod, 0, 1); colorize( fromColor.interpolate(toColor, rColor) ); } // Fade in if ( rLifeF > 0 && da != 0 ) { alpha += da * tmod; if( alpha>maxAlpha ) { da = 0; alpha = maxAlpha; } } // Fade out start callback if( onFadeOutStart!=null && rLifeF>0 && rLifeF-tmod<=0 ) onFadeOutStart(this); rLifeF -= tmod; // Fade out (life) if( rLifeF <= 0 ) alpha -= fadeOutSpeed * tmod; else if( alphaFlicker>0 ) alpha = M.fclamp( alpha + rnd(0, alphaFlicker, true), 0, maxAlpha ); // Check bounds if( bounds!=null && !( x>=bounds.xMin && x<bounds.xMax && y>=bounds.yMin && y<bounds.yMax ) ) { if( onLeaveBounds!=null ) onLeaveBounds(this); kill(); } else if( rLifeF<=0 && ( alpha<=0 || killOnLifeOut ) ) { // Timed out kill(); } else if( onUpdate!=null ) { // Update CB onUpdate(this); } // Delayed callback if( !killed && delayedCb!=null && elapsedLifeS>=delayedCbTimeS ) { var cb = delayedCb; delayedCb = null; delayedCbTimeS = 0; cb(this); } } } } } } /************************************************************ Particle Pool manager ************************************************************/ class ParticlePool { var all : haxe.ds.Vector<HParticle>; var nalloc : Int; public var size(get,never) : Int; inline function get_size() return all.length; public var allocated(get,never) : Int; inline function get_allocated() return nalloc; public function new(tile:h2d.Tile, count:Int, fps:Int) { all = new haxe.ds.Vector(count); nalloc = 0; for(i in 0...count) { var p = @:privateAccess new HParticle(this, tile.clone(), fps); all[i] = p; p.kill(); } } public inline function alloc(sb:SpriteBatch, t:h2d.Tile, x:Float, y:Float, ?pos: AllocPos) : HParticle { return if( nalloc<all.length ) { // Use a killed part var p = all[nalloc]; @:privateAccess p.reset(sb, t, x,y); @:privateAccess p.poolIdx = nalloc; nalloc++; #if debug p.allocPos = pos; #end p; } else { // Find oldest active part var best : HParticle = null; for(p in all) if( best==null || @:privateAccess p.stamp<=@:privateAccess best.stamp ) // TODO optimize that best = p; @:privateAccess best.onKillCallbacks(); @:privateAccess best.reset(sb, t, x, y); #if debug best.allocPos = pos; #end best; } } /** Direct access to a HParticle by its index **/ public inline function get(idx:Int) return idx>=0 && idx<nalloc ? all[idx] : null; /** When a particle is killed, pick last allocated one and move it here. This prevents "gaps" in the pool. **/ inline function free(kp:HParticle) { if( all!=null ) { if( nalloc>1 ) { var idx = @:privateAccess kp.poolIdx; var tmp = all[idx]; all[idx] = all[nalloc-1]; @:privateAccess all[idx].poolIdx = idx; all[nalloc-1] = tmp; nalloc--; } else nalloc = 0; } } /** Count active particles **/ @:noCompletion @:deprecated("Use `allocated` var") public inline function count() return nalloc; /** Destroy every active particles **/ public function clear() { // Because new particles might be allocated during onKill() callbacks, // it's sometimes necessary to repeat the clearing loop multiple times. var repeat = false; var maxRepeats = 10; var p : HParticle = null; do { repeat = false; for(i in 0...size) { p = all[i]; if( @:privateAccess p.onKillCallbacks() ) repeat = true; @:privateAccess p.reset(null); p.visible = false; } if( repeat && maxRepeats--<=0 ) throw("Infinite loop during clear: an onKill() callback is repeatingly allocating new particles."); } while( repeat ); } @:noCompletion @:deprecated("Use clear()") public inline function killAll() clear(); public inline function killAllWithFade() { for( i in 0...nalloc) { all[i].lifeS = 0; all[i].fadeOutSpeed = M.fmax(all[i].fadeOutSpeed, 0.03); } } public function dispose() { for(p in all) @:privateAccess p.dispose(); all = null; } public inline function getAllocatedRatio() return allocated/size; public inline function update(tmod:Float, ?updateCb:HParticle->Void) { var i = 0; var p : HParticle; while( i < nalloc ) { p = all[i]; @:privateAccess p.updatePart(tmod); if( !p.killed ) { if( updateCb!=null ) updateCb( p ); i++; } } } } /************************************************************ Particle auto emitter ************************************************************/ class Emitter { public var id : Null<String>; public var x : Float; public var y : Float; public var wid : Float; public var hei : Float; public var cd : dn.Cooldown; public var delayer : dn.Delayer; /** If this method is set, it should return TRUE to enable the emitter or FALSE to disable it. **/ public var activeCond : Null<Void->Bool>; /** Active state of the emitter **/ public var active(default,set) : Bool; public var tmod : Float; public var destroyed(default,null) : Bool; /** Frequency (in seconds) of the `onUpdate` calls **/ public var tickS : Float; public var padding : Int; public var top(get,never) : Float; inline function get_top() return y; public var bottom(get,never) : Float; inline function get_bottom() return y+hei-1; public var left(get,never) : Float; inline function get_left() return x; public var right(get,never) : Float; inline function get_right() return x+wid-1; var permanent = true; public function new(?id:String, fps:Int) { tickS = 0; this.id = id; destroyed = false; x = y = 0; wid = hei = 0; padding = 0; active = true; delayer = new Delayer(fps); cd = new Cooldown(fps); } public inline function setPosition(x,y, ?w, ?h) { this.x = x; this.y = y; if( w!=null ) wid = w; if( h!=null ) hei = h; if( h==null && w!=null ) hei = w; } public inline function setSize(w, h) { wid = w; hei = h; } public inline function setDurationS(t:Float) { cd.setS("emitterLife", t); permanent = false; } public dynamic function onActivate() {} public dynamic function onDeactivate() {} public dynamic function onUpdate() {} public dynamic function onDispose() {} inline function set_active(v:Bool) { if( v==active || destroyed ) return active; active = v; if( active ) onActivate(); else onDeactivate(); return active; } public function dispose() { if( destroyed ) return; destroyed = true; cd.dispose(); delayer.dispose(); onDispose(); activeCond = null; cd = null; } public inline function update(tmod:Float) { if( activeCond!=null ) active = activeCond(); if( active && !destroyed ) { this.tmod = tmod; cd.update(tmod); delayer.update(tmod); if( tickS<=0 || !cd.has("emitterTick") ) { onUpdate(); cd.setS("emitterTick", tickS); } if( !permanent && !cd.has("emitterLife") ) dispose(); } } }
0
0.891218
1
0.891218
game-dev
MEDIA
0.525644
game-dev,graphics-rendering
0.958132
1
0.958132
natanielruiz/android-yolo
15,156
jni-build/jni/include/external/protobuf/src/google/protobuf/map_field_test.cc
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <map> #include <memory> #ifndef _SHARED_PTR_H #include <google/protobuf/stubs/shared_ptr.h> #endif #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/arena.h> #include <google/protobuf/map.h> #include <google/protobuf/arena_test_util.h> #include <google/protobuf/map_unittest.pb.h> #include <google/protobuf/map_test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/map_field_inl.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/wire_format_lite_inl.h> #include <gtest/gtest.h> namespace google { namespace protobuf { namespace internal { using unittest::TestAllTypes; class MapFieldBaseStub : public MapFieldBase { public: typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; MapFieldBaseStub() {} explicit MapFieldBaseStub(Arena* arena) : MapFieldBase(arena) {} void SyncRepeatedFieldWithMap() const { MapFieldBase::SyncRepeatedFieldWithMap(); } void SyncMapWithRepeatedField() const { MapFieldBase::SyncMapWithRepeatedField(); } // Get underlined repeated field without synchronizing map. RepeatedPtrField<Message>* InternalRepeatedField() { return repeated_field_; } bool IsMapClean() { return state_ != 0; } bool IsRepeatedClean() { return state_ != 1; } void SetMapDirty() { state_ = 0; } void SetRepeatedDirty() { state_ = 1; } bool ContainsMapKey(const MapKey& map_key) const { return false; } bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) { return false; } bool DeleteMapValue(const MapKey& map_key) { return false; } bool EqualIterator(const MapIterator& a, const MapIterator& b) const { return false; } int size() const { return 0; } void MapBegin(MapIterator* map_iter) const {} void MapEnd(MapIterator* map_iter) const {} void InitializeIterator(MapIterator* map_iter) const {} void DeleteIterator(MapIterator* map_iter) const {} void CopyIterator(MapIterator* this_iterator, const MapIterator& other_iterator) const {} void IncreaseIterator(MapIterator* map_iter) const {} void SetDefaultMessageEntry(const Message* message) const {} const Message* GetDefaultMessageEntry() const { return NULL; } }; class MapFieldBasePrimitiveTest : public ::testing::Test { protected: typedef MapField<int32, int32, WireFormatLite::TYPE_INT32, WireFormatLite::TYPE_INT32, false> MapFieldType; MapFieldBasePrimitiveTest() { // Get descriptors map_descriptor_ = unittest::TestMap::descriptor() ->FindFieldByName("map_int32_int32") ->message_type(); key_descriptor_ = map_descriptor_->FindFieldByName("key"); value_descriptor_ = map_descriptor_->FindFieldByName("value"); // Build map field default_entry_ = MessageFactory::generated_factory()->GetPrototype(map_descriptor_); map_field_.reset(new MapFieldType(default_entry_)); map_field_base_ = map_field_.get(); map_ = map_field_->MutableMap(); initial_value_map_[0] = 100; initial_value_map_[1] = 101; map_->insert(initial_value_map_.begin(), initial_value_map_.end()); EXPECT_EQ(2, map_->size()); } google::protobuf::scoped_ptr<MapFieldType> map_field_; MapFieldBase* map_field_base_; Map<int32, int32>* map_; const Descriptor* map_descriptor_; const FieldDescriptor* key_descriptor_; const FieldDescriptor* value_descriptor_; const Message* default_entry_; std::map<int32, int32> initial_value_map_; // copy of initial values inserted }; TEST_F(MapFieldBasePrimitiveTest, SpaceUsedExcludingSelf) { EXPECT_LT(0, map_field_base_->SpaceUsedExcludingSelf()); } TEST_F(MapFieldBasePrimitiveTest, GetRepeatedField) { const RepeatedPtrField<Message>& repeated = reinterpret_cast<const RepeatedPtrField<Message>&>( map_field_base_->GetRepeatedField()); EXPECT_EQ(2, repeated.size()); for (int i = 0; i < repeated.size(); i++) { const Message& message = repeated.Get(i); int key = message.GetReflection()->GetInt32(message, key_descriptor_); int value = message.GetReflection()->GetInt32(message, value_descriptor_); EXPECT_EQ(value, initial_value_map_[key]); } } TEST_F(MapFieldBasePrimitiveTest, MutableRepeatedField) { RepeatedPtrField<Message>* repeated = reinterpret_cast<RepeatedPtrField<Message>*>( map_field_base_->MutableRepeatedField()); EXPECT_EQ(2, repeated->size()); for (int i = 0; i < repeated->size(); i++) { const Message& message = repeated->Get(i); int key = message.GetReflection()->GetInt32(message, key_descriptor_); int value = message.GetReflection()->GetInt32(message, value_descriptor_); EXPECT_EQ(value, initial_value_map_[key]); } } TEST_F(MapFieldBasePrimitiveTest, Arena) { // Allocate a large initial block to avoid mallocs during hooked test. std::vector<char> arena_block(128 * 1024); ArenaOptions options; options.initial_block = &arena_block[0]; options.initial_block_size = arena_block.size(); Arena arena(options); { // TODO(liujisi): Re-write the test to ensure the memory for the map and // repeated fields are allocated from arenas. // NoHeapChecker no_heap; MapFieldType* map_field = Arena::CreateMessage<MapFieldType>(&arena, default_entry_); // Set content in map (*map_field->MutableMap())[100] = 101; // Trigger conversion to repeated field. map_field->GetRepeatedField(); } { // TODO(liujisi): Re-write the test to ensure the memory for the map and // repeated fields are allocated from arenas. // NoHeapChecker no_heap; MapFieldBaseStub* map_field = Arena::CreateMessage<MapFieldBaseStub>(&arena); // Trigger conversion to repeated field. EXPECT_TRUE(map_field->MutableRepeatedField() != NULL); } } namespace { enum State { CLEAN, MAP_DIRTY, REPEATED_DIRTY }; } // anonymous namespace class MapFieldStateTest : public testing::TestWithParam<State> { public: protected: typedef MapField<int32, int32, WireFormatLite::TYPE_INT32, WireFormatLite::TYPE_INT32, false> MapFieldType; typedef MapFieldLite<int32, int32, WireFormatLite::TYPE_INT32, WireFormatLite::TYPE_INT32, false> MapFieldLiteType; MapFieldStateTest() : state_(GetParam()) { // Build map field const Descriptor* map_descriptor = unittest::TestMap::descriptor() ->FindFieldByName("map_int32_int32") ->message_type(); default_entry_ = MessageFactory::generated_factory()->GetPrototype(map_descriptor); map_field_.reset(new MapFieldType(default_entry_)); map_field_base_ = map_field_.get(); Expect(map_field_.get(), MAP_DIRTY, 0, 0, true); switch (state_) { case CLEAN: AddOneStillClean(map_field_.get()); break; case MAP_DIRTY: MakeMapDirty(map_field_.get()); break; case REPEATED_DIRTY: MakeRepeatedDirty(map_field_.get()); break; default: break; } } void AddOneStillClean(MapFieldType* map_field) { MapFieldBase* map_field_base = map_field; Map<int32, int32>* map = map_field->MutableMap(); (*map)[0] = 0; map_field_base->GetRepeatedField(); Expect(map_field, CLEAN, 1, 1, false); } void MakeMapDirty(MapFieldType* map_field) { Map<int32, int32>* map = map_field->MutableMap(); (*map)[0] = 0; Expect(map_field, MAP_DIRTY, 1, 0, true); } void MakeRepeatedDirty(MapFieldType* map_field) { MakeMapDirty(map_field); MapFieldBase* map_field_base = map_field; map_field_base->MutableRepeatedField(); Map<int32, int32>* map = implicit_cast<MapFieldLiteType*>(map_field) ->MapFieldLiteType::MutableMap(); map->clear(); Expect(map_field, REPEATED_DIRTY, 0, 1, false); } void Expect(MapFieldType* map_field, State state, int map_size, int repeated_size, bool is_repeated_null) { MapFieldBase* map_field_base = map_field; MapFieldBaseStub* stub = reinterpret_cast<MapFieldBaseStub*>(map_field_base); Map<int32, int32>* map = implicit_cast<MapFieldLiteType*>(map_field) ->MapFieldLiteType::MutableMap(); RepeatedPtrField<Message>* repeated_field = stub->InternalRepeatedField(); switch (state) { case MAP_DIRTY: EXPECT_FALSE(stub->IsMapClean()); EXPECT_TRUE(stub->IsRepeatedClean()); break; case REPEATED_DIRTY: EXPECT_TRUE(stub->IsMapClean()); EXPECT_FALSE(stub->IsRepeatedClean()); break; case CLEAN: EXPECT_TRUE(stub->IsMapClean()); EXPECT_TRUE(stub->IsRepeatedClean()); break; default: FAIL(); } EXPECT_EQ(map_size, map->size()); if (is_repeated_null) { EXPECT_TRUE(repeated_field == NULL); } else { EXPECT_EQ(repeated_size, repeated_field->size()); } } google::protobuf::scoped_ptr<MapFieldType> map_field_; MapFieldBase* map_field_base_; State state_; const Message* default_entry_; }; INSTANTIATE_TEST_CASE_P(MapFieldStateTestInstance, MapFieldStateTest, ::testing::Values(CLEAN, MAP_DIRTY, REPEATED_DIRTY)); TEST_P(MapFieldStateTest, GetMap) { map_field_->GetMap(); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), CLEAN, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } } TEST_P(MapFieldStateTest, MutableMap) { map_field_->MutableMap(); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } } TEST_P(MapFieldStateTest, MergeFromClean) { MapFieldType other(default_entry_); AddOneStillClean(&other); map_field_->MergeFrom(other); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } Expect(&other, CLEAN, 1, 1, false); } TEST_P(MapFieldStateTest, MergeFromMapDirty) { MapFieldType other(default_entry_); MakeMapDirty(&other); map_field_->MergeFrom(other); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } Expect(&other, MAP_DIRTY, 1, 0, true); } TEST_P(MapFieldStateTest, MergeFromRepeatedDirty) { MapFieldType other(default_entry_); MakeRepeatedDirty(&other); map_field_->MergeFrom(other); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } Expect(&other, CLEAN, 1, 1, false); } TEST_P(MapFieldStateTest, SwapClean) { MapFieldType other(default_entry_); AddOneStillClean(&other); map_field_->Swap(&other); Expect(map_field_.get(), CLEAN, 1, 1, false); switch (state_) { case CLEAN: Expect(&other, CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(&other, MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(&other, REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, SwapMapDirty) { MapFieldType other(default_entry_); MakeMapDirty(&other); map_field_->Swap(&other); Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); switch (state_) { case CLEAN: Expect(&other, CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(&other, MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(&other, REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, SwapRepeatedDirty) { MapFieldType other(default_entry_); MakeRepeatedDirty(&other); map_field_->Swap(&other); Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); switch (state_) { case CLEAN: Expect(&other, CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(&other, MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(&other, REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, Clear) { map_field_->Clear(); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 0, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 0, 0, true); } } TEST_P(MapFieldStateTest, SpaceUsedExcludingSelf) { map_field_base_->SpaceUsedExcludingSelf(); switch (state_) { case CLEAN: Expect(map_field_.get(), CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, GetMapField) { map_field_base_->GetRepeatedField(); if (state_ != REPEATED_DIRTY) { Expect(map_field_.get(), CLEAN, 1, 1, false); } else { Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); } } TEST_P(MapFieldStateTest, MutableMapField) { map_field_base_->MutableRepeatedField(); if (state_ != REPEATED_DIRTY) { Expect(map_field_.get(), REPEATED_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); } } } // namespace internal } // namespace protobuf } // namespace google
0
0.947076
1
0.947076
game-dev
MEDIA
0.735937
game-dev,testing-qa
0.905244
1
0.905244
ismail0234/Subnautica-Below-Zero-Multiplayer
2,734
Subnautica.Events/Patches/Events/Creatures/Freezing.cs
namespace Subnautica.Events.Patches.Events.Creatures { using System; using HarmonyLib; using Subnautica.API.Enums; using Subnautica.API.Extensions; using Subnautica.API.Features; using Subnautica.Events.EventArgs; using UnityEngine; [HarmonyPatch] public class Freezing { /** * * Fonksiyonu yamalar. * * @author Ismail <ismaiil_0234@hotmail.com> * */ [HarmonyPrefix] [HarmonyPatch(typeof(global::CreatureFrozenMixin), nameof(global::CreatureFrozenMixin.Freeze))] private static bool CreatureFrozenMixin_Freeze(global::CreatureFrozenMixin __instance, float endTime) { if (!Network.IsMultiplayerActive || EventBlocker.IsEventBlocked(ProcessType.CreatureFreeze)) { return true; } if (!__instance.enabled) { return false; } try { CreatureFreezingEventArgs args = new CreatureFreezingEventArgs(__instance.gameObject.GetIdentityId(), endTime - Time.time); Handlers.Creatures.OnFreezing(args); return args.IsAllowed; } catch (Exception e) { Log.Error($"Freezed.Prefix: {e}\n{e.StackTrace}"); } return true; } /** * * Fonksiyonu yamalar. * * @author Ismail <ismaiil_0234@hotmail.com> * */ [HarmonyPrefix] [HarmonyPatch(typeof(global::Brinicle), nameof(global::Brinicle.FreezeInternal))] private static bool CreatureFrozenMixin_Freeze(global::Brinicle __instance, GameObject go) { if (!Network.IsMultiplayerActive || !go.GetTechType().IsSynchronizedCreature()) { return true; } if (__instance.state != Brinicle.State.Grow && __instance.state != Brinicle.State.Enabled) { return false; } if (go.TryGetComponent<global::FrozenMixin>(out var component) && !component.IsFrozenInsideIce()) { try { CreatureFreezingEventArgs args = new CreatureFreezingEventArgs(go.GetIdentityId(), float.PositiveInfinity, __instance.gameObject.GetIdentityId()); Handlers.Creatures.OnFreezing(args); return args.IsAllowed; } catch (Exception e) { Log.Error($"Freezed.Prefix: {e}\n{e.StackTrace}"); } } return false; } } }
0
0.904339
1
0.904339
game-dev
MEDIA
0.913414
game-dev
0.880281
1
0.880281
3ddelano/epic-online-services-godot
1,214
sample/scenes/LoginView/EnterCredentials.gd
extends VBoxContainer signal perform_login @onready var id_label = $IdLabel @onready var token_label = $TokenLabel @onready var id_lineedit = $IdLineEdit @onready var token_lineedit = $TokenLineEdit func _ready() -> void: token_lineedit.text_submitted.connect(func(_new_text): perform_login.emit()) func set_helper_texts(id_help: String, token_help: String): if id_help != "": id_label.text = id_help id_label.visible = true id_lineedit.visible = true else: id_label.visible = false id_lineedit.visible = false if token_help != "": token_label.text = token_help token_label.visible = true token_lineedit.visible = true else: token_label.visible = false token_lineedit.visible = false func set_id_text(text: String): id_label.text = text func set_token_text(text: String): token_label.text = text func set_id_value(text: String): id_lineedit.text = text func get_id_value() -> String: return id_lineedit.text func get_token_value() -> String: return token_lineedit.text func reset_lineedits(): id_lineedit.text = "" token_lineedit.text = "" func _notification(what: int) -> void: if what == NOTIFICATION_VISIBILITY_CHANGED: if visible: reset_lineedits()
0
0.827408
1
0.827408
game-dev
MEDIA
0.431987
game-dev
0.853311
1
0.853311
LostArtefacts/TR-Rando
14,680
TRRandomizerCore/Editors/TR2ClassicEditor.cs
using Newtonsoft.Json; using System.Drawing; using TRGE.Coord; using TRGE.Core; using TRImageControl; using TRLevelControl.Model; using TRRandomizerCore.Helpers; using TRRandomizerCore.Processors; using TRRandomizerCore.Randomizers; using TRRandomizerCore.Textures; namespace TRRandomizerCore.Editors; public class TR2ClassicEditor : TR2LevelEditor, ISettingsProvider { private static readonly Point _regularBadgePos = new(1467, 26); private static readonly Point _goldBadgePos = new(1719, 718); private static readonly Point _comboBadgePos = new(29, 880); public RandomizerSettings Settings { get; private set; } public TR2ClassicEditor(TRDirectoryIOArgs args, TREdition edition) : base(args, edition) { } protected override void ApplyConfig(Config config) { Settings = new() { ExcludableEnemies = JsonConvert.DeserializeObject<Dictionary<short, string>>(File.ReadAllText("Resources/TR2/Restrictions/excludable_enemies.json")) }; Settings.ApplyConfig(config); } protected override void StoreConfig(Config config) { Settings.StoreConfig(config); } protected override int GetSaveTarget(int numLevels) { int target = base.GetSaveTarget(numLevels); if (Settings.RandomizeGameStrings || Settings.ReassignPuzzleItems) { target++; } if (Settings.RandomizeNightMode) { target += numLevels; if (!Settings.RandomizeTextures) { // Texture randomizer will run if night mode is on to ensure skyboxes and such like match target += numLevels; } } if (Settings.RandomizeSecrets) { target += numLevels; } if (Settings.RandomizeSecretRewardsPhysical) { target += numLevels; } if (Settings.RandomizeAudio) { target += numLevels; } if (Settings.RandomizeItems) { target += 2 * numLevels; if (Settings.RandomizeItemSprites) { target += numLevels; } } if (Settings.RandomizeStartPosition) { target += numLevels; } // TRX pre-processing target += numLevels; if (Settings.RandomizeEnemies) { // 3 for multithreading cross-level work target += Settings.CrossLevelEnemies ? numLevels * 3 : numLevels; } if (Settings.RandomizeTextures) { // *3 because of multithreaded approach target += numLevels * 3; } if (Settings.RandomizeOutfits) { // *2 because of multithreaded approach target += numLevels * 2; } // Environment randomizer always runs target += numLevels * 2; return target; } protected override void SaveImpl(AbstractTRScriptEditor scriptEditor, TRSaveMonitor monitor) { var levels = scriptEditor.EnabledScriptedLevels.Cast<TRXScriptedLevel>().ToList(); if (scriptEditor.GymAvailable) { levels.Add(scriptEditor.AssaultLevel as TRXScriptedLevel); } // Each processor will have a reference to the script editor, so can // make on-the-fly changes as required. string backupDirectory = _io.BackupDirectory.FullName; string wipDirectory = _io.WIPOutputDirectory.FullName; if (Settings.DevelopmentMode) { var script = scriptEditor.Script as TRXScript; script.EnforceConfig("enable_cheats", true); script.EnforceConfig("enable_console", true); scriptEditor.SaveScript(); } ItemFactory<TR2Entity> itemFactory = new() { DefaultItem = new() { Intensity1 = -1, Intensity2 = -1 } }; TR2TextureMonitorBroker textureMonitor = new(); TR2ItemRandomizer itemRandomizer = new() { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, TextureMonitor = textureMonitor, ItemFactory = itemFactory, }; TR2EnvironmentRandomizer environmentRandomizer = new() { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, TextureMonitor = textureMonitor }; environmentRandomizer.AllocateMirroredLevels(Settings.EnvironmentSeed); if (!monitor.IsCancelled && (Settings.RandomizeGameStrings || Settings.ReassignPuzzleItems)) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Adjusting game strings"); new TR2GameStringRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings }.Randomize(Settings.GameStringsSeed); } if (!monitor.IsCancelled) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Validating data injections"); new TR2XPreProcessor { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, TextureMonitor = textureMonitor, ItemFactory = itemFactory, Settings = Settings, }.Run(); } if (!monitor.IsCancelled && Settings.RandomizeSecrets) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing secrets"); new TR2SecretRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, Mirrorer = environmentRandomizer, ItemFactory = itemFactory, }.Randomize(Settings.SecretSeed); } if (!monitor.IsCancelled && Settings.RandomizeItems) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing items"); itemRandomizer.Randomize(Settings.ItemSeed); } if (!monitor.IsCancelled && Settings.RandomizeSecretRewardsPhysical) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing secret rewards"); new TR2SecretRewardRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, }.Randomize(Settings.SecretRewardsPhysicalSeed); } if (!monitor.IsCancelled && Settings.RandomizeEnemies) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing enemies"); new TR2EnemyRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, TextureMonitor = textureMonitor, ItemFactory = itemFactory, }.Randomize(Settings.EnemySeed); } if (!monitor.IsCancelled && Settings.RandomizeStartPosition) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing start positions"); new TR2StartPositionRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings }.Randomize(Settings.StartPositionSeed); } if (!monitor.IsCancelled) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, Settings.RandomizeEnvironment ? "Randomizing environment" : "Applying default environment packs"); environmentRandomizer.Randomize(Settings.EnvironmentSeed); } if (!monitor.IsCancelled && Settings.RandomizeItems) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Finalizing item randomization"); itemRandomizer.FinalizeRandomization(); } if (!monitor.IsCancelled) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Finalizing environment changes"); environmentRandomizer.FinalizeEnvironment(); } var audioRandomizer = new TR2AudioRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings }; if (!monitor.IsCancelled && Settings.RandomizeAudio) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing audio tracks"); audioRandomizer.Randomize(Settings.AudioSeed); } if (!monitor.IsCancelled && Settings.RandomizeOutfits) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing outfits"); new TR2OutfitRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, TextureMonitor = textureMonitor }.Randomize(Settings.OutfitSeed); } if (!monitor.IsCancelled && Settings.RandomizeNightMode) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing night mode"); new TR2NightModeRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, TextureMonitor = textureMonitor }.Randomize(Settings.NightModeSeed); } if (!monitor.IsCancelled) { if (Settings.RandomizeTextures) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing textures"); new TR2TextureRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, TextureMonitor = textureMonitor }.Randomize(Settings.TextureSeed); } else if (Settings.RandomizeNightMode) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing night mode textures"); new TR2TextureRandomizer { ScriptEditor = scriptEditor, Levels = levels, BasePath = wipDirectory, BackupPath = backupDirectory, SaveMonitor = monitor, Settings = Settings, TextureMonitor = textureMonitor }.Randomize(Settings.NightModeSeed); } } if (!monitor.IsCancelled && Settings.RandomizeItems && Settings.RandomizeItemSprites) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Randomizing Sprites"); itemRandomizer.RandomizeSprites(); } if (!monitor.IsCancelled && Settings.RandomizeAudio) { monitor.FireSaveStateBeginning(TRSaveCategory.Custom, "Embedding sound effects"); audioRandomizer.EmbedSamples(); } AmendTitleAndCredits(scriptEditor, monitor); } private void AmendTitleAndCredits(AbstractTRScriptEditor scriptEditor, TRSaveMonitor monitor) { var script = scriptEditor.Script as TRXScript; string mainMenuPic = Path.GetFileName(script.MainMenuPicture); string backupTitle = Path.Combine(GetReadBasePath(), mainMenuPic); if (File.Exists(backupTitle)) { string editedTitle = Path.Combine(GetWriteBasePath(), "title.png"); TRImage bg = new(backupTitle); TRImage badge = new("Resources/Shared/Graphics/tr2badge-small.png"); bg.Import(badge, scriptEditor.GameMode == GameMode.Gold ? _goldBadgePos : _regularBadgePos, true); if (scriptEditor.GameMode == GameMode.Combined) { TRImage comboBadge = new("Resources/Shared/Graphics/mask-of-xian.png"); bg.Import(comboBadge, _comboBadgePos, true); } bg.Save(editedTitle); string titlePath = "data/title.png"; script.MainMenuPicture = titlePath; script.AddAdditionalBackupFile(titlePath); } { string creditFile = Path.Combine(_io.OutputDirectory.FullName, "trrando.png"); string creditPath = "data/trrando.png"; TRImage bg = new(1920, 1080); TRImage badge = new("Resources/Shared/Graphics/tr2badge-large.png"); bg.Fill(Color.Black); bg.Import(badge, new(960 - badge.Width / 2, 540 - badge.Height / 2), true); bg.Save(creditFile); var finalLevel = scriptEditor.Levels.ToList().Find(l => l.IsFinalLevel) as TRXScriptedLevel; finalLevel.AddSequenceBefore(LevelSequenceType.Total_Stats, new DisplayPictureSequence { Type = LevelSequenceType.Display_Picture, DisplayTime = 5, Path = creditFile, }); script.AddAdditionalBackupFile(creditPath); } scriptEditor.SaveScript(); monitor.FireSaveStateChanged(1); } }
0
0.954714
1
0.954714
game-dev
MEDIA
0.506731
game-dev
0.959733
1
0.959733
mouahrara/aedenthorn
5,089
OutfitSets/IGenericModConfigMenuApi.cs
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI; using StardewModdingAPI.Utilities; using StardewValley; namespace OutfitSets { /// <summary>The API which lets other mods add a config UI through Generic Mod Config Menu.</summary> public interface IGenericModConfigMenuApi { /********* ** Methods *********/ /**** ** Must be called first ****/ /// <summary>Register a mod whose config can be edited through the UI.</summary> /// <param name="mod">The mod's manifest.</param> /// <param name="reset">Reset the mod's config to its default values.</param> /// <param name="save">Save the mod's current config to the <c>config.json</c> file.</param> /// <param name="titleScreenOnly">Whether the options can only be edited from the title screen.</param> /// <remarks>Each mod can only be registered once, unless it's deleted via <see cref="Unregister"/> before calling this again.</remarks> void Register(IManifest mod, Action reset, Action save, bool titleScreenOnly = false); /// <summary>Add a key binding at the current position in the form.</summary> /// <param name="mod">The mod's manifest.</param> /// <param name="getValue">Get the current value from the mod config.</param> /// <param name="setValue">Set a new value in the mod config.</param> /// <param name="name">The label text to show in the form.</param> /// <param name="tooltip">The tooltip text shown when the cursor hovers on the field, or <c>null</c> to disable the tooltip.</param> /// <param name="fieldId">The unique field ID for use with <see cref="OnFieldChanged"/>, or <c>null</c> to auto-generate a randomized ID.</param> void AddKeybind(IManifest mod, Func<SButton> getValue, Action<SButton> setValue, Func<string> name, Func<string> tooltip = null, string fieldId = null); /// <summary>Add a boolean option at the current position in the form.</summary> /// <param name="mod">The mod's manifest.</param> /// <param name="getValue">Get the current value from the mod config.</param> /// <param name="setValue">Set a new value in the mod config.</param> /// <param name="name">The label text to show in the form.</param> /// <param name="tooltip">The tooltip text shown when the cursor hovers on the field, or <c>null</c> to disable the tooltip.</param> /// <param name="fieldId">The unique field ID for use with <see cref="OnFieldChanged"/>, or <c>null</c> to auto-generate a randomized ID.</param> void AddBoolOption(IManifest mod, Func<bool> getValue, Action<bool> setValue, Func<string> name, Func<string> tooltip = null, string fieldId = null); /// <summary>Add an integer option at the current position in the form.</summary> /// <param name="mod">The mod's manifest.</param> /// <param name="getValue">Get the current value from the mod config.</param> /// <param name="setValue">Set a new value in the mod config.</param> /// <param name="name">The label text to show in the form.</param> /// <param name="tooltip">The tooltip text shown when the cursor hovers on the field, or <c>null</c> to disable the tooltip.</param> /// <param name="min">The minimum allowed value, or <c>null</c> to allow any.</param> /// <param name="max">The maximum allowed value, or <c>null</c> to allow any.</param> /// <param name="interval">The interval of values that can be selected.</param> /// <param name="fieldId">The unique field ID for use with <see cref="OnFieldChanged"/>, or <c>null</c> to auto-generate a randomized ID.</param> void AddNumberOption(IManifest mod, Func<int> getValue, Action<int> setValue, Func<string> name, Func<string> tooltip = null, int? min = null, int? max = null, int? interval = null, string fieldId = null); /// <summary>Add a string option at the current position in the form.</summary> /// <param name="mod">The mod's manifest.</param> /// <param name="getValue">Get the current value from the mod config.</param> /// <param name="setValue">Set a new value in the mod config.</param> /// <param name="name">The label text to show in the form.</param> /// <param name="tooltip">The tooltip text shown when the cursor hovers on the field, or <c>null</c> to disable the tooltip.</param> /// <param name="allowedValues">The values that can be selected, or <c>null</c> to allow any.</param> /// <param name="formatAllowedValue">Get the display text to show for a value from <paramref name="allowedValues"/>, or <c>null</c> to show the values as-is.</param> /// <param name="fieldId">The unique field ID for use with <see cref="OnFieldChanged"/>, or <c>null</c> to auto-generate a randomized ID.</param> void AddTextOption(IManifest mod, Func<string> getValue, Action<string> setValue, Func<string> name, Func<string> tooltip = null, string[] allowedValues = null, Func<string, string> formatAllowedValue = null, string fieldId = null); /// <summary>Remove a mod from the config UI and delete all its options and pages.</summary> /// <param name="mod">The mod's manifest.</param> void Unregister(IManifest mod); } }
0
0.748224
1
0.748224
game-dev
MEDIA
0.87406
game-dev
0.602264
1
0.602264
jaquadro/StorageDrawers
8,793
common/src/main/java/com/jaquadro/minecraft/storagedrawers/block/BlockKeyButton.java
package com.jaquadro.minecraft.storagedrawers.block; import com.jaquadro.minecraft.storagedrawers.block.tile.BlockEntityController; import com.jaquadro.minecraft.storagedrawers.config.ModCommonConfig; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; 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.FaceAttachedHorizontalDirectionalBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.AttachFace; import net.minecraft.world.level.block.state.properties.BlockSetType; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; public class BlockKeyButton extends FaceAttachedHorizontalDirectionalBlock { public static final MapCodec<BlockKeyButton> CODEC = RecordCodecBuilder.mapCodec((inst) -> inst.group( KeyType.CODEC.fieldOf("key_type").forGetter(block -> block.keyType), propertiesCodec() ).apply(inst, BlockKeyButton::new)); public static final BooleanProperty POWERED; protected static final VoxelShape CEILING_AABB_X; protected static final VoxelShape CEILING_AABB_Z; protected static final VoxelShape FLOOR_AABB_X; protected static final VoxelShape FLOOR_AABB_Z; protected static final VoxelShape NORTH_AABB; protected static final VoxelShape SOUTH_AABB; protected static final VoxelShape WEST_AABB; protected static final VoxelShape EAST_AABB; protected static final VoxelShape PRESSED_CEILING_AABB_X; protected static final VoxelShape PRESSED_CEILING_AABB_Z; protected static final VoxelShape PRESSED_FLOOR_AABB_X; protected static final VoxelShape PRESSED_FLOOR_AABB_Z; protected static final VoxelShape PRESSED_NORTH_AABB; protected static final VoxelShape PRESSED_SOUTH_AABB; protected static final VoxelShape PRESSED_WEST_AABB; protected static final VoxelShape PRESSED_EAST_AABB; private final KeyType keyType; public BlockKeyButton (KeyType keyType, Properties properties) { super(properties); registerDefaultState(stateDefinition.any() .setValue(FACING, Direction.NORTH) .setValue(POWERED, false) .setValue(FACE, AttachFace.WALL)); this.keyType = keyType; } public MapCodec<BlockKeyButton> codec() { return CODEC; } @Override public VoxelShape getShape(BlockState state, BlockGetter getter, BlockPos pos, CollisionContext collision) { Direction dir = state.getValue(FACING); boolean powered = state.getValue(POWERED); switch (state.getValue(FACE)) { case FLOOR: if (dir.getAxis() == Direction.Axis.X) return powered ? PRESSED_FLOOR_AABB_X : FLOOR_AABB_X; return powered ? PRESSED_FLOOR_AABB_Z : FLOOR_AABB_Z; case WALL: return switch (dir) { case EAST -> powered ? PRESSED_EAST_AABB : EAST_AABB; case WEST -> powered ? PRESSED_WEST_AABB : WEST_AABB; case SOUTH -> powered ? PRESSED_SOUTH_AABB : SOUTH_AABB; case NORTH, UP, DOWN -> powered ? PRESSED_NORTH_AABB : NORTH_AABB; }; case CEILING: default: if (dir.getAxis() == Direction.Axis.X) return powered ? PRESSED_CEILING_AABB_X : CEILING_AABB_X; else return powered ? PRESSED_CEILING_AABB_Z : CEILING_AABB_Z; } } @Override public InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { if (state.getValue(POWERED)) { return InteractionResult.CONSUME; } else { if (!keyType.isEnabled()) return InteractionResult.PASS; this.press(state, level, pos); this.playSound(player, level, pos, true); level.gameEvent(player, GameEvent.BLOCK_ACTIVATE, pos); BlockPos targetPos = pos.offset(state.getValue(FACING).getOpposite().getNormal()); if (state.getValue(FACE) == AttachFace.FLOOR) targetPos = pos.offset(Direction.DOWN.getNormal()); else if (state.getValue(FACE) == AttachFace.CEILING) targetPos = pos.offset(Direction.UP.getNormal()); Block target = level.getBlockState(targetPos).getBlock(); if (target instanceof BlockController controller) controller.toggle(level, targetPos, player, keyType); else if (target instanceof BlockControllerIO io) { BlockEntityController controller = io.getController(level, targetPos); if (controller != null) { BlockController blockController = controller.getBlock(); if (blockController != null) blockController.toggle(level, controller.getBlockPos(), player, keyType); } } return InteractionResult.sidedSuccess(level.isClientSide); } } public void press(BlockState state, Level level, BlockPos pos) { level.setBlock(pos, state.setValue(POWERED, true), 3); this.updateNeighbours(state, level, pos); level.scheduleTick(pos, this, 10); } protected void playSound(@Nullable Player player, LevelAccessor level, BlockPos pos, boolean clickOn) { level.playSound(clickOn ? player : null, pos, this.getSound(clickOn), SoundSource.BLOCKS); } protected SoundEvent getSound(boolean clickOn) { return clickOn ? BlockSetType.OAK.buttonClickOn() : BlockSetType.OAK.buttonClickOff(); } @Override public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (state.getValue(POWERED)) this.checkPressed(state, level, pos); } protected void checkPressed(BlockState state, Level level, BlockPos pos) { if (state.getValue(POWERED)) { level.setBlock(pos, state.setValue(POWERED, false), 3); this.updateNeighbours(state, level, pos); this.playSound(null, level, pos, false); level.gameEvent(null, GameEvent.BLOCK_DEACTIVATE, pos); } } private void updateNeighbours(BlockState state, Level level, BlockPos pos) { level.updateNeighborsAt(pos, this); level.updateNeighborsAt(pos.relative(getConnectedDirection(state).getOpposite()), this); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(FACING, POWERED, FACE); } static { POWERED = BlockStateProperties.POWERED; CEILING_AABB_X = Block.box(3.0, 14.0, 3.0, 13.0, 16.0, 13.0); CEILING_AABB_Z = Block.box(3.0, 14.0, 3.0, 13.0, 16.0, 13.0); FLOOR_AABB_X = Block.box(3.0, 0.0, 3.0, 13.0, 2.0, 13.0); FLOOR_AABB_Z = Block.box(3.0, 0.0, 3.0, 13.0, 2.0, 13.0); NORTH_AABB = Block.box(3.0, 3.0, 14.0, 13.0, 13.0, 16.0); SOUTH_AABB = Block.box(3.0, 3.0, 0.0, 13.0, 13.0, 2.0); WEST_AABB = Block.box(14.0, 3.0, 3.0, 16.0, 13.0, 13.0); EAST_AABB = Block.box(0.0, 3.0, 3.0, 2.0, 13.0, 13.0); PRESSED_CEILING_AABB_X = Block.box(3.0, 15.0, 3.0, 13.0, 16.0, 13.0); PRESSED_CEILING_AABB_Z = Block.box(3.0, 15.0, 3.0, 13.0, 16.0, 13.0); PRESSED_FLOOR_AABB_X = Block.box(3.0, 0.0, 3.0, 13.0, 1.0, 13.0); PRESSED_FLOOR_AABB_Z = Block.box(3.0, 0.0, 3.0, 13.0, 1.0, 13.0); PRESSED_NORTH_AABB = Block.box(3.0, 3.0, 15.0, 13.0, 13.0, 16.0); PRESSED_SOUTH_AABB = Block.box(3.0, 3.0, 0.0, 13.0, 13.0, 1.0); PRESSED_WEST_AABB = Block.box(15.0, 3.0, 3.0, 16.0, 13.0, 13.0); PRESSED_EAST_AABB = Block.box(0.0, 3.0, 3.0, 1.0, 13.0, 13.0); } }
0
0.961171
1
0.961171
game-dev
MEDIA
0.994551
game-dev
0.904866
1
0.904866
Karazaa/Argus
5,508
Argus/Source/Argus/StaticData/RecordDatabases/PlacedArgusActorTeamInfoRecordDatabase.cpp
// Copayright Karazaa. This is a part of an RTS project called Argus. // AUTOGENERATED FILE #include "RecordDatabases/PlacedArgusActorTeamInfoRecordDatabase.h" #include "ArgusEntity.h" #include "ArgusLogging.h" #if WITH_EDITOR && !IS_PACKAGING_ARGUS #include "ArgusStaticData.h" #include "Editor.h" #include "Misc/Paths.h" #include "Subsystems/EditorAssetSubsystem.h" #include "UObject/ObjectSaveContext.h" #include <filesystem> #endif //WITH_EDITOR && !IS_PACKAGING_ARGUS const UPlacedArgusActorTeamInfoRecord* UPlacedArgusActorTeamInfoRecordDatabase::GetRecord(uint32 id) { ARGUS_TRACE(UPlacedArgusActorTeamInfoRecordDatabase::GetRecord) ARGUS_MEMORY_TRACE(ArgusStaticData); bool resized = false; if (static_cast<uint32>(m_UPlacedArgusActorTeamInfoRecordsPersistent.Num()) <= id) { if (!ResizePersistentObjectPointerArrayToFitRecord(id)) { return nullptr; } resized = true; } if (id == 0u) { return nullptr; } if (resized || !m_UPlacedArgusActorTeamInfoRecordsPersistent[id]) { m_UPlacedArgusActorTeamInfoRecordsPersistent[id] = m_UPlacedArgusActorTeamInfoRecords[id].LoadSynchronous(); } if (m_UPlacedArgusActorTeamInfoRecordsPersistent[id]) { m_UPlacedArgusActorTeamInfoRecordsPersistent[id]->m_id = id; } return m_UPlacedArgusActorTeamInfoRecordsPersistent[id]; } const bool UPlacedArgusActorTeamInfoRecordDatabase::AsyncPreLoadRecord(uint32 id) { ARGUS_TRACE(UPlacedArgusActorTeamInfoRecordDatabase::AsyncPreLoadRecord); ARGUS_MEMORY_TRACE(ArgusStaticData); if (static_cast<uint32>(m_UPlacedArgusActorTeamInfoRecordsPersistent.Num()) <= id) { if (!ResizePersistentObjectPointerArrayToFitRecord(id)) { return false; } } if (id == 0u) { return false; } if (m_UPlacedArgusActorTeamInfoRecordsPersistent[id]) { return true; } AssetLoadingComponent* assetLoadingComponent = ArgusEntity::GetSingletonEntity().GetComponent<AssetLoadingComponent>(); ARGUS_RETURN_ON_NULL_BOOL(assetLoadingComponent, ArgusStaticDataLog); assetLoadingComponent->m_streamableManager.RequestAsyncLoad(m_UPlacedArgusActorTeamInfoRecords[id].ToSoftObjectPath(), FStreamableDelegate::CreateLambda ( [this, id]() { if (static_cast<uint32>(m_UPlacedArgusActorTeamInfoRecordsPersistent.Num()) <= id || static_cast<uint32>(m_UPlacedArgusActorTeamInfoRecords.Num()) <= id) { return; } m_UPlacedArgusActorTeamInfoRecordsPersistent[id] = m_UPlacedArgusActorTeamInfoRecords[id].Get();\ if (m_UPlacedArgusActorTeamInfoRecordsPersistent[id]) { m_UPlacedArgusActorTeamInfoRecordsPersistent[id]->OnAsyncLoaded(); } }) ); return true; } bool UPlacedArgusActorTeamInfoRecordDatabase::ResizePersistentObjectPointerArrayToFitRecord(uint32 id) { ARGUS_MEMORY_TRACE(ArgusStaticData); m_UPlacedArgusActorTeamInfoRecordsPersistent.SetNumZeroed(m_UPlacedArgusActorTeamInfoRecords.Num()); if (static_cast<uint32>(m_UPlacedArgusActorTeamInfoRecordsPersistent.Num()) <= id) { ARGUS_LOG ( ArgusStaticDataLog, Error, TEXT("[%s] Could not find %s %d in %s."), ARGUS_FUNCNAME, ARGUS_NAMEOF(id), id, ARGUS_NAMEOF(UPlacedArgusActorTeamInfoRecordDatabase) ); return false; } return true; } #if WITH_EDITOR && !IS_PACKAGING_ARGUS void UPlacedArgusActorTeamInfoRecordDatabase::PreSave(FObjectPreSaveContext saveContext) { FString fullPath = FPaths::ConvertRelativePathToFull(saveContext.GetTargetFilename()); if (!std::filesystem::exists(TCHAR_TO_UTF8(*fullPath))) { TArray<FReferencerInformation> internalReferencers; TArray<FReferencerInformation> externalReferencers; RetrieveReferencers(&internalReferencers, &externalReferencers); if (internalReferencers.IsEmpty() && externalReferencers.IsEmpty()) { ArgusStaticData::RegisterNewUPlacedArgusActorTeamInfoRecordDatabase(this); } } Super::PreSave(saveContext); } void UPlacedArgusActorTeamInfoRecordDatabase::PostEditChangeProperty(FPropertyChangedEvent& propertyChangedEvent) { if (propertyChangedEvent.ChangeType != EPropertyChangeType::ValueSet) { return; } const FString propertyName = propertyChangedEvent.GetPropertyName().ToString(); const FString recordPropertyName = ARGUS_NAMEOF(m_UPlacedArgusActorTeamInfoRecords); if (!propertyName.Equals(recordPropertyName)) { return; } const int32 arrayIndex = propertyChangedEvent.GetArrayIndex(propertyName); UPlacedArgusActorTeamInfoRecord* modifiedUPlacedArgusActorTeamInfoRecord = m_UPlacedArgusActorTeamInfoRecords[arrayIndex].LoadSynchronous(); if (!modifiedUPlacedArgusActorTeamInfoRecord) { return; } modifiedUPlacedArgusActorTeamInfoRecord->m_id = arrayIndex; if (!GEditor) { return; } UEditorAssetSubsystem* editorAssetSubsystem = GEditor->GetEditorSubsystem<UEditorAssetSubsystem>(); if (!editorAssetSubsystem) { return; } editorAssetSubsystem->SaveLoadedAsset(modifiedUPlacedArgusActorTeamInfoRecord, false); editorAssetSubsystem->SaveLoadedAsset(this, false); } void UPlacedArgusActorTeamInfoRecordDatabase::AddUPlacedArgusActorTeamInfoRecordToDatabase(UPlacedArgusActorTeamInfoRecord* record) { const int32 arrayIndex = m_UPlacedArgusActorTeamInfoRecords.Num(); m_UPlacedArgusActorTeamInfoRecords.Add(TSoftObjectPtr(record)); record->m_id = arrayIndex; if (!GEditor) { return; } UEditorAssetSubsystem* editorAssetSubsystem = GEditor->GetEditorSubsystem<UEditorAssetSubsystem>(); if (!editorAssetSubsystem) { return; } editorAssetSubsystem->SaveLoadedAsset(this, false); } #endif //WITH_EDITOR && !IS_PACKAGING_ARGUS
0
0.551533
1
0.551533
game-dev
MEDIA
0.484742
game-dev
0.814097
1
0.814097
ShuangYu1145/Faiths-Fix
6,908
src/main/java/net/minecraft/world/gen/structure/StructureOceanMonument.java
package net.minecraft.world.gen.structure; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Map.Entry; import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; public class StructureOceanMonument extends MapGenStructure { private int field_175800_f; private int field_175801_g; public static final List<BiomeGenBase> field_175802_d = Arrays.asList(new BiomeGenBase[] {BiomeGenBase.ocean, BiomeGenBase.deepOcean, BiomeGenBase.river, BiomeGenBase.frozenOcean, BiomeGenBase.frozenRiver}); private static final List<BiomeGenBase.SpawnListEntry> field_175803_h = Lists.<BiomeGenBase.SpawnListEntry>newArrayList(); public StructureOceanMonument() { this.field_175800_f = 32; this.field_175801_g = 5; } public StructureOceanMonument(Map<String, String> p_i45608_1_) { this(); for (Entry<String, String> entry : p_i45608_1_.entrySet()) { if (((String)entry.getKey()).equals("spacing")) { this.field_175800_f = MathHelper.parseIntWithDefaultAndMax((String)entry.getValue(), this.field_175800_f, 1); } else if (((String)entry.getKey()).equals("separation")) { this.field_175801_g = MathHelper.parseIntWithDefaultAndMax((String)entry.getValue(), this.field_175801_g, 1); } } } public String getStructureName() { return "Monument"; } protected boolean canSpawnStructureAtCoords(int chunkX, int chunkZ) { int i = chunkX; int j = chunkZ; if (chunkX < 0) { chunkX -= this.field_175800_f - 1; } if (chunkZ < 0) { chunkZ -= this.field_175800_f - 1; } int k = chunkX / this.field_175800_f; int l = chunkZ / this.field_175800_f; Random random = this.worldObj.setRandomSeed(k, l, 10387313); k = k * this.field_175800_f; l = l * this.field_175800_f; k = k + (random.nextInt(this.field_175800_f - this.field_175801_g) + random.nextInt(this.field_175800_f - this.field_175801_g)) / 2; l = l + (random.nextInt(this.field_175800_f - this.field_175801_g) + random.nextInt(this.field_175800_f - this.field_175801_g)) / 2; if (i == k && j == l) { if (this.worldObj.getWorldChunkManager().getBiomeGenerator(new BlockPos(i * 16 + 8, 64, j * 16 + 8), (BiomeGenBase)null) != BiomeGenBase.deepOcean) { return false; } boolean flag = this.worldObj.getWorldChunkManager().areBiomesViable(i * 16 + 8, j * 16 + 8, 29, field_175802_d); if (flag) { return true; } } return false; } protected StructureStart getStructureStart(int chunkX, int chunkZ) { return new StructureOceanMonument.StartMonument(this.worldObj, this.rand, chunkX, chunkZ); } public List<BiomeGenBase.SpawnListEntry> getScatteredFeatureSpawnList() { return field_175803_h; } static { field_175803_h.add(new BiomeGenBase.SpawnListEntry(EntityGuardian.class, 1, 2, 4)); } public static class StartMonument extends StructureStart { private Set<ChunkCoordIntPair> field_175791_c = Sets.<ChunkCoordIntPair>newHashSet(); private boolean field_175790_d; public StartMonument() { } public StartMonument(World worldIn, Random p_i45607_2_, int p_i45607_3_, int p_i45607_4_) { super(p_i45607_3_, p_i45607_4_); this.func_175789_b(worldIn, p_i45607_2_, p_i45607_3_, p_i45607_4_); } private void func_175789_b(World worldIn, Random p_175789_2_, int p_175789_3_, int p_175789_4_) { p_175789_2_.setSeed(worldIn.getSeed()); long i = p_175789_2_.nextLong(); long j = p_175789_2_.nextLong(); long k = (long)p_175789_3_ * i; long l = (long)p_175789_4_ * j; p_175789_2_.setSeed(k ^ l ^ worldIn.getSeed()); int i1 = p_175789_3_ * 16 + 8 - 29; int j1 = p_175789_4_ * 16 + 8 - 29; EnumFacing enumfacing = EnumFacing.Plane.HORIZONTAL.random(p_175789_2_); this.components.add(new StructureOceanMonumentPieces.MonumentBuilding(p_175789_2_, i1, j1, enumfacing)); this.updateBoundingBox(); this.field_175790_d = true; } public void generateStructure(World worldIn, Random rand, StructureBoundingBox structurebb) { if (!this.field_175790_d) { this.components.clear(); this.func_175789_b(worldIn, rand, this.getChunkPosX(), this.getChunkPosZ()); } super.generateStructure(worldIn, rand, structurebb); } public boolean func_175788_a(ChunkCoordIntPair pair) { return this.field_175791_c.contains(pair) ? false : super.func_175788_a(pair); } public void func_175787_b(ChunkCoordIntPair pair) { super.func_175787_b(pair); this.field_175791_c.add(pair); } public void writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); NBTTagList nbttaglist = new NBTTagList(); for (ChunkCoordIntPair chunkcoordintpair : this.field_175791_c) { NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setInteger("X", chunkcoordintpair.chunkXPos); nbttagcompound.setInteger("Z", chunkcoordintpair.chunkZPos); nbttaglist.appendTag(nbttagcompound); } tagCompound.setTag("Processed", nbttaglist); } public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); if (tagCompound.hasKey("Processed", 9)) { NBTTagList nbttaglist = tagCompound.getTagList("Processed", 10); for (int i = 0; i < nbttaglist.tagCount(); ++i) { NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); this.field_175791_c.add(new ChunkCoordIntPair(nbttagcompound.getInteger("X"), nbttagcompound.getInteger("Z"))); } } } } }
0
0.799064
1
0.799064
game-dev
MEDIA
0.98691
game-dev
0.920128
1
0.920128
glKarin/com.n0n3m4.diii4a
33,249
Q3E/src/main/jni/source/game/server/hl2/npc_combinecamera.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Security cameras will track a default target (if they have one) // until they either acquire an enemy to track or are told to track // an entity via an input. If they lose their target they will // revert to tracking their default target. They acquire enemies // using the relationship table just like any other NPC. // // Cameras have two zones of awareness, an inner zone formed by the // intersection of an inner FOV and an inner radius. The camera is // fully aware of entities in the inner zone and will acquire enemies // seen there. // // The outer zone of awareness is formed by the intersection of an // outer FOV and an outer radius. The camera is only vaguely aware // of entities in the outer zone and will flash amber when enemies // are there, but will otherwise ignore them. // // They can be made angry via an input, at which time they sound an // alarm and snap a few pictures of whatever they are tracking. They // can also be set to become angry anytime they acquire an enemy. // //=============================================================================// #include "cbase.h" #include "ai_basenpc.h" #include "ai_senses.h" #include "ai_memory.h" #include "engine/IEngineSound.h" #include "ammodef.h" #include "Sprite.h" #include "hl2/hl2_player.h" #include "soundenvelope.h" #include "explode.h" #include "IEffects.h" #include "animation.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Debug visualization ConVar g_debug_combine_camera("g_debug_combine_camera", "0"); #define COMBINE_CAMERA_MODEL "models/combine_camera/combine_camera.mdl" #define COMBINE_CAMERA_GLOW_SPRITE "sprites/glow1.vmt" #define COMBINE_CAMERA_FLASH_SPRITE "sprites/light_glow03.vmt" #define COMBINE_CAMERA_BC_YAW "aim_yaw" #define COMBINE_CAMERA_BC_PITCH "aim_pitch" #define COMBINE_CAMERA_SPREAD VECTOR_CONE_2DEGREES #define COMBINE_CAMERA_MAX_WAIT 5 #define COMBINE_CAMERA_PING_TIME 1.0f // Spawnflags #define SF_COMBINE_CAMERA_BECOMEANGRY 0x00000020 #define SF_COMBINE_CAMERA_IGNOREENEMIES 0x00000040 #define SF_COMBINE_CAMERA_STARTINACTIVE 0x00000080 // Heights #define COMBINE_CAMERA_RETRACT_HEIGHT 24 #define COMBINE_CAMERA_DEPLOY_HEIGHT 64 // Activities int ACT_COMBINE_CAMERA_OPEN; int ACT_COMBINE_CAMERA_CLOSE; int ACT_COMBINE_CAMERA_OPEN_IDLE; int ACT_COMBINE_CAMERA_CLOSED_IDLE; int ACT_COMBINE_CAMERA_FIRE; const float CAMERA_CLICK_INTERVAL = 0.5f; const float CAMERA_MOVE_INTERVAL = 1.0f; // // The camera has two FOVs - a wide one for becoming slightly aware of someone, // a narrow one for becoming totally aware of them. // const float CAMERA_FOV_WIDE = 0.5; const float CAMERA_FOV_NARROW = 0.707; // Camera states enum cameraState_e { CAMERA_SEARCHING, CAMERA_AUTO_SEARCHING, CAMERA_ACTIVE, CAMERA_DEAD, }; // Eye states enum eyeState_t { CAMERA_EYE_IDLE, // Nothing abnormal in the inner or outer viewcone, dim green. CAMERA_EYE_SEEKING_TARGET, // Something in the outer viewcone, flashes amber as it converges on the target. CAMERA_EYE_FOUND_TARGET, // Something in the inner viewcone, bright amber. CAMERA_EYE_ANGRY, // Found a target that we don't like: angry, bright red. CAMERA_EYE_DORMANT, // Not active CAMERA_EYE_DEAD, // Completely invisible CAMERA_EYE_DISABLED, // Turned off, must be reactivated before it'll deploy again (completely invisible) CAMERA_EYE_HAPPY, // Found a target that we like: go green for a second }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CNPC_CombineCamera : public CAI_BaseNPC { DECLARE_CLASS(CNPC_CombineCamera, CAI_BaseNPC); public: CNPC_CombineCamera(); ~CNPC_CombineCamera(); void Precache(); void Spawn(); Vector HeadDirection2D(); int DrawDebugTextOverlays(); void Deploy(); void ActiveThink(); void SearchThink(); void DeathThink(); void InputToggle(inputdata_t &inputdata); void InputEnable(inputdata_t &inputdata); void InputDisable(inputdata_t &inputdata); void InputSetAngry(inputdata_t &inputdata); void InputSetIdle(inputdata_t &inputdata); void DrawDebugGeometryOverlays(void); float MaxYawSpeed(); int OnTakeDamage(const CTakeDamageInfo &inputInfo); Class_T Classify() { return (m_bEnabled) ? CLASS_MILITARY : CLASS_NONE; } bool IsValidEnemy( CBaseEntity *pEnemy ); bool FVisible(CBaseEntity *pEntity, int traceMask = MASK_BLOCKLOS, CBaseEntity **ppBlocker = NULL); Vector EyeOffset(Activity nActivity) { Vector vecEyeOffset(0,0,-64); GetEyePosition(GetModelPtr(), vecEyeOffset); return vecEyeOffset; } Vector EyePosition() { return GetAbsOrigin() + EyeOffset(GetActivity()); } protected: CBaseEntity *GetTarget(); bool UpdateFacing(); void TrackTarget(CBaseEntity *pTarget); bool PreThink(cameraState_e state); void SetEyeState(eyeState_t state); void MaintainEye(); void Ping(); void Toggle(); void Enable(); void Disable(); void SetHeight(float height); CBaseEntity *MaintainEnemy(); void SetAngry(bool bAngry); protected: int m_iAmmoType; int m_iMinHealthDmg; int m_nInnerRadius; // The camera will only lock onto enemies that are within the inner radius. int m_nOuterRadius; // The camera will flash amber when enemies are within the outer radius, but outside the inner radius. bool m_bActive; // The camera is deployed and looking for targets bool m_bAngry; // The camera has gotten angry at someone and sounded an alarm. bool m_bBlinkState; bool m_bEnabled; // Denotes whether the camera is able to deploy or not string_t m_sDefaultTarget; EHANDLE m_hEnemyTarget; // Entity we acquired as an enemy. float m_flPingTime; float m_flClickTime; // Time to take next picture while angry. int m_nClickCount; // Counts pictures taken since we last became angry. float m_flMoveSoundTime; float m_flTurnOffEyeFlashTime; float m_flEyeHappyTime; QAngle m_vecGoalAngles; CSprite *m_pEyeGlow; CSprite *m_pEyeFlash; DECLARE_DATADESC(); }; BEGIN_DATADESC(CNPC_CombineCamera) DEFINE_FIELD(m_iAmmoType, FIELD_INTEGER), DEFINE_KEYFIELD(m_iMinHealthDmg, FIELD_INTEGER, "minhealthdmg"), DEFINE_KEYFIELD(m_nInnerRadius, FIELD_INTEGER, "innerradius"), DEFINE_KEYFIELD(m_nOuterRadius, FIELD_INTEGER, "outerradius"), DEFINE_FIELD(m_bActive, FIELD_BOOLEAN), DEFINE_FIELD(m_bAngry, FIELD_BOOLEAN), DEFINE_FIELD(m_bBlinkState, FIELD_BOOLEAN), DEFINE_FIELD(m_bEnabled, FIELD_BOOLEAN), DEFINE_KEYFIELD(m_sDefaultTarget, FIELD_STRING, "defaulttarget"), DEFINE_FIELD(m_hEnemyTarget, FIELD_EHANDLE), DEFINE_FIELD(m_flPingTime, FIELD_TIME), DEFINE_FIELD(m_flClickTime, FIELD_TIME), DEFINE_FIELD(m_nClickCount, FIELD_INTEGER ), DEFINE_FIELD(m_flMoveSoundTime, FIELD_TIME), DEFINE_FIELD(m_flTurnOffEyeFlashTime, FIELD_TIME), DEFINE_FIELD(m_flEyeHappyTime, FIELD_TIME), DEFINE_FIELD(m_vecGoalAngles, FIELD_VECTOR), DEFINE_FIELD(m_pEyeGlow, FIELD_CLASSPTR), DEFINE_FIELD(m_pEyeFlash, FIELD_CLASSPTR), DEFINE_THINKFUNC(Deploy), DEFINE_THINKFUNC(ActiveThink), DEFINE_THINKFUNC(SearchThink), DEFINE_THINKFUNC(DeathThink), // Inputs DEFINE_INPUTFUNC(FIELD_VOID, "Toggle", InputToggle), DEFINE_INPUTFUNC(FIELD_VOID, "Enable", InputEnable), DEFINE_INPUTFUNC(FIELD_VOID, "Disable", InputDisable), DEFINE_INPUTFUNC(FIELD_VOID, "SetAngry", InputSetAngry), DEFINE_INPUTFUNC(FIELD_VOID, "SetIdle", InputSetIdle), END_DATADESC() LINK_ENTITY_TO_CLASS(npc_combine_camera, CNPC_CombineCamera); //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CNPC_CombineCamera::CNPC_CombineCamera() { m_bActive = false; m_pEyeGlow = NULL; m_pEyeFlash = NULL; m_iAmmoType = -1; m_iMinHealthDmg = 0; m_flPingTime = 0; m_bBlinkState = false; m_bEnabled = false; m_vecGoalAngles.Init(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CNPC_CombineCamera::~CNPC_CombineCamera() { } //----------------------------------------------------------------------------- // Purpose: Precache //----------------------------------------------------------------------------- void CNPC_CombineCamera::Precache() { PrecacheModel(COMBINE_CAMERA_MODEL); PrecacheModel(COMBINE_CAMERA_GLOW_SPRITE); PrecacheModel(COMBINE_CAMERA_FLASH_SPRITE); // Activities ADD_CUSTOM_ACTIVITY(CNPC_CombineCamera, ACT_COMBINE_CAMERA_OPEN); ADD_CUSTOM_ACTIVITY(CNPC_CombineCamera, ACT_COMBINE_CAMERA_CLOSE); ADD_CUSTOM_ACTIVITY(CNPC_CombineCamera, ACT_COMBINE_CAMERA_CLOSED_IDLE); ADD_CUSTOM_ACTIVITY(CNPC_CombineCamera, ACT_COMBINE_CAMERA_OPEN_IDLE); ADD_CUSTOM_ACTIVITY(CNPC_CombineCamera, ACT_COMBINE_CAMERA_FIRE); PrecacheScriptSound( "NPC_CombineCamera.Move" ); PrecacheScriptSound( "NPC_CombineCamera.BecomeIdle" ); PrecacheScriptSound( "NPC_CombineCamera.Active" ); PrecacheScriptSound( "NPC_CombineCamera.Click" ); PrecacheScriptSound( "NPC_CombineCamera.Ping" ); PrecacheScriptSound( "NPC_CombineCamera.Angry" ); PrecacheScriptSound( "NPC_CombineCamera.Die" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: Spawn the entity //----------------------------------------------------------------------------- void CNPC_CombineCamera::Spawn() { Precache(); SetModel(COMBINE_CAMERA_MODEL); m_pEyeFlash = CSprite::SpriteCreate(COMBINE_CAMERA_FLASH_SPRITE, GetLocalOrigin(), FALSE); m_pEyeFlash->SetTransparency(kRenderGlow, 255, 255, 255, 0, kRenderFxNoDissipation); m_pEyeFlash->SetAttachment(this, 2); m_pEyeFlash->SetBrightness(0); m_pEyeFlash->SetScale(1.0); BaseClass::Spawn(); m_HackedGunPos = Vector(0, 0, 12.75); SetViewOffset(EyeOffset(ACT_IDLE)); m_flFieldOfView = CAMERA_FOV_WIDE; m_takedamage = DAMAGE_YES; m_iHealth = 50; m_bloodColor = BLOOD_COLOR_MECH; SetSolid(SOLID_BBOX); AddSolidFlags(FSOLID_NOT_STANDABLE); SetHeight(COMBINE_CAMERA_RETRACT_HEIGHT); AddFlag(FL_AIMTARGET); SetPoseParameter(COMBINE_CAMERA_BC_YAW, 0); SetPoseParameter(COMBINE_CAMERA_BC_PITCH, 0); m_iAmmoType = GetAmmoDef()->Index("Pistol"); // Create our eye sprite m_pEyeGlow = CSprite::SpriteCreate(COMBINE_CAMERA_GLOW_SPRITE, GetLocalOrigin(), false); m_pEyeGlow->SetTransparency(kRenderWorldGlow, 255, 0, 0, 128, kRenderFxNoDissipation); m_pEyeGlow->SetAttachment(this, 2); // Set our enabled state m_bEnabled = ((m_spawnflags & SF_COMBINE_CAMERA_STARTINACTIVE) == false); // Make sure the radii are sane. if (m_nOuterRadius <= 0) { m_nOuterRadius = 300; } if (m_nInnerRadius <= 0) { m_nInnerRadius = 450; } if (m_nOuterRadius < m_nInnerRadius) { V_swap(m_nOuterRadius, m_nInnerRadius); } // Do we start active? if (m_bEnabled) { Deploy(); } else { SetEyeState(CAMERA_EYE_DISABLED); } //Adrian: No shadows on these guys. AddEffects( EF_NOSHADOW ); // Stagger our starting times SetNextThink( gpGlobals->curtime + random->RandomFloat(0.1f, 0.3f) ); // Don't allow us to skip animation setup because our attachments are critical to us! SetBoneCacheFlags( BCF_NO_ANIMATION_SKIP ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CBaseEntity *CNPC_CombineCamera::GetTarget() { return m_hEnemyTarget; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CNPC_CombineCamera::OnTakeDamage(const CTakeDamageInfo &inputInfo) { if (!m_takedamage) return 0; CTakeDamageInfo info = inputInfo; if (m_bActive == false) info.ScaleDamage(0.1f); // If attacker can't do at least the min required damage to us, don't take any damage from them if (info.GetDamage() < m_iMinHealthDmg) return 0; m_iHealth -= info.GetDamage(); if (m_iHealth <= 0) { m_iHealth = 0; m_takedamage = DAMAGE_NO; RemoveFlag(FL_NPC); // why are they set in the first place??? // FIXME: This needs to throw a ragdoll gib or something other than animating the retraction -- jdw ExplosionCreate(GetAbsOrigin(), GetLocalAngles(), this, 100, 100, false); SetThink(&CNPC_CombineCamera::DeathThink); StopSound("Alert"); m_OnDamaged.FireOutput(info.GetInflictor(), this); SetNextThink( gpGlobals->curtime + 0.1f ); return 0; } return 1; } //----------------------------------------------------------------------------- // Purpose: Deploy and start searching for targets. //----------------------------------------------------------------------------- void CNPC_CombineCamera::Deploy() { m_vecGoalAngles = GetAbsAngles(); SetNextThink( gpGlobals->curtime ); SetEyeState(CAMERA_EYE_IDLE); m_bActive = true; SetHeight(COMBINE_CAMERA_DEPLOY_HEIGHT); SetIdealActivity((Activity) ACT_COMBINE_CAMERA_OPEN_IDLE); m_flPlaybackRate = 0; SetThink(&CNPC_CombineCamera::SearchThink); EmitSound("NPC_CombineCamera.Move"); } //----------------------------------------------------------------------------- // Purpose: Returns the speed at which the camera can face a target //----------------------------------------------------------------------------- float CNPC_CombineCamera::MaxYawSpeed() { if (m_hEnemyTarget) return 180.0f; return 60.0f; } //----------------------------------------------------------------------------- // Purpose: Causes the camera to face its desired angles //----------------------------------------------------------------------------- bool CNPC_CombineCamera::UpdateFacing() { bool bMoved = false; matrix3x4_t localToWorld; GetAttachment(LookupAttachment("eyes"), localToWorld); Vector vecGoalDir; AngleVectors(m_vecGoalAngles, &vecGoalDir ); Vector vecGoalLocalDir; VectorIRotate(vecGoalDir, localToWorld, vecGoalLocalDir); QAngle vecGoalLocalAngles; VectorAngles(vecGoalLocalDir, vecGoalLocalAngles); // Update pitch float flDiff = AngleNormalize(UTIL_ApproachAngle( vecGoalLocalAngles.x, 0.0, 0.1f * MaxYawSpeed())); int iPose = LookupPoseParameter(COMBINE_CAMERA_BC_PITCH); SetPoseParameter(iPose, GetPoseParameter(iPose) + (flDiff / 1.5f)); if (fabs(flDiff) > 0.1f) { bMoved = true; } // Update yaw flDiff = AngleNormalize(UTIL_ApproachAngle( vecGoalLocalAngles.y, 0.0, 0.1f * MaxYawSpeed())); iPose = LookupPoseParameter(COMBINE_CAMERA_BC_YAW); SetPoseParameter(iPose, GetPoseParameter(iPose) + (flDiff / 1.5f)); if (fabs(flDiff) > 0.1f) { bMoved = true; } if (bMoved && (m_flMoveSoundTime < gpGlobals->curtime)) { EmitSound("NPC_CombineCamera.Move"); m_flMoveSoundTime = gpGlobals->curtime + CAMERA_MOVE_INTERVAL; } // You're going to make decisions based on this info. So bump the bone cache after you calculate everything InvalidateBoneCache(); return bMoved; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- Vector CNPC_CombineCamera::HeadDirection2D() { Vector vecMuzzle, vecMuzzleDir; GetAttachment("eyes", vecMuzzle, &vecMuzzleDir ); vecMuzzleDir.z = 0; VectorNormalize(vecMuzzleDir); return vecMuzzleDir; } //----------------------------------------------------------------------------- // Purpose: // Input : *pEntity - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_CombineCamera::FVisible(CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker) { CBaseEntity *pHitEntity = NULL; if ( BaseClass::FVisible( pEntity, traceMask, &pHitEntity ) ) return true; // If we hit something that's okay to hit anyway, still fire if ( pHitEntity && pHitEntity->MyCombatCharacterPointer() ) { if (IRelationType(pHitEntity) == D_HT) return true; } if (ppBlocker) { *ppBlocker = pHitEntity; } return false; } //----------------------------------------------------------------------------- // Purpose: Enemies are only valid if they're inside our radius //----------------------------------------------------------------------------- bool CNPC_CombineCamera::IsValidEnemy( CBaseEntity *pEnemy ) { Vector vecDelta = pEnemy->GetAbsOrigin() - GetAbsOrigin(); float flDist = vecDelta.Length(); if ( (flDist > m_nOuterRadius) || !FInViewCone(pEnemy) ) return false; return BaseClass::IsValidEnemy( pEnemy ); } //----------------------------------------------------------------------------- // Purpose: Called when we have no scripted target. Looks for new enemies to track. //----------------------------------------------------------------------------- CBaseEntity *CNPC_CombineCamera::MaintainEnemy() { if (HasSpawnFlags(SF_COMBINE_CAMERA_IGNOREENEMIES)) return NULL; GetSenses()->Look(m_nOuterRadius); CBaseEntity *pEnemy = BestEnemy(); if (pEnemy) { // See if our best enemy is too far away to care about. Vector vecDelta = pEnemy->GetAbsOrigin() - GetAbsOrigin(); float flDist = vecDelta.Length(); if (flDist < m_nOuterRadius) { if (FInViewCone(pEnemy)) { // dvs: HACK: for checking multiple view cones float flSaveFieldOfView = m_flFieldOfView; m_flFieldOfView = CAMERA_FOV_NARROW; // Is the target visible? bool bVisible = FVisible(pEnemy); m_flFieldOfView = flSaveFieldOfView; if ( bVisible ) return pEnemy; } } } return NULL; } //----------------------------------------------------------------------------- // Purpose: Think while actively tracking a target. //----------------------------------------------------------------------------- void CNPC_CombineCamera::ActiveThink() { // Allow descended classes a chance to do something before the think function if (PreThink(CAMERA_ACTIVE)) return; // No active target, look for suspicious characters. CBaseEntity *pTarget = MaintainEnemy(); if ( !pTarget ) { // Nobody suspicious. Go back to being idle. m_hEnemyTarget = NULL; EmitSound("NPC_CombineCamera.BecomeIdle"); SetAngry(false); SetThink(&CNPC_CombineCamera::SearchThink); SetNextThink( gpGlobals->curtime ); return; } // Examine the target until it reaches our inner radius if ( pTarget != m_hEnemyTarget ) { Vector vecDelta = pTarget->GetAbsOrigin() - GetAbsOrigin(); float flDist = vecDelta.Length(); if ( (flDist < m_nInnerRadius) && FInViewCone(pTarget) ) { m_OnFoundEnemy.Set(pTarget, pTarget, this); // If it's a citizen, it's ok. If it's the player, it's not ok. if ( pTarget->IsPlayer() ) { SetEyeState(CAMERA_EYE_FOUND_TARGET); if (HasSpawnFlags(SF_COMBINE_CAMERA_BECOMEANGRY)) { SetAngry(true); } else { EmitSound("NPC_CombineCamera.Active"); } m_OnFoundPlayer.Set(pTarget, pTarget, this); m_hEnemyTarget = pTarget; } else { SetEyeState(CAMERA_EYE_HAPPY); m_flEyeHappyTime = gpGlobals->curtime + 2.0; // Now forget about this target forever AddEntityRelationship( pTarget, D_NU, 99 ); } } else { // If we get angry automatically, we get un-angry automatically if ( HasSpawnFlags(SF_COMBINE_CAMERA_BECOMEANGRY) && m_bAngry ) { SetAngry(false); } m_hEnemyTarget = NULL; // We don't quite see this guy, but we sense him. SetEyeState(CAMERA_EYE_SEEKING_TARGET); } } // Update our think time SetNextThink( gpGlobals->curtime + 0.1f ); TrackTarget(pTarget); MaintainEye(); } //----------------------------------------------------------------------------- // Purpose: // Input : pTarget - //----------------------------------------------------------------------------- void CNPC_CombineCamera::TrackTarget( CBaseEntity *pTarget ) { if (!pTarget) return; // Calculate direction to target Vector vecMid = EyePosition(); Vector vecMidTarget = pTarget->BodyTarget(vecMid); Vector vecDirToTarget = vecMidTarget - vecMid; // We want to look at the target's eyes so we don't jitter Vector vecDirToTargetEyes = pTarget->WorldSpaceCenter() - vecMid; VectorNormalize(vecDirToTargetEyes); QAngle vecAnglesToTarget; VectorAngles(vecDirToTargetEyes, vecAnglesToTarget); // Draw debug info if (g_debug_combine_camera.GetBool()) { NDebugOverlay::Cross3D(vecMid, -Vector(2,2,2), Vector(2,2,2), 0, 255, 0, false, 0.05); NDebugOverlay::Cross3D(pTarget->WorldSpaceCenter(), -Vector(2,2,2), Vector(2,2,2), 0, 255, 0, false, 0.05); NDebugOverlay::Line(vecMid, pTarget->WorldSpaceCenter(), 0, 255, 0, false, 0.05); NDebugOverlay::Cross3D(vecMid, -Vector(2,2,2), Vector(2,2,2), 0, 255, 0, false, 0.05); NDebugOverlay::Cross3D(vecMidTarget, -Vector(2,2,2), Vector(2,2,2), 0, 255, 0, false, 0.05); NDebugOverlay::Line(vecMid, vecMidTarget, 0, 255, 0, false, 0.05f); } Vector vecMuzzle, vecMuzzleDir; QAngle vecMuzzleAng; GetAttachment("eyes", vecMuzzle, &vecMuzzleDir); SetIdealActivity((Activity) ACT_COMBINE_CAMERA_OPEN_IDLE); m_vecGoalAngles.y = vecAnglesToTarget.y; m_vecGoalAngles.x = vecAnglesToTarget.x; // Turn to face UpdateFacing(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_CombineCamera::MaintainEye() { // Angry cameras take a few pictures of their target. if ((m_bAngry) && (m_nClickCount <= 3)) { if ((m_flClickTime != 0) && (m_flClickTime < gpGlobals->curtime)) { m_pEyeFlash->SetScale(1.0); m_pEyeFlash->SetBrightness(255); m_pEyeFlash->SetColor(255,255,255); EmitSound("NPC_CombineCamera.Click"); m_flTurnOffEyeFlashTime = gpGlobals->curtime + 0.1; m_flClickTime = gpGlobals->curtime + CAMERA_CLICK_INTERVAL; } else if ((m_flTurnOffEyeFlashTime != 0) && (m_flTurnOffEyeFlashTime < gpGlobals->curtime)) { m_flTurnOffEyeFlashTime = 0; m_pEyeFlash->SetBrightness( 0, 0.25f ); m_nClickCount++; } } } //----------------------------------------------------------------------------- // Purpose: Target doesn't exist or has eluded us, so search for one //----------------------------------------------------------------------------- void CNPC_CombineCamera::SearchThink() { // Allow descended classes a chance to do something before the think function if (PreThink(CAMERA_SEARCHING)) return; SetNextThink( gpGlobals->curtime + 0.05f ); SetIdealActivity((Activity) ACT_COMBINE_CAMERA_OPEN_IDLE); if ( !GetTarget() ) { // Try to acquire a new target if (MaintainEnemy()) { SetThink( &CNPC_CombineCamera::ActiveThink ); return; } } // Display that we're scanning m_vecGoalAngles.x = 15.0f; m_vecGoalAngles.y = GetAbsAngles().y + (sin(gpGlobals->curtime * 2.0f) * 45.0f); // Turn and ping UpdateFacing(); Ping(); SetEyeState(CAMERA_EYE_IDLE); } //----------------------------------------------------------------------------- // Purpose: Allows a generic think function before the others are called // Input : state - which state the camera is currently in //----------------------------------------------------------------------------- bool CNPC_CombineCamera::PreThink(cameraState_e state) { CheckPVSCondition(); MaintainActivity(); StudioFrameAdvance(); // If we're disabled, shut down if ( !m_bEnabled ) { SetIdealActivity((Activity) ACT_COMBINE_CAMERA_CLOSED_IDLE); SetNextThink( gpGlobals->curtime + 0.1f ); return true; } // Do not interrupt current think function return false; } //----------------------------------------------------------------------------- // Purpose: Sets the state of the glowing eye attached to the camera // Input : state - state the eye should be in //----------------------------------------------------------------------------- void CNPC_CombineCamera::SetEyeState(eyeState_t state) { // Must have a valid eye to affect if (m_pEyeGlow == NULL) return; if (m_bAngry) { m_pEyeGlow->SetColor(255, 0, 0); m_pEyeGlow->SetBrightness(164, 0.1f); m_pEyeGlow->SetScale(0.4f, 0.1f); return; } // If we're switching to IDLE, and we're still happy, use happy instead if ( state == CAMERA_EYE_IDLE && m_flEyeHappyTime > gpGlobals->curtime ) { state = CAMERA_EYE_HAPPY; } // Set the state switch (state) { default: case CAMERA_EYE_IDLE: { m_pEyeGlow->SetColor(0, 255, 0); m_pEyeGlow->SetBrightness(164, 0.1f); m_pEyeGlow->SetScale(0.4f, 0.1f); break; } case CAMERA_EYE_SEEKING_TARGET: { // Toggle our state m_bBlinkState = !m_bBlinkState; // Amber m_pEyeGlow->SetColor(255, 128, 0); if (m_bBlinkState) { // Fade up and scale up m_pEyeGlow->SetScale(0.25f, 0.1f); m_pEyeGlow->SetBrightness(164, 0.1f); } else { // Fade down and scale down m_pEyeGlow->SetScale(0.2f, 0.1f); m_pEyeGlow->SetBrightness(64, 0.1f); } break; } case CAMERA_EYE_FOUND_TARGET: { if (!m_bAngry) { // Amber m_pEyeGlow->SetColor(255, 128, 0); // Fade up and scale up m_pEyeGlow->SetScale(0.45f, 0.1f); m_pEyeGlow->SetBrightness(220, 0.1f); } else { m_pEyeGlow->SetColor(255, 0, 0); m_pEyeGlow->SetBrightness(164, 0.1f); m_pEyeGlow->SetScale(0.4f, 0.1f); } break; } case CAMERA_EYE_DORMANT: // Fade out and scale down { m_pEyeGlow->SetColor(0, 255, 0); m_pEyeGlow->SetScale(0.1f, 0.5f); m_pEyeGlow->SetBrightness(64, 0.5f); break; } case CAMERA_EYE_DEAD: // Fade out slowly { m_pEyeGlow->SetColor(255, 0, 0); m_pEyeGlow->SetScale(0.1f, 3.0f); m_pEyeGlow->SetBrightness(0, 3.0f); break; } case CAMERA_EYE_DISABLED: { m_pEyeGlow->SetColor(0, 255, 0); m_pEyeGlow->SetScale(0.1f, 1.0f); m_pEyeGlow->SetBrightness(0, 1.0f); break; } case CAMERA_EYE_HAPPY: { m_pEyeGlow->SetColor(0, 255, 0); m_pEyeGlow->SetBrightness(255, 0.1f); m_pEyeGlow->SetScale(0.5f, 0.1f); break; } } } //----------------------------------------------------------------------------- // Purpose: Make a pinging noise so the player knows where we are //----------------------------------------------------------------------------- void CNPC_CombineCamera::Ping() { // See if it's time to ping again if (m_flPingTime > gpGlobals->curtime) return; // Ping! EmitSound("NPC_CombineCamera.Ping"); m_flPingTime = gpGlobals->curtime + COMBINE_CAMERA_PING_TIME; } //----------------------------------------------------------------------------- // Purpose: Toggle the camera's state //----------------------------------------------------------------------------- void CNPC_CombineCamera::Toggle() { if (m_bEnabled) { Disable(); } else { Enable(); } } //----------------------------------------------------------------------------- // Purpose: Enable the camera and deploy //----------------------------------------------------------------------------- void CNPC_CombineCamera::Enable() { m_bEnabled = true; SetThink(&CNPC_CombineCamera::Deploy); SetNextThink( gpGlobals->curtime + 0.05f ); } //----------------------------------------------------------------------------- // Purpose: Retire the camera until enabled again //----------------------------------------------------------------------------- void CNPC_CombineCamera::Disable() { m_bEnabled = false; m_hEnemyTarget = NULL; SetNextThink( gpGlobals->curtime + 0.1f ); } //----------------------------------------------------------------------------- // Purpose: Toggle the camera's state via input function //----------------------------------------------------------------------------- void CNPC_CombineCamera::InputToggle(inputdata_t &inputdata) { Toggle(); } //----------------------------------------------------------------------------- // Purpose: Input handler to enable the camera. //----------------------------------------------------------------------------- void CNPC_CombineCamera::InputEnable(inputdata_t &inputdata) { Enable(); } //----------------------------------------------------------------------------- // Purpose: Input handler to disable the camera. //----------------------------------------------------------------------------- void CNPC_CombineCamera::InputDisable(inputdata_t &inputdata) { Disable(); } //----------------------------------------------------------------------------- // Purpose: When we become angry, we make an angry sound and start photographing // whatever target we are tracking. //----------------------------------------------------------------------------- void CNPC_CombineCamera::SetAngry(bool bAngry) { if ((bAngry) && (!m_bAngry)) { m_bAngry = true; m_nClickCount = 0; m_flClickTime = gpGlobals->curtime + 0.4; EmitSound("NPC_CombineCamera.Angry"); SetEyeState(CAMERA_EYE_ANGRY); } else if ((!bAngry) && (m_bAngry)) { m_bAngry = false; // make sure the flash is off (we might be in mid-flash) m_pEyeFlash->SetBrightness(0); SetEyeState(GetTarget() ? CAMERA_EYE_SEEKING_TARGET : CAMERA_EYE_IDLE); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_CombineCamera::InputSetAngry(inputdata_t &inputdata) { SetAngry(true); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_CombineCamera::InputSetIdle(inputdata_t &inputdata) { SetAngry(false); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_CombineCamera::DeathThink() { if (PreThink(CAMERA_DEAD)) return; // Level out our angles m_vecGoalAngles = GetAbsAngles(); SetNextThink( gpGlobals->curtime + 0.1f ); if (m_lifeState != LIFE_DEAD) { m_lifeState = LIFE_DEAD; EmitSound("NPC_CombineCamera.Die"); // lots of smoke Vector pos; CollisionProp()->RandomPointInBounds( vec3_origin, Vector( 1, 1, 1 ), &pos ); CBroadcastRecipientFilter filter; te->Smoke(filter, 0.0, &pos, g_sModelIndexSmoke, 2.5, 10); g_pEffects->Sparks(pos); SetActivity((Activity) ACT_COMBINE_CAMERA_CLOSE); } StudioFrameAdvance(); if (IsActivityFinished() && (UpdateFacing() == false)) { SetHeight(COMBINE_CAMERA_RETRACT_HEIGHT); m_flPlaybackRate = 0; SetThink(NULL); } } //----------------------------------------------------------------------------- // Purpose: // Input : height - //----------------------------------------------------------------------------- void CNPC_CombineCamera::SetHeight(float height) { Vector forward, right, up; AngleVectors(GetLocalAngles(), &forward, &right, &up); Vector mins = (forward * -16.0f) + (right * -16.0f); Vector maxs = (forward * 16.0f) + (right * 16.0f) + (up * -height); if (mins.x > maxs.x) { V_swap(mins.x, maxs.x); } if (mins.y > maxs.y) { V_swap(mins.y, maxs.y); } if (mins.z > maxs.z) { V_swap(mins.z, maxs.z); } SetCollisionBounds(mins, maxs); UTIL_SetSize(this, mins, maxs); } //----------------------------------------------------------------------------- // Purpose: Draw any debug text overlays //----------------------------------------------------------------------------- int CNPC_CombineCamera::DrawDebugTextOverlays(void) { int text_offset = BaseClass::DrawDebugTextOverlays(); if (m_debugOverlays & OVERLAY_TEXT_BIT) { char tempstr[512]; Q_snprintf( tempstr, sizeof( tempstr ),"Enemy : %s", m_hEnemyTarget ? m_hEnemyTarget->GetDebugName() : "<none>"); EntityText(text_offset,tempstr,0); text_offset++; } return text_offset; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_CombineCamera::DrawDebugGeometryOverlays(void) { // ------------------------------ // Draw viewcone if selected // ------------------------------ if ((m_debugOverlays & OVERLAY_NPC_VIEWCONE_BIT)) { float flViewRange = acos(CAMERA_FOV_NARROW); Vector vEyeDir = EyeDirection2D( ); Vector vLeftDir, vRightDir; float fSin, fCos; SinCos( flViewRange, &fSin, &fCos ); vLeftDir.x = vEyeDir.x * fCos - vEyeDir.y * fSin; vLeftDir.y = vEyeDir.x * fSin + vEyeDir.y * fCos; vLeftDir.z = vEyeDir.z; fSin = sin(-flViewRange); fCos = cos(-flViewRange); vRightDir.x = vEyeDir.x * fCos - vEyeDir.y * fSin; vRightDir.y = vEyeDir.x * fSin + vEyeDir.y * fCos; vRightDir.z = vEyeDir.z; NDebugOverlay::BoxDirection(EyePosition(), Vector(0,0,-40), Vector(200,0,40), vLeftDir, 255, 255, 0, 50, 0 ); NDebugOverlay::BoxDirection(EyePosition(), Vector(0,0,-40), Vector(200,0,40), vRightDir, 255, 255, 0, 50, 0 ); NDebugOverlay::Box(EyePosition(), -Vector(2,2,2), Vector(2,2,2), 255, 255, 0, 128, 0 ); } BaseClass::DrawDebugGeometryOverlays(); }
0
0.923491
1
0.923491
game-dev
MEDIA
0.944433
game-dev
0.682734
1
0.682734
gikou-official/Gikou
6,335
src/evaluation.h
/* * 技巧 (Gikou), a USI shogi (Japanese chess) playing engine. * Copyright (C) 2016-2017 Yosuke Demura * except where otherwise indicated. * * 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/>. */ #ifndef EVALUATION_H_ #define EVALUATION_H_ #include <memory> #include "common/bitset.h" #include "common/pack.h" #include "common/valarraykey.h" #include "hand.h" #include "piece.h" #include "psq.h" #include "square.h" #include "types.h" class Position; /** * 評価値のスケールです. * 生の評価値をこのスケールで割ることで、1歩=100点(centipawn)の評価値を得ることができます。 * 言い換えると、現在の実装では、評価値の計算に固定小数点を使っていることになります。 */ constexpr int32_t kFvScale = 1 << 16; /** * 4個の32ビット符合付整数をひとつにまとめたものです. * * Packクラスは、内部的にSIMD演算を利用しているので、4個の整数値を同時に計算することができます。 * 4個の整数値は、以下のように、進行度ごとに異なった評価パラメータを格納しています。 * * 1. KPの場合 * - [0] 序盤 * - [1] 中盤 * - [2] 終盤 * - [3] 進行度計算用の重み(評価値ではありませんが、進行度の計算を評価値の計算と同時に行うため、ここに格納してあります) * * 2. KP以外の評価項目の場合 * - [0] 序盤 * - [1] 手番(序盤用) * - [2] 終盤 * - [3] 手番(終盤用) * * (参考文献) * - 金子知適: 「GPS将棋」の評価関数とコンピュータ将棋による棋譜の検討, * 『コンピュータ将棋の進歩6』, pp.25-45, 共立出版, 2012. * - 金澤裕治: NineDayFeverアピール文書, * http://www.computer-shogi.org/wcsc24/appeal/NineDayFever/NDF.txt, 2014. * - 山下宏: YSSアピール文書, * http://www.computer-shogi.org/wcsc25/appeal/YSS/yssappeal2015_2.txt, 2015. */ typedef Pack<int32_t, 4> PackedScore; /** * 評価値の詳細を保存するためのクラスです. * このように評価値の項目を細かく分類しておくと、必要な項目だけ差分計算することができるという利点があります。 */ struct EvalDetail { EvalDetail operator+(const EvalDetail& rhs) const { return EvalDetail(*this) += rhs; } EvalDetail operator-(const EvalDetail& rhs) const { return EvalDetail(*this) -= rhs; } EvalDetail& operator+=(const EvalDetail& rhs) { kp[kBlack] += rhs.kp[kBlack]; kp[kWhite] += rhs.kp[kWhite]; controls += rhs.controls; two_pieces += rhs.two_pieces; king_safety += rhs.king_safety; sliders += rhs.sliders; return *this; } EvalDetail& operator-=(const EvalDetail& rhs) { kp[kBlack] -= rhs.kp[kBlack]; kp[kWhite] -= rhs.kp[kWhite]; controls -= rhs.controls; two_pieces -= rhs.two_pieces; king_safety -= rhs.king_safety; sliders -= rhs.sliders; return *this; } /** * 局面の進行度と手番を考慮して、最終的な評価値を計算します. * @param side_to_move 手番 * @param progress_output 進行度を出力するためのポインタ * @return 進行度と手番を考慮した、最終的な得点 */ Score ComputeFinalScore(Color side_to_move, double* progress_output = nullptr) const; /** KP(King-Piece)に関する評価値. */ ArrayMap<PackedScore, Color> kp{PackedScore(0), PackedScore(0)}; /** 利きに関する評価値. */ PackedScore controls{0}; /** 2駒の関係(PP: Piece-Piece)に関する評価値. */ PackedScore two_pieces{0}; /** 玉の安全度に関する評価値. */ PackedScore king_safety{0}; /** 飛び駒に関する評価値. */ PackedScore sliders{0}; }; /** * 評価値の計算を行うためのクラスです. */ class Evaluation { public: /** * 評価関数の初期化(評価パラメータのファイルからの読み込み等)を行います. */ static void Init(); static void ReadParametersFromFile(const char* file_name); /** * 局面の評価値を計算します. * @param pos 評価値を計算したい局面 * @return その局面の評価値 */ static Score Evaluate(const Position& pos); /** * すべての評価項目について、評価値を計算します. * @param pos 評価値を計算したい局面 * @param psq_list 駒の位置のインデックスのリスト * @return 評価項目ごとの評価値 */ static EvalDetail EvaluateAll(const Position& pos, const PsqList& psq_list); /** * 評価値の差分計算を行います. * @param pos 評価値を計算したい局面 * @param previous_eval 1手前の局面における、評価項目ごとの評価値 * @param previous_list 1手前の局面における、各マスごとの利きのインデックスのリスト * @param current_list 現在の局面における、各マスごとの利きのインデックスのリスト * @param psq_list 1手前の局面における、駒の位置のインデックスのリスト * @return 現局面における、評価項目ごとの評価値 */ static EvalDetail EvaluateDifference(const Position& pos, const EvalDetail& previous_eval, const PsqControlList& previous_list, const PsqControlList& current_list, PsqList* psq_list); }; /** * 評価値の計算に用いるパラメータ(重み)です. */ struct EvalParameters { /** * 評価パラメータをゼロクリアします. */ void Clear() { std::memset(this, 0, sizeof(*this)); } // // 1. 駒の価値 // /** 駒の価値 [駒の種類] */ ArrayMap<Score, PieceType> material; // // 2. 2駒の位置関係 // /** 玉と玉以外の駒の位置関係 [玉の位置][玉以外の駒の種類及び位置] */ ArrayMap<PackedScore, Square, PsqIndex> king_piece; /** 玉を除く2駒の位置関係 [駒1の種類及び位置][駒2の種類及び位置] */ ArrayMap<PackedScore, PsqIndex, PsqIndex> two_pieces; // // 3. 各マスごとの利き // /** 各マスの利き [先手玉か後手玉か][玉の位置][マスの位置、駒の種類、先手の利き数、後手の利き数] */ ArrayMap<PackedScore, Color, Square, PsqControlIndex> controls; // // 4. 玉の安全度 // /** 玉の安全度 [相手の持ち駒][玉から見た方向][そのマスにある駒][攻め方の利き数][受け方の利き数] */ ArrayMap<Array<PackedScore, 4, 4>, HandSet, Direction, Piece> king_safety; // // 5. 飛車・角・香車の利き // /** 飛車の利き [先手玉か後手玉か][玉の位置][飛車の位置][飛車の利きが届いている位置] */ ArrayMap<PackedScore, Color, Square, Square, Square> rook_control; /** 角の利き [先手玉か後手玉か][玉の位置][角の位置][角の利きが届いている位置] */ ArrayMap<PackedScore, Color, Square, Square, Square> bishop_control; /** 香車の利き [先手玉か後手玉か][玉の位置][香車の位置][香車の利きが届いている位置] */ ArrayMap<PackedScore, Color, Square, Square, Square> lance_control; /** 飛車の利きが付いている駒 [相手玉の位置][飛車が利きをつけている駒の位置][飛車が利きをつけている駒] */ ArrayMap<PackedScore, Square, Square, Piece> rook_threat; /** 角の利きが付いている駒 [相手玉の位置][角が利きをつけている駒の位置][角が利きをつけている駒] */ ArrayMap<PackedScore, Square, Square, Piece> bishop_threat; /** 香車の利きが付いている駒 [相手玉の位置][香車が利きをつけている駒の位置][香車が利きをつけている駒] */ ArrayMap<PackedScore, Square, Square, Piece> lance_threat; // // 6. 手番 // /** 手番 */ PackedScore tempo; }; /** * 評価関数のパラメータを格納します. * evaluation.ccのみならず、学習用のコード(learning.cc等)でも使用するので、extern宣言を付けています。 */ extern std::unique_ptr<EvalParameters> g_eval_params; #endif /* EVALUATION_H_ */
0
0.734925
1
0.734925
game-dev
MEDIA
0.123594
game-dev
0.546817
1
0.546817
mastercomfig/tf2-patches-old
3,783
src/game/server/cstrike/cs_hltvdirector.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "cbase.h" #include "hltvdirector.h" #include "igameevents.h" class CCSHLTVDirector : public CHLTVDirector { public: DECLARE_CLASS( CCSHLTVDirector, CHLTVDirector ); const char** GetModEvents(); void SetHLTVServer( IHLTVServer *hltv ); void CreateShotFromEvent( CHLTVGameEvent *event ); }; void CCSHLTVDirector::SetHLTVServer( IHLTVServer *hltv ) { BaseClass::SetHLTVServer( hltv ); if ( m_pHLTVServer ) { // mod specific events the director uses to find interesting shots ListenForGameEvent( "hostage_rescued" ); ListenForGameEvent( "hostage_killed" ); ListenForGameEvent( "hostage_hurt" ); ListenForGameEvent( "hostage_follows" ); ListenForGameEvent( "bomb_pickup" ); ListenForGameEvent( "bomb_dropped" ); ListenForGameEvent( "bomb_exploded" ); ListenForGameEvent( "bomb_defused" ); ListenForGameEvent( "bomb_planted" ); ListenForGameEvent( "vip_escaped" ); ListenForGameEvent( "vip_killed" ); } } void CCSHLTVDirector::CreateShotFromEvent( CHLTVGameEvent *event ) { // show event at least for 2 more seconds after it occured const char *name = event->m_Event->GetName(); IGameEvent *shot = NULL; if ( !Q_strcmp( "hostage_rescued", name ) || !Q_strcmp( "hostage_hurt", name ) || !Q_strcmp( "hostage_follows", name ) || !Q_strcmp( "hostage_killed", name ) ) { CBaseEntity *player = UTIL_PlayerByUserId( event->m_Event->GetInt("userid") ); if ( !player ) return; // shot player as primary, hostage as secondary target shot = gameeventmanager->CreateEvent( "hltv_chase", true ); shot->SetInt( "target1", player->entindex() ); shot->SetInt( "target2", event->m_Event->GetInt("hostage") ); shot->SetFloat( "distance", 96.0f ); shot->SetInt( "theta", 40 ); shot->SetInt( "phi", 20 ); // shot 2 seconds after event m_nNextShotTick = MIN( m_nNextShotTick, (event->m_Tick+TIME_TO_TICKS(2.0)) ); m_iPVSEntity = player->entindex(); } else if ( !Q_strcmp( "bomb_pickup", name ) || !Q_strcmp( "bomb_dropped", name ) || !Q_strcmp( "bomb_planted", name ) || !Q_strcmp( "bomb_defused", name ) ) { CBaseEntity *player = UTIL_PlayerByUserId( event->m_Event->GetInt("userid") ); if ( !player ) return; shot = gameeventmanager->CreateEvent( "hltv_chase", true ); shot->SetInt( "target1", player->entindex() ); shot->SetInt( "target2", 0 ); shot->SetFloat( "distance", 64.0f ); shot->SetInt( "theta", 200 ); shot->SetInt( "phi", 10 ); // shot 2 seconds after pickup m_nNextShotTick = MIN( m_nNextShotTick, (event->m_Tick+TIME_TO_TICKS(2.0)) ); m_iPVSEntity = player->entindex(); } else { // let baseclass create a shot BaseClass::CreateShotFromEvent( event ); return; } if ( shot ) { m_pHLTVServer->BroadcastEvent( shot ); gameeventmanager->FreeEvent( shot ); DevMsg("DrcCmd: %s\n", name ); } } const char** CCSHLTVDirector::GetModEvents() { // game events relayed to spectator clients static const char *s_modevents[] = { "hltv_status", "hltv_chat", "player_connect", "player_disconnect", "player_team", "player_info", "server_cvar", "player_death", "player_chat", "round_start", "round_end", // additional CS:S events: "bomb_planted", "bomb_defused", "hostage_killed", "hostage_hurt", NULL }; return s_modevents; } static CCSHLTVDirector s_HLTVDirector; // singleton EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CHLTVDirector, IHLTVDirector, INTERFACEVERSION_HLTVDIRECTOR, s_HLTVDirector ); CHLTVDirector* HLTVDirector() { return &s_HLTVDirector; } IGameSystem* HLTVDirectorSystem() { return &s_HLTVDirector; }
0
0.971153
1
0.971153
game-dev
MEDIA
0.971477
game-dev
0.801041
1
0.801041
Kein/Altar
1,027
Source/Altar/Public/VPrimitiveComponentDebugData.h
#pragma once #include "CoreMinimal.h" #include "UObject/Object.h" #include "Engine/EngineTypes.h" #include "VPrimitiveComponentDebugData.generated.h" UCLASS(Blueprintable) class ALTAR_API UVPrimitiveComponentDebugData : public UObject { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FName LabelName; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TEnumAsByte<EComponentMobility::Type> Mobility; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FName CollisionProfileName; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bDoesGenerateOverlapEvents; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bCanEverAffectNavigation; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bIsAllowedToSimulate; UVPrimitiveComponentDebugData(); };
0
0.847316
1
0.847316
game-dev
MEDIA
0.783987
game-dev
0.576082
1
0.576082
angaityel/wotr-re
3,011
lua/foundation/scripts/util/sound_ducking/sound_ducker.lua
-- chunkname: @foundation/scripts/util/sound_ducking/sound_ducker.lua SoundDucker = class(SoundDucker) function SoundDucker:init(config, timpani_world, event_id, callback) fassert(BusVolumeDefaults[config.bus_name], "[MusicManager:lerp_bus()] No default value for the bus named %q", config.bus_name) self._default_volume = BusVolumeDefaults[config.bus_name] self._config = config self._timpani_world = timpani_world self._timer = 0 self._callback = callback self._event_id = event_id self._state = "delay" self._delay_time = config.delay or DuckingConfigs.defaults.delay self._fade_in_time = self._delay_time + config.fade_in_time or DuckingConfigs.defaults.fade_in_time self._fade_out_duration = self._config.fade_out_time or DuckingConfigs.defaults.fade_out_time if config.duration then self._hold_time = self._fade_in_time + config.duration end end function SoundDucker:bus_name() return self._config.bus_name end function SoundDucker:update(dt) self._timer = self._timer + dt if self._state == "delay" then local delay_done = self._timer > self._delay_time if delay_done and self._fade_in_time > self._delay_time then self:_setup_fade_in() elseif delay_done then self._state = "hold" end return self._default_volume elseif self._state == "fade_in" then if self._timer > self._fade_in_time then self._state = "hold" end return self:_interpolate(dt) elseif self._state == "hold" then local holding = self:_is_holding() if not holding and self._fade_out_duration > 0 then self:_setup_fade_out() elseif not holding then self:_done() return self._default_volume end return self._config.volume elseif self._state == "fade_out" then if self._timer > self._fade_out_time then self:_done() return self._default_volume end return self:_interpolate(dt) else return self._default_volume end end function SoundDucker:is_done() return self._state == "done" end function SoundDucker:_is_holding() if self._hold_time then return self._timer <= self._hold_time else return TimpaniWorld.is_playing(self._timpani_world, self._event_id) end end function SoundDucker:_setup_fade_in() self._state = "fade_in" self._fade_timer = 0 self._fade_to_value = self._config.volume self._fade_from_value = self._default_volume self._fade_duration = self._config.fade_in_time end function SoundDucker:_setup_fade_out() self._fade_out_time = self._fade_out_duration + self._timer self._state = "fade_out" self._fade_timer = 0 self._fade_to_value = self._default_volume self._fade_from_value = self._config.volume self._fade_duration = self._config.fade_out_time end function SoundDucker:_done() self._state = "done" if self._callback then self._callback() end end function SoundDucker:_interpolate(dt) self._fade_timer = self._fade_timer + dt return math.lerp(self._fade_from_value, self._fade_to_value, math.clamp(self._fade_timer / self._fade_duration, 0, 1)) end function SoundDucker:destroy() return end
0
0.911439
1
0.911439
game-dev
MEDIA
0.412716
game-dev
0.986351
1
0.986351
KKiiya/BedWars-HotbarManager
3,062
hotbarmanager-plugin/src/main/java/me/kiiya/hotbarmanager/listeners/bedwars2023/ShopOpen.java
package me.kiiya.hotbarmanager.listeners.bedwars2023; import me.kiiya.hotbarmanager.HotbarManager; import me.kiiya.hotbarmanager.api.support.VersionSupport; import me.kiiya.hotbarmanager.utils.Support; import me.kiiya.hotbarmanager.utils.Utility; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import static me.kiiya.hotbarmanager.config.ConfigPaths.*; import static me.kiiya.hotbarmanager.utils.Utility.debug; public class ShopOpen implements Listener { private final VersionSupport vs; public ShopOpen() { vs = HotbarManager.getVersionSupport(); } @EventHandler public void onInventoryOpen(InventoryOpenEvent e) { if (HotbarManager.getSupport() != Support.BEDWARS2023) return; Player player = (Player) e.getPlayer(); if (!HotbarManager.getBW2023Api().getArenaUtil().isPlaying(player)) return; if (e.getView().getTitle().equals(Utility.getMsg(player, "shop-items-messages.inventory-name"))) { ItemStack hotbarManagerItem = new ItemStack(Material.valueOf(HotbarManager.getMainConfig().getString(ITEM_TYPE))); ItemMeta hotbarManagerItemMeta = hotbarManagerItem.getItemMeta(); hotbarManagerItemMeta.setDisplayName(Utility.getMsg(player, INVENTORY_ITEM_NAME)); hotbarManagerItemMeta.setLore(Utility.getListMsg(player, INVENTORY_ITEM_LORE)); hotbarManagerItemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_ENCHANTS); hotbarManagerItem.setItemMeta(hotbarManagerItemMeta); debug("HotbarManager item created for " + player.getName()); Bukkit.getScheduler().runTaskLater(HotbarManager.getInstance(), () -> e.getInventory().setItem(HotbarManager.getMainConfig().getInt(ITEM_POSITION) - 1, vs.setItemTag(hotbarManagerItem, "hbm", "menu")), 1); } } @EventHandler public void onHotbarOpen(InventoryClickEvent e) { Player p = (Player) e.getWhoClicked(); if (p == null) return; if (e.getInventory() == null) return; if (e.getClickedInventory() == null) return; if (e.getCurrentItem() == null) return; if (e.getCurrentItem().getItemMeta() == null) return; if (!HotbarManager.getBW2023Api().getArenaUtil().isPlaying(p)) return; if (e.getView().getTitle().equals(Utility.getMsg(p, "shop-items-messages.inventory-name"))) { String hbmTag = vs.getItemTag(e.getCurrentItem(), "hbm"); debug("HotbarManager item clicked by " + p.getName()); if (hbmTag != null && hbmTag.equalsIgnoreCase("menu")) { Bukkit.getServer().dispatchCommand(p, "hbm"); } } } }
0
0.780662
1
0.780662
game-dev
MEDIA
0.940645
game-dev
0.944444
1
0.944444
baldgg/oogabooga
2,357
oogabooga/examples/input_example.c
// This example is kinda dumb for now, I just log stuff to console. #define MAX_KEYS_PER_BINDING 3 typedef enum Action { ACTION_DASH, ACTION_SHOOT, ACTION_MAX } Action; typedef struct Key_Bind { Input_Key_Code codes[MAX_KEYS_PER_BINDING]; } Key_Bind; // Index with action into key bind Key_Bind key_binds[ACTION_MAX] = {0}; bool is_action_just_pressed(Action action) { for (u64 i = 0; i < MAX_KEYS_PER_BINDING; i++) { Input_Key_Code code = key_binds[action].codes[i]; if (code == 0) continue; if (is_key_just_pressed(code)) return true; } return false; } int entry(int argc, char **argv) { window.title = STR("Input example"); window.point_width = 1280; window.point_height = 720; window.x = 200; window.y = 90; window.clear_color = hex_to_rgba(0x6495EDff); key_binds[ACTION_DASH].codes[0] = KEY_SPACEBAR; key_binds[ACTION_DASH].codes[1] = GAMEPAD_A; key_binds[ACTION_SHOOT].codes[0] = MOUSE_BUTTON_LEFT; key_binds[ACTION_SHOOT].codes[1] = GAMEPAD_RIGHT_BUMPER; float64 last_time = os_get_elapsed_seconds(); while (!window.should_close) { reset_temporary_storage(); if (is_key_just_pressed(GAMEPAD_LEFT_TRIGGER)) { log("Left trigger"); } if (is_key_just_pressed(GAMEPAD_B)) { log("B"); } if (is_action_just_pressed(ACTION_DASH)) log("DASH"); if (is_action_just_pressed(ACTION_SHOOT)) log("PEW PEW"); // Vibrate depending on how far pushed the triggers are set_gamepad_vibration(input_frame.left_trigger, input_frame.right_trigger); // Example to retrieve axes for multiple gamepads for (u64 i = 0; i < input_frame.number_of_events; i++) { Input_Event e = input_frame.events[i]; switch (e.kind) { case INPUT_EVENT_GAMEPAD_AXIS: { if (e.axes_changed & INPUT_AXIS_LEFT_STICK) log("Gamepad %d left stick: %f %f", e.gamepad_index, e.left_stick.x, e.left_stick.y); if (e.axes_changed & INPUT_AXIS_RIGHT_STICK) log("Gamepad %d right stick: %f %f", e.gamepad_index, e.right_stick.x, e.right_stick.y); if (e.axes_changed & INPUT_AXIS_LEFT_TRIGGER) log("Gamepad %d left trigger: %f", e.gamepad_index, e.left_trigger); if (e.axes_changed & INPUT_AXIS_RIGHT_TRIGGER) log("Gamepad %d right trigger: %f", e.gamepad_index, e.right_trigger); break; } default: break; } } os_update(); gfx_update(); } return 0; }
0
0.870695
1
0.870695
game-dev
MEDIA
0.51086
game-dev,desktop-app
0.584677
1
0.584677
latte-soft/datamodelpatch
1,301
src/PatchRoot/DataModelInstances/CoreGui/RobloxGui/Modules/LuaApp/Components/AccountSecurity/Common/ModalErrorText.luau
local l_CorePackages_0 = game:GetService("CorePackages"); local l_Modules_0 = game:GetService("CoreGui").RobloxGui.Modules; local v2 = require(l_CorePackages_0.Roact); local v3 = require(l_CorePackages_0.UIBlox); local v4 = require(l_Modules_0.LuaApp.FitChildren); local v5 = require(l_Modules_0.LuaApp.Components.FitTextLabel); local l_withStyle_0 = v3.Style.withStyle; local v7 = v2.PureComponent:extend(script.Name); v7.defaultProps = { contentWidth = 0 }; v7.render = function(v8) local l_contentWidth_0 = v8.props.contentWidth; local l_layoutOrder_0 = v8.props.layoutOrder; local l_errorText_0 = v8.props.errorText; return l_withStyle_0(function(v12) return v2.createElement(v5, { BackgroundTransparency = 1, fitAxis = v4.FitAxis.Height, Font = v12.Font.Footer.Font, LayoutOrder = l_layoutOrder_0 or nil, Size = UDim2.new(0, l_contentWidth_0, 0, 0), Text = l_errorText_0, TextColor3 = v12.Theme.Alert.Color, TextSize = v12.Font.BaseSize * v12.Font.Footer.RelativeSize, TextTransparency = v12.Theme.TextDefault.Transparency, TextWrapped = true, TextXAlignment = Enum.TextXAlignment.Center }); end); end; return v7;
0
0.751317
1
0.751317
game-dev
MEDIA
0.531432
game-dev
0.878401
1
0.878401
lua9520/source-engine-2018-hl2_src
2,140
game/server/tf/halloween/zombie/zombie_spawner.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // // //============================================================================= #include "cbase.h" #include "tf_shareddefs.h" #include "zombie.h" #include "zombie_spawner.h" LINK_ENTITY_TO_CLASS( tf_zombie_spawner, CZombieSpawner ); BEGIN_DATADESC( CZombieSpawner ) DEFINE_KEYFIELD( m_flZombieLifeTime, FIELD_FLOAT, "zombie_lifetime" ), DEFINE_KEYFIELD( m_nMaxActiveZombies, FIELD_INTEGER, "max_zombies" ), DEFINE_KEYFIELD( m_bInfiniteZombies, FIELD_BOOLEAN, "infinite_zombies" ), DEFINE_KEYFIELD( m_nSkeletonType, FIELD_INTEGER, "zombie_type" ), DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ), DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ), DEFINE_INPUTFUNC( FIELD_INTEGER, "SetMaxActiveZombies", InputSetMaxActiveZombies ), END_DATADESC() CZombieSpawner::CZombieSpawner() { m_bEnabled = false; m_bInfiniteZombies = false; m_nMaxActiveZombies = 1; m_flZombieLifeTime = 0; m_nSkeletonType = 0; m_nSpawned = 0; } void CZombieSpawner::Spawn() { BaseClass::Spawn(); SetNextThink( gpGlobals->curtime ); } void CZombieSpawner::Think() { m_activeZombies.FindAndFastRemove( NULL ); if ( m_bEnabled && ( ( m_bInfiniteZombies && m_activeZombies.Count() < m_nMaxActiveZombies ) || ( !m_bInfiniteZombies && m_nSpawned < m_nMaxActiveZombies ) ) ) { CZombie *pZombie = CZombie::SpawnAtPos( GetAbsOrigin(), m_flZombieLifeTime, TF_TEAM_HALLOWEEN, NULL, (CZombie::SkeletonType_t)m_nSkeletonType ); if ( pZombie ) { m_nSpawned++; m_activeZombies.AddToTail( pZombie ); } SetNextThink( gpGlobals->curtime + RandomFloat( 1.5f, 3.f ) ); return; } SetNextThink( gpGlobals->curtime + 0.2f ); } void CZombieSpawner::InputEnable( inputdata_t &inputdata ) { m_bEnabled = true; SetNextThink( gpGlobals->curtime ); } void CZombieSpawner::InputDisable( inputdata_t &inputdata ) { m_bEnabled = false; m_nSpawned = 0; m_activeZombies.Purge(); SetNextThink( gpGlobals->curtime ); } void CZombieSpawner::InputSetMaxActiveZombies( inputdata_t &inputdata ) { m_nMaxActiveZombies = inputdata.value.Int(); }
0
0.894029
1
0.894029
game-dev
MEDIA
0.986002
game-dev
0.823809
1
0.823809
colobot/colobot
2,555
CBot/src/CBot/CBotInstr/CBotLeftExprVar.cpp
/* * This file is part of the Colobot: Gold Edition source code * Copyright (C) 2001-2023, Daniel Roux, EPSITEC SA & TerranovaTeam * http://epsitec.ch; http://colobot.info; http://github.com/colobot * * 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://gnu.org/licenses */ #include "CBot/CBotInstr/CBotLeftExprVar.h" #include "CBot/CBotStack.h" #include "CBot/CBotCStack.h" #include "CBot/CBotVar/CBotVar.h" #include <cassert> #include <sstream> namespace CBot { CBotLeftExprVar::CBotLeftExprVar() { } CBotLeftExprVar::~CBotLeftExprVar() { } CBotInstr* CBotLeftExprVar::Compile(CBotToken* &p, CBotCStack* pStack) { // Verifies that the token is a variable name if (p->GetType() != TokenTypVar) { pStack->SetError(CBotErrNoVar, p); return nullptr; } CBotLeftExprVar* inst = new CBotLeftExprVar(); inst->SetToken(p); p = p->GetNext(); return inst; } bool CBotLeftExprVar::Execute(CBotStack* &pj) { // Create the variable CBotVar* var1 = CBotVar::Create(m_token.GetString(), m_typevar); var1->SetUniqNum(m_nIdent); pj->AddVar(var1); CBotVar* var2 = pj->GetVar(); // Initial value on the stack if (var2 != nullptr) { if (m_typevar.Eq(CBotTypString) && var2->GetType() != CBotTypString) { var2->Update(pj->GetUserPtr()); var1->SetValString(var2->GetValString()); return true; } var1->SetVal(var2); // Set the value } return true; } void CBotLeftExprVar::RestoreState(CBotStack* &pj, bool bMain) { CBotVar* var1; var1 = pj->FindVar(m_token.GetString()); if (var1 == nullptr) assert(false); var1->SetUniqNum(m_nIdent); // Restore the identifier } std::string CBotLeftExprVar::GetDebugData() { std::stringstream ss; ss << m_token.GetString() << std::endl; //ss << "VarID = " << m_nIdent << std::endl; ss << "type = " << m_typevar.ToString(); return ss.str(); } } // namespace CBot
0
0.883012
1
0.883012
game-dev
MEDIA
0.565846
game-dev
0.874038
1
0.874038
patonlab/CASCADE
6,452
cascade-Jupyternotebook-SMILES/models/cascade/static/cascade/j2s/J/shape/TextShape.js
Clazz.declarePackage ("J.shape"); Clazz.load (["J.shape.Shape", "java.util.Hashtable"], "J.shape.TextShape", ["JU.P3", "$.PT", "JU.C", "$.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.objects = null; this.currentObject = null; this.currentFont = null; this.currentColor = null; this.currentBgColor = null; this.currentTranslucentLevel = 0; this.currentBgTranslucentLevel = 0; this.thisID = null; this.isHover = false; this.isAll = false; Clazz.instantialize (this, arguments); }, J.shape, "TextShape", J.shape.Shape); Clazz.prepareFields (c$, function () { this.objects = new java.util.Hashtable (); }); Clazz.defineMethod (c$, "setPropTS", function (propertyName, value, bsSelected) { if ("text" === propertyName) { var text = value; if (this.currentObject != null) { this.currentObject.setText (text); } else if (this.isAll) { for (var t, $t = this.objects.values ().iterator (); $t.hasNext () && ((t = $t.next ()) || true);) t.setText (text); }return; }if ("font" === propertyName) { this.currentFont = value; if (this.currentObject != null) { this.currentObject.setFont (this.currentFont, true); this.currentObject.setFontScale (0); } else if (this.isAll) { for (var t, $t = this.objects.values ().iterator (); $t.hasNext () && ((t = $t.next ()) || true);) t.setFont (this.currentFont, true); }return; }if ("allOff" === propertyName) { this.currentObject = null; this.isAll = true; this.objects = new java.util.Hashtable (); return; }if ("delete" === propertyName) { if (this.currentObject != null) { this.objects.remove (this.currentObject.target); this.currentObject = null; } else if (this.isAll || this.thisID != null) { var e = this.objects.values ().iterator (); while (e.hasNext ()) { var text = e.next (); if (this.isAll || JU.PT.isMatch (text.target.toUpperCase (), this.thisID, true, true)) { e.remove (); }} }return; }if ("off" === propertyName) { if (this.isAll) { this.objects = new java.util.Hashtable (); this.isAll = false; this.currentObject = null; }if (this.currentObject == null) { return; }this.objects.remove (this.currentObject.target); this.currentObject = null; return; }if ("model" === propertyName) { var modelIndex = (value).intValue (); if (this.currentObject != null) { this.currentObject.modelIndex = modelIndex; } else if (this.isAll) { for (var t, $t = this.objects.values ().iterator (); $t.hasNext () && ((t = $t.next ()) || true);) t.modelIndex = modelIndex; }return; }if ("align" === propertyName) { var align = value; if (this.currentObject != null) { if (!this.currentObject.setAlignmentLCR (align)) JU.Logger.error ("unrecognized align:" + align); } else if (this.isAll) { for (var obj, $obj = this.objects.values ().iterator (); $obj.hasNext () && ((obj = $obj.next ()) || true);) obj.setAlignmentLCR (align); }return; }if ("bgcolor" === propertyName) { this.currentBgColor = value; if (this.currentObject != null) { this.currentObject.bgcolix = JU.C.getColixO (value); } else if (this.isAll) { var e = this.objects.values ().iterator (); while (e.hasNext ()) { e.next ().bgcolix = JU.C.getColixO (value); } }return; }if ("color" === propertyName) { this.currentColor = value; if (this.currentObject != null) { this.currentObject.colix = JU.C.getColixO (value); } else if (this.isAll || this.thisID != null) { var e = this.objects.values ().iterator (); while (e.hasNext ()) { var text = e.next (); if (this.isAll || JU.PT.isMatch (text.target.toUpperCase (), this.thisID, true, true)) { text.colix = JU.C.getColixO (value); }} }return; }if ("target" === propertyName) { var target = value; this.isAll = target.equals ("all"); if (this.isAll || target.equals ("none")) { this.currentObject = null; }return; }var isBackground; if ((isBackground = ("bgtranslucency" === propertyName)) || "translucency" === propertyName) { var isTranslucent = ("translucent" === value); if (isBackground) this.currentBgTranslucentLevel = (isTranslucent ? this.translucentLevel : 0); else this.currentTranslucentLevel = (isTranslucent ? this.translucentLevel : 0); if (this.currentObject != null) { this.currentObject.setTranslucent (this.translucentLevel, isBackground); } else if (this.isAll) { var e = this.objects.values ().iterator (); while (e.hasNext ()) { e.next ().setTranslucent (this.translucentLevel, isBackground); } }return; }if (propertyName === "deleteModelAtoms") { var modelIndex = ((value)[2])[0]; var e = this.objects.values ().iterator (); while (e.hasNext ()) { var text = e.next (); if (text.modelIndex == modelIndex) { e.remove (); } else if (text.modelIndex > modelIndex) { text.modelIndex--; }} return; }this.setPropS (propertyName, value, bsSelected); }, "~S,~O,JU.BS"); Clazz.overrideMethod (c$, "getShapeState", function () { return null; }); Clazz.overrideMethod (c$, "initModelSet", function () { this.currentObject = null; this.isAll = false; }); Clazz.overrideMethod (c$, "setModelVisibilityFlags", function (bsModels) { if (!this.isHover) for (var t, $t = this.objects.values ().iterator (); $t.hasNext () && ((t = $t.next ()) || true);) t.visible = (t.modelIndex < 0 || bsModels.get (t.modelIndex)); }, "JU.BS"); Clazz.overrideMethod (c$, "checkObjectClicked", function (x, y, modifiers, bsVisible, drawPicking) { if (this.isHover || modifiers == 0) return null; var isAntialiased = this.vwr.antialiased; for (var obj, $obj = this.objects.values ().iterator (); $obj.hasNext () && ((obj = $obj.next ()) || true);) { if (obj.checkObjectClicked (isAntialiased, x, y, bsVisible)) { if (obj.script != null) this.vwr.evalStringQuiet (obj.script); var map = new java.util.Hashtable (); map.put ("pt", (obj.xyz == null ? new JU.P3 () : obj.xyz)); var modelIndex = obj.modelIndex; if (modelIndex < 0) modelIndex = 0; map.put ("modelIndex", Integer.$valueOf (modelIndex)); map.put ("model", this.vwr.getModelNumberDotted (modelIndex)); map.put ("id", obj.target); map.put ("type", "echo"); return map; }} return null; }, "~N,~N,~N,JU.BS,~B"); Clazz.overrideMethod (c$, "checkObjectHovered", function (x, y, bsVisible) { if (this.isHover) return false; var haveScripts = false; var isAntialiased = this.vwr.antialiased; for (var obj, $obj = this.objects.values ().iterator (); $obj.hasNext () && ((obj = $obj.next ()) || true);) { if (obj.script != null) { haveScripts = true; if (obj.checkObjectClicked (isAntialiased, x, y, bsVisible)) { this.vwr.setCursor (12); return true; }}} if (haveScripts) this.vwr.setCursor (0); return false; }, "~N,~N,JU.BS"); });
0
0.681714
1
0.681714
game-dev
MEDIA
0.297447
game-dev
0.872271
1
0.872271
IvanCampos/Foundation-Models-Playgrounds
1,372
Foundation-Models-Playgrounds/Playgrounds/ProceduralTexture.swift
// // ProceduralTexture.swift // Foundation-Models-Playgrounds // // Created by IVAN CAMPOS on 6/14/25. // import FoundationModels import Playgrounds @Generable(description: "Simple procedural material description for RealityKit.") struct ProceduralTexture: Codable { var baseColor: String // hex or CSS name var roughness: Float // 0 (smooth) – 1 (rough) var metallic: Float // 0 – 1 var normalIntensity: Float // 0 – 2 var pattern: String? // e.g. "stripes", "marble" } /// LLM output model. @Generable(description: "Procedural material parameters derived from text adjectives.") struct TextureRecipe { var adjectives: [String] var texture: ProceduralTexture @Guide(description: "Tips for further tweaking in Reality Composer Pro.") var authorNotes: String } #Playground { let description = "matte dusty rose clay with subtle horizontal grooves" let instruction = """ Turn the adjective phrase into a procedural material recipe suitable for RealityKit’s `SimpleMaterial`. Fill `ProceduralTexture` fields; choose pattern names that standard shaders can emulate. """ let session = LanguageModelSession(instructions: instruction) let recipe = try await session.respond( to: Prompt(description), generating: TextureRecipe.self ) }
0
0.870955
1
0.870955
game-dev
MEDIA
0.50228
game-dev,graphics-rendering
0.519135
1
0.519135
frankfenghua/ios
13,169
Creating Games with cocos2d for iPhone/9007OS_Code bundle/Chapter 05 -Brick/ch5-brick/libs/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp
/* * Copyright (c) 2006-2011 Erin Catto http://www.box2d.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. */ #include <Box2D/Dynamics/Joints/b2RevoluteJoint.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2TimeStep.h> // Point-to-point constraint // C = p2 - p1 // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Motor constraint // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) { bodyA = bA; bodyB = bB; localAnchorA = bodyA->GetLocalPoint(anchor); localAnchorB = bodyB->GetLocalPoint(anchor); referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); } b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) : b2Joint(def) { m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_referenceAngle = def->referenceAngle; m_impulse.SetZero(); m_motorImpulse = 0.0f; m_lowerAngle = def->lowerAngle; m_upperAngle = def->upperAngle; m_maxMotorTorque = def->maxMotorTorque; m_motorSpeed = def->motorSpeed; m_enableLimit = def->enableLimit; m_enableMotor = def->enableMotor; m_limitState = e_inactiveLimit; } void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; m_mass.ex.y = m_mass.ey.x; m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; m_mass.ex.z = m_mass.ez.x; m_mass.ey.z = m_mass.ez.y; m_mass.ez.z = iA + iB; m_motorMass = iA + iB; if (m_motorMass > 0.0f) { m_motorMass = 1.0f / m_motorMass; } if (m_enableMotor == false || fixedRotation) { m_motorImpulse = 0.0f; } if (m_enableLimit && fixedRotation == false) { float32 jointAngle = aB - aA - m_referenceAngle; if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) { m_limitState = e_equalLimits; } else if (jointAngle <= m_lowerAngle) { if (m_limitState != e_atLowerLimit) { m_impulse.z = 0.0f; } m_limitState = e_atLowerLimit; } else if (jointAngle >= m_upperAngle) { if (m_limitState != e_atUpperLimit) { m_impulse.z = 0.0f; } m_limitState = e_atUpperLimit; } else { m_limitState = e_inactiveLimit; m_impulse.z = 0.0f; } } else { m_limitState = e_inactiveLimit; } if (data.step.warmStarting) { // Scale impulses to support a variable time step. m_impulse *= data.step.dtRatio; m_motorImpulse *= data.step.dtRatio; b2Vec2 P(m_impulse.x, m_impulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); } else { m_impulse.SetZero(); m_motorImpulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) { b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); // Solve motor constraint. if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) { float32 Cdot = wB - wA - m_motorSpeed; float32 impulse = -m_motorMass * Cdot; float32 oldImpulse = m_motorImpulse; float32 maxImpulse = data.step.dt * m_maxMotorTorque; m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); float32 Cdot2 = wB - wA; b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); b2Vec3 impulse = -m_mass.Solve33(Cdot); if (m_limitState == e_equalLimits) { m_impulse += impulse; } else if (m_limitState == e_atLowerLimit) { float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse < 0.0f) { b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; m_impulse.x += reduced.x; m_impulse.y += reduced.y; m_impulse.z = 0.0f; } else { m_impulse += impulse; } } else if (m_limitState == e_atUpperLimit) { float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse > 0.0f) { b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; m_impulse.x += reduced.x; m_impulse.y += reduced.y; m_impulse.z = 0.0f; } else { m_impulse += impulse; } } b2Vec2 P(impulse.x, impulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + impulse.z); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + impulse.z); } else { // Solve point-to-point constraint b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); b2Vec2 impulse = m_mass.Solve22(-Cdot); m_impulse.x += impulse.x; m_impulse.y += impulse.y; vA -= mA * impulse; wA -= iA * b2Cross(m_rA, impulse); vB += mB * impulse; wB += iB * b2Cross(m_rB, impulse); } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) { b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Rot qA(aA), qB(aB); float32 angularError = 0.0f; float32 positionError = 0.0f; bool fixedRotation = (m_invIA + m_invIB == 0.0f); // Solve angular limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { float32 angle = aB - aA - m_referenceAngle; float32 limitImpulse = 0.0f; if (m_limitState == e_equalLimits) { // Prevent large angular corrections float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); limitImpulse = -m_motorMass * C; angularError = b2Abs(C); } else if (m_limitState == e_atLowerLimit) { float32 C = angle - m_lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); limitImpulse = -m_motorMass * C; } else if (m_limitState == e_atUpperLimit) { float32 C = angle - m_upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); limitImpulse = -m_motorMass * C; } aA -= m_invIA * limitImpulse; aB += m_invIB * limitImpulse; } // Solve point-to-point constraint. { qA.Set(aA); qB.Set(aB); b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2 C = cB + rB - cA - rA; positionError = C.Length(); float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; b2Mat22 K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; b2Vec2 impulse = -K.Solve(C); cA -= mA * impulse; aA -= iA * b2Cross(rA, impulse); cB += mB * impulse; aB += iB * b2Cross(rB, impulse); } data.positions[m_indexA].c = cA; data.positions[m_indexA].a = aA; data.positions[m_indexB].c = cB; data.positions[m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2RevoluteJoint::GetAnchorA() const { return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2RevoluteJoint::GetAnchorB() const { return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const { b2Vec2 P(m_impulse.x, m_impulse.y); return inv_dt * P; } float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const { return inv_dt * m_impulse.z; } float32 b2RevoluteJoint::GetJointAngle() const { b2Body* bA = m_bodyA; b2Body* bB = m_bodyB; return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; } float32 b2RevoluteJoint::GetJointSpeed() const { b2Body* bA = m_bodyA; b2Body* bB = m_bodyB; return bB->m_angularVelocity - bA->m_angularVelocity; } bool b2RevoluteJoint::IsMotorEnabled() const { return m_enableMotor; } void b2RevoluteJoint::EnableMotor(bool flag) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_enableMotor = flag; } float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const { return inv_dt * m_motorImpulse; } void b2RevoluteJoint::SetMotorSpeed(float32 speed) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_motorSpeed = speed; } void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_maxMotorTorque = torque; } bool b2RevoluteJoint::IsLimitEnabled() const { return m_enableLimit; } void b2RevoluteJoint::EnableLimit(bool flag) { if (flag != m_enableLimit) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_enableLimit = flag; m_impulse.z = 0.0f; } } float32 b2RevoluteJoint::GetLowerLimit() const { return m_lowerAngle; } float32 b2RevoluteJoint::GetUpperLimit() const { return m_upperAngle; } void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) { b2Assert(lower <= upper); if (lower != m_lowerAngle || upper != m_upperAngle) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_impulse.z = 0.0f; m_lowerAngle = lower; m_upperAngle = upper; } } void b2RevoluteJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2RevoluteJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); }
0
0.973226
1
0.973226
game-dev
MEDIA
0.929009
game-dev
0.989381
1
0.989381
S3RAPH-1M/H2M-GSC-Dump
5,910
42930.gsc
// H1 GSC SOURCE // Generated by https://github.com/xensik/gsc-tool deleteportableradar( var_0 ) { if ( !isdefined( var_0 ) ) return; foreach ( var_2 in level.players ) { if ( isdefined( var_2 ) ) var_2.inplayerportableradar = undefined; } var_0 notify( "death" ); var_0 delete(); } monitorportableradaruse() { self endon( "disconnect" ); level endon( "game_ended" ); self.portableradararray = []; for (;;) { self waittill( "grenade_fire", var_0, var_1 ); if ( var_1 == "portabl_radar" || var_1 == "portable_radar_mp" ) { if ( !isalive( self ) ) { var_0 delete(); continue; } self.portableradararray = common_scripts\utility::array_removeundefined( self.portableradararray ); if ( self.portableradararray.size >= level.maxperplayerexplosives ) deleteportableradar( self.portableradararray[0] ); var_0 waittill( "missile_stuck" ); var_2 = var_0.origin; if ( isdefined( var_0 ) ) var_0 delete(); var_3 = spawn( "script_model", var_2 ); var_3.health = 100; var_3.team = self.team; var_3.owner = self; var_3 setcandamage( 1 ); var_3 makeportableradar( self ); var_3 portableradarsetup( self ); var_3 thread maps\mp\gametypes\_weapons::createbombsquadmodel( "weapon_radar_bombsquad", "tag_origin", self ); var_3 thread portableradarproximitytracker(); thread portableradarwatchowner( var_3 ); self.portableradararray[self.portableradararray.size] = var_3; } } } portableradarsetup( var_0 ) { self setmodel( "weapon_radar" ); if ( level.teambased ) maps\mp\_entityheadicons::setteamheadicon( self.team, ( 0, 0, 20 ) ); else maps\mp\_entityheadicons::setplayerheadicon( var_0, ( 0, 0, 20 ) ); thread portableradardamagelistener( var_0 ); thread portableradaruselistener( var_0 ); thread portableradarbeepsounds(); thread maps\mp\_utility::notusableforjoiningplayers( var_0 ); } portableradarwatchowner( var_0 ) { var_0 endon( "death" ); level endon( "game_ended" ); common_scripts\utility::waittill_any( "disconnect", "joined_team", "joined_spectators", "spawned_player" ); level thread deleteportableradar( var_0 ); } portableradarbeepsounds() { self endon( "death" ); level endon( "game_ended" ); for (;;) { wait 2.0; self playsound( "sentry_gun_beep" ); } } portableradardamagelistener( var_0 ) { self endon( "death" ); self.health = 999999; self.maxhealth = 100; self.damagetaken = 0; for (;;) { self waittill( "damage", var_1, var_2, var_3, var_4, var_5, var_6, var_7, var_8, var_9, var_10 ); if ( !maps\mp\gametypes\_weapons::friendlyfirecheck( self.owner, var_2 ) ) continue; if ( isdefined( var_10 ) ) var_11 = maps\mp\_utility::strip_suffix( var_10, "_lefthand" ); else var_11 = undefined; if ( isdefined( var_11 ) ) { switch ( var_11 ) { case "smoke_grenade_mp": case "flash_grenade_mp": case "concussion_grenade_mp": continue; } } if ( !isdefined( self ) ) return; if ( maps\mp\_utility::ismeleemod( var_5 ) ) self.damagetaken = self.damagetaken + self.maxhealth; if ( isdefined( var_9 ) && var_9 & level.idflags_penetration ) self.wasdamagedfrombulletpenetration = 1; self.wasdamaged = 1; self.damagetaken = self.damagetaken + var_1; if ( isplayer( var_2 ) ) var_2 maps\mp\gametypes\_damagefeedback::updatedamagefeedback( "portable_radar" ); if ( self.damagetaken >= self.maxhealth ) { if ( isdefined( var_0 ) && var_2 != var_0 ) var_2 notify( "destroyed_explosive" ); self playsound( "sentry_explode" ); self.deatheffect = playfx( common_scripts\utility::getfx( "equipment_explode" ), self.origin ); self freeentitysentient(); var_2 thread deleteportableradar( self ); } } } portableradaruselistener( var_0 ) { self endon( "death" ); level endon( "game_ended" ); var_0 endon( "disconnect" ); self setcursorhint( "HINT_NOICON" ); self sethintstring( &"MP_PATCH_PICKUP_PORTABLE_RADAR" ); maps\mp\_utility::setselfusable( var_0 ); for (;;) { self waittill( "trigger", var_0 ); var_1 = var_0 getweaponammostock( "portable_radar_mp" ); if ( var_1 < weaponmaxammo( "portable_radar_mp" ) ) { var_0 playlocalsound( "scavenger_pack_pickup" ); var_0 setweaponammostock( "portable_radar_mp", var_1 + 1 ); var_0 thread deleteportableradar( self ); } } } portableradarproximitytracker() { self endon( "death" ); level endon( "game_ended" ); var_0 = 512; for (;;) { foreach ( var_2 in level.players ) { if ( !isdefined( var_2 ) ) continue; if ( level.teambased && var_2.team == self.team ) continue; if ( var_2 maps\mp\_utility::_hasperk( "specialty_class_lowprofile" ) ) continue; var_3 = distancesquared( self.origin, var_2.origin ); if ( distancesquared( var_2.origin, self.origin ) < var_0 * var_0 ) { var_2.inplayerportableradar = self.owner; continue; } var_2.inplayerportableradar = undefined; } wait 0.05; } }
0
0.971087
1
0.971087
game-dev
MEDIA
0.863344
game-dev
0.855475
1
0.855475
Lekksii/picnic-in-the-oblivion
1,704
scripts/GUI/SplashScreensManager.gd
extends Control @export var _move_to: Control @export var _initial_delay: float = 1 var _splash_screens: Array[SplashScreen] = [] @onready var _splash_screen_container: Control = $"." @onready var _splash_blocker : ColorRect = $"../SplashBlocker" @onready var mm : MainMenu = $"../GAME/MainMenu" func _ready() -> void: if GameManager.main_menu and GameManager.show_splash: if not self.visible: self.show() _splash_blocker.show() _move_to.hide() assert(_move_to) set_process_input(false) for splash_screen in _splash_screen_container.get_children(): splash_screen.hide() _splash_screens.push_back(splash_screen) await get_tree().create_timer(_initial_delay).timeout _start_splash_screen() set_process_input(true) func _input(_event: InputEvent) -> void: if GameManager.main_menu and GameManager.show_splash: if OS.has_feature('windows'): if Input.is_action_just_pressed("pause"): _skip() if OS.has_feature('mobile'): if _event is InputEventScreenTouch: if _event.is_pressed(): _skip() func _start_splash_screen() -> void: if _splash_screens.size() == 0: Input.mouse_mode = Input.MOUSE_MODE_VISIBLE _move_to.show() _splash_blocker.queue_free() self.queue_free() mm.OnSplashFinishedAll() else: if not GameManager.Gui.death_screen.visible and not GameManager.Gui.MainMenuWindow.visible: Input.mouse_mode = Input.MOUSE_MODE_CAPTURED var splash_screen: SplashScreen = _splash_screens.pop_front() _splash_blocker.color = splash_screen.color splash_screen.start() splash_screen.connect("finished", _start_splash_screen) func _skip() -> void: _splash_screen_container.get_child(0).queue_free() _start_splash_screen()
0
0.789454
1
0.789454
game-dev
MEDIA
0.842709
game-dev
0.914733
1
0.914733
SkyFireArchives/SkyFireEMU_420
6,287
src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; 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 */ /* Script Data Start SDName: Boss krystallus SDAuthor: LordVanMartin SD%Complete: SDComment: SDCategory: Script Data End */ #include "ScriptPCH.h" #include "halls_of_stone.h" enum Spells { SPELL_BOULDER_TOSS = 50843, H_SPELL_BOULDER_TOSS = 59742, SPELL_GROUND_SPIKE = 59750, SPELL_GROUND_SLAM = 50827, SPELL_SHATTER = 50810, H_SPELL_SHATTER = 61546, SPELL_SHATTER_EFFECT = 50811, H_SPELL_SHATTER_EFFECT = 61547, SPELL_STONED = 50812, SPELL_STOMP = 48131, H_SPELL_STOMP = 59744 }; enum Yells { SAY_AGGRO = -1599007, SAY_KILL = -1599008, SAY_DEATH = -1599009, SAY_SHATTER = -1599010 }; class boss_krystallus : public CreatureScript { public: boss_krystallus() : CreatureScript("boss_krystallus") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_krystallusAI (pCreature); } struct boss_krystallusAI : public ScriptedAI { boss_krystallusAI(Creature *c) : ScriptedAI(c) { pInstance = c->GetInstanceScript(); } uint32 uiBoulderTossTimer; uint32 uiGroundSpikeTimer; uint32 uiGroundSlamTimer; uint32 uiShatterTimer; uint32 uiStompTimer; bool bIsSlam; InstanceScript* pInstance; void Reset() { bIsSlam = false; uiBoulderTossTimer = 3000 + rand()%6000; uiGroundSpikeTimer = 9000 + rand()%5000; uiGroundSlamTimer = 15000 + rand()%3000; uiStompTimer = 20000 + rand()%9000; uiShatterTimer = 0; if (pInstance) pInstance->SetData(DATA_KRYSTALLUS_EVENT, NOT_STARTED); } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); if (pInstance) pInstance->SetData(DATA_KRYSTALLUS_EVENT, IN_PROGRESS); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (uiBoulderTossTimer <= diff) { if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(pTarget, SPELL_BOULDER_TOSS); uiBoulderTossTimer = 9000 + rand()%6000; } else uiBoulderTossTimer -= diff; if (uiGroundSpikeTimer <= diff) { if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(pTarget, SPELL_GROUND_SPIKE); uiGroundSpikeTimer = 12000 + rand()%5000; } else uiGroundSpikeTimer -= diff; if (uiStompTimer <= diff) { DoCast(me, SPELL_STOMP); uiStompTimer = 20000 + rand()%9000; } else uiStompTimer -= diff; if (uiGroundSlamTimer <= diff) { DoCast(me, SPELL_GROUND_SLAM); bIsSlam = true; uiShatterTimer = 10000; uiGroundSlamTimer = 15000 + rand()%3000; } else uiGroundSlamTimer -= diff; if (bIsSlam) { if (uiShatterTimer <= diff) { DoCast(me, DUNGEON_MODE(SPELL_SHATTER, H_SPELL_SHATTER)); } else uiShatterTimer -= diff; } DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (pInstance) pInstance->SetData(DATA_KRYSTALLUS_EVENT, DONE); } void KilledUnit(Unit * victim) { if (victim == me) return; DoScriptText(SAY_KILL, me); } void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) { //this part should be in the core if (pSpell->Id == SPELL_SHATTER || pSpell->Id == H_SPELL_SHATTER) { //this spell must have custom handling in the core, dealing damage based on distance pTarget->CastSpell(pTarget, DUNGEON_MODE(SPELL_SHATTER_EFFECT, H_SPELL_SHATTER_EFFECT), true); if (pTarget->HasAura(SPELL_STONED)) pTarget->RemoveAurasDueToSpell(SPELL_STONED); //clear this, if we are still performing if (bIsSlam) { bIsSlam = false; //and correct movement, if not already if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE) { if (me->getVictim()) me->GetMotionMaster()->MoveChase(me->getVictim()); } } } } }; }; void AddSC_boss_krystallus() { new boss_krystallus(); }
0
0.968462
1
0.968462
game-dev
MEDIA
0.989346
game-dev
0.980752
1
0.980752
emileb/OpenGames
3,153
opengames/src/main/jni/Doom/gzdoom_2/src/g_hexen/a_fighterplayer.cpp
/* #include "actor.h" #include "gi.h" #include "m_random.h" #include "s_sound.h" #include "d_player.h" #include "a_action.h" #include "p_local.h" #include "a_action.h" #include "a_hexenglobal.h" #include "thingdef/thingdef.h" */ IMPLEMENT_CLASS (AFighterWeapon) IMPLEMENT_CLASS (AClericWeapon) IMPLEMENT_CLASS (AMageWeapon) static FRandom pr_fpatk ("FPunchAttack"); //============================================================================ // // AdjustPlayerAngle // //============================================================================ #define MAX_ANGLE_ADJUST (5*ANGLE_1) void AdjustPlayerAngle (AActor *pmo, AActor *linetarget) { angle_t angle; int difference; angle = R_PointToAngle2 (pmo->x, pmo->y, linetarget->x, linetarget->y); difference = (int)angle - (int)pmo->angle; if (abs(difference) > MAX_ANGLE_ADJUST) { if (difference > 0) { pmo->angle += MAX_ANGLE_ADJUST; } else { pmo->angle -= MAX_ANGLE_ADJUST; } } else { pmo->angle = angle; } } //============================================================================ // // TryPunch // // Returns true if an actor was punched, false if not. // //============================================================================ static bool TryPunch(APlayerPawn *pmo, angle_t angle, int damage, fixed_t power) { const PClass *pufftype; AActor *linetarget; int slope; slope = P_AimLineAttack (pmo, angle, 2*MELEERANGE, &linetarget); if (linetarget != NULL) { if (++pmo->weaponspecial >= 3) { damage <<= 1; power *= 3; pufftype = PClass::FindClass ("HammerPuff"); } else { pufftype = PClass::FindClass ("PunchPuff"); } P_LineAttack (pmo, angle, 2*MELEERANGE, slope, damage, NAME_Melee, pufftype, true, &linetarget); if (linetarget != NULL) { if (linetarget->player != NULL || (linetarget->Mass != INT_MAX && (linetarget->flags3 & MF3_ISMONSTER))) { P_ThrustMobj (linetarget, angle, power); } AdjustPlayerAngle (pmo, linetarget); return true; } } return false; } //============================================================================ // // A_FPunchAttack // //============================================================================ DEFINE_ACTION_FUNCTION(AActor, A_FPunchAttack) { int damage; fixed_t power; int i; player_t *player; if (NULL == (player = self->player)) { return; } APlayerPawn *pmo = player->mo; damage = 40+(pr_fpatk()&15); power = 2*FRACUNIT; for (i = 0; i < 16; i++) { if (TryPunch(pmo, pmo->angle + i*(ANG45/16), damage, power) || TryPunch(pmo, pmo->angle - i*(ANG45/16), damage, power)) { // hit something if (pmo->weaponspecial >= 3) { pmo->weaponspecial = 0; P_SetPsprite (player, ps_weapon, player->ReadyWeapon->FindState ("Fire2")); S_Sound (pmo, CHAN_VOICE, "*fistgrunt", 1, ATTN_NORM); } return; } } // didn't find any creatures, so try to strike any walls pmo->weaponspecial = 0; AActor *linetarget; int slope = P_AimLineAttack (pmo, pmo->angle, MELEERANGE, &linetarget); P_LineAttack (pmo, pmo->angle, MELEERANGE, slope, damage, NAME_Melee, PClass::FindClass("PunchPuff"), true); }
0
0.911347
1
0.911347
game-dev
MEDIA
0.98288
game-dev
0.968758
1
0.968758
Creators-of-Create/Create
1,736
src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerBindPacket.java
package com.simibubi.create.content.redstone.link.controller; import com.simibubi.create.content.redstone.link.LinkBehaviour; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraftforge.items.ItemStackHandler; public class LinkedControllerBindPacket extends LinkedControllerPacketBase { private int button; private BlockPos linkLocation; public LinkedControllerBindPacket(int button, BlockPos linkLocation) { super((BlockPos) null); this.button = button; this.linkLocation = linkLocation; } public LinkedControllerBindPacket(FriendlyByteBuf buffer) { super(buffer); this.button = buffer.readVarInt(); this.linkLocation = buffer.readBlockPos(); } @Override public void write(FriendlyByteBuf buffer) { super.write(buffer); buffer.writeVarInt(button); buffer.writeBlockPos(linkLocation); } @Override protected void handleItem(ServerPlayer player, ItemStack heldItem) { if (player.isSpectator()) return; ItemStackHandler frequencyItems = LinkedControllerItem.getFrequencyItems(heldItem); LinkBehaviour linkBehaviour = BlockEntityBehaviour.get(player.level(), linkLocation, LinkBehaviour.TYPE); if (linkBehaviour == null) return; linkBehaviour.getNetworkKey() .forEachWithContext((f, first) -> frequencyItems.setStackInSlot(button * 2 + (first ? 0 : 1), f.getStack() .copy())); heldItem.getTag() .put("Items", frequencyItems.serializeNBT()); } @Override protected void handleLectern(ServerPlayer player, LecternControllerBlockEntity lectern) {} }
0
0.754814
1
0.754814
game-dev
MEDIA
0.989947
game-dev
0.85536
1
0.85536
Lezhi-Ma/SpecGen-Artifact
4,884
ESCTools2/Escjava/java/escjava/vcGeneration/coq/visitor/simplifiers/TProofSplitter.java
package escjava.vcGeneration.coq.visitor.simplifiers; import java.io.IOException; import java.util.Iterator; import escjava.vcGeneration.TBoolImplies; import escjava.vcGeneration.TBoolOr; import escjava.vcGeneration.TDisplay; import escjava.vcGeneration.TFunction; import escjava.vcGeneration.TNode; import escjava.vcGeneration.TRoot; /** * Split the proof using the <code>or</code>s to find out the cutting points. * It does not duplicate the whole proof, it only duplicate the main * implies path. * After this visitor the {@link TNode#parent} field is inconsistant * apart from the main * <code>TRoot -> TBoolImplies ... -> TBoolImplies -> False</code> path. * The split is done recursively over the ors but for a finite number of time * to avoid explosion of the cases. This limmit is given by the * <code>morbidity</code> of the splitter instance. * @author J. Charles */ public class TProofSplitter extends ATSimplifier { /** tells how much the splitter shall go recursively over the <code>or</code>s */ private int morbidity; /** when the degeneration become unviable: equals 5 */ private final static int MORBIDITY_THRESHOLD = 5; private TRoot currentRoot; /** * Construct a new splitter object with a given morbidity of 0. */ public TProofSplitter() { morbidity = 0; } /** * Construct a new splitter object with a given morbidity. * @param currentMorbidity the morbidity of the new instance */ public TProofSplitter(int currentMorbidity) { morbidity = currentMorbidity; } /** * Visit the children of the root node if the morbidity is * different from 0. */ /* * (non-Javadoc) * @see escjava.vcGeneration.TVisitor#visitTRoot(escjava.vcGeneration.TRoot) */ public void visitTRoot(/*@ non_null @*/ TRoot n) { if(morbidity == MORBIDITY_THRESHOLD) return; currentRoot = n; super.visitTRoot(n); } /** * Visit an implication. * If the implication's first member is a or, it generates * several proof obligations, one for each children of the or. * These proof obligations can be obtained with {@link #getListTerms()}. */ /* * (non-Javadoc) * @see escjava.vcGeneration.TVisitor#visitTBoolImplies(escjava.vcGeneration.TBoolImplies) */ public void visitTBoolImplies(/*@ non_null @*/ TBoolImplies n) { if(n.sons.size() != 2) { TDisplay.err(n.sons.size() +"sons, that's suspicious"); } TNode noddor = (TNode)n.sons.get(0); TNode noddy = (TNode)n.sons.get(1); if(noddor instanceof TBoolOr) { TBoolOr tbo = (TBoolOr) noddor; Iterator iter = tbo.sons.iterator(); if (!(n.parent.parent == null)) { currentRoot.sons.remove(findRoot(n)); while(iter.hasNext()) { TNode nod = cloneAndReplace((TBoolImplies)n.parent,(TNode)iter.next(), noddy); TProofSplitter tps = new TProofSplitter(this.morbidity + 1); TRoot root = new TRoot(); root.sons.add(nod); root.accept(tps); if(tps.currentRoot == null || tps.currentRoot.sons.size() == 0) { currentRoot.sons.add(nod); } else { currentRoot.sons.addAll(tps.currentRoot.sons); } } return; } } noddy.accept(this); } /** * Shallow clone the parents term, the children term * and glue it with node through an implication. * Like: <code>parent -> (node -> noddy)</code>. It * returns the root of the generated term. * @param parent the parent to clone and glue * @param node the node to glue * @param noddy the children to clone and glue * @return returns the root node of the clone */ private TNode cloneAndReplace(TBoolImplies parent, TNode node, TNode noddy) { TNode noddyclone = cloneChildren(noddy); TBoolImplies tbi =new TBoolImplies(); addSon(tbi, 0, node); addSon(tbi, 1, noddyclone); TFunction parentclone = cloneParents(parent); addSon(parentclone, 1, tbi); TFunction tr = findRoot(parentclone); return tr; } /** * Clone a term and its parents. * @param par the term to clone * @return the clone term */ private TFunction cloneParents(TBoolImplies par) { TBoolImplies res = new TBoolImplies(); TBoolImplies oldtmp = res; TNode parent = par; TBoolImplies tmp = null; while (parent.parent != null) { tmp = cloneof((TBoolImplies)parent); addSon(tmp, 1, oldtmp); oldtmp = tmp; parent = parent.parent; } TRoot tr = new TRoot(); tr.type = parent.type; tr.sons.add(tmp); tmp.parent = tr; return res.parent; } /** * Shallow clone the children of a node. * It only clone the implications. * @param noddy the node to clone * @return the cloned node */ private TNode cloneChildren(TNode noddy) { if(! (noddy instanceof TBoolImplies)) return noddy; TBoolImplies nod = (TBoolImplies) noddy; TBoolImplies newnod = cloneof(nod); TNode nnn = cloneChildren((TNode)nod.sons.get(1)); nnn.parent = newnod; return newnod; } }
0
0.912229
1
0.912229
game-dev
MEDIA
0.451661
game-dev
0.76996
1
0.76996
latte-soft/builtinplugins
1,386
src/BuiltInPlugins/TerrainEditor/Src/Components/Gizmos/Plane.luau
local l_script_FirstAncestor_0 = script:FindFirstAncestor("TerrainEditor"); local l_DraggerFramework_0 = l_script_FirstAncestor_0.Packages.DraggerFramework; local v2 = require(l_script_FirstAncestor_0.Packages.Framework); local v3 = require(l_script_FirstAncestor_0.Packages.React); local l_Pane_0 = v2.UI.Pane; local v5 = require(l_DraggerFramework_0.DraggerTools.DraggerToolComponent); local v6 = require(l_script_FirstAncestor_0.Src.Hooks.usePlane); local v7 = require(l_script_FirstAncestor_0.Src.Components.Gizmos.Grid); local v8 = require(l_script_FirstAncestor_0.Src.Types); local l_BrushSettings_0 = v8.BrushSettings; local l_Category_0 = v8.Category; local l_PlaneLock_0 = v8.PlaneLock; local _ = v8.Tool; return function(v13) local v14, v15 = v6(v13.Tool, v13.Value, v13.Save, v13.FromSelf); local v16 = v13.Value[l_Category_0.BrushSettings]; if not (v16[l_BrushSettings_0.PlaneLock] == l_PlaneLock_0.Manual) or not v16[l_BrushSettings_0.ManualPlaneLock] then return nil; else return (v3.createElement(l_Pane_0, {}, { Dragger = if v14.Mock then nil else v3.createElement(v5, v14), Grid = v3.createElement(v7, { AlwaysOnTop = v16[l_BrushSettings_0.ManualPlaneLock], Size = v16[l_BrushSettings_0.BrushSize].Size, Transform = v15 }) })); end; end;
0
0.817041
1
0.817041
game-dev
MEDIA
0.641658
game-dev
0.936004
1
0.936004
Albeoris/Memoria
5,507
Assembly-CSharp/Antlr3/ClassicToken.cs
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime { /** <summary> * A Token object like we'd use in ANTLR 2.x; has an actual string created * and associated with this object. These objects are needed for imaginary * tree nodes that have payload objects. We need to create a Token object * that has a string; the tree node will point at this token. CommonToken * has indexes into a char stream and hence cannot be used to introduce * new strings. * </summary> */ [System.Serializable] public class ClassicToken : IToken { string text; int type; int line; int charPositionInLine; int channel = TokenChannels.Default; /** <summary>What token number is this from 0..n-1 tokens</summary> */ int index; public ClassicToken(int type) { this.type = type; } public ClassicToken(IToken oldToken) { text = oldToken.Text; type = oldToken.Type; line = oldToken.Line; charPositionInLine = oldToken.CharPositionInLine; channel = oldToken.Channel; } public ClassicToken(int type, string text) { this.type = type; this.text = text; } public ClassicToken(int type, string text, int channel) { this.type = type; this.text = text; this.channel = channel; } #region IToken Members public string Text { get { return text; } set { text = value; } } public int Type { get { return type; } set { type = value; } } public int Line { get { return line; } set { line = value; } } public int CharPositionInLine { get { return charPositionInLine; } set { charPositionInLine = value; } } public int Channel { get { return channel; } set { channel = value; } } public int StartIndex { get { return -1; } set { } } public int StopIndex { get { return -1; } set { } } public int TokenIndex { get { return index; } set { index = value; } } public ICharStream InputStream { get { return null; } set { } } #endregion public override string ToString() { string channelStr = ""; if (channel > 0) { channelStr = ",channel=" + channel; } string txt = Text; if (txt != null) { txt = txt.Replace("\n", "\\\\n"); txt = txt.Replace("\r", "\\\\r"); txt = txt.Replace("\t", "\\\\t"); } else { txt = "<no text>"; } return "[@" + TokenIndex + ",'" + txt + "',<" + type + ">" + channelStr + "," + line + ":" + CharPositionInLine + "]"; } } }
0
0.786497
1
0.786497
game-dev
MEDIA
0.192647
game-dev
0.687686
1
0.687686
p-org/P
3,561
Src/PCompiler/CompilerCore/TypeChecker/TypeCheckingUtils.cs
using System; using System.Collections.Generic; using System.Linq; using Antlr4.Runtime; using Plang.Compiler.TypeChecker.AST; using Plang.Compiler.TypeChecker.Types; namespace Plang.Compiler.TypeChecker { public static class TypeCheckingUtils { public static void ValidatePayloadTypes( ITranslationErrorHandler handler, ParserRuleContext context, PLanguageType payloadType, IReadOnlyList<IPExpr> arguments) { if (arguments.Count == 0) { if (!payloadType.IsSameTypeAs(PrimitiveType.Null)) { throw handler.TypeMismatch(context, PrimitiveType.Null, payloadType); } } else if (arguments.Count == 1) { CheckArgument(handler, context, payloadType, arguments[0]); } else if (payloadType.Canonicalize() is TupleType tuple) { foreach (var pair in tuple.Types.Zip(arguments, Tuple.Create)) { CheckArgument(handler, context, pair.Item1, pair.Item2); } } else { throw handler.IncorrectArgumentCount(context, arguments.Count, 1); } } public static void CheckArgument( ITranslationErrorHandler handler, ParserRuleContext context, PLanguageType argumentType, IPExpr arg) { if (!argumentType.IsAssignableFrom(arg.Type)) { throw handler.TypeMismatch(context, arg.Type, argumentType); } } public static IEnumerable<IPExpr> VisitRvalueList(PParser.RvalueListContext context, ExprVisitor visitor) { return context?.rvalue().Select(visitor.Visit) ?? Enumerable.Empty<IPExpr>(); } public static int PrintStmtNumArgs(string message) { // Tried using regex for this and it became a hotspot. // There are specific unit tests for this method. // Do not modify without adding tests. var max = 0; for (var i = 0; i < message.Length; i++) { if (message[i] == '{') { if (++i >= message.Length) { return -1; // error - opened { at end of string } if (message[i] == '{') { continue; } var cur = 0; do { if (!char.IsDigit(message[i])) { return -1; // error - expecting only digits within { ... } } cur = 10 * cur + (message[i] - '0'); } while (++i < message.Length && message[i] != '}'); if (i >= message.Length) { return -1; // error - missing closing } at end of string. } max = Math.Max(cur + 1, max); } else if (message[i] == '}') { if (++i >= message.Length || message[i] != '}') { return -1; // error - stray, unescaped } } } } return max; } } }
0
0.91874
1
0.91874
game-dev
MEDIA
0.14701
game-dev
0.931308
1
0.931308
DoubleDeez/MDMetaDataEditor
1,686
Source/MDMetaDataEditor/Private/Customizations/MDMetaDataEditorCustomizationBase.cpp
// Copyright Dylan Dumesnil. All Rights Reserved. #include "MDMetaDataEditorCustomizationBase.h" #include "Config/MDMetaDataEditorConfig.h" #include "Config/MDMetaDataEditorUserConfig.h" #include "DetailCategoryBuilder.h" #include "DetailLayoutBuilder.h" #include "DetailWidgetRow.h" #include "Engine/UserDefinedStruct.h" #include "HAL/PlatformApplicationMisc.h" #include "IDetailGroup.h" #include "K2Node_CustomEvent.h" #include "K2Node_FunctionEntry.h" #include "K2Node_FunctionResult.h" #include "K2Node_Tunnel.h" #include "Kismet2/BlueprintEditorUtils.h" #include "ScopedTransaction.h" #include "Widgets/Input/SButton.h" #include "Widgets/Input/SCheckBox.h" #include "Widgets/Input/SEditableTextBox.h" #include "Widgets/Input/SNumericEntryBox.h" #include "Widgets/SMDMetaDataGameplayTagPicker.h" #include "Widgets/SMDMetaDataStringComboBox.h" #include "Widgets/Text/STextBlock.h" FMDMetaDataEditorCustomizationBase::FMDMetaDataEditorCustomizationBase(const TWeakPtr<IBlueprintEditor>& BlueprintEditor, TWeakObjectPtr<UBlueprint>&& BlueprintPtr) : BlueprintEditor(BlueprintEditor) , BlueprintPtr(MoveTemp(BlueprintPtr)) {} void FMDMetaDataEditorCustomizationBase::CustomizeDetails(IDetailLayoutBuilder& DetailLayout) { DetailBuilderPtr = &DetailLayout; TArray<TWeakObjectPtr<UObject>> ObjectsBeingCustomized; DetailLayout.GetObjectsBeingCustomized(ObjectsBeingCustomized); if (ObjectsBeingCustomized.Num() != 1) { return; } CustomizeObject(DetailLayout, ObjectsBeingCustomized[0].Get()); } void FMDMetaDataEditorCustomizationBase::RefreshDetails() { if (DetailBuilderPtr != nullptr) { DetailBuilderPtr->ForceRefreshDetails(); DetailBuilderPtr = nullptr; } }
0
0.886245
1
0.886245
game-dev
MEDIA
0.470708
game-dev,desktop-app
0.53732
1
0.53732
Aussiemon/Darktide-Source-Code
4,145
scripts/utilities/orientation.lua
-- chunkname: @scripts/utilities/orientation.lua local InputDevice = require("scripts/managers/input/input_device") local WeaponTemplate = require("scripts/utilities/weapon/weapon_template") local Orientation = {} local _mouse_input, _gamepad_input Orientation.look_delta = function (main_dt, input, fov_sensitivity, mouse_scale, look_delta_context) local mouse_input = _mouse_input(input, look_delta_context) local gamepad_input = _gamepad_input(input, look_delta_context) local look_delta = (mouse_input * mouse_scale + gamepad_input) * fov_sensitivity return look_delta end local PI = math.pi local PI_2 = PI * 2 Orientation.clamp_from_origin = function (current_rad, delta_rad, origin_rad, constraint_rad) local min = origin_rad - constraint_rad * 0.5 local max = origin_rad + constraint_rad * 0.5 local mod = 0 if min < 0 or max > PI_2 then mod = PI end min = (min + mod) % PI_2 max = (max + mod) % PI_2 current_rad = (current_rad + mod) % PI_2 local new_value = math.clamp(current_rad - delta_rad, min, max) - mod return new_value end function _mouse_input(input, look_delta_context) local weapon_action_component = look_delta_context.weapon_action_component local alternate_fire_component = look_delta_context.alternate_fire_component local weapon_template = weapon_action_component and WeaponTemplate.current_weapon_template(weapon_action_component) local ranged_weapon_wielded = weapon_template and WeaponTemplate.is_ranged(weapon_template) local grenade_weapon_wielded = weapon_template and WeaponTemplate.is_grenade(weapon_template) local use_ranged_filter = ranged_weapon_wielded or grenade_weapon_wielded local alternate_fire_is_active = alternate_fire_component and alternate_fire_component.is_active local input_filter_name input_filter_name = use_ranged_filter and alternate_fire_is_active and "look_ranged_alternate_fire" or use_ranged_filter and "look_ranged" or "look" local mouse_input = input:get(input_filter_name) mouse_input.z = 0 return mouse_input end function _gamepad_input(input, look_delta_context) local using_gamepad = Managers.input:is_using_gamepad() if not using_gamepad then return Vector3.zero() end local weapon_action_component = look_delta_context.weapon_action_component local alternate_fire_component = look_delta_context.alternate_fire_component local targeting_data = look_delta_context.targeting_data local weapon_template = weapon_action_component and WeaponTemplate.current_weapon_template(weapon_action_component) local ranged_weapon_wielded = weapon_template and WeaponTemplate.is_ranged(weapon_template) local grenade_weapon_wielded = weapon_template and WeaponTemplate.is_grenade(weapon_template) local melee_weapon_wielded = weapon_template and WeaponTemplate.is_melee(weapon_template) local use_ranged_filter = ranged_weapon_wielded or grenade_weapon_wielded local use_melee_filter = melee_weapon_wielded local alternate_fire_is_active = alternate_fire_component and alternate_fire_component.is_active local targets_within_range = targeting_data and targeting_data.targets_within_range local is_sticky = look_delta_context.is_sticky local is_lunging = look_delta_context.is_lunging local new_input_filter_method = false local aim_assist_type = Managers.save:account_data().input_settings.controller_aim_assist if aim_assist_type ~= "old" then new_input_filter_method = true end local input_filter_name input_filter_name = new_input_filter_method and (is_lunging and "look_controller_lunging" or use_ranged_filter and alternate_fire_is_active and "look_controller_ranged_alternate_fire_improved" or use_ranged_filter and "look_controller_ranged_improved" or "look_controller_improved") or is_lunging and "look_controller_lunging" or use_ranged_filter and alternate_fire_is_active and "look_controller_ranged_alternate_fire" or use_ranged_filter and "look_controller_ranged" or use_melee_filter and targets_within_range and (is_sticky and "look_controller_melee_sticky" or "look_controller_melee") or "look_controller" local gamepad_input = input:get(input_filter_name) return gamepad_input end return Orientation
0
0.94221
1
0.94221
game-dev
MEDIA
0.977367
game-dev
0.819475
1
0.819475
radar/mtg
1,764
spec/cards/scavenging_ooze_spec.rb
require 'spec_helper' RSpec.describe Magic::Cards::ScavengingOoze do include_context "two player game" let(:scavenging_ooze) { ResolvePermanent("Scavenging Ooze", owner: p1) } context "activated ability" do def ability scavenging_ooze.activated_abilities.first end context "when p2 has wood elves in their graveyard" do let(:wood_elves) { Card("Wood Elves") } before do p2.graveyard << wood_elves end it "exiles a card from a graveyard, adds +1/1 counter and p1 gains life" do p1.add_mana(green: 1) starting_life = p1.life p1.activate_ability(ability: ability) do _1 .pay_mana(green: 1) .targeting(wood_elves) end game.stack.resolve! aggregate_failures do expect(wood_elves.zone).to be_exile expect(scavenging_ooze.counters.count).to eq(1) expect(scavenging_ooze.counters.first).to be_a(Magic::Counters::Plus1Plus1) expect(p1.life).to eq(starting_life + 1) end end end context "when p2 has sol ring in their graveyard" do let(:sol_ring) { Card("Sol Ring") } before do p2.graveyard << sol_ring end it "exiles sol ring, does not add counter and p1 does not gain life" do p1.add_mana(green: 1) starting_life = p1.life p1.activate_ability(ability: ability) do _1 .pay_mana(green: 1) .targeting(sol_ring) end game.stack.resolve! aggregate_failures do expect(sol_ring.zone).to be_exile expect(scavenging_ooze.counters.count).to eq(0) expect(p1.life).to eq(starting_life) end end end end end
0
0.888925
1
0.888925
game-dev
MEDIA
0.870955
game-dev,testing-qa
0.656272
1
0.656272
pixelcmtd/CXClient
2,676
src/minecraft/net/minecraft/world/gen/layer/IntCache.java
package net.minecraft.world.gen.layer; import com.google.common.collect.Lists; import java.util.List; public class IntCache { private static int intCacheSize = 256; private static List<int[]> freeSmallArrays = Lists.<int[]>newArrayList(); private static List<int[]> inUseSmallArrays = Lists.<int[]>newArrayList(); private static List<int[]> freeLargeArrays = Lists.<int[]>newArrayList(); private static List<int[]> inUseLargeArrays = Lists.<int[]>newArrayList(); public static synchronized int[] getIntCache(int p_76445_0_) { if (p_76445_0_ <= 256) { if (freeSmallArrays.isEmpty()) { int[] aint4 = new int[256]; inUseSmallArrays.add(aint4); return aint4; } else { int[] aint3 = (int[])freeSmallArrays.remove(freeSmallArrays.size() - 1); inUseSmallArrays.add(aint3); return aint3; } } else if (p_76445_0_ > intCacheSize) { intCacheSize = p_76445_0_; freeLargeArrays.clear(); inUseLargeArrays.clear(); int[] aint2 = new int[intCacheSize]; inUseLargeArrays.add(aint2); return aint2; } else if (freeLargeArrays.isEmpty()) { int[] aint1 = new int[intCacheSize]; inUseLargeArrays.add(aint1); return aint1; } else { int[] aint = (int[])freeLargeArrays.remove(freeLargeArrays.size() - 1); inUseLargeArrays.add(aint); return aint; } } /** * Mark all pre-allocated arrays as available for re-use by moving them to the appropriate free lists. */ public static synchronized void resetIntCache() { if (!freeLargeArrays.isEmpty()) { freeLargeArrays.remove(freeLargeArrays.size() - 1); } if (!freeSmallArrays.isEmpty()) { freeSmallArrays.remove(freeSmallArrays.size() - 1); } freeLargeArrays.addAll(inUseLargeArrays); freeSmallArrays.addAll(inUseSmallArrays); inUseLargeArrays.clear(); inUseSmallArrays.clear(); } /** * Gets a human-readable string that indicates the sizes of all the cache fields. Basically a synchronized static * toString. */ public static synchronized String getCacheSizes() { return "cache: " + freeLargeArrays.size() + ", tcache: " + freeSmallArrays.size() + ", allocated: " + inUseLargeArrays.size() + ", tallocated: " + inUseSmallArrays.size(); } }
0
0.721553
1
0.721553
game-dev
MEDIA
0.551282
game-dev
0.95987
1
0.95987
JetBoom/zombiesurvival
2,096
gamemodes/zombiesurvival/entities/weapons/weapon_zs_rollerminecontrol.lua
AddCSLuaFile() SWEP.PrintName = "Rollermine Control" SWEP.Description = "Controller for your Rollermine." if CLIENT then SWEP.ViewModelFOV = 50 SWEP.BobScale = 0.5 SWEP.SwayScale = 0.5 SWEP.Slot = 4 SWEP.SlotPos = 0 end SWEP.ViewModel = "models/weapons/c_slam.mdl" SWEP.WorldModel = "models/weapons/w_slam.mdl" SWEP.UseHands = true SWEP.EntityClass = "prop_rollermine" SWEP.Primary.Delay = 0 SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "none" SWEP.Secondary.Delay = 20 SWEP.Secondary.Heal = 10 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.WalkSpeed = SPEED_FAST SWEP.NoMagazine = true SWEP.Undroppable = true SWEP.NoPickupNotification = true SWEP.HoldType = "slam" SWEP.NoDeploySpeedChange = true SWEP.NoTransfer = true SWEP.AutoSwitchFrom = false function SWEP:Initialize() self:SetWeaponHoldType(self.HoldType) self:SetDeploySpeed(10) end function SWEP:Think() if self.IdleAnimation and self.IdleAnimation <= CurTime() then self.IdleAnimation = nil self:SendWeaponAnim(ACT_VM_IDLE) end if SERVER then for _, ent in pairs(ents.FindByClass(self.EntityClass)) do if ent:IsValid() and ent:GetObjectOwner() == self:GetOwner() then return end end self:GetOwner():StripWeapon(self:GetClass()) end end function SWEP:PrimaryAttack() if IsFirstTimePredicted() then self:SetDTBool(0, not self:GetDTBool(0)) if CLIENT then MySelf:EmitSound(self:GetDTBool(0) and "buttons/button17.wav" or "buttons/button19.wav", 0) end end end function SWEP:SecondaryAttack() end function SWEP:Reload() return false end function SWEP:Deploy() gamemode.Call("WeaponDeployed", self:GetOwner(), self) self.IdleAnimation = CurTime() + self:SequenceDuration() return true end function SWEP:Holster() self:SetDTBool(0, false) return true end function SWEP:Reload() end if not CLIENT then return end function SWEP:DrawWeaponSelection(x, y, w, h, alpha) self:BaseDrawWeaponSelection(x, y, w, h, alpha) end
0
0.809925
1
0.809925
game-dev
MEDIA
0.735469
game-dev
0.934012
1
0.934012
Deijin27/RanseiLink
2,770
RanseiLink.GuiCore/ViewModels/ModelViewModels/MiniViewModels/EpisodeMiniViewModel.cs
#nullable enable using RanseiLink.Core; using RanseiLink.Core.Enums; using RanseiLink.Core.Models; using RanseiLink.Core.Services; using RanseiLink.Core.Services.ModelServices; using RanseiLink.Core.Util; using System.Xml.Linq; namespace RanseiLink.GuiCore.ViewModels; public class EpisodeMiniViewModel( ICachedSpriteProvider spriteProvider, IBaseWarriorService baseWarriorService, IScenarioWarriorService scenarioWarriorService, IScenarioKingdomService scenarioKingdomService, ICachedMsgBlockService cachedMsgBlockService, Episode model, int id, ICommand selectCommand) : ViewModelBase, IMiniViewModel { public int Id => id; public string Name { get => cachedMsgBlockService.GetMsgOfType(MsgShortcut.EpisodeName, Id); } public object? Image { get { var scenario = (int)model.Scenario; KingdomId startKingdom = KingdomId.Default; foreach (KingdomId kingdom in EnumUtil.GetValuesExceptDefaults<KingdomId>()) { if (model.GetIsStartKingdom(kingdom)) { startKingdom = kingdom; break; } } if (startKingdom == KingdomId.Default) { return null; } var army = scenarioKingdomService.Retrieve(scenario).GetArmy(startKingdom); foreach (var scenWarrior in scenarioWarriorService.Retrieve(scenario).Enumerate()) { if (scenWarrior.Army == army && scenWarrior.Class == WarriorClassId.ArmyLeader) { var baseWarrior = baseWarriorService.Retrieve((int)scenWarrior.Warrior); return spriteProvider.GetSprite(SpriteType.StlBushouS, baseWarrior.Sprite); } } return null; } } public int Difficulty => model.Difficulty; public ICommand SelectCommand { get; } = selectCommand; public bool MatchSearchTerm(string searchTerm) { if (Name.ContainsIgnoreCaseAndAccents(searchTerm)) { return true; } return false; } public void NotifyPropertyChanged(string? name) { switch (name) { case nameof(EpisodeViewModel.Name): RaisePropertyChanged(nameof(Name)); break; case nameof(EpisodeViewModel.Scenario): case nameof(EpisodeViewModel.StartKingdomChanged): RaisePropertyChanged(nameof(Image)); break; case nameof(EpisodeViewModel.Difficulty): RaisePropertyChanged(nameof(Difficulty)); break; } } }
0
0.918432
1
0.918432
game-dev
MEDIA
0.408448
game-dev
0.9404
1
0.9404
Aussiemon/Darktide-Source-Code
1,267
scripts/managers/telemetry/reporters/placed_items_reporter.lua
-- chunkname: @scripts/managers/telemetry/reporters/placed_items_reporter.lua local ReporterInterface = require("scripts/managers/telemetry/reporters/reporter_interface") local PlacedItemsReporter = class("PlacedItemsReporter") PlacedItemsReporter.init = function (self) self._reports = {} end PlacedItemsReporter.update = function (self, dt, t) return end PlacedItemsReporter.report = function (self) if table.is_empty(self._reports) then return end Managers.telemetry_events:placed_items_report(self._reports) end PlacedItemsReporter.register_event = function (self, player, item_name) local subject = player:telemetry_subject() local player_key = string.format("%s:%s", subject.account_id, subject.character_id) local entries = self._reports[player_key] and self._reports[player_key].entries if entries then entries[item_name] = (entries[item_name] or 0) + 1 else local player_data = { telemetry_subject = subject, telemetry_game_session = player:telemetry_game_session(), } self._reports[player_key] = { player_data = player_data, entries = { [item_name] = 1, }, } end end PlacedItemsReporter.destroy = function (self) return end implements(PlacedItemsReporter, ReporterInterface) return PlacedItemsReporter
0
0.842909
1
0.842909
game-dev
MEDIA
0.928994
game-dev
0.790017
1
0.790017
PowerNukkitX/PowerNukkitX
5,941
src/main/java/cn/nukkit/scoreboard/Scoreboard.java
package cn.nukkit.scoreboard; import cn.nukkit.Server; import cn.nukkit.event.scoreboard.ScoreboardLineChangeEvent; import cn.nukkit.scoreboard.data.DisplaySlot; import cn.nukkit.scoreboard.data.SortOrder; import cn.nukkit.scoreboard.displayer.IScoreboardViewer; import cn.nukkit.scoreboard.scorer.FakeScorer; import cn.nukkit.scoreboard.scorer.IScorer; import lombok.Getter; import lombok.Setter; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; @Getter public class Scoreboard implements IScoreboard{ protected String objectiveName; protected String displayName; protected String criteriaName; @Setter protected SortOrder sortOrder; protected Map<DisplaySlot, Set<IScoreboardViewer>> viewers = new HashMap<>(); protected Map<IScorer, IScoreboardLine> lines = new HashMap<>(); { for (var slot : DisplaySlot.values()) { viewers.put(slot, new HashSet<>()); } } public Scoreboard(String objectiveName, String displayName) { this(objectiveName, displayName, "dummy"); } public Scoreboard(String objectiveName, String displayName, String criteriaName) { this(objectiveName, displayName, criteriaName, SortOrder.ASCENDING); } public Scoreboard(String objectiveName, String displayName, String criteriaName, SortOrder sortOrder) { this.objectiveName = objectiveName; this.displayName = displayName; this.criteriaName = criteriaName; this.sortOrder = sortOrder; } @Override public Set<IScoreboardViewer> getAllViewers() { var all = new HashSet<IScoreboardViewer>(); this.viewers.values().forEach(all::addAll); return all; } @Override public Set<IScoreboardViewer> getViewers(DisplaySlot slot) { return this.viewers.get(slot); } @Override public boolean removeViewer(IScoreboardViewer viewer, DisplaySlot slot) { boolean removed = this.viewers.get(slot).remove(viewer); if (removed) viewer.hide(slot); return removed; } @Override public boolean addViewer(IScoreboardViewer viewer, DisplaySlot slot) { boolean added = this.viewers.get(slot).add(viewer); if (added) viewer.display(this, slot); return added; } @Override public boolean containViewer(IScoreboardViewer viewer, DisplaySlot slot) { return this.viewers.get(slot).contains(viewer); } @Override public @Nullable IScoreboardLine getLine(IScorer scorer) { return this.lines.get(scorer); } @Override public boolean addLine(IScoreboardLine line) { if (shouldCallEvent()) { var event = new ScoreboardLineChangeEvent(this, line, line.getScore(), line.getScore(), ScoreboardLineChangeEvent.ActionType.ADD_LINE); Server.getInstance().getPluginManager().callEvent(event); if (event.isCancelled()) return false; line = event.getLine(); } this.lines.put(line.getScorer(), line); updateScore(line); return true; } @Override public boolean addLine(IScorer scorer, int score) { return addLine(new ScoreboardLine(this, scorer, score)); } @Override public boolean addLine(String text, int score) { var fakeScorer = new FakeScorer(text); return addLine(new ScoreboardLine(this, fakeScorer, score)); } @Override public boolean removeLine(IScorer scorer) { var removed = lines.get(scorer); if (removed == null) return false; if (shouldCallEvent()) { var event = new ScoreboardLineChangeEvent(this, removed, removed.getScore(), removed.getScore(), ScoreboardLineChangeEvent.ActionType.REMOVE_LINE); Server.getInstance().getPluginManager().callEvent(event); if (event.isCancelled()) return false; } this.lines.remove(scorer); getAllViewers().forEach(viewer -> viewer.removeLine(removed)); return true; } @Override public boolean removeAllLine(boolean send) { if (lines.isEmpty()) return false; if (shouldCallEvent()) { var event = new ScoreboardLineChangeEvent(this, null, 0, 0, ScoreboardLineChangeEvent.ActionType.REMOVE_ALL_LINES); Server.getInstance().getPluginManager().callEvent(event); if (event.isCancelled()) return false; } if (send) { this.lines.keySet().forEach(this::removeLine); } else { this.lines.clear(); } return true; } @Override public boolean containLine(IScorer scorer) { return this.lines.containsKey(scorer); } @Override public void updateScore(IScoreboardLine update) { getAllViewers().forEach(viewer -> viewer.updateScore(update)); } @Override public void resend() { getAllViewers().forEach(viewer -> viewer.removeScoreboard(this)); this.viewers.forEach((slot, slotViewers) -> { slotViewers.forEach(slotViewer -> { slotViewer.display(this, slot); }); }); } @Override public void setLines(List<String> lines) { removeAllLine(false); AtomicInteger score = new AtomicInteger(); lines.forEach(str -> { var scorer = new FakeScorer(str); this.lines.put(scorer, new ScoreboardLine(this, scorer, score.getAndIncrement())); }); resend(); } @Override public void setLines(Collection<IScoreboardLine> lines) { removeAllLine(false); lines.forEach(line -> this.lines.put(line.getScorer(), line)); resend(); } @Override public boolean shouldCallEvent() { var manager = Server.getInstance().getScoreboardManager(); return manager != null && manager.containScoreboard(this); } }
0
0.969672
1
0.969672
game-dev
MEDIA
0.656974
game-dev
0.973043
1
0.973043
Secrets-of-Sosaria/World
4,534
Data/Scripts/Items/Books/Trades/LearnScales.cs
using System; using Server; using Server.Items; using System.Text; using Server.Mobiles; using Server.Gumps; using Server.Network; using Server.Misc; namespace Server.Items { public class LearnScalesBook : Item { public override Catalogs DefaultCatalog{ get{ return Catalogs.Book; } } [Constructable] public LearnScalesBook( ) : base( 0x1C11 ) { ItemID = RandomThings.GetRandomBookItemID(); Hue = Utility.RandomColor(0); Weight = 1.0; Name = "Reptile Scale Crafts"; } public class LearnScalesGump : Gump { private Item m_Book; private int m_Page; private Mobile m_Mobile; public LearnScalesGump( Mobile from, Item book, int page ): base( 50, 50 ) { m_Book = book; m_Page = page; m_Mobile = from; string color = "#CEAA87"; m_Mobile.SendSound( 0x55 ); Closable = true; Disposable = true; Dragable = true; Resizable = false; AddPage(0); AddImage(0, 0, 7005, book.Hue); AddImage(0, 0, 7006); AddImage(0, 0, 7024, 2789); int prevPage = page - 1; if ( prevPage < 1 ){ prevPage = 900; } int nextPage = page + 1; AddHtml( 106, 44, 215, 20, @"<BODY><BASEFONT Color=" + color + ">" + m_Book.Name + "</BASEFONT></BODY>", (bool)false, (bool)false); AddButton(71, 41, 4014, 4014, prevPage, GumpButtonType.Reply, 0); AddButton(596, 41, 4005, 4005, nextPage, GumpButtonType.Reply, 0); if ( m_Page == 2 ) { int amt = 13; int itm = 0; int x = 75; int y = 75; CraftResource res = CraftResource.RedScales; int modX = 289; int modY = 36; while ( amt > 0 ) { amt--; itm++; AddItem( x, y, 9908, CraftResources.GetHue( res ) ); AddHtml( x+44, y, 200, 20, @"<BODY><BASEFONT Color=" + color + ">" + CraftResources.GetName( res ) + " Scales</BASEFONT></BODY>", (bool)false, (bool)false); y += modY; if ( itm == 9 ){ y = 75; x += modX; } res = (CraftResource)( (int)res + 1 ); } } else { AddItem(75, 85, 26372, 0x99D); AddItem(361, 83, 4017); AddItem(73, 169, 9908, 0x99D); AddItem(82, 139, 3922); AddItem(364, 144, 4016); string craft = "Blacksmiths are able to use the hardened scales of reptiles, to make various types of armor and shields. These scales can vary in color and properties they enhance, for the items you can make from them. Due to the hardened nature of these scales, you would need an anvil and forge in order to heat them and hammer them into the shape required."; string scales = "Use a bladed item, like a dagger or knife, on a corpse by double clicking the item and then selecting the corpse. If there are reptile scales to be taken from it, they will appear in their pack. Different types of scales can be found on many creatures like lizards, dragons and dinosaurs. You can use these scales to make different types of armor and shields by using scaling tools. Some of the types of scales you can find are listed on the next page."; AddHtml( 122, 80, 200, 300, @"<BODY><BASEFONT Color=" + color + ">" + craft + "</BASEFONT></BODY>", (bool)false, (bool)false); AddHtml( 415, 80, 200, 300, @"<BODY><BASEFONT Color=" + color + ">" + scales + "</BASEFONT></BODY>", (bool)false, (bool)false); } } public override void OnResponse( NetState state, RelayInfo info ) { if ( info.ButtonID > 0 ) { m_Page = info.ButtonID; if ( m_Page >= 900 ) m_Page = 2; else if ( m_Page > 2 ) m_Page = 1; else m_Page = info.ButtonID; m_Mobile.SendGump( new LearnScalesGump( m_Mobile, m_Book, m_Page ) ); } else m_Mobile.SendSound( 0x55 ); } } public override void OnDoubleClick( Mobile e ) { if ( !IsChildOf( e.Backpack ) && this.Weight != -50.0 ) { e.SendMessage( "This must be in your backpack to read." ); } else { e.CloseGump( typeof( LearnScalesGump ) ); e.SendGump( new LearnScalesGump( e, this, 1 ) ); Server.Gumps.MyLibrary.readBook ( this, e ); } } public LearnScalesBook(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(); if ( ItemID == 0x02DD || ItemID == 0x201A ) { ItemID = RandomThings.GetRandomBookItemID(); Hue = Utility.RandomColor(0); Name = "Reptile Scale Crafts"; } } } }
0
0.863771
1
0.863771
game-dev
MEDIA
0.969831
game-dev
0.880047
1
0.880047
moai/moai-dev
1,752
src/moai-sim/MOAIAnimCurveVec.h
// Copyright (c) 2010-2017 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #ifndef MOAIANIMCURVEVEC_H #define MOAIANIMCURVEVEC_H #include <moai-sim/MOAIAnimCurveBase.h> #include <moai-sim/MOAINode.h> //================================================================// // MOAIAnimCurveVec //================================================================// /** @lua MOAIAnimCurveVec @text Implementation of animation curve for 3D vector values. */ class MOAIAnimCurveVec : public virtual MOAIAnimCurveBase { private: ZLLeanArray < ZLVec3D > mSamples; ZLVec3D mValue; //----------------------------------------------------------------// static int _getValueAtTime ( lua_State* L ); static int _setKey ( lua_State* L ); //----------------------------------------------------------------// ZLVec3D GetCurveDelta () const; ZLVec3D GetValue ( const MOAIAnimKeySpan& span ) const; //----------------------------------------------------------------// void MOAINode_Update (); public: DECL_LUA_FACTORY ( MOAIAnimCurveVec ) //----------------------------------------------------------------// void ApplyValueAttrOp ( MOAIAttribute& attr, u32 op ); void GetDelta ( MOAIAttribute& attr, const MOAIAnimKeySpan& span0, const MOAIAnimKeySpan& span1 ) const; ZLVec3D GetValue ( float time ) const; void GetValue ( MOAIAttribute& attr, const MOAIAnimKeySpan& span ) const; void GetZero ( MOAIAttribute& attr ) const; MOAIAnimCurveVec (); ~MOAIAnimCurveVec (); void RegisterLuaClass ( MOAILuaState& state ); void RegisterLuaFuncs ( MOAILuaState& state ); void ReserveSamples ( u32 total ); void SetSample ( u32 id, const ZLVec3D& value ); }; #endif
0
0.888446
1
0.888446
game-dev
MEDIA
0.4956
game-dev
0.739556
1
0.739556
BLeeEZ/amperfy
2,779
AmperfyKit/Player/PlayerDownloadPreparationHandler.swift
// // PlayerDownloadPreparationHandler.swift // AmperfyKit // // Created by Maximilian Bauer on 25.11.21. // Copyright (c) 2021 Maximilian Bauer. All rights reserved. // // 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/>. // import Foundation // MARK: - PlayerDownloadPreparationHandler @MainActor class PlayerDownloadPreparationHandler { static let preDownloadCount = 3 private var playerStatus: PlayerStatusPersistent private var queueHandler: PlayQueueHandler private var playableDownloadManager: DownloadManageable init( playerStatus: PlayerStatusPersistent, queueHandler: PlayQueueHandler, playableDownloadManager: DownloadManageable ) { self.playerStatus = playerStatus self.queueHandler = queueHandler self.playableDownloadManager = playableDownloadManager } private func preDownloadNextItems() { let upcomingItemsCount = min( queueHandler.userQueueCount + queueHandler.nextQueueCount, Self.preDownloadCount ) guard upcomingItemsCount > 0 else { return } let userQueueRangeEnd = min(queueHandler.userQueueCount, Self.preDownloadCount) if userQueueRangeEnd > 0 { for i in 0 ... userQueueRangeEnd - 1 { let playable = queueHandler.getUserQueueItem(at: i)! if !playable.isCached, !playable.isRadio { playableDownloadManager.download(object: playable) } } } let nextQueueRangeEnd = min( queueHandler.nextQueueCount, Self.preDownloadCount - userQueueRangeEnd ) if nextQueueRangeEnd > 0 { for i in 0 ... nextQueueRangeEnd - 1 { let playable = queueHandler.getNextQueueItem(at: i)! if !playable.isCached, !playable.isRadio { playableDownloadManager.download(object: playable) } } } } } // MARK: MusicPlayable extension PlayerDownloadPreparationHandler: MusicPlayable { func didStartPlayingFromBeginning() { if playerStatus.isAutoCachePlayedItems { preDownloadNextItems() } } func didStartPlaying() {} func didPause() {} func didStopPlaying() {} func didElapsedTimeChange() {} func didPlaylistChange() {} func didArtworkChange() {} }
0
0.87013
1
0.87013
game-dev
MEDIA
0.252088
game-dev
0.804466
1
0.804466
GreengageDB/greengage
2,159
src/backend/gporca/libnaucrates/include/naucrates/dxl/operators/CDXLPhysicalGatherMotion.h
//--------------------------------------------------------------------------- // Greengage Database // Copyright (C) 2010 Greenplum, Inc. // // @filename: // CDXLPhysicalGatherMotion.h // // @doc: // Class for representing DXL Gather motion operators. //--------------------------------------------------------------------------- #ifndef GPDXL_CDXLPhysicalGatherMotion_H #define GPDXL_CDXLPhysicalGatherMotion_H #include "gpos/base.h" #include "naucrates/dxl/operators/CDXLPhysicalMotion.h" namespace gpdxl { // indices of gather motion elements in the children array enum Edxlgm { EdxlgmIndexProjList = 0, EdxlgmIndexFilter, EdxlgmIndexSortColList, EdxlgmIndexChild, EdxlgmIndexSentinel }; //--------------------------------------------------------------------------- // @class: // CDXLPhysicalGatherMotion // // @doc: // Class for representing DXL gather motion operators // //--------------------------------------------------------------------------- class CDXLPhysicalGatherMotion : public CDXLPhysicalMotion { private: // private copy ctor CDXLPhysicalGatherMotion(const CDXLPhysicalGatherMotion &); public: // ctor/dtor CDXLPhysicalGatherMotion(CMemoryPool *mp); virtual ~CDXLPhysicalGatherMotion(){}; // accessors Edxlopid GetDXLOperator() const; const CWStringConst *GetOpNameStr() const; INT IOutputSegIdx() const; // index of relational child node in the children array virtual ULONG GetRelationChildIdx() const { return EdxlgmIndexChild; } // serialize operator in DXL format virtual void SerializeToDXL(CXMLSerializer *xml_serializer, const CDXLNode *node) const; // conversion function static CDXLPhysicalGatherMotion * Cast(CDXLOperator *dxl_op) { GPOS_ASSERT(NULL != dxl_op); GPOS_ASSERT(EdxlopPhysicalMotionGather == dxl_op->GetDXLOperator()); return dynamic_cast<CDXLPhysicalGatherMotion *>(dxl_op); } #ifdef GPOS_DEBUG // checks whether the operator has valid structure, i.e. number and // types of child nodes void AssertValid(const CDXLNode *, BOOL validate_children) const; #endif // GPOS_DEBUG }; } // namespace gpdxl #endif // !GPDXL_CDXLPhysicalGatherMotion_H // EOF
0
0.535197
1
0.535197
game-dev
MEDIA
0.240602
game-dev
0.775903
1
0.775903
LudiKha/Graphene
1,861
src/Core/Scripts/Model/Form.cs
 using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace Graphene { public interface IModel { void Initialize(VisualElement container, Plate plate); bool Render { get; } System.Action onModelChange { get; set; } void Refresh(VisualElement container); } /// <summary> /// Instructs the <see cref="Renderer"/> to use a custom <see cref="BindAttribute"/> context /// </summary> public interface ICustomBindContext { public object GetCustomBindContext { get; } } /// <summary> /// Instructs the <see cref="Renderer"/> to use a custom <see cref="DrawAttribute"/> context /// </summary> public interface ICustomDrawContext { public object GetCustomDrawContext { get; } } public interface IForm { [Bind("Title")] string Title { get; } void OnSubmit(); void OnCancel(); } public abstract class Form : ScriptableObject, IModel { [field: SerializeField][Bind("Title")] public string Title { get; set; } = "Title"; [field: SerializeField][Bind("Render")] public bool Render { get; set; } = true; public Action onModelChange { get; set; } public event System.Action Redraw; //public abstract List<object> GetDrawableObjects() { } public abstract void Initialize(VisualElement container, Plate plate); public void Refresh(VisualElement container) { } #region ButtonAttribute #if ODIN_INSPECTOR [Sirenix.OdinInspector.Button] #elif NAUGHTY_ATTRIBUTES [NaughtyAttributes.Button] #endif #endregion internal void ForceRedraw() { Redraw?.Invoke(); } //public abstract void Render(UnityEngine.UIElements.VisualElement container, UIControlsTemplates templates); //[Button] //public abstract void OnSubmit(); //[Button] //public abstract void OnCancel(); } }
0
0.861823
1
0.861823
game-dev
MEDIA
0.891996
game-dev
0.752034
1
0.752034
AionGermany/aion-germany
3,556
AL-Game-5.8/data/scripts/system/handlers/quest/cygnea/_15020LaFinDeBlackFinTribe.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package quest.cygnea; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /** * @author pralinka */ public class _15020LaFinDeBlackFinTribe extends QuestHandler { public static final int questId = 15020; public _15020LaFinDeBlackFinTribe() { super(questId); } @Override public void register() { qe.registerQuestNpc(804876).addOnQuestStart(questId); qe.registerQuestNpc(804876).addOnTalkEvent(questId); qe.registerQuestNpc(235826).addOnKillEvent(questId); qe.registerQuestNpc(235827).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) { int var = qs.getQuestVarById(0); if (var == 0) { int targetId = env.getTargetId(); int var1 = qs.getQuestVarById(1); int var2 = qs.getQuestVarById(2); switch (targetId) { case 235826: { if (var1 < 4) { return defaultOnKillEvent(env, 235826, 0, 4, 1); } else if (var1 == 4) { if (var2 == 5) { qs.setQuestVar(1); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return true; } else { return defaultOnKillEvent(env, 235826, 4, 5, 1); } } break; } case 235827: { if (var2 < 4) { return defaultOnKillEvent(env, 235827, 0, 4, 2); } else if (var2 == 4) { if (var1 == 5) { qs.setQuestVar(1); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return true; } else { return defaultOnKillEvent(env, 235827, 4, 5, 2); } } break; } } } } return false; } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); int targetId = env.getTargetId(); DialogAction dialog = env.getDialog(); if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 804876) { if (dialog == DialogAction.QUEST_SELECT) { return sendQuestDialog(env, 4762); } else { return sendQuestStartDialog(env); } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 804876) { if (dialog == DialogAction.QUEST_SELECT) { return sendQuestDialog(env, 2034); } else { return sendQuestEndDialog(env); } } } return false; } }
0
0.92181
1
0.92181
game-dev
MEDIA
0.969374
game-dev
0.970936
1
0.970936
PotRooms/StarResonanceData
22,068
lua/ui/view/mod_intensify_window_view.lua
local UI = Z.UI local super = require("ui.ui_view_base") local mod_intensify_window_view = class("mod_intensify_window_view", super) local MOD_DEFINE = require("ui.model.mod_define") local modCardAllTplItem = require("ui.component.mod.mod_card_all_tpl_item") local loopListView_ = require("ui/component/loop_list_view") local loopGridView_ = require("ui/component/loop_grid_view") local modItemLongItem = require("ui.component.mod.mod_item_long_item") local modEntryListTplItem = require("ui.component.mod.mod_entry_list_tpl_item") local common_filter_helper = require("common.common_filter_helper") function mod_intensify_window_view:ctor() self.uiBinder = nil super.ctor(self, "mod_intensify_window") self.commonVM_ = Z.VMMgr.GetVM("common") self.modData_ = Z.DataMgr.Get("mod_data") self.modVM_ = Z.VMMgr.GetVM("mod") self.itemsVM_ = Z.VMMgr.GetVM("items") self.itemSortFactoryVm_ = Z.VMMgr.GetVM("item_sort_factory") self.weaponVm_ = Z.VMMgr.GetVM("weapon") self.gotoFuncVM_ = Z.VMMgr.GetVM("gotofunc") self.itemClass_ = {} self.filterHelper_ = common_filter_helper.new(self) end function mod_intensify_window_view:OnActive() Z.UnrealSceneMgr:InitSceneCamera() Z.UIMgr:SetUIViewInputIgnore(self.viewConfigKey, 4294967295, true) self:AddClick(self.uiBinder.btn_ask, function() Z.VMMgr.GetVM("helpsys").OpenFullScreenTipsView(400003) end) self:AddClick(self.uiBinder.btn_close, function() Z.UIMgr:CloseView("mod_intensify_window") end) self:AddClick(self.uiBinder.btn_preview, function() self.modVM_.EnterModView() end) self:AddClick(self.uiBinder.btn_cancel, function() self:clearSelectItem() self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshDecompose() end) self:AddClick(self.uiBinder.btn_filter, function() local viewData = { filterRes = self.modData_.ModFilter } self.filterHelper_:ActiveFilterSub(viewData) end) self:AddClick(self.uiBinder.btn_recommend, function() local popViewData = { func = function(data) self.modData_.ModFilter[E.CommonFilterType.ModEffectSelect] = self.filterHelper_.filterSubView_.initFilterTypeData_3() for _, value in pairs(data) do self.modData_.ModFilter[E.CommonFilterType.ModEffectSelect].value[value] = value self.modData_.ModFilter[E.CommonFilterType.ModEffectSelect].param[2][value] = value end local viewData = { filterRes = self.modData_.ModFilter, filterFunc = function(filterRes) self:onSelectFilter(filterRes) end } self.filterHelper_:ActiveFilterSub(viewData) end } Z.UIMgr:OpenView("mod_term_recommend_popup", popViewData) end) self:AddAsyncClick(self.uiBinder.btn_confirm, function() self:confirmDecompose() end) self:AddAsyncClick(self.uiBinder.btn_oneclick_addition, function() self:selectAllBlueMod() end) self.uiBinder.group_tab_item_1.tog_tab_select:AddListener(function(isOn) if isOn then self:selectIntensityType(MOD_DEFINE.ModIntensifyType.Intensify, self.viewData.uuid) end end) self.uiBinder.group_tab_item_2.tog_tab_select:AddListener(function(isOn) if isOn then self:selectIntensityType(MOD_DEFINE.ModIntensifyType.Decompose) end end) if Z.IsPCUI then self.itemListView_ = loopListView_.new(self, self.uiBinder.loop_item, modEntryListTplItem, "mod_entry_list_tpl_pc") else self.itemListView_ = loopListView_.new(self, self.uiBinder.loop_item, modEntryListTplItem, "mod_entry_list_tpl") end self.itemListView_:Init({}) if Z.IsPCUI then self.itemsModDecomposeGridView_ = loopGridView_.new(self, self.uiBinder.loop_decompose_mod, modItemLongItem, "com_item_long_2_pc") else self.itemsModDecomposeGridView_ = loopGridView_.new(self, self.uiBinder.loop_decompose_mod, modItemLongItem, "com_item_long_2") end self.itemsModDecomposeGridView_:Init({}) if Z.IsPCUI then self.itemsDecomposeListView_ = loopListView_.new(self, self.uiBinder.loop_decompose_item, modItemLongItem, "com_item_square_8_pc") else self.itemsDecomposeListView_ = loopListView_.new(self, self.uiBinder.loop_decompose_item, modItemLongItem, "com_item_square_8") end self.itemsDecomposeListView_:Init({}) local filterTypes = { E.CommonFilterType.ModType, E.CommonFilterType.ModQuality, E.CommonFilterType.ModEffectSelect } self.filterHelper_:Init(Lang("ModFilterTitle"), filterTypes, self.uiBinder.node_filter, self.uiBinder.node_filter_s, function(filterRes) self:onSelectFilter(filterRes) end) self.filterHelper_:ActiveEliminateSub(self.modData_.ModFilter) self.isUp_ = true self.isInIntensify_ = false self.filterTags_ = true self.IntensifyEffectId = nil self.IntensifyEffects = {} Z.EventMgr:Add(Z.ConstValue.Mod.OnModIntensify, self.refreshModIntensify, self) Z.EventMgr:Add(Z.ConstValue.Mod.OnModDecompose, self.refreshModDecompose, self) end function mod_intensify_window_view:OnDeActive() Z.EventMgr:Remove(Z.ConstValue.Mod.OnModIntensify, self.refreshModIntensify, self) Z.EventMgr:Remove(Z.ConstValue.Mod.OnModDecompose, self.refreshModDecompose, self) Z.UIMgr:SetUIViewInputIgnore(self.viewConfigKey, 4294967295, false) self.itemListView_:UnInit() self.itemListView_ = nil self.itemsModDecomposeGridView_:UnInit() self.itemsModDecomposeGridView_ = nil self.itemsDecomposeListView_:UnInit() self.itemsDecomposeListView_ = nil for _, itemClass in pairs(self.itemClass_) do itemClass:UnInit() end self.itemClass_ = {} self.intensityType_ = nil self.filterHelper_:DeActive() self.filterTags_ = true Z.CommonTipsVM.CloseTipsContent() if Z.UIMgr:IsActive("mod_item_popup") then Z.UIMgr:CloseView("mod_item_popup") end self:closeSourceTip() self.IntensifyEffectId = nil self:clearIntensifyEffects() end function mod_intensify_window_view:OnRefresh() local intensifyIsOn = self.gotoFuncVM_.CheckFuncCanUse(E.FunctionID.ModIntensify, true) local decomposeIsOn = self.gotoFuncVM_.CheckFuncCanUse(E.FunctionID.ModDecompose, true) self.uiBinder.group_tab_item_1.Ref.UIComp:SetVisible(intensifyIsOn) self.uiBinder.group_tab_item_2.Ref.UIComp:SetVisible(decomposeIsOn) local intensifyType if self.viewData and self.viewData.intensifyType then if MOD_DEFINE.ModIntensifyType.Intensify == self.viewData.intensifyType then if intensifyIsOn then intensifyType = MOD_DEFINE.ModIntensifyType.Intensify else intensifyType = MOD_DEFINE.ModIntensifyType.Decompose end elseif MOD_DEFINE.ModIntensifyType.Decompose == self.viewData.intensifyType then if decomposeIsOn then intensifyType = MOD_DEFINE.ModIntensifyType.Decompose else intensifyType = MOD_DEFINE.ModIntensifyType.Intensify end end end if intensifyType then if intensifyType == MOD_DEFINE.ModIntensifyType.Intensify then if self.uiBinder.group_tab_item_1.tog_tab_select.isOn then self:selectIntensityType(MOD_DEFINE.ModIntensifyType.Intensify, self.viewData.uuid) else self.uiBinder.group_tab_item_1.tog_tab_select.isOn = true end elseif intensifyType == MOD_DEFINE.ModIntensifyType.Decompose then if self.uiBinder.group_tab_item_2.tog_tab_select.isOn then self:selectIntensityType(MOD_DEFINE.ModIntensifyType.Decompose, self.viewData.uuid) else self.uiBinder.group_tab_item_2.tog_tab_select.isOn = true end end elseif self.uiBinder.group_tab_item_1.tog_tab_select.isOn then self:selectIntensityType(MOD_DEFINE.ModIntensifyType.Intensify) elseif self.uiBinder.group_tab_item_2.tog_tab_select.isOn then self:selectIntensityType(MOD_DEFINE.ModIntensifyType.Decompose) end end function mod_intensify_window_view:OnDestory() Z.UnrealSceneMgr:CloseUnrealScene(self.ViewConfigKey) end function mod_intensify_window_view:refreshModIntensify(effectId) self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshIntensify(effectId) end function mod_intensify_window_view:refreshModDecompose() self:clearSelectItem() self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshDecompose() end function mod_intensify_window_view:refreshModLoops() local modConfigMgr = Z.TableMgr.GetTable("ModTableMgr") local sortType = E.EquipItemSortType.Quality local sortFunc = self.itemSortFactoryVm_.GetItemSortFunc(E.BackPackItemPackageType.Mod, { sortType = sortType, 1, isUp = self.isUp_ }) self.modItems_ = self.itemsVM_.GetItemIds(E.BackPackItemPackageType.Mod, nil, sortFunc, true) if #self.modItems_ > 0 then if self.intensityType_ == MOD_DEFINE.ModIntensifyType.Intensify and self.selectUuids_[1] == nil then self.selectUuids_[1] = self.modItems_[1].itemUuid end self.modLoopItems_ = {} local awardIndex = 0 for _, itemInfo in pairs(self.modItems_) do local isSelect = false local isShow = false if self.intensityType_ == MOD_DEFINE.ModIntensifyType.Decompose then if self.selectUuids_[itemInfo.itemUuid] then isSelect = true end isShow = true else local modConfig = modConfigMgr.GetRow(itemInfo.configId) if modConfig and modConfig.IsCanLink then isShow = true end end if isShow then awardIndex = awardIndex + 1 self.modLoopItems_[awardIndex] = { configId = itemInfo.configId, uuid = itemInfo.itemUuid, isSelected = isSelect } end end self.itemListView_:RefreshListView(self.modLoopItems_) self.uiBinder.Ref:SetVisible(self.uiBinder.node_empty, false) else self.selectUuids_ = {} self.modLoopItems_ = {} self.itemListView_:RefreshListView({}) self.uiBinder.Ref:SetVisible(self.uiBinder.node_empty, self.intensityType_ == MOD_DEFINE.ModIntensifyType.Intensify) end end function mod_intensify_window_view:selectIntensityType(type, uuid) if self.intensityType_ == type then return end self.intensityType_ = type self:clearSelectItem() if uuid then self.selectUuids_[1] = uuid self.viewData.uuid = nil end if self.intensityType_ == MOD_DEFINE.ModIntensifyType.Intensify then self.uiBinder.Ref:SetVisible(self.uiBinder.group_card, true) self.uiBinder.Ref:SetVisible(self.uiBinder.group_decompose, false) self.commonVM_.CommonPlayTogAnim(self.uiBinder.group_tab_item_1.anim_tog, self.cancelSource:CreateToken()) self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshIntensify() self.uiBinder.lab_empty_name.text = Lang("Mod_None_Reinforced_Tips") local commonVM = Z.VMMgr.GetVM("common") commonVM.SetLabText(self.uiBinder.lab_title, E.FunctionID.ModIntensify) elseif self.intensityType_ == MOD_DEFINE.ModIntensifyType.Decompose then self.uiBinder.Ref:SetVisible(self.uiBinder.group_card, false) self.uiBinder.Ref:SetVisible(self.uiBinder.group_decompose, true) self.commonVM_.CommonPlayTogAnim(self.uiBinder.group_tab_item_2.anim_tog, self.cancelSource:CreateToken()) self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshDecompose() self.uiBinder.lab_empty_name.text = Lang("NoDecomposableItems") local commonVM = Z.VMMgr.GetVM("common") commonVM.SetLabText(self.uiBinder.lab_title, E.FunctionID.ModDecompose) end self.uiBinder.anim:Play(Z.DOTweenAnimType.Open) self.uiBinder.anim:Restart(Z.DOTweenAnimType.Open) end function mod_intensify_window_view:clearSelectItem() self.selectUuids_ = {} end function mod_intensify_window_view:clearIntensifyEffects() for _, effect in ipairs(self.IntensifyEffects) do self.uiBinder.Ref.UIComp.UIDepth:RemoveChildDepth(effect) effect:ReleseEffGo() end self.IntensifyEffects = {} end function mod_intensify_window_view:refreshIntensify(effectId) self.IntensifyEffectId = effectId self:clearIntensifyEffects() for _, itemClass in pairs(self.itemClass_) do itemClass:UnInit() end self.itemClass_ = {} self.uiBinder.Ref:SetVisible(self.uiBinder.rect_bottom, false) self.uiBinder.lab_mod_intensifytitle.text = "" if self.selectUuids_[1] then self.modData_:SetIntensifyModUuid(self.selectUuids_[1]) self.uiBinder.Ref:SetVisible(self.uiBinder.group_card, true) local unitPath = self.uiBinder.prefab_cash:GetString("mod_card_all_tpl") self.uiBinder.Ref:SetVisible(self.uiBinder.rect_bottom, true) local itemInfo = self.itemsVM_.GetItemInfo(self.selectUuids_[1], E.BackPackItemPackageType.Mod) local itemConfig = Z.TableMgr.GetTable("ItemTableMgr").GetRow(itemInfo.configId) if itemConfig then self.uiBinder.lab_mod_intensifytitle.text = self.itemsVM_.ApplyItemNameWithQualityTag(itemInfo.configId) end if itemInfo and itemInfo.modNewAttr then local allIntensify = true for i = 1, MOD_DEFINE.ModEffectMaxCount do local unit = self.uiBinder["mod_card_all_tpl_" .. i] local attr = itemInfo.modNewAttr.modParts[i] if attr then local logs = {} local logsIndex = 0 if Z.ContainerMgr.CharSerialize.mod and Z.ContainerMgr.CharSerialize.mod.modInfos and Z.ContainerMgr.CharSerialize.mod.modInfos[self.selectUuids_[1]] then local modInfo = Z.ContainerMgr.CharSerialize.mod.modInfos[self.selectUuids_[1]] for _, upgrade in ipairs(modInfo.upgradeRecords) do if upgrade.partId == attr then logsIndex = logsIndex + 1 logs[logsIndex] = upgrade.isSuccess end end end if unit then local itemClass, tempIntensify = modCardAllTplItem.RefreshTpl(unit, attr, logs, self.selectUuids_[1], self, false) table.insert(self.itemClass_, itemClass) allIntensify = allIntensify and tempIntensify end elseif unit then modCardAllTplItem.RefreshTpl(unit, nil, nil, nil, nil, true) end end end else self.modData_:SetIntensifyModUuid(nil) self.uiBinder.Ref:SetVisible(self.uiBinder.group_card, false) end end function mod_intensify_window_view:refreshDecompose() self.modData_:SetIntensifyModUuid(nil) local selectUuids = {} local index = 1 for _, uuid in pairs(self.selectUuids_) do local itemInfo = self.itemsVM_.GetItemInfo(uuid, E.BackPackItemPackageType.Mod) selectUuids[index] = { type = modItemLongItem.Type.ModResolve, uuid = uuid, configId = itemInfo.configId } index = index + 1 end self.itemsModDecomposeGridView_:RefreshListView(selectUuids) local awards = {} local awardIndex = 0 local decomposeItem = self.modVM_.GetModDecompose(selectUuids) local awardPreviewVm = Z.VMMgr.GetVM("awardpreview") for _, item in pairs(decomposeItem) do awardIndex = awardIndex + 1 local labType, lab = awardPreviewVm.GetPreviewShowNum(item) awards[awardIndex] = { type = modItemLongItem.Type.DecomposeItem, configId = item.awardId, isSelected = false, prevDropType = item.PrevDropType, count = item.awardNum, labType = labType, lab = item.PrevDropType == E.AwardPrevDropType.Probability and "" or lab } end self.itemsDecomposeListView_:RefreshListView(awards) if 1 < index then self.uiBinder.Ref:SetVisible(self.uiBinder.node_empty_decompose, false) else self.uiBinder.Ref:SetVisible(self.uiBinder.node_empty_decompose, true) if 0 < #self.modLoopItems_ then self.uiBinder.lab_empty_decompose.text = Lang("PleaseSelectItemWantDecomposeItemLeft") else self.uiBinder.lab_empty_decompose.text = Lang("NoDecomposableItems") end end self.uiBinder.btn_cancel.IsDisabled = index == 1 self.uiBinder.btn_confirm.IsDisabled = index == 1 end function mod_intensify_window_view:SetSelectUuid(uuid) if self.intensityType_ == MOD_DEFINE.ModIntensifyType.Intensify then self.selectUuids_[1] = uuid self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshIntensify() else if self.modVM_.IsModEquip(uuid) then Z.TipsVM.ShowTipsLang(1042107) return end if self.selectUuids_[uuid] then self.selectUuids_[uuid] = nil else self.selectUuids_[uuid] = uuid end self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshDecompose() end end function mod_intensify_window_view:selectAllBlueMod() local tempCount = 0 local mgr = Z.TableMgr.GetTable("ItemTableMgr") for _, item in ipairs(self.modLoopItems_) do local itemConfig = mgr.GetRow(item.configId) if itemConfig.Quality == E.ItemQuality.Blue and not self.modVM_.IsModEquip(item.uuid) then self.selectUuids_[item.uuid] = item.uuid tempCount = tempCount + 1 end end if tempCount == 0 then Z.TipsVM.ShowTipsLang(1042114) else self:refreshModLoops() self:refreshModListLoopByFilter() self:refreshDecompose() end end function mod_intensify_window_view:onSelectFilter(filterRes) self.modData_.ModFilter = filterRes self.filterTags_ = true self:refreshModListLoopByFilter() end function mod_intensify_window_view:refreshModListLoopByFilter() if self.filterTags_ then local selectNeedReset = false if self.intensityType_ == MOD_DEFINE.ModIntensifyType.Intensify then selectNeedReset = true end local tempmodLoopItems = {} local tempmodLoopItemsIndex = 0 for _, item in ipairs(self.modLoopItems_) do local modConfig = Z.TableMgr.GetTable("ModTableMgr").GetRow(item.configId) local itemConfig = Z.TableMgr.GetTable("ItemTableMgr").GetRow(item.configId) local byFiltering = true local tempFilterRes = {} local effectValueCount = 0 if self.modData_.ModFilter[E.CommonFilterType.ModEffectSelect] and self.modData_.ModFilter[E.CommonFilterType.ModEffectSelect].value then effectValueCount = table.zcount(self.modData_.ModFilter[E.CommonFilterType.ModEffectSelect].value) end for type, data in pairs(self.modData_.ModFilter) do tempFilterRes[type] = true if type == E.CommonFilterType.ModType then tempFilterRes[type] = false if data.value[modConfig.ModType] then tempFilterRes[type] = true end end if type == E.CommonFilterType.ModQuality then tempFilterRes[type] = false if data.value[itemConfig.Quality] then tempFilterRes[type] = true end end if type == E.CommonFilterType.ModEffectSelect and 0 < effectValueCount then local itemInfo = self.itemsVM_.GetItemInfo(item.uuid, E.BackPackItemPackageType.Mod) tempFilterRes[type] = false local needCount = 1 if data.param and data.param[1] then needCount = data.param[1] end local tempCount = 0 for _, attr in ipairs(itemInfo.modNewAttr.modParts) do if data.value[attr] then tempCount = tempCount + 1 end end tempFilterRes[type] = needCount <= tempCount end end for _, res in pairs(tempFilterRes) do byFiltering = byFiltering and res end if byFiltering then tempmodLoopItemsIndex = tempmodLoopItemsIndex + 1 tempmodLoopItems[tempmodLoopItemsIndex] = item if selectNeedReset and item.uuid == self.selectUuids_[1] then selectNeedReset = false end end end if selectNeedReset then if tempmodLoopItems[1] and tempmodLoopItems[1].uuid then self.selectUuids_[1] = tempmodLoopItems[1].uuid for _, item in ipairs(tempmodLoopItems) do item.isSelected = self.selectUuids_[1] == item.uuid end else self.selectUuids_ = {} end self:refreshIntensify() elseif self.intensityType_ == MOD_DEFINE.ModIntensifyType.Intensify then for _, item in ipairs(tempmodLoopItems) do item.isSelected = self.selectUuids_[1] == item.uuid end elseif self.intensityType_ == MOD_DEFINE.ModIntensifyType.Decompose then for _, item in ipairs(tempmodLoopItems) do item.isSelected = self.selectUuids_[item.uuid] ~= nil end end self.itemListView_:RefreshListView(tempmodLoopItems) else if self.intensityType_ == MOD_DEFINE.ModIntensifyType.Intensify then for _, item in ipairs(self.modLoopItems_) do item.isSelected = self.selectUuids_[1] == item.uuid end end self.itemListView_:RefreshListView(self.modLoopItems_) end end function mod_intensify_window_view:confirmDecompose() local highQualityMod = false local uuids = {} local count = 1 for _, uuid in pairs(self.selectUuids_) do uuids[count] = uuid count = count + 1 local modInfo = self.itemsVM_.GetItemInfo(uuid, E.BackPackItemPackageType.Mod) local modConfig = Z.TableMgr.GetTable("ItemTableMgr").GetRow(modInfo.configId) if modConfig.Quality >= E.ItemQuality.Purple then highQualityMod = true end end if #uuids == 0 then return end local hightQualityCertainFunc = function() local confirmFunc = function() self.modVM_.AsyncDecomposeMods(uuids, self.cancelSource:CreateToken()) end Z.DialogViewDataMgr:CheckAndOpenPreferencesDialog(Lang("ModDecomposeCertain"), confirmFunc, nil, E.DlgPreferencesType.Login, E.DlgPreferencesKeyType.ModDecomposeCertain) end if highQualityMod then Z.DialogViewDataMgr:OpenNormalDialog(Lang("ModDecomposeHighQualityCertain"), function() hightQualityCertainFunc() end) else hightQualityCertainFunc() end end function mod_intensify_window_view:closeSourceTip() if self.sourceTipId_ then Z.TipsVM.CloseItemTipsView(self.sourceTipId_) self.sourceTipId_ = nil end end function mod_intensify_window_view:openNotEnoughItemTips(itemId, rect) self:closeSourceTip() self.sourceTipId_ = Z.TipsVM.OpenSourceTips(itemId, rect) end return mod_intensify_window_view
0
0.942653
1
0.942653
game-dev
MEDIA
0.701369
game-dev,desktop-app
0.984769
1
0.984769
MJRLegends/ExtraPlanets
6,934
src/main/java/com/mjr/extraplanets/planets/Saturn/worldgen/village/StructureComponentVillageField2.java
package com.mjr.extraplanets.planets.Saturn.worldgen.village; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraft.world.gen.structure.StructureBoundingBox; import net.minecraft.world.gen.structure.StructureComponent; import net.minecraft.world.gen.structure.template.TemplateManager; public class StructureComponentVillageField2 extends StructureComponentVillage { private int averageGroundLevel = -1; private Block cropTypeA; private Block cropTypeB; private Block cropTypeC; private Block cropTypeD; public StructureComponentVillageField2() { } public StructureComponentVillageField2(StructureComponentVillageStartPiece par1ComponentVillageStartPiece, int par2, Random par3Random, StructureBoundingBox par4StructureBoundingBox, EnumFacing par5) { super(par1ComponentVillageStartPiece, par2); this.setCoordBaseMode(par5); this.boundingBox = par4StructureBoundingBox; this.cropTypeA = this.getRandomCrop(par3Random); this.cropTypeB = this.getRandomCrop(par3Random); this.cropTypeC = this.getRandomCrop(par3Random); this.cropTypeD = this.getRandomCrop(par3Random); } @Override protected void writeStructureToNBT(NBTTagCompound nbt) { super.writeStructureToNBT(nbt); nbt.setInteger("AvgGroundLevel", this.averageGroundLevel); nbt.setInteger("CropTypeA", Block.getIdFromBlock(this.cropTypeA)); nbt.setInteger("CropTypeB", Block.getIdFromBlock(this.cropTypeB)); nbt.setInteger("CropTypeC", Block.getIdFromBlock(this.cropTypeC)); nbt.setInteger("CropTypeD", Block.getIdFromBlock(this.cropTypeD)); } @Override protected void readStructureFromNBT(NBTTagCompound nbt, TemplateManager manager) { super.readStructureFromNBT(nbt, manager); this.averageGroundLevel = nbt.getInteger("AvgGroundLevel"); this.cropTypeA = Block.getBlockById(nbt.getInteger("CropTypeA")); this.cropTypeB = Block.getBlockById(nbt.getInteger("CropTypeB")); this.cropTypeC = Block.getBlockById(nbt.getInteger("CropTypeC")); this.cropTypeD = Block.getBlockById(nbt.getInteger("CropTypeD")); } private Block getRandomCrop(Random par1Random) { switch (par1Random.nextInt(5)) { case 0: return Blocks.CARROTS; case 1: return Blocks.POTATOES; default: return Blocks.WHEAT; } } public static StructureComponentVillageField2 func_74900_a(StructureComponentVillageStartPiece par0ComponentVillageStartPiece, List<StructureComponent> par1List, Random rand, int par3, int par4, int par5, EnumFacing par6, int par7) { final StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(par3, par4, par5, 0, 0, 0, 13, 4, 9, par6); return StructureComponentVillage.canVillageGoDeeper(structureboundingbox) && StructureComponent.findIntersecting(par1List, structureboundingbox) == null ? new StructureComponentVillageField2(par0ComponentVillageStartPiece, par7, rand, structureboundingbox, par6) : null; } /** * second Part of Structure generating, this for example places Spiderwebs, Mob Spawners, it closes Mineshafts at the end, it adds Fences... */ @Override public boolean addComponentParts(World par1World, Random rand, StructureBoundingBox par3StructureBoundingBox) { if (this.averageGroundLevel < 0) { this.averageGroundLevel = this.getAverageGroundLevel(par1World, par3StructureBoundingBox); if (this.averageGroundLevel < 0) { return true; } this.boundingBox.offset(0, this.averageGroundLevel - this.boundingBox.maxY + 4 - 1, 0); } this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 0, 12, 4, 8, Blocks.AIR.getDefaultState(), Blocks.AIR.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 1, 2, 0, 7, Blocks.FARMLAND.getDefaultState(), Blocks.FARMLAND.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 4, 0, 1, 5, 0, 7, Blocks.FARMLAND.getDefaultState(), Blocks.FARMLAND.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 7, 0, 1, 8, 0, 7, Blocks.FARMLAND.getDefaultState(), Blocks.FARMLAND.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 10, 0, 1, 11, 0, 7, Blocks.FARMLAND.getDefaultState(), Blocks.FARMLAND.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 0, 0, 0, 8, Blocks.LOG.getDefaultState(), Blocks.LOG.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 6, 0, 0, 6, 0, 8, Blocks.LOG.getDefaultState(), Blocks.LOG.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 12, 0, 0, 12, 0, 8, Blocks.LOG.getDefaultState(), Blocks.LOG.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 0, 11, 0, 0, Blocks.LOG.getDefaultState(), Blocks.LOG.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 8, 11, 0, 8, Blocks.LOG.getDefaultState(), Blocks.LOG.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 3, 0, 1, 3, 0, 7, Blocks.FLOWING_WATER.getDefaultState(), Blocks.FLOWING_WATER.getDefaultState(), false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 9, 0, 1, 9, 0, 7, Blocks.FLOWING_WATER.getDefaultState(), Blocks.FLOWING_WATER.getDefaultState(), false); int i; for (i = 1; i <= 7; ++i) { this.setBlockState(par1World, this.cropTypeA.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 1, 1, i, par3StructureBoundingBox); this.setBlockState(par1World, this.cropTypeA.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 2, 1, i, par3StructureBoundingBox); this.setBlockState(par1World, this.cropTypeB.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 4, 1, i, par3StructureBoundingBox); this.setBlockState(par1World, this.cropTypeB.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 5, 1, i, par3StructureBoundingBox); this.setBlockState(par1World, this.cropTypeC.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 7, 1, i, par3StructureBoundingBox); this.setBlockState(par1World, this.cropTypeC.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 8, 1, i, par3StructureBoundingBox); this.setBlockState(par1World, this.cropTypeD.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 10, 1, i, par3StructureBoundingBox); this.setBlockState(par1World, this.cropTypeD.getStateFromMeta(MathHelper.getInt(rand, 2, 7)), 11, 1, i, par3StructureBoundingBox); } for (i = 0; i < 9; ++i) { for (int j = 0; j < 13; ++j) { this.clearCurrentPositionBlocksUpwards(par1World, j, 4, i, par3StructureBoundingBox); this.replaceAirAndLiquidDownwards(par1World, Blocks.DIRT.getDefaultState(), j, -1, i, par3StructureBoundingBox); } } return true; } }
0
0.905337
1
0.905337
game-dev
MEDIA
0.934135
game-dev
0.912878
1
0.912878
TeamHypersomnia/Hypersomnia
1,532
src/game/cosmos/component_synchronizer.h
#pragma once #include "augs/templates/maybe_const.h" template <class, class> class component_synchronizer; template <class, class> class synchronizer_base; template <class H> void construct_pre_inference(H); class write_synchronized_component_access { template <class, class> friend class synchronizer_base; template <class, class> friend class component_synchronizer; template <class H> friend void construct_pre_inference(H); friend struct perform_transfer_impl; write_synchronized_component_access() {} }; template <class entity_handle_type, class component_type> class synchronizer_base { protected: /* A value of nullptr means that the entity has no such component. */ static constexpr bool is_const = is_handle_const_v<entity_handle_type>; using component_pointer = maybe_const_ptr_t<is_const, component_type>; const component_pointer component; const entity_handle_type handle; public: auto& get_raw_component(write_synchronized_component_access) const { return *component; } const auto& get_raw_component() const { return *component; } auto get_handle() const { return handle; } bool operator==(const std::nullptr_t) const { return component == nullptr; } bool operator!=(const std::nullptr_t) const { return component != nullptr; } explicit operator bool() const { return component != nullptr; } auto* operator->() const { return this; } synchronizer_base( const component_pointer c, const entity_handle_type& h ) : component(c), handle(h) {} };
0
0.971876
1
0.971876
game-dev
MEDIA
0.262021
game-dev
0.894488
1
0.894488
Holic75/KingmakerRebalance
19,871
CallOfTheWild/Classes/Eidolons/Protean.cs
using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints.Classes.Selection; using Kingmaker.Blueprints.Classes.Spells; using Kingmaker.Blueprints.Facts; using Kingmaker.Blueprints.Items.Ecnchantments; using Kingmaker.Blueprints.Items.Weapons; using Kingmaker.Blueprints.Root; using Kingmaker.Controllers; using Kingmaker.Designers.Mechanics.Buffs; using Kingmaker.Designers.Mechanics.Facts; using Kingmaker.ElementsSystem; using Kingmaker.EntitySystem.Stats; using Kingmaker.Enums; using Kingmaker.Enums.Damage; using Kingmaker.RuleSystem; using Kingmaker.RuleSystem.Rules; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Abilities.Blueprints; using Kingmaker.UnitLogic.Abilities.Components; using Kingmaker.UnitLogic.Abilities.Components.AreaEffects; using Kingmaker.UnitLogic.Abilities.Components.Base; using Kingmaker.UnitLogic.Abilities.Components.CasterCheckers; using Kingmaker.UnitLogic.ActivatableAbilities; using Kingmaker.UnitLogic.ActivatableAbilities.Restrictions; using Kingmaker.UnitLogic.Buffs.Blueprints; using Kingmaker.UnitLogic.Buffs.Components; using Kingmaker.UnitLogic.FactLogic; using Kingmaker.UnitLogic.Mechanics; using Kingmaker.UnitLogic.Mechanics.Actions; using Kingmaker.UnitLogic.Mechanics.Components; using Kingmaker.UnitLogic.Mechanics.Conditions; using Kingmaker.Utility; using Kingmaker.View; using Kingmaker.Visual.Animation.Kingmaker; using Kingmaker.Visual.CharacterSystem; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using UnityEngine; using static Kingmaker.UnitLogic.Commands.Base.UnitCommand; namespace CallOfTheWild { public partial class Eidolon { static void createProteanUnit() { var natural_armor2 = library.Get<BlueprintUnitFact>("45a52ce762f637f4c80cc741c91f58b7"); var tatzlwyrm = library.Get<BlueprintUnit>("4dd913232eaf3894890b2bfaabcd8282"); var protean_unit = library.CopyAndAdd<BlueprintUnit>("8a6986e17799d7d4b90f0c158b31c5b9", "ProteanEidolonUnit", ""); protean_unit.Color = tatzlwyrm.Color; protean_unit.Visual = tatzlwyrm.Visual; protean_unit.LocalizedName = protean_unit.LocalizedName.CreateCopy(); protean_unit.LocalizedName.String = Helpers.CreateString(protean_unit.name + ".Name", "Protean Eidolon"); protean_unit.Prefab = tatzlwyrm.Prefab; protean_unit.Alignment = Alignment.ChaoticNeutral; protean_unit.Strength = 12; protean_unit.Dexterity = 16; protean_unit.Constitution = 13; protean_unit.Intelligence = 7; protean_unit.Wisdom = 10; protean_unit.Charisma = 11; protean_unit.Speed = 20.Feet(); protean_unit.AddFacts = new BlueprintUnitFact[] { natural_armor2 }; // { natural_armor2, fx_feature }; protean_unit.Body = protean_unit.Body.CloneObject(); protean_unit.Body.EmptyHandWeapon = library.Get<BlueprintItemWeapon>("20375b5a0c9243d45966bd72c690ab74"); protean_unit.Body.PrimaryHand = library.Get<BlueprintItemWeapon>("a000716f88c969c499a535dadcf09286"); //bite 1d6 protean_unit.Body.SecondaryHand = null; protean_unit.Body.AdditionalLimbs = new BlueprintItemWeapon[0]; protean_unit.Body.AdditionalSecondaryLimbs = new BlueprintItemWeapon[] { library.Get<BlueprintItemWeapon>("b21cd5b03fbb0f542815580e66f85915") }; //tail 1d6 protean_unit.ReplaceComponent<AddClassLevels>(a => { a.Archetypes = new BlueprintArchetype[] { serpentine_archetype }; a.CharacterClass = eidolon_class; a.Skills = new StatType[] { StatType.SkillAthletics, StatType.SkillMobility, StatType.SkillStealth }; a.Selections = new SelectionEntry[0]; }); protean_unit.AddComponents(Helpers.Create<EidolonComponent>()); Helpers.SetField(protean_unit, "m_Portrait", Helpers.createPortrait("EidolonProteanProtrait", "Protean", "")); protean_eidolon = Helpers.CreateProgression("ProteanEidolonProgression", "Protean Eidolon", "Serpentine beings of pure chaos, proteans seek to reshape reality. Protean eidolons appreciate creative summoners who often rebuild their forms. Beyond that, protean eidolons are happy to work with their summoners for any purpose, though they are quick to remind their summoners that while they have a mutually beneficial relationship, they are not servants.", "", Helpers.GetIcon("403cf599412299a4f9d5d925c7b9fb33"), //magic fang FeatureGroup.AnimalCompanion, library.Get<BlueprintFeature>("126712ef923ab204983d6f107629c895").ComponentsArray ); protean_eidolon.IsClassFeature = true; protean_eidolon.ReapplyOnLevelUp = true; protean_eidolon.Classes = new BlueprintCharacterClass[] { Summoner.summoner_class }; protean_eidolon.AddComponent(Common.createPrerequisiteAlignment(Kingmaker.UnitLogic.Alignments.AlignmentMaskType.Chaotic | Kingmaker.UnitLogic.Alignments.AlignmentMaskType.TrueNeutral)); protean_eidolon.ReplaceComponent<AddPet>(a => a.Pet = protean_unit); Summoner.eidolon_selection.AllFeatures = Summoner.eidolon_selection.AllFeatures.AddToArray(protean_eidolon); addLesserEidolon(protean_eidolon); } static void fillProteanProgression() { var base_evolutions = Helpers.CreateFeature("ProteanEidolonBaseEvolutionsFeature", "", "", "", null, FeatureGroup.None, Helpers.Create<EvolutionMechanics.AddPermanentEvolution>(a => a.Feature = Evolutions.resistance[0]) ); base_evolutions.HideInCharacterSheetAndLevelUp = true; var feature1 = Helpers.CreateFeature("ProteanEidolonLevel1Feature", "Base Evolutions", "At 1st level, protean eidolons gain the bite, tail slap and resistance (acid) evolutions.", "", protean_eidolon.Icon, FeatureGroup.None, Helpers.Create<EvolutionMechanics.AddFakeEvolution>(a => a.Feature = Evolutions.bite), Helpers.Create<EvolutionMechanics.AddFakeEvolution>(a => a.Feature = Evolutions.tail_slap), Helpers.CreateAddFeatureOnClassLevel(base_evolutions, 32, Summoner.getSummonerArray(), before: true) ); var feature4 = Helpers.CreateFeature("ProteanEidolonLevel4Feature", "Resistance", "At 4th level, protean eidolons gain electricity resistance 10 and sonic resistance 10.", "", Helpers.GetIcon("21ffef7791ce73f468b6fca4d9371e8b"), //resist energy FeatureGroup.None, addTransferableFeatToEidolon("ProteanEidolonLevel4AddFeature", Common.createEnergyDR(10, DamageEnergyType.Electricity), Common.createEnergyDR(10, DamageEnergyType.Sonic)) ); var feature8 = Helpers.CreateFeature("ProteanEidolonLevel8Feature", "Constrict", "At 8th level, protean eidolons gain the constrict evolution.", "", Evolutions.constrict.Icon, FeatureGroup.None, Helpers.Create<EvolutionMechanics.AddPermanentEvolution>(a => a.Feature = Evolutions.constrict) ); var feature12 = Helpers.CreateFeature("ProteanEidolonLevel12Feature", "Damage Reduction", "At 12th level, protean eidolons gain DR 5/lawful. They also gain the blindsense and flight evolutions.", "", Helpers.GetIcon("9e1ad5d6f87d19e4d8883d63a6e35568"), //mage armor FeatureGroup.None, addTransferableFeatToEidolon("ProteanEidolonLevel12AddFeature", Common.createContextAlignmentDR(Helpers.CreateContextValue(AbilityRankType.Default), DamageAlignment.Lawful), Helpers.CreateContextRankConfig(baseValueType: ContextRankBaseValueType.FeatureList, progression: ContextRankProgression.MultiplyByModifier, stepLevel: 10, min: 5, featureList: new BlueprintFeature[] { Evolutions.damage_reduction } ), Common.createBuffDescriptorImmunity(SpellDescriptor.Sleep), Helpers.Create<RecalculateOnFactsChange>(r => r.CheckedFacts = new BlueprintUnitFact[] { Evolutions.damage_reduction }) ), Helpers.Create<EvolutionMechanics.AddPermanentEvolution>(a => a.Feature = Evolutions.blindsense), Helpers.Create<EvolutionMechanics.AddPermanentEvolution>(a => a.Feature = Evolutions.flight) ); var amorphous_anatomy = Helpers.CreateFeature("ProteanAmorphousFeature", "Amorphous Anatomy", "A protean’s vital organs shift and change shape and position constantly. This grants it a 50 % chance to ignore additional damage caused by critical hits and sneak attacks, and grants it immunity to polymorph effects(unless the protean is a willing target).A protean automatically recovers from physical blindness or deafness after 1 round by growing new sensory organs to replace those that were compromised.", "", Evolutions.amorphous.Icon, FeatureGroup.None, Common.createAddFortification(50), Common.createSpecificBuffImmunity(library.Get<BlueprintBuff>("0a52d8761bfd125429842103aed48b90")), //baleful polymorph Helpers.Create<ProteanBuffRemovalAfter1Round>() ); transferable_abilities.Add(amorphous_anatomy); var feature16 = Helpers.CreateFeature("ProteanEidolonLevel16Feature", "Immunity", "At 16th level, protean eidolons lose the resistance (acid) evolution and instead gain the immunity (acid) evolution. They also gain the amorphous anatomy ability.\n" + "Amorphous Anatomy: A protean’s vital organs shift and change shape and position constantly. This grants it a 50 % chance to ignore additional damage caused by critical hits and sneak attacks, and grants it immunity to polymorph effects (unless the protean is a willing target). A protean automatically recovers from physical blindness or deafness after 1 round by growing new sensory organs to replace those that were compromised.", "", Evolutions.amorphous.Icon, FeatureGroup.None, Helpers.Create<EvolutionMechanics.AddPermanentEvolution>(a => a.Feature = Evolutions.immunity[0]), Common.createAddFeatToAnimalCompanion(amorphous_anatomy) ); var heal = library.CopyAndAdd<BlueprintAbility>("ff8f1534f66559c478448723e16b6624", "ProteanHealAbility", ""); heal.RemoveComponents<AbilityDeliverTouch>(); heal.ReplaceComponent<ContextRankConfig>(c => { Helpers.SetField(c, "m_BaseValueType", ContextRankBaseValueType.ClassLevel); Helpers.SetField(c, "m_Class", new BlueprintCharacterClass[] { Summoner.summoner_class, Eidolon.eidolon_class }); }); var cast_heal = Helpers.Create<ContextActionCastSpell>(c => c.Spell = heal); var polymorph_greater = library.Get<BlueprintAbility>("a9fc28e147dbb364ea4a3c1831e7e55f"); List<BlueprintAbility> polymorph_variants = new List<BlueprintAbility>(); var polymorph_resource = Helpers.CreateAbilityResource("ProteanChangeShapeResource", "", "", "", null); polymorph_resource.SetFixedResource(1); foreach (var v in polymorph_greater.Variants) { var ability = Common.convertToSuperNatural(v, "Protean", new BlueprintCharacterClass[] { Summoner.summoner_class, Eidolon.eidolon_class }, StatType.Charisma, polymorph_resource); ability.Type = AbilityType.Supernatural; ability.Range = AbilityRange.Personal; ability.setMiscAbilityParametersSelfOnly(); var actions = ability.GetComponent<AbilityEffectRunAction>().Actions.Actions; var new_actions = Common.changeAction<ContextActionApplyBuff>(actions, c => { var buff = library.CopyAndAdd<BlueprintBuff>(c.Buff, "Protean" + c.Buff.name, ""); buff.AddComponent(Helpers.CreateAddFactContextActions(deactivated: cast_heal)); c.Buff = buff; } ); ability.ReplaceComponent<AbilityEffectRunAction>(Helpers.CreateRunActions(new_actions)); polymorph_variants.Add(ability); } var change_shape = Common.createVariantWrapper("ProteanChangeShapeAbility", "", polymorph_variants.ToArray()); change_shape.SetNameDescription("Change Shape", "A protean’s form is not fixed. Once per day as a standard action, a protean may change shape into any as per greater polymorph spell. A protean can resume its true form as a free action, and when it does so, it gains the effects of a heal spell (CL equal to the protean’s HD)."); var freedom_of_movement_buff = library.Get<BlueprintBuff>("1533e782fca42b84ea370fc1dcbf4fc1"); var feature20 = Helpers.CreateFeature("ProteanEidolonLevel20Feature", "Change Shape", "At 20th level, protean eidolons gain constant freedom of movement and the protean version of the change shape (greater polymorph) ability.", "", freedom_of_movement_buff.Icon, FeatureGroup.None, addTransferableFeatToEidolon("ProteanEidolonLevel20AddFeature", Common.createAuraFeatureComponent(freedom_of_movement_buff), Helpers.CreateAddFact(change_shape), polymorph_resource.CreateAddAbilityResource() ) ); protean_eidolon.LevelEntries = new LevelEntry[] {Helpers.LevelEntry(1, feature1), Helpers.LevelEntry(4, feature4), Helpers.LevelEntry(8, feature8), Helpers.LevelEntry(12, feature12), Helpers.LevelEntry(16, feature16), Helpers.LevelEntry(20, feature20) }; protean_eidolon.UIGroups = Helpers.CreateUIGroups(feature1, feature4, feature8, feature12, feature16, feature20); setLesserEidolonProgression(protean_eidolon); } } [AllowMultipleComponents] [AllowedOn(typeof(BlueprintUnitFact))] public class ProteanBuffRemovalAfter1Round : RuleInitiatorLogicComponent<RuleApplyBuff> { public override void OnEventAboutToTrigger(RuleApplyBuff evt) { TimeSpan round = 6.Seconds(); if ((evt.Context.SpellDescriptor & SpellDescriptor.Blindness) > 0 || evt.Blueprint == Common.deafened) { Harmony12.Traverse.Create(evt).Property("Duration").SetValue(new TimeSpan?(round)); } } public override void OnEventDidTrigger(RuleApplyBuff evt) { } } }
0
0.801988
1
0.801988
game-dev
MEDIA
0.939553
game-dev
0.90315
1
0.90315
google/lullaby
3,908
redux/redux/modules/base/serialize.h
/* Copyright 2017-2022 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. */ #ifndef REDUX_MODULES_BASE_SERIALIZE_H_ #define REDUX_MODULES_BASE_SERIALIZE_H_ #include "redux/modules/base/archiver.h" #include "redux/modules/base/hash.h" namespace redux { // Serializes the |value| with the |key| using the provided |serializer|. // // An example will help demonstrate its usage. Given the following classes: // // struct BaseClass { // int base_value; // template <typename Archive> // void Serialize(Archive archive) { // archive(&base_value, ConstHash("base_value")); // } // }; // // struct ChildClass : BaseClass { // int child_value; // template <typename Archive> // void Serialize(Archive archive) { // BaseClass::Serialize(archive); // archive(&child_value, ConstHash("child_value")); // } // }; // // struct CompositeClass { // ChildClass child1; // ChildClass child2; // std::string value; // template <typename Archive> // void Serialize(Archive archive) { // archive(&child1, ConstHash("child1")); // archive(&child2, ConstHash("child2")); // archive(&value, ConstHash("value")); // } // }; // // The following code snippet: // Serializer s; // CompositeClass cc; // Serialize(&s, &cc, ConstHash("cc")); // // Will be the equivalent of the following function calls: // s.Begin(Hash("cc")); // s.Begin(Hash("child1")); // s(&cc.child1.base_value, ConstHash("base_value")); // s(&cc.child1.child_value, ConstHash("child_value")); // s.End(); // s.Begin(Hash("child2")); // s(&cc.child2.base_value, ConstHash("base_value")); // s(&cc.child2.child_value, ConstHash("child_value")); // s.End(); // s(&cc.value, ConstHash("value")); // s.End(); // // A Serializer can be any object that provides the following API: // // template <typename T> // void operator()(T* ptr, HashValue key); // // This is the function that performs the actual serialization. It is strongly // recommended that specific overloads be implemented for this function to // handle value types explicitly. For example, while fundamental types (eg. // bools, floats, ints, etc.) and even math types (eg. vec3, quat, etc.) can // be serialized by memcpy'ing there values, values-types like pointers and // STL containers cannot. As such, a purely generic operator() that can // handle all types will likely result in errors. // // bool IsDestructive() const; // // This allows objects that are being serialized to provide special handling // depending on whether the serialization is a "save" operation (ie. the data // in the object is being serialized to a wire format) or a "load" operation // (ie. the data in the object will be overridden by the data from the // Serializer.) // // void Begin(HashValue key); // void End(); // // If implemented, the Begin()/End() functions on a Serializer when // visiting/serializing a new Value type that has a Serialize member function. // Note: the Begin()/End() functions for the Serializer are optional. If they // are not defined, this functionality will be supressed. template <typename Serializer, typename Value> void Serialize(Serializer& serializer, Value& value, HashValue key = {}) { detail::Archiver<Serializer> archive(&serializer); archive(value, key); } } // namespace redux #endif // REDUX_MODULES_BASE_SERIALIZE_H_
0
0.935213
1
0.935213
game-dev
MEDIA
0.182219
game-dev
0.734325
1
0.734325
3MFConsortium/gladius
5,524
gladius/src/mcp/FunctionGraphDeserializer.cpp
/** * @file FunctionGraphDeserializer.cpp */ #include "FunctionGraphDeserializer.h" #include "../nodes/Model.h" #include "../nodes/NodeFactory.h" #include "../nodes/Parameter.h" #include "../nodes/Port.h" #include "../nodes/nodesfwd.h" #include <nlohmann/json.hpp> #include <unordered_map> namespace gladius { namespace mcp { using nlohmann::json; json FunctionGraphDeserializer::applyToModel(nodes::Model & model, json const & graph, bool replace) { // Validate input if (!graph.is_object()) { return json{{"success", false}, {"error", "graph must be a JSON object"}}; } if (!graph.contains("nodes") || !graph["nodes"].is_array()) { return json{{"success", false}, {"error", "graph.nodes must be an array"}}; } // Optionally clear existing graph if (replace) { model.clear(); model.createBeginEndWithDefaultInAndOuts(); } // Build mapping from client ids to actual NodeBase* std::unordered_map<uint32_t, nodes::NodeBase *> idMap; // Keep handles to Begin/End for special mapping auto * beginNode = model.getBeginNode(); auto * endNode = model.getEndNode(); // First pass: create nodes for (const auto & jn : graph["nodes"]) { if (!jn.is_object()) continue; uint32_t clientId = jn.value("id", 0u); std::string type = jn.value("type", ""); std::string displayName = jn.value("display_name", ""); nodes::NodeBase * created = nullptr; // Map special types to existing begin/end if (type == "Input" || type == "Begin") { created = beginNode; if (!displayName.empty()) created->setDisplayName(displayName); } else if (type == "Output" || type == "End") { created = endNode; if (!displayName.empty()) created->setDisplayName(displayName); } else { auto newNode = nodes::NodeFactory::createNode(type); if (!newNode) { return json{{"success", false}, {"error", std::string("Unknown node type: ") + type}}; } if (!displayName.empty()) newNode->setDisplayName(displayName); created = model.insert(std::move(newNode)); } if (jn.contains("position") && jn["position"].is_array() && jn["position"].size() == 2) { auto pos = const_cast<nodes::NodeBase *>(created)->screenPos(); pos.x = static_cast<float>(jn["position"][0].get<double>()); pos.y = static_cast<float>(jn["position"][1].get<double>()); } if (clientId != 0 && created) { idMap[clientId] = created; } } // Update graph/ports prior to linking model.updateGraphAndOrderIfNeeded(); // Second pass: create links if (graph.contains("links") && graph["links"].is_array()) { for (const auto & jl : graph["links"]) { if (!jl.is_object()) continue; uint32_t fromNodeId = jl.value("from_node_id", 0u); uint32_t toNodeId = jl.value("to_node_id", 0u); std::string fromPort = jl.value("from_port", ""); std::string toParam = jl.value("to_parameter", ""); if (!fromNodeId || !toNodeId || fromPort.empty() || toParam.empty()) continue; auto itFrom = idMap.find(fromNodeId); auto itTo = idMap.find(toNodeId); if (itFrom == idMap.end() || itTo == idMap.end()) continue; nodes::NodeBase * srcNode = itFrom->second; nodes::NodeBase * dstNode = itTo->second; auto * port = srcNode->findOutputPort(fromPort); auto * param = dstNode->getParameter(toParam); if (!port || !param) continue; // Ensure port has parent id set and ids are valid model.registerOutput(*port); model.registerInput(*param); model.addLink(port->getId(), param->getId()); } } // Finalize model.updateGraphAndOrderIfNeeded(); json out; out["success"] = true; json jmap = json::object(); for (const auto & [cid, node] : idMap) { jmap[std::to_string(cid)] = node->getId(); } out["id_map"] = jmap; return out; } } // namespace mcp } // namespace gladius
0
0.919182
1
0.919182
game-dev
MEDIA
0.249606
game-dev
0.862006
1
0.862006
magefree/mage
4,157
Mage.Sets/src/mage/cards/m/MazesEnd.java
package mage.cards.m; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTappedAbility; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.ReturnToHandFromBattlefieldSourceCost; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.search.SearchLibraryPutInPlayEffect; import mage.abilities.hint.ValueHint; import mage.abilities.mana.ColorlessManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.FilterCard; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.common.TargetCardInLibrary; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author LevelX2 */ public final class MazesEnd extends CardImpl { private static final FilterCard filterCard = new FilterCard("Gate card"); static { filterCard.add(SubType.GATE.getPredicate()); } public MazesEnd(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.LAND}, ""); // Maze's End enters the battlefield tapped. this.addAbility(new EntersBattlefieldTappedAbility()); // {T}: Add 1. this.addAbility(new ColorlessManaAbility()); // 3, {T}, Return Maze's End to its owner's hand: Search your library for a Gate card, put it onto the battlefield, then shuffle your library. If you control ten or more Gates with different names, you win the game. Ability ability = new SimpleActivatedAbility(new SearchLibraryPutInPlayEffect(new TargetCardInLibrary(filterCard)), new GenericManaCost(3)); ability.addEffect(new MazesEndEffect()); ability.addCost(new TapSourceCost()); ability.addCost(new ReturnToHandFromBattlefieldSourceCost()); ability.addHint(new ValueHint("Gates with different names you control", GatesWithDifferentNamesYouControlCount.instance)); this.addAbility(ability); } private MazesEnd(final MazesEnd card) { super(card); } @Override public MazesEnd copy() { return new MazesEnd(this); } } enum GatesWithDifferentNamesYouControlCount implements DynamicValue { instance; @Override public int calculate(Game game, Ability sourceAbility, Effect effect) { List<String> names = new ArrayList<>(); for (Permanent permanent : game.getBattlefield().getAllActivePermanents(sourceAbility.getControllerId())) { if (permanent.hasSubtype(SubType.GATE, game)) { if (!names.contains(permanent.getName())) { names.add(permanent.getName()); } } } return names.size(); } @Override public GatesWithDifferentNamesYouControlCount copy() { return instance; } @Override public String toString() { return "X"; } @Override public String getMessage() { return "Gates with different names you control"; } } class MazesEndEffect extends OneShotEffect { MazesEndEffect() { super(Outcome.PutLandInPlay); this.staticText = "If you control ten or more Gates with different names, you win the game"; } private MazesEndEffect(final MazesEndEffect effect) { super(effect); } @Override public MazesEndEffect copy() { return new MazesEndEffect(this); } @Override public boolean apply(Game game, Ability source) { int count = GatesWithDifferentNamesYouControlCount.instance.calculate(game, source, this); if (count >= 10) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { controller.won(game); } } return false; } }
0
0.978562
1
0.978562
game-dev
MEDIA
0.989017
game-dev
0.997802
1
0.997802
DanceManiac/Advanced-X-Ray-Public
16,329
SourcesAXR/xrGame/ui/UIWpnParams.cpp
#include "pch_script.h" #include "UIWpnParams.h" #include "UIXmlInit.h" #include "../level.h" #include "game_base_space.h" #include "../ai_space.h" #include "../../xrServerEntities/script_engine.h" #include "inventory_item_object.h" #include "UIInventoryUtilities.h" #include "Weapon.h" #include "WeaponBinoculars.h" #include "WeaponKnife.h" #include "Silencer.h" struct SLuaWpnParams { luabind::functor<float> m_functorRPM; luabind::functor<float> m_functorAccuracy; luabind::functor<float> m_functorDamage; luabind::functor<float> m_functorDamageMP; luabind::functor<float> m_functorHandling; SLuaWpnParams(); ~SLuaWpnParams(); }; SLuaWpnParams::SLuaWpnParams() { bool functor_exists; functor_exists = ai().script_engine().functor("ui_wpn_params.GetRPM", m_functorRPM); VERIFY(functor_exists); functor_exists = ai().script_engine().functor("ui_wpn_params.GetDamage", m_functorDamage); VERIFY(functor_exists); functor_exists = ai().script_engine().functor("ui_wpn_params.GetDamageMP", m_functorDamageMP); VERIFY(functor_exists); functor_exists = ai().script_engine().functor("ui_wpn_params.GetHandling", m_functorHandling); VERIFY(functor_exists); functor_exists = ai().script_engine().functor("ui_wpn_params.GetAccuracy", m_functorAccuracy); VERIFY(functor_exists); } SLuaWpnParams::~SLuaWpnParams() { } SLuaWpnParams* g_lua_wpn_params = NULL; void destroy_lua_wpn_params() { if(g_lua_wpn_params) xr_delete(g_lua_wpn_params); } // ===================================================================== CUIWpnParams::CUIWpnParams() { AttachChild(&m_Prop_line); AttachChild(&m_icon_acc); AttachChild(&m_icon_dam); AttachChild(&m_icon_han); AttachChild(&m_icon_rpm); AttachChild(&m_textAccuracy); AttachChild(&m_textDamage); AttachChild(&m_textHandling); AttachChild(&m_textRPM); AttachChild(&m_progressAccuracy); AttachChild(&m_progressDamage); AttachChild(&m_progressHandling); AttachChild(&m_progressRPM); AttachChild(&m_stAmmo); AttachChild(&m_textAmmoCount); AttachChild(&m_textAmmoCount2); AttachChild(&m_textAmmoTypes); AttachChild(&m_textAmmoUsedType); AttachChild(&m_stAmmoType1); AttachChild(&m_stAmmoType2); // Lex Addon (correct by Suhar_) 7.08.2018 (begin) // Инициализируем переменные для отображения ещё 4 типов патронов в свойствах оружия /*AttachChild(&m_stAmmoType3); AttachChild(&m_stAmmoType4); AttachChild(&m_stAmmoType5); AttachChild(&m_stAmmoType6);*/ // Lex Addon (correct by Suhar_) 7.08.2018 (end) } CUIWpnParams::~CUIWpnParams() { } void CUIWpnParams::InitFromXml(CUIXml& xml_doc) { if (!xml_doc.NavigateToNode("wpn_params", 0)) return; CUIXmlInit::InitWindow (xml_doc, "wpn_params", 0, this); CUIXmlInit::InitStatic (xml_doc, "wpn_params:prop_line", 0, &m_Prop_line); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_accuracy", 0, &m_icon_acc); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_damage", 0, &m_icon_dam); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_handling", 0, &m_icon_han); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_rpm", 0, &m_icon_rpm); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_accuracy", 0, &m_textAccuracy); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_damage", 0, &m_textDamage); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_handling", 0, &m_textHandling); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_rpm", 0, &m_textRPM); m_progressAccuracy.InitFromXml ( xml_doc, "wpn_params:progress_accuracy" ); m_progressDamage.InitFromXml ( xml_doc, "wpn_params:progress_damage" ); m_progressHandling.InitFromXml ( xml_doc, "wpn_params:progress_handling" ); m_progressRPM.InitFromXml ( xml_doc, "wpn_params:progress_rpm" ); if(IsGameTypeSingle()) { CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_ammo", 0, &m_stAmmo); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_ammo_count", 0, &m_textAmmoCount); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_ammo_count2", 0, &m_textAmmoCount2); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_ammo_types", 0, &m_textAmmoTypes); CUIXmlInit::InitTextWnd (xml_doc, "wpn_params:cap_ammo_used_type", 0, &m_textAmmoUsedType); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_ammo_type1", 0, &m_stAmmoType1); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_ammo_type2", 0, &m_stAmmoType2); // Lex Addon (correct by Suhar_) 7.08.2018 (begin) // Читаем параметры отображения отображения ещё 4 типов патронов в свойствах оружия /*CUIXmlInit::InitStatic(xml_doc, "wpn_params:static_ammo_type3", 0, &m_stAmmoType3); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_ammo_type4", 0, &m_stAmmoType4); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_ammo_type5", 0, &m_stAmmoType5); CUIXmlInit::InitStatic (xml_doc, "wpn_params:static_ammo_type6", 0, &m_stAmmoType6);*/ // Lex Addon (correct by Suhar_) 7.08.2018 (end) } } void CUIWpnParams::SetInfo( CInventoryItem* slot_wpn, CInventoryItem& cur_wpn ) { if ( !g_lua_wpn_params ) { g_lua_wpn_params = xr_new<SLuaWpnParams>(); } LPCSTR cur_section = cur_wpn.object().cNameSect().c_str(); string2048 str_upgrades; str_upgrades[0] = 0; cur_wpn.get_upgrades_str( str_upgrades ); float cur_rpm = iFloor(g_lua_wpn_params->m_functorRPM( cur_section, str_upgrades )*53.0f)/53.0f; float cur_accur = iFloor(g_lua_wpn_params->m_functorAccuracy( cur_section, str_upgrades )*53.0f)/53.0f; float cur_hand = iFloor(g_lua_wpn_params->m_functorHandling( cur_section, str_upgrades )*53.0f)/53.0f; float cur_damage = ( GameID() == eGameIDSingle ) ? iFloor(g_lua_wpn_params->m_functorDamage( cur_section, str_upgrades )*53.0f)/53.0f : iFloor(g_lua_wpn_params->m_functorDamageMP( cur_section, str_upgrades )*53.0f)/53.0f; float slot_rpm = cur_rpm; float slot_accur = cur_accur; float slot_hand = cur_hand; float slot_damage = cur_damage; if ( slot_wpn && (slot_wpn != &cur_wpn) ) { LPCSTR slot_section = slot_wpn->object().cNameSect().c_str(); str_upgrades[0] = 0; slot_wpn->get_upgrades_str( str_upgrades ); slot_rpm = iFloor(g_lua_wpn_params->m_functorRPM( slot_section, str_upgrades )*53.0f)/53.0f; slot_accur = iFloor(g_lua_wpn_params->m_functorAccuracy( slot_section, str_upgrades )*53.0f)/53.0f; slot_hand = iFloor(g_lua_wpn_params->m_functorHandling( slot_section, str_upgrades )*53.0f)/53.0f; slot_damage = ( GameID() == eGameIDSingle ) ? iFloor(g_lua_wpn_params->m_functorDamage( slot_section, str_upgrades )*53.0f)/53.0f : iFloor(g_lua_wpn_params->m_functorDamageMP( slot_section, str_upgrades )*53.0f)/53.0f; } m_progressAccuracy.SetTwoPos( cur_accur, slot_accur ); m_progressDamage.SetTwoPos( cur_damage, slot_damage ); m_progressHandling.SetTwoPos( cur_hand, slot_hand ); m_progressRPM.SetTwoPos( cur_rpm, slot_rpm ); const bool showAmmo READ_IF_EXISTS(pSettings, r_bool, cur_section, "show_ammo", true); m_progressRPM.Show(showAmmo); m_progressAccuracy.Show(showAmmo); m_textAccuracy.Show(showAmmo); m_textRPM.Show(showAmmo); m_icon_rpm.Show(showAmmo); m_icon_acc.Show(showAmmo); if(IsGameTypeSingle()) { // Lex Addon (correct by Suhar_) 7.08.2018 (begin) // Инициализируем переменную используемых оружием патронов xr_vector<shared_str> ammo_types; CWeapon* weapon = cur_wpn.cast_weapon(); if(!weapon) return; m_stAmmo.Show(showAmmo); m_textAmmoCount.Show(showAmmo); m_textAmmoCount2.Show(showAmmo); m_textAmmoTypes.Show(showAmmo); m_textAmmoUsedType.Show(showAmmo); m_stAmmoType1.Show(showAmmo); m_stAmmoType2.Show(showAmmo); /*m_stAmmoType3.Show(showAmmo); m_stAmmoType4.Show(showAmmo); m_stAmmoType5.Show(showAmmo); m_stAmmoType6.Show(showAmmo);*/ if (!showAmmo) return; int ammo_count = weapon->GetAmmoMagSize(); int ammo_count2 = ammo_count; if(slot_wpn) { CWeapon* slot_weapon = slot_wpn->cast_weapon(); if(slot_weapon) ammo_count2 = slot_weapon->GetAmmoMagSize(); } if(ammo_count==ammo_count2) m_textAmmoCount2.SetTextColor(color_rgba(170,170,170,255)); else if(ammo_count<ammo_count2) m_textAmmoCount2.SetTextColor(color_rgba(255,0,0,255)); else m_textAmmoCount2.SetTextColor(color_rgba(0,255,0,255)); string128 str; xr_sprintf(str, sizeof(str), "%d", ammo_count); m_textAmmoCount2.SetText(str); ammo_types = weapon->m_ammoTypes; if(ammo_types.empty()) return; // Получаем количчество видов используемых оружием патронов ammo_types_size = ammo_types.size(); xr_sprintf(str, sizeof(str), "%s", pSettings->r_string(ammo_types[0].c_str(), "inv_name_short")); m_textAmmoUsedType.SetTextST(str); m_stAmmoType1.SetShader(InventoryUtilities::GetEquipmentIconsShader()); Frect tex_rect; tex_rect.x1 = float(pSettings->r_u32(ammo_types[0].c_str(), "inv_grid_x") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y1 = float(pSettings->r_u32(ammo_types[0].c_str(), "inv_grid_y") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.x2 = float(pSettings->r_u32(ammo_types[0].c_str(), "inv_grid_width") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y2 = float(pSettings->r_u32(ammo_types[0].c_str(), "inv_grid_height") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.rb.add (tex_rect.lt); m_stAmmoType1.SetTextureRect(tex_rect); m_stAmmoType1.TextureOn(); m_stAmmoType1.SetStretchTexture(true); if (GameConstants::GetUseHQ_Icons()) m_stAmmoType1.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1) * UI().get_current_kx() / 2, (tex_rect.y2 - tex_rect.y1) / 2)); else m_stAmmoType1.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1) * UI().get_current_kx(), tex_rect.y2 - tex_rect.y1)); m_stAmmoType2.SetShader(InventoryUtilities::GetEquipmentIconsShader()); if(ammo_types.size() == 1) { tex_rect.set(0,0,1,1); } else { tex_rect.x1 = float(pSettings->r_u32(ammo_types[1].c_str(), "inv_grid_x") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y1 = float(pSettings->r_u32(ammo_types[1].c_str(), "inv_grid_y") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.x2 = float(pSettings->r_u32(ammo_types[1].c_str(), "inv_grid_width") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y2 = float(pSettings->r_u32(ammo_types[1].c_str(), "inv_grid_height") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.rb.add (tex_rect.lt); } m_stAmmoType2.SetTextureRect(tex_rect); m_stAmmoType2.TextureOn(); m_stAmmoType2.SetStretchTexture(true); if (GameConstants::GetUseHQ_Icons()) m_stAmmoType2.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1) * UI().get_current_kx() / 2, (tex_rect.y2 - tex_rect.y1) / 2)); else m_stAmmoType2.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1) * UI().get_current_kx(), tex_rect.y2 - tex_rect.y1)); /*m_stAmmoType3.SetShader(InventoryUtilities::GetEquipmentIconsShader()); if (ammo_types_size <= 2) { tex_rect.set(0, 0, 1, 1); } else { tex_rect.x1 = float(pSettings->r_u32(ammo_types[2].c_str(), "inv_grid_x") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y1 = float(pSettings->r_u32(ammo_types[2].c_str(), "inv_grid_y") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.x2 = float(pSettings->r_u32(ammo_types[2].c_str(), "inv_grid_width") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y2 = float(pSettings->r_u32(ammo_types[2].c_str(), "inv_grid_height") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.rb.add(tex_rect.lt); } m_stAmmoType3.SetTextureRect(tex_rect); m_stAmmoType3.TextureOn(); m_stAmmoType3.SetStretchTexture(true); m_stAmmoType3.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1)*UI().get_current_kx(), tex_rect.y2 - tex_rect.y1)); m_stAmmoType4.SetShader(InventoryUtilities::GetEquipmentIconsShader()); if (ammo_types_size <= 3) { tex_rect.set(0, 0, 1, 1); } else { tex_rect.x1 = float(pSettings->r_u32(ammo_types[3].c_str(), "inv_grid_x") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y1 = float(pSettings->r_u32(ammo_types[3].c_str(), "inv_grid_y") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.x2 = float(pSettings->r_u32(ammo_types[3].c_str(), "inv_grid_width") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y2 = float(pSettings->r_u32(ammo_types[3].c_str(), "inv_grid_height") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.rb.add(tex_rect.lt); } m_stAmmoType4.SetTextureRect(tex_rect); m_stAmmoType4.TextureOn(); m_stAmmoType4.SetStretchTexture(true); m_stAmmoType4.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1)*UI().get_current_kx(), tex_rect.y2 - tex_rect.y1)); m_stAmmoType5.SetShader(InventoryUtilities::GetEquipmentIconsShader()); if (ammo_types_size <= 4) { tex_rect.set(0, 0, 1, 1); } else { tex_rect.x1 = float(pSettings->r_u32(ammo_types[4].c_str(), "inv_grid_x") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y1 = float(pSettings->r_u32(ammo_types[4].c_str(), "inv_grid_y") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.x2 = float(pSettings->r_u32(ammo_types[4].c_str(), "inv_grid_width") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y2 = float(pSettings->r_u32(ammo_types[4].c_str(), "inv_grid_height") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.rb.add(tex_rect.lt); } m_stAmmoType5.SetTextureRect(tex_rect); m_stAmmoType5.TextureOn(); m_stAmmoType5.SetStretchTexture(true); m_stAmmoType5.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1)*UI().get_current_kx(), tex_rect.y2 - tex_rect.y1)); m_stAmmoType6.SetShader(InventoryUtilities::GetEquipmentIconsShader()); if (ammo_types_size <= 5) { tex_rect.set(0, 0, 1, 1); } else { tex_rect.x1 = float(pSettings->r_u32(ammo_types[5].c_str(), "inv_grid_x") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y1 = float(pSettings->r_u32(ammo_types[5].c_str(), "inv_grid_y") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.x2 = float(pSettings->r_u32(ammo_types[5].c_str(), "inv_grid_width") * INV_GRID_WIDTH(GameConstants::GetUseHQ_Icons())); tex_rect.y2 = float(pSettings->r_u32(ammo_types[5].c_str(), "inv_grid_height") * INV_GRID_HEIGHT(GameConstants::GetUseHQ_Icons())); tex_rect.rb.add(tex_rect.lt); } m_stAmmoType6.SetTextureRect(tex_rect); m_stAmmoType6.TextureOn(); m_stAmmoType6.SetStretchTexture(true); m_stAmmoType6.SetWndSize(Fvector2().set((tex_rect.x2 - tex_rect.x1)*UI().get_current_kx(), tex_rect.y2 - tex_rect.y1)); */ // Lex Addon (correct by Suhar_) 7.08.2018 (end) } } bool CUIWpnParams::Check(CInventoryItem& wpn_section) { LPCSTR wpn_sect = wpn_section.object().cNameSect().c_str(); CWeapon* wpn = smart_cast<CWeapon*>(&wpn_section); if (pSettings->line_exist(wpn_sect, "fire_dispersion_base")) { if (smart_cast<CSilencer*>(&wpn_section)) return false; if (smart_cast<CWeaponBinoculars*>(&wpn_section)) return false; if (smart_cast<CWeaponKnife*>(&wpn_section)) return false; if (!wpn->m_bShowWpnStats) return false; return true; } return false; } // ------------------------------------------------------------------------------------------------- CUIConditionParams::CUIConditionParams() { AttachChild( &m_progress ); AttachChild( &m_text ); } CUIConditionParams::~CUIConditionParams() { } void CUIConditionParams::InitFromXml(CUIXml& xml_doc) { if (!xml_doc.NavigateToNode("condition_params", 0)) return; CUIXmlInit::InitWindow (xml_doc, "condition_params", 0, this); CUIXmlInit::InitStatic ( xml_doc, "condition_params:caption", 0, &m_text ); m_progress.InitFromXml ( xml_doc, "condition_params:progress_state" ); } void CUIConditionParams::SetInfo( CInventoryItem const* slot_item, CInventoryItem const& cur_item ) { float cur_value = cur_item.GetConditionToShow() * 100.0f + 1.0f - EPS; float slot_value = cur_value; if ( slot_item && (slot_item != &cur_item) /*&& (cur_item.object().cNameSect()._get() == slot_item->object().cNameSect()._get())*/ ) { slot_value = slot_item->GetConditionToShow() * 100.0f + 1.0f - EPS; } m_progress.SetTwoPos( cur_value, slot_value ); }
0
0.966886
1
0.966886
game-dev
MEDIA
0.800392
game-dev
0.611705
1
0.611705
LandSandBoat/server
1,311
scripts/items/serving_of_karni_yarik_+1.lua
----------------------------------- -- ID: 5589 -- Item: serving_of_karni_yarik_+1 -- Food Effect: 60Min, All Races ----------------------------------- -- Agility 4 -- Vitality -2 -- Attack % 22 (cap 70) -- Ranged Attack % 22 (cap 70) -- Evasion +7 ----------------------------------- ---@type TItemFood local itemObject = {} itemObject.onItemCheck = function(target, item, param, caster) return xi.itemUtils.foodOnItemCheck(target, xi.foodType.BASIC) end itemObject.onItemUse = function(target, user, item, action) target:addStatusEffect(xi.effect.FOOD, 0, 0, 3600, 0, 0, 0, xi.effectSourceType.FOOD, item:getID(), user:getID()) end itemObject.onEffectGain = function(target, effect) target:addMod(xi.mod.AGI, 4) target:addMod(xi.mod.VIT, -2) target:addMod(xi.mod.FOOD_ATTP, 22) target:addMod(xi.mod.FOOD_ATT_CAP, 70) target:addMod(xi.mod.FOOD_RATTP, 22) target:addMod(xi.mod.FOOD_RATT_CAP, 70) target:addMod(xi.mod.EVA, 7) end itemObject.onEffectLose = function(target, effect) target:delMod(xi.mod.AGI, 4) target:delMod(xi.mod.VIT, -2) target:delMod(xi.mod.FOOD_ATTP, 22) target:delMod(xi.mod.FOOD_ATT_CAP, 70) target:delMod(xi.mod.FOOD_RATTP, 22) target:delMod(xi.mod.FOOD_RATT_CAP, 70) target:delMod(xi.mod.EVA, 7) end return itemObject
0
0.599855
1
0.599855
game-dev
MEDIA
0.992412
game-dev
0.537942
1
0.537942
MisterTea/HyperNEAT
1,804
fuego-0.4/simpleplayers/SpLibertyPlayer.cpp
//---------------------------------------------------------------------------- /** @file SpLibertyPlayer.cpp See SpLibertyPlayer.h */ //---------------------------------------------------------------------------- #include "SgSystem.h" #include "SpLibertyPlayer.h" #include "GoBoardUtil.h" #include "SgConnCompIterator.h" using GoBoardUtil::ExpandToBlocks; using GoBoardUtil::MoveLegalAndNotAtari; //---------------------------------------------------------------------------- int SpLibertyMoveGenerator::Score(SgPoint p) // high score for playing liberties of weak blocks // AR may be suicidal. { SgPointSet nb; const int size = m_board.Size(); nb.Include(p); nb = nb.Border(size) & m_board.Occupied(); ExpandToBlocks(m_board, nb); int score(INT_MIN); if (MoveLegalAndNotAtari(m_board, p)) { score = m_board.NumEmptyNeighbors(p); for (SgConnCompIterator it(nb, m_board.Size()); it; ++it) { int nuLibs = ((*it).Border(size) & m_board.AllEmpty()).Size(); if (nuLibs == 1) score += 20; else if (nuLibs == 2) score += 10; else if (nuLibs == 3) score += 5; else if (nuLibs == 4) score += 3; else ++score; } } return score; } /** counts surplus liberties of all blocks, those above 2. penalty for less than 2 liberties. @todo make threshold of 2 variable, experiment */ int LibertyMinus2(const GoBoard& board, SgBlackWhite color) { int nuLibs = 0; const int size = board.Size(); for (SgConnCompIterator it(board.All(color), board.Size()); it; ++it) { nuLibs += ((*it).Border(size) & board.AllEmpty()).Size() - 2; } return nuLibs; }
0
0.929108
1
0.929108
game-dev
MEDIA
0.727205
game-dev
0.902814
1
0.902814
Squalr/Squally
3,103
Source/Scenes/Platformer/Components/Entities/Friendly/Hexus/UnderflowRuins/Tier5URHexusBehavior.cpp
#include "Tier5URHexusBehavior.h" #include "cocos/base/CCValue.h" #include "Objects/Platformer/ItemPools/HexusPools/UnderflowRuins/HexusPoolURGeneric.h" #include "Scenes/Hexus/CardData/CardKeys.h" #include "Scenes/Hexus/CardData/CardList.h" #include "Scenes/Hexus/Opponents/HexusOpponentData.h" #include "Scenes/Hexus/StateOverride.h" #include "Scenes/Platformer/Components/Entities/Friendly/Hexus/UnderflowRuins/URHexusConfig.h" #include "Resources/HexusResources.h" #include "Resources/SoundResources.h" #include "Strings/Strings.h" using namespace cocos2d; const std::string Tier5URHexusBehavior::MapKey = "ur-t5-hexus"; Tier5URHexusBehavior* Tier5URHexusBehavior::create(GameObject* owner) { Tier5URHexusBehavior* instance = new Tier5URHexusBehavior(owner); instance->autorelease(); return instance; } Tier5URHexusBehavior::Tier5URHexusBehavior(GameObject* owner) : super(owner, SoundResources::Platformer_Entities_Generic_ChatterShort1) { } Tier5URHexusBehavior::~Tier5URHexusBehavior() { } MinMaxPool* Tier5URHexusBehavior::generateReward() { ValueMap properties = ValueMap(); return HexusPoolURGeneric::create(properties); } std::string Tier5URHexusBehavior::getWinLossSaveKey() { // Backwards compatibility, use old string for save key return "angel-hexus"; // Tier5URHexusBehavior::MapKey; } std::string Tier5URHexusBehavior::getBackgroundResource() { return HexusResources::Menus_HexusFrameUnderflowRuins; } std::vector<CardData*> Tier5URHexusBehavior::generateDeck() { const float LocalOrder = 5.0f / URHexusConfig::MaxEntities; return HexusOpponentData::generateDeck(28, this->calculateStrength(LocalOrder, URHexusConfig::ZoneOrder), { CardList::getInstance()->cardListByName[CardKeys::Binary0], CardList::getInstance()->cardListByName[CardKeys::Decimal0], CardList::getInstance()->cardListByName[CardKeys::Hex0], CardList::getInstance()->cardListByName[CardKeys::Binary0], CardList::getInstance()->cardListByName[CardKeys::Decimal0], CardList::getInstance()->cardListByName[CardKeys::Hex0], // CardList::getInstance()->cardListByName[CardKeys::Mov], CardList::getInstance()->cardListByName[CardKeys::Mov], // CardList::getInstance()->cardListByName[CardKeys::Flip1], // CardList::getInstance()->cardListByName[CardKeys::Flip1], // CardList::getInstance()->cardListByName[CardKeys::Flip2], CardList::getInstance()->cardListByName[CardKeys::Flip2], // CardList::getInstance()->cardListByName[CardKeys::Addition], CardList::getInstance()->cardListByName[CardKeys::Addition], // CardList::getInstance()->cardListByName[CardKeys::ShiftLeft], CardList::getInstance()->cardListByName[CardKeys::ShiftLeft], CardList::getInstance()->cardListByName[CardKeys::ShiftRight], CardList::getInstance()->cardListByName[CardKeys::ShiftRight], // CardList::getInstance()->cardListByName[CardKeys::LogicalOr], // CardList::getInstance()->cardListByName[CardKeys::LogicalOr], }); } StateOverride* Tier5URHexusBehavior::getStateOverride() { return nullptr; } std::vector<TutorialBase*> Tier5URHexusBehavior::getTutorials() { return { }; }
0
0.955369
1
0.955369
game-dev
MEDIA
0.711101
game-dev
0.985238
1
0.985238
Los-Vic/GameAbilityNodeSystem
2,890
Assets/GameAbilitySystem/Logic/Subsystem/AbilityInstanceSubsystem.cs
using System.Collections.Generic; using GCL; namespace GAS.Logic { //Ability的Handler不应该AddRef public class AbilityInstanceSubsystem:GameAbilitySubsystem { private readonly List<GameAbility> _needTickAbilities = new(); private readonly List<GameAbility> _traverseAbilityCache = new(); public override void Init() { base.Init(); System.HandlerManagers.AbilityHandlerMgr.Init(GetAbility, DisposeAbility, 1024); } public override void UnInit() { _needTickAbilities.Clear(); _traverseAbilityCache.Clear(); System.HandlerManagers.AbilityHandlerMgr.UnInit(); base.UnInit(); } public override void Update(float deltaTime) { if(_needTickAbilities.Count == 0) return; _traverseAbilityCache.Clear(); _traverseAbilityCache.AddRange(_needTickAbilities); foreach (var a in _traverseAbilityCache) { a.OnTick(); } } internal GameAbility CreateAbility(ref AbilityCreateParam param) { var abilityAsset = System.AssetConfigProvider.GetAbilityAsset(param.Id); if (!abilityAsset) { GameLogger.LogError($"Fail to get ActiveAbilityAsset:{param.Id}"); return null; } var h = System.HandlerManagers.AbilityHandlerMgr.CreateHandler(); System.HandlerManagers.AbilityHandlerMgr.DeRef(h, out var ability); var initParam = new AbilityInitParam() { CreateParam = param, Handler = h }; ability.Init(abilityAsset, ref initParam); return ability; } internal void DestroyAbility(GameAbility ability) { if (ability.State is EAbilityState.MarkDestroy or EAbilityState.UnInitialized) return; ability.MarkDestroy(); RemoveFromTickList(ability); System.HandlerManagers.AbilityHandlerMgr.RemoveRefCount(ability.Handler); } private GameAbility GetAbility() { return System.ClassObjectPoolSubsystem.Get<GameAbility>(); } private void DisposeAbility(GameAbility ability) { GameLogger.Log($"Release ability:{ability}"); System.ClassObjectPoolSubsystem.Release(ability); } internal void AddToTickList(GameAbility ability) { if(_needTickAbilities.Contains(ability)) return; _needTickAbilities.Add(ability); } internal void RemoveFromTickList(GameAbility ability) { _needTickAbilities.Remove(ability); } } }
0
0.854738
1
0.854738
game-dev
MEDIA
0.983494
game-dev
0.918286
1
0.918286
bberberov/scorched3d
2,647
src/common/placement/PlacementObjectRandom.cpp
//////////////////////////////////////////////////////////////////////////////// // Scorched3D (c) 2000-2011 // // This file is part of Scorched3D. // // Scorched3D 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. // // Scorched3D is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //////////////////////////////////////////////////////////////////////////////// #include <placement/PlacementObjectRandom.hpp> #include <common/RandomGenerator.hpp> #include <XML/XMLParser.hpp> PlacementObjectRandom::PlacementObjectRandom() : totalWeight_(0) { } PlacementObjectRandom::~PlacementObjectRandom() { } bool PlacementObjectRandom::readXML(XMLNode *initialNode) { XMLNode *node; while (initialNode->getNamedChild("randomobject", node, false)) { RandomObject randomObject; // Get the weight randomObject.weight = 1; node->getNamedChild("weight", randomObject.weight, false); totalWeight_ += randomObject.weight; // Get the object std::string objecttype; XMLNode *objectNode; if (!node->getNamedChild("object", objectNode)) return false; if (!objectNode->getNamedParameter("type", objecttype)) return false; if (!(randomObject.object = PlacementObject::create(objecttype.c_str()))) return false; if (!randomObject.object->readXML(objectNode)) return false; objects_.push_back(randomObject); } if (!node->failChildren()) return false; return PlacementObject::readXML(node); } void PlacementObjectRandom::createObject(ScorchedContext &context, RandomGenerator &generator, unsigned int &playerId, PlacementType::Position &position) { fixed totalWeight = generator.getRandFixed("PlacementObjectRandom") * totalWeight_; fixed currentWeight = 0; std::vector<RandomObject>::iterator itor; for (itor = objects_.begin(); itor != objects_.end(); ++itor) { RandomObject &object = (*itor); currentWeight += object.weight; if (currentWeight > totalWeight) { PlacementObject *entry = object.object; entry->createObject(context, generator, playerId, position); break; } } }
0
0.88263
1
0.88263
game-dev
MEDIA
0.719504
game-dev
0.942963
1
0.942963
Nextpeer/Nextpeer-UFORUN
19,359
cocos2d-x-2.2/external/Box2D/Collision/b2CollideEdge.cpp
/* * Copyright (c) 2007-2009 Erin Catto http://www.box2d.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. */ #include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2EdgeShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> // Compute contact points for edge versus circle. // This accounts for edge connectivity. void b2CollideEdgeAndCircle(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2CircleShape* circleB, const b2Transform& xfB) { manifold->pointCount = 0; // Compute circle in frame of edge b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; b2Vec2 e = B - A; // Barycentric coordinates float32 u = b2Dot(e, B - Q); float32 v = b2Dot(e, Q - A); float32 radius = edgeA->m_radius + circleB->m_radius; b2ContactFeature cf; cf.indexB = 0; cf.typeB = b2ContactFeature::e_vertex; // Region A if (v <= 0.0f) { b2Vec2 P = A; b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to A? if (edgeA->m_hasVertex0) { b2Vec2 A1 = edgeA->m_vertex0; b2Vec2 B1 = A; b2Vec2 e1 = B1 - A1; float32 u1 = b2Dot(e1, B1 - Q); // Is the circle in Region AB of the previous edge? if (u1 > 0.0f) { return; } } cf.indexA = 0; cf.typeA = b2ContactFeature::e_vertex; manifold->pointCount = 1; manifold->type = b2Manifold::e_circles; manifold->localNormal.SetZero(); manifold->localPoint = P; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; return; } // Region B if (u <= 0.0f) { b2Vec2 P = B; b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to B? if (edgeA->m_hasVertex3) { b2Vec2 B2 = edgeA->m_vertex3; b2Vec2 A2 = B; b2Vec2 e2 = B2 - A2; float32 v2 = b2Dot(e2, Q - A2); // Is the circle in Region AB of the next edge? if (v2 > 0.0f) { return; } } cf.indexA = 1; cf.typeA = b2ContactFeature::e_vertex; manifold->pointCount = 1; manifold->type = b2Manifold::e_circles; manifold->localNormal.SetZero(); manifold->localPoint = P; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; return; } // Region AB float32 den = b2Dot(e, e); b2Assert(den > 0.0f); b2Vec2 P = (1.0f / den) * (u * A + v * B); b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } b2Vec2 n(-e.y, e.x); if (b2Dot(n, Q - A) < 0.0f) { n.Set(-n.x, -n.y); } n.Normalize(); cf.indexA = 0; cf.typeA = b2ContactFeature::e_face; manifold->pointCount = 1; manifold->type = b2Manifold::e_faceA; manifold->localNormal = n; manifold->localPoint = A; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; } // This structure is used to keep track of the best separating axis. struct b2EPAxis { enum Type { e_unknown, e_edgeA, e_edgeB }; Type type; int32 index; float32 separation; }; // This holds polygon B expressed in frame A. struct b2TempPolygon { b2Vec2 vertices[b2_maxPolygonVertices]; b2Vec2 normals[b2_maxPolygonVertices]; int32 count; }; // Reference face used for clipping struct b2ReferenceFace { int32 i1, i2; b2Vec2 v1, v2; b2Vec2 normal; b2Vec2 sideNormal1; float32 sideOffset1; b2Vec2 sideNormal2; float32 sideOffset2; }; // This class collides and edge and a polygon, taking into account edge adjacency. struct b2EPCollider { void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB); b2EPAxis ComputeEdgeSeparation(); b2EPAxis ComputePolygonSeparation(); enum VertexType { e_isolated, e_concave, e_convex }; b2TempPolygon m_polygonB; b2Transform m_xf; b2Vec2 m_centroidB; b2Vec2 m_v0, m_v1, m_v2, m_v3; b2Vec2 m_normal0, m_normal1, m_normal2; b2Vec2 m_normal; VertexType m_type1, m_type2; b2Vec2 m_lowerLimit, m_upperLimit; float32 m_radius; bool m_front; }; // Algorithm: // 1. Classify v1 and v2 // 2. Classify polygon centroid as front or back // 3. Flip normal if necessary // 4. Initialize normal range to [-pi, pi] about face normal // 5. Adjust normal range according to adjacent edges // 6. Visit each separating axes, only accept axes within the range // 7. Return if _any_ axis indicates separation // 8. Clip void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB) { m_xf = b2MulT(xfA, xfB); m_centroidB = b2Mul(m_xf, polygonB->m_centroid); m_v0 = edgeA->m_vertex0; m_v1 = edgeA->m_vertex1; m_v2 = edgeA->m_vertex2; m_v3 = edgeA->m_vertex3; bool hasVertex0 = edgeA->m_hasVertex0; bool hasVertex3 = edgeA->m_hasVertex3; b2Vec2 edge1 = m_v2 - m_v1; edge1.Normalize(); m_normal1.Set(edge1.y, -edge1.x); float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); float32 offset0 = 0.0f, offset2 = 0.0f; bool convex1 = false, convex2 = false; // Is there a preceding edge? if (hasVertex0) { b2Vec2 edge0 = m_v1 - m_v0; edge0.Normalize(); m_normal0.Set(edge0.y, -edge0.x); convex1 = b2Cross(edge0, edge1) >= 0.0f; offset0 = b2Dot(m_normal0, m_centroidB - m_v0); } // Is there a following edge? if (hasVertex3) { b2Vec2 edge2 = m_v3 - m_v2; edge2.Normalize(); m_normal2.Set(edge2.y, -edge2.x); convex2 = b2Cross(edge1, edge2) > 0.0f; offset2 = b2Dot(m_normal2, m_centroidB - m_v2); } // Determine front or back collision. Determine collision normal limits. if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal1; } } else if (convex1) { m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = -m_normal1; } } else if (convex2) { m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal0; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = -m_normal0; } } } else if (hasVertex0) { if (convex1) { m_front = offset0 >= 0.0f || offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal1; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal0; } } } else if (hasVertex3) { if (convex2) { m_front = offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal1; } } else { m_front = offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = m_normal1; } } } else { m_front = offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal1; } } // Get polygonB in frameA m_polygonB.count = polygonB->m_vertexCount; for (int32 i = 0; i < polygonB->m_vertexCount; ++i) { m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); } m_radius = 2.0f * b2_polygonRadius; manifold->pointCount = 0; b2EPAxis edgeAxis = ComputeEdgeSeparation(); // If no valid normal can be found than this edge should not collide. if (edgeAxis.type == b2EPAxis::e_unknown) { return; } if (edgeAxis.separation > m_radius) { return; } b2EPAxis polygonAxis = ComputePolygonSeparation(); if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) { return; } // Use hysteresis for jitter reduction. const float32 k_relativeTol = 0.98f; const float32 k_absoluteTol = 0.001f; b2EPAxis primaryAxis; if (polygonAxis.type == b2EPAxis::e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } b2ClipVertex ie[2]; b2ReferenceFace rf; if (primaryAxis.type == b2EPAxis::e_edgeA) { manifold->type = b2Manifold::e_faceA; // Search for the polygon normal that is most anti-parallel to the edge normal. int32 bestIndex = 0; float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); for (int32 i = 1; i < m_polygonB.count; ++i) { float32 value = b2Dot(m_normal, m_polygonB.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } int32 i1 = bestIndex; int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; ie[0].v = m_polygonB.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = b2ContactFeature::e_face; ie[0].id.cf.typeB = b2ContactFeature::e_vertex; ie[1].v = m_polygonB.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = b2ContactFeature::e_face; ie[1].id.cf.typeB = b2ContactFeature::e_vertex; if (m_front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = m_v1; rf.v2 = m_v2; rf.normal = m_normal1; } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = m_v2; rf.v2 = m_v1; rf.normal = -m_normal1; } } else { manifold->type = b2Manifold::e_faceB; ie[0].v = m_v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = b2ContactFeature::e_vertex; ie[0].id.cf.typeB = b2ContactFeature::e_face; ie[1].v = m_v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = b2ContactFeature::e_vertex; ie[1].id.cf.typeB = b2ContactFeature::e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; rf.v1 = m_polygonB.vertices[rf.i1]; rf.v2 = m_polygonB.vertices[rf.i2]; rf.normal = m_polygonB.normals[rf.i1]; } rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); rf.sideNormal2 = -rf.sideNormal1; rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); // Clip incident edge against extruded edge1 side edges. b2ClipVertex clipPoints1[2]; b2ClipVertex clipPoints2[2]; int32 np; // Clip to box side 1 np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < b2_maxManifoldPoints) { return; } // Clip to negative box side 1 np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < b2_maxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. if (primaryAxis.type == b2EPAxis::e_edgeA) { manifold->localNormal = rf.normal; manifold->localPoint = rf.v1; } else { manifold->localNormal = polygonB->m_normals[rf.i1]; manifold->localPoint = polygonB->m_vertices[rf.i1]; } int32 pointCount = 0; for (int32 i = 0; i < b2_maxManifoldPoints; ++i) { float32 separation; separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); if (separation <= m_radius) { b2ManifoldPoint* cp = manifold->points + pointCount; if (primaryAxis.type == b2EPAxis::e_edgeA) { cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); cp->id = clipPoints2[i].id; } else { cp->localPoint = clipPoints2[i].v; cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold->pointCount = pointCount; } b2EPAxis b2EPCollider::ComputeEdgeSeparation() { b2EPAxis axis; axis.type = b2EPAxis::e_edgeA; axis.index = m_front ? 0 : 1; axis.separation = FLT_MAX; for (int32 i = 0; i < m_polygonB.count; ++i) { float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); if (s < axis.separation) { axis.separation = s; } } return axis; } b2EPAxis b2EPCollider::ComputePolygonSeparation() { b2EPAxis axis; axis.type = b2EPAxis::e_unknown; axis.index = -1; axis.separation = -FLT_MAX; b2Vec2 perp(-m_normal.y, m_normal.x); for (int32 i = 0; i < m_polygonB.count; ++i) { b2Vec2 n = -m_polygonB.normals[i]; float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); float32 s = b2Min(s1, s2); if (s > m_radius) { // No collision axis.type = b2EPAxis::e_edgeB; axis.index = i; axis.separation = s; return axis; } // Adjacency if (b2Dot(n, perp) >= 0.0f) { if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) { continue; } } else { if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) { continue; } } if (s > axis.separation) { axis.type = b2EPAxis::e_edgeB; axis.index = i; axis.separation = s; } } return axis; } void b2CollideEdgeAndPolygon( b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB) { b2EPCollider collider; collider.Collide(manifold, edgeA, xfA, polygonB, xfB); }
0
0.988231
1
0.988231
game-dev
MEDIA
0.655622
game-dev
0.994378
1
0.994378
Adaptvx/Interaction
12,709
Library/Core/AceConfigRegistry-3.0/AceConfigRegistry-3.0.lua
--- AceConfigRegistry-3.0 handles central registration of options tables in use by addons and modules.\\ -- Options tables can be registered as raw tables, OR as function refs that return a table.\\ -- Such functions receive three arguments: "type", "uiName", "appName". \\ -- * Valid **types**: "cmd", "dropdown", "dialog". This is verified by the library at call time. \\ -- * The **uiName** field is expected to contain the full name of the calling addon, including version, e.g. "FooBar-1.0". This is verified by the library at call time.\\ -- * The **appName** field is the options table name as given at registration time \\ -- -- :IterateOptionsTables() (and :GetOptionsTable() if only given one argument) return a function reference that the requesting config handling addon must call with valid "type", "uiName". -- @class file -- @name AceConfigRegistry-3.0 -- @release $Id: AceConfigRegistry-3.0.lua 1296 2022-11-04 18:50:10Z nevcairiel $ local CallbackHandler = LibStub("CallbackHandler-1.0") local MAJOR, MINOR = "AceConfigRegistry-3.0", 21 local AceConfigRegistry = LibStub:NewLibrary(MAJOR, MINOR) if not AceConfigRegistry then return end AceConfigRegistry.tables = AceConfigRegistry.tables or {} if not AceConfigRegistry.callbacks then AceConfigRegistry.callbacks = CallbackHandler:New(AceConfigRegistry) end -- Lua APIs local tinsert, tconcat = table.insert, table.concat local strfind, strmatch = string.find, string.match local type, tostring, select, pairs = type, tostring, select, pairs local error, assert = error, assert ----------------------------------------------------------------------- -- Validating options table consistency: AceConfigRegistry.validated = { -- list of options table names ran through :ValidateOptionsTable automatically. -- CLEARED ON PURPOSE, since newer versions may have newer validators cmd = {}, dropdown = {}, dialog = {}, } local function err(msg, errlvl, ...) local t = {} for i=select("#",...),1,-1 do tinsert(t, (select(i, ...))) end error(MAJOR..":ValidateOptionsTable(): "..tconcat(t,".")..msg, errlvl+2) end local isstring={["string"]=true, _="string"} local isstringfunc={["string"]=true,["function"]=true, _="string or funcref"} local istable={["table"]=true, _="table"} local ismethodtable={["table"]=true,["string"]=true,["function"]=true, _="methodname, funcref or table"} local optstring={["nil"]=true,["string"]=true, _="string"} local optstringfunc={["nil"]=true,["string"]=true,["function"]=true, _="string or funcref"} local optstringnumberfunc={["nil"]=true,["string"]=true,["number"]=true,["function"]=true, _="string, number or funcref"} local optnumber={["nil"]=true,["number"]=true, _="number"} local optmethodfalse={["nil"]=true,["string"]=true,["function"]=true,["boolean"]={[false]=true}, _="methodname, funcref or false"} local optmethodnumber={["nil"]=true,["string"]=true,["function"]=true,["number"]=true, _="methodname, funcref or number"} local optmethodtable={["nil"]=true,["string"]=true,["function"]=true,["table"]=true, _="methodname, funcref or table"} local optmethodbool={["nil"]=true,["string"]=true,["function"]=true,["boolean"]=true, _="methodname, funcref or boolean"} local opttable={["nil"]=true,["table"]=true, _="table"} local optbool={["nil"]=true,["boolean"]=true, _="boolean"} local optboolnumber={["nil"]=true,["boolean"]=true,["number"]=true, _="boolean or number"} local optstringnumber={["nil"]=true,["string"]=true,["number"]=true, _="string or number"} local basekeys={ type=isstring, name=isstringfunc, desc=optstringfunc, descStyle=optstring, order=optmethodnumber, validate=optmethodfalse, confirm=optmethodbool, confirmText=optstring, disabled=optmethodbool, hidden=optmethodbool, guiHidden=optmethodbool, dialogHidden=optmethodbool, dropdownHidden=optmethodbool, cmdHidden=optmethodbool, tooltipHyperlink=optstringfunc, icon=optstringnumberfunc, iconCoords=optmethodtable, handler=opttable, get=optmethodfalse, set=optmethodfalse, func=optmethodfalse, arg={["*"]=true}, width=optstringnumber, } local typedkeys={ header={ control=optstring, dialogControl=optstring, dropdownControl=optstring, }, description={ image=optstringnumberfunc, imageCoords=optmethodtable, imageHeight=optnumber, imageWidth=optnumber, fontSize=optstringfunc, control=optstring, dialogControl=optstring, dropdownControl=optstring, }, group={ args=istable, plugins=opttable, inline=optbool, cmdInline=optbool, guiInline=optbool, dropdownInline=optbool, dialogInline=optbool, childGroups=optstring, }, execute={ image=optstringnumberfunc, imageCoords=optmethodtable, imageHeight=optnumber, imageWidth=optnumber, control=optstring, dialogControl=optstring, dropdownControl=optstring, }, input={ pattern=optstring, usage=optstring, control=optstring, dialogControl=optstring, dropdownControl=optstring, multiline=optboolnumber, }, toggle={ tristate=optbool, image=optstringnumberfunc, imageCoords=optmethodtable, control=optstring, dialogControl=optstring, dropdownControl=optstring, }, tristate={ }, range={ min=optnumber, softMin=optnumber, max=optnumber, softMax=optnumber, step=optnumber, bigStep=optnumber, isPercent=optbool, control=optstring, dialogControl=optstring, dropdownControl=optstring, }, select={ values=ismethodtable, sorting=optmethodtable, style={ ["nil"]=true, ["string"]={dropdown=true,radio=true}, _="string: 'dropdown' or 'radio'" }, control=optstring, dialogControl=optstring, dropdownControl=optstring, itemControl=optstring, }, multiselect={ values=ismethodtable, style=optstring, tristate=optbool, control=optstring, dialogControl=optstring, dropdownControl=optstring, }, color={ hasAlpha=optmethodbool, control=optstring, dialogControl=optstring, dropdownControl=optstring, }, keybinding={ control=optstring, dialogControl=optstring, dropdownControl=optstring, }, } local function validateKey(k,errlvl,...) errlvl=(errlvl or 0)+1 if type(k)~="string" then err("["..tostring(k).."] - key is not a string", errlvl,...) end if strfind(k, "[%c\127]") then err("["..tostring(k).."] - key name contained control characters", errlvl,...) end end local function validateVal(v, oktypes, errlvl,...) errlvl=(errlvl or 0)+1 local isok=oktypes[type(v)] or oktypes["*"] if not isok then err(": expected a "..oktypes._..", got '"..tostring(v).."'", errlvl,...) end if type(isok)=="table" then -- isok was a table containing specific values to be tested for! if not isok[v] then err(": did not expect "..type(v).." value '"..tostring(v).."'", errlvl,...) end end end local function validate(options,errlvl,...) errlvl=(errlvl or 0)+1 -- basic consistency if type(options)~="table" then err(": expected a table, got a "..type(options), errlvl,...) end if type(options.type)~="string" then err(".type: expected a string, got a "..type(options.type), errlvl,...) end -- get type and 'typedkeys' member local tk = typedkeys[options.type] if not tk then err(".type: unknown type '"..options.type.."'", errlvl,...) end -- make sure that all options[] are known parameters for k,v in pairs(options) do if not (tk[k] or basekeys[k]) then err(": unknown parameter", errlvl,tostring(k),...) end end -- verify that required params are there, and that everything is the right type for k,oktypes in pairs(basekeys) do validateVal(options[k], oktypes, errlvl,k,...) end for k,oktypes in pairs(tk) do validateVal(options[k], oktypes, errlvl,k,...) end -- extra logic for groups if options.type=="group" then for k,v in pairs(options.args) do validateKey(k,errlvl,"args",...) validate(v, errlvl,k,"args",...) end if options.plugins then for plugname,plugin in pairs(options.plugins) do if type(plugin)~="table" then err(": expected a table, got '"..tostring(plugin).."'", errlvl,tostring(plugname),"plugins",...) end for k,v in pairs(plugin) do validateKey(k,errlvl,tostring(plugname),"plugins",...) validate(v, errlvl,k,tostring(plugname),"plugins",...) end end end end end --- Validates basic structure and integrity of an options table \\ -- Does NOT verify that get/set etc actually exist, since they can be defined at any depth -- @param options The table to be validated -- @param name The name of the table to be validated (shown in any error message) -- @param errlvl (optional number) error level offset, default 0 (=errors point to the function calling :ValidateOptionsTable) function AceConfigRegistry:ValidateOptionsTable(options,name,errlvl) errlvl=(errlvl or 0)+1 name = name or "Optionstable" if not options.name then options.name=name -- bit of a hack, the root level doesn't really need a .name :-/ end validate(options,errlvl,name) end --- Fires a "ConfigTableChange" callback for those listening in on it, allowing config GUIs to refresh. -- You should call this function if your options table changed from any outside event, like a game event -- or a timer. -- @param appName The application name as given to `:RegisterOptionsTable()` function AceConfigRegistry:NotifyChange(appName) if not AceConfigRegistry.tables[appName] then return end AceConfigRegistry.callbacks:Fire("ConfigTableChange", appName) end -- ------------------------------------------------------------------- -- Registering and retreiving options tables: -- validateGetterArgs: helper function for :GetOptionsTable (or, rather, the getter functions returned by it) local function validateGetterArgs(type, uiName, errlvl) errlvl=(errlvl or 0)+2 if type~="cmd" and type~="dropdown" and type~="dialog" then error(MAJOR..": Requesting options table: 'type' - invalid configuration UI type, expected 'cmd', 'dropdown' or 'dialog'", errlvl) end if not strmatch(uiName, "[A-Za-z]%-[0-9]") then -- Expecting e.g. "MyLib-1.2" error(MAJOR..": Requesting options table: 'uiName' - badly formatted or missing version number. Expected e.g. 'MyLib-1.2'", errlvl) end end --- Register an options table with the config registry. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param options The options table, OR a function reference that generates it on demand. \\ -- See the top of the page for info on arguments passed to such functions. -- @param skipValidation Skip options table validation (primarily useful for extremely huge options, with a noticeable slowdown) function AceConfigRegistry:RegisterOptionsTable(appName, options, skipValidation) if type(options)=="table" then if options.type~="group" then -- quick sanity checker error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - missing type='group' member in root group", 2) end AceConfigRegistry.tables[appName] = function(type, uiName, errlvl) errlvl=(errlvl or 0)+1 validateGetterArgs(type, uiName, errlvl) if not AceConfigRegistry.validated[type][appName] and not skipValidation then AceConfigRegistry:ValidateOptionsTable(options, appName, errlvl) -- upgradable AceConfigRegistry.validated[type][appName] = true end return options end elseif type(options)=="function" then AceConfigRegistry.tables[appName] = function(type, uiName, errlvl) errlvl=(errlvl or 0)+1 validateGetterArgs(type, uiName, errlvl) local tab = assert(options(type, uiName, appName)) if not AceConfigRegistry.validated[type][appName] and not skipValidation then AceConfigRegistry:ValidateOptionsTable(tab, appName, errlvl) -- upgradable AceConfigRegistry.validated[type][appName] = true end return tab end else error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - expected table or function reference", 2) end end --- Returns an iterator of ["appName"]=funcref pairs function AceConfigRegistry:IterateOptionsTables() return pairs(AceConfigRegistry.tables) end --- Query the registry for a specific options table. -- If only appName is given, a function is returned which you -- can call with (type,uiName) to get the table.\\ -- If type&uiName are given, the table is returned. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param type The type of UI to get the table for, one of "cmd", "dropdown", "dialog" -- @param uiName The name of the library/addon querying for the table, e.g. "MyLib-1.0" function AceConfigRegistry:GetOptionsTable(appName, type, uiName) local f = AceConfigRegistry.tables[appName] if not f then return nil end if type then return f(type,uiName,1) -- get the table for us else return f -- return the function end end
0
0.874905
1
0.874905
game-dev
MEDIA
0.401173
game-dev
0.920813
1
0.920813
rotators/fo2238
2,370
Server/scripts/map_redding_lost.fos
// // FOnline: 2238 // Rotators // // map_redding_lost.fos // #include "_macros.fos" #include "factions_h.fos" #include "mapdata_h.fos" #define TERMINAL_DIALOG (9060) #define COMPUTER_DIALOG (1334) uint FACTION = FACTION_REDDING_GUTTERSNIPES; import void ReddingAddElevators() from "map_redding_mine"; import void ReddingAddFloor(uint elev, uint mapid, uint entirenum) from "map_redding_mine"; import bool s_Terminal(Critter& player, Scenery& terminal, int skill, Item@ item) from "factions_terminal"; // // map.Data: // 0 - faction id // 1 - leader chosen (0-not chosen, 1-chosen) // // // Initialize map, and store The Redding Guttersnipes faction id // to be read by their terminal // void map_init(Map& map, bool firstTime) { if(firstTime) { // this map belongs to that faction map.SetData(MAP_DATA_FACTION, FACTION); // no leader yet map.SetData(MAP_DATA_LEADER, 0); } // assign event handlers map.SetEvent(MAP_EVENT_IN_CRITTER, "map_playerfaction_hq@_OnInCritter"); ReddingAddElevators(); uint16 x = 0, y = 0; if(map.GetEntireCoords(11, 0, x, y)) ReddingAddFloor(0, map.Id, 11); } // // Instead of calling factions_terminal, we will use that function // to assign first player who will find this terminal to that faction // bool s_Computer(Critter& player, Scenery& terminal, int skill, Item@ item) { if(!player.IsPlayer() || skill != -1 || valid(item)) return false; Map@ map = player.GetMap(); // run redding computer dialog if(map.GetData(MAP_DATA_LEADER) == 0) { RunDialog(player, COMPUTER_DIALOG, terminal.HexX, terminal.HexY, false); } // run normal terminal dialog else { s_Terminal(player, terminal, skill, item); } return true; } // // Just some hint for the player where to click // bool s_Desk(Critter& player, Scenery& terminal, int skill, Item@ item) { if(!player.IsPlayer() || skill != -1 || valid(item)) return false; player.Say(SAY_NETMSG, "Better check the computer"); return true; } // // This (called by computer dialog) will make player a leader // void r_Leader(Critter& player, Critter@ computer, int value) { AddMember(FACTION, player.Id); ChangeRank(FACTION, player.Id, RANK_LEADER); Map@ map = player.GetMap(); map.SetData(MAP_DATA_LEADER, 1); }
0
0.786523
1
0.786523
game-dev
MEDIA
0.96797
game-dev
0.92876
1
0.92876
bernardosulzbach/dungeon
3,604
src/main/java/org/mafagafogigante/dungeon/util/Percentage.java
package org.mafagafogigante.dungeon.util; import org.mafagafogigante.dungeon.io.Version; import org.mafagafogigante.dungeon.logging.DungeonLogger; import org.jetbrains.annotations.NotNull; import java.io.Serializable; import java.util.Locale; /** * A class that represents a percentage value between 0.0% and 100.00%. */ public class Percentage implements Comparable<Percentage>, Serializable { private static final long serialVersionUID = Version.MAJOR; private static final double ONE = 1.0; private static final double ZERO = 0.0; private final double value; /** * Constructs a percentage from a double between 0 and 1. */ public Percentage(double percentage) { if (DungeonMath.fuzzyCompare(percentage, ZERO) < 0) { value = ZERO; DungeonLogger.warning("Tried to use " + percentage + " as a percentage. Used " + ZERO + " instead."); } else if (DungeonMath.fuzzyCompare(percentage, ONE) > 0) { value = ONE; DungeonLogger.warning("Tried to use " + percentage + " as a percentage. Used " + ONE + " instead."); } else { value = percentage; } } /** * Creates a Percentage object from a String representation of a Percentage. * * <p>Percentage.isValidPercentageString(String) should return true to the provided String. * * @param percentage the String representation of a valid percentage * @return a Percentage object */ public static Percentage fromString(String percentage) { if (!isValidPercentageString(percentage)) { throw new IllegalArgumentException("Provided String is not a valid percentage: " + percentage + "!"); } return new Percentage(doubleFromPercentageString(percentage)); } /** * Checks if a String is a valid percentage string. */ public static boolean isValidPercentageString(String percentage) { if (percentage != null) { try { return isValidPercentageDouble(doubleFromPercentageString(percentage)); } catch (NumberFormatException e) { // Fall to false. } } return false; } private static double doubleFromPercentageString(String percentage) { return Double.parseDouble(trimAndDiscardLastCharacter(percentage)) / 100; } private static boolean isValidPercentageDouble(double value) { return DungeonMath.fuzzyCompare(value, ZERO) >= 0 && DungeonMath.fuzzyCompare(value, ONE) <= 0; } private static String trimAndDiscardLastCharacter(String string) { String trimmed = string.trim(); return trimmed.substring(0, trimmed.length() - 1); } public double toDouble() { return value; } public Percentage add(Percentage extraProficiency) { return new Percentage(Math.min(value + extraProficiency.value, ONE)); } public Percentage multiply(Percentage percentage) { return new Percentage(toDouble() * percentage.toDouble()); } @Override public int compareTo(@NotNull Percentage percentage) { return DungeonMath.fuzzyCompare(toDouble(), percentage.toDouble()); } boolean biggerThanOrEqualTo(Percentage percentage) { return compareTo(percentage) >= 0; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } return compareTo((Percentage) object) == 0; } @Override public int hashCode() { long temp = Double.doubleToLongBits(value); return (int) (temp ^ (temp >>> 32)); } @Override public String toString() { return String.format(Locale.ENGLISH, "%.2f%%", value * 100); } }
0
0.788124
1
0.788124
game-dev
MEDIA
0.318287
game-dev
0.875966
1
0.875966
Potion-Studios/BYG
2,967
Common/src/main/java/potionstudios/byg/common/block/end/StoneEndPlantBlock.java
package potionstudios.byg.common.block.end; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BushBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.NotNull; import potionstudios.byg.common.block.BYGBlocks; public class StoneEndPlantBlock extends BushBlock { protected static final VoxelShape SHAPE = Block.box(5.0D, 0.0D, 5.0D, 11.0D, 10.0D, 11.0D); public StoneEndPlantBlock(Properties builder) { super(builder); } public OffsetType getOffsetType() { return OffsetType.XZ; } public @NotNull VoxelShape getShape(BlockState state, @NotNull BlockGetter reader, @NotNull BlockPos map, @NotNull CollisionContext ctx) { Vec3 Vector3d = state.getOffset(reader, map); return SHAPE.move(Vector3d.x, Vector3d.y, Vector3d.z); } @Override public void randomTick(@NotNull BlockState state, @NotNull ServerLevel worldIn, @NotNull BlockPos pos, RandomSource random) { if (random.nextInt(25) == 0) { int i = 5; for(BlockPos blockpos : BlockPos.betweenClosed(pos.offset(-4, -1, -4), pos.offset(4, 1, 4))) { if (worldIn.getBlockState(blockpos).is(this)) { --i; if (i <= 0) { return; } } } BlockPos blockpos1 = pos.offset(random.nextInt(3) - 1, random.nextInt(2) - random.nextInt(2), random.nextInt(3) - 1); for(int k = 0; k < 4; ++k) { if (worldIn.isEmptyBlock(blockpos1) && state.canSurvive(worldIn, blockpos1)) { pos = blockpos1; } blockpos1 = pos.offset(random.nextInt(3) - 1, random.nextInt(2) - random.nextInt(2), random.nextInt(3) - 1); } if (worldIn.isEmptyBlock(blockpos1) && state.canSurvive(worldIn, blockpos1)) { worldIn.setBlock(blockpos1, state, 2); } } } @Override protected boolean mayPlaceOn(BlockState state, @NotNull BlockGetter worldIn, @NotNull BlockPos pos) { return state.is(BYGBlocks.CRYPTIC_MAGMA_BLOCK.get()) || state.is(BYGBlocks.CRYPTIC_STONE.get()) || state.is(BYGBlocks.CRYPTIC_REDSTONE_ORE.get()) || super.mayPlaceOn(state, worldIn, pos); } @Override public boolean canSurvive(@NotNull BlockState state, @NotNull LevelReader worldIn, BlockPos pos) { BlockPos blockpos = pos.below(); return this.mayPlaceOn(worldIn.getBlockState(blockpos), worldIn, blockpos); } }
0
0.888958
1
0.888958
game-dev
MEDIA
0.995458
game-dev
0.889471
1
0.889471
trapexit/bbf
1,484
src/bbf_file_blocks.cpp
/* ISC License Copyright (c) 2016, Antonio SJ Musumeci <trapexit@spawn.link> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "errors.hpp" #include "file.hpp" #include "options.hpp" #include <iostream> #include <utility> #include <stdint.h> namespace bbf { AppError file_blocks(const Options &opts_) { int rv; File::BlockVector blockvector; rv = File::blocks(opts_.device,blockvector); if(rv < 0) return AppError::opening_file(-rv,opts_.device); for(uint64_t i = 0, ei = blockvector.size(); i != ei; i++) { uint64_t j = blockvector[i].block; const uint64_t ej = blockvector[i].length + j; for(; j != ej; j++) { std::cout << j << std::endl; } } return AppError::success(); } }
0
0.83182
1
0.83182
game-dev
MEDIA
0.078865
game-dev
0.658722
1
0.658722
cmangos/mangos-classic
10,156
src/game/BattleGround/BattleGroundWS.h
/* * This file is part of the CMaNGOS 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 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 */ #ifndef __BATTLEGROUNDWS_H #define __BATTLEGROUNDWS_H #include "BattleGround.h" #include "Tools/Language.h" class BattleGround; enum WSTimers { BG_WS_MAX_TEAM_SCORE = 3, BG_WS_FLAG_RESPAWN_TIME = 23 * IN_MILLISECONDS, BG_WS_FLAG_DROP_TIME = 10 * IN_MILLISECONDS, }; enum WSVariables { BG_WS_NORMAL_FLAG_CAPTURE_REPUTATION = 35, BG_WS_WEEKEND_FLAG_CAPTURE_REPUTATION = 45, BG_WS_NORMAL_WIN_KILLS = 1, BG_WS_WEEKEND_WIN_KILLS = 3, BG_WS_NORMAL_MAP_COMPLETE_KILLS = 2, BG_WS_WEEKEND_MAP_COMPLETE_KILLS = 4 }; enum WSSounds { BG_WS_SOUND_FLAG_CAPTURED_ALLIANCE = 8173, BG_WS_SOUND_FLAG_CAPTURED_HORDE = 8213, BG_WS_SOUND_FLAG_PLACED = 8232, BG_WS_SOUND_FLAG_RETURNED = 8192, BG_WS_SOUND_HORDE_FLAG_PICKED_UP = 8212, BG_WS_SOUND_ALLIANCE_FLAG_PICKED_UP = 8174, BG_WS_SOUND_FLAGS_RESPAWNED = 8232 }; enum WSSpells { BG_WS_SPELL_WARSONG_FLAG = 23333, BG_WS_SPELL_WARSONG_FLAG_DROPPED = 23334, BG_WS_SPELL_SILVERWING_FLAG = 23335, BG_WS_SPELL_SILVERWING_FLAG_DROPPED = 23336 }; enum WSWorldStates { BG_WS_STATE_FLAG_PICKED_UP_FLAG_STATE_ALLIANCE = 1545, BG_WS_STATE_FLAG_PICKED_UP_FLAG_STATE_HORDE = 1546, // FLAG_UNK = 1547, BG_WS_STATE_CAPTURES_ALLIANCE = 1581, // count the flag captures for each team BG_WS_STATE_CAPTURES_HORDE = 1582, BG_WS_STATE_CAPTURES_MAX = 1601, // shows the max allowed flags BG_WS_STATE_FLAG_HORDE = 2338, // shows who captured the current flag BG_WS_STATE_FLAG_ALLIANCE = 2339, }; enum WSFlagActions { BG_WS_FLAG_ACTION_NONE = -1, BG_WS_FLAG_ACTION_PICKEDUP = 0, BG_WS_FLAG_ACTION_RETURNED = 1, BG_WS_FLAG_ACTION_DROPPED = 2, BG_WS_FLAG_ACTION_CAPTURED = 3, BG_WS_FLAG_ACTION_RESPAWN = 4, BG_WS_FLAG_ACTIONS_TOTAL = 5, }; enum WSPickedUpFlagStates { BG_WS_FLAG_STATE_ON_BASE = 0, BG_WS_FLAG_STATE_ON_PLAYER = 1, BG_WS_FLAG_STATE_ON_GROUND = -1 }; enum WSFlagIconStates { BG_WS_FLAG_ICON_INACTIVE = 0, BG_WS_FLAG_ICON_INVISIBLE = 1, BG_WS_FLAG_ICON_VISIBLE = 2, }; enum WSGraveyards { WS_GRAVEYARD_FLAGROOM_ALLIANCE = 769, WS_GRAVEYARD_FLAGROOM_HORDE = 770, WS_GRAVEYARD_MAIN_ALLIANCE = 771, WS_GRAVEYARD_MAIN_HORDE = 772, BG_WS_ZONE_ID_MAIN = 3277, }; enum WSEventIds { WS_EVENT_ALLIANCE_FLAG_PICKUP = 8504, // triggered from flag events - source player, target go WS_EVENT_HORDE_FLAG_PICKUP = 8505, WS_EVENT_ALLIANCE_FLAG_DROP = 8506, // not used; events used for flag handling; triggered from spell WS_EVENT_HORDE_FLAG_DROP = 8507, WS_EVENT_ALLIANCE_FLAG_DROPPED_PICKUP = 8623, WS_EVENT_HORDE_FLAG_DROPPED_PICKUP = 8624, }; enum WSGameObjects { GO_WS_SILVERWING_FLAG = 179830, GO_WS_WARSONG_FLAG = 179831, GO_WS_SILVERWING_FLAG_DROP = 179785, // temp summoned objects when main flag is dropped GO_WS_WARSONG_FLAG_DROP = 179786, }; enum WSAreaTriggers { WS_AT_SILVERWING_ROOM = 3646, WS_AT_WARSONG_ROOM = 3647, }; enum WSScriptEvents { WS_EVENT_FLAG_A = 0, WS_EVENT_FLAG_H = 1, // spiritguides will spawn (same moment, like WS_EVENT_DOOR_OPEN) WS_EVENT_SPIRITGUIDES_SPAWN = 2 }; static const uint32 wsFlagPickedUp[PVP_TEAM_COUNT] = { BG_WS_STATE_FLAG_PICKED_UP_FLAG_STATE_ALLIANCE, BG_WS_STATE_FLAG_PICKED_UP_FLAG_STATE_HORDE }; static const uint32 wsFlagHUDPickedUp[PVP_TEAM_COUNT] = { BG_WS_STATE_FLAG_ALLIANCE, BG_WS_STATE_FLAG_HORDE }; static const uint32 wsDroppedFlagId[PVP_TEAM_COUNT] = { GO_WS_SILVERWING_FLAG_DROP, GO_WS_WARSONG_FLAG_DROP }; struct WarsongData { uint8 flagAction; uint32 messageId, soundId, spellId; ChatMsg chatType; }; // *** Battleground flag data *** // static const WarsongData wsgFlagData[PVP_TEAM_COUNT][BG_WS_FLAG_ACTIONS_TOTAL] = { { {BG_WS_FLAG_ACTION_PICKEDUP, LANG_BG_WS_PICKEDUP_AF, BG_WS_SOUND_ALLIANCE_FLAG_PICKED_UP, BG_WS_SPELL_SILVERWING_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE}, {BG_WS_FLAG_ACTION_RETURNED, LANG_BG_WS_RETURNED_AF, BG_WS_SOUND_FLAG_RETURNED, BG_WS_SPELL_SILVERWING_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE}, {BG_WS_FLAG_ACTION_DROPPED, LANG_BG_WS_DROPPED_AF, 0, BG_WS_SPELL_SILVERWING_FLAG_DROPPED, CHAT_MSG_BG_SYSTEM_ALLIANCE}, {BG_WS_FLAG_ACTION_CAPTURED, LANG_BG_WS_CAPTURED_AF, BG_WS_SOUND_FLAG_CAPTURED_ALLIANCE, 0, CHAT_MSG_BG_SYSTEM_ALLIANCE}, {BG_WS_FLAG_ACTION_RESPAWN, LANG_BG_WS_ALLIANCE_FLAG_RESPAWNED, BG_WS_SOUND_FLAGS_RESPAWNED, 0, CHAT_MSG_BG_SYSTEM_NEUTRAL}, }, { {BG_WS_FLAG_ACTION_PICKEDUP, LANG_BG_WS_PICKEDUP_HF, BG_WS_SOUND_HORDE_FLAG_PICKED_UP, BG_WS_SPELL_WARSONG_FLAG, CHAT_MSG_BG_SYSTEM_HORDE}, {BG_WS_FLAG_ACTION_RETURNED, LANG_BG_WS_RETURNED_HF, BG_WS_SOUND_FLAG_RETURNED, BG_WS_SPELL_WARSONG_FLAG, CHAT_MSG_BG_SYSTEM_HORDE}, {BG_WS_FLAG_ACTION_DROPPED, LANG_BG_WS_DROPPED_HF, 0, BG_WS_SPELL_WARSONG_FLAG_DROPPED, CHAT_MSG_BG_SYSTEM_HORDE}, {BG_WS_FLAG_ACTION_CAPTURED, LANG_BG_WS_CAPTURED_HF, BG_WS_SOUND_FLAG_CAPTURED_HORDE, 0, CHAT_MSG_BG_SYSTEM_HORDE}, {BG_WS_FLAG_ACTION_RESPAWN, LANG_BG_WS_HORDE_FLAG_RESPAWNED, BG_WS_SOUND_FLAGS_RESPAWNED, 0, CHAT_MSG_BG_SYSTEM_NEUTRAL}, } }; class BattleGroundWGScore : public BattleGroundScore { public: BattleGroundWGScore() : flagCaptures(0), flagReturns(0) {}; virtual ~BattleGroundWGScore() {}; uint32 GetAttr1() const override { return flagCaptures; } uint32 GetAttr2() const override { return flagReturns; } uint32 flagCaptures; uint32 flagReturns; }; // Honor granted depending on player's level const uint32 BG_WSG_FlagCapturedHonor[MAX_BATTLEGROUND_BRACKETS] = {48, 82, 136, 226, 378, 396}; const uint32 BG_WSG_WinMatchHonor[MAX_BATTLEGROUND_BRACKETS] = {24, 41, 68, 113, 189, 198}; class BattleGroundWS : public BattleGround { friend class BattleGroundMgr; public: BattleGroundWS(); void Reset() override; void Update(uint32 diff) override; // Main battleground functions void AddPlayer(Player* player) override; void RemovePlayer(Player* player, ObjectGuid guid) override; void StartingEventOpenDoors() override; void EndBattleGround(Team winner) override; // General functions void UpdatePlayerScore(Player* source, uint32 type, uint32 value) override; Team GetPrematureWinner() override; // Battleground event handlers bool HandleEvent(uint32 eventId, Object* source, Object* target) override; bool HandleAreaTrigger(Player* source, uint32 trigger) override; void HandleGameObjectCreate(GameObject* go) override; void HandleKillPlayer(Player* player, Player* killer) override; void HandlePlayerClickedOnFlag(Player* source, GameObject* go) override; void HandlePlayerDroppedFlag(Player* source) override; // Flag handler ObjectGuid const& GetFlagCarrierGuid(uint8 teamIdx) const { return m_flagCarrier[teamIdx]; } private: // Flag Carrier functions void SetFlagCarrier(uint8 teamIdx, ObjectGuid guid) { m_flagCarrier[teamIdx] = guid; } void ClearFlagCarrier(uint8 teamIdx) { m_flagCarrier[teamIdx].Clear(); } bool IsFlagPickedUp(uint8 teamIdx) const { return !m_flagCarrier[teamIdx].IsEmpty(); } // Flag interactions void ClearDroppedFlagGuid(Team team) { m_droppedFlagGuid[GetTeamIndexByTeamId(team)].Clear();} ObjectGuid const& GetDroppedFlagGuid(Team team) const { return m_droppedFlagGuid[GetTeamIndexByTeamId(team)];} void RespawnFlagAtBase(Team team, bool wasCaptured); void RespawnDroppedFlag(Team team); int32 GetFlagState(Team team); void ProcessFlagPickUpFromBase(Player* player, Team attackerTeam); void ProcessDroppedFlagActions(Player* player, GameObject* target); // process score void ProcessPlayerFlagScoreEvent(Player* source); ObjectGuid m_droppedFlagGuid[PVP_TEAM_COUNT]; ObjectGuid m_flagCarrier[PVP_TEAM_COUNT]; bool m_flagOnRespawn[PVP_TEAM_COUNT]; uint32 m_flagsTimer[PVP_TEAM_COUNT]; uint32 m_flagsDropTimer[PVP_TEAM_COUNT]; uint32 m_reputationCapture; uint32 m_honorWinKills; uint32 m_honorEndKills; Team m_lastCapturedFlagTeam; }; #endif
0
0.696748
1
0.696748
game-dev
MEDIA
0.968624
game-dev
0.511444
1
0.511444
keepcalm/BukkitForge
1,665
src/org/bukkit/command/defaults/KillCommand.java
package org.bukkit.command.defaults; import java.util.List; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent; import com.google.common.collect.ImmutableList; public class KillCommand extends VanillaCommand { public KillCommand() { super("kill"); this.description = "Commits suicide, only usable as a player"; this.usageMessage = "/kill"; this.setPermission("bukkit.command.kill"); } @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (sender instanceof Player) { Player player = (Player) sender; EntityDamageEvent ede = new EntityDamageEvent(player, EntityDamageEvent.DamageCause.SUICIDE, 1000); Bukkit.getPluginManager().callEvent(ede); if (ede.isCancelled()) return true; ede.getEntity().setLastDamageCause(ede); player.setHealth(0); sender.sendMessage("Ouch. That look like it hurt."); } else { sender.sendMessage("You can only perform this command as a player"); } return true; } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { Validate.notNull(sender, "Sender cannot be null"); Validate.notNull(args, "Arguments cannot be null"); Validate.notNull(alias, "Alias cannot be null"); return ImmutableList.of(); } }
0
0.858526
1
0.858526
game-dev
MEDIA
0.974064
game-dev
0.909969
1
0.909969
Avatarchik/Pixel-PUBG
3,643
Assets/Game/Scripts/Item/Components/ItemStocker.cs
using UnityEngine; using System.Collections; using UnityEngine.Networking; [RequireComponent(typeof(NetworkIdentity))] [RequireComponent(typeof(CharacterInventory))] public class ItemStocker : NetworkBehaviour { public string StockID = "mybox"; public CharacterInventory inventory; private int updateTemp = 0; private bool stockLoaded = false; private ObjectPlacing placing; public float DistanceLimit = 2; public Vector3 Offset; public string ActiveText = "Interactive"; private CharacterSystem characterTemp; [SyncVar(hook = "OnStockChanged")] public string DataText = ""; public bool AddStarterItem; public bool DestroyIfEmpty = false; public float DestroyDelay = 1; void Start() { inventory = this.GetComponent<CharacterInventory>(); placing = this.GetComponent<ObjectPlacing>(); if (placing) { StockID = placing.ItemUID; } else { stockLoaded = true; } if (isServer) LoadStock(); if (AddStarterItem) { if (inventory) inventory.SetupStarterItem(); } } void OnStockChanged(string datatext) { DataText = datatext; GetUpdateStock(); } public void OpenStock() { GetUpdateStock(); } void Update() { if (inventory == null) return; if (isServer && updateTemp != inventory.UpdateCount && stockLoaded) { UpdateStock(); SaveStock(); updateTemp = inventory.UpdateCount; } if (characterTemp) { if (Vector3.Distance(this.transform.position, characterTemp.transform.position + Offset) > DistanceLimit) { OnExit(); } else { OnStay(); } } if (DestroyIfEmpty) { if (inventory.Items.Count <= 0) { Destroy(this.gameObject, DestroyDelay); } } } public void Pickup(CharacterSystem character) { character.SendMessage("PickupStockCallback", this); } public void PickUpStock(CharacterSystem character) { if (character && character.IsMine) { character.inventory.PeerTrade = inventory; OpenStock(); UnitZ.Hud.OpenSecondInventory(inventory, "Stock"); } characterTemp = character; } void SaveStock() { if (inventory == null || placing == null) return; DataText = inventory.GetItemDataText(); PlayerPrefs.SetString(StockID, DataText); } void LoadStock() { if (inventory == null || placing == null) return; if (PlayerPrefs.HasKey(StockID)) { inventory.SetItemsFromText(PlayerPrefs.GetString(StockID)); stockLoaded = true; } else { stockLoaded = true; SaveStock(); } } void UpdateStock() { if (isServer) { DataText = inventory.GetItemDataText(); } } public void GetUpdateStock() { inventory.SetItemsFromText(DataText); } public void OnStay() { } public void OnExit() { UnitZ.Hud.CloseSecondInventory(); characterTemp.inventory.PeerTrade = null; characterTemp = null; } public void GetInfo() { UnitZ.Hud.ShowInfo(ActiveText,this.transform.position); } }
0
0.855391
1
0.855391
game-dev
MEDIA
0.9049
game-dev
0.816375
1
0.816375
ImpactDevelopment/ClientAPI
4,020
src/main/java/clientapi/util/BlockUtils.java
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.util; import clientapi.util.interfaces.MinecraftAccessible; import clientapi.util.math.Vec3; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import java.util.Objects; /** * Generic Block Utils * * @author Brady * @since 2/24/2017 */ public final class BlockUtils implements MinecraftAccessible { private BlockUtils() {} /** * Gets the block at the specified coordinates * * @param x The x position of the block * @param y The y position of the block * @param z The z position of the block * @return The block, returns null if the world isn't initialized */ public static Block getBlock(int x, int y, int z) { return getBlock(new BlockPos(x, y, z)); } /** * Gets the block at the specified coordinates * * @param x The x position of the block * @param y The y position of the block * @param z The z position of the block * @return The block, returns null if the world isn't initialized */ public static Block getBlock(double x, double y, double z) { return getBlock(new BlockPos(x, y, z)); } /** * Gets the block at the coordinates of the specified {@link Vec3} * * @param vec The vector position * @return The block, returns null if the world isn't initialized */ public static Block getBlock(Vec3 vec) { Objects.requireNonNull(vec); return getBlock(new BlockPos(vec.getX(), vec.getY(), vec.getZ())); } /** * Gets the block at the specified {@link BlockPos} * * @param pos The position of the block * @return The block, returns null if the world isn't initialized */ public static Block getBlock(BlockPos pos) { return mc.world == null ? null : mc.world.getBlockState(pos).getBlock(); } /** * Gets the first block colliding with the * bounding box of the specified entity. * * @param e The entity * @return The block, returns null if the world isn't initialized */ public static Block getBlock(Entity e) { return getBlock(e.getEntityBoundingBox()); } /** * Gets the first block colliding with the offset * bounding box of the specified entity. * * @param e The entity * @param offset The bounding box offset applied * @return The block, returns null if the world isn't initialized */ public static Block getBlock(Entity e, Vec3 offset) { return getBlock(e.getEntityBoundingBox().offset(offset.getX(), offset.getY(), offset.getZ())); } /** * Gets the first block that collides with the * specified bounding box. * * @param bb The bounding box * @return The block, returns null if the world isn't initialized */ public static Block getBlock(AxisAlignedBB bb) { int y = (int) bb.minY; for (int x = (int) Math.floor(bb.minX); x < (int) Math.floor(bb.maxX) + 1; x++) { for (int z = (int) Math.floor(bb.minZ); z < (int) Math.floor(bb.maxZ) + 1; z++) { Block block = getBlock(new BlockPos(x, y, z)); if (block != Blocks.AIR) { return block; } } } return null; } }
0
0.910325
1
0.910325
game-dev
MEDIA
0.864833
game-dev
0.872756
1
0.872756
rustyscreeps/screeps-game-api
1,150
src/objects/impls/structure_road.rs
use wasm_bindgen::prelude::*; use crate::{ objects::{RoomObject, Structure}, prelude::*, }; #[wasm_bindgen] extern "C" { /// An object representing a [`StructureRoad`], which allows creeps to move /// onto this position for half of the fatigue of moving onto a plains tile, /// as well as through terrain walls. /// /// [Screeps documentation](https://docs.screeps.com/api/#StructureRoad) #[wasm_bindgen(extends = RoomObject, extends = Structure)] #[derive(Clone, Debug)] pub type StructureRoad; /// The number of ticks until the road will decay, losing /// [`ROAD_DECAY_AMOUNT`] hits. /// /// [Screeps documentation](https://docs.screeps.com/api/#StructureRoad.ticksToDecay) /// /// [`ROAD_DECAY_AMOUNT`]: crate::constants::ROAD_DECAY_AMOUNT #[wasm_bindgen(method, getter = ticksToDecay)] pub fn ticks_to_decay(this: &StructureRoad) -> u32; } impl CanDecay for StructureRoad { fn ticks_to_decay(&self) -> u32 { Self::ticks_to_decay(self) } } impl Attackable for StructureRoad {} impl Dismantleable for StructureRoad {} impl Repairable for StructureRoad {}
0
0.802864
1
0.802864
game-dev
MEDIA
0.929315
game-dev
0.928175
1
0.928175
liyunfan1223/mod-playerbots
9,868
src/strategy/actions/ListSpellsAction.cpp
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license, you may redistribute it * and/or modify it under version 3 of the License, or (at your option), any later version. */ #include "ListSpellsAction.h" #include "Event.h" #include "Playerbots.h" std::map<uint32, SkillLineAbilityEntry const*> ListSpellsAction::skillSpells; std::set<uint32> ListSpellsAction::vendorItems; bool CompareSpells(const std::pair<uint32, std::string>& s1, const std::pair<uint32, std::string>& s2) { SpellInfo const* si1 = sSpellMgr->GetSpellInfo(s1.first); SpellInfo const* si2 = sSpellMgr->GetSpellInfo(s2.first); if (!si1 || !si2) { LOG_ERROR("playerbots", "SpellInfo missing. {} {}", s1.first, s2.first); return false; } uint32 p1 = si1->SchoolMask * 20000; uint32 p2 = si2->SchoolMask * 20000; uint32 skill1 = 0, skill2 = 0; uint32 skillValue1 = 0, skillValue2 = 0; for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) { if (SkillLineAbilityEntry const* skillLine = sSkillLineAbilityStore.LookupEntry(j)) { if (skillLine->Spell == s1.first) { skill1 = skillLine->SkillLine; skillValue1 = skillLine->TrivialSkillLineRankLow; } if (skillLine->Spell == s2.first) { skill2 = skillLine->SkillLine; skillValue2 = skillLine->TrivialSkillLineRankLow; } } if (skill1 && skill2) break; } p1 += skill1 * 500; p2 += skill2 * 500; p1 += skillValue1; p2 += skillValue2; if (p1 == p2) { return strcmp(si1->SpellName[0], si2->SpellName[0]) > 0; } return p1 > p2; } std::vector<std::pair<uint32, std::string>> ListSpellsAction::GetSpellList(std::string filter) { if (skillSpells.empty()) { for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) { if (SkillLineAbilityEntry const* skillLine = sSkillLineAbilityStore.LookupEntry(j)) skillSpells[skillLine->Spell] = skillLine; } } if (vendorItems.empty()) { QueryResult results = WorldDatabase.Query("SELECT item FROM npc_vendor WHERE maxcount = 0"); if (results) { do { Field* fields = results->Fetch(); int32 entry = fields[0].Get<int32>(); if (entry <= 0) continue; vendorItems.insert(entry); } while (results->NextRow()); } } std::ostringstream posOut; std::ostringstream negOut; uint32 skill = 0; std::vector<std::string> ss = split(filter, ' '); if (!ss.empty()) { skill = chat->parseSkill(ss[0]); if (skill != SKILL_NONE) { filter = ss.size() > 1 ? filter = ss[1] : ""; } if (ss[0] == "first" && ss[1] == "aid") { skill = SKILL_FIRST_AID; filter = ss.size() > 2 ? filter = ss[2] : ""; } } std::string const ignoreList = ",Opening,Closing,Stuck,Remove Insignia,Opening - No Text,Grovel,Duel,Honorless Target,"; std::string alreadySeenList = ","; uint32 minLevel = 0; uint32 maxLevel = 0; if (filter.find("-") != std::string::npos) { std::vector<std::string> ff = split(filter, '-'); minLevel = atoi(ff[0].c_str()); maxLevel = atoi(ff[1].c_str()); filter = ""; } bool craftableOnly = false; if (filter.find("+") != std::string::npos) { craftableOnly = true; filter.erase(remove(filter.begin(), filter.end(), '+'), filter.end()); } uint32 slot = chat->parseSlot(filter); if (slot != EQUIPMENT_SLOT_END) filter = ""; std::vector<std::pair<uint32, std::string>> spells; for (PlayerSpellMap::iterator itr = bot->GetSpellMap().begin(); itr != bot->GetSpellMap().end(); ++itr) { if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->Active) continue; if (!(itr->second->specMask & bot->GetActiveSpecMask())) continue; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); if (!spellInfo) continue; if (spellInfo->IsPassive()) continue; SkillLineAbilityEntry const* skillLine = skillSpells[itr->first]; if (skill != SKILL_NONE && (!skillLine || skillLine->SkillLine != skill)) continue; std::string const comp = spellInfo->SpellName[0]; if (!(ignoreList.find(comp) == std::string::npos && alreadySeenList.find(comp) == std::string::npos)) continue; if (!filter.empty() && !strstri(spellInfo->SpellName[0], filter.c_str())) continue; bool first = true; int32 craftCount = -1; std::ostringstream materials; for (uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x) { if (spellInfo->Reagent[x] <= 0) { continue; } uint32 itemid = spellInfo->Reagent[x]; uint32 reagentsRequired = spellInfo->ReagentCount[x]; if (itemid) { if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemid)) { if (first) { materials << ": "; first = false; } else materials << ", "; materials << chat->FormatItem(proto, reagentsRequired); FindItemByIdVisitor visitor(itemid); uint32 reagentsInInventory = InventoryAction::GetItemCount(&visitor); bool buyable = (vendorItems.find(itemid) != vendorItems.end()); if (!buyable) { uint32 craftable = reagentsInInventory / reagentsRequired; if (craftCount < 0 || craftCount > craftable) craftCount = craftable; } if (reagentsInInventory) materials << "|cffffff00(x" << reagentsInInventory << ")|r "; else if (buyable) materials << "|cffffff00(buy)|r "; } } } if (craftCount < 0) craftCount = 0; std::ostringstream out; bool filtered = false; if (skillLine) { for (uint8 i = 0; i < 3; ++i) { if (spellInfo->Effects[i].Effect == SPELL_EFFECT_CREATE_ITEM) { if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(spellInfo->Effects[i].ItemType)) { if (craftCount) out << "|cffffff00(x" << craftCount << ")|r "; out << chat->FormatItem(proto); if ((minLevel || maxLevel) && (!proto->RequiredLevel || proto->RequiredLevel < minLevel || proto->RequiredLevel > maxLevel)) { filtered = true; break; } if (slot != EQUIPMENT_SLOT_END && bot->FindEquipSlot(proto, slot, true) != slot) { filtered = true; break; } } } } } if (out.str().empty()) out << chat->FormatSpell(spellInfo); if (filtered) continue; if (craftableOnly && !craftCount) continue; out << materials.str(); if (skillLine && skillLine->SkillLine) { uint32 GrayLevel = skillLine->TrivialSkillLineRankHigh; uint32 GreenLevel = (skillLine->TrivialSkillLineRankHigh + skillLine->MinSkillLineRank) / 2; uint32 YellowLevel = skillLine->MinSkillLineRank; uint32 SkillValue = bot->GetSkillValue(skillLine->SkillLine); out << " - "; if (SkillValue >= GrayLevel) out << " |cff808080gray"; else if (SkillValue >= GreenLevel) out << " |cff80be80green"; else if (SkillValue >= YellowLevel) out << " |cffffff00yellow"; else out << " |cffff8040orange"; out << "|r"; } if (out.str().empty()) continue; if (itr->first == 0) { LOG_ERROR("playerbots", "?! {}", itr->first); } spells.push_back(std::pair<uint32, std::string>(itr->first, out.str())); alreadySeenList += spellInfo->SpellName[0]; alreadySeenList += ","; } return spells; } bool ListSpellsAction::Execute(Event event) { Player* master = GetMaster(); if (!master) return false; std::string const filter = event.getParam(); std::vector<std::pair<uint32, std::string>> spells = GetSpellList(filter); botAI->TellMaster("=== Spells ==="); std::sort(spells.begin(), spells.end(), CompareSpells); uint32 count = 0; for (std::vector<std::pair<uint32, std::string>>::iterator i = spells.begin(); i != spells.end(); ++i) { botAI->TellMasterNoFacing(i->second); // if (++count >= 50) // { // std::ostringstream msg; // msg << (spells.size() - 50) << " more..."; // botAI->TellMasterNoFacing(msg.str()); // break; // } } return true; }
0
0.856122
1
0.856122
game-dev
MEDIA
0.721041
game-dev
0.981894
1
0.981894
ldtteam/minecolonies
11,324
src/main/java/com/minecolonies/core/generation/defaults/DefaultEntityLootProvider.java
package com.minecolonies.core.generation.defaults; import com.minecolonies.api.entity.ModEntities; import com.minecolonies.api.items.ModItems; import com.minecolonies.core.generation.SimpleLootTableProvider; import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Items; import net.minecraft.world.level.storage.loot.LootPool; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.entries.EmptyLootItem; import net.minecraft.world.level.storage.loot.entries.LootItem; import net.minecraft.world.level.storage.loot.functions.LootingEnchantFunction; import net.minecraft.world.level.storage.loot.functions.SetItemCountFunction; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator; import net.minecraftforge.registries.ForgeRegistries; import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; /** * Loot table generator for entities */ public class DefaultEntityLootProvider extends SimpleLootTableProvider { public DefaultEntityLootProvider(@NotNull PackOutput packOutput) { super(packOutput); } @NotNull @Override public String getName() { return "Entity Loot Table Provider"; } @Override protected void registerTables(@NotNull final LootTableRegistrar registrar) { registerLoot(registrar, ModEntities.AMAZON, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.BOW).setWeight(15)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.AMAZONSPEARMAN, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(ModItems.spear).setWeight(15)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.AMAZONCHIEF, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.BOW).setWeight(80)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(30))); registerLoot(registrar, ModEntities.BARBARIAN, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.DIAMOND_AXE).setWeight(1)) .add(LootItem.lootTableItem(Items.GOLDEN_AXE).setWeight(2)) .add(LootItem.lootTableItem(Items.IRON_AXE).setWeight(5)) .add(LootItem.lootTableItem(Items.STONE_AXE).setWeight(6)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(3))); registerLoot(registrar, ModEntities.ARCHERBARBARIAN, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.BOW).setWeight(10)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.CHIEFBARBARIAN, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(50)) .add(LootItem.lootTableItem(ModItems.chiefSword).setWeight(1).setQuality(1)) .add(LootItem.lootTableItem(Items.DIAMOND_SWORD).setWeight(5)) .add(LootItem.lootTableItem(Items.GOLDEN_SWORD).setWeight(5)) .add(LootItem.lootTableItem(Items.IRON_SWORD).setWeight(10)) .add(LootItem.lootTableItem(Items.STONE_SWORD).setWeight(20)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(30))); registerLoot(registrar, ModEntities.SHIELDMAIDEN, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.SHIELD).setWeight(10)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.NORSEMEN_ARCHER, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.BOW).setWeight(10)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.NORSEMEN_CHIEF, builder -> builder .setRolls(ConstantValue.exactly(2)) .add(EmptyLootItem.emptyItem().setWeight(50)) .add(LootItem.lootTableItem(Items.LEATHER).setWeight(15).setQuality(5)) .add(LootItem.lootTableItem(Items.DIAMOND_AXE).setWeight(10).setQuality(1)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(50))); registerLoot(registrar, ModEntities.PIRATE, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(ModItems.scimitar).setWeight(6)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(4))); registerLoot(registrar, ModEntities.ARCHERPIRATE, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.BOW).setWeight(10)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.CHIEFPIRATE, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(50)) .add(LootItem.lootTableItem(ModItems.pirateHelmet_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateLegs_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateBoots_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateChest_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateHelmet_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateLegs_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateBoots_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateChest_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.scimitar).setWeight(25).setQuality(1)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(30))); registerLoot(registrar, ModEntities.MUMMY, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(15))); registerLoot(registrar, ModEntities.ARCHERMUMMY, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.BOW).setWeight(10)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.PHARAO, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(50)) .add(LootItem.lootTableItem(ModItems.pharaoscepter).setWeight(3).setQuality(1)) .add(LootItem.lootTableItem(Items.ARROW).setWeight(20) .apply(SetItemCountFunction.setCount(UniformGenerator.between(1, 16))) .apply(LootingEnchantFunction.lootingMultiplier(UniformGenerator.between(1, 32)))) .add(LootItem.lootTableItem(ModItems.firearrow).setWeight(10) .apply(SetItemCountFunction.setCount(UniformGenerator.between(1, 16))) .apply(LootingEnchantFunction.lootingMultiplier(UniformGenerator.between(1, 32)))) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(30))); registerLoot(registrar, ModEntities.DROWNED_PIRATE, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(ModItems.scimitar).setWeight(6)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(4))); registerLoot(registrar, ModEntities.DROWNED_ARCHERPIRATE, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(80)) .add(LootItem.lootTableItem(Items.BOW).setWeight(10)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(5))); registerLoot(registrar, ModEntities.DROWNED_CHIEFPIRATE, builder -> builder .add(EmptyLootItem.emptyItem().setWeight(50)) .add(LootItem.lootTableItem(ModItems.pirateHelmet_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateLegs_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateBoots_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateChest_1).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateHelmet_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateLegs_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateBoots_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.pirateChest_2).setWeight(5).setQuality(1)) .add(LootItem.lootTableItem(ModItems.scimitar).setWeight(25).setQuality(1)) .add(LootItem.lootTableItem(ModItems.ancientTome).setWeight(30))); } private void registerLoot(@NotNull final LootTableRegistrar registrar, @NotNull final EntityType<?> entity, @NotNull final Consumer<LootPool.Builder> builder) { final ResourceLocation entityId = ForgeRegistries.ENTITY_TYPES.getKey(entity); final ResourceLocation lootName = new ResourceLocation(entityId.getNamespace(), "entities/" + entityId.getPath()); final LootPool.Builder pool = LootPool.lootPool() .setRolls(ConstantValue.exactly(1)); builder.accept(pool); registrar.register(lootName, LootContextParamSets.ALL_PARAMS, LootTable.lootTable().withPool(pool)); } }
0
0.693699
1
0.693699
game-dev
MEDIA
0.981596
game-dev
0.949594
1
0.949594
quabug/EntitiesBT
3,861
Packages/builder.odin/Runtime/OdinNode.cs
using System; using System.Collections.Generic; using System.IO; using EntitiesBT.Core; using EntitiesBT.Entities; using EntitiesBT.Nodes; using Sirenix.OdinInspector; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine; using Unity.Entities; namespace EntitiesBT.Components.Odin { [DisallowMultipleComponent, ExecuteInEditMode] public abstract class OdinNode : SerializedMonoBehaviour, INodeDataBuilder { public BehaviorNodeType BehaviorNodeType => NodeType.GetBehaviorNodeAttribute().Type; public int NodeId => NodeType.GetBehaviorNodeAttribute().Id; protected virtual Type NodeType { get; } = typeof(ZeroNode); public virtual IEnumerable<INodeDataBuilder> Children => this.Children<INodeDataBuilder>(); public INodeDataBuilder Self => gameObject.activeSelf ? SelfImpl : null; protected virtual INodeDataBuilder SelfImpl => this; public unsafe BlobAssetReference Build(ITreeNode<INodeDataBuilder>[] builders) { if (NodeType.IsZeroSizeStruct()) return BlobAssetReference.Null; var blobBuilder = new BlobBuilder(Allocator.Temp, UnsafeUtility.SizeOf(NodeType)); try { var dataPtr = blobBuilder.ConstructRootPtrByType(NodeType); Build(dataPtr, blobBuilder, builders); return blobBuilder.CreateReferenceByType(NodeType); } finally { blobBuilder.Dispose(); } } protected virtual unsafe void Build(void* dataPtr, BlobBuilder blobBuilder, ITreeNode<INodeDataBuilder>[] builders) {} protected virtual void Reset() => name = GetType().Name; protected virtual void Update() { #if UNITY_EDITOR if (UnityEditor.EditorApplication.isPlaying) return; int maxChildCount; switch (BehaviorNodeType) { case BehaviorNodeType.Composite: maxChildCount = int.MaxValue; break; case BehaviorNodeType.Decorate: maxChildCount = 1; break; case BehaviorNodeType.Action: maxChildCount = 0; break; default: throw new ArgumentOutOfRangeException(); } var childCount = transform.childCount; if (childCount > maxChildCount) { Debug.LogError($"{BehaviorNodeType} node {name} is not allowed to have more than {maxChildCount} children", gameObject); for (var i = childCount - 1; i >= maxChildCount; i--) DestroyImmediate(transform.GetChild(i).gameObject); } #endif } protected virtual void OnValidate() {} #if UNITY_EDITOR [ContextMenu("Save to file")] public void SaveToFile() { var path = UnityEditor.AssetDatabase.GetAssetPath(gameObject); path = string.IsNullOrEmpty(path) ? Application.dataPath : Path.GetDirectoryName(path); path = UnityEditor.EditorUtility.SaveFilePanel("save path", path, name, "bytes"); if (string.IsNullOrEmpty(path)) return; using (var file = new FileStream(path, FileMode.OpenOrCreate)) this.SaveToStream(file); UnityEditor.AssetDatabase.Refresh(); } #endif } public abstract class OdinNode<T> : OdinNode where T : struct, INodeData { protected override Type NodeType => typeof(T); protected override unsafe void Build(void* dataPtr, BlobBuilder builder, ITreeNode<INodeDataBuilder>[] tree) { Build(ref UnsafeUtility.AsRef<T>(dataPtr), builder, tree); } protected virtual void Build(ref T data, BlobBuilder builder, ITreeNode<INodeDataBuilder>[] tree) {} } }
0
0.913785
1
0.913785
game-dev
MEDIA
0.888317
game-dev
0.96695
1
0.96695
Segs/Segs
1,500
Common/Runtime/RuntimeData.h
#pragma once #include "Common/Runtime/HandleBasedStorage.h" #include "Common/Runtime/Texture.h" #include "Common/Containers/HashMap.h" #include "Common/Containers/String.h" struct SceneModifiers; namespace SEGS { struct IFilesystem; struct RuntimeData; } extern SEGS::RuntimeData& getRuntimeData(); extern void destroyRuntimeData(); namespace SEGS { using HTexture = SingularStoreHandleT<20,12,struct TextureWrapper>; struct PrefabStore; struct RuntimeData { //! Here we store handles to loaded texture headers HashMap<String, HTexture> m_loaded_textures; //! map from texture name to full file path HashMap<String, String> m_texture_paths; PrefabStore * m_prefab_mapping = nullptr; //!< maps directories and model names to geosets SceneModifiers * m_modifiers = nullptr; IFilesystem * m_wrapper = nullptr; bool m_ready = false; //!< set to true if runtime data was read. bool prepare(IFilesystem *fs,const String &directory_path); bool read_prefab_definitions(const String &directory_path); bool read_model_modifiers(const String &directory_path); // This is a non-copyable type RuntimeData(const RuntimeData &) = delete; RuntimeData &operator=(const RuntimeData&) = delete; private: friend RuntimeData& ::getRuntimeData(); RuntimeData(); ~RuntimeData(); }; void preloadTextureNames(IFilesystem *fs,const String &basepath); } //end of SEGS namespace
0
0.930213
1
0.930213
game-dev
MEDIA
0.833473
game-dev
0.669253
1
0.669253
CraftJarvis/GROOT
40,965
jarvis/stark_tech/Malmo/Minecraft/src/main/java/com/microsoft/Malmo/Utils/CraftingHelper.java
// -------------------------------------------------------------------------------------------------- // Copyright (c) 2016 Microsoft Corporation // // 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. // -------------------------------------------------------------------------------------------------- package com.microsoft.Malmo.Utils; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.base.CaseFormat; import com.google.gson.*; import com.microsoft.Malmo.MissionHandlers.RewardForCollectingItemImplementation; import com.microsoft.Malmo.MissionHandlers.RewardForDiscardingItemImplementation; import net.minecraft.block.Block; import net.minecraft.block.material.EnumPushReaction; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.*; import net.minecraft.item.crafting.*; import net.minecraft.stats.Achievement; import net.minecraft.stats.AchievementList; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; public class CraftingHelper { private static Map<EntityPlayerMP, Integer> fuelCaches = new HashMap<EntityPlayerMP, Integer>(); private static final int smeltingCookingTime = new TileEntityFurnace().getCookTime(null); // same for all items, apparently /** * Reset caches<br> * Needed to make sure the player starts with a fresh fuel stash. */ public static void reset() { fuelCaches = new HashMap<EntityPlayerMP, Integer>(); } /** * Attempt to return the raw ingredients required for this recipe.<br> * Ignores all shaping. * * @param recipe the IRecipe to dissect. * @return a list of ItemStacks, amalgamated so that all items of the same type are placed in the same stack. */ public static NonNullList<ItemStack> getIngredients(IRecipe recipe) { // IRecipe helpfully has no method for inspecting the raw ingredients, so we need to do different things depending on the subclass. NonNullList<ItemStack> ingredients = NonNullList.create(); if (recipe instanceof ShapelessRecipes) { List<?> items = ((ShapelessRecipes) recipe).recipeItems; for (Object obj : items) { if (obj instanceof ItemStack) ingredients.add((ItemStack) obj); } } else if (recipe instanceof ShapelessOreRecipe) { NonNullList<Object> objs = ((ShapelessOreRecipe) recipe).getInput(); for (Object o : objs) { if (o != null) { if (o instanceof ItemStack) ingredients.add((ItemStack) o); else if (o instanceof List) { List<?> stacks = (List<?>) o; for (Object stack : stacks) { if (stack instanceof ItemStack) ingredients.add((ItemStack) stack); } } } } } else if (recipe instanceof ShapedRecipes) { ItemStack[] recipeItems = ((ShapedRecipes) recipe).recipeItems; for (ItemStack itemStack : recipeItems) { if (itemStack != null) ingredients.add(itemStack); } } else if (recipe instanceof ShapedOreRecipe) { Object[] items = ((ShapedOreRecipe) recipe).getInput(); for (Object obj : items) { if (obj != null) { if (obj instanceof ItemStack) ingredients.add((ItemStack) obj); else if (obj instanceof List) { List<?> stacks = (List<?>) obj; for (Object stack : stacks) { if (stack instanceof ItemStack) ingredients.add((ItemStack) stack); } } } } } else { // TODO Implement remaining recipe types after incorporating item metadata (e.g. potions for tipped arrows) return ingredients; } return consolidateItemStacks(ingredients); } /** * Take a list of ItemStacks and amalgamate where possible.<br> * * @param inputStacks a list of ItemStacks * @return a list of ItemStacks, where all items of the same type are grouped into one stack. */ public static NonNullList<ItemStack> consolidateItemStacks(NonNullList<ItemStack> inputStacks) { // Horrible n^2 method - we should do something nicer if this ever becomes a bottleneck. NonNullList<ItemStack> outputStacks = NonNullList.create(); for (ItemStack sourceIS : inputStacks) { boolean bFound = false; for (ItemStack destIS : outputStacks) { if (destIS != null && sourceIS != null && itemStackIngredientsMatch(destIS, sourceIS)) { bFound = true; destIS.setCount(destIS.getCount() + sourceIS.getCount()); } } if (!bFound) { assert sourceIS != null; outputStacks.add(sourceIS.copy()); } } return outputStacks; } /** * Inspect a player's inventory to see whether they have enough items to form the supplied list of ItemStacks.<br> * The ingredients list MUST be amalgamated such that no two ItemStacks contain the same type of item. * * @param player * @param ingredients an amalgamated list of ingredients * @return true if the player's inventory contains sufficient quantities of all the required items. */ public static boolean playerHasIngredients(EntityPlayerMP player, List<ItemStack> ingredients) { NonNullList<ItemStack> main = player.inventory.mainInventory; NonNullList<ItemStack> arm = player.inventory.armorInventory; for (ItemStack isIngredient : ingredients) { int target = isIngredient.getCount(); for (int i = 0; i < main.size() + arm.size() && target > 0; i++) { ItemStack isPlayer = (i >= main.size()) ? arm.get(i - main.size()) : main.get(i); if (isPlayer != null && isIngredient != null && itemStackIngredientsMatch(isPlayer, isIngredient)) target -= isPlayer.getCount(); } if (target > 0) return false; // Don't have enough of this. } return true; } /** * Inspect a player's inventory to see whether they have enough items to form the supplied list of ItemStacks.<br> * The ingredients list MUST be amalgamated such that no two ItemStacks contain the same type of item. * * @param player * @param ingredients an amalgamated list of ingredients * @return true if the player's inventory contains sufficient quantities of all the required items. */ public static boolean playerHasIngredients(EntityPlayerSP player, List<ItemStack> ingredients) { NonNullList<ItemStack> main = player.inventory.mainInventory; NonNullList<ItemStack> arm = player.inventory.armorInventory; for (ItemStack isIngredient : ingredients) { int target = isIngredient.getCount(); for (int i = 0; i < main.size() + arm.size() && target > 0; i++) { ItemStack isPlayer = (i >= main.size()) ? arm.get(i - main.size()) : main.get(i); if (isPlayer != null && isIngredient != null && itemStackIngredientsMatch(isPlayer, isIngredient)) target -= isPlayer.getCount(); } if (target > 0) return false; // Don't have enough of this. } return true; } /** * Compare two ItemStacks and see if their items match - take wildcards into account, don't take stacksize into account. * * @param A ItemStack A * @param B ItemStack B * @return true if the stacks contain matching items. */ private static boolean itemStackIngredientsMatch(ItemStack A, ItemStack B) { if (A == null && B == null) return true; if (A == null || B == null) return false; if (A.getMetadata() == OreDictionary.WILDCARD_VALUE || B.getMetadata() == OreDictionary.WILDCARD_VALUE) return A.getItem() == B.getItem(); return ItemStack.areItemsEqual(A, B); } /** * Go through player's inventory and see how much fuel they have. * * @param player * @return the amount of fuel available in ticks */ public static int totalBurnTimeInInventory(EntityPlayerMP player) { Integer fromCache = fuelCaches.get(player); int total = (fromCache != null) ? fromCache : 0; for (int i = 0; i < player.inventory.mainInventory.size(); i++) { ItemStack is = player.inventory.mainInventory.get(i); total += is.getCount() * TileEntityFurnace.getItemBurnTime(is); } return total; } /** * Consume fuel from the player's inventory.<br> * Take it first from their cache, if present, and then from their inventory, starting * at the first slot and working upwards. * * @param player * @param burnAmount amount of fuel to burn, in ticks. */ public static void burnInventory(EntityPlayerMP player, int burnAmount, ItemStack input) { if (!fuelCaches.containsKey(player)) fuelCaches.put(player, -burnAmount); else fuelCaches.put(player, fuelCaches.get(player) - burnAmount); int index = 0; while (fuelCaches.get(player) < 0 && index < player.inventory.mainInventory.size()) { ItemStack is = player.inventory.mainInventory.get(index); if (is != null) { int burnTime = TileEntityFurnace.getItemBurnTime(is); if (burnTime != 0) { // Consume item: if (is.getCount() > 1) is.setCount(is.getCount() - 1); else { // If this is a bucket of lava, we need to consume the lava but leave the bucket. if (is.getItem() == Items.LAVA_BUCKET) { // And if we're cooking wet sponge, we need to leave the bucket filled with water. if (input.getItem() == Item.getItemFromBlock(Blocks.SPONGE) && input.getMetadata() == 1) player.inventory.mainInventory.set(index, new ItemStack(Items.WATER_BUCKET)); else player.inventory.mainInventory.set(index, new ItemStack(Items.BUCKET)); } else player.inventory.mainInventory.get(index).setCount(0); index++; } fuelCaches.put(player, fuelCaches.get(player) + burnTime); } else index++; } else index++; } } /** * Manually attempt to remove ingredients from the player's inventory.<br> * * @param player * @param ingredients */ public static void removeIngredientsFromPlayer(EntityPlayerMP player, List<ItemStack> ingredients) { NonNullList<ItemStack> main = player.inventory.mainInventory; NonNullList<ItemStack> arm = player.inventory.armorInventory; for (ItemStack isIngredient : ingredients) { int target = isIngredient.getCount(); for (int i = 0; i < main.size() + arm.size() && target > 0; i++) { ItemStack isPlayer = (i >= main.size()) ? arm.get(i - main.size()) : main.get(i); if (itemStackIngredientsMatch(isPlayer, isIngredient)) { if (target >= isPlayer.getCount()) { // Consume this stack: target -= isPlayer.getCount(); if (i >= main.size()) arm.get(i - main.size()).setCount(0); else main.get(i).setCount(0); } else { isPlayer.setCount(isPlayer.getCount() - target); target = 0; } } } ItemStack resultForReward = isIngredient.copy(); RewardForDiscardingItemImplementation.LoseItemEvent event = new RewardForDiscardingItemImplementation.LoseItemEvent( player, resultForReward); MinecraftForge.EVENT_BUS.post(event); } } /** * Attempt to find all recipes that result in an item of the requested output. * * @param output the desired item, eg from Types.xsd - "diamond_pickaxe" etc - or as a Minecraft name - eg "tile.woolCarpet.blue" * @param variant if variants should be obeyed in constructing the recipes, i.e. if false, variant blind * @return a list of IRecipe objects that result in this item. */ public static List<IRecipe> getRecipesForRequestedOutput(String output, boolean variant) { List<IRecipe> matchingRecipes = new ArrayList<IRecipe>(); ItemStack target = MinecraftTypeHelper.getItemStackFromParameterString(output); List<?> recipes = CraftingManager.getInstance().getRecipeList(); for (Object obj : recipes) { if (obj == null) continue; if (obj instanceof IRecipe) { ItemStack is = ((IRecipe) obj).getRecipeOutput(); if (target == null) continue; if (variant && ItemStack.areItemsEqual(is, target)) matchingRecipes.add((IRecipe) obj); else if (!variant && is.getItem() == target.getItem()) matchingRecipes.add((IRecipe) obj); } } return matchingRecipes; } /** * Attempt to find all recipes that result in an item of the requested output. * * @param output the desired item, eg from Types.xsd - "diamond_pickaxe" etc - or as a Minecraft name - eg "tile.woolCarpet.blue" * @param variant if variants should be obeyed in constructing the recipes, i.e. if false, variant blind * @return a list of IRecipe objects that result in this item. */ public static List<IRecipe> getRecipesForRequestedOutput(ItemStack output, boolean variant) { List<IRecipe> matchingRecipes = new ArrayList<IRecipe>(); List<?> recipes = CraftingManager.getInstance().getRecipeList(); for (Object obj : recipes) { if (obj == null) continue; if (obj instanceof IRecipe) { ItemStack is = ((IRecipe) obj).getRecipeOutput(); if (output == null) continue; if (variant && ItemStack.areItemsEqual(is, output)) matchingRecipes.add((IRecipe) obj); else if (!variant && is.getItem() == output.getItem()) matchingRecipes.add((IRecipe) obj); } } return matchingRecipes; } /** * Attempt to find a smelting recipe that results in the requested output. * * @param output The output of the furnace burn * @return an ItemStack representing the required input. */ public static ItemStack getSmeltingRecipeForRequestedOutput(String output, EntityPlayerMP player) { ItemStack target = MinecraftTypeHelper.getItemStackFromParameterString(output); if (target == null) return null; for (Map.Entry<ItemStack, ItemStack> e : FurnaceRecipes.instance().getSmeltingList().entrySet()) { if (itemStackIngredientsMatch(target, e.getValue()) && playerHasIngredients(player, Collections.singletonList(e.getKey())) && totalBurnTimeInInventory(player) >= smeltingCookingTime ) { return e.getKey(); } } return null; } /** * This code is copied from SlotCrafting.onCrafting * TODO - convert this into a mixin to avoid duplicating code * @param player - player crafting the items * @param stack - item and quantity that was crafted * @param craftMatrix - the InventoryCrafting representing the item recipe */ protected static void onCrafting(EntityPlayer player, ItemStack stack, InventoryCrafting craftMatrix) { // Unclear why you would get achievements without crafting a non-zero amount of an item but this is behavior // directly from MC if (stack.getCount() > 0) { stack.onCrafting(player.world, player, stack.getCount()); net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(player, stack, craftMatrix); } if (stack.getItem() == Item.getItemFromBlock(Blocks.CRAFTING_TABLE)) { player.addStat(AchievementList.BUILD_WORK_BENCH); } if (stack.getItem() instanceof ItemPickaxe) { player.addStat(AchievementList.BUILD_PICKAXE); } if (stack.getItem() == Item.getItemFromBlock(Blocks.FURNACE)) { player.addStat(AchievementList.BUILD_FURNACE); } if (stack.getItem() instanceof ItemHoe) { player.addStat(AchievementList.BUILD_HOE); } if (stack.getItem() == Items.BREAD) { player.addStat(AchievementList.MAKE_BREAD); } if (stack.getItem() == Items.CAKE) { player.addStat(AchievementList.BAKE_CAKE); } if (stack.getItem() instanceof ItemPickaxe && ((ItemPickaxe)stack.getItem()).getToolMaterial() != Item.ToolMaterial.WOOD) { player.addStat(AchievementList.BUILD_BETTER_PICKAXE); } if (stack.getItem() instanceof ItemSword) { player.addStat(AchievementList.BUILD_SWORD); } if (stack.getItem() == Item.getItemFromBlock(Blocks.ENCHANTING_TABLE)) { player.addStat(AchievementList.ENCHANTMENTS); } if (stack.getItem() == Item.getItemFromBlock(Blocks.BOOKSHELF)) { player.addStat(AchievementList.BOOKCASE); } } /** * Attempt to craft the given recipe.<br> * This pays no attention to tedious things like using the right crafting table * / brewing stand etc, or getting the right shape.<br> * It simply takes the raw ingredients out of the player's inventory, and * inserts the output of the recipe, if possible. * * @param player the SERVER SIDE player that will do the crafting. * @param recipe the IRecipe we wish to craft. * @return true if the recipe had an output, and the player had the required * ingred:xients to create it; false otherwise. */ public static boolean attemptCrafting(EntityPlayerMP player, IRecipe recipe) { if (player == null || recipe == null) return false; ItemStack is = recipe.getRecipeOutput(); List<ItemStack> ingredients = getIngredients(recipe); if (playerHasIngredients(player, ingredients)) { // We have the ingredients we need, so directly manipulate the inventory. // First, remove the ingredients: removeIngredientsFromPlayer(player, ingredients); // Now add the output of the recipe: ItemStack resultForInventory = is.copy(); ItemStack resultForReward = is.copy(); player.inventory.addItemStackToInventory(resultForInventory); RewardForCollectingItemImplementation.GainItemEvent event = new RewardForCollectingItemImplementation.GainItemEvent( player, resultForReward); event.setCause(1); MinecraftForge.EVENT_BUS.post(event); // Now trigger a craft event List<IRecipe> recipes = getRecipesForRequestedOutput(resultForReward, true); for (IRecipe iRecipe : recipes) { if (iRecipe instanceof ShapedRecipes) { ShapedRecipes shapedRecipe = (ShapedRecipes) iRecipe; InventoryCrafting craftMatrix; if (shapedRecipe.recipeItems.length <= 4) craftMatrix = new InventoryCrafting(player.inventoryContainer, 2, 2); else craftMatrix = new InventoryCrafting(player.inventoryContainer, 3, 3); for (int i = 0; i < shapedRecipe.recipeItems.length; i++) craftMatrix.setInventorySlotContents(i, shapedRecipe.recipeItems[i]); onCrafting(player, resultForReward, craftMatrix); break; } else if (iRecipe instanceof ShapelessRecipes) { ShapelessRecipes shapelessRecipe = (ShapelessRecipes) iRecipe; InventoryCrafting craftMatrix; if (shapelessRecipe.recipeItems.size() <= 4) { craftMatrix = new InventoryCrafting(player.inventoryContainer, 2, 2); for (int i = 0; i < shapelessRecipe.recipeItems.size(); i++) craftMatrix.setInventorySlotContents(i, shapelessRecipe.recipeItems.get(i)); } else { craftMatrix = new InventoryCrafting(player.inventoryContainer, 3, 3); for (int i = 0; i < shapelessRecipe.recipeItems.size(); i++) craftMatrix.setInventorySlotContents(i, shapelessRecipe.recipeItems.get(i)); } onCrafting(player, resultForReward, craftMatrix); break; } else if (iRecipe instanceof ShapedOreRecipe) { ShapedOreRecipe oreRecipe = (ShapedOreRecipe) iRecipe; Object[] input = oreRecipe.getInput(); InventoryCrafting craftMatrix = new InventoryCrafting(player.inventoryContainer, 3, 3); for (int i = 0; i < input.length; i++) { if (input[i] instanceof ItemStack) craftMatrix.setInventorySlotContents(i, (ItemStack) input[i]); else if (input[i] instanceof NonNullList) if (((NonNullList) input[i]).size() != 0) craftMatrix.setInventorySlotContents(i, (ItemStack) ((NonNullList) input[i]).get(0)); } onCrafting(player, resultForReward, craftMatrix); } } return true; } return false; } /** * TODO Copied from SlotFurncaeOutput.onCrafting - change to mixin to remove redundant code * @param stack - item stack that was crafted */ protected static void onSmelting(EntityPlayer player, ItemStack stack) { stack.onCrafting(player.world, player, stack.getCount()); if (!player.world.isRemote) { int i = stack.getCount(); float f = FurnaceRecipes.instance().getSmeltingExperience(stack); if (f == 0.0F) { i = 0; } else if (f < 1.0F) { int j = MathHelper.floor((float)i * f); if (j < MathHelper.ceil((float)i * f) && Math.random() < (double)((float)i * f - (float)j)) { ++j; } i = j; } while (i > 0) { int k = EntityXPOrb.getXPSplit(i); i -= k; player.world.spawnEntity(new EntityXPOrb(player.world, player.posX, player.posY + 0.5D, player.posZ + 0.5D, k)); } } net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerSmeltedEvent(player, stack); if (stack.getItem() == Items.IRON_INGOT) { player.addStat(AchievementList.ACQUIRE_IRON); } if (stack.getItem() == Items.COOKED_FISH) { player.addStat(AchievementList.COOK_FISH); } } /** * Attempt to smelt the given item.<br> * This returns instantly, callously disregarding such frivolous niceties as cooking times or the presence of a furnace.<br> * It will, however, consume fuel from the player's inventory. * * @param player * @param input the raw ingredients we want to cook. * @return true if cooking was successful. */ public static boolean attemptSmelting(EntityPlayerMP player, ItemStack input) { if (player == null || input == null) return false; List<ItemStack> ingredients = new ArrayList<ItemStack>(); ingredients.add(input); ItemStack isOutput = FurnaceRecipes.instance().getSmeltingList().get(input); if (isOutput == null) return false; if (playerHasIngredients(player, ingredients) && totalBurnTimeInInventory(player) >= smeltingCookingTime) { removeIngredientsFromPlayer(player, ingredients); burnInventory(player, smeltingCookingTime, input); ItemStack resultForInventory = isOutput.copy(); ItemStack resultForReward = isOutput.copy(); player.inventory.addItemStackToInventory(resultForInventory); RewardForCollectingItemImplementation.GainItemEvent event = new RewardForCollectingItemImplementation.GainItemEvent( player, resultForReward); event.setCause(2); MinecraftForge.EVENT_BUS.post(event); // Trigger the furnace output removed item events onSmelting(player, isOutput); return true; } return false; } private static JsonObject listIngredients(NonNullList<ItemStack> ingredients){ JsonObject jsonObject = new JsonObject(); for (ItemStack ingredient: ingredients){ if (!ingredient.isEmpty() && Item.REGISTRY.getNameForObject(ingredient.getItem()) != null) jsonObject.addProperty(Item.REGISTRY.getNameForObject(ingredient.getItem()).toString().replace("minecraft:", ""), ingredient.getCount()); } return jsonObject; } /** * Little utility method for dumping out a json array of all the Minecraft items, plus as many useful * attributes as we can find for them. This is primarily used by decision_tree_test.py but might be useful for * real-world applications too. */ public static JsonArray generateItemJson(){ JsonArray items = new JsonArray(); for (ResourceLocation i : Item.REGISTRY.getKeys()) { Item item = Item.REGISTRY.getObject(i); if (item != null && Item.REGISTRY.getNameForObject(item) != null) { JsonObject json = new JsonObject(); json.addProperty("type", Item.REGISTRY.getNameForObject(item).toString().replace("minecraft:", "")); json.addProperty("damageable", item.isDamageable()); json.addProperty("rendersIn3D", item.isFull3D()); json.addProperty("repairable", item.isRepairable()); CreativeTabs tab = item.getCreativeTab(); json.addProperty("tab", ((tab != null) ? item.getCreativeTab().getTabLabel() : "none")); ItemStack is = item.getDefaultInstance(); json.addProperty("stackable", is.isStackable()); json.addProperty("stackSize", is.getMaxStackSize()); json.addProperty("useAction", is.getItemUseAction().toString()); json.addProperty("enchantable", is.isItemEnchantable()); json.addProperty("rarity", is.getRarity().toString()); json.addProperty("hasSubtypes", item.getHasSubtypes()); json.addProperty("maxDamage", is.getMaxDamage()); json.addProperty("maxUseDuration", is.getMaxItemUseDuration()); json.addProperty("block", item instanceof ItemBlock); json.addProperty("hasContainerItem", item.hasContainerItem()); json.addProperty("bestEquipmentSlot", EntityLiving.getSlotForItemStack(is).getName()); if (item instanceof ItemBlock) { ItemBlock ib = (ItemBlock) item; Block b = ib.getBlock(); IBlockState bs = b.getDefaultState(); json.addProperty("slipperiness", b.slipperiness); json.addProperty("hardness", bs.getBlockHardness(null, null)); json.addProperty("causesSuffocation", bs.causesSuffocation()); json.addProperty("canProvidePower", bs.canProvidePower()); json.addProperty("translucent", bs.isTranslucent()); Material mat = bs.getMaterial(); json.addProperty("canBurn", mat.getCanBurn()); json.addProperty("isLiquid", mat.isLiquid()); json.addProperty("blocksMovement", mat.blocksMovement()); json.addProperty("needsNoTool", mat.isToolNotRequired()); json.addProperty("isReplaceable", mat.isReplaceable()); json.addProperty("pistonPushable", mat.getMobilityFlag() == EnumPushReaction.NORMAL); json.addProperty("woodenMaterial", mat == Material.WOOD); json.addProperty("ironMaterial", mat == Material.IRON); json.addProperty("glassyMaterial", mat == Material.GLASS); json.addProperty("clothMaterial", mat == Material.CLOTH); boolean hasDirection = false; boolean hasColour = false; boolean hasVariant = false; for (IProperty prop : bs.getProperties().keySet()) { System.out.println(Item.REGISTRY.getNameForObject(item).toString() + " -- " + prop); if (prop instanceof PropertyDirection) hasDirection = true; if (prop instanceof PropertyEnum && prop.getName().equals("color")) hasColour = true; if (prop instanceof PropertyEnum && prop.getName().equals("variant")) { hasVariant = true; json.addProperty("variant", bs.getValue(prop).toString()); } } json.addProperty("hasDirection", hasDirection); json.addProperty("hasColour", hasColour); json.addProperty("hasVariant", hasVariant); } items.add(json); } } return items; } /** * Little utility method for generating a json array of all of the Minecraft blocks */ public static JsonArray generateBlockJson(){ JsonArray blocks = new JsonArray(); for (ResourceLocation i : Block.REGISTRY.getKeys()) { Block block = Block.REGISTRY.getObject(i); JsonObject json = new JsonObject(); json.addProperty("name", Block.REGISTRY.getNameForObject(block).toString().replace("minecraft:", "")); json.addProperty("particleGravity", block.blockParticleGravity); json.addProperty("slipperiness", block.slipperiness); json.addProperty("spawnInBlock", block.canSpawnInBlock()); json.addProperty("isCollidable", block.isCollidable()); try{ json.addProperty("quantityDropped", block.quantityDropped(null)); } catch (NullPointerException ignored){} blocks.add(json); } return blocks; } /** * Little utility method for generating a json array of all of the Minecraft achievements */ public static JsonArray generateAchievements(){ JsonArray achievements = new JsonArray(); for (Achievement achievement : AchievementList.ACHIEVEMENTS) { JsonObject json = new JsonObject(); json.addProperty("statID", achievement.statId); if (achievement.parentAchievement != null && achievement.parentAchievement.statId != null) json.addProperty("parentStatID", achievement.parentAchievement.statId); json.addProperty("isIndependent", achievement.isIndependent); json.addProperty("displayColumn", achievement.displayColumn); json.addProperty("displayRow", achievement.displayRow); json.addProperty("isSpecial", achievement.getSpecial()); json.addProperty("description", achievement.getDescription()); achievements.add(json); } return achievements; } /** * Little utility method for generating a json array of all of the Minecraft base stats */ public static JsonArray generateStats(){ JsonArray stats = new JsonArray(); for (StatBase stat : StatList.ALL_STATS) { JsonObject json = new JsonObject(); json.addProperty("statID", stat.statId); JsonArray tokens = new JsonArray(); for (String token : stat.statId.split("\\.")){ // BAH map drop stat to items_dropped to prevent hash collision in dict keys // MUST change this in JSONWorldDataHelper.java as well!!!! (search above comment) if (token.equals(stat.statId.split("\\.")[stat.statId.split("\\.").length - 1])) if (token.equals("drop")) token = "items_dropped"; tokens.add(new JsonPrimitive(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, token))); } json.add("minerl_keys", tokens); json.addProperty("isIndependent", stat.isIndependent); json.addProperty("isAchievement",stat.isAchievement()); stats.add(json); } return stats; } /** * Little utility method for generating a json array of all of the Minecraft crafting recipes */ public static JsonArray generateCraftingRecipeJson(){ JsonArray craftingRecipes = new JsonArray(); for (IRecipe recipe : CraftingManager.getInstance().getRecipeList()) { if (recipe == null || Item.REGISTRY.getNameForObject(recipe.getRecipeOutput().getItem()) == null) continue; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("outputItemName", Item.REGISTRY.getNameForObject(recipe.getRecipeOutput().getItem()).toString().replace("minecraft:", "")); jsonObject.addProperty("outputCount", recipe.getRecipeOutput().getCount()); jsonObject.addProperty("recipeSize", recipe.getRecipeSize()); jsonObject.addProperty("type", recipe.getClass().getSimpleName()); jsonObject.add( "ingredients", listIngredients(getIngredients(recipe))); craftingRecipes.add(jsonObject); } return craftingRecipes; } /** * Little utility method for generating a json array of all of the Minecraft smelting recipes */ public static JsonArray generateSmeltingRecipeJson(){ JsonArray smeltingRecipes = new JsonArray(); for (ItemStack isInput : FurnaceRecipes.instance().getSmeltingList().keySet()) { ItemStack isOutput = FurnaceRecipes.instance().getSmeltingList().get(isInput); if (Item.REGISTRY.getNameForObject(isOutput.getItem()) == null) continue; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("outputItemName", Item.REGISTRY.getNameForObject(isOutput.getItem()).toString().replace("minecraft:", "")); jsonObject.addProperty("out", isOutput.getCount()); jsonObject.add("ingredients", listIngredients(NonNullList.withSize(1, isInput))); smeltingRecipes.add(jsonObject); } return smeltingRecipes; } /** * Little utility method for dumping out a list of all the Minecraft items, plus as many useful attributes as * we can find for them. This is primarily used by decision_tree_test.py but might be useful for real-world applications too. * * @param filename location to save the dumped list. * @throws IOException */ public static void dumpItemProperties(String filename) throws IOException { FileOutputStream fos = new FileOutputStream("..//..//build//install//Python_Examples//item_database.json"); OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8"); BufferedWriter writer = new BufferedWriter(osw); JsonArray itemTypes = generateItemJson(); writer.write(itemTypes.toString()); writer.close(); } /** * Utility method to auto-generate item, block, and recipe lists as individual json arrays * * @param filename location to save the dumped json file. */ public static void dumpMinecraftObjectRules(String filename) { JsonObject allRecipes = new JsonObject(); allRecipes.addProperty("docstring", "THIS IS AN AUTO GENERATED FILE! This file was generated by " + "com.microsoft.Malmo.Utils.CraftingHelper.dumpMinecraftObjectRules(). Generate this file by " + "launching Malmo and pressing the 'u' key (see MalmoModClient.java) or by adding the following to " + "MixinMinecraftServerRun.java: CraftingHelper.dumpMinecraftObjectRules(\"/full/path/mc_constants.json\");"); allRecipes.add("craftingRecipes", generateCraftingRecipeJson()); allRecipes.add("smeltingRecipes", generateSmeltingRecipeJson()); allRecipes.add("items", generateItemJson()); allRecipes.add("blocks", generateBlockJson()); allRecipes.add("achievements", generateAchievements()); allRecipes.add("stats", generateStats()); try { Writer writer = new FileWriter(filename); Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(allRecipes, writer); System.out.println("Wrote json to " + System.getProperty("user.dir") + filename); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
0
0.875133
1
0.875133
game-dev
MEDIA
0.999096
game-dev
0.983793
1
0.983793
Dimbreath/AzurLaneData
3,063
ja-JP/view/vote/layer/webvotelayer.lua
slot0 = class("WebVoteLayer", import("...base.BaseUI")) function slot0.getUIName(slot0) return "WebVoteUI" end function slot0.setGroup(slot0, slot1) slot0.voteGroup = slot1 slot0.voteShips = slot0.voteGroup:getList() end function slot0.init(slot0) slot0.titleBg1 = slot0:findTF("main/right_panel/title/title_bg1") slot0.titleBg2 = slot0:findTF("main/right_panel/title/title_bg2") slot0.titleBg3 = slot0:findTF("main/right_panel/title/title_bg3") slot0.backBtn = slot0:findTF("blur_panel/adapt/top/back_btn") slot0.title = slot0:findTF("main/right_panel/title/main"):GetComponent(typeof(Text)) slot0.subTitle = slot0:findTF("main/right_panel/title/Text"):GetComponent(typeof(Text)) slot0.tagtimeTF = slot0:findTF("main/right_panel/title/sub"):GetComponent(typeof(Text)) slot0.urlBtn = slot0:findTF("main/right_panel/filter_bg/filter_btn") slot0.helpBtn = slot0:findTF("main/right_panel/title/help") end function slot0.didEnter(slot0) onButton(slot0, slot0.backBtn, function () uv0:emit(uv1.ON_CLOSE) end, SFX_PANEL) onButton(slot0, slot0.helpBtn, function () pg.MsgboxMgr.GetInstance():ShowMsgBox({ type = MSGBOX_TYPE_HELP, helps = pg.gametip[uv0].tip }) end, SFX_PANEL) setActive(slot0.helpBtn, slot0.voteGroup:getConfig("help_text") and slot1 ~= "") onButton(slot0, slot0.urlBtn, function () Application.OpenURL(pg.gameset.vote_web_url.description) end, SFX_PANEL) uv0.PAGES = { { VotePreRaceShipPage, VotePreRaceRankPage }, { VoteGroupRaceShipPage, VoteGroupRaceRankPage }, { VoteGroupRaceShipPage, VoteGroupRaceRankPage }, { VoteGroupRaceShipPage, VoteGroupRaceRankPage }, { VoteFinalsRaceShipsPage, VoteFinalsRaceRankPage }, { VoteGroupRaceShipPage, VotePreRaceRankPage } } slot2 = uv0.PAGES[slot0.voteGroup:getConfig("type")] slot0.ships = slot2[1].New(slot0:findTF("main/right_panel"), slot0.event) slot0.ranks = slot2[2].New(slot0:findTF("main/left_panel"), slot0.event) slot0:UpdateMain() end function slot0.UpdateMain(slot0) slot0:initShips() slot0:initRanks() slot0:initTitles() end function slot0.initShips(slot0) slot0.displays = {} for slot4, slot5 in ipairs(slot0.voteShips) do table.insert(slot0.displays, slot5) end slot0.ships:ExecuteAction("Update", slot0.voteGroup, slot0.displays) end function slot0.initRanks(slot0) slot0.ranks:ExecuteAction("Update", slot0.voteGroup) slot0.ranks:CallbackInvoke(function () setActive(uv0.ranks.webBtn, false) end) end function slot0.initTitles(slot0) slot1 = slot0.voteGroup:getConfig("time_vote") slot0.tagtimeTF.text = slot0.voteGroup:getTimeDesc() slot2 = slot0.voteGroup:isResurrectionRace() if not slot0.voteGroup:isFinalsRace() then slot0.title.text = slot0.voteGroup:getConfig("name") end slot0.subTitle.text = slot0.voteGroup:getConfig("desc") setActive(slot0.titleBg1, not slot2 and not slot3) setActive(slot0.titleBg2, slot2) setActive(slot0.titleBg3, slot3) end function slot0.willExit(slot0) slot0.ships:Destroy() slot0.ranks:Destroy() end return slot0
0
0.523369
1
0.523369
game-dev
MEDIA
0.866793
game-dev
0.879193
1
0.879193
johnnemann/museum-of-mechanics-lockpicking
2,480
Open Museum/Assets/Scripts/MassEffect2Node.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; //This class holds references to the UI elements that make up a node and handles interactions public class MassEffect2Node : MonoBehaviour, ISelectHandler, IPointerEnterHandler, IPointerClickHandler, IPointerExitHandler { //The image that we can set the sprite of to change our appearance public Image nodeImage; //References to the sprite that shows when we're hidden and the one that shows when we're flipped over public Sprite hiddenSprite; public Sprite flippedSprite; //The unique ID of this node public int nodeID; //A reference to the controlling game public MassEffect2LockpickGame lockpickGame; //How long the node stays flipped public float flipTimer = 2.5f; float elapsedFlipTimer = 0.0f; bool flipTimerActive = false; //When the player selects this node public void OnSelect(BaseEventData eventData) { //flip to display side, start countdown timer ShowSprite(); elapsedFlipTimer = 0.0f; flipTimerActive = true; } //When the player decides to lock this sprite to the flipped side and try to find its match (or this is the match) public void LockSprite() { //lock object flipped ShowSprite(); flipTimerActive = false; lockpickGame.SpriteClicked(this); } void Update() { //countdown timer - when this expires, flip the sprite back to the hidden side if (flipTimerActive) { elapsedFlipTimer += Time.deltaTime; if (elapsedFlipTimer >= flipTimer) { flipTimerActive = false; HideSprite(); } } } //Just set the appropriate sprite public void ShowSprite() { nodeImage.sprite = flippedSprite; } public void HideSprite() { nodeImage.sprite = hiddenSprite; } //Handle mouse interaction - on enter we select, on click we lock, and on exit we reset public void OnPointerEnter(PointerEventData eventData) { EventSystem.current.SetSelectedGameObject(this.gameObject); } public void OnPointerClick(PointerEventData eventData) { LockSprite(); } public void OnPointerExit(PointerEventData eventData) { elapsedFlipTimer = flipTimer; EventSystem.current.SetSelectedGameObject(null); } }
0
0.611908
1
0.611908
game-dev
MEDIA
0.949093
game-dev
0.834868
1
0.834868
stingbo/mengine
4,631
src/Services/CommissionPoolService.php
<?php namespace StingBo\Mengine\Services; use StingBo\Mengine\Core\AbstractCommissionPool; use StingBo\Mengine\Core\Order; use StingBo\Mengine\Events\DeleteOrderSuccEvent; use StingBo\Mengine\Events\MatchEvent; use StingBo\Mengine\Events\PushQueueEvent; class CommissionPoolService extends AbstractCommissionPool { /** * 放入委托池. */ public function pushPool(Order $order): bool { $ms_service = new MengineService(); if ($ms_service->isHashDeleted($order)) { return false; } $ms_service->deleteHashOrder($order); $list = $ms_service->getMutexDepth($order->symbol, $order->transaction, $order->price); if ($list) { $order = $this->matchUp($order, $list); // 撮合 if (!$order) { return false; } } // 深度列表、数量更新、节点更新 $depth_link = new DepthLinkService(); $depth_link->pushZset($order); $depth_link->pushDepthHash($order); $depth_link->pushDepthNode($order); event(new PushQueueEvent($order)); return true; } /** * 撤单从委托池删除. */ public function deletePoolOrder(Order $order): bool { $link_service = new LinkService($order->node_link); $node = $link_service->getNode($order->node); if (!$node) { return false; } // order里的volume替换为缓存里节点上的数量,防止order里的数量与当初push的不一致或者部分成交 $order->volume = $node->volume; // 更新委托量 $depth_link = new DepthLinkService(); $depth_link->deleteDepthHash($order); // 从深度列表里删除 $depth_link->deleteZset($order); // 从节点链上删除 $depth_link->deleteDepthNode($order); // 撤单成功通知 event(new DeleteOrderSuccEvent($order)); return true; } /** * 撮合. * * @param Order $order 下单 * @param array $list 价格匹配部分 * * @return null|Order */ public function matchUp(Order $order, array $list): ?Order { // 撮合 foreach ($list as $match_info) { $link_name = $order->symbol.':link:'.$match_info['price']; $link_service = new LinkService($link_name); $order = $this->matchOrder($order, $link_service); if ($order->volume <= 0) { break; } } if ($order->volume > 0) { return $order; } return null; } public function matchOrder($order, $link_service) { $match_order = $link_service->getFirst(); if ($match_order) { $compare_result = bccomp($order->volume, $match_order->volume); switch ($compare_result) { case 1: $match_volume = $match_order->volume; $order->volume = bcsub($order->volume, $match_order->volume); $link_service->deleteNode($match_order); $this->deletePoolMatchOrder($match_order); // 撮合成功通知 event(new MatchEvent($order, $match_order, $match_volume)); // 递归撮合 $this->matchOrder($order, $link_service); break; case 0: $match_volume = $match_order->volume; $order->volume = bcsub($order->volume, $match_order->volume); $link_service->deleteNode($match_order); $this->deletePoolMatchOrder($match_order); // 撮合成功通知 event(new MatchEvent($order, $match_order, $match_volume)); break; case -1: $match_volume = $order->volume; $match_order->volume = bcsub($match_order->volume, $order->volume); $order->volume = 0; $link_service->setNode($match_order->node, $match_order); // 委托池更新数量重新设置 $match_order->volume = $match_volume; $this->deletePoolMatchOrder($match_order); // 撮合成功通知 event(new MatchEvent($order, $match_order, $match_volume)); break; default: break; } return $order; } return $order; } /** * 撮合成交更新委托池. */ public function deletePoolMatchOrder($order) { $depth_link = new DepthLinkService(); // 更新委托量 $depth_link->deleteDepthHash($order); // 从深度列表里删除 $depth_link->deleteZset($order); } }
0
0.923856
1
0.923856
game-dev
MEDIA
0.763498
game-dev,web-backend
0.938764
1
0.938764
UserUnknownFactor/GARbro2
3,631
Legacy/Formats/S/StudioFoma/ArcARC.cs
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; // [991119][I’s9] Lovemation namespace GameRes.Formats.Foma { [Serializable] public class Is9Scheme : ResourceScheme { public IDictionary<string, IDictionary<string, uint>> KnownSchemes; } [Export(typeof(ArchiveFormat))] public class ArcOpener : ArchiveFormat { public override string Tag { get { return "ARC/FOMA"; } } public override string Description { get { return "I's9/Studio FOMA resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public override ArcFile TryOpen (ArcView file) { var arc_name = Path.GetFileName (file.Name).ToUpperInvariant(); if (!KnownArcNames.Contains (arc_name)) return null; var dir_name = VFS.GetDirectoryName (file.Name); foreach (var scheme in KnownSchemes) { var exe_name = VFS.CombinePath (dir_name, scheme.Key); if (VFS.FileExists (exe_name)) { uint table_offset; if (scheme.Value.TryGetValue (arc_name, out table_offset)) { var dir = GetEntryList (exe_name, table_offset, file.MaxOffset); if (dir != null) return new ArcFile (file, this, dir); } } } return null; } internal List<Entry> GetEntryList (string exe_name, long table_offset, long max_offset) { using (var exe_file = VFS.OpenView (exe_name)) { if (table_offset >= exe_file.MaxOffset) return null; var exe = new ExeFile (exe_file); var dir = new List<Entry>(); while (table_offset+12 <= exe_file.MaxOffset) { uint name_addr = exe.View.ReadUInt32 (table_offset); if (0 == name_addr) break; var name = exe.GetCString (name_addr); if (string.IsNullOrEmpty (name)) return null; var entry = Create<Entry> (name); entry.Offset = exe.View.ReadUInt32 (table_offset + 4); entry.Size = exe.View.ReadUInt32 (table_offset + 8); if (!entry.CheckPlacement (max_offset)) return null; dir.Add (entry); table_offset += 12; } return dir; } } Is9Scheme m_scheme = new Is9Scheme { KnownSchemes = new Dictionary<string, IDictionary<string, uint>>() }; HashSet<string> m_known_arc_names = null; public override ResourceScheme Scheme { get { return m_scheme; } set { m_scheme = (Is9Scheme)value; m_known_arc_names = null; } } internal IDictionary<string, IDictionary<string, uint>> KnownSchemes { get { return m_scheme.KnownSchemes; } } internal HashSet<string> KnownArcNames { get { return m_known_arc_names ?? (m_known_arc_names = new HashSet<string> (KnownSchemes.Values.SelectMany (v => v.Keys))); } } } }
0
0.916168
1
0.916168
game-dev
MEDIA
0.316275
game-dev
0.935752
1
0.935752
magefree/mage
6,711
Mage.Sets/src/mage/cards/g/GodEternalKefnet.java
package mage.cards.g; import mage.ApprovingObject; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.GodEternalDiesTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.ReplacementEffectImpl; import mage.abilities.effects.common.cost.SpellCostReductionSourceEffect; import mage.abilities.hint.HintUtils; import mage.abilities.keyword.FlyingAbility; import mage.cards.*; import mage.constants.*; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.players.Player; import mage.watchers.common.CardsAmountDrawnThisTurnWatcher; import java.awt.*; import java.util.UUID; /** * @author JayDi85 */ public final class GodEternalKefnet extends CardImpl { public GodEternalKefnet(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}{U}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.ZOMBIE); this.subtype.add(SubType.GOD); this.power = new MageInt(4); this.toughness = new MageInt(5); // Flying this.addAbility(FlyingAbility.getInstance()); // You may reveal the first card you draw each turn as you draw it. Whenever you reveal an instant or sorcery card this way, // copy that card and you may cast the copy. That copy costs {2} less to cast. this.addAbility(new SimpleStaticAbility(new GodEternalKefnetDrawCardReplacementEffect()), new CardsAmountDrawnThisTurnWatcher()); // When God-Eternal Kefnet dies or is put into exile from the battlefield, you may put it into its owner’s library third from the top. this.addAbility(new GodEternalDiesTriggeredAbility()); } private GodEternalKefnet(final GodEternalKefnet card) { super(card); } @Override public GodEternalKefnet copy() { return new GodEternalKefnet(this); } } class GodEternalKefnetDrawCardReplacementEffect extends ReplacementEffectImpl { GodEternalKefnetDrawCardReplacementEffect() { super(Duration.WhileOnBattlefield, Outcome.Neutral); this.staticText = "You may reveal the first card you draw each turn as you draw it. Whenever you reveal an instant " + "or sorcery card this way, copy that card and you may cast the copy. That copy costs {2} less to cast"; } private GodEternalKefnetDrawCardReplacementEffect(final GodEternalKefnetDrawCardReplacementEffect effect) { super(effect); } @Override public GodEternalKefnetDrawCardReplacementEffect copy() { return new GodEternalKefnetDrawCardReplacementEffect(this); } @Override public boolean replaceEvent(GameEvent event, Ability source, Game game) { // reveal top card and drawn (return false to continue default draw) Permanent god = game.getPermanent(source.getSourceId()); Player you = game.getPlayer(source.getControllerId()); if (god == null && you == null) { return false; } Card topCard = you.getLibrary().getFromTop(game); if (topCard == null) { return false; } // reveal you.setTopCardRevealed(true); // cast copy if (topCard.isInstantOrSorcery(game) && you.chooseUse(outcome, "Copy " + topCard.getName() + " and cast it for {2} less?", source, game)) { Card blueprint = topCard.copy(); if (blueprint instanceof SplitCard) { ((SplitCard) blueprint).getLeftHalfCard().addAbility(new SimpleStaticAbility(Zone.ALL, new SpellCostReductionSourceEffect(2))); ((SplitCard) blueprint).getRightHalfCard().addAbility(new SimpleStaticAbility(Zone.ALL, new SpellCostReductionSourceEffect(2))); } else if (blueprint instanceof ModalDoubleFacedCard) { ((ModalDoubleFacedCard) blueprint).getLeftHalfCard().addAbility(new SimpleStaticAbility(Zone.ALL, new SpellCostReductionSourceEffect(2))); ((ModalDoubleFacedCard) blueprint).getRightHalfCard().addAbility(new SimpleStaticAbility(Zone.ALL, new SpellCostReductionSourceEffect(2))); } else { blueprint.addAbility(new SimpleStaticAbility(Zone.ALL, new SpellCostReductionSourceEffect(2))); } Card copiedCard = game.copyCard(blueprint, source, source.getControllerId()); game.getState().setValue("PlayFromNotOwnHandZone" + copiedCard.getId(), Boolean.TRUE); you.cast(you.chooseAbilityForCast(copiedCard, game, false), game, false, new ApprovingObject(source, game)); game.getState().setValue("PlayFromNotOwnHandZone" + copiedCard.getId(), null); } // draw (return false for default draw) return false; } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.DRAW_CARD; } String getAppliedMark(Game game, Ability source) { return source.getId() + "-applied-" + source.getControllerId() + "-" + game.getState().getTurnNum(); } @Override public boolean applies(GameEvent event, Ability source, Game game) { if (!event.getPlayerId().equals(source.getControllerId())) { return false; } Permanent god = game.getPermanent(source.getSourceId()); Player you = game.getPlayer(source.getControllerId()); if (god == null && you == null) { return false; } Card topCard = you.getLibrary().getFromTop(game); if (topCard == null) { return false; } // only first draw card // if card casted on that turn or controlled changed then needs history from watcher CardsAmountDrawnThisTurnWatcher watcher = game.getState().getWatcher(CardsAmountDrawnThisTurnWatcher.class); if (watcher != null && watcher.getAmountCardsDrawn(event.getPlayerId()) != 0) { return false; } // one time use (if multiple cards drawn) String mark = getAppliedMark(game, source); if (game.getState().getValue(mark) != null) { return false; } game.getState().setValue(mark, true); // ask player to reveal top cards String mes = topCard.getName() + ", " + (topCard.isInstantOrSorcery(game) ? HintUtils.prepareText("you can copy it and cast {2} less", Color.green) : HintUtils.prepareText("you can't copy it", Color.red)); return you.chooseUse(Outcome.Benefit, "Reveal first drawn card (" + mes + ")?", source, game); } }
0
0.993146
1
0.993146
game-dev
MEDIA
0.869634
game-dev
0.996011
1
0.996011
daliansky/XiaoXinPro-13-hackintosh
18,419
EFI/EFI-OC(0.6.8)-PRO13/OC/Kexts/SMCBatteryManager.kext/Contents/Resources/SSDT-BATC.dsl
// SSDT-BATC.dsl // // Based on https://github.com/RehabMan/OS-X-ACPI-Battery-Driver/blob/master/SSDT-BATC.dsl // // An SSDT to combine two batteries into one // initial work/testing by ag6952563 (with assistance by RehabMan) // finalize into generic SSDT by RehabMan // some code cleanup/optimization/and bug fixing by RehabMan // modifications to work VirtualSMC SMCBatteryManager by armenio // add _BIX (easy, following the original code from RehabMan) by armenio // // OS X support for multiple batteries is a bit buggy. // This SSDT can be used to combine two batteries into one, // avoiding the bugs. // // It may need modification depending on the ACPI path of your // existing battery objects. // // IMPORTANT: // // To use this SSDT, you must also patch any Notify for either BAT0 or BAT1 // objects. // // The Notify is used to tell the system when a battery is removed or added. // // Any code: // Notify (...BAT0, ...) // -or // Notify (...BAT1, ...) // // Must be changed to: // Notify (...BATC, ...) // // Refer to Dual Battery Support.md for patching details // DefinitionBlock ("", "SSDT", 2, "ACDT", "BATC", 0x00000000) { External (_SB_.PCI0.LPCB.EC, DeviceObj) External (_SB_.PCI0.LPCB.EC.BAT0, DeviceObj) External (_SB_.PCI0.LPCB.EC.BAT0._BIF, MethodObj) External (_SB_.PCI0.LPCB.EC.BAT0._BIX, MethodObj) External (_SB_.PCI0.LPCB.EC.BAT0._BST, MethodObj) External (_SB_.PCI0.LPCB.EC.BAT0._HID, IntObj) External (_SB_.PCI0.LPCB.EC.BAT0._STA, MethodObj) External (_SB_.PCI0.LPCB.EC.BAT1, DeviceObj) External (_SB_.PCI0.LPCB.EC.BAT1._BIF, MethodObj) External (_SB_.PCI0.LPCB.EC.BAT1._BIX, MethodObj) External (_SB_.PCI0.LPCB.EC.BAT1._BST, MethodObj) External (_SB_.PCI0.LPCB.EC.BAT1._HID, IntObj) External (_SB_.PCI0.LPCB.EC.BAT1._STA, MethodObj) Scope (\_SB.PCI0.LPCB.EC) { Device (BATC) { Name (_HID, EisaId ("PNP0C0A")) Name (_UID, 0x02) Method (_INI) { If (_OSI ("Darwin")) { // disable original battery objects by setting invalid _HID ^^BAT0._HID = 0 ^^BAT1._HID = 0 } } Method (_STA) { If (_OSI ("Darwin")) { // call original _STA for BAT0 and BAT1 // result is bitwise OR between them Return (^^BAT0._STA () | ^^BAT1._STA ()) } Else { Return (Zero) } } Method (_BIF) { // Local0 BAT0._BIF // Local1 BAT1._BIF // Local2 BAT0._STA // Local3 BAT1._STA // Local4/Local5 scratch // gather and validate data from BAT0 Local0 = ^^BAT0._BIF () Local2 = ^^BAT0._STA () If (0x1f == Local2) { // check for invalid design capacity Local4 = DerefOf (Local0 [1]) If (!Local4 || Ones == Local4) { Local2 = 0; } // check for invalid last full charge capacity Local4 = DerefOf (Local0 [2]) If (!Local4 || Ones == Local4) { Local2 = 0; } // check for invalid design voltage Local4 = DerefOf (Local0 [4]) If (!Local4 || Ones == Local4) { Local2 = 0; } } // gather and validate data from BAT1 Local1 = ^^BAT1._BIF () Local3 = ^^BAT1._STA () If (0x1f == Local3) { // check for invalid design capacity Local4 = DerefOf (Local1 [1]) If (!Local4 || Ones == Local4) { Local3 = 0; } // check for invalid last full charge capacity Local4 = DerefOf (Local1 [2]) If (!Local4 || Ones == Local4) { Local3 = 0; } // check for invalid design voltage Local4 = DerefOf (Local1 [4]) If (!Local4 || Ones == Local4) { Local3 = 0; } } // find primary and secondary battery If (0x1f != Local2 && 0x1f == Local3) { // make primary use BAT1 data Local0 = Local1 // BAT1._BIF result Local2 = Local3 // BAT1._STA result Local3 = 0 // no secondary battery } // combine batteries into Local0 result if possible If (0x1f == Local2 && 0x1f == Local3) { // _BIF 0 Power Unit - leave BAT0 value // _BIF 1 Design Capacity - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [1]) Local5 = DerefOf (Local1 [1]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [1] = Local4 + Local5 } // _BIF 2 Last Full Charge Capacity - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [2]) Local5 = DerefOf (Local1 [2]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [2] = Local4 + Local5 } // _BIF 3 Battery Technology - leave BAT0 value // _BIF 4 Design Voltage - average between BAT0 and BAT1 values Local4 = DerefOf (Local0 [4]) Local5 = DerefOf (Local1 [4]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [4] = (Local4 + Local5) / 2 } // _BIF 5 Design Capacity of Warning - add BAT0 and BAT1 values Local0 [5] = DerefOf (Local0 [5]) + DerefOf (Local1 [5]) // _BIF 6 Design Capacity of Low - add BAT0 and BAT1 values Local0 [6] = DerefOf (Local0 [6]) + DerefOf (Local1 [6]) // _BIF 7 Battery Capacity Granularity 1 - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [7]) Local5 = DerefOf (Local1 [7]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [7] = Local4 + Local5 } // _BIF 8 Battery Capacity Granularity 2 - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [8]) Local5 = DerefOf (Local1 [8]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [8] = Local4 + Local5 } // _BIF 9 Model Number - concatenate BAT0 and BAT1 values Local0 [0x09] = Concatenate (Concatenate (DerefOf (Local0 [0x09]), " / "), DerefOf (Local1 [0x09])) // _BIF a Serial Number - concatenate BAT0 and BAT1 values Local0 [0x0a] = Concatenate (Concatenate (DerefOf (Local0 [0x0a]), " / "), DerefOf (Local1 [0x0a])) // _BIF b Battery Type - concatenate BAT0 and BAT1 values Local0 [0x0b] = Concatenate (Concatenate (DerefOf (Local0 [0x0b]), " / "), DerefOf (Local1 [0x0b])) // _BIF c OEM Information - concatenate BAT0 and BAT1 values Local0 [0x0c] = Concatenate (Concatenate (DerefOf (Local0 [0x0c]), " / "), DerefOf (Local1 [0x0c])) } Return (Local0) } // _BIF Method (_BIX) { // Local0 BAT0._BIX // Local1 BAT1._BIX // Local2 BAT0._STA // Local3 BAT1._STA // Local4/Local5 scratch // gather and validate data from BAT0 Local0 = ^^BAT0._BIX () Local2 = ^^BAT0._STA () If (0x1f == Local2) { // check for invalid design capacity Local4 = DerefOf (Local0 [2]) If (!Local4 || Ones == Local4) { Local2 = 0; } // check for invalid last full charge capacity Local4 = DerefOf (Local0 [3]) If (!Local4 || Ones == Local4) { Local2 = 0; } // check for invalid design voltage Local4 = DerefOf (Local0 [5]) If (!Local4 || Ones == Local4) { Local2 = 0; } } // gather and validate data from BAT1 Local1 = ^^BAT1._BIX () Local3 = ^^BAT1._STA () If (0x1f == Local3) { // check for invalid design capacity Local4 = DerefOf (Local1 [2]) If (!Local4 || Ones == Local4) { Local3 = 0; } // check for invalid last full charge capacity Local4 = DerefOf (Local1 [3]) If (!Local4 || Ones == Local4) { Local3 = 0; } // check for invalid design voltage Local4 = DerefOf (Local1 [5]) If (!Local4 || Ones == Local4) { Local3 = 0; } } // find primary and secondary battery If (0x1f != Local2 && 0x1f == Local3) { // make primary use BAT1 data Local0 = Local1 // BAT1._BIX result Local2 = Local3 // BAT1._STA result Local3 = 0 // no secondary battery } // combine batteries into Local0 result if possible If (0x1f == Local2 && 0x1f == Local3) { // _BIX 0 Revision - leave BAT0 value // _BIX 1 Power Unit - leave BAT0 value // _BIX 2 Design Capacity - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [2]) Local5 = DerefOf (Local1 [2]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [2] = Local4 + Local5 } // _BIX 3 Last Full Charge Capacity - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [3]) Local5 = DerefOf (Local1 [3]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [3] = Local4 + Local5 } // _BIX 4 Battery Technology - leave BAT0 value // _BIX 5 Design Voltage - average between BAT0 and BAT1 values Local4 = DerefOf (Local0 [5]) Local5 = DerefOf (Local1 [5]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [5] = (Local4 + Local5) / 2 } // _BIX 6 Design Capacity of Warning - add BAT0 and BAT1 values Local0 [6] = DerefOf (Local0 [6]) + DerefOf (Local1 [6]) // _BIX 7 Design Capacity of Low - add BAT0 and BAT1 values Local0 [7] = DerefOf (Local0 [7]) + DerefOf (Local1 [7]) // _BIX 8 Cycle Count - average between BAT0 and BAT1 values Local4 = DerefOf (Local0 [8]) Local5 = DerefOf (Local1 [8]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [8] = (Local4 + Local5) / 2 } // _BIX 9 Measurement Accuracy - average between BAT0 and BAT1 values Local0 [9] = (DerefOf (Local0 [9]) + DerefOf (Local1 [9])) / 2 // _BIX 0xa Max Sampling Time - average between BAT0 and BAT1 values Local4 = DerefOf (Local0 [0xa]) Local5 = DerefOf (Local1 [0xa]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [0xa] = (Local4 + Local5) / 2 } // _BIX 0xb Min Sampling Time - average between BAT0 and BAT1 values Local4 = DerefOf (Local0 [0xb]) Local5 = DerefOf (Local1 [0xb]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [0xb] = (Local4 + Local5) / 2 } // _BIX 0xc Max Averaging Interval - average between BAT0 and BAT1 values Local0 [0xc] = (DerefOf (Local0 [0xc]) + DerefOf (Local1 [0xc])) / 2 // _BIX 0xd Min Averaging Interval - average between BAT0 and BAT1 values Local0 [0xd] = (DerefOf (Local0 [0xd]) + DerefOf (Local1 [0xd])) / 2 // _BIX 0xe Battery Capacity Granularity 1 - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [0xe]) Local5 = DerefOf (Local1 [0xe]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [0xe] = Local4 + Local5 } // _BIX 0xf Battery Capacity Granularity 2 - add BAT0 and BAT1 values Local4 = DerefOf (Local0 [0xf]) Local5 = DerefOf (Local1 [0xf]) If (0xffffffff != Local4 && 0xffffffff != Local5) { Local0 [0xf] = Local4 + Local5 } // _BIX 10 Model Number - concatenate BAT0 and BAT1 values Local0 [0x10] = Concatenate (Concatenate (DerefOf (Local0 [0x10]), " / "), DerefOf (Local1 [0x10])) // _BIX 11 Serial Number - concatenate BAT0 and BAT1 values Local0 [0x11] = Concatenate (Concatenate (DerefOf (Local0 [0x11]), " / "), DerefOf (Local1 [0x11])) // _BIX 12 Battery Type - concatenate BAT0 and BAT1 values Local0 [0x12] = Concatenate (Concatenate (DerefOf (Local0 [0x12]), " / "), DerefOf (Local1 [0x12])) // _BIX 13 OEM Information - concatenate BAT0 and BAT1 values Local0 [0x13] = Concatenate (Concatenate (DerefOf (Local0 [0x13]), " / "), DerefOf (Local1 [0x13])) // _BIX 14 Battery Swapping Capability - leave BAT0 value for now } Return (Local0) } // _BIX Method (_BST) { // Local0 BAT0._BST // Local1 BAT1._BST // Local2 BAT0._STA // Local3 BAT1._STA // Local4/Local5 scratch // gather battery data from BAT0 Local0 = ^^BAT0._BST () Local2 = ^^BAT0._STA () If (0x1f == Local2) { // check for invalid remaining capacity Local4 = DerefOf (Local0 [2]) If (!Local4 || Ones == Local4) { Local2 = 0; } } // gather battery data from BAT1 Local1 = ^^BAT1._BST () Local3 = ^^BAT1._STA () If (0x1f == Local3) { // check for invalid remaining capacity Local4 = DerefOf (Local1 [2]) If (!Local4 || Ones == Local4) { Local3 = 0; } } // find primary and secondary battery If (0x1f != Local2 && 0x1f == Local3) { // make primary use BAT1 data Local0 = Local1 // BAT1._BST result Local2 = Local3 // BAT1._STA result Local3 = 0 // no secondary battery } // combine batteries into Local0 result if possible If (0x1f == Local2 && 0x1f == Local3) { // _BST 0 - Battery State - if one battery is charging, then charging, else discharging Local4 = DerefOf (Local0 [0]) Local5 = DerefOf (Local1 [0]) If (Local4 != Local5) { If (Local4 == 2 || Local5 == 2) { // 2 = charging Local0 [0] = 2 } ElseIf (Local4 == 1 || Local5 == 1) { // 1 = discharging Local0 [0] = 1 } ElseIf (Local4 == 3 || Local5 == 3) { Local0 [0] = 3 } ElseIf (Local4 == 4 || Local5 == 4) { // critical Local0 [0] = 4 } ElseIf (Local4 == 5 || Local5 == 5) { // critical and discharging Local0 [0] = 5 } // if none of the above, just leave as BAT0 is } // _BST 1 - Battery Present Rate - add BAT0 and BAT1 values Local0 [1] = DerefOf (Local0 [1]) + DerefOf (Local1 [1]) // _BST 2 - Battery Remaining Capacity - add BAT0 and BAT1 values Local0 [2] = DerefOf (Local0 [2]) + DerefOf (Local1 [2]) // _BST 3 - Battery Present Voltage - average between BAT0 and BAT1 values Local0 [3] = (DerefOf (Local0 [3]) + DerefOf (Local1 [3])) / 2 } Return (Local0) } // _BST } // BATC } // Scope (...) } //EOF
0
0.680242
1
0.680242
game-dev
MEDIA
0.45457
game-dev
0.99161
1
0.99161
Queerbric/Inspecio
3,128
src/main/java/io/github/queerbric/inspecio/tooltip/PaintingTooltipComponent.java
/* * Copyright (c) 2023 LambdAurora <email@lambdaurora.dev>, Emi * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.github.queerbric.inspecio.tooltip; import io.github.queerbric.inspecio.Inspecio; import io.github.queerbric.inspecio.mixin.DecorationItemAccessor; import net.minecraft.client.MinecraftClient; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.tooltip.TooltipComponent; import net.minecraft.client.item.TooltipData; import net.minecraft.client.texture.PaintingManager; import net.minecraft.client.texture.Sprite; import net.minecraft.entity.EntityType; import net.minecraft.entity.decoration.painting.PaintingEntity; import net.minecraft.entity.decoration.painting.PaintingVariant; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.registry.Holder; import org.quiltmc.loader.api.minecraft.ClientOnly; import org.quiltmc.qsl.tooltip.api.ConvertibleTooltipData; import java.util.Optional; /** * Represents a painting tooltip for painting items with a known variant. * * @param painting the painting variant * @author LambdAurora * @version 1.8.0 * @since 1.8.0 */ @ClientOnly public record PaintingTooltipComponent(PaintingVariant painting) implements ConvertibleTooltipData, TooltipComponent { public static Optional<TooltipData> of(ItemStack stack) { if (!Inspecio.getConfig().hasPainting()) return Optional.empty(); NbtCompound nbt = stack.getNbt(); if (nbt != null && stack.getItem() instanceof DecorationItemAccessor decorationItem && decorationItem.getEntityType() == EntityType.PAINTING ) { var entityNbt = nbt.getCompound("EntityTag"); if (entityNbt != null) { return PaintingEntity.parse(entityNbt) .map(Holder::value) .map(PaintingTooltipComponent::new); } } return Optional.empty(); } @Override public TooltipComponent toComponent() { return this; } @Override public int getHeight() { return this.painting.getHeight(); } @Override public int getWidth(TextRenderer textRenderer) { return this.painting.getWidth(); } @Override public void drawItems(TextRenderer textRenderer, int x, int y, GuiGraphics graphics) { PaintingManager paintingManager = MinecraftClient.getInstance().getPaintingManager(); Sprite sprite = paintingManager.getPaintingSprite(this.painting); graphics.drawSprite(x, y - 2, 0, this.getWidth(textRenderer), this.getHeight(), sprite); } }
0
0.617772
1
0.617772
game-dev
MEDIA
0.906887
game-dev,graphics-rendering
0.898844
1
0.898844
cliqz-oss/browser-f
8,462
mozilla-release/js/src/gc/ArenaList-inl.h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef gc_ArenaList_inl_h #define gc_ArenaList_inl_h #include "gc/ArenaList.h" #include "gc/Heap.h" #include "gc/Zone.h" void js::gc::SortedArenaListSegment::append(Arena* arena) { MOZ_ASSERT(arena); MOZ_ASSERT_IF(head, head->getAllocKind() == arena->getAllocKind()); *tailp = arena; tailp = &arena->next; } inline js::gc::ArenaList::ArenaList() { clear(); } void js::gc::ArenaList::copy(const ArenaList& other) { other.check(); head_ = other.head_; cursorp_ = other.isCursorAtHead() ? &head_ : other.cursorp_; check(); } inline js::gc::ArenaList::ArenaList(const ArenaList& other) { copy(other); } js::gc::ArenaList& js::gc::ArenaList::operator=(const ArenaList& other) { copy(other); return *this; } inline js::gc::ArenaList::ArenaList(const SortedArenaListSegment& segment) { head_ = segment.head; cursorp_ = segment.isEmpty() ? &head_ : segment.tailp; check(); } // This does checking just of |head_| and |cursorp_|. void js::gc::ArenaList::check() const { #ifdef DEBUG // If the list is empty, it must have this form. MOZ_ASSERT_IF(!head_, cursorp_ == &head_); // If there's an arena following the cursor, it must not be full. Arena* cursor = *cursorp_; MOZ_ASSERT_IF(cursor, cursor->hasFreeThings()); #endif } void js::gc::ArenaList::clear() { head_ = nullptr; cursorp_ = &head_; check(); } js::gc::ArenaList js::gc::ArenaList::copyAndClear() { ArenaList result = *this; clear(); return result; } bool js::gc::ArenaList::isEmpty() const { check(); return !head_; } js::gc::Arena* js::gc::ArenaList::head() const { check(); return head_; } bool js::gc::ArenaList::isCursorAtHead() const { check(); return cursorp_ == &head_; } bool js::gc::ArenaList::isCursorAtEnd() const { check(); return !*cursorp_; } void js::gc::ArenaList::moveCursorToEnd() { while (!isCursorAtEnd()) { cursorp_ = &(*cursorp_)->next; } } js::gc::Arena* js::gc::ArenaList::arenaAfterCursor() const { check(); return *cursorp_; } js::gc::Arena* js::gc::ArenaList::takeNextArena() { check(); Arena* arena = *cursorp_; if (!arena) { return nullptr; } cursorp_ = &arena->next; check(); return arena; } void js::gc::ArenaList::insertAtCursor(Arena* a) { check(); a->next = *cursorp_; *cursorp_ = a; // At this point, the cursor is sitting before |a|. Move it after |a| // if necessary. if (!a->hasFreeThings()) { cursorp_ = &a->next; } check(); } void js::gc::ArenaList::insertBeforeCursor(Arena* a) { check(); a->next = *cursorp_; *cursorp_ = a; cursorp_ = &a->next; check(); } js::gc::ArenaList& js::gc::ArenaList::insertListWithCursorAtEnd( const ArenaList& other) { check(); other.check(); MOZ_ASSERT(other.isCursorAtEnd()); if (other.isCursorAtHead()) { return *this; } // Insert the full arenas of |other| after those of |this|. *other.cursorp_ = *cursorp_; *cursorp_ = other.head_; cursorp_ = other.cursorp_; check(); return *this; } js::gc::SortedArenaList::SortedArenaList(size_t thingsPerArena) { reset(thingsPerArena); } void js::gc::SortedArenaList::setThingsPerArena(size_t thingsPerArena) { MOZ_ASSERT(thingsPerArena && thingsPerArena <= MaxThingsPerArena); thingsPerArena_ = thingsPerArena; } void js::gc::SortedArenaList::reset(size_t thingsPerArena) { setThingsPerArena(thingsPerArena); // Initialize the segments. for (size_t i = 0; i <= thingsPerArena; ++i) { segments[i].clear(); } } void js::gc::SortedArenaList::insertAt(Arena* arena, size_t nfree) { MOZ_ASSERT(nfree <= thingsPerArena_); segments[nfree].append(arena); } void js::gc::SortedArenaList::extractEmpty(Arena** empty) { SortedArenaListSegment& segment = segments[thingsPerArena_]; if (segment.head) { *segment.tailp = *empty; *empty = segment.head; segment.clear(); } } js::gc::ArenaList js::gc::SortedArenaList::toArenaList() { // Link the non-empty segment tails up to the non-empty segment heads. size_t tailIndex = 0; for (size_t headIndex = 1; headIndex <= thingsPerArena_; ++headIndex) { if (headAt(headIndex)) { segments[tailIndex].linkTo(headAt(headIndex)); tailIndex = headIndex; } } // Point the tail of the final non-empty segment at null. Note that if // the list is empty, this will just set segments[0].head to null. segments[tailIndex].linkTo(nullptr); // Create an ArenaList with head and cursor set to the head and tail of // the first segment (if that segment is empty, only the head is used). return ArenaList(segments[0]); } #ifdef DEBUG bool js::gc::FreeLists::allEmpty() const { for (auto i : AllAllocKinds()) { if (!isEmpty(i)) { return false; } } return true; } bool js::gc::FreeLists::isEmpty(AllocKind kind) const { return freeLists_[kind]->isEmpty(); } #endif void js::gc::FreeLists::clear() { for (auto i : AllAllocKinds()) { #ifdef DEBUG auto old = freeLists_[i]; if (!old->isEmpty()) { old->getArena()->checkNoMarkedFreeCells(); } #endif freeLists_[i] = &emptySentinel; } } js::gc::TenuredCell* js::gc::FreeLists::allocate(AllocKind kind) { return freeLists_[kind]->allocate(Arena::thingSize(kind)); } void js::gc::FreeLists::unmarkPreMarkedFreeCells(AllocKind kind) { FreeSpan* freeSpan = freeLists_[kind]; if (!freeSpan->isEmpty()) { freeSpan->getArena()->unmarkPreMarkedFreeCells(); } } JSRuntime* js::gc::ArenaLists::runtime() { return zone_->runtimeFromMainThread(); } JSRuntime* js::gc::ArenaLists::runtimeFromAnyThread() { return zone_->runtimeFromAnyThread(); } js::gc::Arena* js::gc::ArenaLists::getFirstArena(AllocKind thingKind) const { return arenaList(thingKind).head(); } js::gc::Arena* js::gc::ArenaLists::getFirstArenaToSweep( AllocKind thingKind) const { return arenasToSweep(thingKind); } js::gc::Arena* js::gc::ArenaLists::getFirstSweptArena( AllocKind thingKind) const { if (thingKind != incrementalSweptArenaKind.ref()) { return nullptr; } return incrementalSweptArenas.ref().head(); } js::gc::Arena* js::gc::ArenaLists::getFirstNewArenaInMarkPhase( AllocKind thingKind) const { return newArenasInMarkPhase(thingKind).head(); } js::gc::Arena* js::gc::ArenaLists::getArenaAfterCursor( AllocKind thingKind) const { return arenaList(thingKind).arenaAfterCursor(); } bool js::gc::ArenaLists::arenaListsAreEmpty() const { for (auto i : AllAllocKinds()) { /* * The arena cannot be empty if the background finalization is not yet * done. */ if (concurrentUse(i) == ConcurrentUse::BackgroundFinalize) { return false; } if (!arenaList(i).isEmpty()) { return false; } } return true; } void js::gc::ArenaLists::unmarkAll() { for (auto i : AllAllocKinds()) { /* The background finalization must have stopped at this point. */ MOZ_ASSERT(concurrentUse(i) == ConcurrentUse::None); for (Arena* arena = arenaList(i).head(); arena; arena = arena->next) { arena->unmarkAll(); } } } bool js::gc::ArenaLists::doneBackgroundFinalize(AllocKind kind) const { return concurrentUse(kind) != ConcurrentUse::BackgroundFinalize; } bool js::gc::ArenaLists::needBackgroundFinalizeWait(AllocKind kind) const { return concurrentUse(kind) == ConcurrentUse::BackgroundFinalize; } void js::gc::ArenaLists::clearFreeLists() { freeLists().clear(); } MOZ_ALWAYS_INLINE js::gc::TenuredCell* js::gc::ArenaLists::allocateFromFreeList( AllocKind thingKind) { return freeLists().allocate(thingKind); } void js::gc::ArenaLists::unmarkPreMarkedFreeCells() { for (auto i : AllAllocKinds()) { freeLists().unmarkPreMarkedFreeCells(i); } } void js::gc::ArenaLists::mergeNewArenasInMarkPhase() { for (auto i : AllAllocKinds()) { arenaList(i).insertListWithCursorAtEnd(newArenasInMarkPhase(i)); newArenasInMarkPhase(i).clear(); } } void js::gc::ArenaLists::checkEmptyFreeLists() { MOZ_ASSERT(freeLists().allEmpty()); } void js::gc::ArenaLists::checkEmptyArenaLists() { #ifdef DEBUG for (auto i : AllAllocKinds()) { checkEmptyArenaList(i); } #endif } #endif // gc_ArenaList_inl_h
0
0.923147
1
0.923147
game-dev
MEDIA
0.366281
game-dev
0.872154
1
0.872154
KirillOsenkov/StructuredEditor
6,279
CSharpBlocks/Blocks/Property/PropertyBlock.cs
using System.Collections.Generic; using GuiLabs.Editor.Actions; using GuiLabs.Editor.Blocks; using GuiLabs.Utils; using GuiLabs.Canvas.DrawStyle; using GuiLabs.Undo; namespace GuiLabs.Editor.CSharp { [BlockSerialization("property")] public class PropertyBlock : CodeBlock, ICSharpBlock, IClassLevel, IHasName, IHasModifiers { #region ctors public PropertyBlock() : base() { GetAccessor = new PropertyGetBlock(); SetAccessor = new PropertySetBlock(); Init(); } public PropertyBlock(PropertyGetBlock getBlock, PropertySetBlock setBlock) : base() { GetAccessor = getBlock; SetAccessor = setBlock; Init(); } private void Init() { this.MyUniversalControl.OpenCurlyHasNegativeLowerMargin = false; NameBlock.MyControl.Box.Margins.SetLeftAndRight(ShapeStyle.DefaultFontSize); NameBlock.MyControl.Box.SetMouseSensitivityToMargins(); NameBlock.MyControl.Layout(); MyUniversalControl.CanOffsetCurlies = true; this.HMembers.Add(Modifiers); this.HMembers.Add(NameBlock); } #endregion #region ReplaceWithField public void ReplaceWithField() { using (Transaction.Create(Root.ActionManager)) { FieldBlock field = new FieldBlock(); field.Modifiers.SetMany( this.Modifiers.GetModifierString()); field.Name = this.Name; this.Replace(field); } } #endregion #region Name public string Name { get { return NameBlock.Text; } set { NameBlock.Text = value; } } private TextBoxBlock mNameBlock = new MemberNameBlock(); public TextBoxBlock NameBlock { get { return mNameBlock; } set { mNameBlock = value; } } #endregion #region Create public static PropertyBlock Create( string propertyModifiers, string propertyType, string propertyName) { PropertyBlock result = new PropertyBlock(); if (!string.IsNullOrEmpty(propertyModifiers)) { result.Modifiers.SetMany(propertyModifiers); } if (!string.IsNullOrEmpty(propertyType)) { result.Modifiers.Set(propertyType); } if (!string.IsNullOrEmpty(propertyName)) { result.Name = propertyName; } return result; } #endregion #region Parent public ClassOrStructBlock ParentClassOrStruct { get { return this.ParentParent as ClassOrStructBlock; } } #endregion #region Modifiers private MemberModifierContainerBlock mModifiers = new MemberModifierContainerBlock(); public MemberModifierContainerBlock Modifiers { get { return mModifiers; } set { mModifiers = value; } } ModifierContainer IHasModifiers.Modifiers { get { return Modifiers; } } public virtual TypeSelectionBlock TypeBlock { get { MemberModifierContainerBlock mm = Modifiers as MemberModifierContainerBlock; if (mm != null) { return mm.TypeBlock; } return null; } } public string GetModifierOnlyString() { List<ModifierSelectionBlock> modBlocks = new List<ModifierSelectionBlock>(); foreach (ModifierSelectionBlock m in this.Modifiers.ModifierBlocks) { if (m != this.TypeBlock) { modBlocks.Add(m); } } return this.Modifiers.GetModifierString(modBlocks); } public string TypeText { get { return TypeBlock.Text; } } #endregion #region Get private PropertyGetBlock mGetAccessor; public PropertyGetBlock GetAccessor { get { return mGetAccessor; } set { if (mGetAccessor == value) { return; } if (this.Root == null) { AssignGetAccessor(value); } else { using (Transaction.Create(this.Root.ActionManager)) { AssignGetAccessor(value); } } } } private void AssignGetAccessor(PropertyGetBlock value) { if (value == null && mGetAccessor != null) { if (SetAccessor == null) { this.ReplaceWithField(); } else { BlockActions.DeleteBlock(mGetAccessor); } } else if (mGetAccessor == null && value != null) { this.VMembers.AddToBeginning(value); } else if (mGetAccessor != null && value != null) { mGetAccessor.Replace(value); } mGetAccessor = value; } #endregion #region Set private PropertySetBlock mSetAccessor; public PropertySetBlock SetAccessor { get { return mSetAccessor; } set { if (mSetAccessor == value) { return; } if (this.Root == null) { AssignSetAccessor(value); } else { using (Transaction.Create(this.Root.ActionManager)) { AssignSetAccessor(value); } } } } private void AssignSetAccessor(PropertySetBlock value) { if (value == null && mSetAccessor != null) { if (GetAccessor == null) { this.ReplaceWithField(); } else { BlockActions.DeleteBlock(mSetAccessor); } } else if (mSetAccessor == null && value != null) { this.VMembers.Add(value); } else if (mSetAccessor != null && value != null) { mSetAccessor.Replace(value); } mSetAccessor = value; } #endregion #region DefaultFocusableControl public override GuiLabs.Canvas.Controls.Control DefaultFocusableControl() { return Modifiers.DefaultFocusableControl(); } #endregion #region Memento public override void ReadFromMemento(Memento storage) { Name = storage["name"]; TypeBlock.Text = storage["type"]; this.Modifiers.SetMany(storage["modifiers"]); } public override void WriteToMemento(Memento storage) { storage["name"] = Name; storage["type"] = TypeBlock.Text; storage["modifiers"] = GetModifierOnlyString(); } public override void AddChildren(IEnumerable<Block> restoredChildren) { foreach (Block child in restoredChildren) { if (child is PropertyGetBlock) { GetAccessor = child as PropertyGetBlock; } if (child is PropertySetBlock) { SetAccessor = child as PropertySetBlock; } } } #endregion #region Style protected override string StyleName() { return "PropertyBlock"; } #endregion #region AcceptVisitor public override void AcceptVisitor(IVisitor Visitor) { Visitor.Visit(this); } #endregion } }
0
0.984346
1
0.984346
game-dev
MEDIA
0.554337
game-dev,desktop-app
0.975144
1
0.975144
GDACollab/Malisense
3,694
Assets/Plugins/AstarPathfindingProject/Core/Misc/ObjectPool.cs
#if !UNITY_EDITOR // Extra optimizations when not running in the editor, but less error checking #define ASTAR_OPTIMIZE_POOLING #endif using System; using System.Collections.Generic; namespace Pathfinding.Util { public interface IAstarPooledObject { void OnEnterPool(); } /// <summary> /// Lightweight object Pool for IAstarPooledObject. /// Handy class for pooling objects of type T which implements the IAstarPooledObject interface. /// /// Usage: /// - Claim a new object using <code> SomeClass foo = ObjectPool<SomeClass>.Claim (); </code> /// - Use it and do stuff with it /// - Release it with <code> ObjectPool<SomeClass>.Release (foo); </code> /// /// After you have released a object, you should never use it again. /// /// \since Version 3.2 /// Version: Since 3.7.6 this class is thread safe /// See: Pathfinding.Util.ListPool /// See: ObjectPoolSimple /// </summary> public static class ObjectPool<T> where T : class, IAstarPooledObject, new(){ public static T Claim () { return ObjectPoolSimple<T>.Claim(); } public static void Release (ref T obj) { obj.OnEnterPool(); ObjectPoolSimple<T>.Release(ref obj); } } /// <summary> /// Lightweight object Pool. /// Handy class for pooling objects of type T. /// /// Usage: /// - Claim a new object using <code> SomeClass foo = ObjectPool<SomeClass>.Claim (); </code> /// - Use it and do stuff with it /// - Release it with <code> ObjectPool<SomeClass>.Release (foo); </code> /// /// After you have released a object, you should never use it again. /// /// \since Version 3.2 /// Version: Since 3.7.6 this class is thread safe /// See: Pathfinding.Util.ListPool /// See: ObjectPool /// </summary> public static class ObjectPoolSimple<T> where T : class, new(){ /// <summary>Internal pool</summary> static List<T> pool = new List<T>(); #if !ASTAR_NO_POOLING static readonly HashSet<T> inPool = new HashSet<T>(); #endif /// <summary> /// Claim a object. /// Returns a pooled object if any are in the pool. /// Otherwise it creates a new one. /// After usage, this object should be released using the Release function (though not strictly necessary). /// </summary> public static T Claim () { #if ASTAR_NO_POOLING return new T(); #else lock (pool) { if (pool.Count > 0) { T ls = pool[pool.Count-1]; pool.RemoveAt(pool.Count-1); inPool.Remove(ls); return ls; } else { return new T(); } } #endif } /// <summary> /// Releases an object. /// After the object has been released it should not be used anymore. /// The variable will be set to null to prevent silly mistakes. /// /// \throws System.InvalidOperationException /// Releasing an object when it has already been released will cause an exception to be thrown. /// However enabling ASTAR_OPTIMIZE_POOLING will prevent this check. /// /// See: Claim /// </summary> public static void Release (ref T obj) { #if !ASTAR_NO_POOLING lock (pool) { #if !ASTAR_OPTIMIZE_POOLING if (!inPool.Add(obj)) { throw new InvalidOperationException("You are trying to pool an object twice. Please make sure that you only pool it once."); } #endif pool.Add(obj); } #endif obj = null; } /// <summary> /// Clears the pool for objects of this type. /// This is an O(n) operation, where n is the number of pooled objects. /// </summary> public static void Clear () { lock (pool) { #if !ASTAR_OPTIMIZE_POOLING && !ASTAR_NO_POOLING inPool.Clear(); #endif pool.Clear(); } } /// <summary>Number of objects of this type in the pool</summary> public static int GetSize () { return pool.Count; } } }
0
0.886759
1
0.886759
game-dev
MEDIA
0.505967
game-dev
0.917587
1
0.917587
b1inkie/dst-api
1,890
scripts_619045/screens/redux/modslistpopup.lua
local TextListPopup = require "screens/redux/textlistpopup" local function BuildOptionalModLink(mod_name) if PLATFORM == "WIN32_STEAM" or PLATFORM == "LINUX_STEAM" or PLATFORM == "OSX_STEAM" then local link_fn, is_generic_url = ModManager:GetLinkForMod(mod_name) if is_generic_url then return nil else return link_fn end else return nil end end local function BuildModList(mod_ids) local mods = {} for i,v in ipairs(mod_ids) do table.insert(mods, { text = KnownModIndex:GetModFancyName(v) or v, -- Adding onclick with the idea that if you have a ton of -- mods, you'd want to be able to jump to information about -- the problem ones. onclick = BuildOptionalModLink(v), }) end return mods end local function QueryName(modname, modtable, textlistpopup) if IsWorkshopMod(modname) then TheSim:QueryWorkshopModName(GetWorkshopIdNumber(modname), function(isSuccessful, modname) if isSuccessful then modtable.text = modname if textlistpopup ~= nil then textlistpopup.scroll_list:RefreshView() end else print("Workshop Name Query Failed!") end end ) end end local ModsListPopup = Class(TextListPopup, function(self, mods_list, title_text, body_text, buttons, spacing, querynames) local built_mods_list = BuildModList(mods_list) TextListPopup._ctor(self, built_mods_list, title_text, body_text, buttons, spacing, true) if querynames then for _, mod in ipairs(built_mods_list) do QueryName(mod.text, built_mods_list[_], self) end end end) return ModsListPopup
0
0.819112
1
0.819112
game-dev
MEDIA
0.913259
game-dev
0.789564
1
0.789564
marc2k3/foo_spider_monkey_panel
1,444
src/js_objects/internal/global_heap_manager.h
#pragma once namespace mozjs { class IHeapUser { public: IHeapUser() = default; virtual ~IHeapUser() = default; virtual void PrepareForGlobalGc() = 0; }; /// @details Contains a tracer, which is removed only in destructor class GlobalHeapManager { public: /// @remark No need to cleanup JS here, since it must be performed manually beforehand anyway ~GlobalHeapManager() = default; GlobalHeapManager(const GlobalHeapManager&) = delete; GlobalHeapManager& operator=(const GlobalHeapManager&) = delete; static [[nodiscard]] std::unique_ptr<GlobalHeapManager> Create(JSContext* cx); public: void RegisterUser(IHeapUser* heapUser); void UnregisterUser(IHeapUser* heapUser); [[nodiscard]] uint32_t Store(JS::HandleValue valueToStore); [[nodiscard]] uint32_t Store(JS::HandleObject valueToStore); [[nodiscard]] uint32_t Store(JS::HandleFunction valueToStore); [[nodiscard]] JS::Heap<JS::Value>& Get(uint32_t id); void Remove(uint32_t id); void Trace(JSTracer* trc); void PrepareForGc(); private: GlobalHeapManager(JSContext* cx); private: JSContext* pJsCtx_ = nullptr; uint32_t currentHeapId_ = 0; using HeapElement = JS::Heap<JS::Value>; std::mutex heapElementsLock_; std::unordered_map<uint32_t, std::unique_ptr<HeapElement>> heapElements_; std::list<std::unique_ptr<HeapElement>> unusedHeapElements_; std::mutex heapUsersLock_; std::unordered_map<IHeapUser*, IHeapUser*> heapUsers_; }; } // namespace mozjs
0
0.867815
1
0.867815
game-dev
MEDIA
0.426829
game-dev
0.64509
1
0.64509
Farama-Foundation/MicroRTS
19,430
data/ahtn/microrts-ahtn-definition-flexible-portfolio.lisp
(defdomain microrts-flexible-portfolio ( ;; ---- ---- ---- ---- ---- ;; ---- OPERATORS ;; ---- ---- ---- ---- ---- (:operator (!wait ?time) (true) ) (:operator (!wait-for-free-unit ?player) (true) ) (:operator (!fill-with-idles ?player) (true) ) (:operator (!idle ?unitid) (unit ?unitid ?_ ?_ ?_ ?_) ) (:operator (!move ?unitid ?position) (and (unit ?unitid ?type ?player ?r ?oldposition) (can-move ?type) ) ) (:operator (!move-into-attack-range ?unitid1 ?unitid2) (and (unit ?unitid1 ?type1 ?player1 ?r1 ?oldposition1) (unit ?unitid2 ?type2 ?player2 ?r2 ?oldposition2) (can-move ?type1) ) ) (:operator (!move-into-harvest-range ?unitid1 ?unitid2) (and (unit ?unitid1 ?type1 ?player1 ?r1 ?oldposition1) (unit ?unitid2 ?type2 ?player2 ?r2 ?oldposition2) (can-move ?type1) ) ) (:operator (!move-into-return-range ?unitid1 ?unitid2) (and (unit ?unitid1 ?type1 ?player1 ?r1 ?oldposition1) (unit ?unitid2 ?type2 ?player2 ?r2 ?oldposition2) (can-move ?type1) ) ) (:operator (!attack ?unitid1 ?unitid2) (and (unit ?unitid1 ?type1 ?player1 ?r1 ?oldposition1) (unit ?unitid2 ?type2 ?player2 ?r2 ?oldposition2) (can-attack ?type1) (in-attack-range ?unitid1 ?unitid2) ) ) (:operator (!harvest ?unitid1 ?unitid2) (and (unit ?unitid1 ?type1 ?player1 ?r1 ?oldposition1) (unit ?unitid2 Resource ?_ ?r2 ?oldposition2) (can-harvest ?type1) (in-harvest-range ?unitid1 ?unitid2) ) ) (:operator (!return ?unitid1 ?unitid2) (and (unit ?unitid1 ?type1 ?player1 1 ?oldposition1) (unit ?unitid2 Base ?_ ?r2 ?oldposition2) (can-harvest ?type1) (in-return-range ?unitid1 ?unitid2) ) ) (:operator (!produce ?unitid1 ?direction ?type) (and (unit ?unitid1 ?type1 ?player1 ?r1 ?oldposition1) (can-produce ?type1 ?type) (has-resources-to-produce ?player1 ?type) (free-building-position (neighbor-position ?oldposition1 ?direction)) ) ) ;; ---- ---- ---- ---- ---- ;; ---- METHODS ;; ---- ---- ---- ---- ---- ;; Worker rush: (:method dp-rush (destroy-player ?player1 ?player2) (:method (destroy-player-rush ?player1 ?player2)) ) (:method dp-rush-win (destroy-player-rush ?player1 ?player2) (:!condition (and (not (unit ?_ ?_ ?player2 ?_ ?_)) (unit ?_ ?_ ?player1 ?_ ?_) )) ) (:method dp-rush-lose (destroy-player-rush ?player1 ?player2) (:!condition (and (not (unit ?_ ?_ ?player1 ?_ ?_)) (unit ?_ ?_ ?player2 ?_ ?_) )) ) (:method dp-rush-1 (destroy-player-rush ?player1 ?player2) (:sequence (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (unit ?baseid Base ?player1 ?_ ?_) (unit ?resourceid Resource ?_ ?_ ?_) (closest-unit-to ?baseid ?workerid Worker ?player1 1 ?_) )) (:method (destroy-player-rush-reserved-unit ?player1 ?player2 ?workerid)) ) ) (:method dp-rush-2 (destroy-player-rush ?player1 ?player2) (:sequence (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (unit ?baseid Base ?player1 ?_ ?_) (closest-unit-to ?baseid ?resourceid Resource ?_ ?_ ?_) (not (unit ?_ Worker ?player1 1 ?_)) (closest-unit-to ?resourceid ?workerid Worker ?player1 0 ?_) )) (:method (destroy-player-rush-reserved-unit ?player1 ?player2 ?workerid)) ) ) (:method dp-rush-3 (destroy-player-rush ?player1 ?player2) (:sequence (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (unit ?_ ?_ ?player1 ?_ ?_) (or (not (unit ?workerid Worker ?player1 ?_ ?_)) (not (unit ?baseid Base ?player1 ?_ ?_)) (not (unit ?resourceid Resource ?_ ?_ ?_)) ) )) (:method (destroy-player-rush-reserved-unit ?player1 ?player2 -1)) ) ) (:method dprru-win (destroy-player-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:!condition (and (unit ?_ ?_ ?player1 ?_ ?_) (not (unit ?_ ?_ ?player2 ?_ ?_)) )) ) (:method dprru-lose (destroy-player-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (not (unit ?_ ?_ ?player1 ?_ ?_)) )) ) (:method dprru-reservedkilled (destroy-player-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:sequence (:!condition (and (not (= ?reservedunitid -1)) (not (unit ?reservedunitid ?_ ?_ ?_ ?_)))) (:method (destroy-player-rush ?player1 ?player2)) ) ) (:method dprru-reservedok (destroy-player-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:sequence (:!condition (or (= ?reservedunitid -1) (unit ?reservedunitid ?_ ?_ ?_ ?_))) (:method (destroy-player-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid -1)) ) ) (:method dprru-nextunit (destroy-player-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid ?lastunit) (:sequence (:!condition (next-available-unit ?lastunit ?player1 ?unitid)) (:parallel (:method (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid)) (:method (destroy-player-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid ?unitid)) ) ) ) (:method dprru-nomoreunits (destroy-player-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid ?lastunit) (:sequence (:!condition (no-more-available-units ?lastunit ?player1)) (:operator (!fill-with-idles ?player1)) (:operator (!wait-for-free-unit ?player1)) ;; (:operator (!wait 4)) (:method (destroy-player-rush-reserved-unit ?player1 ?player2 ?reservedunitid)) ) ) (:method wrub-reserved-1 (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 0 ?_) (closest-unit-to ?unitid ?resourceid Resource ?_ ?_ ?_) (not (in-harvest-range ?unitid ?resourceid)) )) (:operator (!move-into-harvest-range ?unitid ?resourceid)) ) ) (:method wrub-reserved-2 (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 0 ?_) (closest-unit-to ?unitid ?resourceid Resource ?_ ?_ ?_) (in-harvest-range ?unitid ?resourceid) )) (:operator (!harvest ?unitid ?resourceid)) ) ) (:method wrub-reserved-3 (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 1 ?_) (closest-unit-to ?unitid ?baseid Base ?player1 ?_ ?_) (not (in-return-range ?unitid ?baseid)) )) (:operator (!move-into-return-range ?unitid ?baseid)) ) ) (:method wrub-reserved-4 (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 1 ?_) (closest-unit-to ?unitid ?baseid Base ?player1 ?_ ?_) (in-return-range ?unitid ?baseid) )) (:operator (!return ?unitid ?baseid)) ) ) (:method wrub-reserved-5 (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 1 ?_) (not (closest-unit-to ?unitid ?baseid Base ?player1 ?_ ?_)) )) (:operator (!idle ?unitid)) ) ) (:method wrub-base-produce (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Base ?_ ?_ ?_) (has-resources-to-produce ?player1 Worker) (free-producing-direction ?unitid ?direction) )) (:operator (!produce ?unitid ?direction Worker)) ) ) (:method wrub-base-nothing (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Base ?_ ?_ ?_) (or (not (has-resources-to-produce ?player1 Worker)) (not (free-producing-direction ?unitid ?direction)) ) )) ) ) (:method wrub-barracks (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Barracks ?_ ?_ ?_) )) ) ) (:method wrub-melee-attack (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid ?type ?_ ?_ ?_) (can-attack ?type) (unit ?enemyid ?_ ?player2 ?_ ?_) (in-attack-range ?unitid ?enemyid) )) (:operator (!attack ?unitid ?enemyid)) ) ) (:method wrub-melee-move (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid ?type ?_ ?_ ?_) (can-attack ?type) (unit ?enemyid ?_ ?player2 ?_ ?_) (not (in-attack-range ?unitid ?enemyid)) (path-to-attack ?unitid ?enemyid) )) (:operator (!move-into-attack-range ?unitid ?enemyid)) ) ) (:method wrub-melee-cantmove (worker-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid ?type ?_ ?_ ?_) (can-attack ?type) )) (:!condition (not (and (unit ?enemyid ?_ ?player2 ?_ ?_) (path-to-attack ?unitid ?enemyid) ))) ) ) ;; Light rush: (:method dp-light-rush (destroy-player ?player1 ?player2) (:method (destroy-player-light-rush ?player1 ?player2)) ) (:method dp-light-rush-win (destroy-player-light-rush ?player1 ?player2) (:!condition (and (not (unit ?_ ?_ ?player2 ?_ ?_)) (unit ?_ ?_ ?player1 ?_ ?_) )) ) (:method dp-light-rush-lose (destroy-player-light-rush ?player1 ?player2) (:!condition (and (not (unit ?_ ?_ ?player1 ?_ ?_)) (unit ?_ ?_ ?player2 ?_ ?_) )) ) (:method dp-light-rush-1 (destroy-player-light-rush ?player1 ?player2) (:sequence (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (unit ?baseid Base ?player1 ?_ ?_) (unit ?resourceid Resource ?_ ?_ ?_) (closest-unit-to ?baseid ?workerid Worker ?player1 1 ?_) )) (:method (destroy-player-light-rush-reserved-unit ?player1 ?player2 ?workerid)) ) ) (:method dp-light-rush-2 (destroy-player-light-rush ?player1 ?player2) (:sequence (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (unit ?baseid Base ?player1 ?_ ?_) (closest-unit-to ?baseid ?resourceid Resource ?_ ?_ ?_) (not (unit ?_ Worker ?player1 1 ?_)) (closest-unit-to ?resourceid ?workerid Worker ?player1 0 ?_) )) (:method (destroy-player-light-rush-reserved-unit ?player1 ?player2 ?workerid)) ) ) (:method dp-light-rush-3 (destroy-player-light-rush ?player1 ?player2) (:sequence (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (unit ?_ ?_ ?player1 ?_ ?_) (or (not (unit ?workerid Worker ?player1 ?_ ?_)) (not (unit ?baseid Base ?player1 ?_ ?_)) (not (unit ?resourceid Resource ?_ ?_ ?_)) ) )) (:method (destroy-player-light-rush-reserved-unit ?player1 ?player2 -1)) ) ) (:method dprlru-win (destroy-player-light-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:!condition (and (unit ?_ ?_ ?player1 ?_ ?_) (not (unit ?_ ?_ ?player2 ?_ ?_)) )) ) (:method dprlru-lose (destroy-player-light-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:!condition (and (unit ?_ ?_ ?player2 ?_ ?_) (not (unit ?_ ?_ ?player1 ?_ ?_)) )) ) (:method dprlru-reservedkilled (destroy-player-light-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:sequence (:!condition (and (not (= ?reservedunitid -1)) (not (unit ?reservedunitid ?_ ?_ ?_ ?_)))) (:method (destroy-player-rush ?player1 ?player2)) ) ) (:method dprlru-reservedok (destroy-player-light-rush-reserved-unit ?player1 ?player2 ?reservedunitid) (:sequence (:!condition (or (= ?reservedunitid -1) (unit ?reservedunitid ?_ ?_ ?_ ?_))) (:method (destroy-player-light-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid -1)) ) ) (:method dprlru-nextunit (destroy-player-light-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid ?lastunit) (:sequence (:!condition (next-available-unit ?lastunit ?player1 ?unitid)) (:parallel (:method (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid)) (:method (destroy-player-light-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid ?unitid)) ) ) ) (:method dprlru-nomoreunits (destroy-player-light-rush-reserved-unit-rounds ?player1 ?player2 ?reservedunitid ?lastunit) (:sequence (:!condition (no-more-available-units ?lastunit ?player1)) (:operator (!fill-with-idles ?player1)) (:operator (!wait-for-free-unit ?player1)) ;; (:operator (!wait 4)) (:method (destroy-player-light-rush-reserved-unit ?player1 ?player2 ?reservedunitid)) ) ) (:method lrub-reserved-1 (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 0 ?_) (not (unit ?_ Barracks ?player1 ?_ ?_)) (has-resources-to-produce ?player1 Barracks) (free-producing-direction ?unitid ?direction) )) (:operator (!produce ?unitid ?direction Barracks)) ) ) (:method lrub-reserved-2 (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 0 ?_) (or (unit ?_ Barracks ?player1 ?_ ?_) (not (has-resources-to-produce ?player1 Barracks)) (not (free-producing-direction ?unitid ?direction)) ) (closest-unit-to ?unitid ?resourceid Resource ?_ ?_ ?_) (not (in-harvest-range ?unitid ?resourceid)) )) (:operator (!move-into-harvest-range ?unitid ?resourceid)) ) ) (:method lrub-reserved-3 (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 0 ?_) (or (unit ?_ Barracks ?player1 ?_ ?_) (not (has-resources-to-produce ?player1 Barracks)) (not (free-producing-direction ?unitid ?direction)) ) (closest-unit-to ?unitid ?resourceid Resource ?_ ?_ ?_) (in-harvest-range ?unitid ?resourceid) )) (:operator (!harvest ?unitid ?resourceid)) ) ) (:method lrub-reserved-4 (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 1 ?_) (closest-unit-to ?unitid ?baseid Base ?player1 ?_ ?_) (not (in-return-range ?unitid ?baseid)) )) (:operator (!move-into-return-range ?unitid ?baseid)) ) ) (:method lrub-reserved-5 (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 1 ?_) (closest-unit-to ?unitid ?baseid Base ?player1 ?_ ?_) (in-return-range ?unitid ?baseid) )) (:operator (!return ?unitid ?baseid)) ) ) (:method lrub-reserved-6 (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (= ?unitid ?reservedunitid) (unit ?unitid ?_ ?_ 1 ?_) (not (closest-unit-to ?unitid ?baseid Base ?player1 ?_ ?_)) )) (:operator (!idle ?unitid)) ) ) (:method lrub-base-produce (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Base ?_ ?_ ?_) (not (unit ?_ Worker ?player1 ?_ ?_)) (has-resources-to-produce ?player1 Worker) (free-producing-direction ?unitid ?direction) )) (:operator (!produce ?unitid ?direction Worker)) ) ) (:method lrub-base-nothing (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Base ?_ ?_ ?_) (or (unit ?_ Worker ?player1 ?_ ?_) (not (has-resources-to-produce ?player1 Worker)) (not (free-producing-direction ?unitid ?direction)) ) )) ) ) (:method lrub-barracks-produce (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Barracks ?_ ?_ ?_) (has-resources-to-produce ?player1 Light) (free-producing-direction ?unitid ?direction) )) (:operator (!produce ?unitid ?direction Light)) ) ) (:method lrub-barracks-produce (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Barracks ?_ ?_ ?_) (has-resources-to-produce ?player1 Ranged) (free-producing-direction ?unitid ?direction) )) (:operator (!produce ?unitid ?direction Ranged)) ) ) (:method lrub-barracks-nothing (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid Barracks ?_ ?_ ?_) (or (not (has-resources-to-produce ?player1 Light)) (not (free-producing-direction ?unitid ?direction)) ) )) ) ) (:method lrub-melee-attack (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid ?type ?_ ?_ ?_) (can-attack ?type) (unit ?enemyid ?_ ?player2 ?_ ?_) (in-attack-range ?unitid ?enemyid) )) (:operator (!attack ?unitid ?enemyid)) ) ) (:method lrub-melee-move (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid ?type ?_ ?_ ?_) (can-attack ?type) (unit ?enemyid ?_ ?player2 ?_ ?_) (not (in-attack-range ?unitid ?enemyid)) (path-to-attack ?unitid ?enemyid) )) (:operator (!move-into-attack-range ?unitid ?enemyid)) ) ) (:method lrub-melee-cantmove (light-rush-unit-behavior ?player1 ?player2 ?reservedunitid ?unitid) (:sequence (:!condition (and (not (= ?unitid ?reservedunitid)) (unit ?unitid ?type ?_ ?_ ?_) (can-attack ?type) )) (:!condition (not (and (unit ?enemyid ?_ ?player2 ?_ ?_) (path-to-attack ?unitid ?enemyid) ))) ) ) ) )
0
0.729998
1
0.729998
game-dev
MEDIA
0.854777
game-dev
0.897888
1
0.897888
FTL13/FTL13
1,786
code/modules/awaymissions/bluespaceartillery.dm
/obj/machinery/artillerycontrol var/reload = 60 var/reload_cooldown = 60 var/explosiondev = 3 var/explosionmed = 6 var/explosionlight = 12 name = "bluespace artillery control" icon_state = "control_boxp1" icon = 'icons/obj/machines/particle_accelerator.dmi' density = TRUE anchored = TRUE /obj/machinery/artillerycontrol/process() if(reload < reload_cooldown) reload++ /obj/structure/artilleryplaceholder name = "artillery" icon = 'icons/obj/machines/artillery.dmi' anchored = TRUE density = TRUE /obj/structure/artilleryplaceholder/decorative density = FALSE /obj/machinery/artillerycontrol/attack_hand(mob/user) user.set_machine(src) var/dat = "<B>Bluespace Artillery Control:</B><BR>" dat += "Locked on<BR>" dat += "<B>Charge progress: [reload]/[reload_cooldown]:</B><BR>" dat += "<A href='byond://?src=\ref[src];fire=1'>Open Fire</A><BR>" dat += "Deployment of weapon authorized by <br>Nanotrasen Naval Command<br><br>Remember, friendly fire is grounds for termination of your contract and life.<HR>" user << browse(dat, "window=scroll") onclose(user, "scroll") return /obj/machinery/artillerycontrol/Topic(href, href_list) if(..()) return var/A A = input("Area to bombard", "Open Fire", A) in GLOB.teleportlocs var/area/thearea = GLOB.teleportlocs[A] if(usr.stat || usr.restrained()) return if(reload < reload_cooldown) return if(usr.contents.Find(src) || (in_range(src, usr) && isturf(loc)) || issilicon(usr)) priority_announce("Bluespace artillery fire detected. Brace for impact.") message_admins("[key_name_admin(usr)] has launched an artillery strike.") var/list/L = list() for(var/turf/T in get_area_turfs(thearea.type)) L+=T var/loc = pick(L) explosion(loc,explosiondev,explosionmed,explosionlight) reload = 0
0
0.898346
1
0.898346
game-dev
MEDIA
0.993505
game-dev
0.693282
1
0.693282
ss14Starlight/space-station-14
2,263
Content.Shared/Fluids/AbsorbentComponent.cs
using Content.Shared.Audio; using Content.Shared.FixedPoint; using Robust.Shared.Audio; using Robust.Shared.GameStates; using Robust.Shared.Prototypes; namespace Content.Shared.Fluids; /// <summary> /// For entities that can clean up puddles /// </summary> [RegisterComponent, NetworkedComponent, AutoGenerateComponentState] public sealed partial class AbsorbentComponent : Component { /// <summary> /// Used by the client to display a bar showing the reagents contained when held. /// Has to still be networked in case the item is given to someone who didn't see a mop in PVS. /// </summary> [DataField, AutoNetworkedField] public Dictionary<Color, float> Progress = []; /// <summary> /// Name for solution container, that should be used for absorbed solution storage and as source of absorber solution. /// Default is 'absorbed'. /// </summary> [DataField] public string SolutionName = "absorbed"; /// <summary> /// How much solution we can transfer in one interaction. /// </summary> [DataField] public FixedPoint2 PickupAmount = FixedPoint2.New(100); /// <summary> /// The effect spawned when the puddle fully evaporates. /// </summary> [DataField] public EntProtoId MoppedEffect = "PuddleSparkle"; [DataField] public SoundSpecifier PickupSound = new SoundPathSpecifier("/Audio/Effects/Fluids/watersplash.ogg", AudioParams.Default.WithVariation(SharedContentAudioSystem.DefaultVariation)); [DataField] public SoundSpecifier TransferSound = new SoundPathSpecifier("/Audio/Effects/Fluids/slosh.ogg", AudioParams.Default.WithVariation(SharedContentAudioSystem.DefaultVariation).WithVolume(-3f)); public static readonly SoundSpecifier DefaultTransferSound = new SoundPathSpecifier("/Audio/Effects/Fluids/slosh.ogg", AudioParams.Default.WithVariation(SharedContentAudioSystem.DefaultVariation).WithVolume(-3f)); /// <summary> /// Marker that absorbent component owner should try to use 'absorber solution' to replace solution to be absorbed. /// Target solution will be simply consumed into container if set to false. /// </summary> [DataField] public bool UseAbsorberSolution = true; }
0
0.852124
1
0.852124
game-dev
MEDIA
0.86149
game-dev
0.769061
1
0.769061
eliasdaler/edbr
9,096
games/mtp/src/PhysicsSystem.h
#pragma once #include <iostream> #include <unordered_map> #include <vector> #include <Jolt/Jolt.h> #include <Jolt/Core/JobSystemThreadPool.h> #include <Jolt/Physics/Body/BodyActivationListener.h> #include <Jolt/Physics/Character/CharacterVirtual.h> #include <Jolt/Physics/PhysicsSystem.h> #include <edbr/DevTools/JoltDebugRenderer.h> #include <edbr/Graphics/IdTypes.h> #include <edbr/Math/Transform.h> #include <entt/entity/handle.hpp> #include <entt/entity/registry.hpp> #include "Events.h" #include "VirtualCharacterParams.h" namespace Layers { static constexpr JPH::ObjectLayer NON_MOVING = 0; static constexpr JPH::ObjectLayer MOVING = 1; static constexpr JPH::ObjectLayer NUM_LAYERS = 2; }; struct CPUMesh; class InputManager; class EventManager; class SceneCache; class ObjectLayerPairFilterImpl : public JPH::ObjectLayerPairFilter { public: bool ShouldCollide(JPH::ObjectLayer inObject1, JPH::ObjectLayer inObject2) const override { switch (inObject1) { case Layers::NON_MOVING: return inObject2 == Layers::MOVING; // Non moving only collides with moving case Layers::MOVING: return true; // Moving collides with everything default: JPH_ASSERT(false); return false; } } }; namespace BroadPhaseLayers { static constexpr JPH::BroadPhaseLayer NON_MOVING{0}; static constexpr JPH::BroadPhaseLayer MOVING{1}; static constexpr std::uint32_t NUM_LAYERS{2}; }; // BroadPhaseLayerInterface implementation // This defines a mapping between object and broadphase layers. class BPLayerInterfaceImpl final : public JPH::BroadPhaseLayerInterface { public: BPLayerInterfaceImpl() { // Create a mapping table from object to broad phase layer mObjectToBroadPhase[Layers::NON_MOVING] = BroadPhaseLayers::NON_MOVING; mObjectToBroadPhase[Layers::MOVING] = BroadPhaseLayers::MOVING; } std::uint32_t GetNumBroadPhaseLayers() const override { return BroadPhaseLayers::NUM_LAYERS; } JPH::BroadPhaseLayer GetBroadPhaseLayer(JPH::ObjectLayer inLayer) const override { JPH_ASSERT(inLayer < Layers::NUM_LAYERS); return mObjectToBroadPhase[inLayer]; } #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED) const char* GetBroadPhaseLayerName(JPH::BroadPhaseLayer inLayer) const override { switch ((JPH::BroadPhaseLayer::Type)inLayer) { case (JPH::BroadPhaseLayer::Type)BroadPhaseLayers::NON_MOVING: return "NON_MOVING"; case (JPH::BroadPhaseLayer::Type)BroadPhaseLayers::MOVING: return "MOVING"; default: JPH_ASSERT(false); return "INVALID"; } } #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED private: JPH::BroadPhaseLayer mObjectToBroadPhase[Layers::NUM_LAYERS]; }; /// Class that determines if an object layer can collide with a broadphase layer class ObjectVsBroadPhaseLayerFilterImpl : public JPH::ObjectVsBroadPhaseLayerFilter { public: bool ShouldCollide(JPH::ObjectLayer inLayer1, JPH::BroadPhaseLayer inLayer2) const override { switch (inLayer1) { case Layers::NON_MOVING: return inLayer2 == BroadPhaseLayers::MOVING; case Layers::MOVING: return true; default: JPH_ASSERT(false); return false; } } }; // An example contact listener class MyContactListener : public JPH::ContactListener { public: // See: ContactListener JPH::ValidateResult OnContactValidate( const JPH::Body& inBody1, const JPH::Body& inBody2, JPH::RVec3Arg inBaseOffset, const JPH::CollideShapeResult& inCollisionResult) override { // std::cout << "Contact validate callback" << std::endl; // Allows you to ignore a contact before it is created (using layers to not make objects // collide is cheaper!) return JPH::ValidateResult::AcceptAllContactsForThisBodyPair; } void OnContactAdded( const JPH::Body& inBody1, const JPH::Body& inBody2, const JPH::ContactManifold& inManifold, JPH::ContactSettings& ioSettings) override { // std::cout << "A contact was added" << std::endl; } void OnContactPersisted( const JPH::Body& inBody1, const JPH::Body& inBody2, const JPH::ContactManifold& inManifold, JPH::ContactSettings& ioSettings) override { // std::cout << "A contact was persisted" << std::endl; } void OnContactRemoved(const JPH::SubShapeIDPair& inSubShapePair) override { /* std::cout << "A contact was removed" << inSubShapePair.GetBody1ID().GetIndex() << " " << inSubShapePair.GetBody2ID().GetIndex() << std::endl; */ } }; // An example activation listener class MyBodyActivationListener : public JPH::BodyActivationListener { public: void OnBodyActivated(const JPH::BodyID& inBodyID, std::uint64_t inBodyUserData) override { // std::cout << "A body got activated" << std::endl; } void OnBodyDeactivated(const JPH::BodyID& inBodyID, std::uint64_t inBodyUserData) override { // std::cout << "A body went to sleep" << std::endl; } }; class PhysicsSystem { public: PhysicsSystem(EventManager& eventManager); // Need to call this function before init to initialize various Jolt stuff static void InitStaticObjects(); void init(); void drawDebugShapes(const Camera& camera); void handleCharacterInput( float dt, glm::vec3 movementDirection, bool jumping, bool jumpHeld, bool running); void update(float dt, const glm::quat& characterRotation); void cleanup(); void stopCharacterMovement(); void setCharacterPosition(const glm::vec3 pos); glm::vec3 getCharacterPosition() const; glm::vec3 getCharacterVelocity() const; bool isCharacterOnGround() const; // creates entity physics body void addEntity(entt::handle e, SceneCache& sceneCache); JPH::Ref<JPH::Shape> cacheMeshShape( const std::vector<const CPUMesh*>& meshes, const std::vector<MeshId>& meshIds, const std::vector<Transform>& meshTransforms); JPH::BodyID createBody( entt::handle e, const Transform& transform, JPH::Ref<JPH::Shape> shape, bool staticBody, bool sensor); void updateTransform(JPH::BodyID id, const Transform& transform, bool updateScale = false); void setVelocity(JPH::BodyID id, const glm::vec3& velocity); void syncCharacterTransform(); void syncVisibleTransform(JPH::BodyID id, Transform& transform); void doForBody(JPH::BodyID id, std::function<void(const JPH::Body&)> f); JoltDebugRenderer debugRenderer; void updateDevUI(const InputManager& im, float dt); entt::handle getEntityByBodyID(const JPH::BodyID& bodyID) const; const std::vector<entt::handle>& getInteractableEntities() const { return interactableEntities; } void onEntityTeleported(const EntityTeleportedEvent& event); // Remove physics body on destory void onEntityDestroyed(entt::handle e); // draw settings bool drawCollisionLinesWithDepth{true}; bool drawCollisionShapes{false}; bool drawCollisionShapesWireframe{true}; bool drawCollisionShapeBoundingBox{false}; bool drawSensorsOnly{true}; bool drawCharacterShape{false}; private: void collectInteractableEntities(const glm::quat& characterRotation); void drawBodies(const Camera& camera); void sendCollisionEvents(); JPH::PhysicsSystem physicsSystem; EventManager& eventManager; JPH::Body* floor{nullptr}; std::unique_ptr<JPH::TempAllocatorImpl> tempAllocator; JPH::JobSystemThreadPool job_system; BPLayerInterfaceImpl bpLayerInterface; ObjectVsBroadPhaseLayerFilterImpl objectVsBPLayerFilter; ObjectLayerPairFilterImpl objectVsObjectPairFilter; MyContactListener contactListener; MyBodyActivationListener bodyActivationListener; struct CachedMeshShape { std::vector<MeshId> meshIds; std::vector<Transform> meshTransforms; JPH::Ref<JPH::Shape> meshShape; }; std::vector<CachedMeshShape> cachedMeshShapes; std::unordered_map<std::uint32_t, entt::handle> bodyIDToEntity; std::vector<entt::handle> interactableEntities; // character stuff bool characterOnGround{true}; void createCharacter(entt::handle e, const VirtualCharacterParams& cp); void characterPreUpdate(float dt, const glm::quat& characterRotation); // character data entt::handle characterEntity; JPH::Ref<JPH::CharacterVirtual> character; JPH::RefConst<JPH::Shape> characterShape; JPH::Vec3 characterDesiredVelocity; VirtualCharacterParams characterParams; // character interaction JPH::RefConst<JPH::Shape> characterInteractionShape; float interactionSphereRadius{0.5f}; glm::vec3 interactionSphereOffset{0.f, 1.f, 0.5f}; bool handledPlayerInputThisFrame{false}; };
0
0.934138
1
0.934138
game-dev
MEDIA
0.837556
game-dev
0.817366
1
0.817366
Ordyns/MakeNewWay
6,151
Assets/Plugins/Zenject/Source/Binding/Binders/Factory/FactoryFromBinder/SubContainerBinder/FactorySubContainerBinder0.cs
using System; using ModestTree; namespace Zenject { [NoReflectionBaking] public class FactorySubContainerBinder<TContract> : FactorySubContainerBinderBase<TContract> { public FactorySubContainerBinder( DiContainer bindContainer, BindInfo bindInfo, FactoryBindInfo factoryBindInfo, object subIdentifier) : base(bindContainer, bindInfo, factoryBindInfo, subIdentifier) { } public ScopeConcreteIdArgConditionCopyNonLazyBinder ByMethod(Action<DiContainer> installerMethod) { var subcontainerBindInfo = new SubContainerCreatorBindInfo(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByMethod( container, subcontainerBindInfo, installerMethod), false); return new ScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo); } #if !NOT_UNITY3D public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectMethod(Action<DiContainer> installerMethod) { var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewGameObjectMethod( container, gameObjectInfo, installerMethod), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod( Func<InjectContext, UnityEngine.Object> prefabGetter, Action<DiContainer> installerMethod) { var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefabMethod( container, new PrefabProviderCustom(prefabGetter), gameObjectInfo, installerMethod), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod( UnityEngine.Object prefab, Action<DiContainer> installerMethod) { BindingUtil.AssertIsValidPrefab(prefab); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefabMethod( container, new PrefabProvider(prefab), gameObjectInfo, installerMethod), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceMethod( string resourcePath, Action<DiContainer> installerMethod) { BindingUtil.AssertIsValidResourcePath(resourcePath); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefabMethod( container, new PrefabProviderResource(resourcePath), gameObjectInfo, installerMethod), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } [System.Obsolete("ByNewPrefab has been renamed to ByNewContextPrefab to avoid confusion with ByNewPrefabInstaller and ByNewPrefabMethod")] public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefab(UnityEngine.Object prefab) { return ByNewContextPrefab(prefab); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewContextPrefab(UnityEngine.Object prefab) { BindingUtil.AssertIsValidPrefab(prefab); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefab( container, new PrefabProvider(prefab), gameObjectInfo), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } [System.Obsolete("ByNewPrefabResource has been renamed to ByNewContextPrefabResource to avoid confusion with ByNewPrefabResourceInstaller and ByNewPrefabResourceMethod")] public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResource(string resourcePath) { return ByNewContextPrefabResource(resourcePath); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewContextPrefabResource(string resourcePath) { BindingUtil.AssertIsValidResourcePath(resourcePath); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefab( container, new PrefabProviderResource(resourcePath), gameObjectInfo), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } #endif } }
0
0.845931
1
0.845931
game-dev
MEDIA
0.847814
game-dev
0.795711
1
0.795711
PotRooms/StarResonanceData
3,517
lua/ui/view/fade_window_view.lua
local UI = Z.UI local super = require("ui.ui_view_base") local Fade_windowView = class("Fade_windowView", super) function Fade_windowView:ctor() self.uiBinder = nil super.ctor(self, "fade_window") end function Fade_windowView:onFadeIn(data) if self.timeOutTimer then self.timerMgr:StopTimer(self.timeOutTimer) self.timeOutTimer = nil end self.uiBinder.comp_tween_main:Pause() Z.LuaBridge.SetBackgroundLoadingPriority(true) self.uiBinder.canvas_group_main.alpha = 0 local openAnimType = Z.DOTweenAnimType.Open if data and data.OpenAnimType then openAnimType = data.OpenAnimType end if data and data.IsInstant then self.uiBinder.comp_tween_main:Rewind(openAnimType) self.uiBinder.comp_tween_main:Complete(openAnimType) self:onFadeInEnd(data) else Z.CoroUtil.create_coro_xpcall(function() local coro = Z.CoroUtil.async_to_sync(self.uiBinder.comp_tween_main.CoroPlay) coro(self.uiBinder.comp_tween_main, openAnimType) self:onFadeInEnd(data) end, function(err) if err == ZUtil.ZCancelSource.CancelException then return end Z.LuaBridge.SetBackgroundLoadingPriority(false) end)() end end function Fade_windowView:onFadeInEnd(data) if not data then return end if data.TimeOut ~= nil and data.TimeOut > 0 then self.timeOutTimer = self.timerMgr:StartTimer(function() self.timeOutTimer = nil self:onFadeOut() end, data.TimeOut) end if data.EndCallback ~= nil then data.EndCallback() end if data.MaskType and data.WaitId then Z.WaitFadeManager:SetFadeOutCondition(data.MaskType, data.WaitId) end end function Fade_windowView:onFadeOut(data) if self.timeOutTimer then self.timerMgr:StopTimer(self.timeOutTimer) self.timeOutTimer = nil end self.uiBinder.comp_tween_main:Pause() Z.LuaBridge.SetBackgroundLoadingPriority(false) local closeAnimType = Z.DOTweenAnimType.Close if data and data.CloseAnimType then closeAnimType = data.CloseAnimType end if data and data.IsInstant then self.uiBinder.comp_tween_main:Rewind(closeAnimType) self.uiBinder.comp_tween_main:Complete(closeAnimType) self:onFadeOutEnd(data) else Z.CoroUtil.create_coro_xpcall(function() local coro = Z.CoroUtil.async_to_sync(self.uiBinder.comp_tween_main.CoroPlay) coro(self.uiBinder.comp_tween_main, closeAnimType) self:onFadeOutEnd(data) end)() end end function Fade_windowView:onFadeOutEnd(data) self.uiBinder.canvas_group_main.alpha = 0 if data ~= nil and data.EndCallback ~= nil then data.EndCallback() end Z.UIMgr:CloseView("fade_window") end function Fade_windowView:OnActive() Z.UIMgr:SetUIViewInputIgnore(self.viewConfigKey, 4294967295, true) Z.InputMgr:EnableInput(false, Panda.ZGame.EInputMgrEableSource.FadeWindow) self:bindEvents() end function Fade_windowView:OnDeActive() Z.InputMgr:EnableInput(true, Panda.ZGame.EInputMgrEableSource.FadeWindow) Z.UIMgr:SetUIViewInputIgnore(self.viewConfigKey, 4294967295, false) Z.LuaBridge.SetBackgroundLoadingPriority(false) end function Fade_windowView:OnRefresh() local fadeArgs = self.viewData local color if fadeArgs and fadeArgs.IsWhite then color = Color.New(1, 1, 1, 1) else color = Color.New(0, 0, 0, 1) end self.uiBinder.img_main:SetColor(color) if fadeArgs and fadeArgs.IsOpen then self:onFadeIn(fadeArgs) else self:onFadeOut(fadeArgs) end end function Fade_windowView:bindEvents() end return Fade_windowView
0
0.83704
1
0.83704
game-dev
MEDIA
0.60087
game-dev,desktop-app
0.98468
1
0.98468