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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cortex-command-community/Cortex-Command-Community-Project | 39,158 | Source/Lua/LuaBindingsManagers.cpp | // Make sure that binding definition files are always set to NOT use pre-compiled headers and conformance mode (/permissive) otherwise everything will be on fire!
#include "LuaBindingRegisterDefinitions.h"
using namespace RTE;
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, ActivityMan) {
return luabind::class_<ActivityMan>("ActivityManager")
.property("DefaultActivityType", &ActivityMan::GetDefaultActivityType, &ActivityMan::SetDefaultActivityType)
.property("DefaultActivityName", &ActivityMan::GetDefaultActivityName, &ActivityMan::SetDefaultActivityName)
.def("SetStartActivity", &ActivityMan::SetStartActivity, luabind::adopt(_2)) // Transfers ownership of the Activity to start into the ActivityMan, adopts ownership (_1 is the this ptr)
.def("GetStartActivity", &ActivityMan::GetStartActivity)
.def("GetActivity", &ActivityMan::GetActivity)
.def("StartActivity", (int(ActivityMan::*)(Activity*)) & ActivityMan::StartActivity, luabind::adopt(_2)) // Transfers ownership of the Activity to start into the ActivityMan, adopts ownership (_1 is the this ptr)
.def("StartActivity", (int(ActivityMan::*)(const std::string&, const std::string&)) & ActivityMan::StartActivity)
.def("RestartActivity", &ActivityMan::RestartActivity)
.def("PauseActivity", &ActivityMan::PauseActivity)
.def("EndActivity", &ActivityMan::EndActivity)
.def("ActivityRunning", &ActivityMan::ActivityRunning)
.def("ActivityPaused", &ActivityMan::ActivityPaused)
.def("SaveGame", &ActivityMan::SaveCurrentGame)
.def("LoadGame", &ActivityMan::LoadAndLaunchGame);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, AudioMan) {
return luabind::class_<AudioMan>("AudioManager")
.property("MusicVolume", &AudioMan::GetMusicVolume, &AudioMan::SetMusicVolume)
.property("SoundsVolume", &AudioMan::GetSoundsVolume, &AudioMan::SetSoundsVolume)
.def("StopAll", &AudioMan::StopAll)
.def("GetGlobalPitch", &AudioMan::GetGlobalPitch)
.def("IsMusicPlaying", &AudioMan::IsMusicPlaying)
.def("SetMusicPitch", &AudioMan::SetMusicPitch)
.def("SetMusicMuffledState", &AudioMan::SetMusicMuffledState)
.def("PlaySound", (SoundContainer * (AudioMan::*)(const std::string& filePath)) & AudioMan::PlaySound, luabind::adopt(luabind::result))
.def("PlaySound", (SoundContainer * (AudioMan::*)(const std::string& filePath, const Vector& position)) & AudioMan::PlaySound, luabind::adopt(luabind::result))
.def("PlaySound", (SoundContainer * (AudioMan::*)(const std::string& filePath, const Vector& position, int player)) & AudioMan::PlaySound, luabind::adopt(luabind::result));
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, MusicMan) {
return luabind::class_<MusicMan>("MusicManager")
.def("ResetMusicState", &MusicMan::ResetMusicState)
.def("IsMusicPlaying", &MusicMan::IsMusicPlaying)
.def("PlayDynamicSong", &LuaAdaptersMusicMan::PlayDynamicSong1)
.def("PlayDynamicSong", &LuaAdaptersMusicMan::PlayDynamicSong2)
.def("PlayDynamicSong", &LuaAdaptersMusicMan::PlayDynamicSong3)
.def("PlayDynamicSong", &LuaAdaptersMusicMan::PlayDynamicSong4)
.def("PlayDynamicSong", &LuaAdaptersMusicMan::PlayDynamicSong5)
.def("SetNextDynamicSongSection", &LuaAdaptersMusicMan::SetNextDynamicSongSection1)
.def("SetNextDynamicSongSection", &LuaAdaptersMusicMan::SetNextDynamicSongSection2)
.def("SetNextDynamicSongSection", &LuaAdaptersMusicMan::SetNextDynamicSongSection3)
.def("SetNextDynamicSongSection", &LuaAdaptersMusicMan::SetNextDynamicSongSection4)
.def("CyclePlayingSoundContainers", &LuaAdaptersMusicMan::CyclePlayingSoundContainers1)
.def("CyclePlayingSoundContainers", &LuaAdaptersMusicMan::CyclePlayingSoundContainers2)
.def("GetCurrentDynamicSongSectionType", &MusicMan::GetCurrentSongSectionType)
.def("EndDynamicMusic", &LuaAdaptersMusicMan::EndDynamicMusic1)
.def("EndDynamicMusic", &LuaAdaptersMusicMan::EndDynamicMusic2)
.def("PlayInterruptingMusic", &MusicMan::PlayInterruptingMusic)
.def("EndInterruptingMusic", &MusicMan::EndInterruptingMusic);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, ConsoleMan) {
return luabind::class_<ConsoleMan>("ConsoleManager")
.def("PrintString", &ConsoleMan::PrintString)
.def("SaveInputLog", &ConsoleMan::SaveInputLog)
.def("SaveAllText", &ConsoleMan::SaveAllText)
.def("Clear", &ConsoleMan::ClearLog);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, FrameMan) {
return luabind::class_<FrameMan>("FrameManager")
.property("PlayerScreenWidth", &FrameMan::GetPlayerScreenWidth)
.property("PlayerScreenHeight", &FrameMan::GetPlayerScreenHeight)
.property("ScreenCount", &FrameMan::GetScreenCount)
.property("ResolutionMultiplier", &FrameMan::GetResolutionMultiplier)
.def("IsHudDisabled", &FrameMan::IsHudDisabled)
.def("SetHudDisabled", &FrameMan::SetHudDisabled)
.def("LoadPalette", &FrameMan::LoadPalette)
.def("SetScreenText", &FrameMan::SetScreenText)
.def("ClearScreenText", &FrameMan::ClearScreenText)
.def("FadeInPalette", &FrameMan::FadeInPalette)
.def("FadeOutPalette", &FrameMan::FadeOutPalette)
.def("SaveScreenToPNG", &FrameMan::SaveScreenToPNG)
.def("SaveBitmapToPNG", &FrameMan::SaveBitmapToPNG)
.def("FlashScreen", &FrameMan::FlashScreen)
.def("CalculateTextHeight", &FrameMan::CalculateTextHeight)
.def("CalculateTextWidth", &FrameMan::CalculateTextWidth)
.def("SplitStringToFitWidth", &FrameMan::SplitStringToFitWidth);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, MetaMan) {
return luabind::class_<MetaMan>("MetaManager")
.property("GameName", &MetaMan::GetGameName, &MetaMan::SetGameName)
.property("PlayerTurn", &MetaMan::GetPlayerTurn)
.property("PlayerCount", &MetaMan::GetPlayerCount)
.def_readonly("Players", &MetaMan::m_Players, luabind::return_stl_iterator)
.def("GetTeamOfPlayer", &MetaMan::GetTeamOfPlayer)
.def("GetPlayer", &MetaMan::GetPlayer)
.def("GetMetaPlayerOfInGamePlayer", &MetaMan::GetMetaPlayerOfInGamePlayer);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, MovableMan) {
return luabind::class_<MovableMan>("MovableManager")
.property("MaxDroppedItems", &MovableMan::GetMaxDroppedItems, &MovableMan::SetMaxDroppedItems)
.def_readonly("Actors", &MovableMan::m_Actors, luabind::return_stl_iterator)
.def_readonly("Items", &MovableMan::m_Items, luabind::return_stl_iterator)
.def_readonly("Particles", &MovableMan::m_Particles, luabind::return_stl_iterator)
.def_readonly("AddedActors", &MovableMan::m_AddedActors, luabind::return_stl_iterator)
.def_readonly("AddedItems", &MovableMan::m_AddedItems, luabind::return_stl_iterator)
.def_readonly("AddedParticles", &MovableMan::m_AddedParticles, luabind::return_stl_iterator)
.def_readonly("AlarmEvents", &MovableMan::m_AlarmEvents, luabind::return_stl_iterator)
.def_readonly("AddedAlarmEvents", &MovableMan::m_AddedAlarmEvents, luabind::return_stl_iterator)
.def("GetMOFromID", &MovableMan::GetMOFromID)
.def("FindObjectByUniqueID", &MovableMan::FindObjectByUniqueID)
.def("GetMOIDCount", &MovableMan::GetMOIDCount)
.def("GetTeamMOIDCount", &MovableMan::GetTeamMOIDCount)
.def("PurgeAllMOs", &MovableMan::PurgeAllMOs)
.def("GetNextActorInGroup", &MovableMan::GetNextActorInGroup)
.def("GetPrevActorInGroup", &MovableMan::GetPrevActorInGroup)
.def("GetNextTeamActor", &MovableMan::GetNextTeamActor)
.def("GetPrevTeamActor", &MovableMan::GetPrevTeamActor)
.def("GetClosestTeamActor", (Actor * (MovableMan::*)(int team, int player, const Vector& scenePoint, int maxRadius, Vector& getDistance, const Actor* excludeThis)) & MovableMan::GetClosestTeamActor)
.def("GetClosestTeamActor", (Actor * (MovableMan::*)(int team, int player, const Vector& scenePoint, int maxRadius, Vector& getDistance, bool onlyPlayerControllableActors, const Actor* excludeThis)) & MovableMan::GetClosestTeamActor)
.def("GetClosestEnemyActor", &MovableMan::GetClosestEnemyActor)
.def("GetFirstTeamActor", &MovableMan::GetFirstTeamActor)
.def("GetClosestActor", &MovableMan::GetClosestActor)
.def("GetClosestBrainActor", &MovableMan::GetClosestBrainActor)
.def("GetFirstBrainActor", &MovableMan::GetFirstBrainActor)
.def("GetClosestOtherBrainActor", &MovableMan::GetClosestOtherBrainActor)
.def("GetFirstOtherBrainActor", &MovableMan::GetFirstOtherBrainActor)
.def("GetUnassignedBrain", &MovableMan::GetUnassignedBrain)
.def("GetParticleCount", &MovableMan::GetParticleCount)
.def("GetSplashRatio", &MovableMan::GetSplashRatio)
.def("SortTeamRoster", &MovableMan::SortTeamRoster)
.def("ChangeActorTeam", &MovableMan::ChangeActorTeam)
.def("RemoveActor", &MovableMan::RemoveActor, luabind::adopt(luabind::return_value))
.def("RemoveItem", &MovableMan::RemoveItem, luabind::adopt(luabind::return_value))
.def("RemoveParticle", &MovableMan::RemoveParticle, luabind::adopt(luabind::return_value))
.def("ValidMO", &MovableMan::ValidMO)
.def("IsActor", &MovableMan::IsActor)
.def("IsDevice", &MovableMan::IsDevice)
.def("IsParticle", &MovableMan::IsParticle)
.def("IsOfActor", &MovableMan::IsOfActor)
.def("GetRootMOID", &MovableMan::GetRootMOID)
.def("RemoveMO", &MovableMan::RemoveMO)
.def("KillAllTeamActors", &MovableMan::KillAllTeamActors)
.def("KillAllEnemyActors", &MovableMan::KillAllEnemyActors)
.def("OpenAllDoors", &MovableMan::OpenAllDoors)
.def("IsParticleSettlingEnabled", &MovableMan::IsParticleSettlingEnabled)
.def("EnableParticleSettling", &MovableMan::EnableParticleSettling)
.def("IsMOSubtractionEnabled", &MovableMan::IsMOSubtractionEnabled)
.def("GetMOsInBox", (const std::vector<MovableObject*>* (MovableMan::*)(const Box& box) const) & MovableMan::GetMOsInBox, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsInBox", (const std::vector<MovableObject*>* (MovableMan::*)(const Box& box, int ignoreTeam) const) & MovableMan::GetMOsInBox, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsInBox", (const std::vector<MovableObject*>* (MovableMan::*)(const Box& box, int ignoreTeam, bool getsHitByMOsOnly) const) & MovableMan::GetMOsInBox, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsInRadius", (const std::vector<MovableObject*>* (MovableMan::*)(const Vector& centre, float radius) const) & MovableMan::GetMOsInRadius, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsInRadius", (const std::vector<MovableObject*>* (MovableMan::*)(const Vector& centre, float radius, int ignoreTeam) const) & MovableMan::GetMOsInRadius, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsInRadius", (const std::vector<MovableObject*>* (MovableMan::*)(const Vector& centre, float radius, int ignoreTeam, bool getsHitByMOsOnly) const) & MovableMan::GetMOsInRadius, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsAtPosition", (const std::vector<MovableObject*>* (MovableMan::*)(int pixelX, int pixelY) const) & MovableMan::GetMOsAtPosition, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsAtPosition", (const std::vector<MovableObject*>* (MovableMan::*)(int pixelX, int pixelY, int ignoreTeam) const) & MovableMan::GetMOsAtPosition, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("GetMOsAtPosition", (const std::vector<MovableObject*>* (MovableMan::*)(int pixelX, int pixelY, int ignoreTeam, bool getsHitByMOsOnly) const) & MovableMan::GetMOsAtPosition, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("SendGlobalMessage", &LuaAdaptersMovableMan::SendGlobalMessage1)
.def("SendGlobalMessage", &LuaAdaptersMovableMan::SendGlobalMessage2)
.def("AddMO", &LuaAdaptersMovableMan::AddMO, luabind::adopt(_2))
.def("AddActor", &LuaAdaptersMovableMan::AddActor, luabind::adopt(_2))
.def("AddItem", &LuaAdaptersMovableMan::AddItem, luabind::adopt(_2))
.def("AddParticle", &LuaAdaptersMovableMan::AddParticle, luabind::adopt(_2));
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, PerformanceMan) {
return luabind::class_<PerformanceMan>("PerformanceManager")
.property("ShowPerformanceStats", &PerformanceMan::IsShowingPerformanceStats, &PerformanceMan::ShowPerformanceStats);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, PostProcessMan) {
return luabind::class_<PostProcessMan>("PostProcessManager")
.def("RegisterPostEffect", &PostProcessMan::RegisterPostEffect);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, PresetMan) {
return luabind::class_<PresetMan>("PresetManager")
.def_readonly("Modules", &PresetMan::m_pDataModules, luabind::return_stl_iterator)
.def("LoadDataModule", (bool(PresetMan::*)(const std::string&)) & PresetMan::LoadDataModule)
.def("GetDataModule", &PresetMan::GetDataModule)
.def("GetModuleID", &PresetMan::GetModuleID)
.def("GetModuleIDFromPath", &PresetMan::GetModuleIDFromPath)
.def("GetTotalModuleCount", &PresetMan::GetTotalModuleCount)
.def("GetOfficialModuleCount", &PresetMan::GetOfficialModuleCount)
.def("AddPreset", &PresetMan::AddEntityPreset)
.def("GetPreset", (const Entity* (PresetMan::*)(std::string, std::string, int)) & PresetMan::GetEntityPreset)
.def("GetPreset", (const Entity* (PresetMan::*)(std::string, std::string, std::string)) & PresetMan::GetEntityPreset)
.def("GetLoadout", (Actor * (PresetMan::*)(std::string, std::string, bool)) & PresetMan::GetLoadout, luabind::adopt(luabind::result))
.def("GetLoadout", (Actor * (PresetMan::*)(std::string, int, bool)) & PresetMan::GetLoadout, luabind::adopt(luabind::result))
.def("GetRandomOfGroup", &PresetMan::GetRandomOfGroup)
.def("GetRandomOfGroupInModuleSpace", &PresetMan::GetRandomOfGroupInModuleSpace)
.def("GetEntityDataLocation", &PresetMan::GetEntityDataLocation)
.def("ReadReflectedPreset", &PresetMan::ReadReflectedPreset)
.def("ReloadEntityPreset", &LuaAdaptersPresetMan::ReloadEntityPreset1)
.def("ReloadEntityPreset", &LuaAdaptersPresetMan::ReloadEntityPreset2)
.def("GetAllEntities", &LuaAdaptersPresetMan::GetAllEntities, luabind::adopt(luabind::result) + luabind::return_stl_iterator)
.def("GetAllEntitiesOfGroup", &LuaAdaptersPresetMan::GetAllEntitiesOfGroup, luabind::adopt(luabind::result) + luabind::return_stl_iterator)
.def("GetAllEntitiesOfGroup", &LuaAdaptersPresetMan::GetAllEntitiesOfGroup2, luabind::adopt(luabind::result) + luabind::return_stl_iterator)
.def("GetAllEntitiesOfGroup", &LuaAdaptersPresetMan::GetAllEntitiesOfGroup3, luabind::adopt(luabind::result) + luabind::return_stl_iterator)
.def("ReloadAllScripts", &PresetMan::ReloadAllScripts)
.def("IsModuleOfficial", &PresetMan::IsModuleOfficial)
.def("IsModuleUserdata", &PresetMan::IsModuleUserdata)
.def("GetFullModulePath", &PresetMan::GetFullModulePath);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, PrimitiveMan) {
return luabind::class_<PrimitiveMan>("PrimitiveManager")
.def("DrawLinePrimitive", (void(PrimitiveMan::*)(const Vector& start, const Vector& end, unsigned char color)) & PrimitiveMan::DrawLinePrimitive)
.def("DrawLinePrimitive", (void(PrimitiveMan::*)(const Vector& start, const Vector& end, unsigned char color, int thickness)) & PrimitiveMan::DrawLinePrimitive)
.def("DrawLinePrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const Vector& end, unsigned char color)) & PrimitiveMan::DrawLinePrimitive)
.def("DrawLinePrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const Vector& end, unsigned char color, int thickness)) & PrimitiveMan::DrawLinePrimitive)
.def("DrawArcPrimitive", (void(PrimitiveMan::*)(const Vector& pos, float startAngle, float endAngle, int radius, unsigned char color)) & PrimitiveMan::DrawArcPrimitive)
.def("DrawArcPrimitive", (void(PrimitiveMan::*)(const Vector& pos, float startAngle, float endAngle, int radius, unsigned char color, int thickness)) & PrimitiveMan::DrawArcPrimitive)
.def("DrawArcPrimitive", (void(PrimitiveMan::*)(int player, const Vector& pos, float startAngle, float endAngle, int radius, unsigned char color)) & PrimitiveMan::DrawArcPrimitive)
.def("DrawArcPrimitive", (void(PrimitiveMan::*)(int player, const Vector& pos, float startAngle, float endAngle, int radius, unsigned char color, int thickness)) & PrimitiveMan::DrawArcPrimitive)
.def("DrawSplinePrimitive", (void(PrimitiveMan::*)(const Vector& start, const Vector& guideA, const Vector& guideB, const Vector& end, unsigned char color)) & PrimitiveMan::DrawSplinePrimitive)
.def("DrawSplinePrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const Vector& guideA, const Vector& guideB, const Vector& end, unsigned char color)) & PrimitiveMan::DrawSplinePrimitive)
.def("DrawBoxPrimitive", (void(PrimitiveMan::*)(const Vector& start, const Vector& end, unsigned char color)) & PrimitiveMan::DrawBoxPrimitive)
.def("DrawBoxPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const Vector& end, unsigned char color)) & PrimitiveMan::DrawBoxPrimitive)
.def("DrawBoxFillPrimitive", (void(PrimitiveMan::*)(const Vector& start, const Vector& end, unsigned char color)) & PrimitiveMan::DrawBoxFillPrimitive)
.def("DrawBoxFillPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const Vector& end, unsigned char color)) & PrimitiveMan::DrawBoxFillPrimitive)
.def("DrawRoundedBoxPrimitive", (void(PrimitiveMan::*)(const Vector& start, const Vector& end, int cornerRadius, unsigned char color)) & PrimitiveMan::DrawRoundedBoxPrimitive)
.def("DrawRoundedBoxPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const Vector& end, int cornerRadius, unsigned char color)) & PrimitiveMan::DrawRoundedBoxPrimitive)
.def("DrawRoundedBoxFillPrimitive", (void(PrimitiveMan::*)(const Vector& start, const Vector& end, int cornerRadius, unsigned char color)) & PrimitiveMan::DrawRoundedBoxFillPrimitive)
.def("DrawRoundedBoxFillPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const Vector& end, int cornerRadius, unsigned char color)) & PrimitiveMan::DrawRoundedBoxFillPrimitive)
.def("DrawCirclePrimitive", (void(PrimitiveMan::*)(const Vector& pos, int radius, unsigned char color)) & PrimitiveMan::DrawCirclePrimitive)
.def("DrawCirclePrimitive", (void(PrimitiveMan::*)(int player, const Vector& pos, int radius, unsigned char color)) & PrimitiveMan::DrawCirclePrimitive)
.def("DrawCircleFillPrimitive", (void(PrimitiveMan::*)(const Vector& pos, int radius, unsigned char color)) & PrimitiveMan::DrawCircleFillPrimitive)
.def("DrawCircleFillPrimitive", (void(PrimitiveMan::*)(int player, const Vector& pos, int radius, unsigned char color)) & PrimitiveMan::DrawCircleFillPrimitive)
.def("DrawEllipsePrimitive", (void(PrimitiveMan::*)(const Vector& pos, int horizRadius, int vertRadius, unsigned char color)) & PrimitiveMan::DrawEllipsePrimitive)
.def("DrawEllipsePrimitive", (void(PrimitiveMan::*)(int player, const Vector& pos, int horizRadius, int vertRadius, unsigned char color)) & PrimitiveMan::DrawEllipsePrimitive)
.def("DrawEllipseFillPrimitive", (void(PrimitiveMan::*)(const Vector& pos, int horizRadius, int vertRadius, unsigned char color)) & PrimitiveMan::DrawEllipseFillPrimitive)
.def("DrawEllipseFillPrimitive", (void(PrimitiveMan::*)(int player, const Vector& pos, int horizRadius, int vertRadius, unsigned char color)) & PrimitiveMan::DrawEllipseFillPrimitive)
.def("DrawTrianglePrimitive", (void(PrimitiveMan::*)(const Vector& pointA, const Vector& pointB, const Vector& pointC, unsigned char color)) & PrimitiveMan::DrawTrianglePrimitive)
.def("DrawTrianglePrimitive", (void(PrimitiveMan::*)(int player, const Vector& pointA, const Vector& pointB, const Vector& pointC, unsigned char color)) & PrimitiveMan::DrawTrianglePrimitive)
.def("DrawTriangleFillPrimitive", (void(PrimitiveMan::*)(const Vector& pointA, const Vector& pointB, const Vector& pointC, unsigned char color)) & PrimitiveMan::DrawTriangleFillPrimitive)
.def("DrawTriangleFillPrimitive", (void(PrimitiveMan::*)(int player, const Vector& pointA, const Vector& pointB, const Vector& pointC, unsigned char color)) & PrimitiveMan::DrawTriangleFillPrimitive)
.def("DrawTextPrimitive", (void(PrimitiveMan::*)(const Vector& start, const std::string& text, bool isSmall, int alignment)) & PrimitiveMan::DrawTextPrimitive)
.def("DrawTextPrimitive", (void(PrimitiveMan::*)(const Vector& start, const std::string& text, bool isSmall, int alignment, float rotAngle)) & PrimitiveMan::DrawTextPrimitive)
.def("DrawTextPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const std::string& text, bool isSmall, int alignment)) & PrimitiveMan::DrawTextPrimitive)
.def("DrawTextPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const std::string& text, bool isSmall, int alignment, float rotAngle)) & PrimitiveMan::DrawTextPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame, float scale)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame, float scale, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame, float scale)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const MOSprite* moSprite, float rotAngle, unsigned int frame, float scale, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const std::string& filePath, float rotAngle)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const std::string& filePath, float rotAngle, float scale)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const std::string& filePath, float rotAngle, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(const Vector& start, const std::string& filePath, float rotAngle, float scale, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const std::string& filePath, float rotAngle)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const std::string& filePath, float rotAngle, float scale)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const std::string& filePath, float rotAngle, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawBitmapPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, const std::string& filePath, float rotAngle, float scale, bool hFlipped, bool vFlipped)) & PrimitiveMan::DrawBitmapPrimitive)
.def("DrawIconPrimitive", (void(PrimitiveMan::*)(const Vector& start, Entity* entity)) & PrimitiveMan::DrawIconPrimitive)
.def("DrawIconPrimitive", (void(PrimitiveMan::*)(int player, const Vector& start, Entity* entity)) & PrimitiveMan::DrawIconPrimitive)
.def("DrawPolygonPrimitive", &LuaAdaptersPrimitiveMan::DrawPolygonPrimitive)
.def("DrawPolygonPrimitive", &LuaAdaptersPrimitiveMan::DrawPolygonPrimitiveForPlayer)
.def("DrawPolygonFillPrimitive", &LuaAdaptersPrimitiveMan::DrawPolygonFillPrimitive)
.def("DrawPolygonFillPrimitive", &LuaAdaptersPrimitiveMan::DrawPolygonFillPrimitiveForPlayer)
.def("DrawPrimitives", &LuaAdaptersPrimitiveMan::DrawPrimitivesWithTransparency)
.def("DrawPrimitives", &LuaAdaptersPrimitiveMan::DrawPrimitivesWithBlending)
.def("DrawPrimitives", &LuaAdaptersPrimitiveMan::DrawPrimitivesWithBlendingPerChannel);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, SceneMan) {
return luabind::class_<SceneMan>("SceneManager")
.property("Scene", &SceneMan::GetScene)
.property("SceneDim", &SceneMan::GetSceneDim)
.property("SceneWidth", &SceneMan::GetSceneWidth)
.property("SceneHeight", &SceneMan::GetSceneHeight)
.property("SceneWrapsX", &SceneMan::SceneWrapsX)
.property("SceneWrapsY", &SceneMan::SceneWrapsY)
.property("SceneOrbitDirection", &SceneMan::GetSceneOrbitDirection)
.property("LayerDrawMode", &SceneMan::GetLayerDrawMode, &SceneMan::SetLayerDrawMode)
.property("GlobalAcc", &SceneMan::GetGlobalAcc)
.property("OzPerKg", &SceneMan::GetOzPerKg)
.property("KgPerOz", &SceneMan::GetKgPerOz)
.property("ScrapCompactingHeight", &SceneMan::GetScrapCompactingHeight, &SceneMan::SetScrapCompactingHeight)
.def("LoadScene", (int(SceneMan::*)(std::string, bool, bool)) & SceneMan::LoadScene)
.def("LoadScene", (int(SceneMan::*)(std::string, bool)) & SceneMan::LoadScene)
.def("GetTerrain", &SceneMan::GetTerrain)
.def("GetMaterial", &SceneMan::GetMaterial)
.def("GetMaterialFromID", &SceneMan::GetMaterialFromID)
.def("GetTerrMatter", &SceneMan::GetTerrMatter)
.def("GetMOIDPixel", (MOID(SceneMan::*)(int, int)) & SceneMan::GetMOIDPixel)
.def("GetMOIDPixel", (MOID(SceneMan::*)(int, int, int)) & SceneMan::GetMOIDPixel)
.def("SetLayerDrawMode", &SceneMan::SetLayerDrawMode)
.def("LoadUnseenLayer", &SceneMan::LoadUnseenLayer)
.def("MakeAllUnseen", &SceneMan::MakeAllUnseen)
.def("AnythingUnseen", &SceneMan::AnythingUnseen)
.def("GetUnseenResolution", &SceneMan::GetUnseenResolution)
.def("IsUnseen", &SceneMan::IsUnseen)
.def("RevealUnseen", &SceneMan::RevealUnseen)
.def("RevealUnseenBox", &SceneMan::RevealUnseenBox)
.def("RestoreUnseen", &SceneMan::RestoreUnseen)
.def("RestoreUnseenBox", &SceneMan::RestoreUnseenBox)
.def("CastSeeRay", &SceneMan::CastSeeRay)
.def("CastUnseeRay", &SceneMan::CastUnseeRay)
.def("CastUnseenRay", &SceneMan::CastUnseenRay)
.def("CastMaterialRay", (bool(SceneMan::*)(const Vector&, const Vector&, unsigned char, Vector&, int, bool)) & SceneMan::CastMaterialRay)
.def("CastMaterialRay", (float(SceneMan::*)(const Vector&, const Vector&, unsigned char, int)) & SceneMan::CastMaterialRay)
.def("CastNotMaterialRay", (bool(SceneMan::*)(const Vector&, const Vector&, unsigned char, Vector&, int, bool)) & SceneMan::CastNotMaterialRay)
.def("CastNotMaterialRay", (float(SceneMan::*)(const Vector&, const Vector&, unsigned char, int, bool)) & SceneMan::CastNotMaterialRay)
.def("CastStrengthSumRay", &SceneMan::CastStrengthSumRay)
.def("CastMaxStrengthRay", (float(SceneMan::*)(const Vector&, const Vector&, int, unsigned char)) & SceneMan::CastMaxStrengthRay)
.def("CastMaxStrengthRay", (float(SceneMan::*)(const Vector&, const Vector&, int)) & SceneMan::CastMaxStrengthRay)
.def("CastStrengthRay", &SceneMan::CastStrengthRay)
.def("CastWeaknessRay", &SceneMan::CastWeaknessRay)
.def("CastMORay", &LuaAdaptersSceneMan::CastMORay1)
.def("CastMORay", &LuaAdaptersSceneMan::CastMORay2)
.def("CastAllMOsRay", &LuaAdaptersSceneMan::CastAllMOsRay, luabind::return_stl_iterator)
.def("CastFindMORay", (bool(SceneMan::*)(const Vector&, const Vector&, MOID, const Vector&, unsigned char, bool, int)) & SceneMan::CastFindMORay)
.def("CastFindMORay", &SceneMan::CastFindMORay)
.def("CastObstacleRay", &LuaAdaptersSceneMan::CastObstacleRay1)
.def("CastObstacleRay", &LuaAdaptersSceneMan::CastObstacleRay2)
.def("CastTerrainPenetrationRay", &SceneMan::CastTerrainPenetrationRay)
.def("GetLastRayHitPos", &SceneMan::GetLastRayHitPos)
.def("FindAltitude", (float(SceneMan::*)(const Vector&, int, int)) &SceneMan::FindAltitude)
.def("FindAltitude", (float(SceneMan::*)(const Vector&, int, int, bool)) &SceneMan::FindAltitude)
.def("MovePointToGround", (Vector(SceneMan::*)(const Vector&, int, int)) &SceneMan::MovePointToGround)
.def("MovePointToGround", (Vector(SceneMan::*)(const Vector&, int, int, int)) &SceneMan::MovePointToGround)
.def("IsWithinBounds", &SceneMan::IsWithinBounds)
.def("ForceBounds", (bool(SceneMan::*)(Vector&) const) & SceneMan::ForceBounds) //, out_value(_2))
.def("WrapPosition", (bool(SceneMan::*)(Vector&) const) & SceneMan::WrapPosition) //, out_value(_2))
.def("SnapPosition", &SceneMan::SnapPosition)
.def("ShortestDistance", &SceneMan::ShortestDistance)
.def("WrapBox", &LuaAdaptersSceneMan::WrapBoxes, luabind::return_stl_iterator)
.def("ObscuredPoint", (bool(SceneMan::*)(Vector&, int)) & SceneMan::ObscuredPoint) //, out_value(_2))
.def("ObscuredPoint", (bool(SceneMan::*)(int, int, int)) & SceneMan::ObscuredPoint)
.def("AddSceneObject", &SceneMan::AddSceneObject, luabind::adopt(_2))
.def("CheckAndRemoveOrphans", (int(SceneMan::*)(int, int, int, int, bool)) & SceneMan::RemoveOrphans)
.def("DislodgePixel", &SceneMan::DislodgePixel)
.def("DislodgePixel", &SceneMan::DislodgePixelBool)
.def("DislodgePixelLine", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& start, const Vector& ray, int skip, bool deletePixels) const) & SceneMan::DislodgePixelLine, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("DislodgePixelLine", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& start, const Vector& ray, int skip) const) & SceneMan::DislodgePixelLineNoBool, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("DislodgePixelCircle", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& centre, float radius, bool deletePixels) const) & SceneMan::DislodgePixelCircle, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("DislodgePixelCircle", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& centre, float radius) const) & SceneMan::DislodgePixelCircleNoBool, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("DislodgePixelBox", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& upperLeftCorner, const Vector& lowerRightCorner, bool deletePixels) const) & SceneMan::DislodgePixelBox, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("DislodgePixelBox", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& upperLeftCorner, const Vector& lowerRightCorner) const) & SceneMan::DislodgePixelBoxNoBool, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("DislodgePixelRing", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& centre, float innerRadius, float outerRadius, bool deletePixels) const) & SceneMan::DislodgePixelRing, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator)
.def("DislodgePixelRing", (const std::vector<MOPixel*>* (SceneMan::*)(const Vector& centre, float innerRadius, float outerRadius) const) & SceneMan::DislodgePixelRingNoBool, luabind::adopt(luabind::return_value) + luabind::return_stl_iterator);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, CameraMan) {
return luabind::class_<CameraMan>("CameraManager")
.def("GetOffset", &CameraMan::GetOffset)
.def("SetOffset", &CameraMan::SetOffset)
.def("GetScreenOcclusion", &CameraMan::GetScreenOcclusion)
.def("SetScreenOcclusion", &CameraMan::SetScreenOcclusion)
.def("GetScrollTarget", &CameraMan::GetScrollTarget)
.def("SetScrollTarget", &CameraMan::SetScrollTarget)
.def("TargetDistanceScalar", &CameraMan::TargetDistanceScalar)
.def("CheckOffset", &CameraMan::CheckOffset)
.def("SetScroll", &CameraMan::SetScroll)
.def("AddScreenShake", (void(CameraMan::*)(float, int)) & CameraMan::AddScreenShake)
.def("AddScreenShake", (void(CameraMan::*)(float, const Vector&)) & CameraMan::AddScreenShake);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, SettingsMan) {
return luabind::class_<SettingsMan>("SettingsManager")
.property("PrintDebugInfo", &SettingsMan::PrintDebugInfo, &SettingsMan::SetPrintDebugInfo)
.property("RecommendedMOIDCount", &SettingsMan::RecommendedMOIDCount)
.property("AIUpdateInterval", &SettingsMan::GetAIUpdateInterval, &SettingsMan::SetAIUpdateInterval)
.property("ShowEnemyHUD", &SettingsMan::ShowEnemyHUD)
.property("AutomaticGoldDeposit", &SettingsMan::GetAutomaticGoldDeposit);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, TimerMan) {
return luabind::class_<TimerMan>("TimerManager")
.property("TimeScale", &TimerMan::GetTimeScale, &TimerMan::SetTimeScale)
.property("RealToSimCap", &TimerMan::GetRealToSimCap)
.property("DeltaTimeTicks", &LuaAdaptersTimerMan::GetDeltaTimeTicks, &TimerMan::SetDeltaTimeTicks)
.property("DeltaTimeSecs", &TimerMan::GetDeltaTimeSecs, &TimerMan::SetDeltaTimeSecs)
.property("DeltaTimeMS", &TimerMan::GetDeltaTimeMS)
.property("AIDeltaTimeSecs", &TimerMan::GetAIDeltaTimeSecs)
.property("AIDeltaTimeMS", &TimerMan::GetAIDeltaTimeMS)
.property("TicksPerSecond", &LuaAdaptersTimerMan::GetTicksPerSecond)
.def("TimeForSimUpdate", &TimerMan::TimeForSimUpdate)
.def("DrawnSimUpdate", &TimerMan::DrawnSimUpdate);
}
LuaBindingRegisterFunctionDefinitionForType(ManagerLuaBindings, UInputMan) {
return luabind::class_<UInputMan>("UInputManager")
.property("FlagLAltState", &UInputMan::FlagLAltState)
.property("FlagRAltState", &UInputMan::FlagRAltState)
.property("FlagAltState", &UInputMan::FlagAltState)
.property("FlagLCtrlState", &UInputMan::FlagLCtrlState)
.property("FlagRCtrlState", &UInputMan::FlagRCtrlState)
.property("FlagCtrlState", &UInputMan::FlagCtrlState)
.property("FlagLShiftState", &UInputMan::FlagLShiftState)
.property("FlagRShiftState", &UInputMan::FlagRShiftState)
.property("FlagShiftState", &UInputMan::FlagShiftState)
.def("GetInputDevice", &UInputMan::GetInputDevice)
.def("ElementPressed", &UInputMan::ElementPressed)
.def("ElementReleased", &UInputMan::ElementReleased)
.def("ElementHeld", &UInputMan::ElementHeld)
.def("KeyPressed", (bool(UInputMan::*)(SDL_Keycode, int) const) & UInputMan::KeyPressed)
.def("KeyPressed", (bool(UInputMan::*)(SDL_Keycode) const) & UInputMan::KeyPressedKeycode)
.def("KeyReleased", (bool(UInputMan::*)(SDL_Keycode, int) const) & UInputMan::KeyReleased)
.def("KeyReleased", (bool(UInputMan::*)(SDL_Keycode) const) & UInputMan::KeyReleasedKeycode)
.def("KeyHeld", (bool(UInputMan::*)(SDL_Keycode, int) const) & UInputMan::KeyHeld)
.def("KeyHeld", (bool(UInputMan::*)(SDL_Keycode) const) & UInputMan::KeyHeldKeycode)
.def("ScancodePressed", (bool(UInputMan::*)(SDL_Scancode, int) const) & UInputMan::KeyPressed)
.def("ScancodePressed", (bool(UInputMan::*)(SDL_Scancode) const) & UInputMan::KeyPressedScancode)
.def("ScancodeReleased", (bool(UInputMan::*)(SDL_Scancode, int) const) & UInputMan::KeyReleased)
.def("ScancodeReleased", (bool(UInputMan::*)(SDL_Scancode) const) & UInputMan::KeyReleasedScancode)
.def("ScancodeHeld", (bool(UInputMan::*)(SDL_Scancode, int) const) & UInputMan::KeyHeld)
.def("ScancodeHeld", (bool(UInputMan::*)(SDL_Scancode) const) & UInputMan::KeyHeldScancode)
.def("MouseButtonPressed", &UInputMan::MouseButtonPressed)
.def("MouseButtonReleased", &UInputMan::MouseButtonReleased)
.def("MouseButtonHeld", &UInputMan::MouseButtonHeld)
.def("GetMousePos", &UInputMan::GetAbsoluteMousePosition)
.def("MouseWheelMoved", &UInputMan::MouseWheelMoved)
.def("JoyButtonPressed", &UInputMan::JoyButtonPressed)
.def("JoyButtonReleased", &UInputMan::JoyButtonReleased)
.def("JoyButtonHeld", &UInputMan::JoyButtonHeld)
.def("WhichJoyButtonPressed", &UInputMan::WhichJoyButtonPressed)
.def("JoyDirectionPressed", &UInputMan::JoyDirectionPressed)
.def("JoyDirectionReleased", &UInputMan::JoyDirectionReleased)
.def("JoyDirectionHeld", &UInputMan::JoyDirectionHeld)
.def("AnalogMoveValues", &UInputMan::AnalogMoveValues)
.def("AnalogAimValues", &UInputMan::AnalogAimValues)
.def("SetMouseValueMagnitude", &UInputMan::SetMouseValueMagnitude)
.def("AnalogAxisValue", &UInputMan::AnalogAxisValue)
.def("MouseUsedByPlayer", &UInputMan::MouseUsedByPlayer)
.def("AnyMouseButtonPress", &UInputMan::AnyMouseButtonPress)
.def("GetMouseMovement", &UInputMan::GetMouseMovement)
.def("DisableMouseMoving", &UInputMan::DisableMouseMoving)
.def("SetMousePos", &UInputMan::SetMousePos)
.def("ForceMouseWithinBox", &UInputMan::ForceMouseWithinBox)
.def("AnyKeyPress", &UInputMan::AnyKeyPress)
.def("AnyJoyInput", &UInputMan::AnyJoyInput)
.def("AnyJoyPress", &UInputMan::AnyJoyPress)
.def("AnyJoyButtonPress", &UInputMan::AnyJoyButtonPress)
.def("AnyInput", &UInputMan::AnyKeyOrJoyInput)
.def("AnyPress", &UInputMan::AnyPress)
.def("AnyStartPress", &UInputMan::AnyStartPress)
.def("HasTextInput", &UInputMan::HasTextInput)
.def("GetTextInput", (const std::string& (UInputMan::*)() const) & UInputMan::GetTextInput)
.def("MouseButtonPressed", &LuaAdaptersUInputMan::MouseButtonPressed)
.def("MouseButtonReleased", &LuaAdaptersUInputMan::MouseButtonReleased)
.def("MouseButtonHeld", &LuaAdaptersUInputMan::MouseButtonHeld);
}
| 412 | 0.631433 | 1 | 0.631433 | game-dev | MEDIA | 0.802634 | game-dev | 0.818942 | 1 | 0.818942 |
Eaglercraft-Archive/EaglercraftX-1.8-workspace | 4,311 | src/game/java/net/minecraft/util/ClassInheritanceMultiMap.java | package net.minecraft.util;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**+
* This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code.
*
* Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!"
* Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team
*
* EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved.
*
* 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 HOLDER 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.
*
*/
public class ClassInheritanceMultiMap<T> extends AbstractSet<T> {
private static final Set<Class<?>> field_181158_a = Sets.newHashSet();
private final Map<Class<?>, List<T>> map = Maps.newHashMap();
private final Set<Class<?>> knownKeys = Sets.newIdentityHashSet();
private final Class<T> baseClass;
private final List<T> field_181745_e = Lists.newArrayList();
public ClassInheritanceMultiMap(Class<T> baseClassIn) {
this.baseClass = baseClassIn;
this.knownKeys.add(baseClassIn);
this.map.put(baseClassIn, this.field_181745_e);
for (Class oclass : field_181158_a) {
this.createLookup(oclass);
}
}
protected void createLookup(Class<?> clazz) {
field_181158_a.add(clazz);
for (int i = 0, l = this.field_181745_e.size(); i < l; ++i) {
T object = this.field_181745_e.get(i);
if (clazz.isAssignableFrom(object.getClass())) {
this.func_181743_a(object, clazz);
}
}
this.knownKeys.add(clazz);
}
protected Class<?> func_181157_b(Class<?> parClass1) {
if (this.baseClass.isAssignableFrom(parClass1)) {
if (!this.knownKeys.contains(parClass1)) {
this.createLookup(parClass1);
}
return parClass1;
} else {
throw new IllegalArgumentException("Don\'t know how to search for " + parClass1);
}
}
public boolean add(T parObject) {
for (Class oclass : this.knownKeys) {
if (oclass.isAssignableFrom(parObject.getClass())) {
this.func_181743_a(parObject, oclass);
}
}
return true;
}
private void func_181743_a(T parObject, Class<?> parClass1) {
List list = (List) this.map.get(parClass1);
if (list == null) {
this.map.put(parClass1, (List<T>) Lists.newArrayList(new Object[] { parObject }));
} else {
list.add(parObject);
}
}
public boolean remove(Object parObject) {
Object object = parObject;
boolean flag = false;
for (Class oclass : this.knownKeys) {
if (oclass.isAssignableFrom(object.getClass())) {
List list = (List) this.map.get(oclass);
if (list != null && list.remove(object)) {
flag = true;
}
}
}
return flag;
}
public boolean contains(Object parObject) {
return Iterators.contains(this.getByClass(parObject.getClass()).iterator(), parObject);
}
public <S> Iterable<S> getByClass(final Class<S> clazz) {
return new Iterable<S>() {
public Iterator<S> iterator() {
List list = (List) ClassInheritanceMultiMap.this.map
.get(ClassInheritanceMultiMap.this.func_181157_b(clazz));
if (list == null) {
return Iterators.emptyIterator();
} else {
Iterator iterator = list.iterator();
return Iterators.filter(iterator, clazz);
}
}
};
}
public Iterator<T> iterator() {
return this.field_181745_e.isEmpty() ? Iterators.emptyIterator()
: Iterators.unmodifiableIterator(this.field_181745_e.iterator());
}
public int size() {
return this.field_181745_e.size();
}
} | 412 | 0.912308 | 1 | 0.912308 | game-dev | MEDIA | 0.457986 | game-dev | 0.955318 | 1 | 0.955318 |
MATTYOneInc/AionEncomBase_Java8 | 6,658 | AL-Game/src/com/aionemu/gameserver/network/aion/clientpackets/CM_USE_ITEM.java | /*
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.network.aion.clientpackets;
import java.util.ArrayList;
import com.aionemu.gameserver.model.Race;
import com.aionemu.gameserver.model.TaskId;
import com.aionemu.gameserver.model.gameobjects.HouseObject;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.templates.item.actions.AbstractItemAction;
import com.aionemu.gameserver.model.templates.item.actions.HouseDyeAction;
import com.aionemu.gameserver.model.templates.item.actions.InstanceTimeClear;
import com.aionemu.gameserver.model.templates.item.actions.ItemActions;
import com.aionemu.gameserver.model.templates.item.actions.MultiReturnAction;
import com.aionemu.gameserver.network.aion.AionClientPacket;
import com.aionemu.gameserver.network.aion.AionConnection.State;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.questEngine.QuestEngine;
import com.aionemu.gameserver.questEngine.handlers.HandlerResult;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.restrictions.RestrictionsManager;
import com.aionemu.gameserver.utils.PacketSendUtility;
public class CM_USE_ITEM extends AionClientPacket {
public int uniqueItemId;
public int type, targetItemId, syncId, returnId;
public CM_USE_ITEM(int opcode, State state, State... restStates) {
super(opcode, state, restStates);
}
@Override
protected void readImpl() {
uniqueItemId = readD();
type = readC();
if (type == 2) {
targetItemId = readD();
} else if (type == 5) {
syncId = readD();
} else if (type == 6) {
returnId = readD();
}
}
@Override
protected void runImpl() {
Player player = getConnection().getActivePlayer();
/**
* 5.0 ITEM_USE Cancel System
*/
if (type == 0) {
if (player.getController().hasTask(TaskId.ITEM_USE)) {
player.getController().cancelUseItem();
return;
}
}
if (player.isProtectionActive()) {
player.getController().stopProtectionActiveTask();
}
Item item = player.getInventory().getItemByObjId(uniqueItemId);
Item targetItem = player.getInventory().getItemByObjId(targetItemId);
HouseObject<?> targetHouseObject = null;
if (item == null) {
return;
}
if (targetItem == null) {
targetItem = player.getEquipment().getEquippedItemByObjId(targetItemId);
}
if (targetItem == null && player.getHouseRegistry() != null) {
targetHouseObject = player.getHouseRegistry().getObjectByObjId(targetItemId);
}
if (item.getItemTemplate().getTemplateId() == 165000001 && targetItem.getItemTemplate().canExtract()) {
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_ITEM_COLOR_ERROR);
return;
}
// check use item multicast delay exploit cast (spam)
if (player.isCasting()) {
player.getController().cancelCurrentSkill();
}
if (!RestrictionsManager.canUseItem(player, item)) {
return;
}
if (item.getItemTemplate().getRace() != Race.PC_ALL && item.getItemTemplate().getRace() != player.getRace()) {
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_CANNOT_USE_ITEM_INVALID_RACE);
return;
}
int requiredLevel = item.getItemTemplate().getRequiredLevel(player.getCommonData().getPlayerClass());
if (requiredLevel == -1) {
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_CANNOT_USE_ITEM_INVALID_CLASS);
return;
}
if (requiredLevel > player.getLevel()) {
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE
.STR_CANNOT_USE_ITEM_TOO_LOW_LEVEL_MUST_BE_THIS_LEVEL(item.getNameId(), requiredLevel));
return;
}
HandlerResult result = QuestEngine.getInstance().onItemUseEvent(new QuestEnv(null, player, 0, 0), item);
if (result == HandlerResult.FAILED) {
return;
}
ItemActions itemActions = item.getItemTemplate().getActions();
ArrayList<AbstractItemAction> actions = new ArrayList<AbstractItemAction>();
if (itemActions == null) {
return;
}
for (AbstractItemAction itemAction : itemActions.getItemActions()) {
// check if the item can be used before placing it on the cooldown list.
if (targetHouseObject != null && itemAction instanceof HouseDyeAction) {
HouseDyeAction action = (HouseDyeAction) itemAction;
if (action != null && action.canAct(player, item, targetHouseObject)) {
actions.add(itemAction);
}
} else if (itemAction.canAct(player, item, targetItem)) {
actions.add(itemAction);
}
}
if (actions.size() == 0) {
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_ITEM_IS_NOT_USABLE);
return;
}
// Store Item CD in server Player variable.
// Prevents potion spamming, and relogging to use kisks/aether jelly/long CD
// items.
if (player.isItemUseDisabled(item.getItemTemplate().getUseLimits())) {
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_ITEM_CANT_USE_UNTIL_DELAY_TIME);
return;
}
int useDelay = player.getItemCooldown(item.getItemTemplate());
if (useDelay > 0) {
player.addItemCoolDown(item.getItemTemplate().getUseLimits().getDelayId(),
System.currentTimeMillis() + useDelay, useDelay / 1000);
}
// notify item use observer
player.getObserveController().notifyItemuseObservers(item);
for (AbstractItemAction itemAction : actions) {
if (targetHouseObject != null && itemAction instanceof HouseDyeAction) {
HouseDyeAction action = (HouseDyeAction) itemAction;
action.act(player, item, targetHouseObject);
} else if (type == 5) {
if (itemAction instanceof InstanceTimeClear) {
InstanceTimeClear action = (InstanceTimeClear) itemAction;
int SelectedSyncId = syncId;
action.act(player, item, SelectedSyncId);
}
} else if (type == 6) {
if (itemAction instanceof MultiReturnAction) {
MultiReturnAction action = (MultiReturnAction) itemAction;
int SelectedMapIndex = returnId;
action.act(player, item, SelectedMapIndex);
}
} else {
itemAction.act(player, item, targetItem);
}
}
}
} | 412 | 0.952637 | 1 | 0.952637 | game-dev | MEDIA | 0.918979 | game-dev | 0.917871 | 1 | 0.917871 |
EvolutionRTS/Evolution-RTS | 4,568 | Scripts/ehbotfac.bos | #define TA // This is a TA script
#include "sfxtype.h"
#include "exptype.h"
piece base, base1, base2, base3, base4, spinner1, spinner2, spinner3, spinner4, nanopoint1, nano1, nano2, nano3, nano4, sfxpoint1, sfxpoint2, lilypad;
static-var spray, unitviewer, statechg_DesiredState, statechg_StateChanging, building, terraintype;
// Signal definitions
#define SIG_ACTIVATE 2
SmokeUnit(healthpercent, sleeptime, smoketype)
{
while( get BUILD_PERCENT_LEFT )
{
sleep 400;
}
while( TRUE )
{
healthpercent = get HEALTH;
if( healthpercent < 66 )
{
smoketype = 256 | 2;
if( Rand( 1, 66 ) < healthpercent )
{
smoketype = 256 | 1;
}
emit-sfx 1026 from base;
}
sleeptime = healthpercent * 50;
if( sleeptime < 200 )
{
sleeptime = 200;
}
sleep sleeptime;
}
}
setSFXoccupy(setSFXoccupy_argument)
{
terraintype = setSFXoccupy_argument;
if(terraintype == 2)
{
move base to y-axis [-3] speed [50];
}
else
{
move base to y-axis [-3] speed [50];
}
if(terraintype == 4)
{
move base to y-axis [-3] speed [50];
}
else
{
move base to y-axis [-3] speed [50];
}
}
buildingfx()
{
while( TRUE )
{
if (building)
{
emit-sfx 1024 from nano1;
sleep 60;
emit-sfx 1024 from nano4;
sleep 60;
emit-sfx 1024 from nano3;
sleep 60;
emit-sfx 1024 from nano2;
sleep 60;
}
sleep 600;
}
}
buildingfx2()
{
while( TRUE )
{
if (building)
{
emit-sfx 1025 from nanopoint1;
}
sleep 300;
}
}
fx()
{
while( get BUILD_PERCENT_LEFT )
{
sleep 400;
}
while( TRUE )
{
// if (tech)
// {
emit-sfx 1027 from sfxpoint1;
emit-sfx 1027 from sfxpoint2;
// }
sleep 500;
}
}
OpenYard()
{
spin spinner1 around y-axis speed <50.005495>;
spin spinner2 around y-axis speed <50.005495>;
spin spinner3 around y-axis speed <50.005495>;
spin spinner4 around y-axis speed <50.005495>;
set YARD_OPEN to 1;
while( !get YARD_OPEN )
{
set BUGGER_OFF to 1;
sleep 1500;
set YARD_OPEN to 1;
}
set BUGGER_OFF to 0;
}
CloseYard()
{
stop-spin spinner1 around z-axis decelerate <15.000000>;
stop-spin spinner2 around z-axis decelerate <15.000000>;
stop-spin spinner3 around z-axis decelerate <15.000000>;
stop-spin spinner4 around z-axis decelerate <15.000000>;
set YARD_OPEN to 0;
while( get YARD_OPEN )
{
set BUGGER_OFF to 1;
sleep 1500;
set YARD_OPEN to 0;
}
set BUGGER_OFF to 0;
}
Go()
{
call-script OpenYard();
set INBUILDSTANCE to 1;
}
Stop()
{
set INBUILDSTANCE to 0;
call-script CloseYard();
}
InitState()
{
statechg_DesiredState = TRUE;
statechg_StateChanging = FALSE;
}
RequestState(requestedstate, currentstate)
{
if( statechg_StateChanging )
{
statechg_DesiredState = requestedstate;
return (0);
}
statechg_StateChanging = TRUE;
currentstate = statechg_DesiredState;
statechg_DesiredState = requestedstate;
while( statechg_DesiredState != currentstate )
{
if( statechg_DesiredState == 0 )
{
call-script Go();
currentstate = 0;
}
if( statechg_DesiredState == 1 )
{
call-script Stop();
currentstate = 1;
}
}
statechg_StateChanging = FALSE;
}
Create()
{
unitviewer = FALSE;
spray = 0;
call-script InitState();
start-script SmokeUnit();
start-script Buildingfx();
// start-script Buildingfx2();
start-script fx();
}
QueryNanoPiece(piecenum)
{
if( spray == 0 )
{
piecenum = nano1;
}
if( spray == 1 )
{
piecenum = nano2;
}
if( spray == 2 )
{
piecenum = nano3;
}
if( spray == 3 )
{
piecenum = nano4;
}
++spray;
if( spray >= 4 )
{
spray = 0;
}
}
Activate()
{
signal SIG_ACTIVATE;
start-script RequestState(0);
}
Deactivate()
{
signal SIG_ACTIVATE;
set-signal-mask SIG_ACTIVATE;
set-signal-mask 0;
start-script RequestState(1);
}
StartBuilding()
{
building = 1;
}
StopBuilding()
{
building = 0;
}
QueryBuildInfo(piecenum)
{
piecenum = nanopoint1;
}
Killed(severity, corpsetype) // how it explodes
{
corpsetype = 1;
explode base1 type EXPLODE_ON_HIT;
explode base2 type EXPLODE_ON_HIT;
explode base3 type EXPLODE_ON_HIT;
explode base4 type EXPLODE_ON_HIT;
explode spinner1 type EXPLODE_ON_HIT;
explode spinner2 type EXPLODE_ON_HIT;
explode spinner3 type EXPLODE_ON_HIT;
explode spinner4 type EXPLODE_ON_HIT;
}
| 412 | 0.796912 | 1 | 0.796912 | game-dev | MEDIA | 0.986123 | game-dev | 0.892757 | 1 | 0.892757 |
AAEmu/AAEmu | 1,068 | AAEmu.Game/Models/Game/DoodadObj/Funcs/DoodadFuncBuff.cs | using AAEmu.Game.Core.Managers.World;
using AAEmu.Game.Models.Game.DoodadObj.Templates;
using AAEmu.Game.Models.Game.Units;
namespace AAEmu.Game.Models.Game.DoodadObj.Funcs;
public class DoodadFuncBuff : DoodadFuncTemplate
{
// doodad_funcs
public uint BuffId { get; set; }
public float Radius { get; set; }
public int Count { get; set; }
public uint PermId { get; set; } // Unused
public uint RelationshipId { get; set; }
public override void Use(BaseUnit caster, Doodad owner, uint skillId, int nextPhase = 0)
{
Logger.Trace("DoodadFuncBuff");
// TODO: ImplementRelationShipId
// TODO: Not sure what count is, maximum targets maybe?
if (Radius <= 0f)
{
// Caster only
caster.Buffs.AddBuff(BuffId, caster);
}
else
{
var targets = WorldManager.GetAround<BaseUnit>(caster, Radius, true);
foreach (var target in targets)
{
target.Buffs.AddBuff(BuffId, caster);
}
}
}
}
| 412 | 0.893547 | 1 | 0.893547 | game-dev | MEDIA | 0.972941 | game-dev | 0.933234 | 1 | 0.933234 |
nomnomab/unity-project-patcher | 2,750 | Libs/UniTask/Runtime/UniTask.AsValueTask.cs | #pragma warning disable 0649
#if UNITASK_NETCORE || UNITY_2022_3_OR_NEWER
#define SUPPORT_VALUETASK
#endif
#if SUPPORT_VALUETASK
using System;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
namespace Cysharp.Threading.Tasks
{
public static class UniTaskValueTaskExtensions
{
public static ValueTask AsValueTask(this in UniTask task)
{
#if (UNITASK_NETCORE && NETSTANDARD2_0)
return new ValueTask(new UniTaskValueTaskSource(task), 0);
#else
return task;
#endif
}
public static ValueTask<T> AsValueTask<T>(this in UniTask<T> task)
{
#if (UNITASK_NETCORE && NETSTANDARD2_0)
return new ValueTask<T>(new UniTaskValueTaskSource<T>(task), 0);
#else
return task;
#endif
}
public static async UniTask<T> AsUniTask<T>(this ValueTask<T> task)
{
return await task;
}
public static async UniTask AsUniTask(this ValueTask task)
{
await task;
}
#if (UNITASK_NETCORE && NETSTANDARD2_0)
class UniTaskValueTaskSource : IValueTaskSource
{
readonly UniTask task;
readonly UniTask.Awaiter awaiter;
public UniTaskValueTaskSource(UniTask task)
{
this.task = task;
this.awaiter = task.GetAwaiter();
}
public void GetResult(short token)
{
awaiter.GetResult();
}
public ValueTaskSourceStatus GetStatus(short token)
{
return (ValueTaskSourceStatus)task.Status;
}
public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
{
awaiter.SourceOnCompleted(continuation, state);
}
}
class UniTaskValueTaskSource<T> : IValueTaskSource<T>
{
readonly UniTask<T> task;
readonly UniTask<T>.Awaiter awaiter;
public UniTaskValueTaskSource(UniTask<T> task)
{
this.task = task;
this.awaiter = task.GetAwaiter();
}
public T GetResult(short token)
{
return awaiter.GetResult();
}
public ValueTaskSourceStatus GetStatus(short token)
{
return (ValueTaskSourceStatus)task.Status;
}
public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
{
awaiter.SourceOnCompleted(continuation, state);
}
}
#endif
}
}
#endif
| 412 | 0.914491 | 1 | 0.914491 | game-dev | MEDIA | 0.835584 | game-dev | 0.95044 | 1 | 0.95044 |
openscope/openscope | 10,479 | test/trafficGenerator/buildPreSpawnAircraft.spec.js | import ava from 'ava';
import sinon from 'sinon';
import _floor from 'lodash/floor';
import RouteModel from '../../src/assets/scripts/client/aircraft/FlightManagementSystem/RouteModel';
import {
_calculateOffsetsToEachWaypointInRoute,
_calculateAltitudeOffsets,
_calculateAltitudeAtOffset,
_calculateIdealSpawnAltitudeAtOffset,
buildPreSpawnAircraft
} from '../../src/assets/scripts/client/trafficGenerator/buildPreSpawnAircraft';
import { airportModelFixture } from '../fixtures/airportFixtures';
import {
createNavigationLibraryFixture,
resetNavigationLibraryFixture
} from '../fixtures/navigationLibraryFixtures';
import { ARRIVAL_PATTERN_MOCK } from './_mocks/spawnPatternMocks';
let sandbox;
ava.beforeEach(() => {
sandbox = sinon.createSandbox();
createNavigationLibraryFixture();
});
ava.afterEach(() => {
sandbox.restore();
resetNavigationLibraryFixture();
});
ava('_calculateOffsetsToEachWaypointInRoute() returns array of distances between waypoints, ignoring vector waypoints', (t) => {
const routeModel = new RouteModel('PGS..MLF..OAL..KEPEC..BOACH..CHIPZ..#340');
const waypointModelList = routeModel.waypoints;
const expectedResult = [
0,
166.20954056162077,
391.7193092657528,
553.2190261558699,
575.1449276267966,
613.1666698503408
];
const result = _calculateOffsetsToEachWaypointInRoute(waypointModelList);
t.deepEqual(result, expectedResult);
});
ava('_calculateAltitudeOffsets returns an array of the altitudes required and their ATDs', (t) => {
const routeModel = new RouteModel('PGS.TYSSN4.KLAS01L');
const waypointModelList = routeModel.waypoints;
const waypointOffsetMap = _calculateOffsetsToEachWaypointInRoute(waypointModelList);
const expectedResult = [
[18.958610430426404, 19000],
[41.52033243401482, 12000],
[60.46996764011041, 10000],
[70.68723901280046, 8000]
];
const result = _calculateAltitudeOffsets(waypointModelList, waypointOffsetMap);
t.deepEqual(result, expectedResult);
});
ava('_calculateAltitudeAtOffset throws when there are no altitude restrictions ahead nor behind', (t) => {
const altitudesAtOffsets = [];
const offsetDistanceMock = 25;
t.throws(() => _calculateAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock));
});
ava('_calculateAltitudeAtOffset returns altitude of previous restriction when there are restrictions behind but none ahead', (t) => {
const altitudesAtOffsets = [
[18.958610430426404, 19000],
[41.52033243401482, 12000],
[60.46996764011041, 10000],
[70.68723901280046, 8000]
];
const offsetDistanceMock = 75;
const expectedResult = 8000;
const result = _calculateAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock);
t.true(result === expectedResult);
});
ava('_calculateAltitudeAtOffset returns altitude of next restriction when there are restrictions ahead but none behind', (t) => {
const altitudesAtOffsets = [
[18.958610430426404, 19000],
[41.52033243401482, 12000],
[60.46996764011041, 10000],
[70.68723901280046, 8000]
];
const offsetDistanceMock = 15;
const expectedResult = 19000;
const result = _calculateAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock);
t.true(result === expectedResult);
});
ava('_calculateAltitudeAtOffset returns the interpolated altitude along the optimal descent path', (t) => {
const altitudesAtOffsets = [
[18.958610430426404, 19000],
[41.52033243401482, 12000]
];
const offsetDistanceMock = (18.958610430426404 + 41.52033243401482) / 2;
const expectedResult = _floor((19000 + 12000) / 2, -3);
const result = _calculateAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock);
t.true(result === expectedResult);
});
ava('_calculateIdealSpawnAltitudeAtOffset() returns an interpolated altitude based on available descent distance to boundary when no restrictions exist', (t) => {
const altitudesAtOffsets = [];
const spawnAltitudeMock = 23000;
const airspaceCeilingMock = 11000;
const spawnSpeedMock = 360; // 6 miles per minute
const totalDistanceMock = 60; // 10 minutes to airspace boundary (at 6mpm)
const offsetDistanceMock = 18; // 7 minute to airspace boundary (at 6mpm)
const expectedResult = airspaceCeilingMock + 7000; // 1000fpm descent rate for 1 minute
const result = _calculateIdealSpawnAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock, spawnSpeedMock, spawnAltitudeMock, totalDistanceMock, airspaceCeilingMock);
t.true(expectedResult === result);
});
ava('_calculateIdealSpawnAltitudeAtOffset() returns an interpolated altitude based on available descent distance to first altitude restriction', (t) => {
const altitudesAtOffsets = [
[18.958610430426404, 19000],
[41.52033243401482, 12000],
[60.46996764011041, 10000],
[70.68723901280046, 8000]
];
const spawnAltitudeMock = 23000;
const airspaceCeilingMock = 11000;
const spawnSpeedMock = 360;
const totalDistanceMock = 85;
const offsetDistanceMock = 6.5;
const expectedResult = 21000;
const result = _calculateIdealSpawnAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock, spawnSpeedMock, spawnAltitudeMock, totalDistanceMock, airspaceCeilingMock);
t.true(expectedResult === result);
});
ava('_calculateIdealSpawnAltitudeAtOffset() returns an interpolated altitude based on a flat glidepath between restrictions when spawn point is beyond the first altitude restriction', (t) => {
const altitudesAtOffsets = [
[18.958610430426404, 19000],
[41.52033243401482, 12000],
[60.46996764011041, 10000],
[70.68723901280046, 8000]
];
const spawnAltitudeMock = 23000;
const airspaceCeilingMock = 11000;
const spawnSpeedMock = 360;
const totalDistanceMock = 85;
const offsetDistanceMock = 25;
const expectedResult = 17000;
const result = _calculateIdealSpawnAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock, spawnSpeedMock, spawnAltitudeMock, totalDistanceMock, airspaceCeilingMock);
t.true(expectedResult === result);
});
ava('_calculateIdealSpawnAltitudeAtOffset() returns an appropriate altitude when a range of spawn altitudes is specified instead of a specific one', (t) => {
const altitudesAtOffsets = [
[18.958610430426404, 19000],
[41.52033243401482, 12000],
[60.46996764011041, 10000],
[70.68723901280046, 8000]
];
const spawnAltitudeMock = [23000, 23456];
const airspaceCeilingMock = 11000;
const spawnSpeedMock = 250;
const totalDistanceMock = 85;
const offsetDistanceMock = 0;
const expectedResult = 23000;
const result = _calculateIdealSpawnAltitudeAtOffset(altitudesAtOffsets, offsetDistanceMock, spawnSpeedMock, spawnAltitudeMock, totalDistanceMock, airspaceCeilingMock);
t.true(expectedResult === result);
});
ava('buildPreSpawnAircraft() throws when called with missing parameters', (t) => {
const expectedMessage = /Invalid parameter\(s\) passed to buildPreSpawnAircraft\. Expected spawnPatternJson and currentAirport to be defined, but received .*/;
t.throws(() => buildPreSpawnAircraft(), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(airportModelFixture), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(null, airportModelFixture), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, null), {
instanceOf: TypeError,
message: expectedMessage
});
});
ava('buildPreSpawnAircraft() throws when passed invalid spawnPatternJson', (t) => {
const expectedMessage = /Invalid spawnPatternJson passed to buildPreSpawnAircraft\. Expected a non-empty object, but received .*/;
t.throws(() => buildPreSpawnAircraft({}, airportModelFixture), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft([], airportModelFixture), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(42, airportModelFixture), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft('threeve', airportModelFixture), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(false, airportModelFixture), {
instanceOf: TypeError,
message: expectedMessage
});
});
ava('buildPreSpawnAircraft() throws when passed invalid currentAirport', (t) => {
const expectedMessage = /Invalid currentAirport passed to buildPreSpawnAircraft\. Expected instance of AirportModel, but received .*/;
t.throws(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, {}), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, []), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, 42), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, 'threeve'), {
instanceOf: TypeError,
message: expectedMessage
});
t.throws(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, false), {
instanceOf: TypeError,
message: expectedMessage
});
});
ava('buildPreSpawnAircraft() does not throw when passed valid parameters', (t) => {
t.notThrows(() => buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, airportModelFixture));
});
// ava('buildPreSpawnAircraft() returns an array of objects with correct keys', (t) => {
// const results = buildPreSpawnAircraft(ARRIVAL_PATTERN_MOCK, airportModelFixture);
//
// t.true(_isArray(results));
//
// _map(results, (result) => {
// t.true(typeof result.heading === 'number');
// t.true(typeof result.nextFix === 'string');
// t.true(_isArray(result.positionModel.relativePosition));
// });
// });
| 412 | 0.568588 | 1 | 0.568588 | game-dev | MEDIA | 0.583824 | game-dev | 0.756536 | 1 | 0.756536 |
ReinaS-64892/TexTransTool | 1,266 | Runtime/Common/PropertyName.cs | using System;
using UnityEngine;
namespace net.rs64.TexTransTool
{
[Serializable]
public struct PropertyName
{
[SerializeField] string _propertyName;
#pragma warning disable CS0414 , IDE0052
[SerializeField] bool _useCustomProperty;
[SerializeField] string _shaderName;
#pragma warning restore CS0414 , IDE0052
public PropertyName(string propertyName, bool useCustomProperty = false)
{
_propertyName = propertyName;
_useCustomProperty = useCustomProperty;
_shaderName = "DefaultShader";
}
internal bool UseCustomProperty => _useCustomProperty;
public const string MainTex = "_MainTex";
public static PropertyName DefaultValue => new PropertyName(MainTex);
public override string ToString()
{
return (string)this;
}
public static implicit operator string(PropertyName p) => p._propertyName;
internal PropertyName AsLilToon()
{
var lv = this;
lv._shaderName = "lilToon";
return lv;
}
internal PropertyName AsUnknown()
{
var lv = this;
lv._shaderName = "";
return lv;
}
}
}
| 412 | 0.535383 | 1 | 0.535383 | game-dev | MEDIA | 0.738054 | game-dev | 0.721015 | 1 | 0.721015 |
GrognardsFromHell/TemplePlus | 4,129 | tpdatasrc/palcov/scr/Spell288 - Magic Missile.py | from toee import *
import tpdp
def OnBeginSpellCast( spell ):
print "Magic Missile OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
game.particles( "sp-evocation-conjure", spell.caster )
#spell.num_of_projectiles = spell.num_of_projectiles + 1
#spell.target_list.push_target(spell.caster) # didn't work :(
# generally the sequence is: OnBeginSpellCast, OnBeginProjectile, OnSpellEffect,OnEndProjectile (OnBeginRound isn't called)
def OnSpellEffect( spell ):
print "Magic Missile OnSpellEffect"
# only enable mirror image behavior in strict rules
if not tpdp.config_get_bool('stricterRulesEnforcement'): return
# Calculate which missiles hit mirror images instead of the actual target.
#
# This needs to be calculated ahead of time if we want to simulate picking
# targets _before_ we know which is the real one, for situations where there
# are more missiles than (real and fake) targets.
offsets = []
seen = []
hits = [0,0,0,0,0]
hi = -1
for target_item in spell.target_list:
target = target_item.obj
hi += 1
# handles can't be hashed, so we need to do something like this
if target in seen:
ix = seen.index(target)
# if the same spell target occurs more than once, assume we're targeting
# as many distinct copies if possible
off, copies = offsets[ix]
offsets[ix] = (off+1, copies)
if off % copies > 0: hits[hi] = 1
else:
mirrors = target.d20_query(Q_Critter_Has_Mirror_Image)
# no mirrors, always hit
if mirrors <= 0: continue
copies = mirrors+1
off = dice_new(1, copies, -1).roll()
# save the _next_ offset
offsets.append((off+1, copies))
seen.append(target)
if off > 0: hits[hi] = 1
h1, h2, h3, h4, h5 = hits
spell.caster.condition_add_with_args('Magic Missile Mirror', spell.id, h1, h2, h3, h4, h5)
def OnBeginRound( spell ):
print "Magic Missile OnBeginRound"
def OnBeginProjectile( spell, projectile, index_of_target ):
print "Magic Missile OnBeginProjectile"
projectile.obj_set_int( obj_f_projectile_part_sys_id, game.particles( 'sp-magic missle-proj', projectile ) )
def OnEndProjectile( spell, projectile, index_of_target ):
print "Magic Missile OnEndProjectile"
game.particles_end( projectile.obj_get_int( obj_f_projectile_part_sys_id ) )
target_item = spell.target_list[ index_of_target ]
target = target_item.obj
hit_mirror = spell.caster.d20_query_with_data('Missile Mirror Hit', spell.id, index_of_target + 1)
if hit_mirror > 0:
if target.d20_query(Q_Critter_Has_Mirror_Image) > 0:
mirror_id = target.d20_query_get_data(Q_Critter_Has_Mirror_Image, 0)
target.d20_send_signal(S_Spell_Mirror_Image_Struck, mirror_id, 0)
target.float_mesfile_line('mes\\combat.mes', 109)
game.create_history_from_pattern(10, spell.caster, target)
else: # normal damage
damage_dice = dice_new(1,4,1)
is_enemy = not spell.caster in game.party[0].group_list()
target_charmed = target.d20_query(Q_Critter_Is_Charmed)
if is_enemy and target_charmed:
# NPC enemy is trying to cast on a charmed target - this is mostly meant for the Cult of the Siren encounter
target = party_closest( spell.caster, conscious_only= 1, mode_select= 1, exclude_warded= 1, exclude_charmed = 1) # select nearest conscious PC instead, who isn't already charmed
if target == OBJ_HANDLE_NULL:
target = target_item.obj
# always hits
target.condition_add_with_args('sp-Magic Missile', spell.id, spell.duration, damage_dice.roll())
target_item.partsys_id = game.particles('sp-magic missle-hit', target)
# special scripting for NPCs no longer necessary - NPCs will launch multiple projectiles now
#spell.target_list.remove_target_by_index( index_of_target )
spell.num_of_projectiles -= 1
if spell.num_of_projectiles == 0:
## loc = target.location
## target.destroy()
## mxcr = game.obj_create( 12021, loc )
## game.global_vars[30] = game.global_vars[30] + 1
spell.caster.d20_send_signal(S_Spell_End, spell.id)
spell.spell_end( spell.id, 1 )
def OnEndSpellCast( spell ):
print "Magic Missile OnEndSpellCast"
| 412 | 0.766691 | 1 | 0.766691 | game-dev | MEDIA | 0.953285 | game-dev | 0.855475 | 1 | 0.855475 |
FPSMasterTeam/FPSMaster | 4,535 | shared/java/top/fpsmaster/features/impl/utility/AutoGG.java | package top.fpsmaster.features.impl.utility;
import net.minecraft.event.ClickEvent;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.StringUtils;
import top.fpsmaster.FPSMaster;
import top.fpsmaster.event.Subscribe;
import top.fpsmaster.event.events.EventPacket;
import top.fpsmaster.features.manager.Category;
import top.fpsmaster.features.manager.Module;
import top.fpsmaster.features.settings.impl.BooleanSetting;
import top.fpsmaster.features.settings.impl.ModeSetting;
import top.fpsmaster.features.settings.impl.NumberSetting;
import top.fpsmaster.features.settings.impl.TextSetting;
import top.fpsmaster.interfaces.ProviderManager;
import top.fpsmaster.utils.Utility;
import top.fpsmaster.utils.math.MathTimer;
public class AutoGG extends Module {
private final BooleanSetting autoPlay = new BooleanSetting("AutoPlay", false);
private final NumberSetting delay = new NumberSetting("DelayToPlay", 5, 0, 10, 1, autoPlay::getValue);
private final TextSetting message = new TextSetting("Message", "gg");
private final ModeSetting servers = new ModeSetting("Servers", 0, "hypixel", "kkcraft");
private final String[] hypixelTrigger = new String[]{"Reward Summary", "1st Killer", "Damage Dealt", "奖励总览", "击杀数第一名", "造成伤害"};
private final String[] kkcraftTrigger = new String[]{"获胜者", "第一名杀手", "击杀第一名"};
private final MathTimer timer = new MathTimer();
public AutoGG() {
super("AutoGG", Category.Utility);
this.addSettings(autoPlay, delay, message, servers);
}
@Subscribe
public void onPacket(EventPacket event) {
if (event.type == EventPacket.PacketType.RECEIVE && ProviderManager.packetChat.isPacket(event.packet)) {
IChatComponent componentValue = ProviderManager.packetChat.getChatComponent(event.packet);
String chatMessage = componentValue.getUnformattedText();
switch (servers.getValue()) {
case 0:
if (timer.delay(10000)) {
for (String s : hypixelTrigger) {
if (StringUtils.stripControlCodes(chatMessage).contains(s)) {
Utility.sendChatMessage("/ac " + message.getValue());
timer.reset();
break;
}
}
}
if (autoPlay.getValue()) {
for (IChatComponent chatComponent : componentValue.getSiblings()) {
ClickEvent clickEvent = chatComponent.getChatStyle().getChatClickEvent();
if (clickEvent != null && clickEvent.getAction().equals(ClickEvent.Action.RUN_COMMAND) && clickEvent.getValue().trim().toLowerCase().startsWith("/play ")) {
if (delay.getValue().doubleValue() > 0) {
Utility.sendClientNotify("Sending you to the next game in " + delay.getValue().intValue() + " seconds");
FPSMaster.async.runnable(() -> {
try {
Thread.sleep(delay.getValue().longValue() * 1000);
Utility.sendChatMessage(clickEvent.getValue());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
} else {
Utility.sendChatMessage(clickEvent.getValue());
}
}
}
}
break;
case 1:
if (timer.delay(10000)) {
for (String s : kkcraftTrigger) {
if (StringUtils.stripControlCodes(chatMessage).contains(s)) {
Utility.sendChatMessage(message.getValue());
timer.reset();
if (autoPlay.getValue()) {
Utility.sendClientNotify("AutoPlay is not supported in KKCraft yet");
}
}
}
}
break;
default:
}
}
}
}
| 412 | 0.957207 | 1 | 0.957207 | game-dev | MEDIA | 0.927478 | game-dev | 0.987382 | 1 | 0.987382 |
coolsee/OpenMugen | 2,160 | src/loadso/os2/SDL_sysloadso.c | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_LOADSO_OS2
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* System dependent library loading routines */
#include <stdio.h>
#define INCL_DOSERRORS
#define INCL_DOSMODULEMGR
#include <os2.h>
#include "SDL_loadso.h"
void *SDL_LoadObject(const char *sofile)
{
HMODULE handle = NULL;
char buf[512];
APIRET ulrc = DosLoadModule(buf, sizeof (buf), (char *) sofile, &handle);
/* Generate an error message if all loads failed */
if ((ulrc != NO_ERROR) || (handle == NULL))
SDL_SetError("Failed loading %s: %s", sofile, buf);
return((void *) handle);
}
void *SDL_LoadFunction(void *handle, const char *name)
{
const char *loaderror = "Unknown error";
void *symbol = NULL;
APIRET ulrc = DosQueryProcAddr((HMODULE)handle, 0, (char *)name, &symbol);
if (ulrc == ERROR_INVALID_HANDLE)
loaderror = "Invalid module handle";
else if (ulrc == ERROR_INVALID_NAME)
loaderror = "Symbol not found";
if (symbol == NULL)
SDL_SetError("Failed loading %s: %s", name, loaderror);
return(symbol);
}
void SDL_UnloadObject(void *handle)
{
if ( handle != NULL )
DosFreeModule((HMODULE) handle);
}
#endif /* SDL_LOADSO_OS2 */
| 412 | 0.81663 | 1 | 0.81663 | game-dev | MEDIA | 0.376443 | game-dev | 0.507285 | 1 | 0.507285 |
kendryte/kendryte-tensorflow | 3,936 | tensorflow/lite/tools/make/downloads/flatbuffers/samples/lua/MyGame/Sample/Monster.lua | -- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: Sample
local flatbuffers = require('flatbuffers')
local Monster = {} -- the module
local Monster_mt = {} -- the class metatable
function Monster.New()
local o = {}
setmetatable(o, {__index = Monster_mt})
return o
end
function Monster.GetRootAsMonster(buf, offset)
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Monster.New()
o:Init(buf, n + offset)
return o
end
function Monster_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Monster_mt:Pos()
local o = self.view:Offset(4)
if o ~= 0 then
local x = o + self.view.pos
local obj = require('MyGame.Sample.Vec3').New()
obj:Init(self.view.bytes, x)
return obj
end
end
function Monster_mt:Mana()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
end
return 150
end
function Monster_mt:Hp()
local o = self.view:Offset(8)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
end
return 100
end
function Monster_mt:Name()
local o = self.view:Offset(10)
if o ~= 0 then
return self.view:String(o + self.view.pos)
end
end
function Monster_mt:Inventory(j)
local o = self.view:Offset(14)
if o ~= 0 then
local a = self.view:Vector(o)
return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
end
return 0
end
function Monster_mt:InventoryLength()
local o = self.view:Offset(14)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function Monster_mt:Color()
local o = self.view:Offset(16)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int8, o + self.view.pos)
end
return 2
end
function Monster_mt:Weapons(j)
local o = self.view:Offset(18)
if o ~= 0 then
local x = self.view:Vector(o)
x = x + ((j-1) * 4)
x = self.view:Indirect(x)
local obj = require('MyGame.Sample.Weapon').New()
obj:Init(self.view.bytes, x)
return obj
end
end
function Monster_mt:WeaponsLength()
local o = self.view:Offset(18)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function Monster_mt:EquippedType()
local o = self.view:Offset(20)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
end
return 0
end
function Monster_mt:Equipped()
local o = self.view:Offset(22)
if o ~= 0 then
local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
self.view:Union(obj, o)
return obj
end
end
function Monster.Start(builder) builder:StartObject(10) end
function Monster.AddPos(builder, pos) builder:PrependStructSlot(0, pos, 0) end
function Monster.AddMana(builder, mana) builder:PrependInt16Slot(1, mana, 150) end
function Monster.AddHp(builder, hp) builder:PrependInt16Slot(2, hp, 100) end
function Monster.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(3, name, 0) end
function Monster.AddInventory(builder, inventory) builder:PrependUOffsetTRelativeSlot(5, inventory, 0) end
function Monster.StartInventoryVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
function Monster.AddColor(builder, color) builder:PrependInt8Slot(6, color, 2) end
function Monster.AddWeapons(builder, weapons) builder:PrependUOffsetTRelativeSlot(7, weapons, 0) end
function Monster.StartWeaponsVector(builder, numElems) return builder:StartVector(4, numElems, 4) end
function Monster.AddEquippedType(builder, equippedType) builder:PrependUint8Slot(8, equippedType, 0) end
function Monster.AddEquipped(builder, equipped) builder:PrependUOffsetTRelativeSlot(9, equipped, 0) end
function Monster.End(builder) return builder:EndObject() end
return Monster -- return the module | 412 | 0.741432 | 1 | 0.741432 | game-dev | MEDIA | 0.821499 | game-dev | 0.77427 | 1 | 0.77427 |
dsh2dsh/op2ogse | 3,081 | gamedata/scripts/amk/amk_particle.script | -- -*- mode: lua; coding: windows-1251-dos -*-
class "amk_particle"
function amk_particle:__init( params )
self.type = params.typ or "absolute"
self.dir = params.dir or vector():set( 0, 0, 0 )
self.len = params.len or 1
self.looped = params.looped or false
self.life_time = params.life_time or -1
self.obj = params.obj
self.bone = params.bone
self.pos = params.pos
self.stop_on_death = params.stop_on_death or false
self.gravity = params.gravity or vector():set( 0, 0, 0 )
self.give_dmg = params.give_dmg or false
self.target = params.target
if params.sound then
self.snd = sound_object( params.sound )
self.snd_looped = params.sound_looped or false
end
self.cgravity = vector():set( 0, 0, 0 )
self.particle = particles_object( params.particle )
self.started = false
self.start_time = time_global()
self.finalized = false
self:start()
end
function amk_particle:__finalize()
self.particle:stop()
end
function amk_particle:start()
if not self.particle:playing() then
local pos
if self.bone and self.obj then
pos = self.obj:bone_position( self.bone )
elseif self.pos then
pos = self.pos
end
self.start_pos = pos
if pos then
if self.snd then
if self.snd_looped then
self.snd:play_at_pos( db.actor, pos, 1, sound_object.looped )
else
self.snd:play_at_pos( db.actor, pos )
end
self.snd = nil
end
self.particle:play_at_pos( pos )
self.started = true
end
end
end
function amk_particle:update( delta )
if self.finalized then return end
self.cgravity = self.cgravity:add( self.gravity )
if self.particle:playing() then
if
self.life_time > -1
and time_global() > self.start_time + self.life_time
then
self.started = false
self.looped = false
self:stop()
self.finalized = true
end
local pos
if self.bone and self.obj then
pos = self.obj:bone_position( self.bone )
self.pos = pos
elseif self.dir then
self.pos = self.pos:add(
self.dir:set_length( self.len / self.life_time * delta )
)
self.pos = self.pos:add( self.cgravity )
pos = self.pos
end
if pos then
if self.snd and self.snd:playing() then
self.snd:set_position( pos )
end
self.particle:move_to( pos, pos )
end
else
if self.started then
if self.looped then
self:start()
else
self.started = false
self.looped = false
self:stop()
self.finalized = true
end
end
end
end
function amk_particle:stop()
self.give_dmg = false
if self.particle:playing() then
self.particle:stop_deffered()
end
if self.snd and self.snd:playing() then
self.snd:stop()
end
end
function amk_particle:get_pos()
return self.pos
end
function amk_particle:is_finished()
return self.finalized
end
function amk_particle:on_death()
if self.stop_on_death then
self:stop()
end
end
| 412 | 0.569783 | 1 | 0.569783 | game-dev | MEDIA | 0.189469 | game-dev | 0.913363 | 1 | 0.913363 |
hornyyy/Osu-Toy | 1,996 | osu.Game.Rulesets.Catch/UI/CatcherSprite.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatcherSprite : SkinnableDrawable
{
protected override bool ApplySizeRestrictionsToDefault => true;
public CatcherSprite(CatcherAnimationState state)
: base(new CatchSkinComponent(componentFromState(state)), _ =>
new DefaultCatcherSprite(state), confineMode: ConfineMode.ScaleToFit)
{
RelativeSizeAxes = Axes.None;
Size = new Vector2(CatcherArea.CATCHER_SIZE);
// Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling.
OriginPosition = new Vector2(0.5f, 0.06f) * CatcherArea.CATCHER_SIZE;
}
private static CatchSkinComponents componentFromState(CatcherAnimationState state)
{
switch (state)
{
case CatcherAnimationState.Fail:
return CatchSkinComponents.CatcherFail;
case CatcherAnimationState.Kiai:
return CatchSkinComponents.CatcherKiai;
default:
return CatchSkinComponents.CatcherIdle;
}
}
private class DefaultCatcherSprite : Sprite
{
private readonly CatcherAnimationState state;
public DefaultCatcherSprite(CatcherAnimationState state)
{
this.state = state;
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Texture = textures.Get($"Gameplay/catch/fruit-catcher-{state.ToString().ToLower()}");
}
}
}
}
| 412 | 0.761986 | 1 | 0.761986 | game-dev | MEDIA | 0.866093 | game-dev | 0.95503 | 1 | 0.95503 |
ifcquery/ifcplusplus | 3,460 | IfcPlusPlus/src/ifcpp/IFC4X3/include/IfcTransportElementType.h | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#pragma once
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"
#include "IfcTransportationDeviceType.h"
namespace IFC4X3
{
class IFCQUERY_EXPORT IfcTransportElementTypeEnum;
//ENTITY
class IFCQUERY_EXPORT IfcTransportElementType : public IfcTransportationDeviceType
{
public:
IfcTransportElementType() = default;
IfcTransportElementType( int id );
virtual void getStepLine( std::stringstream& stream, size_t precision ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type, size_t precision ) const;
virtual void readStepArguments( const std::vector<std::string>& args, const BuildingModelMapType<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream, std::unordered_set<int>& entityIdNotFound );
virtual void setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self );
virtual uint8_t getNumAttributes() const { return 10; }
virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const;
virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const;
virtual void unlinkFromInverseCounterparts();
virtual uint32_t classID() const { return 2097647324; }
// IfcRoot -----------------------------------------------------------
// attributes:
// shared_ptr<IfcGloballyUniqueId> m_GlobalId;
// shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional
// shared_ptr<IfcLabel> m_Name; //optional
// shared_ptr<IfcText> m_Description; //optional
// IfcObjectDefinition -----------------------------------------------------------
// inverse attributes:
// std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse;
// std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse;
// std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse;
// std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse;
// std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse;
// std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse;
// std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse;
// IfcTypeObject -----------------------------------------------------------
// attributes:
// shared_ptr<IfcIdentifier> m_ApplicableOccurrence; //optional
// std::vector<shared_ptr<IfcPropertySetDefinition> > m_HasPropertySets; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcRelDefinesByType> > m_Types_inverse;
// IfcTypeProduct -----------------------------------------------------------
// attributes:
// std::vector<shared_ptr<IfcRepresentationMap> > m_RepresentationMaps; //optional
// shared_ptr<IfcLabel> m_Tag; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcRelAssignsToProduct> > m_ReferencedBy_inverse;
// IfcElementType -----------------------------------------------------------
// attributes:
// shared_ptr<IfcLabel> m_ElementType; //optional
// IfcTransportationDeviceType -----------------------------------------------------------
// IfcTransportElementType -----------------------------------------------------------
// attributes:
shared_ptr<IfcTransportElementTypeEnum> m_PredefinedType;
};
}
| 412 | 0.922249 | 1 | 0.922249 | game-dev | MEDIA | 0.627127 | game-dev | 0.653439 | 1 | 0.653439 |
LongbowGames/TreadMarks | 5,276 | src/game/CJoyInput.cpp | // This file is part of Tread Marks
//
// Tread Marks 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.
//
// Tread Marks 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 Tread Marks. If not, see <http://www.gnu.org/licenses/>.
#include "CJoyInput.h"
#include <cmath>
#include <SFML/Window.hpp>
using namespace std;
CJoyInput::CJoyInput() : idJoystick(-1)
{
}
CJoyInput::~CJoyInput()
{
}
CStr getJoystickName(int iId)
{
// SFML doesn't currently support retrieving the name of a joystick, so we'll make our own.
return "Joystick " + String(iId+1);
}
bool CJoyInput::InitController ( int iController )
{
// Default controller in SFML-talk is 0
if(iController == -1)
iController = 0;
if(m_rController.iName == iController)
return true;
if(!sf::Joystick::isConnected(iController))
return false;
memset(LastButtons, 0, sizeof(LastButtons));
memset(&m_rController, 0, sizeof(trControllerStatus));
m_rController.iName = iController;
m_rController.iAxes = 0;
for(auto it = 0; it <= sf::Joystick::AxisCount; ++it)
m_rController.iAxes += sf::Joystick::hasAxis(iController, sf::Joystick::Axis(it));
m_rController.iButtons = sf::Joystick::getButtonCount(iController);
m_rController.rDeviceID.iDevID = m_rController.iName;
m_rController.rDeviceID.sDevName = getJoystickName(iController);
if(sf::Joystick::hasAxis(iController, sf::Joystick::PovX) || sf::Joystick::hasAxis(iController, sf::Joystick::PovY))
m_rController.bHasHat = true;
else
m_rController.bHasHat = false;
m_rController.aHatVector[0] = m_rController.aHatVector[1] = 0;
if (m_rController.iAxes <= 0)
return false;
if (sf::Joystick::hasAxis(iController, sf::Joystick::X))
m_rController.aAxes[_XAXIS].bActive = true;
if (sf::Joystick::hasAxis(iController, sf::Joystick::Y))
m_rController.aAxes[_YAXIS].bActive = true;
if (sf::Joystick::hasAxis(iController, sf::Joystick::Z))
m_rController.aAxes[_ZAXIS].bActive = true;
if (sf::Joystick::hasAxis(iController, sf::Joystick::R))
m_rController.aAxes[_RAXIS].bActive = true;
if (sf::Joystick::hasAxis(iController, sf::Joystick::U))
m_rController.aAxes[_UAXIS].bActive = true;
if (sf::Joystick::hasAxis(iController, sf::Joystick::V))
m_rController.aAxes[_VAXIS].bActive = true;
idJoystick = iController;
return true;
}
int CJoyInput::UnInitController ( void )
{
idJoystick = -1;
memset(&m_rController, 0, sizeof(trControllerStatus));
return 0;
}
int CJoyInput::GetFirstControllerID ( void )
{
if(GetNumberOfControllers() > 0)
return 0;
return -1;
}
bool CJoyInput::GetDeviceInfo(trDeviceID *pDevInfo, int iID )
{
if (iID == -1)
{
if (idJoystick == -1) // if no controller then try to init the defalut
if (!InitController()) // if it don't exist we need to bail
return false;
// copy the current controlers setup to the sruct
pDevInfo->iDevID = m_rController.rDeviceID.iDevID;
pDevInfo->sDevName = m_rController.rDeviceID.sDevName;
return true;
}
if(!sf::Joystick::isConnected(iID))
return false;
pDevInfo->iDevID = iID;
pDevInfo->sDevName = getJoystickName(iID);
return true;
}
int CJoyInput::GetDevIDFromInfo ( trDeviceID *pDevInfo )
{
if (!pDevInfo)
return -1;
for (int i = 0; i < sf::Joystick::Count; i ++)
{
if(getJoystickName(i) == pDevInfo->sDevName)
{
pDevInfo->iDevID = i;
return i;
}
}
return -1;
}
bool CJoyInput::GetControllerName ( int id, CStr* Name )
{
if ( (GetNumberOfControllers() <= 0) || (id > GetNumberOfControllers()) )
return false;
if (!Name)
return false;
if (id == -1)
{
if (idJoystick == -1) // if no controller then try to init the defalut
if (!InitController()) // if it don't exist we need to bail
return false;
// copy the name of the defalut
*Name = m_rController.rDeviceID.sDevName;
return true;
}
*Name = getJoystickName(id);
return true;
}
int CJoyInput::GetNumberOfControllers( void )
{
int i = 0;
for(; i < sf::Joystick::Count; ++i)
if(!sf::Joystick::isConnected(i))
return i;
return i;
}
void CJoyInput::Update(void)
{
bool bError = false;
if(idJoystick != -1)
{
memcpy(LastButtons, m_rController.aButtons, sizeof(LastButtons));
for(int i = _XAXIS; i <= _VAXIS; ++i)
{
if (m_rController.aAxes[i].bActive)
{
m_rController.aAxes[i].position = sf::Joystick::getAxisPosition(idJoystick, sf::Joystick::Axis(i)) / 100.0f;
}
}
if (m_rController.bHasHat)
{
m_rController.aHatVector[0] = sf::Joystick::getAxisPosition(idJoystick, sf::Joystick::PovX) / 100.0f;
m_rController.aHatVector[1] = sf::Joystick::getAxisPosition(idJoystick, sf::Joystick::PovY) / 100.0f;
}
else
m_rController.aHatVector[0] = m_rController.aHatVector[1] = 0;
for (int i = 0; i < m_rController.iButtons; i ++)
m_rController.aButtons[i] = sf::Joystick::isButtonPressed(idJoystick, i);
}
}
| 412 | 0.867135 | 1 | 0.867135 | game-dev | MEDIA | 0.76616 | game-dev | 0.973088 | 1 | 0.973088 |
aquietone/lazbis | 71,143 | init.lua | --[[
Best In Slot - Project Lazarus Edition
aquietone, dlilah, ...
Tracker lua script for all the good stuff to have on Project Lazarus server.
]]
local meta = {version = '3.5.2', name = string.match(string.gsub(debug.getinfo(1, 'S').short_src, '\\init.lua', ''), "[^\\]+$")}
local mq = require('mq')
local ImGui = require('ImGui')
local bisConfig = require('bis')
local spellConfig = require('spells')
local PackageMan = require('mq/PackageMan')
local icons = require('mq/icons')
local sql = PackageMan.Require('lsqlite3')
local dbpath = string.format('%s\\%s', mq.TLO.MacroQuest.Path('resources')(), 'lazbis.db')
local ok, actors = pcall(require, 'actors')
if not ok then
printf('Your version of MacroQuest does not support Lua Actors, exiting.')
mq.exit()
end
-- UI States
local openGUI = true
local shouldDrawGUI = true
local minimizedGUI = false
local currentTab = nil
-- Character info storage
local gear = {}
local group = {}
local sortedGroup = {}
local itemChecks = {}
local tradeskills = {}
local emptySlots = {}
local teams = {}
local spellData = {}
local groupSpellData = {}
-- Item list information
local selectedItemList = bisConfig.ItemLists[bisConfig.DefaultItemList.group][bisConfig.DefaultItemList.index]
local itemList = bisConfig.sebilis
local selectionChanged = true
local firstTimeLoad = true
local settings = {ShowSlots=true,ShowMissingOnly=false,AnnounceNeeds=false,AnnounceChannel='Group',Locked=false}
local orderedSkills = {'Baking', 'Blacksmithing', 'Brewing', 'Fletching', 'Jewelry Making', 'Pottery', 'Tailoring'}
local recipeQuestIdx = 1
local ingredientsArray = {}
local reapplyFilter = false
local slots = {'charm','leftear','head','face','rightear','neck','shoulder','arms','back','leftwrist','rightwrist','ranged','hands','mainhand','offhand','leftfinger','rightfinger','chest','legs','feet','waist','powersource'}
local hideOwnedSpells = false
local server = mq.TLO.EverQuest.Server()
local dbfmt = "INSERT INTO Inventory VALUES ('%s','%s','%s','%s','%s','%s',%d,%d,'%s');\n"
local db
local actor
local teamName = ''
local showPopup = false
local selectedTeam = ''
local DZ_NAMES = {
Raid = {
{name='The Crimson Curse', lockout='The Crimson Curse', zone='Chardok'},
{name='Crest Event', lockout='Threads_of_Chaos', zone='Qeynos Hills (BB)'},
{name='Fippy', lockout='=Broken World', zone='HC Qeynos Hills (pond)'},
{name='$$PAID$$ Fippy', lockout='Broken World [Time Keeper]', zone='Plane of Time'},
{name='DSK', lockout='=Dreadspire_HC', zone='Castle Mistmoore'},
{name='$$PAID$$ DSK', lockout='Dreadspire_HC [Time Keeper]', zone='Plane of Time'},
{name='Veksar', lockout='A Lake of Ill Omens', zone='Lake of Ill Omen'},
{name='Anguish', lockout='=Overlord Mata Muram', zone='Wall of Slaughter', index=3},
{name='Trak', lockout='Trakanon_Final', zone='HC Sebilis'},
{name='FUKU', lockout='The Fabled Undead Knight', zone='Unrest'}
},
Group = {
{name='Venril Sathir', lockout='Revenge on Venril Sathir', zone='Karnors Castle'},
{name='Fenrir', lockout='Bloodfang', zone='West Karana'},
{name='Selana', lockout='Moonshadow', zone='West Karana'},
{name='Finish Them Off', lockout='Finish them off', zone='Castle Mistmoore'},
{name='Keepsakes', lockout='Keepsakes', zone='Surefall Glade'},
{name='Ayonae', lockout='Confront the Maestra', zone='Surefall Glade'},
{name='Howling Stones', lockout='Echoes of Charasis', zone='The Overthere'},
{name='Doll Maker', lockout='Doll Maker', zone='Kithicor Forest'},
},
OldRaids = {
{name='Trial of Hatred', lockout='Proving Grounds: The Mastery of Hatred', zone='MPG'},
{name='Trial of Corruption', lockout='Proving Grounds: The Mastery of Corruption', zone='MPG'},
{name='Trial of Adaptation', lockout='Proving Grounds: The Mastery of Adaptation', zone='MPG'},
{name='Trial of Specialization', lockout='Proving Grounds: The Mastery of Specialization', zone='MPG'},
{name='Trial of Foresight', lockout='Proving Grounds: The Mastery of Foresight', zone='MPG'},
{name='Trial of Endurance', lockout='Proving Grounds: The Mastery of Endurance', zone='MPG'},
{name='Riftseekers', lockout='Riftseeker', zone='Riftseeker'},
{name='Tacvi', lockout='Tunat', zone='Txevu', index=3},
{name='Txevu', lockout='Txevu', zone='Txevu'},
{name='Plane of Time', lockout='Quarm', zone='Plane of Time', index=3}, -- 'Phase 1 Complete', 'Phase 2 Complete', 'Phase 3 Complete', 'Phase 4 Complete', 'Phase 5 Complete', 'Quarm'
}
}
local dzInfo = {[mq.TLO.Me.CleanName()] = {Raid={}, Group={}, OldRaids={}}}
local niceImg = mq.CreateTexture(mq.luaDir .. "/" .. meta.name .. "/bis.png")
local iconImg = mq.CreateTexture(mq.luaDir .. "/" .. meta.name .. "/icon_lazbis.png")
-- Default to e3bca if mq2mono is loaded, else use dannet
local broadcast = '/e3bca'
local selectedBroadcast = 1
local rebroadcast = false
local isBackground = false
local dumpInv = false
local grouponly = false
local argopts = {['0']=function() isBackground=true end, debug=function() debug = true end, dumpinv=function() dumpInv = true end, group=function() grouponly = true broadcast = '/e3bcg' if not mq.TLO.Plugin('mq2mono')() then broadcast = '/dgge' end end}
local debug = false
if not mq.TLO.Plugin('mq2mono')() then broadcast = '/dge' end
local function split(str, char)
return string.gmatch(str, '[^' .. char .. ']+')
end
local function splitToTable(str, char)
local t = {}
for str in split(str, char) do
table.insert(t, str)
end
return t
end
local function addCharacter(name, class, offline, show, msg)
if not group[name] then
if debug then printf('Add character: Name=%s Class=%s Offline=%s Show=%s, Msg=%s', name, class, offline, show, msg) end
local char = {Name=name, Class=class, Offline=offline, Show=show, PingTime=mq.gettime()}
group[name] = char
table.insert(group, char)
table.insert(sortedGroup, char.Name)
table.sort(sortedGroup, function(a,b) return a < b end)
if msg then
selectionChanged = true
msg:send({id='hello',Name=mq.TLO.Me(),Class=mq.TLO.Me.Class.Name()})
end
elseif msg and group[name].Offline then
if debug then printf('Add character: Name=%s Class=%s Offline=%s Show=%s, Msg=%s', name, class, offline, show, msg) end
group[name].Offline = false
group[name].PingTime=mq.gettime()
if selectedBroadcast == 1 or (selectedBroadcast == 3 and mq.TLO.Group.Member(name)()) then
group[name].Show = true
end
end
end
local function simpleExec(stmt)
repeat
local result = db:exec(stmt)
if result ~= 0 then printf('Result: %s', result) end
if result == sql.BUSY then print('\arDatebase was busy!') mq.delay(math.random(10,50)) end
until result ~= sql.BUSY
end
local function initTables()
local foundInventory = false
local foundSettings = false
local foundTradeskills = false
local foundSpells = false
local function versioncallback(udata,cols,values,names)
for i=1,cols do
if values[i] == 'Inventory' then
foundInventory = true
elseif values[i] == 'Settings' then
foundSettings = true
elseif values[i] == 'Tradeskills' then
foundTradeskills = true
elseif values[i] == 'Spells' then
foundSpells = true
end
end
return 0
end
repeat
local result = db:exec([[SELECT name FROM sqlite_master WHERE type='table';]], versioncallback)
if result == sql.BUSY then print('\arDatabase was busy!') mq.delay(math.random(10,50)) end
until result ~= sql.BUSY
if not foundInventory then
simpleExec([[CREATE TABLE IF NOT EXISTS Inventory (Character TEXT NOT NULL, Class TEXT NOT NULL, Server TEXT NOT NULL, Slot TEXT NOT NULL, ItemName TEXT NOT NULL, Location TEXT NOT NULL, Count INTEGER NOT NULL, ComponentCount INTEGER NOT NULL, Category TEXT NOT NULL)]])
end
simpleExec([[DROP TABLE IF EXISTS Info]])
if not foundSettings then
simpleExec([[CREATE TABLE IF NOT EXISTS Settings (Key TEXT UNIQUE NOT NULL, Value TEXT NOT NULL)]])
end
if not foundTradeskills then
simpleExec([[CREATE TABLE IF NOT EXISTS Tradeskills (Character TEXT NOT NULL, Class TEXT NOT NULL, Server TEXT NOT NULL, Tradeskill TEXT NOT NULL, Value INTEGER NOT NULL)]])
end
if not foundSpells then
simpleExec([[CREATE TABLE IF NOT EXISTS Spells (Character TEXT NOT NULL, Class TEXT NOT NULL, Server TEXT NOT NULL, SpellName TEXT NOT NULL, Level INTEGER NOT NULL, Location TEXT NOT NULL)]])
end
-- check version and handle any migrations, none atm
simpleExec(("INSERT INTO Settings VALUES ('Version', '%s') ON CONFLICT(Key) DO UPDATE SET Value = '%s'"):format(meta.version, meta.version))
end
local function settingsRowCallback(udata,cols,values,names)
if values[1]:find('TEAM:') then
-- printf('loaded team %s - %s', values[1], values[2])
teams[values[1]] = {}
for token in string.gmatch(values[2], "[^,]+") do
-- print(token)
table.insert(teams[values[1]], token)
end
return 0
end
local value = values[2]
if value == 'true' then value = true
elseif value == 'false' then value = false
elseif tonumber(value) then value = tonumber(value) end
settings[values[1]] = value
return 0
end
local function initSettings()
repeat
local result = db:exec("SELECT * FROM Settings WHERE Key != 'Version'", settingsRowCallback)
if result == sql.BUSY then print('\arDatabase was busy!') mq.delay(math.random(10,50)) end
until result ~= sql.BUSY
end
local function initDB()
db = sql.open(dbpath)
if db then
db:exec("PRAGMA journal_mode=WAL;")
initTables()
initSettings()
end
end
local function exec(stmt, name, category, action)
for i=1,10 do
local wrappedStmt = ('BEGIN TRANSACTION;%s;COMMIT;'):format(stmt)
if debug then printf('Exec: %s', wrappedStmt) end
local result = db:exec(wrappedStmt)
if result == sql.BUSY then
print('\arDatabase was Busy!') mq.delay(math.random(100,1000))
elseif result ~= sql.OK then
printf('\ar%s failed for name: %s, category: %s, result: %s\n%s', action, name, category, result, wrappedStmt)
elseif result == sql.OK then
if debug then printf('Successfully %s for name: %s, category: %s', action, name, category) end
break
end
end
end
local function clearAllDataForCharacter(name)
local deleteStmt = ("DELETE FROM Inventory WHERE Character = '%s' AND Server = '%s'"):format(name, server)
exec(deleteStmt, name, nil, 'deleted')
end
local function clearCategoryDataForCharacter(name, category)
local deleteStmt = ("DELETE FROM Inventory WHERE Character = '%s' AND Server = '%s' AND Category = '%s'"):format(name, server, category)
exec(deleteStmt, name, category, 'deleted')
end
local function clearTradeskillDataForCharacter(name)
local deleteStmt = ("DELETE FROM Tradeskills WHERE Character = '%s' AND Server = '%s'"):format(name, server)
exec(deleteStmt, name, nil, 'deleted')
end
local function clearSpellDataForCharacter(name)
local deleteStmt = ("DELETE FROM Spells WHERE Character = '%s' AND Server = '%s'"):format(name, server)
exec(deleteStmt, name, nil, 'deleted')
end
local function resolveInvSlot(invslot)
if invslot == 'Bank' then return ' (Bank)' end
local numberinvslot = tonumber(invslot)
if not numberinvslot then return '' end
if numberinvslot >= 23 then
return ' (in bag'..invslot - 22 ..')'
else
return ' ('..mq.TLO.InvSlot(invslot).Name()..')'
end
end
local function buildInsertStmt(name, category)
local stmt = "\n"
local char = group[name]
for slot,value in pairs(gear[name]) do
local itemName = value.actualname
local configSlot = slot ~= 'Wrist1' and slot ~= 'Wrist2' and slot or 'Wrists'
if not itemName then
itemName = itemList[char.Class] and (itemList[char.Class][configSlot] or itemList[char.Class][slot] or itemList.Template[configSlot] or itemList.Template[slot])
if itemName and string.find(itemName, '/') then
itemName = itemName:match("([^/]+)")
end
end
if itemName then
stmt = stmt .. dbfmt:format(name,char.Class,server,slot:gsub('\'','\'\''),itemName:gsub('\'','\'\''),resolveInvSlot(value.invslot):gsub('\'','\'\''),tonumber(value.count) or 0,tonumber(value.componentcount) or 0,category)
end
end
return stmt
end
local function insertCharacterDataForCategory(name, category)
local insertStmt = buildInsertStmt(name, category)
exec(insertStmt, name, category, 'inserted')
end
local function rowCallback(udata,cols,values,names)
if group[values[1]] and not group[values[1]].Offline then return 0 end
addCharacter(values[1], values[2], true, false)
gear[values[1]] = gear[values[1]] or {}
gear[values[1]][values[4]] = {count=tonumber(values[7]), componentcount=tonumber(values[8]), actualname=values[6] and values[5], location=values[6]}
return 0
end
local function loadInv(category)
for _,char in ipairs(group) do
if char.Offline then gear[char.Name] = {} end
end
repeat
local result = db:exec(string.format("SELECT * FROM Inventory WHERE Category='%s' AND Server = '%s';", category, server), rowCallback)
if result == sql.BUSY then print('\arDatabase was busy!') mq.delay(math.random(10,50)) end
until result ~= sql.BUSY
reapplyFilter = true
end
local function tsRowCallback(udata,cols,values,names)
if group[values[1]] and not group[values[1]].Offline then return 0 end
addCharacter(values[1], values[2], true, false)
tradeskills[values[1]] = tradeskills[values[1]] or {}
tradeskills[values[1]][values[4]] = tonumber(values[5])
return 0
end
local function loadTradeskillsFromDB()
for _,char in ipairs(group) do
if char.Offline then tradeskills[char.Name] = {} end
end
repeat
local result = db:exec(string.format("SELECT * FROM Tradeskills WHERE Server = '%s';", server), tsRowCallback)
if result == sql.BUSY then print('\arDatabase was busy!') mq.delay(math.random(10,50)) end
until result ~= sql.BUSY
reapplyFilter = true
end
local function spellRowCallback(udata,cols,values,names)
if group[values[1]] and not group[values[1]].Offline then return 0 end
addCharacter(values[1], values[2], true, false)
groupSpellData[values[1]] = groupSpellData[values[1]] or {}
table.insert(groupSpellData[values[1]], {values[5], values[4], values[6]})
return 0
end
local function loadSpellsFromDB()
for _,char in ipairs(group) do
if char.Offline then groupSpellData[char.Name] = {} end
end
repeat
local result = db:exec(string.format("SELECT * FROM Spells WHERE Server = '%s';", server), spellRowCallback)
if result == sql.BUSY then print('\arDatabase was busy!') mq.delay(math.random(10,50)) end
until result ~= sql.BUSY
reapplyFilter = true
end
local foundItem = nil
local function singleRowCallback(udata,cols,values,names)
foundItem = {Character=values[1], Count=tonumber(values[7]), ItemName=values[6] and values[5], ComponentCount=tonumber(values[8])}
end
local function loadSingleRow(category, charName, itemName)
for _,char in ipairs(group) do
if char.Offline then gear[char.Name] = {} end
end
repeat
local result = db:exec(string.format("SELECT * FROM Inventory WHERE Category='%s' AND Server = '%s' AND Character = '%s' AND ItemName = '%s';", category, server, charName, itemName:gsub('\'','\'\'')), singleRowCallback)
if result == sql.BUSY then print('\arDatabase was busy!') mq.delay(math.random(10,50)) end
until result ~= sql.BUSY
end
local function doDumpInv(name, category)
clearCategoryDataForCharacter(name, category)
insertCharacterDataForCategory(name, category)
end
local function dumpTradeskills(name, skills)
clearTradeskillDataForCharacter(name)
-- name,class,server,skill,value
local char = group[name]
local stmt = "\n"
for skill,value in pairs(skills) do
stmt = stmt .. ("INSERT INTO Tradeskills VALUES ('%s','%s','%s','%s',%d);\n"):format(name, char.Class, server, skill, value)
end
exec(stmt, name, 'Tradeskills', 'inserted')
end
local function dumpSpells(name, spells)
clearSpellDataForCharacter(name)
if not spells then return end
-- name,class,server,skill,value
local char = group[name]
local stmt = "\n"
for _,missingSpell in ipairs(spells) do
stmt = stmt .. ("INSERT INTO Spells VALUES ('%s','%s','%s','%s',%d,'%s');\n"):format(name, char.Class, server, missingSpell[2]:gsub('\'','\'\''), missingSpell[1], missingSpell[3] and missingSpell[3]:gsub('\'','\'\'') or '')
end
exec(stmt, name, 'Spells', 'inserted')
end
local function searchItemsInList(list)
local classItems = bisConfig[list][mq.TLO.Me.Class.Name()]
local templateItems = bisConfig[list].Template
local results = {}
for _,itembucket in ipairs({templateItems,classItems}) do
for slot,item in pairs(itembucket) do
local currentResult = 0
local componentResult = 0
local currentSlot = nil
local actualName = nil
if string.find(item, '/') then
for itemName in split(item, '/') do
if slot == 'Wrists' then
local leftwrist = mq.TLO.Me.Inventory('leftwrist')
local rightwrist = mq.TLO.Me.Inventory('rightwrist')
if leftwrist.Name() == itemName or leftwrist.ID() == tonumber(itemName) then
results['Wrist1'] = {count=1,invslot=9,actualname=leftwrist.Name()}
elseif not results['Wrist1'] then
results['Wrist1'] = {count=0,invslot='',actualname=nil}
end
if rightwrist.Name() == itemName or rightwrist.ID() == tonumber(itemName) then
results['Wrist2'] = {count=1,invslot=10,actualname=rightwrist.Name()}
elseif not results['Wrist2'] then
results['Wrist2'] = {count=0,invslot='',actualname=nil}
end
else
local searchString = itemName
local findItem = mq.TLO.FindItem(searchString)
local findItemBank = mq.TLO.FindItemBank(searchString)
local count = mq.TLO.FindItemCount(searchString)() + mq.TLO.FindItemBankCount(searchString)()
if slot == 'PSAugSprings' and itemName == '39071' and currentResult < 3 then
currentResult = 0
end
if count > 0 and not actualName then
actualName = findItem() or findItemBank()
currentSlot = findItem.ItemSlot() or (findItemBank() and 'Bank') or ''
end
currentResult = currentResult + count
end
end
else
local searchString = item
currentResult = currentResult + mq.TLO.FindItemCount(searchString)() + mq.TLO.FindItemBankCount(searchString)()
currentSlot = mq.TLO.FindItem(searchString).ItemSlot() or (mq.TLO.FindItemBank(searchString)() and 'Bank') or ''
end
if slot ~= 'Wrists' then
if currentResult == 0 and bisConfig[list].Visible and bisConfig[list].Visible[slot] then
local compItem = bisConfig[list].Visible[slot]
componentResult = mq.TLO.FindItemCount(compItem)() + mq.TLO.FindItemBankCount(compItem)()
currentSlot = mq.TLO.FindItem(compItem).ItemSlot() or (mq.TLO.FindItemBank(compItem)() and 'Bank') or ''
end
results[slot] = {count=currentResult, invslot=currentSlot, componentcount=componentResult>0 and componentResult or nil, actualname=actualName}
else
if bisConfig[list].Visible and bisConfig[list].Visible['Wrists'] then
local compItem = bisConfig[list].Visible[slot]
componentResult = mq.TLO.FindItemCount(compItem)() + mq.TLO.FindItemBankCount(compItem)()
if results['Wrist1'].count == 0 and componentResult >= 1 then
results['Wrist1'].count = 1 results['Wrist1'].componentcount = 1
componentResult = componentResult - 1
end
if results['Wrist2'].count == 0 and componentResult >= 1 then
results['Wrist2'].count = 1 results['Wrist2'].componentcount = 1
end
end
end
end
end
return results
end
local function loadTradeskills()
return {
Blacksmithing = mq.TLO.Me.Skill('blacksmithing')(),
Baking = mq.TLO.Me.Skill('baking')(),
Brewing = mq.TLO.Me.Skill('brewing')(),
Tailoring = mq.TLO.Me.Skill('tailoring')(),
Pottery = mq.TLO.Me.Skill('pottery')(),
['Jewelry Making'] = mq.TLO.Me.Skill('jewelry making')(),
Fletching = mq.TLO.Me.Skill('fletching')(),
}
end
local function loadMissingSpells()
local missingSpells = {}
for _,level in ipairs({70,69,68,67,66}) do
local levelSpells = spellConfig[mq.TLO.Me.Class()][level]
for _,spellName in ipairs(levelSpells) do
local spellDetails = splitToTable(spellName, '|')
spellName = spellDetails[1]
local spellLocation = spellDetails[2]
spellData[spellName] = spellData[spellName] or mq.TLO.Me.Book(spellName)() or mq.TLO.Me.CombatAbility(spellName)() or 0
if spellData[spellName] == 0 then
table.insert(missingSpells, {level, spellName, spellLocation})
end
end
end
return missingSpells
end
-- Actor message handler
local function actorCallback(msg)
local content = msg()
if debug then printf('<<< MSG RCVD: id=%s', content.id) end
if content.id == 'hello' then
if debug then printf('=== MSG: id=%s Name=%s Class=%s group=%s', content.id, content.Name, content.Class, content.group) end
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
if isBackground then return end
addCharacter(content.Name, content.Class, false, true, msg)
elseif content.id == 'search' then
if debug then printf('=== MSG: id=%s list=%s', content.id, content.list) end
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
-- {id='search', list='dsk'}
local results = searchItemsInList(content.list)
if debug then printf('>>> SEND MSG: id=%s Name=%s list=%s class=%s', content.id, mq.TLO.Me.CleanName(), content.list, mq.TLO.Me.Class.Name()) end
msg:send({id='result', Name=mq.TLO.Me.CleanName(), list=content.list, class=mq.TLO.Me.Class.Name(), results=results, group=content.group})
elseif content.id == 'result' then
if debug then printf('=== MSG: id=%s Name=%s list=%s class=%s', content.id, content.Name, content.list, content.class) end
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
if isBackground then return end
-- {id='result', Name='name', list='dsk', class='Warrior', results={slot1=1, slot2=0}}
local results = content.results
if results == nil then return end
local char = group[content.Name]
gear[char.Name] = {}
for slot,res in pairs(results) do
if (bisConfig[content.list][content.class] and bisConfig[content.list][content.class][slot]) or bisConfig[content.list].Template[slot] then
gear[char.Name][slot] = res
elseif slot == 'Wrist1' or slot == 'Wrist2' then
gear[char.Name][slot] = res
end
end
if bisConfig[content.list].Visible ~= nil and bisConfig[content.list].Visible.Slots ~= nil then
gear[char.Name].Visible = gear[char.Name].Visible or {}
for slot in split(bisConfig[content.list].Visible.Slots, ',') do
gear[char.Name].Visible[slot] = gear[char.Name][slot]
end
end
reapplyFilter = true
doDumpInv(char.Name, content.list)
elseif content.id == 'tsquery' then
if debug then printf('=== MSG: id=%s', content.id) end
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
local skills = loadTradeskills()
if debug then printf('>>> SEND MSG: id=%s Name=%s Skills=%s', content.id, mq.TLO.Me.CleanName(), skills) end
msg:send({id='tsresult', Skills=skills, Name=mq.TLO.Me.CleanName(), group=content.group})
elseif content.id == 'tsresult' then
if debug then printf('=== MSG: id=%s Name=%s Skills=%s', content.id, content.Name, content.Skills) end
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
if isBackground then return end
local char = group[content.Name]
tradeskills[char.Name] = tradeskills[char.Name] or {}
for name,skill in pairs(content.Skills) do
tradeskills[char.Name][name] = skill
end
dumpTradeskills(char.Name, tradeskills[char.Name])
elseif content.id == 'searchempties' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
local empties={}
for i = 0, 21 do
local slot = mq.TLO.InvSlot(i).Item
if slot.ID() ~= nil then
for j=1,6 do
local augType = slot.AugSlot(j).Type()
if augType and augType ~= 0 and augType ~= 20 and augType ~= 30 then
local augSlot = slot.AugSlot(j).Item()
if not augSlot then--and augType ~= 0 then
-- empty aug slot
table.insert(empties, ('%s: Slot %s, Type %s'):format(slots[i+1], j, augType))
end
end
end
else
-- empty slot
table.insert(empties, slots[i+1])
end
end
if debug then printf('>>> SEND MSG: id=%s Name=%s empties=%s', content.id, mq.TLO.Me.CleanName(), empties) end
msg:send({id='emptiesresult', empties=empties, Name=mq.TLO.Me.CleanName(), group=content.group})
elseif content.id == 'emptiesresult' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
if debug then printf('=== MSG: id=%s Name=%s empties=%s', content.id, content.Name, content.empties) end
if isBackground then return end
emptySlots[content.Name] = content.empties
local message = 'Empties for ' .. content.Name .. ' - '
if not content.empties then return end
for _,empty in ipairs(content.empties) do
message = message .. empty .. ', '
end
elseif content.id == 'searchspells' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
msg:send({id='spellsresult', missingSpells=loadMissingSpells(), Name=mq.TLO.Me.CleanName(), group=content.group})
elseif content.id == 'spellsresult' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
if content.Name == mq.TLO.Me.CleanName() then return end
if isBackground then return end
groupSpellData[content.Name] = content.missingSpells
dumpSpells(content.Name, groupSpellData[content.Name])
elseif content.id == 'dzquery' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
msg:send({id='dzresult', lockouts=dzInfo[mq.TLO.Me.CleanName()], Name=mq.TLO.Me.CleanName(), group=content.group})
elseif content.id == 'dzresult' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
if content.Name == mq.TLO.Me.CleanName() then return end
if isBackground then return end
dzInfo[content.Name] = content.lockouts
elseif content.id == 'pingreq' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
msg:send({id='pingresp', Name=mq.TLO.Me.CleanName(), time=mq.gettime(), group=content.group})
elseif content.id == 'pingresp' then
if content.group and content.group ~= mq.TLO.Group.Leader() then return end
if content.Name == mq.TLO.Me.CleanName() then return end
if not group[content.Name] then return end
if isBackground then return end
group[content.Name].Offline = false
group[content.Name].PingTime = content.time
if debug then printf('char pingtime updated %s %s', content.Name, content.time) end
end
end
local function changeBroadcastMode(tempBroadcast)
local origBroadcast = broadcast
local bChanged = false
if not grouponly then
if not mq.TLO.Plugin('mq2mono')() then
if tempBroadcast == 3 and broadcast ~= '/dgge' then
broadcast = '/dgge'
bChanged = true
elseif broadcast ~= '/dge' then
broadcast = '/dge'
bChanged = true
end
else
if tempBroadcast == 3 and broadcast ~= '/e3bcg' then
broadcast = '/e3bcg'
bChanged = true
elseif broadcast ~= '/e3bca' then
broadcast = '/e3bca'
bChanged = true
end
end
end
if tempBroadcast == 1 or tempBroadcast == 3 then
-- remove offline toons
for _,char in ipairs(group) do
if char.Offline or (tempBroadcast == 3 and not mq.TLO.Group.Member(char.Name)()) then
char.Show = false
elseif tempBroadcast == 1 or (tempBroadcast == 3 and mq.TLO.Group.Member(char.Name)()) then
char.Show = true
end
end
selectedTeam = ''
elseif tempBroadcast == 2 then
-- add offline toons
for _,char in ipairs(group) do
char.Show = true
end
selectedTeam = ''
elseif tempBroadcast == 4 then
selectedTeam = ''
elseif type(tempBroadcast) ~= 'number' then
for _,char in ipairs(group) do char.Show = false end
for _,teamMember in ipairs(teams[tempBroadcast]) do
for _,char in ipairs(group) do
if teamMember == char.Name then char.Show = true end
end
end
end
if bChanged then
rebroadcast = true
mq.cmdf('%s /lua stop %s', origBroadcast, meta.name)
end
selectedBroadcast = tempBroadcast
end
local function getItemColor(slot, count, visibleCount, componentCount)
if componentCount and componentCount > 0 then
return { 1, 1, 0 }
end
-- if slot == 'Wrists2' then
-- return { count == 2 and 0 or 1, count == 2 and 1 or 0, .1 }
-- end
return { count > 0 and 0 or 1, (count > 0 or visibleCount > 0) and 1 or 0, .1 }
end
local function slotRow(slot, tmpGear)
-- local realSlot = slot ~= 'Wrists2' and slot or 'Wrists'
local realSlot = slot
ImGui.TableNextRow()
ImGui.TableNextColumn()
ImGui.Text('' .. slot)
for _, char in ipairs(group) do
if char.Show then
ImGui.TableNextColumn()
if (tmpGear[char.Name] ~= nil and tmpGear[char.Name][realSlot] ~= nil) then
local configSlot = slot
if configSlot == 'Wrist1' or configSlot == 'Wrist2' then
if itemList[char.Class] and itemList[char.Class]['Wrists'] then configSlot = 'Wrists' end
end
local itemName = itemList[char.Class] and itemList[char.Class][configSlot] or itemList.Template[configSlot]
if (itemName ~= nil) then
if string.find(itemName, '/') then
itemName = itemName:match("([^/]+)")
end
local actualName = tmpGear[char.Name][realSlot].actualname
if not actualName or string.find(actualName, '/') then
actualName = itemName
end
local count, invslot = tmpGear[char.Name][realSlot].count, tmpGear[char.Name][realSlot].invslot
local countVis = tmpGear[char.Name].Visible and tmpGear[char.Name].Visible[configSlot] and tmpGear[char.Name].Visible[configSlot].count or 0
local componentcount = tmpGear[char.Name][realSlot].componentcount
local color = getItemColor(slot, tonumber(count), tonumber(countVis), tonumber(componentcount))
ImGui.PushStyleColor(ImGuiCol.Text, color[1], color[2], color[3], 1)
if itemName == actualName then
local resolvedInvSlot = tmpGear[char.Name][realSlot].location or resolveInvSlot(invslot)
local lootDropper = color[2] == 0 and bisConfig.LootDroppers[actualName]
ImGui.Text('%s%s%s', itemName, settings.ShowSlots and resolvedInvSlot or '', lootDropper and ' ('..lootDropper..')' or '')
ImGui.PopStyleColor()
if ImGui.IsItemHovered() and ImGui.IsMouseClicked(ImGuiMouseButton.Left) then
mq.cmdf('/link %s', itemName)
end
else
local lootDropper = color[2] == 0 and bisConfig.LootDroppers[actualName]
local resolvedInvSlot = tmpGear[char.Name][realSlot].location or resolveInvSlot(invslot)
--ImGui.Text('%s%s', itemName, lootDropper and ' ('..lootDropper..')' or '')
ImGui.Text('%s%s%s', itemName, settings.ShowSlots and resolvedInvSlot or '', lootDropper and ' ('..lootDropper..')' or '')
ImGui.PopStyleColor()
if ImGui.IsItemHovered() then
--local resolvedInvSlot = tmpGear[char.Name][realSlot].location or resolveInvSlot(invslot)
ImGui.BeginTooltip()
ImGui.Text('Found ') ImGui.SameLine() ImGui.TextColored(0,1,0,1,'%s', actualName) ImGui.SameLine() ImGui.Text('in slot %s', resolvedInvSlot)
ImGui.EndTooltip()
end
if ImGui.IsItemHovered() and ImGui.IsMouseClicked(ImGuiMouseButton.Left) then
mq.cmdf('/squelch /link %s', itemName)
end
end
end
end
end
end
end
local filter = ''
local filteredGear = {}
local filteredSlots = {}
local useFilter = false
local function filterGear(slots)
filteredGear = {}
filteredSlots = {}
local lowerFilter = filter:lower()
if slots then
for _,category in ipairs(slots) do
local catSlots = category.Slots
for _,slot in ipairs(catSlots) do
for _, char in ipairs(group) do
if (gear[char.Name] ~= nil and gear[char.Name][slot] ~= nil) then
local itemName = itemList[char.Class] and itemList[char.Class][slot] or itemList.Template[slot]
if (itemName ~= nil) and itemName:lower():find(lowerFilter) and (not settings.ShowMissingOnly or gear[char.Name][slot].count == 0) then
filteredGear[char.Name] = filteredGear[char.Name] or {Name=char.Name, Class=char.Class}
filteredGear[char.Name][slot] = gear[char.Name][slot]
if not filteredSlots[category.Name] then
table.insert(filteredSlots, {Name=category.Name, Slots={slot}})
filteredSlots[category.Name] = category.Name
else
for _,cat in ipairs(filteredSlots) do
if cat.Name == category.Name then
local addSlot = true
for _,s in ipairs(cat.Slots) do
if s == slot then
addSlot = false
break
end
end
if addSlot then table.insert(cat.Slots, slot) end
break
end
end
end
end
end
end
end
end
end
end
local ingredientFilter = ''
local filteredIngredients = {}
local useIngredientFilter = false
local function filterIngredients()
filteredIngredients = {}
for _,ingredient in pairs(ingredientsArray) do
if ingredient.Name:lower():find(ingredientFilter:lower()) then
table.insert(filteredIngredients, ingredient)
end
end
end
local function DrawTextLink(label, url)
ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetStyleColor(ImGuiCol.ButtonHovered))
ImGui.Text(label)
ImGui.PopStyleColor()
if ImGui.IsItemHovered() then
if ImGui.IsMouseClicked(ImGuiMouseButton.Left) then
os.execute(('start "" "%s"'):format(url))
end
ImGui.BeginTooltip()
ImGui.Text('%s', url)
ImGui.EndTooltip()
end
end
local ColumnID_Name = 1
local ColumnID_Location = 2
local current_sort_specs = nil
local function CompareWithSortSpecs(a, b)
for n = 1, current_sort_specs.SpecsCount, 1 do
local sort_spec = current_sort_specs:Specs(n)
local delta = 0
local sortA = a
local sortB = b
if sort_spec.ColumnUserID == ColumnID_Name then
sortA = a.Name
sortB = b.Name
elseif sort_spec.ColumnUserID == ColumnID_Location then
sortA = a.Location
sortB = b.Location
end
if sortA < sortB then
delta = -1
elseif sortB < sortA then
delta = 1
else
delta = 0
end
if delta ~= 0 then
if sort_spec.SortDirection == ImGuiSortDirection.Ascending then
return delta < 0
end
return delta > 0
end
end
-- Always return a way to differentiate items.
return a.Name < b.Name
end
local function updateSetting(name, value)
settings[name] = value
simpleExec(("INSERT INTO Settings VALUES ('%s', '%s') ON CONFLICT(Key) DO UPDATE SET Value = '%s'"):format(name, value, value))
end
local function getAnnounceChannel()
if settings.AnnounceChannel == 'Raid' then
if mq.TLO.Raid.Members() > 0 then return '/rs ' else return '/g ' end
elseif settings.AnnounceChannel == 'Group' then
return '/g '
elseif settings.AnnounceChannel == 'Guild' then
return '/gu '
elseif settings.AnnounceChannel == 'Say' then
return '/say '
end
end
local function VerticalSeparator()
ImGui.PushStyleColor(ImGuiCol.Button, 0, 0.2, 0.4, 1)
ImGui.PushStyleColor(ImGuiCol.ButtonActive, 0, 0.2, 0.4, 1)
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, 0, 0.2, 0.4, 1)
ImGui.Button('##separator', 3, 0)
ImGui.PopStyleColor(3)
end
local function LockButton(id, isLocked)
local lockedIcon = settings.Locked and icons.FA_LOCK .. '##' .. id or icons.FA_UNLOCK .. '##' .. id
if ImGui.Button(lockedIcon) then
isLocked = not isLocked
end
return isLocked
end
local function drawCharacterMenus()
ImGui.PushItemWidth(150)
if ImGui.BeginCombo('##Characters', 'Characters', ImGuiComboFlags.HeightLarge) then
for teamName,_ in pairs(teams) do
local _,pressed = ImGui.Checkbox(teamName:gsub('TEAM:', 'Team: '), selectedTeam == teamName)
if pressed then if selectedTeam ~= teamName then selectedTeam = teamName changeBroadcastMode(teamName) else selectedTeam = '' end end
end
local _,pressed = ImGui.Checkbox('All Online', selectedBroadcast == 1)
if pressed then changeBroadcastMode(1) end
_,pressed = ImGui.Checkbox('All Offline', selectedBroadcast == 2)
if pressed then changeBroadcastMode(2) end
_,pressed = ImGui.Checkbox('Group', selectedBroadcast == 3)
if pressed then changeBroadcastMode(3) end
for i,name in ipairs(sortedGroup) do
local char = group[name]
_,pressed = ImGui.Checkbox(char.Name, char.Show or false)
if pressed then
char.Show = not char.Show
changeBroadcastMode(4)
end
end
ImGui.EndCombo()
end
ImGui.PopItemWidth()
ImGui.SameLine()
if ImGui.Button('Save Character Set') then
showPopup = true
ImGui.OpenPopup('Save Team')
ImGui.SetNextWindowSize(200, 90)
end
ImGui.SameLine()
if ImGui.Button('Delete Character Set') then
if selectedTeam then
simpleExec(("DELETE FROM Settings WHERE Key = '%s'"):format(selectedTeam))
teams[teamName] = nil
end
end
ImGui.SameLine()
if ImGui.Button('Delete Selected Characters') then
showPopup = true
ImGui.OpenPopup('Delete Characters')
ImGui.SetNextWindowSize(200, 90)
end
if ImGui.BeginPopupModal('Delete Characters') then
if ImGui.Button('Proceed') then
for _,char in ipairs(group) do
if char.Show then
simpleExec(("DELETE FROM Inventory WHERE Character = '%s' AND Server = '%s'"):format(char.Name, server))
end
end
for i=#sortedGroup,1,-1 do
if group[sortedGroup[i]].Show then table.remove(sortedGroup, i) end
end
for i=#group,1,-1 do
local charName = group[i].Name
if group[i].Show then table.remove(group, i) group[charName] = nil end
end
showPopup = false
ImGui.CloseCurrentPopup()
end
ImGui.SameLine()
if ImGui.Button('Cancel') then
showPopup = false
ImGui.CloseCurrentPopup()
end
ImGui.EndPopup()
end
if ImGui.BeginPopupModal('Save Team', showPopup) then
teamName,_ = ImGui.InputText('Name', teamName)
if ImGui.Button('Save') and teamName ~= '' then
local nameList = ''
local newTeam = {}
for i,char in ipairs(group) do
if char.Show then
table.insert(newTeam, char.Name)
nameList = nameList .. char.Name .. ','
end
end
simpleExec(("INSERT INTO Settings VALUES ('TEAM:%s', '%s') ON CONFLICT(Key) DO UPDATE SET Value = '%s'"):format(teamName, nameList, nameList))
teams['TEAM:'..teamName] = newTeam
showPopup = false
ImGui.CloseCurrentPopup()
teamName = ''
end
ImGui.SameLine()
if ImGui.Button('Cancel') then
showPopup = false
ImGui.CloseCurrentPopup()
teamName = ''
end
ImGui.EndPopup()
end
end
local WINDOW_FLAGS = ImGuiWindowFlags.HorizontalScrollbar
local classes = {Bard='BRD',Beastlord='BST',Berserker='BER',Cleric='CLR',Druid='DRU',Enchanter='ENC',Magician='MAG',Monk='MNK',Necromancer='NEC',Paladin='PAL',Ranger='RNG',Rogue='ROG',['Shadow Knight']='SHD',Shaman='SHM',Warrior='WAR',Wizard='WIZ'}
local function bisGUI()
ImGui.SetNextWindowSize(ImVec2(800,500), ImGuiCond.FirstUseEver)
if minimizedGUI then
openGUI, shouldDrawGUI = ImGui.Begin('BIS Check (' .. meta.version .. ')###BIS Check Mini', openGUI,
bit32.bor(ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoTitleBar))
else
local windowFlags = WINDOW_FLAGS
if settings.Locked then windowFlags = bit32.bor(windowFlags, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoResize) end
openGUI, shouldDrawGUI = ImGui.Begin('BIS Check ('.. meta.version ..')###BIS Check', openGUI, windowFlags)
end
if shouldDrawGUI then
if minimizedGUI then
if ImGui.ImageButton('MinimizeLazBis', iconImg:GetTextureID(), ImVec2(30, 30)) then
minimizedGUI = false
end
if ImGui.IsItemHovered() then
ImGui.SetTooltip("LazBis is Running")
end
else
ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 17)
if ImGui.Button(icons.MD_FULLSCREEN_EXIT) then
minimizedGUI = true
end
if ImGui.IsItemHovered() then
ImGui.BeginTooltip()
ImGui.Text('Minimize')
ImGui.EndTooltip()
end
ImGui.SameLine()
local oldLocked = settings.Locked
settings.Locked = LockButton('bislocked', settings.Locked)
if oldLocked ~= settings.Locked then
updateSetting('Locked', settings.Locked)
end
ImGui.SameLine()
if ImGui.BeginTabBar('bistabs') then
if ImGui.BeginTabItem('Gear') then
currentTab = 'Gear'
local origSelectedItemList = selectedItemList
ImGui.PushItemWidth(150)
ImGui.SetNextWindowSize(150, 350)
if ImGui.BeginCombo('Item List', selectedItemList.name) then
for _, group in ipairs(bisConfig.Groups) do
ImGui.TextColored(1, 1, 0, 1, group)
ImGui.Separator()
for i, list in ipairs(bisConfig.ItemLists[group]) do
if ImGui.Selectable(list.name, selectedItemList.id == list.id) then
selectedItemList = list
settings['SelectedList'] = selectedItemList.id
updateSetting('SelectedList', selectedItemList.id)
end
end
end
ImGui.EndCombo()
end
ImGui.PopItemWidth()
itemList = bisConfig[selectedItemList.id]
local slots = itemList.Main.Slots
if selectedItemList.id ~= origSelectedItemList.id then
selectionChanged = true
filter = ''
settings.ShowMissingOnly = false
updateSetting('SelectedList', selectedItemList.id)
end
ImGui.SameLine()
if ImGui.Button('Refresh') then selectionChanged = true end
ImGui.SameLine()
ImGui.PushItemWidth(300)
local tmpFilter = ImGui.InputTextWithHint('##filter', 'Search...', filter)
ImGui.PopItemWidth()
ImGui.SameLine()
ImGui.Text('Show:')
ImGui.SameLine()
local tmpShowSlots = ImGui.Checkbox('Slots', settings.ShowSlots)
if tmpShowSlots ~= settings.ShowSlots then updateSetting('ShowSlots', tmpShowSlots) end
ImGui.SameLine()
local tmpShowMissingOnly = ImGui.Checkbox('Missing Only', settings.ShowMissingOnly)
if tmpShowMissingOnly ~= settings.ShowMissingOnly or tmpFilter ~= filter or reapplyFilter then
filter = tmpFilter
if tmpShowMissingOnly ~= settings.ShowMissingOnly then updateSetting('ShowMissingOnly', tmpShowMissingOnly) end
filterGear(slots)
reapplyFilter = false
end
if filter ~= '' or settings.ShowMissingOnly then useFilter = true else useFilter = false end
ImGui.SameLine()
VerticalSeparator()
ImGui.SameLine()
ImGui.Text('Announce:')
ImGui.SameLine()
local tmpAnnounceNeeds = ImGui.Checkbox('##AnnounceNeeds', settings.AnnounceNeeds)
if tmpAnnounceNeeds ~= settings.AnnounceNeeds then updateSetting('AnnounceNeeds', tmpAnnounceNeeds) end
ImGui.SameLine()
ImGui.PushItemWidth(90)
if ImGui.BeginCombo('##Channel', settings.AnnounceChannel) then
for i,name in ipairs({'Group','Raid','Guild','Say'}) do
local selected = ImGui.Selectable(name, settings.AnnounceChannel == name)
if selected and name ~= settings.AnnounceChannel then
updateSetting('AnnounceChannel', name)
end
end
ImGui.EndCombo()
end
ImGui.PopItemWidth()
ImGui.SameLine()
VerticalSeparator()
ImGui.SameLine()
drawCharacterMenus()
local numColumns = 1
for _,char in ipairs(group) do if char.Show then numColumns = numColumns + 1 end end
if next(itemChecks) ~= nil then
ImGui.Separator()
if ImGui.Button('X##LinkedItems') then
itemChecks = {}
end
ImGui.SameLine()
ImGui.Text('Linked items:')
if ImGui.BeginTable('linked items', numColumns, bit32.bor(ImGuiTableFlags.NoSavedSettings, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY), -1.0, 115) then
ImGui.TableSetupScrollFreeze(0, 1)
ImGui.TableSetupColumn('ItemName', bit32.bor(ImGuiTableColumnFlags.NoSort, ImGuiTableColumnFlags.WidthFixed), 250, 0)
for i,char in ipairs(group) do
if char.Show then
ImGui.TableSetupColumn(char.Name, bit32.bor(ImGuiTableColumnFlags.NoSort, ImGuiTableColumnFlags.WidthFixed), -1.0, 0)
end
end
ImGui.TableHeadersRow()
for itemName, _ in pairs(itemChecks) do
ImGui.TableNextRow()
ImGui.TableSetColumnIndex(0)
if ImGui.Button('X##' .. itemName) then
itemChecks[itemName] = nil
end
ImGui.SameLine()
if ImGui.Button('Announce##'..itemName) then
local message = getAnnounceChannel()
local doSend = false
message = message .. itemName .. ' - '
for _,name in ipairs(sortedGroup) do
local char = group[name]
if itemChecks[itemName][char.Name] == false then
-- message = message .. string.format('%s(%s)', char.Name, classes[char.Class]) .. ', '
message = message .. char.Name .. ', '
doSend = true
end
end
if doSend then mq.cmd(message) end
end
ImGui.SameLine()
ImGui.Text(itemName)
if itemChecks[itemName] then
for _,char in ipairs(group) do
if char.Show then
ImGui.TableNextColumn()
if itemChecks[itemName][char.Name] ~= nil then
local hasItem = itemChecks[itemName][char.Name]
ImGui.PushStyleColor(ImGuiCol.Text, hasItem and 0 or 1, hasItem and 1 or 0, 0.1, 1)
ImGui.Text(hasItem and 'HAVE' or 'NEED')
ImGui.PopStyleColor()
end
end
end
end
end
ImGui.EndTable()
end
end
if ImGui.BeginTable('gear', numColumns, bit32.bor(ImGuiTableFlags.BordersInner, ImGuiTableFlags.RowBg, ImGuiTableFlags.Reorderable, ImGuiTableFlags.NoSavedSettings, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY)) then
ImGui.TableSetupScrollFreeze(0, 1)
ImGui.TableSetupColumn('Item', bit32.bor(ImGuiTableColumnFlags.NoSort, ImGuiTableColumnFlags.WidthFixed), -1.0, 0)
for i,char in ipairs(group) do
if char.Show then
ImGui.TableSetupColumn(char.Name, bit32.bor(ImGuiTableColumnFlags.NoSort, ImGuiTableColumnFlags.WidthFixed), -1.0, 0)
end
end
ImGui.TableHeadersRow()
local tmpSlots = slots
local tmpGear = gear
if useFilter then tmpSlots = filteredSlots tmpGear = filteredGear end
if tmpSlots then
for _,category in ipairs(tmpSlots) do
local catName = category.Name
ImGui.TableNextRow()
ImGui.TableNextColumn()
if ImGui.TreeNodeEx(catName, bit32.bor(ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.DefaultOpen)) then
local catSlots = category.Slots
for _,slot in ipairs(catSlots) do
if slot ~= 'Wrists' then
slotRow(slot, tmpGear)
else
slotRow('Wrist1', tmpGear)
slotRow('Wrist2', tmpGear)
end
end
ImGui.TreePop()
end
if catName == 'Powersource' and selectedItemList.id == 'questitems' then
ImGui.TableNextRow()
ImGui.TableNextColumn()
if ImGui.TreeNodeEx('Tradeskills', bit32.bor(ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.DefaultOpen)) then
for _,name in ipairs(orderedSkills) do
ImGui.TableNextRow()
ImGui.TableNextColumn()
ImGui.Text(name)
for _,char in ipairs(group) do
if char.Show then
ImGui.TableNextColumn()
local skill = tradeskills[char.Name] and tradeskills[char.Name][name] or 0
ImGui.TextColored(skill < 300 and 1 or 0, skill == 300 and 1 or 0, 0, 1, '%s', tradeskills[char.Name] and tradeskills[char.Name][name])
end
end
end
ImGui.TreePop()
end
end
end
end
ImGui.EndTable()
end
ImGui.EndTabItem()
end
if ImGui.BeginTabItem('Empties') then
currentTab = 'Empties'
local hadEmpties = false
for char,empties in pairs(emptySlots) do
if empties then
ImGui.PushID(char)
hadEmpties = true
if ImGui.TreeNode('%s', char) then
for _,empty in ipairs(empties) do
ImGui.Text(' - %s', empty)
end
ImGui.TreePop()
end
ImGui.PopID()
end
end
if not hadEmpties then
ImGui.ImageButton('NiceButton', niceImg:GetTextureID(), ImVec2(200, 200),ImVec2(0.0,0.0), ImVec2(.55, .7))
end
ImGui.EndTabItem()
end
if bisConfig.StatFoodRecipes and ImGui.BeginTabItem('Stat Food') then
currentTab = 'Stat Food'
if ImGui.BeginTabBar('##statfoodtabs') then
if ImGui.BeginTabItem('Recipes') then
for _,recipe in ipairs(bisConfig.StatFoodRecipes) do
ImGui.PushStyleColor(ImGuiCol.Text, 0,1,1,1)
local expanded = ImGui.TreeNode(recipe.Name)
ImGui.PopStyleColor()
if expanded then
ImGui.Indent(30)
for _,ingredient in ipairs(recipe.Ingredients) do
ImGui.Text('%s%s', ingredient, bisConfig.StatFoodIngredients[ingredient] and ' - '..bisConfig.StatFoodIngredients[ingredient].Location or '')
ImGui.SameLine()
ImGui.TextColored(1,1,0,1,'(%s)', mq.TLO.FindItemCount('='..ingredient))
end
ImGui.Unindent(30)
ImGui.TreePop()
end
end
ImGui.EndTabItem()
end
if ImGui.BeginTabItem('Quests') then
ImGui.PushItemWidth(300)
if ImGui.BeginCombo('Quest', bisConfig.StatFoodQuests[recipeQuestIdx].Name) then
for i,quest in ipairs(bisConfig.StatFoodQuests) do
if ImGui.Selectable(quest.Name, recipeQuestIdx == i) then
recipeQuestIdx = i
end
end
ImGui.EndCombo()
end
ImGui.PopItemWidth()
for _,questStep in ipairs(bisConfig.StatFoodQuests[recipeQuestIdx].Recipes) do
ImGui.TextColored(0,1,1,1,questStep.Name)
ImGui.Indent(25)
for _,step in ipairs(questStep.Steps) do
ImGui.Text('\xee\x97\x8c %s', step)
end
ImGui.Unindent(25)
end
ImGui.EndTabItem()
end
if ImGui.BeginTabItem('Ingredients') then
ImGui.SameLine()
ImGui.PushItemWidth(300)
local tmpIngredientFilter = ImGui.InputTextWithHint('##ingredientfilter', 'Search...', ingredientFilter)
ImGui.PopItemWidth()
if tmpIngredientFilter ~= ingredientFilter then
ingredientFilter = tmpIngredientFilter
filterIngredients()
end
if ingredientFilter ~= '' then useIngredientFilter = true else useIngredientFilter = false end
local tmpIngredients = ingredientsArray
if useIngredientFilter then tmpIngredients = filteredIngredients end
if ImGui.BeginTable('Ingredients', 3, bit32.bor(ImGuiTableFlags.BordersInner, ImGuiTableFlags.RowBg, ImGuiTableFlags.Reorderable, ImGuiTableFlags.NoSavedSettings, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.Sortable)) then
ImGui.TableSetupScrollFreeze(0, 1)
ImGui.TableSetupColumn('Ingredient', bit32.bor(ImGuiTableColumnFlags.DefaultSort, ImGuiTableColumnFlags.WidthFixed), -1.0, ColumnID_Name)
ImGui.TableSetupColumn('Location', bit32.bor(ImGuiTableColumnFlags.WidthFixed), -1.0, ColumnID_Location)
ImGui.TableSetupColumn('Count', bit32.bor(ImGuiTableColumnFlags.NoSort, ImGuiTableColumnFlags.WidthFixed), -1.0, 0)
ImGui.TableHeadersRow()
local sort_specs = ImGui.TableGetSortSpecs()
if sort_specs then
if sort_specs.SpecsDirty then
current_sort_specs = sort_specs
table.sort(tmpIngredients, CompareWithSortSpecs)
current_sort_specs = nil
sort_specs.SpecsDirty = false
end
end
for _,ingredient in ipairs(tmpIngredients) do
ImGui.TableNextRow()
ImGui.TableNextColumn()
ImGui.Text(ingredient.Name)
ImGui.TableNextColumn()
ImGui.Text(ingredient.Location)
ImGui.TableNextColumn()
ImGui.Text('%s', mq.TLO.FindItemCount('='..ingredient.Name)())
end
ImGui.EndTable()
end
ImGui.EndTabItem()
end
ImGui.EndTabBar()
end
ImGui.EndTabItem()
end
if ImGui.BeginTabItem('Spells') then
currentTab = 'Spells'
hideOwnedSpells = ImGui.Checkbox('Missing Only', hideOwnedSpells)
ImGui.SameLine()
if ImGui.Button('Refresh') then selectionChanged = true end
ImGui.SameLine()
ImGui.TextColored(1, 0, 0, 1, 'Note: Other toons only send missing spells')
ImGui.SameLine()
VerticalSeparator()
ImGui.SameLine()
drawCharacterMenus()
local numSpellDataToons = 1
for _,_ in pairs(groupSpellData) do numSpellDataToons = numSpellDataToons + 1 end
ImGui.Columns(6)
ImGui.Text('%s', mq.TLO.Me.CleanName())
if ImGui.BeginTable('Spells', 2, bit32.bor(ImGuiTableFlags.BordersInner, ImGuiTableFlags.RowBg, ImGuiTableFlags.NoSavedSettings, ImGuiTableFlags.ScrollY), -1, 300) then
ImGui.TableSetupScrollFreeze(0, 1)
ImGui.TableSetupColumn('Name', bit32.bor(ImGuiTableColumnFlags.WidthFixed), -1, 2)
ImGui.TableSetupColumn('Location', bit32.bor(ImGuiTableColumnFlags.WidthFixed), -1, 3)
ImGui.TableHeadersRow()
for _,level in ipairs({70,69,68,67,66}) do
ImGui.TableNextRow()
ImGui.TableNextColumn()
if ImGui.TreeNodeEx(level..'##'..mq.TLO.Me.CleanName(), bit32.bor(ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.DefaultOpen)) then
local levelSpells = spellConfig[mq.TLO.Me.Class()][level]
for _,spellName in ipairs(levelSpells) do
local spellDetails = splitToTable(spellName, '|')
spellName = spellDetails[1]
local spellLocation = spellDetails[2]
spellData[spellName] = spellData[spellName] or mq.TLO.Me.Book(spellName)() or mq.TLO.Me.CombatAbility(spellName)() or 0
if not hideOwnedSpells or spellData[spellName] == 0 then
ImGui.TableNextRow()
ImGui.TableNextColumn()
ImGui.TextColored(spellData[spellName] == 0 and 1 or 0, spellData[spellName] ~= 0 and 1 or 0, 0, 1, '%s', spellName)
ImGui.TableNextColumn()
ImGui.Text('%s', spellLocation)
end
end
ImGui.TreePop()
end
end
ImGui.EndTable()
end
for i,char in ipairs(group) do
if char.Show and groupSpellData[char.Name] then
local data = groupSpellData[char.Name]
ImGui.NextColumn()
ImGui.Text('%s', char.Name)
if ImGui.BeginTable('Spells'..char.Name, 2, bit32.bor(ImGuiTableFlags.BordersInner, ImGuiTableFlags.RowBg, ImGuiTableFlags.NoSavedSettings, ImGuiTableFlags.ScrollY), -1, 300) then
ImGui.TableSetupScrollFreeze(0, 1)
ImGui.TableSetupColumn('Name', bit32.bor(ImGuiTableColumnFlags.WidthFixed), -1, 2)
ImGui.TableSetupColumn('Location', bit32.bor(ImGuiTableColumnFlags.WidthFixed), -1, 3)
ImGui.TableHeadersRow()
for _,level in ipairs({70,69,68,67,66}) do
ImGui.TableNextRow()
ImGui.TableNextColumn()
if ImGui.TreeNodeEx(level..'##'..char.Name, bit32.bor(ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.DefaultOpen)) then
for _,entry in ipairs(data) do
if tonumber(entry[1]) == level then
ImGui.TableNextRow()
ImGui.TableNextColumn()
ImGui.TextColored(1, 0, 0, 1, '%s', entry[2])
ImGui.TableNextColumn()
ImGui.Text('%s', entry[3])
end
end
ImGui.TreePop()
end
end
ImGui.EndTable()
end
end
end
ImGui.Columns(1)
ImGui.EndTabItem()
end
if ImGui.BeginTabItem('Lockouts') then
currentTab = 'Lockouts'
drawCharacterMenus()
local numColumns = 1
for _,char in ipairs(group) do if char.Show and not char.Offline then numColumns = numColumns + 1 end end
if ImGui.BeginTable('Lockouts', numColumns, bit32.bor(ImGuiTableFlags.BordersInner, ImGuiTableFlags.RowBg, ImGuiTableFlags.Reorderable, ImGuiTableFlags.NoSavedSettings, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.Sortable)) then
ImGui.TableSetupScrollFreeze(0, 1)
ImGui.TableSetupColumn('Name', bit32.bor(ImGuiTableColumnFlags.NoSort, ImGuiTableColumnFlags.WidthFixed), -1.0, 1)
for i,char in ipairs(group) do
if char.Show and not char.Offline then
ImGui.TableSetupColumn(char.Name, bit32.bor(ImGuiTableColumnFlags.NoSort, ImGuiTableColumnFlags.WidthFixed), -1.0, 0)
end
end
ImGui.TableHeadersRow()
-- for _,category in ipairs({'Raid','Group','OldRaids'}) do
for _,category in ipairs({'Raid','Group'}) do
ImGui.TableNextRow()
ImGui.TableNextColumn()
if ImGui.TreeNodeEx(category, bit32.bor(ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.DefaultOpen)) then
for _,instance in ipairs(DZ_NAMES[category]) do
ImGui.TableNextRow()
ImGui.TableNextColumn()
ImGui.Text('%s (%s)', instance.name, instance.zone)
for _,char in ipairs(group) do
if char.Show and not char.Offline then
ImGui.TableNextColumn()
if not dzInfo[char.Name] then
ImGui.Text(icons.FA_SPINNER)
elseif dzInfo[char.Name][category] and dzInfo[char.Name][category][instance.name] then
ImGui.TextColored(1,0,0,1, icons.FA_LOCK)
if ImGui.IsItemHovered() then
ImGui.BeginTooltip()
ImGui.TextColored(0,1,1,1, 'Available in: %s', dzInfo[char.Name][category][instance.name])
ImGui.EndTooltip()
end
else
ImGui.TextColored(0,1,0,1, icons.FA_UNLOCK)
end
end
end
end
ImGui.TreePop()
end
end
ImGui.EndTable()
end
ImGui.EndTabItem()
end
for _,infoTab in ipairs(bisConfig.Info) do
if ImGui.BeginTabItem(infoTab.Name) then
currentTab = infoTab.Name
ImGui.Text(infoTab.Text)
ImGui.EndTabItem()
end
end
if ImGui.BeginTabItem('Links') then
currentTab = 'Links'
for _,link in ipairs(bisConfig.Links) do
DrawTextLink(link.label, link.url)
end
ImGui.EndTabItem()
end
ImGui.EndTabBar()
end
ImGui.PopStyleVar()
end
end
ImGui.End()
if not openGUI and not minimizedGUI then
mq.cmdf('%s /lua stop %s', broadcast, meta.name)
mq.exit()
end
end
local function resolveGroupId()
return grouponly and mq.TLO.Group.Leader() or nil
end
local function searchAll()
if currentTab == 'Gear' or firstTimeLoad then
for _, char in ipairs(group) do
if not char.Offline then
actor:send({character=char.Name}, {id='search', list=selectedItemList.id, group=resolveGroupId()})
if selectedItemList.id == 'questitems' or firstTimeLoad then actor:send({character=char.Name}, {id='tsquery'}) end
end
end
end
if currentTab == 'Empties' or firstTimeLoad then
for _, char in ipairs(group) do
if not char.Offline then actor:send({character=char.Name}, {id='searchempties', group=resolveGroupId()}) end
end
end
if currentTab == 'Spells' or firstTimeLoad then
for _, char in ipairs(group) do
if not char.Offline then actor:send({character=char.Name}, {id='searchspells', group=resolveGroupId()}) end
end
end
if currentTab == 'Lockouts' or firstTimeLoad then
for _, char in ipairs(group) do
if not char.Offline then actor:send({character=char.Name}, {id='dzquery', group=resolveGroupId()}) end
end
end
end
local function doPing()
for _,char in ipairs(group) do
if not char.Offline then actor:send({character=char.Name}, {id='pingreq', group=resolveGroupId()}) end
end
end
local LINK_TYPES = nil
if mq.LinkTypes then
LINK_TYPES = {
[mq.LinkTypes.Item] = 'Item',
[mq.LinkTypes.Player] = 'Player',
[mq.LinkTypes.Spam] = 'Spam',
[mq.LinkTypes.Achievement] = 'Achievement',
[mq.LinkTypes.Dialog] = 'Dialog',
[mq.LinkTypes.Command] = 'Command',
[mq.LinkTypes.Spell] = 'Spell',
[mq.LinkTypes.Faction] = 'Faction',
}
end
local recentlyAnnounced = {}
local function sayCallback(line)
local itemLinks = {}
local foundAnyLinks = false
if mq.ExtractLinks then
local links = mq.ExtractLinks(line)
for _,link in ipairs(links) do
if link.type == mq.LinkTypes.Item then
local item = mq.ParseItemLink(link.link)
itemLinks[item.itemName] = link.link
foundAnyLinks = true
end
end
end
if itemList == nil or group == nil or gear == nil or (mq.LinkTypes and not foundAnyLinks) then
return
end
if string.find(line, 'Burns') then
return
end
local currentZone = mq.TLO.Zone.ShortName()
-- currentZone = 'anguish'
local currentZoneList = bisConfig.ZoneMap[currentZone] and bisConfig.ItemLists[bisConfig.ZoneMap[currentZone].group][bisConfig.ZoneMap[currentZone].index]
local scanLists = currentZoneList and {currentZoneList} or bisConfig.ItemLists['Raid Best In Slot']
local messages = {}
for _,list in ipairs(scanLists) do
for _, name in ipairs(sortedGroup) do
local char = group[name]
if char.Show then
local classItems = bisConfig[list.id][char.Class]
local templateItems = bisConfig[list.id].Template
local visibleItems = bisConfig[list.id].Visible
for _,itembucket in ipairs({classItems,templateItems,visibleItems}) do
for slot,item in pairs(itembucket) do
if item then
for itemName in split(item, '/') do
if string.find(line, itemName:gsub('-','%%-')) then
local hasItem = gear[char.Name][slot] ~= nil and (gear[char.Name][slot].count > 0 or (gear[char.Name][slot].componentcount or 0) > 0)
if not hasItem and list.id ~= selectedItemList.id then
loadSingleRow(list.id, char.Name, itemName)
if foundItem and (foundItem.Count > 0 or (foundItem.ComponentCount or 0) > 0) then hasItem = true end
foundItem = nil
end
itemChecks[itemName] = itemChecks[itemName] or {}
itemChecks[itemName][char.Name] = hasItem
if debug then printf('list.id=%s slot=%s item=%s hasItem=%s', list.id, slot, item, hasItem) end
if not hasItem then
if not messages[itemName] then
if itemLinks[itemName] then messages[itemName] = itemLinks[itemName] .. ' - ' else messages[itemName] = itemName .. ' - ' end
end
messages[itemName] = messages[itemName] .. char.Name .. ', '
end
end
end
end
end
end
end
end
end
if settings.AnnounceNeeds then
for itemName,msg in pairs(messages) do
if not recentlyAnnounced[itemName] or mq.gettime() - recentlyAnnounced[itemName] > 30000 then
local prefix = getAnnounceChannel()
mq.cmdf('%s%s', prefix, msg)
recentlyAnnounced[itemName] = mq.gettime()
end
end
end
end
local function lootedCallback(line, who, item)
if who == 'You' then who = mq.TLO.Me.CleanName() end
if not group[who] then return end
local char = group[who]
local currentZone = mq.TLO.Zone.ShortName()
local listToScan = bisConfig.ZoneMap[currentZone] and bisConfig.ItemLists[bisConfig.ZoneMap[currentZone].group][bisConfig.ZoneMap[currentZone].index]
if not listToScan then return end
local classItems = bisConfig[listToScan.id][char.Class]
local templateItems = bisConfig[listToScan.id].Template
local visibleItems = bisConfig[listToScan.id].Visible
for _,itembucket in ipairs({classItems,templateItems,visibleItems}) do
for slot,itemLine in pairs(itembucket) do
for itemName in split(itemLine, '/') do
if itemName == item then
if listToScan.id == selectedItemList.id then
gear[char.Name][slot] = gear[char.Name][slot] or {count=0, componentcount=0, actualname=item}
if visibleItems and visibleItems[slot] == item then
gear[char.Name][slot].componentcount = (gear[char.Name][slot].componentcount or 0) + 1
else
gear[char.Name][slot].count = (gear[char.Name][slot].count or 0) + 1
end
end
local stmt = dbfmt:format(char.Name,char.Class,server,slot:gsub('\'','\'\''),item:gsub('\'','\'\''),'',gear[char.Name] and gear[char.Name][slot].count or 0,gear[char.Name] and gear[char.Name][slot].componentcount or 0,listToScan.id)
exec(stmt, char.Name, listToScan.id, 'inserted')
end
end
end
end
end
local function writeAllItemLists()
local name = mq.TLO.Me.CleanName()
addCharacter(name, mq.TLO.Me.Class.Name(), false, true)
local insertStmt = ''
for _,group in ipairs(bisConfig.Groups) do
for _,list in ipairs(bisConfig.ItemLists[group]) do
itemList = bisConfig[list.id]
gear[name] = searchItemsInList(list.id)
insertStmt = insertStmt .. buildInsertStmt(name, list.id)
end
clearAllDataForCharacter(name)
exec(insertStmt, name, nil, 'inserted')
end
-- clear spell data
clearSpellDataForCharacter(name)
-- insert spell data
dumpSpells(name, loadMissingSpells())
-- clear tradeskill data
clearTradeskillDataForCharacter(name)
-- insert tradeskill data
dumpTradeskills(mq.TLO.Me.CleanName(), loadTradeskills())
end
local function zonedCallback()
local zone = mq.TLO.Zone.ShortName()
-- Load item list for specific zone if inside raid instance for that zone
if bisConfig.ZoneMap[zone] then
local newItemList = bisConfig.ItemLists[bisConfig.ZoneMap[zone].group][bisConfig.ZoneMap[zone].index]
if newItemList.id ~= selectedItemList.id then
selectedItemList = newItemList
itemList = bisConfig[selectedItemList.id]
selectionChanged = true
filter = ''
printf('Switched BIS list to %s', zone)
end
end
end
local function bisCommand(...)
local args = {...}
if args[1] == 'missing' then
local missingSpellsText = {}
local classSpells = spellConfig[mq.TLO.Me.Class()]
for _,level in ipairs({70,69,68,67,66}) do
local levelSpells = classSpells[level]
for _,spellName in ipairs(levelSpells) do
if spellData[spellName] == 0 then
table.insert(missingSpellsText, ('- %s: %s'):format(level, spellName))
end
end
end
printf('Missing Spells:\n%s', table.concat(missingSpellsText, '\n'))
elseif args[1] == 'lockouts' then
local output = ''
-- for _,category in ipairs({'Raid','Group','OldRaids'}) do
for _,category in ipairs({'Raid','Group'}) do
if not args[2] or args[2]:lower() == category:lower() then
for _,dz in ipairs(DZ_NAMES[category]) do
output = output .. '\ay' .. dz.name .. '\ax \ar' .. category .. '\ax (\ag' .. dz.zone .. '\ax): '
for _,char in ipairs(group) do
if char.Show and not char.Offline then
if dzInfo[char.Name] and dzInfo[char.Name][category] and dzInfo[char.Name][category][dz.name] then output = output .. '\ar' .. char.Name .. '\ax, ' else output = output .. '\ag' .. char.Name .. '\ax, ' end
end
end
output = output .. '\n'
end
print(output)
end
end
end
end
local function populateDZInfo()
mq.TLO.Window('DynamicZoneWnd').DoOpen()
mq.delay(1)
mq.TLO.Window('DynamicZoneWnd').DoClose()
mq.delay(1)
-- for _,category in ipairs({'Raid','Group','OldRaids'}) do
for _,category in ipairs({'Raid','Group'}) do
for _,dz in ipairs(DZ_NAMES[category]) do
local idx = mq.TLO.Window('DynamicZoneWnd/DZ_TimerList').List(dz.lockout,dz.index or 2)()
if idx then
dzInfo[mq.TLO.Me.CleanName()][category][dz.name] = mq.TLO.Window('DynamicZoneWnd/DZ_TimerList').List(idx,1)()
end
end
end
end
local function resolveArgs(args)
printf('\ag%s\ax started with \ay%d\ax arguments:', meta.name, #args)
for i, arg in ipairs(args) do
printf('args[%d]: %s', i, arg)
end
for _,arg in ipairs(args) do
if argopts[arg] then
argopts[arg]()
end
end
if not isBackground then
initDB()
else
openGUI = false
end
if dumpInv then
writeAllItemLists()
mq.exit()
end
if isBackground then openGUI = false end
end
local function init(args)
resolveArgs(args)
actor = actors.register(actorCallback)
populateDZInfo()
if isBackground then
mq.delay(100)
actor:send({id='hello',Name=mq.TLO.Me(),Class=mq.TLO.Me.Class.Name(),group=resolveGroupId()})
while true do
mq.delay(1000)
end
end
local zone = mq.TLO.Zone.ShortName()
-- Load item list for specific zone if inside raid instance for that zone
if bisConfig.ZoneMap[zone] then
selectedItemList = bisConfig.ItemLists[bisConfig.ZoneMap[zone].group][bisConfig.ZoneMap[zone].index]
itemList = bisConfig[selectedItemList.id]
else
-- Otherwise load the last list we were looking at
if settings['SelectedList'] then
for _, group in ipairs(bisConfig.Groups) do
for _, list in ipairs(bisConfig.ItemLists[group]) do
if list.id == settings['SelectedList'] then
selectedItemList = list
break
end
end
end
end
end
for name,ingredient in pairs(bisConfig.StatFoodIngredients) do
table.insert(ingredientsArray, {Name=name, Location=ingredient.Location})
end
table.sort(ingredientsArray, function(a,b) return a.Name < b.Name end)
addCharacter(mq.TLO.Me.CleanName(), mq.TLO.Me.Class.Name(), false, true)
mq.cmdf('%s /lua stop %s', broadcast, meta.name)
mq.delay(500)
mq.cmdf('%s /lua run %s 0%s%s', broadcast, meta.name, resolveGroupId() and ' group' or '', debug and ' debug' or '')
mq.delay(500)
mq.event('meSayItems', 'You say, #*#', sayCallback, {keepLinks = true})
mq.event('sayItems', '#*# says, #*#', sayCallback, {keepLinks = true})
mq.event('rsayItems', '#*# tells the raid, #*#', sayCallback, {keepLinks = true})
mq.event('rMeSayItems', 'You tell your raid, #*#', sayCallback, {keepLinks = true})
mq.event('gsayItems', '#*# tells the group, #*#', sayCallback, {keepLinks = true})
mq.event('gMeSayItems', 'You tell your party, #*#', sayCallback, {keepLinks = true})
mq.event('zoned', 'You have entered #*#', zonedCallback)
-- loot callback doesn't work right, just disable them for now
-- mq.event('otherLootedItem', '#*#--#1# has looted a #2#.--#*#', lootedCallback, {keepLinks = true})
-- mq.event('youLootedItem', '#*#--#1# have looted a #2#.--#*#', lootedCallback, {keepLinks = true})
mq.imgui.init('BISCheck', bisGUI)
mq.bind('/bis', bisCommand)
end
init({...})
local lastPingTime = mq.gettime() + 15000
while openGUI do
mq.delay(1000)
if rebroadcast then
gear = {}
itemChecks = {}
tradeskills = {}
for _,c in ipairs(group) do if c.Name ~= mq.TLO.Me.CleanName() then c.Offline = true printf('set %s offline', c.Name) end end
mq.delay(500)
mq.cmdf('%s /lua run %s 0%s%s', broadcast, meta.name, resolveGroupId() and ' group' or '', debug and ' debug' or '')
mq.delay(500)
selectionChanged = true
rebroadcast = false
end
if selectionChanged then
selectionChanged = false
searchAll()
if currentTab == 'Gear' or firstTimeLoad then loadInv(selectedItemList.id) end
if (currentTab == 'Gear' and selectedItemList.id == 'questitems') or firstTimeLoad then loadTradeskillsFromDB() end
if currentTab == 'Spells' or firstTimeLoad then loadSpellsFromDB() end
if firstTimeLoad then firstTimeLoad = false end
end
for itemName,lastAnnounced in pairs(recentlyAnnounced) do
if mq.gettime() - lastAnnounced > 30000 then
recentlyAnnounced[itemName] = nil
end
end
local curTime = mq.gettime()
if curTime - lastPingTime > 25000 then
if debug then printf('send ping') end
doPing()
group[mq.TLO.Me.CleanName()].PingTime = curTime
lastPingTime = curTime
end
for _,char in ipairs(group) do
if curTime - char.PingTime > 90000 then
if debug then printf('char hasnt responded %s %s %s', char.Name, curTime, char.PingTime) end
char.Offline = true
end
end
mq.doevents()
end | 412 | 0.763868 | 1 | 0.763868 | game-dev | MEDIA | 0.63214 | game-dev | 0.940522 | 1 | 0.940522 |
Code-Guy/Bamboo | 5,518 | external/jolt/Jolt/Physics/Collision/Shape/CylinderShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
#include <Jolt/Physics/PhysicsSettings.h>
JPH_NAMESPACE_BEGIN
/// Class that constructs a CylinderShape
class JPH_EXPORT CylinderShapeSettings final : public ConvexShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, CylinderShapeSettings)
/// Default constructor for deserialization
CylinderShapeSettings() = default;
/// Create a shape centered around the origin with one top at (0, -inHalfHeight, 0) and the other at (0, inHalfHeight, 0) and radius inRadius.
/// (internally the convex radius will be subtracted from the cylinder the total cylinder will not grow with the convex radius, but the edges of the cylinder will be rounded a bit).
CylinderShapeSettings(float inHalfHeight, float inRadius, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShapeSettings(inMaterial), mHalfHeight(inHalfHeight), mRadius(inRadius), mConvexRadius(inConvexRadius) { }
// See: ShapeSettings
virtual ShapeResult Create() const override;
float mHalfHeight = 0.0f;
float mRadius = 0.0f;
float mConvexRadius = 0.0f;
};
/// A cylinder
class JPH_EXPORT CylinderShape final : public ConvexShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
CylinderShape() : ConvexShape(EShapeSubType::Cylinder) { }
CylinderShape(const CylinderShapeSettings &inSettings, ShapeResult &outResult);
/// Create a shape centered around the origin with one top at (0, -inHalfHeight, 0) and the other at (0, inHalfHeight, 0) and radius inRadius.
/// (internally the convex radius will be subtracted from the cylinder the total cylinder will not grow with the convex radius, but the edges of the cylinder will be rounded a bit).
CylinderShape(float inHalfHeight, float inRadius, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr);
/// Get half height of cylinder
float GetHalfHeight() const { return mHalfHeight; }
/// Get radius of cylinder
float GetRadius() const { return mRadius; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override;
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return min(mHalfHeight, mRadius); }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See ConvexShape::GetSupportFunction
virtual const Support * GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
using ConvexShape::CastRay;
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::ColideSoftBodyVertices
virtual void CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, float inDeltaTime, Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const override;
// See Shape::TransformShape
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this), 0); }
// See Shape::GetVolume
virtual float GetVolume() const override { return 2.0f * JPH_PI * mHalfHeight * Square(mRadius); }
/// Get the convex radius of this cylinder
float GetConvexRadius() const { return mConvexRadius; }
// See Shape::IsValidScale
virtual bool IsValidScale(Vec3Arg inScale) const override;
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Class for GetSupportFunction
class Cylinder;
float mHalfHeight = 0.0f;
float mRadius = 0.0f;
float mConvexRadius = 0.0f;
};
JPH_NAMESPACE_END
| 412 | 0.859871 | 1 | 0.859871 | game-dev | MEDIA | 0.756853 | game-dev,graphics-rendering | 0.726608 | 1 | 0.726608 |
Kei-Luna/LunaGC_5.3.0 | 5,168 | src/generated/main/java/emu/grasscutter/net/proto/IslandPartySailStageOuterClass.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: IslandPartySailStage.proto
package emu.grasscutter.net.proto;
public final class IslandPartySailStageOuterClass {
private IslandPartySailStageOuterClass() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
/**
* <pre>
* Obf: IAJMOMGBODC
* </pre>
*
* Protobuf enum {@code IslandPartySailStage}
*/
public enum IslandPartySailStage
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>ISLAND_PARTY_SAIL_STAGE_NONE = 0;</code>
*/
ISLAND_PARTY_SAIL_STAGE_NONE(0),
/**
* <code>ISLAND_PARTY_SAIL_STAGE_SAIL = 1;</code>
*/
ISLAND_PARTY_SAIL_STAGE_SAIL(1),
/**
* <code>ISLAND_PARTY_SAIL_STAGE_BATTLE = 2;</code>
*/
ISLAND_PARTY_SAIL_STAGE_BATTLE(2),
UNRECOGNIZED(-1),
;
/**
* <code>ISLAND_PARTY_SAIL_STAGE_NONE = 0;</code>
*/
public static final int ISLAND_PARTY_SAIL_STAGE_NONE_VALUE = 0;
/**
* <code>ISLAND_PARTY_SAIL_STAGE_SAIL = 1;</code>
*/
public static final int ISLAND_PARTY_SAIL_STAGE_SAIL_VALUE = 1;
/**
* <code>ISLAND_PARTY_SAIL_STAGE_BATTLE = 2;</code>
*/
public static final int ISLAND_PARTY_SAIL_STAGE_BATTLE_VALUE = 2;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static IslandPartySailStage valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static IslandPartySailStage forNumber(int value) {
switch (value) {
case 0: return ISLAND_PARTY_SAIL_STAGE_NONE;
case 1: return ISLAND_PARTY_SAIL_STAGE_SAIL;
case 2: return ISLAND_PARTY_SAIL_STAGE_BATTLE;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<IslandPartySailStage>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
IslandPartySailStage> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<IslandPartySailStage>() {
public IslandPartySailStage findValueByNumber(int number) {
return IslandPartySailStage.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return emu.grasscutter.net.proto.IslandPartySailStageOuterClass.getDescriptor().getEnumTypes().get(0);
}
private static final IslandPartySailStage[] VALUES = values();
public static IslandPartySailStage valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private IslandPartySailStage(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:IslandPartySailStage)
}
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\032IslandPartySailStage.proto*~\n\024IslandPa" +
"rtySailStage\022 \n\034ISLAND_PARTY_SAIL_STAGE_" +
"NONE\020\000\022 \n\034ISLAND_PARTY_SAIL_STAGE_SAIL\020\001" +
"\022\"\n\036ISLAND_PARTY_SAIL_STAGE_BATTLE\020\002B\033\n\031" +
"emu.grasscutter.net.protob\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
});
}
// @@protoc_insertion_point(outer_class_scope)
}
| 412 | 0.863647 | 1 | 0.863647 | game-dev | MEDIA | 0.597972 | game-dev,networking | 0.7735 | 1 | 0.7735 |
Vek17/TabletopTweaks-Core | 1,989 | TabletopTweaks-Core/NewComponents/IgnoreArmorMaxDexBonus.cs | using Kingmaker.Blueprints.Items.Armors;
using Kingmaker.Blueprints.JsonSystem;
using Kingmaker.PubSubSystem;
using Kingmaker.RuleSystem.Rules;
using Kingmaker.UnitLogic;
using Kingmaker.Utility;
using System.Linq;
namespace TabletopTweaks.Core.NewComponents {
[TypeId("0542dd3cbb5949a7b120f2165758db9b")]
public class IgnoreArmorMaxDexBonus : UnitFactComponentDelegate,
IInitiatorRulebookHandler<RuleCalculateArmorMaxDexBonusLimit>,
IRulebookHandler<RuleCalculateArmorMaxDexBonusLimit>,
ISubscriber, IInitiatorRulebookSubscriber {
public override void OnTurnOn() {
base.OnTurnOn();
if (Owner.Body.Armor.HasArmor && Owner.Body.Armor.Armor.Blueprint.IsArmor) {
Owner.Body.Armor.Armor.RecalculateStats();
Owner.Body.Armor.Armor.RecalculateMaxDexBonus();
if (Owner.Body.SecondaryHand.HasShield) {
Owner.Body.SecondaryHand.MaybeShield.ArmorComponent.RecalculateStats();
Owner.Body.SecondaryHand.MaybeShield.ArmorComponent.RecalculateMaxDexBonus();
}
}
}
public void OnEventAboutToTrigger(RuleCalculateArmorMaxDexBonusLimit evt) {
}
public void OnEventDidTrigger(RuleCalculateArmorMaxDexBonusLimit evt) {
if (!CheckCategory) {
evt.Result = null;
return;
}
if (!evt.Armor.Blueprint.IsShield && CheckCategory && (Categorys.Contains(evt.Armor.ArmorType()) || Categorys.Contains(evt.Armor.Blueprint.ProficiencyGroup))) {
evt.Result = null;
return;
}
if (evt.Armor.Blueprint.IsShield && CheckCategory && Categorys.Contains(evt.Armor.Blueprint.ProficiencyGroup)) {
evt.Result = null;
}
}
public bool CheckCategory = true;
[ShowIf("CheckCategory")]
public ArmorProficiencyGroup[] Categorys;
}
}
| 412 | 0.89997 | 1 | 0.89997 | game-dev | MEDIA | 0.984557 | game-dev | 0.882796 | 1 | 0.882796 |
AU-Avengers/TOU-Mira | 12,427 | TownOfUs/Patches/Misc/ChatCommandsPatch.cs | using System.Globalization;
using HarmonyLib;
using MiraAPI.GameOptions;
using Reactor.Networking.Attributes;
using Reactor.Utilities.Extensions;
using TownOfUs.Modules;
using TownOfUs.Options;
using TownOfUs.Patches.Options;
using TownOfUs.Roles.Crewmate;
using TownOfUs.Roles.Neutral;
using TownOfUs.Roles.Other;
using TownOfUs.Utilities;
namespace TownOfUs.Patches.Misc;
[HarmonyPatch(typeof(ChatController), nameof(ChatController.SendChat))]
public static class ChatPatches
{
// ReSharper disable once InconsistentNaming
public static bool Prefix(ChatController __instance)
{
var text = __instance.freeChatField.Text.ToLower(CultureInfo.InvariantCulture);
var textRegular = __instance.freeChatField.Text.WithoutRichText();
if (textRegular.Length < 1 || textRegular.Length > 100)
{
return true;
}
var spaceLess = text.Replace(" ", string.Empty);
if (spaceLess.StartsWith("/spec", StringComparison.OrdinalIgnoreCase))
{
if (!LobbyBehaviour.Instance)
{
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, "<color=#8BFDFD>System</color>", "You cannot select your spectate status outside of the lobby!");
}
else
{
if (SpectatorRole.TrackedSpectators.Contains(PlayerControl.LocalPlayer.Data.PlayerName))
{
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, "<color=#8BFDFD>System</color>", "You are no longer a spectator!");
RpcRemoveSpectator(PlayerControl.LocalPlayer);
}
else
{
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, "<color=#8BFDFD>System</color>", "Set yourself as a spectator!");
RpcSelectSpectator(PlayerControl.LocalPlayer);
}
}
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (spaceLess.StartsWith("/", StringComparison.OrdinalIgnoreCase)
&& spaceLess.Contains("summary", StringComparison.OrdinalIgnoreCase))
{
var title = "<color=#8BFDFD>System</color>";
var msg = "No game summary to show!";
if (GameHistory.EndGameSummary != string.Empty)
{
var factionText = string.Empty;
if (GameHistory.WinningFaction != string.Empty)
{
factionText = $"<size=80%>Winning Team: {GameHistory.WinningFaction}</size>\n";
}
title = $"<color=#8BFDFD>System</color>\n<size=62%>{factionText}{GameHistory.EndGameSummary}</size>";
msg = string.Empty;
}
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, title, msg);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (spaceLess.StartsWith("/nerfme", StringComparison.OrdinalIgnoreCase))
{
var title = "<color=#8BFDFD>System</color>";
var msg = "You cannot Nerf yourself outside of the lobby!";
if (LobbyBehaviour.Instance)
{
VisionPatch.NerfMe = !VisionPatch.NerfMe;
msg = $"Toggled Nerf Status To {VisionPatch.NerfMe}!";
}
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, title, msg);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (spaceLess.StartsWith("/setname", StringComparison.OrdinalIgnoreCase))
{
var title = "<color=#8BFDFD>System</color>";
if (text.StartsWith("/setname ", StringComparison.OrdinalIgnoreCase))
{
textRegular = textRegular[9..];
}
else if (text.StartsWith("/setname", StringComparison.OrdinalIgnoreCase))
{
textRegular = textRegular[8..];
}
else if (text.StartsWith("/ setname ", StringComparison.OrdinalIgnoreCase))
{
textRegular = textRegular[10..];
}
else if (text.StartsWith("/ setname", StringComparison.OrdinalIgnoreCase))
{
textRegular = textRegular[9..];
}
var msg = "You cannot change your name outside of the lobby!";
if (LobbyBehaviour.Instance)
{
if (textRegular.Length < 1 || textRegular.Length > 12)
{
msg =
"The player name must be at least 1 character long, and cannot be more than 12 characters long!";
}
else if (PlayerControl.AllPlayerControls.ToArray().Any(x => x.Data.PlayerName.ToLower(CultureInfo.InvariantCulture).Trim() == textRegular.ToLower(CultureInfo.InvariantCulture).Trim() && x.Data.PlayerId != PlayerControl.LocalPlayer.PlayerId))
{
msg = $"Another player has a name too similar to {textRegular}! Please try a different name.";
}
else
{
PlayerControl.LocalPlayer.CmdCheckName(textRegular);
msg = $"Changed player name for the next match to: {textRegular}";
}
}
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, title, msg);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (spaceLess.StartsWith("/help", StringComparison.OrdinalIgnoreCase))
{
var title = "<color=#8BFDFD>System</color>";
List<string> randomNames =
[
"Atony", "Alchlc", "angxlwtf", "Digi", "Donners", "K3ndo", "DragonBreath", "Pietro", "Nix", "Daemon", "6pak",
"twix", "xerm", "XtraCube", "Zeo", "Slushie", "chloe", "moon", "decii", "Northie", "GD", "Chilled",
"Himi", "Riki", "Leafly", "miniduikboot"
];
var msg = "<size=75%>Chat Commands:\n" +
"/help - Shows this message\n" +
"/nerfme - Cuts your vision in half\n" +
$"/setname - Change your name to whatever text follows the command (like /setname {randomNames.Random()}) for the next match.\n" +
"/spec - Allows you to spectate for the rest of the game automatically.\n" +
"/summary - Shows the previous end game summary\n</size>";
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, title, msg);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (spaceLess.StartsWith("/jail", StringComparison.OrdinalIgnoreCase))
{
var title = "<color=#8BFDFD>System</color>";
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, title,
"The mod no longer supports /jail chat. Use the red in-game chat button instead.");
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (spaceLess.StartsWith("/", StringComparison.OrdinalIgnoreCase))
{
var title = "<color=#8BFDFD>System</color>";
MiscUtils.AddFakeChat(PlayerControl.LocalPlayer.Data, title,
"Invalid command. If you need information on chat commands, type /help. If you are trying to know what a role or modifier does, check out the in-game wiki by pressing the globe icon on the top right of your screen.");
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (TeamChatPatches.TeamChatActive && !PlayerControl.LocalPlayer.HasDied() &&
(PlayerControl.LocalPlayer.Data.Role is JailorRole || PlayerControl.LocalPlayer.IsJailed() ||
PlayerControl.LocalPlayer.Data.Role is VampireRole || PlayerControl.LocalPlayer.IsImpostor()))
{
var genOpt = OptionGroupSingleton<GeneralOptions>.Instance;
if (PlayerControl.LocalPlayer.Data.Role is JailorRole)
{
TeamChatPatches.RpcSendJailorChat(PlayerControl.LocalPlayer, textRegular);
MiscUtils.AddTeamChat(PlayerControl.LocalPlayer.Data,
$"<color=#{TownOfUsColors.Jailor.ToHtmlStringRGBA()}>{PlayerControl.LocalPlayer.Data.PlayerName} (Jailor)</color>",
textRegular, onLeft: false);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (PlayerControl.LocalPlayer.IsJailed())
{
TeamChatPatches.RpcSendJaileeChat(PlayerControl.LocalPlayer, textRegular);
MiscUtils.AddTeamChat(PlayerControl.LocalPlayer.Data,
$"<color=#{TownOfUsColors.Jailor.ToHtmlStringRGBA()}>{PlayerControl.LocalPlayer.Data.PlayerName} (Jailed)</color>",
textRegular, onLeft: false);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (PlayerControl.LocalPlayer.Data.Role is VampireRole && genOpt.VampireChat)
{
TeamChatPatches.RpcSendVampTeamChat(PlayerControl.LocalPlayer, textRegular);
MiscUtils.AddTeamChat(PlayerControl.LocalPlayer.Data,
$"<color=#{TownOfUsColors.Vampire.ToHtmlStringRGBA()}>{PlayerControl.LocalPlayer.Data.PlayerName} (Vampire Chat)</color>",
textRegular, onLeft: false);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
if (PlayerControl.LocalPlayer.IsImpostor() &&
genOpt is { FFAImpostorMode: false, ImpostorChat.Value: true })
{
TeamChatPatches.RpcSendImpTeamChat(PlayerControl.LocalPlayer, textRegular);
MiscUtils.AddTeamChat(PlayerControl.LocalPlayer.Data,
$"<color=#{TownOfUsColors.ImpSoft.ToHtmlStringRGBA()}>{PlayerControl.LocalPlayer.Data.PlayerName} (Impostor Chat)</color>",
textRegular, onLeft: false);
__instance.freeChatField.Clear();
__instance.quickChatMenu.Clear();
__instance.quickChatField.Clear();
__instance.UpdateChatMode();
return false;
}
return true;
}
return true;
}
[MethodRpc((uint)TownOfUsRpc.SelectSpectator, SendImmediately = true)]
public static void RpcSelectSpectator(PlayerControl player)
{
if (!SpectatorRole.TrackedSpectators.Contains(player.Data.PlayerName))
{
SpectatorRole.TrackedSpectators.Add(player.Data.PlayerName);
}
}
[MethodRpc((uint)TownOfUsRpc.RemoveSpectator, SendImmediately = true)]
public static void RpcRemoveSpectator(PlayerControl player)
{
if (SpectatorRole.TrackedSpectators.Contains(player.Data.PlayerName))
{
SpectatorRole.TrackedSpectators.Remove(player.Data.PlayerName);
}
}
} | 412 | 0.922399 | 1 | 0.922399 | game-dev | MEDIA | 0.957867 | game-dev | 0.971183 | 1 | 0.971183 |
OpenACCUserGroup/openacc-users-group | 2,142 | Contributed_Sample_Codes/NAS_SHOC_OpenACC_2.5/NPB-CUDA/SP/timers.cpp | #include <stdio.h>
#include <sys/time.h>
#include "main.h"
char *Timers::t_names[t_last];
void Timers::init_timer() {
t_names[t_total] = "total";
t_names[t_rhsx] = "rhsx";
t_names[t_rhsy] = "rhsy";
t_names[t_rhsz] = "rhsz";
t_names[t_rhs] = "rhs";
t_names[t_xsolve] = "xsolve";
t_names[t_ysolve] = "ysolve";
t_names[t_zsolve] = "zsolve";
t_names[t_rdis1] = "redist1";
t_names[t_rdis2] = "redist2";
t_names[t_tzetar] = "tzetar";
t_names[t_ninvr] = "ninvr";
t_names[t_pinvr] = "pinvr";
t_names[t_txinvr] = "txinvr";
t_names[t_add] = "add";
}
Timers::Timers() {
elapsed = new double [t_last];
start = new double [t_last];
}
Timers::~Timers() {
delete[] elapsed;
delete[] start;
}
void Timers::timer_clear(int n) {
elapsed[n] = 0.0;
}
void Timers::timer_clear_all() {
for (int i = 0; i < t_last; i++) elapsed[i] = 0.0;
}
void Timers::timer_start(int n) {
start[n] = elapsed_time();
}
void Timers::timer_stop (int n) {
elapsed[n] += elapsed_time() - start[n];
}
double Timers::timer_read(int n) {
return elapsed[n];
}
double Timers::elapsed_time() {
// a generic timer
static int sec = -1;
struct timeval tv;
gettimeofday(&tv, 0L);
if (sec < 0) sec = tv.tv_sec;
return (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec;
}
void Timers::timer_print() {
double trecs[t_last], tmax;
for (int i = 0; i < t_last; i++) trecs[i] = timer_read(i);
tmax = trecs[0] == 0.0 ? 1.0 : trecs[0];
printf(" SECTION Time (secs)\n");
for (int i = 0; i < t_last; i++) {
printf(" %8s:%9.3f (%6.2f\%)\n", t_names[i], trecs[i], trecs[i]*100./tmax);
if (i == t_rhs) {
double t = trecs[t_rhsx] + trecs[t_rhsy] + trecs[t_rhsz];
printf(" --> %8s:%9.3f (%6.2f\%)\n", "sub-rhs", t, t*100.0/tmax);
t = trecs[i] - t;
printf(" --> %8s:%9.3f (%6.2f\%)\n", "rest-rhs", t, t*100.0/tmax);
} else if (i == t_zsolve) {
double t = trecs[t_zsolve] - trecs[t_rdis1] - trecs[t_rdis2];
printf(" --> %8s:%9.3f (%6.2f\%)\n", "sub-zsol", t, t*100.0/tmax);
} else if (i == t_rdis2) {
double t = trecs[t_rdis1] + trecs[t_rdis2];
printf(" --> %8s:%9.3f (%6.2f\%)\n", "redist", t, t*100.0/tmax);
}
}
}
| 412 | 0.565416 | 1 | 0.565416 | game-dev | MEDIA | 0.330689 | game-dev | 0.87215 | 1 | 0.87215 |
blurite/rsprot | 1,293 | protocol/osrs-228/osrs-228-model/src/main/kotlin/net/rsprot/protocol/game/outgoing/inv/UpdateInvStopTransmit.kt | package net.rsprot.protocol.game.outgoing.inv
import net.rsprot.protocol.ServerProtCategory
import net.rsprot.protocol.game.outgoing.GameServerProtCategory
import net.rsprot.protocol.message.OutgoingGameMessage
/**
* Update inv stop transmit is used by the server to inform the client
* that no more updates for a given inventory are expected.
* In OldSchool RuneScape, this is sent whenever an interface that's
* linked to the inventory is sent.
* In doing so, the client will wipe its cache of the given inventory.
* There is no technical reason to send this, however, as it doesn't
* prevent anything from functioning as normal.
* @property inventoryId the id of the inventory to stop listening to
*/
public class UpdateInvStopTransmit(
public val inventoryId: Int,
) : OutgoingGameMessage {
override val category: ServerProtCategory
get() = GameServerProtCategory.HIGH_PRIORITY_PROT
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as UpdateInvStopTransmit
return inventoryId == other.inventoryId
}
override fun hashCode(): Int = inventoryId
override fun toString(): String = "UpdateInvStopTransmit(inventoryId=$inventoryId)"
}
| 412 | 0.903941 | 1 | 0.903941 | game-dev | MEDIA | 0.610696 | game-dev | 0.81189 | 1 | 0.81189 |
StrongPC123/Far-Cry-1-Source-Full | 22,623 | FARCRY/Main.cpp | //////////////////////////////////////////////////////////////////////
//
// Game Source Code
//
// File: Main.cpp
// Description: Game Entry point
//
// History:
// - August 27, 2001: Created by Alberto Demichelis
// - October 2, 2002: Modified by Timur Davidenko.
//
//////////////////////////////////////////////////////////////////////
#ifdef WIN32
#include <windows.h>
#include <process.h>
#endif
//#define FARCRY_CD_CHECK_RUSSIAN
#define FARCRY_CD_LABEL _T("FARCRY_1")
//////////////////////////////////////////////////////////////////////////
// Timur.
// This is FarCry.exe authentication function, this code is not for public release!!
//////////////////////////////////////////////////////////////////////////
void AuthCheckFunction( void *data )
{
// src and trg can be the same pointer (in place encryption)
// len must be in bytes and must be multiple of 8 byts (64bits).
// key is 128bit: int key[4] = {n1,n2,n3,n4};
// void encipher(unsigned int *const v,unsigned int *const w,const unsigned int *const k )
#define TEA_ENCODE( src,trg,len,key ) {\
register unsigned int *v = (src), *w = (trg), *k = (key), nlen = (len) >> 3; \
register unsigned int delta=0x9E3779B9,a=k[0],b=k[1],c=k[2],d=k[3]; \
while (nlen--) {\
register unsigned int y=v[0],z=v[1],n=32,sum=0; \
while(n-->0) { sum += delta; y += (z << 4)+a ^ z+sum ^ (z >> 5)+b; z += (y << 4)+c ^ y+sum ^ (y >> 5)+d; } \
w[0]=y; w[1]=z; v+=2,w+=2; }}
// src and trg can be the same pointer (in place decryption)
// len must be in bytes and must be multiple of 8 byts (64bits).
// key is 128bit: int key[4] = {n1,n2,n3,n4};
// void decipher(unsigned int *const v,unsigned int *const w,const unsigned int *const k)
#define TEA_DECODE( src,trg,len,key ) {\
register unsigned int *v = (src), *w = (trg), *k = (key), nlen = (len) >> 3; \
register unsigned int delta=0x9E3779B9,a=k[0],b=k[1],c=k[2],d=k[3]; \
while (nlen--) { \
register unsigned int y=v[0],z=v[1],sum=0xC6EF3720,n=32; \
while(n-->0) { z -= (y << 4)+c ^ y+sum ^ (y >> 5)+d; y -= (z << 4)+a ^ z+sum ^ (z >> 5)+b; sum -= delta; } \
w[0]=y; w[1]=z; v+=2,w+=2; }}
// Data assumed to be 32 bytes.
int key1[4] = {1873613783,235688123,812763783,1745863682};
TEA_DECODE( (unsigned int*)data,(unsigned int*)data,32,(unsigned int*)key1 );
int key2[4] = {1897178562,734896899,156436554,902793442};
TEA_ENCODE( (unsigned int*)data,(unsigned int*)data,32,(unsigned int*)key2 );
}
#define NOT_USE_CRY_MEMORY_MANAGER
#include <platform.h>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string>
#include <algorithm>
/////////////////////////////////////////////////////////////////////////////
// CRY Stuff ////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#include "Cry_Math.h"
#include <Cry_Camera.h>
#include <IRenderer.h>
#include <ILog.h>
#include <ISystem.h>
#include <IGame.h>
#include <IConsole.h>
#include <IInput.h>
#include <IStreamEngine.h>
#include "resource.h" // IDI_ICON
// _WAT_comments
//#ifdef USE_MEM_POOL
//_DECLARE_POOL("FarCry",1000*1024);
//#endif
//
static ISystem *g_pISystem=NULL;
static bool g_bSystemRelaunch = false;
static char szMasterCDFolder[_MAX_PATH];
#ifdef WIN32
static HMODULE g_hSystemHandle=NULL;
#define DLL_SYSTEM "CrySystem.dll"
#define DLL_GAME "CryGame.dll"
#endif
#ifndef PS2
#if !defined(PS2)
bool RunGame(HINSTANCE hInstance,const char *sCmdLine);
#else
bool RunGame(HINSTANCE hInstance);
#endif
#ifdef _XBOX
void main()
{
RunGame(NULL,"");
}
#ifndef _DEBUG
int _strcmpi( const char *string1, const char *string2 )
{
return _stricmp( string1, string2 );
}
int system( const char *command )
{
return 0;
}
char * getenv( const char *varname )
{
return 0;
}
#endif //_DEBUG
#endif // _XBOX
//FNC_CryFree _CryFree = NULL;
#ifndef _XBOX
void SetMasterCDFolder()
{
char szExeFileName[_MAX_PATH];
// Get the path of the executable
GetModuleFileName( GetModuleHandle(NULL), szExeFileName, sizeof(szExeFileName));
char path_buffer[_MAX_PATH];
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_splitpath( szExeFileName, drive, dir, fname, ext );
_makepath( path_buffer, drive,dir,NULL,NULL );
strcat( path_buffer,".." );
SetCurrentDirectory( path_buffer );
GetCurrentDirectory( sizeof(szMasterCDFolder),szMasterCDFolder );
}
#ifdef FARCRY_CD_CHECK_RUSSIAN
#include <winioctl.h>
#include <tchar.h>
typedef std::basic_string< TCHAR > tstring;
typedef std::vector< TCHAR > tvector;
void CheckFarCryCD( HINSTANCE hInstance )
{
bool bRet( false );
DWORD nBufferSize( GetLogicalDriveStrings( 0, 0 ) );
if( 0 < nBufferSize )
{
// get list of all available logical drives
tvector rawDriveLetters( nBufferSize + 1 );
GetLogicalDriveStrings( nBufferSize, &rawDriveLetters[ 0 ] );
// quickly scan all drives
tvector::size_type i( 0 );
while( true )
{
// check if current drive is cd/dvd drive
if( DRIVE_CDROM == GetDriveType( &rawDriveLetters[ i ] ) )
{
// get volume name
tvector cdVolumeName( MAX_VOLUME_ID_SIZE + 1 );
if( FALSE != GetVolumeInformation( &rawDriveLetters[ i ],
&cdVolumeName[ 0 ], (DWORD) cdVolumeName.size(), 0, 0, 0, 0, 0 ) )
{
// check volume name to verify it's Far Cry's game cd/dvd
tstring cdVolumeLabel( &cdVolumeName[ 0 ] );
if( cdVolumeLabel == FARCRY_CD_LABEL)
{
// found Far Cry's game cd/dvd, copy information and bail out
//szCDPath = &rawDriveLetters[ i ];
return;
}
}
}
// proceed to next drive
while( 0 != rawDriveLetters[ i ] )
{
++i;
}
++i; // skip null termination of current drive
// check if we're out of drive letters
if( 0 == rawDriveLetters[ i ] )
{
// double null termination found, bail out
break;
}
}
}
// Not CD/DVD with FARCRY_1 label found. Give to user warning message and bail out.
char str[1024];
LoadString( hInstance,IDS_NOCD,str,sizeof(str) );
MessageBox( NULL,str,_T("CD Check Error"),MB_OK|MB_ICONERROR );
exit(1);
}
#else
void CheckFarCryCD( HINSTANCE hInstance ) {};
#endif // FARCRY_CD_CHECK_RUSSIAN
///////////////////////////////////////////////
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
#ifdef _DEBUG
int tmpDbgFlag;
tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
// Check heap every
//_CrtSetBreakAlloc(119065);
#endif
// [marco] If a previous instance is running, activate
// the old one and terminate the new one, depending
// on command line devmode status
HWND hwndPrev;
static char szWndClass[] = "CryENGINE";
bool bDevMode=false;
bool bRelaunching=false;
if (lpCmdLine)
{
if (strstr(lpCmdLine,"-DEVMODE"))
bDevMode=true;
if (strstr(lpCmdLine,"-RELAUNCHING"))
bRelaunching=true;
}
// in devmode we don't care, we allow to run multiple instances
// for mp debugging
if (!bDevMode)
{
hwndPrev = FindWindow (szWndClass, NULL);
// not in devmode and we found another window - see if the
// system is relaunching, in this case is fine 'cos the application
// will be closed immediately after
if (hwndPrev && !bRelaunching)
{
SetForegroundWindow (hwndPrev);
return (-1);
}
}
CheckFarCryCD(hInstance);
SetMasterCDFolder();
#if !defined(PS2)
RunGame(hInstance,lpCmdLine);
#else
RunGame(hInstance);
#endif
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// Window procedure
RECT rect;
switch (msg)
{
case WM_MOVE:
{
// TODO
break;
}
case WM_DISPLAYCHANGE:
{
// TODO
break;
}
case WM_SIZE:
{
// Check to see if we are losing our window
if ((wParam == SIZE_MAXHIDE) || (wParam == SIZE_MINIMIZED))
{
// TODO
break;
}
GetClientRect(hWnd, &rect);
if (g_pISystem && !g_bSystemRelaunch)
g_pISystem->GetIRenderer()->ChangeViewport(0, 0, LOWORD(lParam), HIWORD(lParam));
break;
}
case WM_ACTIVATEAPP:
{
if (!wParam)
{
if (g_pISystem && g_pISystem->GetIInput())
{
g_pISystem->GetIInput()->ClearKeyState();
g_pISystem->GetIInput()->SetMouseExclusive(false);
g_pISystem->GetIInput()->SetKeyboardExclusive(false);
}
}
else
{
if (g_pISystem && g_pISystem->GetIInput())
{
g_pISystem->GetIInput()->ClearKeyState();
g_pISystem->GetIInput()->SetMouseExclusive(true);
g_pISystem->GetIInput()->SetKeyboardExclusive(true);
}
}
break;
}
case WM_MOUSEACTIVATE:
{
return MA_ACTIVATEANDEAT;
}
case WM_ACTIVATE:
{
if (wParam == WA_INACTIVE)
{
if (g_pISystem && g_pISystem->GetIInput())
{
g_pISystem->GetIInput()->ClearKeyState();
g_pISystem->GetIInput()->SetMouseExclusive(false);
g_pISystem->GetIInput()->SetKeyboardExclusive(false);
}
}
else if ((wParam == WA_ACTIVE) ||(wParam == WA_CLICKACTIVE))
{
if (g_pISystem && g_pISystem->GetIInput())
{
g_pISystem->GetIInput()->SetMouseExclusive(true);
g_pISystem->GetIInput()->SetKeyboardExclusive(true);
}
}
break;
}
case WM_ENTERSIZEMOVE:
case WM_ENTERMENULOOP:
{
return 0;
}
case WM_SETFOCUS:
{
if (g_pISystem && g_pISystem->GetIInput())
{
g_pISystem->GetIInput()->ClearKeyState();
g_pISystem->GetIInput()->SetMouseExclusive(true);
g_pISystem->GetIInput()->SetKeyboardExclusive(true);
}
break;
}
case WM_KILLFOCUS:
{
if (g_pISystem && g_pISystem->GetIInput())
{
g_pISystem->GetIInput()->ClearKeyState();
g_pISystem->GetIInput()->SetMouseExclusive(false);
g_pISystem->GetIInput()->SetKeyboardExclusive(false);
}
break;
}
case WM_DESTROY:
{
// TODO
break;
}
case WM_HOTKEY:
return 0;
break;
case WM_SYSKEYDOWN:
{
if (g_pISystem && g_pISystem->GetIInput())
g_pISystem->GetIInput()->FeedVirtualKey(wParam,lParam,true);
break;
}
case WM_SYSKEYUP:
{
if (g_pISystem && g_pISystem->GetIInput())
g_pISystem->GetIInput()->FeedVirtualKey(wParam,lParam,false);
break;
}
case WM_KEYDOWN:
if (g_pISystem && g_pISystem->GetIInput())
g_pISystem->GetIInput()->FeedVirtualKey(wParam,lParam,true);
break;
case WM_KEYUP:
if (g_pISystem && g_pISystem->GetIInput())
g_pISystem->GetIInput()->FeedVirtualKey(wParam,lParam,false);
break;
case WM_CHAR:
{
break;
}
case 0x020A: // WM_MOUSEWHEEL
g_pISystem->GetIInput()->GetIMouse()->SetMouseWheelRotation((short) HIWORD(wParam));
break;
case WM_QUIT:
{
/*m_pGame->Release();
m_pGame = NULL;
*/
/*
if (g_pISystem)
{
g_pISystem->Quit();
}
*/
break;
}
case WM_CLOSE:
{
if (g_pISystem)
{
g_pISystem->Quit();
}
break;
}
}
return (DefWindowProc(hWnd, msg, wParam, lParam));
}
bool RegisterWindow(HINSTANCE hInst)
{
// Register a window class
WNDCLASS wc;
wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 4;
wc.cbWndExtra = 4;
wc.hInstance = hInst;
wc.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_ICON));
wc.hCursor = NULL;
wc.hbrBackground =(HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = "CryENGINE";
if (!RegisterClass(&wc))
return false;
else
return true;
}
#endif
#else //PS2
bool RunGamePS2(IGame *hInstance)
{
SSystemInitParams sip;
sip.sLogFileName = "log.txt";
g_pISystem = CreateSystemInterface( sip );
if (!g_pISystem)
{
//Error( "CreateSystemInterface Failed" );
return false;
}
// Enable Log verbosity.
g_pISystem->GetILog()->EnableVerbosity(true);
/////////////////////////////////////////////////////////////////////
// INITIAL CONSOLE STATUS IS ACTIVE
/////////////////////////////////////////////////////////////////////
g_pISystem->GetIConsole()->ShowConsole(true);
//////////////////////////////////////////////////////////////////////////////////////////////////////////
SGameInitParams gip;
if (!g_pISystem->CreateGame( gip ))
{
//Error( "CreateGame Failed" );
return false;
}
IGame *pGame = g_pISystem->GetIGame();
pGame->Run(bRelaunch);
// Release System and Game.
g_pISystem->Release();
g_pISystem = NULL;
return true;
}
#endif //PS2
// returns the decimal string representation of the given int
string IntToString (int nNumber)
{
char szNumber[16];
// itoa (nNumber, szNumber, 10);
sprintf (szNumber, "%d", nNumber);
return szNumber;
}
// returns hexadecimal string representation of the given dword
string UIntToHexString(DWORD dwNumber)
{
char szNumber[24];
sprintf (szNumber, "0x%X", dwNumber);
return szNumber;
}
string TryFormatWinError(DWORD dwError)
{
#ifdef WIN32
LPVOID lpMsgBuf; // pointer to the buffer that will accept the formatted message
//DWORD dwLastError = OsGetLastError(); // the last user error for which the description should be formatted
DWORD dwFormattedMsgLen = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL );
if (!dwFormattedMsgLen)
// error. return both the user error and the error received during formatting the user error
return string();
else
{// the lpMsgBuf contains allocated by the system call message that is to be returned.
// we'll copy it into sResult and free it and return sResult
string sResult = (LPCTSTR) lpMsgBuf;
LocalFree (lpMsgBuf);
while (!sResult.empty() && ((unsigned char)sResult[sResult.length()-1]) < 0x20)
sResult.resize(sResult.length()-1);
return sResult;
}
#else
return "Unknown error";
#endif
}
// returns the string representation (in natural language) of the last error retrieved by GetLastError()
string FormatWinError(DWORD dwError)
{
string sResult = TryFormatWinError(dwError);
if (sResult.empty())
// error. return both the user error and the error received during formatting the user error
sResult = "Error " + IntToString (GetLastError()) + " while formatting error message";
return sResult + "\n(" + (dwError & 0x80000000 ? UIntToHexString(dwError):IntToString(dwError)) + ")";
}
#define MAX_CMDLINE_LEN 256
#include <crtdbg.h>
///////////////////////////////////////////////
// Load the game DLL and run it
static void
InvokeExternalConfigTool()
{
#if defined(WIN32) || defined(WIN64)
try
{
// build tmp working directory
char tmpWorkingDir[ MAX_PATH ];
GetModuleFileName( 0, tmpWorkingDir, MAX_PATH );
strlwr( tmpWorkingDir );
// look for \bin as it should work for either \bin32 and \bin64
char* pBin( strstr( tmpWorkingDir, "\\bin" ) );
if( 0 != pBin )
{
// trunc tmp working directory path to X:\...\MasterCD
*pBin = 0;
// save current working directory
char curWorkingDir[ MAX_PATH ];
GetCurrentDirectory( MAX_PATH, curWorkingDir );
// set temporary working directory and launch external config tool
SetCurrentDirectory( tmpWorkingDir );
_spawnl( _P_WAIT, "Bin32\\FarCryConfigurator.exe", "Bin32\\FarCryConfigurator.exe", "/Caller=FarCry", 0 );
// restore current working directory
SetCurrentDirectory( curWorkingDir );
}
}
catch( ... )
{
}
#endif
}
//////////////////////////////////////////////////////////////////////////
//#define GERMAN_GORE_CHECK
#ifdef GERMAN_GORE_CHECK
#include "IEntitySystem.h"
#endif
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
bool RunGame(HINSTANCE hInstance,const char *sCmdLine)
{
InvokeExternalConfigTool();
HWND hWnd=NULL;
// initialize the system
bool bRelaunch=false;
char szLocalCmdLine[MAX_CMDLINE_LEN];
memset(szLocalCmdLine,0,MAX_CMDLINE_LEN);
if (sCmdLine)
strncpy(szLocalCmdLine,sCmdLine,MAX_CMDLINE_LEN);
do {
//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF);
SSystemInitParams sip;
sip.sLogFileName = "log.txt";
if (szLocalCmdLine[0])
{
int nLen=(int)strlen(szLocalCmdLine);
if (nLen>MAX_CMDLINE_LEN)
nLen=MAX_CMDLINE_LEN;
strncpy(sip.szSystemCmdLine,szLocalCmdLine,nLen);
}
#ifndef _XBOX
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
if (!hWnd && !RegisterWindow(hInstance))
{
if (!hWnd && RegisterWindow(hInstance))
{
MessageBox(0, "Cannot Register Window\n", "Error", MB_OK | MB_DEFAULT_DESKTOP_ONLY);
return false;
}
}
g_hSystemHandle = LoadLibrary(DLL_SYSTEM);
if (!g_hSystemHandle)
{
DWORD dwLastError = GetLastError();
MessageBox( NULL,("CrySystem.dll Loading Failed:\n" + TryFormatWinError(dwLastError)).c_str(),"FarCry Error",MB_OK|MB_ICONERROR );
return false;
}
PFNCREATESYSTEMINTERFACE pfnCreateSystemInterface =
(PFNCREATESYSTEMINTERFACE)::GetProcAddress( g_hSystemHandle,"CreateSystemInterface" );
// Initialize with instance and window handles.
sip.hInstance = hInstance;
sip.hWnd = hWnd;
sip.pSystem = g_pISystem;
sip.pCheckFunc = AuthCheckFunction;
// initialize the system
g_pISystem = pfnCreateSystemInterface( sip );
if (!g_pISystem)
{
MessageBox( NULL,"CreateSystemInterface Failed","FarCry Error",MB_OK|MB_ICONERROR );
return false;
}
#else
// initialize the system
g_pISystem = CreateSystemInterface( sip );
#endif
//////////////////////////////////////////////////////////////////////////
#ifdef GERMAN_GORE_CHECK
string sVar=string("g")+"_"+"g"+"o"+"r"+"e";
ICVar *pGore=g_pISystem->GetIConsole()->CreateVariable(sVar.c_str(),"1",VF_DUMPTODISK|VF_READONLY);
pGore->ForceSet("1");
#endif
//////////////////////////////////////////////////////////////////////////
// Enable Log verbosity.
g_pISystem->GetILog()->EnableVerbosity(true);
{
AutoSuspendTimeQuota suspender (g_pISystem->GetStreamEngine());
/////////////////////////////////////////////////////////////////////
// INITIAL CONSOLE STATUS IS INACTIVE
/////////////////////////////////////////////////////////////////////
g_pISystem->GetIConsole()->ShowConsole(false);
g_pISystem->GetIConsole()->SetScrollMax(600/2);
#ifdef WIN32
SGameInitParams ip;
ip.sGameDLL = DLL_GAME;
if (szLocalCmdLine[0])
strncpy(ip.szGameCmdLine,szLocalCmdLine,sizeof(ip.szGameCmdLine));
#ifdef GORE_CHECK
ICVar *pGore=g_pISystem->GetIConsole()->CreateVariable("g_gore","1",VF_DUMPTODISK|VF_READONLY);
pGore->ForceSet("1");
#endif
if (!g_pISystem->CreateGame( ip ))
{
MessageBox( NULL,"CreateGame Failed: CryGame.dll","FarCry Error",MB_OK|MB_ICONERROR );
return false;
}
#else
SGameInitParams ip;
if (!g_pISystem->CreateGame( ip ))
{
//Error( "CreateGame Failed" );
return false;
}
#endif
// g_pISystem->GetIConsole()->ExecuteString(sCmdLine);
}
g_bSystemRelaunch = false;
// set the controls to exclusive mode
g_pISystem->GetIInput()->ClearKeyState();
g_pISystem->GetIInput()->SetMouseExclusive(true);
g_pISystem->GetIInput()->SetKeyboardExclusive(true);
IGame *pGame = g_pISystem->GetIGame();
//////////////////////////////////////////////////////////////////////////
#ifdef GERMAN_GORE_CHECK
string sDLL=string("C")+"r"+"y"+"E"+"n"+"t"+"i"+"t"+"y"+"S"+"y"+"s"+"t"+"e"+"m"+"."+"d"+"l"+"l";
HMODULE tDLL= ::LoadLibrary(sDLL.c_str());
if (!tDLL)
{
return false;
g_pISystem->Release();
g_pISystem->Release();
g_pISystem++;
}
PFNCREATEMAINENTITYSYSTEM pfnCreateEntitySystem;
string sFunc=string("C")+"r"+"e"+"a"+"t"+"e"+"M"+"a"+"i"+"n"+"E"+"n"+"t"+"i"+"t"+"y"+"S"+"y"+"s"+"t"+"e"+"m";
pfnCreateEntitySystem = (PFNCREATEMAINENTITYSYSTEM) ::GetProcAddress( tDLL, sFunc.c_str());
if (!pfnCreateEntitySystem)
{
return false;
g_pISystem->Release();
g_pISystem->Release();
g_pISystem++;
}
::FreeLibrary(tDLL);
#endif
//////////////////////////////////////////////////////////////////////////
pGame->Run(bRelaunch);
// remove the previous cmdline in case we relaunch
memset(szLocalCmdLine,0,MAX_CMDLINE_LEN);
if (g_pISystem)
{
const char *szMod=NULL;
IGameMods *pMods=pGame->GetModsInterface();
if (pMods)
szMod=pMods->GetCurrentMod();
if (szMod!=NULL && (strlen(szMod)>0))
{
// the game is relaunching because the MOD changed -
// add it as system paramter for the next relaunch
//strncpy(szLocalCmdLine,szMod,MAX_CMDLINE_LEN);
sprintf(szLocalCmdLine,"-MOD:%s",szMod);
}
hWnd = (HWND)g_pISystem->GetIRenderer()->GetHWND();
g_pISystem->Relaunch(bRelaunch);
g_bSystemRelaunch = true;
if (!bRelaunch)
SAFE_RELEASE(g_pISystem);
}
#ifdef WIN32
/*
// Call to free all allocated memory.
if (g_bSystemRelaunch)
{
typedef void* (*PFN_CRYFREEMEMORYPOOLS)();
PFN_CRYFREEMEMORYPOOLS pfnCryFreeMemoryPools = (PFN_CRYFREEMEMORYPOOLS)::GetProcAddress( g_hSystemHandle,"CryFreeMemoryPools" );
if (pfnCryFreeMemoryPools)
pfnCryFreeMemoryPools();
}
*/
if (!bRelaunch)
::FreeLibrary(g_hSystemHandle);
g_hSystemHandle= NULL;
if (hWnd)
{
::DestroyWindow((HWND)hWnd);
hWnd = NULL;
}
#endif;
} while(false);
if (bRelaunch)
{
#ifdef WIN32
// Start a new FarCry process, before exiting this one.
// use the new command line when restarting
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset( &pi,0,sizeof(pi) );
memset( &si,0,sizeof(si) );
si.cb = sizeof(si);
char szExe[_MAX_PATH];
GetModuleFileName( NULL,szExe,sizeof(szExe) );
// [marco] must alloc a new one 'cos could be modified
// by CreateProcess
char *szBuf=NULL;
if (szLocalCmdLine[0])
{
szBuf = new char[strlen(szLocalCmdLine) + strlen(szExe) + strlen("-RELAUNCHING") + 4];
sprintf(szBuf,"%s %s -RELAUNCHING",szExe,szLocalCmdLine);
}
else
{
szBuf = new char[strlen(szExe) + strlen("-RELAUNCHING") + 4];
sprintf(szBuf,"%s -RELAUNCHING",szExe);
}
CreateProcess(0,szBuf,NULL,NULL,FALSE,NULL,NULL,szMasterCDFolder,&si,&pi );
// Now terminate this process as fast as possible.
ExitProcess( 0 );
#endif WIN32
}
return true;
} | 412 | 0.978764 | 1 | 0.978764 | game-dev | MEDIA | 0.748272 | game-dev | 0.989337 | 1 | 0.989337 |
Chuyu-Team/VC-LTL | 1,034 | src/14.15.26726/vcruntime/delete_scalar_size.cpp | //
// delete_scalar_size.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Defines the scalar operator delete, size_t overload.
//
#include <vcruntime_internal.h>
#include <vcruntime_new.h>
////////////////////////////////////////////////////////////////
// delete() Fallback Ordering
//
// +-------------+
// |delete_scalar<----+-----------------------+
// +--^----------+ | |
// | | |
// +--+---------+ +--+---------------+ +----+----------------+
// |delete_array| |delete_scalar_size| |delete_scalar_nothrow|
// +--^----^----+ +------------------+ +---------------------+
// | |
// | +-------------------+
// | |
// +--+--------------+ +------+-------------+
// |delete_array_size| |delete_array_nothrow|
// +-----------------+ +--------------------+
_CRT_SECURITYCRITICAL_ATTRIBUTE
void __CRTDECL operator delete(void* const block, size_t const) noexcept
{
operator delete(block);
}
| 412 | 0.930561 | 1 | 0.930561 | game-dev | MEDIA | 0.380432 | game-dev | 0.82369 | 1 | 0.82369 |
slicol/Snaker | 7,441 | Assets/SGF/Unity/DelayInvoker.cs | ////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 无BUG 不修改 //
////////////////////////////////////////////////////////////////////
/*
* 描述:
* 作者:slicol
*/
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.Collections;
namespace SGF.Unity
{
public delegate void DelayFunction(object[] args);
public class DelayInvoker : MonoSingleton<DelayInvoker>
{
private List<DelayHelper> m_lstHelper;
private List<DelayHelper> m_lstUnscaledHelper;
private static WaitForEndOfFrame ms_waitForEndOfFrame = new WaitForEndOfFrame();
class DelayHelper
{
public object group;
public float delay;
public DelayFunction func;
public object[] args;
public void Invoke()
{
if (func != null)
{
try
{
func(args);
}
catch(Exception e)
{
Debuger.LogError("DelayInvoker", "Invoke() Error:{0}\n{1}", e.Message, e.StackTrace);
}
}
}
}
public static void DelayInvoke(object group, float delay, DelayFunction func, params object[] args)
{
DelayInvoker.Instance.DelayInvokeWorker(group, delay, func, args);
}
public static void DelayInvoke(float delay, DelayFunction func, params object[] args)
{
DelayInvoker.Instance.DelayInvokeWorker(null, delay, func, args);
}
public static void UnscaledDelayInvoke(float delay, DelayFunction func, params object[] args)
{
DelayInvoker.Instance.UnscaledDelayInvokeWorker(null, delay, func, args);
}
public static void CancelInvoke(object group)
{
DelayInvoker.Instance.CancelInvokeWorker(group);
}
//====================================================================
private void DelayInvokeWorker(object group, float delay, DelayFunction func, params object[] args)
{
if (m_lstHelper == null)
{
m_lstHelper = new List<DelayHelper>();
}
DelayHelper helper = new DelayHelper();
helper.group = group;
helper.delay = delay;
helper.func += func;
helper.args = args;
m_lstHelper.Add(helper);
}
private void UnscaledDelayInvokeWorker(object group, float delay, DelayFunction func, params object[] args)
{
if (m_lstUnscaledHelper == null)
{
m_lstUnscaledHelper = new List<DelayHelper>();
}
DelayHelper helper = new DelayHelper();
helper.group = group;
helper.delay = delay;
helper.func += func;
helper.args = args;
m_lstUnscaledHelper.Add(helper);
}
private void CancelInvokeWorker(object group)
{
if (null != m_lstHelper)
{
if (group == null)
{
for (int i = 0; i < m_lstHelper.Count; i++)
{
m_lstHelper[i] = null;
}
m_lstHelper.Clear();
return;
}
for (int i = 0; i < m_lstHelper.Count(); ++i)
{
DelayHelper helper = m_lstHelper[i];
if (helper.group == group)
{
m_lstHelper.RemoveAt(i);
i--;
}
}
}
}
//====================================================================
void Update()
{
if (null != m_lstHelper)
{
for (int i = 0; i < m_lstHelper.Count(); ++i)
{
DelayHelper helper = m_lstHelper[i];
helper.delay -= UnityEngine.Time.deltaTime;
if (helper.delay <= 0)
{
m_lstHelper.RemoveAt(i);
i--;
helper.Invoke();
}
}
}
if (null != m_lstUnscaledHelper)
{
for (int i = 0; i < m_lstUnscaledHelper.Count(); ++i)
{
DelayHelper helper = m_lstUnscaledHelper[i];
helper.delay -= UnityEngine.Time.unscaledDeltaTime;
if (helper.delay <= 0)
{
m_lstUnscaledHelper.RemoveAt(i);
i--;
helper.Invoke();
}
}
}
}
void OnDisable()
{
// Debug.Log("DelayInvoker Release!!!");
CancelInvoke(null);
this.StopAllCoroutines();
}
//====================================================================
public static void DelayInvokerOnEndOfFrame(DelayFunction func, params object[] args)
{
Instance.StartCoroutine(DelayInvokerOnEndOfFrameWorker(func, args));
}
private static IEnumerator DelayInvokerOnEndOfFrameWorker(DelayFunction func, params object[] args)
{
yield return ms_waitForEndOfFrame;
//Profiler.BeginSample("DelayInvoker_DelayInvokerOnEndOfFrame");
try
{
func(args);
}
catch (Exception e)
{
Debuger.LogError("DelayInvoker", "DelayInvokerOnEndOfFrame() Error:{0}\n{1}", e.Message, e.StackTrace);
}
//Profiler.EndSample();
}
public static void FixedTimeInvoke(int hours, int minitue)
{
}
}
} | 412 | 0.937313 | 1 | 0.937313 | game-dev | MEDIA | 0.227939 | game-dev | 0.978971 | 1 | 0.978971 |
DavidS-Repo/chunker | 4,737 | Chunker/main/PlayerEvents.java | package main;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import static main.ConsoleColorUtils.*;
/**
* Listener for player-related events to manage loaded chunks during pre-generation.
*/
public class PlayerEvents implements Listener {
private final ConcurrentHashMap<Integer, PreGenerationTask> tasks;
/**
* Initializes the listener with a map of pre-generation tasks.
*
* @param tasks a map of pre-generation tasks keyed by their identifiers
*/
public PlayerEvents(ConcurrentHashMap<Integer, PreGenerationTask> tasks) {
this.tasks = tasks;
}
/**
* Updates loaded chunks when a player moves between chunks.
*
* @param event the player move event
*/
@EventHandler(priority = EventPriority.MONITOR)
private void onPlayerMove(PlayerMoveEvent event) {
try {
Player player = event.getPlayer();
Chunk fromChunk = event.getFrom().getChunk();
Chunk toChunk = event.getTo().getChunk();
if (fromChunk.equals(toChunk)) {
return;
}
// Use the new factory method instead of the constructor.
ChunkPos fromChunkPos = ChunkPos.get(fromChunk.getX(), fromChunk.getZ());
ChunkPos toChunkPos = ChunkPos.get(toChunk.getX(), toChunk.getZ());
UUID playerId = player.getUniqueId();
synchronized (tasks) {
for (PreGenerationTask task : tasks.values()) {
task.playerChunkMap.computeIfAbsent(playerId, k -> ConcurrentHashMap.newKeySet());
Set<ChunkPos> playerChunks = task.playerChunkMap.get(playerId);
boolean removed = playerChunks.remove(fromChunkPos);
if (removed) {
boolean stillLoaded = task.playerChunkMap.values().stream()
.anyMatch(set -> set.contains(fromChunkPos));
if (!stillLoaded) {
task.playerLoadedChunks.remove(fromChunkPos);
}
}
boolean added = playerChunks.add(toChunkPos);
if (added) {
task.playerLoadedChunks.add(toChunkPos);
}
}
}
} catch (Exception e) {
exceptionMsg("Exception in onPlayerMove: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Cleans up loaded chunks when a player disconnects.
*
* @param event the player quit event
*/
@EventHandler(priority = EventPriority.MONITOR)
private void onPlayerQuit(PlayerQuitEvent event) {
try {
Player player = event.getPlayer();
UUID playerId = player.getUniqueId();
synchronized (tasks) {
for (PreGenerationTask task : tasks.values()) {
Set<ChunkPos> playerChunks = task.playerChunkMap.remove(playerId);
if (playerChunks != null) {
for (ChunkPos chunkPos : playerChunks) {
boolean stillLoaded = task.playerChunkMap.values().stream()
.anyMatch(set -> set.contains(chunkPos));
if (!stillLoaded) {
task.playerLoadedChunks.remove(chunkPos);
}
}
}
}
}
} catch (Exception e) {
exceptionMsg("Exception in onPlayerQuit: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Updates loaded chunks when a player changes worlds.
*
* @param event the player changed world event
*/
@EventHandler(priority = EventPriority.MONITOR)
private void onPlayerChangedWorld(PlayerChangedWorldEvent event) {
try {
Player player = event.getPlayer();
World newWorld = player.getWorld();
Chunk toChunk = player.getLocation().getChunk();
UUID playerId = player.getUniqueId();
synchronized (tasks) {
for (PreGenerationTask task : tasks.values()) {
Set<ChunkPos> playerChunks = task.playerChunkMap.remove(playerId);
if (playerChunks != null) {
for (ChunkPos chunkPos : playerChunks) {
boolean stillLoaded = task.playerChunkMap.values().stream()
.anyMatch(set -> set.contains(chunkPos));
if (!stillLoaded) {
task.playerLoadedChunks.remove(chunkPos);
}
}
}
if (task.world.equals(newWorld)) {
task.playerChunkMap.computeIfAbsent(playerId, k -> ConcurrentHashMap.newKeySet());
Set<ChunkPos> newPlayerChunks = task.playerChunkMap.get(playerId);
// Use the new factory method instead of the constructor.
ChunkPos toChunkPos = ChunkPos.get(toChunk.getX(), toChunk.getZ());
if (newPlayerChunks.add(toChunkPos)) {
task.playerLoadedChunks.add(toChunkPos);
}
}
}
}
} catch (Exception e) {
exceptionMsg("Exception in onPlayerChangedWorld: " + e.getMessage());
e.printStackTrace();
}
}
}
| 412 | 0.841722 | 1 | 0.841722 | game-dev | MEDIA | 0.875453 | game-dev | 0.942354 | 1 | 0.942354 |
Sduibek/fixtsrc | 16,077 | SCRIPTS/THOMAS2.SSL | procedure start; variable SrcObj := 0; variable SrcIsParty := 0;
procedure combat;
procedure critter_p_proc;// script_action == 12
procedure pickup_p_proc;// script_action == 4
procedure destroy_p_proc;// script_action == 18
procedure look_at_p_proc;// script_action == 21
procedure talk_p_proc;// script_action == 11
procedure thomasend;
procedure thomas00;
procedure thomas01;
procedure thomas02;
procedure thomas03;
procedure thomas04;
procedure thomas05;
procedure thomas06;
procedure thomas07;
procedure thomas08;
procedure thomas09;
procedure thomas10;
procedure thomas11;
procedure thomas12;
procedure thomas13;
procedure thomas14;
procedure thomas15;
procedure thomas16;
procedure thomas17;
procedure thomas18;
procedure thomas19;
procedure thomas20;
procedure thomas21;
procedure thomas22;
variable hostile;
variable Only_Once := 1;
procedure get_reaction;
procedure ReactToLevel;
procedure LevelToReact;
procedure UpReact;
procedure DownReact;
procedure BottomReact;
procedure TopReact;
procedure BigUpReact;
procedure BigDownReact;
procedure UpReactLevel;
procedure DownReactLevel;
procedure Goodbyes;
variable exit_line;
procedure start
begin
if local_var(12) != 1 then begin// Fallout Fixt lvar12 - this code block heals critter to full HP one time (first time player enters the map) to make sure they always start with full HP.
if metarule(14, 0) then begin// Fallout Fixt lvar12 - first visit to map?
if metarule(22, 0) == 0 then begin// Fallout Fixt lvar12 - Not currently loading a save?
if get_critter_stat(self_obj, 7) > 0 then begin critter_heal(self_obj, 999); end// if obj_is_carrying_obj_pid(self_obj, 46) > 0 then begin display_msg("S-bag " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 90) > 0 then begin display_msg("Pack " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 93) > 0 then begin display_msg("M-bag " + proto_data(obj_pid(self_obj), 1)); end
if global_var(330) then begin if critter_inven_obj(self_obj, 0) <= 0 then begin// Equip held armor if not currently wearing any.
variable A; if obj_carrying_pid_obj(self_obj, 17) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING COMBAT ARMOR..."); A := obj_carrying_pid_obj(self_obj, 17); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 2) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING METAL ARMOR..."); A := obj_carrying_pid_obj(self_obj, 2); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 1) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER ARMOR..."); A := obj_carrying_pid_obj(self_obj, 1); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 74) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER JACKET..."); A := obj_carrying_pid_obj(self_obj, 74); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 113) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING ROBES..."); A := obj_carrying_pid_obj(self_obj, 113); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end end end end end end end
set_local_var(12, 1);
if obj_carrying_pid_obj(self_obj, 239) then begin
variable BroArmor := 0;
BroArmor := obj_carrying_pid_obj(self_obj, 239);
rm_obj_from_inven(dude_obj, BroArmor);
destroy_object(BroArmor);
BroArmor := 0;
BroArmor := create_object_sid(239, 0, 0, -1);
add_obj_to_inven(self_obj, BroArmor);
wield_obj_critter(self_obj, BroArmor);
end
end
end
end
if Only_Once then begin
/* TEAM_NUM */ critter_add_trait(self_obj, 1, 6, 44);
/* AI_PACKET */ critter_add_trait(self_obj, 1, 5, 64);
end
if (script_action == 21) then begin//MOUSE-OVER DESCRIPTION -- look_at_p_proc - (usually brief length. hovered mouse over object, haven't clicked on it.)
call look_at_p_proc;
end
else begin
if (script_action == 4) then begin//<---caught stealing! (pickup_p_proc)
call pickup_p_proc;
end
else begin
if (script_action == 11) then begin//<--- talk_p_proc (Face icon), can also call "do_dialogue" or "do_dialog"
call talk_p_proc;
end
else begin
if (script_action == 12) then begin//<-- critter_p_proc - (can also be "Critter_Action") - do they see you, should they wander, should they attack you, etc..
call critter_p_proc;
end
else begin
if (script_action == 18) then begin//destroy_p_proc - Object or Critter has been killed or otherwise eradicated. Fall down go boom.
call destroy_p_proc;
end
end
end
end
end
end
procedure combat
begin
hostile := 1;
end
procedure critter_p_proc
begin
if (global_var(250)) then begin
hostile := 1;
end
if (tile_distance_objs(self_obj, dude_obj) > 12) then begin
hostile := 0;
end
if (hostile) then begin// This must come FIRST as an if/then/else before "attack dude" type code, otherwise it runs too soon and can override other attack calls
set_global_var(250, 1);
hostile := 0;
attack_complex(dude_obj, 0, 1, 0, 0, 30000, 0, 0);
end
end
procedure pickup_p_proc
begin
if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin
hostile := 1;
end
end
procedure talk_p_proc
begin
anim(dude_obj, 1000, rotation_to_tile(tile_num(dude_obj), tile_num(self_obj)));
call get_reaction;
start_gdialog(685, self_obj, 4, -1, -1);
gsay_start;
if (local_var(4) != 1) then begin
set_local_var(4, 1);
if (local_var(1) == 1) then begin
call thomas01;
end
else begin
call thomas00;
end
end
else begin
if (local_var(1) == 1) then begin
if (local_var(6) != 0) then begin
call thomas09;
end
else begin
call thomas08;
end
end
else begin
if (local_var(6) != 0) then begin
call thomas20;
end
else begin
call thomas19;
end
end
end
gsay_end;
end_dialogue;
end
procedure destroy_p_proc
begin
//
//BEGIN WEAPON DROP MOD CODE
//--original code and mod by:--
// Josan12 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=18843) and
// MIB88 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=4464)
//
if global_var(460) and not(global_var(0)) and (critter_inven_obj(self_obj, 1) or critter_inven_obj(self_obj, 2)) then begin// only run if Weapon Drop is enabled, AND Fixes Only is disabled, AND actually holding something
variable item1 := 0; variable item2 := 0; variable armor := 0; variable item1PID := 0; variable item2PID := 0; variable armorPID := 0; variable drophex := 0; if global_var(325) then begin debug_msg("Weapon Drop BEGINS"); end
if (critter_inven_obj(self_obj, 1) > 0) then begin item1 := critter_inven_obj(self_obj, 1); end if (critter_inven_obj(self_obj, 2) > 0) then begin item2 := critter_inven_obj(self_obj, 2); end if (critter_inven_obj(self_obj, 0) > 0) then begin armor := critter_inven_obj(self_obj, 0); end if item1 then begin item1PID := obj_pid(item1); end if item2 then begin item2PID := obj_pid(item2); end if armor then begin armorPID := obj_pid(armor); end drophex := tile_num_in_direction(tile_num(self_obj), random(0, 5), random(global_var(461), global_var(462)));
if (item1PID != 19) and (item1PID != 21) and (item1PID != 79) and (item1PID != 205) and (item1PID != 234) and (item1PID != 235) and (item1PID != 244) and (item2PID != 19) and (item2PID != 21) and (item2PID != 79) and (item2PID != 205) and (item2PID != 234) and (item2PID != 235) and (item2PID != 244) then begin//Don't drop if: Rock (19), Brass Knuckles (21), Flare (79), Lit Flare (205), Spiked Knuckles (234), Power Fist (235), or Gold Nugget (244)
if (item1 > 0) then begin if (obj_item_subtype(item1) == 3) then begin
rm_obj_from_inven(self_obj, item1); move_to(item1, drophex, elevation(self_obj)); end end
if (item2 > 0) then begin if (obj_item_subtype(item2) == 3) then begin
rm_obj_from_inven(self_obj, item2); move_to(item2, drophex, elevation(self_obj)); end end if global_var(325) then begin debug_msg("Weapon Drop ENDS"); end
end
end
//END WEAPON DROP MOD CODE
//
set_global_var(250, 1);
rm_timer_event(self_obj);
if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin
if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin
set_global_var(317, 1);
set_global_var(157, 0);
end
if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin
set_global_var(157, 1);
set_global_var(317, 0);
end
set_global_var(159, global_var(159) + 1);// THIS MONSTER WAS A GOOD GUY. INCREASE GoodGuysKilled COUNTER
if ((global_var(159) % 2) == 0) then begin
set_global_var(155, (global_var(155) - 1));
end
end
end
procedure look_at_p_proc
begin
script_overrides;
display_msg(message_str(685, 100));
end
procedure thomasend
begin
end
procedure thomas00
begin
gsay_reply(685, 101);
giq_option(4, 685, 102, thomas05, 50);
giq_option(4, 685, 103, thomas06, 50);
giq_option(4, 685, 104, thomas04, 50);
giq_option(4, 685, 105, thomasend, 50);
giq_option(-3, 685, 106, thomas02, 50);
end
procedure thomas01
begin
gsay_reply(685, 108);
giq_option(4, 685, 102, thomas05, 50);
giq_option(4, 685, 103, thomas06, 50);
giq_option(4, 685, 104, thomas04, 50);
giq_option(4, 685, 105, thomasend, 50);
giq_option(-3, 685, 106, thomas02, 50);
end
procedure thomas02
begin
gsay_message(685, 109, 51);
end
procedure thomas03
begin
gsay_message(685, 110, 51);
end
procedure thomas04
begin
gsay_message(685, message_str(685, 111) + proto_data(obj_pid(dude_obj), 1) + message_str(685, 112), 51);
end
procedure thomas05
begin
gsay_message(685, 113, 50);
end
procedure thomas06
begin
if (get_critter_stat(dude_obj, 34) == 0) then begin
gsay_reply(685, 114);
end
else begin
gsay_reply(685, 115);
end
call thomas10;
end
procedure thomas07
begin
gsay_reply(685, 125);
call thomas10;
end
procedure thomas08
begin
if (local_var(5) != 0) then begin
set_local_var(5, 1);
gsay_reply(685, 126);
end
else begin
gsay_reply(685, 127);
end
call thomas10;
end
procedure thomas09
begin
gsay_reply(685, 125);
giq_option(4, 685, 102, thomas05, 50);
giq_option(4, 685, 103, thomas06, 50);
giq_option(4, 685, 104, thomas04, 50);
giq_option(4, 685, 105, thomas21, 50);
giq_option(-3, 685, 107, thomas02, 50);
end
procedure thomas10
begin
giq_option(4, 685, 118, thomas11, 50);
giq_option(4, 685, 119, thomas12, 50);
giq_option(4, 685, 120, thomas13, 50);
giq_option(4, 685, 121, thomas14, 50);
giq_option(4, 685, 122, thomas15, 50);
giq_option(4, 685, 123, thomas16, 50);
giq_option(4, 685, 124, thomas17, 50);
giq_option(-3, 685, 106, thomas02, 50);
end
procedure thomas11
begin
if global_var(547) then begin
gfade_out(1);
gfade_out(1);
end
gfade_out(1);
gfade_in(1);
display_msg(message_str(685, 130));
set_local_var(6, 1);
end
procedure thomas12
begin
if global_var(547) then begin
gfade_out(1);
gfade_out(1);
end
gfade_out(1);
gfade_in(1);
display_msg(message_str(685, 132));
set_local_var(6, 1);
end
procedure thomas13
begin
if global_var(547) then begin
gfade_out(1);
gfade_out(1);
end
gfade_out(1);
gfade_in(1);
display_msg(message_str(685, 134));
set_local_var(6, 1);
end
procedure thomas14
begin
if global_var(547) then begin
gfade_out(1);
gfade_out(1);
end
gfade_out(1);
gfade_in(1);
display_msg(message_str(685, 135));
set_local_var(6, 1);
end
procedure thomas15
begin
if global_var(547) then begin
gfade_out(1);
gfade_out(1);
end
gfade_out(1);
gfade_in(1);
display_msg(message_str(685, 136));
set_local_var(6, 1);
end
procedure thomas16
begin
if global_var(547) then begin
gfade_out(1);
gfade_out(1);
end
gfade_out(1);
gfade_in(1);
display_msg(message_str(685, 137));
set_local_var(6, 1);
end
procedure thomas17
begin
gsay_message(685, 138, 50);
end
procedure thomas18
begin
gsay_message(685, 139, 51);
end
procedure thomas19
begin
if (local_var(5) != 0) then begin
set_local_var(5, 1);
gsay_reply(685, 140);
end
else begin
gsay_reply(685, 127);
end
call thomas10;
end
procedure thomas20
begin
gsay_reply(685, 140);
giq_option(4, 685, 102, thomas03, 50);
giq_option(4, 685, 103, thomas07, 50);
giq_option(4, 685, 104, thomas04, 50);
giq_option(4, 685, 105, thomas22, 50);
giq_option(-3, 685, 107, thomas02, 50);
end
procedure thomas21
begin
gsay_message(685, 142, 50);
end
procedure thomas22
begin
gsay_message(685, 143, 51);
end
procedure get_reaction
begin
if (local_var(2) == 0) then begin
set_local_var(0, 50);
set_local_var(1, 2);
set_local_var(2, 1);
set_local_var(0, local_var(0) + (5 * get_critter_stat(dude_obj, 3)) - 25);
set_local_var(0, local_var(0) + (10 * has_trait(0, dude_obj, 10)));
if (has_trait(0, dude_obj, 39)) then begin
if (global_var(155) > 0) then begin
set_local_var(0, local_var(0) + global_var(155));
end
else begin
set_local_var(0, local_var(0) - global_var(155));
end
end
else begin
if (local_var(3) == 1) then begin
set_local_var(0, local_var(0) - global_var(155));
end
else begin
set_local_var(0, local_var(0) + global_var(155));
end
end
if (global_var(158) >= global_var(545)) then begin
set_local_var(0, local_var(0) - 30);
end
if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin
set_local_var(0, local_var(0) + 20);
end
if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin
set_local_var(0, local_var(0) - 20);
end
call ReactToLevel;
end
end
procedure ReactToLevel
begin
if (local_var(0) <= 25) then begin
set_local_var(1, 1);
end
else begin
if (local_var(0) <= 75) then begin
set_local_var(1, 2);
end
else begin
set_local_var(1, 3);
end
end
end
procedure LevelToReact
begin
if (local_var(1) == 1) then begin
set_local_var(0, random(1, 25));
end
else begin
if (local_var(1) == 2) then begin
set_local_var(0, random(26, 75));
end
else begin
set_local_var(0, random(76, 100));
end
end
end
procedure UpReact
begin
set_local_var(0, local_var(0) + 10);
call ReactToLevel;
end
procedure DownReact
begin
set_local_var(0, local_var(0) - 10);
call ReactToLevel;
end
procedure BottomReact
begin
set_local_var(1, 1);
set_local_var(0, 1);
end
procedure TopReact
begin
set_local_var(0, 100);
set_local_var(1, 3);
end
procedure BigUpReact
begin
set_local_var(0, local_var(0) + 25);
call ReactToLevel;
end
procedure BigDownReact
begin
set_local_var(0, local_var(0) - 25);
call ReactToLevel;
end
procedure UpReactLevel
begin
set_local_var(1, local_var(1) + 1);
if (local_var(1) > 3) then begin
set_local_var(1, 3);
end
call LevelToReact;
end
procedure DownReactLevel
begin
set_local_var(1, local_var(1) - 1);
if (local_var(1) < 1) then begin
set_local_var(1, 1);
end
call LevelToReact;
end
procedure Goodbyes
begin
exit_line := message_str(634, random(100, 105));
end
| 412 | 0.789614 | 1 | 0.789614 | game-dev | MEDIA | 0.962373 | game-dev | 0.880682 | 1 | 0.880682 |
candybox2/candybox2.github.io | 2,776 | code/main/Database.ts | ///<reference path="./../../libs/jquery.d.ts"/>
module Database{
// Variables
var asciiMap: { [s: string]: string[]; } = {}; // A map which associates strings (the keys) to array of strings (the ascii arts)
var asciiSizeMap: { [s: string]: Pos; } = {}; // A map which associates strings (the keys) to the sizes of ascii arts
var textMap: { [s: string]: string; } = {}; // A map which associated strings (the keys) to strings (the texts)
// Public functions
export function addAscii(asciiName: string, width: number, height: number, asciiArray: string[]): void{
asciiMap[asciiName] = asciiArray;
asciiSizeMap[asciiName] = new Pos(width, height);
}
export function addText(key: string, text: string): void{
textMap[key] = text;
}
export function isTranslated(): boolean{
if(Saving.loadString("gameLanguage") != "en")
return true;
return false;
}
// Public getters
export function getAscii(key: string): string[]{
if(asciiMap[key] == null)
console.log("Error : trying to access the unknown ascii art \"" + key + "\"");
return asciiMap[key];
}
export function getAsciiHeight(key: string): number{
return asciiSizeMap[key].y;
}
export function getAsciiWidth(key: string): number{
return asciiSizeMap[key].x;
}
export function getPartOfAscii(key: string, y1: number, y2: number): string[]{
return getAscii(key).slice(y1, y2);
}
export function getText(key: string): string{
if(textMap["en." + key] == null)
console.log("Error : trying to access the unknown text \"" + key + "\"");
return textMap["en." + key];
}
export function getTranslatedText(key: string): string{
// If we have a language (other than english) selected
if(Saving.loadString("gameLanguage") != "en"){
// If the translated text can't be found
if(textMap[Saving.loadString("gameLanguage") + "." + key] == null)
console.log("Error : trying to access the unknown translated text \"" + key + "\" for language " + Saving.loadString("gameLanguage") + "."); // Error
// If the translated text isn't chinese
if(Saving.loadString("gameLanguage") != "zh")
return textMap[Saving.loadString("gameLanguage") + "." + key]; // We just return the text
// Else, the translated text is chinese
else
return textMap[Saving.loadString("gameLanguage") + "." + key].addChineseSpaces(); // We return the text after adding spaces
}
// Else, we return an empty string
return "";
}
}
| 412 | 0.512931 | 1 | 0.512931 | game-dev | MEDIA | 0.820622 | game-dev | 0.798813 | 1 | 0.798813 |
ax-grymyr/l2dn-server | 1,075 | L2Dn/L2Dn.GameServer.Model/Model/Conditions/ConditionPlayerCanEscape.cs | using L2Dn.GameServer.Model.Actor;
using L2Dn.GameServer.Model.Items;
using L2Dn.GameServer.Model.Skills;
namespace L2Dn.GameServer.Model.Conditions;
/**
* Player Can Escape condition implementation.
* @author Adry_85
*/
public sealed class ConditionPlayerCanEscape(bool value): Condition
{
protected override bool TestImpl(Creature effector, Creature? effected, Skill? skill, ItemTemplate? item)
{
bool canTeleport = true;
Player? player = effector.getActingPlayer();
if (player is null)
canTeleport = false;
else if (player.isInDuel())
canTeleport = false;
else if (player.isControlBlocked())
canTeleport = false;
else if (player.isCombatFlagEquipped())
canTeleport = false;
else if (player.isFlying() || player.isFlyingMounted())
canTeleport = false;
else if (player.isInOlympiadMode())
canTeleport = false;
else if (player.isOnEvent())
canTeleport = false;
return value == canTeleport;
}
} | 412 | 0.816551 | 1 | 0.816551 | game-dev | MEDIA | 0.897809 | game-dev | 0.729778 | 1 | 0.729778 |
RCInet/LastEpoch_Mods | 4,197 | AssetBundleExport/Library/PackageCache/com.unity.visualscripting@1b53f46e931b/Editor/VisualScripting.Core/Dependencies/ReorderableList/ElementAdderMenu/GenericElementAdderMenuBuilder.cs | // Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Unity.VisualScripting.ReorderableList.Element_Adder_Menu
{
internal sealed class GenericElementAdderMenuBuilder<TContext> : IElementAdderMenuBuilder<TContext>
{
public GenericElementAdderMenuBuilder()
{
_typeDisplayNameFormatter = NicifyTypeName;
}
private Type _contractType;
private IElementAdder<TContext> _elementAdder;
private Func<Type, string> _typeDisplayNameFormatter;
private List<Func<Type, bool>> _typeFilters = new List<Func<Type, bool>>();
private List<IElementAdderMenuCommand<TContext>> _customCommands = new List<IElementAdderMenuCommand<TContext>>();
public void SetContractType(Type contractType)
{
_contractType = contractType;
}
public void SetElementAdder(IElementAdder<TContext> elementAdder)
{
_elementAdder = elementAdder;
}
public void SetTypeDisplayNameFormatter(Func<Type, string> formatter)
{
_typeDisplayNameFormatter = formatter ?? NicifyTypeName;
}
public void AddTypeFilter(Func<Type, bool> typeFilter)
{
if (typeFilter == null)
{
throw new ArgumentNullException(nameof(typeFilter));
}
_typeFilters.Add(typeFilter);
}
public void AddCustomCommand(IElementAdderMenuCommand<TContext> command)
{
if (command == null)
{
throw new ArgumentNullException(nameof(command));
}
_customCommands.Add(command);
}
public IElementAdderMenu GetMenu()
{
var menu = new GenericElementAdderMenu();
AddCommandsToMenu(menu, _customCommands);
if (_contractType != null)
{
AddCommandsToMenu(menu, ElementAdderMeta.GetMenuCommands<TContext>(_contractType));
AddConcreteTypesToMenu(menu, ElementAdderMeta.GetConcreteElementTypes(_contractType, _typeFilters.ToArray()));
}
return menu;
}
private void AddCommandsToMenu(GenericElementAdderMenu menu, IList<IElementAdderMenuCommand<TContext>> commands)
{
if (commands.Count == 0)
{
return;
}
if (!menu.IsEmpty)
{
menu.AddSeparator();
}
foreach (var command in commands)
{
if (_elementAdder != null && command.CanExecute(_elementAdder))
{
menu.AddItem(command.Content, () => command.Execute(_elementAdder));
}
else
{
menu.AddDisabledItem(command.Content);
}
}
}
private void AddConcreteTypesToMenu(GenericElementAdderMenu menu, Type[] concreteTypes)
{
if (concreteTypes.Length == 0)
{
return;
}
if (!menu.IsEmpty)
{
menu.AddSeparator();
}
foreach (var concreteType in concreteTypes)
{
var content = new GUIContent(_typeDisplayNameFormatter(concreteType));
if (_elementAdder != null && _elementAdder.CanAddElement(concreteType))
{
menu.AddItem(content, () =>
{
if (_elementAdder.CanAddElement(concreteType))
{
_elementAdder.AddElement(concreteType);
}
});
}
else
{
menu.AddDisabledItem(content);
}
}
}
private static string NicifyTypeName(Type type)
{
return ObjectNames.NicifyVariableName(type.Name);
}
}
}
| 412 | 0.813754 | 1 | 0.813754 | game-dev | MEDIA | 0.520745 | game-dev | 0.902606 | 1 | 0.902606 |
electronicarts/CnC_Generals_Zero_Hour | 6,405 | Generals/Code/GameEngine/Source/GameLogic/Object/Upgrade/RadarUpgrade.cpp | /*
** Command & Conquer Generals(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: RadarUpgrade.cpp /////////////////////////////////////////////////////////////////////////////
// Author: Colin Day, March 2002
// Desc: Radar upgrades
///////////////////////////////////////////////////////////////////////////////////////////////////
// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
#include "Common/ModelState.h"
#include "Common/Player.h"
#include "Common/Xfer.h"
#include "GameClient/Drawable.h"
#include "GameLogic/Object.h"
#include "GameLogic/Module/RadarUpdate.h"
#include "GameLogic/Module/RadarUpgrade.h"
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void RadarUpgradeModuleData::buildFieldParse(MultiIniFieldParse& p)
{
UpgradeModuleData::buildFieldParse(p);
static const FieldParse dataFieldParse[] =
{
{ "DisableProof", INI::parseBool, NULL, offsetof( RadarUpgradeModuleData, m_isDisableProof ) },
{ 0, 0, 0, 0 }
};
p.add(dataFieldParse);
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
RadarUpgrade::RadarUpgrade( Thing *thing, const ModuleData* moduleData ) :
UpgradeModule( thing, moduleData )
{
} // end RadarUpgrade
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
RadarUpgrade::~RadarUpgrade( void )
{
} // end ~RadarUpgrade
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void RadarUpgrade::onDelete( void )
{
const RadarUpgradeModuleData *md = getRadarUpgradeModuleData();
// if we haven't been upgraded there is nothing to clean up
if( isAlreadyUpgraded() == FALSE )
return;
// If we're currently disabled, we shouldn't do anything, because we've already done it.
if ( getObject()->isDisabled() )
return;
// remove the radar from the player
Player *player = getObject()->getControllingPlayer();
if( player )
player->removeRadar( md->m_isDisableProof );
// this upgrade module is now "not upgraded"
setUpgradeExecuted(FALSE);
} // end onDelete
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void RadarUpgrade::onCapture( Player *oldOwner, Player *newOwner )
{
const RadarUpgradeModuleData *md = getRadarUpgradeModuleData();
// do nothing if we haven't upgraded yet
if( isAlreadyUpgraded() == FALSE )
return;
// If we're currently disabled, we shouldn't do anything, because we've already done it.
if ( getObject()->isDisabled() )
return;
// remove radar from old player and add to new player
if( oldOwner )
{
oldOwner->removeRadar( md->m_isDisableProof );
setUpgradeExecuted(FALSE);
} // end if
if( newOwner )
{
newOwner->addRadar( md->m_isDisableProof );
setUpgradeExecuted(TRUE);
} // end if
} // end onCapture
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void RadarUpgrade::upgradeImplementation( void )
{
const RadarUpgradeModuleData *md = getRadarUpgradeModuleData();
Player *player = getObject()->getControllingPlayer();
// update the player with another radar facility
player->addRadar( md->m_isDisableProof );
// find the radar update module of this object
NameKeyType radarUpdateKey = NAMEKEY( "RadarUpdate" );
RadarUpdate *radarUpdate = (RadarUpdate *)getObject()->findUpdateModule( radarUpdateKey );
if( radarUpdate )
radarUpdate->extendRadar();
} // end upgradeImplementation
// ------------------------------------------------------------------------------------------------
/** CRC */
// ------------------------------------------------------------------------------------------------
void RadarUpgrade::crc( Xfer *xfer )
{
// extend base class
UpgradeModule::crc( xfer );
} // end crc
// ------------------------------------------------------------------------------------------------
/** Xfer method
* Version Info:
* 1: Initial version */
// ------------------------------------------------------------------------------------------------
void RadarUpgrade::xfer( Xfer *xfer )
{
// version
XferVersion currentVersion = 1;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
// extend base class
UpgradeModule::xfer( xfer );
} // end xfer
// ------------------------------------------------------------------------------------------------
/** Load post process */
// ------------------------------------------------------------------------------------------------
void RadarUpgrade::loadPostProcess( void )
{
// extend base class
UpgradeModule::loadPostProcess();
} // end loadPostProcess
| 412 | 0.716566 | 1 | 0.716566 | game-dev | MEDIA | 0.961662 | game-dev | 0.898294 | 1 | 0.898294 |
melanchall/drywetmidi | 1,082 | DryWetMidi/Composing/Actions/SetProgram/SetGeneralMidiProgramAction.cs | using Melanchall.DryWetMidi.Interaction;
using Melanchall.DryWetMidi.Standards;
namespace Melanchall.DryWetMidi.Composing
{
internal sealed class SetGeneralMidiProgramAction : PatternAction
{
#region Constructor
public SetGeneralMidiProgramAction(GeneralMidiProgram program)
{
Program = program;
}
#endregion
#region Properties
public GeneralMidiProgram Program { get; }
#endregion
#region Overrides
public override PatternActionResult Invoke(long time, PatternContext context)
{
if (State != PatternActionState.Enabled)
return PatternActionResult.DoNothing;
var programEvent = Program.GetProgramEvent(context.Channel);
var timedEvent = new TimedEvent(programEvent, time);
return new PatternActionResult(time, new[] { timedEvent });
}
public override PatternAction Clone()
{
return new SetGeneralMidiProgramAction(Program);
}
#endregion
}
}
| 412 | 0.84257 | 1 | 0.84257 | game-dev | MEDIA | 0.806689 | game-dev | 0.674213 | 1 | 0.674213 |
IgnaceMaes/MaterialSkin | 13,887 | MaterialSkin/Animations/AnimationManager.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace MaterialSkin.Animations
{
class AnimationManager
{
public bool InterruptAnimation { get; set; }
public double Increment { get; set; }
public double SecondaryIncrement { get; set; }
public AnimationType AnimationType { get; set; }
public bool Singular { get; set; }
public delegate void AnimationFinished(object sender);
public event AnimationFinished OnAnimationFinished;
public delegate void AnimationProgress(object sender);
public event AnimationProgress OnAnimationProgress;
private readonly List<double> _animationProgresses;
private readonly List<Point> _animationSources;
private readonly List<AnimationDirection> _animationDirections;
private readonly List<object[]> _animationDatas;
private const double MIN_VALUE = 0.00;
private const double MAX_VALUE = 1.00;
private readonly Timer _animationTimer = new Timer { Interval = 5, Enabled = false };
/// <summary>
/// Constructor
/// </summary>
/// <param name="singular">If true, only one animation is supported. The current animation will be replaced with the new one. If false, a new animation is added to the list.</param>
public AnimationManager(bool singular = true)
{
_animationProgresses = new List<double>();
_animationSources = new List<Point>();
_animationDirections = new List<AnimationDirection>();
_animationDatas = new List<object[]>();
Increment = 0.03;
SecondaryIncrement = 0.03;
AnimationType = AnimationType.Linear;
InterruptAnimation = true;
Singular = singular;
if (Singular)
{
_animationProgresses.Add(0);
_animationSources.Add(new Point(0, 0));
_animationDirections.Add(AnimationDirection.In);
}
_animationTimer.Tick += AnimationTimerOnTick;
}
private void AnimationTimerOnTick(object sender, EventArgs eventArgs)
{
for (var i = 0; i < _animationProgresses.Count; i++)
{
UpdateProgress(i);
if (!Singular)
{
if ((_animationDirections[i] == AnimationDirection.InOutIn && _animationProgresses[i] == MAX_VALUE))
{
_animationDirections[i] = AnimationDirection.InOutOut;
}
else if ((_animationDirections[i] == AnimationDirection.InOutRepeatingIn && _animationProgresses[i] == MIN_VALUE))
{
_animationDirections[i] = AnimationDirection.InOutRepeatingOut;
}
else if ((_animationDirections[i] == AnimationDirection.InOutRepeatingOut && _animationProgresses[i] == MIN_VALUE))
{
_animationDirections[i] = AnimationDirection.InOutRepeatingIn;
}
else if (
(_animationDirections[i] == AnimationDirection.In && _animationProgresses[i] == MAX_VALUE) ||
(_animationDirections[i] == AnimationDirection.Out && _animationProgresses[i] == MIN_VALUE) ||
(_animationDirections[i] == AnimationDirection.InOutOut && _animationProgresses[i] == MIN_VALUE))
{
_animationProgresses.RemoveAt(i);
_animationSources.RemoveAt(i);
_animationDirections.RemoveAt(i);
_animationDatas.RemoveAt(i);
}
}
else
{
if ((_animationDirections[i] == AnimationDirection.InOutIn && _animationProgresses[i] == MAX_VALUE))
{
_animationDirections[i] = AnimationDirection.InOutOut;
}
else if ((_animationDirections[i] == AnimationDirection.InOutRepeatingIn && _animationProgresses[i] == MAX_VALUE))
{
_animationDirections[i] = AnimationDirection.InOutRepeatingOut;
}
else if ((_animationDirections[i] == AnimationDirection.InOutRepeatingOut && _animationProgresses[i] == MIN_VALUE))
{
_animationDirections[i] = AnimationDirection.InOutRepeatingIn;
}
}
}
OnAnimationProgress?.Invoke(this);
}
public bool IsAnimating()
{
return _animationTimer.Enabled;
}
public void StartNewAnimation(AnimationDirection animationDirection, object[] data = null)
{
StartNewAnimation(animationDirection, new Point(0, 0), data);
}
public void StartNewAnimation(AnimationDirection animationDirection, Point animationSource, object[] data = null)
{
if (!IsAnimating() || InterruptAnimation)
{
if (Singular && _animationDirections.Count > 0)
{
_animationDirections[0] = animationDirection;
}
else
{
_animationDirections.Add(animationDirection);
}
if (Singular && _animationSources.Count > 0)
{
_animationSources[0] = animationSource;
}
else
{
_animationSources.Add(animationSource);
}
if (!(Singular && _animationProgresses.Count > 0))
{
switch (_animationDirections[_animationDirections.Count - 1])
{
case AnimationDirection.InOutRepeatingIn:
case AnimationDirection.InOutIn:
case AnimationDirection.In:
_animationProgresses.Add(MIN_VALUE);
break;
case AnimationDirection.InOutRepeatingOut:
case AnimationDirection.InOutOut:
case AnimationDirection.Out:
_animationProgresses.Add(MAX_VALUE);
break;
default:
throw new Exception("Invalid AnimationDirection");
}
}
if (Singular && _animationDatas.Count > 0)
{
_animationDatas[0] = data ?? new object[] { };
}
else
{
_animationDatas.Add(data ?? new object[] { });
}
}
_animationTimer.Start();
}
public void UpdateProgress(int index)
{
switch (_animationDirections[index])
{
case AnimationDirection.InOutRepeatingIn:
case AnimationDirection.InOutIn:
case AnimationDirection.In:
IncrementProgress(index);
break;
case AnimationDirection.InOutRepeatingOut:
case AnimationDirection.InOutOut:
case AnimationDirection.Out:
DecrementProgress(index);
break;
default:
throw new Exception("No AnimationDirection has been set");
}
}
private void IncrementProgress(int index)
{
_animationProgresses[index] += Increment;
if (_animationProgresses[index] > MAX_VALUE)
{
_animationProgresses[index] = MAX_VALUE;
for (int i = 0; i < GetAnimationCount(); i++)
{
if (_animationDirections[i] == AnimationDirection.InOutIn) return;
if (_animationDirections[i] == AnimationDirection.InOutRepeatingIn) return;
if (_animationDirections[i] == AnimationDirection.InOutRepeatingOut) return;
if (_animationDirections[i] == AnimationDirection.InOutOut && _animationProgresses[i] != MAX_VALUE) return;
if (_animationDirections[i] == AnimationDirection.In && _animationProgresses[i] != MAX_VALUE) return;
}
_animationTimer.Stop();
OnAnimationFinished?.Invoke(this);
}
}
private void DecrementProgress(int index)
{
_animationProgresses[index] -= (_animationDirections[index] == AnimationDirection.InOutOut || _animationDirections[index] == AnimationDirection.InOutRepeatingOut) ? SecondaryIncrement : Increment;
if (_animationProgresses[index] < MIN_VALUE)
{
_animationProgresses[index] = MIN_VALUE;
for (var i = 0; i < GetAnimationCount(); i++)
{
if (_animationDirections[i] == AnimationDirection.InOutIn) return;
if (_animationDirections[i] == AnimationDirection.InOutRepeatingIn) return;
if (_animationDirections[i] == AnimationDirection.InOutRepeatingOut) return;
if (_animationDirections[i] == AnimationDirection.InOutOut && _animationProgresses[i] != MIN_VALUE) return;
if (_animationDirections[i] == AnimationDirection.Out && _animationProgresses[i] != MIN_VALUE) return;
}
_animationTimer.Stop();
OnAnimationFinished?.Invoke(this);
}
}
public double GetProgress()
{
if (!Singular)
throw new Exception("Animation is not set to Singular.");
if (_animationProgresses.Count == 0)
throw new Exception("Invalid animation");
return GetProgress(0);
}
public double GetProgress(int index)
{
if (!(index < GetAnimationCount()))
throw new IndexOutOfRangeException("Invalid animation index");
switch (AnimationType)
{
case AnimationType.Linear:
return AnimationLinear.CalculateProgress(_animationProgresses[index]);
case AnimationType.EaseInOut:
return AnimationEaseInOut.CalculateProgress(_animationProgresses[index]);
case AnimationType.EaseOut:
return AnimationEaseOut.CalculateProgress(_animationProgresses[index]);
case AnimationType.CustomQuadratic:
return AnimationCustomQuadratic.CalculateProgress(_animationProgresses[index]);
default:
throw new NotImplementedException("The given AnimationType is not implemented");
}
}
public Point GetSource(int index)
{
if (!(index < GetAnimationCount()))
throw new IndexOutOfRangeException("Invalid animation index");
return _animationSources[index];
}
public Point GetSource()
{
if (!Singular)
throw new Exception("Animation is not set to Singular.");
if (_animationSources.Count == 0)
throw new Exception("Invalid animation");
return _animationSources[0];
}
public AnimationDirection GetDirection()
{
if (!Singular)
throw new Exception("Animation is not set to Singular.");
if (_animationDirections.Count == 0)
throw new Exception("Invalid animation");
return _animationDirections[0];
}
public AnimationDirection GetDirection(int index)
{
if (!(index < _animationDirections.Count))
throw new IndexOutOfRangeException("Invalid animation index");
return _animationDirections[index];
}
public object[] GetData()
{
if (!Singular)
throw new Exception("Animation is not set to Singular.");
if (_animationDatas.Count == 0)
throw new Exception("Invalid animation");
return _animationDatas[0];
}
public object[] GetData(int index)
{
if (!(index < _animationDatas.Count))
throw new IndexOutOfRangeException("Invalid animation index");
return _animationDatas[index];
}
public int GetAnimationCount()
{
return _animationProgresses.Count;
}
public void SetProgress(double progress)
{
if (!Singular)
throw new Exception("Animation is not set to Singular.");
if (_animationProgresses.Count == 0)
throw new Exception("Invalid animation");
_animationProgresses[0] = progress;
}
public void SetDirection(AnimationDirection direction)
{
if (!Singular)
throw new Exception("Animation is not set to Singular.");
if (_animationProgresses.Count == 0)
throw new Exception("Invalid animation");
_animationDirections[0] = direction;
}
public void SetData(object[] data)
{
if (!Singular)
throw new Exception("Animation is not set to Singular.");
if (_animationDatas.Count == 0)
throw new Exception("Invalid animation");
_animationDatas[0] = data;
}
}
}
| 412 | 0.732888 | 1 | 0.732888 | game-dev | MEDIA | 0.499283 | game-dev | 0.679159 | 1 | 0.679159 |
CharlieTap/chasm | 2,594 | libs/stack/src/commonMain/kotlin/io/github/charlietap/chasm/stack/Stack.kt | package io.github.charlietap.chasm.stack
import kotlin.jvm.JvmOverloads
class Stack<T>
@JvmOverloads
constructor(minCapacity: Int = MIN_CAPACITY) {
private var elements: Array<T?>
private var top = 0
init {
val arrayCapacity: Int =
if (minCapacity.countOneBits() != 1) {
(minCapacity - 1).takeHighestOneBit() shl 1
} else {
minCapacity
}
@Suppress("UNCHECKED_CAST")
elements = arrayOfNulls<Any?>(arrayCapacity) as Array<T?>
}
fun push(value: T) {
elements[top] = value
top++
if (top == elements.size) {
doubleCapacity()
}
}
fun pushAll(values: Array<T>) {
val requiredSize = top + values.size
while (requiredSize > elements.size) {
doubleCapacity()
}
values.copyInto(elements, startIndex = 0, endIndex = values.size, destinationOffset = top)
top += values.size
}
fun popOrNull(): T? = try {
top--
val value = elements[top]
elements[top] = null
value
} catch (_: Exception) {
top++
null
}
fun peekOrNull(): T? = try {
elements[top - 1]
} catch (_: Exception) {
null
}
fun peekNthOrNull(n: Int): T? = try {
elements[top - 1 - n]
} catch (_: Exception) {
null
}
fun shrink(preserveTopN: Int, depth: Int) {
elements.copyInto(
destination = elements,
destinationOffset = depth,
startIndex = top - preserveTopN,
endIndex = top,
)
var i = depth + preserveTopN
while (i < top) {
elements[i] = null
i++
}
top = depth + preserveTopN
}
fun depth(): Int = top
fun clear() {
for (i in 0 until top) {
elements[i] = null
}
top = 0
}
fun entries() = buildList {
for (i in 0 until top) {
@Suppress("UNCHECKED_CAST")
add(elements[i] as T)
}
}
private fun doubleCapacity() {
val newCapacity = elements.size * 2
elements = elements.copyOf(newCapacity)
}
}
private const val MIN_CAPACITY = 256
| 412 | 0.959775 | 1 | 0.959775 | game-dev | MEDIA | 0.898219 | game-dev | 0.987807 | 1 | 0.987807 |
ratrecommends/dice-heroes | 3,221 | main/src/com/vlaaad/dice/game/actions/imp/RestrictUseAbilities.java | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vlaaad.dice.game.actions.imp;
import com.vlaaad.common.util.Function;
import com.vlaaad.common.util.MapHelper;
import com.vlaaad.common.util.Numbers;
import com.vlaaad.common.util.futures.Future;
import com.vlaaad.common.util.futures.IFuture;
import com.vlaaad.dice.game.actions.CreatureAction;
import com.vlaaad.dice.game.actions.results.IActionResult;
import com.vlaaad.dice.game.actions.results.imp.GiveExpResult;
import com.vlaaad.dice.game.actions.results.imp.RestrictUseAbilitiesResult;
import com.vlaaad.dice.game.actions.results.imp.SequenceResult;
import com.vlaaad.dice.game.config.abilities.Ability;
import com.vlaaad.dice.game.config.attributes.Attribute;
import com.vlaaad.dice.game.config.thesaurus.Thesaurus;
import com.vlaaad.dice.game.objects.Creature;
import com.vlaaad.dice.game.util.ExpHelper;
import com.vlaaad.dice.game.world.World;
import java.util.Map;
/**
* Created 17.04.14 by vlaaad
*/
public class RestrictUseAbilities extends CreatureAction {
private float radius;
private int turnCount;
public RestrictUseAbilities(Ability owner) {
super(owner);
}
@Override protected void doInit(Object setup) {
Map map = (Map) setup;
//{radius: 6, turns: 8}
radius = MapHelper.get(map, "radius", Numbers.ONE).floatValue();
turnCount = MapHelper.get(map, "turns", Numbers.ONE).intValue();
}
@Override public void fillDescriptionParams(Thesaurus.Params params, Creature creature) {
params.with("turns", String.valueOf(turnCount));
params.with("radius", String.valueOf((int) radius));
}
@Override public IFuture<? extends IActionResult> apply(final Creature creature, World world) {
return withCreature(creature, creatures(creature, new Function<Creature, Boolean>() {
@Override public Boolean apply(Creature that) {
return creature.inRelation(Creature.CreatureRelation.enemy, that) && that.get(Attribute.canUseProfessionAbilities);
}
}, radius), new Function<Creature, IFuture<? extends IActionResult>>() {
@Override public IFuture<? extends IActionResult> apply(Creature target) {
return Future.completed(new SequenceResult(
new RestrictUseAbilitiesResult(owner, creature, target, turnCount),
new GiveExpResult(creature, ExpHelper.MIN_EXP)
));
}
});
}
}
| 412 | 0.604134 | 1 | 0.604134 | game-dev | MEDIA | 0.760153 | game-dev | 0.971124 | 1 | 0.971124 |
jinglikeblue/ZeroGameKit | 1,273 | Assets/Zero/Scripts/Patterns/BaseModuleGroup.cs | using System;
using System.Reflection;
namespace Zero
{
/// <summary>
/// 模块组基类
/// </summary>
public abstract class BaseModuleGroup : IDisposable
{
protected BaseModuleGroup()
{
InitModules();
}
~BaseModuleGroup()
{
DisposeModules();
}
public void Dispose()
{
DisposeModules();
}
void InitModules()
{
PropertyInfo[] properties = GetType().GetProperties();
foreach (PropertyInfo v in properties)
{
if(v.GetValue(this) == null)
{
v.SetValue(this, Activator.CreateInstance(v.PropertyType));
}
}
}
void DisposeModules()
{
PropertyInfo[] properties = GetType().GetProperties();
foreach(PropertyInfo v in properties)
{
var module = v.GetValue(this) as BaseModule;
module.Dispose();
v.SetValue(this, null);
}
}
protected void ResetModules()
{
DisposeModules();
InitModules();
}
}
} | 412 | 0.94074 | 1 | 0.94074 | game-dev | MEDIA | 0.867596 | game-dev | 0.961466 | 1 | 0.961466 |
apple/foundationdb | 2,935 | flowbench/BenchVersionVectorSerialization.cpp | /*
* BenchVersionVector.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2024 Apple Inc. and the FoundationDB project authors
*
* 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.
*/
#include "flow/Arena.h"
#include "benchmark/benchmark.h"
#include "fdbclient/VersionVector.h"
#include <cstdint>
struct TestContextArena {
Arena& _arena;
Arena& arena() { return _arena; }
ProtocolVersion protocolVersion() const { return g_network->protocolVersion(); }
uint8_t* allocate(size_t size) { return new (_arena) uint8_t[size]; }
};
static void bench_serializable_traits_version(benchmark::State& state) {
int tagCount = state.range(0);
Version version = 100000;
VersionVector serializedVV(version);
for (int i = 0; i < tagCount; i++) {
serializedVV.setVersion(Tag(0, i), ++version);
}
size_t size = 0;
VersionVector deserializedVV;
for (auto _ : state) {
Standalone<StringRef> msg = ObjectWriter::toValue(serializedVV, Unversioned());
// Capture the serialized buffer size.
state.PauseTiming();
size = msg.size();
state.ResumeTiming();
ObjectReader rd(msg.begin(), Unversioned());
rd.deserialize(deserializedVV);
}
ASSERT(serializedVV.compare(deserializedVV));
state.SetItemsProcessed(static_cast<long>(state.iterations()));
state.counters.insert({ { "Tags", tagCount }, { "Size", size } });
}
static void bench_dynamic_size_traits_version(benchmark::State& state) {
Arena arena;
TestContextArena context{ arena };
int tagCount = state.range(0);
Version version = 100000;
VersionVector serializedVV(version);
for (int i = 0; i < tagCount; i++) {
serializedVV.setVersion(Tag(0, i), ++version);
}
size_t size = 0;
VersionVector deserializedVV;
for (auto _ : state) {
size = dynamic_size_traits<VersionVector>::size(serializedVV, context);
uint8_t* buf = context.allocate(size);
dynamic_size_traits<VersionVector>::save(buf, serializedVV, context);
dynamic_size_traits<VersionVector>::load(buf, size, deserializedVV, context);
}
ASSERT(serializedVV.compare(deserializedVV));
state.SetItemsProcessed(static_cast<long>(state.iterations()));
state.counters.insert({ { "Tags", tagCount }, { "Size", size } });
}
BENCHMARK(bench_serializable_traits_version)->Ranges({ { 1 << 4, 1 << 10 } })->ReportAggregatesOnly(true);
BENCHMARK(bench_dynamic_size_traits_version)->Ranges({ { 1 << 4, 1 << 10 } })->ReportAggregatesOnly(true);
| 412 | 0.942307 | 1 | 0.942307 | game-dev | MEDIA | 0.232325 | game-dev | 0.942876 | 1 | 0.942876 |
manisha-v/Unity3D | 2,057 | Part2 - 3D Object Intraction/Codes/Library/PackageCache/com.unity.ugui@1.0.0/Editor/EventSystem/EventSystemEditor.cs | using UnityEngine;
using UnityEngine.EventSystems;
namespace UnityEditor.EventSystems
{
[CustomEditor(typeof(EventSystem), true)]
/// <summary>
/// Custom Editor for the EventSystem Component.
/// Extend this class to write a custom editor for a component derived from EventSystem.
/// </summary>
public class EventSystemEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
var eventSystem = target as EventSystem;
if (eventSystem == null)
return;
if (eventSystem.GetComponent<BaseInputModule>() != null)
return;
// no input modules :(
if (GUILayout.Button("Add Default Input Modules"))
{
ObjectFactory.AddComponent<StandaloneInputModule>(eventSystem.gameObject);
Undo.RegisterCreatedObjectUndo(eventSystem.gameObject, "Add StandaloneInputModule");
}
}
public override bool HasPreviewGUI()
{
return Application.isPlaying;
}
private GUIStyle m_PreviewLabelStyle;
protected GUIStyle previewLabelStyle
{
get
{
if (m_PreviewLabelStyle == null)
{
m_PreviewLabelStyle = new GUIStyle("PreOverlayLabel")
{
richText = true,
alignment = TextAnchor.UpperLeft,
fontStyle = FontStyle.Normal
};
}
return m_PreviewLabelStyle;
}
}
public override bool RequiresConstantRepaint()
{
return Application.isPlaying;
}
public override void OnPreviewGUI(Rect rect, GUIStyle background)
{
var system = target as EventSystem;
if (system == null)
return;
GUI.Label(rect, system.ToString(), previewLabelStyle);
}
}
}
| 412 | 0.755383 | 1 | 0.755383 | game-dev | MEDIA | 0.925234 | game-dev | 0.784861 | 1 | 0.784861 |
amate/scrsndcpy | 43,939 | delayFrame/SDL/SDL_events.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_events.h
*
* Include file for SDL event handling.
*/
#ifndef SDL_events_h_
#define SDL_events_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_video.h"
#include "SDL_keyboard.h"
#include "SDL_mouse.h"
#include "SDL_joystick.h"
#include "SDL_gamecontroller.h"
#include "SDL_quit.h"
#include "SDL_gesture.h"
#include "SDL_touch.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* General keyboard/mouse state definitions */
#define SDL_RELEASED 0
#define SDL_PRESSED 1
/**
* The types of events that can be delivered.
*/
typedef enum
{
SDL_FIRSTEVENT = 0, /**< Unused (do not remove) */
/* Application events */
SDL_QUIT = 0x100, /**< User-requested quit */
/* These application events have special meaning on iOS, see README-ios.md for details */
SDL_APP_TERMINATING, /**< The application is being terminated by the OS
Called on iOS in applicationWillTerminate()
Called on Android in onDestroy()
*/
SDL_APP_LOWMEMORY, /**< The application is low on memory, free memory if possible.
Called on iOS in applicationDidReceiveMemoryWarning()
Called on Android in onLowMemory()
*/
SDL_APP_WILLENTERBACKGROUND, /**< The application is about to enter the background
Called on iOS in applicationWillResignActive()
Called on Android in onPause()
*/
SDL_APP_DIDENTERBACKGROUND, /**< The application did enter the background and may not get CPU for some time
Called on iOS in applicationDidEnterBackground()
Called on Android in onPause()
*/
SDL_APP_WILLENTERFOREGROUND, /**< The application is about to enter the foreground
Called on iOS in applicationWillEnterForeground()
Called on Android in onResume()
*/
SDL_APP_DIDENTERFOREGROUND, /**< The application is now interactive
Called on iOS in applicationDidBecomeActive()
Called on Android in onResume()
*/
SDL_LOCALECHANGED, /**< The user's locale preferences have changed. */
/* Display events */
SDL_DISPLAYEVENT = 0x150, /**< Display state change */
/* Window events */
SDL_WINDOWEVENT = 0x200, /**< Window state change */
SDL_SYSWMEVENT, /**< System specific event */
/* Keyboard events */
SDL_KEYDOWN = 0x300, /**< Key pressed */
SDL_KEYUP, /**< Key released */
SDL_TEXTEDITING, /**< Keyboard text editing (composition) */
SDL_TEXTINPUT, /**< Keyboard text input */
SDL_KEYMAPCHANGED, /**< Keymap changed due to a system event such as an
input language or keyboard layout change.
*/
/* Mouse events */
SDL_MOUSEMOTION = 0x400, /**< Mouse moved */
SDL_MOUSEBUTTONDOWN, /**< Mouse button pressed */
SDL_MOUSEBUTTONUP, /**< Mouse button released */
SDL_MOUSEWHEEL, /**< Mouse wheel motion */
/* Joystick events */
SDL_JOYAXISMOTION = 0x600, /**< Joystick axis motion */
SDL_JOYBALLMOTION, /**< Joystick trackball motion */
SDL_JOYHATMOTION, /**< Joystick hat position change */
SDL_JOYBUTTONDOWN, /**< Joystick button pressed */
SDL_JOYBUTTONUP, /**< Joystick button released */
SDL_JOYDEVICEADDED, /**< A new joystick has been inserted into the system */
SDL_JOYDEVICEREMOVED, /**< An opened joystick has been removed */
/* Game controller events */
SDL_CONTROLLERAXISMOTION = 0x650, /**< Game controller axis motion */
SDL_CONTROLLERBUTTONDOWN, /**< Game controller button pressed */
SDL_CONTROLLERBUTTONUP, /**< Game controller button released */
SDL_CONTROLLERDEVICEADDED, /**< A new Game controller has been inserted into the system */
SDL_CONTROLLERDEVICEREMOVED, /**< An opened Game controller has been removed */
SDL_CONTROLLERDEVICEREMAPPED, /**< The controller mapping was updated */
SDL_CONTROLLERTOUCHPADDOWN, /**< Game controller touchpad was touched */
SDL_CONTROLLERTOUCHPADMOTION, /**< Game controller touchpad finger was moved */
SDL_CONTROLLERTOUCHPADUP, /**< Game controller touchpad finger was lifted */
SDL_CONTROLLERSENSORUPDATE, /**< Game controller sensor was updated */
/* Touch events */
SDL_FINGERDOWN = 0x700,
SDL_FINGERUP,
SDL_FINGERMOTION,
/* Gesture events */
SDL_DOLLARGESTURE = 0x800,
SDL_DOLLARRECORD,
SDL_MULTIGESTURE,
/* Clipboard events */
SDL_CLIPBOARDUPDATE = 0x900, /**< The clipboard changed */
/* Drag and drop events */
SDL_DROPFILE = 0x1000, /**< The system requests a file open */
SDL_DROPTEXT, /**< text/plain drag-and-drop event */
SDL_DROPBEGIN, /**< A new set of drops is beginning (NULL filename) */
SDL_DROPCOMPLETE, /**< Current set of drops is now complete (NULL filename) */
/* Audio hotplug events */
SDL_AUDIODEVICEADDED = 0x1100, /**< A new audio device is available */
SDL_AUDIODEVICEREMOVED, /**< An audio device has been removed. */
/* Sensor events */
SDL_SENSORUPDATE = 0x1200, /**< A sensor was updated */
/* Render events */
SDL_RENDER_TARGETS_RESET = 0x2000, /**< The render targets have been reset and their contents need to be updated */
SDL_RENDER_DEVICE_RESET, /**< The device has been reset and all textures need to be recreated */
/** Events ::SDL_USEREVENT through ::SDL_LASTEVENT are for your use,
* and should be allocated with SDL_RegisterEvents()
*/
SDL_USEREVENT = 0x8000,
/**
* This last event is only for bounding internal arrays
*/
SDL_LASTEVENT = 0xFFFF
} SDL_EventType;
/**
* \brief Fields shared by every event
*/
typedef struct SDL_CommonEvent
{
Uint32 type;
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
} SDL_CommonEvent;
/**
* \brief Display state change event data (event.display.*)
*/
typedef struct SDL_DisplayEvent
{
Uint32 type; /**< ::SDL_DISPLAYEVENT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 display; /**< The associated display index */
Uint8 event; /**< ::SDL_DisplayEventID */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint32 data1; /**< event dependent data */
} SDL_DisplayEvent;
/**
* \brief Window state change event data (event.window.*)
*/
typedef struct SDL_WindowEvent
{
Uint32 type; /**< ::SDL_WINDOWEVENT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The associated window */
Uint8 event; /**< ::SDL_WindowEventID */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint32 data1; /**< event dependent data */
Sint32 data2; /**< event dependent data */
} SDL_WindowEvent;
/**
* \brief Keyboard button event structure (event.key.*)
*/
typedef struct SDL_KeyboardEvent
{
Uint32 type; /**< ::SDL_KEYDOWN or ::SDL_KEYUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with keyboard focus, if any */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 repeat; /**< Non-zero if this is a key repeat */
Uint8 padding2;
Uint8 padding3;
SDL_Keysym keysym; /**< The key that was pressed or released */
} SDL_KeyboardEvent;
#define SDL_TEXTEDITINGEVENT_TEXT_SIZE (32)
/**
* \brief Keyboard text editing event structure (event.edit.*)
*/
typedef struct SDL_TextEditingEvent
{
Uint32 type; /**< ::SDL_TEXTEDITING */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with keyboard focus, if any */
char text[SDL_TEXTEDITINGEVENT_TEXT_SIZE]; /**< The editing text */
Sint32 start; /**< The start cursor of selected editing text */
Sint32 length; /**< The length of selected editing text */
} SDL_TextEditingEvent;
#define SDL_TEXTINPUTEVENT_TEXT_SIZE (32)
/**
* \brief Keyboard text input event structure (event.text.*)
*/
typedef struct SDL_TextInputEvent
{
Uint32 type; /**< ::SDL_TEXTINPUT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with keyboard focus, if any */
char text[SDL_TEXTINPUTEVENT_TEXT_SIZE]; /**< The input text */
} SDL_TextInputEvent;
/**
* \brief Mouse motion event structure (event.motion.*)
*/
typedef struct SDL_MouseMotionEvent
{
Uint32 type; /**< ::SDL_MOUSEMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with mouse focus, if any */
Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
Uint32 state; /**< The current button state */
Sint32 x; /**< X coordinate, relative to window */
Sint32 y; /**< Y coordinate, relative to window */
Sint32 xrel; /**< The relative motion in the X direction */
Sint32 yrel; /**< The relative motion in the Y direction */
} SDL_MouseMotionEvent;
/**
* \brief Mouse button event structure (event.button.*)
*/
typedef struct SDL_MouseButtonEvent
{
Uint32 type; /**< ::SDL_MOUSEBUTTONDOWN or ::SDL_MOUSEBUTTONUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with mouse focus, if any */
Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
Uint8 button; /**< The mouse button index */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 clicks; /**< 1 for single-click, 2 for double-click, etc. */
Uint8 padding1;
Sint32 x; /**< X coordinate, relative to window */
Sint32 y; /**< Y coordinate, relative to window */
} SDL_MouseButtonEvent;
/**
* \brief Mouse wheel event structure (event.wheel.*)
*/
typedef struct SDL_MouseWheelEvent
{
Uint32 type; /**< ::SDL_MOUSEWHEEL */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with mouse focus, if any */
Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
Sint32 x; /**< The amount scrolled horizontally, positive to the right and negative to the left */
Sint32 y; /**< The amount scrolled vertically, positive away from the user and negative toward the user */
Uint32 direction; /**< Set to one of the SDL_MOUSEWHEEL_* defines. When FLIPPED the values in X and Y will be opposite. Multiply by -1 to change them back */
} SDL_MouseWheelEvent;
/**
* \brief Joystick axis motion event structure (event.jaxis.*)
*/
typedef struct SDL_JoyAxisEvent
{
Uint32 type; /**< ::SDL_JOYAXISMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 axis; /**< The joystick axis index */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint16 value; /**< The axis value (range: -32768 to 32767) */
Uint16 padding4;
} SDL_JoyAxisEvent;
/**
* \brief Joystick trackball motion event structure (event.jball.*)
*/
typedef struct SDL_JoyBallEvent
{
Uint32 type; /**< ::SDL_JOYBALLMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 ball; /**< The joystick trackball index */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint16 xrel; /**< The relative motion in the X direction */
Sint16 yrel; /**< The relative motion in the Y direction */
} SDL_JoyBallEvent;
/**
* \brief Joystick hat position change event structure (event.jhat.*)
*/
typedef struct SDL_JoyHatEvent
{
Uint32 type; /**< ::SDL_JOYHATMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 hat; /**< The joystick hat index */
Uint8 value; /**< The hat position value.
* \sa ::SDL_HAT_LEFTUP ::SDL_HAT_UP ::SDL_HAT_RIGHTUP
* \sa ::SDL_HAT_LEFT ::SDL_HAT_CENTERED ::SDL_HAT_RIGHT
* \sa ::SDL_HAT_LEFTDOWN ::SDL_HAT_DOWN ::SDL_HAT_RIGHTDOWN
*
* Note that zero means the POV is centered.
*/
Uint8 padding1;
Uint8 padding2;
} SDL_JoyHatEvent;
/**
* \brief Joystick button event structure (event.jbutton.*)
*/
typedef struct SDL_JoyButtonEvent
{
Uint32 type; /**< ::SDL_JOYBUTTONDOWN or ::SDL_JOYBUTTONUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 button; /**< The joystick button index */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 padding1;
Uint8 padding2;
} SDL_JoyButtonEvent;
/**
* \brief Joystick device event structure (event.jdevice.*)
*/
typedef struct SDL_JoyDeviceEvent
{
Uint32 type; /**< ::SDL_JOYDEVICEADDED or ::SDL_JOYDEVICEREMOVED */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Sint32 which; /**< The joystick device index for the ADDED event, instance id for the REMOVED event */
} SDL_JoyDeviceEvent;
/**
* \brief Game controller axis motion event structure (event.caxis.*)
*/
typedef struct SDL_ControllerAxisEvent
{
Uint32 type; /**< ::SDL_CONTROLLERAXISMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 axis; /**< The controller axis (SDL_GameControllerAxis) */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint16 value; /**< The axis value (range: -32768 to 32767) */
Uint16 padding4;
} SDL_ControllerAxisEvent;
/**
* \brief Game controller button event structure (event.cbutton.*)
*/
typedef struct SDL_ControllerButtonEvent
{
Uint32 type; /**< ::SDL_CONTROLLERBUTTONDOWN or ::SDL_CONTROLLERBUTTONUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 button; /**< The controller button (SDL_GameControllerButton) */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 padding1;
Uint8 padding2;
} SDL_ControllerButtonEvent;
/**
* \brief Controller device event structure (event.cdevice.*)
*/
typedef struct SDL_ControllerDeviceEvent
{
Uint32 type; /**< ::SDL_CONTROLLERDEVICEADDED, ::SDL_CONTROLLERDEVICEREMOVED, or ::SDL_CONTROLLERDEVICEREMAPPED */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Sint32 which; /**< The joystick device index for the ADDED event, instance id for the REMOVED or REMAPPED event */
} SDL_ControllerDeviceEvent;
/**
* \brief Game controller touchpad event structure (event.ctouchpad.*)
*/
typedef struct SDL_ControllerTouchpadEvent
{
Uint32 type; /**< ::SDL_CONTROLLERTOUCHPADDOWN or ::SDL_CONTROLLERTOUCHPADMOTION or ::SDL_CONTROLLERTOUCHPADUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Sint32 touchpad; /**< The index of the touchpad */
Sint32 finger; /**< The index of the finger on the touchpad */
float x; /**< Normalized in the range 0...1 with 0 being on the left */
float y; /**< Normalized in the range 0...1 with 0 being at the top */
float pressure; /**< Normalized in the range 0...1 */
} SDL_ControllerTouchpadEvent;
/**
* \brief Game controller sensor event structure (event.csensor.*)
*/
typedef struct SDL_ControllerSensorEvent
{
Uint32 type; /**< ::SDL_CONTROLLERSENSORUPDATE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Sint32 sensor; /**< The type of the sensor, one of the values of ::SDL_SensorType */
float data[3]; /**< Up to 3 values from the sensor, as defined in SDL_sensor.h */
} SDL_ControllerSensorEvent;
/**
* \brief Audio device event structure (event.adevice.*)
*/
typedef struct SDL_AudioDeviceEvent
{
Uint32 type; /**< ::SDL_AUDIODEVICEADDED, or ::SDL_AUDIODEVICEREMOVED */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 which; /**< The audio device index for the ADDED event (valid until next SDL_GetNumAudioDevices() call), SDL_AudioDeviceID for the REMOVED event */
Uint8 iscapture; /**< zero if an output device, non-zero if a capture device. */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
} SDL_AudioDeviceEvent;
/**
* \brief Touch finger event structure (event.tfinger.*)
*/
typedef struct SDL_TouchFingerEvent
{
Uint32 type; /**< ::SDL_FINGERMOTION or ::SDL_FINGERDOWN or ::SDL_FINGERUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_TouchID touchId; /**< The touch device id */
SDL_FingerID fingerId;
float x; /**< Normalized in the range 0...1 */
float y; /**< Normalized in the range 0...1 */
float dx; /**< Normalized in the range -1...1 */
float dy; /**< Normalized in the range -1...1 */
float pressure; /**< Normalized in the range 0...1 */
Uint32 windowID; /**< The window underneath the finger, if any */
} SDL_TouchFingerEvent;
/**
* \brief Multiple Finger Gesture Event (event.mgesture.*)
*/
typedef struct SDL_MultiGestureEvent
{
Uint32 type; /**< ::SDL_MULTIGESTURE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_TouchID touchId; /**< The touch device id */
float dTheta;
float dDist;
float x;
float y;
Uint16 numFingers;
Uint16 padding;
} SDL_MultiGestureEvent;
/**
* \brief Dollar Gesture Event (event.dgesture.*)
*/
typedef struct SDL_DollarGestureEvent
{
Uint32 type; /**< ::SDL_DOLLARGESTURE or ::SDL_DOLLARRECORD */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_TouchID touchId; /**< The touch device id */
SDL_GestureID gestureId;
Uint32 numFingers;
float error;
float x; /**< Normalized center of gesture */
float y; /**< Normalized center of gesture */
} SDL_DollarGestureEvent;
/**
* \brief An event used to request a file open by the system (event.drop.*)
* This event is enabled by default, you can disable it with SDL_EventState().
* \note If this event is enabled, you must free the filename in the event.
*/
typedef struct SDL_DropEvent
{
Uint32 type; /**< ::SDL_DROPBEGIN or ::SDL_DROPFILE or ::SDL_DROPTEXT or ::SDL_DROPCOMPLETE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
char *file; /**< The file name, which should be freed with SDL_free(), is NULL on begin/complete */
Uint32 windowID; /**< The window that was dropped on, if any */
} SDL_DropEvent;
/**
* \brief Sensor event structure (event.sensor.*)
*/
typedef struct SDL_SensorEvent
{
Uint32 type; /**< ::SDL_SENSORUPDATE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Sint32 which; /**< The instance ID of the sensor */
float data[6]; /**< Up to 6 values from the sensor - additional values can be queried using SDL_SensorGetData() */
} SDL_SensorEvent;
/**
* \brief The "quit requested" event
*/
typedef struct SDL_QuitEvent
{
Uint32 type; /**< ::SDL_QUIT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
} SDL_QuitEvent;
/**
* \brief OS Specific event
*/
typedef struct SDL_OSEvent
{
Uint32 type; /**< ::SDL_QUIT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
} SDL_OSEvent;
/**
* \brief A user-defined event type (event.user.*)
*/
typedef struct SDL_UserEvent
{
Uint32 type; /**< ::SDL_USEREVENT through ::SDL_LASTEVENT-1 */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The associated window if any */
Sint32 code; /**< User defined event code */
void *data1; /**< User defined data pointer */
void *data2; /**< User defined data pointer */
} SDL_UserEvent;
struct SDL_SysWMmsg;
typedef struct SDL_SysWMmsg SDL_SysWMmsg;
/**
* \brief A video driver dependent system event (event.syswm.*)
* This event is disabled by default, you can enable it with SDL_EventState()
*
* \note If you want to use this event, you should include SDL_syswm.h.
*/
typedef struct SDL_SysWMEvent
{
Uint32 type; /**< ::SDL_SYSWMEVENT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_SysWMmsg *msg; /**< driver dependent data, defined in SDL_syswm.h */
} SDL_SysWMEvent;
/**
* \brief General event structure
*/
typedef union SDL_Event
{
Uint32 type; /**< Event type, shared with all events */
SDL_CommonEvent common; /**< Common event data */
SDL_DisplayEvent display; /**< Display event data */
SDL_WindowEvent window; /**< Window event data */
SDL_KeyboardEvent key; /**< Keyboard event data */
SDL_TextEditingEvent edit; /**< Text editing event data */
SDL_TextInputEvent text; /**< Text input event data */
SDL_MouseMotionEvent motion; /**< Mouse motion event data */
SDL_MouseButtonEvent button; /**< Mouse button event data */
SDL_MouseWheelEvent wheel; /**< Mouse wheel event data */
SDL_JoyAxisEvent jaxis; /**< Joystick axis event data */
SDL_JoyBallEvent jball; /**< Joystick ball event data */
SDL_JoyHatEvent jhat; /**< Joystick hat event data */
SDL_JoyButtonEvent jbutton; /**< Joystick button event data */
SDL_JoyDeviceEvent jdevice; /**< Joystick device change event data */
SDL_ControllerAxisEvent caxis; /**< Game Controller axis event data */
SDL_ControllerButtonEvent cbutton; /**< Game Controller button event data */
SDL_ControllerDeviceEvent cdevice; /**< Game Controller device event data */
SDL_ControllerTouchpadEvent ctouchpad; /**< Game Controller touchpad event data */
SDL_ControllerSensorEvent csensor; /**< Game Controller sensor event data */
SDL_AudioDeviceEvent adevice; /**< Audio device event data */
SDL_SensorEvent sensor; /**< Sensor event data */
SDL_QuitEvent quit; /**< Quit request event data */
SDL_UserEvent user; /**< Custom event data */
SDL_SysWMEvent syswm; /**< System dependent window event data */
SDL_TouchFingerEvent tfinger; /**< Touch finger event data */
SDL_MultiGestureEvent mgesture; /**< Gesture event data */
SDL_DollarGestureEvent dgesture; /**< Gesture event data */
SDL_DropEvent drop; /**< Drag and drop event data */
/* This is necessary for ABI compatibility between Visual C++ and GCC.
Visual C++ will respect the push pack pragma and use 52 bytes (size of
SDL_TextEditingEvent, the largest structure for 32-bit and 64-bit
architectures) for this union, and GCC will use the alignment of the
largest datatype within the union, which is 8 bytes on 64-bit
architectures.
So... we'll add padding to force the size to be 56 bytes for both.
On architectures where pointers are 16 bytes, this needs rounding up to
the next multiple of 16, 64, and on architectures where pointers are
even larger the size of SDL_UserEvent will dominate as being 3 pointers.
*/
Uint8 padding[sizeof(void *) <= 8 ? 56 : sizeof(void *) == 16 ? 64 : 3 * sizeof(void *)];
} SDL_Event;
/* Make sure we haven't broken binary compatibility */
SDL_COMPILE_TIME_ASSERT(SDL_Event, sizeof(SDL_Event) == sizeof(((SDL_Event *)NULL)->padding));
/* Function prototypes */
/**
* Pump the event loop, gathering events from the input devices.
*
* This function updates the event queue and internal input device state.
*
* **WARNING**: This should only be run in the thread that initialized the
* video subsystem, and for extra safety, you should consider only doing those
* things on the main thread in any case.
*
* SDL_PumpEvents() gathers all the pending input information from devices and
* places it in the event queue. Without calls to SDL_PumpEvents() no events
* would ever be placed on the queue. Often the need for calls to
* SDL_PumpEvents() is hidden from the user since SDL_PollEvent() and
* SDL_WaitEvent() implicitly call SDL_PumpEvents(). However, if you are not
* polling or waiting for events (e.g. you are filtering them), then you must
* call SDL_PumpEvents() to force an event queue update.
*
* \sa SDL_PollEvent
* \sa SDL_WaitEvent
*/
extern DECLSPEC void SDLCALL SDL_PumpEvents(void);
/* @{ */
typedef enum
{
SDL_ADDEVENT,
SDL_PEEKEVENT,
SDL_GETEVENT
} SDL_eventaction;
/**
* Check the event queue for messages and optionally return them.
*
* `action` may be any of the following:
*
* - `SDL_ADDEVENT`: up to `numevents` events will be added to the back of the
* event queue.
* - `SDL_PEEKEVENT`: `numevents` events at the front of the event queue,
* within the specified minimum and maximum type, will be returned to the
* caller and will _not_ be removed from the queue.
* - `SDL_GETEVENT`: up to `numevents` events at the front of the event queue,
* within the specified minimum and maximum type, will be returned to the
* caller and will be removed from the queue.
*
* You may have to call SDL_PumpEvents() before calling this function.
* Otherwise, the events may not be ready to be filtered when you call
* SDL_PeepEvents().
*
* This function is thread-safe.
*
* \param events destination buffer for the retrieved events
* \param numevents if action is SDL_ADDEVENT, the number of events to add
* back to the event queue; if action is SDL_PEEKEVENT or
* SDL_GETEVENT, the maximum number of events to retrieve
* \param action action to take; see [[#action|Remarks]] for details
* \param minType minimum value of the event type to be considered;
* SDL_FIRSTEVENT is a safe choice
* \param maxType maximum value of the event type to be considered;
* SDL_LASTEVENT is a safe choice
* \returns the number of events actually stored or a negative error code on
* failure; call SDL_GetError() for more information.
*
* \sa SDL_PollEvent
* \sa SDL_PumpEvents
* \sa SDL_PushEvent
*/
extern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event * events, int numevents,
SDL_eventaction action,
Uint32 minType, Uint32 maxType);
/* @} */
/**
* Check for the existence of a certain event type in the event queue.
*
* If you need to check for a range of event types, use SDL_HasEvents()
* instead.
*
* \param type the type of event to be queried; see SDL_EventType for details
* \returns SDL_TRUE if events matching `type` are present, or SDL_FALSE if
* events matching `type` are not present.
*
* \sa SDL_HasEvents
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasEvent(Uint32 type);
/**
* Check for the existence of certain event types in the event queue.
*
* If you need to check for a single event type, use SDL_HasEvent() instead.
*
* \param minType the low end of event type to be queried, inclusive; see
* SDL_EventType for details
* \param maxType the high end of event type to be queried, inclusive; see
* SDL_EventType for details
* \returns SDL_TRUE if events with type >= `minType` and <= `maxType` are
* present, or SDL_FALSE if not.
*
* \sa SDL_HasEvents
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasEvents(Uint32 minType, Uint32 maxType);
/**
* Clear events of a specific type from the event queue.
*
* This will unconditionally remove any events from the queue that match
* `type`. If you need to remove a range of event types, use SDL_FlushEvents()
* instead.
*
* It's also normal to just ignore events you don't care about in your event
* loop without calling this function.
*
* This function only affects currently queued events. If you want to make
* sure that all pending OS events are flushed, you can call SDL_PumpEvents()
* on the main thread immediately before the flush call.
*
* \param type the type of event to be cleared; see SDL_EventType for details
*
* \sa SDL_FlushEvents
*/
extern DECLSPEC void SDLCALL SDL_FlushEvent(Uint32 type);
/**
* Clear events of a range of types from the event queue.
*
* This will unconditionally remove any events from the queue that are in the
* range of `minType` to `maxType`, inclusive. If you need to remove a single
* event type, use SDL_FlushEvent() instead.
*
* It's also normal to just ignore events you don't care about in your event
* loop without calling this function.
*
* This function only affects currently queued events. If you want to make
* sure that all pending OS events are flushed, you can call SDL_PumpEvents()
* on the main thread immediately before the flush call.
*
* \param minType the low end of event type to be cleared, inclusive; see
* SDL_EventType for details
* \param maxType the high end of event type to be cleared, inclusive; see
* SDL_EventType for details
*
* \sa SDL_FlushEvent
*/
extern DECLSPEC void SDLCALL SDL_FlushEvents(Uint32 minType, Uint32 maxType);
/**
* Poll for currently pending events.
*
* If `event` is not NULL, the next event is removed from the queue and stored
* in the SDL_Event structure pointed to by `event`. The 1 returned refers to
* this event, immediately stored in the SDL Event structure -- not an event
* to follow.
*
* If `event` is NULL, it simply returns 1 if there is an event in the queue,
* but will not remove it from the queue.
*
* As this function implicitly calls SDL_PumpEvents(), you can only call this
* function in the thread that set the video mode.
*
* SDL_PollEvent() is the favored way of receiving system events since it can
* be done from the main loop and does not suspend the main loop while waiting
* on an event to be posted.
*
* The common practice is to fully process the event queue once every frame,
* usually as a first step before updating the game's state:
*
* ```c
* while (game_is_still_running) {
* SDL_Event event;
* while (SDL_PollEvent(&event)) { // poll until all events are handled!
* // decide what to do with this event.
* }
*
* // update game state, draw the current frame
* }
* ```
*
* \param event the SDL_Event structure to be filled with the next event from
* the queue, or NULL
* \returns 1 if there is a pending event or 0 if there are none available.
*
* \sa SDL_GetEventFilter
* \sa SDL_PeepEvents
* \sa SDL_PushEvent
* \sa SDL_SetEventFilter
* \sa SDL_WaitEvent
* \sa SDL_WaitEventTimeout
*/
extern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event * event);
/**
* Wait indefinitely for the next available event.
*
* If `event` is not NULL, the next event is removed from the queue and stored
* in the SDL_Event structure pointed to by `event`.
*
* As this function implicitly calls SDL_PumpEvents(), you can only call this
* function in the thread that initialized the video subsystem.
*
* \param event the SDL_Event structure to be filled in with the next event
* from the queue, or NULL
* \returns 1 on success or 0 if there was an error while waiting for events;
* call SDL_GetError() for more information.
*
* \sa SDL_PollEvent
* \sa SDL_PumpEvents
* \sa SDL_WaitEventTimeout
*/
extern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event * event);
/**
* Wait until the specified timeout (in milliseconds) for the next available
* event.
*
* If `event` is not NULL, the next event is removed from the queue and stored
* in the SDL_Event structure pointed to by `event`.
*
* As this function implicitly calls SDL_PumpEvents(), you can only call this
* function in the thread that initialized the video subsystem.
*
* \param event the SDL_Event structure to be filled in with the next event
* from the queue, or NULL
* \param timeout the maximum number of milliseconds to wait for the next
* available event
* \returns 1 on success or 0 if there was an error while waiting for events;
* call SDL_GetError() for more information. This also returns 0 if
* the timeout elapsed without an event arriving.
*
* \sa SDL_PollEvent
* \sa SDL_PumpEvents
* \sa SDL_WaitEvent
*/
extern DECLSPEC int SDLCALL SDL_WaitEventTimeout(SDL_Event * event,
int timeout);
/**
* Add an event to the event queue.
*
* The event queue can actually be used as a two way communication channel.
* Not only can events be read from the queue, but the user can also push
* their own events onto it. `event` is a pointer to the event structure you
* wish to push onto the queue. The event is copied into the queue, and the
* caller may dispose of the memory pointed to after SDL_PushEvent() returns.
*
* Note: Pushing device input events onto the queue doesn't modify the state
* of the device within SDL.
*
* This function is thread-safe, and can be called from other threads safely.
*
* Note: Events pushed onto the queue with SDL_PushEvent() get passed through
* the event filter but events added with SDL_PeepEvents() do not.
*
* For pushing application-specific events, please use SDL_RegisterEvents() to
* get an event type that does not conflict with other code that also wants
* its own custom event types.
*
* \param event the SDL_Event to be added to the queue
* \returns 1 on success, 0 if the event was filtered, or a negative error
* code on failure; call SDL_GetError() for more information. A
* common reason for error is the event queue being full.
*
* \sa SDL_PeepEvents
* \sa SDL_PollEvent
* \sa SDL_RegisterEvents
*/
extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event * event);
/**
* A function pointer used for callbacks that watch the event queue.
*
* \param userdata what was passed as `userdata` to SDL_SetEventFilter()
* or SDL_AddEventWatch, etc
* \param event the event that triggered the callback
* \returns 1 to permit event to be added to the queue, and 0 to disallow
* it. When used with SDL_AddEventWatch, the return value is ignored.
*
* \sa SDL_SetEventFilter
* \sa SDL_AddEventWatch
*/
typedef int (SDLCALL * SDL_EventFilter) (void *userdata, SDL_Event * event);
/**
* Set up a filter to process all events before they change internal state and
* are posted to the internal event queue.
*
* If the filter function returns 1 when called, then the event will be added
* to the internal queue. If it returns 0, then the event will be dropped from
* the queue, but the internal state will still be updated. This allows
* selective filtering of dynamically arriving events.
*
* **WARNING**: Be very careful of what you do in the event filter function,
* as it may run in a different thread!
*
* On platforms that support it, if the quit event is generated by an
* interrupt signal (e.g. pressing Ctrl-C), it will be delivered to the
* application at the next event poll.
*
* There is one caveat when dealing with the ::SDL_QuitEvent event type. The
* event filter is only called when the window manager desires to close the
* application window. If the event filter returns 1, then the window will be
* closed, otherwise the window will remain open if possible.
*
* Note: Disabled events never make it to the event filter function; see
* SDL_EventState().
*
* Note: If you just want to inspect events without filtering, you should use
* SDL_AddEventWatch() instead.
*
* Note: Events pushed onto the queue with SDL_PushEvent() get passed through
* the event filter, but events pushed onto the queue with SDL_PeepEvents() do
* not.
*
* \param filter An SDL_EventFilter function to call when an event happens
* \param userdata a pointer that is passed to `filter`
*
* \sa SDL_AddEventWatch
* \sa SDL_EventState
* \sa SDL_GetEventFilter
* \sa SDL_PeepEvents
* \sa SDL_PushEvent
*/
extern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter,
void *userdata);
/**
* Query the current event filter.
*
* This function can be used to "chain" filters, by saving the existing filter
* before replacing it with a function that will call that saved filter.
*
* \param filter the current callback function will be stored here
* \param userdata the pointer that is passed to the current event filter will
* be stored here
* \returns SDL_TRUE on success or SDL_FALSE if there is no event filter set.
*
* \sa SDL_SetEventFilter
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GetEventFilter(SDL_EventFilter * filter,
void **userdata);
/**
* Add a callback to be triggered when an event is added to the event queue.
*
* `filter` will be called when an event happens, and its return value is
* ignored.
*
* **WARNING**: Be very careful of what you do in the event filter function,
* as it may run in a different thread!
*
* If the quit event is generated by a signal (e.g. SIGINT), it will bypass
* the internal queue and be delivered to the watch callback immediately, and
* arrive at the next event poll.
*
* Note: the callback is called for events posted by the user through
* SDL_PushEvent(), but not for disabled events, nor for events by a filter
* callback set with SDL_SetEventFilter(), nor for events posted by the user
* through SDL_PeepEvents().
*
* \param filter an SDL_EventFilter function to call when an event happens.
* \param userdata a pointer that is passed to `filter`
*
* \sa SDL_DelEventWatch
* \sa SDL_SetEventFilter
*/
extern DECLSPEC void SDLCALL SDL_AddEventWatch(SDL_EventFilter filter,
void *userdata);
/**
* Remove an event watch callback added with SDL_AddEventWatch().
*
* This function takes the same input as SDL_AddEventWatch() to identify and
* delete the corresponding callback.
*
* \param filter the function originally passed to SDL_AddEventWatch()
* \param userdata the pointer originally passed to SDL_AddEventWatch()
*
* \sa SDL_AddEventWatch
*/
extern DECLSPEC void SDLCALL SDL_DelEventWatch(SDL_EventFilter filter,
void *userdata);
/**
* Run a specific filter function on the current event queue, removing any
* events for which the filter returns 0.
*
* See SDL_SetEventFilter() for more information. Unlike SDL_SetEventFilter(),
* this function does not change the filter permanently, it only uses the
* supplied filter until this function returns.
*
* \param filter the SDL_EventFilter function to call when an event happens
* \param userdata a pointer that is passed to `filter`
*
* \sa SDL_GetEventFilter
* \sa SDL_SetEventFilter
*/
extern DECLSPEC void SDLCALL SDL_FilterEvents(SDL_EventFilter filter,
void *userdata);
/* @{ */
#define SDL_QUERY -1
#define SDL_IGNORE 0
#define SDL_DISABLE 0
#define SDL_ENABLE 1
/**
* Set the state of processing events by type.
*
* `state` may be any of the following:
*
* - `SDL_QUERY`: returns the current processing state of the specified event
* - `SDL_IGNORE` (aka `SDL_DISABLE`): the event will automatically be dropped
* from the event queue and will not be filtered
* - `SDL_ENABLE`: the event will be processed normally
*
* \param type the type of event; see SDL_EventType for details
* \param state how to process the event
* \returns `SDL_DISABLE` or `SDL_ENABLE`, representing the processing state
* of the event before this function makes any changes to it.
*
* \sa SDL_GetEventState
*/
extern DECLSPEC Uint8 SDLCALL SDL_EventState(Uint32 type, int state);
/* @} */
#define SDL_GetEventState(type) SDL_EventState(type, SDL_QUERY)
/**
* Allocate a set of user-defined events, and return the beginning event
* number for that set of events.
*
* Calling this function with `numevents` <= 0 is an error and will return
* (Uint32)-1.
*
* Note, (Uint32)-1 means the maximum unsigned 32-bit integer value (or
* 0xFFFFFFFF), but is clearer to write.
*
* \param numevents the number of events to be allocated
* \returns the beginning event number, or (Uint32)-1 if there are not enough
* user-defined events left.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_PushEvent
*/
extern DECLSPEC Uint32 SDLCALL SDL_RegisterEvents(int numevents);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_events_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.771479 | 1 | 0.771479 | game-dev | MEDIA | 0.693307 | game-dev | 0.586088 | 1 | 0.586088 |
MATTYOneInc/AionEncomBase_Java8 | 1,669 | AL-Game/src/com/aionemu/gameserver/world/geo/DummyGeoMap.java | /*
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.world.geo;
import com.aionemu.gameserver.geoEngine.math.Vector3f;
import com.aionemu.gameserver.geoEngine.models.GeoMap;
import com.aionemu.gameserver.geoEngine.scene.Spatial;
/**
* @author ATracer
*/
public class DummyGeoMap extends GeoMap {
public DummyGeoMap(String name, int worldSize) {
super(name, worldSize);
}
@Override
public final float getZ(float x, float y, float z, int instanceId) {
return z;
}
@Override
public final boolean canSee(float x, float y, float z, float targetX, float targetY, float targetZ, float limit,
int instanceId) {
return true;
}
@Override
public Vector3f getClosestCollision(float x, float y, float z, float targetX, float targetY, float targetZ,
boolean changeDirction, boolean fly, int instanceId, byte intentions) {
return new Vector3f(targetX, targetY, targetZ);
}
@Override
public void setDoorState(int instanceId, String name, boolean state) {
}
@Override
public int attachChild(Spatial child) {
return 0;
}
} | 412 | 0.582547 | 1 | 0.582547 | game-dev | MEDIA | 0.972754 | game-dev | 0.575439 | 1 | 0.575439 |
evemuproject/evemu_server | 35,704 | src/eve-server/system/cosmicMgrs/DungeonMgr.cpp |
/**
* @name DungeonMgr.cpp
* Dungeon management system for EVEmu
*
* @Author: Allan
* @date: 12 December 2015
* @updated: 27 August 2017
*/
#include "eve-server.h"
#include "EVEServerConfig.h"
#include "PyServiceMgr.h"
#include "StaticDataMgr.h"
#include "system/SystemBubble.h"
#include "system/cosmicMgrs/AnomalyMgr.h"
#include "system/cosmicMgrs/BeltMgr.h"
#include "system/cosmicMgrs/DungeonMgr.h"
#include "system/cosmicMgrs/SpawnMgr.h"
DungeonDataMgr::DungeonDataMgr()
{
m_dungeonID = DUNGEON_ID;
}
int DungeonDataMgr::Initialize()
{
// for now, we are deleting all saved dungeons on startup. will fix this later as system matures.
ManagerDB::ClearDungeons();
Populate();
sLog.Blue(" DungeonDataMgr", "Dungeon Data Manager Initialized.");
return 1;
}
void DungeonDataMgr::Populate()
{
double start = GetTimeMSeconds();
DBQueryResult* res = new DBQueryResult();
DBResultRow row;
ManagerDB::GetDunTemplates(*res);
while (res->GetRow(row)) {
// SELECT dunTemplateID, dunTemplateName, dunEntryID, dunSpawnID, dunRoomID FROM dunTemplates
Dungeon::Template dtemplates = Dungeon::Template();
dtemplates.dunName = row.GetText(1);
dtemplates.dunRoomID = row.GetInt(4);
dtemplates.dunEntryID = row.GetInt(2);
dtemplates.dunSpawnClass = row.GetInt(3);
templates.emplace(row.GetInt(0), dtemplates);
}
//res->Reset();
ManagerDB::GetDunRoomData(*res);
while (res->GetRow(row)) {
// SELECT dunRoomID, dunGroupID, xpos, ypos, zpos FROM dunRoomData
Dungeon::RoomData drooms = Dungeon::RoomData();
drooms.dunGroupID = row.GetInt(1);
drooms.x = row.GetInt(2);
drooms.y = row.GetInt(3);
drooms.z = row.GetInt(4);
rooms.emplace(row.GetInt(0), drooms);
}
//res->Reset();
ManagerDB::GetDunGroupData(*res);
while (res->GetRow(row)) {
// SELECT d.dunGroupID, d.itemTypeID, d.itemGroupID, t.typeName, t.groupID, g.categoryID, t.radius, d.xpos, d.ypos, d.zpos FROM dunGroupData
Dungeon::GroupData dgroups = Dungeon::GroupData();
dgroups.typeID = row.GetInt(1);
dgroups.typeName = row.GetText(3);
dgroups.typeGrpID = row.GetInt(4);
dgroups.typeCatID = row.GetInt(5);
dgroups.radius = row.GetInt(6);
dgroups.x = row.GetInt(7);
dgroups.y = row.GetInt(8);
dgroups.z = row.GetInt(9);
groups.emplace(row.GetInt(0), dgroups);
}
//res->Reset();
ManagerDB::GetDunEntryData(*res);
while (res->GetRow(row)) {
//SELECT dunEntryID, xpos, ypos, zpos FROM dunEntryData
Dungeon::EntryData dentry = Dungeon::EntryData();
dentry.x = row.GetInt(1);
dentry.y = row.GetInt(2);
dentry.z = row.GetInt(3);
entrys.emplace(row.GetInt(0), dentry);
}
/* not ready yet
//res->Reset();
ManagerDB::GetDunSpawnInfo(*res);
while (res->GetRow(row)) {
//SELECT dunRoomSpawnID, dunRoomSpawnType, xpos, ypos, zpos
Dungeon::RoomSpawnInfo spawn = Dungeon::RoomSpawnInfo();
spawn.dunRoomSpawnID = row.GetInt(0);
spawn.dunRoomSpawnType = row.GetInt(1);
spawn.x = row.GetInt(2);
spawn.y = row.GetInt(3);
spawn.z = row.GetInt(4);
groups.emplace(spawn.dunRoomSpawnID, spawn);
} */
// sort/save template room/group data to avoid compilation later?
//cleanup
SafeDelete(res);
//sLog.Cyan(" DungeonDataMgr", "%u rooms in %u buckets and %u groups in %u buckets for %u dungeon templates loaded in %.3fms.",\
rooms.size(), rooms.bucket_count(), groups.size(), groups.bucket_count(), templates.size(), (GetTimeMSeconds() - start));
sLog.Cyan(" DungeonDataMgr", "%u entrys, %u rooms and %u groups for %u dungeon templates loaded in %.3fms.",\
entrys.size(), rooms.size(), groups.size(), templates.size(), (GetTimeMSeconds() - start));
}
void DungeonDataMgr::AddDungeon(Dungeon::ActiveData& dungeon)
{
activeDungeons.emplace(dungeon.systemID, dungeon);
_log(COSMIC_MGR__DEBUG, "Added Dungeon %u (%u) in systemID %u to active dungeon list.", dungeon.dunItemID, dungeon.dunTemplateID, dungeon.systemID);
//ManagerDB::SaveActiveDungeon(dungeon);
}
void DungeonDataMgr::GetDungeons(std::vector<Dungeon::ActiveData>& dunList)
{
for (auto cur : activeDungeons)
dunList.push_back(cur.second);
}
bool DungeonDataMgr::GetTemplate(uint32 templateID, Dungeon::Template& dTemplate) {
std::map<uint32, Dungeon::Template>::iterator itr = templates.find(templateID);
if (itr == templates.end()) {
_log(COSMIC_MGR__ERROR, "DungeonDataMgr - templateID %u not found.", templateID);
return false;
}
dTemplate = itr->second;
return true;
}
const char* DungeonDataMgr::GetDungeonType(int8 typeID)
{
switch (typeID) {
case Dungeon::Type::Mission: return "Mission";
case Dungeon::Type::Gravimetric: return "Gravimetric";
case Dungeon::Type::Magnetometric: return "Magnetometric";
case Dungeon::Type::Radar: return "Radar";
case Dungeon::Type::Ladar: return "Ladar";
case Dungeon::Type::Rated: return "Rated";
case Dungeon::Type::Anomaly: return "Anomaly";
case Dungeon::Type::Unrated: return "Unrated";
case Dungeon::Type::Escalation: return "Escalation";
case Dungeon::Type::Wormhole: return "Wormhole";
default: return "Invalid";
}
}
DungeonMgr::DungeonMgr(SystemManager* mgr, PyServiceMgr& svc)
: m_system(mgr),
m_services(svc),
m_anomMgr(nullptr),
m_spawnMgr(nullptr)
{
m_initalized = false;
m_anomalyItems.clear();
}
DungeonMgr::~DungeonMgr()
{
//for now we're deleting everything till i can write proper item handling code
/* this is not needed as all items are temp at this time.
for (auto cur : m_dungeonList)
for (auto item : cur.second)
InventoryDB::DeleteItem(item);
*/
}
bool DungeonMgr::Init(AnomalyMgr* anomMgr, SpawnMgr* spawnMgr)
{
m_anomMgr = anomMgr;
m_spawnMgr = spawnMgr;
if (m_anomMgr == nullptr) {
_log(COSMIC_MGR__ERROR, "System Init Fault. anomMgr == nullptr. Not Initializing Dungeon Manager for %s(%u)", m_system->GetName(), m_system->GetID());
return m_initalized;
}
if (m_spawnMgr == nullptr) {
_log(COSMIC_MGR__ERROR, "System Init Fault. spawnMgr == nullptr. Not Initializing Dungeon Manager for %s(%u)", m_system->GetName(), m_system->GetID());
return m_initalized;
}
if (!sConfig.cosmic.DungeonEnabled){
_log(COSMIC_MGR__MESSAGE, "Dungeon System Disabled. Not Initializing Dungeon Manager for %s(%u)", m_system->GetName(), m_system->GetID());
return true;
}
if (!sConfig.cosmic.AnomalyEnabled) {
_log(COSMIC_MGR__MESSAGE, "Anomaly System Disabled. Not Initializing Dungeon Manager for %s(%u)", m_system->GetName(), m_system->GetID());
return true;
}
if (!sConfig.npc.RoamingSpawns and !sConfig.npc.StaticSpawns) {
_log(COSMIC_MGR__MESSAGE, "SpawnMgr Disabled. Not Initializing Dungeon Manager for %s(%u)", m_system->GetName(), m_system->GetID());
return true;
}
if (!sConfig.cosmic.BeltEnabled) {
_log(COSMIC_MGR__MESSAGE, "BeltMgr Disabled. Not Initializing Dungeon Manager for %s(%u)", m_system->GetName(), m_system->GetID());
return true;
}
m_spawnMgr->SetDungMgr(this);
Load();
_log(COSMIC_MGR__MESSAGE, "DungeonMgr Initialized for %s(%u)", m_system->GetName(), m_system->GetID());
m_initalized = true;
return m_initalized;
}
// called from systemMgr
void DungeonMgr::Process() {
if (!m_initalized)
return;
// this is used to remove empty/completed/timed-out dungons....eventually
}
void DungeonMgr::Load()
{
std::vector<Dungeon::ActiveData> dungeons;
ManagerDB::GetSavedDungeons(m_system->GetID(), dungeons);
/** @todo this will need more work as the system matures...
for(auto dungeon : dungeons) {
InventoryItemRef dungeonRef = m_system->itemFactory()->GetItem( dungeon.dungeonID );
if( !dungeonRef ) {
_log(COSMIC_MGR__WARNING, "DungeonMgr::Load() - Unable to spawn dungeon item #%u:'%s' of type %u.", dungeon.dungeonID, dungeon.typeID);
continue;
}
AsteroidSE* asteroidObj = new AsteroidSE( dungeonRef, *(m_system->GetServiceMgr()), m_system );
if( !asteroidObj ) {
_log(COSMIC_MGR__WARNING, "DungeonMgr::Load() - Unable to spawn dungeon entity #%u:'%s' of type %u.", dungeon.dungeonID, dungeon.typeID);
continue;
}
_log(COSMIC_MGR__TRACE, "DungeonMgr::Load() - Loaded dungeon %u, type %u for %s(%u)", dungeon.dungeonID, dungeon.typeID, m_system->GetName(), m_systemID );
sBubbleMgr.Add( asteroidObj );
sDunDataMgr.AddDungeon(std::pair<uint32, Dungeon::ActiveData*>(m_system->GetID(), dungeon));
} */
}
bool DungeonMgr::Create(uint32 templateID, CosmicSignature& sig)
{
Dungeon::Template dTemplate = Dungeon::Template();
if (!sDunDataMgr.GetTemplate(templateID, dTemplate))
return false;
if (dTemplate.dunRoomID == 0) {
_log(COSMIC_MGR__ERROR, "DungeonMgr::Create() - roomID is 0 for template %u.", templateID);
return false;
}
if ((sig.dungeonType < Dungeon::Type::Wormhole) // 1 - 5
or (sig.ownerID == factionRogueDrones)) {
sig.sigName = dTemplate.dunName;
} else {
sig.sigName = sDataMgr.GetFactionName(sig.ownerID);
sig.sigName += dTemplate.dunName;
}
// spawn and save actual anomaly item // typeID, ownerID, locationID, flag, name, &_position
/** @todo make specific table for dungeon items: dungeonID, systemID, entity shit if we decide to keep them. */
/*
std::string info = "Dungeon: ";
info += sig.sigName;
info += " in ";
info += m_system->GetName();
*/
ItemData iData(sig.sigTypeID, sig.ownerID, sig.systemID, flagNone, sig.sigName.c_str(), sig.position/*, info*/);
InventoryItemRef iRef = InventoryItem::SpawnItem(sItemFactory.GetNextTempID(), iData);
if (iRef.get() == nullptr) // make error and exit
return false;
CelestialSE* cSE = new CelestialSE(iRef, *(m_system->GetServiceMgr()), m_system);
if (cSE == nullptr)
return false; // we'll get over it.
// dont add signal thru sysMgr. signal is added when this returns to anomMgr
m_system->AddEntity(cSE, false);
sig.sigItemID = iRef->itemID();
sig.bubbleID = cSE->SysBubble()->GetID();
_log(COSMIC_MGR__TRACE, "DungeonMgr::Create() - %s using templateID %u and roomID %i", sig.sigName.c_str(), templateID, dTemplate.dunRoomID);
/* do we need this? persistent dungeons?
if ((typeID == 1) or (typeID == 8) or (typeID == 9) or (typeID == 10)) {
// setup data to save active dungeon
ActiveDungeon dungeon = ActiveDungeon();
dungeon.dunExpiryTime = Win32TimeNow() + (EvE::Time::Day * 3); // 3 days - i know this isnt right. just for testing.
dungeon.dunTemplateID = templateID;
dungeon.dunItemID = sig.sigItemID;
dungeon.state = 0; //dunType here.
dungeon.systemID = sig.systemID;
dungeon.x = sig.x;
dungeon.y = sig.y;
dungeon.z = sig.z;
sDunDataMgr.AddDungeon(dungeon);
} */
/* roomID format. ABCD
* A = roomtype - 1:combat, 2:rescue, 3:capture, 4:salvage, 5:relic, 6:hacking, 7:roids, 8:clouds, 9:recon
* B = level - 0:none, 1:f, 2:d, 3:c, 4:af/ad, 5:bc, 6:ac, 7:bs, 8:abs, 9:hard
* C = amount/size - 0:code defined 1:small(1-5), 2:medium(2-10), 3:large(5-25), 4:enormous(10-50), 5:colossal(20-100), 6-9:ice
* D = faction - 0=drone, 1:Serpentis, 2:Angel, 3:Blood, 4:Guristas, 5:Sansha, 6:Amarr, 7:Caldari, 8:Gallente, 9:Minmatar
* D = sublevel - 0:gas, 1-5:ore, 6-9:ice
*/
int16 x=0, y=0, z=0;
Dungeon::GroupData grp;
auto roomRange = sDunDataMgr.rooms.equal_range(dTemplate.dunRoomID);
for (auto it = roomRange.first; it != roomRange.second; ++it) {
x = it->second.x;
y = it->second.y;
z = it->second.z;
auto groupRange = sDunDataMgr.groups.equal_range(it->second.dunGroupID);
for (auto it2 = groupRange.first; it2 != groupRange.second; ++it2) {
grp.typeCatID = it2->second.typeCatID;
grp.typeGrpID = it2->second.typeGrpID;
grp.typeName = it2->second.typeName;
grp.typeID = it2->second.typeID;
grp.x = (x + it2->second.x);
grp.y = (y + it2->second.y);
grp.z = (z + it2->second.z);
m_anomalyItems.push_back(grp);
}
}
if (sig.dungeonType == Dungeon::Type::Gravimetric) {
// dungeon template for grav sites just give 'extra' roid data
int16 size = m_anomalyItems.size();
uint8 divisor = 10;
if (size < 100)
divisor = 100;
float chance = (100.0 /size) /divisor;
if (chance < 0.01)
chance = 0.01;
std::unordered_multimap<float, uint16> roidTypes;
for (auto cur : m_anomalyItems)
roidTypes.emplace(chance, cur.typeID);
m_system->GetBeltMgr()->Create(sig, roidTypes);
// clear out extra roids data to continue with room deco
m_anomalyItems.clear();
} else {
// other types have a chance for roids.
}
// create deco items for this dungeon
CreateDeco(templateID, sig);
// item spawning method
uint32 systemID = m_system->GetID();
std::vector<uint32> items;
GPoint pos2(NULL_ORIGIN);
std::vector<Dungeon::GroupData>::iterator itr = m_anomalyItems.begin(), end = m_anomalyItems.end();
while (itr != end) {
pos2.x = sig.position.x + itr->x;
pos2.y = sig.position.y + itr->y;
pos2.z = sig.position.z + itr->z;
// typeID, ownerID, locationID, flag, name, &_position
ItemData dData(itr->typeID, sig.ownerID, systemID, flagNone, itr->typeName.c_str(), pos2);
iRef = InventoryItem::SpawnItem(sItemFactory.GetNextTempID(), dData);
if (iRef.get() == nullptr) // we'll survive...
continue;
// should ALL of these be CelestialSEs?
cSE = new CelestialSE(iRef, *(m_system->GetServiceMgr()), m_system);
m_system->AddEntity(cSE, false);
items.push_back(iRef->itemID());
++itr;
}
if (dTemplate.dunSpawnClass > 0)
m_spawnMgr->DoSpawnForAnomaly(sBubbleMgr.FindBubble(m_system->GetID(), sig.position), dTemplate.dunSpawnClass);
_log(COSMIC_MGR__TRACE, "DungeonMgr::Create() - dungeonID %u created for %s with %u items.", \
sig.sigItemID, sig.sigName.c_str(), m_anomalyItems.size());
m_anomalyItems.clear();
if (!items.empty())
m_dungeonList.emplace(sig.sigItemID, items);
return true;
}
/*
* Band 1/5 1/10 1/15 1/20 1/25 1/40 1/45 1/60 1/80
* Percentage 20.0% 10.0% 6.67% 5.0% 4.0% 2.5% 2.22% 1.67% 1.25%
*/
/* templateID format. ABCDE
* A = site - 1:mission, 2:grav, 3:mag, 4:radar, 5:ladar, 6:ded, 7:anomaly, 8:unrated, 9:escalation
* B = sec - mission: 1-9 (incomplete); others - sysSec: 1=hi, 2=lo, 3=null, 4=mid;
* C = type - grav: ore 0-5, ice 6-9; anomaly: 1-5; mission: 1-9; mag: *see below*; ded: 1-8; ladar/radar: 1-8
* D = level - mission: 1-9; grav: ore 1-3, ice 0; mag: *see below*; radar: 1-norm; 2-digital(nullsec); ladar: 1; anomaly: 1-5
* E = faction - 0=code defined, 1=Serpentis, 2=Angel, 3=Blood, 4=Guristas, 5=Sansha, 6=Drones, 7=region sov, 8=region rat, 9=other
*
* NOTE: mag sites have multiple types and levels based on other variables.
* types are defined as relic(1), salvage(2), and drone(3), with salvage being dominant.
* for hisec and losec, levels are 1-8 for relic and salvage. there are no drone mag sites here
* for nullsec, relic site levels are 1-8, salvage site levels are 1-4, and drone site levels are 1-7
*
* NOTE: faction can only be 8 for grav and anomaly sites, unless drones (6). all others MUST use 1-6
*/
bool DungeonMgr::MakeDungeon(CosmicSignature& sig)
{
float secRating = m_system->GetSystemSecurityRating();
int8 sec = 1; // > 0.6
if (secRating < -0.2) {
sec = 3;
} else if (secRating < 0.2) {
sec = 4;
} else if (secRating < 0.6) {
sec = 2;
}
float level(1.0f);
int8 type(1);
// need to determine region sov, region rat or other here also
int8 faction(GetFaction(sig.ownerID));
using namespace Dungeon::Type;
switch (sig.dungeonType) {
case Gravimetric: { // 2
faction = 8; // region rat
// all roid types can spawn in grav sites.
level = MakeRandomFloat();
if (level < 0.1) {
level = 3;
} else if (level < 0.3) {
level = 2;
} else {
level = 1;
}
// sigStrength depends on roid types as well as trueSec
if (sec == 1) { // hi sec
sig.sigStrength = 0.2 /level; // 1/5 base
//sig.sigStrength = 0.0125; // testing 1/80
type = MakeRandomInt(0,5);
} else if (sec == 2) { // lo sec
sig.sigStrength = 0.1 /level; // 1/10 base
type = MakeRandomInt(0,3);
} else if (sec == 4) { // mid sec
sig.sigStrength = 0.0667 /level; // 1/15 base
type = MakeRandomInt(0,2);
} else { // null sec
sig.sigStrength = 0.05 /level; // 1/20 base
type = MakeRandomInt(0,2);
}
} break;
case Magnetometric: { // 3
level = MakeRandomFloat();
if (sec == 3) { // nullsec
if (level < 0.1) { // 10% to be drone site
level = 3;
type = MakeRandomInt(1,7);
sig.sigStrength = 0.0125; // 1/80
} else if (level < 0.3) { // 20% to be relic site
level = 1;
type = MakeRandomInt(1,8);
sig.sigStrength = 0.025; // 1/40
} else { // else salvage site
level = 1;
type = MakeRandomInt(1,4);
sig.sigStrength = 0.05; // 1/20
}
} else { // hi, mid and lo sec
type = MakeRandomInt(1,8);
if (level < 0.3) { // 20% to be relic site
level = 1;
sig.sigStrength = 0.05; // 1/20
} else {
level = 2;
sig.sigStrength = 0.1; // 1/10
}
}
if (level == 3) {
faction = 6; // drone
} else if (faction == 6) {
// lvls 1&2 cannot be drone. set to region pirate
faction = GetFaction(sDataMgr.GetRegionRatFaction(m_system->GetRegionID()));
}
} break;
case Radar: { // 4
// type 1, level 1 are covert research (ghost sites)
// level 2 are digital sites and region-specific (only in nullsec)
// both are incomplete and will be harder than reg sites.
type = MakeRandomInt(1,8);
if (sec == 1) {
sig.sigStrength = 0.1; // 1/10
if (type == 1) { // Covert Research
level = 1;
sig.sigStrength = 0.05; // 1/20
}
} else if (sec == 2) {
sig.sigStrength = 0.05; // 1/20
if (type == 1) { // Covert Research
level = 1;
sig.sigStrength = 0.025; // 1/40
}
} else if (sec == 3) {
sig.sigStrength = 0.025; // 1/40
if (faction == 0) { // this should not hit
level = 2;
sig.sigStrength = 0.0222; // 1/45
} else if (type == 1) { // Covert Research
level = 1;
sig.sigStrength = 0.0167; // 1/60
}
}
} break;
case Ladar: { // 5
faction = 0;
type = MakeRandomInt(1,8);
if (sec == 1) {
sig.sigStrength = 0.1; // 1/10
} else if (sec == 2) {
sig.sigStrength = 0.05; // 1/20
} else if (sec == 3) {
sig.sigStrength = 0.025; // 1/40
}
} break;
case Anomaly: { // 7
type = MakeRandomInt(1,5);
// if anomaly is non-drone, set template variables for types.
// looking over this again (years later) it dont make much sense.
// will have to look deeper when i have time.
if (faction != 6) {
faction = 8;
if (sec == 1) {
if (type == 1) {
level = GetRandLevel();
}
} else if (sec == 2) {
if (type == 2) {
level = GetRandLevel();
} else if (type == 4) {
level = GetRandLevel();
}
} else if (sec == 3) {
if (type == 1) {
level = GetRandLevel();
} else if (type == 3) {
level = GetRandLevel();
}
}
}
} break;
// yes, these will 'fall thru' to 'Unrated' here. this is on purpose
case Escalation: // 9
case Rated: { // 10
//sig.dungeonType = 9;
};
case Mission: { // 1
// not sure how im gonna do this one yet...make it unrated for now
sig.dungeonType = 8;
};
case Unrated: { // 8
if (faction == 6) {
type = MakeRandomInt(1,3);
} else {
faction = 0;
type = MakeRandomInt(1,5);
}
} break;
case 0:
default: {
sig.dungeonType = 7;
MakeDungeon(sig);
} break;
}
if (faction == 7) {
// faction is defined to be region sovereign holder.
// this hasnt been written yet, so default to region rats
faction = GetFaction(sDataMgr.GetRegionRatFaction(m_system->GetRegionID()));
}
uint32 templateID = (sig.dungeonType * 10000) + (sec * 1000) + (type * 100) + (level * 10) + faction;
_log(COSMIC_MGR__TRACE, "DungeonMgr::MakeDungeon() - Calling Create for type %s(%u) using templateID %u", \
sDunDataMgr.GetDungeonType(sig.dungeonType), sig.dungeonType, templateID);
return Create(templateID, sig);
}
int8 DungeonMgr::GetFaction(uint32 factionID)
{
switch (factionID) {
case factionAngel: return 2;
case factionSanshas: return 5;
case factionGuristas: return 4;
case factionSerpentis: return 1;
case factionBloodRaider: return 3;
case factionRogueDrones: return 6;
case 0: return 7;
// these are incomplete. set to default (region rat)
case factionAmarr:
case factionAmmatar:
case factionCaldari:
case factionGallente:
case factionMinmatar:
default:
return GetFaction(sDataMgr.GetRegionRatFaction(m_system->GetRegionID()));
}
}
int8 DungeonMgr::GetRandLevel()
{
double level = MakeRandomFloat();
_log(COSMIC_MGR__TRACE, "DungeonMgr::GetRandLevel() - level = %.2f", level);
if (level < 0.15) {
return 4;
} else if (level < 0.25) {
return 3;
} else if (level < 0.50) {
return 2;
} else {
return 1;
}
}
/*
struct CosmicSignature {
std::string sigID; // this is unique xxx-nnn id displayed in scanner
std::string sigName;
uint32 ownerID;
uint32 systemID;
uint32 sigItemID; // itemID of this entry
uint8 dungeonType;
uint16 sigTypeID;
uint16 sigGroupID;
uint16 scanGroupID;
uint16 scanAttributeID;
GPoint position;
};
*/
void DungeonMgr::CreateDeco(uint32 templateID, CosmicSignature& sig)
{
/** @todo this needs work for proper sizing of deco. */
/* templateID format. ABCDE
* A = site - 1:mission, 2:grav, 3:mag, 4:radar, 5:ladar, 6:ded, 7:anomaly, 8:unrated, 9:escalation
* B = sec - mission: 1-9 (incomplete); others - sysSec: 1=hi, 2=lo, 3=null, 4=mid;
* C = type - grav: ore 0-5, ice 6-9; anomaly: 1-5; mission: 1-9; mag: *see below*; ded: 1-8; ladar/radar: 1-8
* D = level - mission: 1-9; grav: ore 1-3, ice 0; mag: *see below*; radar: 1-norm; 2-digital(nullsec); ladar: 1; anomaly: 1-5
* E = faction - 0=code defined, 1=Serpentis, 2=Angel, 3=Blood, 4=Guristas, 5=Sansha, 6=Drones, 7=region sov, 8=region rat, 9=other
*
* NOTE: mag sites have multiple types and levels based on other variables.
* levels are defined as relic(1), salvage(2), and drone(3), with salvage being dominant.
* for hisec and losec, types are 1-8 for relic and salvage. there are no drone mag sites here
* for nullsec, relic site types are 1-8, salvage site types are 1-4, and drone site types are 1-7
*
* NOTE: faction can only be 8 for grav and anomaly sites, unless drones (6). all others MUST use 1-6
*/
// templateID = (sig.dungeonType *10000) + (sec *1000) + (type *100) + (level *10) + factionID;
uint8 factionID = templateID % 10;
uint8 level = templateID / 10 % 10;
uint8 type = templateID / 100 % 10;
//uint8 sec = templateID / 1000 % 10;
// create groupIDs for this dungeon, and add to vector
// NOTE: these are NOT invGroups here....
std::vector<uint16> groupVec;
groupVec.clear();
// all groups get the worthless mining types and misc deco items
groupVec.push_back(131); //misc roids
groupVec.push_back(132); //worthless mining types
groupVec.push_back(691); // misc
// add worthless shit to vector
AddDecoToVector(sig.dungeonType, templateID, groupVec);
// clear out vector before adding specific types
groupVec.clear();
using namespace Dungeon::Type;
switch (sig.dungeonType) {
case Mission: { //1
} break;
case Gravimetric: { //2
groupVec.push_back(130); //named roids
groupVec.push_back(160); //asteroid colony items
groupVec.push_back(620); // Starbase
groupVec.push_back(630); // Habitation
} break;
case Magnetometric: { //3
groupVec.push_back(620); // Starbase
groupVec.push_back(630); // Habitation
groupVec.push_back(640); // Stationary
groupVec.push_back(650); // Indestructible
groupVec.push_back(660); // Forcefield
groupVec.push_back(670); // Shipyard
groupVec.push_back(680); // Construction
groupVec.push_back(690); // Storage
} break;
case Radar: { //4
groupVec.push_back(130); //named roids
groupVec.push_back(160); //asteroid colony items
groupVec.push_back(630); // Habitation
groupVec.push_back(640); // Stationary
} break;
case Ladar: { //5
groupVec.push_back(160); //asteroid colony items
groupVec.push_back(670); // Shipyard
groupVec.push_back(680); // Construction
groupVec.push_back(690); // Storage
} break;
case Anomaly: //7
case Rated: { //10
groupVec.push_back(430); //lco misc
groupVec.push_back(431); //lco Habitation
groupVec.push_back(432); //lco drug labs
groupVec.push_back(433); //lco Starbase
groupVec.push_back(630); // Habitation
groupVec.push_back(640); // Stationary
groupVec.push_back(650); // Indestructible
} break;
case Unrated: { //8
groupVec.push_back(430); //lco misc
groupVec.push_back(431); //lco Habitation
groupVec.push_back(432); //lco drug labs
groupVec.push_back(433); //lco Starbase
} break;
case Escalation: { //9
groupVec.push_back(640); // Stationary
groupVec.push_back(650); // Indestructible
} break;
}
// add misc shit to vector
AddDecoToVector(sig.dungeonType, templateID, groupVec);
// clear out vector before adding specific faction types
groupVec.clear();
switch (sig.dungeonType) {
case Anomaly: //7
case Unrated: //8
case Escalation: //9
case Rated: { //10
switch (factionID) {
case 1: { //Serpentis
groupVec.push_back(401); //faction lco
groupVec.push_back(601); //faction base
} break;
case 2: { //Angel
groupVec.push_back(402); //faction lco
groupVec.push_back(602); //faction base
} break;
case 3: { //Blood
groupVec.push_back(403); //faction lco
groupVec.push_back(603); //faction base
} break;
case 4: { //Guristas
groupVec.push_back(404); //faction lco
groupVec.push_back(604); //faction base
} break;
case 5: { //Sansha
groupVec.push_back(405); //faction lco
groupVec.push_back(605); //faction base
} break;
case 6: { //Drones
groupVec.push_back(406); //faction lco
groupVec.push_back(606); //faction base
} break;
// make error for default or 0 here?
}
}
}
AddDecoToVector(sig.dungeonType, templateID, groupVec);
}
void DungeonMgr::AddDecoToVector(uint8 dunType, uint32 templateID, std::vector<uint16>& groupVec)
{
// templateID = (sig.dungeonType *10000) + (sec *1000) + (type *100) + (level *10) + factionID;
uint8 factionID = templateID % 10;
uint8 level = templateID / 10 % 10;
uint8 type = templateID / 100 % 10;
uint8 sec = templateID / 1000 % 10;
int8 step = 0;
uint16 count = 0, radius = 0, pos = 10000 * level;
double theta = 0;
// level is 0 to 9, system multiplier is 0.1 to 2.0 (x10 is 1-20)
level *= (m_system->GetSecValue() *10); // config variable here?
// set origLevel 0 to 18, rounding up
uint8 origLevel = ceil(level /10);
if (origLevel < 1)
origLevel = 1;
for (auto cur : groupVec) {
level = origLevel;
count = sDunDataMgr.groups.count(cur);
if (count < 1)
continue;
_log(COSMIC_MGR__DEBUG, "DungeonMgr::AddDecoToVector() - %s(%u): faction %u, group %u, type %u, level %u, count %u, baseLvl %u",\
sDunDataMgr.GetDungeonType(dunType), dunType, factionID, \
cur, type, level, count, origLevel);
auto groupRange = sDunDataMgr.groups.equal_range(cur);
auto it = groupRange.first;
double degreeSeparation = (250/level);
// make 1-20 random items in the anomaly based on system trusec
for (uint8 i=0; i < level; ++i) {
Dungeon::GroupData grp = Dungeon::GroupData();
step = MakeRandomInt(1,count);
std::advance(it,step); // this is some fancy shit here
grp.typeID = it->second.typeID;
grp.typeName = it->second.typeName;
grp.typeGrpID = it->second.typeGrpID;
grp.typeCatID = it->second.typeCatID;
// site size and item radius determine position
radius = it->second.radius;
//if (sig.dungeonType == Gravimetric) {
theta = EvE::Trig::Deg2Rad(degreeSeparation * i);
//theta = MakeRandomFloat(0, EvE::Trig::Pi);
grp.x = (radius + pos * std::cos(theta)) * (IsEven(MakeRandomInt(0,10)) ? -1 : 1);
grp.z = (radius + pos * std::sin(theta)) * -1;
/*
grp.y = MakeRandomFloat(-radius, radius);
} else if (IsEven(MakeRandomInt(0,10))) {
grp.x = (pos + it->second.x + (radius*2)) * (IsEven(MakeRandomInt(0,10)) ? -1 : 1);
grp.z = pos + it->second.z + radius;
} else {
grp.x = (pos + it->second.x + radius) * -1;
grp.z = (pos + it->second.z + (radius*2)) * -1;
} */
grp.y = it->second.y + MakeRandomInt(-5000, radius * 2);
m_anomalyItems.push_back(grp);
it = groupRange.first;
}
}
}
/* groupID format
ABB - item def groups
A = group type - 1:deco, 2:system effect beacon, 3:mining, 4:lco, 5:ships, 6:base, 7:station gun, 8:station wrecks, 9:misc
B = 1:space objects, 2:effect beacons, 3:roid types, 4:ice types, 5:, 6:asteroid colony, 7:, 8:, 9:misc
B = ship/gun faction: 1:Amarr, 2:Caldari, 3:Gallente, 4:Minmatar, 5:Sentinel, 6:Guardian
B = faction: 00:none, 01:Serpentis, 02:Angel, 03:Blood, 04:Guristas, 05:Sansha, 06:Drones, 07:Amarr, 08:Caldari, 09:Gallente,
10:Minmatar, 11:Sleeper, 12:Talocan, 13:Ammatar
1xx deco items
110 wormholes
13x mining types
130 named roids
131 misc roids
132 worthless mining types
140 infested items
160 Asteroid Colony
191 Monument
2xx effect beacons **incomplete
211 Electronic
212 omni
22x Incursion
23x Black Hole
24x Magnetar
25x Pulsar
26x Red Giant
27x Wolf Rayet
28x Cataclysmic Variable
3xx mining objects
30x ore
34x ice
36x clouds
4xx lco
401 Serpentis
402 Angel
403 Blood
404 Guristas
405 Sansha
406 drone
407 Amarr
408 Caldari
409 Gallente
410 Minmatar
42x lco ships
43x lco structures
430 lco misc
431 lco Habitation
432 lco drug labs
433 lco Starbase
5xx ships
51x Amarr
52x Caldari
53x Gallente
54x Minmatar
6xx base
601 Serpentis
602 Angel
603 Blood
604 Guristas
605 Sansha
606 drone
607 Amarr
608 Caldari
609 Gallente
610 Minmatar
611 Sleeper
612 Talocan
613 Ammatar
620 Starbase
630 Habitation
640 Stationary
650 Indestructible
660 Forcefield
670 Shipyard
680 Construction
690 Storage
691 misc
7xx station guns **incomplete
8xx station and structure ruins **incomplete
80x Sansha
81x Amarr
82x Caldari
83x Gallente
84x Minmatar
85x misc ruined parts
86x misc debris
9xx misc **incomplete
91x comets
92x clouds
93x environment
96x event lco/lcs
*/
/*
In player-owned sovereign nullsec, using Ore Prospecting Arrays,
(23510,'Small Asteroid Cluster',0,2,0,1,0,0,0),
(23520,'Moderate Asteroid Cluster',0,2,0,15,0,0,0),
(23530,'Large Asteroid Cluster',0,2,0,29,0,0,0),
(23540,' Enormous Asteroid Cluster ',0,2,0,29,0,0,0),
(23550,'Colossal Asteroid Cluster',0,2,0,29,0,0,0),
*/ | 412 | 0.941116 | 1 | 0.941116 | game-dev | MEDIA | 0.93357 | game-dev | 0.856044 | 1 | 0.856044 |
SonahSofern/Xenoblade-Series-Randomizer | 6,797 | XC3/XC3_Scripts/Enemy.py |
import json, random, copy, traceback, math
from XC3.XC3_Scripts import IDs, Options
from scripts import Helper, JSONParser, PopupDescriptions, Enemies as Enemy
# https://xenobladedata.github.io/xb3_130/SYS_GimmickLocation.html#25513 useful file has enemy xyz and probably how fights dteremine where try again places you
# To fix:
# Too many agnus/keves soldier enemies dillutes the pool of intereszting enemies
StaticEnemyData:list[Enemy.EnemyGroup] = []
def Enemies(targetGroup, isNormal, isUnique, isBoss, isSuperboss, isEnemies, isMatchSizeOption:Options.Option, isBossGroupBalancing):
global StaticEnemyData
GroupFightViolations = GetGroupFightViolations()
GroupFightIDs = GetGroupFightIDs()
Aggro = ["<AB4BA3D5>", "<1104E9C5>", "<B5C5F3B3>", "<EC666A80>", "<64251F47>", "<3B6DFBC4>"]
RetryBattleLandmark = "<9A220E4D>"
PostBattleConqueredPopup = "CatMain" # Currently not using it has weird effects fights take a long time to end after enemy goes down without it happens eithery way with UMs so something is wrong with UMS
ignoreKeys = ["$id", "ID", PostBattleConqueredPopup, "Level", "IdMove", "NamedFlag", "IdDropPrecious", "FlgLevAttack", "FlgLevBattleOff", "FlgDmgFloor", "FlgFixed", "IdMove", "FlgNoVanish", "FlgSpDead" , "KillEffType", "FlgSerious", RetryBattleLandmark, "<3CEBD0A4>", "<C6717CFE>", "FlgKeepSword", "FlgColonyReleased", "FlgNoDead", "FlgNoTarget", "ExpRate", "GoldRate", "FlgNoFalling"] + Aggro
actKeys = ["ActType"]
with open("XC3/JsonOutputs/fld/FLD_EnemyData.json", 'r+', encoding='utf-8') as eneFile:
with open("XC3/JsonOutputs/btl/BTL_Enemy.json", 'r+', encoding='utf-8') as paramFile:
with open("XC3/JsonOutputs/btl/BTL_EnRsc.json", 'r+', encoding='utf-8') as rscFile:
paramData = json.load(paramFile)
rscData = json.load(rscFile)
eneData = json.load(eneFile)
isMatchSize = isMatchSizeOption.GetState()
eRando = Enemy.EnemyRandomizer(IDs.NormalMonsters, IDs.UniqueMonsters, IDs.BossMonsters, IDs.SuperbossMonsters, isEnemies, isNormal, isUnique, isBoss, isSuperboss, "Resource", "IdBattleEnemy", eneData, paramData, rscData, actKeys=actKeys)
if StaticEnemyData == []:
StaticEnemyData = eRando.GenEnemyData()
for en in eneData["rows"]:
if eRando.FilterEnemies(en, targetGroup):
continue
newEn = eRando.CreateRandomEnemy(StaticEnemyData)
eRando.ActTypeFix(newEn, en) # Flying Enemies and some enemies in Erythia will still fall despite act type fix
HPLimitFix(en, newEn, eRando)
# if isBossGroupBalancing:
# eRando.BalanceFight(en, newEn, GroupFightIDs, GroupFightViolations)
if isMatchSize:
EnemySizeHelper(en, newEn, eRando)
IntroFightBalances(en, newEn, eRando)
Helper.CopyKeys(en, newEn, ignoreKeys)
for group in StaticEnemyData:
group.RefreshCurrentGroup()
if StaticEnemyData == []:
Bandaids(eRando)
JSONParser.CloseFile(eneData, eneFile)
JSONParser.CloseFile(paramData, paramFile)
JSONParser.CloseFile(rscData, rscFile)
def HPLimitFix(en, newEn, eRando:Enemy.EnemyRandomizer):
oldRSC = eRando.FindParam(en)
newRSC = eRando.FindParam(newEn)
if oldRSC["LowerLimitHP"] != newRSC["LowerLimitHP"]:
eRando.ChangeStats([newEn], [("LowerLimitHP", oldRSC["LowerLimitHP"])])
def SummonFix(): # For now this is lower priority for how difficult it would be to fix so im removing summons
with open("XC3/JsonOutputs/btl/BTL_EnSummon.json", 'r+', encoding='utf-8') as summonFile:
summonData = json.load(summonFile)
for summon in summonData["rows"]:
for i in range(1,4):
summon[f"EnemyID0{i}"] = 0
JSONParser.CloseFile(summonData, summonFile)
def EnemySizeHelper(oldEn, newEn, eRando:Enemy.EnemyRandomizer):
Massive = 3
Large = 2
Normal = 1
Small = 0
multDict = {
(Massive, Large): 3,
(Massive, Normal): 4,
(Massive, Small): 5,
(Large, Normal): 3,
(Large, Small): 4,
(Normal, Small): 1,
}
keys = ["Scale", "EliteScale", "WeaponScale"]
eRando.EnemySizeMatch(oldEn, newEn, keys, multDict)
def GetGroupFightViolations():
return []
def GetGroupFightIDs():
return []
def BreakTutorial(eRando:Enemy.EnemyRandomizer): # Tutorial that requires an enemy to be break, topple, dazed
breakTutorial = [738]
eRando.ChangeStats(breakTutorial, [("RstBreak", 0)])
def IntroFightBalances(en, newEn, eRando:Enemy.EnemyRandomizer):
introTutorial = [449, 450, 451, 452, 453, 454, 455]
bossIntroFights = [456, 457]
returningToColony = [737 ,739]
breakTutorial = [738]
Piranhax = [588]
DrifterRopl = [458]
StealthShip = [460,461,462]
Sentry = [463]
AgnusTrio = [464,465,466]
MysteriousEnemy = [467]
cantLoseFights = introTutorial + bossIntroFights + returningToColony
introFights = breakTutorial + Piranhax + DrifterRopl + Sentry + StealthShip + AgnusTrio + MysteriousEnemy + cantLoseFights
if en["$id"] in introFights:
oldEnParam = eRando.FindParam(en)
if en["$id"] in cantLoseFights:
hpChange = 5
else:
hpChange = oldEnParam["StRevHp"]
eRando.ChangeStats([newEn], [("StRevHp", hpChange),("StRevStr", oldEnParam["StRevStr"]),("StRevHeal", oldEnParam["StRevHeal"]),("StRevDex", oldEnParam["StRevDex"]),("StRevAgi", oldEnParam["StRevAgi"])])
def Bandaids(eRando):
BreakTutorial(eRando)
SummonFix()
def EnemyDesc(name):
desc = PopupDescriptions.Description()
desc.Header("Enemies")
desc.Text("This randomizes enemies in the world from the target category into the chosen ones.")
desc.Header(Options.BossEnemyOption_MatchSize.name)
desc.Text("Shrinks/grows enemies to match the size of the original enemy.")
return desc | 412 | 0.734035 | 1 | 0.734035 | game-dev | MEDIA | 0.39809 | game-dev | 0.879842 | 1 | 0.879842 |
suyoumo/DeepClaude_Benchmark | 2,744 | src/2025-03-04-03-28-40--deepseek-chat-0304/python/exercises/practice/go-counting/go_counting.py |
WHITE = 'W'
BLACK = 'B'
EMPTY = ' '
class Board:
"""Count territories of each player in a Go game
Args:
board (list[str]): A two-dimensional Go board
"""
def __init__(self, board):
self.board = [list(row) for row in board]
self.height = len(self.board)
self.width = len(self.board[0]) if self.height else 0
def _is_valid(self, x, y):
"""Check if coordinates are within board bounds"""
return 0 <= x < self.width and 0 <= y < self.height
def territory(self, x, y):
"""Find the owner and the territories given a coordinate on
the board
Args:
x (int): Column on the board
y (int): Row on the board
Returns:
(str, set): A tuple, the first element being the owner
of that area. One of "W", "B", "". The
second being a set of coordinates, representing
the owner's territories.
Raises:
ValueError: If coordinates are invalid
"""
if not self._is_valid(x, y):
raise ValueError('Invalid coordinate')
if self.board[y][x] != ' ':
return ('', set())
visited = set()
queue = [(x, y)]
borders = set()
while queue:
cx, cy = queue.pop(0)
if (cx, cy) in visited:
continue
visited.add((cx, cy))
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nx, ny = cx + dx, cy + dy
if not self._is_valid(nx, ny):
continue
if self.board[ny][nx] == ' ':
if (nx, ny) not in visited:
queue.append((nx, ny))
else:
borders.add(self.board[ny][nx])
if len(borders) == 1:
owner = borders.pop()
else:
owner = ''
return (owner, visited)
def territories(self):
"""Find the owners and the territories of the whole board
Args:
none
Returns:
dict(str, set): A dictionary whose key being the owner
, i.e. "W", "B", "". The value being a set
of coordinates owned by the owner.
"""
result = {'B': set(), 'W': set(), '': set()}
visited = set()
for y in range(self.height):
for x in range(self.width):
if self.board[y][x] == ' ' and (x, y) not in visited:
owner, territory = self.territory(x, y)
result[owner].update(territory)
visited.update(territory)
return result
| 412 | 0.944406 | 1 | 0.944406 | game-dev | MEDIA | 0.829638 | game-dev | 0.910835 | 1 | 0.910835 |
AtomicGameEngine/AtomicGameEngine | 2,702 | Source/Atomic/Atomic2D/CollisionChain2D.h | //
// Copyright (c) 2008-2017 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
#include "../Atomic2D/CollisionShape2D.h"
namespace Atomic
{
/// 2D chain collision component.
class ATOMIC_API CollisionChain2D : public CollisionShape2D
{
ATOMIC_OBJECT(CollisionChain2D, CollisionShape2D);
public:
/// Construct.
CollisionChain2D(Context* context);
/// Destruct.
virtual ~CollisionChain2D();
/// Register object factory.
static void RegisterObject(Context* context);
/// Set loop.
void SetLoop(bool loop);
/// Set vertex count.
void SetVertexCount(unsigned count);
/// Set vertex.
void SetVertex(unsigned index, const Vector2& vertex);
/// Set vertices.
void SetVertices(const PODVector<Vector2>& vertices);
/// Set vertices attribute.
void SetVerticesAttr(const PODVector<unsigned char>& value);
/// Return loop.
bool GetLoop() const { return loop_; }
/// Return vertex count.
unsigned GetVertexCount() const { return vertices_.Size(); }
/// Return vertex.
const Vector2& GetVertex(unsigned index) const { return (index < vertices_.Size()) ? vertices_[index] : Vector2::ZERO; }
/// Return vertices.
const PODVector<Vector2>& GetVertices() const { return vertices_; }
/// Return vertices attribute.
PODVector<unsigned char> GetVerticesAttr() const;
private:
/// Apply node world scale.
virtual void ApplyNodeWorldScale();
/// Recreate fixture.
void RecreateFixture();
/// Chain shape.
b2ChainShape chainShape_;
/// Loop.
bool loop_;
/// Vertices.
PODVector<Vector2> vertices_;
};
}
| 412 | 0.831378 | 1 | 0.831378 | game-dev | MEDIA | 0.682594 | game-dev,graphics-rendering | 0.747265 | 1 | 0.747265 |
CalamityTeam/CalamityModPublic | 1,920 | Items/Weapons/Melee/SpineOfThanatos.cs | using CalamityMod.Projectiles.Melee;
using CalamityMod.Rarities;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Weapons.Melee
{
public class SpineOfThanatos : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Weapons.Melee";
public override void SetDefaults()
{
Item.width = Item.height = 28;
Item.damage = 128;
Item.value = CalamityGlobalItem.RarityVioletBuyPrice;
Item.rare = ModContent.RarityType<Violet>();
Item.noMelee = true;
Item.noUseGraphic = true;
Item.channel = true;
Item.autoReuse = true;
Item.DamageType = DamageClass.MeleeNoSpeed;
Item.useAnimation = Item.useTime = 24;
Item.useStyle = ItemUseStyleID.Shoot;
Item.knockBack = 8f;
Item.UseSound = SoundID.Item68;
Item.shootSpeed = 1f;
Item.shoot = ModContent.ProjectileType<SpineOfThanatosProjectile>();
}
public override bool CanUseItem(Player player) => player.ownedProjectileCounts[Item.shoot] <= 0;
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
for (int i = 0; i < 2; i++)
Projectile.NewProjectile(source, position.X, position.Y, velocity.X, velocity.Y, type, damage, knockback, player.whoAmI, 0f, (i == 0f).ToDirectionInt());
// Create a third, final whip that does not swing around at all and instead simply flies towards the mouse.
Projectile.NewProjectile(source, position.X, position.Y, velocity.X, velocity.Y, type, damage, knockback, player.whoAmI, 0f, 0f);
return false;
}
}
}
| 412 | 0.885904 | 1 | 0.885904 | game-dev | MEDIA | 0.992423 | game-dev | 0.877016 | 1 | 0.877016 |
shedaniel/cloth-config | 8,408 | common/src/main/java/me/shedaniel/clothconfig2/gui/entries/IntegerSliderEntry.java | /*
* This file is part of Cloth Config.
* Copyright (C) 2020 - 2021 shedaniel
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package me.shedaniel.clothconfig2.gui.entries;
import com.google.common.collect.Lists;
import com.mojang.blaze3d.platform.Window;
import com.mojang.blaze3d.vertex.PoseStack;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.AbstractSliderButton;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.narration.NarratableEntry;
import net.minecraft.network.chat.Component;
import net.minecraft.util.Mth;
import org.jetbrains.annotations.ApiStatus;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@Environment(EnvType.CLIENT)
public class IntegerSliderEntry extends TooltipListEntry<Integer> {
protected Slider sliderWidget;
protected Button resetButton;
protected AtomicInteger value;
protected final long orginial;
private int minimum, maximum;
private final Supplier<Integer> defaultValue;
private Function<Integer, Component> textGetter = integer -> Component.literal(String.format("Value: %d", integer));
private final List<AbstractWidget> widgets;
@ApiStatus.Internal
@Deprecated
public IntegerSliderEntry(Component fieldName, int minimum, int maximum, int value, Component resetButtonKey, Supplier<Integer> defaultValue, Consumer<Integer> saveConsumer) {
this(fieldName, minimum, maximum, value, resetButtonKey, defaultValue, saveConsumer, null);
}
@ApiStatus.Internal
@Deprecated
public IntegerSliderEntry(Component fieldName, int minimum, int maximum, int value, Component resetButtonKey, Supplier<Integer> defaultValue, Consumer<Integer> saveConsumer, Supplier<Optional<Component[]>> tooltipSupplier) {
this(fieldName, minimum, maximum, value, resetButtonKey, defaultValue, saveConsumer, tooltipSupplier, false);
}
@ApiStatus.Internal
@Deprecated
public IntegerSliderEntry(Component fieldName, int minimum, int maximum, int value, Component resetButtonKey, Supplier<Integer> defaultValue, Consumer<Integer> saveConsumer, Supplier<Optional<Component[]>> tooltipSupplier, boolean requiresRestart) {
super(fieldName, tooltipSupplier, requiresRestart);
this.orginial = value;
this.defaultValue = defaultValue;
this.value = new AtomicInteger(value);
this.saveCallback = saveConsumer;
this.maximum = maximum;
this.minimum = minimum;
this.sliderWidget = new Slider(0, 0, 152, 20, ((double) this.value.get() - minimum) / Math.abs(maximum - minimum));
this.resetButton = new Button(0, 0, Minecraft.getInstance().font.width(resetButtonKey) + 6, 20, resetButtonKey, widget -> {
setValue(defaultValue.get());
});
this.sliderWidget.setMessage(textGetter.apply(IntegerSliderEntry.this.value.get()));
this.widgets = Lists.newArrayList(sliderWidget, resetButton);
}
public Function<Integer, Component> getTextGetter() {
return textGetter;
}
public IntegerSliderEntry setTextGetter(Function<Integer, Component> textGetter) {
this.textGetter = textGetter;
this.sliderWidget.setMessage(textGetter.apply(IntegerSliderEntry.this.value.get()));
return this;
}
@Override
public Integer getValue() {
return value.get();
}
@Deprecated
public void setValue(int value) {
sliderWidget.setValue((Mth.clamp(value, minimum, maximum) - minimum) / (double) Math.abs(maximum - minimum));
this.value.set(Math.min(Math.max(value, minimum), maximum));
sliderWidget.updateMessage();
}
@Override
public boolean isEdited() {
return super.isEdited() || getValue() != orginial;
}
@Override
public Optional<Integer> getDefaultValue() {
return defaultValue == null ? Optional.empty() : Optional.ofNullable(defaultValue.get());
}
@Override
public List<? extends GuiEventListener> children() {
return widgets;
}
@Override
public List<? extends NarratableEntry> narratables() {
return widgets;
}
public IntegerSliderEntry setMaximum(int maximum) {
this.maximum = maximum;
return this;
}
public IntegerSliderEntry setMinimum(int minimum) {
this.minimum = minimum;
return this;
}
@Override
public void render(PoseStack matrices, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean isHovered, float delta) {
super.render(matrices, index, y, x, entryWidth, entryHeight, mouseX, mouseY, isHovered, delta);
Window window = Minecraft.getInstance().getWindow();
this.resetButton.active = isEditable() && getDefaultValue().isPresent() && defaultValue.get() != value.get();
this.resetButton.y = y;
this.sliderWidget.active = isEditable();
this.sliderWidget.y = y;
Component displayedFieldName = getDisplayedFieldName();
if (Minecraft.getInstance().font.isBidirectional()) {
Minecraft.getInstance().font.drawShadow(matrices, displayedFieldName.getVisualOrderText(), window.getGuiScaledWidth() - x - Minecraft.getInstance().font.width(displayedFieldName), y + 6, getPreferredTextColor());
this.resetButton.x = x;
this.sliderWidget.x = x + resetButton.getWidth() + 1;
} else {
Minecraft.getInstance().font.drawShadow(matrices, displayedFieldName.getVisualOrderText(), x, y + 6, getPreferredTextColor());
this.resetButton.x = x + entryWidth - resetButton.getWidth();
this.sliderWidget.x = x + entryWidth - 150;
}
this.sliderWidget.setWidth(150 - resetButton.getWidth() - 2);
resetButton.render(matrices, mouseX, mouseY, delta);
sliderWidget.render(matrices, mouseX, mouseY, delta);
}
private class Slider extends AbstractSliderButton {
protected Slider(int int_1, int int_2, int int_3, int int_4, double double_1) {
super(int_1, int_2, int_3, int_4, Component.empty(), double_1);
}
@Override
public void updateMessage() {
setMessage(textGetter.apply(IntegerSliderEntry.this.value.get()));
}
@Override
protected void applyValue() {
IntegerSliderEntry.this.value.set((int) (minimum + Math.abs(maximum - minimum) * value));
}
@Override
public boolean keyPressed(int int_1, int int_2, int int_3) {
if (!isEditable())
return false;
return super.keyPressed(int_1, int_2, int_3);
}
@Override
public boolean mouseDragged(double double_1, double double_2, int int_1, double double_3, double double_4) {
if (!isEditable())
return false;
return super.mouseDragged(double_1, double_2, int_1, double_3, double_4);
}
public double getProgress() {
return value;
}
public void setProgress(double integer) {
this.value = integer;
}
public void setValue(double integer) {
this.value = integer;
}
}
}
| 412 | 0.857122 | 1 | 0.857122 | game-dev | MEDIA | 0.717402 | game-dev | 0.948784 | 1 | 0.948784 |
python-qt-tools/PyQt5-stubs | 10,144 | tests/qflags/test_QtWidgets_StandardButtons_StandardButton.py | # mypy: no-warn-unreachable
import sys
from typing import Union, TypeVar, Type
if sys.version_info[:2] >= (3,8):
from typing import Literal
else:
from typing_extensions import Literal
import pytest
### Specific part
# file generated from qflags_test_template.py for QFlags class "QMessageBox.StandardButtons" and flag class "QMessageBox.StandardButton"
from PyQt5 import QtWidgets
OneFlagClass = QtWidgets.QMessageBox.StandardButton
MultiFlagClass = QtWidgets.QMessageBox.StandardButtons
oneFlagRefValue1 = QtWidgets.QMessageBox.StandardButton.NoButton
oneFlagRefValue2 = QtWidgets.QMessageBox.StandardButton.Ok
OR_CONVERTS_TO_MULTI: Literal[True] = True
OR_INT_CONVERTS_TO_MULTI: Literal[False] = False
INT_OR_CONVERTS_TO_MULTI: Literal[True] = True
### End of specific part
def assert_type_of_value_int(value: int) -> None:
'''Raise an exception if the value is not of type expected_type'''
assert isinstance(value, int)
def assert_type_of_value_oneFlag(value: OneFlagClass) -> None:
'''Raise an exception if the value is not of type expected_type'''
assert type(value) == OneFlagClass
def assert_type_of_value_multiFlag(value: MultiFlagClass) -> None:
'''Raise an exception if the value is not of type expected_type'''
assert type(value) == MultiFlagClass
def test_on_one_flag_class() -> None:
oneFlagValue1 = oneFlagRefValue1
oneFlagValue2 = oneFlagRefValue2
oneFlagValueTest = oneFlagValue1 # type: OneFlagClass
intValue = 0 # type: int
oneOrMultiFlagValueTest = oneFlagValue1 # type: Union[OneFlagClass, MultiFlagClass]
oneFlagOrIntValue = oneFlagValue1 # type: Union[int, OneFlagClass]
# upcast from OneFlagClass to int
intValue = oneFlagValue1
# conversion also accepted
intValue = int(oneFlagValue1)
# this is not supported type-safely for a good reason
oneFlagValueTest = 1 # type: ignore
# correct way to do it
oneFlagValueTest = OneFlagClass(1)
oneFlagValueTest = OneFlagClass(oneFlagValue1)
# The rules of OneFlagClass conversion defined in PyQt5 are:
# 1. | ~= with OneFlagClass return a MultiFlagClass (which is not compatible to int)
# Note that this breaks Liskov principle
# 2. everything else returns int: & ^ &= ^=
# 3. operations with int return int.
if OR_CONVERTS_TO_MULTI:
assert_type_of_value_multiFlag(oneFlagValue1 | oneFlagValue2)
else:
assert_type_of_value_int(oneFlagValue1 | oneFlagValue2)
assert_type_of_value_int(~oneFlagValue1)
assert_type_of_value_int(oneFlagValue1 & oneFlagValue2)
assert_type_of_value_int(oneFlagValue1 ^ oneFlagValue2)
# right operand
if OR_INT_CONVERTS_TO_MULTI:
assert_type_of_value_multiFlag(oneFlagValue1 | 1)
else:
assert_type_of_value_int(oneFlagValue1 | 1)
assert_type_of_value_int(oneFlagValue1 & 1)
assert_type_of_value_int(oneFlagValue1 ^ 1)
assert_type_of_value_int(oneFlagValue1 + 1)
assert_type_of_value_int(oneFlagValue1 - 1)
# left operand
if INT_OR_CONVERTS_TO_MULTI:
assert_type_of_value_multiFlag(1 | oneFlagValue1)
else:
assert_type_of_value_int(1 | oneFlagValue1)
assert_type_of_value_int(1 & oneFlagValue1)
assert_type_of_value_int(1 ^ oneFlagValue1)
assert_type_of_value_int(1 + oneFlagValue1)
assert_type_of_value_int(1 - oneFlagValue1)
if OR_CONVERTS_TO_MULTI:
oneOrMultiFlagValueTest = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneOrMultiFlagValueTest)
oneOrMultiFlagValueTest |= oneFlagValue2
assert_type_of_value_multiFlag(oneOrMultiFlagValueTest) # nice violation of Liskov principle here
else:
oneFlagOrIntValue = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneFlagOrIntValue)
oneFlagOrIntValue |= oneFlagValue2
assert_type_of_value_int(oneFlagOrIntValue)
if OR_INT_CONVERTS_TO_MULTI:
oneOrMultiFlagValueTest = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneOrMultiFlagValueTest)
oneOrMultiFlagValueTest |= 1
assert_type_of_value_multiFlag(oneOrMultiFlagValueTest)
else:
oneFlagOrIntValue = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneFlagOrIntValue)
oneFlagOrIntValue |= 1
assert_type_of_value_int(oneFlagOrIntValue)
oneFlagOrIntValue = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneFlagOrIntValue)
oneFlagOrIntValue &= 1
assert_type_of_value_int(oneFlagOrIntValue)
oneFlagOrIntValue = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneFlagOrIntValue)
oneFlagOrIntValue &= oneFlagValue2
assert_type_of_value_int(oneFlagOrIntValue)
oneFlagOrIntValue = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneFlagOrIntValue)
oneFlagOrIntValue ^= 1
assert_type_of_value_int(oneFlagOrIntValue)
oneFlagOrIntValue = oneFlagValue1 # reset type and value
assert_type_of_value_oneFlag(oneFlagOrIntValue)
oneFlagOrIntValue ^= oneFlagValue2
assert_type_of_value_int(oneFlagOrIntValue)
def test_on_multi_flag_class() -> None:
oneFlagValue1 = oneFlagRefValue1
multiFlagValue1 = MultiFlagClass()
multiFlagValue2 = MultiFlagClass()
multiFlagValueTest = multiFlagValue1 # type: MultiFlagClass
intValue = 0
assert_type_of_value_oneFlag(oneFlagValue1)
assert_type_of_value_multiFlag(multiFlagValue1)
assert_type_of_value_multiFlag(multiFlagValue2)
assert_type_of_value_multiFlag(multiFlagValueTest)
assert_type_of_value_int(intValue)
# MultiFlagClass may be created by combining MultiFlagClass together
assert_type_of_value_multiFlag( ~multiFlagValue1 )
assert_type_of_value_multiFlag( multiFlagValue1 | multiFlagValue2 )
assert_type_of_value_multiFlag( multiFlagValue1 & multiFlagValue2 )
assert_type_of_value_multiFlag( multiFlagValue1 ^ multiFlagValue2 )
# MultiFlagClass may be created by combining MultiFlagClass and OneFlagClass, left or right
assert_type_of_value_multiFlag( multiFlagValue1 | oneFlagValue1 )
assert_type_of_value_multiFlag( multiFlagValue1 & oneFlagValue1 )
assert_type_of_value_multiFlag( multiFlagValue1 ^ oneFlagValue1 )
assert_type_of_value_multiFlag( oneFlagValue1 | multiFlagValue1 )
assert_type_of_value_multiFlag( oneFlagValue1 & multiFlagValue1 )
assert_type_of_value_multiFlag( oneFlagValue1 ^ multiFlagValue1 )
# MultClassFlag may be created by combining MultiFlagClass and int, right only
assert_type_of_value_multiFlag(multiFlagValue1 | 1)
assert_type_of_value_multiFlag(multiFlagValue1 & 1)
assert_type_of_value_multiFlag(multiFlagValue1 ^ 1)
# this is rejected by mypy and is slightly annoying: you can not pass a OneFlagClass variable to a method expecting a MultiFlagClass
# explicit typing must be used on those methods to accept both OneFlagClass and MultiFlagClass
multiFlagValueTest = oneFlagValue1 # type: ignore
# correct way to do it
multiFlagValueTest = MultiFlagClass(oneFlagValue1)
assert_type_of_value_multiFlag(multiFlagValueTest)
# this is rejected for the same reason as for OneFlagClass.
intValue = multiFlagValueTest # type: ignore
# correct way to do it
intValue = int(multiFlagValueTest)
assert_type_of_value_int(intValue)
# rejected by mypy rightfully
multiFlagValueTest = 1 # type: ignore
# correct way to do it
multiFlagValueTest = MultiFlagClass(1)
# assignments operations with OneFlagClass
assert_type_of_value_multiFlag(multiFlagValueTest)
multiFlagValueTest |= oneFlagValue1
assert_type_of_value_multiFlag(multiFlagValueTest)
assert_type_of_value_multiFlag(multiFlagValueTest)
multiFlagValueTest &= oneFlagValue1
assert_type_of_value_multiFlag(multiFlagValueTest)
assert_type_of_value_multiFlag(multiFlagValueTest)
multiFlagValueTest ^= oneFlagValue1
assert_type_of_value_multiFlag(multiFlagValueTest)
# assignments operations with int
assert_type_of_value_multiFlag(multiFlagValueTest)
multiFlagValueTest |= 1
assert_type_of_value_multiFlag(multiFlagValueTest)
assert_type_of_value_multiFlag(multiFlagValueTest)
multiFlagValueTest &= 1
assert_type_of_value_multiFlag(multiFlagValueTest)
assert_type_of_value_multiFlag(multiFlagValueTest)
multiFlagValueTest ^= 1
assert_type_of_value_multiFlag(multiFlagValueTest)
#########################################################1
#
# Exploring errors
#
#########################################################1
# This checks the following:
# + and - operations are not supported on MultiFlagClass
# combining int with MultiFlagClass does not work
pytest.raises(TypeError, lambda: 1 | multiFlagValue1 ) # type: ignore[operator]
pytest.raises(TypeError, lambda: 1 & multiFlagValue1 ) # type: ignore[operator]
pytest.raises(TypeError, lambda: 1 ^ multiFlagValue1 ) # type: ignore[operator]
pytest.raises(TypeError, lambda: multiFlagValue1 + multiFlagValue2 ) # type: ignore[operator]
pytest.raises(TypeError, lambda: multiFlagValue1 - multiFlagValue2 ) # type: ignore[operator]
pytest.raises(TypeError, lambda: multiFlagValue1 + oneFlagValue1) # type: ignore[operator]
pytest.raises(TypeError, lambda: multiFlagValue1 - oneFlagValue1) # type: ignore[operator]
pytest.raises(TypeError, lambda: multiFlagValue1 + 1) # type: ignore[operator]
pytest.raises(TypeError, lambda: multiFlagValue1 - 1) # type: ignore[operator]
pytest.raises(TypeError, lambda: oneFlagValue1 + multiFlagValue1) # type: ignore[operator]
pytest.raises(TypeError, lambda: oneFlagValue1 - multiFlagValue1) # type: ignore[operator]
pytest.raises(TypeError, lambda: 1 + multiFlagValue1) # type: ignore[operator]
pytest.raises(TypeError, lambda: 1 - multiFlagValue1) # type: ignore[operator]
def f1() -> None:
multiFlagValueTest = MultiFlagClass()
multiFlagValueTest += oneFlagValue1 # type: ignore[assignment, operator]
def f2() -> None:
multiFlagValueTest = MultiFlagClass()
multiFlagValueTest += 1 # type: ignore[assignment, operator]
def f3() -> None:
multiFlagValueTest = MultiFlagClass()
multiFlagValueTest -= oneFlagValue1 # type: ignore[assignment, operator]
def f4() -> None:
multiFlagValueTest = MultiFlagClass()
multiFlagValueTest -= 1 # type: ignore[assignment, operator]
pytest.raises(TypeError, f1)
pytest.raises(TypeError, f2)
pytest.raises(TypeError, f3)
pytest.raises(TypeError, f4)
| 412 | 0.844478 | 1 | 0.844478 | game-dev | MEDIA | 0.341381 | game-dev | 0.627655 | 1 | 0.627655 |
commandlineparser/commandline | 1,770 | src/CommandLine/Core/Verb.cs | // Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace CommandLine.Core
{
sealed class Verb
{
public Verb(string name, string helpText, bool hidden, bool isDefault, string[] aliases)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
Name = name;
HelpText = helpText ?? throw new ArgumentNullException(nameof(helpText));
Hidden = hidden;
IsDefault = isDefault;
Aliases = aliases ?? new string[0];
}
public string Name { get; private set; }
public string HelpText { get; private set; }
public bool Hidden { get; private set; }
public bool IsDefault { get; private set; }
public string[] Aliases { get; private set; }
public static Verb FromAttribute(VerbAttribute attribute)
{
return new Verb(
attribute.Name,
attribute.HelpText,
attribute.Hidden,
attribute.IsDefault,
attribute.Aliases
);
}
public static IEnumerable<Tuple<Verb, Type>> SelectFromTypes(IEnumerable<Type> types)
{
return from type in types
let attrs = type.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true).ToArray()
where attrs.Length == 1
select Tuple.Create(
FromAttribute((VerbAttribute)attrs.Single()),
type);
}
}
}
| 412 | 0.633475 | 1 | 0.633475 | game-dev | MEDIA | 0.278953 | game-dev | 0.939022 | 1 | 0.939022 |
Arcnor/pixel-dungeon-gdx | 2,835 | core/src/com/watabou/pixeldungeon/actors/hero/HeroSubClass.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.pixeldungeon.actors.hero;
import com.watabou.utils.Bundle;
public enum HeroSubClass {
NONE( null, null ),
GLADIATOR( "gladiator",
"A successful attack with a melee weapon allows the _Gladiator_ to start a combo, " +
"in which every next successful hit inflicts more damage." ),
BERSERKER( "berserker",
"When severely wounded, the _Berserker_ enters a state of wild fury " +
"significantly increasing his damage output." ),
WARLOCK( "warlock",
"After killing an enemy the _Warlock_ consumes its soul. " +
"It heals his wounds and satisfies his hunger." ),
BATTLEMAGE( "battlemage",
"When fighting with a wand in his hands, the _Battlemage_ inflicts additional damage depending " +
"on the current number of charges. Every successful hit restores 1 charge to this wand." ),
ASSASSIN( "assassin",
"When performing a surprise attack, the _Assassin_ inflicts additional damage to his target." ),
FREERUNNER( "freerunner",
"The _Freerunner_ can move almost twice faster, than most of the monsters. When he " +
"is running, the Freerunner is much harder to hit. For that he must be unencumbered and not starving." ),
SNIPER( "sniper",
"_Snipers_ are able to detect weak points in an enemy's armor, " +
"effectively ignoring it when using a missile weapon." ),
WARDEN( "warden",
"Having a strong connection with forces of nature gives _Wardens_ an ability to gather dewdrops and " +
"seeds from plants. Also trampling a high grass grants them a temporary armor buff." );
private String title;
private String desc;
private HeroSubClass( String title, String desc ) {
this.title = title;
this.desc = desc;
}
public String title() {
return title;
}
public String desc() {
return desc;
}
private static final String SUBCLASS = "subClass";
public void storeInBundle( Bundle bundle ) {
bundle.put( SUBCLASS, toString() );
}
public static HeroSubClass restoreInBundle( Bundle bundle ) {
String value = bundle.getString( SUBCLASS );
try {
return valueOf( value );
} catch (Exception e) {
return NONE;
}
}
}
| 412 | 0.800109 | 1 | 0.800109 | game-dev | MEDIA | 0.957789 | game-dev | 0.979841 | 1 | 0.979841 |
XFactHD/FramedBlocks | 2,732 | src/main/java/io/github/xfacthd/framedblocks/common/blockentity/doubled/slopeedge/FramedElevatedDoubleCornerSlopeEdgeBlockEntity.java | package io.github.xfacthd.framedblocks.common.blockentity.doubled.slopeedge;
import io.github.xfacthd.framedblocks.api.block.FramedProperties;
import io.github.xfacthd.framedblocks.api.block.blockentity.FramedDoubleBlockEntity;
import io.github.xfacthd.framedblocks.api.util.Utils;
import io.github.xfacthd.framedblocks.common.FBContent;
import io.github.xfacthd.framedblocks.common.data.PropertyHolder;
import io.github.xfacthd.framedblocks.common.data.property.CornerType;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
public class FramedElevatedDoubleCornerSlopeEdgeBlockEntity extends FramedDoubleBlockEntity
{
public FramedElevatedDoubleCornerSlopeEdgeBlockEntity(BlockPos pos, BlockState state)
{
super(FBContent.BE_TYPE_FRAMED_ELEVATED_DOUBLE_CORNER_SLOPE_EDGE.value(), pos, state);
}
@Override
protected boolean hitSecondary(BlockHitResult hit, Vec3 lookVec, Vec3 eyePos)
{
Direction dir = getBlockState().getValue(FramedProperties.FACING_HOR);
CornerType type = getBlockState().getValue(PropertyHolder.CORNER_TYPE);
Direction side = hit.getDirection();
Direction baseFace = switch (type)
{
case BOTTOM -> Direction.DOWN;
case TOP -> Direction.UP;
default -> dir;
};
if (side == baseFace) return false;
Vec3 hitVec = hit.getLocation();
Direction xFront;
Direction yFront;
if (type.isHorizontal())
{
xFront = type.isRight() ? dir.getCounterClockWise() : dir.getClockWise();
yFront = type.isTop() ? Direction.DOWN : Direction.UP;
}
else
{
xFront = dir.getClockWise();
yFront = dir.getOpposite();
}
if (side == baseFace.getOpposite())
{
double offX = Utils.fractionInDir(hitVec, xFront);
double offY = Utils.fractionInDir(hitVec, yFront);
return offX > .5D || offY > .5D;
}
else if (side == xFront || side == yFront)
{
double off = Utils.fractionInDir(hitVec, baseFace.getOpposite());
return off > .5D;
}
else if (side == xFront.getOpposite() || side == yFront.getOpposite())
{
double offY = (Utils.fractionInDir(hitVec, baseFace.getOpposite()) - .5D) * 2D;
double offXZ = (Utils.fractionInDir(hitVec, side == xFront.getOpposite() ? yFront : xFront) - .5D) * 2D;
return offXZ >= 0D && offY >= (1D - offXZ);
}
return false;
}
}
| 412 | 0.763202 | 1 | 0.763202 | game-dev | MEDIA | 0.530402 | game-dev | 0.749618 | 1 | 0.749618 |
lsw5530/RPG_GameFramework | 5,625 | Client_GF/Assets/XLua/Src/CopyByValue.cs | /*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
namespace XLua
{
public static partial class CopyByValue
{
// for int 8
public static bool Pack(IntPtr buff, int offset, byte field)
{
return LuaAPI.xlua_pack_int8_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out byte field)
{
return LuaAPI.xlua_unpack_int8_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, sbyte field)
{
return LuaAPI.xlua_pack_int8_t(buff, offset, (byte)field);
}
public static bool UnPack(IntPtr buff, int offset, out sbyte field)
{
byte tfield;
bool ret = LuaAPI.xlua_unpack_int8_t(buff, offset, out tfield);
field = (sbyte)tfield;
return ret;
}
// for int16
public static bool Pack(IntPtr buff, int offset, short field)
{
return LuaAPI.xlua_pack_int16_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out short field)
{
return LuaAPI.xlua_unpack_int16_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, ushort field)
{
return LuaAPI.xlua_pack_int16_t(buff, offset, (short)field);
}
public static bool UnPack(IntPtr buff, int offset, out ushort field)
{
short tfield;
bool ret = LuaAPI.xlua_unpack_int16_t(buff, offset, out tfield);
field = (ushort)tfield;
return ret;
}
// for int32
public static bool Pack(IntPtr buff, int offset, int field)
{
return LuaAPI.xlua_pack_int32_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out int field)
{
return LuaAPI.xlua_unpack_int32_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, uint field)
{
return LuaAPI.xlua_pack_int32_t(buff, offset, (int)field);
}
public static bool UnPack(IntPtr buff, int offset, out uint field)
{
int tfield;
bool ret = LuaAPI.xlua_unpack_int32_t(buff, offset, out tfield);
field = (uint)tfield;
return ret;
}
// for int64
public static bool Pack(IntPtr buff, int offset, long field)
{
return LuaAPI.xlua_pack_int64_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out long field)
{
return LuaAPI.xlua_unpack_int64_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, ulong field)
{
return LuaAPI.xlua_pack_int64_t(buff, offset, (long)field);
}
public static bool UnPack(IntPtr buff, int offset, out ulong field)
{
long tfield;
bool ret = LuaAPI.xlua_unpack_int64_t(buff, offset, out tfield);
field = (ulong)tfield;
return ret;
}
// for float
public static bool Pack(IntPtr buff, int offset, float field)
{
return LuaAPI.xlua_pack_float(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out float field)
{
return LuaAPI.xlua_unpack_float(buff, offset, out field);
}
// for double
public static bool Pack(IntPtr buff, int offset, double field)
{
return LuaAPI.xlua_pack_double(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out double field)
{
return LuaAPI.xlua_unpack_double(buff, offset, out field);
}
// for decimal
public static bool Pack(IntPtr buff, int offset, decimal field)
{
return LuaAPI.xlua_pack_decimal(buff, offset, ref field);
}
public static bool UnPack(IntPtr buff, int offset, out decimal field)
{
byte scale;
byte sign;
int hi32;
ulong lo64;
if (!LuaAPI.xlua_unpack_decimal(buff, offset, out scale, out sign, out hi32, out lo64))
{
field = default(decimal);
return false;
}
field = new Decimal((int)(lo64 & 0xFFFFFFFF), (int)(lo64 >> 32), hi32, (sign & 0x80) != 0, scale);
return true;
}
public static bool IsStruct(Type type)
{
return type.IsValueType() && !type.IsEnum() && !type.IsPrimitive();
}
}
}
| 412 | 0.723357 | 1 | 0.723357 | game-dev | MEDIA | 0.449005 | game-dev | 0.55654 | 1 | 0.55654 |
space-wizards/space-station-14 | 4,163 | Content.Client/Maps/GridDraggingSystem.cs | using System.Numerics;
using Content.Shared.Maps;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Shared.Input;
using Robust.Shared.Map;
using Robust.Shared.Physics.Components;
using Robust.Shared.Timing;
namespace Content.Client.Maps;
/// <inheritdoc />
public sealed class GridDraggingSystem : SharedGridDraggingSystem
{
[Dependency] private readonly IEyeManager _eyeManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly IInputManager _inputManager = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly InputSystem _inputSystem = default!;
[Dependency] private readonly SharedTransformSystem _transformSystem = default!;
public bool Enabled { get; set; }
private EntityUid? _dragging;
private Vector2 _localPosition;
private MapCoordinates? _lastMousePosition;
public override void Initialize()
{
base.Initialize();
SubscribeNetworkEvent<GridDragToggleMessage>(OnToggleMessage);
}
private void OnToggleMessage(GridDragToggleMessage ev)
{
if (Enabled == ev.Enabled)
return;
Enabled = ev.Enabled;
if (!Enabled)
StopDragging();
}
private void StartDragging(EntityUid grid, Vector2 localPosition)
{
_dragging = grid;
_localPosition = localPosition;
if (HasComp<PhysicsComponent>(grid))
{
RaiseNetworkEvent(new GridDragVelocityRequest()
{
Grid = GetNetEntity(grid),
LinearVelocity = Vector2.Zero
});
}
}
private void StopDragging()
{
if (_dragging == null) return;
if (_lastMousePosition != null && TryComp(_dragging.Value, out TransformComponent? xform) &&
TryComp<PhysicsComponent>(_dragging.Value, out _) &&
xform.MapID == _lastMousePosition.Value.MapId)
{
var tickTime = _gameTiming.TickPeriod;
var distance = _lastMousePosition.Value.Position - _transformSystem.GetWorldPosition(xform);
RaiseNetworkEvent(new GridDragVelocityRequest()
{
Grid = GetNetEntity(_dragging.Value),
LinearVelocity = distance.LengthSquared() > 0f ? (distance / (float) tickTime.TotalSeconds) * 0.25f : Vector2.Zero,
});
}
_dragging = null;
_localPosition = Vector2.Zero;
_lastMousePosition = null;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
if (!Enabled || !_gameTiming.IsFirstTimePredicted) return;
var state = _inputSystem.CmdStates.GetState(EngineKeyFunctions.Use);
if (state != BoundKeyState.Down)
{
StopDragging();
return;
}
var mouseScreenPos = _inputManager.MouseScreenPosition;
var mousePos = _eyeManager.PixelToMap(mouseScreenPos);
if (_dragging == null)
{
if (!_mapManager.TryFindGridAt(mousePos, out var gridUid, out var grid))
return;
StartDragging(gridUid, Vector2.Transform(mousePos.Position, _transformSystem.GetInvWorldMatrix(gridUid)));
}
if (!TryComp(_dragging, out TransformComponent? xform))
{
StopDragging();
return;
}
if (xform.MapID != mousePos.MapId)
{
StopDragging();
return;
}
var localToWorld = Vector2.Transform(_localPosition, _transformSystem.GetWorldMatrix(xform));
if (localToWorld.EqualsApprox(mousePos.Position, 0.01f)) return;
var requestedGridOrigin = mousePos.Position - _transformSystem.GetWorldRotation(xform).RotateVec(_localPosition);
_lastMousePosition = new MapCoordinates(requestedGridOrigin, mousePos.MapId);
RaiseNetworkEvent(new GridDragRequestPosition()
{
Grid = GetNetEntity(_dragging.Value),
WorldPosition = requestedGridOrigin,
});
}
}
| 412 | 0.939472 | 1 | 0.939472 | game-dev | MEDIA | 0.8893 | game-dev | 0.984414 | 1 | 0.984414 |
Decencies/CheatBreaker | 2,616 | CheatBreaker/src/main/java/net/minecraft/client/resources/ResourcePackListEntryDefault.java | package net.minecraft.client.resources;
import com.google.gson.JsonParseException;
import java.io.IOException;
import net.minecraft.client.gui.GuiScreenResourcePacks;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.data.PackMetadataSection;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ResourcePackListEntryDefault extends ResourcePackListEntry
{
private static final Logger logger = LogManager.getLogger();
private final IResourcePack field_148320_d;
private final ResourceLocation field_148321_e;
public ResourcePackListEntryDefault(GuiScreenResourcePacks p_i45052_1_)
{
super(p_i45052_1_);
this.field_148320_d = this.field_148317_a.getResourcePackRepository().rprDefaultResourcePack;
DynamicTexture var2;
try
{
var2 = new DynamicTexture(this.field_148320_d.getPackImage());
}
catch (IOException var4)
{
var2 = TextureUtil.missingTexture;
}
this.field_148321_e = this.field_148317_a.getTextureManager().getDynamicTextureLocation("texturepackicon", var2);
}
protected String func_148311_a()
{
try
{
PackMetadataSection var1 = (PackMetadataSection)this.field_148320_d.getPackMetadata(this.field_148317_a.getResourcePackRepository().rprMetadataSerializer, "pack");
if (var1 != null)
{
return var1.func_152805_a().getFormattedText();
}
}
catch (JsonParseException var2)
{
logger.error("Couldn\'t load metadata info", var2);
}
catch (IOException var3)
{
logger.error("Couldn\'t load metadata info", var3);
}
return EnumChatFormatting.RED + "Missing " + "pack.mcmeta" + " :(";
}
protected boolean func_148309_e()
{
return false;
}
protected boolean func_148308_f()
{
return false;
}
protected boolean func_148314_g()
{
return false;
}
protected boolean func_148307_h()
{
return false;
}
protected String func_148312_b()
{
return "Default";
}
protected void func_148313_c()
{
this.field_148317_a.getTextureManager().bindTexture(this.field_148321_e);
}
protected boolean func_148310_d()
{
return false;
}
}
| 412 | 0.862714 | 1 | 0.862714 | game-dev | MEDIA | 0.932261 | game-dev | 0.912997 | 1 | 0.912997 |
OvercastNetwork/SportBukkit | 2,047 | snapshot/CraftBukkit/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java | package org.bukkit.craftbukkit.entity;
import net.minecraft.server.EntityFireworks;
import net.minecraft.server.ItemStack;
import net.minecraft.server.Items;
import org.bukkit.Material;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.inventory.meta.FireworkMeta;
import java.util.Random;
public class CraftFirework extends CraftEntity implements Firework {
private final Random random = new Random();
private final CraftItemStack item;
public CraftFirework(CraftServer server, EntityFireworks entity) {
super(server, entity);
ItemStack item = getHandle().getDataWatcher().get(EntityFireworks.FIREWORK_ITEM);
if (item.isEmpty()) {
item = new ItemStack(Items.FIREWORKS);
getHandle().getDataWatcher().set(EntityFireworks.FIREWORK_ITEM, item);
}
this.item = CraftItemStack.asCraftMirror(item);
// Ensure the item is a firework...
if (this.item.getType() != Material.FIREWORK) {
this.item.setType(Material.FIREWORK);
}
}
@Override
public EntityFireworks getHandle() {
return (EntityFireworks) entity;
}
@Override
public String toString() {
return "CraftFirework";
}
@Override
public EntityType getType() {
return EntityType.FIREWORK;
}
@Override
public FireworkMeta getFireworkMeta() {
return (FireworkMeta) item.getItemMeta();
}
@Override
public void setFireworkMeta(FireworkMeta meta) {
item.setItemMeta(meta);
// Copied from EntityFireworks constructor, update firework lifetime/power
getHandle().expectedLifespan = 10 * (1 + meta.getPower()) + random.nextInt(6) + random.nextInt(7);
getHandle().getDataWatcher().markDirty(EntityFireworks.FIREWORK_ITEM);
}
@Override
public void detonate() {
getHandle().expectedLifespan = 0;
}
}
| 412 | 0.756258 | 1 | 0.756258 | game-dev | MEDIA | 0.950853 | game-dev | 0.824955 | 1 | 0.824955 |
magefree/mage | 1,813 | Mage.Sets/src/mage/cards/s/SwiftWarden.java |
package mage.cards.s;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.keyword.FlashAbility;
import mage.abilities.keyword.HexproofAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.constants.TargetController;
import mage.filter.FilterPermanent;
import mage.target.TargetPermanent;
/**
*
* @author LevelX2
*/
public final class SwiftWarden extends CardImpl {
private static final FilterPermanent filter = new FilterPermanent("Merfolk you control");
static {
filter.add(TargetController.YOU.getControllerPredicate());
filter.add(SubType.MERFOLK.getPredicate());
}
public SwiftWarden(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{G}{G}");
this.subtype.add(SubType.MERFOLK);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// Flash
this.addAbility(FlashAbility.getInstance());
// When Swift Warden enters the battlefield, target Merfolk you control gains hexproof until end of turn.
Ability ability = new EntersBattlefieldTriggeredAbility(new GainAbilityTargetEffect(HexproofAbility.getInstance(), Duration.EndOfTurn));
ability.addTarget(new TargetPermanent(filter));
this.addAbility(ability);
}
private SwiftWarden(final SwiftWarden card) {
super(card);
}
@Override
public SwiftWarden copy() {
return new SwiftWarden(this);
}
}
| 412 | 0.965461 | 1 | 0.965461 | game-dev | MEDIA | 0.975803 | game-dev | 0.993278 | 1 | 0.993278 |
WolfyScript/CustomCrafting | 3,352 | spigot/src/main/java/me/wolfyscript/customcrafting/recipes/conditions/AdvancedWorkbenchCondition.java | /*
* ____ _ _ ____ ___ ____ _ _ ____ ____ ____ ____ ___ _ _ _ ____
* | | | [__ | | | |\/| | |__/ |__| |___ | | |\ | | __
* |___ |__| ___] | |__| | | |___ | \ | | | | | | \| |__]
*
* CustomCrafting Recipe creation and management tool for Minecraft
* Copyright (C) 2021 WolfyScript
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package me.wolfyscript.customcrafting.recipes.conditions;
import com.wolfyscript.utilities.bukkit.items.CustomItemBlockData;
import me.wolfyscript.customcrafting.CustomCrafting;
import me.wolfyscript.customcrafting.recipes.CraftingRecipe;
import me.wolfyscript.customcrafting.recipes.CustomRecipe;
import me.wolfyscript.customcrafting.recipes.RecipeType;
import me.wolfyscript.customcrafting.utils.NamespacedKeyUtils;
import me.wolfyscript.utilities.api.WolfyUtilCore;
import me.wolfyscript.utilities.util.NamespacedKey;
import org.bukkit.Material;
import java.util.List;
public class AdvancedWorkbenchCondition extends Condition<AdvancedWorkbenchCondition> {
public static final NamespacedKey KEY = new NamespacedKey(NamespacedKeyUtils.NAMESPACE, "advanced_workbench");
public AdvancedWorkbenchCondition() {
super(KEY);
setAvailableOptions(Conditions.Option.EXACT);
}
@Override
public boolean check(CustomRecipe<?> recipe, Conditions.Data data) {
if (recipe instanceof CraftingRecipe) {
if (data.getBlock() != null) {
return WolfyUtilCore.getInstance().getPersistentStorage().getOrCreateWorldStorage(data.getBlock().getWorld())
.getBlock(data.getBlock().getLocation())
.flatMap(blockStorage -> blockStorage.getData(CustomItemBlockData.ID, CustomItemBlockData.class)
.map(customItemData -> customItemData.getItem().equals(CustomCrafting.ADVANCED_WORKBENCH) || customItemData.getItem().equals(CustomCrafting.ADVANCED_CRAFTING_TABLE))
)
.orElse(false);
}
return false;
}
return true;
}
@Override
public boolean isApplicable(CustomRecipe<?> recipe) {
return RecipeType.Container.CRAFTING.isInstance(recipe);
}
public static class GUIComponent extends IconGUIComponent<AdvancedWorkbenchCondition> {
public GUIComponent() {
super(Material.CRAFTING_TABLE, getLangKey("advanced_crafting_table", "name"), List.of(getLangKey("advanced_crafting_table", "description")));
}
@Override
public boolean shouldRender(RecipeType<?> type) {
return RecipeType.Container.CRAFTING.has(type);
}
}
}
| 412 | 0.891637 | 1 | 0.891637 | game-dev | MEDIA | 0.968271 | game-dev | 0.844228 | 1 | 0.844228 |
ReactVision/virocore | 2,361 | macos/Libraries/bullet/include/BulletCollision/NarrowPhaseCollision/btConvexCast.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
*/
#ifndef BT_CONVEX_CAST_H
#define BT_CONVEX_CAST_H
#include "LinearMath/btTransform.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btScalar.h"
class btMinkowskiSumShape;
#include "LinearMath/btIDebugDraw.h"
/// btConvexCast is an interface for Casting
class btConvexCast
{
public:
virtual ~btConvexCast();
///RayResult stores the closest result
/// alternatively, add a callback method to decide about closest/all results
struct CastResult
{
//virtual bool addRayResult(const btVector3& normal,btScalar fraction) = 0;
virtual void DebugDraw(btScalar fraction) {(void)fraction;}
virtual void drawCoordSystem(const btTransform& trans) {(void)trans;}
virtual void reportFailure(int errNo, int numIterations) {(void)errNo;(void)numIterations;}
CastResult()
:m_fraction(btScalar(BT_LARGE_FLOAT)),
m_debugDrawer(0),
m_allowedPenetration(btScalar(0))
{
}
virtual ~CastResult() {};
btTransform m_hitTransformA;
btTransform m_hitTransformB;
btVector3 m_normal;
btVector3 m_hitPoint;
btScalar m_fraction; //input and output
btIDebugDraw* m_debugDrawer;
btScalar m_allowedPenetration;
};
/// cast a convex against another convex object
virtual bool calcTimeOfImpact(
const btTransform& fromA,
const btTransform& toA,
const btTransform& fromB,
const btTransform& toB,
CastResult& result) = 0;
};
#endif //BT_CONVEX_CAST_H
| 412 | 0.958802 | 1 | 0.958802 | game-dev | MEDIA | 0.978243 | game-dev | 0.941296 | 1 | 0.941296 |
Elfocrash/L2dotNET | 3,917 | src/L2dotNET/Network/serverpackets/SystemMessage.cs | using System.Collections.Generic;
using L2dotNET.DataContracts.Shared.Enums;
using L2dotNET.Models;
using L2dotNET.Models.Items;
using L2dotNET.Models.Npcs;
using L2dotNET.Models.Player;
namespace L2dotNET.Network.serverpackets
{
public class SystemMessage : GameserverPacket
{
private readonly List<object[]> _data = new List<object[]>();
public int MessgeId;
public SystemMessage(SystemMessageId msgId)
{
MessgeId = (int)msgId;
}
public SystemMessage AddString(string val)
{
_data.Add(new object[] { 0, val });
return this;
}
public SystemMessage AddNumber(int val)
{
_data.Add(new object[] { 1, val });
return this;
}
public SystemMessage AddNumber(double val)
{
_data.Add(new object[] { 1, (int)val });
return this;
}
public SystemMessage AddNpcName(int val)
{
_data.Add(new object[] { 2, 1000000 + val });
return this;
}
public SystemMessage AddItemName(int val)
{
_data.Add(new object[] { 3, val });
return this;
}
public SystemMessage AddSkillName(int val, int lvl)
{
_data.Add(new object[] { 4, val, lvl });
return this;
}
public void AddCastleName(int val)
{
_data.Add(new object[] { 5, val });
}
public void AddItemCount(int val)
{
_data.Add(new object[] { 6, val });
}
public void AddZoneName(int val, int y, int z)
{
_data.Add(new object[] { 7, val, y, z });
}
public void AddElementName(int val)
{
_data.Add(new object[] { 9, val });
}
public void AddInstanceName(int val)
{
_data.Add(new object[] { 10, val });
}
public SystemMessage AddPlayerName(string val)
{
_data.Add(new object[] { 12, val });
return this;
}
public SystemMessage AddName(L2Object obj)
{
if (obj is L2Player)
return AddPlayerName(((L2Player)obj).Name);
if (obj is L2Npc)
return AddNpcName(((L2Npc)obj).NpcId);
if (obj is L2Item)
return AddItemName(((L2Item)obj).Template.ItemId);
return AddString(obj.AsString());
}
public void AddSysStr(int val)
{
_data.Add(new object[] { 13, val });
}
public override void Write()
{
WriteByte(0x64);
WriteInt(MessgeId);
WriteInt(_data.Count);
foreach (object[] d in _data)
{
int type = (int)d[0];
WriteInt(type);
switch (type)
{
case 0: //text
case 12:
WriteString((string)d[1]);
break;
case 1: //number
case 2: //npcid
case 3: //itemid
case 5:
case 9:
case 10:
case 13:
WriteInt((int)d[1]);
break;
case 4: //skillname
WriteInt((int)d[1]);
WriteInt((int)d[2]);
break;
case 6:
WriteLong((long)d[1]);
break;
case 7: //zone
WriteInt((int)d[1]);
WriteInt((int)d[2]);
WriteInt((int)d[3]);
break;
}
}
}
}
} | 412 | 0.856496 | 1 | 0.856496 | game-dev | MEDIA | 0.624098 | game-dev,networking | 0.569599 | 1 | 0.569599 |
Sigma-Skidder-Team/SigmaRebase | 2,234 | src/main/java/net/minecraft/command/impl/DeOpCommand.java | package net.minecraft.command.impl;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.command.arguments.GameProfileArgument;
import net.minecraft.server.management.PlayerList;
import net.minecraft.util.text.TranslationTextComponent;
public class DeOpCommand
{
private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(new TranslationTextComponent("commands.deop.failed"));
public static void register(CommandDispatcher<CommandSource> dispatcher)
{
dispatcher.register(Commands.literal("deop").requires((p_198325_0_) ->
{
return p_198325_0_.hasPermissionLevel(3);
}).then(Commands.argument("targets", GameProfileArgument.gameProfile()).suggests((p_198323_0_, p_198323_1_) ->
{
return ISuggestionProvider.suggest(p_198323_0_.getSource().getServer().getPlayerList().getOppedPlayerNames(), p_198323_1_);
}).executes((p_198324_0_) ->
{
return deopPlayers(p_198324_0_.getSource(), GameProfileArgument.getGameProfiles(p_198324_0_, "targets"));
})));
}
private static int deopPlayers(CommandSource source, Collection<GameProfile> players) throws CommandSyntaxException
{
PlayerList playerlist = source.getServer().getPlayerList();
int i = 0;
for (GameProfile gameprofile : players)
{
if (playerlist.canSendCommands(gameprofile))
{
playerlist.removeOp(gameprofile);
++i;
source.sendFeedback(new TranslationTextComponent("commands.deop.success", players.iterator().next().getName()), true);
}
}
if (i == 0)
{
throw FAILED_EXCEPTION.create();
}
else
{
source.getServer().kickPlayersNotWhitelisted(source);
return i;
}
}
}
| 412 | 0.826527 | 1 | 0.826527 | game-dev | MEDIA | 0.944033 | game-dev | 0.960338 | 1 | 0.960338 |
magefree/mage | 1,124 | Mage.Sets/src/mage/cards/m/MirrodinAvenged.java | package mage.cards.m;
import mage.abilities.effects.common.DestroyTargetEffect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.StaticFilters;
import mage.target.TargetPermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class MirrodinAvenged extends CardImpl {
public MirrodinAvenged(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{B}");
// Destroy target creature that was dealt damage this turn.
this.getSpellAbility().addEffect(new DestroyTargetEffect());
this.getSpellAbility().addTarget(new TargetPermanent(StaticFilters.FILTER_CREATURE_DAMAGED_THIS_TURN));
// Draw a card.
this.getSpellAbility().addEffect(new DrawCardSourceControllerEffect(1).concatBy("<br>"));
}
private MirrodinAvenged(final MirrodinAvenged card) {
super(card);
}
@Override
public MirrodinAvenged copy() {
return new MirrodinAvenged(this);
}
}
| 412 | 0.92561 | 1 | 0.92561 | game-dev | MEDIA | 0.85415 | game-dev | 0.93936 | 1 | 0.93936 |
baileyholl/Ars-Nouveau | 2,287 | src/main/java/com/hollingsworth/arsnouveau/common/network/PacketUpdateSpellColorAll.java | package com.hollingsworth.arsnouveau.common.network;
import com.hollingsworth.arsnouveau.ArsNouveau;
import com.hollingsworth.arsnouveau.api.registry.SpellCasterRegistry;
import com.hollingsworth.arsnouveau.api.spell.AbstractCaster;
import com.hollingsworth.arsnouveau.client.particle.ParticleColor;
import com.hollingsworth.arsnouveau.common.items.SpellBook;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.ItemStack;
public class PacketUpdateSpellColorAll extends PacketUpdateSpellColors {
public PacketUpdateSpellColorAll(int slot, ParticleColor color, boolean mainHand) {
super(slot, color, mainHand);
}
public PacketUpdateSpellColorAll(RegistryFriendlyByteBuf buf) {
super(buf);
}
public void toBytes(RegistryFriendlyByteBuf buf) {
super.toBytes(buf);
}
@Override
public void onServerReceived(MinecraftServer minecraftServer, ServerPlayer player) {
ItemStack stack = player.getItemInHand(mainHand ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND);
if (stack.getItem() instanceof SpellBook) {
AbstractCaster<?> caster = SpellCasterRegistry.from(stack);
for (int i = 0; i < caster.getMaxSlots(); i++) {
caster = caster.setColor(color, i);
}
caster.setCurrentSlot(castSlot).saveToStack(stack);
Networking.sendToPlayerClient(new PacketUpdateBookGUI(stack), player);
Networking.sendToPlayerClient(new PacketOpenSpellBook(mainHand ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND), player);
}
}
public static final Type<PacketUpdateSpellColorAll> TYPE = new Type<>(ArsNouveau.prefix("update_spell_color_all"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketUpdateSpellColorAll> CODEC = StreamCodec.ofMember(PacketUpdateSpellColorAll::toBytes, PacketUpdateSpellColorAll::new);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}
| 412 | 0.85082 | 1 | 0.85082 | game-dev | MEDIA | 0.895206 | game-dev,networking | 0.741687 | 1 | 0.741687 |
ronbrogan/OpenH2 | 25,061 | src/OpenH2.Engine/Systems/Physics/PhysxPhysicsSystem.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using OpenH2.Core.Architecture;
using OpenH2.Engine.Components;
using OpenH2.Engine.Components.Globals;
using OpenH2.Engine.Stores;
using OpenH2.Engine.Systems.Movement;
using OpenH2.Foundation.Physics;
using OpenH2.Physics.Colliders;
using OpenH2.Physics.Core;
using OpenH2.Physics.Proxying;
using OpenH2.Physx.Extensions;
using OpenH2.Physx.Proxies;
using PhysX;
using PhysX.VisualDebugger;
using ErrorCode = PhysX.ErrorCode;
using PxFoundation = PhysX.Foundation;
using PxPhysics = PhysX.Physics;
using PxScene = PhysX.Scene;
using PxTolerancesScale = PhysX.TolerancesScale;
namespace OpenH2.Engine.Systems.Physics
{
public class PhysxPhysicsSystem : WorldSystem
{
private PxFoundation physxFoundation;
private PxPhysics physxPhysics;
private PxScene physxScene;
private PxTolerancesScale physxScale;
private ControllerManager controllerManager;
private Cooking cooker;
private Pvd pvd;
private Material defaultMat;
private Material characterControlMat;
private Material frictionlessMat;
private MaterialListComponent materialList;
private Material[] globalMaterials;
private Dictionary<int, Material> adhocMaterials = new Dictionary<int, Material>();
private Dictionary<MoverComponent, Controller> ControllerMap = new Dictionary<MoverComponent, Controller>();
private PhysicsForceQueue queuedForces = new PhysicsForceQueue();
private IContactCreateProvider contactProvider;
private InputStore input;
public bool StepMode = false;
public bool ShouldStep = false;
private SimulationCallback simCallback;
public PhysxPhysicsSystem(World world) : base(world)
{
// Setup PhysX infra here
physxFoundation = new PxFoundation(new ConsoleErrorCallback());
physxScale = new PxTolerancesScale()
{
Length = 0.1f,
Speed = 98.1f
};
#if DEBUG
pvd = new Pvd(physxFoundation);
pvd.Connect("localhost", 5425, TimeSpan.FromSeconds(2), InstrumentationFlag.Debug);
physxPhysics = new PxPhysics(physxFoundation, physxScale, false, pvd);
#else
this.physxPhysics = new PxPhysics(this.physxFoundation, this.physxScale);
#endif
defaultMat = physxPhysics.CreateMaterial(0.5f, 0.5f, 0.1f);
characterControlMat = physxPhysics.CreateMaterial(0.5f, 0.5f, 0f);
characterControlMat.RestitutionCombineMode = CombineMode.Minimum;
frictionlessMat = physxPhysics.CreateMaterial(0f, 0f, 0f);
frictionlessMat.RestitutionCombineMode = CombineMode.Minimum;
frictionlessMat.Flags = MaterialFlags.DisableFriction;
var sceneDesc = new SceneDesc(physxScale)
{
BroadPhaseType = BroadPhaseType.SweepAndPrune,
Gravity = world.Gravity,
Flags = SceneFlag.EnableStabilization,
SolverType = SolverType.TGS,
FilterShader = new DefaultFilterShader(),
BounceThresholdVelocity = 0.2f * world.Gravity.Length()
};
physxScene = physxPhysics.CreateScene(sceneDesc);
#if DEBUG
physxScene.SetVisualizationParameter(VisualizationParameter.ContactPoint, true);
physxScene.SetVisualizationParameter(VisualizationParameter.ContactNormal, true);
physxScene.SetVisualizationParameter(VisualizationParameter.ContactForce, true);
physxScene.SetVisualizationParameter(VisualizationParameter.ContactError, true);
var pvdClient = physxScene.GetPvdSceneClient();
pvdClient.SetScenePvdFlags(SceneVisualizationFlags.TransmitContacts | SceneVisualizationFlags.TransmitConstraints | SceneVisualizationFlags.TransmitSceneQueries);
#endif
var cookingParams = new CookingParams()
{
Scale = physxScale,
AreaTestEpsilon = 0.001f,
MidphaseDesc = new MidphaseDesc()
{
Bvh33Desc = new Bvh33MidphaseDesc()
{
MeshCookingHint = MeshCookingHint.SimulationPerformance
}
},
BuildTriangleAdjacencies = true,
MeshCookingHint = MeshCookingHint.SimulationPerformance,
MeshWeldTolerance = 0.001f
};
cooker = physxPhysics.CreateCooking(cookingParams);
controllerManager = physxScene.CreateControllerManager();
var contactProv = new ContactModifyProxy();
contactProvider = contactProv;
physxScene.ContactModifyCallback = contactProv;
simCallback = new SimulationCallback();
physxScene.SetSimulationEventCallback(simCallback);
}
public override void Initialize(Core.Architecture.Scene scene)
{
// Setup materials from globals
adhocMaterials.Clear();
materialList = world.Components<MaterialListComponent>().FirstOrDefault();
Debug.Assert(materialList != null);
var allMaterials = materialList.GetPhysicsMaterials();
globalMaterials = new Material[allMaterials.Length + 1];
globalMaterials[0] = defaultMat;
Debug.Assert(allMaterials.Length > allMaterials.Max(m => m.Id));
foreach (var mat in allMaterials)
{
GetOrCreateMaterial(mat.Id);
}
// Cook terrain and static geom meshes
var terrains = world.Components<StaticTerrainComponent>();
foreach (var terrain in terrains)
{
AddTerrain(terrain);
}
var sceneries = world.Components<StaticGeometryComponent>();
foreach (var scenery in sceneries)
{
AddStaticGeom(scenery);
}
var rigidBodies = world.Components<RigidBodyComponent>();
foreach (var body in rigidBodies)
{
AddRigidBodyComponent(body);
}
var movers = world.Components<MoverComponent>();
foreach (var mover in movers)
{
AddCharacterController(mover);
}
var triggers = world.Components<TriggerGeometryComponent>();
foreach (var trigger in triggers)
{
AddTrigger(trigger);
}
scene.OnEntityAdd += AddEntity;
scene.OnEntityRemove += RemoveEntity;
}
private const float stepSize = 1f / 100f;
private double totalTime = 0d;
private double simulatedTime = 0d;
public override void Update(double timestep)
{
totalTime += timestep;
// Take fixed-size steps until we've caught up with reality
while (totalTime - simulatedTime > stepSize)
{
simulatedTime += stepSize;
TakeStep(stepSize);
}
}
private void TakeStep(float step)
{
// Split simulation to allow modification of current simulation step
physxScene.Collide(step);
physxScene.FetchCollision(block: true);
// Need to apply any forces here, between FetchCollision and Advance.
// However, contacts aren't available here - we'll need to record contacts or something during ContactModify via the Collide phase
foreach (var (body, velocity) in queuedForces.VelocityChanges)
{
body.AddVelocity(velocity);
}
foreach (var (body, force) in queuedForces.ForceChanges)
{
body.AddForce(force);
}
queuedForces.Clear();
physxScene.Advance();
physxScene.FetchResults(block: true);
// Update all engine transforms
foreach (var actor in physxScene.RigidDynamicActors)
{
if (actor.UserData is RigidBodyComponent rigid)
{
rigid.Transform.UseTransformationMatrix(actor.GlobalPose);
}
else if (actor.UserData is MoverComponent mover)
{
mover.Transform.Position = actor.GlobalPosePosition;
mover.Transform.UpdateDerivedData();
}
}
foreach (var controller in controllerManager.Controllers)
{
if (controller.Actor.UserData is MoverComponent mover)
{
mover.Transform.Position = controller.Position;
mover.Transform.UpdateDerivedData();
}
}
// TODO: track touch found/lost somwhere
foreach (var triggerSet in simCallback.TriggerEventSets)
{
foreach (var triggerEvent in triggerSet)
{
var comp = triggerEvent.TriggerActor.UserData as TriggerGeometryComponent;
Debug.Assert(comp != null);
Console.WriteLine($"[TRIG] {comp.Name} <{triggerEvent.Status}> {triggerEvent.OtherActor.UserData.ToString()}");
}
}
simCallback.TriggerEventSets.Clear();
}
public void AddEntity(Entity entity)
{
var rigidBodies = entity.GetChildren<RigidBodyComponent>();
foreach (var body in rigidBodies)
{
AddRigidBodyComponent(body);
}
if (entity.TryGetChild<MoverComponent>(out var mover))
{
AddCharacterController(mover);
}
foreach (var trigger in entity.GetChildren<TriggerGeometryComponent>())
{
AddTrigger(trigger);
}
if (entity.TryGetChild<StaticTerrainComponent>(out var terrain))
{
AddTerrain(terrain);
}
if (entity.TryGetChild<StaticGeometryComponent>(out var geom))
{
AddStaticGeom(geom);
}
}
private void RemoveEntity(Entity entity)
{
if (entity.TryGetChild<RigidBodyComponent>(out var rigidBody))
{
RemoveRigidBodyComponent(rigidBody);
}
if (entity.TryGetChild<MoverComponent>(out var mover))
{
RemoveCharacterController(mover);
}
if (entity.TryGetChild<TriggerGeometryComponent>(out var trigger))
{
RemoveTrigger(trigger);
}
if (entity.TryGetChild<StaticTerrainComponent>(out var terrain))
{
RemoveTerrain(terrain);
}
if (entity.TryGetChild<StaticGeometryComponent>(out var geom))
{
RemoveStaticGeom(geom);
}
}
public void AddRigidBodyComponent(RigidBodyComponent component)
{
if (component.PhysicsImplementation is not RigidDynamic dynamic)
{
dynamic = physxPhysics.CreateRigidDynamic(component.Transform.TransformationMatrix);
dynamic.CenterOfMassLocalPose = Matrix4x4.CreateTranslation(component.CenterOfMass);
dynamic.MassSpaceInertiaTensor = MathUtil.Diagonalize(component.InertiaTensor);
dynamic.Mass = component.Mass;
component.PhysicsImplementation = new RigidBodyProxy(dynamic);
if (component.IsDynamic == false)
{
dynamic.RigidBodyFlags = RigidBodyFlag.Kinematic;
}
dynamic.UserData = component;
dynamic.Name = component.Parent.FriendlyName ?? component.Parent.Id.ToString();
AddCollider(dynamic, component.Collider);
}
physxScene.AddActor(dynamic);
if (component.IsDynamic)
{
dynamic.PutToSleep();
}
}
// TODO: Currently, this system is responsible for creating and setting PhysicsImplementation properties
// -issue: PhysicsImplementations can't be passed/delegated before this system is initialized, as the props are unset
// -motive: DynamicMovementController wants to be able to setup callbacks before any physics events happen
public void AddCharacterController(MoverComponent component)
{
var config = component.Config;
var radius = 0.175f;
// TODO: reduce duplicated code
if (component.Mode == MoverComponent.MovementMode.Freecam)
{
var posPose = Matrix4x4.CreateTranslation(component.Transform.TransformationMatrix.Translation);
var rot = Matrix4x4.CreateRotationY(MathF.PI / -2f);
var body = physxPhysics.CreateRigidDynamic(rot * posPose);
body.MassSpaceInertiaTensor = new Vector3(0, 0, 0);
body.Mass = 175f;
body.UserData = component;
body.RigidBodyFlags = RigidBodyFlag.Kinematic;
var capsuleDesc = new CapsuleGeometry(radius, config.Height / 2f - radius);
var shape = RigidActorExt.CreateExclusiveShape(body, capsuleDesc, characterControlMat);
// TODO: centralize filter data construction
shape.SimulationFilterData = new FilterData((uint)(OpenH2FilterData.NoClip | OpenH2FilterData.PlayerCharacter), 0, 0, 0);
shape.ContactOffset = 0.001f;
shape.RestOffset = 0.0009f;
var bodyProxy = new RigidBodyProxy(body);
component.PhysicsImplementation = bodyProxy;
physxScene.AddActor(body);
}
if (component.Mode == MoverComponent.MovementMode.KinematicCharacterControl)
{
var desc = new CapsuleControllerDesc()
{
Height = config.Height - .02f - 2 * radius,
Position = component.Transform.Position,
Radius = radius,
MaxJumpHeight = 1f,
UpDirection = EngineGlobals.Up,
SlopeLimit = MathF.Cos(0.872665f), // cos(50 degrees)
StepOffset = 0.1f,
Material = defaultMat,
ContactOffset = 0.0001f,
ReportCallback = new CustomHitReport()
};
var controller = controllerManager.CreateController<CapsuleController>(desc);
controller.Actor.UserData = component;
component.PhysicsImplementation = new KinematicCharacterControllerProxy(controller);
ControllerMap.Add(component, controller);
}
else if (component.Mode == MoverComponent.MovementMode.DynamicCharacterControl)
{
var posPose = Matrix4x4.CreateTranslation(component.Transform.TransformationMatrix.Translation);
var rot = Matrix4x4.CreateRotationY(MathF.PI / -2f);
var body = physxPhysics.CreateRigidDynamic(rot * posPose);
body.MassSpaceInertiaTensor = new Vector3(0, 0, 0);
body.Mass = 175f;
body.UserData = component;
var capsuleDesc = new CapsuleGeometry(radius, config.Height / 2f - radius);
var shape = RigidActorExt.CreateExclusiveShape(body, capsuleDesc, characterControlMat);
// TODO: centralize filter data construction
shape.SimulationFilterData = new FilterData((uint)OpenH2FilterData.PlayerCharacter, 0, 0, 0);
shape.ContactOffset = 0.001f;
shape.RestOffset = 0.0009f;
var bodyProxy = new RigidBodyProxy(body);
component.PhysicsImplementation = bodyProxy;
physxScene.AddActor(body);
if (component.State is DynamicMovementController dynamicMover)
{
var contactInfo = ContactCallbackData.Normal;
contactProvider.RegisterContactCallback(body, contactInfo, dynamicMover.ContactFound);
}
}
}
public void AddTrigger(TriggerGeometryComponent component)
{
var halfSize = component.Size / 2f;
var posPose = Matrix4x4.CreateTranslation(component.Transform.TransformationMatrix.Translation);
var rot = Matrix4x4.CreateFromQuaternion(component.Transform.Orientation);
var posCorrection = Matrix4x4.CreateTranslation(halfSize);
var body = physxPhysics.CreateRigidStatic(posCorrection * rot * posPose);
body.Name = component.Name;
Geometry volume = component.Shape switch
{
TriggerGeometryShape.Cuboid => new BoxGeometry(halfSize),
};
var shape = RigidActorExt.CreateExclusiveShape(body, volume, defaultMat, ShapeFlag.TriggerShape);
shape.SimulationFilterData = new FilterData((uint)OpenH2FilterData.TriggerVolume, 0, 0, 0);
body.UserData = component;
physxScene.AddActor(body);
}
private void AddStaticGeom(StaticGeometryComponent geom)
{
if (geom.PhysicsActor is RigidStatic existingRigid)
{
physxScene.AddActor(existingRigid);
return;
}
var rigid = physxPhysics.CreateRigidStatic(geom.Transform.TransformationMatrix);
AddCollider(rigid, geom.Collider);
physxScene.AddActor(rigid);
geom.PhysicsActor = rigid;
}
private void AddTerrain(StaticTerrainComponent terrain)
{
if (terrain.PhysicsActor is RigidStatic existingRigid)
{
physxScene.AddActor(existingRigid);
return;
}
var rigid = physxPhysics.CreateRigidStatic();
AddCollider(rigid, terrain.Collider);
physxScene.AddActor(rigid);
terrain.PhysicsActor = rigid;
}
private void RemoveStaticGeom(StaticGeometryComponent geom)
{
if (geom.PhysicsActor is RigidStatic rigid)
{
physxScene.RemoveActor(rigid);
}
}
private void RemoveTerrain(StaticTerrainComponent terrain)
{
if (terrain.PhysicsActor is RigidStatic rigid)
{
physxScene.RemoveActor(rigid);
}
}
public void RemoveRigidBodyComponent(RigidBodyComponent component)
{
if (component.PhysicsImplementation is RigidBodyProxy p)
{
physxScene.RemoveActor(p.RigidBody);
}
}
private void RemoveCharacterController(MoverComponent mover)
{
if (ControllerMap.TryGetValue(mover, out var ctrl))
{
//?
}
}
private void RemoveTrigger(TriggerGeometryComponent comp)
{
// TODO: implement cleaning up triggers
}
private void AddCollider(RigidActor actor, ICollider collider)
{
if (collider is AggregateCollider agg)
{
foreach (var c in agg.ColliderComponents)
AddCollider(actor, c);
}
else if (collider is TriangleMeshCollider triCollider)
{
var desc = triCollider.GetDescriptor(GetMaterialIndices);
// Avoiding offline cook path for now because
// 1. Comments in Physx.Net imply memory leak using streams
// 2. I don't want to deal with disk caching cooks yet
var finalMesh = physxPhysics.CreateTriangleMesh(cooker, desc);
var meshGeom = new TriangleMeshGeometry(finalMesh);
RigidActorExt.CreateExclusiveShape(actor, meshGeom, globalMaterials, null);
}
else if (collider is TriangleModelCollider triModelCollider)
{
foreach (var mesh in triModelCollider.MeshColliders)
{
var desc = mesh.GetDescriptor(GetMaterialIndices);
// Avoiding offline cook path for now because
// 1. Comments in Physx.Net imply memory leak using streams
// 2. I don't want to deal with disk caching cooks yet
var finalMesh = physxPhysics.CreateTriangleMesh(cooker, desc);
var meshGeom = new TriangleMeshGeometry(finalMesh);
RigidActorExt.CreateExclusiveShape(actor, meshGeom, globalMaterials, null);
}
}
else if (collider is IVertexBasedCollider vertCollider)
{
var desc = new ConvexMeshDesc() { Flags = ConvexFlag.ComputeConvex };
desc.SetPositions(vertCollider.GetTransformedVertices());
var mesh = physxPhysics.CreateConvexMesh(cooker, desc);
var geom = new ConvexMeshGeometry(mesh);
var mat = GetOrCreateMaterial(vertCollider.PhysicsMaterial);
// TODO: re-use shared shapes instead of creating exclusive
RigidActorExt.CreateExclusiveShape(actor, geom, mat);
}
else if (collider is ConvexModelCollider modelCollider)
{
foreach (var verts in modelCollider.Meshes)
{
var desc = new ConvexMeshDesc() { Flags = ConvexFlag.ComputeConvex };
desc.SetPositions(verts);
var mesh = physxPhysics.CreateConvexMesh(cooker, desc);
var geom = new ConvexMeshGeometry(mesh);
var mat = GetOrCreateMaterial(modelCollider.PhysicsMaterial);
// TODO: re-use shared shapes instead of creating exclusive
RigidActorExt.CreateExclusiveShape(actor, geom, mat);
}
}
}
private Material GetOrCreateMaterial(int id)
{
// This method accounts for having defaultMat at location 0 of the globalMaterials array
// Because of this, any id check against the array must be incremented by 1 and checked appropriately
Material mat;
// If it's a valid index and the expanded mats array can hold it, and it's not null, use it
if (id >= 0 && globalMaterials.Length - 1 > id && globalMaterials[id + 1] != null)
return globalMaterials[id + 1];
else if (adhocMaterials.TryGetValue(id, out mat))
return mat;
// Get original def with raw id
var matDef = materialList?.GetPhysicsMaterial(id);
if (matDef == null)
return defaultMat;
mat = physxPhysics.CreateMaterial(matDef.StaticFriction, matDef.DynamicFriction, matDef.Restitution);
// If it's a valid index and the expanded mats array can hold it, set it
if (id >= 0 && globalMaterials.Length - 1 > id)
globalMaterials[id + 1] = mat;
else
adhocMaterials[id] = mat;
return mat;
}
private short[] GetMaterialIndices(int[] array)
{
// Add 1 to the index (account for default mat at 0)
// and cast to short for PhysX
return array.Select(i => (short)(i + 1)).ToArray();
}
private class CustomHitReport : UserControllerHitReport
{
public override void OnControllerHit(ControllersHit hit)
{
//throw new NotImplementedException();
}
public override void OnObstacleHit(ControllerObstacleHit hit)
{
//throw new NotImplementedException();
}
public override void OnShapeHit(ControllerShapeHit hit)
{
if (hit.Shape.Actor.IsDynamic == false)
return;
var dynamicActor = hit.Shape.Actor as RigidDynamic;
dynamicActor.AddForceAtPosition(hit.WorldNormal, hit.WorldPosition, ForceMode.Impulse, true);
}
}
private class ConsoleErrorCallback : ErrorCallback
{
public override void ReportError(ErrorCode errorCode, string message, string file, int lineNumber)
{
Console.WriteLine("[PHYSX-{0}] {1} @ {2}:{3}", errorCode.ToString(), message, file, lineNumber);
}
}
}
}
| 412 | 0.785254 | 1 | 0.785254 | game-dev | MEDIA | 0.952292 | game-dev | 0.919843 | 1 | 0.919843 |
Praytic/youtd2 | 1,857 | src/towers/tower_behaviors/void_drake.gd | extends TowerBehavior
var silence_bt: BuffType
func get_tier_stats() -> Dictionary:
return {
1: {mod_damage_add = 0.12, silence_duration = 1.25, silence_duration_add = 0.07, boss_silence_multiplier = 0.33, void_exp_loss = 0.010, void_exp_loss_add = 0.0002},
2: {mod_damage_add = 0.20, silence_duration = 1.75, silence_duration_add = 0.13, boss_silence_multiplier = 0.25, void_exp_loss = 0.015, void_exp_loss_add = 0.0003},
}
func load_triggers(triggers: BuffType):
triggers.add_event_on_damage(on_damage)
triggers.add_periodic_event(periodic, 1.0)
func tower_init():
silence_bt = CbSilence.new("void_drake_silence", 0, 0, false, self)
func on_damage(event: Event):
var creep: Unit = event.get_target()
var silence_duration: float = _stats.silence_duration + _stats.silence_duration_add * tower.get_level()
if creep.get_size() == CreepSize.enm.BOSS:
silence_duration = silence_duration * _stats.boss_silence_multiplier
silence_bt.apply_only_timed(tower, event.get_target(), silence_duration)
func periodic(_event: Event):
var level: int = tower.get_level()
var current_exp: float = tower.get_exp()
var exp_for_level: int = Experience.get_exp_for_level(level)
var exp_before_level_down: float = current_exp - exp_for_level
var exp_removed: float = current_exp * (_stats.void_exp_loss + _stats.void_exp_loss_add * level)
if exp_removed > exp_before_level_down:
exp_removed = exp_before_level_down
if exp_removed >= 0.1 && level != 25:
tower.remove_exp_flat(exp_removed)
func on_create(preceding: Tower):
if preceding == null:
return
var same_family: bool = tower.get_family() == preceding.get_family()
if same_family:
var exp_loss: float = tower.get_exp() * (0.5 + 0.01 * tower.get_level())
tower.remove_exp_flat(exp_loss)
else:
var exp_loss: float = tower.get_exp()
tower.remove_exp_flat(exp_loss)
| 412 | 0.860301 | 1 | 0.860301 | game-dev | MEDIA | 0.905258 | game-dev | 0.874787 | 1 | 0.874787 |
LingASDJ/Magic_Ling_Pixel_Dungeon | 22,603 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/bosses/bossrush/Rival.java | package com.shatteredpixel.shatteredpixeldungeon.actors.mobs.bosses.bossrush;
import static com.shatteredpixel.shatteredpixeldungeon.Dungeon.hero;
import static com.shatteredpixel.shatteredpixeldungeon.Dungeon.level;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.Statistics;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Boss;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Amok;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.BlobImmunity;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Chill;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Corrosion;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Corruption;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Doom;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Dread;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.FrostBurning;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Healing;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Paralysis;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.PinCushion;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Terror;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.MobSpawner;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.lb.RivalSprite;
import com.shatteredpixel.shatteredpixeldungeon.effects.CellEmitter;
import com.shatteredpixel.shatteredpixeldungeon.effects.Flare;
import com.shatteredpixel.shatteredpixeldungeon.effects.Speck;
import com.shatteredpixel.shatteredpixeldungeon.effects.SpellSprite;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.items.KindofMisc;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor.Glyph;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfHealing;
import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfHaste;
import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfTenacity;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRetribution;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTeleportation;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.exotic.ScrollOfPsionicBlast;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.Wand;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfBlastWave;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfCorrosion;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfFirebolt;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfFrost;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfMagicMissile;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.hightwand.WandOfVenom;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.Weapon.Enchantment;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.enchantments.Grim;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MeleeWeapon;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.missiles.MissileWeapon;
import com.shatteredpixel.shatteredpixeldungeon.levels.nosync.DeepShadowLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.traps.GrimTrap;
import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.CharSprite;
import com.shatteredpixel.shatteredpixeldungeon.ui.BossHealthBar;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.Bundle;
import com.watabou.utils.Callback;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Random;
import com.watabou.utils.Reflection;
import java.util.ArrayList;
public class Rival extends Boss implements Callback {
private static final float TIME_TO_ZAP = 1f;
@Override
public String name() {
if(Dungeon.hero != null){
return Messages.get(this,"name",hero.name());
} else {
return Messages.get(this,"namex");
}
}
{
spriteClass = RivalSprite.class;
properties.add(Property.BOSS);
HUNTING = new Hunting();
WANDERING = new Wandering();
if(Statistics.bossRushMode){
immunities.add(Corrosion.class);
immunities.add(Chill.class);
immunities.add(FrostBurning.class);
}
}
public MeleeWeapon weapon;
public Armor armor;
public KindofMisc misc1;
public KindofMisc misc2;
public Wand wand;
public MissileWeapon missile;
private int blinkCooldown = 0;
private boolean blink( int target ) {
Ballistica route = new Ballistica( pos, target, Ballistica.PROJECTILE);
int cell = route.collisionPos;
BlobImmunity mb = buff(BlobImmunity.class);{
if(mb == null && Random.Int(10)<4){
GLog.w( Messages.get(this, "protected",name()) );
Buff.prolong( this, BlobImmunity.class, BlobImmunity.DURATION*2 );
SpellSprite.show(this, SpellSprite.PURITY);
}
}
//can't occupy the same cell as another char, so move back one.
if (Actor.findChar( cell ) != null && cell != this.pos)
cell = route.path.get(route.dist-1);
if (level.avoid[ cell ] || (properties().contains(Property.LARGE) && !level.openSpace[cell])){
ArrayList<Integer> candidates = new ArrayList<>();
for (int n : PathFinder.NEIGHBOURS8) {
cell = route.collisionPos + n;
if (level.passable[cell]
&& Actor.findChar( cell ) == null
&& (!properties().contains(Property.LARGE) || level.openSpace[cell])) {
candidates.add( cell );
}
}
if (candidates.size() > 0)
cell = Random.element(candidates);
else {
blinkCooldown = Random.IntRange(4, 6);
return false;
}
}
ScrollOfTeleportation.appear( this, cell );
blinkCooldown = Random.IntRange(4, 6);
return true;
}
public Rival() {
super();
int lvl = Dungeon.hero == null ? 30 : hero.lvl;
if(hero != null){
//melee
do {
weapon = (MeleeWeapon)Generator.random(Generator.Category.WEAPON);
} while (weapon.cursed);
weapon.enchant(Enchantment.random());
weapon.identify();
flying = true;
//armor
do {
armor = (Armor)Generator.random(Generator.Category.ARMOR);
} while (armor.cursed);
armor.inscribe(Glyph.random());
armor.identify();
//misc1
do {
misc1 = (KindofMisc)Generator.random(Generator.Category.RING);
} while (misc1.cursed);
misc1.identify();
//misc2
do {
misc2 = (KindofMisc)Generator.random(Generator.Category.RING);
} while (misc2.cursed);
misc2.identify();
//wand
do {
wand = RandomWand();
} while (wand.cursed);
wand.updateLevel();
wand.curCharges = 20;
wand.identify();
//missile
do {
missile = (MissileWeapon)Generator.random(Generator.Category.MISSILE);
} while (missile.cursed);
defenseSkill = (int)(armor.evasionFactor( this, 7 + lvl ));
} else {
defenseSkill = 7 + lvl;
}
HP = HT = 50 + lvl * 5;
EXP = lvl * 17;
}
private static final String WEAPON = "weapon";
private static final String ARMOR = "armor";
private static final String MISC1 = "misc1";
private static final String MISC2 = "misc2";
private static final String WAND = "wand";
private static final String MISSILE = "missile";
private static final String BLINK_CD = "blink_cd";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put( WEAPON, weapon );
bundle.put( ARMOR, armor );
bundle.put( MISC1, misc1 );
bundle.put( MISC2, misc2 );
bundle.put( WAND, wand );
bundle.put( MISSILE, missile );
bundle.put(BLINK_CD, blinkCooldown);
}
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
weapon = (MeleeWeapon) bundle.get( WEAPON );
armor = (Armor) bundle.get( ARMOR );
misc1 = (KindofMisc) bundle.get( MISC1 );
misc2 = (KindofMisc) bundle.get( MISC2 );
wand = (Wand) bundle.get( WAND );
blinkCooldown = bundle.getInt(BLINK_CD);
missile = (MissileWeapon) bundle.get( MISSILE );
if (state != SLEEPING) BossHealthBar.assignBoss(this);
if ((HP*2 <= HT)) BossHealthBar.bleed(true);
}
@Override
public int damageRoll() {
int dmg = 0;
dmg += weapon.damageRoll( this );
if (dmg < 0) dmg = 0;
return dmg;
}
@Override
public int drRoll() {
int dr = 0;
dr += Random.NormalIntRange( armor.DRMin(), armor.DRMax() );
dr += Random.NormalIntRange( 0, weapon.defenseFactor( this ) );
if (dr < 0) dr = 0;
return dr;
}
@Override
public int attackSkill( Char target ) {
return (int)((16 + Dungeon.depth) * weapon.accuracyFactor( this,target ));
}
@Override
public float attackDelay() {
return super.attackDelay() * weapon.speedFactor( this );
}
@Override
public float speed() {
float speed = 0;
if(misc1 instanceof RingOfHaste || misc2 instanceof RingOfHaste){
speed += RingOfHaste.speedMultiplier(this);
}
if(armor != null){
speed += armor.speedFactor( this, super.speed() );
}
return speed;
}
@Override
protected boolean getCloser(int target) {
// 判断远程攻击能力是否失效
boolean hasRangedOption;
if (HP < HT / 2) {
// 半血以下时,投掷武器是否可用?
hasRangedOption = missile != null && missile.quantity > 0;
} else {
// 半血以上时,法杖充能是否可用?
hasRangedOption = wand != null && wand.curCharges > 0;
}
// 如果没有远程攻击手段,强制逼近玩家
if (!hasRangedOption) {
return super.getCloser(target);
}
// 如果有远程攻击手段,执行原有逻辑
if (HP < HT / 2 && state == HUNTING) {
// 半血以下且处于 HUNTING 状态时,远离玩家
return enemySeen && getFurther(target);
} else if (fieldOfView[target] && level.distance(pos, target) > 2 && blinkCooldown <= 0 && !rooted) {
// 使用闪烁技能逼近玩家
if (blink(target)) {
spend(-1 / speed());
return true;
} else {
return false;
}
} else {
// 其他情况,正常逼近玩家
blinkCooldown--;
return super.getCloser(target);
}
}
@Override
protected boolean canAttack(Char enemy) {
boolean canRanged = (HP < HT/2 && missile.quantity > 0)
|| (HP >= HT/2 && wand.curCharges > 0);
boolean canMelee = level.adjacent(pos, enemy.pos) || weapon.canReach(this, enemy.pos);
return canRanged || canMelee || super.canAttack(enemy);
}
@Override
protected boolean doAttack(Char enemy) {
// 检查是否在近战范围内
boolean inMeleeRange = level.adjacent(pos, enemy.pos) || weapon.canReach(this, enemy.pos);
// 如果不在近战范围内,尝试远程攻击
if (!inMeleeRange) {
boolean visible = fieldOfView[pos] || fieldOfView[enemy.pos];
// 半血以下时,优先使用投掷武器
if (HP < HT / 2 && missile != null && missile.quantity > 0) {
if (visible) {
sprite.toss(enemy.pos); // 可见时播放投掷动画
} else {
toss(); // 不可见时直接投掷
}
missile.quantity--; // 消耗投掷武器弹药
return !visible; // 返回是否不可见
}
// 半血以上时,优先使用法杖
if (wand != null && wand.curCharges > 0) {
if (visible) {
sprite.zap(enemy.pos); // 可见时播放法杖动画
} else {
zap(); // 不可见时直接施法
}
wand.curCharges--; // 消耗法杖充能
return !visible; // 返回是否不可见
}
}
// 如果没有远程攻击条件,或者已经在近战范围内,切换到近战攻击
return super.doAttack(enemy);
}
private void zap() {
spend( TIME_TO_ZAP );
final Ballistica shot = new Ballistica( pos, enemy == null ? 0 :enemy.pos, wand.collisionProperties);
wand.rivalOnZap( shot, this );
}
private void toss() {
spend( TIME_TO_ZAP );
if (hit( this, enemy, true )) {
enemy.damage( this.missile.damageRoll(this), this.missile.getClass() );
} else {
enemy.sprite.showStatus( CharSprite.NEUTRAL, enemy.defenseVerb() );
}
}
public void onZapComplete() {
zap();
next();
}
public void onTossComplete() {
toss();
next();
}
@Override
public void call() {
next();
}
@Override
public int attackProc( Char enemy, int damage ) {
damage = super.attackProc( enemy, damage );
return weapon.proc( this, enemy, damage );
}
@Override
public int defenseProc( Char enemy, int damage ) {
damage = super.defenseProc( enemy, damage );
return armor.proc( enemy, this, damage );
}
@Override
public void damage( int dmg, Object src ) {
super.damage( dmg, src );
if (HP <= 0) {
spend( TICK );
}
}
private int SummonMob() {
int order;
DeepShadowLevel.State state = ((DeepShadowLevel) level).state();
switch(state) {
case PHASE_3:
order = Random.NormalIntRange(16, 19);
break;
case PHASE_4:
order = Random.NormalIntRange(21, 24);
break;
case PHASE_2:case PHASE_1:
order = Random.NormalIntRange(11, 14);
break;
default:
order = Random.NormalIntRange(6, 9);;
break;
}
return order;
}
public void summon(int Rpos) {
if(Statistics.bossRushMode){
sprite.centerEmitter().start( Speck.factory( Speck.SCREAM ), 0.4f, 2 );
Sample.INSTANCE.play( Assets.Sounds.CHALLENGE );
int numberOfMobs = Random.Int(2, 6);
for(int i = 0;i <= numberOfMobs ; i++){
Mob syncmob = Reflection.newInstance(MobSpawner.getMobRotation(SummonMob()).get(0));
syncmob.state = syncmob.WANDERING;
syncmob.pos = Rpos;
if (SummonMob() > 20) {
syncmob.HP = (int) (syncmob.HT * 0.75f);
syncmob.defenseSkill = syncmob.defenseSkill / 2;
}
syncmob.immunities.add(Corrosion.class);
syncmob.immunities.add(Chill.class);
GameScene.add(syncmob);
syncmob.beckon(hero.pos);
}
yell( Messages.get(this, "arise") );
}
}
@Override
public void die( Object cause ) {
level.unseal();
DeepShadowLevel.State state = ((DeepShadowLevel) level).state();
if (state != DeepShadowLevel.State.WON) {
//cures doom and drops missile weapons
for (Buff buff : buffs()) {
if (buff instanceof Doom || buff instanceof PinCushion) {
buff.detach();
}
}
switch(state) {
case BRIDGE:
HP = 1;
PotionOfHealing.cure(this);
Buff.detach(this, Paralysis.class);
((DeepShadowLevel) level).progress();
yell( Messages.get(this, "interrobang") );
return;
case PHASE_1:
case PHASE_2:
case PHASE_3:
case PHASE_4:
HP = HT;
for (Mob mob : level.mobs.toArray(new Mob[0])){
if(mob instanceof Rival){
Buff.affect(mob, Dread.class);
}
}
PotionOfHealing.cure(this);
Buff.detach(this, Paralysis.class);
if (level.heroFOV[pos] && hero.isAlive()) {
new Flare(8, 32).color(0xFFFF66, true).show(sprite, 2f);
CellEmitter.get(this.pos).start(Speck.factory(Speck.LIGHT), 0.2f, 3);
Sample.INSTANCE.play( Assets.Sounds.TELEPORT );
GLog.w( Messages.get(this, "revive") );
}
((DeepShadowLevel) level).progress();
yell( Messages.get(this, "exclamation") );
switch (state) {
case PHASE_1:
wand = new WandOfFrost();
wand.curCharges = 20;
wand.level(3);
wand.updateLevel();
missile.quantity = 2;
break;
case PHASE_2:
wand = new WandOfBlastWave();
wand.curCharges = 40;
misc1 = new RingOfHaste();
wand.level(2);
wand.updateLevel();
missile.quantity = 2;
break;
case PHASE_3:
wand = new WandOfFirebolt();
misc1 = new RingOfHaste();
wand.level(1);
wand.updateLevel();
wand.curCharges = 80;
missile.quantity = 3;
break;
case PHASE_4:
wand = new WandOfVenom();
wand.curCharges = 10;
wand.level(4);
wand.updateLevel();
missile.quantity = Random.IntRange(2, 4);
break;
}
HP = HT;
missile = (MissileWeapon)Generator.random(Generator.Category.MISSILE);
return;
case PHASE_5:
((DeepShadowLevel) level).progress();
super.die( cause );
wand = new WandOfMagicMissile();
misc1 = new RingOfTenacity();
wand.curCharges = 4;
Statistics.doNotLookLing = true;
GameScene.bossSlain();
yell( Messages.get(this, "ellipsis") );
return;
case WON:
default:
}
} else {
super.die( cause );
GameScene.bossSlain();
yell( Messages.get(this, "ellipsis") );
}
}
@Override
public void notice() {
super.notice();
level.seal();
//BGMPlayer.playBGM(Assets.BGM_YOU, true);
if (!BossHealthBar.isAssigned()) {
BossHealthBar.assignBoss(this);
yell(Messages.get(this, "question"));
}
}
@Override
public String description() {
String desc = super.description();
if(Dungeon.hero != null){
desc += Messages.get(this, "weapon", weapon.toString() );
desc += Messages.get(this, "armor", armor.toString() );
desc += Messages.get(this, "ring", misc1.toString() );
desc += Messages.get(this, "ring", misc2.toString() );
desc += Messages.get(this, "wand", wand.toString() );
desc += Messages.get(this, "missile", missile.toString() );
desc += Messages.get(this, "ankhs");
} else {
desc += "";
}
return desc;
}
{
resistances.add( Grim.class );
resistances.add( GrimTrap.class );
resistances.add( ScrollOfRetribution.class );
resistances.add( ScrollOfPsionicBlast.class );
immunities.add( Amok.class );
immunities.add( Corruption.class );
immunities.add( Terror.class );
}
private Wand RandomWand() {
wand = new WandOfCorrosion();
wand.curCharges = 20;
return wand;
}
public class Hunting extends Mob.Hunting {
@Override
public boolean act(boolean enemyInFOV, boolean justAlerted) {
enemySeen = enemyInFOV;
if (!enemyInFOV) {
PotionOfHealing.cure(Rival.this);
}
if(Random.Int(10)==1){
Buff.affect(Rival.this, Healing.class).setHeal(5, 0f, 6);
}
return super.act( enemyInFOV, justAlerted );
}
}
protected class Wandering extends Mob.Wandering{
@Override
protected int randomDestination() {
//of two potential wander positions, picks the one closest to the hero
int pos1 = super.randomDestination();
int pos2 = super.randomDestination();
PathFinder.buildDistanceMap(Dungeon.hero.pos, level.passable);
if (PathFinder.distance[pos2] < PathFinder.distance[pos1]){
return pos2;
} else {
return pos1;
}
}
}
}
| 412 | 0.973989 | 1 | 0.973989 | game-dev | MEDIA | 0.995313 | game-dev | 0.776652 | 1 | 0.776652 |
fmang/oshu | 5,983 | lib/ui/osu.cc | /**
* \file lib/ui/osu.cc
* \ingroup ui
*
* \brief
* Drawing routines specific to the osu!standard game mode.
*/
#include "ui/osu.h"
#include "game/osu.h"
#include "video/display.h"
#include "video/texture.h"
#include <assert.h>
static void draw_hint(oshu::osu_ui &view, oshu::hit *hit)
{
oshu::game_base *game = &view.game;
double now = game->clock.now;
if (hit->time > now && hit->state == oshu::INITIAL_HIT) {
SDL_SetRenderDrawColor(view.display->renderer, 255, 128, 64, 255);
double ratio = (double) (hit->time - now) / game->beatmap.difficulty.approach_time;
double base_radius = game->beatmap.difficulty.circle_radius;
double radius = base_radius + ratio * game->beatmap.difficulty.approach_size;
oshu::draw_scaled_texture(
view.display, &view.approach_circle, hit->p,
2. * radius / std::real(view.approach_circle.size)
);
}
}
static void draw_hit_mark(oshu::osu_ui &view, oshu::hit *hit)
{
oshu::game_base *game = &view.game;
if (hit->state == oshu::GOOD_HIT) {
double leniency = game->beatmap.difficulty.leniency;
oshu::texture *mark = &view.good_mark;
if (hit->offset < - leniency / 2)
mark = &view.early_mark;
else if (hit->offset > leniency / 2)
mark = &view.late_mark;
oshu::draw_texture(view.display, mark, oshu::end_point(hit));
} else if (hit->state == oshu::MISSED_HIT) {
oshu::draw_texture(view.display, &view.bad_mark, oshu::end_point(hit));
} else if (hit->state == oshu::SKIPPED_HIT) {
oshu::draw_texture(view.display, &view.skip_mark, oshu::end_point(hit));
}
}
static void draw_hit_circle(oshu::osu_ui &view, oshu::hit *hit)
{
oshu::display *display = view.display;
if (hit->state == oshu::INITIAL_HIT) {
assert (hit->color != NULL);
oshu::draw_texture(display, &view.circles[hit->color->index], hit->p);
draw_hint(view, hit);
} else {
draw_hit_mark(view, hit);
}
}
static void draw_slider(oshu::osu_ui &view, oshu::hit *hit)
{
oshu::game_base *game = &view.game;
oshu::display *display = view.display;
double now = game->clock.now;
if (hit->state == oshu::INITIAL_HIT || hit->state == oshu::SLIDING_HIT) {
if (!hit->texture) {
oshu::osu_paint_slider(view, hit);
assert (hit->texture != NULL);
}
oshu::draw_texture(view.display, hit->texture, hit->p);
draw_hint(view, hit);
/* ball */
double t = (now - hit->time) / hit->slider.duration;
if (hit->state == oshu::SLIDING_HIT) {
oshu::point ball = oshu::path_at(&hit->slider.path, t < 0 ? 0 : t);
oshu::draw_texture(display, &view.slider_ball, ball);
}
} else {
draw_hit_mark(view, hit);
}
}
static void draw_hit(oshu::osu_ui &view, oshu::hit *hit)
{
if (hit->type & oshu::SLIDER_HIT)
draw_slider(view, hit);
else if (hit->type & oshu::CIRCLE_HIT)
draw_hit_circle(view, hit);
}
/**
* Connect two hits with a dotted line.
*
* ( ) · · · · ( )
*
* First, compute the visual distance between two hits, which is the distance
* between the center, minus the two radii. Then split this interval in steps
* of 15 pixels. Because we need an integral number of steps, floor it.
*
* The flooring would cause a extra padding after the last point, so we need to
* recalibrate the interval by dividing the distance by the number of steps.
*
* Now we have our steps:
*
* ( ) | | | | ( )
*
However, for some reason, this yields an excessive visual margin before the
first point and after the last point. To remedy this, the dots are put in the
middle of the steps, instead of between.
*
* ( ) · | · | · | · | · ( )
*
* Voilà!
*
*/
static void connect_hits(oshu::osu_ui &view, oshu::hit *a, oshu::hit *b)
{
oshu::game_base *game = &view.game;
if (a->state != oshu::INITIAL_HIT && a->state != oshu::SLIDING_HIT)
return;
oshu::point a_end = oshu::end_point(a);
double radius = game->beatmap.difficulty.circle_radius;
double interval = 15;
double center_distance = std::abs(b->p - a_end);
double edge_distance = center_distance - 2 * radius;
if (edge_distance < interval)
return;
int steps = edge_distance / interval;
assert (steps >= 1);
interval = edge_distance / steps; /* recalibrate */
oshu::vector direction = (b->p - a_end) / center_distance;
oshu::point start = a_end + direction * radius;
oshu::vector step = direction * interval;
for (int i = 0; i < steps; ++i)
oshu::draw_texture(view.display, &view.connector, start + (i + .5) * step);
}
namespace oshu {
osu_ui::osu_ui(oshu::display *display, oshu::osu_game &game)
: display(display), game(game)
{
assert (display != nullptr);
oshu::osu_view(display);
oshu::osu_paint_resources(*this);
if (oshu::create_cursor(display, &cursor) < 0)
throw std::runtime_error("could not create cursor");
oshu::reset_view(display);
mouse = std::make_shared<osu_mouse>(display);
game.mouse = mouse;
}
osu_ui::~osu_ui()
{
SDL_ShowCursor(SDL_ENABLE);
oshu::osu_free_resources(*this);
oshu::destroy_cursor(&cursor);
}
/**
* Draw all the visible nodes from the beatmap, according to the current
* position in the song.
*/
void osu_ui::draw()
{
oshu::osu_view(display);
oshu::hit *cursor = oshu::look_hit_up(&game, game.beatmap.difficulty.approach_time);
oshu::hit *next = NULL;
double now = game.clock.now;
for (oshu::hit *hit = cursor; hit; hit = hit->previous) {
if (!(hit->type & (oshu::CIRCLE_HIT | oshu::SLIDER_HIT)))
continue;
if (oshu::hit_end_time(hit) < now - game.beatmap.difficulty.approach_time)
break;
if (next && next->combo == hit->combo)
connect_hits(*this, hit, next);
draw_hit(*this, hit);
next = hit;
}
oshu::show_cursor(&this->cursor);
oshu::reset_view(display);
}
osu_mouse::osu_mouse(oshu::display *display)
: display(display)
{
}
oshu::point osu_mouse::position()
{
oshu::osu_view(display);
oshu::point mouse = oshu::get_mouse(display);
oshu::reset_view(display);
return mouse;
}
}
void oshu::osu_view(oshu::display *display)
{
oshu::fit_view(&display->view, oshu::size{640, 480});
oshu::resize_view(&display->view, oshu::size{512, 384});
}
| 412 | 0.795454 | 1 | 0.795454 | game-dev | MEDIA | 0.787252 | game-dev | 0.896596 | 1 | 0.896596 |
paxo-phone/PaxOS-8 | 40,161 | src/lib/SDL2-2.28.2/include/SDL_gamecontroller.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_gamecontroller.h
*
* Include file for SDL game controller event handling
*/
#ifndef SDL_gamecontroller_h_
#define SDL_gamecontroller_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_rwops.h"
#include "SDL_sensor.h"
#include "SDL_joystick.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \file SDL_gamecontroller.h
*
* In order to use these functions, SDL_Init() must have been called
* with the ::SDL_INIT_GAMECONTROLLER flag. This causes SDL to scan the system
* for game controllers, and load appropriate drivers.
*
* If you would like to receive controller updates while the application
* is in the background, you should set the following hint before calling
* SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS
*/
/**
* The gamecontroller structure used to identify an SDL game controller
*/
struct _SDL_GameController;
typedef struct _SDL_GameController SDL_GameController;
typedef enum
{
SDL_CONTROLLER_TYPE_UNKNOWN = 0,
SDL_CONTROLLER_TYPE_XBOX360,
SDL_CONTROLLER_TYPE_XBOXONE,
SDL_CONTROLLER_TYPE_PS3,
SDL_CONTROLLER_TYPE_PS4,
SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO,
SDL_CONTROLLER_TYPE_VIRTUAL,
SDL_CONTROLLER_TYPE_PS5,
SDL_CONTROLLER_TYPE_AMAZON_LUNA,
SDL_CONTROLLER_TYPE_GOOGLE_STADIA,
SDL_CONTROLLER_TYPE_NVIDIA_SHIELD,
SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT,
SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT,
SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR
} SDL_GameControllerType;
typedef enum
{
SDL_CONTROLLER_BINDTYPE_NONE = 0,
SDL_CONTROLLER_BINDTYPE_BUTTON,
SDL_CONTROLLER_BINDTYPE_AXIS,
SDL_CONTROLLER_BINDTYPE_HAT
} SDL_GameControllerBindType;
/**
* Get the SDL joystick layer binding for this controller button/axis mapping
*/
typedef struct SDL_GameControllerButtonBind
{
SDL_GameControllerBindType bindType;
union
{
int button;
int axis;
struct {
int hat;
int hat_mask;
} hat;
} value;
} SDL_GameControllerButtonBind;
/**
* To count the number of game controllers in the system for the following:
*
* ```c
* int nJoysticks = SDL_NumJoysticks();
* int nGameControllers = 0;
* for (int i = 0; i < nJoysticks; i++) {
* if (SDL_IsGameController(i)) {
* nGameControllers++;
* }
* }
* ```
*
* Using the SDL_HINT_GAMECONTROLLERCONFIG hint or the SDL_GameControllerAddMapping() you can add support for controllers SDL is unaware of or cause an existing controller to have a different binding. The format is:
* guid,name,mappings
*
* Where GUID is the string value from SDL_JoystickGetGUIDString(), name is the human readable string for the device and mappings are controller mappings to joystick ones.
* Under Windows there is a reserved GUID of "xinput" that covers any XInput devices.
* The mapping format for joystick is:
* bX - a joystick button, index X
* hX.Y - hat X with value Y
* aX - axis X of the joystick
* Buttons can be used as a controller axis and vice versa.
*
* This string shows an example of a valid mapping for a controller
*
* ```c
* "03000000341a00003608000000000000,PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7",
* ```
*/
/**
* Load a set of Game Controller mappings from a seekable SDL data stream.
*
* You can call this function several times, if needed, to load different
* database files.
*
* If a new mapping is loaded for an already known controller GUID, the later
* version will overwrite the one currently loaded.
*
* Mappings not belonging to the current platform or with no platform field
* specified will be ignored (i.e. mappings for Linux will be ignored in
* Windows, etc).
*
* This function will load the text database entirely in memory before
* processing it, so take this into consideration if you are in a memory
* constrained environment.
*
* \param rw the data stream for the mappings to be added
* \param freerw non-zero to close the stream after being read
* \returns the number of mappings added or -1 on error; call SDL_GetError()
* for more information.
*
* \since This function is available since SDL 2.0.2.
*
* \sa SDL_GameControllerAddMapping
* \sa SDL_GameControllerAddMappingsFromFile
* \sa SDL_GameControllerMappingForGUID
*/
extern DECLSPEC int SDLCALL SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw);
/**
* Load a set of mappings from a file, filtered by the current SDL_GetPlatform()
*
* Convenience macro.
*/
#define SDL_GameControllerAddMappingsFromFile(file) SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), 1)
/**
* Add support for controllers that SDL is unaware of or to cause an existing
* controller to have a different binding.
*
* The mapping string has the format "GUID,name,mapping", where GUID is the
* string value from SDL_JoystickGetGUIDString(), name is the human readable
* string for the device and mappings are controller mappings to joystick
* ones. Under Windows there is a reserved GUID of "xinput" that covers all
* XInput devices. The mapping format for joystick is: {| |bX |a joystick
* button, index X |- |hX.Y |hat X with value Y |- |aX |axis X of the joystick
* |} Buttons can be used as a controller axes and vice versa.
*
* This string shows an example of a valid mapping for a controller:
*
* ```c
* "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7"
* ```
*
* \param mappingString the mapping string
* \returns 1 if a new mapping is added, 0 if an existing mapping is updated,
* -1 on error; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerMapping
* \sa SDL_GameControllerMappingForGUID
*/
extern DECLSPEC int SDLCALL SDL_GameControllerAddMapping(const char* mappingString);
/**
* Get the number of mappings installed.
*
* \returns the number of mappings.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerNumMappings(void);
/**
* Get the mapping at a particular index.
*
* \returns the mapping string. Must be freed with SDL_free(). Returns NULL if
* the index is out of range.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForIndex(int mapping_index);
/**
* Get the game controller mapping string for a given GUID.
*
* The returned string must be freed with SDL_free().
*
* \param guid a structure containing the GUID for which a mapping is desired
* \returns a mapping string or NULL on error; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetDeviceGUID
* \sa SDL_JoystickGetGUID
*/
extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForGUID(SDL_JoystickGUID guid);
/**
* Get the current mapping of a Game Controller.
*
* The returned string must be freed with SDL_free().
*
* Details about mappings are discussed with SDL_GameControllerAddMapping().
*
* \param gamecontroller the game controller you want to get the current
* mapping for
* \returns a string that has the controller's mapping or NULL if no mapping
* is available; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerAddMapping
* \sa SDL_GameControllerMappingForGUID
*/
extern DECLSPEC char * SDLCALL SDL_GameControllerMapping(SDL_GameController *gamecontroller);
/**
* Check if the given joystick is supported by the game controller interface.
*
* `joystick_index` is the same as the `device_index` passed to
* SDL_JoystickOpen().
*
* \param joystick_index the device_index of a device, up to
* SDL_NumJoysticks()
* \returns SDL_TRUE if the given joystick is supported by the game controller
* interface, SDL_FALSE if it isn't or it's an invalid index.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerNameForIndex
* \sa SDL_GameControllerOpen
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsGameController(int joystick_index);
/**
* Get the implementation dependent name for the game controller.
*
* This function can be called before any controllers are opened.
*
* `joystick_index` is the same as the `device_index` passed to
* SDL_JoystickOpen().
*
* \param joystick_index the device_index of a device, from zero to
* SDL_NumJoysticks()-1
* \returns the implementation-dependent name for the game controller, or NULL
* if there is no name or the index is invalid.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerName
* \sa SDL_GameControllerOpen
* \sa SDL_IsGameController
*/
extern DECLSPEC const char *SDLCALL SDL_GameControllerNameForIndex(int joystick_index);
/**
* Get the implementation dependent path for the game controller.
*
* This function can be called before any controllers are opened.
*
* `joystick_index` is the same as the `device_index` passed to
* SDL_JoystickOpen().
*
* \param joystick_index the device_index of a device, from zero to
* SDL_NumJoysticks()-1
* \returns the implementation-dependent path for the game controller, or NULL
* if there is no path or the index is invalid.
*
* \since This function is available since SDL 2.24.0.
*
* \sa SDL_GameControllerPath
*/
extern DECLSPEC const char *SDLCALL SDL_GameControllerPathForIndex(int joystick_index);
/**
* Get the type of a game controller.
*
* This can be called before any controllers are opened.
*
* \param joystick_index the device_index of a device, from zero to
* SDL_NumJoysticks()-1
* \returns the controller type.
*
* \since This function is available since SDL 2.0.12.
*/
extern DECLSPEC SDL_GameControllerType SDLCALL SDL_GameControllerTypeForIndex(int joystick_index);
/**
* Get the mapping of a game controller.
*
* This can be called before any controllers are opened.
*
* \param joystick_index the device_index of a device, from zero to
* SDL_NumJoysticks()-1
* \returns the mapping string. Must be freed with SDL_free(). Returns NULL if
* no mapping is available.
*
* \since This function is available since SDL 2.0.9.
*/
extern DECLSPEC char *SDLCALL SDL_GameControllerMappingForDeviceIndex(int joystick_index);
/**
* Open a game controller for use.
*
* `joystick_index` is the same as the `device_index` passed to
* SDL_JoystickOpen().
*
* The index passed as an argument refers to the N'th game controller on the
* system. This index is not the value which will identify this controller in
* future controller events. The joystick's instance id (SDL_JoystickID) will
* be used there instead.
*
* \param joystick_index the device_index of a device, up to
* SDL_NumJoysticks()
* \returns a gamecontroller identifier or NULL if an error occurred; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerClose
* \sa SDL_GameControllerNameForIndex
* \sa SDL_IsGameController
*/
extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerOpen(int joystick_index);
/**
* Get the SDL_GameController associated with an instance id.
*
* \param joyid the instance id to get the SDL_GameController for
* \returns an SDL_GameController on success or NULL on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.4.
*/
extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromInstanceID(SDL_JoystickID joyid);
/**
* Get the SDL_GameController associated with a player index.
*
* Please note that the player index is _not_ the device index, nor is it the
* instance id!
*
* \param player_index the player index, which is not the device index or the
* instance id!
* \returns the SDL_GameController associated with a player index.
*
* \since This function is available since SDL 2.0.12.
*
* \sa SDL_GameControllerGetPlayerIndex
* \sa SDL_GameControllerSetPlayerIndex
*/
extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromPlayerIndex(int player_index);
/**
* Get the implementation-dependent name for an opened game controller.
*
* This is the same name as returned by SDL_GameControllerNameForIndex(), but
* it takes a controller identifier instead of the (unstable) device index.
*
* \param gamecontroller a game controller identifier previously returned by
* SDL_GameControllerOpen()
* \returns the implementation dependent name for the game controller, or NULL
* if there is no name or the identifier passed is invalid.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerNameForIndex
* \sa SDL_GameControllerOpen
*/
extern DECLSPEC const char *SDLCALL SDL_GameControllerName(SDL_GameController *gamecontroller);
/**
* Get the implementation-dependent path for an opened game controller.
*
* This is the same path as returned by SDL_GameControllerNameForIndex(), but
* it takes a controller identifier instead of the (unstable) device index.
*
* \param gamecontroller a game controller identifier previously returned by
* SDL_GameControllerOpen()
* \returns the implementation dependent path for the game controller, or NULL
* if there is no path or the identifier passed is invalid.
*
* \since This function is available since SDL 2.24.0.
*
* \sa SDL_GameControllerPathForIndex
*/
extern DECLSPEC const char *SDLCALL SDL_GameControllerPath(SDL_GameController *gamecontroller);
/**
* Get the type of this currently opened controller
*
* This is the same name as returned by SDL_GameControllerTypeForIndex(), but
* it takes a controller identifier instead of the (unstable) device index.
*
* \param gamecontroller the game controller object to query.
* \returns the controller type.
*
* \since This function is available since SDL 2.0.12.
*/
extern DECLSPEC SDL_GameControllerType SDLCALL SDL_GameControllerGetType(SDL_GameController *gamecontroller);
/**
* Get the player index of an opened game controller.
*
* For XInput controllers this returns the XInput user index.
*
* \param gamecontroller the game controller object to query.
* \returns the player index for controller, or -1 if it's not available.
*
* \since This function is available since SDL 2.0.9.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerGetPlayerIndex(SDL_GameController *gamecontroller);
/**
* Set the player index of an opened game controller.
*
* \param gamecontroller the game controller object to adjust.
* \param player_index Player index to assign to this controller, or -1 to
* clear the player index and turn off player LEDs.
*
* \since This function is available since SDL 2.0.12.
*/
extern DECLSPEC void SDLCALL SDL_GameControllerSetPlayerIndex(SDL_GameController *gamecontroller, int player_index);
/**
* Get the USB vendor ID of an opened controller, if available.
*
* If the vendor ID isn't available this function returns 0.
*
* \param gamecontroller the game controller object to query.
* \return the USB vendor ID, or zero if unavailable.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetVendor(SDL_GameController *gamecontroller);
/**
* Get the USB product ID of an opened controller, if available.
*
* If the product ID isn't available this function returns 0.
*
* \param gamecontroller the game controller object to query.
* \return the USB product ID, or zero if unavailable.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProduct(SDL_GameController *gamecontroller);
/**
* Get the product version of an opened controller, if available.
*
* If the product version isn't available this function returns 0.
*
* \param gamecontroller the game controller object to query.
* \return the USB product version, or zero if unavailable.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProductVersion(SDL_GameController *gamecontroller);
/**
* Get the firmware version of an opened controller, if available.
*
* If the firmware version isn't available this function returns 0.
*
* \param gamecontroller the game controller object to query.
* \return the controller firmware version, or zero if unavailable.
*
* \since This function is available since SDL 2.24.0.
*/
extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetFirmwareVersion(SDL_GameController *gamecontroller);
/**
* Get the serial number of an opened controller, if available.
*
* Returns the serial number of the controller, or NULL if it is not
* available.
*
* \param gamecontroller the game controller object to query.
* \return the serial number, or NULL if unavailable.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC const char * SDLCALL SDL_GameControllerGetSerial(SDL_GameController *gamecontroller);
/**
* Check if a controller has been opened and is currently connected.
*
* \param gamecontroller a game controller identifier previously returned by
* SDL_GameControllerOpen()
* \returns SDL_TRUE if the controller has been opened and is currently
* connected, or SDL_FALSE if not.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerClose
* \sa SDL_GameControllerOpen
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerGetAttached(SDL_GameController *gamecontroller);
/**
* Get the Joystick ID from a Game Controller.
*
* This function will give you a SDL_Joystick object, which allows you to use
* the SDL_Joystick functions with a SDL_GameController object. This would be
* useful for getting a joystick's position at any given time, even if it
* hasn't moved (moving it would produce an event, which would have the axis'
* value).
*
* The pointer returned is owned by the SDL_GameController. You should not
* call SDL_JoystickClose() on it, for example, since doing so will likely
* cause SDL to crash.
*
* \param gamecontroller the game controller object that you want to get a
* joystick from
* \returns a SDL_Joystick object; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_GameControllerGetJoystick(SDL_GameController *gamecontroller);
/**
* Query or change current state of Game Controller events.
*
* If controller events are disabled, you must call SDL_GameControllerUpdate()
* yourself and check the state of the controller when you want controller
* information.
*
* Any number can be passed to SDL_GameControllerEventState(), but only -1, 0,
* and 1 will have any effect. Other numbers will just be returned.
*
* \param state can be one of `SDL_QUERY`, `SDL_IGNORE`, or `SDL_ENABLE`
* \returns the same value passed to the function, with exception to -1
* (SDL_QUERY), which will return the current state.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickEventState
*/
extern DECLSPEC int SDLCALL SDL_GameControllerEventState(int state);
/**
* Manually pump game controller updates if not using the loop.
*
* This function is called automatically by the event loop if events are
* enabled. Under such circumstances, it will not be necessary to call this
* function.
*
* \since This function is available since SDL 2.0.0.
*/
extern DECLSPEC void SDLCALL SDL_GameControllerUpdate(void);
/**
* The list of axes available from a controller
*
* Thumbstick axis values range from SDL_JOYSTICK_AXIS_MIN to SDL_JOYSTICK_AXIS_MAX,
* and are centered within ~8000 of zero, though advanced UI will allow users to set
* or autodetect the dead zone, which varies between controllers.
*
* Trigger axis values range from 0 to SDL_JOYSTICK_AXIS_MAX.
*/
typedef enum
{
SDL_CONTROLLER_AXIS_INVALID = -1,
SDL_CONTROLLER_AXIS_LEFTX,
SDL_CONTROLLER_AXIS_LEFTY,
SDL_CONTROLLER_AXIS_RIGHTX,
SDL_CONTROLLER_AXIS_RIGHTY,
SDL_CONTROLLER_AXIS_TRIGGERLEFT,
SDL_CONTROLLER_AXIS_TRIGGERRIGHT,
SDL_CONTROLLER_AXIS_MAX
} SDL_GameControllerAxis;
/**
* Convert a string into SDL_GameControllerAxis enum.
*
* This function is called internally to translate SDL_GameController mapping
* strings for the underlying joystick device into the consistent
* SDL_GameController mapping. You do not normally need to call this function
* unless you are parsing SDL_GameController mappings in your own code.
*
* Note specially that "righttrigger" and "lefttrigger" map to
* `SDL_CONTROLLER_AXIS_TRIGGERRIGHT` and `SDL_CONTROLLER_AXIS_TRIGGERLEFT`,
* respectively.
*
* \param str string representing a SDL_GameController axis
* \returns the SDL_GameControllerAxis enum corresponding to the input string,
* or `SDL_CONTROLLER_AXIS_INVALID` if no match was found.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerGetStringForAxis
*/
extern DECLSPEC SDL_GameControllerAxis SDLCALL SDL_GameControllerGetAxisFromString(const char *str);
/**
* Convert from an SDL_GameControllerAxis enum to a string.
*
* The caller should not SDL_free() the returned string.
*
* \param axis an enum value for a given SDL_GameControllerAxis
* \returns a string for the given axis, or NULL if an invalid axis is
* specified. The string returned is of the format used by
* SDL_GameController mapping strings.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerGetAxisFromString
*/
extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForAxis(SDL_GameControllerAxis axis);
/**
* Get the SDL joystick layer binding for a controller axis mapping.
*
* \param gamecontroller a game controller
* \param axis an axis enum value (one of the SDL_GameControllerAxis values)
* \returns a SDL_GameControllerButtonBind describing the bind. On failure
* (like the given Controller axis doesn't exist on the device), its
* `.bindType` will be `SDL_CONTROLLER_BINDTYPE_NONE`.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerGetBindForButton
*/
extern DECLSPEC SDL_GameControllerButtonBind SDLCALL
SDL_GameControllerGetBindForAxis(SDL_GameController *gamecontroller,
SDL_GameControllerAxis axis);
/**
* Query whether a game controller has a given axis.
*
* This merely reports whether the controller's mapping defined this axis, as
* that is all the information SDL has about the physical device.
*
* \param gamecontroller a game controller
* \param axis an axis enum value (an SDL_GameControllerAxis value)
* \returns SDL_TRUE if the controller has this axis, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC SDL_bool SDLCALL
SDL_GameControllerHasAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis);
/**
* Get the current state of an axis control on a game controller.
*
* The axis indices start at index 0.
*
* The state is a value ranging from -32768 to 32767. Triggers, however, range
* from 0 to 32767 (they never return a negative value).
*
* \param gamecontroller a game controller
* \param axis an axis index (one of the SDL_GameControllerAxis values)
* \returns axis state (including 0) on success or 0 (also) on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerGetButton
*/
extern DECLSPEC Sint16 SDLCALL
SDL_GameControllerGetAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis);
/**
* The list of buttons available from a controller
*/
typedef enum
{
SDL_CONTROLLER_BUTTON_INVALID = -1,
SDL_CONTROLLER_BUTTON_A,
SDL_CONTROLLER_BUTTON_B,
SDL_CONTROLLER_BUTTON_X,
SDL_CONTROLLER_BUTTON_Y,
SDL_CONTROLLER_BUTTON_BACK,
SDL_CONTROLLER_BUTTON_GUIDE,
SDL_CONTROLLER_BUTTON_START,
SDL_CONTROLLER_BUTTON_LEFTSTICK,
SDL_CONTROLLER_BUTTON_RIGHTSTICK,
SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
SDL_CONTROLLER_BUTTON_DPAD_UP,
SDL_CONTROLLER_BUTTON_DPAD_DOWN,
SDL_CONTROLLER_BUTTON_DPAD_LEFT,
SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
SDL_CONTROLLER_BUTTON_MISC1, /* Xbox Series X share button, PS5 microphone button, Nintendo Switch Pro capture button, Amazon Luna microphone button */
SDL_CONTROLLER_BUTTON_PADDLE1, /* Xbox Elite paddle P1 (upper left, facing the back) */
SDL_CONTROLLER_BUTTON_PADDLE2, /* Xbox Elite paddle P3 (upper right, facing the back) */
SDL_CONTROLLER_BUTTON_PADDLE3, /* Xbox Elite paddle P2 (lower left, facing the back) */
SDL_CONTROLLER_BUTTON_PADDLE4, /* Xbox Elite paddle P4 (lower right, facing the back) */
SDL_CONTROLLER_BUTTON_TOUCHPAD, /* PS4/PS5 touchpad button */
SDL_CONTROLLER_BUTTON_MAX
} SDL_GameControllerButton;
/**
* Convert a string into an SDL_GameControllerButton enum.
*
* This function is called internally to translate SDL_GameController mapping
* strings for the underlying joystick device into the consistent
* SDL_GameController mapping. You do not normally need to call this function
* unless you are parsing SDL_GameController mappings in your own code.
*
* \param str string representing a SDL_GameController axis
* \returns the SDL_GameControllerButton enum corresponding to the input
* string, or `SDL_CONTROLLER_AXIS_INVALID` if no match was found.
*
* \since This function is available since SDL 2.0.0.
*/
extern DECLSPEC SDL_GameControllerButton SDLCALL SDL_GameControllerGetButtonFromString(const char *str);
/**
* Convert from an SDL_GameControllerButton enum to a string.
*
* The caller should not SDL_free() the returned string.
*
* \param button an enum value for a given SDL_GameControllerButton
* \returns a string for the given button, or NULL if an invalid button is
* specified. The string returned is of the format used by
* SDL_GameController mapping strings.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerGetButtonFromString
*/
extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForButton(SDL_GameControllerButton button);
/**
* Get the SDL joystick layer binding for a controller button mapping.
*
* \param gamecontroller a game controller
* \param button an button enum value (an SDL_GameControllerButton value)
* \returns a SDL_GameControllerButtonBind describing the bind. On failure
* (like the given Controller button doesn't exist on the device),
* its `.bindType` will be `SDL_CONTROLLER_BINDTYPE_NONE`.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerGetBindForAxis
*/
extern DECLSPEC SDL_GameControllerButtonBind SDLCALL
SDL_GameControllerGetBindForButton(SDL_GameController *gamecontroller,
SDL_GameControllerButton button);
/**
* Query whether a game controller has a given button.
*
* This merely reports whether the controller's mapping defined this button,
* as that is all the information SDL has about the physical device.
*
* \param gamecontroller a game controller
* \param button a button enum value (an SDL_GameControllerButton value)
* \returns SDL_TRUE if the controller has this button, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasButton(SDL_GameController *gamecontroller,
SDL_GameControllerButton button);
/**
* Get the current state of a button on a game controller.
*
* \param gamecontroller a game controller
* \param button a button index (one of the SDL_GameControllerButton values)
* \returns 1 for pressed state or 0 for not pressed state or error; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerGetAxis
*/
extern DECLSPEC Uint8 SDLCALL SDL_GameControllerGetButton(SDL_GameController *gamecontroller,
SDL_GameControllerButton button);
/**
* Get the number of touchpads on a game controller.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerGetNumTouchpads(SDL_GameController *gamecontroller);
/**
* Get the number of supported simultaneous fingers on a touchpad on a game
* controller.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerGetNumTouchpadFingers(SDL_GameController *gamecontroller, int touchpad);
/**
* Get the current state of a finger on a touchpad on a game controller.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerGetTouchpadFinger(SDL_GameController *gamecontroller, int touchpad, int finger, Uint8 *state, float *x, float *y, float *pressure);
/**
* Return whether a game controller has a particular sensor.
*
* \param gamecontroller The controller to query
* \param type The type of sensor to query
* \returns SDL_TRUE if the sensor exists, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasSensor(SDL_GameController *gamecontroller, SDL_SensorType type);
/**
* Set whether data reporting for a game controller sensor is enabled.
*
* \param gamecontroller The controller to update
* \param type The type of sensor to enable/disable
* \param enabled Whether data reporting should be enabled
* \returns 0 or -1 if an error occurred.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerSetSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type, SDL_bool enabled);
/**
* Query whether sensor data reporting is enabled for a game controller.
*
* \param gamecontroller The controller to query
* \param type The type of sensor to query
* \returns SDL_TRUE if the sensor is enabled, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerIsSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type);
/**
* Get the data rate (number of events per second) of a game controller
* sensor.
*
* \param gamecontroller The controller to query
* \param type The type of sensor to query
* \return the data rate, or 0.0f if the data rate is not available.
*
* \since This function is available since SDL 2.0.16.
*/
extern DECLSPEC float SDLCALL SDL_GameControllerGetSensorDataRate(SDL_GameController *gamecontroller, SDL_SensorType type);
/**
* Get the current state of a game controller sensor.
*
* The number of values and interpretation of the data is sensor dependent.
* See SDL_sensor.h for the details for each type of sensor.
*
* \param gamecontroller The controller to query
* \param type The type of sensor to query
* \param data A pointer filled with the current sensor state
* \param num_values The number of values to write to data
* \return 0 or -1 if an error occurred.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerGetSensorData(SDL_GameController *gamecontroller, SDL_SensorType type, float *data, int num_values);
/**
* Get the current state of a game controller sensor with the timestamp of the
* last update.
*
* The number of values and interpretation of the data is sensor dependent.
* See SDL_sensor.h for the details for each type of sensor.
*
* \param gamecontroller The controller to query
* \param type The type of sensor to query
* \param timestamp A pointer filled with the timestamp in microseconds of the
* current sensor reading if available, or 0 if not
* \param data A pointer filled with the current sensor state
* \param num_values The number of values to write to data
* \return 0 or -1 if an error occurred.
*
* \since This function is available since SDL 2.26.0.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerGetSensorDataWithTimestamp(SDL_GameController *gamecontroller, SDL_SensorType type, Uint64 *timestamp, float *data, int num_values);
/**
* Start a rumble effect on a game controller.
*
* Each call to this function cancels any previous rumble effect, and calling
* it with 0 intensity stops any rumbling.
*
* \param gamecontroller The controller to vibrate
* \param low_frequency_rumble The intensity of the low frequency (left)
* rumble motor, from 0 to 0xFFFF
* \param high_frequency_rumble The intensity of the high frequency (right)
* rumble motor, from 0 to 0xFFFF
* \param duration_ms The duration of the rumble effect, in milliseconds
* \returns 0, or -1 if rumble isn't supported on this controller
*
* \since This function is available since SDL 2.0.9.
*
* \sa SDL_GameControllerHasRumble
*/
extern DECLSPEC int SDLCALL SDL_GameControllerRumble(SDL_GameController *gamecontroller, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms);
/**
* Start a rumble effect in the game controller's triggers.
*
* Each call to this function cancels any previous trigger rumble effect, and
* calling it with 0 intensity stops any rumbling.
*
* Note that this is rumbling of the _triggers_ and not the game controller as
* a whole. This is currently only supported on Xbox One controllers. If you
* want the (more common) whole-controller rumble, use
* SDL_GameControllerRumble() instead.
*
* \param gamecontroller The controller to vibrate
* \param left_rumble The intensity of the left trigger rumble motor, from 0
* to 0xFFFF
* \param right_rumble The intensity of the right trigger rumble motor, from 0
* to 0xFFFF
* \param duration_ms The duration of the rumble effect, in milliseconds
* \returns 0, or -1 if trigger rumble isn't supported on this controller
*
* \since This function is available since SDL 2.0.14.
*
* \sa SDL_GameControllerHasRumbleTriggers
*/
extern DECLSPEC int SDLCALL SDL_GameControllerRumbleTriggers(SDL_GameController *gamecontroller, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms);
/**
* Query whether a game controller has an LED.
*
* \param gamecontroller The controller to query
* \returns SDL_TRUE, or SDL_FALSE if this controller does not have a
* modifiable LED
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasLED(SDL_GameController *gamecontroller);
/**
* Query whether a game controller has rumble support.
*
* \param gamecontroller The controller to query
* \returns SDL_TRUE, or SDL_FALSE if this controller does not have rumble
* support
*
* \since This function is available since SDL 2.0.18.
*
* \sa SDL_GameControllerRumble
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasRumble(SDL_GameController *gamecontroller);
/**
* Query whether a game controller has rumble support on triggers.
*
* \param gamecontroller The controller to query
* \returns SDL_TRUE, or SDL_FALSE if this controller does not have trigger
* rumble support
*
* \since This function is available since SDL 2.0.18.
*
* \sa SDL_GameControllerRumbleTriggers
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasRumbleTriggers(SDL_GameController *gamecontroller);
/**
* Update a game controller's LED color.
*
* \param gamecontroller The controller to update
* \param red The intensity of the red LED
* \param green The intensity of the green LED
* \param blue The intensity of the blue LED
* \returns 0, or -1 if this controller does not have a modifiable LED
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerSetLED(SDL_GameController *gamecontroller, Uint8 red, Uint8 green, Uint8 blue);
/**
* Send a controller specific effect packet
*
* \param gamecontroller The controller to affect
* \param data The data to send to the controller
* \param size The size of the data to send to the controller
* \returns 0, or -1 if this controller or driver doesn't support effect
* packets
*
* \since This function is available since SDL 2.0.16.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerSendEffect(SDL_GameController *gamecontroller, const void *data, int size);
/**
* Close a game controller previously opened with SDL_GameControllerOpen().
*
* \param gamecontroller a game controller identifier previously returned by
* SDL_GameControllerOpen()
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerOpen
*/
extern DECLSPEC void SDLCALL SDL_GameControllerClose(SDL_GameController *gamecontroller);
/**
* Return the sfSymbolsName for a given button on a game controller on Apple
* platforms.
*
* \param gamecontroller the controller to query
* \param button a button on the game controller
* \returns the sfSymbolsName or NULL if the name can't be found
*
* \since This function is available since SDL 2.0.18.
*
* \sa SDL_GameControllerGetAppleSFSymbolsNameForAxis
*/
extern DECLSPEC const char* SDLCALL SDL_GameControllerGetAppleSFSymbolsNameForButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button);
/**
* Return the sfSymbolsName for a given axis on a game controller on Apple
* platforms.
*
* \param gamecontroller the controller to query
* \param axis an axis on the game controller
* \returns the sfSymbolsName or NULL if the name can't be found
*
* \since This function is available since SDL 2.0.18.
*
* \sa SDL_GameControllerGetAppleSFSymbolsNameForButton
*/
extern DECLSPEC const char* SDLCALL SDL_GameControllerGetAppleSFSymbolsNameForAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_gamecontroller_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.895696 | 1 | 0.895696 | game-dev | MEDIA | 0.91581 | game-dev | 0.722759 | 1 | 0.722759 |
jose-villegas/VCTRenderer | 2,486 | engine/types/uniform_collection.h | #pragma once
#include <vector>
/// <summary>
/// Holds collections of program uniforms of the same type
/// these collections have to be identifier by countable identifier
/// </summary>
template<typename T1, typename T2>
class UniformCollection
{
public:
/// <summary>
/// Active uniforms identifiers
/// </summary>
/// <returns>A vector containing all active identifiers</returns>
const std::vector<T2> &Actives() const;
/// <summary>
/// Resizes the specified identifier vector
/// </summary>
/// <param name="idCount">The identifier count.</param>
void Resize(const size_t idCount);
/// <summary>
/// Saves the specified identifier and related program uniform
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="uniform">The program uniform.</param>
void Save(T2 id, T1 uniform);
/// <summary>
/// Determines whether the class holds an uniform
/// associated with the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>boolean</returns>
bool Has(const T2 &id) const;
/// <summary>
/// Indexes for the class, returns the id associated uniform
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>The uniform</returns>
T1 &operator[](const T2 &id);
private:
std::vector<std::pair<T2, T1> *> links;
std::vector<T2> actives;
};
template<typename T1, typename T2>
void UniformCollection<T1, T2>::Resize(const size_t idCount)
{
links.clear();
links.resize(idCount);
}
template<typename T1, typename T2>
void UniformCollection<T1, T2>::Save(T2 id, T1 uniform)
{
if (static_cast<int>(id) < 0 || static_cast<size_t>(id) >= links.size())
{
return;
}
actives.push_back(std::move(id));
links[static_cast<int>(id)] = new std::pair<T2, T1>(actives.back(),
std::move(uniform));
}
template<typename T1, typename T2>
bool UniformCollection<T1, T2>::Has(const T2 &id) const
{
return links[static_cast<int>(id)] != nullptr;
}
template<typename T1, typename T2>
const std::vector<T2> &UniformCollection<T1, T2>::Actives()
const
{
return actives;
}
template<typename T1, typename T2>
T1 &UniformCollection<T1, T2>::operator[](const T2 &id)
{
return links[static_cast<int>(id)]->second;
}
| 412 | 0.950775 | 1 | 0.950775 | game-dev | MEDIA | 0.145484 | game-dev | 0.866391 | 1 | 0.866391 |
SkelletonX/DDTank4.1 | 12,179 | Source Flash/scripts/shop/manager/ShopGiftsManager.as | package shop.manager
{
import baglocked.BaglockedManager;
import com.pickgliss.events.FrameEvent;
import com.pickgliss.toplevel.StageReferance;
import com.pickgliss.ui.ComponentFactory;
import com.pickgliss.ui.LayerManager;
import com.pickgliss.ui.controls.BaseButton;
import com.pickgliss.ui.controls.Frame;
import com.pickgliss.ui.controls.NumberSelecter;
import com.pickgliss.ui.image.Scale9CornerImage;
import com.pickgliss.ui.image.ScaleBitmapImage;
import com.pickgliss.ui.text.FilterFrameText;
import com.pickgliss.ui.text.GradientText;
import com.pickgliss.utils.ObjectUtils;
import ddt.data.goods.ShopCarItemInfo;
import ddt.data.goods.ShopItemInfo;
import ddt.events.CrazyTankSocketEvent;
import ddt.manager.LanguageMgr;
import ddt.manager.LeavePageManager;
import ddt.manager.MessageTipManager;
import ddt.manager.PlayerManager;
import ddt.manager.ShopManager;
import ddt.manager.SocketManager;
import ddt.manager.SoundManager;
import ddt.utils.FilterWordManager;
import ddt.utils.PositionUtils;
import flash.display.Bitmap;
import flash.events.Event;
import flash.events.MouseEvent;
import shop.view.ShopCartItem;
import shop.view.ShopPresentClearingFrame;
public class ShopGiftsManager
{
private static var _instance:ShopGiftsManager;
private var _frame:Frame;
private var _shopCartItem:ShopCartItem;
private var _commodityPricesText1:FilterFrameText;
private var _commodityPricesText2:FilterFrameText;
private var _commodityPricesText3:FilterFrameText;
private var _giftsBtn:BaseButton;
private var _numberSelecter:NumberSelecter;
private var _goodsID:int;
private var _shopPresentClearingFrame:ShopPresentClearingFrame;
private var _isDiscountType:Boolean = true;
private var _type:int = 0;
public function ShopGiftsManager()
{
super();
}
public static function get Instance() : ShopGiftsManager
{
if(_instance == null)
{
_instance = new ShopGiftsManager();
}
return _instance;
}
public function buy(param1:int, param2:Boolean = false, param3:int = 1) : void
{
if(this._frame)
{
return;
}
this._goodsID = param1;
this._isDiscountType = param2;
this._type = param3;
this.initView();
this.addEvent();
LayerManager.Instance.addToLayer(this._frame,LayerManager.GAME_DYNAMIC_LAYER,true,LayerManager.BLCAK_BLOCKGOUND);
}
private function initView() : void
{
var _loc5_:ShopCarItemInfo = null;
this._frame = ComponentFactory.Instance.creatComponentByStylename("core.shop.CheckOutViewFrame");
this._frame.titleText = LanguageMgr.GetTranslation("shop.view.present");
var _loc1_:Scale9CornerImage = ComponentFactory.Instance.creatComponentByStylename("core.shop.CheckOutViewBg");
this._frame.addToContent(_loc1_);
this._giftsBtn = ComponentFactory.Instance.creatComponentByStylename("core.shop.GiftsBtn");
this._frame.addToContent(this._giftsBtn);
var _loc2_:Bitmap = ComponentFactory.Instance.creatBitmap("asset.shop.CheckOutViewBg");
PositionUtils.setPos(_loc2_,"shop.CheckOutViewBgPos");
this._frame.addToContent(_loc2_);
var _loc3_:ScaleBitmapImage = ComponentFactory.Instance.creatComponentByStylename("core.shop.NumberSelecterTextBg");
PositionUtils.setPos(_loc3_,"shop.NumberSelecterTextBgPos");
this._frame.addToContent(_loc3_);
var _loc4_:ShopItemInfo = null;
if(!this._isDiscountType)
{
_loc4_ = ShopManager.Instance.getShopItemByGoodsID(this._goodsID);
if(_loc4_ == null)
{
_loc4_ = ShopManager.Instance.getGoodsByTemplateID(this._goodsID);
}
}
_loc5_ = new ShopCarItemInfo(_loc4_.GoodsID,_loc4_.TemplateID);
ObjectUtils.copyProperties(_loc5_,_loc4_);
this._shopCartItem = new ShopCartItem();
PositionUtils.setPos(this._shopCartItem,"shop.shopCartItemPos");
this._shopCartItem.closeBtn.visible = false;
this._shopCartItem.shopItemInfo = _loc5_;
this._shopCartItem.setColor(_loc5_.Color);
this._frame.addToContent(this._shopCartItem);
var _loc6_:GradientText = ComponentFactory.Instance.creatComponentByStylename("vipName");
PositionUtils.setPos(_loc6_,"shop.ShopBuyManagerTextImgPos");
_loc6_.text = LanguageMgr.GetTranslation("shop.manager.ShopBuyManager.textImg");
this._frame.addToContent(_loc6_);
this._numberSelecter = ComponentFactory.Instance.creatComponentByStylename("core.shop.NumberSelecter");
this._frame.addToContent(this._numberSelecter);
this._commodityPricesText1 = ComponentFactory.Instance.creatComponentByStylename("core.shop.CommodityPricesText");
PositionUtils.setPos(this._commodityPricesText1,"shop.commodityPricesText1Pos");
this._commodityPricesText1.text = "0";
this._frame.addToContent(this._commodityPricesText1);
this._commodityPricesText2 = ComponentFactory.Instance.creatComponentByStylename("core.shop.CommodityPricesText");
PositionUtils.setPos(this._commodityPricesText2,"shop.commodityPricesText2Pos");
this._commodityPricesText2.text = "0";
this._frame.addToContent(this._commodityPricesText2);
this._commodityPricesText3 = ComponentFactory.Instance.creatComponentByStylename("core.shop.CommodityPricesText");
PositionUtils.setPos(this._commodityPricesText3,"shop.commodityPricesText3Pos");
this._commodityPricesText3.text = "0";
this._frame.addToContent(this._commodityPricesText3);
this.updateCommodityPrices();
}
private function addEvent() : void
{
this._giftsBtn.addEventListener(MouseEvent.CLICK,this.__giftsBtnClick);
this._numberSelecter.addEventListener(Event.CHANGE,this.__numberSelecterChange);
this._shopCartItem.addEventListener(ShopCartItem.CONDITION_CHANGE,this.__shopCartItemChange);
this._frame.addEventListener(FrameEvent.RESPONSE,this.__framePesponse);
SocketManager.Instance.addEventListener(CrazyTankSocketEvent.GOODS_PRESENT,this.onPresent);
}
private function removeEvent() : void
{
this._giftsBtn.removeEventListener(MouseEvent.CLICK,this.__giftsBtnClick);
this._numberSelecter.removeEventListener(Event.CHANGE,this.__numberSelecterChange);
this._shopCartItem.removeEventListener(ShopCartItem.CONDITION_CHANGE,this.__shopCartItemChange);
this._frame.removeEventListener(FrameEvent.RESPONSE,this.__framePesponse);
SocketManager.Instance.removeEventListener(CrazyTankSocketEvent.GOODS_PRESENT,this.onPresent);
}
private function updateCommodityPrices() : void
{
this._commodityPricesText1.text = (this._shopCartItem.shopItemInfo.getCurrentPrice().moneyValue * this._numberSelecter.currentValue).toString();
this._commodityPricesText2.text = (this._shopCartItem.shopItemInfo.getCurrentPrice().giftValue * this._numberSelecter.currentValue).toString();
this._commodityPricesText3.text = (this._shopCartItem.shopItemInfo.getCurrentPrice().medalValue * this._numberSelecter.currentValue).toString();
}
protected function __giftsBtnClick(param1:MouseEvent) : void
{
SoundManager.instance.play("008");
this._shopPresentClearingFrame = ComponentFactory.Instance.creatComponentByStylename("core.shop.ShopPresentClearingFrame");
this._shopPresentClearingFrame.show();
this._shopPresentClearingFrame.presentBtn.addEventListener(MouseEvent.CLICK,this.__presentBtnClick);
this._shopPresentClearingFrame.addEventListener(FrameEvent.RESPONSE,this.__responseHandler);
}
private function __responseHandler(param1:FrameEvent) : void
{
if(param1.responseCode == FrameEvent.CLOSE_CLICK || param1.responseCode == FrameEvent.ESC_CLICK)
{
StageReferance.stage.focus = this._frame;
}
}
protected function __presentBtnClick(param1:MouseEvent) : void
{
var _loc10_:ShopCarItemInfo = null;
SoundManager.instance.play("008");
if(PlayerManager.Instance.Self.bagLocked)
{
BaglockedManager.Instance.show();
return;
}
if(this._shopPresentClearingFrame.nameInput.text == "")
{
MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("shop.ShopIIPresentView.give"));
return;
}
if(FilterWordManager.IsNullorEmpty(this._shopPresentClearingFrame.nameInput.text))
{
MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("shop.ShopIIPresentView.space"));
return;
}
var _loc2_:int = this._shopCartItem.shopItemInfo.getCurrentPrice().moneyValue;
if(PlayerManager.Instance.Self.Money < _loc2_ && _loc2_ != 0)
{
LeavePageManager.showFillFrame();
return;
}
this._shopPresentClearingFrame.presentBtn.enable = false;
var _loc3_:Array = new Array();
var _loc4_:Array = new Array();
var _loc5_:Array = new Array();
var _loc6_:Array = new Array();
var _loc7_:Array = new Array();
var _loc8_:int = 0;
while(_loc8_ < this._numberSelecter.currentValue)
{
_loc10_ = this._shopCartItem.shopItemInfo;
_loc3_.push(_loc10_.GoodsID);
_loc4_.push(_loc10_.currentBuyType);
_loc5_.push(_loc10_.Color);
_loc6_.push("");
_loc7_.push("");
_loc8_++;
}
var _loc9_:String = FilterWordManager.filterWrod(this._shopPresentClearingFrame.textArea.text);
SocketManager.Instance.out.sendPresentGoods(_loc3_,_loc4_,_loc5_,_loc9_,this._shopPresentClearingFrame.nameInput.text);
}
protected function onPresent(param1:CrazyTankSocketEvent) : void
{
this._shopPresentClearingFrame.presentBtn.enable = true;
this._shopPresentClearingFrame.presentBtn.removeEventListener(MouseEvent.CLICK,this.__presentBtnClick);
this._shopPresentClearingFrame.dispose();
this._shopPresentClearingFrame = null;
var _loc2_:Boolean = param1.pkg.readBoolean();
this.dispose();
}
protected function __numberSelecterChange(param1:Event) : void
{
SoundManager.instance.play("008");
this.updateCommodityPrices();
}
protected function __shopCartItemChange(param1:Event) : void
{
this.updateCommodityPrices();
}
protected function __framePesponse(param1:FrameEvent) : void
{
SoundManager.instance.play("008");
switch(param1.responseCode)
{
case FrameEvent.CLOSE_CLICK:
case FrameEvent.ESC_CLICK:
this.dispose();
}
}
private function dispose() : void
{
this.removeEvent();
ObjectUtils.disposeObject(this._frame);
this._frame = null;
ObjectUtils.disposeObject(this._shopCartItem);
this._shopCartItem = null;
ObjectUtils.disposeObject(this._commodityPricesText1);
this._commodityPricesText1 = null;
ObjectUtils.disposeObject(this._commodityPricesText2);
this._commodityPricesText1 = null;
ObjectUtils.disposeObject(this._commodityPricesText3);
this._commodityPricesText1 = null;
ObjectUtils.disposeObject(this._giftsBtn);
this._giftsBtn = null;
ObjectUtils.disposeObject(this._numberSelecter);
this._numberSelecter = null;
}
}
}
| 412 | 0.884243 | 1 | 0.884243 | game-dev | MEDIA | 0.553307 | game-dev | 0.93066 | 1 | 0.93066 |
juzzlin/DustRacing2D | 1,684 | src/game/MiniCore/src/Physics/mcseparationevent.hh | // This file belongs to the "MiniCore" game engine.
// Copyright (C) 2010 Jussi Lind <jussi.lind@iki.fi>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
//
#ifndef MCSEPARATIONEVENT_HH
#define MCSEPARATIONEVENT_HH
#include "mcevent.hh"
#include "mcvector3d.hh"
class MCObject;
/*! \class MCSeparationEvent
* \brief Event sent when two objects does not collide anymore.*/
class MCSeparationEvent : public MCEvent
{
public:
/*! Constructor.
* \param separatedObject The separated object. */
MCSeparationEvent(MCObject & separatedObject);
//! Destructor.
~MCSeparationEvent() override;
//! Get separated object.
MCObject & separatedObject() const;
//! Return the typeId.
static unsigned int typeId();
//! \reimp
virtual unsigned int instanceTypeId() const override;
private:
DISABLE_COPY(MCSeparationEvent);
DISABLE_ASSI(MCSeparationEvent);
MCObject & m_separatedObject;
static unsigned int m_typeId;
};
#endif // MCSEPARATIONEVENT_HH
| 412 | 0.681611 | 1 | 0.681611 | game-dev | MEDIA | 0.595933 | game-dev | 0.638446 | 1 | 0.638446 |
D363N6UY/MapleStory-v113-Server-Eimulator | 6,872 | Libs/scripts/npc/2091005.js | var status = -1;
var sel;
var mapid;
function start() {
mapid = cm.getMapId();
if (mapid == 925020001) {
cm.sendSimple("My master is the most powerful man in Mu Lung. Are you telling me you're trying to challenge our great master? Don't say I didn't warn you. \r #b#L0# I want to tackle him myself.#l \n\r #L1# I want to challenge him as a team.#l \n\r #L2# I want a belt.#l \n\r #L3# I want to reset my training points.#l \n\r #L5# What's a Mu Lung Training Tower?#l");
} else if (isRestingSpot(mapid)) {
cm.sendSimple("I'm amazed to know that you've safely reached up to this level. I can guarantee you, however, that it won't get any easier. What do you think? Do you want to keep going?#b \n\r #L0# Yes, I'll keep going.#l \n\r #L1# I want out#l \n\r #L2# I want to save my progress on record.#l");
} else {
cm.sendYesNo("What? You're ready to quit already? You just need to move on to the next level. Are you sure you want to quit?");
}
}
function action(mode, type, selection) {
if (mapid == 925020001) {
if (mode == 1) {
status++;
} else {
cm.dispose();
return;
}
if (status == 0) {
sel = selection;
if (sel == 5) {
cm.sendNext("My master is the most powerful individual in Mu Lung, and he is responsible for erecting this amazing Mu Lung Training Tower. Mu Lung Training Tower is a colossal training facility that consists of 38 floors. Each floor represents additional levels of difficulty. Of course, with your skills, reaching the top floor will be impossible...");
cm.dispose();
} else if (sel == 3) {
cm.sendYesNo("You know if you reset your training points, then it'll return to 0, right? I can honestly say that it's not necessarily a bad thing. Once you reset your training points and start over again, then you'll be able to receive the belts once more. Do you want to reset your training points?");
} else if (sel == 2) {
cm.sendSimple("Your total training points so far are #b"+cm.getDojoPoints()+"#k. Our master loves talented individuals, so if you rack up enough training points, you'll be able to receive a belt based on your training points...\n\r #L0##i1132000:# #t1132000# (500)#l \n\r #L1##i1132001:# #t1132001# (1500)#l \n\r #L2##i1132002:# #t1132002# (3000)#l \n\r #L3##i1132003:# #t1132003# (4500)#l \n\r #L4##i1132004:# #t1132004# (6000)#l\r\n");
} else if (sel == 1) {
if (cm.getParty() != null) {
if (cm.isLeader()) {
cm.sendOk("Would you like to Enter now?");
} else {
cm.sendOk("Hey, you're not even a leader of your party. What are you doing trying to sneak in? Tell your party leader to talk to me if you want to enter the premise...");
}
}
} else if (sel == 0) {
if (cm.getParty() != null) {
cm.sendOk("Please leave your party.");
cm.dispose();
}
var record = cm.getQuestRecord(150000);
var data = record.getCustomData();
if (data != null) {
var idd = get_restinFieldID(parseInt(data));
if (idd != 925020002) {
cm.dojoAgent_NextMap(true, true , idd );
record.setCustomData(null);
} else {
cm.sendOk("Please try again later.");
}
} else {
cm.start_DojoAgent(true, false);
}
cm.dispose();
// cm.sendYesNo("The last time you took the challenge yourself, you were able to reach Floor #18. I can take you straight to that floor, if you want. Are you interested?");
}
} else if (status == 1) {
if (sel == 3) {
cm.setDojoRecord(true);
cm.sendOk("I have resetted your training points to 0.");
} else if (sel == 2) {
var record = cm.getDojoRecord();
var required = 0;
switch (record) {
case 0:
required = 500;
break;
case 1:
required = 1500;
break;
case 2:
required = 3000;
break;
case 3:
required = 4500;
break;
case 4:
required = 6000;
break;
case 5:
required = 9000;
break;
case 6:
required = 11000;
break;
case 7:
required = 15000;
break;
}
if (record == selection && cm.getDojoPoints() >= required) {
var item = 1132000 + record;
if (cm.canHold(item)) {
cm.gainItem(item, 1);
cm.setDojoRecord(false);
} else {
cm.sendOk("Please check if you have any available slot in your inventory.");
}
} else {
cm.sendOk("You either already have it or insufficient training points. Do try getting the weaker belts first.");
}
cm.dispose();
} else if (sel == 1) {
cm.start_DojoAgent(true, true);
cm.dispose();
}
}
} else if (isRestingSpot(mapid)) {
if (mode == 1) {
status++;
} else {
cm.dispose();
return;
}
if (status == 0) {
sel = selection;
if (sel == 0) {
if (cm.getParty() == null || cm.isLeader()) {
cm.dojoAgent_NextMap(true, true);
} else {
cm.sendOk("Only the leader may go on.");
}
//cm.getQuestRecord(150000).setCustomData(null);
cm.dispose();
} else if (sel == 1) {
cm.askAcceptDecline("Do you want to quit? You really want to leave here?");
} else if (sel == 2) {
if (cm.getParty() == null) {
var stage = get_stageId(cm.getMapId());
cm.getQuestRecord(150000).setCustomData(stage);
cm.sendOk("I have just recorded your progress. The next time you get here, I'll sent you directly to this level.");
cm.dispose();
} else {
cm.sendOk("Hey.. you can't record your progress with a team...");
cm.dispose();
}
}
} else if (status == 1) {
if (sel == 1) {
if (cm.isLeader()) {
cm.warpParty(925020002);
} else {
cm.warp(925020002);
}
}
cm.dispose();
}
} else {
if (mode == 1) {
if (cm.isLeader()) {
cm.warpParty(925020002);
} else {
cm.warp(925020002);
}
}
cm.dispose();
}
}
function get_restinFieldID(id) {
var idd = 925020002;
switch (id) {
case 1:
idd = 925020600;
break;
case 2:
idd = 925021200;
break;
case 3:
idd = 925021800;
break;
case 4:
idd = 925022400;
break;
case 5:
idd = 925023000;
break;
case 6:
idd = 925023600;
break;
}
for (var i = 0; i < 10; i++) {
var canenterr = true;
for (var x = 1; x < 39; x++) {
var map = cm.getMap(925020000 + 100 * x + i);
if (map.getCharactersSize() > 0) {
canenterr = false;
break;
}
}
if (canenterr) {
idd += i;
break;
}
}
return idd;
}
function get_stageId(mapid) {
if (mapid >= 925020600 && mapid <= 925020614) {
return 1;
} else if (mapid >= 925021200 && mapid <= 925021214) {
return 2;
} else if (mapid >= 925021800 && mapid <= 925021814) {
return 3;
} else if (mapid >= 925022400 && mapid <= 925022414) {
return 4;
} else if (mapid >= 925023000 && mapid <= 925023014) {
return 5;
} else if (mapid >= 925023600 && mapid <= 925023614) {
return 6;
}
return 0;
}
function isRestingSpot(id) {
return (get_stageId(id) > 0);
} | 412 | 0.627326 | 1 | 0.627326 | game-dev | MEDIA | 0.868186 | game-dev | 0.918563 | 1 | 0.918563 |
Lokathor/fermium | 15,629 | SDL2-2.26.5/include/SDL_keycode.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_keycode.h
*
* Defines constants which identify keyboard keys and modifiers.
*/
#ifndef SDL_keycode_h_
#define SDL_keycode_h_
#include "SDL_stdinc.h"
#include "SDL_scancode.h"
/**
* \brief The SDL virtual key representation.
*
* Values of this type are used to represent keyboard keys using the current
* layout of the keyboard. These values include Unicode values representing
* the unmodified character that would be generated by pressing the key, or
* an SDLK_* constant for those keys that do not generate characters.
*
* A special exception is the number keys at the top of the keyboard which
* always map to SDLK_0...SDLK_9, regardless of layout.
*/
typedef Sint32 SDL_Keycode;
#define SDLK_SCANCODE_MASK (1<<30)
#define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK)
typedef enum
{
SDLK_UNKNOWN = 0,
SDLK_RETURN = '\r',
SDLK_ESCAPE = '\x1B',
SDLK_BACKSPACE = '\b',
SDLK_TAB = '\t',
SDLK_SPACE = ' ',
SDLK_EXCLAIM = '!',
SDLK_QUOTEDBL = '"',
SDLK_HASH = '#',
SDLK_PERCENT = '%',
SDLK_DOLLAR = '$',
SDLK_AMPERSAND = '&',
SDLK_QUOTE = '\'',
SDLK_LEFTPAREN = '(',
SDLK_RIGHTPAREN = ')',
SDLK_ASTERISK = '*',
SDLK_PLUS = '+',
SDLK_COMMA = ',',
SDLK_MINUS = '-',
SDLK_PERIOD = '.',
SDLK_SLASH = '/',
SDLK_0 = '0',
SDLK_1 = '1',
SDLK_2 = '2',
SDLK_3 = '3',
SDLK_4 = '4',
SDLK_5 = '5',
SDLK_6 = '6',
SDLK_7 = '7',
SDLK_8 = '8',
SDLK_9 = '9',
SDLK_COLON = ':',
SDLK_SEMICOLON = ';',
SDLK_LESS = '<',
SDLK_EQUALS = '=',
SDLK_GREATER = '>',
SDLK_QUESTION = '?',
SDLK_AT = '@',
/*
Skip uppercase letters
*/
SDLK_LEFTBRACKET = '[',
SDLK_BACKSLASH = '\\',
SDLK_RIGHTBRACKET = ']',
SDLK_CARET = '^',
SDLK_UNDERSCORE = '_',
SDLK_BACKQUOTE = '`',
SDLK_a = 'a',
SDLK_b = 'b',
SDLK_c = 'c',
SDLK_d = 'd',
SDLK_e = 'e',
SDLK_f = 'f',
SDLK_g = 'g',
SDLK_h = 'h',
SDLK_i = 'i',
SDLK_j = 'j',
SDLK_k = 'k',
SDLK_l = 'l',
SDLK_m = 'm',
SDLK_n = 'n',
SDLK_o = 'o',
SDLK_p = 'p',
SDLK_q = 'q',
SDLK_r = 'r',
SDLK_s = 's',
SDLK_t = 't',
SDLK_u = 'u',
SDLK_v = 'v',
SDLK_w = 'w',
SDLK_x = 'x',
SDLK_y = 'y',
SDLK_z = 'z',
SDLK_CAPSLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CAPSLOCK),
SDLK_F1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F1),
SDLK_F2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F2),
SDLK_F3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F3),
SDLK_F4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F4),
SDLK_F5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F5),
SDLK_F6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F6),
SDLK_F7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F7),
SDLK_F8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F8),
SDLK_F9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F9),
SDLK_F10 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F10),
SDLK_F11 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F11),
SDLK_F12 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F12),
SDLK_PRINTSCREEN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRINTSCREEN),
SDLK_SCROLLLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SCROLLLOCK),
SDLK_PAUSE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAUSE),
SDLK_INSERT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INSERT),
SDLK_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HOME),
SDLK_PAGEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEUP),
SDLK_DELETE = '\x7F',
SDLK_END = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_END),
SDLK_PAGEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEDOWN),
SDLK_RIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RIGHT),
SDLK_LEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LEFT),
SDLK_DOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DOWN),
SDLK_UP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UP),
SDLK_NUMLOCKCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_NUMLOCKCLEAR),
SDLK_KP_DIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DIVIDE),
SDLK_KP_MULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MULTIPLY),
SDLK_KP_MINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MINUS),
SDLK_KP_PLUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUS),
SDLK_KP_ENTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_ENTER),
SDLK_KP_1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_1),
SDLK_KP_2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_2),
SDLK_KP_3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_3),
SDLK_KP_4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_4),
SDLK_KP_5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_5),
SDLK_KP_6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_6),
SDLK_KP_7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_7),
SDLK_KP_8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_8),
SDLK_KP_9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_9),
SDLK_KP_0 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_0),
SDLK_KP_PERIOD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERIOD),
SDLK_APPLICATION = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APPLICATION),
SDLK_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_POWER),
SDLK_KP_EQUALS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALS),
SDLK_F13 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F13),
SDLK_F14 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F14),
SDLK_F15 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F15),
SDLK_F16 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F16),
SDLK_F17 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F17),
SDLK_F18 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F18),
SDLK_F19 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F19),
SDLK_F20 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F20),
SDLK_F21 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F21),
SDLK_F22 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F22),
SDLK_F23 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F23),
SDLK_F24 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F24),
SDLK_EXECUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXECUTE),
SDLK_HELP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HELP),
SDLK_MENU = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MENU),
SDLK_SELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SELECT),
SDLK_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_STOP),
SDLK_AGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AGAIN),
SDLK_UNDO = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UNDO),
SDLK_CUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CUT),
SDLK_COPY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COPY),
SDLK_PASTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PASTE),
SDLK_FIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_FIND),
SDLK_MUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MUTE),
SDLK_VOLUMEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEUP),
SDLK_VOLUMEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEDOWN),
SDLK_KP_COMMA = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COMMA),
SDLK_KP_EQUALSAS400 =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALSAS400),
SDLK_ALTERASE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ALTERASE),
SDLK_SYSREQ = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SYSREQ),
SDLK_CANCEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CANCEL),
SDLK_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEAR),
SDLK_PRIOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRIOR),
SDLK_RETURN2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RETURN2),
SDLK_SEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SEPARATOR),
SDLK_OUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OUT),
SDLK_OPER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OPER),
SDLK_CLEARAGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEARAGAIN),
SDLK_CRSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CRSEL),
SDLK_EXSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXSEL),
SDLK_KP_00 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_00),
SDLK_KP_000 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_000),
SDLK_THOUSANDSSEPARATOR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_THOUSANDSSEPARATOR),
SDLK_DECIMALSEPARATOR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DECIMALSEPARATOR),
SDLK_CURRENCYUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYUNIT),
SDLK_CURRENCYSUBUNIT =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYSUBUNIT),
SDLK_KP_LEFTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTPAREN),
SDLK_KP_RIGHTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTPAREN),
SDLK_KP_LEFTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTBRACE),
SDLK_KP_RIGHTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTBRACE),
SDLK_KP_TAB = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_TAB),
SDLK_KP_BACKSPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BACKSPACE),
SDLK_KP_A = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_A),
SDLK_KP_B = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_B),
SDLK_KP_C = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_C),
SDLK_KP_D = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_D),
SDLK_KP_E = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_E),
SDLK_KP_F = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_F),
SDLK_KP_XOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_XOR),
SDLK_KP_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_POWER),
SDLK_KP_PERCENT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERCENT),
SDLK_KP_LESS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LESS),
SDLK_KP_GREATER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_GREATER),
SDLK_KP_AMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AMPERSAND),
SDLK_KP_DBLAMPERSAND =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLAMPERSAND),
SDLK_KP_VERTICALBAR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_VERTICALBAR),
SDLK_KP_DBLVERTICALBAR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLVERTICALBAR),
SDLK_KP_COLON = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COLON),
SDLK_KP_HASH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HASH),
SDLK_KP_SPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_SPACE),
SDLK_KP_AT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AT),
SDLK_KP_EXCLAM = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EXCLAM),
SDLK_KP_MEMSTORE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSTORE),
SDLK_KP_MEMRECALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMRECALL),
SDLK_KP_MEMCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMCLEAR),
SDLK_KP_MEMADD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMADD),
SDLK_KP_MEMSUBTRACT =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSUBTRACT),
SDLK_KP_MEMMULTIPLY =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMMULTIPLY),
SDLK_KP_MEMDIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMDIVIDE),
SDLK_KP_PLUSMINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUSMINUS),
SDLK_KP_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEAR),
SDLK_KP_CLEARENTRY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEARENTRY),
SDLK_KP_BINARY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BINARY),
SDLK_KP_OCTAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_OCTAL),
SDLK_KP_DECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DECIMAL),
SDLK_KP_HEXADECIMAL =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HEXADECIMAL),
SDLK_LCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LCTRL),
SDLK_LSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LSHIFT),
SDLK_LALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LALT),
SDLK_LGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LGUI),
SDLK_RCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RCTRL),
SDLK_RSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RSHIFT),
SDLK_RALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RALT),
SDLK_RGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RGUI),
SDLK_MODE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MODE),
SDLK_AUDIONEXT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIONEXT),
SDLK_AUDIOPREV = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPREV),
SDLK_AUDIOSTOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOSTOP),
SDLK_AUDIOPLAY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPLAY),
SDLK_AUDIOMUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOMUTE),
SDLK_MEDIASELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIASELECT),
SDLK_WWW = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_WWW),
SDLK_MAIL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MAIL),
SDLK_CALCULATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALCULATOR),
SDLK_COMPUTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COMPUTER),
SDLK_AC_SEARCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SEARCH),
SDLK_AC_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_HOME),
SDLK_AC_BACK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BACK),
SDLK_AC_FORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_FORWARD),
SDLK_AC_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_STOP),
SDLK_AC_REFRESH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_REFRESH),
SDLK_AC_BOOKMARKS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BOOKMARKS),
SDLK_BRIGHTNESSDOWN =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSDOWN),
SDLK_BRIGHTNESSUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSUP),
SDLK_DISPLAYSWITCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DISPLAYSWITCH),
SDLK_KBDILLUMTOGGLE =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMTOGGLE),
SDLK_KBDILLUMDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMDOWN),
SDLK_KBDILLUMUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMUP),
SDLK_EJECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EJECT),
SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP),
SDLK_APP1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP1),
SDLK_APP2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP2),
SDLK_AUDIOREWIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOREWIND),
SDLK_AUDIOFASTFORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOFASTFORWARD),
SDLK_SOFTLEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SOFTLEFT),
SDLK_SOFTRIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SOFTRIGHT),
SDLK_CALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALL),
SDLK_ENDCALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ENDCALL)
} SDL_KeyCode;
/**
* \brief Enumeration of valid key mods (possibly OR'd together).
*/
typedef enum
{
KMOD_NONE = 0x0000,
KMOD_LSHIFT = 0x0001,
KMOD_RSHIFT = 0x0002,
KMOD_LCTRL = 0x0040,
KMOD_RCTRL = 0x0080,
KMOD_LALT = 0x0100,
KMOD_RALT = 0x0200,
KMOD_LGUI = 0x0400,
KMOD_RGUI = 0x0800,
KMOD_NUM = 0x1000,
KMOD_CAPS = 0x2000,
KMOD_MODE = 0x4000,
KMOD_SCROLL = 0x8000,
KMOD_CTRL = KMOD_LCTRL | KMOD_RCTRL,
KMOD_SHIFT = KMOD_LSHIFT | KMOD_RSHIFT,
KMOD_ALT = KMOD_LALT | KMOD_RALT,
KMOD_GUI = KMOD_LGUI | KMOD_RGUI,
KMOD_RESERVED = KMOD_SCROLL /* This is for source-level compatibility with SDL 2.0.0. */
} SDL_Keymod;
#endif /* SDL_keycode_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.842944 | 1 | 0.842944 | game-dev | MEDIA | 0.745928 | game-dev | 0.704268 | 1 | 0.704268 |
MSW-Git/MSWPackages | 1,296 | quest-achievement-package/MyDesk/QuestAndAchievement/Core/Quest/QuestCategoryEnum.mlua | @Logic
script QuestCategoryEnum extends Logic
property table EnumToStrTable = {}
property table EnumToUIStrTable = {}
property table StrToEnumTable = {}
property integer None = 0
property integer Epic = 1
property integer Sub = 2
property integer Cycle = 3
method boolean Init()
local enumStrList = {
{ "Epic", "에픽" },
{ "Sub", "서브" },
{ "Cycle", "반복" },
}
local enumToStrTable = self.EnumToStrTable
local enumToUIStrTable = self.EnumToUIStrTable
local strToEnumTable = self.StrToEnumTable
for i = 1, #enumStrList do
local str = enumStrList[i][1]
local uiStr = enumStrList[i][2]
local enum = self[str]
if enum == nil then
log_error("Cannot find enum. " .. str)
return false
end
if enumToStrTable[enum] ~= nil then
log_error("Already existing enum. " .. str)
return false
end
enumToStrTable[enum] = str
enumToUIStrTable[enum] = uiStr
strToEnumTable[str] = enum
end
return true
end
method integer ToEnum(string str)
local enum = self.StrToEnumTable[str]
if enum == nil then
return self.None
end
return enum
end
method string ToStr(integer enum)
return self.EnumToStrTable[enum]
end
method string ToUIStr(integer enum)
return self.EnumToUIStrTable[enum]
end
end | 412 | 0.604664 | 1 | 0.604664 | game-dev | MEDIA | 0.147933 | game-dev | 0.845425 | 1 | 0.845425 |
Dreaming381/Latios-Framework | 18,264 | PsyshockPhysics/Physics/Internal/Queries/ColliderCollider/CompoundTerrain.cs | using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
namespace Latios.Psyshock
{
internal static class CompoundTerrain
{
public static bool DistanceBetween(in TerrainCollider terrain,
in RigidTransform terrainTransform,
in CompoundCollider compound,
in RigidTransform compoundTransform,
float maxDistance,
out ColliderDistanceResult result)
{
var processor = new DistanceBetweenClosestProcessor { bestIndex = -1, bestDistance = float.MaxValue };
DistanceBetweenAll(in terrain, in terrainTransform, in compound, in compoundTransform, maxDistance, ref processor);
var hit = processor.bestIndex >= 0;
if (!hit)
{
result = default;
return false;
}
var triangleIndices = terrain.terrainColliderBlob.Value.GetTriangle(processor.bestIndex);
var triangle = PointRayTerrain.CreateLocalTriangle(ref terrain.terrainColliderBlob.Value,
triangleIndices,
terrain.baseHeightOffset,
terrain.scale);
hit = TriangleCompound.DistanceBetween(in compound, in compoundTransform, in triangle, in terrainTransform, maxDistance, out result);
(result.hitpointA, result.hitpointB) = (result.hitpointB, result.hitpointA);
(result.normalA, result.normalB) = (result.normalB, result.normalA);
result.subColliderIndexB = result.subColliderIndexA;
result.subColliderIndexA = processor.bestIndex;
return hit;
}
public static unsafe void DistanceBetweenAll<T>(in TerrainCollider terrain,
in RigidTransform terrainTransform,
in CompoundCollider compound,
in RigidTransform compoundTransform,
float maxDistance,
ref T processor) where T : unmanaged, IDistanceBetweenAllProcessor
{
var aabb = Physics.AabbFrom(compound, math.mul(math.inverse(terrainTransform), compoundTransform));
var inverseScale = math.rcp(terrain.scale);
var validAxes = math.isfinite(inverseScale);
var crosses = (aabb.min < 0f) & (aabb.max > 0f);
if (math.any(!crosses & !validAxes))
return;
Physics.GetCenterExtents(aabb, out var center, out var extents);
center *= inverseScale;
extents *= inverseScale;
var min = (int3)math.floor(center - extents);
var max = (int3)math.ceil(center + extents);
min.y -= terrain.baseHeightOffset;
max.y -= terrain.baseHeightOffset;
var minInt = math.select(short.MinValue, min, validAxes);
var maxInt = math.select(short.MaxValue, max, validAxes);
if (minInt.y > terrain.terrainColliderBlob.Value.maxHeight || maxInt.y < terrain.terrainColliderBlob.Value.minHeight)
return;
var terrainProcessor = new DistanceBetweenAllProcessor<T>
{
compound = compound,
compoundTransform = compoundTransform,
maxDistance = maxDistance,
minHeight = (short)minInt.y,
maxHeight = (short)minInt.y,
heightOffset = terrain.baseHeightOffset,
scale = terrain.scale,
terrainTransform = terrainTransform,
processor = (T*)UnsafeUtility.AddressOf(ref processor)
};
terrain.terrainColliderBlob.Value.FindTriangles(minInt.x, minInt.z, maxInt.x, maxInt.z, ref terrainProcessor);
}
public static bool ColliderCast(in CompoundCollider compoundToCast,
in RigidTransform castStart,
float3 castEnd,
in TerrainCollider targetTerrain,
in RigidTransform targetTerrainTransform,
out ColliderCastResult result)
{
var targetTerrainTransformInverse = math.inverse(targetTerrainTransform);
var casterInTargetSpace = math.mul(targetTerrainTransformInverse, castStart);
var aabb =
Physics.AabbFrom(compoundToCast, in casterInTargetSpace, casterInTargetSpace.pos + math.rotate(targetTerrainTransformInverse, castEnd - castStart.pos));
var inverseScale = math.rcp(targetTerrain.scale);
var validAxes = math.isfinite(inverseScale);
result = default;
var crosses = (aabb.min < 0f) & (aabb.max > 0f);
if (math.any(!crosses & !validAxes))
return false;
Physics.GetCenterExtents(aabb, out var center, out var extents);
center *= inverseScale;
extents *= inverseScale;
var min = (int3)math.floor(center - extents);
var max = (int3)math.ceil(center + extents);
min.y -= targetTerrain.baseHeightOffset;
max.y -= targetTerrain.baseHeightOffset;
var minInt = math.select(short.MinValue, min, validAxes);
var maxInt = math.select(short.MaxValue, max, validAxes);
if (minInt.y > targetTerrain.terrainColliderBlob.Value.maxHeight || maxInt.y < targetTerrain.terrainColliderBlob.Value.minHeight)
return false;
var processor = new CastProcessor
{
bestDistance = float.MaxValue,
bestIndex = -1,
found = false,
invalid = false,
compound = compoundToCast,
castStart = castStart,
castEnd = castEnd,
terrainTransform = targetTerrainTransform,
minHeight = (short)minInt.y,
maxHeight = (short)minInt.y,
heightOffset = targetTerrain.baseHeightOffset,
scale = targetTerrain.scale,
};
targetTerrain.terrainColliderBlob.Value.FindTriangles(minInt.x, minInt.z, maxInt.x, maxInt.z, ref processor);
if (processor.invalid || !processor.found)
return false;
var hitTransform = castStart;
hitTransform.pos += math.normalize(castEnd - castStart.pos) * processor.bestDistance;
var triangleIndices = targetTerrain.terrainColliderBlob.Value.GetTriangle(processor.bestIndex);
var triangle = PointRayTerrain.CreateLocalTriangle(ref targetTerrain.terrainColliderBlob.Value,
triangleIndices,
targetTerrain.baseHeightOffset,
targetTerrain.scale);
TriangleCompound.DistanceBetween(in compoundToCast,
in hitTransform,
in triangle,
in targetTerrainTransform,
1f,
out var distanceResult);
result = new ColliderCastResult
{
hitpoint = distanceResult.hitpointA,
normalOnCaster = distanceResult.normalA,
normalOnTarget = distanceResult.normalB,
subColliderIndexOnCaster = processor.bestIndex,
subColliderIndexOnTarget = distanceResult.subColliderIndexA,
distance = math.distance(hitTransform.pos, castStart.pos)
};
return true;
}
public static bool ColliderCast(in TerrainCollider terrainToCast,
in RigidTransform castStart,
float3 castEnd,
in CompoundCollider targetCompound,
in RigidTransform targetCompoundTransform,
out ColliderCastResult result)
{
var castReverse = castStart.pos - castEnd;
var worldToCasterSpace = math.inverse(castStart);
var targetInCasterSpace = math.mul(worldToCasterSpace, targetCompoundTransform);
var reverseCastEnd = targetInCasterSpace.pos + math.rotate(worldToCasterSpace, castReverse);
var aabb = Physics.AabbFrom(targetCompound, in targetInCasterSpace, reverseCastEnd);
var inverseScale = math.rcp(terrainToCast.scale);
var validAxes = math.isfinite(inverseScale);
result = default;
var crosses = (aabb.min < 0f) & (aabb.max > 0f);
if (math.any(!crosses & !validAxes))
return false;
Physics.GetCenterExtents(aabb, out var center, out var extents);
center *= inverseScale;
extents *= inverseScale;
var min = (int3)math.floor(center - extents);
var max = (int3)math.ceil(center + extents);
min.y -= terrainToCast.baseHeightOffset;
max.y -= terrainToCast.baseHeightOffset;
var minInt = math.select(short.MinValue, min, validAxes);
var maxInt = math.select(short.MaxValue, max, validAxes);
if (minInt.y > terrainToCast.terrainColliderBlob.Value.maxHeight || maxInt.y < terrainToCast.terrainColliderBlob.Value.minHeight)
return false;
var processor = new CastProcessor
{
bestDistance = float.MaxValue,
bestIndex = -1,
found = false,
invalid = false,
compound = targetCompound,
castStart = castStart,
castEnd = castEnd,
terrainTransform = RigidTransform.identity,
minHeight = (short)minInt.y,
maxHeight = (short)minInt.y,
heightOffset = terrainToCast.baseHeightOffset,
scale = terrainToCast.scale,
};
terrainToCast.terrainColliderBlob.Value.FindTriangles(minInt.x, minInt.z, maxInt.x, maxInt.z, ref processor);
if (processor.invalid || !processor.found)
{
result = default;
return false;
}
var hitTransform = castStart;
hitTransform.pos += math.normalize(castEnd - castStart.pos) * processor.bestDistance;
var triangleIndices = terrainToCast.terrainColliderBlob.Value.GetTriangle(processor.bestIndex);
var triangle = PointRayTerrain.CreateLocalTriangle(ref terrainToCast.terrainColliderBlob.Value,
triangleIndices,
terrainToCast.baseHeightOffset,
terrainToCast.scale);
TriangleCompound.DistanceBetween(in targetCompound,
in targetCompoundTransform,
in triangle,
in hitTransform,
1f,
out var distanceResult);
result = new ColliderCastResult
{
hitpoint = distanceResult.hitpointB,
normalOnCaster = distanceResult.normalB,
normalOnTarget = distanceResult.normalA,
subColliderIndexOnCaster = distanceResult.subColliderIndexA,
subColliderIndexOnTarget = processor.bestIndex,
distance = math.distance(hitTransform.pos, castStart.pos)
};
return true;
}
public static UnitySim.ContactsBetweenResult UnityContactsBetween(in TerrainCollider terrain,
in RigidTransform terrainTransform,
in CompoundCollider compound,
in RigidTransform compoundTransform,
in ColliderDistanceResult distanceResult)
{
var triangleIndices = terrain.terrainColliderBlob.Value.GetTriangle(distanceResult.subColliderIndexA);
var triangle = PointRayTerrain.CreateLocalTriangle(ref terrain.terrainColliderBlob.Value, triangleIndices, terrain.baseHeightOffset, terrain.scale);
return TriangleCompound.UnityContactsBetween(in compound, in compoundTransform, in triangle, in terrainTransform, distanceResult.ToFlipped()).ToFlipped();
}
struct DistanceBetweenClosestProcessor : IDistanceBetweenAllProcessor
{
public int bestIndex;
public float bestDistance;
public void Execute(in ColliderDistanceResult result)
{
if (bestIndex < 0 || result.distance < bestDistance)
{
bestIndex = result.subColliderIndexA;
bestDistance = result.distance;
}
}
}
unsafe struct DistanceBetweenAllProcessor<T> : TerrainColliderBlob.IFindTrianglesProcessor where T : unmanaged, IDistanceBetweenAllProcessor
{
public CompoundCollider compound;
public RigidTransform compoundTransform;
public float maxDistance;
public short minHeight;
public short maxHeight;
public int heightOffset;
public float3 scale;
public RigidTransform terrainTransform;
public T* processor;
public ulong FilterPatch(ref TerrainColliderBlob.Patch patch, ulong borderMask, short quadsPerBit)
{
var mask = patch.GetFilteredQuadMaskFromHeights(minHeight, maxHeight);
mask &= borderMask;
return mask;
}
public void Execute(ref TerrainColliderBlob blob, int3 triangleHeightIndices, int triangleIndex)
{
var triangle = PointRayTerrain.CreateLocalTriangle(ref blob, triangleHeightIndices, heightOffset, scale);
var hit =
TriangleCompound.DistanceBetween(in compound, in compoundTransform, in triangle, in terrainTransform, maxDistance, out var tempResult);
tempResult.subColliderIndexB = triangleIndex;
tempResult = tempResult.ToFlipped();
if (hit)
{
processor->Execute(in tempResult);
}
}
}
struct CastProcessor : TerrainColliderBlob.IFindTrianglesProcessor
{
public CompoundCollider compound;
public RigidTransform castStart;
public float3 castEnd;
public RigidTransform terrainTransform;
public short minHeight;
public short maxHeight;
public int heightOffset;
public float3 scale;
public float bestDistance;
public int bestIndex;
public bool found;
public bool invalid;
public ulong FilterPatch(ref TerrainColliderBlob.Patch patch, ulong borderMask, short quadsPerBit)
{
if (invalid)
return 0;
var mask = patch.GetFilteredQuadMaskFromHeights(minHeight, maxHeight);
mask &= borderMask;
return mask;
}
public void Execute(ref TerrainColliderBlob blob, int3 triangleHeightIndices, int triangleIndex)
{
if (invalid)
return;
var triangle = PointRayTerrain.CreateLocalTriangle(ref blob, triangleHeightIndices, heightOffset, scale);
Physics.ScaleStretchCollider(ref triangle, 1f, scale);
// Check that we don't start already intersecting.
if (TriangleCompound.DistanceBetween(in compound, in castStart, in triangle, in terrainTransform, 0f, out _))
{
invalid = true;
return;
}
if (TriangleCompound.ColliderCast(in compound, in castStart, castEnd, in triangle, in terrainTransform, out var hit))
{
if (!found || hit.distance < bestDistance)
{
found = true;
bestDistance = hit.distance;
bestIndex = triangleIndex;
}
}
}
}
}
}
| 412 | 0.910262 | 1 | 0.910262 | game-dev | MEDIA | 0.904366 | game-dev | 0.997006 | 1 | 0.997006 |
google/tock-on-titan | 114,483 | third_party/syn-1.0.11/src/gen/visit_mut.rs | // This file is @generated by syn-internal-codegen.
// It is not intended for manual editing.
#![allow(unused_variables)]
#[cfg(any(feature = "full", feature = "derive"))]
use crate::gen::helper::visit_mut::*;
#[cfg(any(feature = "full", feature = "derive"))]
use crate::punctuated::Punctuated;
use crate::*;
use proc_macro2::Span;
#[cfg(feature = "full")]
macro_rules! full {
($e:expr) => {
$e
};
}
#[cfg(all(feature = "derive", not(feature = "full")))]
macro_rules! full {
($e:expr) => {
unreachable!()
};
}
#[cfg(any(feature = "full", feature = "derive"))]
macro_rules! skip {
($($tt:tt)*) => {};
}
/// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in
/// place.
///
/// See the [module documentation] for details.
///
/// [module documentation]: self
///
/// *This trait is available if Syn is built with the `"visit-mut"` feature.*
pub trait VisitMut {
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_abi_mut(&mut self, i: &mut Abi) {
visit_abi_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_angle_bracketed_generic_arguments_mut(
&mut self,
i: &mut AngleBracketedGenericArguments,
) {
visit_angle_bracketed_generic_arguments_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_arm_mut(&mut self, i: &mut Arm) {
visit_arm_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_attr_style_mut(&mut self, i: &mut AttrStyle) {
visit_attr_style_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_attribute_mut(&mut self, i: &mut Attribute) {
visit_attribute_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_bare_fn_arg_mut(&mut self, i: &mut BareFnArg) {
visit_bare_fn_arg_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_bin_op_mut(&mut self, i: &mut BinOp) {
visit_bin_op_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_binding_mut(&mut self, i: &mut Binding) {
visit_binding_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_block_mut(&mut self, i: &mut Block) {
visit_block_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_bound_lifetimes_mut(&mut self, i: &mut BoundLifetimes) {
visit_bound_lifetimes_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_const_param_mut(&mut self, i: &mut ConstParam) {
visit_const_param_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_constraint_mut(&mut self, i: &mut Constraint) {
visit_constraint_mut(self, i)
}
#[cfg(feature = "derive")]
fn visit_data_mut(&mut self, i: &mut Data) {
visit_data_mut(self, i)
}
#[cfg(feature = "derive")]
fn visit_data_enum_mut(&mut self, i: &mut DataEnum) {
visit_data_enum_mut(self, i)
}
#[cfg(feature = "derive")]
fn visit_data_struct_mut(&mut self, i: &mut DataStruct) {
visit_data_struct_mut(self, i)
}
#[cfg(feature = "derive")]
fn visit_data_union_mut(&mut self, i: &mut DataUnion) {
visit_data_union_mut(self, i)
}
#[cfg(feature = "derive")]
fn visit_derive_input_mut(&mut self, i: &mut DeriveInput) {
visit_derive_input_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_mut(&mut self, i: &mut Expr) {
visit_expr_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_array_mut(&mut self, i: &mut ExprArray) {
visit_expr_array_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_assign_mut(&mut self, i: &mut ExprAssign) {
visit_expr_assign_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_assign_op_mut(&mut self, i: &mut ExprAssignOp) {
visit_expr_assign_op_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_async_mut(&mut self, i: &mut ExprAsync) {
visit_expr_async_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_await_mut(&mut self, i: &mut ExprAwait) {
visit_expr_await_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_binary_mut(&mut self, i: &mut ExprBinary) {
visit_expr_binary_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_block_mut(&mut self, i: &mut ExprBlock) {
visit_expr_block_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_box_mut(&mut self, i: &mut ExprBox) {
visit_expr_box_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_break_mut(&mut self, i: &mut ExprBreak) {
visit_expr_break_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_call_mut(&mut self, i: &mut ExprCall) {
visit_expr_call_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_cast_mut(&mut self, i: &mut ExprCast) {
visit_expr_cast_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_closure_mut(&mut self, i: &mut ExprClosure) {
visit_expr_closure_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_continue_mut(&mut self, i: &mut ExprContinue) {
visit_expr_continue_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_field_mut(&mut self, i: &mut ExprField) {
visit_expr_field_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_for_loop_mut(&mut self, i: &mut ExprForLoop) {
visit_expr_for_loop_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_group_mut(&mut self, i: &mut ExprGroup) {
visit_expr_group_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_if_mut(&mut self, i: &mut ExprIf) {
visit_expr_if_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_index_mut(&mut self, i: &mut ExprIndex) {
visit_expr_index_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_let_mut(&mut self, i: &mut ExprLet) {
visit_expr_let_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_lit_mut(&mut self, i: &mut ExprLit) {
visit_expr_lit_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_loop_mut(&mut self, i: &mut ExprLoop) {
visit_expr_loop_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_macro_mut(&mut self, i: &mut ExprMacro) {
visit_expr_macro_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_match_mut(&mut self, i: &mut ExprMatch) {
visit_expr_match_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_method_call_mut(&mut self, i: &mut ExprMethodCall) {
visit_expr_method_call_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_paren_mut(&mut self, i: &mut ExprParen) {
visit_expr_paren_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_path_mut(&mut self, i: &mut ExprPath) {
visit_expr_path_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_range_mut(&mut self, i: &mut ExprRange) {
visit_expr_range_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_reference_mut(&mut self, i: &mut ExprReference) {
visit_expr_reference_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_repeat_mut(&mut self, i: &mut ExprRepeat) {
visit_expr_repeat_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_return_mut(&mut self, i: &mut ExprReturn) {
visit_expr_return_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_struct_mut(&mut self, i: &mut ExprStruct) {
visit_expr_struct_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_try_mut(&mut self, i: &mut ExprTry) {
visit_expr_try_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_try_block_mut(&mut self, i: &mut ExprTryBlock) {
visit_expr_try_block_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_tuple_mut(&mut self, i: &mut ExprTuple) {
visit_expr_tuple_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_type_mut(&mut self, i: &mut ExprType) {
visit_expr_type_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_expr_unary_mut(&mut self, i: &mut ExprUnary) {
visit_expr_unary_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_unsafe_mut(&mut self, i: &mut ExprUnsafe) {
visit_expr_unsafe_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_while_mut(&mut self, i: &mut ExprWhile) {
visit_expr_while_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_expr_yield_mut(&mut self, i: &mut ExprYield) {
visit_expr_yield_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_field_mut(&mut self, i: &mut Field) {
visit_field_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_field_pat_mut(&mut self, i: &mut FieldPat) {
visit_field_pat_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_field_value_mut(&mut self, i: &mut FieldValue) {
visit_field_value_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_fields_mut(&mut self, i: &mut Fields) {
visit_fields_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_fields_named_mut(&mut self, i: &mut FieldsNamed) {
visit_fields_named_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_fields_unnamed_mut(&mut self, i: &mut FieldsUnnamed) {
visit_fields_unnamed_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_file_mut(&mut self, i: &mut File) {
visit_file_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_fn_arg_mut(&mut self, i: &mut FnArg) {
visit_fn_arg_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_foreign_item_mut(&mut self, i: &mut ForeignItem) {
visit_foreign_item_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_foreign_item_fn_mut(&mut self, i: &mut ForeignItemFn) {
visit_foreign_item_fn_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_foreign_item_macro_mut(&mut self, i: &mut ForeignItemMacro) {
visit_foreign_item_macro_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_foreign_item_static_mut(&mut self, i: &mut ForeignItemStatic) {
visit_foreign_item_static_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_foreign_item_type_mut(&mut self, i: &mut ForeignItemType) {
visit_foreign_item_type_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_generic_argument_mut(&mut self, i: &mut GenericArgument) {
visit_generic_argument_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_generic_method_argument_mut(&mut self, i: &mut GenericMethodArgument) {
visit_generic_method_argument_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_generic_param_mut(&mut self, i: &mut GenericParam) {
visit_generic_param_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_generics_mut(&mut self, i: &mut Generics) {
visit_generics_mut(self, i)
}
fn visit_ident_mut(&mut self, i: &mut Ident) {
visit_ident_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_impl_item_mut(&mut self, i: &mut ImplItem) {
visit_impl_item_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_impl_item_const_mut(&mut self, i: &mut ImplItemConst) {
visit_impl_item_const_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_impl_item_macro_mut(&mut self, i: &mut ImplItemMacro) {
visit_impl_item_macro_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_impl_item_method_mut(&mut self, i: &mut ImplItemMethod) {
visit_impl_item_method_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_impl_item_type_mut(&mut self, i: &mut ImplItemType) {
visit_impl_item_type_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_index_mut(&mut self, i: &mut Index) {
visit_index_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_mut(&mut self, i: &mut Item) {
visit_item_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_const_mut(&mut self, i: &mut ItemConst) {
visit_item_const_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_enum_mut(&mut self, i: &mut ItemEnum) {
visit_item_enum_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_extern_crate_mut(&mut self, i: &mut ItemExternCrate) {
visit_item_extern_crate_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_fn_mut(&mut self, i: &mut ItemFn) {
visit_item_fn_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_foreign_mod_mut(&mut self, i: &mut ItemForeignMod) {
visit_item_foreign_mod_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_impl_mut(&mut self, i: &mut ItemImpl) {
visit_item_impl_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_macro_mut(&mut self, i: &mut ItemMacro) {
visit_item_macro_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_macro2_mut(&mut self, i: &mut ItemMacro2) {
visit_item_macro2_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_mod_mut(&mut self, i: &mut ItemMod) {
visit_item_mod_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_static_mut(&mut self, i: &mut ItemStatic) {
visit_item_static_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_struct_mut(&mut self, i: &mut ItemStruct) {
visit_item_struct_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_trait_mut(&mut self, i: &mut ItemTrait) {
visit_item_trait_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_trait_alias_mut(&mut self, i: &mut ItemTraitAlias) {
visit_item_trait_alias_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_type_mut(&mut self, i: &mut ItemType) {
visit_item_type_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_union_mut(&mut self, i: &mut ItemUnion) {
visit_item_union_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_item_use_mut(&mut self, i: &mut ItemUse) {
visit_item_use_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_label_mut(&mut self, i: &mut Label) {
visit_label_mut(self, i)
}
fn visit_lifetime_mut(&mut self, i: &mut Lifetime) {
visit_lifetime_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lifetime_def_mut(&mut self, i: &mut LifetimeDef) {
visit_lifetime_def_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_mut(&mut self, i: &mut Lit) {
visit_lit_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_bool_mut(&mut self, i: &mut LitBool) {
visit_lit_bool_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_byte_mut(&mut self, i: &mut LitByte) {
visit_lit_byte_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_byte_str_mut(&mut self, i: &mut LitByteStr) {
visit_lit_byte_str_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_char_mut(&mut self, i: &mut LitChar) {
visit_lit_char_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_float_mut(&mut self, i: &mut LitFloat) {
visit_lit_float_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_int_mut(&mut self, i: &mut LitInt) {
visit_lit_int_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_lit_str_mut(&mut self, i: &mut LitStr) {
visit_lit_str_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_local_mut(&mut self, i: &mut Local) {
visit_local_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_macro_mut(&mut self, i: &mut Macro) {
visit_macro_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_macro_delimiter_mut(&mut self, i: &mut MacroDelimiter) {
visit_macro_delimiter_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_member_mut(&mut self, i: &mut Member) {
visit_member_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_meta_mut(&mut self, i: &mut Meta) {
visit_meta_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_meta_list_mut(&mut self, i: &mut MetaList) {
visit_meta_list_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_meta_name_value_mut(&mut self, i: &mut MetaNameValue) {
visit_meta_name_value_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_method_turbofish_mut(&mut self, i: &mut MethodTurbofish) {
visit_method_turbofish_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_nested_meta_mut(&mut self, i: &mut NestedMeta) {
visit_nested_meta_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_parenthesized_generic_arguments_mut(&mut self, i: &mut ParenthesizedGenericArguments) {
visit_parenthesized_generic_arguments_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_mut(&mut self, i: &mut Pat) {
visit_pat_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_box_mut(&mut self, i: &mut PatBox) {
visit_pat_box_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_ident_mut(&mut self, i: &mut PatIdent) {
visit_pat_ident_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_lit_mut(&mut self, i: &mut PatLit) {
visit_pat_lit_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_macro_mut(&mut self, i: &mut PatMacro) {
visit_pat_macro_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_or_mut(&mut self, i: &mut PatOr) {
visit_pat_or_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_path_mut(&mut self, i: &mut PatPath) {
visit_pat_path_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_range_mut(&mut self, i: &mut PatRange) {
visit_pat_range_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_reference_mut(&mut self, i: &mut PatReference) {
visit_pat_reference_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_rest_mut(&mut self, i: &mut PatRest) {
visit_pat_rest_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_slice_mut(&mut self, i: &mut PatSlice) {
visit_pat_slice_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_struct_mut(&mut self, i: &mut PatStruct) {
visit_pat_struct_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_tuple_mut(&mut self, i: &mut PatTuple) {
visit_pat_tuple_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_tuple_struct_mut(&mut self, i: &mut PatTupleStruct) {
visit_pat_tuple_struct_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_type_mut(&mut self, i: &mut PatType) {
visit_pat_type_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_pat_wild_mut(&mut self, i: &mut PatWild) {
visit_pat_wild_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_path_mut(&mut self, i: &mut Path) {
visit_path_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_path_arguments_mut(&mut self, i: &mut PathArguments) {
visit_path_arguments_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_path_segment_mut(&mut self, i: &mut PathSegment) {
visit_path_segment_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_predicate_eq_mut(&mut self, i: &mut PredicateEq) {
visit_predicate_eq_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_predicate_lifetime_mut(&mut self, i: &mut PredicateLifetime) {
visit_predicate_lifetime_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_predicate_type_mut(&mut self, i: &mut PredicateType) {
visit_predicate_type_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_qself_mut(&mut self, i: &mut QSelf) {
visit_qself_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_range_limits_mut(&mut self, i: &mut RangeLimits) {
visit_range_limits_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_receiver_mut(&mut self, i: &mut Receiver) {
visit_receiver_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_return_type_mut(&mut self, i: &mut ReturnType) {
visit_return_type_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_signature_mut(&mut self, i: &mut Signature) {
visit_signature_mut(self, i)
}
fn visit_span_mut(&mut self, i: &mut Span) {
visit_span_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_stmt_mut(&mut self, i: &mut Stmt) {
visit_stmt_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_trait_bound_mut(&mut self, i: &mut TraitBound) {
visit_trait_bound_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_trait_bound_modifier_mut(&mut self, i: &mut TraitBoundModifier) {
visit_trait_bound_modifier_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_trait_item_mut(&mut self, i: &mut TraitItem) {
visit_trait_item_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_trait_item_const_mut(&mut self, i: &mut TraitItemConst) {
visit_trait_item_const_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_trait_item_macro_mut(&mut self, i: &mut TraitItemMacro) {
visit_trait_item_macro_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_trait_item_method_mut(&mut self, i: &mut TraitItemMethod) {
visit_trait_item_method_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_trait_item_type_mut(&mut self, i: &mut TraitItemType) {
visit_trait_item_type_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_mut(&mut self, i: &mut Type) {
visit_type_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_array_mut(&mut self, i: &mut TypeArray) {
visit_type_array_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_bare_fn_mut(&mut self, i: &mut TypeBareFn) {
visit_type_bare_fn_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_group_mut(&mut self, i: &mut TypeGroup) {
visit_type_group_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_impl_trait_mut(&mut self, i: &mut TypeImplTrait) {
visit_type_impl_trait_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_infer_mut(&mut self, i: &mut TypeInfer) {
visit_type_infer_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_macro_mut(&mut self, i: &mut TypeMacro) {
visit_type_macro_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_never_mut(&mut self, i: &mut TypeNever) {
visit_type_never_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_param_mut(&mut self, i: &mut TypeParam) {
visit_type_param_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_param_bound_mut(&mut self, i: &mut TypeParamBound) {
visit_type_param_bound_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_paren_mut(&mut self, i: &mut TypeParen) {
visit_type_paren_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_path_mut(&mut self, i: &mut TypePath) {
visit_type_path_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_ptr_mut(&mut self, i: &mut TypePtr) {
visit_type_ptr_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_reference_mut(&mut self, i: &mut TypeReference) {
visit_type_reference_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_slice_mut(&mut self, i: &mut TypeSlice) {
visit_type_slice_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_trait_object_mut(&mut self, i: &mut TypeTraitObject) {
visit_type_trait_object_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_type_tuple_mut(&mut self, i: &mut TypeTuple) {
visit_type_tuple_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_un_op_mut(&mut self, i: &mut UnOp) {
visit_un_op_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_use_glob_mut(&mut self, i: &mut UseGlob) {
visit_use_glob_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_use_group_mut(&mut self, i: &mut UseGroup) {
visit_use_group_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_use_name_mut(&mut self, i: &mut UseName) {
visit_use_name_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_use_path_mut(&mut self, i: &mut UsePath) {
visit_use_path_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_use_rename_mut(&mut self, i: &mut UseRename) {
visit_use_rename_mut(self, i)
}
#[cfg(feature = "full")]
fn visit_use_tree_mut(&mut self, i: &mut UseTree) {
visit_use_tree_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_variadic_mut(&mut self, i: &mut Variadic) {
visit_variadic_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_variant_mut(&mut self, i: &mut Variant) {
visit_variant_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_vis_crate_mut(&mut self, i: &mut VisCrate) {
visit_vis_crate_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_vis_public_mut(&mut self, i: &mut VisPublic) {
visit_vis_public_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_vis_restricted_mut(&mut self, i: &mut VisRestricted) {
visit_vis_restricted_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_visibility_mut(&mut self, i: &mut Visibility) {
visit_visibility_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_where_clause_mut(&mut self, i: &mut WhereClause) {
visit_where_clause_mut(self, i)
}
#[cfg(any(feature = "derive", feature = "full"))]
fn visit_where_predicate_mut(&mut self, i: &mut WherePredicate) {
visit_where_predicate_mut(self, i)
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_abi_mut<V>(v: &mut V, node: &mut Abi)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.extern_token.span);
if let Some(it) = &mut node.name {
v.visit_lit_str_mut(it)
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_angle_bracketed_generic_arguments_mut<V>(
v: &mut V,
node: &mut AngleBracketedGenericArguments,
) where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.colon2_token {
tokens_helper(v, &mut it.spans)
};
tokens_helper(v, &mut node.lt_token.spans);
for el in Punctuated::pairs_mut(&mut node.args) {
let (it, p) = el.into_tuple();
v.visit_generic_argument_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
tokens_helper(v, &mut node.gt_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_arm_mut<V>(v: &mut V, node: &mut Arm)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_pat_mut(&mut node.pat);
if let Some(it) = &mut node.guard {
tokens_helper(v, &mut (it).0.span);
v.visit_expr_mut(&mut *(it).1);
};
tokens_helper(v, &mut node.fat_arrow_token.spans);
v.visit_expr_mut(&mut *node.body);
if let Some(it) = &mut node.comma {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_attr_style_mut<V>(v: &mut V, node: &mut AttrStyle)
where
V: VisitMut + ?Sized,
{
match node {
AttrStyle::Outer => {}
AttrStyle::Inner(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_attribute_mut<V>(v: &mut V, node: &mut Attribute)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.pound_token.spans);
v.visit_attr_style_mut(&mut node.style);
tokens_helper(v, &mut node.bracket_token.span);
v.visit_path_mut(&mut node.path);
skip!(node.tokens);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_bare_fn_arg_mut<V>(v: &mut V, node: &mut BareFnArg)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.name {
v.visit_ident_mut(&mut (it).0);
tokens_helper(v, &mut (it).1.spans);
};
v.visit_type_mut(&mut node.ty);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_bin_op_mut<V>(v: &mut V, node: &mut BinOp)
where
V: VisitMut + ?Sized,
{
match node {
BinOp::Add(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Sub(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Mul(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Div(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Rem(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::And(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Or(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::BitXor(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::BitAnd(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::BitOr(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Shl(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Shr(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Eq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Lt(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Le(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Ne(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Ge(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::Gt(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::AddEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::SubEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::MulEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::DivEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::RemEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::BitXorEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::BitAndEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::BitOrEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::ShlEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
BinOp::ShrEq(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_binding_mut<V>(v: &mut V, node: &mut Binding)
where
V: VisitMut + ?Sized,
{
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_type_mut(&mut node.ty);
}
#[cfg(feature = "full")]
pub fn visit_block_mut<V>(v: &mut V, node: &mut Block)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.brace_token.span);
for it in &mut node.stmts {
v.visit_stmt_mut(it)
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_bound_lifetimes_mut<V>(v: &mut V, node: &mut BoundLifetimes)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.for_token.span);
tokens_helper(v, &mut node.lt_token.spans);
for el in Punctuated::pairs_mut(&mut node.lifetimes) {
let (it, p) = el.into_tuple();
v.visit_lifetime_def_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
tokens_helper(v, &mut node.gt_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_const_param_mut<V>(v: &mut V, node: &mut ConstParam)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.const_token.span);
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut node.ty);
if let Some(it) = &mut node.eq_token {
tokens_helper(v, &mut it.spans)
};
if let Some(it) = &mut node.default {
v.visit_expr_mut(it)
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_constraint_mut<V>(v: &mut V, node: &mut Constraint)
where
V: VisitMut + ?Sized,
{
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon_token.spans);
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "derive")]
pub fn visit_data_mut<V>(v: &mut V, node: &mut Data)
where
V: VisitMut + ?Sized,
{
match node {
Data::Struct(_binding_0) => {
v.visit_data_struct_mut(_binding_0);
}
Data::Enum(_binding_0) => {
v.visit_data_enum_mut(_binding_0);
}
Data::Union(_binding_0) => {
v.visit_data_union_mut(_binding_0);
}
}
}
#[cfg(feature = "derive")]
pub fn visit_data_enum_mut<V>(v: &mut V, node: &mut DataEnum)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.enum_token.span);
tokens_helper(v, &mut node.brace_token.span);
for el in Punctuated::pairs_mut(&mut node.variants) {
let (it, p) = el.into_tuple();
v.visit_variant_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "derive")]
pub fn visit_data_struct_mut<V>(v: &mut V, node: &mut DataStruct)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.struct_token.span);
v.visit_fields_mut(&mut node.fields);
if let Some(it) = &mut node.semi_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "derive")]
pub fn visit_data_union_mut<V>(v: &mut V, node: &mut DataUnion)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.union_token.span);
v.visit_fields_named_mut(&mut node.fields);
}
#[cfg(feature = "derive")]
pub fn visit_derive_input_mut<V>(v: &mut V, node: &mut DeriveInput)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
v.visit_data_mut(&mut node.data);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_mut<V>(v: &mut V, node: &mut Expr)
where
V: VisitMut + ?Sized,
{
match node {
Expr::Array(_binding_0) => {
full!(v.visit_expr_array_mut(_binding_0));
}
Expr::Assign(_binding_0) => {
full!(v.visit_expr_assign_mut(_binding_0));
}
Expr::AssignOp(_binding_0) => {
full!(v.visit_expr_assign_op_mut(_binding_0));
}
Expr::Async(_binding_0) => {
full!(v.visit_expr_async_mut(_binding_0));
}
Expr::Await(_binding_0) => {
full!(v.visit_expr_await_mut(_binding_0));
}
Expr::Binary(_binding_0) => {
v.visit_expr_binary_mut(_binding_0);
}
Expr::Block(_binding_0) => {
full!(v.visit_expr_block_mut(_binding_0));
}
Expr::Box(_binding_0) => {
full!(v.visit_expr_box_mut(_binding_0));
}
Expr::Break(_binding_0) => {
full!(v.visit_expr_break_mut(_binding_0));
}
Expr::Call(_binding_0) => {
v.visit_expr_call_mut(_binding_0);
}
Expr::Cast(_binding_0) => {
v.visit_expr_cast_mut(_binding_0);
}
Expr::Closure(_binding_0) => {
full!(v.visit_expr_closure_mut(_binding_0));
}
Expr::Continue(_binding_0) => {
full!(v.visit_expr_continue_mut(_binding_0));
}
Expr::Field(_binding_0) => {
v.visit_expr_field_mut(_binding_0);
}
Expr::ForLoop(_binding_0) => {
full!(v.visit_expr_for_loop_mut(_binding_0));
}
Expr::Group(_binding_0) => {
full!(v.visit_expr_group_mut(_binding_0));
}
Expr::If(_binding_0) => {
full!(v.visit_expr_if_mut(_binding_0));
}
Expr::Index(_binding_0) => {
v.visit_expr_index_mut(_binding_0);
}
Expr::Let(_binding_0) => {
full!(v.visit_expr_let_mut(_binding_0));
}
Expr::Lit(_binding_0) => {
v.visit_expr_lit_mut(_binding_0);
}
Expr::Loop(_binding_0) => {
full!(v.visit_expr_loop_mut(_binding_0));
}
Expr::Macro(_binding_0) => {
full!(v.visit_expr_macro_mut(_binding_0));
}
Expr::Match(_binding_0) => {
full!(v.visit_expr_match_mut(_binding_0));
}
Expr::MethodCall(_binding_0) => {
full!(v.visit_expr_method_call_mut(_binding_0));
}
Expr::Paren(_binding_0) => {
v.visit_expr_paren_mut(_binding_0);
}
Expr::Path(_binding_0) => {
v.visit_expr_path_mut(_binding_0);
}
Expr::Range(_binding_0) => {
full!(v.visit_expr_range_mut(_binding_0));
}
Expr::Reference(_binding_0) => {
full!(v.visit_expr_reference_mut(_binding_0));
}
Expr::Repeat(_binding_0) => {
full!(v.visit_expr_repeat_mut(_binding_0));
}
Expr::Return(_binding_0) => {
full!(v.visit_expr_return_mut(_binding_0));
}
Expr::Struct(_binding_0) => {
full!(v.visit_expr_struct_mut(_binding_0));
}
Expr::Try(_binding_0) => {
full!(v.visit_expr_try_mut(_binding_0));
}
Expr::TryBlock(_binding_0) => {
full!(v.visit_expr_try_block_mut(_binding_0));
}
Expr::Tuple(_binding_0) => {
full!(v.visit_expr_tuple_mut(_binding_0));
}
Expr::Type(_binding_0) => {
full!(v.visit_expr_type_mut(_binding_0));
}
Expr::Unary(_binding_0) => {
v.visit_expr_unary_mut(_binding_0);
}
Expr::Unsafe(_binding_0) => {
full!(v.visit_expr_unsafe_mut(_binding_0));
}
Expr::Verbatim(_binding_0) => {
skip!(_binding_0);
}
Expr::While(_binding_0) => {
full!(v.visit_expr_while_mut(_binding_0));
}
Expr::Yield(_binding_0) => {
full!(v.visit_expr_yield_mut(_binding_0));
}
_ => unreachable!(),
}
}
#[cfg(feature = "full")]
pub fn visit_expr_array_mut<V>(v: &mut V, node: &mut ExprArray)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.bracket_token.span);
for el in Punctuated::pairs_mut(&mut node.elems) {
let (it, p) = el.into_tuple();
v.visit_expr_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_expr_assign_mut<V>(v: &mut V, node: &mut ExprAssign)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.left);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_expr_mut(&mut *node.right);
}
#[cfg(feature = "full")]
pub fn visit_expr_assign_op_mut<V>(v: &mut V, node: &mut ExprAssignOp)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.left);
v.visit_bin_op_mut(&mut node.op);
v.visit_expr_mut(&mut *node.right);
}
#[cfg(feature = "full")]
pub fn visit_expr_async_mut<V>(v: &mut V, node: &mut ExprAsync)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.async_token.span);
if let Some(it) = &mut node.capture {
tokens_helper(v, &mut it.span)
};
v.visit_block_mut(&mut node.block);
}
#[cfg(feature = "full")]
pub fn visit_expr_await_mut<V>(v: &mut V, node: &mut ExprAwait)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.base);
tokens_helper(v, &mut node.dot_token.spans);
tokens_helper(v, &mut node.await_token.span);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_binary_mut<V>(v: &mut V, node: &mut ExprBinary)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.left);
v.visit_bin_op_mut(&mut node.op);
v.visit_expr_mut(&mut *node.right);
}
#[cfg(feature = "full")]
pub fn visit_expr_block_mut<V>(v: &mut V, node: &mut ExprBlock)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.label {
v.visit_label_mut(it)
};
v.visit_block_mut(&mut node.block);
}
#[cfg(feature = "full")]
pub fn visit_expr_box_mut<V>(v: &mut V, node: &mut ExprBox)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.box_token.span);
v.visit_expr_mut(&mut *node.expr);
}
#[cfg(feature = "full")]
pub fn visit_expr_break_mut<V>(v: &mut V, node: &mut ExprBreak)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.break_token.span);
if let Some(it) = &mut node.label {
v.visit_lifetime_mut(it)
};
if let Some(it) = &mut node.expr {
v.visit_expr_mut(&mut **it)
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_call_mut<V>(v: &mut V, node: &mut ExprCall)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.func);
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.args) {
let (it, p) = el.into_tuple();
v.visit_expr_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_cast_mut<V>(v: &mut V, node: &mut ExprCast)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.as_token.span);
v.visit_type_mut(&mut *node.ty);
}
#[cfg(feature = "full")]
pub fn visit_expr_closure_mut<V>(v: &mut V, node: &mut ExprClosure)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.asyncness {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.movability {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.capture {
tokens_helper(v, &mut it.span)
};
tokens_helper(v, &mut node.or1_token.spans);
for el in Punctuated::pairs_mut(&mut node.inputs) {
let (it, p) = el.into_tuple();
v.visit_pat_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
tokens_helper(v, &mut node.or2_token.spans);
v.visit_return_type_mut(&mut node.output);
v.visit_expr_mut(&mut *node.body);
}
#[cfg(feature = "full")]
pub fn visit_expr_continue_mut<V>(v: &mut V, node: &mut ExprContinue)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.continue_token.span);
if let Some(it) = &mut node.label {
v.visit_lifetime_mut(it)
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_field_mut<V>(v: &mut V, node: &mut ExprField)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.base);
tokens_helper(v, &mut node.dot_token.spans);
v.visit_member_mut(&mut node.member);
}
#[cfg(feature = "full")]
pub fn visit_expr_for_loop_mut<V>(v: &mut V, node: &mut ExprForLoop)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.label {
v.visit_label_mut(it)
};
tokens_helper(v, &mut node.for_token.span);
v.visit_pat_mut(&mut node.pat);
tokens_helper(v, &mut node.in_token.span);
v.visit_expr_mut(&mut *node.expr);
v.visit_block_mut(&mut node.body);
}
#[cfg(feature = "full")]
pub fn visit_expr_group_mut<V>(v: &mut V, node: &mut ExprGroup)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.group_token.span);
v.visit_expr_mut(&mut *node.expr);
}
#[cfg(feature = "full")]
pub fn visit_expr_if_mut<V>(v: &mut V, node: &mut ExprIf)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.if_token.span);
v.visit_expr_mut(&mut *node.cond);
v.visit_block_mut(&mut node.then_branch);
if let Some(it) = &mut node.else_branch {
tokens_helper(v, &mut (it).0.span);
v.visit_expr_mut(&mut *(it).1);
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_index_mut<V>(v: &mut V, node: &mut ExprIndex)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.bracket_token.span);
v.visit_expr_mut(&mut *node.index);
}
#[cfg(feature = "full")]
pub fn visit_expr_let_mut<V>(v: &mut V, node: &mut ExprLet)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.let_token.span);
v.visit_pat_mut(&mut node.pat);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_expr_mut(&mut *node.expr);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_lit_mut<V>(v: &mut V, node: &mut ExprLit)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_lit_mut(&mut node.lit);
}
#[cfg(feature = "full")]
pub fn visit_expr_loop_mut<V>(v: &mut V, node: &mut ExprLoop)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.label {
v.visit_label_mut(it)
};
tokens_helper(v, &mut node.loop_token.span);
v.visit_block_mut(&mut node.body);
}
#[cfg(feature = "full")]
pub fn visit_expr_macro_mut<V>(v: &mut V, node: &mut ExprMacro)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_macro_mut(&mut node.mac);
}
#[cfg(feature = "full")]
pub fn visit_expr_match_mut<V>(v: &mut V, node: &mut ExprMatch)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.match_token.span);
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.brace_token.span);
for it in &mut node.arms {
v.visit_arm_mut(it)
}
}
#[cfg(feature = "full")]
pub fn visit_expr_method_call_mut<V>(v: &mut V, node: &mut ExprMethodCall)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.receiver);
tokens_helper(v, &mut node.dot_token.spans);
v.visit_ident_mut(&mut node.method);
if let Some(it) = &mut node.turbofish {
v.visit_method_turbofish_mut(it)
};
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.args) {
let (it, p) = el.into_tuple();
v.visit_expr_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_paren_mut<V>(v: &mut V, node: &mut ExprParen)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.paren_token.span);
v.visit_expr_mut(&mut *node.expr);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_path_mut<V>(v: &mut V, node: &mut ExprPath)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.qself {
v.visit_qself_mut(it)
};
v.visit_path_mut(&mut node.path);
}
#[cfg(feature = "full")]
pub fn visit_expr_range_mut<V>(v: &mut V, node: &mut ExprRange)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.from {
v.visit_expr_mut(&mut **it)
};
v.visit_range_limits_mut(&mut node.limits);
if let Some(it) = &mut node.to {
v.visit_expr_mut(&mut **it)
};
}
#[cfg(feature = "full")]
pub fn visit_expr_reference_mut<V>(v: &mut V, node: &mut ExprReference)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.and_token.spans);
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
v.visit_expr_mut(&mut *node.expr);
}
#[cfg(feature = "full")]
pub fn visit_expr_repeat_mut<V>(v: &mut V, node: &mut ExprRepeat)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.bracket_token.span);
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.semi_token.spans);
v.visit_expr_mut(&mut *node.len);
}
#[cfg(feature = "full")]
pub fn visit_expr_return_mut<V>(v: &mut V, node: &mut ExprReturn)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.return_token.span);
if let Some(it) = &mut node.expr {
v.visit_expr_mut(&mut **it)
};
}
#[cfg(feature = "full")]
pub fn visit_expr_struct_mut<V>(v: &mut V, node: &mut ExprStruct)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_path_mut(&mut node.path);
tokens_helper(v, &mut node.brace_token.span);
for el in Punctuated::pairs_mut(&mut node.fields) {
let (it, p) = el.into_tuple();
v.visit_field_value_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
if let Some(it) = &mut node.dot2_token {
tokens_helper(v, &mut it.spans)
};
if let Some(it) = &mut node.rest {
v.visit_expr_mut(&mut **it)
};
}
#[cfg(feature = "full")]
pub fn visit_expr_try_mut<V>(v: &mut V, node: &mut ExprTry)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.question_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_expr_try_block_mut<V>(v: &mut V, node: &mut ExprTryBlock)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.try_token.span);
v.visit_block_mut(&mut node.block);
}
#[cfg(feature = "full")]
pub fn visit_expr_tuple_mut<V>(v: &mut V, node: &mut ExprTuple)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.elems) {
let (it, p) = el.into_tuple();
v.visit_expr_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_expr_type_mut<V>(v: &mut V, node: &mut ExprType)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut *node.ty);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_expr_unary_mut<V>(v: &mut V, node: &mut ExprUnary)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_un_op_mut(&mut node.op);
v.visit_expr_mut(&mut *node.expr);
}
#[cfg(feature = "full")]
pub fn visit_expr_unsafe_mut<V>(v: &mut V, node: &mut ExprUnsafe)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.unsafe_token.span);
v.visit_block_mut(&mut node.block);
}
#[cfg(feature = "full")]
pub fn visit_expr_while_mut<V>(v: &mut V, node: &mut ExprWhile)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.label {
v.visit_label_mut(it)
};
tokens_helper(v, &mut node.while_token.span);
v.visit_expr_mut(&mut *node.cond);
v.visit_block_mut(&mut node.body);
}
#[cfg(feature = "full")]
pub fn visit_expr_yield_mut<V>(v: &mut V, node: &mut ExprYield)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.yield_token.span);
if let Some(it) = &mut node.expr {
v.visit_expr_mut(&mut **it)
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_field_mut<V>(v: &mut V, node: &mut Field)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
if let Some(it) = &mut node.ident {
v.visit_ident_mut(it)
};
if let Some(it) = &mut node.colon_token {
tokens_helper(v, &mut it.spans)
};
v.visit_type_mut(&mut node.ty);
}
#[cfg(feature = "full")]
pub fn visit_field_pat_mut<V>(v: &mut V, node: &mut FieldPat)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_member_mut(&mut node.member);
if let Some(it) = &mut node.colon_token {
tokens_helper(v, &mut it.spans)
};
v.visit_pat_mut(&mut *node.pat);
}
#[cfg(feature = "full")]
pub fn visit_field_value_mut<V>(v: &mut V, node: &mut FieldValue)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_member_mut(&mut node.member);
if let Some(it) = &mut node.colon_token {
tokens_helper(v, &mut it.spans)
};
v.visit_expr_mut(&mut node.expr);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_fields_mut<V>(v: &mut V, node: &mut Fields)
where
V: VisitMut + ?Sized,
{
match node {
Fields::Named(_binding_0) => {
v.visit_fields_named_mut(_binding_0);
}
Fields::Unnamed(_binding_0) => {
v.visit_fields_unnamed_mut(_binding_0);
}
Fields::Unit => {}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_fields_named_mut<V>(v: &mut V, node: &mut FieldsNamed)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.brace_token.span);
for el in Punctuated::pairs_mut(&mut node.named) {
let (it, p) = el.into_tuple();
v.visit_field_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_fields_unnamed_mut<V>(v: &mut V, node: &mut FieldsUnnamed)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.unnamed) {
let (it, p) = el.into_tuple();
v.visit_field_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_file_mut<V>(v: &mut V, node: &mut File)
where
V: VisitMut + ?Sized,
{
skip!(node.shebang);
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
for it in &mut node.items {
v.visit_item_mut(it)
}
}
#[cfg(feature = "full")]
pub fn visit_fn_arg_mut<V>(v: &mut V, node: &mut FnArg)
where
V: VisitMut + ?Sized,
{
match node {
FnArg::Receiver(_binding_0) => {
v.visit_receiver_mut(_binding_0);
}
FnArg::Typed(_binding_0) => {
v.visit_pat_type_mut(_binding_0);
}
}
}
#[cfg(feature = "full")]
pub fn visit_foreign_item_mut<V>(v: &mut V, node: &mut ForeignItem)
where
V: VisitMut + ?Sized,
{
match node {
ForeignItem::Fn(_binding_0) => {
v.visit_foreign_item_fn_mut(_binding_0);
}
ForeignItem::Static(_binding_0) => {
v.visit_foreign_item_static_mut(_binding_0);
}
ForeignItem::Type(_binding_0) => {
v.visit_foreign_item_type_mut(_binding_0);
}
ForeignItem::Macro(_binding_0) => {
v.visit_foreign_item_macro_mut(_binding_0);
}
ForeignItem::Verbatim(_binding_0) => {
skip!(_binding_0);
}
_ => unreachable!(),
}
}
#[cfg(feature = "full")]
pub fn visit_foreign_item_fn_mut<V>(v: &mut V, node: &mut ForeignItemFn)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
v.visit_signature_mut(&mut node.sig);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_foreign_item_macro_mut<V>(v: &mut V, node: &mut ForeignItemMacro)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_macro_mut(&mut node.mac);
if let Some(it) = &mut node.semi_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_foreign_item_static_mut<V>(v: &mut V, node: &mut ForeignItemStatic)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.static_token.span);
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut *node.ty);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_foreign_item_type_mut<V>(v: &mut V, node: &mut ForeignItemType)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.type_token.span);
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_generic_argument_mut<V>(v: &mut V, node: &mut GenericArgument)
where
V: VisitMut + ?Sized,
{
match node {
GenericArgument::Lifetime(_binding_0) => {
v.visit_lifetime_mut(_binding_0);
}
GenericArgument::Type(_binding_0) => {
v.visit_type_mut(_binding_0);
}
GenericArgument::Binding(_binding_0) => {
v.visit_binding_mut(_binding_0);
}
GenericArgument::Constraint(_binding_0) => {
v.visit_constraint_mut(_binding_0);
}
GenericArgument::Const(_binding_0) => {
v.visit_expr_mut(_binding_0);
}
}
}
#[cfg(feature = "full")]
pub fn visit_generic_method_argument_mut<V>(v: &mut V, node: &mut GenericMethodArgument)
where
V: VisitMut + ?Sized,
{
match node {
GenericMethodArgument::Type(_binding_0) => {
v.visit_type_mut(_binding_0);
}
GenericMethodArgument::Const(_binding_0) => {
v.visit_expr_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_generic_param_mut<V>(v: &mut V, node: &mut GenericParam)
where
V: VisitMut + ?Sized,
{
match node {
GenericParam::Type(_binding_0) => {
v.visit_type_param_mut(_binding_0);
}
GenericParam::Lifetime(_binding_0) => {
v.visit_lifetime_def_mut(_binding_0);
}
GenericParam::Const(_binding_0) => {
v.visit_const_param_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_generics_mut<V>(v: &mut V, node: &mut Generics)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.lt_token {
tokens_helper(v, &mut it.spans)
};
for el in Punctuated::pairs_mut(&mut node.params) {
let (it, p) = el.into_tuple();
v.visit_generic_param_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
if let Some(it) = &mut node.gt_token {
tokens_helper(v, &mut it.spans)
};
if let Some(it) = &mut node.where_clause {
v.visit_where_clause_mut(it)
};
}
pub fn visit_ident_mut<V>(v: &mut V, node: &mut Ident)
where
V: VisitMut + ?Sized,
{
let mut span = node.span();
v.visit_span_mut(&mut span);
node.set_span(span);
}
#[cfg(feature = "full")]
pub fn visit_impl_item_mut<V>(v: &mut V, node: &mut ImplItem)
where
V: VisitMut + ?Sized,
{
match node {
ImplItem::Const(_binding_0) => {
v.visit_impl_item_const_mut(_binding_0);
}
ImplItem::Method(_binding_0) => {
v.visit_impl_item_method_mut(_binding_0);
}
ImplItem::Type(_binding_0) => {
v.visit_impl_item_type_mut(_binding_0);
}
ImplItem::Macro(_binding_0) => {
v.visit_impl_item_macro_mut(_binding_0);
}
ImplItem::Verbatim(_binding_0) => {
skip!(_binding_0);
}
_ => unreachable!(),
}
}
#[cfg(feature = "full")]
pub fn visit_impl_item_const_mut<V>(v: &mut V, node: &mut ImplItemConst)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
if let Some(it) = &mut node.defaultness {
tokens_helper(v, &mut it.span)
};
tokens_helper(v, &mut node.const_token.span);
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut node.ty);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_expr_mut(&mut node.expr);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_impl_item_macro_mut<V>(v: &mut V, node: &mut ImplItemMacro)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_macro_mut(&mut node.mac);
if let Some(it) = &mut node.semi_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_impl_item_method_mut<V>(v: &mut V, node: &mut ImplItemMethod)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
if let Some(it) = &mut node.defaultness {
tokens_helper(v, &mut it.span)
};
v.visit_signature_mut(&mut node.sig);
v.visit_block_mut(&mut node.block);
}
#[cfg(feature = "full")]
pub fn visit_impl_item_type_mut<V>(v: &mut V, node: &mut ImplItemType)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
if let Some(it) = &mut node.defaultness {
tokens_helper(v, &mut it.span)
};
tokens_helper(v, &mut node.type_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_type_mut(&mut node.ty);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_index_mut<V>(v: &mut V, node: &mut Index)
where
V: VisitMut + ?Sized,
{
skip!(node.index);
v.visit_span_mut(&mut node.span);
}
#[cfg(feature = "full")]
pub fn visit_item_mut<V>(v: &mut V, node: &mut Item)
where
V: VisitMut + ?Sized,
{
match node {
Item::Const(_binding_0) => {
v.visit_item_const_mut(_binding_0);
}
Item::Enum(_binding_0) => {
v.visit_item_enum_mut(_binding_0);
}
Item::ExternCrate(_binding_0) => {
v.visit_item_extern_crate_mut(_binding_0);
}
Item::Fn(_binding_0) => {
v.visit_item_fn_mut(_binding_0);
}
Item::ForeignMod(_binding_0) => {
v.visit_item_foreign_mod_mut(_binding_0);
}
Item::Impl(_binding_0) => {
v.visit_item_impl_mut(_binding_0);
}
Item::Macro(_binding_0) => {
v.visit_item_macro_mut(_binding_0);
}
Item::Macro2(_binding_0) => {
v.visit_item_macro2_mut(_binding_0);
}
Item::Mod(_binding_0) => {
v.visit_item_mod_mut(_binding_0);
}
Item::Static(_binding_0) => {
v.visit_item_static_mut(_binding_0);
}
Item::Struct(_binding_0) => {
v.visit_item_struct_mut(_binding_0);
}
Item::Trait(_binding_0) => {
v.visit_item_trait_mut(_binding_0);
}
Item::TraitAlias(_binding_0) => {
v.visit_item_trait_alias_mut(_binding_0);
}
Item::Type(_binding_0) => {
v.visit_item_type_mut(_binding_0);
}
Item::Union(_binding_0) => {
v.visit_item_union_mut(_binding_0);
}
Item::Use(_binding_0) => {
v.visit_item_use_mut(_binding_0);
}
Item::Verbatim(_binding_0) => {
skip!(_binding_0);
}
_ => unreachable!(),
}
}
#[cfg(feature = "full")]
pub fn visit_item_const_mut<V>(v: &mut V, node: &mut ItemConst)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.const_token.span);
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut *node.ty);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_item_enum_mut<V>(v: &mut V, node: &mut ItemEnum)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.enum_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
tokens_helper(v, &mut node.brace_token.span);
for el in Punctuated::pairs_mut(&mut node.variants) {
let (it, p) = el.into_tuple();
v.visit_variant_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_item_extern_crate_mut<V>(v: &mut V, node: &mut ItemExternCrate)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.extern_token.span);
tokens_helper(v, &mut node.crate_token.span);
v.visit_ident_mut(&mut node.ident);
if let Some(it) = &mut node.rename {
tokens_helper(v, &mut (it).0.span);
v.visit_ident_mut(&mut (it).1);
};
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_item_fn_mut<V>(v: &mut V, node: &mut ItemFn)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
v.visit_signature_mut(&mut node.sig);
v.visit_block_mut(&mut *node.block);
}
#[cfg(feature = "full")]
pub fn visit_item_foreign_mod_mut<V>(v: &mut V, node: &mut ItemForeignMod)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_abi_mut(&mut node.abi);
tokens_helper(v, &mut node.brace_token.span);
for it in &mut node.items {
v.visit_foreign_item_mut(it)
}
}
#[cfg(feature = "full")]
pub fn visit_item_impl_mut<V>(v: &mut V, node: &mut ItemImpl)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.defaultness {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.unsafety {
tokens_helper(v, &mut it.span)
};
tokens_helper(v, &mut node.impl_token.span);
v.visit_generics_mut(&mut node.generics);
if let Some(it) = &mut node.trait_ {
if let Some(it) = &mut (it).0 {
tokens_helper(v, &mut it.spans)
};
v.visit_path_mut(&mut (it).1);
tokens_helper(v, &mut (it).2.span);
};
v.visit_type_mut(&mut *node.self_ty);
tokens_helper(v, &mut node.brace_token.span);
for it in &mut node.items {
v.visit_impl_item_mut(it)
}
}
#[cfg(feature = "full")]
pub fn visit_item_macro_mut<V>(v: &mut V, node: &mut ItemMacro)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.ident {
v.visit_ident_mut(it)
};
v.visit_macro_mut(&mut node.mac);
if let Some(it) = &mut node.semi_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_item_macro2_mut<V>(v: &mut V, node: &mut ItemMacro2)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.macro_token.span);
v.visit_ident_mut(&mut node.ident);
skip!(node.rules);
}
#[cfg(feature = "full")]
pub fn visit_item_mod_mut<V>(v: &mut V, node: &mut ItemMod)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.mod_token.span);
v.visit_ident_mut(&mut node.ident);
if let Some(it) = &mut node.content {
tokens_helper(v, &mut (it).0.span);
for it in &mut (it).1 {
v.visit_item_mut(it)
}
};
if let Some(it) = &mut node.semi {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_item_static_mut<V>(v: &mut V, node: &mut ItemStatic)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.static_token.span);
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut *node.ty);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_expr_mut(&mut *node.expr);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_item_struct_mut<V>(v: &mut V, node: &mut ItemStruct)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.struct_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
v.visit_fields_mut(&mut node.fields);
if let Some(it) = &mut node.semi_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_item_trait_mut<V>(v: &mut V, node: &mut ItemTrait)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
if let Some(it) = &mut node.unsafety {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.auto_token {
tokens_helper(v, &mut it.span)
};
tokens_helper(v, &mut node.trait_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
if let Some(it) = &mut node.colon_token {
tokens_helper(v, &mut it.spans)
};
for el in Punctuated::pairs_mut(&mut node.supertraits) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
tokens_helper(v, &mut node.brace_token.span);
for it in &mut node.items {
v.visit_trait_item_mut(it)
}
}
#[cfg(feature = "full")]
pub fn visit_item_trait_alias_mut<V>(v: &mut V, node: &mut ItemTraitAlias)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.trait_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
tokens_helper(v, &mut node.eq_token.spans);
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_item_type_mut<V>(v: &mut V, node: &mut ItemType)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.type_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_type_mut(&mut *node.ty);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_item_union_mut<V>(v: &mut V, node: &mut ItemUnion)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.union_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
v.visit_fields_named_mut(&mut node.fields);
}
#[cfg(feature = "full")]
pub fn visit_item_use_mut<V>(v: &mut V, node: &mut ItemUse)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_visibility_mut(&mut node.vis);
tokens_helper(v, &mut node.use_token.span);
if let Some(it) = &mut node.leading_colon {
tokens_helper(v, &mut it.spans)
};
v.visit_use_tree_mut(&mut node.tree);
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_label_mut<V>(v: &mut V, node: &mut Label)
where
V: VisitMut + ?Sized,
{
v.visit_lifetime_mut(&mut node.name);
tokens_helper(v, &mut node.colon_token.spans);
}
pub fn visit_lifetime_mut<V>(v: &mut V, node: &mut Lifetime)
where
V: VisitMut + ?Sized,
{
v.visit_span_mut(&mut node.apostrophe);
v.visit_ident_mut(&mut node.ident);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lifetime_def_mut<V>(v: &mut V, node: &mut LifetimeDef)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_lifetime_mut(&mut node.lifetime);
if let Some(it) = &mut node.colon_token {
tokens_helper(v, &mut it.spans)
};
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_lifetime_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_mut<V>(v: &mut V, node: &mut Lit)
where
V: VisitMut + ?Sized,
{
match node {
Lit::Str(_binding_0) => {
v.visit_lit_str_mut(_binding_0);
}
Lit::ByteStr(_binding_0) => {
v.visit_lit_byte_str_mut(_binding_0);
}
Lit::Byte(_binding_0) => {
v.visit_lit_byte_mut(_binding_0);
}
Lit::Char(_binding_0) => {
v.visit_lit_char_mut(_binding_0);
}
Lit::Int(_binding_0) => {
v.visit_lit_int_mut(_binding_0);
}
Lit::Float(_binding_0) => {
v.visit_lit_float_mut(_binding_0);
}
Lit::Bool(_binding_0) => {
v.visit_lit_bool_mut(_binding_0);
}
Lit::Verbatim(_binding_0) => {
skip!(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_bool_mut<V>(v: &mut V, node: &mut LitBool)
where
V: VisitMut + ?Sized,
{
skip!(node.value);
v.visit_span_mut(&mut node.span);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_byte_mut<V>(v: &mut V, node: &mut LitByte)
where
V: VisitMut + ?Sized,
{
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_byte_str_mut<V>(v: &mut V, node: &mut LitByteStr)
where
V: VisitMut + ?Sized,
{
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_char_mut<V>(v: &mut V, node: &mut LitChar)
where
V: VisitMut + ?Sized,
{
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_float_mut<V>(v: &mut V, node: &mut LitFloat)
where
V: VisitMut + ?Sized,
{
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_int_mut<V>(v: &mut V, node: &mut LitInt)
where
V: VisitMut + ?Sized,
{
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_lit_str_mut<V>(v: &mut V, node: &mut LitStr)
where
V: VisitMut + ?Sized,
{
}
#[cfg(feature = "full")]
pub fn visit_local_mut<V>(v: &mut V, node: &mut Local)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.let_token.span);
v.visit_pat_mut(&mut node.pat);
if let Some(it) = &mut node.init {
tokens_helper(v, &mut (it).0.spans);
v.visit_expr_mut(&mut *(it).1);
};
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_macro_mut<V>(v: &mut V, node: &mut Macro)
where
V: VisitMut + ?Sized,
{
v.visit_path_mut(&mut node.path);
tokens_helper(v, &mut node.bang_token.spans);
v.visit_macro_delimiter_mut(&mut node.delimiter);
skip!(node.tokens);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_macro_delimiter_mut<V>(v: &mut V, node: &mut MacroDelimiter)
where
V: VisitMut + ?Sized,
{
match node {
MacroDelimiter::Paren(_binding_0) => {
tokens_helper(v, &mut _binding_0.span);
}
MacroDelimiter::Brace(_binding_0) => {
tokens_helper(v, &mut _binding_0.span);
}
MacroDelimiter::Bracket(_binding_0) => {
tokens_helper(v, &mut _binding_0.span);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_member_mut<V>(v: &mut V, node: &mut Member)
where
V: VisitMut + ?Sized,
{
match node {
Member::Named(_binding_0) => {
v.visit_ident_mut(_binding_0);
}
Member::Unnamed(_binding_0) => {
v.visit_index_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_meta_mut<V>(v: &mut V, node: &mut Meta)
where
V: VisitMut + ?Sized,
{
match node {
Meta::Path(_binding_0) => {
v.visit_path_mut(_binding_0);
}
Meta::List(_binding_0) => {
v.visit_meta_list_mut(_binding_0);
}
Meta::NameValue(_binding_0) => {
v.visit_meta_name_value_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_meta_list_mut<V>(v: &mut V, node: &mut MetaList)
where
V: VisitMut + ?Sized,
{
v.visit_path_mut(&mut node.path);
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.nested) {
let (it, p) = el.into_tuple();
v.visit_nested_meta_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_meta_name_value_mut<V>(v: &mut V, node: &mut MetaNameValue)
where
V: VisitMut + ?Sized,
{
v.visit_path_mut(&mut node.path);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_lit_mut(&mut node.lit);
}
#[cfg(feature = "full")]
pub fn visit_method_turbofish_mut<V>(v: &mut V, node: &mut MethodTurbofish)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.colon2_token.spans);
tokens_helper(v, &mut node.lt_token.spans);
for el in Punctuated::pairs_mut(&mut node.args) {
let (it, p) = el.into_tuple();
v.visit_generic_method_argument_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
tokens_helper(v, &mut node.gt_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_nested_meta_mut<V>(v: &mut V, node: &mut NestedMeta)
where
V: VisitMut + ?Sized,
{
match node {
NestedMeta::Meta(_binding_0) => {
v.visit_meta_mut(_binding_0);
}
NestedMeta::Lit(_binding_0) => {
v.visit_lit_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_parenthesized_generic_arguments_mut<V>(
v: &mut V,
node: &mut ParenthesizedGenericArguments,
) where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.inputs) {
let (it, p) = el.into_tuple();
v.visit_type_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
v.visit_return_type_mut(&mut node.output);
}
#[cfg(feature = "full")]
pub fn visit_pat_mut<V>(v: &mut V, node: &mut Pat)
where
V: VisitMut + ?Sized,
{
match node {
Pat::Box(_binding_0) => {
v.visit_pat_box_mut(_binding_0);
}
Pat::Ident(_binding_0) => {
v.visit_pat_ident_mut(_binding_0);
}
Pat::Lit(_binding_0) => {
v.visit_pat_lit_mut(_binding_0);
}
Pat::Macro(_binding_0) => {
v.visit_pat_macro_mut(_binding_0);
}
Pat::Or(_binding_0) => {
v.visit_pat_or_mut(_binding_0);
}
Pat::Path(_binding_0) => {
v.visit_pat_path_mut(_binding_0);
}
Pat::Range(_binding_0) => {
v.visit_pat_range_mut(_binding_0);
}
Pat::Reference(_binding_0) => {
v.visit_pat_reference_mut(_binding_0);
}
Pat::Rest(_binding_0) => {
v.visit_pat_rest_mut(_binding_0);
}
Pat::Slice(_binding_0) => {
v.visit_pat_slice_mut(_binding_0);
}
Pat::Struct(_binding_0) => {
v.visit_pat_struct_mut(_binding_0);
}
Pat::Tuple(_binding_0) => {
v.visit_pat_tuple_mut(_binding_0);
}
Pat::TupleStruct(_binding_0) => {
v.visit_pat_tuple_struct_mut(_binding_0);
}
Pat::Type(_binding_0) => {
v.visit_pat_type_mut(_binding_0);
}
Pat::Verbatim(_binding_0) => {
skip!(_binding_0);
}
Pat::Wild(_binding_0) => {
v.visit_pat_wild_mut(_binding_0);
}
_ => unreachable!(),
}
}
#[cfg(feature = "full")]
pub fn visit_pat_box_mut<V>(v: &mut V, node: &mut PatBox)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.box_token.span);
v.visit_pat_mut(&mut *node.pat);
}
#[cfg(feature = "full")]
pub fn visit_pat_ident_mut<V>(v: &mut V, node: &mut PatIdent)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.by_ref {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
v.visit_ident_mut(&mut node.ident);
if let Some(it) = &mut node.subpat {
tokens_helper(v, &mut (it).0.spans);
v.visit_pat_mut(&mut *(it).1);
};
}
#[cfg(feature = "full")]
pub fn visit_pat_lit_mut<V>(v: &mut V, node: &mut PatLit)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.expr);
}
#[cfg(feature = "full")]
pub fn visit_pat_macro_mut<V>(v: &mut V, node: &mut PatMacro)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_macro_mut(&mut node.mac);
}
#[cfg(feature = "full")]
pub fn visit_pat_or_mut<V>(v: &mut V, node: &mut PatOr)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.leading_vert {
tokens_helper(v, &mut it.spans)
};
for el in Punctuated::pairs_mut(&mut node.cases) {
let (it, p) = el.into_tuple();
v.visit_pat_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_pat_path_mut<V>(v: &mut V, node: &mut PatPath)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.qself {
v.visit_qself_mut(it)
};
v.visit_path_mut(&mut node.path);
}
#[cfg(feature = "full")]
pub fn visit_pat_range_mut<V>(v: &mut V, node: &mut PatRange)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_expr_mut(&mut *node.lo);
v.visit_range_limits_mut(&mut node.limits);
v.visit_expr_mut(&mut *node.hi);
}
#[cfg(feature = "full")]
pub fn visit_pat_reference_mut<V>(v: &mut V, node: &mut PatReference)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.and_token.spans);
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
v.visit_pat_mut(&mut *node.pat);
}
#[cfg(feature = "full")]
pub fn visit_pat_rest_mut<V>(v: &mut V, node: &mut PatRest)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.dot2_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_pat_slice_mut<V>(v: &mut V, node: &mut PatSlice)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.bracket_token.span);
for el in Punctuated::pairs_mut(&mut node.elems) {
let (it, p) = el.into_tuple();
v.visit_pat_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_pat_struct_mut<V>(v: &mut V, node: &mut PatStruct)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_path_mut(&mut node.path);
tokens_helper(v, &mut node.brace_token.span);
for el in Punctuated::pairs_mut(&mut node.fields) {
let (it, p) = el.into_tuple();
v.visit_field_pat_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
if let Some(it) = &mut node.dot2_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_pat_tuple_mut<V>(v: &mut V, node: &mut PatTuple)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.elems) {
let (it, p) = el.into_tuple();
v.visit_pat_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_pat_tuple_struct_mut<V>(v: &mut V, node: &mut PatTupleStruct)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_path_mut(&mut node.path);
v.visit_pat_tuple_mut(&mut node.pat);
}
#[cfg(feature = "full")]
pub fn visit_pat_type_mut<V>(v: &mut V, node: &mut PatType)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_pat_mut(&mut *node.pat);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut *node.ty);
}
#[cfg(feature = "full")]
pub fn visit_pat_wild_mut<V>(v: &mut V, node: &mut PatWild)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.underscore_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_path_mut<V>(v: &mut V, node: &mut Path)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.leading_colon {
tokens_helper(v, &mut it.spans)
};
for el in Punctuated::pairs_mut(&mut node.segments) {
let (it, p) = el.into_tuple();
v.visit_path_segment_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_path_arguments_mut<V>(v: &mut V, node: &mut PathArguments)
where
V: VisitMut + ?Sized,
{
match node {
PathArguments::None => {}
PathArguments::AngleBracketed(_binding_0) => {
v.visit_angle_bracketed_generic_arguments_mut(_binding_0);
}
PathArguments::Parenthesized(_binding_0) => {
v.visit_parenthesized_generic_arguments_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_path_segment_mut<V>(v: &mut V, node: &mut PathSegment)
where
V: VisitMut + ?Sized,
{
v.visit_ident_mut(&mut node.ident);
v.visit_path_arguments_mut(&mut node.arguments);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_predicate_eq_mut<V>(v: &mut V, node: &mut PredicateEq)
where
V: VisitMut + ?Sized,
{
v.visit_type_mut(&mut node.lhs_ty);
tokens_helper(v, &mut node.eq_token.spans);
v.visit_type_mut(&mut node.rhs_ty);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_predicate_lifetime_mut<V>(v: &mut V, node: &mut PredicateLifetime)
where
V: VisitMut + ?Sized,
{
v.visit_lifetime_mut(&mut node.lifetime);
tokens_helper(v, &mut node.colon_token.spans);
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_lifetime_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_predicate_type_mut<V>(v: &mut V, node: &mut PredicateType)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.lifetimes {
v.visit_bound_lifetimes_mut(it)
};
v.visit_type_mut(&mut node.bounded_ty);
tokens_helper(v, &mut node.colon_token.spans);
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_qself_mut<V>(v: &mut V, node: &mut QSelf)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.lt_token.spans);
v.visit_type_mut(&mut *node.ty);
skip!(node.position);
if let Some(it) = &mut node.as_token {
tokens_helper(v, &mut it.span)
};
tokens_helper(v, &mut node.gt_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_range_limits_mut<V>(v: &mut V, node: &mut RangeLimits)
where
V: VisitMut + ?Sized,
{
match node {
RangeLimits::HalfOpen(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
RangeLimits::Closed(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_receiver_mut<V>(v: &mut V, node: &mut Receiver)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
if let Some(it) = &mut node.reference {
tokens_helper(v, &mut (it).0.spans);
if let Some(it) = &mut (it).1 {
v.visit_lifetime_mut(it)
};
};
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
tokens_helper(v, &mut node.self_token.span);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_return_type_mut<V>(v: &mut V, node: &mut ReturnType)
where
V: VisitMut + ?Sized,
{
match node {
ReturnType::Default => {}
ReturnType::Type(_binding_0, _binding_1) => {
tokens_helper(v, &mut _binding_0.spans);
v.visit_type_mut(&mut **_binding_1);
}
}
}
#[cfg(feature = "full")]
pub fn visit_signature_mut<V>(v: &mut V, node: &mut Signature)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.constness {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.asyncness {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.unsafety {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.abi {
v.visit_abi_mut(it)
};
tokens_helper(v, &mut node.fn_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.inputs) {
let (it, p) = el.into_tuple();
v.visit_fn_arg_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
if let Some(it) = &mut node.variadic {
v.visit_variadic_mut(it)
};
v.visit_return_type_mut(&mut node.output);
}
pub fn visit_span_mut<V>(v: &mut V, node: &mut Span)
where
V: VisitMut + ?Sized,
{
}
#[cfg(feature = "full")]
pub fn visit_stmt_mut<V>(v: &mut V, node: &mut Stmt)
where
V: VisitMut + ?Sized,
{
match node {
Stmt::Local(_binding_0) => {
v.visit_local_mut(_binding_0);
}
Stmt::Item(_binding_0) => {
v.visit_item_mut(_binding_0);
}
Stmt::Expr(_binding_0) => {
v.visit_expr_mut(_binding_0);
}
Stmt::Semi(_binding_0, _binding_1) => {
v.visit_expr_mut(_binding_0);
tokens_helper(v, &mut _binding_1.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_trait_bound_mut<V>(v: &mut V, node: &mut TraitBound)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.paren_token {
tokens_helper(v, &mut it.span)
};
v.visit_trait_bound_modifier_mut(&mut node.modifier);
if let Some(it) = &mut node.lifetimes {
v.visit_bound_lifetimes_mut(it)
};
v.visit_path_mut(&mut node.path);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_trait_bound_modifier_mut<V>(v: &mut V, node: &mut TraitBoundModifier)
where
V: VisitMut + ?Sized,
{
match node {
TraitBoundModifier::None => {}
TraitBoundModifier::Maybe(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_trait_item_mut<V>(v: &mut V, node: &mut TraitItem)
where
V: VisitMut + ?Sized,
{
match node {
TraitItem::Const(_binding_0) => {
v.visit_trait_item_const_mut(_binding_0);
}
TraitItem::Method(_binding_0) => {
v.visit_trait_item_method_mut(_binding_0);
}
TraitItem::Type(_binding_0) => {
v.visit_trait_item_type_mut(_binding_0);
}
TraitItem::Macro(_binding_0) => {
v.visit_trait_item_macro_mut(_binding_0);
}
TraitItem::Verbatim(_binding_0) => {
skip!(_binding_0);
}
_ => unreachable!(),
}
}
#[cfg(feature = "full")]
pub fn visit_trait_item_const_mut<V>(v: &mut V, node: &mut TraitItemConst)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.const_token.span);
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon_token.spans);
v.visit_type_mut(&mut node.ty);
if let Some(it) = &mut node.default {
tokens_helper(v, &mut (it).0.spans);
v.visit_expr_mut(&mut (it).1);
};
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_trait_item_macro_mut<V>(v: &mut V, node: &mut TraitItemMacro)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_macro_mut(&mut node.mac);
if let Some(it) = &mut node.semi_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_trait_item_method_mut<V>(v: &mut V, node: &mut TraitItemMethod)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_signature_mut(&mut node.sig);
if let Some(it) = &mut node.default {
v.visit_block_mut(it)
};
if let Some(it) = &mut node.semi_token {
tokens_helper(v, &mut it.spans)
};
}
#[cfg(feature = "full")]
pub fn visit_trait_item_type_mut<V>(v: &mut V, node: &mut TraitItemType)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.type_token.span);
v.visit_ident_mut(&mut node.ident);
v.visit_generics_mut(&mut node.generics);
if let Some(it) = &mut node.colon_token {
tokens_helper(v, &mut it.spans)
};
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
if let Some(it) = &mut node.default {
tokens_helper(v, &mut (it).0.spans);
v.visit_type_mut(&mut (it).1);
};
tokens_helper(v, &mut node.semi_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_mut<V>(v: &mut V, node: &mut Type)
where
V: VisitMut + ?Sized,
{
match node {
Type::Array(_binding_0) => {
v.visit_type_array_mut(_binding_0);
}
Type::BareFn(_binding_0) => {
v.visit_type_bare_fn_mut(_binding_0);
}
Type::Group(_binding_0) => {
v.visit_type_group_mut(_binding_0);
}
Type::ImplTrait(_binding_0) => {
v.visit_type_impl_trait_mut(_binding_0);
}
Type::Infer(_binding_0) => {
v.visit_type_infer_mut(_binding_0);
}
Type::Macro(_binding_0) => {
v.visit_type_macro_mut(_binding_0);
}
Type::Never(_binding_0) => {
v.visit_type_never_mut(_binding_0);
}
Type::Paren(_binding_0) => {
v.visit_type_paren_mut(_binding_0);
}
Type::Path(_binding_0) => {
v.visit_type_path_mut(_binding_0);
}
Type::Ptr(_binding_0) => {
v.visit_type_ptr_mut(_binding_0);
}
Type::Reference(_binding_0) => {
v.visit_type_reference_mut(_binding_0);
}
Type::Slice(_binding_0) => {
v.visit_type_slice_mut(_binding_0);
}
Type::TraitObject(_binding_0) => {
v.visit_type_trait_object_mut(_binding_0);
}
Type::Tuple(_binding_0) => {
v.visit_type_tuple_mut(_binding_0);
}
Type::Verbatim(_binding_0) => {
skip!(_binding_0);
}
_ => unreachable!(),
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_array_mut<V>(v: &mut V, node: &mut TypeArray)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.bracket_token.span);
v.visit_type_mut(&mut *node.elem);
tokens_helper(v, &mut node.semi_token.spans);
v.visit_expr_mut(&mut node.len);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_bare_fn_mut<V>(v: &mut V, node: &mut TypeBareFn)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.lifetimes {
v.visit_bound_lifetimes_mut(it)
};
if let Some(it) = &mut node.unsafety {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.abi {
v.visit_abi_mut(it)
};
tokens_helper(v, &mut node.fn_token.span);
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.inputs) {
let (it, p) = el.into_tuple();
v.visit_bare_fn_arg_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
if let Some(it) = &mut node.variadic {
v.visit_variadic_mut(it)
};
v.visit_return_type_mut(&mut node.output);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_group_mut<V>(v: &mut V, node: &mut TypeGroup)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.group_token.span);
v.visit_type_mut(&mut *node.elem);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_impl_trait_mut<V>(v: &mut V, node: &mut TypeImplTrait)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.impl_token.span);
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_infer_mut<V>(v: &mut V, node: &mut TypeInfer)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.underscore_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_macro_mut<V>(v: &mut V, node: &mut TypeMacro)
where
V: VisitMut + ?Sized,
{
v.visit_macro_mut(&mut node.mac);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_never_mut<V>(v: &mut V, node: &mut TypeNever)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.bang_token.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_param_mut<V>(v: &mut V, node: &mut TypeParam)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_ident_mut(&mut node.ident);
if let Some(it) = &mut node.colon_token {
tokens_helper(v, &mut it.spans)
};
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
if let Some(it) = &mut node.eq_token {
tokens_helper(v, &mut it.spans)
};
if let Some(it) = &mut node.default {
v.visit_type_mut(it)
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_param_bound_mut<V>(v: &mut V, node: &mut TypeParamBound)
where
V: VisitMut + ?Sized,
{
match node {
TypeParamBound::Trait(_binding_0) => {
v.visit_trait_bound_mut(_binding_0);
}
TypeParamBound::Lifetime(_binding_0) => {
v.visit_lifetime_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_paren_mut<V>(v: &mut V, node: &mut TypeParen)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.paren_token.span);
v.visit_type_mut(&mut *node.elem);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_path_mut<V>(v: &mut V, node: &mut TypePath)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.qself {
v.visit_qself_mut(it)
};
v.visit_path_mut(&mut node.path);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_ptr_mut<V>(v: &mut V, node: &mut TypePtr)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.star_token.spans);
if let Some(it) = &mut node.const_token {
tokens_helper(v, &mut it.span)
};
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
v.visit_type_mut(&mut *node.elem);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_reference_mut<V>(v: &mut V, node: &mut TypeReference)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.and_token.spans);
if let Some(it) = &mut node.lifetime {
v.visit_lifetime_mut(it)
};
if let Some(it) = &mut node.mutability {
tokens_helper(v, &mut it.span)
};
v.visit_type_mut(&mut *node.elem);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_slice_mut<V>(v: &mut V, node: &mut TypeSlice)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.bracket_token.span);
v.visit_type_mut(&mut *node.elem);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_trait_object_mut<V>(v: &mut V, node: &mut TypeTraitObject)
where
V: VisitMut + ?Sized,
{
if let Some(it) = &mut node.dyn_token {
tokens_helper(v, &mut it.span)
};
for el in Punctuated::pairs_mut(&mut node.bounds) {
let (it, p) = el.into_tuple();
v.visit_type_param_bound_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_type_tuple_mut<V>(v: &mut V, node: &mut TypeTuple)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.paren_token.span);
for el in Punctuated::pairs_mut(&mut node.elems) {
let (it, p) = el.into_tuple();
v.visit_type_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_un_op_mut<V>(v: &mut V, node: &mut UnOp)
where
V: VisitMut + ?Sized,
{
match node {
UnOp::Deref(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
UnOp::Not(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
UnOp::Neg(_binding_0) => {
tokens_helper(v, &mut _binding_0.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_use_glob_mut<V>(v: &mut V, node: &mut UseGlob)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.star_token.spans);
}
#[cfg(feature = "full")]
pub fn visit_use_group_mut<V>(v: &mut V, node: &mut UseGroup)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.brace_token.span);
for el in Punctuated::pairs_mut(&mut node.items) {
let (it, p) = el.into_tuple();
v.visit_use_tree_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(feature = "full")]
pub fn visit_use_name_mut<V>(v: &mut V, node: &mut UseName)
where
V: VisitMut + ?Sized,
{
v.visit_ident_mut(&mut node.ident);
}
#[cfg(feature = "full")]
pub fn visit_use_path_mut<V>(v: &mut V, node: &mut UsePath)
where
V: VisitMut + ?Sized,
{
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.colon2_token.spans);
v.visit_use_tree_mut(&mut *node.tree);
}
#[cfg(feature = "full")]
pub fn visit_use_rename_mut<V>(v: &mut V, node: &mut UseRename)
where
V: VisitMut + ?Sized,
{
v.visit_ident_mut(&mut node.ident);
tokens_helper(v, &mut node.as_token.span);
v.visit_ident_mut(&mut node.rename);
}
#[cfg(feature = "full")]
pub fn visit_use_tree_mut<V>(v: &mut V, node: &mut UseTree)
where
V: VisitMut + ?Sized,
{
match node {
UseTree::Path(_binding_0) => {
v.visit_use_path_mut(_binding_0);
}
UseTree::Name(_binding_0) => {
v.visit_use_name_mut(_binding_0);
}
UseTree::Rename(_binding_0) => {
v.visit_use_rename_mut(_binding_0);
}
UseTree::Glob(_binding_0) => {
v.visit_use_glob_mut(_binding_0);
}
UseTree::Group(_binding_0) => {
v.visit_use_group_mut(_binding_0);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_variadic_mut<V>(v: &mut V, node: &mut Variadic)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
tokens_helper(v, &mut node.dots.spans);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_variant_mut<V>(v: &mut V, node: &mut Variant)
where
V: VisitMut + ?Sized,
{
for it in &mut node.attrs {
v.visit_attribute_mut(it)
}
v.visit_ident_mut(&mut node.ident);
v.visit_fields_mut(&mut node.fields);
if let Some(it) = &mut node.discriminant {
tokens_helper(v, &mut (it).0.spans);
v.visit_expr_mut(&mut (it).1);
};
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_vis_crate_mut<V>(v: &mut V, node: &mut VisCrate)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.crate_token.span);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_vis_public_mut<V>(v: &mut V, node: &mut VisPublic)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.pub_token.span);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_vis_restricted_mut<V>(v: &mut V, node: &mut VisRestricted)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.pub_token.span);
tokens_helper(v, &mut node.paren_token.span);
if let Some(it) = &mut node.in_token {
tokens_helper(v, &mut it.span)
};
v.visit_path_mut(&mut *node.path);
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_visibility_mut<V>(v: &mut V, node: &mut Visibility)
where
V: VisitMut + ?Sized,
{
match node {
Visibility::Public(_binding_0) => {
v.visit_vis_public_mut(_binding_0);
}
Visibility::Crate(_binding_0) => {
v.visit_vis_crate_mut(_binding_0);
}
Visibility::Restricted(_binding_0) => {
v.visit_vis_restricted_mut(_binding_0);
}
Visibility::Inherited => {}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_where_clause_mut<V>(v: &mut V, node: &mut WhereClause)
where
V: VisitMut + ?Sized,
{
tokens_helper(v, &mut node.where_token.span);
for el in Punctuated::pairs_mut(&mut node.predicates) {
let (it, p) = el.into_tuple();
v.visit_where_predicate_mut(it);
if let Some(p) = p {
tokens_helper(v, &mut p.spans);
}
}
}
#[cfg(any(feature = "derive", feature = "full"))]
pub fn visit_where_predicate_mut<V>(v: &mut V, node: &mut WherePredicate)
where
V: VisitMut + ?Sized,
{
match node {
WherePredicate::Type(_binding_0) => {
v.visit_predicate_type_mut(_binding_0);
}
WherePredicate::Lifetime(_binding_0) => {
v.visit_predicate_lifetime_mut(_binding_0);
}
WherePredicate::Eq(_binding_0) => {
v.visit_predicate_eq_mut(_binding_0);
}
}
}
| 412 | 0.791509 | 1 | 0.791509 | game-dev | MEDIA | 0.200864 | game-dev | 0.757131 | 1 | 0.757131 |
wangjieest/GenericMessagePlugin | 4,844 | Plugins/GMP/Source/GMP/Private/GMPLocalSharedStorage.cpp | // Copyright GenericMessagePlugin, Inc. All Rights Reserved.
#include "GMPLocalSharedStorage.h"
#include "GMPLocalSharedStorageInternal.h"
#include "GMPWorldLocals.h"
#if GMP_WITH_MSG_HOLDER
bool ULocalSharedStorage::SetLocalSharedMessage(const UObject* InCtx, FName Key, FGMPPropHeapHolderArray&& Params, ELocalSharedOverrideMode Mode)
{
auto Mgr = GetInternal(InCtx);
auto Find = Mgr->MessageHolders.Find(Key);
if (!Find || Mode == ELocalSharedOverrideMode::Override)
{
Mgr->MessageHolders.FindOrAdd(Key) = MoveTemp(Params);
return true;
}
return false;
}
const FGMPPropHeapHolderArray* ULocalSharedStorage::GetLocalSharedMessage(const UObject* InCtx, FName Key)
{
if (!InCtx)
return nullptr;
auto Mgr = GetInternal(InCtx);
auto Find = Mgr->MessageHolders.Find(Key);
return Find;
}
#endif
DEFINE_FUNCTION(ULocalSharedStorage::execK2_SetLocalSharedStorage)
{
P_GET_OBJECT(UObject, InCtx);
P_GET_STRUCT(FName, Key);
P_GET_ENUM(ELocalSharedOverrideMode, Mode);
P_GET_UBOOL(bGameScope);
Stack.MostRecentProperty = nullptr;
Stack.StepCompiledIn<FProperty>(nullptr);
auto Prop = Stack.MostRecentProperty;
auto Ptr = Stack.MostRecentPropertyAddress;
P_FINISH
P_NATIVE_BEGIN
if (bGameScope)
InCtx = GMP::WorldLocals::GetGameInstance(InCtx);
*(bool*)RESULT_PARAM = SetLocalSharedStorageImpl(InCtx, Key, Mode, Prop, Ptr);
P_NATIVE_END
}
DEFINE_FUNCTION(ULocalSharedStorage::execK2_GetLocalSharedStorage)
{
P_GET_OBJECT(UObject, InCtx);
P_GET_STRUCT(FName, Key);
P_GET_UBOOL(bGameScope);
Stack.MostRecentProperty = nullptr;
Stack.StepCompiledIn<FProperty>(nullptr);
auto Prop = Stack.MostRecentProperty;
auto Ptr = Stack.MostRecentPropertyAddress;
P_FINISH
P_NATIVE_BEGIN
if (bGameScope)
InCtx = GMP::WorldLocals::GetGameInstance(InCtx);
auto Result = GetLocalSharedStorageImpl(InCtx, Key, Prop);
*(bool*)RESULT_PARAM = !!Result;
if (Result)
{
Prop->CopyCompleteValue(Ptr, Result);
}
P_NATIVE_END
}
void ULocalSharedStorageInternal::AddReferencedObjects(UObject* InThis, FReferenceCollector& Collector)
{
ULocalSharedStorageInternal* This = CastChecked<ULocalSharedStorageInternal>(InThis);
Collector.AddReferencedObjects(This->ObjectMap);
for (auto& Pair : This->StructMap)
{
Pair.Value.AddStructReferencedObjects(Collector);
}
for (auto& Pair : This->PropertyStores)
{
Pair.Value->AddStructReferencedObjects(Collector);
}
for (auto& Pair : This->MessageHolders)
{
for (auto& Holder : Pair.Value)
{
Holder.AddStructReferencedObjects(Collector);
}
}
}
bool ULocalSharedStorage::SetLocalSharedStorageImpl(const UObject* InCtx, FName Key, ELocalSharedOverrideMode Mode, const FProperty* Prop, const void* Data)
{
auto Mgr = GetInternal(InCtx);
if (auto StructProp = CastField<FStructProperty>(Prop))
{
FInstancedStruct* Find = Mgr->StructMap.Find(Key);
if (!Find || Mode == ELocalSharedOverrideMode::Override)
{
Mgr->StructMap.FindOrAdd(Key).InitializeAs(StructProp->Struct, (const uint8*)Data);
return true;
}
}
else if (auto ObjPropBase = CastField<FObjectProperty>(Prop))
{
auto* ObjPtr = Mgr->ObjectMap.Find(Key);
if (!ObjPtr || Mode == ELocalSharedOverrideMode::Override)
{
Mgr->ObjectMap.FindOrAdd(Key) = *(UObject**)Data;
return true;
}
}
else
{
ULocalSharedStorageInternal::FPropertyStorePtr& StorePtr = Mgr->PropertyStores.FindOrAdd(Key);
if (!StorePtr.IsValid() || Mode == ELocalSharedOverrideMode::Override)
{
static auto GetElementSize = [](const FProperty* Prop) {
#if UE_5_05_OR_LATER
return Prop->GetElementSize();
#else
return Prop->ElementSize;
#endif
};
StorePtr.Reset(FGMPPropHeapHolder::MakePropHolder(Prop, Data, nullptr));
return true;
}
}
return false;
}
void* ULocalSharedStorage::GetLocalSharedStorageImpl(const UObject* InCtx, FName Key, const FProperty* Prop)
{
auto Mgr = GetInternal(InCtx);
if (auto StructProp = CastField<FStructProperty>(Prop))
{
if (FInstancedStruct* Find = Mgr->StructMap.Find(Key))
{
return Find->GetMutableMemory();
}
}
else if (auto ObjProp = CastField<FObjectProperty>(Prop))
{
if (TObjectPtr<UObject>* ObjPtr = Mgr->ObjectMap.Find(Key))
{
return (*ObjPtr).Get();
}
}
else
{
if (ULocalSharedStorageInternal::FPropertyStorePtr* StorePtr = Mgr->PropertyStores.Find(Key))
{
return (*StorePtr)->GetAddr();
}
}
return nullptr;
}
ULocalSharedStorageInternal* ULocalSharedStorage::GetInternal(const UObject* InCtx)
{
ULocalSharedStorageInternal* Mgr = nullptr;
if (!InCtx || InCtx->IsA<UGameInstance>())
{
Mgr = GMP::LocalObject<ULocalSharedStorageInternal>(static_cast<const UGameInstance*>(InCtx));
}
else if (auto LP = Cast<ULocalPlayer>(InCtx))
{
Mgr = GMP::LocalObject<ULocalSharedStorageInternal>(LP);
}
else
{
Mgr = GMP::WorldLocalObject<ULocalSharedStorageInternal>(InCtx);
}
return Mgr;
}
| 412 | 0.966584 | 1 | 0.966584 | game-dev | MEDIA | 0.749253 | game-dev | 0.937942 | 1 | 0.937942 |
Space-Stories/space-station-14 | 1,416 | Content.Client/Chemistry/Visualizers/FoamVisualsComponent.cs | using Robust.Client.Animations;
using Robust.Client.Graphics;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom;
namespace Content.Client.Chemistry.Visualizers;
/// <summary>
/// A component that makes foam play an animation when it dissolves.
/// </summary>
[RegisterComponent]
[Access(typeof(FoamVisualizerSystem))]
public sealed partial class FoamVisualsComponent : Component
{
/// <summary>
/// The id of the animation used when the foam dissolves.
/// </summary>
public const string AnimationKey = "foamdissolve_animation";
[DataField(customTypeSerializer: typeof(TimeOffsetSerializer))]
public TimeSpan StartTime;
/// <summary>
/// How long the foam visually dissolves for.
/// </summary>
[DataField]
public float AnimationTime = 0.5f;
/// <summary>
/// The state of the entities base sprite RSI that is displayed when the foam dissolves.
/// Cannot use <see cref="RSI.StateKey"/> because it does not have <see cref="DataDefinitionAttribute"/> and I am not making an engine PR at this time.
/// </summary>
[DataField]
public string AnimationState = "foam-dissolve";
/// <summary>
/// The animation used while the foam dissolves.
/// Generated by <see cref="FoamVisualizerSystem.OnComponentInit"/>.
/// </summary>
[ViewVariables(VVAccess.ReadOnly)]
public Animation Animation = default!;
}
| 412 | 0.796631 | 1 | 0.796631 | game-dev | MEDIA | 0.797018 | game-dev | 0.721034 | 1 | 0.721034 |
x3bits/MikuMikuXR | 2,419 | Assets/MikuMikuXR/Components/TouchEventDetector.cs | using UnityEngine;
using UnityEngine.Events;
namespace MikuMikuXR.Components
{
public class TouchEventDetector : MonoBehaviour
{
private bool _isEnabled;
private int _lastCount;
private TouchData _downTouch;
private TouchData _lastTouch;
private class TouchData
{
public float Time;
public int Frame;
public Vector2 Pos;
}
public bool Enabled
{
get { return _isEnabled; }
set
{
if (_isEnabled == value)
{
return;
}
_isEnabled = value;
if (_isEnabled)
{
Update();
}
}
}
public UnityEvent OnShortClick;
private void Update()
{
if (!Enabled)
{
return;
}
var touchCount = GetTouchCount();
if (touchCount == 1)
{
_lastTouch = GetTouchData();
if (_lastCount == 0)
{
_downTouch = _lastTouch;
}
}
if (_lastCount == 1 && touchCount == 0)
{
var upTouch = _lastTouch;
if ((upTouch.Time - _downTouch.Time < 0.5f || upTouch.Frame - _downTouch.Frame < 2)
&& (upTouch.Pos - _downTouch.Pos).magnitude <
Mathf.Max(20.0f, Mathf.Min(Screen.width, Screen.height) / 100.0f))
{
OnShortClick.Invoke();
}
}
_lastCount = touchCount;
}
private static TouchData GetTouchData()
{
var ret = new TouchData
{
Time = Time.time,
Frame = Time.frameCount,
Pos = Input.mousePosition
};
#if UNITY_EDITOR
ret.Pos = Input.mousePosition;
#else
ret.Pos = Input.GetTouch (0).position;
#endif
return ret;
}
private static int GetTouchCount()
{
#if UNITY_EDITOR
if (Input.GetMouseButton(0))
{
return 1;
}
return 0;
#else
return Input.touchCount;
#endif
}
}
} | 412 | 0.891339 | 1 | 0.891339 | game-dev | MEDIA | 0.511535 | game-dev | 0.95778 | 1 | 0.95778 |
axx0/Civ2-clone | 1,324 | EtoFormsUI/EtoFormsUI/Players/Orders/FortifyOrder.cs | using Civ2engine;
using Civ2engine.Enums;
using Civ2engine.IO;
using Civ2engine.MapObjects;
using Civ2engine.UnitActions;
using Civ2engine.Units;
using Eto.Forms;
namespace EtoFormsUI.Players.Orders
{
public class FortifyOrder : Order
{
private readonly Game _game;
public FortifyOrder(Main mainForm, string defaultLabel, Game game) : base(mainForm, Keys.F, defaultLabel, 2)
{
_game = game;
}
public override Order Update(Tile activeTile, Unit activeUnit)
{
if (activeUnit == null)
{
SetCommandState(OrderStatus.Illegal);
}
else if (activeUnit.AIrole == AIroleType.Settle)
{
SetCommandState(OrderStatus.Illegal);
}
else
{
var canFortifyHere = UnitFunctions.CanFortifyHere(activeUnit, activeTile);
SetCommandState(canFortifyHere.Enabled ? OrderStatus.Active : OrderStatus.Disabled);
}
return this;
}
protected override void Execute(LocalPlayer player)
{
player.ActiveUnit.Order = OrderType.Fortify;
player.ActiveUnit.MovePointsLost = player.ActiveUnit.MaxMovePoints;
_game.ChooseNextUnit();
}
}
} | 412 | 0.772724 | 1 | 0.772724 | game-dev | MEDIA | 0.759964 | game-dev | 0.693954 | 1 | 0.693954 |
IzzelAliz/Arclight | 1,676 | arclight-common/src/main/java/io/izzel/arclight/common/mixin/core/world/entity/animal/ParrotMixin.java | package io.izzel.arclight.common.mixin.core.world.entity.animal;
import net.minecraft.util.RandomSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.animal.Parrot;
import net.minecraft.world.entity.player.Player;
import org.bukkit.event.entity.EntityPotionEffectEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(Parrot.class)
public abstract class ParrotMixin extends AnimalMixin {
@Inject(method = "mobInteract", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/animal/Parrot;addEffect(Lnet/minecraft/world/effect/MobEffectInstance;)Z"))
private void arclight$feed(Player playerIn, InteractionHand hand, CallbackInfoReturnable<InteractionResult> cir) {
bridge$pushEffectCause(EntityPotionEffectEvent.Cause.FOOD);
}
@Redirect(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/animal/Parrot;setOrderedToSit(Z)V"))
private void arclight$handledInSuper(Parrot parrotEntity, boolean p_233687_1_) {
}
@Redirect(method = "mobInteract", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/RandomSource;nextInt(I)I"))
private int arclight$tame(RandomSource instance, int i, Player player) {
var ret = instance.nextInt(i);
return ret == 0 && this.bridge$common$animalTameEvent(player) ? ret : 1;
}
}
| 412 | 0.829988 | 1 | 0.829988 | game-dev | MEDIA | 0.995448 | game-dev | 0.76244 | 1 | 0.76244 |
Craftventure/open-plugin-parts | 3,532 | net/craftventure/core/feature/balloon/physics/DefaultBalloonPhysics.kt | package net.craftventure.core.feature.balloon.physics
import com.squareup.moshi.JsonClass
import net.craftventure.bukkit.ktx.extension.add
import net.craftventure.bukkit.ktx.extension.set
import net.craftventure.core.CraftventureCore
import net.craftventure.core.feature.balloon.types.ExtensibleBalloon
import net.craftventure.core.utils.InterpolationUtils
import org.bukkit.Location
import org.bukkit.util.Vector
import java.util.*
import kotlin.math.abs
class DefaultBalloonPhysics(
private val data: Json = Json(),
private val random: Random = CraftventureCore.getRandom()
) : BalloonPhysics() {
private val inertia = Vector(0.0, 0.2, 0.0)
private val temp = Vector(0, 0, 0)
private val yInertia = 0.05
private var rotationSpeed = CraftventureCore.getRandom().nextFloat()
override val currentRotationalForces: Double
get() = rotationSpeed.toDouble()
override fun update(
balloon: ExtensibleBalloon,
ownerLocation: Location,
balloonLocation: Location,
oldBalloonLocation: Location
) {
// val balloonHolder = balloon.balloonHolder ?: return
val leashLength = (data.maxLeashLength ?: balloon.leashLength)
.coerceAtMost(balloon.balloonHolder?.maxLeashLength ?: Double.MAX_VALUE)
rotationSpeed *= 0.97f
if (rotationSpeed < 1 && rotationSpeed > -1) {
if (rotationSpeed >= 0)
rotationSpeed = 1f
else
rotationSpeed = -1f
}
balloon.angle += rotationSpeed
temp.set(balloonLocation.x, balloonLocation.y, balloonLocation.z)
inertia.multiply(0.95)
if (inertia.y < yInertia) {
inertia.y = Math.min(yInertia, inertia.y + yInertia)
}
// Logger.console("%s", inertia);
if (abs(inertia.x) < 0.02 && abs(inertia.y) < 0.06 && abs(inertia.z) < 0.02)
inertia.add(
(random.nextDouble() * 0.016) - 0.008,
(random.nextDouble() * 0.016) - 0.008,
(random.nextDouble() * 0.016) - 0.008
)
balloonLocation.add(inertia.x, inertia.y, inertia.z)
// ownerLocation.getWorld().spawnParticle(Particle.END_ROD, ownerLocation, 1, 0, 0, 0, 0);
val distance = ownerLocation.distance(balloonLocation)
if (distance > leashLength) {
val percentage = leashLength / distance
balloonLocation.x = InterpolationUtils.linearInterpolate(ownerLocation.x, balloonLocation.x, percentage)
balloonLocation.y = InterpolationUtils.linearInterpolate(ownerLocation.y, balloonLocation.y, percentage)
balloonLocation.z = InterpolationUtils.linearInterpolate(ownerLocation.z, balloonLocation.z, percentage)
}
inertia.set(balloonLocation.x - temp.x, balloonLocation.y - temp.y, balloonLocation.z - temp.z)
rotationSpeed += (inertia.x - inertia.z).toFloat() * 2.5f
// if (oldLocation!!.distanceSquared(location!!) > 25 * 25) {
// Bukkit.getScheduler().scheduleSyncDelayedTask(
// CraftventureCore.getInstance(),
// { tracker!!.forceRespawn(player) },
// 5
// )
// }
}
@JsonClass(generateAdapter = true)
class Json(
val maxLeashLength: Double? = null
) : BalloonPhysics.Json() {
override fun toPhysics(): BalloonPhysics = DefaultBalloonPhysics(this)
companion object {
const val type = "default"
}
}
} | 412 | 0.745268 | 1 | 0.745268 | game-dev | MEDIA | 0.861333 | game-dev | 0.922274 | 1 | 0.922274 |
magefree/mage | 1,458 | Mage.Sets/src/mage/cards/u/UlvenwaldMysteries.java | package mage.cards.u;
import mage.abilities.common.DiesCreatureTriggeredAbility;
import mage.abilities.common.SacrificePermanentTriggeredAbility;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.keyword.InvestigateEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.StaticFilters;
import mage.game.permanent.token.HumanSoldierToken;
import java.util.UUID;
/**
*
* @author fireshoes
*/
public final class UlvenwaldMysteries extends CardImpl {
public UlvenwaldMysteries(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{2}{G}");
// Whenever a nontoken creature you control dies, investigate. <i>(Create a colorless Clue artifact token with "{2}, Sacrifice this artifact: Draw a card.")</i>
this.addAbility(new DiesCreatureTriggeredAbility(new InvestigateEffect(), false, StaticFilters.FILTER_CONTROLLED_CREATURE_NON_TOKEN));
// Whenever you sacrifice a Clue, create a 1/1 white Human Soldier creature token.
this.addAbility(new SacrificePermanentTriggeredAbility(new CreateTokenEffect(new HumanSoldierToken()), StaticFilters.FILTER_CONTROLLED_CLUE));
}
private UlvenwaldMysteries(final UlvenwaldMysteries card) {
super(card);
}
@Override
public UlvenwaldMysteries copy() {
return new UlvenwaldMysteries(this);
}
}
| 412 | 0.962535 | 1 | 0.962535 | game-dev | MEDIA | 0.765758 | game-dev | 0.886733 | 1 | 0.886733 |
oculus-samples/Unreal-HandGameplay | 5,053 | Plugins/OculusHandTools/Source/OculusHandPoseRecognition/Private/HandPoseRecognizer.cpp | // Copyright (c) Meta Platforms, Inc. and affiliates.
#include "HandPoseRecognizer.h"
#include "OculusHandPoseRecognitionModule.h"
#include <limits>
UHandPoseRecognizer::UHandPoseRecognizer(const FObjectInitializer& ObjectInitializer):
Super(ObjectInitializer)
{
PrimaryComponentTick.bCanEverTick = true;
// Recognition default parameters
Side = EOculusXRHandType::None;
RecognitionInterval = 0.0f;
DefaultConfidenceFloor = 0.5;
DampingFactor = 0.0f;
// Current hand pose being recognized
TimeSinceLastRecognition = 0.0f;
CurrentHandPose = -1;
CurrentHandPoseDuration = 0.0f;
CurrentHandPoseConfidence = 0.0f;
CurrentHandPoseError = std::numeric_limits<float>::max();
// Encoded hand pose logged index
LoggedIndex = 0;
}
void UHandPoseRecognizer::BeginPlay()
{
Super::BeginPlay();
// We decode the hand poses
for (auto PatternIndex = 0; PatternIndex < Poses.Num(); ++PatternIndex)
{
if (!Poses[PatternIndex].Decode())
{
UE_LOG(LogHandPoseRecognition, Error, TEXT("UHandPoseRecognizer(%s) encoded pose at index %d is invalid."),
*GetName(),
PatternIndex);
}
}
}
FRotator UHandPoseRecognizer::GetWristRotator(FQuat ComponentQuat) const
{
auto ComponentRotator = ComponentQuat.Rotator();
auto const World = GetWorld();
if (!World) return ComponentRotator;
auto const PlayerController = World->GetFirstPlayerController();
if (!PlayerController) return ComponentRotator;
auto const ComponentRotationToCamera = PlayerController->PlayerCameraManager->GetTransform().InverseTransformRotation(ComponentQuat).Rotator();
ComponentRotator.Yaw = ComponentRotationToCamera.Yaw;
return ComponentRotator;
}
void UHandPoseRecognizer::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (Side == EOculusXRHandType::None)
{
// Recognizer is disabled
return;
}
// Recognition is throttled
TimeSinceLastRecognition += DeltaTime;
if (TimeSinceLastRecognition < RecognitionInterval)
{
return;
}
// Ignore low confidence cases
if (UOculusXRInputFunctionLibrary::GetTrackingConfidence(Side) == EOculusXRTrackingConfidence::Low)
{
return;
}
// Updating tracked hand.
// Note that the wrist rotation pitch and roll are world relative, and the yaw is hmd relative.
Pose.UpdatePose(Side, GetWristRotator(GetComponentQuat()));
// Finding closest pattern
auto ClosestHandPose = -1;
auto ClosestHandPoseConfidence = DefaultConfidenceFloor;
auto ClosestHandPoseError = std::numeric_limits<float>::max();
auto HighestConfidence = 0.0f;
for (auto PatternIndex = 0; PatternIndex < Poses.Num(); ++PatternIndex)
{
// Skip patterns that are not for this side
if (Poses[PatternIndex].GetHandType() != Side)
continue;
// Computing confidence (we ignore the wrist yaw by default)
auto RawError = 0.0f;
auto const Confidence = Poses[PatternIndex].ComputeConfidence(Pose, &RawError);
// UE_LOG(LogHandPoseRecognition, Error, TEXT("%s confidence %0.0f raw error %0.0f"), *Poses[PatternIndex].PoseName, Confidence, RawError);
// We always record the smallest error, in case no pattern matches
if (HighestConfidence < Confidence)
HighestConfidence = Confidence;
// We update the best pattern match (first: best match so far has lower confidence than the current pose)
if (ClosestHandPoseConfidence < Confidence)
{
// Second: checking for custom pose error ceiling
if (Poses[PatternIndex].CustomConfidenceFloor > 0.0f && Confidence < Poses[PatternIndex].CustomConfidenceFloor)
continue;
ClosestHandPoseConfidence = Confidence;
ClosestHandPoseError = RawError;
ClosestHandPose = PatternIndex;
}
}
// If we have no match, we report the highest confidence seen.
if (ClosestHandPose == -1)
{
ClosestHandPoseConfidence = HighestConfidence;
}
if (CurrentHandPose == ClosestHandPose)
{
// Same pose as before is being held
CurrentHandPoseDuration += TimeSinceLastRecognition;
TimeSinceLastRecognition = 0.0;
CurrentHandPoseConfidence = DampingFactor * CurrentHandPoseConfidence + (1.0f - DampingFactor) * ClosestHandPoseConfidence;
CurrentHandPoseError = DampingFactor * CurrentHandPoseError + (1.0f - DampingFactor) * ClosestHandPoseError;
}
else
{
// Change of pose
CurrentHandPose = ClosestHandPose;
CurrentHandPoseDuration = 0.0f;
CurrentHandPoseConfidence = ClosestHandPoseConfidence;
CurrentHandPoseError = ClosestHandPoseError;
}
}
bool UHandPoseRecognizer::GetRecognizedHandPose(int& Index, FString& Name, float& Duration, float& Error, float& Confidence)
{
Index = CurrentHandPose;
Duration = CurrentHandPoseDuration;
Error = CurrentHandPoseError;
Confidence = CurrentHandPoseConfidence;
if (Index >= 0 && Index < Poses.Num())
{
Name = Poses[Index].PoseName;
return true;
}
Name = TEXT("None");
return false;
}
void UHandPoseRecognizer::LogEncodedHandPose()
{
Pose.Encode();
UE_LOG(LogHandPoseRecognition, Warning, TEXT("HAND POSE %d: %s"), LoggedIndex++, *Pose.CustomEncodedPose);
}
| 412 | 0.88126 | 1 | 0.88126 | game-dev | MEDIA | 0.624316 | game-dev | 0.800977 | 1 | 0.800977 |
Simre1/reactimate | 1,625 | reactimate-game/src/Reactimate/Game/Input.hs | module Reactimate.Game.Input
( inputEvents,
keyboardState,
mousePosition,
mouseButtons,
gameShouldQuit,
)
where
import Linear (V2 (..))
import Reactimate
import Reactimate.Game.Environment (GameEnv (..))
import Reactimate.Game.Graphics (Camera (..))
import SDL qualified
-- | Handle SDL events as they happen. This can be useful if you want to catch events which happen in between simulations.
inputEvents :: GameEnv -> Event SDL.Event
inputEvents _ = callback $ \fin fire -> do
eventWatch <- SDL.addEventWatch fire
addFinalizer fin $ SDL.delEventWatch eventWatch
-- | Get the current keyboard state.
keyboardState :: GameEnv -> Behavior (SDL.Scancode -> Bool)
keyboardState _ = makeBehavior $ arrIO $ \_ -> do
SDL.getKeyboardState
-- | Get the position of the mouse relative to the camera.
mousePosition :: GameEnv -> Signal Camera (V2 Int)
mousePosition gameEnv = arrIO $ \camera -> do
windowSize <- fmap fromIntegral <$> SDL.get (SDL.windowSize gameEnv.window)
realMousePosition <- fmap fromIntegral . SDL.unP <$> SDL.getAbsoluteMouseLocation
let (V2 x y) = quot <$> (realMousePosition * camera.viewport) <*> windowSize
(V2 _ vy) = camera.viewport
pure $ V2 x (vy - y)
-- | Get the current mouse button state
mouseButtons :: GameEnv -> Behavior (SDL.MouseButton -> Bool)
mouseButtons _ = makeBehavior $ arrIO $ const $ do
SDL.getMouseButtons
-- | Checks if a SDL Quit event was triggered
gameShouldQuit :: GameEnv -> Behavior Bool
gameShouldQuit gameEnv =
makeBehavior $
accumulateEvent (||) False $
(== SDL.QuitEvent) . SDL.eventPayload <$> inputEvents gameEnv
| 412 | 0.726119 | 1 | 0.726119 | game-dev | MEDIA | 0.905341 | game-dev | 0.793908 | 1 | 0.793908 |
a-b-street/abstreet | 1,765 | apps/santa/src/controls.rs | use geom::{Angle, Speed};
use widgetry::{EventCtx, Key};
// TODO The timestep accumulation seems fine. What's wrong? Clamping errors repeated?
const HACK: f64 = 5.0;
pub struct InstantController {
/// Which of the 8 directions are we facing, based on the last set of keys pressed down?
pub facing: Angle,
}
impl InstantController {
pub fn new() -> InstantController {
InstantController {
facing: Angle::ZERO,
}
}
pub fn displacement(&mut self, ctx: &mut EventCtx, speed: Speed) -> Option<(f64, f64)> {
let dt = ctx.input.nonblocking_is_update_event()?;
// Work around a few bugs here.
//
// 1) The Santa sprites are all facing 180 degrees, not 0, so invert X.
// 2) Invert y so that negative is up.
//
// It's confusing, but self.facing winds up working for rotating the sprite, and the output
// displacement works.
self.facing = angle_from_arrow_keys(ctx)?.opposite();
let magnitude = (dt * HACK * speed).inner_meters();
let (sin, cos) = self.facing.normalized_radians().sin_cos();
Some((-magnitude * cos, -magnitude * sin))
}
}
pub fn angle_from_arrow_keys(ctx: &EventCtx) -> Option<Angle> {
let mut x: f64 = 0.0;
let mut y: f64 = 0.0;
if ctx.is_key_down(Key::LeftArrow) || ctx.is_key_down(Key::A) {
x -= 1.0;
}
if ctx.is_key_down(Key::RightArrow) || ctx.is_key_down(Key::D) {
x += 1.0;
}
if ctx.is_key_down(Key::UpArrow) || ctx.is_key_down(Key::W) {
y -= 1.0;
}
if ctx.is_key_down(Key::DownArrow) || ctx.is_key_down(Key::S) {
y += 1.0;
}
if x == 0.0 && y == 0.0 {
return None;
}
Some(Angle::new_rads(y.atan2(x)))
}
| 412 | 0.842895 | 1 | 0.842895 | game-dev | MEDIA | 0.807921 | game-dev | 0.968742 | 1 | 0.968742 |
KittyPBoxx/pokeemerald-net-demo | 7,918 | PokecomChannel/PokecomChannel/source/libwiigui/gui_button.cpp | /****************************************************************************
* libwiigui
*
* Tantric 2009
*
* gui_button.cpp
*
* GUI class definitions
***************************************************************************/
#include "gui.h"
/**
* Constructor for the GuiButton class.
*/
GuiButton::GuiButton(int w, int h)
{
width = w;
height = h;
image = nullptr;
imageOver = nullptr;
imageHold = nullptr;
imageClick = nullptr;
icon = nullptr;
iconOver = nullptr;
iconHold = nullptr;
iconClick = nullptr;
for(int i=0; i < 3; i++)
{
label[i] = nullptr;
labelOver[i] = nullptr;
labelHold[i] = nullptr;
labelClick[i] = nullptr;
}
soundOver = nullptr;
soundHold = nullptr;
soundClick = nullptr;
tooltip = nullptr;
selectable = true;
holdable = false;
clickable = true;
}
/**
* Destructor for the GuiButton class.
*/
GuiButton::~GuiButton()
{
}
void GuiButton::SetImage(GuiImage* img)
{
image = img;
if(img) img->SetParent(this);
}
void GuiButton::SetImageOver(GuiImage* img)
{
imageOver = img;
if(img) img->SetParent(this);
}
void GuiButton::SetImageHold(GuiImage* img)
{
imageHold = img;
if(img) img->SetParent(this);
}
void GuiButton::SetImageClick(GuiImage* img)
{
imageClick = img;
if(img) img->SetParent(this);
}
void GuiButton::SetIcon(GuiImage* img)
{
icon = img;
if(img) img->SetParent(this);
}
void GuiButton::SetIconOver(GuiImage* img)
{
iconOver = img;
if(img) img->SetParent(this);
}
void GuiButton::SetIconHold(GuiImage* img)
{
iconHold = img;
if(img) img->SetParent(this);
}
void GuiButton::SetIconClick(GuiImage* img)
{
iconClick = img;
if(img) img->SetParent(this);
}
void GuiButton::SetLabel(GuiText* txt, int n)
{
label[n] = txt;
if(txt) txt->SetParent(this);
}
void GuiButton::SetLabelOver(GuiText* txt, int n)
{
labelOver[n] = txt;
if(txt) txt->SetParent(this);
}
void GuiButton::SetLabelHold(GuiText* txt, int n)
{
labelHold[n] = txt;
if(txt) txt->SetParent(this);
}
void GuiButton::SetLabelClick(GuiText* txt, int n)
{
labelClick[n] = txt;
if(txt) txt->SetParent(this);
}
void GuiButton::SetSoundOver(GuiSound * snd)
{
soundOver = snd;
}
void GuiButton::SetSoundHold(GuiSound * snd)
{
soundHold = snd;
}
void GuiButton::SetSoundClick(GuiSound * snd)
{
soundClick = snd;
}
void GuiButton::SetTooltip(GuiTooltip* t)
{
tooltip = t;
if(t)
tooltip->SetParent(this);
}
/**
* Draw the button on screen
*/
void GuiButton::Draw()
{
if(!this->IsVisible())
return;
if(state == STATE::SELECTED || state == STATE::HELD)
{
if(imageOver)
imageOver->Draw();
else if(image) // draw image
image->Draw();
if(iconOver)
iconOver->Draw();
else if(icon) // draw icon
icon->Draw();
// draw text
if(labelOver[0])
labelOver[0]->Draw();
else if(label[0])
label[0]->Draw();
if(labelOver[1])
labelOver[1]->Draw();
else if(label[1])
label[1]->Draw();
if(labelOver[2])
labelOver[2]->Draw();
else if(label[2])
label[2]->Draw();
}
else
{
if(image) // draw image
image->Draw();
if(icon) // draw icon
icon->Draw();
// draw text
if(label[0])
label[0]->Draw();
if(label[1])
label[1]->Draw();
if(label[2])
label[2]->Draw();
}
this->UpdateEffects();
}
void GuiButton::DrawTooltip()
{
if(tooltip)
tooltip->DrawTooltip();
}
void GuiButton::ResetText()
{
for(int i=0; i<3; i++)
{
if(label[i])
label[i]->ResetText();
if(labelOver[i])
labelOver[i]->ResetText();
}
if(tooltip)
tooltip->ResetText();
}
void GuiButton::Update(GuiTrigger * t)
{
if(state == STATE::CLICKED || state == STATE::DISABLED || !t)
return;
else if(parentElement && parentElement->GetState() == STATE::DISABLED)
return;
#ifdef HW_RVL
// cursor
if(t->wpad->ir.valid && t->chan >= 0)
{
if(this->IsInside(t->wpad->ir.x, t->wpad->ir.y))
{
if(state == STATE::DEFAULT) // we weren't on the button before!
{
this->SetState(STATE::SELECTED, t->chan);
if(this->Rumble())
rumbleRequest[t->chan] = 1;
if(soundOver)
soundOver->Play();
if(effectsOver && !effects)
{
// initiate effects
effects = effectsOver;
effectAmount = effectAmountOver;
effectTarget = effectTargetOver;
}
}
}
else
{
if(state == STATE::SELECTED && (stateChan == t->chan || stateChan == -1))
this->ResetState();
if(effectTarget == effectTargetOver && effectAmount == effectAmountOver)
{
// initiate effects (in reverse)
effects = effectsOver;
effectAmount = -effectAmountOver;
effectTarget = 100;
}
}
}
#endif
// button triggers
if(this->IsClickable())
{
s32 wm_btns, wm_btns_trig, cc_btns, cc_btns_trig, wiidrc_btns, wiidrc_btns_trig;
for(int i=0; i<3; i++)
{
if(trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan))
{
// higher 16 bits only (wiimote)
wm_btns = t->wpad->btns_d << 16;
wm_btns_trig = trigger[i]->wpad->btns_d << 16;
// lower 16 bits only (classic controller)
cc_btns = t->wpad->btns_d >> 16;
cc_btns_trig = trigger[i]->wpad->btns_d >> 16;
// Wii U Gamepad
wiidrc_btns = t->wiidrcdata.btns_d;
wiidrc_btns_trig = trigger[i]->wiidrcdata.btns_d;
if(
(t->wpad->btns_d > 0 &&
(wm_btns == wm_btns_trig ||
(cc_btns == cc_btns_trig && t->wpad->exp.type == EXP_CLASSIC))) ||
(t->pad.btns_d == trigger[i]->pad.btns_d && t->pad.btns_d > 0) ||
(wiidrc_btns == wiidrc_btns_trig && wiidrc_btns > 0))
{
if(t->chan == stateChan || stateChan == -1)
{
if(state == STATE::SELECTED)
{
if(!t->wpad->ir.valid || this->IsInside(t->wpad->ir.x, t->wpad->ir.y))
{
this->SetState(STATE::CLICKED, t->chan);
if(soundClick)
soundClick->Play();
}
}
else if(trigger[i]->type == TRIGGER::BUTTON_ONLY)
{
this->SetState(STATE::CLICKED, t->chan);
}
else if(trigger[i]->type == TRIGGER::BUTTON_ONLY_IN_FOCUS &&
parentElement->IsFocused())
{
this->SetState(STATE::CLICKED, t->chan);
}
}
}
}
}
}
if(this->IsHoldable())
{
bool held = false;
s32 wm_btns, wm_btns_h, wm_btns_trig, cc_btns, cc_btns_h, cc_btns_trig, wiidrc_btns, wiidrc_btns_h, wiidrc_btns_trig;
for(int i=0; i<3; i++)
{
if(trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan))
{
// higher 16 bits only (wiimote)
wm_btns = t->wpad->btns_d << 16;
wm_btns_h = t->wpad->btns_h << 16;
wm_btns_trig = trigger[i]->wpad->btns_h << 16;
// lower 16 bits only (classic controller)
cc_btns = t->wpad->btns_d >> 16;
cc_btns_h = t->wpad->btns_h >> 16;
cc_btns_trig = trigger[i]->wpad->btns_h >> 16;
// Wii U Gamepad
wiidrc_btns = t->wiidrcdata.btns_d;
wiidrc_btns_h = t->wiidrcdata.btns_h;
wiidrc_btns_trig = trigger[i]->wiidrcdata.btns_h;
if(
(t->wpad->btns_d > 0 &&
(wm_btns == wm_btns_trig ||
(cc_btns == cc_btns_trig && t->wpad->exp.type == EXP_CLASSIC))) ||
(t->pad.btns_d == trigger[i]->pad.btns_h && t->pad.btns_d > 0) ||
(wiidrc_btns == wiidrc_btns_trig && wiidrc_btns > 0))
{
if(trigger[i]->type == TRIGGER::HELD && state == STATE::SELECTED &&
(t->chan == stateChan || stateChan == -1))
this->SetState(STATE::CLICKED, t->chan);
}
if(
(t->wpad->btns_h > 0 &&
(wm_btns_h == wm_btns_trig ||
(cc_btns_h == cc_btns_trig && t->wpad->exp.type == EXP_CLASSIC))) ||
(t->pad.btns_h == trigger[i]->pad.btns_h && t->pad.btns_h > 0) ||
(wiidrc_btns_h == wiidrc_btns_trig && wiidrc_btns_h > 0))
{
if(trigger[i]->type == TRIGGER::HELD)
held = true;
}
if(!held && state == STATE::HELD && stateChan == t->chan)
{
this->ResetState();
}
else if(held && state == STATE::CLICKED && stateChan == t->chan)
{
this->SetState(STATE::HELD, t->chan);
}
}
}
}
if(updateCB)
updateCB(this);
}
| 412 | 0.959524 | 1 | 0.959524 | game-dev | MEDIA | 0.432935 | game-dev | 0.983641 | 1 | 0.983641 |
ashishps1/awesome-low-level-design | 1,508 | solutions/golang/snakeandladdergame/snake_and_ladder_game.go | package snakeandladdergame
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
type SnakeAndLadderGame struct {
ID int64
Board *Board
Players []*Player
Dice *Dice
CurrentPlayerIdx int
}
func NewSnakeAndLadderGame(playerNames []string) *SnakeAndLadderGame {
game := &SnakeAndLadderGame{
ID: generateID(),
Board: NewBoard(),
Dice: NewDice(),
Players: []*Player{},
CurrentPlayerIdx: 0,
}
for _, name := range playerNames {
game.Players = append(game.Players, NewPlayer(name))
}
return game
}
func (g *SnakeAndLadderGame) Play(wg *sync.WaitGroup) {
for !g.isGameOver() {
player := g.Players[g.CurrentPlayerIdx]
roll := g.Dice.Roll()
newPosition := player.Position + roll
if newPosition <= g.Board.Size {
player.Position = g.Board.GetNewPosition(newPosition)
fmt.Printf("Game: %d :- %s rolled a %d and moved to position %d\n", g.ID, player.Name, roll, player.Position)
}
if player.Position == g.Board.Size {
fmt.Printf("For Game %d :- %s wins!\n", g.ID, player.Name)
break
}
g.CurrentPlayerIdx = (g.CurrentPlayerIdx + 1) % len(g.Players)
time.Sleep(10 * time.Millisecond) //To simulate the demo
}
wg.Done()
}
func (g *SnakeAndLadderGame) isGameOver() bool {
for _, player := range g.Players {
if player.Position == g.Board.Size {
return true
}
}
return false
}
var idCounter int64
func generateID() int64 {
return atomic.AddInt64(&idCounter, 1)
}
| 412 | 0.51096 | 1 | 0.51096 | game-dev | MEDIA | 0.715868 | game-dev | 0.824766 | 1 | 0.824766 |
v3921358/MapleRoot | 2,309 | MapleRoot/scripts/npc/1104102.js | /*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2016 - 2019 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var npcid = 1104102;
var baseJob = 13;
var status;
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else {
if (mode == 0 && type > 0) {
cm.dispose();
return;
}
if (mode == 1) {
status++;
} else {
status--;
}
if (status == 0) {
if (Math.floor(cm.getJobId() / 100) != baseJob) {
cm.sendOk("Hello there, #h0#. Are you helping us finding the intruder? He is not in this area, I've already searched here.");
cm.dispose();
return;
}
cm.sendOk("Darn, you found me! Then, there's only one way out! Let's fight, like #rBlack Wings#k should!");
} else if (status == 1) {
var mapobj = cm.getMap();
var npcpos = mapobj.getMapObject(cm.getNpcObjectId()).getPosition();
spawnMob(npcpos.x, npcpos.y, 9001009, mapobj);
mapobj.destroyNPC(npcid);
cm.dispose();
}
}
}
function spawnMob(x, y, id, map) {
if (map.getMonsterById(id) != null) {
return;
}
const LifeFactory = Java.type('server.life.LifeFactory');
const Point = Java.type('java.awt.Point');
var mob = LifeFactory.getMonster(id);
map.spawnMonsterOnGroundBelow(mob, new Point(x, y));
} | 412 | 0.700614 | 1 | 0.700614 | game-dev | MEDIA | 0.901885 | game-dev | 0.901397 | 1 | 0.901397 |
Elfocrash/L2dotNET | 1,961 | src/L2dotNET/Models/Zones/Classes/MotherTreeZone.cs | using L2dotNET.DataContracts.Shared.Enums;
using L2dotNET.Models.Player;
using L2dotNET.Network.serverpackets;
using L2dotNET.Tables;
using L2dotNET.Utility;
namespace L2dotNET.Models.Zones.Classes
{
class MotherTreeZone : L2Zone
{
public MotherTreeZone(IdFactory idFactory) : base(idFactory)
{
ZoneId = idFactory.NextId();
Enabled = true;
}
public override void OnEnter(L2Object obj)
{
if (!Enabled)
return;
base.OnEnter(obj);
obj.OnEnterZoneAsync(this);
if (!(obj is L2Player))
return;
L2Player p = (L2Player)obj;
p.SendSystemMessage((SystemMessageId)Template.EnteringMessageNo);
if (Template.AffectRace.EqualsIgnoreCase("all"))
return;
if (!Template.AffectRace.EqualsIgnoreCase("elf"))
return;
if (p.BaseClass.ClassId.ClassRace != ClassRace.Elf)
return;
// p._stats.p_regen_hp += Template._hp_regen_bonus;
// p._stats.p_regen_mp += Template._mp_regen_bonus;
}
public override void OnExit(L2Object obj, bool cls)
{
if (!Enabled)
return;
base.OnExit(obj, cls);
obj.OnExitZoneAsync(this, cls);
if (!(obj is L2Player))
return;
L2Player p = (L2Player)obj;
p.SendSystemMessage((SystemMessageId)Template.LeavingMessageNo);
if (Template.AffectRace.EqualsIgnoreCase("all"))
return;
if (!Template.AffectRace.EqualsIgnoreCase("elf"))
return;
if (p.BaseClass.ClassId.ClassRace != ClassRace.Elf)
return;
// p._stats.p_regen_hp -= Template._hp_regen_bonus;
// p._stats.p_regen_mp -= Template._mp_regen_bonus;
}
}
} | 412 | 0.698047 | 1 | 0.698047 | game-dev | MEDIA | 0.420302 | game-dev | 0.923293 | 1 | 0.923293 |
RogyDev/Rogy-Engine- | 2,414 | Rogy/ThirdParty/Bullet/BulletCollision/CollisionShapes/btMinkowskiSumShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.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.
*/
#ifndef BT_MINKOWSKI_SUM_SHAPE_H
#define BT_MINKOWSKI_SUM_SHAPE_H
#include "btConvexInternalShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
/// The btMinkowskiSumShape is only for advanced users. This shape represents implicit based minkowski sum of two convex implicit shapes.
ATTRIBUTE_ALIGNED16(class) btMinkowskiSumShape : public btConvexInternalShape
{
btTransform m_transA;
btTransform m_transB;
const btConvexShape* m_shapeA;
const btConvexShape* m_shapeB;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btMinkowskiSumShape(const btConvexShape* shapeA,const btConvexShape* shapeB);
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
void setTransformA(const btTransform& transA) { m_transA = transA;}
void setTransformB(const btTransform& transB) { m_transB = transB;}
const btTransform& getTransformA()const { return m_transA;}
const btTransform& GetTransformB()const { return m_transB;}
virtual btScalar getMargin() const;
const btConvexShape* getShapeA() const { return m_shapeA;}
const btConvexShape* getShapeB() const { return m_shapeB;}
virtual const char* getName()const
{
return "MinkowskiSum";
}
};
#endif //BT_MINKOWSKI_SUM_SHAPE_H
| 412 | 0.879718 | 1 | 0.879718 | game-dev | MEDIA | 0.977066 | game-dev | 0.667522 | 1 | 0.667522 |
DarkstarProject/darkstar | 1,450 | scripts/zones/Western_Adoulin/npcs/Ruth.lua | -----------------------------------
-- Area: Western Adoulin
-- NPC: Ruth
-- Type: Standard NPC and Quest NPC
-- Involved With Quest: 'A Pioneers Best (Imaginary) Friend'
-- !pos -144 4 -10 256
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/status");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local APBIF = player:getQuestStatus(ADOULIN, dsp.quest.id.adoulin.A_PIONEERS_BEST_IMAGINARY_FRIEND);
local SOA_Mission = player:getCurrentMission(SOA);
if (SOA_Mission >= dsp.mission.id.soa.LIFE_ON_THE_FRONTIER) then
if ((APBIF == QUEST_ACCEPTED) and (not player:hasStatusEffect(dsp.effect.IONIS))) then
-- Progresses Quest: 'A Pioneers Best (Imaginary) Friend'
player:startEvent(2523);
else
-- Standard dialogue, after joining colonization effort
player:startEvent(590);
end
else
-- Dialogue prior to joining colonization effort
player:startEvent(503);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 2523) then
-- Progresses Quest: 'A Pioneers Best (Imaginary) Friend'
player:delStatusEffectsByFlag(dsp.effectFlag.INFLUENCE, true)
player:addStatusEffect(dsp.effect.IONIS, 0, 0, 9000);
end
end;
| 412 | 0.940574 | 1 | 0.940574 | game-dev | MEDIA | 0.996317 | game-dev | 0.963427 | 1 | 0.963427 |
mastercomfig/tf2-patches-old | 1,710 | src/game/client/tf/vgui/item_slot_panel.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef ITEM_SLOT_PANEL_H
#define ITEM_SLOT_PANEL_H
#include "base_loadout_panel.h"
class CItemCriteriaSelectionPanel;
//-----------------------------------------------------------------------------
// A loadout screen that handles modifying the loadout of a specific item
//-----------------------------------------------------------------------------
class CItemSlotPanel : public CBaseLoadoutPanel
{
DECLARE_CLASS_SIMPLE( CItemSlotPanel, CBaseLoadoutPanel );
public:
CItemSlotPanel( vgui::Panel *parent );
~CItemSlotPanel();
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void PerformLayout( void );
virtual void AddNewItemPanel( int iPanelIndex ) OVERRIDE;
virtual void UpdateModelPanels( void ) OVERRIDE;
virtual int GetNumItemPanels( void ) OVERRIDE;
virtual void OnShowPanel( bool bVisible, bool bReturningFromArmory ) OVERRIDE;
MESSAGE_FUNC_PTR( OnItemPanelMouseReleased, "ItemPanelMouseReleased", panel );
MESSAGE_FUNC_PARAMS( OnSelectionReturned, "SelectionReturned", data );
MESSAGE_FUNC( OnCancelSelection, "CancelSelection" );
virtual void OnCommand( const char *command );
void SetItem( CEconItem* pItem );
private:
CEconItem *m_pItem;
struct ItemSlot_t
{
CAttribute_ItemSlotCriteria m_slotCriteriaAttribute;
itemid_t m_ulOriginalID;
bool m_bHasSlot;
};
CUtlVector< ItemSlot_t > m_itemSlots;
int m_iCurrentSlotIndex;
CItemSelectionCriteria m_selectionCriteria;
CItemCriteriaSelectionPanel *m_pSelectionPanel;
};
#endif // ITEM_SLOT_PANEL_H
| 412 | 0.989979 | 1 | 0.989979 | game-dev | MEDIA | 0.544704 | game-dev,graphics-rendering | 0.641019 | 1 | 0.641019 |
bozimmerman/CoffeeMud | 7,065 | resources/quests/templates/auto_delivery4.quest | #!QUESTMAKER_START_SCRIPT Auto Delivery #4
#The player must pay one or more existing mobs somewhere else in your
#world. A reward is optionally given after payment.
#
#!QUESTMAKER_PAGE Quest Name/Duration
#Enter the unique name and starting time/duration for your new quest.
#Times are entered as a simple number or math expression to denote a
#time in default ticks (4 second period), or you may follow the expression
#with the word seconds, minutes, hours, days, mudhours, muddays, mudweeks,
#mudmonths, or mudyears. Time expressions may include numbers, math
#symbols, or the ? operator to generate random numbers. Example:
#"5 + 3?10 minutes" would generate a frequency of 8-15 minutes.#
#
#Quest ID:
#Enter a unique name/id for your quest:
#$QUEST_ID=$UNIQUE_QUEST_NAME=auto_delivery_4
#
#Quest Name:
#Enter a friendly displayable name for your quest:
#$QUEST_NAME=$STRING=Auto Delivery #4
#
#Quest Frequency:
#This is the time between quest starts.
#$FREQUENCY=$TIMEEXPRESSION=90 minutes
#
#Quest Duration:
#This is how long your quest remains running, and how long a player
#accepting the quest has to complete the quest and report back in.
#$DURATION=$TIMEEXPRESSION=90 minutes
#
#!QUESTMAKER_PAGE Specify the Quest Criteria and Instructions
#The criteria for players and instructions they need.
#
#Quest-Player Criterium:
#A Zapper Mask to describe what kinds of players will receive this quest.
#You can use this to set race, level, or other requirements.
#$QUEST_CRITERIA=$ZAPPERMASK
#
#Instructions:
#Specify some the instructions and justification for the quest.
#$QUEST_INSTRUCTIONSSTRING=($LONG_STRING)=Find ${2 *} at that one place and give him $[1 *]. Be careful!
#
#Success:
#This is what the player sees when the player completes the quest.
#$QUEST_WINSPEECH_TEXT=($LONG_STRING)=Delivery complete!
#
#!QUESTMAKER_PAGE Specify the Deliveree Mobs
#The Deliveree Mob is the mob the player must find and deliver the item to.
#
#Deliverees:
#Specify below the deliveree mobs who will have the items delivered.
#
#Deliveree mob names:
#Specify the mobs who will act as the capturable mob or mobs.
#See help on ZAPPERMASK for information on zapper mask syntax.
#$DELIVEREE_MASK=$ZAPPERMASK
#
#Amount of money:
#The total amount of money required to complete the quest. This will be in
the deliveree mobs local currency.
#$DELIVEREE_COUNT=($EXPRESSION)=100
#
#Deliveree response:
#You may optionally specify some additional bit of speech the deliveree
#mob will say to the players after they arrive.
#$DELIVEREE_ANNOUNCE=($LONG_STRING)=Are you here to pay me? If so, here I am!
#
#Delivery response:
#You may optionally specify some additional bit of speech the deliveree
#mob will say to the players after they have handed over the item/items.
#$DELIVERY_RESPONSE=($LONG_STRING)=Thanks!
#
#!QUESTMAKER_PAGE Quest Completion
#Select some rewards for completing the deliveries:
#
#Reward items:
#Specify zero or more items to choose from as a reward
#$REWARD_ITEMS=$ITEMXML_ZEROORMORE
#
#Quest Point?
#$QUEST_POINT=$CHOOSE=YES,NO
#Amount of experience points, blank for none, or a number% for percent of exp to next level:
#$EXP=($STRING)=10%
#
#Player Faction to give to or take from:
#$FACTION=($FACTION)
#If you selected a faction above, enter a new numeric amount,
#or enter +value to add, or --value to subtract:
#$NUMFACTION=($STRING)
#
#Select whether a player may complete this quest multiple times,
#or 'prev' to require a previous quest, if multiple found.
#$MULTIPLE=$CHOOSE=YES,NO,PREV
#
#$CATEGORY=($HIDDEN)=
#
#!QUESTMAKER_END_SCRIPT Auto Delivery #4
set name $QUEST_ID
set display $QUEST_NAME
set author $#AUTHOR
set questtype auto_delivery4
set category $CATEGORY
set instructions $QUEST_INSTRUCTIONSSTRING
set wait $FREQUENCY
set interval 1
quiet
set room
set area
set pcmobgroup reselect any mask=$QUEST_CRITERIA
give script LOAD=$QUEST_ID_playertrack.script
set area
set room
set mobgroup
set mob
set duration $DURATION
<?xml version="1.0"?>
<FILE><NAME>$QUEST_ID_rewarditems.xml</NAME><DATA><ITEMS>$REWARD_ITEMS</ITEMS></DATA></FILE>
<FILE><NAME>$QUEST_ID_playertrack.script</NAME>
<DATA>
FUNCTION_PROG CHECK_DONE
if EVAL('$<$i $QUEST_ID_DELIVERED>' >= $DELIVEREE_COUNT) and QUESTSCRIPTED($i *)
if EVAL('$EXP' != '')
mpexp $i $EXP
endif
if EVAL('$FACTION' != '')
mpfaction $i $FACTION +$NUMFACTION
endif
if EVAL('$QUEST_POINT' == 'YES') AND !QUESTWINNER($n *)
mpforce $i mpoload QuestPoint
mpechoat $i You receive a quest point.
endif
if EVAL('$GOLD' != '') AND EVAL('$GOLD' > 0)
mpforce $i mpoload $GOLD
mpechoat $i You receive $b.
endif
mpforce $i mpoload fromfile $QUEST_ID_rewarditems.xml any
if EVAL('$b' != '')
mpechoat $i You receive $b.
endif
mpquestwin $i *
mpecho $QUEST_WINSPEECH_TEXT
mpendquest $i
mpqset * STATISTICS SUCCESS
IF EVAL('$MULTIPLE' == 'PREV')
mptransfer $i $i
ENDIF
endif
~
FUNCTION_PROG CAN_ACCEPT
if ISLIKE($n '$QUEST_CRITERIA') and ISPC($n) and ( EVAL('$MULTIPLE' != 'PREV') or QUESTWINNER($n previous) )
if EVAL('$MULTIPLE' == 'YES') OR !QUESTWINNER($n *)
if !QUESTSCRIPTED($n *)
RETURN TRUE
endif
endif
endif
RETURN CANCEL
~
FUNCTION_PROG DO_ACCEPT
mpqset * STATISTICS ACCEPTED
mpscript $n INDIVIDUAL SAVABLE STATIC=LOAD=$QUEST_ID_playertrack.script
~
ONCE_PROG 100
mpsetvar $i INSTRUCTIONS $QUEST_INSTRUCTIONSSTRING
if var($i $QUEST_ID_DELIVERED = '')
mpsetvar $i $QUEST_ID_DELIVERED 0
endif
mpsetvar $i PROGRESS Delivered: $<$i $QUEST_ID_DELIVERED>/$DELIVEREE_COUNT
IF QVAR(* DURATION != '0')
if QVAR(* REMAINING == '')
MPENDQUEST $i
RETURN
else
mpsetvar $i TIME_REMAINING $%QVAR(* REMAINING)%
endif
ENDIF
mpechoat $i $QUEST_INSTRUCTIONSSTRING
~
GREET_PROG 100
if ISLIKE($n '$DELIVEREE_MASK') AND CANSEE($n $i) AND !STRCONTAINS('$<$i $QUEST_ID_DELIVERED>' $@n)
mpforce $n sayto $i $DELIVEREE_ANNOUNCE
endif
~
ENTRY_PROG 100
if INROOM($i == $g)
for $0 = 1 to '$%NUMMOBSROOM(*)%'
mpargset $1 $%ROOMMOB($0)%
if ISLIKE($1 '$DELIVEREE_MASK') AND CANSEE($1 $i) AND !STRCONTAINS('$<$i $QUEST_ID_DELIVERED>' $@1)
mpforce $1 sayto "$i" $DELIVEREE_ANNOUNCE
endif
next
endif
~
GIVING_PROG all
if ISLIKE($o '-JAVACLASS +GenCoins +StdCoins') AND ISLIKE($t '$DELIVEREE_MASK') AND EVAL('$%GSTAT($o CURRENCY)%' == '$%GSTAT($t CURRENCY)%')
mpsetvar $i $QUEST_ID_DELIVERED +$%GOLDAMT($o)%
mpforce $t mpjunk $o
mpforce $t sayto "$i" $DELIVERY_RESPONSE
mpechoat $i That's $<$i $QUEST_ID_DELIVERED> / $DELIVEREE_COUNT
mpsetvar $i PROGRESS Paid $<$i $QUEST_ID_DELIVERED> / $DELIVEREE_COUNT
mpcallfunc CHECK_DONE
else
mpforce $t sayto "$i" What's this?
mpforce $t give "$o" "$i"
endif
~
RAND_PROG 25
IF QVAR(* DURATION != '0')
if QVAR(* REMAINING == '')
MPENDQUEST $i
else
mpsetvar $i TIME_REMAINING $%QVAR(* REMAINING)%
endif
ENDIF
~
QUEST_TIME_PROG * -1
MPECHOAT $i The quest "$QUEST_NAME" has ended.
~
QUEST_TIME_PROG * 1
MPECHOAT $i The quest "$QUEST_NAME" has 1 minute remaining.
~
</DATA></FILE> | 412 | 0.862503 | 1 | 0.862503 | game-dev | MEDIA | 0.973317 | game-dev | 0.876303 | 1 | 0.876303 |
GrahamBurgers/BossReworks | 1,423 | files/boss_deer/edit.lua | dofile("mods/boss_reworks/files/lib/injection.lua")
local nxml = dofile("mods/boss_reworks/files/lib/nxml.lua")
local path = "data/entities/animals/boss_spirit/islandspirit.xml"
local tree = nxml.parse(ModTextFileGetContent(path))
for k, v in ipairs(tree.children) do
if v.name == "LuaComponent" then
if v.attr.script_source_file == "data/entities/animals/boss_spirit/islandspirit.lua" then
v.attr.script_source_file = "mods/boss_reworks/files/boss_deer/logic.lua"
v.attr.script_damage_received = "mods/boss_reworks/files/boss_deer/logic.lua"
v.attr.script_death = "mods/boss_reworks/files/boss_deer/logic.lua"
end
if v.attr.script_source_file == "data/entities/animals/boss_spirit/init.lua" then
v.attr.script_source_file = "mods/boss_reworks/files/boss_deer/init.lua"
end
end
if v.name == "Base" then
for k2, v2 in ipairs(v.children) do
if v2.name == "DamageModelComponent" then
v2.attr.hp = 10
v2.attr.blood_multiplier = 0.1
v2.children[1].attr.slice = 0.5
v2.children[1].attr.projectile = 0.6
v2.children[1].attr.holy = -4
end
end
end
if v.name == "Entity" then
for k2, v2 in ipairs(v.children) do
if v2.attr.effect == "PROTECTION_PROJECTILE" then
v2.attr.frames = "1"
end
end
end
end
table.insert(tree.children,
nxml.parse('<VariableStorageComponent _tags="no_gold_drop"> </VariableStorageComponent>'))
ModTextFileSetContent(path, tostring(tree)) | 412 | 0.818846 | 1 | 0.818846 | game-dev | MEDIA | 0.886785 | game-dev | 0.875174 | 1 | 0.875174 |
miniwebkit/src | 3,017 | graphics/skia/src/animator/SkAnimateSet.cpp | /* libs/graphics/animator/SkAnimateSet.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "SkAnimateSet.h"
#include "SkAnimateMaker.h"
#include "SkAnimateProperties.h"
#include "SkParse.h"
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkSet::fInfo[] = {
SK_MEMBER(begin, MSec),
SK_MEMBER(dur, MSec),
SK_MEMBER_PROPERTY(dynamic, Boolean),
SK_MEMBER(field, String),
// SK_MEMBER(formula, DynamicString),
SK_MEMBER(lval, DynamicString),
// SK_MEMBER_PROPERTY(reset, Boolean),
SK_MEMBER_PROPERTY(step, Int),
SK_MEMBER(target, DynamicString),
SK_MEMBER(to, DynamicString)
};
#endif
DEFINE_GET_MEMBER(SkSet);
SkSet::SkSet() {
dur = 1;
}
#ifdef SK_DUMP_ENABLED
void SkSet::dump(SkAnimateMaker* maker) {
INHERITED::dump(maker);
if (dur != 1) {
#ifdef SK_CAN_USE_FLOAT
SkDebugf("dur=\"%g\" ", SkScalarToFloat(SkScalarDiv(dur,1000)));
#else
SkDebugf("dur=\"%x\" ", SkScalarDiv(dur,1000));
#endif
}
//don't want double />\n's
SkDebugf("/>\n");
}
#endif
void SkSet::refresh(SkAnimateMaker& maker) {
fFieldInfo->setValue(maker, &fValues, 0, fFieldInfo->fCount, NULL,
fFieldInfo->getType(), to);
}
void SkSet::onEndElement(SkAnimateMaker& maker) {
if (resolveCommon(maker) == false)
return;
if (fFieldInfo == NULL) {
maker.setErrorCode(SkDisplayXMLParserError::kFieldNotInTarget);
return;
}
fReset = dur != 1;
SkDisplayTypes outType = fFieldInfo->getType();
int comps = outType == SkType_String || outType == SkType_DynamicString ? 1 :
fFieldInfo->getSize((const SkDisplayable*) fTarget) / sizeof(int);
if (fValues.getType() == SkType_Unknown) {
fValues.setType(outType);
fValues.setCount(comps);
if (outType == SkType_String || outType == SkType_DynamicString)
fValues[0].fString = SkNEW(SkString);
else
memset(fValues.begin(), 0, fValues.count() * sizeof(fValues.begin()[0]));
} else {
SkASSERT(fValues.getType() == outType);
if (fFieldInfo->fType == SkType_Array)
comps = fValues.count();
else
SkASSERT(fValues.count() == comps);
}
if (formula.size() > 0) {
comps = 1;
outType = SkType_MSec;
}
fFieldInfo->setValue(maker, &fValues, fFieldOffset, comps, this, outType, formula.size() > 0 ? formula : to);
fComponents = fValues.count();
}
| 412 | 0.935184 | 1 | 0.935184 | game-dev | MEDIA | 0.543174 | game-dev,graphics-rendering | 0.960631 | 1 | 0.960631 |
neilmewada/CrystalEngine | 1,805 | Engine/Source/FusionCore/Public/Widget/FContainerWidget.h | #pragma once
namespace CE
{
CLASS()
class FUSIONCORE_API FContainerWidget : public FWidget
{
CE_CLASS(FContainerWidget, FWidget)
public:
FContainerWidget();
u32 GetChildCount() const { return children.GetSize(); }
Ref<FWidget> GetChild(u32 index) const { return children[index].Lock(); }
Ref<FWidget> FindChildByName(const CE::Name& name, SubClass<FWidget> widgetClass = FWidget::StaticClass());
template<class T> requires TIsBaseClassOf<FWidget, T>::Value
Ref<T> FindChildByName(const CE::Name& name)
{
return Object::CastTo<T>(FindChildByName(name, T::StaticClass()));
}
void SetContextRecursively(FFusionContext* context) override;
FWidget* HitTest(Vec2 localMousePos) override;
bool ChildExistsRecursive(FWidget* child) override;
void ApplyStyleRecursively() override;
void HandleEvent(FEvent* event) override;
void InsertChild(int index, FWidget* child);
void RemoveChildAt(int index);
void MoveChildToIndex(FWidget* child, int index);
void DestroyAllChildren();
void QueueDestroyAllChildren();
void RemoveAllChildren();
protected:
void OnPaint(FPainter* painter) override;
void ClearStyle() override;
bool TryAddChild(FWidget* child) override;
bool TryRemoveChild(FWidget* child) override;
void OnChildWidgetDestroyed(FWidget* child) override;
protected: // - Fields -
FIELD()
Array<WeakRef<FWidget>> children{};
public: // - Fusion Properties -
FUSION_PROPERTY(bool, ClipChildren);
FUSION_PROPERTY(Color, DebugColor);
FUSION_WIDGET;
};
} // namespace CE
#include "FContainerWidget.rtti.h" | 412 | 0.956675 | 1 | 0.956675 | game-dev | MEDIA | 0.544142 | game-dev,desktop-app | 0.948479 | 1 | 0.948479 |
ForgeEssentials/ForgeEssentials | 27,168 | src/main/java/com/forgeessentials/core/ForgeEssentials.java | package com.forgeessentials.core;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.Level;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.api.UserIdent;
import com.forgeessentials.commons.BuildInfo;
import com.forgeessentials.commons.events.RegisterPacketEvent;
import com.forgeessentials.commons.network.NetworkUtils;
import com.forgeessentials.commons.network.packets.Packet01SelectionUpdate;
import com.forgeessentials.commons.network.packets.Packet03PlayerPermissions;
import com.forgeessentials.commons.network.packets.Packet05Noclip;
import com.forgeessentials.compat.BaublesCompat;
import com.forgeessentials.compat.HelpFixer;
import com.forgeessentials.compat.worldedit.WEIntegration;
import com.forgeessentials.core.commands.CommandFEInfo;
import com.forgeessentials.core.commands.CommandFEWorldInfo;
import com.forgeessentials.core.commands.CommandFeReload;
import com.forgeessentials.core.commands.CommandFeSettings;
import com.forgeessentials.core.commands.CommandTest;
import com.forgeessentials.core.commands.CommandUuid;
import com.forgeessentials.core.commands.registration.FECommandManager;
import com.forgeessentials.core.config.ConfigBase;
import com.forgeessentials.core.environment.Environment;
import com.forgeessentials.core.misc.BlockModListFile;
import com.forgeessentials.core.misc.CommandPermissionManager;
import com.forgeessentials.core.misc.Packet0HandshakeHandler;
import com.forgeessentials.core.misc.RespawnHandler;
import com.forgeessentials.core.misc.TaskRegistry;
import com.forgeessentials.core.misc.TeleportHelper;
import com.forgeessentials.core.misc.Translator;
import com.forgeessentials.core.moduleLauncher.FEModule.Instance;
import com.forgeessentials.core.moduleLauncher.ModuleLauncher;
import com.forgeessentials.data.v2.DataManager;
import com.forgeessentials.playerlogger.TestClass;
import com.forgeessentials.protection.ModuleProtection;
import com.forgeessentials.util.CommandUtils;
import com.forgeessentials.util.CommandUtils.CommandInfo;
import com.forgeessentials.util.PlayerInfo;
import com.forgeessentials.util.ServerUtil;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerAboutToStartEvent;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerStartedEvent;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerStartingEvent;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerStoppedEvent;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerStoppingEvent;
import com.forgeessentials.util.events.player.PlayerPositionEventFactory;
import com.forgeessentials.util.output.ChatOutputHandler;
import com.forgeessentials.util.output.logger.LoggingHandler;
import com.forgeessentials.util.questioner.Questioner;
import com.forgeessentials.util.selections.CommandDeselect;
import com.forgeessentials.util.selections.CommandExpand;
import com.forgeessentials.util.selections.CommandExpandY;
import com.forgeessentials.util.selections.CommandPos1;
import com.forgeessentials.util.selections.CommandPos2;
import com.forgeessentials.util.selections.CommandWand;
import com.forgeessentials.util.selections.SelectionHandler;
import com.google.gson.JsonParseException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.Builder;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.CommandEvent;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent;
import net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent;
import net.minecraftforge.fml.event.server.FMLServerStartedEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.event.server.FMLServerStoppedEvent;
import net.minecraftforge.fml.event.server.FMLServerStoppingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.loading.FMLPaths;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.fml.network.FMLNetworkConstants;
import net.minecraftforge.server.permission.DefaultPermissionLevel;
/**
* Main mod class
*/
@Mod(ForgeEssentials.MODID)
@Mod.EventBusSubscriber(modid = ForgeEssentials.MODID)
public class ForgeEssentials
{
public static final String MODID = "forgeessentials";
public static final int CURRENT_MODULE_VERSION =1;
public static final String FE_DIRECTORY = "ForgeEssentials";
@Instance
public static ForgeEssentials instance;
public static IEventBus modMain;
public static ModContainer MOD_CONTAINER;
public static Random rnd = new Random();
/* ------------------------------------------------------------ */
public static final String PERM = "fe";
public static final String PERM_CORE = PERM + ".core";
public static final String PERM_INFO = PERM_CORE + ".info";
public static final String PERM_RELOAD = PERM_CORE + ".reload";
public static final String PERM_VERSIONINFO = PERM_CORE + ".versioninfo";
/* ------------------------------------------------------------ */
/* ForgeEssentials core submodules */
protected static ConfigBase configManager;
protected static ModuleLauncher moduleLauncher;
protected static TaskRegistry tasks;
protected static PlayerPositionEventFactory factory;
protected static TeleportHelper teleportHelper;
protected static Questioner questioner;
protected static FECommandManager commandManager;
/* ------------------------------------------------------------ */
private static File feDirectory;
// private static File moduleDirectory;
private static File jarLocation;
protected static boolean debugMode = true;
protected static boolean safeMode = false;
protected static boolean logCommandsToConsole;
private RespawnHandler respawnHandler;
private SelectionHandler selectionHandler;
public static boolean isCubicChunksInstalled = false;
/* ------------------------------------------------------------ */
public ForgeEssentials()
{
TestClass.get();
LoggingHandler.init();
LoggingHandler.felog.info("ForgeEssentialsInt");
instance = this;
// Set mod as server only
MOD_CONTAINER = ModLoadingContext.get().getActiveContainer();
ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST,
() -> Pair.of(() -> FMLNetworkConstants.IGNORESERVERONLY, (a, b) -> true));
modMain = FMLJavaModLoadingContext.get().getModEventBus();
tasks = new TaskRegistry();
List<ModInfo> mods = ModList.get().getMods();
for (ModInfo mod : mods)
{
if (mod.getModId().equals("forgeessentials"))
{
jarLocation = mod.getOwningFile().getFile().getFilePath().toFile();
break;
}
}
BuildInfo.getBuildInfo(jarLocation);
initConfiguration();
Environment.check();
MinecraftForge.EVENT_BUS.register(this);
modMain.addListener(this::preInit);
modMain.addListener(this::postLoad);
moduleLauncher = new ModuleLauncher();
NetworkUtils.init();
// Load submodules
moduleLauncher.init();
}
public void preInit(FMLCommonSetupEvent event)
{
LoggingHandler.felog.info("ForgeEssentials CommonSetup");
LoggingHandler.felog.info(String.format("Running ForgeEssentials %s (%s)-%s", BuildInfo.getCurrentVersion(),
BuildInfo.getBuildHash(), BuildInfo.getBuildType()));
// Handle submodules parents, must be called after mod loading
moduleLauncher.handleModuleParents();
if (safeMode) {
LoggingHandler.felog.warn("You are running FE in safe mode. Please only do so if requested to by the ForgeEssentials team.");
}
ForgeEssentials.getConfigManager().bakeAllRegisteredConfigs(false);
// Set up logger level
toggleDebug();
// Register core submodules
factory = new PlayerPositionEventFactory();
teleportHelper = new TeleportHelper();
questioner = new Questioner();
respawnHandler = new RespawnHandler();
selectionHandler = new SelectionHandler();
// MinecraftForge.EVENT_BUS.register(new CompatReiMinimap());
if(ModuleLauncher.getModuleList().contains(WEIntegration.weModule)) {
WEIntegration.instance.postLoad();
}
}
public void postLoad(FMLLoadCompleteEvent e)
{
LoggingHandler.felog.info("ForgeEssentials LoadCompleteEvent");
commandManager = new FECommandManager();
isCubicChunksInstalled = ModList.get().isLoaded("cubicchunks");
}
/* ------------------------------------------------------------ */
private void initConfiguration()
{
feDirectory = new File(FMLPaths.GAMEDIR.get().toFile(), FE_DIRECTORY);
feDirectory.mkdirs();
configManager = new ConfigBase();
ConfigBase.getModuleConfig().loadModuleConfig();
ConfigBase.getModuleConfig().saveConfig();
configManager.registerSpecs(new FEConfig());
}
private void toggleDebug()
{
if (isDebug())
LoggingHandler.setLevel(Level.DEBUG);
else
LoggingHandler.setLevel(Level.INFO);
}
private void registerNetworkMessages()
{
LoggingHandler.felog.info("ForgeEssentials registering network Packets");
// Load network packages
NetworkUtils.registerClientToServer(0, Packet0HandshakeHandler.class, Packet0HandshakeHandler::encode, Packet0HandshakeHandler::decode,
Packet0HandshakeHandler::handler);
NetworkUtils.registerServerToClient(1, Packet01SelectionUpdate.class, Packet01SelectionUpdate::encode, Packet01SelectionUpdate::decode,
Packet01SelectionUpdate::handler);
// NetworkUtils.registerServerToClient(2, Packet2Reach.class, Packet2Reach::decode); old times
NetworkUtils.registerServerToClient(3, Packet03PlayerPermissions.class, Packet03PlayerPermissions::encode, Packet03PlayerPermissions::decode,
Packet03PlayerPermissions::handler);
// NetworkUtils.registerServerToClient(2, Packet4Economy.class, Packet4Economy::decode); old times
NetworkUtils.registerServerToClient(5, Packet05Noclip.class, Packet05Noclip::encode, Packet05Noclip::decode, Packet05Noclip::handler);
// Packet6AuthLogin is registered in the Auth Module
// Packet7Remote is registered in the Remote Module
MinecraftForge.EVENT_BUS.post(new RegisterPacketEvent());
// Packet8AuthReply is registered in the Remote Module
// Packet9AuthRequest is registered in the Remote Module
}
/* ------------------------------------------------------------ */
@SubscribeEvent
public void registerCommandEvent(final RegisterCommandsEvent event)
{
LoggingHandler.felog.debug("ForgeEssentials Register Commands Event");
FECommandManager.registerCommand(new CommandFEInfo(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandFeReload(true), event.getDispatcher());
CommandFeSettings settings = new CommandFeSettings(true);
FECommandManager.registerCommand(settings, event.getDispatcher());
MinecraftForge.EVENT_BUS.register(settings);
FECommandManager.registerCommand(new CommandTest(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandWand(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandUuid(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandFEWorldInfo(true), event.getDispatcher());
if (!ModuleLauncher.getModuleList().contains(WEIntegration.weModule))
{
FECommandManager.registerCommand(new CommandPos1(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandPos2(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandDeselect(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandExpand(true), event.getDispatcher());
FECommandManager.registerCommand(new CommandExpandY(true), event.getDispatcher());
}
}
@SubscribeEvent
public void serverPreInit(FMLServerAboutToStartEvent e)
{
BuildInfo.startVersionChecks(MODID);
LoggingHandler.felog.info("Registered " + FECommandManager.getTotalCommandNumber() + " commands");
LoggingHandler.felog.info("ForgeEssentials ServerAboutToStart");
//Register Server-Client Packets
registerNetworkMessages();
// Initialize data manager once server begins to start
DataManager.setInstance(new DataManager(new File(ServerUtil.getWorldPath(), "FEData/json")));
//Load ConfigurableCommands after DataManager is created
FECommandManager.loadConfigurableCommand();
MinecraftForge.EVENT_BUS.post(new FEModuleServerAboutToStartEvent(e));
new BaublesCompat();
}
@SubscribeEvent
public void serverStarting(FMLServerStartingEvent e)
{
LoggingHandler.felog.info("ForgeEssentials ServerStarting");
BlockModListFile.makeModList();
BlockModListFile.dumpFMLRegistries();
// TODO REIMPLEMENT
// ForgeChunkManager.setForcedChunkLoadingCallback(ForgeEssentials.MODID, new FEChunkLoader());
registerPermissions();
FECommandManager.aliaseManager.saveData();
MinecraftForge.EVENT_BUS.post(new FEModuleServerStartingEvent(e));
if(BuildInfo.isOutdated()) {
LoggingHandler.felog.warn("-------------------------------------------------------------------------------------");
LoggingHandler.felog.warn(Translator.format("WARNING! Using ForgeEssentials build #%s, latest build is #%s",BuildInfo.getCurrentVersion(), BuildInfo.getLatestVersion()));
LoggingHandler.felog.warn("We highly recommend updating asap to get the latest security and bug fixes");
LoggingHandler.felog.warn("-------------------------------------------------------------------------------------");
}
}
@SubscribeEvent
public void serverStarted(FMLServerStartedEvent e)
{
LoggingHandler.felog.info("ForgeEssentials ServerStarted");
MinecraftForge.EVENT_BUS.post(new FEModuleServerStartedEvent(e));
// Do permission registration in first server tick.
MinecraftForge.EVENT_BUS.register(new CommandPermissionRegistrationHandler());
}
public static final class CommandPermissionRegistrationHandler
{
@SubscribeEvent
public void serverTickEvent(TickEvent.ServerTickEvent event)
{
CommandPermissionManager.registerCommandPermissions();
MinecraftForge.EVENT_BUS.unregister(this);
}
}
@SubscribeEvent
public void serverStopping(FMLServerStoppingEvent e)
{
LoggingHandler.felog.info("ForgeEssentials ServerStopping");
MinecraftForge.EVENT_BUS.post(new FEModuleServerStoppingEvent(e));
PlayerInfo.discardAll();
}
@SubscribeEvent
public void serverStopped(FMLServerStoppedEvent e)
{
LoggingHandler.felog.info("ForgeEssentials ServerStopped");
try
{
MinecraftForge.EVENT_BUS.post(new FEModuleServerStoppedEvent(e));
FECommandManager.clearRegisteredCommands();
Translator.save();
ConfigBase.getModuleConfig().saveConfig();
}
catch (RuntimeException ex)
{
LoggingHandler.felog.fatal("Caught Runtime Exception During Server Stop event! Suppressing Fire!", ex);
}
}
protected void registerPermissions()
{
APIRegistry.perms.registerPermission(PERM_VERSIONINFO, DefaultPermissionLevel.OP,
"Shows notification to the player if FE version is outdated");
CommandPermissionManager.registerCommandPermission("help", DefaultPermissionLevel.ALL);
CommandPermissionManager.registerCommandPermission("config", DefaultPermissionLevel.OP);
CommandPermissionManager.registerCommandPermission("forge", DefaultPermissionLevel.OP);
CommandPermissionManager.registerCommandPermission("trigger", DefaultPermissionLevel.OP);
// Teleport
APIRegistry.perms.registerPermissionProperty(TeleportHelper.TELEPORT_COOLDOWN, "5",
"Allow bypassing teleport cooldown");
APIRegistry.perms.registerPermissionProperty(TeleportHelper.TELEPORT_WARMUP, "3",
"Allow bypassing teleport warmup");
APIRegistry.perms.registerPermissionPropertyOp(TeleportHelper.TELEPORT_COOLDOWN, "0");
APIRegistry.perms.registerPermissionPropertyOp(TeleportHelper.TELEPORT_WARMUP, "0");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_CROSSDIM_FROM, DefaultPermissionLevel.ALL,
"Allow teleporting cross-dimensionally from a dimension");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_CROSSDIM_TO, DefaultPermissionLevel.ALL,
"Allow teleporting cross-dimensionally to a dimension");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_CROSSDIM_PORTALFROM, DefaultPermissionLevel.ALL,
"Allow teleporting cross-dimensionally from a dimension via a portal");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_CROSSDIM_PORTALTO, DefaultPermissionLevel.ALL,
"Allow teleporting cross-dimensionally to a dimension via a portal (target coordinates are origin for vanilla portals)");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_FROM, DefaultPermissionLevel.ALL,
"Allow being teleported from a certain location / dimension");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_TO, DefaultPermissionLevel.ALL,
"Allow being teleported to a certain location / dimension");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_PORTALFROM, DefaultPermissionLevel.ALL,
"Allow being teleported from a certain location / dimension via a portal");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_PORTALTO, DefaultPermissionLevel.ALL,
"Allow being teleported to a certain location / dimension via a portal");
APIRegistry.perms.registerPermission(ModuleProtection.COMMANDBLOCK_PERM, DefaultPermissionLevel.OP,
"Lowest node for restricting access to CommandBlocks");
CommandFeSettings.addSetting("Teleport", "warmup", TeleportHelper.TELEPORT_WARMUP);
CommandFeSettings.addSetting("Teleport", "cooldown", TeleportHelper.TELEPORT_COOLDOWN);
}
/* ------------------------------------------------------------ */
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void playerLoggedInEvent(PlayerEvent.PlayerLoggedInEvent event)
{
if (event.getEntity() instanceof PlayerEntity)
{
ServerPlayerEntity player = (ServerPlayerEntity) event.getPlayer();
UserIdent.login(player);
PlayerInfo.login(player.getGameProfile().getId());
try
{
PlayerInfo.login(player.getGameProfile().getId());
}
catch (JsonParseException e)
{
player.connection.disconnect(new StringTextComponent(
"Unable to Parse PlayerInfo file, please contact your admin for assistance and ask them to check the log!"));
LoggingHandler.felog.fatal(
"Unable to Parse PlayerInfo file! If this is date related, please check S:format_gson_compat in your main.cfg file!",
e);
}
if (FEConfig.checkSpacesInNames)
{
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(player.getGameProfile().getName());
if (matcher.find())
{
String msg = Translator.format("Invalid name \"%s\" containing spaces. Please change your name!",
event.getPlayer().getDisplayName().getString());
Entity entity = event.getEntity();
if (!(entity instanceof ServerPlayerEntity))
{
return;
}
ServerPlayerEntity serverplayer = (ServerPlayerEntity) entity;
serverplayer.connection.disconnect(new StringTextComponent(msg));
}
}
// Show version notification
if (BuildInfo.isOutdated() && UserIdent.get(player).checkPermission(PERM_VERSIONINFO))
ChatOutputHandler.chatWarning(player, Translator.format(
"ForgeEssentials server build #%s is outdated. The current build is #%s. Consider updating to get latest security and bug fixes.",
BuildInfo.getCurrentVersion(), BuildInfo.getLatestVersion()));
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void playerLoggedOutEvent(PlayerEvent.PlayerLoggedOutEvent event)
{
if (event.getEntity() instanceof PlayerEntity)
{
PlayerInfo.logout(event.getPlayer().getGameProfile().getId());
UserIdent.logout((PlayerEntity) event.getPlayer());
}
}
@SubscribeEvent
public void playerRespawnEvent(PlayerEvent.PlayerRespawnEvent event)
{
if (event.getEntity() instanceof PlayerEntity)
{
UserIdent.get((PlayerEntity) event.getPlayer());
}
}
/* ------------------------------------------------------------ */
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void commandEvent(CommandEvent event) throws CommandSyntaxException
{
if (event.getParseResults().getContext().getNodes().isEmpty())
return;
boolean perm = false;
CommandInfo info = CommandUtils.getCommandInfo(event);
if (info.getSource().getEntity() instanceof ServerPlayerEntity)
{
perm = checkPerms("command." + info.getPermissionNode(), CommandUtils.getServerPlayer(info.getSource()));
}
else
{
perm = true;
}
if (logCommandsToConsole)
{
LoggingHandler.felog
.info(String.format("Player \"%s\" %s command \"%s %s\"", info.getSource().getTextName(),
perm ? "used" : "tried to use", info.getCommandName(), info.getActualArgsString()));
}
if (!perm)
{
event.setCanceled(true);
info.getSource().sendFailure(new StringTextComponent("You dont have permission to use this command!"));
}
}
public boolean checkPerms(String commandPermissionNode, ServerPlayerEntity sender)
{
//LoggingHandler.felog.debug("Checking command perm: " + commandPermissionNode);
return APIRegistry.perms.checkUserPermission(UserIdent.get(sender), commandPermissionNode);
}
/* ------------------------------------------------------------ */
static ForgeConfigSpec.BooleanValue FEcheckVersion;
static ForgeConfigSpec.BooleanValue FEdebugMode;
static ForgeConfigSpec.BooleanValue FEsafeMode;
static ForgeConfigSpec.BooleanValue FEhideWorldEditCommands;
static ForgeConfigSpec.BooleanValue FElogCommandsToConsole;
public static Builder load(Builder BUILDER, boolean isReload)
{
FEcheckVersion = BUILDER.comment("Check for newer versions of ForgeEssentials on load?").define("versionCheck",
true);
// configManager.setUseCanonicalConfig(SERVER_BUILDER.comment("For modules that
// support it, place their configs in this file.").define("canonicalConfigs",
// false).get());
FEdebugMode = BUILDER.comment("Activates developer debug mode. Spams your FML logs.").define("debug", false);
FEsafeMode = BUILDER
.comment("Activates safe mode with will ignore some errors which would normally crash the game."
+ "Please only enable this after being instructed to do so by FE team in response to an issue on GitHub!")
.define("safeMode", false);
FEhideWorldEditCommands = BUILDER
.comment("Hide WorldEdit commands from /help and only show them in //help command")
.define("hide_worldedit_help", true);
FElogCommandsToConsole = BUILDER.comment("Log commands to console").define("logCommands", false);
return BUILDER;
}
public static void bakeConfig(boolean reload)
{
if (reload)
Translator.translations.clear();
Translator.load();
BuildInfo.needCheckVersion = FEcheckVersion.get();
// configManager.setUseCanonicalConfig(SERVER_BUILDER.comment("For modules that
// support it, place their configs in this file.").define("canonicalConfigs",
// false).get());
debugMode = FEdebugMode.get();
safeMode = FEsafeMode.get();
HelpFixer.hideWorldEditCommands = FEhideWorldEditCommands.get();
logCommandsToConsole = FElogCommandsToConsole.get();
}
/* ------------------------------------------------------------ */
public static ConfigBase getConfigManager()
{
return configManager;
}
public static File getFEDirectory()
{
return feDirectory;
}
public static boolean isDebug()
{
return debugMode;
}
public static boolean isSafeMode()
{
return safeMode;
}
public static File getJarLocation()
{
return jarLocation;
}
public RespawnHandler getRespawnHandler()
{
return respawnHandler;
}
public SelectionHandler getSelectionHandler()
{
return selectionHandler;
}
}
| 412 | 0.979479 | 1 | 0.979479 | game-dev | MEDIA | 0.978526 | game-dev | 0.873842 | 1 | 0.873842 |
chaoticgd/wrench | 29,402 | src/assetmgr/asset_codegen.cpp | /*
wrench - A set of modding tools for the Ratchet & Clank PS2 games.
Copyright (C) 2022 chaoticgd
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <string>
#include <vector>
#undef NDEBUG
#include <assert.h>
#include <stdarg.h>
#include <string.h>
#include <platform/fileio.h>
#include <wtf/wtf.h>
#define INTEGER_ATTRIB "IntegerAttribute"
#define FLOAT_ATTRIB "FloatAttribute"
#define BOOLEAN_ATTRIB "BooleanAttribute"
#define STRING_ATTRIB "StringAttribute"
#define ARRAY_ATTRIB "ArrayAttribute"
#define VECTOR3_ATTRIB "Vector3Attribute"
#define COLOUR_ATTRIB "ColourAttribute"
#define ASSET_LINK_ATTRIB "AssetLinkAttribute"
#define FILE_REFERENCE_ATTRIB "FileReferenceAttribute"
static void generate_asset_type(const WtfNode* asset_type, int id);
static void generate_create_asset_function(const WtfNode* root);
static void generate_asset_string_to_type_function(const WtfNode* root);
static void generate_asset_type_to_string_function(const WtfNode* root);
static void generate_dispatch_table_from_asset_type_function(const WtfNode* root);
static void generate_asset_implementation(const WtfNode* asset_type);
static void generate_read_function(const WtfNode* asset_type);
static void generate_read_attribute_code(const WtfNode* node, const char* result, const char* attrib, int depth);
static void generate_attribute_type_check_code(const std::string& attribute, const char* expected, const char* name, int ind);
static void generate_write_function(const WtfNode* asset_type);
static void generate_asset_write_code(const WtfNode* node, const char* expr, int depth);
static void generate_attribute_getter_and_setter_functions(const WtfNode* asset_type);
static void generate_attribute_getter_code(const WtfNode* attribute, int depth);
static void generate_attribute_setter_code(const WtfNode* attribute, int depth);
static void generate_child_functions(const WtfNode* asset_type);
static std::string node_to_cpp_type(const WtfNode* node);
static void indent(int ind);
static void out(const char* format, ...);
static FILE* out_file = NULL;
static WrenchFileHandle* out_handle = NULL;
int main(int argc, char** argv)
{
assert(argc == 2 || argc == 3);
WrenchFileHandle* file = file_open(argv[1], WRENCH_FILE_MODE_READ);
if (!file) {
fprintf(stderr, "Failed to open input file.\n");
return 1;
}
std::vector<char> bytes;
char c;
while (file_read(&c, 1, file) == 1) {
bytes.emplace_back(c);
}
bytes.push_back(0);
file_close(file);
if (argc == 3) {
out_handle = file_open(argv[2], WRENCH_FILE_MODE_WRITE);
} else {
out_file = stdout;
}
char* error = NULL;
WtfNode* root = wtf_parse((char*) bytes.data(), &error);
if (error) {
fprintf(stderr, "Failed to parse asset schema. %s\n", error);
return 1;
}
const WtfAttribute* format_version = wtf_attribute(root, "format_version");
assert(format_version && format_version->type == WTF_NUMBER);
out("// Generated from %s. Do not edit.\n\n", argv[1]);
out("// *****************************************************************************\n");
out("// Header\n");
out("// *****************************************************************************\n\n");
out("#ifdef GENERATED_ASSET_HEADER\n\n");
out("#define ASSET_FORMAT_VERSION %d\n\n", format_version->number.i);
for (const WtfNode* node = wtf_first_child(root, "AssetType"); node != NULL; node = wtf_next_sibling(node, "AssetType")) {
out("class %sAsset;\n", node->tag);
}
out("std::unique_ptr<Asset> create_asset(AssetType type, AssetFile& file, Asset* parent, std::string tag);\n");
out("AssetType asset_string_to_type(const char* type_name);\n");
out("const char* asset_type_to_string(AssetType type);\n");
out("AssetDispatchTable* dispatch_table_from_asset_type(AssetType type);\n");
int id = 0;
for (const WtfNode* node = wtf_first_child(root, "AssetType"); node != NULL; node = wtf_next_sibling(node, "AssetType")) {
generate_asset_type(node, id++);
}
out("#endif\n\n");
out("// *****************************************************************************\n");
out("// Implementation\n");
out("// *****************************************************************************\n\n");
out("#ifdef GENERATED_ASSET_IMPLEMENTATION\n");
generate_create_asset_function(root);
generate_asset_string_to_type_function(root);
generate_asset_type_to_string_function(root);
generate_dispatch_table_from_asset_type_function(root);
const WtfNode* first_asset_type = wtf_first_child(root, "AssetType");
for (const WtfNode* node = first_asset_type; node != NULL; node = wtf_next_sibling(node, "AssetType")) {
if (node != first_asset_type) {
out("\n");
out("// *****************************************************************************\n");
}
generate_asset_implementation(node);
}
out("#endif\n");
wtf_free(root);
if (out_handle != NULL) {
file_close(out_handle);
}
}
static void generate_asset_type(const WtfNode* asset_type, int id)
{
out("class %sAsset : public Asset {\n", asset_type->tag);
int attribute_count = 0;
for (WtfNode* node = asset_type->first_child; node != NULL; node = node->next_sibling) {
std::string cpp_type = node_to_cpp_type(node);
if (!cpp_type.empty()) {
if (attribute_count == 0) {
out("\tenum {\n");
}
out("\t\tATTRIB_%s = (1 << %d),\n", node->tag, attribute_count);
attribute_count++;
}
}
if (attribute_count > 0) {
out("\t};\n");
}
// We use a bitfield to store whether each attribute exists instead of
// something like std::optional to save memory. If you need this to be
// higher turn the m_attrib_exists in the Asset class into a u64.
assert(attribute_count <= 32);
for (WtfNode* node = asset_type->first_child; node != NULL; node = node->next_sibling) {
std::string cpp_type = node_to_cpp_type(node);
if (!cpp_type.empty()) {
out("\t%s m_attribute_%s;\n", cpp_type.c_str(), node->tag);
attribute_count++;
}
}
out("\n");
out("public:\n");
out("\t%sAsset(AssetFile& file, Asset* parent, std::string tag);\n", asset_type->tag);
out("\t\n");
out("\tvoid for_each_attribute(AssetVisitorCallback callback) override {}\n");
out("\tvoid for_each_attribute(ConstAssetVisitorCallback callback) const override {}\n");
out("\tvoid read_attributes(const WtfNode* node) override;\n");
out("\tvoid write_attributes(WtfWriter* ctx) const override;\n");
out("\tvoid validate_attributes() const override {}\n");
out("\t\n");
out("\tstatic AssetDispatchTable funcs;\n");
bool first = true;
for (WtfNode* node = asset_type->first_child; node != NULL; node = node->next_sibling) {
std::string getter_name = node->tag;
assert(getter_name.size() >= 1);
if (getter_name[0] >= '0' && getter_name[0] <= '9') {
getter_name = '_' + getter_name;
}
std::string cpp_type = node_to_cpp_type(node);
if (!cpp_type.empty()) {
if (first) {
out("\t\n");
first = false;
}
out("\t\n");
out("\tbool has_%s() const;\n", getter_name.c_str());
out("\t%s %s() const;\n", cpp_type.c_str(), getter_name.c_str());
out("\t%s %s(%s def) const;\n", cpp_type.c_str(), getter_name.c_str(), cpp_type.c_str());
out("\tvoid set_%s(%s src_0);\n", node->tag, cpp_type.c_str());
}
if (strcmp(node->type_name, "Child") == 0) {
if (first) {
out("\t\n");
first = false;
}
const WtfAttribute* allowed_types = wtf_attribute(node, "allowed_types");
assert(allowed_types);
assert(allowed_types->type == WTF_ARRAY);
assert(allowed_types->first_array_element);
assert(allowed_types->first_array_element->type == WTF_STRING);
const char* child_type = allowed_types->first_array_element->string.begin;
if (allowed_types->first_array_element->next) {
out("\ttemplate <typename ChildType>\n");
} else {
out("\ttemplate <typename ChildType = %sAsset>\n", child_type);
}
out("\tChildType& %s(AssetAccessorMode mode = DO_NOT_SWITCH_FILES)\n", getter_name.c_str());
out("\t{\n");
out("\t\tif (mode == SWITCH_FILES) {\n");
out("\t\t\treturn foreign_child<ChildType>(\"%s/%s\", false, \"%s\");\n", node->tag, node->tag, node->tag);
out("\t\t} else {\n");
out("\t\t\treturn child<ChildType>(\"%s\");\n", node->tag);
out("\t\t}\n");
out("\t}\n");
if (allowed_types->first_array_element->next) {
out("\ttemplate <typename ChildType>\n");
} else {
out("\ttemplate <typename ChildType = %sAsset>\n", child_type);
}
out("\tChildType& %s(std::string path) { return foreign_child<ChildType>(path, false, \"%s\"); }\n", getter_name.c_str(), node->tag);
out("\tbool has_%s() const;\n", node->tag);
if (allowed_types->first_array_element->next) {
out("\tAsset& get_%s();\n", node->tag);
out("\tconst Asset& get_%s() const;\n", node->tag);
} else {
out("\t%sAsset& get_%s();\n", child_type, node->tag);
out("\tconst %sAsset& get_%s() const;\n", child_type, node->tag);
}
}
}
out("\t\n");
out("\tstatic const constexpr AssetType ASSET_TYPE = AssetType{%d};\n", id);
out("};\n\n");
}
static void generate_create_asset_function(const WtfNode* root)
{
out("std::unique_ptr<Asset> create_asset(AssetType type, AssetFile& file, Asset* parent, std::string tag) {\n");
out("\tswitch (type.id) {\n");
for (const WtfNode* node = wtf_first_child(root, "AssetType"); node != NULL; node = wtf_next_sibling(node, "AssetType")) {
out("\t\tcase %sAsset::ASSET_TYPE.id: return std::make_unique<%sAsset>(file, parent, std::move(tag));\n", node->tag, node->tag);
}
out("\t}\n");
out("\treturn nullptr;\n");
out("}\n\n");
}
static void generate_asset_string_to_type_function(const WtfNode* root)
{
out("AssetType asset_string_to_type(const char* type_name)\n");
out("{\n");
int id = 0;
for (const WtfNode* node = wtf_first_child(root, "AssetType"); node != NULL; node = wtf_next_sibling(node, "AssetType")) {
out("\tif (strcmp(type_name, \"%s\") == 0) return AssetType{%d};\n", node->tag, id++);
}
out("\treturn NULL_ASSET_TYPE;\n");
out("}\n\n");
}
static void generate_asset_type_to_string_function(const WtfNode* root)
{
out("const char* asset_type_to_string(AssetType type)\n");
out("{\n");
out("\tswitch (type.id) {\n");
for (const WtfNode* node = wtf_first_child(root, "AssetType"); node != NULL; node = wtf_next_sibling(node, "AssetType")) {
out("\t\tcase %sAsset::ASSET_TYPE.id: return \"%s\";\n", node->tag, node->tag);
}
out("\t}\n");
out("\treturn nullptr;\n");
out("}\n\n");
}
static void generate_dispatch_table_from_asset_type_function(const WtfNode* root)
{
out("AssetDispatchTable* dispatch_table_from_asset_type(AssetType type)\n");
out("{\n");
out("\tswitch (type.id) {\n");
for (const WtfNode* node = wtf_first_child(root, "AssetType"); node != NULL; node = wtf_next_sibling(node, "AssetType")) {
out("\t\tcase %sAsset::ASSET_TYPE.id: return &%sAsset::funcs;\n", node->tag, node->tag);
}
out("\t}\n");
out("\treturn nullptr;\n");
out("}\n\n");
}
static void generate_asset_implementation(const WtfNode* asset_type)
{
out("\n");
out("%sAsset::%sAsset(AssetFile& file, Asset* parent, std::string tag)\n", asset_type->tag, asset_type->tag);
out("\t: Asset(file, parent, ASSET_TYPE, std::move(tag), funcs)\n");
out("{\n");
const WtfAttribute* wad = wtf_attribute(asset_type, "wad");
if (wad && wad->type == WTF_BOOLEAN && wad->boolean) {
out("\tflags |= ASSET_IS_WAD;\n");
}
const WtfAttribute* level_wad = wtf_attribute(asset_type, "level_wad");
if (level_wad && level_wad->type == WTF_BOOLEAN && level_wad->boolean) {
out("\tflags |= ASSET_IS_LEVEL_WAD;\n");
}
const WtfAttribute* bin_leaf = wtf_attribute(asset_type, "bin_leaf");
if (bin_leaf && bin_leaf->type == WTF_BOOLEAN && bin_leaf->boolean) {
out("\tflags |= ASSET_IS_BIN_LEAF;\n");
}
const WtfAttribute* flattenable = wtf_attribute(asset_type, "flattenable");
if (flattenable && flattenable->type == WTF_BOOLEAN && flattenable->boolean) {
out("\tflags |= ASSET_IS_FLATTENABLE;\n");
}
out("}\n\n");
generate_read_function(asset_type);
generate_write_function(asset_type);
out("AssetDispatchTable %sAsset::funcs;\n", asset_type->tag);
generate_attribute_getter_and_setter_functions(asset_type);
generate_child_functions(asset_type);
}
static void generate_read_function(const WtfNode* asset_type)
{
bool first = true;
out("void %sAsset::read_attributes(const WtfNode* node)\n", asset_type->tag);
out("{\n");
for (WtfNode* node = asset_type->first_child; node != NULL; node = node->next_sibling) {
std::string type = node_to_cpp_type(node);
if (!type.empty()) {
if (!first) {
out("\t\n");
} else {
first = false;
}
std::string result = std::string("m_attribute_") + node->tag;
std::string attrib = std::string("attribute_") + node->tag;
out("\tconst WtfAttribute* %s = wtf_attribute(node, \"%s\");\n", attrib.c_str(), node->tag);
out("\tif (%s) {\n", attrib.c_str());
generate_read_attribute_code(node, result.c_str(), attrib.c_str(), 0);
out("\t\tm_attrib_exists |= ATTRIB_%s;\n", node->tag);
out("\t}\n");
}
}
out("}\n\n");
}
static void generate_read_attribute_code(const WtfNode* node, const char* result, const char* attrib, int depth)
{
int ind = depth + 2;
if (strcmp(node->type_name, INTEGER_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_NUMBER", node->tag, ind);
indent(ind); out("%s = %s->number.i;\n", result, attrib);
}
if (strcmp(node->type_name, FLOAT_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_NUMBER", node->tag, ind);
indent(ind); out("%s = %s->number.f;\n", result, attrib);
}
if (strcmp(node->type_name, BOOLEAN_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_BOOLEAN", node->tag, ind);
indent(ind); out("%s = %s->boolean;\n", result, attrib);
}
if (strcmp(node->type_name, STRING_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_STRING", node->tag, ind);
indent(ind); out("%s = std::string(%s->string.begin, (size_t) (%s->string.end - %s->string.begin));\n", result, attrib, attrib, attrib);
}
if (strcmp(node->type_name, ARRAY_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_ARRAY", node->tag, ind);
const WtfNode* element = wtf_child(node, NULL, "element");
assert(element);
std::string element_type = node_to_cpp_type(element);
std::string element_result = std::string("temp_") + std::to_string(depth);
std::string element_attrib = "element_" + std::to_string(depth);
indent(ind); out("for (const WtfAttribute* %s = %s->first_array_element; %s != NULL; %s = %s->next) {\n",
element_attrib.c_str(), attrib, element_attrib.c_str(), element_attrib.c_str(), element_attrib.c_str());
indent(ind); out("\t%s %s;\n", element_type.c_str(), element_result.c_str());
generate_read_attribute_code(element, element_result.c_str(), element_attrib.c_str(), depth + 1);
indent(ind); out("\t%s.emplace_back(std::move(%s));\n", result, element_result.c_str());
indent(ind); out("}\n");
}
if (strcmp(node->type_name, VECTOR3_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_ARRAY", node->tag, ind);
indent(ind); out("WtfAttribute* x_elem = %s->first_array_element;\n", attrib);
indent(ind); out("WtfAttribute* y_elem = x_elem ? x_elem->next : nullptr;\n");
indent(ind); out("WtfAttribute* z_elem = y_elem ? y_elem->next : nullptr;\n");
indent(ind); out("verify(z_elem, \"A Vector3 attribute does not have 3 elements.\");\n");
indent(ind); out("verify(x_elem->type == WTF_NUMBER, \"A Vector3 attribute has elements that aren't numbers.\");\n");
indent(ind); out("verify(y_elem->type == WTF_NUMBER, \"A Vector3 attribute has elements that aren't numbers.\");\n");
indent(ind); out("verify(z_elem->type == WTF_NUMBER, \"A Vector3 attribute has elements that aren't numbers.\");\n");
indent(ind); out("%s = glm::vec3(x_elem->number.f, y_elem->number.f, z_elem->number.f);\n", result);
}
if (strcmp(node->type_name, COLOUR_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_ARRAY", node->tag, ind);
indent(ind); out("WtfAttribute* r_elem = %s->first_array_element;\n", attrib);
indent(ind); out("WtfAttribute* g_elem = r_elem ? r_elem->next : nullptr;\n");
indent(ind); out("WtfAttribute* b_elem = g_elem ? g_elem->next : nullptr;\n");
indent(ind); out("WtfAttribute* a_elem = b_elem ? b_elem->next : nullptr;\n");
indent(ind); out("verify(a_elem, \"A Colour attribute does not have 4 elements.\");\n");
indent(ind); out("verify(r_elem->type == WTF_NUMBER, \"A Colour attribute has elements that aren't numbers.\");\n");
indent(ind); out("verify(g_elem->type == WTF_NUMBER, \"A Colour attribute has elements that aren't numbers.\");\n");
indent(ind); out("verify(b_elem->type == WTF_NUMBER, \"A Colour attribute has elements that aren't numbers.\");\n");
indent(ind); out("verify(a_elem->type == WTF_NUMBER, \"A Colour attribute has elements that aren't numbers.\");\n");
indent(ind); out("%s = glm::vec4(r_elem->number.f, g_elem->number.f, b_elem->number.f, a_elem->number.f);\n", result);
}
if (strcmp(node->type_name, ASSET_LINK_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_STRING", node->tag, ind);
indent(ind); out("%s = AssetLink();\n", result);
indent(ind); out("%s.set(%s->string.begin);\n", result, attrib);
}
if (strcmp(node->type_name, FILE_REFERENCE_ATTRIB) == 0) {
generate_attribute_type_check_code(attrib, "WTF_STRING", node->tag, ind);
indent(ind); out("%s = FileReference(file(), %s->string.begin);\n", result, attrib);
}
}
static void generate_attribute_type_check_code(const std::string& attribute, const char* expected, const char* name, int ind)
{
indent(ind); out("verify(%s->type == %s, \"Asset attribute '%s' has invalid type.\");\n",
attribute.c_str(), expected, name);
}
static void generate_write_function(const WtfNode* asset_type)
{
out("void %sAsset::write_attributes(WtfWriter* ctx) const\n", asset_type->tag);
out("{\n");
for (WtfNode* node = asset_type->first_child; node != NULL; node = node->next_sibling) {
std::string cpp_type = node_to_cpp_type(node);
if (!cpp_type.empty()) {
out("\tif (m_attrib_exists & ATTRIB_%s) {\n", node->tag);
out("\t\twtf_begin_attribute(ctx, \"%s\");\n", node->tag);
std::string expr = std::string("m_attribute_") + node->tag;
generate_asset_write_code(node, expr.c_str(), 0);
out("\t\twtf_end_attribute(ctx);\n");
out("\t}\n");
}
}
out("}\n\n");
}
static void generate_asset_write_code(const WtfNode* node, const char* expr, int depth)
{
int ind = depth + 2;
if (strcmp(node->type_name, INTEGER_ATTRIB) == 0) {
indent(ind); out("wtf_write_integer(ctx, %s);\n", expr);
}
if (strcmp(node->type_name, FLOAT_ATTRIB) == 0) {
indent(ind); out("wtf_write_float(ctx, %s);\n", expr);
}
if (strcmp(node->type_name, BOOLEAN_ATTRIB) == 0) {
indent(ind); out("wtf_write_boolean(ctx, %s);\n", expr);
}
if (strcmp(node->type_name, STRING_ATTRIB) == 0) {
indent(ind); out("wtf_write_string(ctx, %s.c_str(), %s.c_str() + %s.size());\n", expr, expr, expr);
}
if (strcmp(node->type_name, ARRAY_ATTRIB) == 0) {
const WtfNode* element = wtf_child(node, NULL, "element");
assert(element);
std::string element_expr = "element_" + std::to_string(depth);
indent(ind); out("wtf_begin_array(ctx);\n");
indent(ind); out("for (const auto& %s : %s) {\n", element_expr.c_str(), expr);
generate_asset_write_code(element, element_expr.c_str(), depth + 1);
indent(ind); out("}\n");
indent(ind); out("wtf_end_array(ctx);\n");
}
if (strcmp(node->type_name, VECTOR3_ATTRIB) == 0) {
indent(ind); out("float floats[3] = {%s.x, %s.y, %s.z};\n", expr, expr, expr);
indent(ind); out("wtf_write_floats(ctx, ARRAY_PAIR(floats));\n");
}
if (strcmp(node->type_name, COLOUR_ATTRIB) == 0) {
indent(ind); out("float floats[4] = {%s.x, %s.y, %s.z, %s.w};\n", expr, expr, expr, expr);
indent(ind); out("wtf_write_floats(ctx, ARRAY_PAIR(floats));\n");
}
if (strcmp(node->type_name, ASSET_LINK_ATTRIB) == 0) {
indent(ind); out("wtf_write_string(ctx, %s.to_string().c_str());\n", expr);
}
if (strcmp(node->type_name, FILE_REFERENCE_ATTRIB) == 0) {
indent(ind); out("std::string path_%d = %s.path.string();\n", depth, expr);
indent(ind); out("wtf_write_string(ctx, path_%d.c_str());\n", depth);
}
}
static void generate_attribute_getter_and_setter_functions(const WtfNode* asset_type)
{
for (WtfNode* node = asset_type->first_child; node != NULL; node = node->next_sibling) {
std::string cpp_type = node_to_cpp_type(node);
if (!cpp_type.empty()) {
std::string getter_name = node->tag;
assert(getter_name.size() >= 1);
if (getter_name[0] >= '0' && getter_name[0] <= '9') {
getter_name = '_' + getter_name;
}
out("bool %sAsset::has_%s() const\n", asset_type->tag, getter_name.c_str());
out("{\n");
out("\tfor (const Asset* asset = this; asset != nullptr; asset = asset->lower_precedence()) {\n");
out("\t\tif (asset->physical_type() == physical_type() && (static_cast<const %sAsset*>(asset)->m_attrib_exists & ATTRIB_%s)) {\n", asset_type->tag, node->tag);
out("\t\t\treturn true;\n");
out("\t\t}\n");
out("\t}\n");
out("\treturn false;\n");
out("}\n");
out("\n");
for (int getter_type = 0; getter_type < 2; getter_type++) {
if (getter_type == 0) {
out("%s %sAsset::%s() const\n", cpp_type.c_str(), asset_type->tag, getter_name.c_str());
out("{\n");
} else {
out("%s %sAsset::%s(%s def) const\n", cpp_type.c_str(), asset_type->tag, getter_name.c_str(), cpp_type.c_str());
out("{\n");
}
out("\tfor (const Asset* asset = &highest_precedence(); asset != nullptr; asset = asset->lower_precedence()) {\n");
out("\t\tif (asset->physical_type() == ASSET_TYPE) {\n");
out("\t\t\t%s dest_0;\n", cpp_type.c_str());
out("\t\t\tconst auto& sub = static_cast<const %sAsset&>(*asset);\n", asset_type->tag);
out("\t\t\tif (sub.m_attrib_exists & ATTRIB_%s) {\n", node->tag);
out("\t\t\t\tconst %s& src_0 = sub.m_attribute_%s;\n", cpp_type.c_str(), node->tag);
generate_attribute_getter_code(node, 0);
out("\t\t\t\treturn dest_0;\n");
out("\t\t\t}\n");
out("\t\t}\n");
out("\t}\n");
if (getter_type == 0) {
out("\tverify_not_reached(\"Asset '%%s' has missing attribute '%s'.\",\n"
"\t\tabsolute_link().to_string().c_str());\n", node->tag);
} else {
out("\treturn def;\n");
}
out("}\n");
out("\n");
}
out("void %sAsset::set_%s(%s src_0)\n", asset_type->tag, node->tag, cpp_type.c_str());
out("{\n");
out("\tassert(bank().is_writeable());\n");
out("\t%s dest_0;\n", cpp_type.c_str());
generate_attribute_setter_code(node, 0);
out("\tm_attribute_%s = std::move(dest_0);\n", node->tag);
out("\tm_attrib_exists |= ATTRIB_%s;\n", node->tag);
out("}\n");
out("\n");
}
}
}
static void generate_attribute_getter_code(const WtfNode* attribute, int depth)
{
int ind = depth + 4;
if (strcmp(attribute->type_name, INTEGER_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, FLOAT_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, BOOLEAN_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, STRING_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, ARRAY_ATTRIB) == 0) {
indent(ind); out("for (const auto& src_%d : src_%d) {\n", depth + 1, depth);
indent(ind); out("\tdecltype(dest_%d)::value_type dest_%d;\n", depth, depth + 1);
generate_attribute_getter_code(wtf_child(attribute, NULL, "element"), depth + 1);
indent(ind); out("\tdest_%d.emplace_back(std::move(dest_%d));\n", depth, depth + 1);
indent(ind); out("}\n");
}
if (strcmp(attribute->type_name, VECTOR3_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, COLOUR_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, ASSET_LINK_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, FILE_REFERENCE_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
}
static void generate_attribute_setter_code(const WtfNode* attribute, int depth)
{
int ind = depth + 1;
if (strcmp(attribute->type_name, INTEGER_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, FLOAT_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, BOOLEAN_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, STRING_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, ARRAY_ATTRIB) == 0) {
indent(ind); out("for (const auto& src_%d : src_%d) {\n", depth + 1, depth);
indent(ind); out("\tdecltype(dest_%d)::value_type dest_%d;\n", depth, depth + 1);
generate_attribute_setter_code(wtf_child(attribute, NULL, "element"), depth + 1);
indent(ind); out("\tdest_%d.emplace_back(std::move(dest_%d));\n", depth, depth + 1);
indent(ind); out("}\n");
}
if (strcmp(attribute->type_name, VECTOR3_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, COLOUR_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, ASSET_LINK_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
if (strcmp(attribute->type_name, FILE_REFERENCE_ATTRIB) == 0) {
indent(ind); out("dest_%d = src_%d;\n", depth, depth);
}
}
static void generate_child_functions(const WtfNode* asset_type)
{
for (WtfNode* node = asset_type->first_child; node != NULL; node = node->next_sibling) {
if (strcmp(node->type_name, "Child") == 0) {
std::string getter_name = node->tag;
assert(getter_name.size() >= 1);
if (getter_name[0] >= '0' && getter_name[0] <= '9') {
getter_name = '_' + getter_name;
}
const WtfAttribute* allowed_types = wtf_attribute(node, "allowed_types");
assert(allowed_types);
assert(allowed_types->type == WTF_ARRAY);
assert(allowed_types->first_array_element);
assert(allowed_types->first_array_element->type == WTF_STRING);
const char* child_type = allowed_types->first_array_element->string.begin;
out("bool %sAsset::has_%s() const\n", asset_type->tag, node->tag);
out("{\n");
out("\treturn has_child(\"%s\");\n", node->tag);
out("}\n");
out("\n");
for (int is_const = 0; is_const < 2; is_const++) {
const char* qualifier_space_after = is_const ? "const " : "";
const char* qualifier_space_before = is_const ? " const" : "";
if (allowed_types->first_array_element->next) {
out("%sAsset& %sAsset::get_%s()%s\n", qualifier_space_after, asset_type->tag, node->tag, qualifier_space_before);
out("{\n");
out("\treturn get_child(\"%s\");\n", node->tag);
} else {
out("%s%sAsset& %sAsset::get_%s()%s\n", qualifier_space_after, child_type, asset_type->tag, node->tag, qualifier_space_before);
out("{\n");
out("\treturn get_child(\"%s\").as<%sAsset>();\n", node->tag, child_type);
}
out("}\n");
out("\n");
}
}
}
}
static std::string node_to_cpp_type(const WtfNode* node)
{
if (strcmp(node->type_name, INTEGER_ATTRIB) == 0) {
return "int";
}
if (strcmp(node->type_name, FLOAT_ATTRIB) == 0) {
return "float";
}
if (strcmp(node->type_name, BOOLEAN_ATTRIB) == 0) {
return "bool";
}
if (strcmp(node->type_name, STRING_ATTRIB) == 0) {
return "std::string";
}
if (strcmp(node->type_name, ARRAY_ATTRIB) == 0) {
const WtfNode* element = wtf_child(node, NULL, "element");
assert(element);
std::string element_type = node_to_cpp_type(element);
assert(!element_type.empty());
return "std::vector<" + element_type + ">";
}
if (strcmp(node->type_name, VECTOR3_ATTRIB) == 0) {
return "glm::vec3";
}
if (strcmp(node->type_name, COLOUR_ATTRIB) == 0) {
return "glm::vec4";
}
if (strcmp(node->type_name, ASSET_LINK_ATTRIB) == 0) {
return "AssetLink";
}
if (strcmp(node->type_name, FILE_REFERENCE_ATTRIB) == 0) {
return "FileReference";
}
return "";
}
static void indent(int ind)
{
for (int i = 0; i < ind; i++) {
out("\t");
}
}
static void out(const char* format, ...)
{
va_list list;
va_start(list, format);
if (out_file != NULL) {
vfprintf(out_file, format, list);
}
if (out_handle != NULL) {
file_vprintf(out_handle, format, list);
}
va_end(list);
}
| 412 | 0.944599 | 1 | 0.944599 | game-dev | MEDIA | 0.369875 | game-dev | 0.854364 | 1 | 0.854364 |
bates64/papermario-dx | 1,518 | src/world/area_omo/omo_05/main.c | #include "omo_05.h"
EvtScript N(EVS_ExitWalk_omo_17_0) = EVT_EXIT_WALK(60, omo_05_ENTRY_0, "omo_17", omo_17_ENTRY_0);
EvtScript N(EVS_ExitWalk_omo_17_1) = EVT_EXIT_WALK(60, omo_05_ENTRY_1, "omo_17", omo_17_ENTRY_1);
EvtScript N(EVS_BindExitTriggers) = {
BindTrigger(Ref(N(EVS_ExitWalk_omo_17_0)), TRIGGER_FLOOR_ABOVE, COLLIDER_deili3, 1, 0)
BindTrigger(Ref(N(EVS_ExitWalk_omo_17_1)), TRIGGER_FLOOR_ABOVE, COLLIDER_deili4, 1, 0)
Return
End
};
EvtScript N(EVS_Main) = {
Set(GB_WorldLocation, LOCATION_SHY_GUYS_TOYBOX)
Call(SetSpriteShading, SHADING_NONE)
EVT_SETUP_CAMERA_NO_LEAD(0, 0, 0)
Call(MakeNpcs, TRUE, Ref(N(DefaultNPCs)))
ExecWait(N(EVS_MakeEntities))
ExecWait(N(EVS_SetupGizmos))
Exec(N(EVS_SetupMusic))
Call(SetGroupVisibility, MODEL_popo, MODEL_GROUP_HIDDEN)
IfGe(GB_StoryProgress, STORY_CH4_GAVE_CAKE_TO_GOURMET_GUY)
Call(RotateModel, MODEL_o331, 105, 0, 1, 0)
Call(RotateModel, MODEL_o332, 105, 0, 1, 0)
Call(RotateModel, MODEL_o333, 105, 0, 1, 0)
Call(RotateModel, MODEL_o328, 105, 0, 1, 0)
Call(RotateModel, MODEL_o329, 105, 0, 1, 0)
Call(RotateModel, MODEL_o330, 105, 0, 1, 0)
Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_tt1, COLLIDER_FLAGS_UPPER_MASK)
Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_tt2, COLLIDER_FLAGS_UPPER_MASK)
EndIf
Set(LVar0, Ref(N(EVS_BindExitTriggers)))
Exec(EnterWalk)
Wait(1)
Return
End
};
| 412 | 0.919586 | 1 | 0.919586 | game-dev | MEDIA | 0.939149 | game-dev | 0.987852 | 1 | 0.987852 |
NeotokyoRebuild/neo | 38,989 | src/game/server/NextBot/NextBotGroundLocomotion.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
// NextBotGroundLocomotion.cpp
// Basic ground-based movement for NextBotCombatCharacters
// Author: Michael Booth, February 2009
// Note: This is a refactoring of ZombieBotLocomotion from L4D
#include "cbase.h"
#include "func_break.h"
#include "func_breakablesurf.h"
#include "activitylist.h"
#include "BasePropDoor.h"
#include "nav.h"
#include "NextBot.h"
#include "NextBotGroundLocomotion.h"
#include "NextBotUtil.h"
#include "functorutils.h"
#include "SharedFunctorUtils.h"
#include "tier0/vprof.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#pragma warning( disable : 4355 ) // warning 'this' used in base member initializer list - we're using it safely
//----------------------------------------------------------------------------------------------------------
NextBotGroundLocomotion::NextBotGroundLocomotion( INextBot *bot ) : ILocomotion( bot )
{
m_nextBot = NULL;
m_ladder = NULL;
m_desiredLean.x = 0.0f;
m_desiredLean.y = 0.0f;
m_desiredLean.z = 0.0f;
m_bRecomputePostureOnCollision = false;
m_ignorePhysicsPropTimer.Invalidate();
}
//----------------------------------------------------------------------------------------------------------
NextBotGroundLocomotion::~NextBotGroundLocomotion()
{
}
//----------------------------------------------------------------------------------------------------------
/**
* Reset locomotor to initial state
*/
void NextBotGroundLocomotion::Reset( void )
{
BaseClass::Reset();
m_bRecomputePostureOnCollision = false;
m_ignorePhysicsPropTimer.Invalidate();
m_nextBot = static_cast< NextBotCombatCharacter * >( GetBot()->GetEntity() );
m_desiredSpeed = 0.0f;
m_velocity = vec3_origin;
m_acceleration = vec3_origin;
m_desiredLean.x = 0.0f;
m_desiredLean.y = 0.0f;
m_desiredLean.z = 0.0f;
m_ladder = NULL;
m_isJumping = false;
m_isJumpingAcrossGap = false;
m_ground = NULL;
m_groundNormal = Vector( 0, 0, 1.0f );
m_isClimbingUpToLedge = false;
m_isUsingFullFeetTrace = false;
m_moveVector = Vector( 1, 0, 0 );
m_priorPos = m_nextBot->GetPosition();
m_lastValidPos = m_nextBot->GetPosition();
m_inhibitObstacleAvoidanceTimer.Invalidate();
m_accumApproachVectors = vec3_origin;
m_accumApproachWeights = 0.0f;
}
//----------------------------------------------------------------------------------------------------------
/**
* Move the bot along a ladder
*/
bool NextBotGroundLocomotion::TraverseLadder( void )
{
// not climbing a ladder right now
return false;
}
//----------------------------------------------------------------------------------------------------------
/**
* Update internal state
*/
void NextBotGroundLocomotion::Update( void )
{
VPROF_BUDGET( "NextBotGroundLocomotion::Update", "NextBot" );
BaseClass::Update();
const float deltaT = GetUpdateInterval();
// apply accumulated position changes
ApplyAccumulatedApproach();
// need to do this first thing, because ground constraints, etc, can change it
Vector origPos = GetFeet();
IBody *body = GetBot()->GetBodyInterface();
if ( TraverseLadder() )
{
// bot is climbing a ladder
return;
}
if ( !body->IsPostureMobile() )
{
// sitting/lying on the ground - no slip
m_acceleration.x = 0.0f;
m_acceleration.y = 0.0f;
m_velocity.x = 0.0f;
m_velocity.y = 0.0f;
}
bool wasOnGround = IsOnGround();
if ( !body->HasActivityType( IBody::MOTION_CONTROLLED_Z ) )
{
// fall if in the air
if ( !IsOnGround() )
{
// no ground below us - fall
m_acceleration.z -= GetGravity();
}
if ( !IsClimbingOrJumping() || m_velocity.z <= 0.0f )
{
// keep us on the ground
UpdateGroundConstraint();
}
}
Vector newPos = GetFeet();
//
// Update position physics
//
Vector right( m_moveVector.y, -m_moveVector.x, 0.0f );
if ( IsOnGround() ) // || m_isClimbingUpToLedge )
{
if ( IsAttemptingToMove() )
{
float forwardSpeed = DotProduct( m_velocity, m_moveVector );
Vector forwardVelocity = forwardSpeed * m_moveVector;
Vector sideVelocity = DotProduct( m_velocity, right ) * right;
Vector frictionAccel = vec3_origin;
// only apply friction along forward direction if we are sliding backwards
if ( forwardSpeed < 0.0f )
{
frictionAccel = -GetFrictionForward() * forwardVelocity;
}
// always apply lateral friction to counteract sideslip
frictionAccel += -GetFrictionSideways() * sideVelocity;
m_acceleration.x += frictionAccel.x;
m_acceleration.y += frictionAccel.y;
}
else
{
// come to a stop if we haven't been told to move
m_acceleration = vec3_origin;
m_velocity = vec3_origin;
}
}
// compute new position, taking into account MOTION_CONTROLLED animations in progress
if ( body->HasActivityType( IBody::MOTION_CONTROLLED_XY ) )
{
m_acceleration.x = 0.0f;
m_acceleration.y = 0.0f;
m_velocity.x = GetBot()->GetEntity()->GetAbsVelocity().x;
m_velocity.y = GetBot()->GetEntity()->GetAbsVelocity().y;
}
else
{
// euler integration
m_velocity.x += m_acceleration.x * deltaT;
m_velocity.y += m_acceleration.y * deltaT;
// euler integration
newPos.x += m_velocity.x * deltaT;
newPos.y += m_velocity.y * deltaT;
}
if ( body->HasActivityType( IBody::MOTION_CONTROLLED_Z ) )
{
m_acceleration.z = 0.0f;
m_velocity.z = GetBot()->GetEntity()->GetAbsVelocity().z;
}
else
{
// euler integration
m_velocity.z += m_acceleration.z * deltaT;
// euler integration
newPos.z += m_velocity.z * deltaT;
}
// move bot to new position, resolving collisions along the way
UpdatePosition( newPos );
// set actual velocity based on position change after collision resolution step
Vector adjustedVelocity = ( GetFeet() - origPos ) / deltaT;
if ( !body->HasActivityType( IBody::MOTION_CONTROLLED_XY ) )
{
m_velocity.x = adjustedVelocity.x;
m_velocity.y = adjustedVelocity.y;
}
if ( !body->HasActivityType( IBody::MOTION_CONTROLLED_Z ) )
{
m_velocity.z = adjustedVelocity.z;
}
// collision resolution may create very high instantaneous velocities, limit it
Vector2D groundVel = m_velocity.AsVector2D();
m_actualSpeed = groundVel.NormalizeInPlace();
if ( IsOnGround() )
{
if ( m_actualSpeed > GetRunSpeed() )
{
m_actualSpeed = GetRunSpeed();
m_velocity.x = m_actualSpeed * groundVel.x;
m_velocity.y = m_actualSpeed * groundVel.y;
}
// remove downward velocity when landing on the ground
if ( !wasOnGround )
{
m_velocity.z = 0.0f;
m_acceleration.z = 0.0f;
}
}
else
{
// we're falling. if our velocity has become zero for any reason, shove it forward
const float epsilon = 1.0f;
if ( m_velocity.IsLengthLessThan( epsilon ) )
{
m_velocity = GetRunSpeed() * GetGroundMotionVector();
}
}
// update entity velocity to that of locomotor
m_nextBot->SetAbsVelocity( m_velocity );
#ifdef LEANING
// lean sideways proportional to lateral acceleration
QAngle lean = GetDesiredLean();
float sideAccel = DotProduct( right, m_acceleration );
float slide = sideAccel / GetMaxAcceleration();
// max lean depends on how fast we're actually moving
float maxLeanAngle = NextBotLeanMaxAngle.GetFloat() * m_actualSpeed / GetRunSpeed();
// actual lean angle is proportional to lateral acceleration (sliding)
float desiredSideLean = -maxLeanAngle * slide;
lean.y += ( desiredSideLean - lean.y ) * NextBotLeanRate.GetFloat() * deltaT;
SetDesiredLean( lean );
#endif // _DEBUG
// reset acceleration accumulation
m_acceleration = vec3_origin;
// debug display
if ( GetBot()->IsDebugging( NEXTBOT_LOCOMOTION ) )
{
// track position over time
if ( IsOnGround() )
{
NDebugOverlay::Cross3D( GetFeet(), 1.0f, 0, 255, 0, true, 15.0f );
}
else
{
NDebugOverlay::Cross3D( GetFeet(), 1.0f, 0, 255, 255, true, 15.0f );
}
}
}
//----------------------------------------------------------------------------------------------------------
/**
* Move directly towards given position.
* We need to do this in-air as well to land jumps.
*/
void NextBotGroundLocomotion::Approach( const Vector &rawPos, float goalWeight )
{
BaseClass::Approach( rawPos );
m_accumApproachVectors += ( rawPos - GetFeet() ) * goalWeight;
m_accumApproachWeights += goalWeight;
m_bRecomputePostureOnCollision = true;
}
//----------------------------------------------------------------------------------------------------------
void NextBotGroundLocomotion::ApplyAccumulatedApproach( void )
{
VPROF_BUDGET( "NextBotGroundLocomotion::ApplyAccumulatedApproach", "NextBot" );
Vector rawPos = GetFeet();
const float deltaT = GetUpdateInterval();
if ( deltaT <= 0.0f )
return;
if ( m_accumApproachWeights > 0.0f )
{
Vector approachDelta = m_accumApproachVectors / m_accumApproachWeights;
// limit total movement to our max speed
float maxMove = GetRunSpeed() * deltaT;
float desiredMove = approachDelta.NormalizeInPlace();
if ( desiredMove > maxMove )
{
desiredMove = maxMove;
}
rawPos += desiredMove * approachDelta;
m_accumApproachVectors = vec3_origin;
m_accumApproachWeights = 0.0f;
}
// can only move in 2D - geometry moves us up and down
Vector pos( rawPos.x, rawPos.y, GetFeet().z );
if ( !GetBot()->GetBodyInterface()->IsPostureMobile() )
{
// body is not in a movable state right now
return;
}
Vector currentPos = m_nextBot->GetPosition();
// compute unit vector to goal position
m_moveVector = pos - currentPos;
m_moveVector.z = 0.0f;
float change = m_moveVector.NormalizeInPlace();
const float epsilon = 0.001f;
if ( change < epsilon )
{
// no motion
m_forwardLean = 0.0f;
m_sideLean = 0.0f;
return;
}
/*
// lean forward/backward based on acceleration
float desiredLean = m_acceleration / NextBotLeanForwardAccel.GetFloat();
QAngle lean = GetDesiredLean();
lean.x = NextBotLeanMaxAngle.GetFloat() * clamp( desiredLean, -1.0f, 1.0f );
SetDesiredLean( lean );
*/
Vector newPos;
// if we just started a jump, don't snap to the ground - let us get in the air first
if ( DidJustJump() || !IsOnGround() )
{
if ( false && m_isClimbingUpToLedge ) // causes bots to hang in air stuck against edges
{
// drive towards the approach position in XY to help reach ledge
m_moveVector = m_ledgeJumpGoalPos - currentPos;
m_moveVector.z = 0.0f;
m_moveVector.NormalizeInPlace();
m_acceleration += GetMaxAcceleration() * m_moveVector;
}
}
else if ( IsOnGround() )
{
// on the ground - move towards the approach position
m_isClimbingUpToLedge = false;
// snap forward movement vector along floor
const Vector &groundNormal = GetGroundNormal();
Vector left( -m_moveVector.y, m_moveVector.x, 0.0f );
m_moveVector = CrossProduct( left, groundNormal );
m_moveVector.NormalizeInPlace();
// limit maximum forward speed from self-acceleration
float forwardSpeed = DotProduct( m_velocity, m_moveVector );
float maxSpeed = MIN( m_desiredSpeed, GetSpeedLimit() );
if ( forwardSpeed < maxSpeed )
{
float ratio = ( forwardSpeed <= 0.0f ) ? 0.0f : ( forwardSpeed / maxSpeed );
float governor = 1.0f - ( ratio * ratio * ratio * ratio );
// accelerate towards goal
m_acceleration += governor * GetMaxAcceleration() * m_moveVector;
}
}
}
//----------------------------------------------------------------------------------------------------------
/**
* Move the bot to the precise given position immediately,
*/
void NextBotGroundLocomotion::DriveTo( const Vector &pos )
{
BaseClass::DriveTo( pos );
m_bRecomputePostureOnCollision = true;
UpdatePosition( pos );
}
//--------------------------------------------------------------------------------------------
/*
* Trace filter solely for use with DetectCollision() below.
*/
class GroundLocomotionCollisionTraceFilter : public CTraceFilterSimple
{
public:
GroundLocomotionCollisionTraceFilter( INextBot *me, const IHandleEntity *passentity, int collisionGroup ) : CTraceFilterSimple( passentity, collisionGroup )
{
m_me = me;
}
virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )
{
if ( CTraceFilterSimple::ShouldHitEntity( pServerEntity, contentsMask ) )
{
CBaseEntity *entity = EntityFromEntityHandle( pServerEntity );
// don't collide with ourself
if ( entity && m_me->IsSelf( entity ) )
return false;
return m_me->GetLocomotionInterface()->ShouldCollideWith( entity );
}
return false;
}
INextBot *m_me;
};
//----------------------------------------------------------------------------------------------------------
/**
* Check for collisions during move and attempt to resolve them
*/
bool NextBotGroundLocomotion::DetectCollision( trace_t *pTrace, int &recursionLimit, const Vector &from, const Vector &to, const Vector &vecMins, const Vector &vecMaxs )
{
IBody *body = GetBot()->GetBodyInterface();
CBaseEntity *ignore = m_ignorePhysicsPropTimer.IsElapsed() ? NULL : m_ignorePhysicsProp;
GroundLocomotionCollisionTraceFilter filter( GetBot(), ignore, body->GetCollisionGroup() );
TraceHull( from, to, vecMins, vecMaxs, body->GetSolidMask(), &filter, pTrace );
if ( !pTrace->DidHit() )
return false;
//
// A collision occurred - resolve it
//
// bust through "flimsy" breakables and keep on going
if ( pTrace->DidHitNonWorldEntity() && pTrace->m_pEnt != NULL )
{
CBaseEntity *other = pTrace->m_pEnt;
if ( !other->MyCombatCharacterPointer() && IsEntityTraversable( other, IMMEDIATELY ) /*&& IsFlimsy( other )*/ )
{
if ( recursionLimit <= 0 )
return true;
--recursionLimit;
// break the weak breakable we collided with
CTakeDamageInfo damageInfo( GetBot()->GetEntity(), GetBot()->GetEntity(), 100.0f, DMG_CRUSH );
CalculateExplosiveDamageForce( &damageInfo, GetMotionVector(), pTrace->endpos );
other->TakeDamage( damageInfo );
// retry trace now that the breakable is out of the way
return DetectCollision( pTrace, recursionLimit, from, to, vecMins, vecMaxs );
}
}
/// @todo Only invoke OnContact() and Touch() once per collision pair
// inform other components of collision
if ( GetBot()->ShouldTouch( pTrace->m_pEnt ) )
{
GetBot()->OnContact( pTrace->m_pEnt, pTrace );
}
INextBot *them = dynamic_cast< INextBot * >( pTrace->m_pEnt );
if ( them && them->ShouldTouch( m_nextBot ) )
{
/// @todo construct mirror of trace
them->OnContact( m_nextBot );
}
else
{
pTrace->m_pEnt->Touch( GetBot()->GetEntity() );
}
return true;
}
//----------------------------------------------------------------------------------------------------------
Vector NextBotGroundLocomotion::ResolveCollision( const Vector &from, const Vector &to, int recursionLimit )
{
VPROF_BUDGET( "NextBotGroundLocomotion::ResolveCollision", "NextBotExpensive" );
IBody *body = GetBot()->GetBodyInterface();
if ( body == NULL || recursionLimit < 0 )
{
Assert( !m_bRecomputePostureOnCollision );
return to;
}
// Only bother to recompute posture if we're currently standing or crouching
if ( m_bRecomputePostureOnCollision )
{
if ( !body->IsActualPosture( IBody::STAND ) && !body->IsActualPosture( IBody::CROUCH ) )
{
m_bRecomputePostureOnCollision = false;
}
}
// get bounding limits, ignoring step-upable height
bool bPerformCrouchTest = false;
Vector mins;
Vector maxs;
if ( m_isUsingFullFeetTrace )
{
mins = body->GetHullMins();
}
else
{
mins = body->GetHullMins() + Vector( 0, 0, GetStepHeight() );
}
if ( !m_bRecomputePostureOnCollision )
{
maxs = body->GetHullMaxs();
if ( mins.z >= maxs.z )
{
// if mins.z is greater than maxs.z, the engine will Assert
// in UTIL_TraceHull, and it won't work as advertised.
mins.z = maxs.z - 2.0f;
}
}
else
{
const float halfSize = body->GetHullWidth() / 2.0f;
maxs.Init( halfSize, halfSize, body->GetStandHullHeight() );
bPerformCrouchTest = true;
}
trace_t trace;
Vector desiredGoal = to;
Vector resolvedGoal;
IBody::PostureType nPosture = IBody::STAND;
while( true )
{
bool bCollided = DetectCollision( &trace, recursionLimit, from, desiredGoal, mins, maxs );
if ( !bCollided )
{
resolvedGoal = desiredGoal;
break;
}
// If we hit really close to our target, then stop
if ( !trace.startsolid && desiredGoal.DistToSqr( trace.endpos ) < 1.0f )
{
resolvedGoal = trace.endpos;
break;
}
// Check for crouch test, if it's necessary
// Don't bother about checking for crouch if we hit an actor
// Also don't bother checking for crouch if we hit a plane that pushes us upwards
if ( bPerformCrouchTest )
{
// Don't do this work twice
bPerformCrouchTest = false;
nPosture = body->GetDesiredPosture();
if ( !trace.m_pEnt->MyNextBotPointer() && !trace.m_pEnt->IsPlayer() )
{
// Here, our standing trace hit the world or something non-breakable
// If we're not currently crouching, then see if we could travel
// the entire distance if we were crouched
if ( nPosture != IBody::CROUCH )
{
trace_t crouchTrace;
NextBotTraversableTraceFilter crouchFilter( GetBot(), ILocomotion::IMMEDIATELY );
Vector vecCrouchMax( maxs.x, maxs.y, body->GetCrouchHullHeight() );
TraceHull( from, desiredGoal, mins, vecCrouchMax, body->GetSolidMask(), &crouchFilter, &crouchTrace );
if ( crouchTrace.fraction >= 1.0f && !crouchTrace.startsolid )
{
nPosture = IBody::CROUCH;
}
}
}
else if ( nPosture == IBody::CROUCH )
{
// Here, our standing trace hit an actor
// NOTE: This test occurs almost never, based on my tests
// Converts from crouch to stand in the case where the player
// is currently crouching, *and* his first trace (with the standing hull)
// hits an actor *and* if he didn't hit that actor, he could have
// moved standing the entire way to his desired endpoint
trace_t standTrace;
NextBotTraversableTraceFilter standFilter( GetBot(), ILocomotion::IMMEDIATELY );
TraceHull( from, desiredGoal, mins, maxs, body->GetSolidMask(), &standFilter, &standTrace );
if ( standTrace.fraction >= 1.0f && !standTrace.startsolid )
{
nPosture = IBody::STAND;
}
}
// Our first trace was based on the standing hull.
// If we need be crouched, the trace was bogus; we need to do another
if ( nPosture == IBody::CROUCH )
{
maxs.z = body->GetCrouchHullHeight();
continue;
}
}
if ( trace.startsolid )
{
// stuck inside solid; don't move
if ( trace.m_pEnt && !trace.m_pEnt->IsWorld() )
{
// only ignore physics props that are not doors
if ( dynamic_cast< CPhysicsProp * >( trace.m_pEnt ) != NULL && dynamic_cast< CBasePropDoor * >( trace.m_pEnt ) == NULL )
{
IPhysicsObject *physics = trace.m_pEnt->VPhysicsGetObject();
if ( physics && physics->IsMoveable() )
{
// we've intersected a (likely moving) physics prop - ignore it for awhile so we can move out of it
m_ignorePhysicsProp = trace.m_pEnt;
m_ignorePhysicsPropTimer.Start( 1.0f );
}
}
}
// return to last known non-interpenetrating position
resolvedGoal = m_lastValidPos;
break;
}
if ( --recursionLimit <= 0 )
{
// reached recursion limit, no more adjusting allowed
resolvedGoal = trace.endpos;
break;
}
// never slide downwards/concave to avoid getting stuck in the ground
if ( trace.plane.normal.z < 0.0f )
{
trace.plane.normal.z = 0.0f;
trace.plane.normal.NormalizeInPlace();
}
// slide off of surface we hit
Vector fullMove = desiredGoal - from;
Vector leftToMove = fullMove * ( 1.0f - trace.fraction );
// obey climbing slope limit
if ( !body->HasActivityType( IBody::MOTION_CONTROLLED_Z ) &&
trace.plane.normal.z < GetTraversableSlopeLimit() &&
fullMove.z > 0.0f )
{
fullMove.z = 0.0f;
trace.plane.normal.z = 0.0f;
trace.plane.normal.NormalizeInPlace();
}
float blocked = DotProduct( trace.plane.normal, leftToMove );
Vector unconstrained = fullMove - blocked * trace.plane.normal;
if ( GetBot()->IsDebugging( NEXTBOT_LOCOMOTION ) )
{
NDebugOverlay::Line( trace.endpos,
trace.endpos + 20.0f * trace.plane.normal,
255, 0, 150, true, 15.0f );
}
// check for collisions along remainder of move
// But don't bother if we're not going to deflect much
Vector remainingMove = from + unconstrained;
if ( remainingMove.DistToSqr( trace.endpos ) < 1.0f )
{
resolvedGoal = trace.endpos;
break;
}
desiredGoal = remainingMove;
}
if ( !trace.startsolid )
{
m_lastValidPos = resolvedGoal;
}
if ( m_bRecomputePostureOnCollision )
{
m_bRecomputePostureOnCollision = false;
if ( !body->IsActualPosture( nPosture ) )
{
body->SetDesiredPosture( nPosture );
}
}
return resolvedGoal;
}
//--------------------------------------------------------------------------------------------------------
/**
* Collect the closest actors
*/
class ClosestActorsScan
{
public:
ClosestActorsScan( const Vector &spot, int team, float maxRange = 0.0f, CBaseCombatCharacter *ignore = NULL )
{
m_spot = spot;
m_team = team;
m_close = NULL;
if ( maxRange > 0.0f )
{
m_closeRangeSq = maxRange * maxRange;
}
else
{
m_closeRangeSq = 999999999.9f;
}
m_ignore = ignore;
}
bool operator() ( CBaseCombatCharacter *actor )
{
if (actor == m_ignore)
return true;
if (actor->IsAlive() && (m_team == TEAM_ANY || actor->GetTeamNumber() == m_team))
{
Vector to = actor->WorldSpaceCenter() - m_spot;
float rangeSq = to.LengthSqr();
if (rangeSq < m_closeRangeSq)
{
m_closeRangeSq = rangeSq;
m_close = actor;
}
}
return true;
}
CBaseCombatCharacter *GetActor( void ) const
{
return m_close;
}
bool IsCloserThan( float range )
{
return (m_closeRangeSq < (range * range));
}
bool IsFartherThan( float range )
{
return (m_closeRangeSq > (range * range));
}
Vector m_spot;
int m_team;
CBaseCombatCharacter *m_close;
float m_closeRangeSq;
CBaseCombatCharacter *m_ignore;
};
#ifdef SKIPME
//----------------------------------------------------------------------------------------------------------
/**
* Push away zombies that are interpenetrating
*/
Vector NextBotGroundLocomotion::ResolveZombieCollisions( const Vector &pos )
{
Vector adjustedNewPos = pos;
Infected *me = m_nextBot->MyInfectedPointer();
const float hullWidth = me->GetBodyInterface()->GetHullWidth();
// only avoid if we're actually trying to move somewhere, and are enraged
if ( me != NULL && !IsUsingLadder() && !IsClimbingOrJumping() && IsOnGround() && m_nextBot->IsAlive() && IsAttemptingToMove() /*&& GetBot()->GetBodyInterface()->IsArousal( IBody::INTENSE )*/ )
{
VPROF_BUDGET( "NextBotGroundLocomotion::ResolveZombieCollisions", "NextBot" );
const CUtlVector< CHandle< Infected > > &neighbors = me->GetNeighbors();
Vector avoid = vec3_origin;
float avoidWeight = 0.0f;
FOR_EACH_VEC( neighbors, it )
{
Infected *them = neighbors[ it ];
if ( them )
{
Vector toThem = them->GetAbsOrigin() - me->GetAbsOrigin();
toThem.z = 0.0f;
float range = toThem.NormalizeInPlace();
if ( range < hullWidth )
{
// these two infected are in contact
me->Touch( them );
// move out of contact
float penetration = hullWidth - range;
float weight = 1.0f + ( 2.0f * penetration/hullWidth );
avoid += -weight * toThem;
avoidWeight += weight;
}
}
}
if ( avoidWeight > 0.0f )
{
adjustedNewPos += 3.0f * ( avoid / avoidWeight );
}
}
return adjustedNewPos;
}
#endif // _DEBUG
//----------------------------------------------------------------------------------------------------------
/**
* Move to newPos, resolving any collisions along the way
*/
void NextBotGroundLocomotion::UpdatePosition( const Vector &newPos )
{
VPROF_BUDGET( "NextBotGroundLocomotion::UpdatePosition", "NextBot" );
if ( NextBotStop.GetBool() || (m_nextBot->GetFlags() & FL_FROZEN) != 0 || newPos == m_nextBot->GetPosition() )
{
return;
}
// avoid very nearby Actors to simulate "mushy" collisions between actors in contact with each other
//Vector adjustedNewPos = ResolveZombieCollisions( newPos );
Vector adjustedNewPos = newPos;
// check for collisions during move and resolve them
const int recursionLimit = 3;
Vector safePos = ResolveCollision( m_nextBot->GetPosition(), adjustedNewPos, recursionLimit );
// set the bot's position
if ( GetBot()->GetIntentionInterface()->IsPositionAllowed( GetBot(), safePos ) != ANSWER_NO )
{
m_nextBot->SetPosition( safePos );
}
}
//----------------------------------------------------------------------------------------------------------
/**
* Prevent bot from sliding through floor, and snap to the ground if we're very near it
*/
void NextBotGroundLocomotion::UpdateGroundConstraint( void )
{
VPROF_BUDGET( "NextBotGroundLocomotion::UpdateGroundConstraint", "NextBotExpensive" );
// if we're up on the upward arc of our jump, don't interfere by snapping to ground
// don't do ground constraint if we're climbing a ladder
if ( DidJustJump() || IsAscendingOrDescendingLadder() )
{
m_isUsingFullFeetTrace = false;
return;
}
IBody *body = GetBot()->GetBodyInterface();
if ( body == NULL )
{
return;
}
float halfWidth = body->GetHullWidth()/2.0f;
// since we only care about ground collisions, keep hull short to avoid issues with low ceilings
/// @TODO: We need to also check actual hull height to avoid interpenetrating the world
float hullHeight = GetStepHeight();
// always need tolerance even when jumping/falling to make sure we detect ground penetration
// must be at least step height to avoid 'falling' down stairs
const float stickToGroundTolerance = GetStepHeight() + 0.01f;
trace_t ground;
NextBotTraceFilterIgnoreActors filter( m_nextBot, body->GetCollisionGroup() );
TraceHull( m_nextBot->GetPosition() + Vector( 0, 0, GetStepHeight() + 0.001f ),
m_nextBot->GetPosition() + Vector( 0, 0, -stickToGroundTolerance ),
Vector( -halfWidth, -halfWidth, 0 ),
Vector( halfWidth, halfWidth, hullHeight ),
body->GetSolidMask(), &filter, &ground );
if ( ground.startsolid )
{
// we're inside the ground - bad news
if ( GetBot()->IsDebugging( NEXTBOT_LOCOMOTION ) && !( gpGlobals->framecount % 60 ) )
{
DevMsg( "%3.2f: Inside ground, ( %.0f, %.0f, %.0f )\n", gpGlobals->curtime, m_nextBot->GetPosition().x, m_nextBot->GetPosition().y, m_nextBot->GetPosition().z );
}
return;
}
if ( ground.fraction < 1.0f )
{
// there is ground below us
m_groundNormal = ground.plane.normal;
m_isUsingFullFeetTrace = false;
// zero velocity normal to the ground
float normalVel = DotProduct( m_groundNormal, m_velocity );
m_velocity -= normalVel * m_groundNormal;
// check slope limit
if ( ground.plane.normal.z < GetTraversableSlopeLimit() )
{
// too steep to stand here
// too steep to be ground - treat it like a wall hit
if ( ( m_velocity.x * ground.plane.normal.x + m_velocity.y * ground.plane.normal.y ) <= 0.0f )
{
GetBot()->OnContact( ground.m_pEnt, &ground );
}
// we're contacting some kind of ground
// zero accelerations normal to the ground
float normalAccel = DotProduct( m_groundNormal, m_acceleration );
m_acceleration -= normalAccel * m_groundNormal;
if ( GetBot()->IsDebugging( NEXTBOT_LOCOMOTION ) )
{
DevMsg( "%3.2f: NextBotGroundLocomotion - Too steep to stand here\n", gpGlobals->curtime );
NDebugOverlay::Line( GetFeet(), GetFeet() + 20.0f * ground.plane.normal, 255, 150, 0, true, 5.0f );
}
// clear out upward velocity so we don't walk up lightpoles
m_velocity.z = MIN( 0, m_velocity.z );
m_acceleration.z = MIN( 0, m_acceleration.z );
return;
}
// inform other components of collision if we didn't land on the 'world'
if ( ground.m_pEnt && !ground.m_pEnt->IsWorld() )
{
GetBot()->OnContact( ground.m_pEnt, &ground );
}
// snap us to the ground
m_nextBot->SetPosition( ground.endpos );
if ( !IsOnGround() )
{
// just landed
m_nextBot->SetGroundEntity( ground.m_pEnt );
m_ground = ground.m_pEnt;
// landing stops any jump in progress
m_isJumping = false;
m_isJumpingAcrossGap = false;
GetBot()->OnLandOnGround( ground.m_pEnt );
}
}
else
{
// not on the ground
if ( IsOnGround() )
{
GetBot()->OnLeaveGround( m_nextBot->GetGroundEntity() );
if ( !IsClimbingUpToLedge() && !IsJumpingAcrossGap() )
{
m_isUsingFullFeetTrace = true; // We're in the air and there's space below us, so use the full trace
m_acceleration.z -= GetGravity(); // start our gravity now
}
}
}
}
//----------------------------------------------------------------------------------------------------------
/*
void NextBotGroundLocomotion::StandUp( void )
{
// make sure there is room to stand
trace_t result;
const float halfSize = GetHullWidth()/3.0f;
Vector standHullMin( -halfSize, -halfSize, GetStepHeight() + 0.1f );
Vector standHullMax( halfSize, halfSize, GetStandHullHeight() );
TraceHull( GetFeet(), GetFeet(), standHullMin, standHullMax, MASK_NPCSOLID, m_nextBot, MASK_DEFAULTPLAYERSOLID, &result );
if ( result.fraction >= 1.0f && !result.startsolid )
{
m_isCrouching = false;
}
}
*/
//----------------------------------------------------------------------------------------------------------
/**
* Initiate a climb to an adjacent high ledge
*/
bool NextBotGroundLocomotion::ClimbUpToLedge( const Vector &landingGoal, const Vector &landingForward, const CBaseEntity *obstacle )
{
return false;
}
//----------------------------------------------------------------------------------------------------------
/**
* Initiate a jump across an empty volume of space to far side
*/
void NextBotGroundLocomotion::JumpAcrossGap( const Vector &landingGoal, const Vector &landingForward )
{
// can only jump if we're on the ground
if ( !IsOnGround() )
{
return;
}
IBody *body = GetBot()->GetBodyInterface();
if ( !body->StartActivity( ACT_JUMP ) )
{
// body can't jump right now
return;
}
// scale impulse to land on target
Vector toGoal = landingGoal - GetFeet();
// equation doesn't work if we're jumping upwards
float height = toGoal.z;
toGoal.z = 0.0f;
float range = toGoal.NormalizeInPlace();
// jump out at 45 degree angle
const float cos45 = 0.7071f;
// avoid division by zero
if ( height > 0.9f * range )
{
height = 0.9f * range;
}
// ballistic equation to find initial velocity assuming 45 degree inclination and landing at give range and height
float launchVel = ( range / cos45 ) / sqrt( ( 2.0f * ( range - height ) ) / GetGravity() );
Vector up( 0, 0, 1 );
Vector ahead = up + toGoal;
ahead.NormalizeInPlace();
//m_velocity = cos45 * launchVel * ahead;
m_velocity = launchVel * ahead;
m_acceleration = vec3_origin;
m_isJumping = true;
m_isJumpingAcrossGap = true;
m_isClimbingUpToLedge = false;
GetBot()->OnLeaveGround( m_nextBot->GetGroundEntity() );
}
//----------------------------------------------------------------------------------------------------------
/**
* Initiate a simple undirected jump in the air
*/
void NextBotGroundLocomotion::Jump( void )
{
// can only jump if we're on the ground
if ( !IsOnGround() )
{
return;
}
IBody *body = GetBot()->GetBodyInterface();
if ( !body->StartActivity( ACT_JUMP ) )
{
// body can't jump right now
return;
}
// jump straight up
m_velocity.z = sqrt( 2.0f * GetGravity() * GetMaxJumpHeight() );
m_isJumping = true;
m_isClimbingUpToLedge = false;
GetBot()->OnLeaveGround( m_nextBot->GetGroundEntity() );
}
//----------------------------------------------------------------------------------------------------------
/**
* Set movement speed to running
*/
void NextBotGroundLocomotion::Run( void )
{
m_desiredSpeed = GetRunSpeed();
}
//----------------------------------------------------------------------------------------------------------
/**
* Set movement speed to walking
*/
void NextBotGroundLocomotion::Walk( void )
{
m_desiredSpeed = GetWalkSpeed();
}
//----------------------------------------------------------------------------------------------------------
/**
* Set movement speed to stopeed
*/
void NextBotGroundLocomotion::Stop( void )
{
m_desiredSpeed = 0.0f;
}
//----------------------------------------------------------------------------------------------------------
/**
* Return true if standing on something
*/
bool NextBotGroundLocomotion::IsOnGround( void ) const
{
return (m_nextBot->GetGroundEntity() != NULL);
}
//----------------------------------------------------------------------------------------------------------
/**
* Invoked when bot leaves ground for any reason
*/
void NextBotGroundLocomotion::OnLeaveGround( CBaseEntity *ground )
{
m_nextBot->SetGroundEntity( NULL );
m_ground = NULL;
if ( GetBot()->IsDebugging( NEXTBOT_LOCOMOTION ) )
{
DevMsg( "%3.2f: NextBotGroundLocomotion::OnLeaveGround\n", gpGlobals->curtime );
}
}
//----------------------------------------------------------------------------------------------------------
/**
* Invoked when bot lands on the ground after being in the air
*/
void NextBotGroundLocomotion::OnLandOnGround( CBaseEntity *ground )
{
if ( GetBot()->IsDebugging( NEXTBOT_LOCOMOTION ) )
{
DevMsg( "%3.2f: NextBotGroundLocomotion::GetBot()->OnLandOnGround\n", gpGlobals->curtime );
}
}
//----------------------------------------------------------------------------------------------------------
/**
* Get maximum speed bot can reach, regardless of desired speed
*/
float NextBotGroundLocomotion::GetSpeedLimit( void ) const
{
// if we're crouched, move at reduced speed
if ( !GetBot()->GetBodyInterface()->IsActualPosture( IBody::STAND ) )
{
return 0.75f * GetRunSpeed();
}
// no limit
return 99999999.9f;
}
//----------------------------------------------------------------------------------------------------------
/**
* Climb the given ladder to the top and dismount
*/
void NextBotGroundLocomotion::ClimbLadder( const CNavLadder *ladder, const CNavArea *dismountGoal )
{
// if we're already climbing this ladder, don't restart
if ( m_ladder == ladder && m_isGoingUpLadder )
{
return;
}
m_ladder = ladder;
m_ladderDismountGoal = dismountGoal;
m_isGoingUpLadder = true;
IBody *body = GetBot()->GetBodyInterface();
if ( body )
{
// line them up to climb in XY
Vector mountSpot = m_ladder->m_bottom + m_ladder->GetNormal() * (0.75f * body->GetHullWidth());
mountSpot.z = GetBot()->GetPosition().z;
UpdatePosition( mountSpot );
body->StartActivity( ACT_CLIMB_UP, IBody::MOTION_CONTROLLED_Z );
}
}
//----------------------------------------------------------------------------------------------------------
/**
* Descend the given ladder to the bottom and dismount
*/
void NextBotGroundLocomotion::DescendLadder( const CNavLadder *ladder, const CNavArea *dismountGoal )
{
// if we're already descending this ladder, don't restart
if ( m_ladder == ladder && !m_isGoingUpLadder )
{
return;
}
m_ladder = ladder;
m_ladderDismountGoal = dismountGoal;
m_isGoingUpLadder = false;
IBody *body = GetBot()->GetBodyInterface();
if ( body )
{
// line them up to climb in XY
Vector mountSpot = m_ladder->m_top + m_ladder->GetNormal() * (0.75f * body->GetHullWidth());
mountSpot.z = GetBot()->GetPosition().z;
UpdatePosition( mountSpot );
float ladderYaw = UTIL_VecToYaw( -m_ladder->GetNormal() );
QAngle angles = m_nextBot->GetLocalAngles();
angles.y = ladderYaw;
m_nextBot->SetLocalAngles( angles );
body->StartActivity( ACT_CLIMB_DOWN, IBody::MOTION_CONTROLLED_Z );
}
}
//----------------------------------------------------------------------------------------------------------
bool NextBotGroundLocomotion::IsUsingLadder( void ) const
{
return ( m_ladder != NULL );
}
//----------------------------------------------------------------------------------------------------------
/**
* We are actually on the ladder right now, either climbing up or down
*/
bool NextBotGroundLocomotion::IsAscendingOrDescendingLadder( void ) const
{
return IsUsingLadder();
}
//----------------------------------------------------------------------------------------------------------
/**
* Return position of "feet" - point below centroid of bot at feet level
*/
const Vector &NextBotGroundLocomotion::GetFeet( void ) const
{
return m_nextBot->GetPosition();
}
//----------------------------------------------------------------------------------------------------------
const Vector & NextBotGroundLocomotion::GetAcceleration( void ) const
{
return m_acceleration;
}
//----------------------------------------------------------------------------------------------------------
void NextBotGroundLocomotion::SetAcceleration( const Vector &accel )
{
m_acceleration = accel;
}
//----------------------------------------------------------------------------------------------------------
void NextBotGroundLocomotion::SetVelocity( const Vector &vel )
{
m_velocity = vel;
}
//----------------------------------------------------------------------------------------------------------
/**
* Return current world space velocity
*/
const Vector &NextBotGroundLocomotion::GetVelocity( void ) const
{
return m_velocity;
}
//----------------------------------------------------------------------------------------------------------
/**
* Invoked when an bot reaches its MoveTo goal
*/
void NextBotGroundLocomotion::OnMoveToSuccess( const Path *path )
{
// stop
m_velocity = vec3_origin;
m_acceleration = vec3_origin;
}
//----------------------------------------------------------------------------------------------------------
/**
* Invoked when an bot fails to reach a MoveTo goal
*/
void NextBotGroundLocomotion::OnMoveToFailure( const Path *path, MoveToFailureType reason )
{
// stop
m_velocity = vec3_origin;
m_acceleration = vec3_origin;
}
//----------------------------------------------------------------------------------------------------------
bool NextBotGroundLocomotion::DidJustJump( void ) const
{
return IsClimbingOrJumping() && (m_nextBot->GetAbsVelocity().z > 0.0f);
}
//----------------------------------------------------------------------------------------------------------
/**
* Rotate body to face towards "target"
*/
void NextBotGroundLocomotion::FaceTowards( const Vector &target )
{
const float deltaT = GetUpdateInterval();
QAngle angles = m_nextBot->GetLocalAngles();
float desiredYaw = UTIL_VecToYaw( target - GetFeet() );
float angleDiff = UTIL_AngleDiff( desiredYaw, angles.y );
float deltaYaw = GetMaxYawRate() * deltaT;
if (angleDiff < -deltaYaw)
{
angles.y -= deltaYaw;
}
else if (angleDiff > deltaYaw)
{
angles.y += deltaYaw;
}
else
{
angles.y += angleDiff;
}
m_nextBot->SetLocalAngles( angles );
}
| 412 | 0.869084 | 1 | 0.869084 | game-dev | MEDIA | 0.986678 | game-dev | 0.986616 | 1 | 0.986616 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.