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
SourceEngine-CommunityEdition/source
15,338
game/shared/cstrike/bot/bot_util.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// // Author: Michael S. Booth (mike@turtlerockstudios.com), 2003 #include "cbase.h" #include "cs_shareddefs.h" #include "engine/IEngineSound.h" #include "KeyValues.h" #include "bot.h" #include "bot_util.h" #include "bot_profile.h" #include "cs_bot.h" #include <ctype.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" static int s_iBeamSprite = 0; //-------------------------------------------------------------------------------------------------------------- /** * Return true if given name is already in use by another player */ bool UTIL_IsNameTaken( const char *name, bool ignoreHumans ) { for ( int i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (player == NULL) continue; if (player->IsPlayer() && player->IsBot()) { // bots can have prefixes so we need to check the name // against the profile name instead. CCSBot *bot = dynamic_cast<CCSBot *>(player); if ( bot && bot->GetProfile()->GetName() && FStrEq(name, bot->GetProfile()->GetName())) { return true; } } else { if (!ignoreHumans) { if (FStrEq( name, player->GetPlayerName() )) return true; } } } return false; } //-------------------------------------------------------------------------------------------------------------- int UTIL_ClientsInGame( void ) { int count = 0; for ( int i = 1; i <= gpGlobals->maxClients; ++i ) { CBaseEntity *player = UTIL_PlayerByIndex( i ); if (player == NULL) continue; count++; } return count; } //-------------------------------------------------------------------------------------------------------------- /** * Return the number of non-bots on the given team */ int UTIL_HumansOnTeam( int teamID, bool isAlive ) { int count = 0; for ( int i = 1; i <= gpGlobals->maxClients; ++i ) { CBaseEntity *entity = UTIL_PlayerByIndex( i ); if ( entity == NULL ) continue; CBasePlayer *player = static_cast<CBasePlayer *>( entity ); if (player->IsBot()) continue; if (player->GetTeamNumber() != teamID) continue; if (isAlive && !player->IsAlive()) continue; count++; } return count; } //-------------------------------------------------------------------------------------------------------------- int UTIL_BotsInGame( void ) { int count = 0; for (int i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>(UTIL_PlayerByIndex( i )); if ( player == NULL ) continue; if ( !player->IsBot() ) continue; count++; } return count; } //-------------------------------------------------------------------------------------------------------------- /** * Kick a bot from the given team. If no bot exists on the team, return false. */ bool UTIL_KickBotFromTeam( int kickTeam ) { int i; // try to kick a dead bot first for ( i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (player == NULL) continue; if (!player->IsBot()) continue; if (!player->IsAlive() && player->GetTeamNumber() == kickTeam) { // its a bot on the right team - kick it engine->ServerCommand( UTIL_VarArgs( "kick \"%s\"\n", player->GetPlayerName() ) ); return true; } } // no dead bots, kick any bot on the given team for ( i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (player == NULL) continue; if (!player->IsBot()) continue; if (player->GetTeamNumber() == kickTeam) { // its a bot on the right team - kick it engine->ServerCommand( UTIL_VarArgs( "kick \"%s\"\n", player->GetPlayerName() ) ); return true; } } return false; } //-------------------------------------------------------------------------------------------------------------- /** * Return true if all of the members of the given team are bots */ bool UTIL_IsTeamAllBots( int team ) { int botCount = 0; for( int i=1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (player == NULL) continue; // skip players on other teams if (player->GetTeamNumber() != team) continue; // if not a bot, fail the test if (!player->IsBot()) return false; // is a bot on given team ++botCount; } // if team is empty, there are no bots return (botCount) ? true : false; } //-------------------------------------------------------------------------------------------------------------- /** * Return the closest active player to the given position. * If 'distance' is non-NULL, the distance to the closest player is returned in it. */ extern CBasePlayer *UTIL_GetClosestPlayer( const Vector &pos, float *distance ) { CBasePlayer *closePlayer = NULL; float closeDistSq = 999999999999.9f; for ( int i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (!IsEntityValid( player )) continue; if (!player->IsAlive()) continue; Vector playerOrigin = GetCentroid( player ); float distSq = (playerOrigin - pos).LengthSqr(); if (distSq < closeDistSq) { closeDistSq = distSq; closePlayer = static_cast<CBasePlayer *>( player ); } } if (distance) *distance = (float)sqrt( closeDistSq ); return closePlayer; } //-------------------------------------------------------------------------------------------------------------- /** * Return the closest active player on the given team to the given position. * If 'distance' is non-NULL, the distance to the closest player is returned in it. */ extern CBasePlayer *UTIL_GetClosestPlayer( const Vector &pos, int team, float *distance ) { CBasePlayer *closePlayer = NULL; float closeDistSq = 999999999999.9f; for ( int i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (!IsEntityValid( player )) continue; if (!player->IsAlive()) continue; if (player->GetTeamNumber() != team) continue; Vector playerOrigin = GetCentroid( player ); float distSq = (playerOrigin - pos).LengthSqr(); if (distSq < closeDistSq) { closeDistSq = distSq; closePlayer = static_cast<CBasePlayer *>( player ); } } if (distance) *distance = (float)sqrt( closeDistSq ); return closePlayer; } //-------------------------------------------------------------------------------------------------------------- // Takes the bot pointer and constructs the net name using the current bot name prefix. void UTIL_ConstructBotNetName( char *name, int nameLength, const BotProfile *profile ) { if (profile == NULL) { name[0] = 0; return; } // if there is no bot prefix just use the profile name. if ((cv_bot_prefix.GetString() == NULL) || (strlen(cv_bot_prefix.GetString()) == 0)) { Q_strncpy( name, profile->GetName(), nameLength ); return; } // find the highest difficulty const char *diffStr = BotDifficultyName[0]; for ( int i=BOT_EXPERT; i>0; --i ) { if ( profile->IsDifficulty( (BotDifficultyType)i ) ) { diffStr = BotDifficultyName[i]; break; } } const char *weaponStr = NULL; if ( profile->GetWeaponPreferenceCount() ) { weaponStr = profile->GetWeaponPreferenceAsString( 0 ); const char *translatedAlias = GetTranslatedWeaponAlias( weaponStr ); char wpnName[128]; Q_snprintf( wpnName, sizeof( wpnName ), "weapon_%s", translatedAlias ); WEAPON_FILE_INFO_HANDLE hWpnInfo = LookupWeaponInfoSlot( wpnName ); if ( hWpnInfo != GetInvalidWeaponInfoHandle() ) { CCSWeaponInfo *pWeaponInfo = dynamic_cast< CCSWeaponInfo* >( GetFileWeaponInfoFromHandle( hWpnInfo ) ); if ( pWeaponInfo ) { CSWeaponType weaponType = pWeaponInfo->m_WeaponType; weaponStr = WeaponClassAsString( weaponType ); } } } if ( !weaponStr ) { weaponStr = ""; } char skillStr[16]; Q_snprintf( skillStr, sizeof( skillStr ), "%.0f", profile->GetSkill()*100 ); char temp[MAX_PLAYER_NAME_LENGTH*2]; char prefix[MAX_PLAYER_NAME_LENGTH*2]; Q_strncpy( temp, cv_bot_prefix.GetString(), sizeof( temp ) ); Q_StrSubst( temp, "<difficulty>", diffStr, prefix, sizeof( prefix ) ); Q_StrSubst( prefix, "<weaponclass>", weaponStr, temp, sizeof( temp ) ); Q_StrSubst( temp, "<skill>", skillStr, prefix, sizeof( prefix ) ); Q_snprintf( name, nameLength, "%s %s", prefix, profile->GetName() ); } //-------------------------------------------------------------------------------------------------------------- /** * Return true if anyone on the given team can see the given spot */ bool UTIL_IsVisibleToTeam( const Vector &spot, int team ) { for( int i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (player == NULL) continue; if (!player->IsAlive()) continue; if (player->GetTeamNumber() != team) continue; trace_t result; UTIL_TraceLine( player->EyePosition(), spot, CONTENTS_SOLID, player, COLLISION_GROUP_NONE, &result ); if (result.fraction == 1.0f) return true; } return false; } //------------------------------------------------------------------------------------------------------------ void UTIL_DrawBeamFromEnt( int i, Vector vecEnd, int iLifetime, byte bRed, byte bGreen, byte bBlue ) { /* BOTPORT: What is the replacement for MESSAGE_BEGIN? MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecEnd ); // vecEnd = origin??? WRITE_BYTE( TE_BEAMENTPOINT ); WRITE_SHORT( i ); WRITE_COORD( vecEnd.x ); WRITE_COORD( vecEnd.y ); WRITE_COORD( vecEnd.z ); WRITE_SHORT( s_iBeamSprite ); WRITE_BYTE( 0 ); // startframe WRITE_BYTE( 0 ); // framerate WRITE_BYTE( iLifetime ); // life WRITE_BYTE( 10 ); // width WRITE_BYTE( 0 ); // noise WRITE_BYTE( bRed ); // r, g, b WRITE_BYTE( bGreen ); // r, g, b WRITE_BYTE( bBlue ); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 0 ); // speed MESSAGE_END(); */ } //------------------------------------------------------------------------------------------------------------ void UTIL_DrawBeamPoints( Vector vecStart, Vector vecEnd, int iLifetime, byte bRed, byte bGreen, byte bBlue ) { NDebugOverlay::Line( vecStart, vecEnd, bRed, bGreen, bBlue, true, 0.1f ); /* MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecStart ); WRITE_BYTE( TE_BEAMPOINTS ); WRITE_COORD( vecStart.x ); WRITE_COORD( vecStart.y ); WRITE_COORD( vecStart.z ); WRITE_COORD( vecEnd.x ); WRITE_COORD( vecEnd.y ); WRITE_COORD( vecEnd.z ); WRITE_SHORT( s_iBeamSprite ); WRITE_BYTE( 0 ); // startframe WRITE_BYTE( 0 ); // framerate WRITE_BYTE( iLifetime ); // life WRITE_BYTE( 10 ); // width WRITE_BYTE( 0 ); // noise WRITE_BYTE( bRed ); // r, g, b WRITE_BYTE( bGreen ); // r, g, b WRITE_BYTE( bBlue ); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 0 ); // speed MESSAGE_END(); */ } //------------------------------------------------------------------------------------------------------------ void CONSOLE_ECHO( const char * pszMsg, ... ) { va_list argptr; static char szStr[1024]; va_start( argptr, pszMsg ); vsprintf( szStr, pszMsg, argptr ); va_end( argptr ); Msg( "%s", szStr ); } //------------------------------------------------------------------------------------------------------------ void BotPrecache( void ) { s_iBeamSprite = CBaseEntity::PrecacheModel( "sprites/smoke.spr" ); } //------------------------------------------------------------------------------------------------------------ #define COS_TABLE_SIZE 256 static float cosTable[ COS_TABLE_SIZE ]; void InitBotTrig( void ) { for( int i=0; i<COS_TABLE_SIZE; ++i ) { float angle = (float)(2.0f * M_PI * i / (float)(COS_TABLE_SIZE-1)); cosTable[i] = (float)cos( angle ); } } float BotCOS( float angle ) { angle = AngleNormalizePositive( angle ); int i = (int)( angle * (COS_TABLE_SIZE-1) / 360.0f ); return cosTable[i]; } float BotSIN( float angle ) { angle = AngleNormalizePositive( angle - 90 ); int i = (int)( angle * (COS_TABLE_SIZE-1) / 360.0f ); return cosTable[i]; } //-------------------------------------------------------------------------------------------------------------- /** * Send a "hint" message to all players, dead or alive. */ void HintMessageToAllPlayers( const char *message ) { hudtextparms_t textParms; textParms.x = -1.0f; textParms.y = -1.0f; textParms.fadeinTime = 1.0f; textParms.fadeoutTime = 5.0f; textParms.holdTime = 5.0f; textParms.fxTime = 0.0f; textParms.r1 = 100; textParms.g1 = 255; textParms.b1 = 100; textParms.r2 = 255; textParms.g2 = 255; textParms.b2 = 255; textParms.effect = 0; textParms.channel = 0; UTIL_HudMessageAll( textParms, message ); } //-------------------------------------------------------------------------------------------------------------------- /** * Return true if moving from "start" to "finish" will cross a player's line of fire. * The path from "start" to "finish" is assumed to be a straight line. * "start" and "finish" are assumed to be points on the ground. */ bool IsCrossingLineOfFire( const Vector &start, const Vector &finish, CBaseEntity *ignore, int ignoreTeam ) { for ( int p=1; p <= gpGlobals->maxClients; ++p ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( p ) ); if (!IsEntityValid( player )) continue; if (player == ignore) continue; if (!player->IsAlive()) continue; if (ignoreTeam && player->GetTeamNumber() == ignoreTeam) continue; // compute player's unit aiming vector Vector viewForward; AngleVectors( player->EyeAngles() + player->GetPunchAngle(), &viewForward ); const float longRange = 5000.0f; Vector playerOrigin = GetCentroid( player ); Vector playerTarget = playerOrigin + longRange * viewForward; Vector result( 0, 0, 0 ); if (IsIntersecting2D( start, finish, playerOrigin, playerTarget, &result )) { // simple check to see if intersection lies in the Z range of the path float loZ, hiZ; if (start.z < finish.z) { loZ = start.z; hiZ = finish.z; } else { loZ = finish.z; hiZ = start.z; } if (result.z >= loZ && result.z <= hiZ + HumanHeight) return true; } } return false; } //-------------------------------------------------------------------------------------------------------------- /** * Performs a simple case-insensitive string comparison, honoring trailing * wildcards */ bool WildcardMatch( const char *query, const char *test ) { if ( !query || !test ) return false; while ( *test && *query ) { char nameChar = *test; char queryChar = *query; if ( tolower(nameChar) != tolower(queryChar) ) // case-insensitive break; ++test; ++query; } if ( *query == 0 && *test == 0 ) return true; // Support trailing * if ( *query == '*' ) return true; return false; }
1
0.81809
1
0.81809
game-dev
MEDIA
0.798016
game-dev,networking
0.966593
1
0.966593
folgerwang/UnrealEngine
16,154
Engine/Source/Editor/BlueprintGraph/Private/K2Node_DynamicCast.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "K2Node_DynamicCast.h" #include "UObject/Interface.h" #include "Engine/Blueprint.h" #include "Framework/Commands/UIAction.h" #include "Framework/MultiBox/MultiBoxBuilder.h" #include "EdGraphSchema_K2.h" #include "BlueprintEditorSettings.h" #include "Kismet2/CompilerResultsLog.h" #include "DynamicCastHandler.h" #include "EditorCategoryUtils.h" #include "Kismet2/KismetEditorUtilities.h" #include "ScopedTransaction.h" #define LOCTEXT_NAMESPACE "K2Node_DynamicCast" namespace UK2Node_DynamicCastImpl { static const FName CastSuccessPinName("bSuccess"); } UK2Node_DynamicCast::UK2Node_DynamicCast(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , bIsPureCast(false) { } void UK2Node_DynamicCast::AllocateDefaultPins() { const bool bReferenceObsoleteClass = TargetType && TargetType->HasAnyClassFlags(CLASS_NewerVersionExists); if (bReferenceObsoleteClass) { Message_Error(FString::Printf(TEXT("Node '%s' references obsolete class '%s'"), *GetPathName(), *TargetType->GetPathName())); } ensure(!bReferenceObsoleteClass); const UEdGraphSchema_K2* K2Schema = Cast<UEdGraphSchema_K2>(GetSchema()); check(K2Schema != nullptr); if (!K2Schema->DoesGraphSupportImpureFunctions(GetGraph())) { bIsPureCast = true; } if (!bIsPureCast) { // Input - Execution Pin CreatePin(EGPD_Input, UEdGraphSchema_K2::PC_Exec, UEdGraphSchema_K2::PN_Execute); // Output - Execution Pins CreatePin(EGPD_Output, UEdGraphSchema_K2::PC_Exec, UEdGraphSchema_K2::PN_CastSucceeded); CreatePin(EGPD_Output, UEdGraphSchema_K2::PC_Exec, UEdGraphSchema_K2::PN_CastFailed); } // Input - Source type Pin CreatePin(EGPD_Input, UEdGraphSchema_K2::PC_Wildcard, UObject::StaticClass(), UEdGraphSchema_K2::PN_ObjectToCast); // Output - Data Pin if (TargetType) { const FString CastResultPinName = UEdGraphSchema_K2::PN_CastedValuePrefix + TargetType->GetDisplayNameText().ToString(); if (TargetType->IsChildOf(UInterface::StaticClass())) { CreatePin(EGPD_Output, UEdGraphSchema_K2::PC_Interface, *TargetType, *CastResultPinName); } else { CreatePin(EGPD_Output, UEdGraphSchema_K2::PC_Object, *TargetType, *CastResultPinName); } } UEdGraphPin* BoolSuccessPin = CreatePin(EGPD_Output, UEdGraphSchema_K2::PC_Boolean, UK2Node_DynamicCastImpl::CastSuccessPinName); BoolSuccessPin->bHidden = !bIsPureCast; Super::AllocateDefaultPins(); } FLinearColor UK2Node_DynamicCast::GetNodeTitleColor() const { return FLinearColor(0.0f, 0.55f, 0.62f); } FSlateIcon UK2Node_DynamicCast::GetIconAndTint(FLinearColor& OutColor) const { static FSlateIcon Icon("EditorStyle", "GraphEditor.Cast_16x"); return Icon; } FText UK2Node_DynamicCast::GetNodeTitle(ENodeTitleType::Type TitleType) const { if (TargetType == nullptr) { return NSLOCTEXT("K2Node_DynamicCast", "BadCastNode", "Bad cast node"); } else if (CachedNodeTitle.IsOutOfDate(this)) { // If casting to BP class, use BP name not class name (ie. remove the _C) FString TargetName; UBlueprint* CastToBP = UBlueprint::GetBlueprintFromClass(TargetType); if (CastToBP != NULL) { TargetName = CastToBP->GetName(); } else { TargetName = TargetType->GetName(); } FFormatNamedArguments Args; Args.Add(TEXT("TargetName"), FText::FromString(TargetName)); // FText::Format() is slow, so we cache this to save on performance CachedNodeTitle.SetCachedText(FText::Format(NSLOCTEXT("K2Node_DynamicCast", "CastTo", "Cast To {TargetName}"), Args), this); } return CachedNodeTitle; } void UK2Node_DynamicCast::GetContextMenuActions(const FGraphNodeContextMenuBuilder& Context) const { Super::GetContextMenuActions(Context); if (!Context.bIsDebugging) { Context.MenuBuilder->BeginSection("K2NodeDynamicCast", LOCTEXT("DynamicCastHeader", "Cast")); { FText MenuEntryTitle = LOCTEXT("MakePureTitle", "Convert to pure cast"); FText MenuEntryTooltip = LOCTEXT("MakePureTooltip", "Removes the execution pins to make the node more versatile (NOTE: the cast could still fail, resulting in an invalid output)."); bool bCanTogglePurity = true; auto CanExecutePurityToggle = [](bool const bInCanTogglePurity)->bool { return bInCanTogglePurity; }; if (bIsPureCast) { MenuEntryTitle = LOCTEXT("MakeImpureTitle", "Convert to impure cast"); MenuEntryTooltip = LOCTEXT("MakeImpureTooltip", "Adds in branching execution pins so that you can separatly handle when the cast fails/succeeds."); const UEdGraphSchema_K2* K2Schema = Cast<UEdGraphSchema_K2>(GetSchema()); check(K2Schema != nullptr); bCanTogglePurity = K2Schema->DoesGraphSupportImpureFunctions(GetGraph()); if (!bCanTogglePurity) { MenuEntryTooltip = LOCTEXT("CannotMakeImpureTooltip", "This graph does not support impure calls (and you should therefore test the cast's result for validity)."); } } Context.MenuBuilder->AddMenuEntry( MenuEntryTitle, MenuEntryTooltip, FSlateIcon(), FUIAction( FExecuteAction::CreateUObject(this, &UK2Node_DynamicCast::TogglePurity), FCanExecuteAction::CreateStatic(CanExecutePurityToggle, bCanTogglePurity), FIsActionChecked() ) ); } Context.MenuBuilder->EndSection(); } } void UK2Node_DynamicCast::PostReconstructNode() { Super::PostReconstructNode(); // update the pin name (to "Interface" if an interface is connected) NotifyPinConnectionListChanged(GetCastSourcePin()); } void UK2Node_DynamicCast::PostPlacedNewNode() { Super::PostPlacedNewNode(); const UBlueprintEditorSettings* BlueprintSettings = GetDefault<UBlueprintEditorSettings>(); SetPurity(BlueprintSettings->bFavorPureCastNodes); } UEdGraphPin* UK2Node_DynamicCast::GetValidCastPin() const { UEdGraphPin* Pin = FindPin(UEdGraphSchema_K2::PN_CastSucceeded); check((Pin != nullptr) || bIsPureCast); check((Pin == nullptr) || (Pin->Direction == EGPD_Output)); return Pin; } UEdGraphPin* UK2Node_DynamicCast::GetInvalidCastPin() const { UEdGraphPin* Pin = FindPin(UEdGraphSchema_K2::PN_CastFailed); check((Pin != nullptr) || bIsPureCast); check((Pin == nullptr) || (Pin->Direction == EGPD_Output)); return Pin; } UEdGraphPin* UK2Node_DynamicCast::GetCastResultPin() const { if(TargetType != nullptr) { for (int32 PinIdx = 0; PinIdx < Pins.Num(); PinIdx++) { if (Pins[PinIdx]->PinType.PinSubCategoryObject == *TargetType && Pins[PinIdx]->Direction == EGPD_Output && Pins[PinIdx]->PinName.ToString().StartsWith(UEdGraphSchema_K2::PN_CastedValuePrefix)) { return Pins[PinIdx]; } } } return nullptr; } UEdGraphPin* UK2Node_DynamicCast::GetCastSourcePin() const { UEdGraphPin* Pin = FindPin(UEdGraphSchema_K2::PN_ObjectToCast); check(Pin); check(Pin->Direction == EGPD_Input); return Pin; } UEdGraphPin* UK2Node_DynamicCast::GetBoolSuccessPin() const { UEdGraphPin* Pin = FindPin(UK2Node_DynamicCastImpl::CastSuccessPinName); check((Pin == nullptr) || (Pin->Direction == EGPD_Output)); return Pin; } void UK2Node_DynamicCast::SetPurity(bool bNewPurity) { if (bNewPurity != bIsPureCast) { bIsPureCast = bNewPurity; bool const bHasBeenConstructed = (Pins.Num() > 0); if (bHasBeenConstructed) { ReconstructNode(); } } } void UK2Node_DynamicCast::TogglePurity() { const FText TransactionTitle = bIsPureCast ? LOCTEXT("TogglePurityToImpure", "Convert to Impure Cast") : LOCTEXT("TogglePurityToPure", "Convert to Pure Cast"); const FScopedTransaction Transaction( TransactionTitle ); Modify(); SetPurity(!bIsPureCast); } UK2Node::ERedirectType UK2Node_DynamicCast::DoPinsMatchForReconstruction(const UEdGraphPin* NewPin, int32 NewPinIndex, const UEdGraphPin* OldPin, int32 OldPinIndex) const { ERedirectType RedirectType = Super::DoPinsMatchForReconstruction(NewPin, NewPinIndex, OldPin, OldPinIndex); if((ERedirectType_None == RedirectType) && (NULL != NewPin) && (NULL != OldPin)) { const bool bProperPrefix = NewPin->PinName.ToString().StartsWith(UEdGraphSchema_K2::PN_CastedValuePrefix, ESearchCase::CaseSensitive) && OldPin->PinName.ToString().StartsWith(UEdGraphSchema_K2::PN_CastedValuePrefix, ESearchCase::CaseSensitive); const bool bClassMatch = NewPin->PinType.PinSubCategoryObject.IsValid() && (NewPin->PinType.PinSubCategoryObject == OldPin->PinType.PinSubCategoryObject); if(bProperPrefix && bClassMatch) { RedirectType = ERedirectType_Name; } } return RedirectType; } FNodeHandlingFunctor* UK2Node_DynamicCast::CreateNodeHandler(FKismetCompilerContext& CompilerContext) const { return new FKCHandler_DynamicCast(CompilerContext, KCST_DynamicCast); } bool UK2Node_DynamicCast::HasExternalDependencies(TArray<class UStruct*>* OptionalOutput) const { const UBlueprint* SourceBlueprint = GetBlueprint(); UClass* SourceClass = *TargetType; const bool bResult = (SourceClass != NULL) && (SourceClass->ClassGeneratedBy != SourceBlueprint); if (bResult && OptionalOutput) { OptionalOutput->AddUnique(SourceClass); } const bool bSuperResult = Super::HasExternalDependencies(OptionalOutput); return bSuperResult || bResult; } FText UK2Node_DynamicCast::GetMenuCategory() const { static FNodeTextCache CachedCategory; if (CachedCategory.IsOutOfDate(this)) { // FText::Format() is slow, so we cache this to save on performance CachedCategory.SetCachedText(FEditorCategoryUtils::BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("ActionMenuCategory", "Casting")), this); } return CachedCategory; } FBlueprintNodeSignature UK2Node_DynamicCast::GetSignature() const { FBlueprintNodeSignature NodeSignature = Super::GetSignature(); NodeSignature.AddSubObject(TargetType); return NodeSignature; } bool UK2Node_DynamicCast::IsConnectionDisallowed(const UEdGraphPin* MyPin, const UEdGraphPin* OtherPin, FString& OutReason) const { bool bIsDisallowed = Super::IsConnectionDisallowed(MyPin, OtherPin, OutReason); if (MyPin == GetCastSourcePin()) { const FEdGraphPinType& OtherPinType = OtherPin->PinType; const FText OtherPinName = OtherPin->PinFriendlyName.IsEmpty() ? FText::FromName(OtherPin->PinName) : OtherPin->PinFriendlyName; if (OtherPinType.IsContainer()) { bIsDisallowed = true; OutReason = LOCTEXT("CannotContainerCast", "You cannot cast containers of objects.").ToString(); } else if (TargetType == nullptr) { bIsDisallowed = true; OutReason = LOCTEXT("InvalidTargetType", "This cast has an invalid target type (was the class deleted without a redirect?).").ToString(); } else if ((OtherPinType.PinCategory == UEdGraphSchema_K2::PC_Interface) || TargetType->HasAnyClassFlags(CLASS_Interface)) { // allow all interface casts } else if (OtherPinType.PinCategory == UEdGraphSchema_K2::PC_Object) { // let's handle wasted cast inputs with warnings in ValidateNodeDuringCompilation() instead } else { bIsDisallowed = true; OutReason = LOCTEXT("NonObjectCast", "You can only cast objects/interfaces.").ToString(); } } return bIsDisallowed; } void UK2Node_DynamicCast::NotifyPinConnectionListChanged(UEdGraphPin* Pin) { Super::NotifyPinConnectionListChanged(Pin); if (Pin == GetCastSourcePin()) { Pin->PinFriendlyName = FText::GetEmpty(); FEdGraphPinType& InputPinType = Pin->PinType; if (Pin->LinkedTo.Num() == 0) { InputPinType.PinCategory = UEdGraphSchema_K2::PC_Wildcard; InputPinType.PinSubCategory = NAME_None; InputPinType.PinSubCategoryObject = nullptr; } else { const FEdGraphPinType& ConnectedPinType = Pin->LinkedTo[0]->PinType; if (ConnectedPinType.PinCategory == UEdGraphSchema_K2::PC_Interface) { Pin->PinFriendlyName = LOCTEXT("InterfaceInputName", "Interface"); InputPinType.PinCategory = UEdGraphSchema_K2::PC_Interface; InputPinType.PinSubCategoryObject = ConnectedPinType.PinSubCategoryObject; } else if (ConnectedPinType.PinCategory == UEdGraphSchema_K2::PC_Object) { InputPinType.PinCategory = UEdGraphSchema_K2::PC_Object; InputPinType.PinSubCategoryObject = UObject::StaticClass(); } } } } void UK2Node_DynamicCast::ReallocatePinsDuringReconstruction(TArray<UEdGraphPin*>& OldPins) { Super::ReallocatePinsDuringReconstruction(OldPins); // Update exec pins if we converted from impure to pure ReconnectPureExecPins(OldPins); } void UK2Node_DynamicCast::ValidateNodeDuringCompilation(FCompilerResultsLog& MessageLog) const { Super::ValidateNodeDuringCompilation(MessageLog); UEdGraphPin* SourcePin = GetCastSourcePin(); if (SourcePin->LinkedTo.Num() > 0) { UClass* SourceType = *TargetType; if (SourceType == nullptr) { return; } SourceType = SourceType->GetAuthoritativeClass(); for (UEdGraphPin* CastInput : SourcePin->LinkedTo) { const FEdGraphPinType& SourcePinType = CastInput->PinType; if (SourcePinType.PinCategory != UEdGraphSchema_K2::PC_Object) { // all other types should have been rejected by IsConnectionDisallowed() continue; } UClass* SourceClass = Cast<UClass>(SourcePinType.PinSubCategoryObject.Get()); if ((SourceClass == nullptr) && (SourcePinType.PinSubCategory == UEdGraphSchema_K2::PSC_Self)) { if (UK2Node* K2Node = Cast<UK2Node>(CastInput->GetOwningNode())) { SourceClass = K2Node->GetBlueprint()->GeneratedClass; } } if (SourceClass == nullptr) { const FString SourcePinName = CastInput->PinFriendlyName.IsEmpty() ? CastInput->PinName.ToString() : CastInput->PinFriendlyName.ToString(); FText const ErrorFormat = LOCTEXT("BadCastInputFmt", "'{0}' does not have a clear object type (invalid input into @@)."); MessageLog.Error( *FText::Format(ErrorFormat, FText::FromString(SourcePinName)).ToString(), this ); continue; } SourceClass = SourceClass->GetAuthoritativeClass(); if (SourceClass == SourceType) { const FString SourcePinName = CastInput->PinFriendlyName.IsEmpty() ? CastInput->PinName.ToString() : CastInput->PinFriendlyName.ToString(); FText const WarningFormat = LOCTEXT("EqualObjectCastFmt", "'{0}' is already a '{1}', you don't need @@."); MessageLog.Note( *FText::Format(WarningFormat, FText::FromString(SourcePinName), TargetType->GetDisplayNameText()).ToString(), this ); } else if (SourceClass->IsChildOf(SourceType)) { const FString SourcePinName = CastInput->PinFriendlyName.IsEmpty() ? CastInput->PinName.ToString() : CastInput->PinFriendlyName.ToString(); FText const WarningFormat = LOCTEXT("UnneededObjectCastFmt", "'{0}' is already a '{1}' (which inherits from '{2}'), so you don't need @@."); MessageLog.Note( *FText::Format(WarningFormat, FText::FromString(SourcePinName), SourceClass->GetDisplayNameText(), TargetType->GetDisplayNameText()).ToString(), this ); } else if (!SourceType->IsChildOf(SourceClass) && !FKismetEditorUtilities::IsClassABlueprintInterface(SourceType)) { FText const WarningFormat = LOCTEXT("DisallowedObjectCast", "'{0}' does not inherit from '{1}' (@@ would always fail)."); MessageLog.Warning( *FText::Format(WarningFormat, TargetType->GetDisplayNameText(), SourceClass->GetDisplayNameText()).ToString(), this ); } } } } bool UK2Node_DynamicCast::ReconnectPureExecPins(TArray<UEdGraphPin*>& OldPins) { if (bIsPureCast) { // look for an old exec pin UEdGraphPin* PinExec = nullptr; for (UEdGraphPin* Pin : OldPins) { if (Pin->PinName == UEdGraphSchema_K2::PN_Execute) { PinExec = Pin; break; } } if (PinExec) { // look for old then pin UEdGraphPin* PinThen = nullptr; for (UEdGraphPin* Pin : OldPins) { if (Pin->PinName == UEdGraphSchema_K2::PN_Then) { PinThen = Pin; break; } } if (PinThen) { // reconnect all incoming links to old exec pin to the far end of the old then pin. if (PinThen->LinkedTo.Num() > 0) { UEdGraphPin* PinThenLinked = PinThen->LinkedTo[0]; while (PinExec->LinkedTo.Num() > 0) { UEdGraphPin* PinExecLinked = PinExec->LinkedTo[0]; PinExecLinked->BreakLinkTo(PinExec); PinExecLinked->MakeLinkTo(PinThenLinked); } return true; } } } } return false; } #undef LOCTEXT_NAMESPACE
1
0.853679
1
0.853679
game-dev
MEDIA
0.489104
game-dev
0.810408
1
0.810408
SolidAlloy/ExtEvents
1,995
Runtime/Events/ExtEvent`3.cs
namespace ExtEvents { using System; using System.Runtime.CompilerServices; using JetBrains.Annotations; [Serializable] public class ExtEvent<T1, T2, T3> : BaseExtEvent { private readonly unsafe void*[] _arguments = new void*[3]; private Type[] _eventParamTypes; protected override Type[] EventParamTypes => _eventParamTypes ??= new Type[] { typeof(T1), typeof(T2), typeof(T3) }; /// <summary> /// The dynamic listeners list that you can add your listener to. /// </summary> [PublicAPI] public event Action<T1, T2, T3> DynamicListeners; internal override Delegate _dynamicListeners => DynamicListeners; /// <summary> /// Invokes all listeners of the event. /// </summary> [PublicAPI] public void Invoke(T1 arg1, T2 arg2, T3 arg3) { unsafe { _arguments[0] = Unsafe.AsPointer(ref arg1); _arguments[1] = Unsafe.AsPointer(ref arg2); _arguments[2] = Unsafe.AsPointer(ref arg3); // ReSharper disable once ForCanBeConvertedToForeach for (int index = 0; index < _persistentListeners.Length; index++) { _persistentListeners[index].Invoke(_arguments); } } DynamicListeners?.Invoke(arg1, arg2, arg3); } public static ExtEvent<T1, T2, T3> operator +(ExtEvent<T1, T2, T3> extEvent, Action<T1, T2, T3> listener) { if (extEvent == null) return null; extEvent.DynamicListeners += listener; return extEvent; } public static ExtEvent<T1, T2, T3> operator -(ExtEvent<T1, T2, T3> extEvent, Action<T1, T2, T3> listener) { if (extEvent == null) return null; extEvent.DynamicListeners -= listener; return extEvent; } } }
1
0.944138
1
0.944138
game-dev
MEDIA
0.489784
game-dev
0.915476
1
0.915476
maiple/opengml
2,746
src/interpreter/library/fn_joystick.cpp
#include "libpre.h" #include "fn_joystick.h" #include "libpost.h" #include "ogm/interpreter/Variable.hpp" #include "ogm/common/error.hpp" #include "ogm/common/util.hpp" #include "ogm/interpreter/Executor.hpp" #include "ogm/interpreter/execute.hpp" #include "ogm/interpreter/display/Display.hpp" #include <string> #include "ogm/common/error.hpp" #include <cctype> #include <cstdlib> using namespace ogm::interpreter; using namespace ogm::interpreter::fn; #define frame staticExecutor.m_frame void ogm::interpreter::fn::gamepad_is_supported(VO out) { out = frame.m_display->get_joysticks_supported(); } void ogm::interpreter::fn::gamepad_get_device_count(VO out) { out = static_cast<real_t>(frame.m_display->get_joystick_max()); } void ogm::interpreter::fn::gamepad_is_connected(VO out, V i) { out = frame.m_display->get_joystick_connected(i.castCoerce<int32_t>()); } void ogm::interpreter::fn::gamepad_get_description(VO out, V i) { out = frame.m_display->get_joystick_name(i.castCoerce<int32_t>()); } void ogm::interpreter::fn::gamepad_axis_count(VO out, V i) { out = static_cast<real_t>(frame.m_display->get_joystick_axis_count(i.castCoerce<int32_t>())); } void ogm::interpreter::fn::gamepad_axis_value(VO out, V i, V a) { // OGM constants for axes begin at 15. out = static_cast<real_t>(frame.m_display->get_joystick_axis_value(i.castCoerce<int32_t>(), a.castCoerce<int32_t>() - 15)); } void ogm::interpreter::fn::gamepad_button_count(VO out, V i) { out = frame.m_display->get_joystick_button_count(i.castCoerce<int32_t>()); } void ogm::interpreter::fn::gamepad_button_value(VO out, V i, V j) { // OGM constants for axes begin at 15. real_t r = static_cast<real_t>(frame.m_display->get_joystick_axis_value(i.castCoerce<int32_t>(), j.castCoerce<int32_t>() - 15)); r *= -1; r += 1; r *= 0.5; r = std::clamp(r, 0.0, 1.0); out = r; } void ogm::interpreter::fn::gamepad_button_check(VO out, V j, V i) { out = frame.m_display->get_joystick_button_down(j.castCoerce<int32_t>(), i.castCoerce<int32_t>()); } void ogm::interpreter::fn::gamepad_button_check_pressed(VO out, V j, V i) { out = frame.m_display->get_joystick_button_pressed(j.castCoerce<int32_t>(), i.castCoerce<int32_t>()); } void ogm::interpreter::fn::gamepad_button_check_released(VO out, V j, V i) { out = frame.m_display->get_joystick_button_released(j.castCoerce<int32_t>(), i.castCoerce<int32_t>()); } void ogm::interpreter::fn::joystick_exists(VO out, V i) { out = frame.m_display->get_joystick_connected(i.castCoerce<int32_t>() + 1); } void ogm::interpreter::fn::joystick_has_pov(VO out, V i) { out = false; } void ogm::interpreter::fn::joystick_pov(VO out, V i) { out = 0; }
1
0.852534
1
0.852534
game-dev
MEDIA
0.494683
game-dev
0.618648
1
0.618648
Eaglercraft-Archive/EaglercraftX-1.8-workspace
3,360
src/game/java/net/minecraft/client/model/ModelZombieVillager.java
package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; /**+ * 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 ModelZombieVillager extends ModelBiped { public ModelZombieVillager() { this(0.0F, 0.0F, false); } public ModelZombieVillager(float parFloat1, float parFloat2, boolean parFlag) { super(parFloat1, 0.0F, 64, parFlag ? 32 : 64); if (parFlag) { this.bipedHead = new ModelRenderer(this, 0, 0); this.bipedHead.addBox(-4.0F, -10.0F, -4.0F, 8, 8, 8, parFloat1); this.bipedHead.setRotationPoint(0.0F, 0.0F + parFloat2, 0.0F); } else { this.bipedHead = new ModelRenderer(this); this.bipedHead.setRotationPoint(0.0F, 0.0F + parFloat2, 0.0F); this.bipedHead.setTextureOffset(0, 32).addBox(-4.0F, -10.0F, -4.0F, 8, 10, 8, parFloat1); this.bipedHead.setTextureOffset(24, 32).addBox(-1.0F, -3.0F, -6.0F, 2, 4, 2, parFloat1); } } /**+ * Sets the model's various rotation angles. For bipeds, par1 * and par2 are used for animating the movement of arms and * legs, where par1 represents the time(so that arms and legs * swing back and forth) and par2 represents how "far" arms and * legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); float f6 = MathHelper.sin(this.swingProgress * 3.1415927F); float f7 = MathHelper.sin((1.0F - (1.0F - this.swingProgress) * (1.0F - this.swingProgress)) * 3.1415927F); this.bipedRightArm.rotateAngleZ = 0.0F; this.bipedLeftArm.rotateAngleZ = 0.0F; this.bipedRightArm.rotateAngleY = -(0.1F - f6 * 0.6F); this.bipedLeftArm.rotateAngleY = 0.1F - f6 * 0.6F; this.bipedRightArm.rotateAngleX = -1.5707964F; this.bipedLeftArm.rotateAngleX = -1.5707964F; this.bipedRightArm.rotateAngleX -= f6 * 1.2F - f7 * 0.4F; this.bipedLeftArm.rotateAngleX -= f6 * 1.2F - f7 * 0.4F; this.bipedRightArm.rotateAngleZ += MathHelper.cos(f2 * 0.09F) * 0.05F + 0.05F; this.bipedLeftArm.rotateAngleZ -= MathHelper.cos(f2 * 0.09F) * 0.05F + 0.05F; this.bipedRightArm.rotateAngleX += MathHelper.sin(f2 * 0.067F) * 0.05F; this.bipedLeftArm.rotateAngleX -= MathHelper.sin(f2 * 0.067F) * 0.05F; } }
1
0.819885
1
0.819885
game-dev
MEDIA
0.911238
game-dev
0.986247
1
0.986247
Mojang/DataFixerUpper
1,596
src/main/java/com/mojang/datafixers/types/families/ListAlgebra.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package com.mojang.datafixers.types.families; import com.mojang.datafixers.RewriteResult; import com.mojang.datafixers.functions.PointFree; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public final class ListAlgebra implements Algebra { private final String name; private final List<RewriteResult<?, ?>> views; private int hashCode; public ListAlgebra(final String name, final List<RewriteResult<?, ?>> views) { this.name = name; this.views = views; } @Override public RewriteResult<?, ?> apply(final int index) { return views.get(index); } @Override public String toString() { return toString(0); } @Override public String toString(final int level) { final String wrap = "\n" + PointFree.indent(level + 1); return "Algebra[" + name + wrap + views.stream().map(view -> view.view().function().toString(level + 1)).collect(Collectors.joining(wrap)) + "\n" + PointFree.indent(level) + "]"; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ListAlgebra)) { return false; } final ListAlgebra that = (ListAlgebra) o; return Objects.equals(views, that.views); } @Override public int hashCode() { if (hashCode == 0) { hashCode = views.hashCode(); } return hashCode; } }
1
0.853711
1
0.853711
game-dev
MEDIA
0.250197
game-dev
0.950178
1
0.950178
Mogara/QSanguosha-v2
16,236
src/core/structs.h
#ifndef _STRUCTS_H #define _STRUCTS_H class Room; class TriggerSkill; class Card; class Slash; #include "serverplayer.h" struct DamageStruct { enum Nature { Normal, // normal slash, duel and most damage caused by skill Fire, // fire slash, fire attack and few damage skill (Yeyan, etc) Thunder // lightning, thunder slash, and few damage skill (Leiji, etc) }; DamageStruct(); DamageStruct(const Card *card, ServerPlayer *from, ServerPlayer *to, int damage = 1, Nature nature = Normal); DamageStruct(const QString &reason, ServerPlayer *from, ServerPlayer *to, int damage = 1, Nature nature = Normal); ServerPlayer *from; ServerPlayer *to; const Card *card; int damage; Nature nature; bool chain; bool transfer; bool by_user; QString reason; QString transfer_reason; bool prevented; QString getReason() const; }; struct CardEffectStruct { CardEffectStruct(); const Card *card; ServerPlayer *from; ServerPlayer *to; bool multiple; // helper to judge whether the card has multiple targets // does not make sense if the card inherits SkillCard bool nullified; }; struct SlashEffectStruct { SlashEffectStruct(); int jink_num; const Card *slash; const Card *jink; ServerPlayer *from; ServerPlayer *to; int drank; DamageStruct::Nature nature; bool nullified; }; struct CardUseStruct { enum CardUseReason { CARD_USE_REASON_UNKNOWN = 0x00, CARD_USE_REASON_PLAY = 0x01, CARD_USE_REASON_RESPONSE = 0x02, CARD_USE_REASON_RESPONSE_USE = 0x12 }; CardUseStruct(); CardUseStruct(const Card *card, ServerPlayer *from, QList<ServerPlayer *> to, bool isOwnerUse = true); CardUseStruct(const Card *card, ServerPlayer *from, ServerPlayer *target, bool isOwnerUse = true); bool isValid(const QString &pattern) const; void parse(const QString &str, Room *room); bool tryParse(const QVariant &usage, Room *room); const Card *card; ServerPlayer *from; QList<ServerPlayer *> to; bool m_isOwnerUse; bool m_addHistory; bool m_isHandcard; QStringList nullified_list; }; class CardMoveReason { public: int m_reason; QString m_playerId; // the cause (not the source) of the movement, such as "lusu" when "dimeng", or "zhanghe" when "qiaobian" QString m_targetId; // To keep this structure lightweight, currently this is only used for UI purpose. // It will be set to empty if multiple targets are involved. NEVER use it for trigger condition // judgement!!! It will not accurately reflect the real reason. QString m_skillName; // skill that triggers movement of the cards, such as "longdang", "dimeng" QString m_eventName; // additional arg such as "lebusishu" on top of "S_REASON_JUDGE" QVariant m_extraData; // additional data and will not be parsed to clients inline CardMoveReason() { m_reason = S_REASON_UNKNOWN; } inline CardMoveReason(int moveReason, QString playerId) { m_reason = moveReason; m_playerId = playerId; } inline CardMoveReason(int moveReason, QString playerId, QString skillName, QString eventName) { m_reason = moveReason; m_playerId = playerId; m_skillName = skillName; m_eventName = eventName; } inline CardMoveReason(int moveReason, QString playerId, QString targetId, QString skillName, QString eventName) { m_reason = moveReason; m_playerId = playerId; m_targetId = targetId; m_skillName = skillName; m_eventName = eventName; } bool tryParse(const QVariant &); QVariant toVariant() const; inline bool operator == (const CardMoveReason &other) const { return m_reason == other.m_reason && m_playerId == other.m_playerId && m_targetId == other.m_targetId && m_skillName == other.m_skillName && m_eventName == other.m_eventName; } static const int S_REASON_UNKNOWN = 0x00; static const int S_REASON_USE = 0x01; static const int S_REASON_RESPONSE = 0x02; static const int S_REASON_DISCARD = 0x03; static const int S_REASON_RECAST = 0x04; // ironchain etc. static const int S_REASON_PINDIAN = 0x05; static const int S_REASON_DRAW = 0x06; static const int S_REASON_GOTCARD = 0x07; static const int S_REASON_SHOW = 0x08; static const int S_REASON_TRANSFER = 0x09; static const int S_REASON_PUT = 0x0A; //subcategory of use static const int S_REASON_LETUSE = 0x11; // use a card when self is not current //subcategory of response static const int S_REASON_RETRIAL = 0x12; //subcategory of discard static const int S_REASON_RULEDISCARD = 0x13; // discard at one's Player::Discard for gamerule static const int S_REASON_THROW = 0x23; /* gamerule(dying or punish) as the cost of some skills */ static const int S_REASON_DISMANTLE = 0x33; // one throw card of another //subcategory of gotcard static const int S_REASON_GIVE = 0x17; // from one hand to another hand static const int S_REASON_EXTRACTION = 0x27; // from another's place to one's hand static const int S_REASON_GOTBACK = 0x37; // from placetable to hand static const int S_REASON_RECYCLE = 0x47; // from discardpile to hand static const int S_REASON_ROB = 0x57; // got a definite card from other's hand static const int S_REASON_PREVIEWGIVE = 0x67; // give cards after previewing, i.e. Yiji & Miji //subcategory of show static const int S_REASON_TURNOVER = 0x18; // show n cards from drawpile static const int S_REASON_JUDGE = 0x28; // show a card from drawpile for judge static const int S_REASON_PREVIEW = 0x38; // Not done yet, plan for view some cards for self only(guanxing yiji miji) static const int S_REASON_DEMONSTRATE = 0x48; // show a card which copy one to move to table //subcategory of transfer static const int S_REASON_SWAP = 0x19; // exchange card for two players static const int S_REASON_OVERRIDE = 0x29; // exchange cards from cards in game static const int S_REASON_EXCHANGE_FROM_PILE = 0x39;// exchange cards from cards moved out of game (for qixing only) //subcategory of put static const int S_REASON_NATURAL_ENTER = 0x1A; // a card with no-owner move into discardpile // e.g. delayed trick enters discardpile static const int S_REASON_REMOVE_FROM_PILE = 0x2A; // cards moved out of game go back into discardpile static const int S_REASON_JUDGEDONE = 0x3A; // judge card move into discardpile static const int S_REASON_CHANGE_EQUIP = 0x4A; // replace existed equip static const int S_MASK_BASIC_REASON = 0x0F; }; struct CardsMoveOneTimeStruct { QList<int> card_ids; QList<Player::Place> from_places; Player::Place to_place; CardMoveReason reason; Player *from, *to; QStringList from_pile_names; QString to_pile_name; QList<bool> open; // helper to prevent sending card_id to unrelevant clients bool is_last_handcard; inline void removeCardIds(const QList<int> &to_remove) { foreach (int id, to_remove) { int index = card_ids.indexOf(id); if (index != -1) { card_ids.removeAt(index); from_places.removeAt(index); from_pile_names.removeAt(index); open.removeAt(index); } } } }; struct CardsMoveStruct { inline CardsMoveStruct() { from_place = Player::PlaceUnknown; to_place = Player::PlaceUnknown; from = NULL; to = NULL; is_last_handcard = false; } inline CardsMoveStruct(const QList<int> &ids, Player *from, Player *to, Player::Place from_place, Player::Place to_place, CardMoveReason reason) { this->card_ids = ids; this->from_place = from_place; this->to_place = to_place; this->from = from; this->to = to; this->reason = reason; this->is_last_handcard = false; if (from) this->from_player_name = from->objectName(); if (to) this->to_player_name = to->objectName(); } inline CardsMoveStruct(const QList<int> &ids, Player *to, Player::Place to_place, CardMoveReason reason) { this->card_ids = ids; this->from_place = Player::PlaceUnknown; this->to_place = to_place; this->from = NULL; this->to = to; this->reason = reason; this->is_last_handcard = false; if (to) this->to_player_name = to->objectName(); } inline CardsMoveStruct(int id, Player *from, Player *to, Player::Place from_place, Player::Place to_place, CardMoveReason reason) { this->card_ids << id; this->from_place = from_place; this->to_place = to_place; this->from = from; this->to = to; this->reason = reason; this->is_last_handcard = false; if (from) this->from_player_name = from->objectName(); if (to) this->to_player_name = to->objectName(); } inline CardsMoveStruct(int id, Player *to, Player::Place to_place, CardMoveReason reason) { this->card_ids << id; this->from_place = Player::PlaceUnknown; this->to_place = to_place; this->from = NULL; this->to = to; this->reason = reason; this->is_last_handcard = false; if (to) this->to_player_name = to->objectName(); } inline bool operator == (const CardsMoveStruct &other) const { return from == other.from && from_place == other.from_place && from_pile_name == other.from_pile_name && from_player_name == other.from_player_name; } inline bool operator < (const CardsMoveStruct &other) const { return from < other.from || from_place < other.from_place || from_pile_name < other.from_pile_name || from_player_name < other.from_player_name; } QList<int> card_ids; Player::Place from_place, to_place; QString from_player_name, to_player_name; QString from_pile_name, to_pile_name; Player *from, *to; CardMoveReason reason; bool open; // helper to prevent sending card_id to unrelevant clients bool is_last_handcard; bool tryParse(const QVariant &arg); QVariant toVariant() const; inline bool isRelevant(const Player *player) { return player != NULL && (from == player || (to == player && to_place != Player::PlaceSpecial)); } }; struct DyingStruct { DyingStruct(); ServerPlayer *who; // who is ask for help DamageStruct *damage; // if it is NULL that means the dying is caused by losing hp }; struct DeathStruct { DeathStruct(); ServerPlayer *who; // who is dead DamageStruct *damage; // if it is NULL that means the dying is caused by losing hp }; struct RecoverStruct { RecoverStruct(ServerPlayer *who = NULL, const Card *card = NULL, int recover = 1); int recover; ServerPlayer *who; const Card *card; }; struct PindianStruct { PindianStruct(); bool isSuccess() const; ServerPlayer *from; ServerPlayer *to; const Card *from_card; const Card *to_card; int from_number; int to_number; QString reason; bool success; }; struct JudgeStruct { JudgeStruct(); bool isGood() const; bool isBad() const; bool isEffected() const; void updateResult(); bool isGood(const Card *card) const; // For AI ServerPlayer *who; const Card *card; QString pattern; bool good; QString reason; bool time_consuming; bool negative; bool play_animation; ServerPlayer *retrial_by_response; // record whether the current judge card is provided by a response retrial private: enum TrialResult { TRIAL_RESULT_UNKNOWN, TRIAL_RESULT_GOOD, TRIAL_RESULT_BAD } _m_result; }; struct PhaseChangeStruct { PhaseChangeStruct(); Player::Phase from; Player::Phase to; }; struct PhaseStruct { inline PhaseStruct() { phase = Player::PhaseNone; skipped = 0; } Player::Phase phase; int skipped; // 0 - not skipped; 1 - skipped by effect; -1 - skipped by cost }; struct CardResponseStruct { inline CardResponseStruct() { m_card = NULL; m_who = NULL; m_isUse = false; m_isRetrial = false; } inline CardResponseStruct(const Card *card) { m_card = card; m_who = NULL; m_isUse = false; m_isRetrial = false; } inline CardResponseStruct(const Card *card, ServerPlayer *who) { m_card = card; m_who = who; m_isUse = false; m_isRetrial = false; } inline CardResponseStruct(const Card *card, bool isUse) { m_card = card; m_who = NULL; m_isUse = isUse; m_isRetrial = false; } inline CardResponseStruct(const Card *card, ServerPlayer *who, bool isUse) { m_card = card; m_who = who; m_isUse = isUse; m_isRetrial = false; } const Card *m_card; ServerPlayer *m_who; bool m_isUse; bool m_isHandcard; bool m_isRetrial; }; enum TriggerEvent { NonTrigger, GameStart, TurnStart, EventPhaseStart, EventPhaseProceeding, EventPhaseEnd, EventPhaseChanging, EventPhaseSkipping, DrawNCards, AfterDrawNCards, DrawInitialCards, AfterDrawInitialCards, PreHpRecover, HpRecover, PreHpLost, HpLost, HpChanged, MaxHpChanged, EventLoseSkill, EventAcquireSkill, StartJudge, AskForRetrial, FinishRetrial, FinishJudge, PindianVerifying, Pindian, TurnedOver, ChainStateChanged, ConfirmDamage, // confirm the damage's count and damage's nature Predamage, // trigger the certain skill -- jueqing DamageForseen, // the first event in a damage -- kuangfeng dawu DamageCaused, // the moment for -- qianxi.. DamageInflicted, // the moment for -- tianxiang.. PreDamageDone, // before reducing Hp DamageDone, // it's time to do the damage Damage, // the moment for -- lieren.. Damaged, // the moment for -- yiji.. DamageComplete, // the moment for trigger iron chain EnterDying, Dying, QuitDying, AskForPeaches, AskForPeachesDone, Death, BuryVictim, BeforeGameOverJudge, GameOverJudge, GameFinished, SlashEffected, SlashProceed, SlashHit, SlashMissed, JinkEffect, NullificationEffect, CardAsked, PreCardResponded, CardResponded, BeforeCardsMove, // sometimes we need to record cards before the move CardsMoveOneTime, PreCardUsed, // for AI to filter events only. CardUsed, TargetSpecifying, TargetConfirming, TargetSpecified, TargetConfirmed, CardEffect, // for AI to filter events only CardEffected, PostCardEffected, CardFinished, TrickCardCanceling, TrickEffect, ChoiceMade, StageChange, // For hulao pass only FetchDrawPileCard, // For miniscenarios only ActionedReset, // For 3v3 only Debut, // For 1v1 only TurnBroken, // For the skill 'DanShou'. Do not use it to trigger events NumOfEvents }; Q_DECLARE_METATYPE(DamageStruct) Q_DECLARE_METATYPE(CardEffectStruct) Q_DECLARE_METATYPE(SlashEffectStruct) Q_DECLARE_METATYPE(CardUseStruct) Q_DECLARE_METATYPE(CardsMoveStruct) Q_DECLARE_METATYPE(CardsMoveOneTimeStruct) Q_DECLARE_METATYPE(DyingStruct) Q_DECLARE_METATYPE(DeathStruct) Q_DECLARE_METATYPE(RecoverStruct) Q_DECLARE_METATYPE(PhaseChangeStruct) Q_DECLARE_METATYPE(CardResponseStruct) Q_DECLARE_METATYPE(const Card *) Q_DECLARE_METATYPE(ServerPlayer *) Q_DECLARE_METATYPE(JudgeStruct *) Q_DECLARE_METATYPE(PindianStruct *) #endif
1
0.977689
1
0.977689
game-dev
MEDIA
0.669424
game-dev
0.889036
1
0.889036
ProjectIgnis/CardScripts
2,403
unofficial/c511369001.lua
--嵐闘機ストームライダーグリフォール --Stormrider Griffore --Scripted by Belisk local s,id=GetID() function s.initial_effect(c) --Special Summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,id) e1:SetRange(LOCATION_HAND) e1:SetCondition(s.spcon) e1:SetTarget(s.sptg) e1:SetOperation(s.spop) c:RegisterEffect(e1) --Set & Special Summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_HAND) e2:SetCountLimit(1,id,EFFECT_COUNT_CODE_DUEL) e2:SetCondition(s.spcon2) e2:SetTarget(s.sptg2) e2:SetOperation(s.spop2) c:RegisterEffect(e2) end function s.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(aux.TRUE,tp,0,LOCATION_MZONE,1,nil) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0) end function s.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end function s.spcon2(e,c) if c==nil then return true end return Duel.GetFieldGroupCount(0,LOCATION_ONFIELD,LOCATION_ONFIELD)==0 end function s.sptg2(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0 and Duel.GetLocationCount(1-tp,LOCATION_SZONE)>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,tp,LOCATION_HAND) end function s.filter(c) return c:IsSpellTrap() and c:IsSSetable() end function s.spop2(e,tp,eg,ep,ev,re,r,rp) local hg=Duel.GetFieldGroup(tp,0,LOCATION_HAND) if #hg==0 then return end Duel.ConfirmCards(tp,hg) if Duel.GetLocationCount(1-tp,LOCATION_SZONE)>0 and hg:IsExists(s.filter,1,nil) then local st=hg:Filter(s.filter,nil) if #st>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET) local set=st:Select(tp,1,1,nil):GetFirst() Duel.SSet(tp,set,1-tp) if set:IsLocation(LOCATION_SZONE) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP) end end end Duel.ShuffleHand(1-tp) end
1
0.836332
1
0.836332
game-dev
MEDIA
0.984688
game-dev
0.943703
1
0.943703
jsettlers/settlers-remake
2,507
jsettlers.logic/src/main/java/jsettlers/logic/map/grid/objects/IMapObjectsManagerGrid.java
/******************************************************************************* * Copyright (c) 2015 - 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.logic.map.grid.objects; import java.io.Serializable; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.landscape.EResourceType; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.position.ShortPoint2D; import jsettlers.logic.objects.arrow.IArrowAttackableGrid; import jsettlers.logic.player.Player; public interface IMapObjectsManagerGrid extends Serializable, IArrowAttackableGrid { AbstractHexMapObject getMapObject(int x, int y, EMapObjectType mapObjectType); void setLandscape(int x, int y, ELandscapeType landscapeType); void addMapObject(int x, int y, AbstractHexMapObject mapObject); boolean isBlocked(int x, int y); void setBlocked(int x, int y, boolean blocked); boolean isProtected(int x, int y); void setProtected(int x, int y, boolean protect); boolean removeMapObject(int x, int y, AbstractHexMapObject mapObject); short getWidth(); short getHeight(); boolean isInBounds(int x, int y); EResourceType getResourceTypeAt(int x, int y); byte getResourceAmountAt(int x, int y); boolean isBuildingAreaAt(short x, short y); boolean hasMapObjectType(int x, int y, EMapObjectType... mapObjectTypes); void spawnDonkey(ShortPoint2D position, Player player); }
1
0.86644
1
0.86644
game-dev
MEDIA
0.667543
game-dev,graphics-rendering
0.972565
1
0.972565
Meridaw/Vanilla-Macros
2,925
Warlock/Graguk's Warlock Macros.md
## 3rd February 2006: ## ZHC and TOEP (Thanks Cominagetcha): ``` /script if GetInventoryItemCooldown("player", 13) == 0 then UseInventoryItem(13); SpellStopCasting(); end /script if GetInventoryItemCooldown("player", 14) == 0 then UseInventoryItem(14); SpellStopCasting(); end /cast Shadow Bolt ``` ## 13th October 2005: ## Updated Siphon Life macro: ``` /script z=0;for i=1,16 do GameTooltipTextLeft1:SetText(nil);GameTooltip:SetUnitDebuff("target",i);if GameTooltipTextLeft1:GetText()=="Siphon Life" then z=1;end;end;if z==1 then TargetNearestEnemy();else CastSpellByName("Siphon Life");end ``` ## ToEP and Shadow Bolt macro using Astryl's method so it doesn't require 2 presses of the button - it will only activate if your target's health is above 30%, *or* it's a player. It assumes the lower trinket slot - use Trinket0Slot if you have it in the upper slot: ``` /script local a=GetInventorySlotInfo("Trinket1Slot");local b,c=GetInventoryItemCooldown("player",a);if c <= 0 and (UnitHealth("target") > 30 or UnitIsPlayer("target")) then UseInventoryItem(a);SpellStopCasting();end CastSpellByName("Shadow Bolt(rank 9)"); ``` ## Amplify Curse and Curse of Agony macro Updated Amplify Curse if it's up (you need to use the "SCAN SPELLBOOK" macro to find the ID in *your* spellbook - change 16 to your ID), then immediately also cast the highest rank of Curse of Agony. ``` /script local e, f, g = GetSpellCooldown(16, SpellBookFrame.bookType); if (f <= 0) then CastSpellByName("Amplify Curse"); SpellStopCasting();end; CastSpellByName("Curse of Agony"); ``` ## Updated Amplify Curse, else Curse of Exhaustion: ``` /script local e, f, g = GetSpellCooldown(16, SpellBookFrame.bookType); if (f <= 0) then CastSpellByName("Amplify Curse");SpellStopCasting();end; CastSpellByName("Curse of Exhaustion"); ``` ## Updated Sacrifice, Fel Domination, Summon Voidwalker macro: First press will Sac a voidwalker (only if it's up), second press activate Fel Domination if it's up and then summon a voidwalker (use the "SCAN SPELLBOOK" macro to find the ID of Fel Domination and Summon Voidwalker in *your* spellbook and replace 16 and 100 respectively with your ID): ``` /script local e,f=GetSpellCooldown(16, SpellBookFrame.bookType);if UnitCreatureFamily("pet") == "Voidwalker" then CastPetAction(5); elseif f<=0 then CastSpellByName("Fel Domination");SpellStopCasting();end; CastSpell(100, SpellBookFrame.bookType); ``` ## SCAN SPELLBOOK: How to find the location of Fel Domination or Amplify Curse etc. Change "Fel Domination" to "Amplify Curse" if that's what you are looking for. Use this ID in GetSpellCooldown instead of 16 that I use in the examples. ``` /script for id = 1, 180, 1 do local spellName, subSpellName = GetSpellName(id, SpellBookFrame.bookType);if spellName and string.find(spellName, "Fel Domination", 1, true) then ChatFrame1:AddMessage("ID is "..id, 1.0, 1.0, 0.5); end; end; ``` Made by Graguk
1
0.910365
1
0.910365
game-dev
MEDIA
0.958723
game-dev
0.946327
1
0.946327
iccb1013/Sheng.Winform.IDE
3,658
SourceCode/Source/Kernal/Reflection/ReflectionAttributeHelper.cs
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace Sheng.SailingEase.Kernal { public static class ReflectionAttributeHelper { public static List<T> GetCustomAttributes<T>(Assembly assembly, bool inherit) where T : Attribute { List<T> list = new List<T>(); Type[] exportedTypes = assembly.GetTypes(); for (int i = 0; i < exportedTypes.Length; i++) { if (exportedTypes[i].IsClass) { object[] attObjs = exportedTypes[i].GetCustomAttributes(typeof(T), inherit); if (attObjs.Length > 0) { list.AddRange(attObjs.Cast<T>()); } } } return list; } public static List<Type> GetCompriseCustomAttributeTypes<T>(Assembly assembly, bool inherit) where T : Attribute { List<Type> list = new List<Type>(); Type[] exportedTypes = assembly.GetTypes(); for (int i = 0; i < exportedTypes.Length; i++) { if (exportedTypes[i].IsClass) { object[] attObjs = exportedTypes[i].GetCustomAttributes(typeof(T), inherit); if (attObjs.Length > 0) { list.Add(exportedTypes[i]); } } } return list; } public static List<AttributeAndTypeRelation> GetAttributeAndTypeRelation<T>(Assembly assembly, bool inherit) where T : Attribute { List<AttributeAndTypeRelation> list = new List<AttributeAndTypeRelation>(); Type[] exportedTypes = assembly.GetTypes(); for (int i = 0; i < exportedTypes.Length; i++) { if (exportedTypes[i].IsClass) { object[] attObjs = exportedTypes[i].GetCustomAttributes(typeof(T), inherit); foreach (Attribute item in attObjs) { list.Add(new AttributeAndTypeRelation(item, exportedTypes[i])); } } } return list; } public static List<Type> GetImplementInterfaceTypes<T>(Assembly assembly) { string interfaceName = typeof(T).Name; List<Type> list = new List<Type>(); Type[] exportedTypes = assembly.GetTypes(); for (int i = 0; i < exportedTypes.Length; i++) { if (exportedTypes[i].IsClass) { if(exportedTypes[i].GetInterface(interfaceName) != null) { list.Add(exportedTypes[i]); } } } return list; } } public class AttributeAndTypeRelation { private Attribute _attribute; public Attribute Attribute { get { return _attribute; } } private Type _type; public Type Type { get { return _type; } } public AttributeAndTypeRelation(Attribute attribute, Type type) { _attribute = attribute; _type = type; } } }
1
0.802425
1
0.802425
game-dev
MEDIA
0.166179
game-dev
0.888568
1
0.888568
laomo404/GameplayMessageRouter
2,131
GameplayMessageRouter/Source/GameplayMessageNodes/Public/K2Node_AsyncAction_ListenForGameplayMessages.h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "K2Node_AsyncAction.h" #include "Containers/Array.h" #include "K2Node_BaseAsyncTask.h" #include "UObject/UObjectGlobals.h" #include "K2Node_AsyncAction_ListenForGameplayMessages.generated.h" class FBlueprintActionDatabaseRegistrar; class FKismetCompilerContext; class FMulticastDelegateProperty; class FString; class UEdGraph; class UEdGraphPin; class UObject; /** * Blueprint node which is spawned to handle the async logic for UAsyncAction_RegisterGameplayMessageReceiver */ UCLASS() class UK2Node_AsyncAction_ListenForGameplayMessages : public UK2Node_AsyncAction { GENERATED_BODY() //~UEdGraphNode interface virtual void PostReconstructNode() override; virtual void PinDefaultValueChanged(UEdGraphPin* ChangedPin) override; virtual void GetPinHoverText(const UEdGraphPin& Pin, FString& HoverTextOut) const override; //~End of UEdGraphNode interface //~UK2Node interface virtual void GetMenuActions(FBlueprintActionDatabaseRegistrar& ActionRegistrar) const override; virtual void AllocateDefaultPins() override; //~End of UK2Node interface protected: virtual bool HandleDelegates( const TArray<FBaseAsyncTaskHelper::FOutputPinAndLocalVariable>& VariableOutputs, UEdGraphPin* ProxyObjectPin, UEdGraphPin*& InOutLastThenPin, UEdGraph* SourceGraph, FKismetCompilerContext& CompilerContext) override; private: // Add the GetPayload flow to the end of the delegate handler's logic chain bool HandlePayloadImplementation( FMulticastDelegateProperty* CurrentProperty, const FBaseAsyncTaskHelper::FOutputPinAndLocalVariable& ProxyObjectVar, const FBaseAsyncTaskHelper::FOutputPinAndLocalVariable& PayloadVar, const FBaseAsyncTaskHelper::FOutputPinAndLocalVariable& ActualChannelVar, UEdGraphPin*& InOutLastActivatedThenPin, UEdGraph* SourceGraph, FKismetCompilerContext& CompilerContext); // Make sure the output Payload wildcard matches the input PayloadType void RefreshOutputPayloadType(); UEdGraphPin* GetPayloadPin() const; UEdGraphPin* GetPayloadTypePin() const; UEdGraphPin* GetOutputChannelPin() const; };
1
0.769723
1
0.769723
game-dev
MEDIA
0.633876
game-dev
0.511929
1
0.511929
AtomicGameEngine/AtomicGameEngine
2,692
Source/ThirdParty/Bullet/src/BulletCollision/CollisionShapes/btSphereShape.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_SPHERE_MINKOWSKI_H #define BT_SPHERE_MINKOWSKI_H #include "btConvexInternalShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types ///The btSphereShape implements an implicit sphere, centered around a local origin with radius. ATTRIBUTE_ALIGNED16(class) btSphereShape : public btConvexInternalShape { public: BT_DECLARE_ALIGNED_ALLOCATOR(); btSphereShape (btScalar radius) : btConvexInternalShape () { m_shapeType = SPHERE_SHAPE_PROXYTYPE; m_implicitShapeDimensions.setX(radius); m_collisionMargin = radius; } virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; //notice that the vectors should be unit length virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; btScalar getRadius() const { return m_implicitShapeDimensions.getX() * m_localScaling.getX();} void setUnscaledRadius(btScalar radius) { m_implicitShapeDimensions.setX(radius); btConvexInternalShape::setMargin(radius); } //debugging virtual const char* getName()const {return "SPHERE";} virtual void setMargin(btScalar margin) { btConvexInternalShape::setMargin(margin); } virtual btScalar getMargin() const { //to improve gjk behaviour, use radius+margin as the full margin, so never get into the penetration case //this means, non-uniform scaling is not supported anymore return getRadius(); } }; #endif //BT_SPHERE_MINKOWSKI_H
1
0.870951
1
0.870951
game-dev
MEDIA
0.994699
game-dev
0.847366
1
0.847366
lua9520/source-engine-2018-hl2_src
4,134
game/client/tf2/playeroverlayname.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include <KeyValues.h> #include "playeroverlay.h" #include "playeroverlayname.h" #include <KeyValues.h> #include "commanderoverlay.h" #include "hud_commander_statuspanel.h" #include <vgui/IVGui.h> #include <vgui/IScheme.h> //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- CHudPlayerOverlayName::CHudPlayerOverlayName( CHudPlayerOverlay *baseOverlay, const char *name ) : vgui::Label( (vgui::Panel *)NULL, "OverlayName", name ) { m_pBaseOverlay = baseOverlay; Q_strncpy( m_szName, name, sizeof( m_szName ) ); SetPaintBackgroundEnabled( false ); // Send mouse inputs (but not cursorenter/exit for now) up to parent SetReflectMouse( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CHudPlayerOverlayName::~CHudPlayerOverlayName( void ) { } bool CHudPlayerOverlayName::Init( KeyValues* pInitData ) { if (!pInitData) return false; if (!ParseRGBA(pInitData, "fgcolor", m_fgColor )) return false; if (!ParseRGBA(pInitData, "bgcolor", m_bgColor )) return false; int x, y, w, h; if (!ParseRect(pInitData, "position", x, y, w, h )) return false; SetPos( x, y ); SetSize( w, h ); SetContentAlignment( vgui::Label::a_west ); return true; } void CHudPlayerOverlayName::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); SetFont( pScheme->GetFont( "primary" ) ); } //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- void CHudPlayerOverlayName::SetName( const char *name ) { Q_strncpy( m_szName, name, sizeof( m_szName ) ); SetText( name ); } void CHudPlayerOverlayName::Paint() { m_pBaseOverlay->SetColorLevel( this, m_fgColor, m_bgColor ); BaseClass::Paint(); } void CHudPlayerOverlayName::SetReflectMouse( bool reflect ) { m_bReflectMouse = true; } void CHudPlayerOverlayName::OnCursorMoved(int x,int y) { if ( !m_bReflectMouse ) return; if ( !GetParent() ) return; LocalToScreen( x, y ); vgui::ivgui()->PostMessage( GetParent()->GetVPanel(), new KeyValues( "CursorMoved", "xpos", x, "ypos", y ), GetVPanel() ); } void CHudPlayerOverlayName::OnMousePressed(vgui::MouseCode code) { if ( !m_bReflectMouse ) return; if ( !GetParent() ) return; vgui::ivgui()->PostMessage( GetParent()->GetVPanel(), new KeyValues( "MousePressed", "code", code ), GetVPanel() ); } void CHudPlayerOverlayName::OnMouseDoublePressed(vgui::MouseCode code) { if ( !m_bReflectMouse ) return; if ( !GetParent() ) return; vgui::ivgui()->PostMessage( GetParent()->GetVPanel(), new KeyValues( "MouseDoublePressed", "code", code ), GetVPanel() ); } void CHudPlayerOverlayName::OnMouseReleased(vgui::MouseCode code) { if ( !m_bReflectMouse ) return; if ( !GetParent() ) return; vgui::ivgui()->PostMessage( GetParent()->GetVPanel(), new KeyValues( "MouseReleased", "code", code ), GetVPanel() ); } void CHudPlayerOverlayName::OnMouseWheeled(int delta) { if ( !m_bReflectMouse ) return; if ( !GetParent() ) return; vgui::ivgui()->PostMessage( GetParent()->GetVPanel(), new KeyValues( "MouseWheeled", "delta", delta ), GetVPanel() ); } void CHudPlayerOverlayName::OnCursorEntered() { if ( m_pBaseOverlay->GetMouseOverText() ) { StatusPrint( TYPE_HINT, "%s", m_pBaseOverlay->GetMouseOverText() ); } } void CHudPlayerOverlayName::OnCursorExited() { if ( m_pBaseOverlay->GetMouseOverText() ) { StatusClear(); } }
1
0.872704
1
0.872704
game-dev
MEDIA
0.640019
game-dev,desktop-app
0.983301
1
0.983301
ggez/good-web-game
12,221
src/lib.rs
//! # Good Web Game //! //! [![Discord chat](https://img.shields.io/discord/710177966440579103.svg?label=discord%20chat)](https://discord.gg/jum3Fjek2A) //! [![Docs Status](https://docs.rs/good-web-game/badge.svg)](https://docs.rs/good-web-game) //! [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ggez/good-web-game/blob/master/LICENSE) //! [![Crates.io](https://img.shields.io/crates/v/good-web-game.svg)](https://crates.io/crates/good-web-game) //! //! good-web-game is a wasm32-unknown-unknown implementation of a [ggez](https://github.com/ggez/ggez) subset on top of [miniquad](https://github.com/not-fl3/miniquad/). Originally built to run [Zemeroth](https://github.com/ozkriff/zemeroth) on the web. //! //! It has been recently updated to support much of the ggez 0.6.1 API. If you're already working with ggez you might use this library to port your game to the web (or perhaps even mobile). //! Since it also runs well on desktop it also offers an alternative implementation of ggez, which might always come in handy. //! //! If you are just looking for a well supported minimal high-level engine on top of miniquad you might want to take a look at [macroquad](https://github.com/not-fl3/macroquad/). //! //! ## Status //! //! "good-web-game" implements most of the ggez 0.6.1 API. //! //! ### Differences //! //! * boilerplate code differs slightly, [as shown here](https://github.com/PSteinhaus/PSteinhaus.github.io/tree/main/ggez/web-examples#ggez-animation-example) //! * audio API differs slightly due to use of `quad-snd` instead of `rodio` for easy portability //! * shaders have to be written in GLSL100, due to support for WebGL1 //! * API for creation of shaders and their corresponding uniform structs differs slightly, but the workflow remains the same, see [the `shader` example](examples/shader.rs) //! //! ### Missing / Not available: //! //! * filesystem with writing access (if you need it take a look at [`quad-storage`](https://github.com/optozorax/quad-storage)) //! * writing your own event loop (doesn't make much sense on callback-only platforms like HTML5) //! * spatial audio (overall audio support is still relatively limited) //! * resolution control in fullscreen mode //! * setting window position / size (the latter is available on Windows, but buggy) //! * screenshot function //! * window icon //! * gamepad support on WASM (as `gilrs` depends on wasm-bindgen) //! //! ### On blurry graphics //! //! You may run into somewhat blurry graphics. This is caused by high-dpi rendering: //! //! When run on a system with a scaling factor unequal to 1 the graphics may appear blurry, due to the drawbuffer being scaled up, to achieve a window of the size requested by your OS. //! This size is usually "the size you specified in `Conf`" * "your OS scaling factor". //! //! To avoid this set `Conf::high_dpi` to `true`. This leads to the drawbuffer being the size of your actual physical window. It also means though that you can't be sure how big your drawable space will actually be, as this will then depend on where the program is being run. //! //! We aim towards changing this, so that windows are always created with the physical size specified in `Conf`, but that's not directly supported by miniquad currently. #![doc( html_logo_url = "https://raw.githubusercontent.com/ggez/good-web-game/master/about/logo.png" )] pub mod audio; pub mod conf; pub mod error; pub mod event; pub mod filesystem; pub mod goodies; pub mod graphics; pub mod input; pub mod timer; mod context; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; pub use crate::context::Context; pub use crate::error::*; pub use cgmath; // re-exported for those who want/need even more control pub extern crate miniquad; pub extern crate mint; use crate::event::ErrorOrigin; use crate::filesystem::Filesystem; #[cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "android",)))] use crate::input::gamepad::GamepadId; use crate::input::mouse; use miniquad::GraphicsContext; #[cfg(feature = "log-impl")] pub use miniquad::{debug, info, log, warn}; struct EventHandlerWrapper<E: std::error::Error> { event_handler: Box<dyn event::EventHandler<E>>, context: Context, } impl<E: std::error::Error> miniquad::EventHandler for EventHandlerWrapper<E> { fn update(&mut self, quad_ctx: &mut GraphicsContext) { // if the program is to quit, quit // (in ggez this is done before looking at any of the events of this frame, but this isn't // possible here, so this is the closest it can get) if !self.context.continuing { quad_ctx.order_quit(); // TODO: Even after this has been called the app might continue on executing into `EventHandler::update` // starting another game logic cycle. This could be pretty bad... // for now we somewhat fix this by yielding the time slice and simply returning std::thread::yield_now(); return; } // in ggez tick is called before update, so I moved this to the front self.context.timer_context.tick(); // release all buffers that were kept alive for the previous frame graphics::release_dropped_bindings(); // before running the game logic update the gamepad state #[cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "android",)))] { while let Some(gilrs::Event { id, event, .. }) = self.context.gamepad_context.next_event() { match event { gilrs::EventType::ButtonPressed(button, _) => { self.event_handler.gamepad_button_down_event( &mut self.context, quad_ctx, button, GamepadId(id), ); } gilrs::EventType::ButtonReleased(button, _) => { self.event_handler.gamepad_button_up_event( &mut self.context, quad_ctx, button, GamepadId(id), ); } gilrs::EventType::AxisChanged(axis, value, _) => { self.event_handler.gamepad_axis_event( &mut self.context, quad_ctx, axis, value, GamepadId(id), ); } _ => {} } } } // do ggez 0.6 style error handling if let Err(e) = self.event_handler.update(&mut self.context, quad_ctx) { error!("Error on EventHandler::update(): {:?}", e); // TODO: maybe use miniquad-logging here instead, but I haven't looked into it yet eprintln!("Error on EventHandler::update(): {:?}", e); if self .event_handler .on_error(&mut self.context, quad_ctx, ErrorOrigin::Update, e) { event::quit(&mut self.context); } } } fn draw(&mut self, quad_ctx: &mut GraphicsContext) { // do ggez 0.6 style error handling if let Err(e) = self.event_handler.draw(&mut self.context, quad_ctx) { error!("Error on EventHandler::draw(): {:?}", e); eprintln!("Error on EventHandler::draw(): {:?}", e); if self .event_handler .on_error(&mut self.context, quad_ctx, ErrorOrigin::Draw, e) { event::quit(&mut self.context); } } // reset the mouse frame delta value self.context.mouse_context.reset_delta(); } fn resize_event(&mut self, quad_ctx: &mut GraphicsContext, width: f32, height: f32) { self.event_handler .resize_event(&mut self.context, quad_ctx, width, height); } fn mouse_motion_event(&mut self, quad_ctx: &mut GraphicsContext, x: f32, y: f32) { self.context .mouse_context .input_handler .handle_mouse_move(x, y); let old_pos = mouse::last_position(&self.context); let dx = x - old_pos.x; let dy = y - old_pos.y; // update the frame delta value let old_delta = mouse::delta(&self.context); self.context .mouse_context .set_delta((old_delta.x + dx, old_delta.y + dy).into()); self.context.mouse_context.set_last_position((x, y).into()); self.event_handler .mouse_motion_event(&mut self.context, quad_ctx, x, y, dx, dy); } fn mouse_button_down_event( &mut self, quad_ctx: &mut GraphicsContext, button: miniquad::MouseButton, x: f32, y: f32, ) { self.context .mouse_context .input_handler .handle_mouse_down(button); self.event_handler.mouse_button_down_event( &mut self.context, quad_ctx, button.into(), x, y, ); } fn mouse_button_up_event( &mut self, quad_ctx: &mut GraphicsContext, button: miniquad::MouseButton, x: f32, y: f32, ) { self.context .mouse_context .input_handler .handle_mouse_up(button); self.event_handler .mouse_button_up_event(&mut self.context, quad_ctx, button.into(), x, y); } fn char_event( &mut self, quad_ctx: &mut GraphicsContext, character: char, _keymods: miniquad::KeyMods, _repeat: bool, ) { self.event_handler .text_input_event(&mut self.context, quad_ctx, character); } fn key_down_event( &mut self, quad_ctx: &mut GraphicsContext, keycode: miniquad::KeyCode, keymods: miniquad::KeyMods, repeat: bool, ) { // first update the keyboard context state self.context.keyboard_context.set_key(keycode, true); // then hand it to the user self.event_handler.key_down_event( &mut self.context, quad_ctx, keycode, keymods.into(), repeat, ); } fn key_up_event( &mut self, quad_ctx: &mut GraphicsContext, keycode: miniquad::KeyCode, keymods: miniquad::KeyMods, ) { self.context.keyboard_context.set_key(keycode, false); self.event_handler .key_up_event(&mut self.context, quad_ctx, keycode, keymods.into()); } fn touch_event( &mut self, quad_ctx: &mut GraphicsContext, phase: miniquad::TouchPhase, id: u64, x: f32, y: f32, ) { self.event_handler .touch_event(&mut self.context, quad_ctx, phase, id, x, y); } } /// Starts the game. Takes a start configuration, allowing you to specify additional options like /// high-dpi behavior, as well as a function specifying how to create the event handler from the /// new context. pub fn start<F, E>(conf: conf::Conf, f: F) -> GameResult where E: std::error::Error + 'static, F: 'static + FnOnce(&mut Context, &mut miniquad::GraphicsContext) -> Box<dyn event::EventHandler<E>>, { let fs = Filesystem::new(&conf); let quad_conf = conf.into(); miniquad::start(quad_conf, |ctx| { let mut context = Context::new(ctx, fs); // uncommenting this leads to wrong window sizes as `set_window_size` is currently buggy //context.quad_ctx.set_window_size(800 as u32, 600 as u32); let (d_w, d_h) = ctx.screen_size(); context .gfx_context .set_screen_coordinates(graphics::Rect::new(0., 0., d_w, d_h)); let event_handler = f(&mut context, ctx); Box::new(EventHandlerWrapper { event_handler, context, }) }); Ok(()) }
1
0.863774
1
0.863774
game-dev
MEDIA
0.826384
game-dev
0.910178
1
0.910178
kolmafia/kolmafia
1,941
src/net/sourceforge/kolmafia/request/coinmaster/shop/GotporkPDRequest.java
package net.sourceforge.kolmafia.request.coinmaster.shop; import java.util.regex.Pattern; import net.sourceforge.kolmafia.AdventureResult; import net.sourceforge.kolmafia.CoinmasterData; import net.sourceforge.kolmafia.KoLCharacter; import net.sourceforge.kolmafia.objectpool.ItemPool; import net.sourceforge.kolmafia.session.BatManager; import net.sourceforge.kolmafia.session.InventoryManager; import net.sourceforge.kolmafia.session.LimitMode; public abstract class GotporkPDRequest extends CoinMasterShopRequest { public static final String master = "Gotpork P. D."; public static final String SHOPID = "batman_pd"; private static final Pattern TOKEN_PATTERN = Pattern.compile("<td>([\\d,]+) incriminating evidence"); public static final AdventureResult COIN = ItemPool.get(ItemPool.INCRIMINATING_EVIDENCE, 1); public static final CoinmasterData GOTPORK_PD = new CoinmasterData(master, "Gotpork P. D.", GotporkPDRequest.class) .withToken("incriminating evidence") .withTokenPattern(TOKEN_PATTERN) .withItem(COIN) .withShopRowFields(master, SHOPID) .withItemBuyPrice(GotporkPDRequest::itemBuyPrice) .withAccessible(GotporkPDRequest::accessible); private static AdventureResult itemBuyPrice(final Integer itemId) { int price = GOTPORK_PD.getBuyPrice(itemId); if (price == 1) { return COIN; } // price increased by 3 each time you buy one int count = InventoryManager.getCount(itemId); if (count > 0) { price = 3 * (count + 1); } return COIN.getInstance(price); } public static String accessible() { if (KoLCharacter.getLimitMode() != LimitMode.BATMAN) { return "Only Batfellow can go to the Gotpork P. D."; } if (BatManager.currentBatZone() != BatManager.DOWNTOWN) { return "Batfellow can only visit the Gotpork Police Department while Downtown."; } return null; } }
1
0.732841
1
0.732841
game-dev
MEDIA
0.977036
game-dev
0.851291
1
0.851291
leethomason/MicroPather
6,567
dungeon.cpp
/* Copyright (c) 2000-2012 Lee Thomason (www.grinninglizard.com) 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. */ #define USE_PATHER #include <ctype.h> #include <stdio.h> #include <memory.h> #include <math.h> #include <vector> #include <iostream> #ifdef USE_PATHER #include "micropather.h" using namespace micropather; #endif const int MAPX = 30; const int MAPY = 10; const char gMap[MAPX*MAPY+1] = //"012345678901234567890123456789" " | | |" " | |----+ | +" "---+ +---DD-+ +--+--+ " " | +-- +" " +----+ +---+ " "---+ + D D | " " | | +----+ +----+ +--+" " D | | | " " | +-------+ +-+ |--+ " "---+ | +"; class Dungeon #ifdef USE_PATHER : public Graph #endif { private: Dungeon( const Dungeon& ); void operator=( const Dungeon& ); int playerX, playerY; MPVector<void*> path; bool doorsOpen; bool showConsidered; MicroPather* pather; public: Dungeon() : playerX( 0 ), playerY( 0 ), doorsOpen( false ), showConsidered( false ), pather( 0 ) { pather = new MicroPather( this, 20 ); // Use a very small memory block to stress the pather } virtual ~Dungeon() { delete pather; } int X() { return playerX; } int Y() { return playerY; } void ClearPath() { #ifdef USE_PATHER path.resize( 0 ); #endif } void ToggleTouched() { showConsidered = !showConsidered; pather->Reset(); } void ToggleDoor() { doorsOpen = !doorsOpen; #ifdef USE_PATHER pather->Reset(); #endif } int Passable( int nx, int ny ) { if ( nx >= 0 && nx < MAPX && ny >= 0 && ny < MAPY ) { int index = ny*MAPX+nx; char c = gMap[ index ]; if ( c == ' ' ) return 1; else if ( c == 'D' ) return 2; } return 0; } int SetPos( int nx, int ny ) { int result = 0; if ( Passable( nx, ny ) == 1 ) { #ifdef USE_PATHER float totalCost; if ( showConsidered ) pather->Reset(); result = pather->Solve( XYToNode( playerX, playerY ), XYToNode( nx, ny ), &path, &totalCost ); if ( result == MicroPather::SOLVED ) { playerX = nx; playerY = ny; } printf( "Pather returned %d\n", result ); #else playerX = nx; playerY = ny; #endif } return result; } void Print() { char buf[ MAPX+1 ]; MPVector< void* > stateVec; if ( showConsidered ) pather->StatesInPool( &stateVec ); printf( " doors %s\n", doorsOpen ? "open" : "closed" ); printf( " 0 10 20\n" ); printf( " 012345678901234567890123456789\n" ); for( int j=0; j<MAPY; ++j ) { // Copy in the line. memcpy( buf, &gMap[MAPX*j], MAPX+1 ); buf[MAPX]=0; #ifdef USE_PATHER unsigned k; // Wildly inefficient demo code. unsigned size = path.size(); for( k=0; k<size; ++k ) { int x, y; NodeToXY( path[k], &x, &y ); if ( y == j ) buf[x] = '0' + k%10; } if ( showConsidered ) { for( k=0; k<stateVec.size(); ++k ) { int x, y; NodeToXY( stateVec[k], &x, &y ); if ( y == j ) buf[x] = 'x'; } } #endif // Insert the player if ( j==playerY ) buf[playerX] = 'i'; printf( "%d%s\n", j%10, buf ); } } #ifdef USE_PATHER void NodeToXY( void* node, int* x, int* y ) { intptr_t index = (intptr_t)node; *y = index / MAPX; *x = index - *y * MAPX; } void* XYToNode( int x, int y ) { return (void*) ( y*MAPX + x ); } virtual float LeastCostEstimate( void* nodeStart, void* nodeEnd ) { int xStart, yStart, xEnd, yEnd; NodeToXY( nodeStart, &xStart, &yStart ); NodeToXY( nodeEnd, &xEnd, &yEnd ); /* Compute the minimum path cost using distance measurement. It is possible to compute the exact minimum path using the fact that you can move only on a straight line or on a diagonal, and this will yield a better result. */ int dx = xStart - xEnd; int dy = yStart - yEnd; return (float) sqrt( (double)(dx*dx) + (double)(dy*dy) ); } virtual void AdjacentCost( void* node, micropather::MPVector< StateCost > *neighbors ) { int x, y; const int dx[8] = { 1, 1, 0, -1, -1, -1, 0, 1 }; const int dy[8] = { 0, 1, 1, 1, 0, -1, -1, -1 }; const float cost[8] = { 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f }; NodeToXY( node, &x, &y ); for( int i=0; i<8; ++i ) { int nx = x + dx[i]; int ny = y + dy[i]; int pass = Passable( nx, ny ); if ( pass > 0 ) { if ( pass == 1 || doorsOpen ) { // Normal floor StateCost nodeCost = { XYToNode( nx, ny ), cost[i] }; neighbors->push_back( nodeCost ); } else { // Normal floor StateCost nodeCost = { XYToNode( nx, ny ), FLT_MAX }; neighbors->push_back( nodeCost ); } } } } virtual void PrintStateInfo( void* node ) { int x, y; NodeToXY( node, &x, &y ); printf( "(%d,%d)", x, y ); } #endif }; int main( int /*argc*/, const char** /*argv*/ ) { Dungeon dungeon; bool done = false; char buf[ 256 ]; while ( !done ) { dungeon.Print(); printf( "\n# # to move, q to quit, r to redraw, d to toggle doors, t for touched\n" ); //gets( buf ); //printf( "\n" ); std::cin.getline( buf, 256 ); if ( *buf ) { if ( buf[0] == 'q' ) { done = true; } else if ( buf[0] == 'd' ) { dungeon.ToggleDoor(); dungeon.ClearPath(); } else if ( buf[0] == 't' ) { dungeon.ToggleTouched(); } else if ( buf[0] == 'r' ) { dungeon.ClearPath(); } else if ( isdigit( buf[0] ) ) { int x, y; sscanf( buf, "%d %d", &x, &y ); // sleazy, I know dungeon.SetPos( x, y ); } } else { dungeon.ClearPath(); } } return 0; }
1
0.924121
1
0.924121
game-dev
MEDIA
0.905538
game-dev
0.953954
1
0.953954
jabuwu/shanty-quest
1,569
src/game/quests/plank/trigger.rs
use crate::common::prelude::*; use crate::game::prelude::*; use bevy::prelude::*; use super::{Plank1Cutscene, PlankQuestStage}; pub struct PlankTriggerPlugin; impl Plugin for PlankTriggerPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, (plank_trigger_world_spawn, plank_trigger_check)); } } #[derive(Component)] pub struct PlankTrigger; fn plank_trigger_world_spawn( mut ev_spawn: EventReader<WorldLocationsSpawnEvent>, mut commands: Commands, world_locations: Res<WorldLocations>, ) { for _ in ev_spawn.iter() { let triggers = world_locations.get_multiple_rect("PlankTrigger"); for trigger in triggers { commands.spawn(( TransformBundle::default(), Transform2::from_translation(trigger.position).with_depth((DepthLayer::Entity, 0.)), Trigger::new(CollisionShape::Rect { size: trigger.size }), PlankTrigger, )); } } } fn plank_trigger_check( query: Query<&Trigger, With<PlankTrigger>>, mut game_state: ResMut<GameState>, mut ev_cutscene_plank1: EventWriter<CutsceneStartEvent<Plank1Cutscene>>, ) { for trigger in query.iter() { if trigger.triggered() { if let Quest::Plank(quest) = &mut game_state.quests.active_quest { if matches!(quest.stage, PlankQuestStage::TalkedToMayor) { ev_cutscene_plank1.send_default(); quest.stage = PlankQuestStage::Dialogue1; } } } } }
1
0.878363
1
0.878363
game-dev
MEDIA
0.987082
game-dev
0.756306
1
0.756306
blizzhackers/kolbot-SoloPlay
6,116
BuildFiles/druid/druid.WolfBuild.js
/** * @filename druid.WolfBuild.js * @author theBGuy * @desc Fury wolf final build * */ (function (module) { module.exports = (function () { const build = { caster: false, skillstab: sdk.skills.tabs.ShapeShifting, wantedskills: [sdk.skills.Werewolf, sdk.skills.Lycanthropy, sdk.skills.Fury], usefulskills: [sdk.skills.HeartofWolverine, sdk.skills.Grizzly], precastSkills: [sdk.skills.Werewolf, sdk.skills.HeartofWolverine, sdk.skills.Grizzly], wantedMerc: MercData[sdk.skills.Might], stats: [ ["strength", 103], ["dexterity", 35], ["vitality", "all"] ], skills: [ [sdk.skills.Werewolf, 20, true], [sdk.skills.Lycanthropy, 20, true], [sdk.skills.Fury, 20, true], [sdk.skills.Grizzly, 1, false], [sdk.skills.HeartofWolverine, 20, true], [sdk.skills.FeralRage, 10, false], [sdk.skills.Grizzly, 15], ], charms: { ResLife: { max: 3, have: [], classid: sdk.items.SmallCharm, /** @param {ItemUnit} check */ stats: function (check) { return ( !check.unique && check.classid === this.classid && check.allRes === 5 && check.getStat(sdk.stats.MaxHp) === 20 ); } }, ResMf: { max: 2, have: [], classid: sdk.items.SmallCharm, /** @param {ItemUnit} check */ stats: function (check) { return ( !check.unique && check.classid === this.classid && check.allRes === 5 && check.getStat(sdk.stats.MagicBonus) === 7 ); } }, ResFHR: { max: 1, have: [], classid: sdk.items.SmallCharm, /** @param {ItemUnit} check */ stats: function (check) { return ( !check.unique && check.classid === this.classid && check.allRes === 5 && check.getStat(sdk.stats.FHR) === 5 ); } }, Skiller: { max: 2, have: [], classid: sdk.items.GrandCharm, /** @param {ItemUnit} check */ stats: function (check) { return ( !check.unique && check.classid === this.classid && check.getStat(sdk.stats.AddSkillTab, sdk.skills.tabs.ShapeShifting) === 1 && check.getStat(sdk.stats.MaxHp) >= 40 ); } }, }, AutoBuildTemplate: { 1: { Update: function () { Config.AttackSkill = [ -1, sdk.skills.Fury, sdk.skills.FeralRage, sdk.skills.Fury, sdk.skills.FeralRage, sdk.skills.Rabies, -1 ]; Config.LowManaSkill = [0, 0]; Config.Wereform = "Werewolf"; Config.SummonAnimal = "Grizzly"; Config.SummonSpirit = "Heart of Wolverine"; } }, }, respec: function () { return ( me.checkItem({ name: sdk.locale.items.Ribcracker, classid: sdk.items.Stalagmite }).have && me.checkItem({ name: sdk.locale.items.ChainsofHonor, }).have ); }, active: function () { return this.respec() && me.getSkill(sdk.skills.Werewolf, sdk.skills.subindex.HardPoints) === 20; }, }; let finalGear = [ // autoequip final gear // Weapon - Upp'ed Ribcracker "[name] == stalagmite && [quality] == unique # [enhanceddamage] >= 300 && [ias] >= 50 # [tier] == 110000", // Helmet - Jalal's Mane "[name] == totemicmask && [quality] == unique # [druidskills] == 2 && [shapeshiftingskilltab] == 2 # [tier] == tierscore(item, 110000)", // Belt - Verdungo's "[name] == mithrilcoil && [quality] == unique && [flag] != ethereal # [enhanceddefense] >= 90 # [tier] == tierscore(item, 110000)", // Armor - CoH "[type] == armor && [flag] == runeword && [flag] != ethereal # [fireresist] == 65 && [hpregen] == 7 # [tier] == 110000", // Gloves - Dracul's "[name] == vampirebonegloves && [quality] == unique && [flag] != ethereal # [enhanceddefense] >= 90 # [tier] == tierscore(item, 110000)", // Amulet - Maras "[type] == amulet && [quality] == unique # [strength] == 5 && [coldresist] >= 30 # [tier] == tierscore(item, 110000)", // Final Rings - Perfect Wisp & Bul-Kathos' Wedding Band "[type] == ring && [quality] == unique # [itemabsorblightpercent] == 20 # [tier] == tierscore(item, 110000)", "[type] == ring && [quality] == unique # [maxstamina] == 50 && [lifeleech] == 5 # [tier] == tierscore(item, 110000)", // Rings - Wisp & Bul-Kathos' Wedding Band "[type] == ring && [quality] == unique # [itemabsorblightpercent] >= 10 # [tier] == tierscore(item, 110000)", "[type] == ring && [quality] == unique # [maxstamina] == 50 && [lifeleech] >= 3 # [tier] == tierscore(item, 110000)", // Merc Final Armor - Fortitude "[type] == armor && [flag] == runeword # [enhanceddefense] >= 200 && [enhanceddamage] >= 300 # [merctier] == 100000", // Merc Armor - Treachery "[type] == armor && [flag] == runeword # [ias] == 45 && [coldresist] == 30 # [merctier] == 50000 + mercscore(item)", // Merc Final Helmet - Eth Andy's "[name] == demonhead && [quality] == unique && [flag] == ethereal # [strength] >= 25 && [enhanceddefense] >= 100 # [merctier] == 50000 + mercscore(item)", // Merc Helmet - Andy's "[name] == demonhead && [quality] == unique && [flag] != ethereal # [strength] >= 25 && [enhanceddefense] >= 100 # [merctier] == 40000 + mercscore(item)", // Merc Weapon - Reaper's Toll "[name] == thresher && [quality] == unique # [enhanceddamage] >= 190 && [lifeleech] >= 11 # [merctier] == 100000 + mercscore(item)", ]; NTIP.buildList(finalGear); NTIP.buildFinalGear(finalGear); return build; })(); })(module);
1
0.764434
1
0.764434
game-dev
MEDIA
0.781546
game-dev
0.917304
1
0.917304
TheMade4/Relictium
1,107
src/main/java/me/jellysquid/mods/sodium/client/model/quad/blender/BlockColorSettings.java
package me.jellysquid.mods.sodium.client.model.quad.blender; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; public interface BlockColorSettings<T> { /** * Configures whether biome colors from a color provider will be interpolated for this block. You should only * enable this functionality if your color provider returns values based upon a pair of coordinates in the world, * and not if it needs access to the block state itself. * * @return True if interpolation should be used, otherwise false. */ boolean useSmoothColorBlending(IBlockAccess view, T state, BlockPos pos); @SuppressWarnings("unchecked") static boolean isSmoothBlendingEnabled(IBlockAccess world, IBlockState state, BlockPos pos) { if (state.getBlock() instanceof BlockColorSettings) { BlockColorSettings<IBlockState> settings = (BlockColorSettings<IBlockState>) state.getBlock(); return settings.useSmoothColorBlending(world, state, pos); } return false; } }
1
0.787583
1
0.787583
game-dev
MEDIA
0.933985
game-dev
0.784612
1
0.784612
GregTech6/gregtech6
4,676
src/main/java/gregtech/items/tools/electric/GT_Tool_JackHammer_HV.java
/** * Copyright (c) 2023 GregTech-6 Team * * This file is part of GregTech. * * GregTech 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. * * GregTech 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 GregTech. If not, see <http://www.gnu.org/licenses/>. */ package gregtech.items.tools.electric; import gregapi.data.RM; import gregapi.item.multiitem.MultiItemTool; import gregapi.item.multiitem.behaviors.Behavior_Switch_Metadata; import gregapi.old.Textures; import gregapi.recipes.Recipe; import gregapi.render.IIconContainer; import gregapi.util.ST; import net.minecraft.block.Block; import net.minecraft.block.BlockSilverfish; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.event.world.BlockEvent; import java.util.List; import static gregapi.data.CS.*; public class GT_Tool_JackHammer_HV extends GT_Tool_MiningDrill_LV { public final int mSwitchIndex; public GT_Tool_JackHammer_HV(int aSwitchIndex) { mSwitchIndex = aSwitchIndex; } @Override public int getToolDamagePerBlockBreak() { return 200; } @Override public int getToolDamagePerDropConversion() { return 200; } @Override public int getToolDamagePerContainerCraft() { return 3200; } @Override public int getToolDamagePerEntityAttack() { return 800; } @Override public int getBaseQuality() { return 1; } @Override public float getBaseDamage() { return 3.0F; } @Override public float getSpeedMultiplier() { return 12.0F; } @Override public float getMaxDurabilityMultiplier() { return 2.0F; } @Override public String getCraftingSound() { return SFX.IC_DRILL_HARD; } @Override public String getEntityHitSound() { return SFX.IC_DRILL_HARD; } @Override public String getMiningSound() { return SFX.IC_DRILL_HARD; } @Override public boolean canCollect() {return F;} @Override public boolean isMinableBlock(Block aBlock, byte aMetaData) { return TOOL_pickaxe.equalsIgnoreCase(aBlock.getHarvestTool(aMetaData)) || aBlock instanceof BlockSilverfish || aBlock.getMaterial() == Material.rock || aBlock.getMaterial() == Material.glass || aBlock.getMaterial() == Material.ice || aBlock.getMaterial() == Material.packedIce; } @Override public int convertBlockDrops(List<ItemStack> aDrops, ItemStack aStack, EntityPlayer aPlayer, Block aBlock, long aAvailableDurability, int aX, int aY, int aZ, byte aMetaData, int aFortune, boolean aSilkTouch, BlockEvent.HarvestDropsEvent aEvent) { int rConversions = 0; Recipe tRecipe; if (aBlock.hasTileEntity(aMetaData) || null == (tRecipe = RM.Hammer.findRecipe(null, null, true, Integer.MAX_VALUE, null, ZL_FS, ST.make(aBlock, 1, aMetaData)))) { List<ItemStack> tDrops = ST.arraylist(); for (int i = 0; i < aDrops.size(); i++) { tRecipe = RM.Hammer.findRecipe(null, null, true, Integer.MAX_VALUE, null, ZL_FS, ST.amount(1, aDrops.get(i))); if (tRecipe != null) { byte tStackSize = (byte)aDrops.get(i).stackSize; rConversions += tStackSize; aDrops.remove(i--); if (tRecipe.mOutputs.length > 0) for (byte j = 0; j < tStackSize; j++) { ItemStack[] tHammeringOutput = tRecipe.getOutputs(); for (int k = 0; k < tHammeringOutput.length; k++) if (tHammeringOutput[k] != null) tDrops.add(tHammeringOutput[k]); } } } aDrops.addAll(tDrops); } else { aDrops.clear(); ItemStack[] tHammeringOutput = tRecipe.getOutputs(RNGSUS); for (int k = 0; k < tHammeringOutput.length; k++) if (tHammeringOutput[k] != null) aDrops.add(tHammeringOutput[k]); rConversions++; } return rConversions; } @Override public void onStatsAddedToTool(MultiItemTool aItem, int aID) { aItem.addItemBehavior(aID, new Behavior_Switch_Metadata(mSwitchIndex, T, T)); super.onStatsAddedToTool(aItem, aID); } @Override public IIconContainer getIcon(boolean aIsToolHead, ItemStack aStack) { return aIsToolHead ? Textures.ItemIcons.VOID : Textures.ItemIcons.JACKHAMMER; } @Override public String getDeathMessage() { return "[VICTIM] has been jackhammered into pieces by [KILLER]"; } }
1
0.880448
1
0.880448
game-dev
MEDIA
0.963691
game-dev
0.94035
1
0.94035
gamingdotme/opensource-casino-v10
43,579
casino/app/Games/MagicOwlAM/SlotSettings.php
<?php namespace VanguardLTE\Games\MagicOwlAM { class SlotSettings { public $playerId = null; public $splitScreen = null; public $reelStrip1 = null; public $reelStrip2 = null; public $reelStrip3 = null; public $reelStrip4 = null; public $reelStrip5 = null; public $reelStrip6 = null; public $reelStripBonus1 = null; public $reelStripBonus2 = null; public $reelStripBonus3 = null; public $reelStripBonus4 = null; public $reelStripBonus5 = null; public $reelStripBonus6 = null; public $slotId = ''; public $slotDBId = ''; public $Line = null; public $scaleMode = null; public $numFloat = null; public $gameLine = null; public $Bet = null; public $isBonusStart = null; public $Balance = null; public $SymbolGame = null; public $GambleType = null; public $lastEvent = null; public $Jackpots = []; public $keyController = null; public $slotViewState = null; public $hideButtons = null; public $slotReelsConfig = null; public $slotFreeCount = null; public $slotFreeMpl = null; public $slotWildMpl = null; public $slotExitUrl = null; public $slotBonus = null; public $slotBonusType = null; public $slotScatterType = null; public $slotGamble = null; public $Paytable = []; public $slotSounds = []; private $jpgs = null; private $Bank = null; private $Percent = null; private $WinLine = null; private $WinGamble = null; private $Bonus = null; private $shop_id = null; public $currency = null; public $user = null; public $game = null; public $shop = null; public $jpgPercentZero = false; public $count_balance = null; public function __construct($sid, $playerId) { $this->slotId = $sid; $this->playerId = $playerId; $user = \VanguardLTE\User::lockForUpdate()->find($this->playerId); $this->user = $user; $this->shop_id = $user->shop_id; $gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get(); $game = \VanguardLTE\Game::where([ 'name' => $this->slotId, 'shop_id' => $this->shop_id ])->lockForUpdate()->first(); $this->shop = \VanguardLTE\Shop::find($this->shop_id); $this->game = $game; $this->MaxWin = $this->shop->max_win; if( $game->stat_in > 0 ) { $this->currentRTP = $game->stat_out / $game->stat_in * 100; } else { $this->currentRTP = 0; } $this->increaseRTP = 1; $this->CurrentDenom = $this->game->denomination; $this->scaleMode = 0; $this->numFloat = 0; $this->Paytable['SYM_0'] = [ 0, 0, 0, 50, 200, 500 ]; $this->Paytable['SYM_1'] = [ 0, 0, 0, 25, 100, 250 ]; $this->Paytable['SYM_2'] = [ 0, 0, 0, 20, 50, 150 ]; $this->Paytable['SYM_3'] = [ 0, 0, 0, 15, 30, 100 ]; $this->Paytable['SYM_4'] = [ 0, 0, 0, 15, 30, 100 ]; $this->Paytable['SYM_5'] = [ 0, 0, 0, 10, 20, 75 ]; $this->Paytable['SYM_6'] = [ 0, 0, 0, 10, 20, 75 ]; $this->Paytable['SYM_7'] = [ 0, 0, 0, 5, 10, 50 ]; $this->Paytable['SYM_8'] = [ 0, 0, 0, 5, 10, 50 ]; $this->Paytable['SYM_9'] = [ 0, 0, 0, 2, 2, 2 ]; $reel = new GameReel(); foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $reelStrip ) { if( count($reel->reelsStrip[$reelStrip]) ) { $this->$reelStrip = $reel->reelsStrip[$reelStrip]; } } foreach( [ 'reelStripBonus1', 'reelStripBonus2', 'reelStripBonus3', 'reelStripBonus4', 'reelStripBonus5', 'reelStripBonus6' ] as $reelStrip ) { if( count($reel->reelsStripBonus[$reelStrip]) ) { $this->$reelStrip = $reel->reelsStripBonus[$reelStrip]; } } $this->keyController = [ '13' => 'uiButtonSpin,uiButtonSkip', '49' => 'uiButtonInfo', '50' => 'uiButtonCollect', '51' => 'uiButtonExit2', '52' => 'uiButtonLinesMinus', '53' => 'uiButtonLinesPlus', '54' => 'uiButtonBetMinus', '55' => 'uiButtonBetPlus', '56' => 'uiButtonGamble', '57' => 'uiButtonRed', '48' => 'uiButtonBlack', '189' => 'uiButtonAuto', '187' => 'uiButtonSpin' ]; $this->slotReelsConfig = [ [ 425, 142, 3 ], [ 669, 142, 3 ], [ 913, 142, 3 ], [ 1157, 142, 3 ], [ 1401, 142, 3 ] ]; $this->slotBonusType = 1; $this->slotScatterType = 0; $this->splitScreen = false; $this->slotBonus = true; $this->slotGamble = true; $this->slotFastStop = 1; $this->slotExitUrl = '/'; $this->slotWildMpl = 1; $this->GambleType = 1; $this->slotFreeCount = 5; $this->slotFreeMpl = 1; $this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState); $this->hideButtons = []; $this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get(); $this->Line = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; $this->gameLine = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]; $this->Bet = explode(',', $game->bet); if( $this->Bet[0] < 0.01 ) { foreach( $this->Bet as &$bt ) { $bt = $bt * 10; } } $this->Balance = $user->balance; $this->SymbolGame = [ '0', '1', 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]; $this->Bank = $game->get_gamebank(); $this->Percent = $this->shop->percent; $this->WinGamble = $game->rezerv; $this->slotDBId = $game->id; $this->slotCurrency = $user->shop->currency; $this->count_balance = $user->count_balance; if( $user->address > 0 && $user->count_balance == 0 ) { $this->Percent = 0; $this->jpgPercentZero = true; } else if( $user->count_balance == 0 ) { $this->Percent = 100; } if( !isset($this->user->session) || strlen($this->user->session) <= 0 ) { $this->user->session = serialize([]); } $this->gameData = unserialize($this->user->session); if( count($this->gameData) > 0 ) { foreach( $this->gameData as $key => $vl ) { if( $vl['timelife'] <= time() ) { unset($this->gameData[$key]); } } } if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 ) { $this->game->advanced = serialize([]); } $this->gameDataStatic = unserialize($this->game->advanced); $this->gameDataStatic = unserialize($this->game->advanced); if( count($this->gameDataStatic) > 0 ) { foreach( $this->gameDataStatic as $key => $vl ) { if( $vl['timelife'] <= time() ) { unset($this->gameDataStatic[$key]); } } } } public function is_active() { if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) ) { \VanguardLTE\Session::where('user_id', $this->user->id)->delete(); $this->user->update(['remember_token' => null]); return false; } if( !$this->game->view ) { return false; } if( $this->shop->is_blocked ) { return false; } if( $this->user->is_blocked ) { return false; } if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED ) { return false; } return true; } public function SetGameData($key, $value) { $timeLife = 86400; $this->gameData[$key] = [ 'timelife' => time() + $timeLife, 'payload' => $value ]; } public function GetGameData($key) { if( isset($this->gameData[$key]) ) { return $this->gameData[$key]['payload']; } else { return 0; } } public function FormatFloat($num) { $str0 = explode('.', $num); if( isset($str0[1]) ) { if( strlen($str0[1]) > 4 ) { return round($num * 100) / 100; } else if( strlen($str0[1]) > 2 ) { return floor($num * 100) / 100; } else { return $num; } } else { return $num; } } public function SaveGameData() { $this->user->session = serialize($this->gameData); $this->user->save(); } public function CheckBonusWin() { $allRateCnt = 0; $allRate = 0; foreach( $this->Paytable as $vl ) { foreach( $vl as $vl2 ) { if( $vl2 > 0 ) { $allRateCnt++; $allRate += $vl2; break; } } } return $allRate / $allRateCnt; } public function GetRandomPay() { $allRate = []; foreach( $this->Paytable as $vl ) { foreach( $vl as $vl2 ) { if( $vl2 > 0 ) { $allRate[] = $vl2; } } } shuffle($allRate); if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) ) { $allRate[0] = 0; } return $allRate[0]; } public function HasGameDataStatic($key) { if( isset($this->gameDataStatic[$key]) ) { return true; } else { return false; } } public function SaveGameDataStatic() { $this->game->advanced = serialize($this->gameDataStatic); $this->game->save(); $this->game->refresh(); } public function SetGameDataStatic($key, $value) { $timeLife = 86400; $this->gameDataStatic[$key] = [ 'timelife' => time() + $timeLife, 'payload' => $value ]; } public function GetGameDataStatic($key) { if( isset($this->gameDataStatic[$key]) ) { return $this->gameDataStatic[$key]['payload']; } else { return 0; } } public function HasGameData($key) { if( isset($this->gameData[$key]) ) { return true; } else { return false; } } public function HexFormat($num) { $str = strlen(dechex($num)) . dechex($num); return $str; } public function FormatReelStrips($pf) { $resultReelStrips = ''; foreach( [ 'reelStrip' . $pf . '1', 'reelStrip' . $pf . '2', 'reelStrip' . $pf . '3', 'reelStrip' . $pf . '4', 'reelStrip' . $pf . '5', 'reelStrip' . $pf . '6' ] as $reelStrip ) { if( $this->$reelStrip != '' ) { $data = $this->$reelStrip; foreach( $data as &$item ) { $item = str_replace('"', '', $item); $item = trim($item); $item = dechex($item); } $rLength = dechex(count($data)); $resultReelStrips .= (strlen($rLength) . $rLength . implode('', $data)); } } return $resultReelStrips; } public function GetRandomReels() { $reelsPos1 = rand(0, count($this->reelStrip1) - 1); $reelsPos2 = rand(0, count($this->reelStrip2) - 1); $reelsPos3 = rand(0, count($this->reelStrip3) - 1); $reelsPos4 = rand(0, count($this->reelStrip4) - 1); $reelsPos5 = rand(0, count($this->reelStrip5) - 1); return $this->HexFormat($reelsPos1) . $this->HexFormat($reelsPos2) . $this->HexFormat($reelsPos3) . $this->HexFormat($reelsPos4) . $this->HexFormat($reelsPos5); } public function GetHistory() { $history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [ $this->slotDBId, $this->playerId ])->get(); $this->lastEvent = 'NULL'; foreach( $history as $log ) { $tmpLog = json_decode($log->str); if( $tmpLog->responseEvent != 'gambleResult' ) { $this->lastEvent = $log->str; break; } } if( isset($tmpLog) ) { return $tmpLog; } else { return 'NULL'; } } public function UpdateJackpots($bet) { $bet = $bet * $this->CurrentDenom; $count_balance = $this->count_balance; $jsum = []; $payJack = 0; for( $i = 0; $i < count($this->jpgs); $i++ ) { if( $count_balance == 0 || $this->jpgPercentZero ) { $jsum[$i] = $this->jpgs[$i]->balance; } else if( $count_balance < $bet ) { $jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance; } else { $jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance; } if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 ) { if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id ) { } else { $payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom; $jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum(); $this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom); if( $this->jpgs[$i]->get_pay_sum() > 0 ) { \VanguardLTE\StatGame::create([ 'user_id' => $this->playerId, 'balance' => $this->Balance * $this->CurrentDenom, 'bet' => 0, 'win' => $this->jpgs[$i]->get_pay_sum(), 'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id, 'in_game' => 0, 'in_jpg' => 0, 'in_profit' => 0, 'shop_id' => $this->shop_id, 'date_time' => \Carbon\Carbon::now() ]); } } $i++; } $this->jpgs[$i]->balance = $jsum[$i]; $this->jpgs[$i]->save(); if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') ) { $summ = $this->jpgs[$i]->get_start_balance(); if( $summ > 0 ) { $this->jpgs[$i]->add_jpg('add', $summ); } } } if( $payJack > 0 ) { $payJack = sprintf('%01.2f', $payJack); $this->Jackpots['jackPay'] = $payJack; } } public function GetBank($slotState = '') { if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' ) { $slotState = 'bonus'; } else { $slotState = ''; } $game = $this->game; $this->Bank = $game->get_gamebank($slotState); return $this->Bank / $this->CurrentDenom; } public function GetPercent() { return $this->Percent; } public function GetCountBalanceUser() { return $this->user->count_balance; } public function InternalErrorSilent($errcode) { $strLog = ''; $strLog .= "\n"; $strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}'); $strLog .= "\n"; $strLog .= ' ############################################### '; $strLog .= "\n"; $slg = ''; if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') ) { $slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log'); } file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog); } public function InternalError($errcode) { $strLog = ''; $strLog .= "\n"; $strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}'); $strLog .= "\n"; $strLog .= ' ############################################### '; $strLog .= "\n"; $slg = ''; if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') ) { $slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log'); } file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog); exit( '' ); } public function SetBank($slotState = '', $sum, $slotEvent = '') { if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' ) { $slotState = 'bonus'; } else { $slotState = ''; } if( $this->GetBank($slotState) + $sum < 0 ) { $this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum)); } $sum = $sum * $this->CurrentDenom; $game = $this->game; $bankBonusSum = 0; if( $sum > 0 && $slotEvent == 'bet' ) { $this->toGameBanks = 0; $this->toSlotJackBanks = 0; $this->toSysJackBanks = 0; $this->betProfit = 0; $prc = $this->GetPercent(); $prc_b = 10; if( $prc <= $prc_b ) { $prc_b = 0; } $count_balance = $this->count_balance; $gameBet = $sum / $this->GetPercent() * 100; if( $count_balance < $gameBet && $count_balance > 0 ) { $firstBid = $count_balance; $secondBid = $gameBet - $firstBid; if( isset($this->betRemains0) ) { $secondBid = $this->betRemains0; } $bankSum = $firstBid / 100 * $this->GetPercent(); $sum = $bankSum + $secondBid; $bankBonusSum = $firstBid / 100 * $prc_b; } else if( $count_balance > 0 ) { $bankBonusSum = $gameBet / 100 * $prc_b; } for( $i = 0; $i < count($this->jpgs); $i++ ) { if( !$this->jpgPercentZero ) { if( $count_balance < $gameBet && $count_balance > 0 ) { $this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent); } else if( $count_balance > 0 ) { $this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent); } } } $this->toGameBanks = $sum; $this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks; } if( $sum > 0 ) { $this->toGameBanks = $sum; } if( $bankBonusSum > 0 ) { $sum -= $bankBonusSum; $game->set_gamebank($bankBonusSum, 'inc', 'bonus'); } if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) ) { $sum = $this->betRemains; } $game->set_gamebank($sum, 'inc', $slotState); $game->save(); return $game; } public function SetBalance($sum, $slotEvent = '') { if( $this->GetBalance() + $sum < 0 ) { $this->InternalError('Balance_ ' . $sum); } $sum = $sum * $this->CurrentDenom; if( $sum < 0 && $slotEvent == 'bet' ) { $user = $this->user; if( $user->count_balance == 0 ) { $remains = []; $this->betRemains = 0; $sm = abs($sum); if( $user->address < $sm && $user->address > 0 ) { $remains[] = $sm - $user->address; } for( $i = 0; $i < count($remains); $i++ ) { if( $this->betRemains < $remains[$i] ) { $this->betRemains = $remains[$i]; } } } if( $user->count_balance > 0 && $user->count_balance < abs($sum) ) { $remains0 = []; $sm = abs($sum); $tmpSum = $sm - $user->count_balance; $this->betRemains0 = $tmpSum; if( $user->address > 0 ) { $this->betRemains0 = 0; if( $user->address < $tmpSum && $user->address > 0 ) { $remains0[] = $tmpSum - $user->address; } for( $i = 0; $i < count($remains0); $i++ ) { if( $this->betRemains0 < $remains0[$i] ) { $this->betRemains0 = $remains0[$i]; } } } } $sum0 = abs($sum); if( $user->count_balance == 0 ) { $sm = abs($sum); if( $user->address < $sm && $user->address > 0 ) { $user->address = 0; } else if( $user->address > 0 ) { $user->address -= $sm; } } else if( $user->count_balance > 0 && $user->count_balance < $sum0 ) { $sm = $sum0 - $user->count_balance; if( $user->address < $sm && $user->address > 0 ) { $user->address = 0; } else if( $user->address > 0 ) { $user->address -= $sm; } } $this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance); $this->user->count_balance = $this->FormatFloat($this->user->count_balance); } $this->user->increment('balance', $sum); $this->user->balance = $this->FormatFloat($this->user->balance); $this->user->save(); return $this->user; } public function GetBalance() { $user = $this->user; $this->Balance = $user->balance / $this->CurrentDenom; return $this->Balance; } public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState) { $reportName = $this->slotId . ' ' . $slotState; if( $slotState == 'freespin' ) { $reportName = $this->slotId . ' FG'; } else if( $slotState == 'bet' ) { $reportName = $this->slotId . ''; } else if( $slotState == 'slotGamble' ) { $reportName = $this->slotId . ' DG'; } $game = $this->game; if( $slotState == 'bet' ) { $this->user->update_level('bet', $bet * $lines * $this->CurrentDenom); } if( $slotState != 'freespin' ) { $game->increment('stat_in', $bet * $lines * $this->CurrentDenom); } $game->increment('stat_out', $win * $this->CurrentDenom); $game->tournament_stat($slotState, $this->user->id, $bet * $lines * $this->CurrentDenom, $win * $this->CurrentDenom); $this->user->update(['last_bid' => \Carbon\Carbon::now()]); if( !isset($this->betProfit) ) { $this->betProfit = 0; $this->toGameBanks = 0; $this->toSlotJackBanks = 0; $this->toSysJackBanks = 0; } if( !isset($this->toGameBanks) ) { $this->toGameBanks = 0; } $this->game->increment('bids'); $this->game->refresh(); $gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first(); if( $gamebank ) { list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id); } else { $slotsBank = $game->get_gamebank('', 'slots'); $bonusBank = $game->get_gamebank('bonus', 'bonus'); $fishBank = $game->get_gamebank('', 'fish'); $tableBank = $game->get_gamebank('', 'table_bank'); $littleBank = $game->get_gamebank('', 'little'); } $totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank; \VanguardLTE\GameLog::create([ 'game_id' => $this->slotDBId, 'user_id' => $this->playerId, 'ip' => $_SERVER['REMOTE_ADDR'], 'str' => $spinSymbols, 'shop_id' => $this->shop_id ]); \VanguardLTE\StatGame::create([ 'user_id' => $this->playerId, 'balance' => $this->Balance * $this->CurrentDenom, 'bet' => $bet * $lines * $this->CurrentDenom, 'win' => $win * $this->CurrentDenom, 'game' => $reportName, 'in_game' => $this->toGameBanks, 'in_jpg' => $this->toSlotJackBanks, 'in_profit' => $this->betProfit, 'denomination' => $this->CurrentDenom, 'shop_id' => $this->shop_id, 'slots_bank' => (double)$slotsBank, 'bonus_bank' => (double)$bonusBank, 'fish_bank' => (double)$fishBank, 'table_bank' => (double)$tableBank, 'little_bank' => (double)$littleBank, 'total_bank' => (double)$totalBank, 'date_time' => \Carbon\Carbon::now() ]); } public function GetSpinSettings($garantType = 'bet', $bet, $lines) { $curField = 10; switch( $lines ) { case 10: $curField = 10; break; case 9: case 8: $curField = 9; break; case 7: case 6: $curField = 7; break; case 5: case 4: $curField = 5; break; case 3: case 2: $curField = 3; break; case 1: $curField = 1; break; default: $curField = 10; break; } if( $garantType != 'bet' ) { $pref = '_bonus'; } else { $pref = ''; } $this->AllBet = $bet * $lines; $linesPercentConfigSpin = $this->game->get_lines_percent_config('spin'); $linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus'); $currentPercent = $this->shop->percent; $currentSpinWinChance = 0; $currentBonusWinChance = 0; $percentLevel = ''; foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v ) { $l = explode('_', $k); $l0 = $l[0]; $l1 = $l[1]; if( $l0 <= $currentPercent && $currentPercent <= $l1 ) { $percentLevel = $k; break; } } $currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel]; $currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel]; $RtpControlCount = 200; if( !$this->HasGameDataStatic('SpinWinLimit') ) { $this->SetGameDataStatic('SpinWinLimit', 0); } if( !$this->HasGameDataStatic('RtpControlCount') ) { $this->SetGameDataStatic('RtpControlCount', $RtpControlCount); } if( $this->game->stat_in > 0 ) { $rtpRange = $this->game->stat_out / $this->game->stat_in * 100; } else { $rtpRange = 0; } if( $this->GetGameDataStatic('RtpControlCount') == 0 ) { if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 ) { $this->SetGameDataStatic('SpinWinLimit', rand(25, 50)); } if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 ) { $currentBonusWinChance = 5000; $currentSpinWinChance = 20; $this->MaxWin = rand(1, 5); if( $rtpRange < ($currentPercent - 1) ) { $this->SetGameDataStatic('SpinWinLimit', 0); $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); } } } else if( $this->GetGameDataStatic('RtpControlCount') < 0 ) { if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 ) { $this->SetGameDataStatic('SpinWinLimit', rand(25, 50)); } $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 ) { $currentBonusWinChance = 5000; $currentSpinWinChance = 10; $this->MaxWin = rand(1, 5); if( $rtpRange < ($currentPercent - 1) ) { $this->SetGameDataStatic('SpinWinLimit', 0); } } if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) ) { $this->SetGameDataStatic('RtpControlCount', $RtpControlCount); } } else { $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); } $bonusWin = rand(1, $currentBonusWinChance); $spinWin = rand(1, $currentSpinWinChance); $return = [ 'none', 0 ]; if( $bonusWin == 1 && $this->slotBonus ) { $this->isBonusStart = true; $garantType = 'bonus'; $winLimit = $this->GetBank($garantType); $return = [ 'bonus', $winLimit ]; if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) ) { $return = [ 'none', 0 ]; } } else if( $spinWin == 1 ) { $winLimit = $this->GetBank($garantType); $return = [ 'win', $winLimit ]; } if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) ) { $randomPush = rand(1, 10); if( $randomPush == 1 ) { $winLimit = $this->GetBank(''); $return = [ 'win', $winLimit ]; } } return $return; } public function GetRandomScatterPos($rp) { $rpResult = []; for( $i = 0; $i < count($rp); $i++ ) { if( $rp[$i] == '9' ) { if( $i == 0 ) { array_push($rpResult, $i); array_push($rpResult, $i + 1); } else if( $i == (count($rp) - 1) ) { array_push($rpResult, $i - 1); } else { array_push($rpResult, $i); array_push($rpResult, $i + 1); array_push($rpResult, $i - 1); } } } shuffle($rpResult); if( !isset($rpResult[0]) ) { $rpResult[0] = rand(2, count($rp) - 3); } return $rpResult[0]; } public function GetGambleSettings() { $spinWin = rand(1, $this->WinGamble); return $spinWin; } public function GetReelStrips($winType, $slotEvent) { $game = $this->game; if( $slotEvent == 'freespin' ) { $reel = new GameReel(); $fArr = $reel->reelsStripBonus; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $reelStrip ) { $curReel = array_shift($fArr); if( count($curReel) ) { $this->$reelStrip = $curReel; } } } if( $winType != 'bonus' ) { $prs = []; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $index => $reelStrip ) { if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 ) { $prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3); } } } else { $reelsId = []; $scattersCnt = 3; $reelsId = [ 1, 2, 3, 4, 5 ]; for( $i = 0; $i < count($reelsId); $i++ ) { if( $i == 0 || $i == 2 || $i == 4 ) { $prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]}); } else { $prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3); } } } $reel = [ 'rp' => [] ]; foreach( $prs as $index => $value ) { $key = $this->{'reelStrip' . $index}; $cnt = count($key); $key[-1] = $key[$cnt - 1]; $key[$cnt] = $key[0]; $reel['reel' . $index][0] = $key[$value - 1]; $reel['reel' . $index][1] = $key[$value]; $reel['reel' . $index][2] = $key[$value + 1]; $reel['reel' . $index][3] = $key[$value + 2]; $reel['reel' . $index][4] = ''; $reel['rp'][] = $value; } return $reel; } } }
1
0.609711
1
0.609711
game-dev
MEDIA
0.510978
game-dev
0.800522
1
0.800522
steos/php-quickcheck
22,022
src/QuickCheck/Generator.php
<?php namespace QuickCheck; /** * A monadic generator that produces lazy shrink trees. * Based on clojure.test.check.generators. * * @package QuickCheck */ class Generator { private $gen; private function __construct(callable $gen) { $this->gen = $gen; } /** * invokes the generator with the given RNG and size * * @param Random $rng * @param int $size * @return ShrinkTreeNode */ public function call(Random $rng, $size) { return call_user_func($this->gen, $rng, $size); } public static function pure($value) { return new self(function ($rng, $size) use ($value) { return $value; }); } public function fmap(callable $k) { return new self(function ($rng, $size) use ($k) { return call_user_func($k, call_user_func($this->gen, $rng, $size)); }); } /** * Creates a new generator by mapping $k over the value of this generator * * @param callable $k must return a new Generator * @return Generator */ public function flatMap(callable $k) { return new self(function ($rng, $size) use ($k) { return call_user_func($k, $this->call($rng, $size))->call($rng, $size); }); } /** * turns a list of generators into a generator of a list * * @param Generator[]|\Iterator $xs * @return Generator */ private static function sequence($xs) { return Lazy::reduce( function (Generator $acc, Generator $elem) { return $acc->flatMap(function ($xs) use ($elem) { return $elem->flatMap(function ($y) use ($xs) { return self::pure(Arrays::append($xs, $y)); }); }); }, $xs, self::pure([]) ); } /** * maps function f over the values produced by this generator * * @param callable $f * @return Generator */ public function map(callable $f) { return $this->fmap(function (ShrinkTreeNode $node) use ($f) { return $node->map($f); }); } /** * creates a new generator that passes the result of this generator * to the callable $k which should return a new generator. * * @param callable $k * @return Generator */ public function chain(callable $k) { return $this->flatMap( function (ShrinkTreeNode $rose) use ($k) { $gen = new self(function ($rng, $size) use ($rose, $k) { return $rose->map($k)->map( function (self $g) use ($rng, $size) { return $g->call($rng, $size); } ); }); return $gen->fmap(function (ShrinkTreeNode $node) { return $node->join(); }); } ); } /** * creates a generator that always returns $value and never shrinks * * @param mixed $value * @return Generator */ public static function unit($value) { return self::pure(ShrinkTreeNode::pure($value)); } // helpers // -------------------------------------------------- public static function sizes($maxSize) { return Lazy::cycle(function () use ($maxSize) { return Lazy::range(0, $maxSize); }); } /** * returns an infinite sequence of random samples from this generator bounded by $maxSize * * @param int $maxSize * @return \Generator */ public function samples($maxSize = 100) { $rng = new Random(); return Lazy::map( function ($size) use ($rng) { return $this->call($rng, $size)->getValue(); }, self::sizes($maxSize) ); } /** * returns an array of $num random samples from this generator * * @param int $num * @return array */ public function takeSamples($num = 10) { return Lazy::realize(Lazy::take($num, $this->samples())); } // internal helpers // -------------------------------------------------- private static function halfs($n) { while (0 != $n) { yield $n; $n = intval($n / 2); } } private static function shrinkInt($i) { return Lazy::map( function ($val) use ($i) { return $i - $val; }, self::halfs($i) ); } private static function intRoseTree($val) { return new ShrinkTreeNode($val, function () use ($val) { return Lazy::map( function ($x) { return self::intRoseTree($x); }, self::shrinkInt($val) ); }); } private static function sized(callable $sizedGen) { return new self(function ($rng, $size) use ($sizedGen) { $gen = call_user_func($sizedGen, $size); return $gen->call($rng, $size); }); } private static function randRange(Random $rng, $lower, $upper) { if ($lower > $upper) { throw new \InvalidArgumentException(); } $factor = $rng->nextDouble(); return (int)floor($lower + ($factor * (1.0 + $upper) - $factor * $lower)); } private static function getArgs(array $args) { if (count($args) == 1 && is_array($args[0])) { return $args[0]; } return $args; } // combinators and helpers // -------------------------------------------------- /** * creates a generator that returns numbers in the range $lower to $upper, inclusive * * @param int $lower * @param int $upper * @return Generator */ public static function choose($lower, $upper) { return new self(function (Random $rng, $size) use ($lower, $upper) { $val = self::randRange($rng, $lower, $upper); $tree = self::intRoseTree($val); return $tree->filter(function ($x) use ($lower, $upper) { return $x >= $lower && $x <= $upper; }); }); } /** * creates a new generator based on this generator with size always bound to $n * * @param int $n * @return Generator */ public function resize($n) { return new self(function ($rng, $size) use ($n) { return $this->call($rng, $n); }); } /** * creates a new generator that returns an array whose elements are chosen * from the list of given generators. Individual elements shrink according to * their generator but the array will never shrink in count. * * Accepts either a variadic number of args or a single array of generators. * * Example: * Gen::tuples(Gen::booleans(), Gen::ints()) * Gen::tuples([Gen::booleans(), Gen::ints()]) * * @return Generator */ public static function tuples() { $seq = self::sequence(self::getArgs(func_get_args())); return $seq->flatMap(function ($roses) { return self::pure(ShrinkTreeNode::zip( function (...$xs) { return $xs; }, $roses )); }); } /** * creates a generator that returns a positive or negative integer bounded * by the generators size parameter. * * @return Generator */ public static function ints() { return self::sized(function ($size) { return self::choose(-$size, $size); }); } /** * creates a generator that produces arrays whose elements * are chosen from $gen. * * If no $min or $max are specified the array size will be bounded by the * generators maxSize argument and shrink to the empty array. * * If $min and $max is specified the array size will be bounded by $min and $max (inclusive) * and will not shrink below $min. * * If $min is specified without $max the generated arrays will always be of size $min * and don't shrink in size at all (equivalent to tuple). * * @param Generator $gen * @param int $min * @param int $max * @return Generator */ public static function arraysOf(self $gen, int $min = null, int $max = null) { if ($min !== null && $max === null) { return self::tuples(Lazy::realize(Lazy::repeat($min, $gen))); } else if ($min !== null && $max !== null) { return self::choose($min, $max)->flatMap(function(ShrinkTreeNode $num) use ($gen, $min, $max) { $seq = self::sequence(Lazy::repeat($num->getValue(), $gen)); return $seq->flatMap(function($roses) use ($min, $max) { return self::pure(ShrinkTreeNode::shrink(function (...$xs) { return $xs; }, $roses))->flatMap(function(ShrinkTreeNode $rose) use ($min, $max) { return self::pure($rose->filter(function($x) use ($min, $max) { return count($x) >= $min && count($x) <= $max; })); }); }); }); } else { $sized = self::sized(function ($s) { return self::choose(0, $s); }); return $sized->flatMap(function (ShrinkTreeNode $numRose) use ($gen) { $seq = self::sequence(Lazy::repeat($numRose->getValue(), $gen)); return $seq->flatMap(function ($roses) { return self::pure(ShrinkTreeNode::shrink(function (...$xs) { return $xs; }, $roses)); }); }); } } /** * creates a generator that produces arrays whose elements * are chosen from this generator. * * @return Generator */ public function intoArrays(int $min = null, int $max = null) { return self::arraysOf($this, $min, $max); } /** * creates a generator that produces characters from 0-255 * * @return Generator */ public static function chars() { return self::choose(0, 255)->map('chr'); } /** * creates a generator that produces only ASCII characters * * @return Generator */ public static function asciiChars() { return self::choose(32, 126)->map('chr'); } /** * creates a generator that produces alphanumeric characters * * @return Generator */ public static function alphaNumChars() { return self::oneOf( self::choose(48, 57), self::choose(65, 90), self::choose(97, 122) )->map('chr'); } /** * creates a generator that produces only alphabetic characters * * @return Generator */ public static function alphaChars() { return self::oneOf( self::choose(65, 90), self::choose(97, 122) )->map('chr'); } public function dontShrink() { return $this->flatMap(function (ShrinkTreeNode $x) { return self::unit($x->getRoot()); }); } public function toStrings() { return $this->map(function ($x) { return is_array($x) ? implode('', $x) : (string)$x; }); } /** * creates a generator that produces strings; may contain unprintable chars * * @return Generator */ public static function strings() { return self::chars()->intoArrays()->toStrings(); } /** * creates a generator that produces ASCII strings * * @return Generator */ public static function asciiStrings() { return self::asciiChars()->intoArrays()->toStrings(); } /** * creates a generator that produces alphanumeric strings * * @return Generator */ public static function alphaNumStrings() { return self::alphaNumChars()->intoArrays()->toStrings(); } /** * creates a generator that produces alphabetic strings * * @return Generator */ public static function alphaStrings() { return self::alphaChars()->intoArrays()->toStrings(); } /** * creates a generator that produces arrays with keys chosen from $keygen * and values chosen from $valgen. * * @param Generator $keygen * @param Generator $valgen * * @return Generator */ public static function maps(self $keygen, self $valgen) { return self::tuples($keygen, $valgen) ->intoArrays() ->map(function ($tuples) { $map = []; foreach ($tuples as $tuple) { [$key, $val] = $tuple; $map[$key] = $val; } return $map; }); } /** * creates a generator that produces arrays with keys chosen from * this generator and values chosen from $valgen. * * @param Generator $valgen * @return Generator */ public function mapsTo(self $valgen) { return self::maps($this, $valgen); } /** * creates a generator that produces arrays with keys chosen from * $keygen and values chosen from this generator. * * @param Generator $keygen * @return Generator */ public function mapsFrom(self $keygen) { return self::maps($keygen, $this); } /** * creates a generator that produces arrays with the same keys as in $map * where each corresponding value is chosen from a specified generator. * * Example: * Gen::mapsWith( * 'foo' => Gen::booleans(), * 'bar' => Gen::ints() * ) * * @param array $map * @return Generator */ public static function mapsWith(array $map) { return self::tuples($map)->map(function ($vals) use ($map) { return array_combine(array_keys($map), $vals); }); } /** * creates a new generator that randomly chooses a value from the list * of provided generators. Shrinks toward earlier generators as well as shrinking * the generated value itself. * * Accepts either a variadic number of args or a single array of generators. * * Example: * Gen::oneOf(Gen::booleans(), Gen::ints()) * Gen::oneOf([Gen::booleans(), Gen::ints()]) * * @return Generator */ public static function oneOf() { $generators = self::getArgs(func_get_args()); $num = count($generators); if ($num < 2) { throw new \InvalidArgumentException(); } return self::choose(0, $num - 1) ->chain(function ($index) use ($generators) { return $generators[$index]; }); } /** * creates a generator that randomly chooses from the specified values * * Accepts either a variadic number of args or a single array of values. * * Example: * Gen::elements('foo', 'bar', 'baz') * Gen::elements(['foo', 'bar', 'baz']) * * @return Generator */ public static function elements() { $coll = self::getArgs(func_get_args()); if (empty($coll)) { throw new \InvalidArgumentException(); } return self::choose(0, count($coll) - 1) ->flatMap(function (ShrinkTreeNode $rose) use ($coll) { return self::pure($rose->map( function ($index) use ($coll) { return $coll[$index]; } )); }); } /** * creates a new generator that generates values from this generator such that they * satisfy callable $pred. * At most $maxTries attempts will be made to generate a value that satisfies the * predicate. At every retry the size parameter will be increased. In case of failure * an exception will be thrown. * * @param callable $pred * @param int $maxTries * @return Generator * @throws \RuntimeException */ public function suchThat(callable $pred, $maxTries = 10) { return new self(function ($rng, $size) use ($pred, $maxTries) { for ($i = 0; $i < $maxTries; ++$i) { $value = $this->call($rng, $size); if (call_user_func($pred, $value->getValue())) { return $value->filter($pred); } $size++; } throw new \RuntimeException( "couldn't satisfy such-that predicate after $maxTries tries." ); }); } public function notEmpty($maxTries = 10) { return $this->suchThat(function ($x) { return !empty($x); }, $maxTries); } /** * creates a generator that produces true or false. Shrinks to false. * * @return Generator */ public static function booleans() { return self::elements(false, true); } /** * creates a generator that produces positive integers bounded by * the generators size parameter. * * @return Generator */ public static function posInts() { return self::ints()->map(function ($x) { return abs($x); }); } /** * creates a generator that produces negative integers bounded by * the generators size parameter. * * @return Generator */ public static function negInts() { return self::ints()->map(function ($x) { return -abs($x); }); } /** * creates a generator that produces strictly positive integers bounded by * the generators size parameter. * * @return Generator */ public static function strictlyPosInts() { return self::ints()->map(function ($x) { return abs($x)+1; }); } /** * creates a generator that produces strictly negative integers bounded by * the generators size parameter. * * @return Generator */ public static function strictlyNegInts() { return self::ints()->map(function ($x) { return -abs($x)-1; }); } /** * creates a generator that produces values from specified generators based on * likelihoods. The likelihood of a generator being chosen is its likelihood divided * by the sum of all likelihoods. * * Example: * Gen::frequency( * 5, Gen::ints(), * 3, Gen::booleans(), * 2, Gen::alphaStrings() * ) * * @return Generator */ public static function frequency() { $args = func_get_args(); $argc = count($args); if ($argc < 2 || $argc % 2 != 0) { throw new \InvalidArgumentException(); } $total = array_sum(Lazy::realize(Lazy::takeNth(2, $args))); $pairs = Lazy::realize(Lazy::partition(2, $args)); return self::choose(1, $total)->flatMap( function (ShrinkTreeNode $rose) use ($pairs) { $n = $rose->getValue(); foreach ($pairs as $pair) { [$chance, $gen] = $pair; if ($n <= $chance) { return $gen; } $n = $n - $chance; } } ); } public static function simpleTypes() { return self::oneOf( self::ints(), self::chars(), self::strings(), self::booleans() ); } public static function simplePrintableTypes() { return self::oneOf( self::ints(), self::asciiChars(), self::asciiStrings(), self::booleans() ); } public static function containerTypes(self $innerType) { return self::oneOf( $innerType->intoArrays(), $innerType->mapsFrom(self::oneOf(self::ints(), self::strings())) ); } private static function recursiveHelper($container, $scalar, $scalarSize, $childrenSize, $height) { if ($height == 0) { return $scalar->resize($scalarSize); } else { return call_user_func( $container, self::recursiveHelper( $container, $scalar, $scalarSize, $childrenSize, $height - 1 ) ); } } public static function recursive(callable $container, self $scalar) { return self::sized(function ($size) use ($container, $scalar) { return self::choose(1, 5)->chain( function ($height) use ($container, $scalar, $size) { $childrenSize = pow($size, 1 / $height); return self::recursiveHelper( $container, $scalar, $size, $childrenSize, $height ); } ); }); } public static function any() { return self::recursive( [__CLASS__, 'containerTypes'], self::simpleTypes() ); } public static function anyPrintable() { return self::recursive( [__CLASS__, 'containerTypes'], self::simplePrintableTypes() ); } }
1
0.845271
1
0.845271
game-dev
MEDIA
0.573017
game-dev
0.954333
1
0.954333
magmafoundation/Magma-Neo
2,188
patches/net/minecraft/client/renderer/entity/layers/ElytraLayer.java.patch
--- a/net/minecraft/client/renderer/entity/layers/ElytraLayer.java +++ b/net/minecraft/client/renderer/entity/layers/ElytraLayer.java @@ -45,7 +_,7 @@ float p_116960_ ) { ItemStack itemstack = p_116954_.getItemBySlot(EquipmentSlot.CHEST); - if (itemstack.is(Items.ELYTRA)) { + if (shouldRender(itemstack, p_116954_)) { ResourceLocation resourcelocation; if (p_116954_ instanceof AbstractClientPlayer abstractclientplayer) { PlayerSkin playerskin = abstractclientplayer.getSkin(); @@ -54,10 +_,10 @@ } else if (playerskin.capeTexture() != null && abstractclientplayer.isModelPartShown(PlayerModelPart.CAPE)) { resourcelocation = playerskin.capeTexture(); } else { - resourcelocation = WINGS_LOCATION; + resourcelocation = getElytraTexture(itemstack, p_116954_); } } else { - resourcelocation = WINGS_LOCATION; + resourcelocation = getElytraTexture(itemstack, p_116954_); } p_116951_.pushPose(); @@ -68,5 +_,30 @@ this.elytraModel.renderToBuffer(p_116951_, vertexconsumer, p_116953_, OverlayTexture.NO_OVERLAY); p_116951_.popPose(); } + } + + /** + * Determines if the ElytraLayer should render. + * ItemStack and Entity are provided for modder convenience, + * For example, using the same ElytraLayer for multiple custom Elytra. + * + * @param stack The Elytra ItemStack + * @param entity The entity being rendered. + * @return If the ElytraLayer should render. + */ + public boolean shouldRender(ItemStack stack, T entity) { + return stack.getItem() == Items.ELYTRA; + } + + /** + * Gets the texture to use with this ElytraLayer. + * This assumes the vanilla Elytra model. + * + * @param stack The Elytra ItemStack. + * @param entity The entity being rendered. + * @return The texture. + */ + public ResourceLocation getElytraTexture(ItemStack stack, T entity) { + return WINGS_LOCATION; } }
1
0.641718
1
0.641718
game-dev
MEDIA
0.889901
game-dev,graphics-rendering
0.660642
1
0.660642
Particular/NServiceBus
4,416
src/NServiceBus.Core/Sagas/Sagas.cs
namespace NServiceBus.Features; using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NServiceBus.Sagas; /// <summary> /// Used to configure saga. /// </summary> public class Sagas : Feature { internal Sagas() { EnableByDefault(); Defaults(s => { conventions = s.Get<Conventions>(); var sagas = s.GetAvailableTypes().Where(IsSagaType).ToList(); if (sagas.Count > 0) { conventions.AddSystemMessagesConventions(t => IsTypeATimeoutHandledByAnySaga(t, sagas)); } s.EnableFeatureByDefault<SynchronizedStorage>(); }); Defaults(s => s.Set(new SagaMetadataCollection())); Prerequisite(context => !context.Settings.GetOrDefault<bool>("Endpoint.SendOnly"), "Sagas are only relevant for endpoints receiving messages."); Prerequisite(config => config.Settings.GetAvailableTypes().Any(IsSagaType), "No sagas were found in the scanned types"); DependsOn<SynchronizedStorage>(); } /// <summary> /// See <see cref="Feature.Setup" />. /// </summary> protected internal override void Setup(FeatureConfigurationContext context) { if (!context.Settings.HasSupportFor<StorageType.Sagas>()) { throw new Exception("The selected persistence doesn't have support for saga storage. Select another persistence or disable the sagas feature using endpointConfiguration.DisableFeature<Sagas>()"); } var sagaIdGenerator = context.Settings.GetOrDefault<ISagaIdGenerator>() ?? new DefaultSagaIdGenerator(); var sagaMetaModel = context.Settings.Get<SagaMetadataCollection>(); sagaMetaModel.Initialize(context.Settings.GetAvailableTypes(), conventions); var verifyIfEntitiesAreShared = !context.Settings.GetOrDefault<bool>(SagaSettings.DisableVerifyingIfEntitiesAreShared); if (verifyIfEntitiesAreShared) { sagaMetaModel.VerifyIfEntitiesAreShared(); } RegisterCustomFindersInContainer(context.Services, sagaMetaModel); foreach (var t in context.Settings.GetAvailableTypes()) { if (IsSagaNotFoundHandler(t)) { context.Services.AddTransient(typeof(IHandleSagaNotFound), t); } } // Register the Saga related behaviors for incoming messages context.Pipeline.Register("InvokeSaga", b => new SagaPersistenceBehavior(b.GetRequiredService<ISagaPersister>(), sagaIdGenerator, sagaMetaModel), "Invokes the saga logic"); context.Pipeline.Register("InvokeSagaNotFound", new InvokeSagaNotFoundBehavior(), "Invokes saga not found logic"); context.Pipeline.Register("AttachSagaDetailsToOutGoingMessage", new AttachSagaDetailsToOutGoingMessageBehavior(), "Makes sure that outgoing messages have saga info attached to them"); } static void RegisterCustomFindersInContainer(IServiceCollection container, IEnumerable<SagaMetadata> sagaMetaModel) { foreach (var finder in sagaMetaModel.SelectMany(m => m.Finders)) { container.AddTransient(finder.Type); if (finder.Properties.TryGetValue("custom-finder-clr-type", out var customFinderType)) { container.AddTransient((Type)customFinderType); } } } static bool IsSagaType(Type t) { return IsCompatible(t, typeof(Saga)); } static bool IsSagaNotFoundHandler(Type t) { return IsCompatible(t, typeof(IHandleSagaNotFound)); } static bool IsCompatible(Type t, Type source) { return source.IsAssignableFrom(t) && t != source && !t.IsAbstract && !t.IsInterface && !t.IsGenericType; } static bool IsTypeATimeoutHandledByAnySaga(Type type, IEnumerable<Type> sagas) { // MakeGenericType() throws an exception if passed a ref struct type // Messages cannot be ref struct types if (type.IsByRefLike) { return false; } var timeoutHandler = typeof(IHandleTimeouts<>).MakeGenericType(type); var messageHandler = typeof(IHandleMessages<>).MakeGenericType(type); return sagas.Any(t => timeoutHandler.IsAssignableFrom(t) && !messageHandler.IsAssignableFrom(t)); } Conventions conventions; }
1
0.885954
1
0.885954
game-dev
MEDIA
0.809661
game-dev
0.827463
1
0.827463
SebLague/Tiny-Chess-Bot-Challenge-Results
3,463
Bots/Bot_298.cs
namespace auto_Bot_298; using ChessChallenge.API; using System; using System.Collections.Generic; using System.Linq; public class Bot_298 : IChessBot { public Dictionary<string, int> eve = new(); public Dictionary<string, int> cck = new(); public int width = 1; public int timerestrict = 1300; public Move Think(Board board, Timer timer) { if (timer.MillisecondsRemaining < 12000) { width = 4; return SmallCheck(board, 0, 3).Key; } Move x = SmallCheck(board, 0, 4).Key; DivertedConsole.Write((width, timer.MillisecondsElapsedThisTurn, "evaluate:", Evaluate(board))); if (timer.MillisecondsElapsedThisTurn > timerestrict + 200) { width -= 1; } else if (timer.MillisecondsElapsedThisTurn < timerestrict - 200) { width += 1; } return x; } public KeyValuePair<Move, int> SmallCheck(Board board, int frames, int limit) { Move[] moves = board.GetLegalMoves(); Dictionary<Move, int> hihi = new(); for (int i = 0; i < moves.Length; i++) { board.MakeMove(moves[i]); string f = board.GetFenString(); if (frames < limit && board.GetLegalMoves().Length > 0) { if (!cck.ContainsKey(f)) { cck[f] = -SmallCheck(board, 0, 0).Value; } hihi[moves[i]] = cck[f]; } else { if (!eve.ContainsKey(f)) { eve[f] = Evaluate(board); } hihi[moves[i]] = eve[f]; } board.UndoMove(moves[i]); } if (frames < limit) { List<KeyValuePair<Move, int>> sorted = hihi.OrderBy(kv => kv.Value).ToList(); for (int i = 0; i < Math.Min(width, hihi.Count); i++) { board.MakeMove(sorted[i].Key); if (board.GetLegalMoves().Length > 0) { hihi[sorted[i].Key] = -SmallCheck(board, frames + 1, limit).Value; } board.UndoMove(sorted[i].Key); } } KeyValuePair<Move, int> hehe = hihi.Aggregate((l, r) => l.Value < r.Value ? l : r); return hehe; //returns how good the position is for the next player } readonly PieceType[] piece_types = { PieceType.Pawn, PieceType.Knight, PieceType.Bishop, PieceType.Rook, PieceType.Queen }; readonly int[] piece_values = { 94, 281, 297, 512, 936 }; public int Evaluate(Board board) { if (board.IsInCheckmate()) { return -9000000; } if (board.IsDraw()) { return 0; } if (board.IsInCheck()) { return -SmallCheck(board, 0, 0).Value; } bool white = board.IsWhiteToMove; int value = 0; for (int i = 0; i < piece_types.Length; i++) { int count = board.GetPieceList(piece_types[i], white).Count - board.GetPieceList(piece_types[i], !white).Count; value += piece_values[i] * count; } //value += board.GetLegalMoves().Length; board.TrySkipTurn(); value -= board.GetLegalMoves().Length; board.UndoSkipTurn(); return value; } }
1
0.814258
1
0.814258
game-dev
MEDIA
0.480276
game-dev
0.905069
1
0.905069
ntorm1/Atlas
1,333
modules/model/XGBoost.hpp
#pragma once #ifdef ATLAS_EXPORTS #define ATLAS_API __declspec(dllexport) #else #define ATLAS_API __declspec(dllimport) #endif #include "AtlasFeature.hpp" #ifdef ATLAS_XGBOOST import ModelBaseModule; #include "standard/AtlasLinAlg.hpp" #include "standard/AtlasCore.hpp" namespace Atlas { namespace Model { class XGBoostModel; //============================================================================ class XGBoostModelConfig { friend class XGBoostModel; private: SharedPtr<ModelConfig> m_base_config; public: ATLAS_API XGBoostModelConfig( SharedPtr<ModelConfig> base_config ) noexcept; ATLAS_API ~XGBoostModelConfig() noexcept = default; }; struct XGBoostModelImpl; //============================================================================ class XGBoostModel : public ModelBase { private: XGBoostModelImpl* m_impl; SharedPtr<const XGBoostModelConfig> m_xgb_config; public: ATLAS_API XGBoostModel( String id, Vector<SharedPtr<AST::StrategyBufferOpNode>> features, SharedPtr<ModelTarget> target, SharedPtr<const XGBoostModelConfig> config ) noexcept; ATLAS_API ~XGBoostModel() noexcept; void train() noexcept override; void reset() noexcept override; void predict() noexcept override; [[nodiscard]] bool isSame(StrategyBufferOpNode const* other) const noexcept override; }; } } #endif
1
0.813928
1
0.813928
game-dev
MEDIA
0.336131
game-dev
0.500599
1
0.500599
MicrosoftDocs/cpp-docs
10,732
docs/parallel/concrt/reference/concurrency-namespace-operators.md
--- description: "Learn more about: concurrency namespace Operators" title: "concurrency namespace Operators" ms.date: "11/04/2016" f1_keywords: ["concrt/concurrency::operator!=", "concrt/concurrency::operator&&"] ms.assetid: 8e373f23-fc8e-49f7-82e6-ba0c57b822f8 --- # concurrency namespace Operators :::row::: :::column span=""::: [`operator||`](#operator_lor)\ [`operator&&`](#operator_amp_amp) :::column-end::: :::column span=""::: [`operator==`](#operator_eq_eq)\ [`operator!=`](#operator_neq) :::column-end::: :::column span=""::: [`operator<`](#operator_lt)\ [`operator<=`](#operator_lt_eq) :::column-end::: :::column span=""::: [`operator>`](#operator_gt)\ [`operator>=`](#operator_gt_eq) :::column-end::: :::row-end::: ## <a name="operator_lor"></a> `operator||` Operator Creates a task that will complete successfully when either of the tasks supplied as arguments completes successfully. ```cpp template<typename ReturnType> task<ReturnType> operator||( const task<ReturnType>& lhs, const task<ReturnType>& rhs); template<typename ReturnType> task<std::vector<ReturnType>> operator||( const task<std::vector<ReturnType>>& lhs, const task<ReturnType>& rhs); template<typename ReturnType> task<std::vector<ReturnType>> operator||( const task<ReturnType>& lhs, const task<std::vector<ReturnType>>& rhs); inline task<void> operator||( const task<void>& lhs, const task<void>& rhs); ``` ### Parameters *ReturnType*<br/> The type of the returned task. *lhs*<br/> The first task to combine into the resulting task. *rhs*<br/> The second task to combine into the resulting task. ### Return Value A task that completes successfully when either of the input tasks has completed successfully. If the input tasks are of type `T`, the output of this function will be a `task<std::vector<T>`. If the input tasks are of type **`void`** the output task will also be a `task<void>`. ### Remarks If both of the tasks are canceled or throw exceptions, the returned task will complete in the canceled state, and one of the exceptions, if any are encountered, will be thrown when you call `get()` or `wait()` on that task. ## <a name="operator_amp_amp"></a> `operator&&` Operator Creates a task that will complete successfully when both of the tasks supplied as arguments complete successfully. ```cpp template<typename ReturnType> task<std::vector<ReturnType>> operator&&( const task<ReturnType>& lhs, const task<ReturnType>& rhs); template<typename ReturnType> task<std::vector<ReturnType>> operator&&( const task<std::vector<ReturnType>>& lhs, const task<ReturnType>& rhs); template<typename ReturnType> task<std::vector<ReturnType>> operator&&( const task<ReturnType>& lhs, const task<std::vector<ReturnType>>& rhs); template<typename ReturnType> task<std::vector<ReturnType>> operator&&( const task<std::vector<ReturnType>>& lhs, const task<std::vector<ReturnType>>& rhs); inline task<void> operator&&( const task<void>& lhs, const task<void>& rhs); ``` ### Parameters *ReturnType*<br/> The type of the returned task. *lhs*<br/> The first task to combine into the resulting task. *rhs*<br/> The second task to combine into the resulting task. ### Return Value A task that completes successfully when both of the input tasks have completed successfully. If the input tasks are of type `T`, the output of this function will be a `task<std::vector<T>>`. If the input tasks are of type **`void`** the output task will also be a `task<void>`. ### Remarks If one of the tasks is canceled or throws an exception, the returned task will complete early, in the canceled state, and the exception, if one occurs, will be thrown if you call `get()` or `wait()` on that task. ## <a name="operator_eq_eq"></a> operator== Operator Tests if the `concurrent_vector` object on the left side of the operator is equal to the `concurrent_vector` object on the right side. ```cpp template<typename T, class A1, class A2> inline bool operator== ( const concurrent_vector<T, A1>& _A, const concurrent_vector<T, A2>& _B); ``` ### Parameters *T*<br/> The data type of the elements stored in the concurrent vectors. *A1*<br/> The allocator type of the first `concurrent_vector` object. *A2*<br/> The allocator type of the second `concurrent_vector` object. *_A*<br/> An object of type `concurrent_vector`. *_B*<br/> An object of type `concurrent_vector`. ### Return Value **`true`** if the concurrent vector on the left side of the operator is equal to the concurrent vector on the right side of the operator; otherwise **`false`**. ### Remarks Two concurrent vectors are equal if they have the same number of elements and their respective elements have the same values. Otherwise, they are unequal. This method is not concurrency-safe with respect to other methods that could modify either of the concurrent vectors `_A` or `_B`. ## <a name="operator_neq"></a> operator!= Operator Tests if the `concurrent_vector` object on the left side of the operator is not equal to the `concurrent_vector` object on the right side. ```cpp template<typename T, class A1, class A2> inline bool operator!= ( const concurrent_vector<T, A1>& _A, const concurrent_vector<T, A2>& _B); ``` ### Parameters *T*<br/> The data type of the elements stored in the concurrent vectors. *A1*<br/> The allocator type of the first `concurrent_vector` object. *A2*<br/> The allocator type of the second `concurrent_vector` object. *_A*<br/> An object of type `concurrent_vector`. *_B*<br/> An object of type `concurrent_vector`. ### Return Value **`true`** if the concurrent vectors are not equal; **`false`** if the concurrent vectors are equal. ### Remarks Two concurrent vectors are equal if they have the same number of elements and their respective elements have the same values. Otherwise, they are unequal. This method is not concurrency-safe with respect to other methods that could modify either of the concurrent vectors `_A` or `_B`. ## <a name="operator_lt"></a> `operator<` Operator Tests if the `concurrent_vector` object on the left side of the operator is less than the `concurrent_vector` object on the right side. ```cpp template<typename T, class A1, class A2> inline bool operator<( const concurrent_vector<T, A1>& _A, const concurrent_vector<T, A2>& _B); ``` ### Parameters *T*<br/> The data type of the elements stored in the concurrent vectors. *A1*<br/> The allocator type of the first `concurrent_vector` object. *A2*<br/> The allocator type of the second `concurrent_vector` object. *_A*<br/> An object of type `concurrent_vector`. *_B*<br/> An object of type `concurrent_vector`. ### Return Value **`true`** if the concurrent vector on the left side of the operator is less than the concurrent vector on the right side of the operator; otherwise **`false`**. ### Remarks The behavior of this operator is identical to the equivalent operator for the `vector` class in the `std` namespace. This method is not concurrency-safe with respect to other methods that could modify either of the concurrent vectors `_A` or `_B`. ## <a name="operator_lt_eq"></a> `operator<=` Operator Tests if the `concurrent_vector` object on the left side of the operator is less than or equal to the `concurrent_vector` object on the right side. ```cpp template<typename T, class A1, class A2> inline bool operator<= ( const concurrent_vector<T, A1>& _A, const concurrent_vector<T, A2>& _B); ``` ### Parameters *T*<br/> The data type of the elements stored in the concurrent vectors. *A1*<br/> The allocator type of the first `concurrent_vector` object. *A2*<br/> The allocator type of the second `concurrent_vector` object. *_A*<br/> An object of type `concurrent_vector`. *_B*<br/> An object of type `concurrent_vector`. ### Return Value **`true`** if the concurrent vector on the left side of the operator is less than or equal to the concurrent vector on the right side of the operator; otherwise **`false`**. ### Remarks The behavior of this operator is identical to the equivalent operator for the `vector` class in the `std` namespace. This method is not concurrency-safe with respect to other methods that could modify either of the concurrent vectors `_A` or `_B`. ## <a name="operator_gt"></a> `operator>` Operator Tests if the `concurrent_vector` object on the left side of the operator is greater than the `concurrent_vector` object on the right side. ```cpp template<typename T, class A1, class A2> inline bool operator>( const concurrent_vector<T, A1>& _A, const concurrent_vector<T, A2>& _B); ``` ### Parameters *T*<br/> The data type of the elements stored in the concurrent vectors. *A1*<br/> The allocator type of the first `concurrent_vector` object. *A2*<br/> The allocator type of the second `concurrent_vector` object. *_A*<br/> An object of type `concurrent_vector`. *_B*<br/> An object of type `concurrent_vector`. ### Return Value **`true`** if the concurrent vector on the left side of the operator is greater than the concurrent vector on the right side of the operator; otherwise **`false`**. ### Remarks The behavior of this operator is identical to the equivalent operator for the `vector` class in the `std` namespace. This method is not concurrency-safe with respect to other methods that could modify either of the concurrent vectors `_A` or `_B`. ## <a name="operator_gt_eq"></a> `operator>=` Operator Tests if the `concurrent_vector` object on the left side of the operator is greater than or equal to the `concurrent_vector` object on the right side. ```cpp template<typename T, class A1, class A2> inline bool operator>= ( const concurrent_vector<T, A1>& _A, const concurrent_vector<T, A2>& _B); ``` ### Parameters *T*<br/> The data type of the elements stored in the concurrent vectors. *A1*<br/> The allocator type of the first `concurrent_vector` object. *A2*<br/> The allocator type of the second `concurrent_vector` object. *_A*<br/> An object of type `concurrent_vector`. *_B*<br/> An object of type `concurrent_vector`. ### Return Value **`true`** if the concurrent vector on the left side of the operator is greater than or equal to the concurrent vector on the right side of the operator; otherwise **`false`**. ### Remarks The behavior of this operator is identical to the equivalent operator for the `vector` class in the `std` namespace. This method is not concurrency-safe with respect to other methods that could modify either of the concurrent vectors `_A` or `_B`. ## See also [concurrency Namespace](concurrency-namespace.md)
1
0.854041
1
0.854041
game-dev
MEDIA
0.268563
game-dev
0.933588
1
0.933588
AntaresSimulatorTeam/Antares_Simulator
1,117
src/tests/resources/modeler/1_6/input/model-libraries/lib_example_1_6.yml
library: id: lib_example_1_6 description: test model library models: - id: node_2gen_1load description: A simple node with two generators and one load parameters: - id: load time-dependent: false scenario-dependent: false - id: gen1_max_p time-dependent: false scenario-dependent: false - id: gen1_prop_cost time-dependent: true scenario-dependent: false - id: gen2_max_p time-dependent: true scenario-dependent: false - id: gen2_prop_cost time-dependent: false scenario-dependent: false variables: - id: gen1_p lower-bound: 0 upper-bound: gen1_max_p variable-type: continuous - id: gen2_p lower-bound: 0 upper-bound: gen2_max_p variable-type: continuous constraints: - id: balance expression: gen1_p + gen2_p - load = 0 objective-contributions: - id: objective expression: gen1_p * gen1_prop_cost + gen2_p * gen2_prop_cost
1
0.618365
1
0.618365
game-dev
MEDIA
0.840661
game-dev
0.645555
1
0.645555
SimFlowCFD/RapidCFD-dev
6,325
src/OpenFOAM/meshes/primitiveShapes/objectHit/PointIndexHit.H
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::PointIndexHit Description This class describes the interaction of (usually) a face and a point. It carries the info of a successful hit and (if successful), returns the interaction point. like pointHit but carries face (or cell, edge etc.) index SourceFiles \*---------------------------------------------------------------------------*/ #ifndef PointIndexHit_H #define PointIndexHit_H #include "bool.H" #include "point.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class PointIndexHit Declaration \*---------------------------------------------------------------------------*/ template<class Point> class PointIndexHit { // Private data //- Hit success bool hit_; //- Point of hit; invalid for misses Point hitPoint_; //- label of face hit label index_; public: // Constructors //- Construct from components PointIndexHit(const bool success, const Point& p, const label index) : hit_(success), hitPoint_(p), index_(index) {} //- Construct from point. Hit and distance set later PointIndexHit(const Point& p) : hit_(false), hitPoint_(p), index_(-1) {} //- Construct null PointIndexHit() : hit_(false), hitPoint_(vector::zero), index_(-1) {} //- Construct from Istream PointIndexHit(Istream& is) { is >> *this; } // Member Functions //- Is there a hit bool hit() const { return hit_; } //- Return index label index() const { return index_; } //- Return hit point const Point& hitPoint() const { if (!hit_) { FatalErrorIn("PointIndexHit::hitPoint() const") << "requested a hit point for a miss" << abort(FatalError); } return hitPoint_; } //- Return miss point const Point& missPoint() const { if (hit_) { FatalErrorIn("PointIndexHit::missPoint() const") << "requested a miss point for a hit" << abort(FatalError); } return hitPoint_; } //- Return point with no checking const Point& rawPoint() const { return hitPoint_; } Point& rawPoint() { return hitPoint_; } void setHit() { hit_ = true; } void setMiss() { hit_ = false; } void setPoint(const Point& p) { hitPoint_ = p; } void setIndex(const label index) { index_ = index; } bool operator==(const PointIndexHit& rhs) const { return hit_ == rhs.hit() && hitPoint_ == rhs.rawPoint() && index_ == rhs.index(); } bool operator!=(const PointIndexHit& rhs) const { return !operator==(rhs); } void write(Ostream& os) { if (hit()) { os << "hit:" << hitPoint() << " index:" << index(); } else { os << "miss:" << missPoint() << " index:" << index(); } } friend Ostream& operator<< (Ostream& os, const PointIndexHit& pHit) { if (os.format() == IOstream::ASCII) { os << pHit.hit_ << token::SPACE << pHit.hitPoint_ << token::SPACE << pHit.index_; } else { os.write ( reinterpret_cast<const char*>(&pHit), sizeof(PointIndexHit) ); } // Check state of Ostream os.check("Ostream& operator<<(Ostream&, const PointIndexHit&)"); return os; } friend Istream& operator>>(Istream& is, PointIndexHit& pHit) { if (is.format() == IOstream::ASCII) { return is >> pHit.hit_ >> pHit.hitPoint_ >> pHit.index_; } else { is.read ( reinterpret_cast<char*>(&pHit), sizeof(PointIndexHit) ); } // Check state of Istream is.check("Istream& operator>>(Istream&, PointIndexHit&)"); return is; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
1
0.914178
1
0.914178
game-dev
MEDIA
0.547516
game-dev
0.945092
1
0.945092
Prograda/Skybolt
1,808
src/Skybolt/SkyboltCommon/Event.h
/* Copyright Matthew Reid * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #pragma once #include <vector> #include <map> #include <memory> #include <set> #include <typeindex> namespace skybolt { class Event { public: virtual ~Event() {} }; class EventEmitter; //! Receives Events emitted by EventEmitter class EventListener { public: EventListener(); virtual ~EventListener(); virtual void onEvent(const Event&) = 0; private: void _addEmitter(EventEmitter*); void _removeEmitter(EventEmitter*); std::set<EventEmitter*> mEmitters; bool mDestroying; friend class EventEmitter; }; //! Class for emitting events which can be received by EventListener class EventEmitter { public: virtual ~EventEmitter(); template <class EventT> void addEventListener(EventListener* listener) { listener->_addEmitter(this); mListenerMap[typeid(EventT)].insert(listener); } //! Call this to explicitally remove a listener. //! Otherwise listener will be removed automatically when the listener is destroyed. void removeEventListener(EventListener*); template <class EventT> void emitEvent(const EventT& event) const { auto it = mListenerMap.find(typeid(event)); if (it != mListenerMap.end()) { // Take copy of listeners before calling onEvent(), // incase the listeners list changes as a result of onEvent(). std::set<EventListener*> listeners = it->second; for (const auto& item : listeners) { item->onEvent(event); } } } private: typedef std::set<EventListener*> EventListeners; typedef std::map<std::type_index, EventListeners> ListenerMap; ListenerMap mListenerMap; }; } // namespace skybolt
1
0.912658
1
0.912658
game-dev
MEDIA
0.218079
game-dev
0.933802
1
0.933802
microsoft/Win2D-Samples
11,941
ExampleGallery/Particles/ParticleSystem.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using Microsoft.Graphics.Canvas; using System; using System.Collections.Generic; using System.Numerics; using System.Threading.Tasks; using Windows.Foundation; namespace ExampleGallery { // ParticleSystem is an abstract class that provides the basic functionality to // create a particle effect. Different subclasses will have different effects, // such as fire, explosions, and plumes of smoke. To use these subclasses, // simply call AddParticles, and pass in where the particles should be created. public abstract class ParticleSystem { // The texture this particle system will use. protected CanvasBitmap bitmap; Vector2 bitmapCenter; Rect bitmapBounds; // The particles currently in use by this system. These are reused, // so calling AddParticles will not normally cause any allocations. List<Particle> activeParticles = new List<Particle>(); // Keeps track of particles that are not curently being used by an effect. // When new particles are requested, particles are taken from here. // When particles are finished they are transferred back to here. static Stack<Particle> freeParticles = new Stack<Particle>(); // This region of values control the "look" of the particle system, and should // be set by derived particle systems in the InitializeConstants method. The // values are then used by the virtual function InitializeParticle. Subclasses // can override InitializeParticle for further customization. #region Constants to be set by subclasses // minNumParticles and maxNumParticles control the number of particles that are // added when AddParticles is called. The number of particles will be a random // number between minNumParticles and maxNumParticles. protected int minNumParticles; protected int maxNumParticles; // This controls the bitmap that the particle system uses. protected string bitmapFilename; // minInitialSpeed and maxInitialSpeed are used to control the initial velocity // of the particles. The particle's initial speed will be a random number between these two. // The direction is determined by the function PickRandomDirection, which can be overriden. protected float minInitialSpeed; protected float maxInitialSpeed; // minAcceleration and maxAcceleration are used to control the acceleration of the particles. // The particle's acceleration will be a random number between these two. By default, the // direction of acceleration is the same as the direction of the initial velocity. protected float minAcceleration; protected float maxAcceleration; // minRotationSpeed and maxRotationSpeed control the particles' angular velocity: the // speed at which particles will rotate. Each particle's rotation speed will be a random // number between minRotationSpeed and maxRotationSpeed. Use smaller numbers to make // particle systems look calm and wispy, and large numbers for more violent effects. protected float minRotationSpeed; protected float maxRotationSpeed; // minLifetime and maxLifetime are used to control the lifetime. Each particle's lifetime // will be a random number between these two. Lifetime is used to determine how long a // particle "lasts." Also, in the base implementation of Draw, lifetime is also used to // calculate alpha and scale values to avoid particles suddenly "popping" into view protected float minLifetime; protected float maxLifetime; // to get some additional variance in the appearance of the particles, we give them all // random scales. the scale is a value between minScale and maxScale, and is additionally // affected by the particle's lifetime to avoid particles "popping" into view. protected float minScale; protected float maxScale; // Different effects can use different blend states. // Fire and explosions work well with additive blending, for example. protected CanvasBlend blendState; #endregion // Constructs a new ParticleSystem. protected ParticleSystem() { InitializeConstants(); } // This abstract function must be overriden by subclasses of ParticleSystem. It is // here that they should set all the constants marked in the region "constants to // be set by subclasses", which give each ParticleSystem its specific flavor. protected abstract void InitializeConstants(); // Loads the bitmap that will be used to draw this particle system. public virtual async Task CreateResourcesAsync(ICanvasResourceCreator resourceCreator) { bitmap = await CanvasBitmap.LoadAsync(resourceCreator, bitmapFilename); bitmapCenter = bitmap.Size.ToVector2() / 2; bitmapBounds = bitmap.Bounds; } // AddParticles's job is to add an effect somewhere on the screen. public void AddParticles(Vector2 where) { // The number of particles we want for this effect is a random number // somewhere between the two constants specified by the subclasses. int numParticles = Utils.Random.Next(minNumParticles, maxNumParticles); // Activate that many particles. for (int i = 0; i < numParticles; i++) { // Grab a particle from the freeParticles store, or create a new one if freeParticles is empty. Particle particle = (freeParticles.Count > 0) ? freeParticles.Pop() : new Particle(); InitializeParticle(particle, where); activeParticles.Add(particle); } } // Randomizes some properties for a particle, then calls Initialize on it. // This can be overriden by subclasses if they want to modify the way particles // are created. For example, SmokePlumeParticleSystem overrides this function // make all particles accelerate to the right, simulating wind. protected virtual void InitializeParticle(Particle particle, Vector2 where) { // First, call PickRandomDirection to figure out which way the particle // will be moving. Velocity and acceleration values will come from this. Vector2 direction = PickRandomDirection(); // Pick some random values for our particle. float velocity = Utils.RandomBetween(minInitialSpeed, maxInitialSpeed); float acceleration = Utils.RandomBetween(minAcceleration, maxAcceleration); float lifetime = Utils.RandomBetween(minLifetime, maxLifetime); float scale = Utils.RandomBetween(minScale, maxScale); float rotationSpeed = Utils.RandomBetween(minRotationSpeed, maxRotationSpeed); // Then initialize the particle with these random values. particle.Initialize(where, velocity * direction, acceleration * direction, lifetime, scale, rotationSpeed); } // PickRandomDirection is used by InitializeParticles to decide which direction // particles will move. The default implementation is a random vector on a circle. protected virtual Vector2 PickRandomDirection() { float angle = Utils.RandomBetween(0, (float)Math.PI * 2); return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)); } // Updates all of the active particles. public void Update(float elapsedTime) { // Go through the active particles in reverse order, so our loop // index stays valid even when we decide to remove some of them. for (int i = activeParticles.Count - 1; i >= 0; i--) { Particle particle = activeParticles[i]; if (!particle.Update(elapsedTime)) { // If the particle is no longer active, move it from activeParticles to freeParticles. activeParticles.RemoveAt(i); freeParticles.Push(particle); } } } // Draws all of the active particles. public void Draw(CanvasDrawingSession drawingSession, bool useSpriteBatch) { var previousBlend = drawingSession.Blend; drawingSession.Blend = blendState; if (useSpriteBatch) { using (var spriteBatch = drawingSession.CreateSpriteBatch()) { Draw(drawingSession, spriteBatch); } } else { Draw(drawingSession, null); } drawingSession.Blend = previousBlend; } void Draw(CanvasDrawingSession drawingSession, CanvasSpriteBatch spriteBatch) { // Go through the particles in reverse order, so new ones are drawn underneath // older ones. This improves visual appearance of effects like smoke plume // where many particles are created at the same position over a period of time. for (int i = activeParticles.Count - 1; i >= 0; i--) { Particle particle = activeParticles[i]; // Normalized lifetime is a value from 0 to 1 and represents how far a particle // is through its life. 0 means it just started, .5 is half way through, and // 1.0 means it's just about to be finished. This value will be used to calculate // alpha and scale, to avoid having particles suddenly appear or disappear. float normalizedLifetime = particle.TimeSinceStart / particle.Lifetime; // We want particles to fade in and fade out, so we'll calculate alpha to be // (normalizedLifetime) * (1 - normalizedLifetime). This way, when normalizedLifetime // is 0 or 1, alpha is 0. The maximum value is at normalizedLifetime = .5, and is: // // (normalizedLifetime) * (1-normalizedLifetime) // (.5) * (1-.5) // .25 // // Since we want the maximum alpha to be 1, not .25, we'll scale the entire equation by 4. float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime); // Make particles grow as they age. // They'll start at 75% of their size, and increase to 100% once they're finished. float scale = particle.Scale * (.75f + .25f * normalizedLifetime); if (spriteBatch != null) { spriteBatch.Draw(bitmap, particle.Position, new Vector4(1, 1, 1, alpha), bitmapCenter, particle.Rotation, new Vector2(scale), CanvasSpriteFlip.None); } else { // Compute a transform matrix for this particle. var transform = Matrix3x2.CreateRotation(particle.Rotation, bitmapCenter) * Matrix3x2.CreateScale(scale, bitmapCenter) * Matrix3x2.CreateTranslation(particle.Position - bitmapCenter); // Draw the particle. drawingSession.DrawImage(bitmap, 0, 0, bitmapBounds, alpha, CanvasImageInterpolation.Linear, new Matrix4x4(transform)); } } } } }
1
0.883753
1
0.883753
game-dev
MEDIA
0.851889
game-dev,graphics-rendering
0.843245
1
0.843245
Hoto-Mocha/New-Blue-Archive-Pixel-Dungeon
1,561
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Roots.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2025 Evan Debenham * * 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.shatteredpixel.shatteredpixeldungeon.actors.buffs; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.ui.BuffIndicator; public class Roots extends FlavourBuff { public static final float DURATION = 5f; { type = buffType.NEGATIVE; announced = true; } @Override public boolean attachTo( Char target ) { if (!target.flying && super.attachTo( target )) { target.rooted = true; return true; } else { return false; } } @Override public void detach() { target.rooted = false; super.detach(); } @Override public int icon() { return BuffIndicator.ROOTS; } @Override public float iconFadePercent() { return Math.max(0, (DURATION - visualcooldown()) / DURATION); } }
1
0.543929
1
0.543929
game-dev
MEDIA
0.973734
game-dev
0.562098
1
0.562098
nerdcave/CollisionSprite
5,237
examples/cocos2d 1.x (no iPad retina)/PhysicsEditorSpriteTest/libs/Box2D/Dynamics/Joints/b2PrismaticJoint.h
/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * 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 B2_PRISMATIC_JOINT_H #define B2_PRISMATIC_JOINT_H #include <Box2D/Dynamics/Joints/b2Joint.h> /// Prismatic joint definition. This requires defining a line of /// motion using an axis and an anchor point. The definition uses local /// anchor points and a local axis so that the initial configuration /// can violate the constraint slightly. The joint translation is zero /// when the local anchor points coincide in world space. Using local /// anchors and a local axis helps when saving and loading a game. /// @warning at least one body should by dynamic with a non-fixed rotation. struct b2PrismaticJointDef : public b2JointDef { b2PrismaticJointDef() { type = e_prismaticJoint; localAnchorA.SetZero(); localAnchorB.SetZero(); localAxis1.Set(1.0f, 0.0f); referenceAngle = 0.0f; enableLimit = false; lowerTranslation = 0.0f; upperTranslation = 0.0f; enableMotor = false; maxMotorForce = 0.0f; motorSpeed = 0.0f; } /// Initialize the bodies, anchors, axis, and reference angle using the world /// anchor and world axis. void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); /// The local anchor point relative to body1's origin. b2Vec2 localAnchorA; /// The local anchor point relative to body2's origin. b2Vec2 localAnchorB; /// The local translation axis in body1. b2Vec2 localAxis1; /// The constrained angle between the bodies: body2_angle - body1_angle. float32 referenceAngle; /// Enable/disable the joint limit. bool enableLimit; /// The lower translation limit, usually in meters. float32 lowerTranslation; /// The upper translation limit, usually in meters. float32 upperTranslation; /// Enable/disable the joint motor. bool enableMotor; /// The maximum motor torque, usually in N-m. float32 maxMotorForce; /// The desired motor speed in radians per second. float32 motorSpeed; }; /// A prismatic joint. This joint provides one degree of freedom: translation /// along an axis fixed in body1. Relative rotation is prevented. You can /// use a joint limit to restrict the range of motion and a joint motor to /// drive the motion or to model joint friction. class b2PrismaticJoint : public b2Joint { public: b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorB() const; b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; /// Get the current joint translation, usually in meters. float32 GetJointTranslation() const; /// Get the current joint translation speed, usually in meters per second. float32 GetJointSpeed() const; /// Is the joint limit enabled? bool IsLimitEnabled() const; /// Enable/disable the joint limit. void EnableLimit(bool flag); /// Get the lower joint limit, usually in meters. float32 GetLowerLimit() const; /// Get the upper joint limit, usually in meters. float32 GetUpperLimit() const; /// Set the joint limits, usually in meters. void SetLimits(float32 lower, float32 upper); /// Is the joint motor enabled? bool IsMotorEnabled() const; /// Enable/disable the joint motor. void EnableMotor(bool flag); /// Set the motor speed, usually in meters per second. void SetMotorSpeed(float32 speed); /// Get the motor speed, usually in meters per second. float32 GetMotorSpeed() const; /// Set the maximum motor force, usually in N. void SetMaxMotorForce(float32 force); /// Get the current motor force, usually in N. float32 GetMotorForce() const; protected: friend class b2Joint; friend class b2GearJoint; b2PrismaticJoint(const b2PrismaticJointDef* def); void InitVelocityConstraints(const b2TimeStep& step); void SolveVelocityConstraints(const b2TimeStep& step); bool SolvePositionConstraints(float32 baumgarte); b2Vec2 m_localAnchor1; b2Vec2 m_localAnchor2; b2Vec2 m_localXAxis1; b2Vec2 m_localYAxis1; float32 m_refAngle; b2Vec2 m_axis, m_perp; float32 m_s1, m_s2; float32 m_a1, m_a2; b2Mat33 m_K; b2Vec3 m_impulse; float32 m_motorMass; // effective mass for motor/limit translational constraint. float32 m_motorImpulse; float32 m_lowerTranslation; float32 m_upperTranslation; float32 m_maxMotorForce; float32 m_motorSpeed; bool m_enableLimit; bool m_enableMotor; b2LimitState m_limitState; }; inline float32 b2PrismaticJoint::GetMotorSpeed() const { return m_motorSpeed; } #endif
1
0.861923
1
0.861923
game-dev
MEDIA
0.974252
game-dev
0.799234
1
0.799234
quinoacomputing/quinoa
3,184
src/Control/Toggle.hpp
// ***************************************************************************** /*! \file src/Control/Toggle.hpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019-2021 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Toggle is the base for an Option, doing generic searches \details Toggle is the base for an Option, doing generic searches. */ // ***************************************************************************** #ifndef Toggle_h #define Toggle_h #include <map> #include "Exception.hpp" #include "PrintUtil.hpp" namespace tk { //! \brief Toggle is the base for an Option, doing generic searches //! \details Toggle is templated on an enum type (a strongly typed enum), whose //! values are used as keys in maps of associated option values. //! \see Control/Option for client code examples template< typename Enum > class Toggle { public: using EnumType = Enum; //! Used to access template typename from outside //! Lookup group name const std::string& group() const { return groupname; } //! Lookup Enum value based on keyword, Enum must exist //! \param[in] keyword Keyword to search for //! \return Strongly-typed enum value associated to keyword if found Enum value( const std::string& keyword ) const { auto it = values.find( keyword ); Assert( it != end(values), std::string("Cannot find value for keyword \"") + keyword + "\"" ); return it->second; } //! Check if keyword exists //! \param[in] keyword Keyword to search for //! \return True if keyword if found bool exist( const std::string& keyword ) const { return values.find( keyword ) != end( values ) ? true : false; } //! Lookup option name based on Enum //! \param[in] val Enum value to search for //! \return Keyword if enum value is found const std::string& name( Enum val ) const { auto it = names.find( val ); Assert( it != end(names), std::string("Cannot find name for value \"") << val << "\"" ); return it->second; } protected: //! Constructor protected: designed to be used only as a base class //! \param[in] g Group name of the option set //! \param[in] n Map associating enum values to option names //! \param[in] v Map associating keyword strings to enum values //! \details Note that all arguments are rvalues, thus the objects gutted //! and this is the only constructor provided. explicit Toggle( std::string&& g, std::map< Enum, std::string >&& n, std::map< std::string, Enum >&& v ) : groupname( std::move(g) ), names( std::move(n) ), values( std::move(v) ) { Assert( names.size() == values.size(), "map sizes differ in Toggle" ); } private: std::string groupname; //!< Group name of the option set std::map< Enum, std::string > names; //!< Map of enums -> names std::map< std::string, Enum > values; //!< Map of keywords -> enums }; } // tk:: #endif // Toggle_h
1
0.931395
1
0.931395
game-dev
MEDIA
0.210409
game-dev
0.924811
1
0.924811
spartanoah/acrimony-client
2,049
net/minecraft/entity/projectile/EntityEgg.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package net.minecraft.entity.projectile; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityChicken; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; public class EntityEgg extends EntityThrowable { public EntityEgg(World worldIn) { super(worldIn); } public EntityEgg(World worldIn, EntityLivingBase throwerIn) { super(worldIn, throwerIn); } public EntityEgg(World worldIn, double x, double y, double z) { super(worldIn, x, y, z); } @Override protected void onImpact(MovingObjectPosition p_70184_1_) { if (p_70184_1_.entityHit != null) { p_70184_1_.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0.0f); } if (!this.worldObj.isRemote && this.rand.nextInt(8) == 0) { int i = 1; if (this.rand.nextInt(32) == 0) { i = 4; } for (int j = 0; j < i; ++j) { EntityChicken entitychicken = new EntityChicken(this.worldObj); entitychicken.setGrowingAge(-24000); entitychicken.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, 0.0f); this.worldObj.spawnEntityInWorld(entitychicken); } } double d0 = 0.08; for (int k = 0; k < 8; ++k) { this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, this.posX, this.posY, this.posZ, ((double)this.rand.nextFloat() - 0.5) * 0.08, ((double)this.rand.nextFloat() - 0.5) * 0.08, ((double)this.rand.nextFloat() - 0.5) * 0.08, Item.getIdFromItem(Items.egg)); } if (!this.worldObj.isRemote) { this.setDead(); } } }
1
0.614219
1
0.614219
game-dev
MEDIA
0.992782
game-dev
0.556316
1
0.556316
lzk228/space-axolotl-14
1,037
Content.Shared/Radiation/Systems/RadiationPulseSystem.cs
using Content.Shared.Radiation.Components; using Robust.Shared.Spawners; using Robust.Shared.Timing; namespace Content.Shared.Radiation.Systems; public sealed class RadiationPulseSystem : EntitySystem { [Dependency] private readonly IGameTiming _timing = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<RadiationPulseComponent, ComponentStartup>(OnStartup); } private void OnStartup(EntityUid uid, RadiationPulseComponent component, ComponentStartup args) { component.StartTime = _timing.RealTime; // try to get despawn time or keep default duration time if (TryComp<TimedDespawnComponent>(uid, out var despawn)) { component.VisualDuration = despawn.Lifetime; } // try to get radiation range or keep default visual range if (TryComp<RadiationSourceComponent>(uid, out var radSource)) { component.VisualRange = radSource.Intensity / radSource.Slope; } } }
1
0.896596
1
0.896596
game-dev
MEDIA
0.532521
game-dev
0.75326
1
0.75326
Dimbreath/AzurLaneData
2,848
zh-TW/model/vo/powerrank.lua
slot0 = class("PowerRank", import(".PlayerAttire")) slot0.TYPE_POWER = 1 slot0.TYPE_COLLECTION = 2 slot0.TYPE_PT = 3 slot0.TYPE_PLEDGE = 4 slot0.TYPE_CHALLENGE = 5 slot0.TYPE_EXTRA_CHAPTER = 6 slot0.TYPE_ACT_BOSS_BATTLE = 7 slot0.TYPE_MILITARY_RANK = 8 slot0.typeInfo = { { title_word = { 5, 8, 7, 1 }, score_icon = { "ui/billboardui_atlas", "power_icon" } }, { title_word = { 5, 8, 7, 2 } }, { title_word = { 5, 8, 7, 2 }, score_icon = { "ui/commonui_atlas", "pt_icon" }, act_type = ActivityConst.ACTIVITY_TYPE_PT_RANK }, { title_word = { 5, 8, 7, 3 } }, { title_word = { 5, 8, 7, 4 }, act_type = ActivityConst.ACTIVITY_TYPE_CHALLENGE_RANK }, { title_word = { 5, 8, 7, 4 }, act_type = ActivityConst.ACTIVITY_TYPE_EXTRA_CHAPTER_RANK }, { title_word = { 5, 8, 7, 10 }, act_type = ActivityConst.ACTIVITY_TYPE_BOSS_RANK }, { title_word = { 5, 8, 6, 9 }, score_icon = { "ui/billboardui_atlas", "rank_icon" } } } function slot0.Ctor(slot0, slot1, slot2) uv0.super.Ctor(slot0, slot1) slot0.id = slot1.user_id or slot1.id slot0.lv = slot1.lv or slot1.level slot0.name = slot1.name slot0.power = slot1.point or slot1.score or 0 slot0.rank = slot1.rank or 0 slot0.arenaRank = math.min(math.max(slot1.arena_rank or 0, 1), 14) slot0.type = slot2 end function slot0.getPainting(slot0) return pg.ship_skin_template[slot0.skinId] and slot1.painting or "unknown" end function slot0.setRank(slot0, slot1) slot0.rank = slot1 end function slot0.setArenaRank(slot0, slot1) slot0.arenaRank = slot1 end function slot0.getPowerTxt(slot0) if slot0.type == uv0.TYPE_POWER then return math.floor(slot0.power^0.667) elseif slot0.type == uv0.TYPE_COLLECTION then return string.format("%0.01f", slot0.power / getProxy(CollectionProxy):getCollectionTotal() * 100) .. "%" elseif slot0.type == uv0.TYPE_MILITARY_RANK then return slot0.power + SeasonInfo.INIT_POINT else return slot0.power end end function slot0.getTitleWord(slot0, slot1, slot2) for slot7 = 1, 4 do table.insert({}, i18n("ranking_word_" .. uv0.typeInfo[slot1].title_word[slot7])) end if slot1 == uv0.TYPE_PT then slot3[4] = pg.item_data_statistics[id2ItemId(getProxy(ActivityProxy):getActivityById(slot2):getConfig("config_id"))].name end return slot3 end function slot0.getScoreIcon(slot0, slot1) return uv0.typeInfo[slot1].score_icon end function slot0.getActivityByRankType(slot0, slot1) if not uv0.typeInfo[slot1].act_type then return nil end return _.detect(getProxy(ActivityProxy):getActivitiesByType(uv0.typeInfo[slot1].act_type), function (slot0) return not slot0:isEnd() and (uv0 ~= uv1.TYPE_PT or tonumber(slot0:getConfig("config_data")) > 0) end) end return slot0
1
0.721837
1
0.721837
game-dev
MEDIA
0.904851
game-dev
0.799613
1
0.799613
Demonheadge/PokeScape
62,926
src/evolution_scene.c
#include "global.h" #include "malloc.h" #include "battle.h" #include "battle_message.h" #include "bg.h" #include "data.h" #include "decompress.h" #include "evolution_scene.h" #include "evolution_graphics.h" #include "gpu_regs.h" #include "item.h" #include "link.h" #include "link_rfu.h" #include "m4a.h" #include "main.h" #include "menu.h" #include "overworld.h" #include "palette.h" #include "pokedex.h" #include "pokemon.h" #include "pokemon_summary_screen.h" #include "scanline_effect.h" #include "sound.h" #include "sprite.h" #include "string_util.h" #include "strings.h" #include "task.h" #include "text.h" #include "text_window.h" #include "trig.h" #include "trade.h" #include "util.h" #include "constants/battle_string_ids.h" #include "constants/songs.h" #include "constants/rgb.h" #include "constants/items.h" struct EvoInfo { u8 preEvoSpriteId; u8 postEvoSpriteId; u8 evoTaskId; u8 delayTimer; u16 savedPalette[48]; }; static EWRAM_DATA struct EvoInfo *sEvoStructPtr = NULL; static EWRAM_DATA u16 *sBgAnimPal = NULL; void (*gCB2_AfterEvolution)(void); #define sEvoCursorPos gBattleCommunication[1] // when learning a new move #define sEvoGraphicsTaskId gBattleCommunication[2] static void Task_EvolutionScene(u8 taskId); static void Task_TradeEvolutionScene(u8 taskId); static void CB2_EvolutionSceneUpdate(void); static void CB2_TradeEvolutionSceneUpdate(void); static void EvoDummyFunc(void); static void VBlankCB_EvolutionScene(void); static void VBlankCB_TradeEvolutionScene(void); static void EvoScene_DoMonAnimAndCry(u8 monSpriteId, u16 speciesId); static bool32 EvoScene_IsMonAnimFinished(u8 monSpriteId); static void StartBgAnimation(bool8 isLink); static void StopBgAnimation(void); static void Task_AnimateBg(u8 taskId); static void RestoreBgAfterAnim(void); static const u16 sUnusedPal1[] = INCBIN_U16("graphics/evolution_scene/unused_1.gbapal"); static const u32 sBgAnim_Gfx[] = INCBIN_U32("graphics/evolution_scene/bg.4bpp.lz"); static const u32 sBgAnim_Inner_Tilemap[] = INCBIN_U32("graphics/evolution_scene/bg_inner.bin.lz"); static const u32 sBgAnim_Outer_Tilemap[] = INCBIN_U32("graphics/evolution_scene/bg_outer.bin.lz"); static const u16 sBgAnim_Intro_Pal[] = INCBIN_U16("graphics/evolution_scene/bg_anim_intro.gbapal"); static const u16 sUnusedPal2[] = INCBIN_U16("graphics/evolution_scene/unused_2.gbapal"); static const u16 sUnusedPal3[] = INCBIN_U16("graphics/evolution_scene/unused_3.gbapal"); static const u16 sUnusedPal4[] = INCBIN_U16("graphics/evolution_scene/unused_4.gbapal"); static const u16 sBgAnim_Pal[] = INCBIN_U16("graphics/evolution_scene/bg_anim.gbapal"); static const u8 sText_ShedinjaJapaneseName[] = _("ヌケニン"); // The below table is used by Task_UpdateBgPalette to control the speed at which the bg color updates. // The first two values are indexes into sBgAnim_PalIndexes (indirectly, via sBgAnimPal), and are // the start and end of the range of colors in sBgAnim_PalIndexes it will move through incrementally // before starting over. It will repeat this cycle x number of times, where x = the 3rd value, // delaying each increment by y, where y = the 4th value. // Once it has cycled x number of times, it will move to the next array in this table. static const u8 sBgAnim_PaletteControl[][4] = { { 0, 12, 1, 6 }, { 13, 36, 5, 2 }, { 13, 24, 1, 2 }, { 37, 49, 1, 6 }, }; // Indexes into sBgAnim_Pal, 0 is black, transitioning to a bright light blue (172, 213, 255) at 13 static const u8 sBgAnim_PalIndexes[][16] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0 }, { 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0 }, { 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0 }, { 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 0, 0 }, { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 0 }, { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 12, 0, 0 }, { 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 12, 11, 0, 0 }, { 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 12, 11, 10, 0, 0 }, { 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 12, 11, 10, 9, 0, 0 }, { 0, 6, 7, 8, 9, 10, 11, 12, 13, 12, 11, 10, 9, 8, 0, 0 }, { 0, 7, 8, 9, 10, 11, 12, 13, 12, 11, 10, 9, 8, 7, 0, 0 }, { 0, 8, 9, 10, 11, 12, 13, 12, 11, 10, 9, 8, 7, 6, 0, 0 }, { 0, 9, 10, 11, 12, 13, 12, 11, 10, 9, 8, 7, 6, 5, 0, 0 }, { 0, 10, 11, 12, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 0, 0 }, { 0, 11, 12, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 0, 0 }, { 0, 12, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 0, 0 }, { 0, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0 }, { 0, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 0, 0 }, { 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 0, 0 }, { 0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 0, 0 }, { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 0, 0 }, { 0, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 0, 0 }, { 0, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 0, 0 }, { 0, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0 }, { 0, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0 }, { 0, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0 }, { 0, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0 }, { 0, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 0 }, { 0, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0 }, { 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0 }, { 0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0 }, { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; static void CB2_BeginEvolutionScene(void) { UpdatePaletteFade(); RunTasks(); } #define tState data[0] #define tPreEvoSpecies data[1] #define tPostEvoSpecies data[2] #define tCanStop data[3] #define tBits data[3] #define tLearnsFirstMove data[4] #define tLearnMoveState data[6] #define tLearnMoveYesState data[7] #define tLearnMoveNoState data[8] #define tEvoWasStopped data[9] #define tPartyId data[10] #define TASK_BIT_CAN_STOP (1 << 0) #define TASK_BIT_LEARN_MOVE (1 << 7) static void Task_BeginEvolutionScene(u8 taskId) { struct Pokemon *mon = NULL; switch (gTasks[taskId].tState) { case 0: BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK); gTasks[taskId].tState++; break; case 1: if (!gPaletteFade.active) { u16 postEvoSpecies; bool8 canStopEvo; u8 partyId; mon = &gPlayerParty[gTasks[taskId].tPartyId]; postEvoSpecies = gTasks[taskId].tPostEvoSpecies; canStopEvo = gTasks[taskId].tCanStop; partyId = gTasks[taskId].tPartyId; DestroyTask(taskId); EvolutionScene(mon, postEvoSpecies, canStopEvo, partyId); } break; } } void BeginEvolutionScene(struct Pokemon *mon, u16 postEvoSpecies, bool8 canStopEvo, u8 partyId) { u8 taskId = CreateTask(Task_BeginEvolutionScene, 0); gTasks[taskId].tState = 0; gTasks[taskId].tPostEvoSpecies = postEvoSpecies; gTasks[taskId].tCanStop = canStopEvo; gTasks[taskId].tPartyId = partyId; SetMainCallback2(CB2_BeginEvolutionScene); } void EvolutionScene(struct Pokemon *mon, u16 postEvoSpecies, bool8 canStopEvo, u8 partyId) { u8 name[POKEMON_NAME_BUFFER_SIZE]; u16 currSpecies; u32 trainerId, personality; u8 id; SetHBlankCallback(NULL); SetVBlankCallback(NULL); CpuFill32(0, (void *)(VRAM), VRAM_SIZE); SetGpuReg(REG_OFFSET_MOSAIC, 0); SetGpuReg(REG_OFFSET_WIN0H, 0); SetGpuReg(REG_OFFSET_WIN0V, 0); SetGpuReg(REG_OFFSET_WIN1H, 0); SetGpuReg(REG_OFFSET_WIN1V, 0); SetGpuReg(REG_OFFSET_WININ, 0); SetGpuReg(REG_OFFSET_WINOUT, 0); ResetPaletteFade(); gBattle_BG0_X = 0; gBattle_BG0_Y = 0; gBattle_BG1_X = 0; gBattle_BG1_Y = 0; gBattle_BG2_X = 0; gBattle_BG2_Y = 0; gBattle_BG3_X = 256; gBattle_BG3_Y = 0; gBattleTerrain = BATTLE_TERRAIN_PLAIN; InitBattleBgsVideo(); LoadBattleTextboxAndBackground(); ResetSpriteData(); ScanlineEffect_Stop(); ResetTasks(); FreeAllSpritePalettes(); gReservedSpritePaletteCount = 4; sEvoStructPtr = AllocZeroed(sizeof(struct EvoInfo)); AllocateMonSpritesGfx(); GetMonData(mon, MON_DATA_NICKNAME, name); StringCopy_Nickname(gStringVar1, name); StringCopy(gStringVar2, GetSpeciesName(postEvoSpecies)); // preEvo sprite currSpecies = GetMonData(mon, MON_DATA_SPECIES); trainerId = GetMonData(mon, MON_DATA_OT_ID); personality = GetMonData(mon, MON_DATA_PERSONALITY); LoadSpecialPokePic(gMonSpritesGfxPtr->sprites.ptr[B_POSITION_OPPONENT_LEFT], currSpecies, personality, TRUE); LoadCompressedPalette(GetMonSpritePalFromSpeciesAndPersonality(currSpecies, trainerId, personality), OBJ_PLTT_ID(1), PLTT_SIZE_4BPP); SetMultiuseSpriteTemplateToPokemon(currSpecies, B_POSITION_OPPONENT_LEFT); gMultiuseSpriteTemplate.affineAnims = gDummySpriteAffineAnimTable; sEvoStructPtr->preEvoSpriteId = id = CreateSprite(&gMultiuseSpriteTemplate, 120, 64, 30); gSprites[id].callback = SpriteCallbackDummy_2; gSprites[id].oam.paletteNum = 1; gSprites[id].invisible = TRUE; // postEvo sprite LoadSpecialPokePic(gMonSpritesGfxPtr->sprites.ptr[B_POSITION_OPPONENT_RIGHT], postEvoSpecies, personality, TRUE); LoadCompressedPalette(GetMonSpritePalFromSpeciesAndPersonality(postEvoSpecies, trainerId, personality), OBJ_PLTT_ID(2), PLTT_SIZE_4BPP); SetMultiuseSpriteTemplateToPokemon(postEvoSpecies, B_POSITION_OPPONENT_RIGHT); gMultiuseSpriteTemplate.affineAnims = gDummySpriteAffineAnimTable; sEvoStructPtr->postEvoSpriteId = id = CreateSprite(&gMultiuseSpriteTemplate, 120, 64, 30); gSprites[id].callback = SpriteCallbackDummy_2; gSprites[id].oam.paletteNum = 2; gSprites[id].invisible = TRUE; LoadEvoSparkleSpriteAndPal(); sEvoStructPtr->evoTaskId = id = CreateTask(Task_EvolutionScene, 0); gTasks[id].tState = 0; gTasks[id].tPreEvoSpecies = currSpecies; gTasks[id].tPostEvoSpecies = postEvoSpecies; gTasks[id].tCanStop = canStopEvo; gTasks[id].tLearnsFirstMove = TRUE; gTasks[id].tEvoWasStopped = FALSE; gTasks[id].tPartyId = partyId; memcpy(&sEvoStructPtr->savedPalette, &gPlttBufferUnfaded[BG_PLTT_ID(2)], sizeof(sEvoStructPtr->savedPalette)); SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_OBJ_ON | DISPCNT_BG_ALL_ON | DISPCNT_OBJ_1D_MAP); SetHBlankCallback(EvoDummyFunc); SetVBlankCallback(VBlankCB_EvolutionScene); m4aMPlayAllStop(); SetMainCallback2(CB2_EvolutionSceneUpdate); } static void CB2_EvolutionSceneLoadGraphics(void) { u8 id; u16 postEvoSpecies; u32 trainerId, personality; struct Pokemon *mon = &gPlayerParty[gTasks[sEvoStructPtr->evoTaskId].tPartyId]; postEvoSpecies = gTasks[sEvoStructPtr->evoTaskId].tPostEvoSpecies; trainerId = GetMonData(mon, MON_DATA_OT_ID); personality = GetMonData(mon, MON_DATA_PERSONALITY); SetHBlankCallback(NULL); SetVBlankCallback(NULL); CpuFill32(0, (void *)(VRAM), VRAM_SIZE); SetGpuReg(REG_OFFSET_MOSAIC, 0); SetGpuReg(REG_OFFSET_WIN0H, 0); SetGpuReg(REG_OFFSET_WIN0V, 0); SetGpuReg(REG_OFFSET_WIN1H, 0); SetGpuReg(REG_OFFSET_WIN1V, 0); SetGpuReg(REG_OFFSET_WININ, 0); SetGpuReg(REG_OFFSET_WINOUT, 0); ResetPaletteFade(); gBattle_BG0_X = 0; gBattle_BG0_Y = 0; gBattle_BG1_X = 0; gBattle_BG1_Y = 0; gBattle_BG2_X = 0; gBattle_BG2_Y = 0; gBattle_BG3_X = 256; gBattle_BG3_Y = 0; gBattleTerrain = BATTLE_TERRAIN_PLAIN; InitBattleBgsVideo(); LoadBattleTextboxAndBackground(); ResetSpriteData(); FreeAllSpritePalettes(); gReservedSpritePaletteCount = 4; LoadSpecialPokePic(gMonSpritesGfxPtr->sprites.ptr[B_POSITION_OPPONENT_RIGHT], postEvoSpecies, personality, TRUE); LoadCompressedPalette(GetMonSpritePalFromSpeciesAndPersonality(postEvoSpecies, trainerId, personality), OBJ_PLTT_ID(2), PLTT_SIZE_4BPP); SetMultiuseSpriteTemplateToPokemon(postEvoSpecies, B_POSITION_OPPONENT_RIGHT); gMultiuseSpriteTemplate.affineAnims = gDummySpriteAffineAnimTable; sEvoStructPtr->postEvoSpriteId = id = CreateSprite(&gMultiuseSpriteTemplate, 120, 64, 30); gSprites[id].callback = SpriteCallbackDummy_2; gSprites[id].oam.paletteNum = 2; SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_OBJ_ON | DISPCNT_BG_ALL_ON | DISPCNT_OBJ_1D_MAP); SetHBlankCallback(EvoDummyFunc); SetVBlankCallback(VBlankCB_EvolutionScene); SetMainCallback2(CB2_EvolutionSceneUpdate); BeginNormalPaletteFade(PALETTES_ALL, 0, 0x10, 0, RGB_BLACK); ShowBg(0); ShowBg(1); ShowBg(2); ShowBg(3); } static void CB2_TradeEvolutionSceneLoadGraphics(void) { struct Pokemon *mon = &gPlayerParty[gTasks[sEvoStructPtr->evoTaskId].tPartyId]; u16 postEvoSpecies = gTasks[sEvoStructPtr->evoTaskId].tPostEvoSpecies; switch (gMain.state) { case 0: SetGpuReg(REG_OFFSET_DISPCNT, 0); SetHBlankCallback(NULL); SetVBlankCallback(NULL); ResetSpriteData(); FreeAllSpritePalettes(); gReservedSpritePaletteCount = 4; gBattle_BG0_X = 0; gBattle_BG0_Y = 0; gBattle_BG1_X = 0; gBattle_BG1_Y = 0; gBattle_BG2_X = 0; gBattle_BG2_Y = 0; gBattle_BG3_X = 256; gBattle_BG3_Y = 0; gMain.state++; break; case 1: ResetPaletteFade(); SetHBlankCallback(EvoDummyFunc); SetVBlankCallback(VBlankCB_TradeEvolutionScene); gMain.state++; break; case 2: LoadTradeAnimGfx(); gMain.state++; break; case 3: FillBgTilemapBufferRect(1, 0, 0, 0, 0x20, 0x20, 0x11); CopyBgTilemapBufferToVram(1); gMain.state++; break; case 4: { u32 trainerId = GetMonData(mon, MON_DATA_OT_ID); u32 personality = GetMonData(mon, MON_DATA_PERSONALITY); LoadSpecialPokePic(gMonSpritesGfxPtr->sprites.ptr[B_POSITION_OPPONENT_RIGHT], postEvoSpecies, personality, TRUE); LoadCompressedPalette(GetMonSpritePalFromSpeciesAndPersonality(postEvoSpecies, trainerId, personality), OBJ_PLTT_ID(2), PLTT_SIZE_4BPP); gMain.state++; } break; case 5: { u8 id; SetMultiuseSpriteTemplateToPokemon(postEvoSpecies, B_POSITION_OPPONENT_LEFT); gMultiuseSpriteTemplate.affineAnims = gDummySpriteAffineAnimTable; sEvoStructPtr->postEvoSpriteId = id = CreateSprite(&gMultiuseSpriteTemplate, 120, 64, 30); gSprites[id].callback = SpriteCallbackDummy_2; gSprites[id].oam.paletteNum = 2; gMain.state++; LinkTradeDrawWindow(); } break; case 6: if (gWirelessCommType) { LoadWirelessStatusIndicatorSpriteGfx(); CreateWirelessStatusIndicatorSprite(0, 0); } BlendPalettes(PALETTES_ALL, 0x10, RGB_BLACK); gMain.state++; break; case 7: BeginNormalPaletteFade(PALETTES_ALL, 0, 0x10, 0, RGB_BLACK); InitTradeSequenceBgGpuRegs(); ShowBg(0); ShowBg(1); SetMainCallback2(CB2_TradeEvolutionSceneUpdate); SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_OBJ_ON | DISPCNT_BG0_ON | DISPCNT_BG1_ON | DISPCNT_OBJ_1D_MAP); break; } } void TradeEvolutionScene(struct Pokemon *mon, u16 postEvoSpecies, u8 preEvoSpriteId, u8 partyId) { u8 name[POKEMON_NAME_BUFFER_SIZE]; u16 currSpecies; u32 trainerId, personality; u8 id; GetMonData(mon, MON_DATA_NICKNAME, name); StringCopy_Nickname(gStringVar1, name); StringCopy(gStringVar2, GetSpeciesName(postEvoSpecies)); gAffineAnimsDisabled = TRUE; // preEvo sprite currSpecies = GetMonData(mon, MON_DATA_SPECIES); personality = GetMonData(mon, MON_DATA_PERSONALITY); trainerId = GetMonData(mon, MON_DATA_OT_ID); sEvoStructPtr = AllocZeroed(sizeof(struct EvoInfo)); sEvoStructPtr->preEvoSpriteId = preEvoSpriteId; LoadSpecialPokePic(gMonSpritesGfxPtr->sprites.ptr[B_POSITION_OPPONENT_LEFT], postEvoSpecies, personality, TRUE); LoadCompressedPalette(GetMonSpritePalFromSpeciesAndPersonality(postEvoSpecies, trainerId, personality), OBJ_PLTT_ID(2), PLTT_SIZE_4BPP); SetMultiuseSpriteTemplateToPokemon(postEvoSpecies, B_POSITION_OPPONENT_LEFT); gMultiuseSpriteTemplate.affineAnims = gDummySpriteAffineAnimTable; sEvoStructPtr->postEvoSpriteId = id = CreateSprite(&gMultiuseSpriteTemplate, 120, 64, 30); gSprites[id].callback = SpriteCallbackDummy_2; gSprites[id].oam.paletteNum = 2; gSprites[id].invisible = TRUE; LoadEvoSparkleSpriteAndPal(); sEvoStructPtr->evoTaskId = id = CreateTask(Task_TradeEvolutionScene, 0); gTasks[id].tState = 0; gTasks[id].tPreEvoSpecies = currSpecies; gTasks[id].tPostEvoSpecies = postEvoSpecies; gTasks[id].tLearnsFirstMove = TRUE; gTasks[id].tEvoWasStopped = FALSE; gTasks[id].tPartyId = partyId; gBattle_BG0_X = 0; gBattle_BG0_Y = 0; gBattle_BG1_X = 0; gBattle_BG1_Y = 0; gBattle_BG2_X = 0; gBattle_BG2_Y = 0; gBattle_BG3_X = 256; gBattle_BG3_Y = 0; gTextFlags.useAlternateDownArrow = TRUE; SetVBlankCallback(VBlankCB_TradeEvolutionScene); SetMainCallback2(CB2_TradeEvolutionSceneUpdate); } static void CB2_EvolutionSceneUpdate(void) { AnimateSprites(); BuildOamBuffer(); RunTextPrinters(); UpdatePaletteFade(); RunTasks(); } static void CB2_TradeEvolutionSceneUpdate(void) { AnimateSprites(); BuildOamBuffer(); RunTextPrinters(); UpdatePaletteFade(); RunTasks(); } static void CreateShedinja(u16 preEvoSpecies, struct Pokemon *mon) { u32 data = 0; #if P_SHEDINJA_BALL >= GEN_4 u16 ball = ITEM_POUCH; #endif const struct Evolution *evolutions = GetSpeciesEvolutions(preEvoSpecies); if (evolutions == NULL) return; if (evolutions[0].method == EVO_LEVEL_NINJASK && gPlayerPartyCount < PARTY_SIZE #if P_SHEDINJA_BALL >= GEN_4 && (CheckBagHasItem(ball, 1)) #endif ) { s32 i; struct Pokemon *shedinja = &gPlayerParty[gPlayerPartyCount]; CopyMon(&gPlayerParty[gPlayerPartyCount], mon, sizeof(struct Pokemon)); SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_SPECIES, &evolutions[1].targetSpecies); SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_NICKNAME, GetSpeciesName(evolutions[1].targetSpecies)); SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_HELD_ITEM, &data); SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_MARKINGS, &data); SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_ENCRYPT_SEPARATOR, &data); #if P_SHEDINJA_BALL >= GEN_4 SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_POKEBALL, &ball); RemoveBagItem(ball, 1); #endif for (i = MON_DATA_COOL_RIBBON; i < MON_DATA_COOL_RIBBON + CONTEST_CATEGORIES_COUNT; i++) SetMonData(&gPlayerParty[gPlayerPartyCount], i, &data); for (i = MON_DATA_CHAMPION_RIBBON; i <= MON_DATA_UNUSED_RIBBONS; i++) SetMonData(&gPlayerParty[gPlayerPartyCount], i, &data); SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_STATUS, &data); data = MAIL_NONE; SetMonData(&gPlayerParty[gPlayerPartyCount], MON_DATA_MAIL, &data); CalculateMonStats(&gPlayerParty[gPlayerPartyCount]); CalculatePlayerPartyCount(); GetSetPokedexFlag(SpeciesToNationalPokedexNum(evolutions[1].targetSpecies), FLAG_SET_SEEN); GetSetPokedexFlag(SpeciesToNationalPokedexNum(evolutions[1].targetSpecies), FLAG_SET_CAUGHT); if (GetMonData(shedinja, MON_DATA_SPECIES) == SPECIES_SHEDINJA && GetMonData(shedinja, MON_DATA_LANGUAGE) == LANGUAGE_JAPANESE && GetMonData(mon, MON_DATA_SPECIES) == SPECIES_NINJASK) SetMonData(shedinja, MON_DATA_NICKNAME, sText_ShedinjaJapaneseName); } } // States for the main switch in Task_EvolutionScene enum { EVOSTATE_FADE_IN, EVOSTATE_INTRO_MSG, EVOSTATE_INTRO_MON_ANIM, EVOSTATE_INTRO_SOUND, EVOSTATE_START_MUSIC, EVOSTATE_START_BG_AND_SPARKLE_SPIRAL, EVOSTATE_SPARKLE_ARC, EVOSTATE_CYCLE_MON_SPRITE, EVOSTATE_WAIT_CYCLE_MON_SPRITE, EVOSTATE_SPARKLE_CIRCLE, EVOSTATE_SPARKLE_SPRAY, EVOSTATE_EVO_SOUND, EVOSTATE_RESTORE_SCREEN, EVOSTATE_EVO_MON_ANIM, EVOSTATE_SET_MON_EVOLVED, EVOSTATE_TRY_LEARN_MOVE, EVOSTATE_END, EVOSTATE_CANCEL, EVOSTATE_CANCEL_MON_ANIM, EVOSTATE_CANCEL_MSG, EVOSTATE_LEARNED_MOVE, EVOSTATE_TRY_LEARN_ANOTHER_MOVE, EVOSTATE_REPLACE_MOVE, }; // States for the switch in EVOSTATE_REPLACE_MOVE enum { MVSTATE_INTRO_MSG_1, MVSTATE_INTRO_MSG_2, MVSTATE_INTRO_MSG_3, MVSTATE_PRINT_YES_NO, MVSTATE_HANDLE_YES_NO, MVSTATE_SHOW_MOVE_SELECT, MVSTATE_HANDLE_MOVE_SELECT, MVSTATE_FORGET_MSG_1, MVSTATE_FORGET_MSG_2, MVSTATE_LEARNED_MOVE, MVSTATE_ASK_CANCEL, MVSTATE_CANCEL, MVSTATE_RETRY_AFTER_HM, }; // Task data from CycleEvolutionMonSprite #define tEvoStopped data[8] static void Task_EvolutionScene(u8 taskId) { u32 var; struct Pokemon *mon = &gPlayerParty[gTasks[taskId].tPartyId]; // check if B Button was held, so the evolution gets stopped if (gMain.heldKeys == B_BUTTON && gTasks[taskId].tState == EVOSTATE_WAIT_CYCLE_MON_SPRITE && gTasks[sEvoGraphicsTaskId].isActive && gTasks[taskId].tBits & TASK_BIT_CAN_STOP) { gTasks[taskId].tState = EVOSTATE_CANCEL; gTasks[sEvoGraphicsTaskId].tEvoStopped = TRUE; StopBgAnimation(); return; } switch (gTasks[taskId].tState) { case EVOSTATE_FADE_IN: BeginNormalPaletteFade(PALETTES_ALL, 0, 0x10, 0, RGB_BLACK); gSprites[sEvoStructPtr->preEvoSpriteId].invisible = FALSE; gTasks[taskId].tState++; ShowBg(0); ShowBg(1); ShowBg(2); ShowBg(3); break; case EVOSTATE_INTRO_MSG: if (!gPaletteFade.active) { StringExpandPlaceholders(gStringVar4, gText_PkmnIsEvolving); BattlePutTextOnWindow(gStringVar4, B_WIN_MSG); gTasks[taskId].tState++; } break; case EVOSTATE_INTRO_MON_ANIM: if (!IsTextPrinterActive(0)) { EvoScene_DoMonAnimAndCry(sEvoStructPtr->preEvoSpriteId, gTasks[taskId].tPreEvoSpecies); gTasks[taskId].tState++; } break; case EVOSTATE_INTRO_SOUND: if (EvoScene_IsMonAnimFinished(sEvoStructPtr->preEvoSpriteId)) { PlaySE(MUS_EVOLUTION_INTRO); gTasks[taskId].tState++; } break; case EVOSTATE_START_MUSIC: if (!IsSEPlaying()) { // Start music, fade background to black PlayNewMapMusic(MUS_EVOLUTION); gTasks[taskId].tState++; BeginNormalPaletteFade(0x1C, 4, 0, 0x10, RGB_BLACK); } break; case EVOSTATE_START_BG_AND_SPARKLE_SPIRAL: if (!gPaletteFade.active) { StartBgAnimation(FALSE); sEvoGraphicsTaskId = EvolutionSparkles_SpiralUpward(17); gTasks[taskId].tState++; } break; case EVOSTATE_SPARKLE_ARC: if (!gTasks[sEvoGraphicsTaskId].isActive) { gTasks[taskId].tState++; sEvoStructPtr->delayTimer = 1; sEvoGraphicsTaskId = EvolutionSparkles_ArcDown(); } break; case EVOSTATE_CYCLE_MON_SPRITE: // launch task that flashes pre evo with post evo sprites if (!gTasks[sEvoGraphicsTaskId].isActive) { sEvoGraphicsTaskId = CycleEvolutionMonSprite(sEvoStructPtr->preEvoSpriteId, sEvoStructPtr->postEvoSpriteId); gTasks[taskId].tState++; } break; case EVOSTATE_WAIT_CYCLE_MON_SPRITE: if (--sEvoStructPtr->delayTimer == 0) { sEvoStructPtr->delayTimer = 3; if (!gTasks[sEvoGraphicsTaskId].isActive) gTasks[taskId].tState++; } break; case EVOSTATE_SPARKLE_CIRCLE: sEvoGraphicsTaskId = EvolutionSparkles_CircleInward(); gTasks[taskId].tState++; break; case EVOSTATE_SPARKLE_SPRAY: if (!gTasks[sEvoGraphicsTaskId].isActive) { sEvoGraphicsTaskId = EvolutionSparkles_SprayAndFlash(gTasks[taskId].tPostEvoSpecies); gTasks[taskId].tState++; } break; case EVOSTATE_EVO_SOUND: if (!gTasks[sEvoGraphicsTaskId].isActive) { PlaySE(SE_EXP); gTasks[taskId].tState++; } break; case EVOSTATE_RESTORE_SCREEN: // stop music, return screen to pre-fade state if (IsSEPlaying()) { m4aMPlayAllStop(); memcpy(&gPlttBufferUnfaded[BG_PLTT_ID(2)], sEvoStructPtr->savedPalette, sizeof(sEvoStructPtr->savedPalette)); RestoreBgAfterAnim(); BeginNormalPaletteFade(0x1C, 0, 0x10, 0, RGB_BLACK); gTasks[taskId].tState++; } break; case EVOSTATE_EVO_MON_ANIM: if (!gPaletteFade.active) { EvoScene_DoMonAnimAndCry(sEvoStructPtr->postEvoSpriteId, gTasks[taskId].tPostEvoSpecies); gTasks[taskId].tState++; } break; case EVOSTATE_SET_MON_EVOLVED: if (IsCryFinished()) { StringExpandPlaceholders(gStringVar4, gText_CongratsPkmnEvolved); BattlePutTextOnWindow(gStringVar4, B_WIN_MSG); PlayBGM(MUS_EVOLVED); gTasks[taskId].tState++; SetMonData(mon, MON_DATA_SPECIES, (void *)(&gTasks[taskId].tPostEvoSpecies)); CalculateMonStats(mon); EvolutionRenameMon(mon, gTasks[taskId].tPreEvoSpecies, gTasks[taskId].tPostEvoSpecies); GetSetPokedexFlag(SpeciesToNationalPokedexNum(gTasks[taskId].tPostEvoSpecies), FLAG_SET_SEEN); GetSetPokedexFlag(SpeciesToNationalPokedexNum(gTasks[taskId].tPostEvoSpecies), FLAG_SET_CAUGHT); IncrementGameStat(GAME_STAT_EVOLVED_POKEMON); } break; case EVOSTATE_TRY_LEARN_MOVE: if (!IsTextPrinterActive(0)) { var = MonTryLearningNewMoveEvolution(mon, gTasks[taskId].tLearnsFirstMove); if (var != MOVE_NONE && !gTasks[taskId].tEvoWasStopped) { u8 nickname[POKEMON_NAME_BUFFER_SIZE]; if (!(gTasks[taskId].tBits & TASK_BIT_LEARN_MOVE)) { StopMapMusic(); Overworld_PlaySpecialMapMusic(); } gTasks[taskId].tBits |= TASK_BIT_LEARN_MOVE; gTasks[taskId].tLearnsFirstMove = FALSE; gTasks[taskId].tLearnMoveState = MVSTATE_INTRO_MSG_1; GetMonData(mon, MON_DATA_NICKNAME, nickname); StringCopy_Nickname(gBattleTextBuff1, nickname); if (var == MON_HAS_MAX_MOVES) gTasks[taskId].tState = EVOSTATE_REPLACE_MOVE; else if (var == MON_ALREADY_KNOWS_MOVE) break; else gTasks[taskId].tState = EVOSTATE_LEARNED_MOVE; } else // no move to learn, or evolution was canceled { BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK); gTasks[taskId].tState++; } } break; case EVOSTATE_END: if (!gPaletteFade.active) { if (!(gTasks[taskId].tBits & TASK_BIT_LEARN_MOVE)) { StopMapMusic(); Overworld_PlaySpecialMapMusic(); } if (!gTasks[taskId].tEvoWasStopped) CreateShedinja(gTasks[taskId].tPreEvoSpecies, mon); DestroyTask(taskId); FreeMonSpritesGfx(); FREE_AND_SET_NULL(sEvoStructPtr); FreeAllWindowBuffers(); SetMainCallback2(gCB2_AfterEvolution); } break; case EVOSTATE_CANCEL: if (!gTasks[sEvoGraphicsTaskId].isActive) { m4aMPlayAllStop(); BeginNormalPaletteFade(0x6001C, 0, 0x10, 0, RGB_WHITE); gTasks[taskId].tState++; } break; case EVOSTATE_CANCEL_MON_ANIM: if (!gPaletteFade.active) { EvoScene_DoMonAnimAndCry(sEvoStructPtr->preEvoSpriteId, gTasks[taskId].tPreEvoSpecies); gTasks[taskId].tState++; } break; case EVOSTATE_CANCEL_MSG: if (EvoScene_IsMonAnimFinished(sEvoStructPtr->preEvoSpriteId)) { if (gTasks[taskId].tEvoWasStopped) // FRLG auto cancellation StringExpandPlaceholders(gStringVar4, gText_EllipsisQuestionMark); else StringExpandPlaceholders(gStringVar4, gText_PkmnStoppedEvolving); BattlePutTextOnWindow(gStringVar4, B_WIN_MSG); gTasks[taskId].tEvoWasStopped = TRUE; gTasks[taskId].tState = EVOSTATE_TRY_LEARN_MOVE; } break; case EVOSTATE_LEARNED_MOVE: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { BufferMoveToLearnIntoBattleTextBuff2(); PlayFanfare(MUS_LEVEL_UP); BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_PKMNLEARNEDMOVE - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnsFirstMove = 0x40; // re-used as a counter gTasks[taskId].tState++; } break; case EVOSTATE_TRY_LEARN_ANOTHER_MOVE: if (!IsTextPrinterActive(0) && !IsSEPlaying() && --gTasks[taskId].tLearnsFirstMove == 0) gTasks[taskId].tState = EVOSTATE_TRY_LEARN_MOVE; break; case EVOSTATE_REPLACE_MOVE: switch (gTasks[taskId].tLearnMoveState) { case MVSTATE_INTRO_MSG_1: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { // "{mon} is trying to learn {move}" BufferMoveToLearnIntoBattleTextBuff2(); BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_TRYTOLEARNMOVE1 - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnMoveState++; } break; case MVSTATE_INTRO_MSG_2: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { // "But, {mon} can't learn more than four moves" BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_TRYTOLEARNMOVE2 - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnMoveState++; } break; case MVSTATE_INTRO_MSG_3: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { // "Delete a move to make room for {move}?" BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_TRYTOLEARNMOVE3 - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnMoveYesState = MVSTATE_SHOW_MOVE_SELECT; gTasks[taskId].tLearnMoveNoState = MVSTATE_ASK_CANCEL; gTasks[taskId].tLearnMoveState++; } case MVSTATE_PRINT_YES_NO: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { HandleBattleWindow(YESNOBOX_X_Y, 0); BattlePutTextOnWindow(gText_BattleYesNoChoice, B_WIN_YESNO); gTasks[taskId].tLearnMoveState++; sEvoCursorPos = 0; BattleCreateYesNoCursorAt(0); } break; case MVSTATE_HANDLE_YES_NO: // This Yes/No is used for both the initial "delete move?" prompt // and for the "stop learning move?" prompt // What Yes/No do next is determined by tLearnMoveYesState / tLearnMoveNoState if (JOY_NEW(DPAD_UP) && sEvoCursorPos != 0) { // Moved onto YES PlaySE(SE_SELECT); BattleDestroyYesNoCursorAt(sEvoCursorPos); sEvoCursorPos = 0; BattleCreateYesNoCursorAt(0); } if (JOY_NEW(DPAD_DOWN) && sEvoCursorPos == 0) { // Moved onto NO PlaySE(SE_SELECT); BattleDestroyYesNoCursorAt(sEvoCursorPos); sEvoCursorPos = 1; BattleCreateYesNoCursorAt(1); } if (JOY_NEW(A_BUTTON)) { HandleBattleWindow(YESNOBOX_X_Y, WINDOW_CLEAR); PlaySE(SE_SELECT); if (sEvoCursorPos != 0) { // NO gTasks[taskId].tLearnMoveState = gTasks[taskId].tLearnMoveNoState; } else { // YES gTasks[taskId].tLearnMoveState = gTasks[taskId].tLearnMoveYesState; if (gTasks[taskId].tLearnMoveState == MVSTATE_SHOW_MOVE_SELECT) BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK); } } if (JOY_NEW(B_BUTTON)) { // Equivalent to selecting NO HandleBattleWindow(YESNOBOX_X_Y, WINDOW_CLEAR); PlaySE(SE_SELECT); gTasks[taskId].tLearnMoveState = gTasks[taskId].tLearnMoveNoState; } break; case MVSTATE_SHOW_MOVE_SELECT: if (!gPaletteFade.active) { FreeAllWindowBuffers(); ShowSelectMovePokemonSummaryScreen(gPlayerParty, gTasks[taskId].tPartyId, gPlayerPartyCount - 1, CB2_EvolutionSceneLoadGraphics, gMoveToLearn); gTasks[taskId].tLearnMoveState++; } break; case MVSTATE_HANDLE_MOVE_SELECT: if (!gPaletteFade.active && gMain.callback2 == CB2_EvolutionSceneUpdate) { var = GetMoveSlotToReplace(); if (var == MAX_MON_MOVES) { // Didn't select move slot gTasks[taskId].tLearnMoveState = MVSTATE_ASK_CANCEL; } else { // Selected move to forget u16 move = GetMonData(mon, var + MON_DATA_MOVE1); if (IsMoveHM(move)) { // Can't forget HMs BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_HMMOVESCANTBEFORGOTTEN - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnMoveState = MVSTATE_RETRY_AFTER_HM; } else { // Forget move PREPARE_MOVE_BUFFER(gBattleTextBuff2, move) RemoveMonPPBonus(mon, var); SetMonMoveSlot(mon, gMoveToLearn, var); gTasks[taskId].tLearnMoveState++; } } } break; case MVSTATE_FORGET_MSG_1: BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_123POOF - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnMoveState++; break; case MVSTATE_FORGET_MSG_2: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_PKMNFORGOTMOVE - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnMoveState++; } break; case MVSTATE_LEARNED_MOVE: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_ANDELLIPSIS - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tState = EVOSTATE_LEARNED_MOVE; } break; case MVSTATE_ASK_CANCEL: BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_STOPLEARNINGMOVE - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tLearnMoveYesState = MVSTATE_CANCEL; gTasks[taskId].tLearnMoveNoState = MVSTATE_INTRO_MSG_1; gTasks[taskId].tLearnMoveState = MVSTATE_PRINT_YES_NO; break; case MVSTATE_CANCEL: BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_DIDNOTLEARNMOVE - BATTLESTRINGS_TABLE_START]); BattlePutTextOnWindow(gDisplayedStringBattle, B_WIN_MSG); gTasks[taskId].tState = EVOSTATE_TRY_LEARN_MOVE; break; case MVSTATE_RETRY_AFTER_HM: if (!IsTextPrinterActive(0) && !IsSEPlaying()) gTasks[taskId].tLearnMoveState = MVSTATE_SHOW_MOVE_SELECT; break; } break; } } // States for the main switch in Task_TradeEvolutionScene enum { T_EVOSTATE_INTRO_MSG, T_EVOSTATE_INTRO_CRY, T_EVOSTATE_INTRO_SOUND, T_EVOSTATE_START_MUSIC, T_EVOSTATE_START_BG_AND_SPARKLE_SPIRAL, T_EVOSTATE_SPARKLE_ARC, T_EVOSTATE_CYCLE_MON_SPRITE, T_EVOSTATE_WAIT_CYCLE_MON_SPRITE, T_EVOSTATE_SPARKLE_CIRCLE, T_EVOSTATE_SPARKLE_SPRAY, T_EVOSTATE_EVO_SOUND, T_EVOSTATE_EVO_MON_ANIM, T_EVOSTATE_SET_MON_EVOLVED, T_EVOSTATE_TRY_LEARN_MOVE, T_EVOSTATE_END, T_EVOSTATE_CANCEL, T_EVOSTATE_CANCEL_MON_ANIM, T_EVOSTATE_CANCEL_MSG, T_EVOSTATE_LEARNED_MOVE, T_EVOSTATE_TRY_LEARN_ANOTHER_MOVE, T_EVOSTATE_REPLACE_MOVE, }; // States for the switch in T_EVOSTATE_REPLACE_MOVE enum { T_MVSTATE_INTRO_MSG_1, T_MVSTATE_INTRO_MSG_2, T_MVSTATE_INTRO_MSG_3, T_MVSTATE_PRINT_YES_NO, T_MVSTATE_HANDLE_YES_NO, T_MVSTATE_SHOW_MOVE_SELECT, T_MVSTATE_HANDLE_MOVE_SELECT, T_MVSTATE_FORGET_MSG, T_MVSTATE_LEARNED_MOVE, T_MVSTATE_ASK_CANCEL, T_MVSTATE_CANCEL, T_MVSTATE_RETRY_AFTER_HM, }; // Compare to Task_EvolutionScene, very similar static void Task_TradeEvolutionScene(u8 taskId) { u32 var = 0; struct Pokemon *mon = &gPlayerParty[gTasks[taskId].tPartyId]; switch (gTasks[taskId].tState) { case T_EVOSTATE_INTRO_MSG: StringExpandPlaceholders(gStringVar4, gText_PkmnIsEvolving); DrawTextOnTradeWindow(0, gStringVar4, 1); gTasks[taskId].tState++; break; case T_EVOSTATE_INTRO_CRY: if (!IsTextPrinterActive(0)) { PlayCry_Normal(gTasks[taskId].tPreEvoSpecies, 0); gTasks[taskId].tState++; } break; case T_EVOSTATE_INTRO_SOUND: if (IsCryFinished()) { m4aSongNumStop(MUS_EVOLUTION); PlaySE(MUS_EVOLUTION_INTRO); gTasks[taskId].tState++; } break; case T_EVOSTATE_START_MUSIC: if (!IsSEPlaying()) { PlayBGM(MUS_EVOLUTION); gTasks[taskId].tState++; BeginNormalPaletteFade(0x1C, 4, 0, 0x10, RGB_BLACK); } break; case T_EVOSTATE_START_BG_AND_SPARKLE_SPIRAL: if (!gPaletteFade.active) { StartBgAnimation(TRUE); var = gSprites[sEvoStructPtr->preEvoSpriteId].oam.paletteNum + 16; sEvoGraphicsTaskId = EvolutionSparkles_SpiralUpward(var); gTasks[taskId].tState++; SetGpuReg(REG_OFFSET_BG3CNT, BGCNT_PRIORITY(3) | BGCNT_SCREENBASE(6)); } break; case T_EVOSTATE_SPARKLE_ARC: if (!gTasks[sEvoGraphicsTaskId].isActive) { gTasks[taskId].tState++; sEvoStructPtr->delayTimer = 1; sEvoGraphicsTaskId = EvolutionSparkles_ArcDown(); } break; case T_EVOSTATE_CYCLE_MON_SPRITE: if (!gTasks[sEvoGraphicsTaskId].isActive) { sEvoGraphicsTaskId = CycleEvolutionMonSprite(sEvoStructPtr->preEvoSpriteId, sEvoStructPtr->postEvoSpriteId); gTasks[taskId].tState++; } break; case T_EVOSTATE_WAIT_CYCLE_MON_SPRITE: if (--sEvoStructPtr->delayTimer == 0) { sEvoStructPtr->delayTimer = 3; if (!gTasks[sEvoGraphicsTaskId].isActive) gTasks[taskId].tState++; } break; case T_EVOSTATE_SPARKLE_CIRCLE: sEvoGraphicsTaskId = EvolutionSparkles_CircleInward(); gTasks[taskId].tState++; break; case T_EVOSTATE_SPARKLE_SPRAY: if (!gTasks[sEvoGraphicsTaskId].isActive) { sEvoGraphicsTaskId = EvolutionSparkles_SprayAndFlash_Trade(gTasks[taskId].tPostEvoSpecies); gTasks[taskId].tState++; } break; case T_EVOSTATE_EVO_SOUND: if (!gTasks[sEvoGraphicsTaskId].isActive) { PlaySE(SE_EXP); gTasks[taskId].tState++; } break; case T_EVOSTATE_EVO_MON_ANIM: if (IsSEPlaying()) { // Restore bg, do mon anim/cry Free(sBgAnimPal); EvoScene_DoMonAnimAndCry(sEvoStructPtr->postEvoSpriteId, gTasks[taskId].tPostEvoSpecies); memcpy(&gPlttBufferUnfaded[BG_PLTT_ID(2)], sEvoStructPtr->savedPalette, sizeof(sEvoStructPtr->savedPalette)); gTasks[taskId].tState++; } break; case T_EVOSTATE_SET_MON_EVOLVED: if (IsCryFinished()) { StringExpandPlaceholders(gStringVar4, gText_CongratsPkmnEvolved); DrawTextOnTradeWindow(0, gStringVar4, 1); PlayFanfare(MUS_EVOLVED); gTasks[taskId].tState++; SetMonData(mon, MON_DATA_SPECIES, (&gTasks[taskId].tPostEvoSpecies)); CalculateMonStats(mon); EvolutionRenameMon(mon, gTasks[taskId].tPreEvoSpecies, gTasks[taskId].tPostEvoSpecies); GetSetPokedexFlag(SpeciesToNationalPokedexNum(gTasks[taskId].tPostEvoSpecies), FLAG_SET_SEEN); GetSetPokedexFlag(SpeciesToNationalPokedexNum(gTasks[taskId].tPostEvoSpecies), FLAG_SET_CAUGHT); IncrementGameStat(GAME_STAT_EVOLVED_POKEMON); } break; case T_EVOSTATE_TRY_LEARN_MOVE: if (!IsTextPrinterActive(0) && IsFanfareTaskInactive() == TRUE) { var = MonTryLearningNewMoveEvolution(mon, gTasks[taskId].tLearnsFirstMove); if (var != MOVE_NONE && !gTasks[taskId].tEvoWasStopped) { u8 nickname[POKEMON_NAME_BUFFER_SIZE]; gTasks[taskId].tBits |= TASK_BIT_LEARN_MOVE; gTasks[taskId].tLearnsFirstMove = FALSE; gTasks[taskId].tLearnMoveState = 0; GetMonData(mon, MON_DATA_NICKNAME, nickname); StringCopy_Nickname(gBattleTextBuff1, nickname); if (var == MON_HAS_MAX_MOVES) gTasks[taskId].tState = T_EVOSTATE_REPLACE_MOVE; else if (var == MON_ALREADY_KNOWS_MOVE) break; else gTasks[taskId].tState = T_EVOSTATE_LEARNED_MOVE; } else { PlayBGM(MUS_EVOLUTION); DrawTextOnTradeWindow(0, gText_CommunicationStandby5, 1); gTasks[taskId].tState++; } } break; case T_EVOSTATE_END: if (!IsTextPrinterActive(0)) { DestroyTask(taskId); FREE_AND_SET_NULL(sEvoStructPtr); gTextFlags.useAlternateDownArrow = FALSE; SetMainCallback2(gCB2_AfterEvolution); } break; case T_EVOSTATE_CANCEL: if (!gTasks[sEvoGraphicsTaskId].isActive) { m4aMPlayAllStop(); BeginNormalPaletteFade((1 << (gSprites[sEvoStructPtr->preEvoSpriteId].oam.paletteNum + 16)) | (0x4001C), 0, 0x10, 0, RGB_WHITE); gTasks[taskId].tState++; } break; case T_EVOSTATE_CANCEL_MON_ANIM: if (!gPaletteFade.active) { EvoScene_DoMonAnimAndCry(sEvoStructPtr->preEvoSpriteId, gTasks[taskId].tPreEvoSpecies); gTasks[taskId].tState++; } break; case T_EVOSTATE_CANCEL_MSG: if (EvoScene_IsMonAnimFinished(sEvoStructPtr->preEvoSpriteId)) { StringExpandPlaceholders(gStringVar4, gText_EllipsisQuestionMark); DrawTextOnTradeWindow(0, gStringVar4, 1); gTasks[taskId].tEvoWasStopped = TRUE; gTasks[taskId].tState = T_EVOSTATE_TRY_LEARN_MOVE; } break; case T_EVOSTATE_LEARNED_MOVE: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { BufferMoveToLearnIntoBattleTextBuff2(); PlayFanfare(MUS_LEVEL_UP); BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_PKMNLEARNEDMOVE - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnsFirstMove = 0x40; // re-used as a counter gTasks[taskId].tState++; } break; case T_EVOSTATE_TRY_LEARN_ANOTHER_MOVE: if (!IsTextPrinterActive(0) && IsFanfareTaskInactive() == TRUE && --gTasks[taskId].tLearnsFirstMove == 0) gTasks[taskId].tState = T_EVOSTATE_TRY_LEARN_MOVE; break; case T_EVOSTATE_REPLACE_MOVE: switch (gTasks[taskId].tLearnMoveState) { case T_MVSTATE_INTRO_MSG_1: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { // "{mon} is trying to learn {move}" BufferMoveToLearnIntoBattleTextBuff2(); BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_TRYTOLEARNMOVE1 - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveState++; } break; case T_MVSTATE_INTRO_MSG_2: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { // "But, {mon} can't learn more than four moves" BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_TRYTOLEARNMOVE2 - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveState++; } break; case T_MVSTATE_INTRO_MSG_3: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { // "Delete a move to make room for {move}?" BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_TRYTOLEARNMOVE3 - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveYesState = T_MVSTATE_SHOW_MOVE_SELECT; gTasks[taskId].tLearnMoveNoState = T_MVSTATE_ASK_CANCEL; gTasks[taskId].tLearnMoveState++; } case T_MVSTATE_PRINT_YES_NO: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { LoadUserWindowBorderGfx(0, 0xA8, BG_PLTT_ID(14)); CreateYesNoMenu(&gTradeEvolutionSceneYesNoWindowTemplate, 0xA8, 0xE, 0); sEvoCursorPos = 0; gTasks[taskId].tLearnMoveState++; sEvoCursorPos = 0; } break; case T_MVSTATE_HANDLE_YES_NO: switch (Menu_ProcessInputNoWrapClearOnChoose()) { case 0: // YES sEvoCursorPos = 0; BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_EMPTYSTRING3 - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveState = gTasks[taskId].tLearnMoveYesState; if (gTasks[taskId].tLearnMoveState == T_MVSTATE_SHOW_MOVE_SELECT) BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK); break; case 1: // NO case MENU_B_PRESSED: sEvoCursorPos = 1; BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_EMPTYSTRING3 - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveState = gTasks[taskId].tLearnMoveNoState; break; } break; case T_MVSTATE_SHOW_MOVE_SELECT: if (!gPaletteFade.active) { if (gWirelessCommType) DestroyWirelessStatusIndicatorSprite(); Free(GetBgTilemapBuffer(3)); Free(GetBgTilemapBuffer(1)); Free(GetBgTilemapBuffer(0)); FreeAllWindowBuffers(); ShowSelectMovePokemonSummaryScreen(gPlayerParty, gTasks[taskId].tPartyId, gPlayerPartyCount - 1, CB2_TradeEvolutionSceneLoadGraphics, gMoveToLearn); gTasks[taskId].tLearnMoveState++; } break; case T_MVSTATE_HANDLE_MOVE_SELECT: if (!gPaletteFade.active && gMain.callback2 == CB2_TradeEvolutionSceneUpdate) { var = GetMoveSlotToReplace(); if (var == MAX_MON_MOVES) { // Didn't select move slot gTasks[taskId].tLearnMoveState = T_MVSTATE_ASK_CANCEL; } else { // Selected move to forget u16 move = GetMonData(mon, var + MON_DATA_MOVE1); if (IsMoveHM(move)) { // Can't forget HMs BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_HMMOVESCANTBEFORGOTTEN - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveState = T_MVSTATE_RETRY_AFTER_HM; } else { // Forget move PREPARE_MOVE_BUFFER(gBattleTextBuff2, move) RemoveMonPPBonus(mon, var); SetMonMoveSlot(mon, gMoveToLearn, var); BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_123POOF - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveState++; } } } break; case T_MVSTATE_FORGET_MSG: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_PKMNFORGOTMOVE - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveState++; } break; case T_MVSTATE_LEARNED_MOVE: if (!IsTextPrinterActive(0) && !IsSEPlaying()) { BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_ANDELLIPSIS - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tState = T_EVOSTATE_LEARNED_MOVE; } break; case T_MVSTATE_ASK_CANCEL: BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_STOPLEARNINGMOVE - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tLearnMoveYesState = T_MVSTATE_CANCEL; gTasks[taskId].tLearnMoveNoState = T_MVSTATE_INTRO_MSG_1; gTasks[taskId].tLearnMoveState = T_MVSTATE_PRINT_YES_NO; break; case T_MVSTATE_CANCEL: BattleStringExpandPlaceholdersToDisplayedString(gBattleStringsTable[STRINGID_DIDNOTLEARNMOVE - BATTLESTRINGS_TABLE_START]); DrawTextOnTradeWindow(0, gDisplayedStringBattle, 1); gTasks[taskId].tState = T_EVOSTATE_TRY_LEARN_MOVE; break; case T_MVSTATE_RETRY_AFTER_HM: if (!IsTextPrinterActive(0) && !IsSEPlaying()) gTasks[taskId].tLearnMoveState = T_MVSTATE_SHOW_MOVE_SELECT; break; } break; } } #undef tState #undef tPreEvoSpecies #undef tPostEvoSpecies #undef tCanStop #undef tBits #undef tLearnsFirstMove #undef tLearnMoveState #undef tLearnMoveYesState #undef tLearnMoveNoState #undef tEvoWasStopped #undef tPartyId static void EvoDummyFunc(void) { } static void VBlankCB_EvolutionScene(void) { SetGpuReg(REG_OFFSET_BG0HOFS, gBattle_BG0_X); SetGpuReg(REG_OFFSET_BG0VOFS, gBattle_BG0_Y); SetGpuReg(REG_OFFSET_BG1HOFS, gBattle_BG1_X); SetGpuReg(REG_OFFSET_BG1VOFS, gBattle_BG1_Y); SetGpuReg(REG_OFFSET_BG2HOFS, gBattle_BG2_X); SetGpuReg(REG_OFFSET_BG2VOFS, gBattle_BG2_Y); SetGpuReg(REG_OFFSET_BG3HOFS, gBattle_BG3_X); SetGpuReg(REG_OFFSET_BG3VOFS, gBattle_BG3_Y); LoadOam(); ProcessSpriteCopyRequests(); TransferPlttBuffer(); ScanlineEffect_InitHBlankDmaTransfer(); } static void VBlankCB_TradeEvolutionScene(void) { SetGpuReg(REG_OFFSET_BG0HOFS, gBattle_BG0_X); SetGpuReg(REG_OFFSET_BG0VOFS, gBattle_BG0_Y); SetGpuReg(REG_OFFSET_BG1HOFS, gBattle_BG1_X); SetGpuReg(REG_OFFSET_BG1VOFS, gBattle_BG1_Y); SetGpuReg(REG_OFFSET_BG2HOFS, gBattle_BG2_X); SetGpuReg(REG_OFFSET_BG2VOFS, gBattle_BG2_Y); SetGpuReg(REG_OFFSET_BG3HOFS, gBattle_BG3_X); SetGpuReg(REG_OFFSET_BG3VOFS, gBattle_BG3_Y); LoadOam(); ProcessSpriteCopyRequests(); TransferPlttBuffer(); ScanlineEffect_InitHBlankDmaTransfer(); } #define tCycleTimer data[0] #define tPalStage data[1] #define tControlStage data[2] #define tNumCycles data[3] #define tStartTimer data[5] #define tPaused data[6] // See comments above sBgAnim_PaletteControl #define START_PAL sBgAnim_PaletteControl[tControlStage][0] #define END_PAL sBgAnim_PaletteControl[tControlStage][1] #define CYCLES sBgAnim_PaletteControl[tControlStage][2] #define DELAY sBgAnim_PaletteControl[tControlStage][3] // Cycles the background through a set range of palettes in a series // of stages, each stage having a different palette range and timing static void Task_UpdateBgPalette(u8 taskId) { s16 *data = gTasks[taskId].data; if (tPaused) return; if (tStartTimer++ < 20) return; if (tCycleTimer++ > DELAY) { if (END_PAL == tPalStage) { // Reached final palette in current stage, completed a 'cycle' // If this is the final cycle for this stage, move to the next stage tNumCycles++; if (tNumCycles == CYCLES) { tNumCycles = 0; tControlStage++; } tPalStage = START_PAL; } else { // Haven't reached final palette in current stage, load the current palette LoadPalette(&sBgAnimPal[tPalStage * 16], BG_PLTT_ID(10), PLTT_SIZE_4BPP); tCycleTimer = 0; tPalStage++; } } if (tControlStage == (int)ARRAY_COUNT(sBgAnim_PaletteControl[0])) DestroyTask(taskId); } #undef tCycleTimer #undef tPalStage #undef tControlStage #undef tNumCycles #undef tStartTimer #undef START_PAL #undef END_PAL #undef CYCLES #undef DELAY #define tIsLink data[2] static void CreateBgAnimTask(bool8 isLink) { u8 taskId = CreateTask(Task_AnimateBg, 7); if (!isLink) gTasks[taskId].tIsLink = FALSE; else gTasks[taskId].tIsLink = TRUE; } static void Task_AnimateBg(u8 taskId) { u16 *outer_X, *outer_Y; u16 *inner_X = &gBattle_BG1_X; u16 *inner_Y = &gBattle_BG1_Y; if (!gTasks[taskId].tIsLink) { outer_X = &gBattle_BG2_X; outer_Y = &gBattle_BG2_Y; } else { outer_X = &gBattle_BG3_X; outer_Y = &gBattle_BG3_Y; } gTasks[taskId].data[0] = (gTasks[taskId].data[0] + 5) & 0xFF; gTasks[taskId].data[1] = (gTasks[taskId].data[0] + 0x80) & 0xFF; *inner_X = Cos(gTasks[taskId].data[0], 4) + 8; *inner_Y = Sin(gTasks[taskId].data[0], 4) + 16; *outer_X = Cos(gTasks[taskId].data[1], 4) + 8; *outer_Y = Sin(gTasks[taskId].data[1], 4) + 16; if (!FuncIsActiveTask(Task_UpdateBgPalette)) { DestroyTask(taskId); *inner_X = 0; *inner_Y = 0; *outer_X = 256; *outer_Y = 0; } } #undef tIsLink static void InitMovingBgPalette(u16 *palette) { s32 i, j; for (i = 0; i < (int)ARRAY_COUNT(sBgAnim_PalIndexes); i++) { for (j = 0; j < 16; j++) { palette[i * 16 + j] = sBgAnim_Pal[sBgAnim_PalIndexes[i][j]]; } } } static void StartBgAnimation(bool8 isLink) { u8 innerBgId, outerBgId; sBgAnimPal = AllocZeroed(0x640); InitMovingBgPalette(sBgAnimPal); if (!isLink) innerBgId = 1, outerBgId = 2; else innerBgId = 1, outerBgId = 3; LoadPalette(sBgAnim_Intro_Pal, BG_PLTT_ID(10), PLTT_SIZE_4BPP); DecompressAndLoadBgGfxUsingHeap(1, sBgAnim_Gfx, FALSE, 0, 0); CopyToBgTilemapBuffer(innerBgId, sBgAnim_Inner_Tilemap, 0, 0); CopyToBgTilemapBuffer(outerBgId, sBgAnim_Outer_Tilemap, 0, 0); CopyBgTilemapBufferToVram(innerBgId); CopyBgTilemapBufferToVram(outerBgId); if (!isLink) { SetGpuReg(REG_OFFSET_BLDCNT, BLDCNT_TGT1_BG1 | BLDCNT_EFFECT_BLEND | BLDCNT_TGT2_BG2); SetGpuReg(REG_OFFSET_BLDALPHA, BLDALPHA_BLEND(8, 8)); SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_OBJ_ON | DISPCNT_BG2_ON | DISPCNT_BG1_ON | DISPCNT_BG0_ON | DISPCNT_OBJ_1D_MAP); SetBgAttribute(innerBgId, BG_ATTR_PRIORITY, 2); SetBgAttribute(outerBgId, BG_ATTR_PRIORITY, 2); ShowBg(1); ShowBg(2); } else { SetGpuReg(REG_OFFSET_BLDCNT, BLDCNT_TGT1_BG1 | BLDCNT_EFFECT_BLEND | BLDCNT_TGT2_BG3); SetGpuReg(REG_OFFSET_BLDALPHA, BLDALPHA_BLEND(8, 8)); SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_OBJ_ON | DISPCNT_BG3_ON | DISPCNT_BG1_ON | DISPCNT_BG0_ON | DISPCNT_OBJ_1D_MAP); } CreateTask(Task_UpdateBgPalette, 5); CreateBgAnimTask(isLink); } static void UNUSED PauseBgPaletteAnim(void) { u8 taskId = FindTaskIdByFunc(Task_UpdateBgPalette); if (taskId != TASK_NONE) gTasks[taskId].tPaused = TRUE; FillPalette(RGB_BLACK, BG_PLTT_ID(10), PLTT_SIZE_4BPP); } #undef tPaused static void StopBgAnimation(void) { u8 taskId; if ((taskId = FindTaskIdByFunc(Task_UpdateBgPalette)) != TASK_NONE) DestroyTask(taskId); if ((taskId = FindTaskIdByFunc(Task_AnimateBg)) != TASK_NONE) DestroyTask(taskId); FillPalette(RGB_BLACK, BG_PLTT_ID(10), PLTT_SIZE_4BPP); RestoreBgAfterAnim(); } static void RestoreBgAfterAnim(void) { SetGpuReg(REG_OFFSET_BLDCNT, 0); gBattle_BG1_X = 0; gBattle_BG1_Y = 0; gBattle_BG2_X = 0; SetBgAttribute(1, BG_ATTR_PRIORITY, GetBattleBgTemplateData(1, 5)); SetBgAttribute(2, BG_ATTR_PRIORITY, GetBattleBgTemplateData(2, 5)); SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_OBJ_ON | DISPCNT_BG3_ON | DISPCNT_BG0_ON | DISPCNT_OBJ_1D_MAP); Free(sBgAnimPal); } static void EvoScene_DoMonAnimAndCry(u8 monSpriteId, u16 speciesId) { DoMonFrontSpriteAnimation(&gSprites[monSpriteId], speciesId, FALSE, 0); } static bool32 EvoScene_IsMonAnimFinished(u8 monSpriteId) { if (gSprites[monSpriteId].callback == SpriteCallbackDummy) return TRUE; return FALSE; }
1
0.927145
1
0.927145
game-dev
MEDIA
0.884608
game-dev
0.865677
1
0.865677
DorothySei/Casino-Game-GameFi
3,857
Blackjack/sui/blackjack/sources/blackjack.move
module blackjack::game { use sui::object::{Self, UID}; use sui::transfer; use sui::tx_context::{Self, TxContext}; use sui::coin::{Self, Coin, TreasuryCap}; use sui::balance::{Self, Balance}; use sui::event; use sui::table::{Self, Table}; use sui::vec_map::{Self, VecMap}; use sui::vec_set::{Self, VecSet}; use sui::math; use sui::randomness::Random; // ===== Constants ===== const EInvalidGameState: u64 = 0; const EInvalidBetAmount: u64 = 1; const ENotPlayer: u64 = 2; const ENotCasino: u64 = 3; // ===== Structs ===== struct BlackjackGame has key { id: UID, casino: address, player: address, status: u8, bet: u64, dealer_cards: VecMap<u8, Card>, player_cards: VecMap<u8, Card>, chip_balance: Balance<CHIP>, } struct Card has store, copy, drop { suit: u8, number: u8, } struct CHIP has drop {} // ===== Events ===== struct GameInitialized has copy, drop { game_id: ID, casino: address, } struct GameStarted has copy, drop { game_id: ID, player: address, } struct BetPlaced has copy, drop { game_id: ID, player: address, amount: u64, } // ===== Functions ===== public fun initialize(casino: &mut TxContext) { let game = BlackjackGame { id: object::new(casino), casino: tx_context::sender(casino), player: @0x0, status: 0, // New bet: 0, dealer_cards: vec_map::empty(), player_cards: vec_map::empty(), chip_balance: balance::zero(), }; // Emit initialization event event::emit(GameInitialized { game_id: object::id(&game), casino: tx_context::sender(casino), }); // Transfer game object to casino transfer::share_object(game); } public fun start_game(game: &mut BlackjackGame, player: &mut TxContext) { assert!(game.status == 0, EInvalidGameState); assert!(tx_context::sender(player) != game.casino, ENotPlayer); game.player = tx_context::sender(player); game.status = 1; // WaitingForBet // Emit game started event event::emit(GameStarted { game_id: object::id(game), player: tx_context::sender(player), }); } public fun place_bet( game: &mut BlackjackGame, bet: Coin<CHIP>, player: &mut TxContext ) { assert!(game.status == 1, EInvalidGameState); assert!(tx_context::sender(player) == game.player, ENotPlayer); let bet_amount = coin::value(&bet); assert!(bet_amount % 100 == 0, EInvalidBetAmount); game.chip_balance = balance::join(game.chip_balance, coin::into_balance(bet)); game.bet = bet_amount; game.status = 2; // WaitingForDeal event::emit(BetPlaced { game_id: object::id(game), player: tx_context::sender(player), amount: bet_amount, }); } // Add more game logic functions here (deal, hit, stand, etc.) fun calculate_score(cards: &VecMap<u8, Card>): u8 { let score = 0; let aces = 0; let i = 0; while (i < vec_map::length(cards)) { let card = vec_map::get(cards, i); if (card.number == 1) { aces = aces + 1; score = score + 11; } else if (card.number >= 10) { score = score + 10; } else { score = score + card.number; }; i = i + 1; }; while (score > 21 && aces > 0) { score = score - 10; aces = aces - 1; }; score } }
1
0.848948
1
0.848948
game-dev
MEDIA
0.933635
game-dev
0.959466
1
0.959466
legastero/stanza
1,192
src/protocol/xep0115.ts
// ==================================================================== // XEP-0115: Entity Capabilities // -------------------------------------------------------------------- // Source: https://xmpp.org/extensions/xep-0115.html // Version: 1.5.1 (2016-10-06) // ==================================================================== import { attribute, DefinitionOptions, staticValue } from '../jxt'; import { NS_DISCO_LEGACY_CAPS } from '../Namespaces'; declare module './' { export interface StreamFeatures { legacyCapabilities?: LegacyEntityCaps[]; } export interface Presence { legacyCapabilities?: LegacyEntityCaps[]; } } export interface LegacyEntityCaps { node: string; value: string; algorithm: string; } const Protocol: DefinitionOptions = { aliases: [ { path: 'presence.legacyCapabilities', multiple: true }, { path: 'features.legacyCapabilities', multiple: true } ], element: 'c', fields: { algorithm: attribute('hash'), legacy: staticValue(true), node: attribute('node'), value: attribute('ver') }, namespace: NS_DISCO_LEGACY_CAPS }; export default Protocol;
1
0.606148
1
0.606148
game-dev
MEDIA
0.459263
game-dev
0.524787
1
0.524787
NebulaSS13/Nebula
3,839
code/game/objects/structures/crates_lockers/closets/statue.dm
/obj/structure/closet/statue //what name = "statue" desc = "An incredibly lifelike marble carving." icon = 'icons/obj/structures/statue.dmi' icon_state = "human_male" density = TRUE anchored = TRUE setup = 0 current_health = 0 //destroying the statue kills the mob within var/intialTox = 0 //these are here to keep the mob from taking damage from things that logically wouldn't affect a rock var/intialFire = 0 //it's a little sloppy I know but it was this or the GODMODE flag. Lesser of two evils. var/intialBrute = 0 var/intialOxy = 0 var/timer = 240 //eventually the person will be freed /obj/structure/closet/statue/Initialize(mapload, var/mob/living/L) if(L && (ishuman(L) || L.isMonkey() || iscorgi(L))) if(L.buckled) L.buckled = null L.anchored = FALSE if(L.client) L.client.perspective = EYE_PERSPECTIVE L.client.eye = src L.forceMove(src) L.add_genetic_condition(GENE_COND_MUTED) current_health = L.current_health + 100 //stoning damaged mobs will result in easier to shatter statues intialTox = L.get_damage(TOX) intialFire = L.get_damage(BURN) intialBrute = L.get_damage(BRUTE) intialOxy = L.get_damage(OXY) if(ishuman(L)) name = "statue of [L.name]" if(L.gender == "female") icon_state = "human_female" else if(L.isMonkey()) name = "statue of a monkey" icon_state = "monkey" else if(iscorgi(L)) name = "statue of a corgi" icon_state = "corgi" desc = "If it takes forever, I will wait for you..." if(current_health == 0) //meaning if the statue didn't find a valid target return INITIALIZE_HINT_QDEL START_PROCESSING(SSobj, src) . = ..(mapload) /obj/structure/closet/statue/Process() timer-- for(var/mob/living/M in src) //Go-go gadget stasis field M.set_damage(TOX, intialTox) M.take_damage(intialFire - M.get_damage(BURN), BURN, do_update_health = FALSE) M.take_damage(intialBrute - M.get_damage(BRUTE)) M.set_damage(OXY, intialOxy) if (timer <= 0) dump_contents() STOP_PROCESSING(SSobj, src) qdel(src) /obj/structure/closet/statue/dump_contents(atom/forced_loc = loc, mob/user) for(var/obj/O in src) O.dropInto(forced_loc) for(var/mob/living/M in src) M.dropInto(forced_loc) M.remove_genetic_condition(GENE_COND_MUTED) M.take_overall_damage((M.current_health - current_health - 100),0) //any new damage the statue incurred is transfered to the mob if(M.client) M.client.eye = M.client.mob M.client.perspective = MOB_PERSPECTIVE /obj/structure/closet/statue/open(mob/user) return /obj/structure/closet/statue/close(mob/user) return /obj/structure/closet/statue/toggle() return /obj/structure/closet/statue/proc/check_health() if(current_health <= 0) for(var/mob/M in src) shatter(M) /obj/structure/closet/statue/bullet_act(var/obj/item/projectile/Proj) current_health -= Proj.get_structure_damage() check_health() return /obj/structure/closet/statue/explosion_act(severity) for(var/mob/M in src) M.explosion_act(severity) ..() if(!QDELETED(src)) current_health -= 60 / severity check_health() /obj/structure/closet/statue/attackby(obj/item/used_item, mob/user) current_health -= used_item.expend_attack_force(user) user.do_attack_animation(src) visible_message("<span class='danger'>[user] strikes [src] with [used_item].</span>") check_health() return TRUE /obj/structure/closet/statue/receive_mouse_drop(atom/dropping, mob/user, params) return TRUE /obj/structure/closet/statue/relaymove() return /obj/structure/closet/statue/attack_hand() SHOULD_CALL_PARENT(FALSE) return TRUE /obj/structure/closet/statue/verb_toggleopen() return /obj/structure/closet/statue/on_update_icon() return /obj/structure/closet/statue/proc/shatter(mob/user) if (user) user.dust() dump_contents() visible_message("<span class='warning'>[src] shatters!.</span>") qdel(src)
1
0.967008
1
0.967008
game-dev
MEDIA
0.980591
game-dev
0.810119
1
0.810119
PGMDev/PGM
3,567
core/src/main/java/tc/oc/pgm/listeners/WorldProblemListener.java
package tc.oc.pgm.listeners; import static tc.oc.pgm.util.material.MaterialUtils.MATERIAL_UTILS; import static tc.oc.pgm.util.nms.NMSHacks.NMS_HACKS; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import java.util.Map; import java.util.logging.Logger; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.plugin.Plugin; import tc.oc.pgm.api.Permissions; import tc.oc.pgm.util.ClassLogger; import tc.oc.pgm.util.block.BlockVectorSet; import tc.oc.pgm.util.collection.DefaultMapAdapter; import tc.oc.pgm.util.material.Materials; public class WorldProblemListener implements Listener { private static final int RANDOM_TICK_SPEED_LIMIT = 30; private final Logger logger; private final SetMultimap<World, Chunk> repairedChunks = HashMultimap.create(); private static final Map<World, BlockVectorSet> block36Locations = new DefaultMapAdapter<>(world -> new BlockVectorSet(), true); public WorldProblemListener(Plugin plugin) { this.logger = ClassLogger.get(plugin.getLogger(), getClass()); } void broadcastDeveloperWarning(String message) { logger.warning(message); Bukkit.broadcast(ChatColor.RED + message, Permissions.DEBUG); } @EventHandler public void warnRandomTickRate(WorldLoadEvent event) { String str = event.getWorld().getGameRuleValue("randomTickSpeed"); if (str != null) { int value = Integer.parseInt(str); if (value > RANDOM_TICK_SPEED_LIMIT) { broadcastDeveloperWarning("Gamerule 'randomTickSpeed' is set to " + value + " for this world (normal value is 3). This may overload the server."); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void unloadWorld(WorldUnloadEvent event) { this.repairedChunks.removeAll(event.getWorld()); block36Locations.remove(event.getWorld()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void repairChunk(ChunkLoadEvent event) { if (this.repairedChunks.put(event.getWorld(), event.getChunk())) { // Set by modern platform on 1.13+ worlds - we want to treat only the older worlds if (!event.getWorld().hasMetadata("is-post-flattening")) { // Replace formerly invisible half-iron-door blocks with barriers for (Block ironDoor : NMS_HACKS.getBlocks(event.getChunk(), Materials.IRON_DOOR)) { BlockFace half = MATERIAL_UTILS.isUpperHalfOfDoor(ironDoor) ? BlockFace.UP : BlockFace.DOWN; if (ironDoor.getRelative(half.getOppositeFace()).getType() != Materials.IRON_DOOR) { ironDoor.setType(Material.BARRIER, false); } } } // Remove all block 36 and remember the ones at y=0 so VoidFilter can check them for (Block block36 : NMS_HACKS.getBlocks(event.getChunk(), Materials.MOVING_PISTON)) { if (block36.getY() == 0) { block36Locations .get(event.getWorld()) .add(block36.getX(), block36.getY(), block36.getZ()); } block36.setType(Material.AIR, false); } } } public static boolean wasBlock36(World world, int x, int y, int z) { return block36Locations.get(world).contains(x, y, z); } }
1
0.867374
1
0.867374
game-dev
MEDIA
0.974621
game-dev
0.928548
1
0.928548
pokerregion/poker
7,629
poker/room/pkr.py
import re from decimal import Decimal import pytz from zope.interface import implementer from .. import handhistory as hh from ..constants import Action, Currency, Game, GameType, Limit, MoneyType from ..hand import Card, Combo __all__ = ["PKRHandHistory"] @implementer(hh.IStreet) class _Street(hh._BaseStreet): def _parse_cards(self, boardline): self.cards = ( Card(boardline[6:9:2]), Card(boardline[11:14:2]), Card(boardline[16:19:2]), ) def _parse_actions(self, actionlines): actions = [] for line in actionlines: if line.startswith("Pot sizes:"): self._parse_pot(line) elif " " in line: actions.append(hh._PlayerAction(*self._parse_player_action(line))) else: raise self.actions = tuple(actions) if actions else None def _parse_pot(self, line): amount_start_index = 12 amount = line[amount_start_index:] self.pot = Decimal(amount) def _parse_player_action(self, line): space_index = line.find(" ") name = line[:space_index] end_action_index = line.find(" ", space_index + 1) # -1 means not found if end_action_index == -1: end_action_index = None # until the end action = Action(line[space_index + 1 : end_action_index]) if end_action_index: amount_start_index = line.find("$") + 1 amount = line[amount_start_index:] return name, action, Decimal(amount) else: return name, action, None @implementer(hh.IHandHistory) class PKRHandHistory(hh._SplittableHandHistoryMixin, hh._BaseHandHistory): """Parses PKR hand histories.""" currency = Currency.USD tournament_ident = None tournament_name = None tournament_level = None _DATE_FORMAT = "%d %b %Y %H:%M:%S" _TZ = pytz.UTC _SPLIT_CARD_SPACE = slice(0, 3, 2) _STREET_SECTIONS = {"flop": 2, "turn": 3, "river": 4} _split_re = re.compile(r"Dealing |\nDealing Cards\n|Taking |Moving |\n") _blinds_re = re.compile(r"^Blinds are now \$([\d.]*) / \$([\d.]*)$") _hero_re = re.compile(r"^\[(. .)\]\[(. .)\] to (?P<hero_name>.*)$") _seat_re = re.compile(r"^Seat (\d\d?): (.*) - \$([\d.]*) ?(.*)$") _sizes_re = re.compile(r"^Pot sizes: \$([\d.]*)$") _card_re = re.compile(r"\[(. .)\]") _rake_re = re.compile(r"Rake of \$([\d.]*) from pot \d$") _win_re = re.compile(r"^(.*) wins \$([\d.]*) with: ") def parse_header(self): # sections[1] is after blinds, before preflop # section[2] is before flop # sections[-1] is before showdown self._split_raw() self.table_name = self._splitted[0][6:] # cut off "Table " self.ident = self._splitted[1][15:] # cut off "Starting Hand #" self._parse_date(self._splitted[2][20:]) # cut off "Start time of hand: " self.game = Game(self._splitted[4][11:]) # cut off "Game Type: " self.limit = Limit(self._splitted[5][12:]) # cut off "Limit Type: " self.game_type = GameType(self._splitted[6][12:]) # cut off "Table Type: " match = self._blinds_re.match(self._splitted[8]) self.sb = Decimal(match.group(1)) self.bb = Decimal(match.group(2)) self.buyin = self.bb * 100 def parse(self): """Parses the body of the hand history, but first parse header if not yet parsed.""" if not self.header_parsed: self.parse_header() self._parse_players() self._parse_button() self._parse_hero() self._parse_preflop() self._parse_flop() self._parse_street("turn") self._parse_street("river") self._parse_showdown() self._parse_extra() self._del_split_vars() self.parsed = True def _parse_players(self): # In hh there is no indication of max_players, # so init for 10, as there are 10 player tables on PKR. players = self._init_seats(10) for line in self._splitted[10:]: match = self._seat_re.match(line) if not match: break seat_number = int(match.group(1)) players[seat_number - 1] = hh._Player( name=match.group(2), stack=Decimal(match.group(3)), seat=seat_number, combo=None, ) self.max_players = seat_number self.players = players[: self.max_players] def _parse_button(self): button_row = self._splitted[self._sections[0] + 1] # cut last two because there can be 10 seats also # in case of one digit, the first char will be a space # but int() can convert it without hiccups :) button_seat = int(button_row[-2:]) self.button = self.players[button_seat - 1] def _parse_hero(self): dealt_row = self._splitted[self._sections[1] + 1] match = self._hero_re.match(dealt_row) first = match.group(1)[self._SPLIT_CARD_SPACE] second = match.group(2)[self._SPLIT_CARD_SPACE] hero, hero_index = self._get_hero_from_players(match.group("hero_name")) hero.combo = Combo(first + second) self.hero = self.players[hero_index] = hero if self.button.name == self.hero.name: self.button = self.hero def _parse_preflop(self): start = self._sections[1] + 2 stop = self._splitted.index("", start + 1) - 1 self.preflop_actions = tuple(self._splitted[start:stop]) def _parse_flop(self): flop_section = self._STREET_SECTIONS["flop"] start = self._sections[flop_section] + 1 stop = next(v for v in self._sections if v > start) floplines = self._splitted[start:stop] self.flop = _Street(floplines) def _parse_street(self, street): section = self._STREET_SECTIONS[street] try: start = self._sections[section] + 1 street_line = self._splitted[start] cards = [ x[self._SPLIT_CARD_SPACE] for x in self._card_re.findall(street_line) ] setattr(self, street, Card(cards[0])) stop = next(v for v in self._sections if v > start) - 1 setattr(self, f"{street}_actions", tuple(self._splitted[start + 1 : stop])) sizes_line = self._splitted[start - 2] pot = Decimal(self._sizes_re.match(sizes_line).group(1)) setattr(self, f"{street}_pot", pot) except IndexError: setattr(self, street, None) setattr(self, f"{street}_actions", None) setattr(self, f"{street}_pot", None) def _parse_showdown(self): start = self._sections[-1] + 1 rake_line = self._splitted[start] match = self._rake_re.match(rake_line) self.rake = Decimal(match.group(1)) winners = [] total_pot = self.rake for line in self._splitted[start:]: if "shows" in line: self.show_down = True elif "wins" in line: match = self._win_re.match(line) winners.append(match.group(1)) total_pot += Decimal(match.group(2)) self.winners = tuple(winners) self.total_pot = total_pot def _parse_extra(self): self.extra = dict() self.extra["last_ident"] = self._splitted[3][11:] # cut off "Last Hand #" self.extra["money_type"] = MoneyType( self._splitted[7][12:] ) # cut off "Money Type: "
1
0.865247
1
0.865247
game-dev
MEDIA
0.738636
game-dev
0.977871
1
0.977871
DataPlusProgram/GodotWadImporter
2,110
addons/gameAssetImporter/scenes/console/nativeFuncs.gd
extends Node @onready var console = $"../.." @onready var consoleRoot = $"../../../" func close(): consoleRoot.hide() func clear(): %logText.text = "" func cls(): clear() func quit(): get_tree().quit() func clearhistory(): $"../..".history.clear() func getg(): for i in %execute.scripts: breakpoint func loader(): var node = load("res://addons/gameAssetImporter/scenes/makeUI/makeUI.tscn").instantiate() get_tree().get_root().add_child(node) func spawn(entStr,gameStr = ""): entStr = entStr.to_lower() var players = get_tree().get_nodes_in_group("player") for i in players: if i.get_node_or_null("gunManager/shootCast") != null: var cast : RayCast3D = i.get_node_or_null("gunManager/shootCast") var point = cast.get_collision_point() var ent = ENTG.spawn(get_tree(),entStr,point,Vector3.ZERO,gameStr) if ent == null: print('Failed to spawn ' + entStr) return print('Failed to spawn ' + entStr) func getentitylist(gameStr) -> String: gameStr = gameStr.to_lower() var dict = ENTG.getEntityDict(get_tree(),gameStr) var runningStr = "" for str in dict.keys(): print(str) runningStr += str + "\n" return runningStr func kill(): for i in get_tree().get_nodes_in_group("player"): if i.has_method("takeDamage"): i.takeDamage({"amt":99999}) func getinputs(): var retStr = "" var inputs = Input.get_connected_joypads() for i in inputs: retStr += str(i) + ": " + Input.get_joy_name(i) + "\n" #var t3 = 3 #retStr + Input.get_joy_info(i)["raw_name"] + "\n" return retStr func entdbg(): var entDebugMenu = load("res://addons/gameAssetImporter/scenes/entityDebug/entityDebugDialog.tscn").instantiate() add_child(entDebugMenu) func orphans(): print("--------") print_orphan_nodes() func map(mapName:String): var map = ENTG.createMap(mapName,get_tree(),"") if map == null: return for cMap in get_tree().get_nodes_in_group("level"): cMap.queue_free() func maplist(): return mapnames() func mapnames(): return ENTG.printMapNames(get_tree(),"") func clearentitycache(): ENTG.clearEntityCaches(get_tree())
1
0.639439
1
0.639439
game-dev
MEDIA
0.953521
game-dev
0.854631
1
0.854631
ServUO/ServUO
2,308
Scripts/Mobiles/Normal/Zombie.cs
using System; using Server.Items; namespace Server.Mobiles { [CorpseName("a rotting corpse")] public class Zombie : BaseCreature { [Constructable] public Zombie() : base(AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4) { Name = "a zombie"; Body = 3; BaseSoundID = 471; SetStr(46, 70); SetDex(31, 50); SetInt(26, 40); SetHits(28, 42); SetDamage(3, 7); SetDamageType(ResistanceType.Physical, 100); SetResistance(ResistanceType.Physical, 15, 20); SetResistance(ResistanceType.Cold, 20, 30); SetResistance(ResistanceType.Poison, 5, 10); SetSkill(SkillName.MagicResist, 15.1, 40.0); SetSkill(SkillName.Tactics, 35.1, 50.0); SetSkill(SkillName.Wrestling, 35.1, 50.0); Fame = 600; Karma = -600; VirtualArmor = 18; PackBodyPartOrBones(); } public Zombie(Serial serial) : base(serial) { } public override bool BleedImmune { get { return true; } } public override Poison PoisonImmune { get { return Poison.Regular; } } public override TribeType Tribe { get { return TribeType.Undead; } } public override OppositionGroup OppositionGroup { get { return OppositionGroup.FeyAndUndead; } } public override void GenerateLoot() { AddLoot(LootPack.Meager); } public override bool IsEnemy(Mobile m) { if(Region.IsPartOf("Haven Island")) { return false; } return base.IsEnemy(m); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
1
0.93412
1
0.93412
game-dev
MEDIA
0.984598
game-dev
0.856594
1
0.856594
AgoraIO-Community/Agora_Unity_WebGL
1,066
Assets/FunctionalTest/DevDemo/ButtonHandler.cs
using UnityEngine; using UnityEngine.UI; namespace agora_gs_test { public class ButtonHandler : MonoBehaviour { /// <summary> /// React to a button click event. Used in the UI Button action definition. /// </summary> /// <param name="button"></param> public void onButtonClicked(Button button) { // which GameObject? GameObject go = GameObject.Find("GameController"); if (go != null) { TestHome gameController = go.GetComponent<TestHome>(); if (gameController == null) { Debug.LogError("Missing game controller..."); return; } if (button.name == "JoinButton") { gameController.onJoinButtonClicked(); } else if (button.name == "LeaveButton") { gameController.onLeaveButtonClicked(); } } } } }
1
0.615583
1
0.615583
game-dev
MEDIA
0.841179
game-dev
0.548144
1
0.548144
Farama-Foundation/ViZDoom
13,716
src/vizdoom/src/b_game.cpp
/******************************************* * B_game.h * * Description: * * Misc things that has to do with the bot, * * like it's spawning etc. * * Makes the bot fit into game * * * *******************************************/ /*The files which are modified for Cajun Purpose D_player.h (v0.85: added some variables) D_netcmd.c (v0.71) D_netcmd.h (v0.71) D_main.c (v0.71) D_ticcmd.h (v0.71) G_game.c (v0.95: Too make demorecording work somewhat) G_input.c (v0.95: added some keycommands) G_input.h (v0.95) P_mobj.c (v0.95: changed much in the P_MobjThinker(), a little in P_SpawnPlayerMissile(), maybee something else ) P_mobj.h (v0.95: Removed some unnecessary variables) P_user.c (v0.95: It's only one change maybee it already was there in 0.71) P_inter.c (v0.95: lot of changes) P_pspr.c (v0.71) P_map.c (v0.95: Test missile for bots) P_tick.c (v0.95: Freeze mode things only) P_local.h (v0.95: added> extern int tmsectortype) Info.c (v0.95: maybee same as 0.71) Info.h (v0.95: maybee same as 0.71) M_menu.c (v0.95: an extra menu in the key setup with the new commands) R_main.c (v0.95: Fix for bot's view) wi_stuff.c (v0.97: To remove bots correct) (v0.85) Removed all my code from: P_enemy.c New file: b_move.c ****************************************** What I know has to be done. in near future. - Do some hunting/fleeing functions. - Make the roaming 100% flawfree. - Fix all SIGSEVS (Below is known SIGSEVS) -Nada (but they might be there) ****************************************** Everything that is changed is marked (maybe commented) with "Added by MC" */ #include "doomdef.h" #include "p_local.h" #include "b_bot.h" #include "g_game.h" #include "m_random.h" #include "doomstat.h" #include "cmdlib.h" #include "sc_man.h" #include "stats.h" #include "m_misc.h" #include "sbar.h" #include "p_acs.h" #include "teaminfo.h" #include "i_system.h" #include "d_net.h" #include "d_netinf.h" //VIZDOOM_CODE EXTERN_CVAR (String, viz_bots_path) static FRandom pr_botspawn ("BotSpawn"); //Externs FCajunMaster bglobal; cycle_t BotThinkCycles, BotSupportCycles; int BotWTG; static const char *BotConfigStrings[] = { "name", "aiming", "perfection", "reaction", "isp", "team", NULL }; enum { BOTCFG_NAME, BOTCFG_AIMING, BOTCFG_PERFECTION, BOTCFG_REACTION, BOTCFG_ISP, BOTCFG_TEAM }; FCajunMaster::~FCajunMaster() { ForgetBots(); } //This function is called every tick (from g_game.c). void FCajunMaster::Main () { BotThinkCycles.Reset(); if (demoplayback || gamestate != GS_LEVEL || consoleplayer != Net_Arbitrator) return; //Add new bots? if (wanted_botnum > botnum && !freeze) { if (t_join == ((wanted_botnum - botnum) * SPAWN_DELAY)) { if (!SpawnBot (getspawned[spawn_tries])) wanted_botnum--; spawn_tries++; } t_join--; } //Check if player should go observer. Or un observe if (bot_observer && !observer && !netgame) { Printf ("%s is now observer\n", players[consoleplayer].userinfo.GetName()); observer = true; players[consoleplayer].mo->UnlinkFromWorld (); players[consoleplayer].mo->flags = MF_DROPOFF|MF_NOBLOCKMAP|MF_NOCLIP|MF_NOTDMATCH|MF_NOGRAVITY|MF_FRIENDLY; players[consoleplayer].mo->flags2 |= MF2_FLY; players[consoleplayer].mo->LinkToWorld (); } else if (!bot_observer && observer && !netgame) //Go back { Printf ("%s returned to the fray\n", players[consoleplayer].userinfo.GetName()); observer = false; players[consoleplayer].mo->UnlinkFromWorld (); players[consoleplayer].mo->flags = MF_SOLID|MF_SHOOTABLE|MF_DROPOFF|MF_PICKUP|MF_NOTDMATCH|MF_FRIENDLY; players[consoleplayer].mo->flags2 &= ~MF2_FLY; players[consoleplayer].mo->LinkToWorld (); } } void FCajunMaster::Init () { botnum = 0; firstthing = NULL; spawn_tries = 0; freeze = false; observer = false; body1 = NULL; body2 = NULL; if (ctf && teamplay == false) teamplay = true; //Need teamplay for ctf. (which is not done yet) t_join = (wanted_botnum + 1) * SPAWN_DELAY; //The + is to let player get away before the bots come in. if (botinfo == NULL) { LoadBots (); } else { botinfo_t *thebot = botinfo; while (thebot != NULL) { thebot->inuse = BOTINUSE_No; thebot = thebot->next; } } } //Called on each level exit (from g_game.c). void FCajunMaster::End () { int i; //Arrange wanted botnum and their names, so they can be spawned next level. getspawned.Clear(); if (deathmatch) { for (i = 0; i < MAXPLAYERS; i++) { if (players[i].Bot != NULL) { getspawned.Push(players[i].userinfo.GetName()); } } wanted_botnum = botnum; } } //Name can be optional, if = NULL //then a random bot is spawned. //If no bot with name = name found //the function will CONS print an //error message and will not spawn //anything. //The color parameter can be either a //color (range from 0-10), or = NOCOLOR. //The color parameter overides bots //individual colors if not = NOCOLOR. bool FCajunMaster::SpawnBot (const char *name, int color) { //COLORS static const char colors[11][17] = { "\\color\\40 cf 00", //0 = Green "\\color\\b0 b0 b0", //1 = Gray "\\color\\50 50 60", //2 = Indigo "\\color\\8f 00 00", //3 = Deep Red "\\color\\ff ff ff", //4 = White "\\color\\ff af 3f", //5 = Bright Brown "\\color\\bf 00 00", //6 = Red "\\color\\00 00 ff", //7 = Blue "\\color\\00 00 7f", //8 = Dark Blue "\\color\\ff ff 00", //9 = Yellow "\\color\\cf df 90" //10 = Bleached Bone }; botinfo_t *thebot = botinfo; int botshift = 0; if (name) { // Check if exist or already in the game. while (thebot && stricmp (name, thebot->name)) { botshift++; thebot = thebot->next; } if (thebot == NULL) { Printf ("couldn't find %s in bots config\n", name); return false; } else if (thebot->inuse == BOTINUSE_Waiting) { return false; } else if (thebot->inuse == BOTINUSE_Yes) { Printf ("%s is already in the thick\n", name); return false; } } else { //Spawn a random bot from bots.cfg if no name given. TArray<botinfo_t *> BotInfoAvailable; while (thebot) { if (thebot->inuse == BOTINUSE_No) BotInfoAvailable.Push (thebot); thebot = thebot->next; } if (BotInfoAvailable.Size () == 0) { Printf ("Couldn't spawn bot; no bot left in bots config\n"); return false; } thebot = BotInfoAvailable[pr_botspawn() % BotInfoAvailable.Size ()]; botinfo_t *thebot2 = botinfo; while (thebot2) { if (thebot == thebot2) break; botshift++; thebot2 = thebot2->next; } } thebot->inuse = BOTINUSE_Waiting; Net_WriteByte (DEM_ADDBOT); Net_WriteByte (botshift); { //Set color. char concat[512]; strcpy (concat, thebot->info); if (color == NOCOLOR && bot_next_color < NOCOLOR && bot_next_color >= 0) { strcat (concat, colors[bot_next_color]); } if (TeamLibrary.IsValidTeam (thebot->lastteam)) { // Keep the bot on the same team when switching levels mysnprintf (concat + strlen(concat), countof(concat) - strlen(concat), "\\team\\%d\n", thebot->lastteam); } Net_WriteString (concat); } Net_WriteByte(thebot->skill.aiming); Net_WriteByte(thebot->skill.perfection); Net_WriteByte(thebot->skill.reaction); Net_WriteByte(thebot->skill.isp); return true; } void FCajunMaster::TryAddBot (BYTE **stream, int player) { int botshift = ReadByte (stream); char *info = ReadString (stream); botskill_t skill; skill.aiming = ReadByte (stream); skill.perfection = ReadByte (stream); skill.reaction = ReadByte (stream); skill.isp = ReadByte (stream); botinfo_t *thebot = NULL; if (consoleplayer == player) { thebot = botinfo; while (botshift > 0) { thebot = thebot->next; botshift--; } } if (DoAddBot ((BYTE *)info, skill)) { //Increment this. botnum++; if (thebot != NULL) { thebot->inuse = BOTINUSE_Yes; } } else { if (thebot != NULL) { thebot->inuse = BOTINUSE_No; } } delete[] info; } bool FCajunMaster::DoAddBot (BYTE *info, botskill_t skill) { int bnum; for (bnum = 0; bnum < MAXPLAYERS; bnum++) { if (!playeringame[bnum]) { break; } } if (bnum == MAXPLAYERS) { Printf ("The maximum of %d players/bots has been reached\n", MAXPLAYERS); return false; } D_ReadUserInfoStrings (bnum, &info, false); multiplayer = true; //Prevents cheating and so on; emulates real netgame (almost). players[bnum].Bot = new DBot; players[bnum].Bot->player = &players[bnum]; players[bnum].Bot->skill = skill; playeringame[bnum] = true; players[bnum].mo = NULL; players[bnum].playerstate = PST_ENTER; if (teamplay) Printf ("%s joined the %s team\n", players[bnum].userinfo.GetName(), Teams[players[bnum].userinfo.GetTeam()].GetName()); else Printf ("%s joined the game\n", players[bnum].userinfo.GetName()); G_DoReborn (bnum, true); if (StatusBar != NULL) { StatusBar->MultiplayerChanged (); } return true; } void FCajunMaster::RemoveAllBots (bool fromlist) { int i, j; for (i = 0; i < MAXPLAYERS; ++i) { if (players[i].Bot != NULL) { // If a player is looking through this bot's eyes, make him // look through his own eyes instead. for (j = 0; j < MAXPLAYERS; ++j) { if (i != j && playeringame[j] && players[j].Bot == NULL) { if (players[j].camera == players[i].mo) { players[j].camera = players[j].mo; if (j == consoleplayer) { StatusBar->AttachToPlayer (players + j); } } } } FBehavior::StaticStartTypedScripts (SCRIPT_Disconnect, players[i].mo, true, i, true); ClearPlayer (i, !fromlist); } } if (fromlist) { wanted_botnum = 0; } botnum = 0; } //------------------ //Reads data for bot from //a .bot file. //The skills and other data should //be arranged as follows in the bot file: // //{ // Name bot's name // Aiming 0-100 // Perfection 0-100 // Reaction 0-100 // Isp 0-100 (Instincts of Self Preservation) // ??? any other valid userinfo strings can go here //} static void appendinfo (char *&front, const char *back) { char *newstr; if (front) { size_t newlen = strlen (front) + strlen (back) + 2; newstr = new char[newlen]; strcpy (newstr, front); delete[] front; } else { size_t newlen = strlen (back) + 2; newstr = new char[newlen]; newstr[0] = 0; } strcat (newstr, "\\"); strcat (newstr, back); front = newstr; } void FCajunMaster::ForgetBots () { botinfo_t *thebot = botinfo; while (thebot) { botinfo_t *next = thebot->next; delete[] thebot->name; delete[] thebot->info; delete thebot; thebot = next; } botinfo = NULL; } bool FCajunMaster::LoadBots () { FScanner sc; FString bots_filepath; bool gotteam = false; int loaded_bots = 0; bglobal.ForgetBots (); bots_filepath = *viz_bots_path; if(!FileExists(bots_filepath)) { bots_filepath = M_GetCajunPath(BOTFILENAME); } if (bots_filepath.IsEmpty()) { Printf ("No bots file \"%s\", so no bots\n", bots_filepath.GetChars()); return false; } sc.OpenFile(bots_filepath); while (sc.GetString ()) { if (!sc.Compare ("{")) { sc.ScriptError ("Unexpected token '%s'\n", sc.String); } botinfo_t *newinfo = new botinfo_t; bool gotclass = false; memset (newinfo, 0, sizeof(*newinfo)); newinfo->info = copystring ("\\autoaim\\0\\movebob\\.25"); for (;;) { sc.MustGetString (); if (sc.Compare ("}")) break; switch (sc.MatchString (BotConfigStrings)) { case BOTCFG_NAME: sc.MustGetString (); appendinfo (newinfo->info, "name"); appendinfo (newinfo->info, sc.String); newinfo->name = copystring (sc.String); break; case BOTCFG_AIMING: sc.MustGetNumber (); newinfo->skill.aiming = sc.Number; break; case BOTCFG_PERFECTION: sc.MustGetNumber (); newinfo->skill.perfection = sc.Number; break; case BOTCFG_REACTION: sc.MustGetNumber (); newinfo->skill.reaction = sc.Number; break; case BOTCFG_ISP: sc.MustGetNumber (); newinfo->skill.isp = sc.Number; break; case BOTCFG_TEAM: { char teamstr[16]; BYTE teamnum; sc.MustGetString (); if (IsNum (sc.String)) { teamnum = atoi (sc.String); if (!TeamLibrary.IsValidTeam (teamnum)) { teamnum = TEAM_NONE; } } else { teamnum = TEAM_NONE; for (unsigned int i = 0; i < Teams.Size(); ++i) { if (stricmp (Teams[i].GetName (), sc.String) == 0) { teamnum = i; break; } } } appendinfo (newinfo->info, "team"); mysnprintf (teamstr, countof(teamstr), "%d", teamnum); appendinfo (newinfo->info, teamstr); gotteam = true; break; } default: if (stricmp (sc.String, "playerclass") == 0) { gotclass = true; } appendinfo (newinfo->info, sc.String); sc.MustGetString (); appendinfo (newinfo->info, sc.String); break; } } if (!gotclass) { // Bots that don't specify a class get a random one appendinfo (newinfo->info, "playerclass"); appendinfo (newinfo->info, "random"); } if (!gotteam) { // Same for bot teams appendinfo (newinfo->info, "team"); appendinfo (newinfo->info, "255"); } newinfo->next = bglobal.botinfo; newinfo->lastteam = TEAM_NONE; bglobal.botinfo = newinfo; loaded_bots++; } Printf ("%d bots read from %s\n", loaded_bots, bots_filepath.GetChars()); return true; } ADD_STAT (bots) { FString out; out.Format ("think = %04.1f ms support = %04.1f ms wtg = %d", BotThinkCycles.TimeMS(), BotSupportCycles.TimeMS(), BotWTG); return out; }
1
0.812824
1
0.812824
game-dev
MEDIA
0.839569
game-dev
0.919284
1
0.919284
AscensionGameDev/Intersect-Engine
5,388
Framework/Intersect.Framework/Threading/ThreadQueue.cs
using System.Runtime.CompilerServices; namespace Intersect.Framework.Threading; public sealed partial class ThreadQueue : ActionQueue<ThreadQueue, ManualResetEventSlim> { public static readonly ThreadQueue Default = new(); private readonly object _lock = new(); private readonly Stack<ManualResetEventSlim> _resetEventPool = []; private readonly HashSet<CancellationTokenSource> _pendingCancellationTokenSources = []; private readonly int? _spinCount; private int _mainThreadId; public ThreadQueue(int? spinCount = null) : base(beginInvokePending: BeginInvokePending, endInvokePending: null) { _spinCount = spinCount; SetMainThreadId(); } public ThreadQueue(ThreadQueue parent) : base(beginInvokePending: BeginInvokePending, endInvokePending: null) { _spinCount = parent._spinCount; _mainThreadId = parent._mainThreadId; } protected override bool IsActive => IsOnMainThread; public bool IsOnMainThread { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _mainThreadId == Environment.CurrentManagedThreadId; } public override void ClearPending() { base.ClearPending(); CancellationTokenSource[] pendingCancellationTokenSources; lock (_pendingCancellationTokenSources) { pendingCancellationTokenSources = _pendingCancellationTokenSources.ToArray(); _pendingCancellationTokenSources.Clear(); } foreach (var cancellationTokenSource in pendingCancellationTokenSources) { cancellationTokenSource.Cancel(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void BeginInvokePending(ThreadQueue @this) => @this.ThrowIfNotOnMainThread(); protected override ManualResetEventSlim EnqueueCreateState() => ResetEventPoolPop(); protected override void EnqueueSuccessful(ManualResetEventSlim resetEvent) { CancellationTokenSource cancellationTokenSource = new(); lock (_pendingCancellationTokenSources) { _pendingCancellationTokenSources.Add(cancellationTokenSource); } try { resetEvent.Wait(cancellationTokenSource.Token); } catch (OperationCanceledException operationCanceledException) { if (!cancellationTokenSource.IsCancellationRequested || !operationCanceledException.CancellationToken.Equals(cancellationTokenSource.Token)) { throw; } } lock (_pendingCancellationTokenSources) { _pendingCancellationTokenSources.Remove(cancellationTokenSource); } } protected override void EnqueueFinally(ManualResetEventSlim resetEvent) => ResetEventPoolPush(resetEvent); protected override Action<ManualResetEventSlim> PostInvocationAction { get; } = static resetEvent => resetEvent.Set(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RunOnMainThread(Action action) => Enqueue(action); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RunOnMainThread<TState>(Action<TState> action, TState state) => Enqueue(action, state); [MethodImpl(MethodImplOptions.AggressiveInlining)] public TReturn RunOnMainThread<TState, TReturn>(Func<TState, TReturn> func, TState state) => EnqueueReturn(func, state); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RunOnMainThread<TState0, TState1>(Action<TState0, TState1> action, TState0 state0, TState1 state1) => Enqueue(action, state0, state1); [MethodImpl(MethodImplOptions.AggressiveInlining)] public TReturn RunOnMainThread<TState0, TState1, TReturn>(Func<TState0, TState1, TReturn> func, TState0 state0, TState1 state1) => EnqueueReturn(func, state0, state1); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RunOnMainThread<TState0, TState1, TState2>( Action<TState0, TState1, TState2> action, TState0 state0, TState1 state1, TState2 state2 ) => Enqueue(action, state0, state1, state2); private ManualResetEventSlim ResetEventPoolPop() { lock (_resetEventPool) { if (_resetEventPool.TryPop(out var resetEvent)) { return resetEvent; } } return _spinCount.HasValue ? new ManualResetEventSlim(false, _spinCount.Value) : new ManualResetEventSlim(); } private void ResetEventPoolPush(ManualResetEventSlim resetEvent) { resetEvent.Reset(); lock (_resetEventPool) { _resetEventPool.Push(resetEvent); } } public void SetMainThreadId(int? mainThreadId = null) { lock (_lock) { _mainThreadId = mainThreadId ?? Environment.CurrentManagedThreadId; } } public void SetMainThreadId(ThreadQueue other) { lock (_lock) { _mainThreadId = other._mainThreadId; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ThrowIfNotOnMainThread() { if (IsOnMainThread) { return; } throw new InvalidOperationException("Operation was not called on the main thread."); } }
1
0.926316
1
0.926316
game-dev
MEDIA
0.389181
game-dev
0.985565
1
0.985565
flowplayer/flash
1,979
plugins/captions/src/actionscript/org/flowplayer/captions/CCButton.as
/* * This file is part of Flowplayer, http://flowplayer.org * * By: Anssi Piirainen, <support@flowplayer.org> *Copyright (c) 2008-2011 Flowplayer Oy * * Released under the MIT License: * http://www.opensource.org/licenses/mit-license.php */ package org.flowplayer.captions { import flash.display.Sprite; import flash.events.MouseEvent; import flash.text.TextField; import org.flowplayer.view.AbstractSprite; import org.flowplayer.view.Flowplayer; internal class CCButton extends AbstractSprite { private var _text:TextField; private var _background:Sprite; private var _textColor:Number; private var _label:String; public function CCButton(player:Flowplayer, label:String) { _label = label; _background = new Sprite(); _background.buttonMode = true; addChild(_background); createText(player); isDown = true; } protected override function onResize():void { drawBackground(); _text.x = 2; _text.y = 0; } public function get clickArea():Sprite { return _background; } private function drawBackground():void { _background.graphics.clear(), _background.graphics.lineStyle(2, 0x555555); _background.graphics.beginFill(0xaaaaaa, 1); _background.graphics.drawRoundRect(0, 0, width, height, 6, 6); _background.graphics.endFill(); } private function createText(player:Flowplayer):void { _text = player.createTextField(8, true); _text.text = _label; _text.textColor = _textColor; addChild(_text); _text.selectable = false; _text.mouseEnabled = false; } public function set isDown(isDown:Boolean):void { _textColor = isDown ? 0 : 0xff2222; _text.textColor = _textColor; } } }
1
0.593192
1
0.593192
game-dev
MEDIA
0.577116
game-dev
0.853993
1
0.853993
ImLegiitXD/Dream-Advanced
8,762
dll/back/1.12/net/minecraft/entity/passive/EntitySquid.java
package net.minecraft.entity.passive; import javax.annotation.Nullable; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.MoverType; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.init.MobEffects; import net.minecraft.init.SoundEvents; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; import net.minecraft.util.datafix.DataFixer; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraft.world.storage.loot.LootTableList; public class EntitySquid extends EntityWaterMob { public float squidPitch; public float prevSquidPitch; public float squidYaw; public float prevSquidYaw; /** * appears to be rotation in radians; we already have pitch & yaw, so this completes the triumvirate. */ public float squidRotation; /** previous squidRotation in radians */ public float prevSquidRotation; /** angle of the tentacles in radians */ public float tentacleAngle; /** the last calculated angle of the tentacles in radians */ public float lastTentacleAngle; private float randomMotionSpeed; /** change in squidRotation in radians. */ private float rotationVelocity; private float rotateSpeed; private float randomMotionVecX; private float randomMotionVecY; private float randomMotionVecZ; public EntitySquid(World worldIn) { super(worldIn); this.setSize(0.8F, 0.8F); this.rand.setSeed((long)(1 + this.getEntityId())); this.rotationVelocity = 1.0F / (this.rand.nextFloat() + 1.0F) * 0.2F; } public static void registerFixesSquid(DataFixer fixer) { EntityLiving.registerFixesMob(fixer, EntitySquid.class); } protected void initEntityAI() { this.tasks.addTask(0, new EntitySquid.AIMoveRandom(this)); } protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(10.0D); } public float getEyeHeight() { return this.height * 0.5F; } protected SoundEvent getAmbientSound() { return SoundEvents.ENTITY_SQUID_AMBIENT; } protected SoundEvent getHurtSound(DamageSource damageSourceIn) { return SoundEvents.ENTITY_SQUID_HURT; } protected SoundEvent getDeathSound() { return SoundEvents.ENTITY_SQUID_DEATH; } /** * Returns the volume for the sounds this mob makes. */ protected float getSoundVolume() { return 0.4F; } /** * returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to * prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; } @Nullable protected ResourceLocation getLootTable() { return LootTableList.ENTITIES_SQUID; } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); this.prevSquidPitch = this.squidPitch; this.prevSquidYaw = this.squidYaw; this.prevSquidRotation = this.squidRotation; this.lastTentacleAngle = this.tentacleAngle; this.squidRotation += this.rotationVelocity; if ((double)this.squidRotation > (Math.PI * 2D)) { if (this.world.isRemote) { this.squidRotation = ((float)Math.PI * 2F); } else { this.squidRotation = (float)((double)this.squidRotation - (Math.PI * 2D)); if (this.rand.nextInt(10) == 0) { this.rotationVelocity = 1.0F / (this.rand.nextFloat() + 1.0F) * 0.2F; } this.world.setEntityState(this, (byte)19); } } if (this.inWater) { if (this.squidRotation < (float)Math.PI) { float f = this.squidRotation / (float)Math.PI; this.tentacleAngle = MathHelper.sin(f * f * (float)Math.PI) * (float)Math.PI * 0.25F; if ((double)f > 0.75D) { this.randomMotionSpeed = 1.0F; this.rotateSpeed = 1.0F; } else { this.rotateSpeed *= 0.8F; } } else { this.tentacleAngle = 0.0F; this.randomMotionSpeed *= 0.9F; this.rotateSpeed *= 0.99F; } if (!this.world.isRemote) { this.motionX = (double)(this.randomMotionVecX * this.randomMotionSpeed); this.motionY = (double)(this.randomMotionVecY * this.randomMotionSpeed); this.motionZ = (double)(this.randomMotionVecZ * this.randomMotionSpeed); } float f1 = MathHelper.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ); this.renderYawOffset += (-((float)MathHelper.atan2(this.motionX, this.motionZ)) * (180F / (float)Math.PI) - this.renderYawOffset) * 0.1F; this.rotationYaw = this.renderYawOffset; this.squidYaw = (float)((double)this.squidYaw + Math.PI * (double)this.rotateSpeed * 1.5D); this.squidPitch += (-((float)MathHelper.atan2((double)f1, this.motionY)) * (180F / (float)Math.PI) - this.squidPitch) * 0.1F; } else { this.tentacleAngle = MathHelper.abs(MathHelper.sin(this.squidRotation)) * (float)Math.PI * 0.25F; if (!this.world.isRemote) { this.motionX = 0.0D; this.motionZ = 0.0D; if (this.isPotionActive(MobEffects.LEVITATION)) { this.motionY += 0.05D * (double)(this.getActivePotionEffect(MobEffects.LEVITATION).getAmplifier() + 1) - this.motionY; } else if (!this.hasNoGravity()) { this.motionY -= 0.08D; } this.motionY *= 0.9800000190734863D; } this.squidPitch = (float)((double)this.squidPitch + (double)(-90.0F - this.squidPitch) * 0.02D); } } public void travel(float p_191986_1_, float p_191986_2_, float p_191986_3_) { this.move(MoverType.SELF, this.motionX, this.motionY, this.motionZ); } /** * Checks if the entity's current position is a valid location to spawn this entity. */ public boolean getCanSpawnHere() { return this.posY > 45.0D && this.posY < (double)this.world.getSeaLevel() && super.getCanSpawnHere(); } /** * Handler for {@link World#setEntityState} */ public void handleStatusUpdate(byte id) { if (id == 19) { this.squidRotation = 0.0F; } else { super.handleStatusUpdate(id); } } public void setMovementVector(float randomMotionVecXIn, float randomMotionVecYIn, float randomMotionVecZIn) { this.randomMotionVecX = randomMotionVecXIn; this.randomMotionVecY = randomMotionVecYIn; this.randomMotionVecZ = randomMotionVecZIn; } public boolean hasMovementVector() { return this.randomMotionVecX != 0.0F || this.randomMotionVecY != 0.0F || this.randomMotionVecZ != 0.0F; } static class AIMoveRandom extends EntityAIBase { private final EntitySquid squid; public AIMoveRandom(EntitySquid p_i45859_1_) { this.squid = p_i45859_1_; } public boolean shouldExecute() { return true; } public void updateTask() { int i = this.squid.getIdleTime(); if (i > 100) { this.squid.setMovementVector(0.0F, 0.0F, 0.0F); } else if (this.squid.getRNG().nextInt(50) == 0 || !this.squid.inWater || !this.squid.hasMovementVector()) { float f = this.squid.getRNG().nextFloat() * ((float)Math.PI * 2F); float f1 = MathHelper.cos(f) * 0.2F; float f2 = -0.1F + this.squid.getRNG().nextFloat() * 0.2F; float f3 = MathHelper.sin(f) * 0.2F; this.squid.setMovementVector(f1, f2, f3); } } } }
1
0.844783
1
0.844783
game-dev
MEDIA
0.854736
game-dev
0.985599
1
0.985599
mimilewis/MapleStory143
7,194
src/main/java/server/maps/MapleNodes.java
package server.maps; import tools.Pair; import java.awt.*; import java.util.*; import java.util.List; public class MapleNodes { private final Map<Integer, MapleNodeInfo> nodes; //used for HOB pq. private final List<Rectangle> areas; private final List<MaplePlatform> platforms; private final List<MonsterPoint> monsterPoints; private final List<Integer> skillIds; private final List<Pair<Integer, Integer>> mobsToSpawn; private final List<Pair<Point, Integer>> guardiansToSpawn; private final List<Pair<String, Integer>> flags; private final List<DirectionInfo> directionInfo; private final int mapid; private int nodeStart = -1; private boolean firstHighest = true; public MapleNodes(int mapid) { nodes = new LinkedHashMap<>(); areas = new ArrayList<>(); platforms = new ArrayList<>(); skillIds = new ArrayList<>(); directionInfo = new ArrayList<>(); monsterPoints = new ArrayList<>(); mobsToSpawn = new ArrayList<>(); guardiansToSpawn = new ArrayList<>(); flags = new ArrayList<>(); this.mapid = mapid; } public void setNodeStart(int ns) { this.nodeStart = ns; } public void addDirection(int key, DirectionInfo d) { this.directionInfo.add(key, d); } public DirectionInfo getDirection(int key) { if (key >= directionInfo.size()) { return null; } return directionInfo.get(key); } public List<Pair<String, Integer>> getFlags() { return flags; } public void addFlag(Pair<String, Integer> f) { flags.add(f); } public void addNode(MapleNodeInfo mni) { this.nodes.put(mni.key, mni); } public Collection<MapleNodeInfo> getNodes() { return new ArrayList<>(nodes.values()); } public MapleNodeInfo getNode(int index) { int i = 1; for (MapleNodeInfo x : getNodes()) { if (i == index) { return x; } i++; } return null; } public boolean isLastNode(int index) { return index == nodes.size(); } private int getNextNode(MapleNodeInfo mni) { if (mni == null) { return -1; } addNode(mni); // output part /* * StringBuilder b = new StringBuilder(mapid + " added key " + mni.key + * ". edges: "); for (int i : mni.edge) { b.append(i + ", "); } * System.out.println(b.toString()); * FileoutputUtil.log(FileoutputUtil.PacketEx_Log, b.toString()); */ // output part end int ret = -1; for (int i : mni.edge) { if (!nodes.containsKey(i)) { if (ret != -1 && (mapid / 100 == 9211204 || mapid / 100 == 9320001)) { if (!firstHighest) { ret = Math.min(ret, i); } else { firstHighest = false; ret = Math.max(ret, i); //two ways for stage 5 to get to end, thats highest ->lowest, and lowest -> highest(doesn't work) break; } } else { ret = i; } } } mni.nextNode = ret; return ret; } public void sortNodes() { if (nodes.size() <= 0 || nodeStart < 0) { return; } Map<Integer, MapleNodeInfo> unsortedNodes = new HashMap<>(nodes); int nodeSize = unsortedNodes.size(); nodes.clear(); int nextNode = getNextNode(unsortedNodes.get(nodeStart)); while (nodes.size() != nodeSize && nextNode >= 0) { nextNode = getNextNode(unsortedNodes.get(nextNode)); } } public void addMapleArea(Rectangle rec) { areas.add(rec); } public List<Rectangle> getAreas() { return new ArrayList<>(areas); } public Rectangle getArea(int index) { return getAreas().get(index); } public void addPlatform(MaplePlatform mp) { this.platforms.add(mp); } public List<MaplePlatform> getPlatforms() { return new ArrayList<>(platforms); } public List<MonsterPoint> getMonsterPoints() { return monsterPoints; } public void addMonsterPoint(int x, int y, int fh, int cy, int team) { this.monsterPoints.add(new MonsterPoint(x, y, fh, cy, team)); } public void addMobSpawn(int mobId, int spendCP) { this.mobsToSpawn.add(new Pair<>(mobId, spendCP)); } public List<Pair<Integer, Integer>> getMobsToSpawn() { return mobsToSpawn; } public void addGuardianSpawn(Point guardian, int team) { this.guardiansToSpawn.add(new Pair<>(guardian, team)); } public List<Pair<Point, Integer>> getGuardians() { return guardiansToSpawn; } public List<Integer> getSkillIds() { return skillIds; } public void addSkillId(int z) { this.skillIds.add(z); } public static class MapleNodeInfo { public final int node; public final int key; public final int x; public final int y; public final int attr; public final List<Integer> edge; public int nextNode = -1; public MapleNodeInfo(int node, int key, int x, int y, int attr, List<Integer> edge) { this.node = node; this.key = key; this.x = x; this.y = y; this.attr = attr; this.edge = edge; } } public static class DirectionInfo { public final int x; public final int y; public final int key; public final boolean forcedInput; public final List<String> eventQ = new ArrayList<>(); public DirectionInfo(int key, int x, int y, boolean forcedInput) { this.key = key; this.x = x; this.y = y; this.forcedInput = forcedInput; } } public static class MaplePlatform { public final String name; public final int start; public final int speed; public final int x1; public final int y1; public final int x2; public final int y2; public final int r; public final List<Integer> SN; public MaplePlatform(String name, int start, int speed, int x1, int y1, int x2, int y2, int r, List<Integer> SN) { this.name = name; this.start = start; this.speed = speed; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.r = r; this.SN = SN; } } public static class MonsterPoint { public final int x; public final int y; public final int fh; public final int cy; public final int team; public MonsterPoint(int x, int y, int fh, int cy, int team) { this.x = x; this.y = y; this.fh = fh; this.cy = cy; this.team = team; } } }
1
0.802953
1
0.802953
game-dev
MEDIA
0.792092
game-dev
0.975172
1
0.975172
ReactVision/virocore
1,943
macos/Libraries/bullet/include/BulletCollision/CollisionShapes/btConvexPolyhedron.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2011 Advanced Micro Devices, Inc. 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. */ ///This file was written by Erwin Coumans #ifndef _BT_POLYHEDRAL_FEATURES_H #define _BT_POLYHEDRAL_FEATURES_H #include "LinearMath/btTransform.h" #include "LinearMath/btAlignedObjectArray.h" #define TEST_INTERNAL_OBJECTS 1 struct btFace { btAlignedObjectArray<int> m_indices; // btAlignedObjectArray<int> m_connectedFaces; btScalar m_plane[4]; }; ATTRIBUTE_ALIGNED16(class) btConvexPolyhedron { public: BT_DECLARE_ALIGNED_ALLOCATOR(); btConvexPolyhedron(); virtual ~btConvexPolyhedron(); btAlignedObjectArray<btVector3> m_vertices; btAlignedObjectArray<btFace> m_faces; btAlignedObjectArray<btVector3> m_uniqueEdges; btVector3 m_localCenter; btVector3 m_extents; btScalar m_radius; btVector3 mC; btVector3 mE; void initialize(); bool testContainment() const; void project(const btTransform& trans, const btVector3& dir, btScalar& minProj, btScalar& maxProj, btVector3& witnesPtMin,btVector3& witnesPtMax) const; }; #endif //_BT_POLYHEDRAL_FEATURES_H
1
0.781552
1
0.781552
game-dev
MEDIA
0.995734
game-dev
0.516654
1
0.516654
Ragebones/StormCore
8,933
src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp
/* * Copyright (C) 2014-2017 StormCore * * 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Laj SD%Complete: 90 SDComment: Immunities are wrong, must be adjusted to use resistance from creature_templates. Most spells require database support. SDCategory: Tempest Keep, The Botanica EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "the_botanica.h" enum Spells { SPELL_ALLERGIC_REACTION = 34697, SPELL_TELEPORT_SELF = 34673, SPELL_SUMMON_LASHER_1 = 34681, SPELL_SUMMON_FLAYER_1 = 34682, SPELL_SUMMON_LASHER_2 = 34684, SPELL_SUMMON_FLAYER_2 = 34685, SPELL_SUMMON_LASHER_3 = 34686, SPELL_SUMMON_FLAYER_4 = 34687, SPELL_SUMMON_LASHER_4 = 34688, SPELL_SUMMON_FLAYER_3 = 34690 }; enum Misc { EMOTE_SUMMON = 0, MODEL_DEFAULT = 13109, MODEL_ARCANE = 14213, MODEL_FIRE = 13110, MODEL_FROST = 14112, MODEL_NATURE = 14214 }; class boss_laj : public CreatureScript { public: boss_laj() : CreatureScript("boss_laj") { } struct boss_lajAI : public BossAI { boss_lajAI(Creature* creature) : BossAI(creature, DATA_LAJ) { Initialize(); } void Initialize() { CanSummon = false; Teleport_Timer = 20000; Summon_Timer = 2500; Transform_Timer = 30000; Allergic_Timer = 5000; } bool CanSummon; uint32 Teleport_Timer; uint32 Summon_Timer; uint32 Transform_Timer; uint32 Allergic_Timer; void Reset() override { me->SetDisplayId(MODEL_DEFAULT); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_SHADOW, true); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_ARCANE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_NATURE, false); Initialize(); } void DoTransform() { switch (rand32() % 5) { case 0: me->SetDisplayId(MODEL_DEFAULT); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_SHADOW, true); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_ARCANE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_NATURE, false); break; case 1: me->SetDisplayId(MODEL_ARCANE); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_SHADOW, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_ARCANE, true); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_NATURE, false); break; case 2: me->SetDisplayId(MODEL_FIRE); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_SHADOW, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_ARCANE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, true); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_NATURE, false); break; case 3: me->SetDisplayId(MODEL_FROST); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_SHADOW, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_ARCANE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, true); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_NATURE, false); break; case 4: me->SetDisplayId(MODEL_NATURE); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_SHADOW, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_ARCANE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, false); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_NATURE, true); break; } } void DoSummons() { switch (rand32() % 4) { case 0: DoCast(me, SPELL_SUMMON_LASHER_1, true); DoCast(me, SPELL_SUMMON_FLAYER_1, true); break; case 1: DoCast(me, SPELL_SUMMON_LASHER_2, true); DoCast(me, SPELL_SUMMON_FLAYER_2, true); break; case 2: DoCast(me, SPELL_SUMMON_LASHER_3, true); DoCast(me, SPELL_SUMMON_FLAYER_3, true); break; case 3: DoCast(me, SPELL_SUMMON_LASHER_4, true); DoCast(me, SPELL_SUMMON_FLAYER_4, true); break; } CanSummon = false; } void EnterCombat(Unit* /*who*/) override { } void JustSummoned(Creature* summon) override { if (summon && me->GetVictim()) summon->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0)); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; if (CanSummon) { if (Summon_Timer <= diff) { Talk(EMOTE_SUMMON); DoSummons(); Summon_Timer = 2500; } else Summon_Timer -= diff; } if (Allergic_Timer <= diff) { DoCastVictim(SPELL_ALLERGIC_REACTION); Allergic_Timer = 25000 + rand32() % 15000; } else Allergic_Timer -= diff; if (Teleport_Timer <= diff) { DoCast(me, SPELL_TELEPORT_SELF); Teleport_Timer = 30000 + rand32() % 10000; CanSummon = true; } else Teleport_Timer -= diff; if (Transform_Timer <= diff) { DoTransform(); Transform_Timer = 25000 + rand32() % 15000; } else Transform_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new boss_lajAI(creature); } }; void AddSC_boss_laj() { new boss_laj(); }
1
0.81799
1
0.81799
game-dev
MEDIA
0.379489
game-dev
0.865165
1
0.865165
MudBlazor/MudBlazor
1,228
src/MudBlazor/Components/Slider/SliderContext.cs
// Copyright (c) MudBlazor 2021 // MudBlazor licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace MudBlazor; #nullable enable /// <summary> /// The current state of a <see cref="MudSlider{T}"/> component, containing both the value and nullable value. /// </summary> /// <remarks> /// This state is a cascading parameter for <see cref="MudSlider{T}"/> components. /// </remarks> /// <typeparam name="T">The type of the value the slider represents.</typeparam> public class SliderContext<T> where T : struct { /// <summary> /// The value of the slider. /// </summary> public T Value { get; } /// <summary> /// The nullable value of the slider. /// </summary> public T? NullableValue { get; } /// <summary> /// Initializes a new instance of the <see cref="SliderContext{T}"/> class with the specified value and nullable value. /// </summary> /// <param name="value">The value of the slider.</param> /// <param name="nullableValue">The nullable value of the slider.</param> public SliderContext(T value, T? nullableValue) { NullableValue = nullableValue; Value = value; } }
1
0.733204
1
0.733204
game-dev
MEDIA
0.312792
game-dev
0.59313
1
0.59313
meetric1/gmod-infinite-map
10,102
lua/infmap/sv_inf_chunks.lua
// physgun, gravgun, and use support local ply_objs = {} local function pickup(ply, ent) ply_objs[ply] = ent end // kind of cursed.. key = player, value = prop local function drop(ply, ent) ply_objs[ply] = nil end hook.Add("OnPhysgunPickup", "infinite_detour", pickup) hook.Add("PhysgunDrop", "infinte_detour", drop) hook.Add("GravGunOnPickedUp", "infinite_detour", pickup) hook.Add("GravGunOnDropped", "infinte_detour", drop) hook.Add("OnPlayerPhysicsPickup", "infinite_detour", pickup) hook.Add("OnPlayerPhysicsDrop", "infinte_detour", drop) // setting position kills all velocity for some reason local source_bounds = 2^14 - 64 local function unfucked_SetPos(ent, pos, filter) if ent:GetParent():IsValid() then return end // parents are local, dont setpos.. lets hope the parent entity itself was also teleported // clamp position inside source bounds incase contraption is massive // helps things like simphys cars not fucking die pos[1] = math.Clamp(pos[1], -source_bounds, source_bounds) pos[2] = math.Clamp(pos[2], -source_bounds, source_bounds) pos[3] = math.Clamp(pos[3], -source_bounds, source_bounds) // ragdoll moment if ent:IsRagdoll() then for i = 0, ent:GetPhysicsObjectCount() - 1 do local phys = ent:GetPhysicsObjectNum(i) local vel = phys:GetVelocity() local ang_vel = phys:GetAngleVelocity() local diff = phys:InfMap_GetPos() - ent:InfMap_GetPos() phys:InfMap_SetPos(pos + diff, true) phys:SetVelocity(vel) phys:SetAngleVelocity(ang_vel) end end ent:InfMap_SetPos(pos) end local function unfucked_SetVelAng(ent, vel, ang) if !IsValid(ent) then return end local phys = ent:GetPhysicsObject() if phys:IsValid() then if ang then phys:SetAngles(ang) end phys:SetVelocity(vel) else if ang then ent:SetAngles(ang) end ent:SetVelocity(vel) end end local function update_entity(ent, pos, chunk) if ent:IsPlayer() then // carried props are teleported to the next chunk local carry = ply_objs[ent] if IsValid(carry) then // teleport entire contraption InfMap.constrained_status(carry) // initialize constrained data local ent_pos = ent:InfMap_GetPos() for _, constrained_ent in ipairs(carry.CONSTRAINED_DATA or {ent, carry}) do // includes itself if !constrained_ent:IsValid() or InfMap.filter_entities(constrained_ent) then continue end if constrained_ent != carry then constrained_ent:ForcePlayerDrop() end local constrained_vel = constrained_ent:GetVelocity() local constrained_ang = constrained_ent:GetAngles() InfMap.prop_update_chunk(constrained_ent, chunk) unfucked_SetPos(constrained_ent, pos + (constrained_ent:InfMap_GetPos() - ent_pos)) unfucked_SetVelAng(constrained_ent, constrained_vel, constrained_ang) end InfMap.reset_constrained_data(carry) end end InfMap.prop_update_chunk(ent, chunk) unfucked_SetPos(ent, pos) end // which entities should be checked per frame local all_ents = {} timer.Create("infinite_chunkmove_update", 0.1, 0, function() all_ents = ents.GetAll() for i = #all_ents, 1, -1 do // iterate downward // if invalid is true, then the entity should be removed from the table calculated per frame local ent = all_ents[i] local invalid = !ent.CHUNK_OFFSET invalid = invalid or InfMap.filter_entities(ent) invalid = invalid or ent:GetVelocity() == Vector() invalid = invalid or IsValid(ent:GetParent()) invalid = invalid or ent:IsPlayer() and !ent:Alive() if invalid then table.remove(all_ents, i) // remove invalid entity end // gravhull support local ship = ent.MyShip or ent.InShip if IsValid(ship) then InfMap.gravhull_ents[ent] = ship else InfMap.gravhull_ents[ent] = nil end end end) // gravhull prop chunk updater InfMap.gravhull_ents = {} hook.Add("Think", "infinite_gravhull_update", function() for ent, ship in pairs(InfMap.gravhull_ents) do if !IsValid(ent) or !IsValid(ship) then InfMap.gravhull_ents[ent] = nil continue end if ship.CHUNK_OFFSET != ent.CHUNK_OFFSET then InfMap.prop_update_chunk(ent, ship.CHUNK_OFFSET) end end end) // object wrapping, if in next chunk, put in next chunk and do localization math hook.Add("Think", "infinite_chunkmove", function() for _, main_ent in ipairs(all_ents) do if !IsValid(main_ent) then continue end if !main_ent.CHUNK_OFFSET then continue end if !InfMap.in_chunk(main_ent:InfMap_GetPos(), InfMap.chunk_size + 1) then // add 1 to avoid recourring teleport when prop is perfectly at chunk boundery if !InfMap.constrained_status(main_ent) then continue end if main_ent:IsPlayerHolding() then continue end // physgun, gravgun, and use support local pos, offset = InfMap.localize_vector(main_ent:InfMap_GetPos()) local final_chunk_offset = main_ent.CHUNK_OFFSET + offset local main_ent_pos = main_ent:InfMap_GetPos() local constrained_vel = {} local constrained_ang = {} //grab ang+vel before teleport local main_vel = main_ent:GetVelocity() local main_ang = main_ent:GetAngles() for v, constrained_ent in ipairs(main_ent.CONSTRAINED_DATA) do if !IsValid(constrained_ent) then continue end constrained_vel[v] = constrained_ent:GetVelocity() constrained_ang[v] = constrained_ent:GetAngles() end for _, constrained_ent in ipairs(main_ent.CONSTRAINED_DATA) do // includes itself if main_ent == constrained_ent then continue end if !constrained_ent:IsValid() or InfMap.filter_entities(constrained_ent) then continue end local phys = constrained_ent:GetPhysicsObject() if constrained_ent != main_ent then constrained_ent:ForcePlayerDrop() end //if constrained_ent.CHUNK_OFFSET != main_ent.CHUNK_OFFSET then continue end local delta_pos = pos + (constrained_ent:InfMap_GetPos() - main_ent_pos) update_entity(constrained_ent, delta_pos, final_chunk_offset) end // update main ent update_entity(main_ent, pos, final_chunk_offset) // set vel+ang after teleport on constrained props for v, constrained_ent in ipairs(main_ent.CONSTRAINED_DATA) do unfucked_SetVelAng(constrained_ent,constrained_vel[v],constrained_ang[v]) end //set vel+ang on main prop after teleport unfucked_SetVelAng(main_ent,main_vel,main_ang) else InfMap.reset_constrained_data(main_ent) end end end) // collision with props crossing through chunk bounderies local co = coroutine.create(function() while true do local err, str = pcall(function() for _, ent in ipairs(ents.GetAll()) do if !IsValid(ent) then continue end if InfMap.filter_entities(ent) then continue end ///////////////////////////////// if !ent.CHUNK_OFFSET then continue end if !ent:IsSolid() or !ent:GetModel() then continue end if IsValid(ent:GetParent()) then continue end //if ent:GetVelocity() == Vector() then continue end // player support if ent:IsPlayer() and (ent:GetMoveType() == MOVETYPE_NOCLIP or !ent:Alive()) then continue end // check all surrounding chunks with a fast check using radius instead of bounding box local bounding_radius = ent:BoundingRadius() // no tiny props, too much computation if bounding_radius < 10 then continue end if !InfMap.in_chunk(ent:InfMap_GetPos(), InfMap.chunk_size - bounding_radius) then ent.CHUNK_CLONES = ent.CHUNK_CLONES or {} local i = 0 local aabb_min, aabb_max = ent:InfMap_WorldSpaceAABB() for z = -1, 1 do for y = -1, 1 do for x = -1, 1 do // never clone in the same chunk the object is already in if x == 0 and y == 0 and z == 0 then continue end i = i + 1 // if in chunk next to it, clone local chunk_pos = Vector(x, y, z) * InfMap.chunk_size * 2 local chunk_min = chunk_pos - Vector(1, 1, 1) * InfMap.chunk_size local chunk_max = chunk_pos + Vector(1, 1, 1) * InfMap.chunk_size //debugoverlay.Box(chunk_pos, chunk_min, chunk_max, 0.1, Color(255, 0, 255, 0)) if InfMap.intersect_box(aabb_min, aabb_max, chunk_min, chunk_max) then // dont clone 2 times if IsValid(ent.CHUNK_CLONES[i]) then continue end // clone object local e = ents.Create("infmap_clone") e:SetReferenceData(ent, Vector(x, y, z)) e:Spawn() ent.CHUNK_CLONES[i] = e else if !ent.CHUNK_CLONES[i] then continue end // remove cloned object if its moved out of chunk SafeRemoveEntity(ent.CHUNK_CLONES[i]) ent.CHUNK_CLONES[i] = nil end end end end else // outside of area for cloning to happen, remove all clones if ent.CHUNK_CLONES then for _, e in pairs(ent.CHUNK_CLONES) do SafeRemoveEntity(e) end ent.CHUNK_CLONES = nil end end coroutine.yield() end end) if !err then print(str) end coroutine.yield() end end) // cross chunk collision hook.Add("Think", "infinite_ccc", function() coroutine.resume(co) end) // when players spawn reset them to 0,0,0 chunk hook.Add("PlayerSpawn", "infmap_plyreset", function(ply, trans) InfMap.prop_update_chunk(ply, Vector()) end) // if player enters seat from another chunk set them to that chunk local function vehicle_edit(ply, veh) local co1 = ply.CHUNK_OFFSET local co2 = veh.CHUNK_OFFSET if co1 and co2 and co1 != co2 then InfMap.prop_update_chunk(ply, co2) end end hook.Add("PlayerEnteredVehicle", "infmap_seatreset", vehicle_edit) hook.Add("PlayerLeaveVehicle", "infmap_seatreset", vehicle_edit) // when entities are spawned, put them in designated chunks local ent_unfilter = { rpg_missile = true, crossbow_bolt = true, } hook.Add("OnEntityCreated", "infinite_propreset", function(ent) timer.Simple(0, function() // let entity data table update if IsValid(ent) then if ent.CHUNK_OFFSET then return end if InfMap.filter_entities(ent) and !ent_unfilter[ent:GetClass()] then return end local pos = Vector() local owner = ent:GetOwner() if !IsValid(owner) then owner = ent:GetParent() end if IsValid(owner) and owner.CHUNK_OFFSET then pos = owner.CHUNK_OFFSET end InfMap.prop_update_chunk(ent, pos) end end) end)
1
0.811513
1
0.811513
game-dev
MEDIA
0.750032
game-dev
0.99006
1
0.99006
b3agz/Code-A-Game-Like-Minecraft-In-Unity
10,688
12-threading/Assets/Scripts/World.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class World : MonoBehaviour { public int seed; public BiomeAttributes biome; public Transform player; public Vector3 spawnPosition; public Material material; public Material transparentMaterial; public BlockType[] blocktypes; Chunk[,] chunks = new Chunk[VoxelData.WorldSizeInChunks, VoxelData.WorldSizeInChunks]; List<ChunkCoord> activeChunks = new List<ChunkCoord>(); public ChunkCoord playerChunkCoord; ChunkCoord playerLastChunkCoord; List<ChunkCoord> chunksToCreate = new List<ChunkCoord>(); List<Chunk> chunksToUpdate = new List<Chunk>(); public Queue<Chunk> chunksToDraw = new Queue<Chunk>(); bool applyingModifications = false; Queue<Queue<VoxelMod>> modifications = new Queue<Queue<VoxelMod>>(); public GameObject debugScreen; private void Start() { Random.InitState(seed); spawnPosition = new Vector3((VoxelData.WorldSizeInChunks * VoxelData.ChunkWidth) / 2f, VoxelData.ChunkHeight - 50f, (VoxelData.WorldSizeInChunks * VoxelData.ChunkWidth) / 2f); GenerateWorld(); playerLastChunkCoord = GetChunkCoordFromVector3(player.position); } private void Update() { playerChunkCoord = GetChunkCoordFromVector3(player.position); // Only update the chunks if the player has moved from the chunk they were previously on. if (!playerChunkCoord.Equals(playerLastChunkCoord)) CheckViewDistance(); if (!applyingModifications) ApplyModifications(); if (chunksToCreate.Count > 0) CreateChunk(); if (chunksToUpdate.Count > 0) UpdateChunks(); if (chunksToDraw.Count > 0) lock (chunksToDraw) { if (chunksToDraw.Peek().isEditable) chunksToDraw.Dequeue().CreateMesh(); } if (Input.GetKeyDown(KeyCode.F3)) debugScreen.SetActive(!debugScreen.activeSelf); } void GenerateWorld () { for (int x = (VoxelData.WorldSizeInChunks / 2) - VoxelData.ViewDistanceInChunks; x < (VoxelData.WorldSizeInChunks / 2) + VoxelData.ViewDistanceInChunks; x++) { for (int z = (VoxelData.WorldSizeInChunks / 2) - VoxelData.ViewDistanceInChunks; z < (VoxelData.WorldSizeInChunks / 2) + VoxelData.ViewDistanceInChunks; z++) { chunks[x, z] = new Chunk(new ChunkCoord(x, z), this, true); activeChunks.Add(new ChunkCoord(x, z)); } } player.position = spawnPosition; } void CreateChunk () { ChunkCoord c = chunksToCreate[0]; chunksToCreate.RemoveAt(0); activeChunks.Add(c); chunks[c.x, c.z].Init(); } void UpdateChunks () { bool updated = false; int index = 0; while (!updated && index < chunksToUpdate.Count - 1) { if (chunksToUpdate[index].isEditable) { chunksToUpdate[index].UpdateChunk(); chunksToUpdate.RemoveAt(index); updated = true; } else index++; } } void ApplyModifications () { applyingModifications = true; while (modifications.Count > 0) { Queue<VoxelMod> queue = modifications.Dequeue(); while (queue.Count > 0) { VoxelMod v = queue.Dequeue(); ChunkCoord c = GetChunkCoordFromVector3(v.position); if (chunks[c.x, c.z] == null) { chunks[c.x, c.z] = new Chunk(c, this, true); activeChunks.Add(c); } chunks[c.x, c.z].modifications.Enqueue(v); if (!chunksToUpdate.Contains(chunks[c.x, c.z])) chunksToUpdate.Add(chunks[c.x, c.z]); } } applyingModifications = false; } ChunkCoord GetChunkCoordFromVector3 (Vector3 pos) { int x = Mathf.FloorToInt(pos.x / VoxelData.ChunkWidth); int z = Mathf.FloorToInt(pos.z / VoxelData.ChunkWidth); return new ChunkCoord(x, z); } public Chunk GetChunkFromVector3 (Vector3 pos) { int x = Mathf.FloorToInt(pos.x / VoxelData.ChunkWidth); int z = Mathf.FloorToInt(pos.z / VoxelData.ChunkWidth); return chunks[x, z]; } void CheckViewDistance () { ChunkCoord coord = GetChunkCoordFromVector3(player.position); playerLastChunkCoord = playerChunkCoord; List<ChunkCoord> previouslyActiveChunks = new List<ChunkCoord>(activeChunks); // Loop through all chunks currently within view distance of the player. for (int x = coord.x - VoxelData.ViewDistanceInChunks; x < coord.x + VoxelData.ViewDistanceInChunks; x++) { for (int z = coord.z - VoxelData.ViewDistanceInChunks; z < coord.z + VoxelData.ViewDistanceInChunks; z++) { // If the current chunk is in the world... if (IsChunkInWorld (new ChunkCoord (x, z))) { // Check if it active, if not, activate it. if (chunks[x, z] == null) { chunks[x, z] = new Chunk(new ChunkCoord(x, z), this, false); chunksToCreate.Add(new ChunkCoord(x, z)); } else if (!chunks[x, z].isActive) { chunks[x, z].isActive = true; } activeChunks.Add(new ChunkCoord(x, z)); } // Check through previously active chunks to see if this chunk is there. If it is, remove it from the list. for (int i = 0; i < previouslyActiveChunks.Count; i++) { if (previouslyActiveChunks[i].Equals(new ChunkCoord(x, z))) previouslyActiveChunks.RemoveAt(i); } } } // Any chunks left in the previousActiveChunks list are no longer in the player's view distance, so loop through and disable them. foreach (ChunkCoord c in previouslyActiveChunks) chunks[c.x, c.z].isActive = false; } public bool CheckForVoxel (Vector3 pos) { ChunkCoord thisChunk = new ChunkCoord(pos); if (!IsChunkInWorld(thisChunk) || pos.y < 0 || pos.y > VoxelData.ChunkHeight) return false; if (chunks[thisChunk.x, thisChunk.z] != null && chunks[thisChunk.x, thisChunk.z].isEditable) return blocktypes[chunks[thisChunk.x, thisChunk.z].GetVoxelFromGlobalVector3(pos)].isSolid; return blocktypes[GetVoxel(pos)].isSolid; } public bool CheckIfVoxelTransparent (Vector3 pos) { ChunkCoord thisChunk = new ChunkCoord(pos); if (!IsChunkInWorld(thisChunk) || pos.y < 0 || pos.y > VoxelData.ChunkHeight) return false; if (chunks[thisChunk.x, thisChunk.z] != null && chunks[thisChunk.x, thisChunk.z].isEditable) return blocktypes[chunks[thisChunk.x, thisChunk.z].GetVoxelFromGlobalVector3(pos)].isTransparent; return blocktypes[GetVoxel(pos)].isTransparent; } public byte GetVoxel (Vector3 pos) { int yPos = Mathf.FloorToInt(pos.y); /* IMMUTABLE PASS */ // If outside world, return air. if (!IsVoxelInWorld(pos)) return 0; // If bottom block of chunk, return bedrock. if (yPos == 0) return 1; /* BASIC TERRAIN PASS */ int terrainHeight = Mathf.FloorToInt(biome.terrainHeight * Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.terrainScale)) + biome.solidGroundHeight; byte voxelValue = 0; if (yPos == terrainHeight) voxelValue = 3; else if (yPos < terrainHeight && yPos > terrainHeight - 4) voxelValue = 5; else if (yPos > terrainHeight) return 0; else voxelValue = 2; /* SECOND PASS */ if (voxelValue == 2) { foreach (Lode lode in biome.lodes) { if (yPos > lode.minHeight && yPos < lode.maxHeight) if (Noise.Get3DPerlin(pos, lode.noiseOffset, lode.scale, lode.threshold)) voxelValue = lode.blockID; } } /* TREE PASS */ if (yPos == terrainHeight) { if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.treeZoneScale) > biome.treeZoneThreshold) { if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.treePlacementScale) > biome.treePlacementThreshold) { modifications.Enqueue(Structure.MakeTree(pos, biome.minTreeHeight, biome.maxTreeHeight)); } } } return voxelValue; } bool IsChunkInWorld (ChunkCoord coord) { if (coord.x > 0 && coord.x < VoxelData.WorldSizeInChunks - 1 && coord.z > 0 && coord.z < VoxelData.WorldSizeInChunks - 1) return true; else return false; } bool IsVoxelInWorld (Vector3 pos) { if (pos.x >= 0 && pos.x < VoxelData.WorldSizeInVoxels && pos.y >= 0 && pos.y < VoxelData.ChunkHeight && pos.z >= 0 && pos.z < VoxelData.WorldSizeInVoxels) return true; else return false; } } [System.Serializable] public class BlockType { public string blockName; public bool isSolid; public bool isTransparent; public Sprite icon; [Header("Texture Values")] public int backFaceTexture; public int frontFaceTexture; public int topFaceTexture; public int bottomFaceTexture; public int leftFaceTexture; public int rightFaceTexture; // Back, Front, Top, Bottom, Left, Right public int GetTextureID (int faceIndex) { switch (faceIndex) { case 0: return backFaceTexture; case 1: return frontFaceTexture; case 2: return topFaceTexture; case 3: return bottomFaceTexture; case 4: return leftFaceTexture; case 5: return rightFaceTexture; default: Debug.Log("Error in GetTextureID; invalid face index"); return 0; } } } public class VoxelMod { public Vector3 position; public byte id; public VoxelMod () { position = new Vector3(); id = 0; } public VoxelMod (Vector3 _position, byte _id) { position = _position; id = _id; } }
1
0.871714
1
0.871714
game-dev
MEDIA
0.94249
game-dev
0.842006
1
0.842006
openpool/openpool-core-unity
1,319
UnityModule/OpenPool/Assets/UnitySteer/Behaviors/AutonomousVehicle.cs
using UnityEngine; using UnitySteer; /// <summary> /// Vehicle subclass which automatically applies the steering forces from /// the components attached to the object. AutonomousVehicle is characterized /// for the vehicle always moving in the same direction as its forward vector, /// unlike Bipeds which are able to side-step. /// </summary> [AddComponentMenu("UnitySteer/Vehicle/Autonomous")] public class AutonomousVehicle : TickedVehicle { #region Internal state values float _speed; #endregion public override float Speed { get { return _speed; } set { _speed = Mathf.Clamp(value, 0, MaxSpeed); DesiredSpeed = _speed; } } /// <summary> /// Current vehicle velocity /// </summary> public override Vector3 Velocity { get { return Transform.forward * _speed; } set { throw new System.NotSupportedException("Cannot set the velocity directly on AutonomousVehicle"); } } #region Speed-related methods public override void UpdateOrientationVelocity(Vector3 velocity) { Speed = velocity.magnitude; OrientationVelocity = _speed != 0 ? velocity / _speed : Transform.forward; } protected override Vector3 CalculatePositionDelta(float deltaTime) { return Velocity * deltaTime; } protected override void ZeroVelocity() { Speed = 0; } #endregion }
1
0.836572
1
0.836572
game-dev
MEDIA
0.949461
game-dev
0.934433
1
0.934433
lazarv/wasm-doom
19,542
src/doom/p_switch.c
// // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005-2014 Simon Howard // // 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. // // // DESCRIPTION: // Switches, buttons. Two-state animation. Exits. // #include <stdio.h> #include "i_system.h" #include "deh_main.h" #include "doomdef.h" #include "p_local.h" #include "i_swap.h" // [crispy] SHORT() #include "w_wad.h" // [crispy] W_CheckNumForName() #include "z_zone.h" // [crispy] Z_ChangeTag() #include "g_game.h" #include "s_sound.h" // Data. #include "sounds.h" // State. #include "doomstat.h" #include "r_state.h" // // CHANGE THE TEXTURE OF A WALL SWITCH TO ITS OPPOSITE // // [crispy] add support for SWITCHES lumps switchlist_t alphSwitchList_vanilla[] = { // Doom shareware episode 1 switches {"SW1BRCOM", "SW2BRCOM", 1}, {"SW1BRN1", "SW2BRN1", 1}, {"SW1BRN2", "SW2BRN2", 1}, {"SW1BRNGN", "SW2BRNGN", 1}, {"SW1BROWN", "SW2BROWN", 1}, {"SW1COMM", "SW2COMM", 1}, {"SW1COMP", "SW2COMP", 1}, {"SW1DIRT", "SW2DIRT", 1}, {"SW1EXIT", "SW2EXIT", 1}, {"SW1GRAY", "SW2GRAY", 1}, {"SW1GRAY1", "SW2GRAY1", 1}, {"SW1METAL", "SW2METAL", 1}, {"SW1PIPE", "SW2PIPE", 1}, {"SW1SLAD", "SW2SLAD", 1}, {"SW1STARG", "SW2STARG", 1}, {"SW1STON1", "SW2STON1", 1}, {"SW1STON2", "SW2STON2", 1}, {"SW1STONE", "SW2STONE", 1}, {"SW1STRTN", "SW2STRTN", 1}, // Doom registered episodes 2&3 switches {"SW1BLUE", "SW2BLUE", 2}, {"SW1CMT", "SW2CMT", 2}, {"SW1GARG", "SW2GARG", 2}, {"SW1GSTON", "SW2GSTON", 2}, {"SW1HOT", "SW2HOT", 2}, {"SW1LION", "SW2LION", 2}, {"SW1SATYR", "SW2SATYR", 2}, {"SW1SKIN", "SW2SKIN", 2}, {"SW1VINE", "SW2VINE", 2}, {"SW1WOOD", "SW2WOOD", 2}, // Doom II switches {"SW1PANEL", "SW2PANEL", 3}, {"SW1ROCK", "SW2ROCK", 3}, {"SW1MET2", "SW2MET2", 3}, {"SW1WDMET", "SW2WDMET", 3}, {"SW1BRIK", "SW2BRIK", 3}, {"SW1MOD1", "SW2MOD1", 3}, {"SW1ZIM", "SW2ZIM", 3}, {"SW1STON6", "SW2STON6", 3}, {"SW1TEK", "SW2TEK", 3}, {"SW1MARB", "SW2MARB", 3}, {"SW1SKULL", "SW2SKULL", 3}, // [crispy] SWITCHES lumps are supposed to end like this {"\0", "\0", 0} }; // [crispy] remove MAXSWITCHES limit int *switchlist; int numswitches; static size_t maxswitches; button_t *buttonlist; // [crispy] remove MAXBUTTONS limit int maxbuttons; // [crispy] remove MAXBUTTONS limit // // P_InitSwitchList // Only called at game initialization. // void P_InitSwitchList(void) { int i, slindex, episode; // [crispy] add support for SWITCHES lumps switchlist_t *alphSwitchList; boolean from_lump; if ((from_lump = (W_CheckNumForName("SWITCHES") != -1))) { alphSwitchList = W_CacheLumpName("SWITCHES", PU_STATIC); } else { alphSwitchList = alphSwitchList_vanilla; } // Note that this is called "episode" here but it's actually something // quite different. As we progress from Shareware->Registered->Doom II // we support more switch textures. switch (gamemode) { case registered: case retail: episode = 2; break; case commercial: episode = 3; break; default: episode = 1; break; } slindex = 0; for (i = 0; alphSwitchList[i].episode; i++) { const short alphSwitchList_episode = from_lump ? SHORT(alphSwitchList[i].episode) : alphSwitchList[i].episode; // [crispy] remove MAXSWITCHES limit if (slindex + 1 >= maxswitches) { size_t newmax = maxswitches ? 2 * maxswitches : MAXSWITCHES; switchlist = I_Realloc(switchlist, newmax * sizeof(*switchlist)); maxswitches = newmax; } if (alphSwitchList_episode <= episode) { switchlist[slindex++] = R_TextureNumForName(DEH_String(alphSwitchList[i].name1)); switchlist[slindex++] = R_TextureNumForName(DEH_String(alphSwitchList[i].name2)); } } numswitches = slindex / 2; switchlist[slindex] = -1; // [crispy] add support for SWITCHES lumps if (from_lump) { Z_ChangeTag(alphSwitchList, PU_CACHE); } // [crispy] pre-allocate some memory for the buttonlist[] array buttonlist = I_Realloc(NULL, sizeof(*buttonlist) * (maxbuttons = MAXBUTTONS)); memset(buttonlist, 0, sizeof(*buttonlist) * maxbuttons); } // // Start a button counting down till it turns off. // void P_StartButton ( line_t* line, bwhere_e w, int texture, int time ) { int i; // See if button is already pressed for (i = 0;i < maxbuttons;i++) { if (buttonlist[i].btimer && buttonlist[i].line == line) { // [crispy] register up to three buttons at once for lines with more than one switch texture if (buttonlist[i].where == w) { return; } } } for (i = 0;i < maxbuttons;i++) { if (!buttonlist[i].btimer) { buttonlist[i].line = line; buttonlist[i].where = w; buttonlist[i].btexture = texture; buttonlist[i].btimer = time; buttonlist[i].soundorg = &line->soundorg; // [crispy] corrected sound source return; } } // [crispy] remove MAXBUTTONS limit { maxbuttons = 2 * maxbuttons; buttonlist = I_Realloc(buttonlist, sizeof(*buttonlist) * maxbuttons); memset(buttonlist + maxbuttons/2, 0, sizeof(*buttonlist) * maxbuttons/2); return P_StartButton(line, w, texture, time); } I_Error("P_StartButton: no button slots left!"); } // // Function that changes wall texture. // Tell it if switch is ok to use again (1=yes, it's a button). // void P_ChangeSwitchTexture ( line_t* line, int useAgain ) { int texTop; int texMid; int texBot; int i; int sound; if (!useAgain) line->special = 0; texTop = sides[line->sidenum[0]].toptexture; texMid = sides[line->sidenum[0]].midtexture; texBot = sides[line->sidenum[0]].bottomtexture; sound = sfx_swtchn; // EXIT SWITCH? if (line->special == 11) sound = sfx_swtchx; for (i = 0;i < numswitches*2;i++) { if (switchlist[i] == texTop) { S_StartSoundOnce(&line->soundorg,sound); // [crispy] corrected sound source sides[line->sidenum[0]].toptexture = switchlist[i^1]; if (useAgain) P_StartButton(line,top,switchlist[i],BUTTONTIME); // return; } // [crispy] register up to three buttons at once for lines with more than one switch texture // else { if (switchlist[i] == texMid) { S_StartSoundOnce(&line->soundorg,sound); // [crispy] corrected sound source sides[line->sidenum[0]].midtexture = switchlist[i^1]; if (useAgain) P_StartButton(line, middle,switchlist[i],BUTTONTIME); // return; } // [crispy] register up to three buttons at once for lines with more than one switch texture // else { if (switchlist[i] == texBot) { S_StartSoundOnce(&line->soundorg,sound); // [crispy] corrected sound source sides[line->sidenum[0]].bottomtexture = switchlist[i^1]; if (useAgain) P_StartButton(line, bottom,switchlist[i],BUTTONTIME); // return; } } } } } // // P_UseSpecialLine // Called when a thing uses a special line. // Only the front sides of lines are usable. // boolean P_UseSpecialLine ( mobj_t* thing, line_t* line, int side ) { // Err... // Use the back sides of VERY SPECIAL lines... if (side) { switch(line->special) { case 124: // Sliding door open&close // UNUSED? break; default: return false; break; } } // pointer to line function is NULL by default, set non-null if // line special is push or switch generalized linedef type int (*linefunc)(line_t *line)=NULL; // check each range of generalized linedefs if ((unsigned)line->special >= GenEnd) { // Out of range for GenFloors } else if ((unsigned)line->special >= GenFloorBase) { if (!thing->player) if ((line->special & FloorChange) || !(line->special & FloorModel)) return false; // FloorModel is "Allow Monsters" if FloorChange is 0 if (/*!comperr(comperr_zerotag) &&*/ !line->tag && ((line->special&6)!=6)) //e6y //jff 2/27/98 all non-manual return false; // generalized types require tag linefunc = EV_DoGenFloor; } else if ((unsigned)line->special >= GenCeilingBase) { if (!thing->player) if ((line->special & CeilingChange) || !(line->special & CeilingModel)) return false; // CeilingModel is "Allow Monsters" if CeilingChange is 0 if (/*!comperr(comperr_zerotag) &&*/ !line->tag && ((line->special&6)!=6)) //e6y //jff 2/27/98 all non-manual return false; // generalized types require tag linefunc = EV_DoGenCeiling; } else if ((unsigned)line->special >= GenDoorBase) { if (!thing->player) { if (!(line->special & DoorMonster)) return false; // monsters disallowed from this door if (line->flags & ML_SECRET) // they can't open secret doors either return false; } if (/*!comperr(comperr_zerotag) &&*/ !line->tag && ((line->special&6)!=6)) //e6y //jff 3/2/98 all non-manual return false; // generalized types require tag linefunc = EV_DoGenDoor; } else if ((unsigned)line->special >= GenLockedBase) { if (!thing->player) return false; // monsters disallowed from unlocking doors if (!P_CanUnlockGenDoor(line,thing->player)) return false; if (/*!comperr(comperr_zerotag) &&*/ !line->tag && ((line->special&6)!=6)) //e6y //jff 2/27/98 all non-manual return false; // generalized types require tag linefunc = EV_DoGenLockedDoor; } else if ((unsigned)line->special >= GenLiftBase) { if (!thing->player) if (!(line->special & LiftMonster)) return false; // monsters disallowed if (/*!comperr(comperr_zerotag) &&*/ !line->tag && ((line->special&6)!=6)) //e6y //jff 2/27/98 all non-manual return false; // generalized types require tag linefunc = EV_DoGenLift; } else if ((unsigned)line->special >= GenStairsBase) { if (!thing->player) if (!(line->special & StairMonster)) return false; // monsters disallowed if (/*!comperr(comperr_zerotag) &&*/ !line->tag && ((line->special&6)!=6)) //e6y //jff 2/27/98 all non-manual return false; // generalized types require tag linefunc = EV_DoGenStairs; } else if ((unsigned)line->special >= GenCrusherBase) { if (!thing->player) if (!(line->special & CrusherMonster)) return false; // monsters disallowed if (/*!comperr(comperr_zerotag) &&*/ !line->tag && ((line->special&6)!=6)) //e6y //jff 2/27/98 all non-manual return false; // generalized types require tag linefunc = EV_DoGenCrusher; } if (linefunc) switch((line->special & TriggerType) >> TriggerTypeShift) { case PushOnce: if (!side) if (linefunc(line)) line->special = 0; return true; case PushMany: if (!side) linefunc(line); return true; case SwitchOnce: if (linefunc(line)) P_ChangeSwitchTexture(line,0); return true; case SwitchMany: if (linefunc(line)) P_ChangeSwitchTexture(line,1); return true; default: // if not a switch/push type, do nothing here return false; } // Switches that other things can activate. if (!thing->player) { // never open secret doors if (line->flags & ML_SECRET) return false; switch(line->special) { case 1: // MANUAL DOOR RAISE case 32: // MANUAL BLUE case 33: // MANUAL RED case 34: // MANUAL YELLOW break; default: return false; break; } } // do something switch (line->special) { // MANUALS case 1: // Vertical Door case 26: // Blue Door/Locked case 27: // Yellow Door /Locked case 28: // Red Door /Locked case 31: // Manual door open case 32: // Blue locked door open case 33: // Red locked door open case 34: // Yellow locked door open case 117: // Blazing door raise case 118: // Blazing door open EV_VerticalDoor (line, thing); break; //UNUSED - Door Slide Open&Close // case 124: // EV_SlidingDoor (line, thing); // break; // SWITCHES case 7: // Build Stairs if (EV_BuildStairs(line,build8)) P_ChangeSwitchTexture(line,0); break; case 9: // Change Donut if (EV_DoDonut(line)) P_ChangeSwitchTexture(line,0); break; case 11: // Exit level P_ChangeSwitchTexture(line,0); G_ExitLevel (); break; case 14: // Raise Floor 32 and change texture if (EV_DoPlat(line,raiseAndChange,32)) P_ChangeSwitchTexture(line,0); break; case 15: // Raise Floor 24 and change texture if (EV_DoPlat(line,raiseAndChange,24)) P_ChangeSwitchTexture(line,0); break; case 18: // Raise Floor to next highest floor if (EV_DoFloor(line, raiseFloorToNearest)) P_ChangeSwitchTexture(line,0); break; case 20: // Raise Plat next highest floor and change texture if (EV_DoPlat(line,raiseToNearestAndChange,0)) P_ChangeSwitchTexture(line,0); break; case 21: // PlatDownWaitUpStay if (EV_DoPlat(line,downWaitUpStay,0)) P_ChangeSwitchTexture(line,0); break; case 23: // Lower Floor to Lowest if (EV_DoFloor(line,lowerFloorToLowest)) P_ChangeSwitchTexture(line,0); break; case 29: // Raise Door if (EV_DoDoor(line,normal)) P_ChangeSwitchTexture(line,0); break; case 41: // Lower Ceiling to Floor if (EV_DoCeiling(line,lowerToFloor)) P_ChangeSwitchTexture(line,0); break; case 71: // Turbo Lower Floor if (EV_DoFloor(line,turboLower)) P_ChangeSwitchTexture(line,0); break; case 49: // Ceiling Crush And Raise if (EV_DoCeiling(line,crushAndRaise)) P_ChangeSwitchTexture(line,0); break; case 50: // Close Door if (EV_DoDoor(line,closeDoor)) P_ChangeSwitchTexture(line,0); break; case 51: // Secret EXIT P_ChangeSwitchTexture(line,0); G_SecretExitLevel (); break; case 55: // Raise Floor Crush if (EV_DoFloor(line,raiseFloorCrush)) P_ChangeSwitchTexture(line,0); break; case 101: // Raise Floor if (EV_DoFloor(line,raiseFloor)) P_ChangeSwitchTexture(line,0); break; case 102: // Lower Floor to Surrounding floor height if (EV_DoFloor(line,lowerFloor)) P_ChangeSwitchTexture(line,0); break; case 103: // Open Door if (EV_DoDoor(line,openDoor)) P_ChangeSwitchTexture(line,0); break; case 111: // Blazing Door Raise (faster than TURBO!) if (EV_DoDoor (line,blazeRaise)) P_ChangeSwitchTexture(line,0); break; case 112: // Blazing Door Open (faster than TURBO!) if (EV_DoDoor (line,blazeOpen)) P_ChangeSwitchTexture(line,0); break; case 113: // Blazing Door Close (faster than TURBO!) if (EV_DoDoor (line,blazeClose)) P_ChangeSwitchTexture(line,0); break; case 122: // Blazing PlatDownWaitUpStay if (EV_DoPlat(line,blazeDWUS,0)) P_ChangeSwitchTexture(line,0); break; case 127: // Build Stairs Turbo 16 if (EV_BuildStairs(line,turbo16)) P_ChangeSwitchTexture(line,0); break; case 131: // Raise Floor Turbo if (EV_DoFloor(line,raiseFloorTurbo)) P_ChangeSwitchTexture(line,0); break; case 133: // BlzOpenDoor BLUE case 135: // BlzOpenDoor RED case 137: // BlzOpenDoor YELLOW if (EV_DoLockedDoor (line,blazeOpen,thing)) P_ChangeSwitchTexture(line,0); break; case 140: // Raise Floor 512 if (EV_DoFloor(line,raiseFloor512)) P_ChangeSwitchTexture(line,0); break; // BUTTONS case 42: // Close Door if (EV_DoDoor(line,closeDoor)) P_ChangeSwitchTexture(line,1); break; case 43: // Lower Ceiling to Floor if (EV_DoCeiling(line,lowerToFloor)) P_ChangeSwitchTexture(line,1); break; case 45: // Lower Floor to Surrounding floor height if (EV_DoFloor(line,lowerFloor)) P_ChangeSwitchTexture(line,1); break; case 60: // Lower Floor to Lowest if (EV_DoFloor(line,lowerFloorToLowest)) P_ChangeSwitchTexture(line,1); break; case 61: // Open Door if (EV_DoDoor(line,openDoor)) P_ChangeSwitchTexture(line,1); break; case 62: // PlatDownWaitUpStay if (EV_DoPlat(line,downWaitUpStay,1)) P_ChangeSwitchTexture(line,1); break; case 63: // Raise Door if (EV_DoDoor(line,normal)) P_ChangeSwitchTexture(line,1); break; case 64: // Raise Floor to ceiling if (EV_DoFloor(line,raiseFloor)) P_ChangeSwitchTexture(line,1); break; case 66: // Raise Floor 24 and change texture if (EV_DoPlat(line,raiseAndChange,24)) P_ChangeSwitchTexture(line,1); break; case 67: // Raise Floor 32 and change texture if (EV_DoPlat(line,raiseAndChange,32)) P_ChangeSwitchTexture(line,1); break; case 65: // Raise Floor Crush if (EV_DoFloor(line,raiseFloorCrush)) P_ChangeSwitchTexture(line,1); break; case 68: // Raise Plat to next highest floor and change texture if (EV_DoPlat(line,raiseToNearestAndChange,0)) P_ChangeSwitchTexture(line,1); break; case 69: // Raise Floor to next highest floor if (EV_DoFloor(line, raiseFloorToNearest)) P_ChangeSwitchTexture(line,1); break; case 70: // Turbo Lower Floor if (EV_DoFloor(line,turboLower)) P_ChangeSwitchTexture(line,1); break; case 114: // Blazing Door Raise (faster than TURBO!) if (EV_DoDoor (line,blazeRaise)) P_ChangeSwitchTexture(line,1); break; case 115: // Blazing Door Open (faster than TURBO!) if (EV_DoDoor (line,blazeOpen)) P_ChangeSwitchTexture(line,1); break; case 116: // Blazing Door Close (faster than TURBO!) if (EV_DoDoor (line,blazeClose)) P_ChangeSwitchTexture(line,1); break; case 123: // Blazing PlatDownWaitUpStay if (EV_DoPlat(line,blazeDWUS,0)) P_ChangeSwitchTexture(line,1); break; case 132: // Raise Floor Turbo if (EV_DoFloor(line,raiseFloorTurbo)) P_ChangeSwitchTexture(line,1); break; case 99: // BlzOpenDoor BLUE case 134: // BlzOpenDoor RED case 136: // BlzOpenDoor YELLOW if (EV_DoLockedDoor (line,blazeOpen,thing)) P_ChangeSwitchTexture(line,1); break; case 138: // Light Turn On EV_LightTurnOn(line,255); P_ChangeSwitchTexture(line,1); break; case 139: // Light Turn Off EV_LightTurnOn(line,35); P_ChangeSwitchTexture(line,1); break; } return true; }
1
0.965609
1
0.965609
game-dev
MEDIA
0.806918
game-dev,embedded-firmware
0.958706
1
0.958706
LagoLunatic/dsvrandom
1,238
randomizers/cosmetic/bgm_randomizer.rb
module BgmRandomizer def randomize_bgm remaining_song_indexes = BGM_RANDO_AVAILABLE_SONG_INDEXES.dup remaining_song_indexes.shuffle!(random: rng) if GAME == "por" (0..15).each do |bgm_index| new_song_index = remaining_song_indexes.pop() game.write_song_index_by_bgm_index(new_song_index, bgm_index) end else SECTOR_INDEX_TO_SECTOR_NAME[0].keys.each do |sector_index| if GAME == "dos" && [0x0A, 0x0C, 0x0D, 0x0E, 0x0F].include?(sector_index) # Skip the sectors that don't use the BGM we set (Menace, Prologue, Epilogue, Boss Rush, Enemy Set Mode). next end if GAME == "por" && [0x0C].include?(sector_index) # Skip the room with Dracula dying in the sunlight since it doesn't use the BGM we set. next end new_song_index = remaining_song_indexes.pop() game.write_song_index_by_area_and_sector(new_song_index, 0, sector_index) end AREA_INDEX_TO_AREA_NAME.keys.each do |area_index| next if area_index == 0 new_song_index = remaining_song_indexes.pop() game.write_song_index_by_area_and_sector(new_song_index, area_index, 0) end end end end
1
0.582796
1
0.582796
game-dev
MEDIA
0.663963
game-dev
0.762486
1
0.762486
PMC-Unga-Marines/Unga-Marines
27,187
code/game/objects/structures/stool_bed_chair_nest/bed.dm
/obj/structure/bed name = "bed" desc = "A mattress seated on a rectangular metallic frame. This is used to support a lying person in a comfortable manner, notably for regular sleep. Ancient technology, but still useful." icon_state = "bed" icon = 'icons/obj/objects.dmi' buckle_flags = CAN_BUCKLE|BUCKLE_PREVENTS_PULL buckle_lying = 90 allow_pass_flags = PASS_LOW_STRUCTURE|PASSABLE resistance_flags = XENO_DAMAGEABLE max_integrity = 40 resistance_flags = XENO_DAMAGEABLE hit_sound = 'sound/effects/metalhit.ogg' coverage = 10 var/dropmetal = TRUE var/buildstacktype = /obj/item/stack/sheet/metal var/buildstackamount = 1 /// To fold into an item (e.g. roller bed item) var/foldabletype /// pixel x shift to give to the buckled mob var/buckling_x = 0 ///pixel y shift to give to the buckled mob. This stacks with the lying down pixel shift when relevant var/buckling_y = -2 var/obj/structure/closet/bodybag/buckled_bodybag /// Whether you can buckle bodybags to this bed var/accepts_bodybag = FALSE /// Used by beds that change sprite when something is buckled to them var/base_bed_icon /obj/structure/bed/nometal dropmetal = FALSE /obj/structure/bed/bunkbed name = "bunk bed" icon_state = "bunkbed" /obj/structure/bed/update_icon_state() . = ..() if(!base_bed_icon) return if(LAZYLEN(buckled_mobs) || buckled_bodybag) icon_state = "[base_bed_icon]_up" else icon_state = "[base_bed_icon]_down" /obj/structure/bed/Destroy() if(buckled_bodybag) unbuckle_bodybag() return ..() /obj/structure/bed/deconstruct(disassembled, mob/living/blame_mob) if(buildstacktype && dropmetal) new buildstacktype(loc, buildstackamount) return ..() /obj/structure/bed/post_buckle_mob(mob/buckling_mob) . = ..() buckling_mob.pixel_y = buckling_y buckling_mob.pixel_x = buckling_x if(base_bed_icon) density = TRUE update_icon() /obj/structure/bed/post_unbuckle_mob(mob/buckled_mob) . = ..() buckled_mob.pixel_y = initial(buckled_mob.pixel_y) buckled_mob.pixel_x = initial(buckled_mob.pixel_x) if(base_bed_icon) density = FALSE update_icon() if(isliving(buckled_mob)) //Properly update whether we're lying or not var/mob/living/unbuckled_target = buckled_mob if(HAS_TRAIT(unbuckled_target, TRAIT_FLOORED)) unbuckled_target.set_lying_angle(pick(90, 270)) /obj/structure/bed/set_glide_size(target = 8) . = ..() buckled_bodybag?.set_glide_size(target) //Unsafe proc /obj/structure/bed/proc/buckle_bodybag(obj/structure/closet/bodybag/B, mob/user) if(buckled_bodybag || buckled) return B.visible_message(span_notice("[user] buckles [B] to [src]!")) B.roller_buckled = src B.glide_modifier_flags |= GLIDE_MOD_BUCKLED B.loc = loc B.setDir(dir) B.layer = layer + 0.1 buckled_bodybag = B density = TRUE update_icon() if(buckling_y) buckled_bodybag.pixel_y = buckling_y if(B.pulledby) B.pulledby.stop_pulling() if(pulledby) B.set_glide_size(pulledby.glide_size) /obj/structure/bed/proc/unbuckle_bodybag(mob/user) if(!buckled_bodybag) return buckled_bodybag.layer = initial(buckled_bodybag.layer) buckled_bodybag.pixel_y = initial(buckled_bodybag.pixel_y) buckled_bodybag.roller_buckled = null buckled_bodybag.glide_modifier_flags &= ~GLIDE_MOD_BUCKLED buckled_bodybag.reset_glide_size() buckled_bodybag = null density = FALSE update_icon() //Trying to buckle a mob /obj/structure/bed/buckle_mob(mob/living/buckling_mob, force = FALSE, check_loc = TRUE, lying_buckle = FALSE, hands_needed = 0, target_hands_needed = 0, silent) if(buckled_bodybag) return FALSE return ..() /obj/structure/bed/Moved(atom/old_loc, movement_dir, forced, list/old_locs) . = ..() if(!buckled_bodybag || buckled_bodybag.Move(loc, movement_dir, glide_size)) return TRUE forceMove(buckled_bodybag.loc) return FALSE /obj/structure/bed/roller/CanAllowThrough(atom/movable/mover, turf/target) if(mover == buckled_bodybag) return TRUE return ..() /obj/structure/bed/MouseDrop_T(atom/dropping, mob/user) if(accepts_bodybag && !buckled_bodybag && !LAZYLEN(buckled_mobs) && istype(dropping,/obj/structure/closet/bodybag) && ishuman(user)) var/obj/structure/closet/bodybag/B = dropping if(!B.roller_buckled && !B.anchored) buckle_bodybag(B, user) return TRUE else return ..() /obj/structure/bed/MouseDrop(atom/over_object) . = ..() if(foldabletype && !LAZYLEN(buckled_mobs) && !buckled_bodybag) if(ishuman(over_object)) var/mob/living/carbon/human/H = over_object if(H == usr && !H.incapacitated() && Adjacent(H) && in_range(src, over_object)) var/obj/item/I = new foldabletype(get_turf(src)) H.put_in_hands(I) if(istype(I,/obj/item/roller/medevac)) //We need to preserve key variables like linked beacons and cooldowns. var/obj/item/roller/medevac/M = I var/obj/structure/bed/medevac_stretcher/B = src if(B.last_teleport) M.last_teleport = B.last_teleport if(world.time < M.last_teleport) START_PROCESSING(SSprocessing, M) M.update_icon() if(B.linked_beacon) B.linked_beacon.add_stretcher(M, null, TRUE) B.linked_beacon.remove_stretcher(src, null, TRUE) qdel(src) /obj/structure/bed/wrench_act(mob/living/user, obj/item/I) if(!buildstacktype) return playsound(loc, 'sound/items/ratchet.ogg', 25, 1) if(dropmetal) new buildstacktype(loc, buildstackamount) qdel(src) /obj/structure/bed/grab_interact(obj/item/grab/grab, mob/user, base_damage = 5, is_sharp = FALSE) . = ..() if(.) return if(LAZYLEN(buckled_mobs) || buckled_bodybag) return if(!ismob(grab.grabbed_thing)) return var/mob/grabbed_mob = grab.grabbed_thing to_chat(user, span_notice("You place [grabbed_mob] on [src].")) grabbed_mob.forceMove(loc) return TRUE /obj/structure/bed/pre_crush_act(mob/living/carbon/xenomorph/charger, datum/action/ability/xeno_action/ready_charge/charge_datum) . = ..() if(!.) return if(buckled_bodybag) unbuckle_bodybag() /obj/structure/bed/alien icon_state = "abed" /obj/structure/bed/fancy name = "fancy bed" desc = "For prime comfort." /obj/structure/bed/pred icon = 'icons/obj/machines/yautja_machines.dmi' icon_state = "bed" /obj/structure/bed/pred/alt icon_state = "abed" /* * Roller beds */ /obj/structure/bed/roller name = "roller bed" desc = "A basic cushioned leather board resting on a small frame. Not very comfortable at all, but allows the patient to rest lying down while moved to another location rapidly." icon = 'icons/obj/rollerbed.dmi' icon_state = "roller_down" anchored = FALSE buckle_flags = CAN_BUCKLE drag_delay = 0 //Pulling something on wheels is easy buckling_y = 3 foldabletype = /obj/item/roller accepts_bodybag = TRUE base_bed_icon = "roller" /obj/item/roller name = "roller bed" desc = "A collapsed roller bed that can be carried around." icon = 'icons/obj/rollerbed.dmi' icon_state = "folded" w_class = WEIGHT_CLASS_SMALL drag_delay = 1 /// Pulling something on wheels is easy var/rollertype = /obj/structure/bed/roller /obj/item/roller/attack_self(mob/user) deploy_roller(user, user.loc) /obj/item/roller/afterattack(atom/target, mob/user, proximity) if(!proximity || !isturf(target) || target.density) return var/turf/target_turf = target for(var/atom/atom_to_check AS in target_turf) if(atom_to_check.density) return deploy_roller(user, target_turf) /obj/item/roller/attackby(obj/item/I, mob/user, params) . = ..() if(.) return if(istype(I, /obj/item/roller_holder) && rollertype == /obj/structure/bed/roller) var/obj/item/roller_holder/RH = I if(RH.held) return to_chat(user, span_notice("You pick up [src].")) forceMove(RH) RH.held = src /obj/item/roller/proc/deploy_roller(mob/user, atom/location) var/obj/structure/bed/roller/R = new rollertype(location) user.temporarilyRemoveItemFromInventory(src) if(istype(R,/obj/structure/bed/medevac_stretcher)) //We need to preserve key variables like linked beacons and cooldowns. var/obj/item/roller/medevac/I = src var/obj/structure/bed/medevac_stretcher/B = R if(I.last_teleport) B.last_teleport = I.last_teleport if(I.linked_beacon) I.linked_beacon.add_stretcher(B, null, TRUE) I.linked_beacon.remove_stretcher(I, null, TRUE) qdel(src) /obj/item/roller_holder name = "roller bed rack" desc = "A rack for carrying a collapsed roller bed." icon = 'icons/obj/rollerbed.dmi' icon_state = "folded" var/obj/item/roller/held /obj/item/roller_holder/Initialize(mapload) . = ..() held = new(src) /obj/item/roller_holder/attack_self(mob/user as mob) if(!held) to_chat(user, span_warning("The rack is empty.")) return var/obj/structure/bed/roller/R = new(user.loc) to_chat(user, span_notice("You deploy [R].")) qdel(held) held = null //////////////////////////////////////////// //MEDEVAC STRETCHER ////////////////////////////////////////////// //List of all activated medevac stretchers GLOBAL_LIST_EMPTY(activated_medevac_stretchers) /obj/structure/bed/medevac_stretcher name = "medevac stretcher" desc = "A medevac stretcher with integrated beacon for rapid evacuation of an injured patient via dropship lift and an emergency bluespace teleporter for tele-evacuation to a linked beacon. Accepts patients and body bags." icon = 'icons/obj/rollerbed.dmi' icon_state = "stretcher_down" buckling_y = 0 buildstacktype = null foldabletype = /obj/item/roller/medevac base_bed_icon = "stretcher" accepts_bodybag = TRUE resistance_flags = NONE var/teleport_timer = null var/last_teleport = null var/obj/item/medevac_beacon/linked_beacon = null var/stretcher_activated var/obj/item/radio/headset/mainship/doc/radio ///A busy var to check if the strecher is already used to send someone to the beacon var/busy = FALSE /obj/structure/bed/medevac_stretcher/Initialize(mapload) . = ..() radio = new(src) /obj/structure/bed/medevac_stretcher/examine(mob/user) . = ..() . += span_warning("Right-click to activate. Unique action to activate on yourself.") /obj/structure/bed/medevac_stretcher/attack_alien(mob/living/carbon/xenomorph/xeno_attacker, damage_amount = xeno_attacker.xeno_caste.melee_damage, damage_type = BRUTE, damage_flag = MELEE, effects = TRUE, armor_penetration = 0, isrightclick = FALSE) if(xeno_attacker.status_flags & INCORPOREAL) return FALSE if(buckled_bodybag) unbuckle_bodybag() for(var/m in buckled_mobs) user_unbuckle_mob(m, xeno_attacker, TRUE) /obj/structure/bed/medevac_stretcher/attack_ghost(mob/dead/observer/user) . = ..() if(!linked_beacon?.loc) return user.forceMove(get_turf(linked_beacon)) /obj/structure/bed/medevac_stretcher/Destroy() QDEL_NULL(radio) if(linked_beacon) linked_beacon.remove_stretcher(src) return ..() /obj/structure/bed/medevac_stretcher/update_overlays() . = ..() if(stretcher_activated) . += image("beacon_active_[density ? "up":"down"]") if(LAZYLEN(buckled_mobs) || buckled_bodybag) . += image("icon_state"="stretcher_box","layer"=LYING_MOB_LAYER + 0.1) /obj/structure/bed/medevac_stretcher/attack_hand_alternate(mob/living/user) activate_medevac_teleport(user) /obj/structure/bed/medevac_stretcher/proc/activate_medevac_teleport(mob/user) if(!ishuman(user)) return if(busy) return if(!linked_beacon) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) to_chat(user, span_warning("[src]'s bluespace engine isn't linked to any medvac beacon.")) return if(user.faction != linked_beacon.faction) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) visible_message(span_warning("[src]'s safeties kick in before displacement as it fails to detect correct identification codes.")) return if(world.time < last_teleport ) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) to_chat(user, span_warning("[src]'s bluespace engine is still recharging; it will be ready in [round(last_teleport - world.time) * 0.1] seconds.")) return if(user in buckled_mobs) to_chat(user, span_warning("You can't reach the teleportation activation button while buckled to [src].")) return if(!linked_beacon.planted) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) to_chat(user, span_warning("[src]'s bluespace engine linked medvac beacon isn't planted and active!")) return if(!linked_beacon.check_power()) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) to_chat(user, span_warning("[src]'s bluespace engine linked medvac beacon is unpowered.")) return if(is_centcom_level(linked_beacon.z)) // No. No using teleportation to teleport to the adminzone. playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) to_chat(user, span_warning("[src]'s beacon is out of range!")) return user.visible_message(span_warning("[user] activates [src]'s bluespace engine, causing it to rev to life."), span_warning("You activate [src]'s bluespace engine, causing it to rev to life.")) playsound(loc,'sound/mecha/powerup.ogg', 25, FALSE) teleport_timer = addtimer(CALLBACK(src, PROC_REF(medevac_teleport), user), MEDEVAC_TELE_DELAY, TIMER_STOPPABLE|TIMER_UNIQUE) //Activate after 5 second delay. RegisterSignal(src, COMSIG_MOVABLE_UNBUCKLE, PROC_REF(on_mob_unbuckle)) busy = TRUE /obj/structure/bed/medevac_stretcher/proc/on_mob_unbuckle(datum/source, mob/living/buckled_mob, force = FALSE) SIGNAL_HANDLER busy = FALSE UnregisterSignal(src, COMSIG_MOVABLE_UNBUCKLE) deltimer(teleport_timer) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) visible_message(span_warning("[src]'s safeties kick in, no longer detecting a buckled user.")) /obj/structure/bed/medevac_stretcher/proc/medevac_teleport(mob/user) UnregisterSignal(src, COMSIG_MOVABLE_UNBUCKLE) busy = FALSE if(!linked_beacon || !linked_beacon.check_power() || !linked_beacon.planted) //Beacon has to be planted in a powered area. playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) visible_message(span_warning("[src]'s safeties kick in before displacement as it fails to detect a powered, linked, and planted medvac beacon.")) return var/mob/living/M if(LAZYLEN(buckled_mobs)) M = buckled_mobs[1] else if(buckled_bodybag) M = locate(/mob/living) in buckled_bodybag.contents else playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) visible_message(span_warning("[src]'s bluespace engine aborts displacement, being unable to detect an appropriate evacuee.")) return if(!M) //We need a mob to teleport or no deal playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) visible_message(span_warning("[src]'s bluespace engine aborts displacement, being unable to detect an appropriate evacuee.")) return if(M.faction != linked_beacon.faction) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) visible_message(span_warning("[src]'s safeties kick in before displacement as it fails to detect correct identification codes.")) return visible_message(span_notice("<b>[M] vanishes in a flash of sparks as [src]'s bluespace engine generates its displacement field.</b>")) if(buckled_bodybag) var/obj/structure/closet/bodybag/teleported_bodybag = buckled_bodybag unbuckle_bodybag() teleported_bodybag.forceMove(get_turf(linked_beacon)) else unbuckle_mob(M) M.forceMove(get_turf(linked_beacon)) //Pretty SFX var/datum/effect_system/spark_spread/spark_system spark_system = new /datum/effect_system/spark_spread() spark_system.set_up(5, 0, src) spark_system.attach(src) spark_system.start(src) playsound(loc,'sound/effects/phasein.ogg', 50, FALSE) var/datum/effect_system/spark_spread/spark_system2 spark_system2 = new /datum/effect_system/spark_spread() spark_system2.set_up(5, 0, linked_beacon) spark_system2.attach(linked_beacon) spark_system2.start(linked_beacon) playsound(linked_beacon.loc,'sound/effects/phasein.ogg', 50, FALSE) linked_beacon.medvac_alert(M) //We warn med channel about the mob, not what was teleported. last_teleport = world.time + MEDEVAC_COOLDOWN /obj/structure/bed/medevac_stretcher/attackby(obj/item/I, mob/user, params) . = ..() if(.) return if(istype(I, /obj/item/medevac_beacon)) var/obj/item/medevac_beacon/B = I B.add_stretcher(src, user) else if(istype(I, /obj/item/healthanalyzer)) //Allows us to use the analyzer on the occupant without taking him out. var/mob/living/occupant if(LAZYLEN(buckled_mobs)) occupant = buckled_mobs[1] else if(buckled_bodybag) occupant = locate(/mob/living) in buckled_bodybag.contents var/obj/item/healthanalyzer/J = I J.attack(occupant, user) /obj/structure/bed/medevac_stretcher/proc/medvac_alert(mob/M) playsound(loc, 'sound/machines/ping.ogg', 50, FALSE) radio.talk_into(src, "Patient [M] has been tele-vaced to medvac beacon at: [get_area(linked_beacon)]. Coordinates: (X: [linked_beacon.x], Y: [linked_beacon.y])", RADIO_CHANNEL_MEDICAL) /obj/structure/bed/medevac_stretcher/examine(mob/user) . = ..() var/list/details = list() if(linked_beacon) details += "It's linked to a beacon located at: [get_area(linked_beacon)]. Coordinates: (X: [linked_beacon.x], Y: [linked_beacon.y]).</br>" if(world.time < last_teleport) details += "Its bluespace engine is currently recharging. <b>The interface displays: [round(last_teleport - world.time) * 0.1] seconds until it has recharged.</b></br>" if(LAZYLEN(buckled_mobs)) details += "It contains [buckled_mobs[1]].</br>" else if(buckled_bodybag) var/mob/living/M = locate(/mob/living) in buckled_bodybag.contents details += "It contains [M].</br>" . += span_notice("[details.Join(" ")]") /obj/item/roller/medevac name = "medevac stretcher" desc = "A collapsed medevac stretcher that can be carried around. Can be used to instantly transport a marine to a linked beacon. Don't forget the beacon!" icon_state = "stretcher_folded" var/last_teleport = null var/obj/item/medevac_beacon/linked_beacon = null rollertype = /obj/structure/bed/medevac_stretcher ///Visual timer for the medevac cooldown var/timer_cooldown ///Who is currently holding onto the medevac roller? var/mob/holder /obj/item/roller/medevac/unique_action(mob/user) . = ..() deploy_roller(user, user.loc) var/obj/structure/bed/medevac_stretcher/stretcher = locate(/obj/structure/bed/medevac_stretcher) in user.loc stretcher.activate_medevac_teleport(user) stretcher.buckle_mob(user) return TRUE /obj/item/roller/medevac/Destroy() STOP_PROCESSING(SSprocessing, src) holder = null if(linked_beacon) linked_beacon.remove_stretcher(src) return ..() /obj/item/roller/medevac/process() timer_cooldown = max(last_teleport - world.time, 0) if(!timer_cooldown) if(holder) balloon_alert(holder, "Medevac charged!") playsound(loc,'sound/machines/ping.ogg', 10, FALSE) STOP_PROCESSING(SSprocessing, src) update_icon() /obj/item/roller/medevac/attack_self(mob/user) deploy_roller(user, user.loc) /obj/item/roller/medevac/attack_ghost(mob/dead/observer/user) . = ..() if(!linked_beacon?.loc) return user.forceMove(get_turf(linked_beacon)) /obj/item/roller/medevac/dropped(mob/user) . = ..() holder = null update_icon() /obj/item/roller/medevac/pickup(mob/user) . = ..() holder = user /obj/item/roller/medevac/examine(mob/user) . = ..() var/list/details = list() if(linked_beacon) details += "It's linked to a beacon located at: [get_area(linked_beacon)]. Coordinates: (X: [linked_beacon.x], Y: [linked_beacon.y]).</br>" if(world.time < last_teleport) details += "[span_warning("It's bluespace engine is currently recharging. The interface estimates: [round(last_teleport - world.time) * 0.1] seconds until it has recharged.")]</br>" . += span_notice("[details.Join(" ")]") /obj/item/roller/medevac/update_overlays() . = ..() var/display_timer_cooldown = CEILING((timer_cooldown) * 0.1, 1) if(isturf(loc) || !display_timer_cooldown) return var/mutable_appearance/desc = mutable_appearance('icons/misc/12x12.dmi') desc.maptext = MAPTEXT("[display_timer_cooldown]s") . += desc /obj/item/roller/medevac/attackby(obj/item/I, mob/user, params) . = ..() if(.) return if(istype(I, /obj/item/medevac_beacon)) var/obj/item/medevac_beacon/B = I B.add_stretcher(src, user) /obj/item/medevac_beacon name = "medevac beacon" desc = "A specialized teleportation beacon that links with a medvac stretcher; provides the target destination for the stretcher's displacement field. WARNING: Must be in a powered area to function." icon = 'icons/obj/items/beacon.dmi' icon_state = "med_beacon0" w_class = WEIGHT_CLASS_SMALL var/planted = FALSE var/locked = FALSE var/list/obj/item/roller/medevac/linked_beds = list() var/list/obj/structure/bed/medevac_stretcher/linked_beds_deployed = list() req_one_access = list(ACCESS_MARINE_MEDPREP, ACCESS_MARINE_LEADER, ACCESS_MARINE_MEDBAY) var/obj/item/radio/headset/mainship/doc/radio /obj/item/medevac_beacon/Initialize(mapload) . = ..() radio = new(src) /obj/item/medevac_beacon/Destroy() QDEL_NULL(radio) for(var/obj/item/roller/medevac/rollerbed in linked_beds) rollerbed.linked_beacon = null for(var/obj/structure/bed/medevac_stretcher/stretcherbed in linked_beds) stretcherbed.linked_beacon = null linked_beds = null linked_beds_deployed = null return ..() /obj/item/medevac_beacon/examine(mob/user) . = ..() var/list/details = list() if(!check_power()) details += "<b>It's currently unpowered.</b></br>" else details += "<b>It's currently powered.</b></br>" details += "It's currently linked to:</b></br>" if(!linked_beds && !linked_beds_deployed) details += "<b>No beds detected!</b></br>" else for(var/obj/structure/bed/medevac_stretcher/stretcherbed in linked_beds_deployed) var/turf/bed_turf = get_turf(stretcherbed) details += "[world.time < stretcherbed.last_teleport ? "\[[round((stretcherbed.last_teleport - world.time) * 0.1)]s\]" : "\[READY\]"] Deployed medevac stretcher at: X:[bed_turf.x], Y:[bed_turf.y] - \[[get_area(bed_turf)]\]</br>" for(var/obj/item/roller/medevac/rollerbed in linked_beds) var/turf/bed_turf = get_turf(rollerbed) details += "[world.time < rollerbed.last_teleport ? "\[[round((rollerbed.last_teleport - world.time) * 0.1)]s\]" : "\[READY\]"] Medevac roller at: X:[bed_turf.x], Y:[bed_turf.y] \[[get_area(bed_turf)]\]" for(var/mob/M in bed_turf.contents) if(M.contains(rollerbed)) details += "- \[<b>[M]</b>\]" details += "</br>" . += span_notice("[details.Join(" ")]") /obj/item/medevac_beacon/proc/medvac_alert(mob/M) playsound(loc, 'sound/machines/ping.ogg', 50, FALSE) radio.talk_into(src, "Patient [M] has been tele-vaced to medvac beacon at: [get_area(src)]. Coordinates: (X: [x], Y: [y])", RADIO_CHANNEL_MEDICAL) /obj/item/medevac_beacon/attack_self(mob/user) if(locked) to_chat(user, span_warning("[src]'s interface is locked! Only a Squad Leader, Corpsman, or Medical Officer can unlock it now.")) return user.drop_held_item() anchored = TRUE planted = TRUE to_chat(user, span_warning("You plant and activate [src].")) icon_state = "med_beacon1" playsound(loc,'sound/machines/ping.ogg', 25, FALSE) faction = user.faction /obj/item/medevac_beacon/attack_hand(mob/living/user) . = ..() if(.) return if(locked) to_chat(user, span_warning("[src]'s interface is locked! Only a Squad Leader, Corpsman, or Medical Officer can unlock it now.")) return if(planted) anchored = FALSE planted = FALSE to_chat(user, span_warning("You retrieve and deactivate [src].")) icon_state = "med_beacon0" playsound(loc,'sound/machines/click.ogg', 25, FALSE) /obj/item/medevac_beacon/attack_ghost(mob/dead/observer/user) . = ..() if(!linked_beds && !linked_beds_deployed) return var/list/obj/destinations = SANITIZE_LIST(linked_beds) + SANITIZE_LIST(linked_beds_deployed) var/obj/target if(length(linked_beds + linked_beds_deployed) > 1) var/list/medevac_assoc = list() for(var/obj/destination in destinations) var/turf/T = get_turf(destination) medevac_assoc["X:[T.x], Y:[T.y] - \[[get_area(destination)]\]"] = destination destinations = list() for(var/destination in medevac_assoc) destinations += destination var/input = tgui_input_list(user, "Choose a medevac to teleport to:", "Ghost Medevac teleport", destinations, null, 0) if(!input) return target = medevac_assoc[input] if(!input) return else target = destinations[1] if(!target || QDELETED(target) || !target.loc) return user.forceMove(get_turf(target)) /obj/item/medevac_beacon/attackby(obj/item/I, mob/user, params) //Corpsmen can lock their beacons. . = ..() if(.) return if(istype(I, /obj/item/card/id)) if(!allowed(user)) to_chat(user, span_warning("Access denied.")) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) return locked = !locked user.visible_message(span_notice("[user] [locked ? "locks" : "unlocks"] [src]'s interface."), span_notice("You [locked ? "lock" : "unlock"] [src]'s interface.")) else if(istype(I, /obj/item/roller/medevac)) if(locked) to_chat(user, span_warning("Access denied.")) playsound(loc,'sound/machines/buzz-two.ogg', 25, FALSE) return add_stretcher(I, user) /obj/item/medevac_beacon/proc/check_power() var/area/A = loc?.loc if(!A || !isarea(A)) return FALSE return(A.powered(1)) /// Adds a medevac roller or stretcher to the medevac beacon. Returns TRUE if the beacon is in the linked_beds* list and false if it is not in there. /obj/item/medevac_beacon/proc/add_stretcher(obj/target_bed, mob/user, silent = FALSE) var/obj/item/roller/medevac/rollerbed = target_bed if(istype(rollerbed, /obj/item/roller/medevac)) if(rollerbed in linked_beds) if(!silent) if(user) balloon_alert(user, "Already linked!") playsound(loc,'sound/machines/buzz-sigh.ogg', 25, FALSE) return TRUE if(rollerbed.linked_beacon) rollerbed.linked_beacon.remove_stretcher(rollerbed) linked_beds += rollerbed rollerbed.linked_beacon = src if(!silent) if(user) balloon_alert(user, "Linked!") playsound(loc,'sound/machines/ping.ogg', 25, FALSE) return TRUE var/obj/structure/bed/medevac_stretcher/stretcherbed = target_bed if(istype(stretcherbed, /obj/structure/bed/medevac_stretcher)) if(stretcherbed in linked_beds_deployed) if(!silent) if(user) balloon_alert(user, "Already linked!") playsound(loc,'sound/machines/buzz-sigh.ogg', 25, FALSE) return TRUE if(stretcherbed.linked_beacon) stretcherbed.linked_beacon.remove_stretcher(stretcherbed) linked_beds_deployed += stretcherbed stretcherbed.linked_beacon = src if(!silent) if(user) balloon_alert(user, "Linked!") playsound(loc,'sound/machines/ping.ogg', 25, FALSE) return TRUE return FALSE /// Removes the stretcher from the linked_beds* list. Returns TRUE if the bed is not linked to the beacon and FALSE otherwise. /obj/item/medevac_beacon/proc/remove_stretcher(obj/target_bed) var/obj/item/roller/medevac/rollerbed = target_bed if(rollerbed && (rollerbed in linked_beds) && rollerbed.linked_beacon == src) rollerbed.linked_beacon = null linked_beds -= rollerbed return TRUE var/obj/structure/bed/medevac_stretcher/stretcherbed = target_bed if(stretcherbed && (stretcherbed in linked_beds_deployed) && stretcherbed.linked_beacon == src) stretcherbed.linked_beacon = null linked_beds_deployed -= stretcherbed return TRUE return FALSE
1
0.991489
1
0.991489
game-dev
MEDIA
0.956345
game-dev
0.992765
1
0.992765
NethermindEth/nethermind
4,142
src/Nethermind/Nethermind.Evm/ReleaseSpecExtensions.cs
// SPDX-FileCopyrightText: 2025 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only using System; using Nethermind.Core; using Nethermind.Core.Specs; namespace Nethermind.Evm { public static class ReleaseSpecExtensions { public static long GetClearReversalRefund(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? RefundOf.SResetReversedHotCold : spec.UseIstanbulNetGasMetering ? RefundOf.SResetReversedEip2200 : spec.UseConstantinopleNetGasMetering ? RefundOf.SResetReversedEip1283 : throw new InvalidOperationException("Asking about the net metered cost when net metering not enabled"); public static long GetSetReversalRefund(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? RefundOf.SSetReversedHotCold : spec.UseIstanbulNetGasMetering ? RefundOf.SSetReversedEip2200 : spec.UseConstantinopleNetGasMetering ? RefundOf.SSetReversedEip1283 : throw new InvalidOperationException("Asking about the net metered cost when net metering not enabled"); public static long GetSStoreResetCost(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? GasCostOf.SReset - GasCostOf.ColdSLoad : GasCostOf.SReset; public static long GetNetMeteredSStoreCost(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? GasCostOf.WarmStateRead : spec.UseIstanbulNetGasMetering ? GasCostOf.SStoreNetMeteredEip2200 : spec.UseConstantinopleNetGasMetering ? GasCostOf.SStoreNetMeteredEip1283 : throw new InvalidOperationException("Asking about the net metered cost when net metering not enabled"); public static long GetBalanceCost(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? 0L : spec.UseLargeStateDDosProtection ? GasCostOf.BalanceEip1884 : spec.UseShanghaiDDosProtection ? GasCostOf.BalanceEip150 : GasCostOf.Balance; public static long GetSLoadCost(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? 0L : spec.UseLargeStateDDosProtection ? GasCostOf.SLoadEip1884 : spec.UseShanghaiDDosProtection ? GasCostOf.SLoadEip150 : GasCostOf.SLoad; public static long GetExtCodeHashCost(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? 0L : spec.UseLargeStateDDosProtection ? GasCostOf.ExtCodeHashEip1884 : GasCostOf.ExtCodeHash; public static long GetExtCodeCost(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? 0L : spec.UseShanghaiDDosProtection ? GasCostOf.ExtCodeEip150 : GasCostOf.ExtCode; public static long GetCallCost(this IReleaseSpec spec) => spec.UseHotAndColdStorage ? 0L : spec.UseShanghaiDDosProtection ? GasCostOf.CallEip150 : GasCostOf.Call; public static long GetExpByteCost(this IReleaseSpec spec) => spec.UseExpDDosProtection ? GasCostOf.ExpByteEip160 : GasCostOf.ExpByte; public static ulong GetMaxBlobGasPerBlock(this IReleaseSpec spec) => spec.MaxBlobCount * Eip4844Constants.GasPerBlob; public static ulong GetMaxBlobGasPerTx(this IReleaseSpec spec) => spec.MaxBlobsPerTx * Eip4844Constants.GasPerBlob; public static ulong GetTargetBlobGasPerBlock(this IReleaseSpec spec) => spec.TargetBlobCount * Eip4844Constants.GasPerBlob; } }
1
0.795231
1
0.795231
game-dev
MEDIA
0.391886
game-dev
0.800117
1
0.800117
Odonno/ReduxSimple
2,753
ReduxSimple/StateLens.Explicit.cs
using Converto; namespace ReduxSimple; internal class ExplicitStateLens<TState, TFeatureState> : BaseStateLens<TState, TFeatureState> where TState : class, new() where TFeatureState : class, new() { private readonly Func<TState, TFeatureState> _featureSelector; private readonly Func<TState, TFeatureState, TState> _stateReducer; public ExplicitStateLens( Func<TState, TFeatureState> featureSelector, Func<TState, TFeatureState, TState> stateReducer ) { _featureSelector = featureSelector; _stateReducer = stateReducer; } public override On<TState> CreateParentReducer(On<TFeatureState> on) { return new On<TState> { Reduce = (state, action) => { if (on?.Reduce == null) return state; var featureState = _featureSelector(state); var reducerResult = on.Reduce(featureState, action); if (featureState.IsDeepEqual(reducerResult)) return state; return _stateReducer(state, reducerResult); }, Types = on.Types }; } } internal class ExplicitStateLens<TState, TAction, TFeatureState> : BaseStateLens<TState, TFeatureState> where TState : class, new() where TFeatureState : class, new() { private readonly Func<TState, TAction, TFeatureState> _featureSelector; private readonly Func<TState, TAction, TFeatureState, TState> _stateReducer; public ExplicitStateLens( Func<TState, TAction, TFeatureState> featureSelector, Func<TState, TAction, TFeatureState, TState> stateReducer ) { _featureSelector = featureSelector; _stateReducer = stateReducer; } public override On<TState> CreateParentReducer(On<TFeatureState> on) { return new On<TState> { Reduce = (state, action) => { if (on?.Reduce == null) return state; if (action is TAction typedAction) { var featureState = _featureSelector(state, typedAction); var reducerResult = on.Reduce(featureState, action); if (featureState.IsDeepEqual(reducerResult)) return state; return _stateReducer(state, typedAction, reducerResult); } throw new NotSupportedException( $"This type `{typeof(TAction).Name}` of action cannot be used in the reducer reducer of `{typeof(TFeatureState).Name}` inside `{typeof(TState).Name}`." ); }, Types = on.Types }; } }
1
0.831943
1
0.831943
game-dev
MEDIA
0.583141
game-dev
0.664766
1
0.664766
quiverteam/Engine
2,523
src/movieobjects/dmemouseinput.cpp
//====== Copyright 1996-2004, Valve Corporation, All rights reserved. ======= // // Purpose: // //============================================================================= #include "movieobjects/dmemouseinput.h" #include "movieobjects_interfaces.h" #include "datamodel/dmelementfactoryhelper.h" #include "vgui/iinput.h" #include "vgui/ipanel.h" #include "tier3/tier3.h" #include "tier0/dbg.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Expose this class to the scene database //----------------------------------------------------------------------------- IMPLEMENT_ELEMENT_FACTORY( DmeMouseInput, CDmeMouseInput ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDmeMouseInput::OnConstruction() { m_x.Init( this, "x" ); m_y.Init( this, "y" ); m_xOrigin = 0.0f; m_yOrigin = 0.0f; } void CDmeMouseInput::OnDestruction() { } //----------------------------------------------------------------------------- // IsDirty - ie needs to operate //----------------------------------------------------------------------------- bool CDmeMouseInput::IsDirty() { float flX, flY; GetNormalizedCursorPos( flX, flY ); flX -= m_xOrigin; flY -= m_yOrigin; return ( flX != GetValue< float >( "x" ) ) || ( flY != GetValue< float >( "y" ) ); } void CDmeMouseInput::Operate() { float flX, flY; GetNormalizedCursorPos( flX, flY ); SetValue( "x", flX - m_xOrigin ); SetValue( "y", flY - m_yOrigin ); // Msg( "CDmeMouseInput::Operate() at <%f, %f>\n", flX, flY ); } void CDmeMouseInput::GetInputAttributes( CUtlVector< CDmAttribute * > &attrs ) { } void CDmeMouseInput::GetOutputAttributes( CUtlVector< CDmAttribute * > &attrs ) { attrs.AddToTail( GetAttribute( "x" ) ); attrs.AddToTail( GetAttribute( "y" ) ); } void CDmeMouseInput::ResetOrigin( float dx, float dy ) { GetNormalizedCursorPos( m_xOrigin, m_yOrigin ); m_xOrigin += dx; m_yOrigin += dy; } void CDmeMouseInput::GetNormalizedCursorPos( float &flX, float &flY ) { int x, y; g_pVGuiInput->GetCursorPos( x, y ); vgui::VPANEL vpanel = g_pVGuiInput->GetFocus(); if ( !vpanel ) { flX = flY = 0.0f; return; } int x0, y0; g_pVGuiPanel->GetPos( vpanel, x0, y0 ); int w, h; g_pVGuiPanel->GetSize( vpanel, w, h ); flX = ( x - x0 ) / float(w); flY = ( y - y0 ) / float(h); }
1
0.714436
1
0.714436
game-dev
MEDIA
0.698807
game-dev
0.706913
1
0.706913
mono/roslyn
8,535
src/Compilers/VisualBasic/Portable/Symbols/Source/SourceClonedParameterSymbol.vb
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a source parameter cloned from another <see cref="SourceParameterSymbol"/> , ''' when they must share attribute data. ''' </summary> ''' <remarks> ''' For example, parameters on delegate Invoke method are cloned to delegate BeginInvoke, EndInvoke methods. ''' </remarks> Friend Class SourceClonedParameterSymbol Inherits SourceParameterSymbolBase Private ReadOnly m_originalParam As SourceParameterSymbol Friend Sub New(originalParam As SourceParameterSymbol, newOwner As MethodSymbol, newOrdinal As Integer) MyBase.New(newOwner, newOrdinal) Debug.Assert(originalParam IsNot Nothing) m_originalParam = originalParam End Sub Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get ' Since you can't get from the syntax node that represents the orginal parameter ' back to this symbol we decided not to return the original syntax node here. Return ImmutableArray(Of SyntaxReference).Empty End Get End Property #Region "Forwarded" Public Overrides ReadOnly Property Type As TypeSymbol Get Return m_originalParam.Type End Get End Property Friend Overrides ReadOnly Property IsMetadataIn As Boolean Get Return m_originalParam.IsMetadataIn End Get End Property Friend Overrides ReadOnly Property IsMetadataOut As Boolean Get Return m_originalParam.IsMetadataOut End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return m_originalParam.Locations End Get End Property Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return m_originalParam.GetAttributes() End Function Public Overrides ReadOnly Property Name As String Get Return m_originalParam.Name End Get End Property Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return m_originalParam.CustomModifiers End Get End Property Friend Overrides ReadOnly Property HasByRefBeforeCustomModifiers As Boolean Get Return m_originalParam.HasByRefBeforeCustomModifiers End Get End Property Friend Overloads Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return m_originalParam.ExplicitDefaultConstantValue(inProgress) End Get End Property Friend Overrides ReadOnly Property HasParamArrayAttribute As Boolean Get Return m_originalParam.HasParamArrayAttribute End Get End Property Friend Overrides ReadOnly Property HasDefaultValueAttribute As Boolean Get Return m_originalParam.HasDefaultValueAttribute End Get End Property Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return m_originalParam.HasExplicitDefaultValue End Get End Property Friend Overrides ReadOnly Property HasOptionCompare As Boolean Get Return m_originalParam.HasOptionCompare End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get Return m_originalParam.IsIDispatchConstant End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get Return m_originalParam.IsIUnknownConstant End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Return m_originalParam.IsCallerLineNumber End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Return m_originalParam.IsCallerMemberName End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Return m_originalParam.IsCallerFilePath End Get End Property Public Overrides ReadOnly Property IsByRef As Boolean Get Return m_originalParam.IsByRef End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return m_originalParam.IsExplicitByRef End Get End Property Public Overrides ReadOnly Property IsOptional As Boolean Get Return m_originalParam.IsOptional End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get Return m_originalParam.IsParamArray End Get End Property Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get Return m_originalParam.MarshallingInformation End Get End Property #End Region Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), hasByRefBeforeCustomModifiers As Boolean) As ParameterSymbol Return New SourceClonedParameterSymbolWithCustomModifiers(m_originalParam, DirectCast(Me.ContainingSymbol, MethodSymbol), Me.Ordinal, type, customModifiers, hasByRefBeforeCustomModifiers) End Function Friend NotInheritable Class SourceClonedParameterSymbolWithCustomModifiers Inherits SourceClonedParameterSymbol Private ReadOnly m_type As TypeSymbol Private ReadOnly m_customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly m_hasByRefBeforeCustomModifiers As Boolean Friend Sub New( originalParam As SourceParameterSymbol, newOwner As MethodSymbol, newOrdinal As Integer, type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), hasByRefBeforeCustomModifiers As Boolean ) MyBase.New(originalParam, newOwner, newOrdinal) m_type = type m_customModifiers = If(customModifiers.IsDefault, ImmutableArray(Of CustomModifier).Empty, customModifiers) m_hasByRefBeforeCustomModifiers = hasByRefBeforeCustomModifiers End Sub Public Overrides ReadOnly Property Type As TypeSymbol Get Return m_type End Get End Property Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return m_customModifiers End Get End Property Friend Overrides ReadOnly Property HasByRefBeforeCustomModifiers As Boolean Get Return m_hasByRefBeforeCustomModifiers End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), hasByRefBeforeCustomModifiers As Boolean) As ParameterSymbol Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
1
0.754497
1
0.754497
game-dev
MEDIA
0.242026
game-dev
0.688068
1
0.688068
BobbyAnguelov/Esoterica
41,874
Code/Engine/Entity/EntityMap.cpp
#include "EntityMap.h" #include "EntityLog.h" #include "EntityInitializationContext.h" #include "EntityLoadingContext.h" #include "EntityWorldSystem.h" #include "Entity.h" #include "Base/Resource/ResourceSystem.h" #include "Base/TypeSystem/TypeRegistry.h" #include "Base/Profiling.h" //------------------------------------------------------------------------- namespace EE::EntityModel { EntityMap::EntityMap() : m_entityUpdateEventBindingID( Entity::OnEntityInternalStateUpdated().Bind( [this] ( Entity* pEntity ) { OnEntityStateUpdated( pEntity ); } ) ) , m_isTransientMap( true ) {} EntityMap::EntityMap( ResourceID mapResourceID ) : m_pMapDesc( mapResourceID ) , m_entityUpdateEventBindingID( Entity::OnEntityInternalStateUpdated().Bind( [this] ( Entity* pEntity ) { OnEntityStateUpdated( pEntity ); } ) ) {} EntityMap::EntityMap( EntityMap const& map ) : m_entityUpdateEventBindingID( Entity::OnEntityInternalStateUpdated().Bind( [this] ( Entity* pEntity ) { OnEntityStateUpdated( pEntity ); } ) ) { operator=( map ); } EntityMap::EntityMap( EntityMap&& map ) : m_entityUpdateEventBindingID( Entity::OnEntityInternalStateUpdated().Bind( [this] ( Entity* pEntity ) { OnEntityStateUpdated( pEntity ); } ) ) { operator=( eastl::move( map ) ); } EntityMap::~EntityMap() { EE_ASSERT( IsUnloaded() ); EE_ASSERT( m_entities.empty() && m_entityIDLookupMap.empty() ); EE_ASSERT( m_entitiesToLoad.empty() && m_entitiesToRemove.empty() ); #if EE_DEVELOPMENT_TOOLS EE_ASSERT( m_entitiesToHotReload.empty() ); EE_ASSERT( m_editedEntities.empty() ); #endif Entity::OnEntityInternalStateUpdated().Unbind( m_entityUpdateEventBindingID ); } //------------------------------------------------------------------------- EntityMap& EntityMap::operator=( EntityMap const& map ) { // Only allow copy constructor for unloaded maps EE_ASSERT( m_status == Status::Unloaded && map.m_status == Status::Unloaded ); #if EE_DEVELOPMENT_TOOLS EE_ASSERT( map.m_entitiesToHotReload.empty() ); #endif m_pMapDesc = map.m_pMapDesc; const_cast<bool&>( m_isTransientMap ) = map.m_isTransientMap; return *this; } EntityMap& EntityMap::operator=( EntityMap&& map ) { #if EE_DEVELOPMENT_TOOLS EE_ASSERT( map.m_entitiesToHotReload.empty() ); #endif m_ID = map.m_ID; m_entities.swap( map.m_entities ); m_entityIDLookupMap.swap( map.m_entityIDLookupMap ); m_pMapDesc = eastl::move( map.m_pMapDesc ); m_entitiesCurrentlyLoading = eastl::move( map.m_entitiesCurrentlyLoading ); m_status = map.m_status; const_cast<bool&>( m_isTransientMap ) = map.m_isTransientMap; // Clear source map map.m_ID.Clear(); map.m_status = Status::Unloaded; return *this; } //------------------------------------------------------------------------- // Entity Management //------------------------------------------------------------------------- void EntityMap::AddEntities( TVector<Entity*> const& entities, Transform const& offsetTransform ) { Threading::RecursiveScopeLock lock( m_mutex ); m_entityIDLookupMap.reserve( m_entityIDLookupMap.size() + entities.size() ); #if EE_DEVELOPMENT_TOOLS m_entityNameLookupMap.reserve( m_entityNameLookupMap.size() + entities.size() ); #endif //------------------------------------------------------------------------- bool const applyOffset = !offsetTransform.IsIdentity(); for ( auto& pEntity : entities ) { // Shift entity by the specified offset if ( applyOffset && pEntity->IsSpatialEntity() ) { pEntity->SetWorldTransform( pEntity->GetWorldTransform() * offsetTransform ); } AddEntity( pEntity ); } } void EntityMap::AddEntity( Entity* pEntity ) { // Ensure that the entity to add, is not already part of a collection and that it is not initialized EE_ASSERT( pEntity != nullptr && !pEntity->IsAddedToMap() && !pEntity->HasRequestedComponentLoad() ); EE_ASSERT( !VectorContains( m_entitiesToLoad, pEntity ) ); // Entity validation //------------------------------------------------------------------------- // Ensure spatial parenting and unique name #if EE_DEVELOPMENT_TOOLS if ( pEntity->HasSpatialParent() ) { EE_ASSERT( ContainsEntity( pEntity->GetSpatialParent()->GetID() ) ); } pEntity->m_name = GenerateUniqueEntityNameID( pEntity->m_name ); #endif // Add entity //------------------------------------------------------------------------- Threading::RecursiveScopeLock lock( m_mutex ); pEntity->m_mapID = m_ID; m_entities.emplace_back( pEntity ); m_entitiesToLoad.emplace_back( pEntity ); // Add to lookup maps //------------------------------------------------------------------------- m_entityIDLookupMap.insert( TPair<EntityID, Entity*>( pEntity->m_ID, pEntity ) ); #if EE_DEVELOPMENT_TOOLS m_entityNameLookupMap.insert( TPair<StringID, Entity*>( pEntity->m_name, pEntity ) ); #endif } void EntityMap::AddEntityCollection( TaskSystem* pTaskSystem, TypeSystem::TypeRegistry const& typeRegistry, EntityCollection const& entityCollectionDesc, Transform const& offsetTransform, TVector<Entity*>* pOutCreatedEntities ) { TVector<Entity*> scratchVector; TVector<Entity*>& createdEntities = ( pOutCreatedEntities != nullptr ) ? *pOutCreatedEntities : scratchVector; //------------------------------------------------------------------------- createdEntities.clear(); createdEntities = entityCollectionDesc.CreateEntities( typeRegistry, pTaskSystem ); AddEntities( createdEntities, offsetTransform ); } Entity* EntityMap::RemoveEntityInternal( EntityID entityID, bool destroyEntityOnceRemoved ) { Threading::RecursiveScopeLock lock( m_mutex ); // Handle spatial hierarchy //------------------------------------------------------------------------- Entity* pEntityToRemove = FindEntity( entityID ); EE_ASSERT( pEntityToRemove != nullptr ); if ( !pEntityToRemove->m_attachedEntities.empty() ) { // If we have a parent, re-parent all children to it if ( pEntityToRemove->m_pParentSpatialEntity != nullptr ) { for ( auto pAttachedEntity : pEntityToRemove->m_attachedEntities ) { pAttachedEntity->SetSpatialParent( pEntityToRemove->m_pParentSpatialEntity ); } } else // If we have no parent, remove spatial parent { for ( auto pAttachedEntity : pEntityToRemove->m_attachedEntities ) { pAttachedEntity->ClearSpatialParent(); } } } // Remove from map //------------------------------------------------------------------------- m_entities.erase_first_unsorted( pEntityToRemove ); // Remove from internal lookup maps //------------------------------------------------------------------------- auto IDLookupIter = m_entityIDLookupMap.find( pEntityToRemove->m_ID ); EE_ASSERT( IDLookupIter != m_entityIDLookupMap.end() ); m_entityIDLookupMap.erase( IDLookupIter ); #if EE_DEVELOPMENT_TOOLS auto nameLookupIter = m_entityNameLookupMap.find( pEntityToRemove->m_name ); EE_ASSERT( nameLookupIter != m_entityNameLookupMap.end() ); m_entityNameLookupMap.erase( nameLookupIter ); #endif // Schedule unload //------------------------------------------------------------------------- // Check if the entity is in the add queue, if so just cancel the request int32_t const entityIdx = VectorFindIndex( m_entitiesToLoad, entityID, [] ( Entity* pEntity, EntityID entityID ) { return pEntity->GetID() == entityID; } ); if ( entityIdx != InvalidIndex ) { pEntityToRemove = m_entitiesToLoad[entityIdx]; m_entitiesToLoad.erase_unsorted( m_entitiesToLoad.begin() + entityIdx ); if ( destroyEntityOnceRemoved ) { EE::Delete( pEntityToRemove ); } } else // Queue removal { m_entitiesToRemove.emplace_back( RemovalRequest( pEntityToRemove, destroyEntityOnceRemoved ) ); } //------------------------------------------------------------------------- // Do not return anything if we are requesting destruction if ( destroyEntityOnceRemoved ) { pEntityToRemove = nullptr; } return pEntityToRemove; } Entity* EntityMap::RemoveEntity( EntityID entityID ) { Entity* pEntityToRemove = RemoveEntityInternal( entityID, false ); EE_ASSERT( pEntityToRemove != nullptr ); return pEntityToRemove; } void EntityMap::DestroyEntity( EntityID entityID ) { RemoveEntityInternal( entityID, true ); } void EntityMap::OnEntityStateUpdated( Entity* pEntity ) { if ( pEntity->GetMapID() == m_ID ) { EE_ASSERT( FindEntity( pEntity->GetID() ) ); Threading::RecursiveScopeLock lock( m_mutex ); if ( !VectorContains( m_entitiesCurrentlyLoading, pEntity ) ) { m_entitiesCurrentlyLoading.emplace_back( pEntity ); } } } //------------------------------------------------------------------------- // Loading //------------------------------------------------------------------------- void EntityMap::Load( LoadingContext const& loadingContext, InitializationContext& initializationContext ) { EE_ASSERT( Threading::IsMainThread() && loadingContext.IsValid() ); EE_ASSERT( m_status == Status::Unloaded ); Threading::RecursiveScopeLock lock( m_mutex ); if ( m_isTransientMap ) { m_status = Status::Loaded; } else // Request loading of map resource { loadingContext.m_pResourceSystem->LoadResource( m_pMapDesc ); m_status = Status::Loading; } } void EntityMap::ProcessMapLoading( LoadingContext const& loadingContext ) { EE_PROFILE_SCOPE_ENTITY( "Map Loading" ); EE_ASSERT( m_status == Status::Loading ); EE_ASSERT( !m_isTransientMap ); //------------------------------------------------------------------------- // Wait for the map descriptor to load if ( m_pMapDesc.IsUnloaded() || m_pMapDesc.IsLoading() ) { return; } //------------------------------------------------------------------------- // Check for load failure if ( m_pMapDesc.HasLoadingFailed() ) { m_status = Status::LoadFailed; loadingContext.m_pResourceSystem->UnloadResource( m_pMapDesc ); return; } //------------------------------------------------------------------------- // Instantiate the map if ( m_pMapDesc->IsValid() ) { // Create all required entities TVector<Entity*> const createdEntities = m_pMapDesc->CreateEntities( *loadingContext.m_pTypeRegistry, loadingContext.m_pTaskSystem ); // Reserve memory for new entities in internal structures m_entities.reserve( m_entities.size() + createdEntities.size() ); m_entitiesToLoad.reserve( m_entitiesToLoad.size() + createdEntities.size() ); m_entityIDLookupMap.reserve( m_entityIDLookupMap.size() + createdEntities.size() ); m_entitiesCurrentlyLoading.reserve( m_entitiesCurrentlyLoading.size() + createdEntities.size() ); #if EE_DEVELOPMENT_TOOLS m_entityNameLookupMap.reserve( m_entityNameLookupMap.size() + createdEntities.size() ); #endif // Add entities for ( auto pEntity : createdEntities ) { AddEntity( pEntity ); } m_status = Status::Loaded; } else // Invalid map data is treated as a failed load { m_status = Status::LoadFailed; } // Release map resource ptr once loading has completed loadingContext.m_pResourceSystem->UnloadResource( m_pMapDesc ); } void EntityMap::Unload( LoadingContext const& loadingContext, InitializationContext& initializationContext ) { EE_ASSERT( m_status != Status::Unloaded ); Threading::RecursiveScopeLock lock( m_mutex ); m_status = Status::Unloading; } void EntityMap::ProcessMapUnloading( LoadingContext const& loadingContext, InitializationContext& initializationContext ) { EE_PROFILE_SCOPE_ENTITY( "Map Unload" ); EE_ASSERT( m_status == Status::Unloading ); // Cancel any load requests //------------------------------------------------------------------------- m_entitiesCurrentlyLoading.clear(); m_entitiesToLoad.clear(); // Shutdown all entities //------------------------------------------------------------------------- // Shutdown all entities that have been requested for removal ProcessEntityShutdownRequests( initializationContext ); // Shutdown map entities { struct EntityShutdownTask : public ITaskSet { EntityShutdownTask( InitializationContext& initializationContext, TVector<Entity*>& entities ) : m_initializationContext( initializationContext ) , m_entitiesToShutdown( entities ) { m_SetSize = (uint32_t) m_entitiesToShutdown.size(); } virtual void ExecuteRange( TaskSetPartition range, uint32_t threadnum ) override final { EE_PROFILE_SCOPE_ENTITY( "Shutdown Entities" ); for ( uint64_t i = range.start; i < range.end; ++i ) { auto pEntity = m_entitiesToShutdown[i]; if ( pEntity->IsInitialized() ) { // Only shutdown non-spatial and root spatial entities. Attached entities will be shutdown by their parents if ( !pEntity->IsSpatialEntity() || !pEntity->HasSpatialParent() ) { pEntity->Shutdown( m_initializationContext ); } } } } private: InitializationContext& m_initializationContext; TVector<Entity*>& m_entitiesToShutdown; }; //------------------------------------------------------------------------- EntityShutdownTask shutdownTask( initializationContext, m_entities ); initializationContext.m_pTaskSystem->ScheduleTask( &shutdownTask ); initializationContext.m_pTaskSystem->WaitForTask( &shutdownTask ); } // Process all unregistration requests ProcessEntityRegistrationRequests( initializationContext ); // Unload and destroy entities //------------------------------------------------------------------------- // Unload all entities that have been requested for removal ProcessEntityRemovalRequests( loadingContext ); // Unload and destroy map entities for ( auto& pEntity : m_entities ) { EE_ASSERT( !pEntity->IsInitialized() ); if ( pEntity->IsLoaded() ) { pEntity->UnloadComponents( loadingContext ); } EE::Delete( pEntity ); } m_entities.clear(); m_entityIDLookupMap.clear(); #if EE_DEVELOPMENT_TOOLS m_entityNameLookupMap.clear(); #endif // Unload the map resource //------------------------------------------------------------------------- if ( !m_isTransientMap && m_pMapDesc.WasRequested() ) { loadingContext.m_pResourceSystem->UnloadResource( m_pMapDesc ); } m_status = Status::Unloaded; } //------------------------------------------------------------------------- void EntityMap::ProcessEntityShutdownRequests( InitializationContext& initializationContext ) { EE_PROFILE_SCOPE_ENTITY( "Entity Shutdown" ); // No point parallelizing this, since this should never have that many entries in it for ( int32_t i = (int32_t) m_entitiesToRemove.size() - 1; i >= 0; i-- ) { auto pEntityToShutdown = m_entitiesToRemove[i].m_pEntity; if ( pEntityToShutdown->IsInitialized() ) { pEntityToShutdown->Shutdown( initializationContext ); } } } void EntityMap::ProcessEntityRemovalRequests( LoadingContext const& loadingContext ) { EE_PROFILE_SCOPE_ENTITY( "Entity Removal" ); for ( int32_t i = (int32_t) m_entitiesToRemove.size() - 1; i >= 0; i-- ) { auto& removalRequest = m_entitiesToRemove[i]; auto pEntityToRemove = removalRequest.m_pEntity; EE_ASSERT( !pEntityToRemove->IsInitialized() ); // Remove from currently loading list m_entitiesCurrentlyLoading.erase_first_unsorted( pEntityToRemove ); // Unload entity pEntityToRemove->UnloadComponents( loadingContext ); pEntityToRemove->m_mapID.Clear(); // Destroy the entity if this is a destruction request if ( removalRequest.m_shouldDestroy ) { EE::Delete( pEntityToRemove ); } // Remove the request from the list m_entitiesToRemove.erase_unsorted( m_entitiesToRemove.begin() + i ); } } void EntityMap::ProcessEntityLoadingAndInitialization( LoadingContext const& loadingContext, InitializationContext& initializationContext ) { EE_PROFILE_SCOPE_ENTITY( "Entity Loading/Initialization" ); // Request load for unloaded entities // No point parallelizing this since the resource system locks a mutex for each load/unload call! for ( auto pEntityToAdd : m_entitiesToLoad ) { // Ensure that the entity to add, is not already part of a collection and that it's shutdown EE_ASSERT( pEntityToAdd != nullptr && pEntityToAdd->m_mapID == m_ID && !pEntityToAdd->IsInitialized() ); // Request component load pEntityToAdd->LoadComponents( loadingContext ); EE_ASSERT( !VectorContains( m_entitiesCurrentlyLoading, pEntityToAdd ) ); m_entitiesCurrentlyLoading.emplace_back( pEntityToAdd ); } m_entitiesToLoad.clear(); //------------------------------------------------------------------------- struct EntityLoadingTask : public ITaskSet { EntityLoadingTask( LoadingContext const& loadingContext, InitializationContext& initializationContext, TVector<Entity*>& entitiesToLoad ) : m_loadingContext( loadingContext ) , m_initializationContext( initializationContext ) , m_entitiesToLoad( entitiesToLoad ) { m_SetSize = (uint32_t) m_entitiesToLoad.size(); } virtual void ExecuteRange( TaskSetPartition range, uint32_t threadnum ) override final { EE_PROFILE_SCOPE_ENTITY( "Load and Initialize Entities" ); for ( uint32_t i = range.start; i < range.end; ++i ) { auto pEntity = m_entitiesToLoad[i]; if ( pEntity->UpdateEntityState( m_loadingContext, m_initializationContext ) ) { #if EE_DEVELOPMENT_TOOLS for ( auto pComponent : pEntity->GetComponents() ) { EE_ASSERT( pComponent->IsInitialized() || pComponent->HasLoadingFailed() ); } #endif // Initialize any entities that loaded successfully if ( pEntity->IsLoaded() ) { // Prevent us from initializing entities whose parents are not yet initialized, this ensures that our attachment chains have a consistent initialized state if ( pEntity->HasSpatialParent() ) { // We need to recheck the initialization state of this entity since while waiting for the lock, it could have been initialized by the parent Threading::RecursiveScopeLock parentLock( pEntity->GetSpatialParent()->m_internalStateMutex ); if ( !pEntity->IsInitialized() && pEntity->GetSpatialParent()->IsInitialized() ) { pEntity->Initialize( m_initializationContext ); } } else { pEntity->Initialize( m_initializationContext ); } } } else // Entity is still loading { bool result = m_stillLoadingEntities.enqueue( pEntity ); EE_ASSERT( result ); } } } public: Threading::LockFreeQueue<Entity*> m_stillLoadingEntities; private: LoadingContext const& m_loadingContext; InitializationContext& m_initializationContext; TVector<Entity*>& m_entitiesToLoad; }; //------------------------------------------------------------------------- if ( !m_entitiesCurrentlyLoading.empty() ) { EntityLoadingTask loadingTask( loadingContext, initializationContext, m_entitiesCurrentlyLoading ); loadingContext.m_pTaskSystem->ScheduleTask( &loadingTask ); loadingContext.m_pTaskSystem->WaitForTask( &loadingTask ); //------------------------------------------------------------------------- // Track the number of entities that still need loading size_t const numEntitiesStillLoading = loadingTask.m_stillLoadingEntities.size_approx(); m_entitiesCurrentlyLoading.resize( numEntitiesStillLoading ); size_t numDequeued = loadingTask.m_stillLoadingEntities.try_dequeue_bulk( m_entitiesCurrentlyLoading.data(), numEntitiesStillLoading ); EE_ASSERT( numEntitiesStillLoading == numDequeued ); } } //------------------------------------------------------------------------- void EntityMap::ProcessEntityRegistrationRequests( InitializationContext& initializationContext ) { EE_ASSERT( Threading::IsMainThread() ); //------------------------------------------------------------------------- // Entity Registrations //------------------------------------------------------------------------- { EE_PROFILE_SCOPE_ENTITY( "Entity Update Registration" ); Entity* pEntity = nullptr; while ( initializationContext.m_unregisterForEntityUpdate.try_dequeue( pEntity ) ) { EE_ASSERT( pEntity != nullptr && pEntity->m_updateRegistrationStatus == Entity::UpdateRegistrationStatus::QueuedForUnregister ); initializationContext.m_entityUpdateList.erase_first_unsorted( pEntity ); pEntity->m_updateRegistrationStatus = Entity::UpdateRegistrationStatus::Unregistered; } //------------------------------------------------------------------------- while ( initializationContext.m_registerForEntityUpdate.try_dequeue( pEntity ) ) { EE_ASSERT( pEntity != nullptr ); EE_ASSERT( pEntity->IsInitialized() ); EE_ASSERT( pEntity->m_updateRegistrationStatus == Entity::UpdateRegistrationStatus::QueuedForRegister ); EE_ASSERT( !pEntity->HasSpatialParent() ); // Attached entities are not allowed to be directly updated initializationContext.m_entityUpdateList.push_back( pEntity ); pEntity->m_updateRegistrationStatus = Entity::UpdateRegistrationStatus::Registered; } } //------------------------------------------------------------------------- // Component Registrations //------------------------------------------------------------------------- // Create a task that splits per-system registration across multiple threads struct ComponentRegistrationTask : public ITaskSet { ComponentRegistrationTask( TVector<EntityWorldSystem*> const& worldSystems, TVector<EntityModel::EntityComponentPair> const& componentsToRegister, TVector<EntityModel::EntityComponentPair> const& componentsToUnregister ) : m_worldSystems( worldSystems ) , m_componentsToRegister( componentsToRegister ) , m_componentsToUnregister( componentsToUnregister ) { m_SetSize = (uint32_t) worldSystems.size(); } virtual void ExecuteRange( TaskSetPartition range, uint32_t threadnum ) override final { EE_PROFILE_SCOPE_ENTITY( "Component World Registration Task" ); // Register/Unregister component with World Systems //------------------------------------------------------------------------- for ( uint64_t i = range.start; i < range.end; ++i ) { auto pSystem = m_worldSystems[i]; //------------------------------------------------------------------------- size_t const numComponentsToUnregister = m_componentsToUnregister.size(); for ( auto c = 0u; c < numComponentsToUnregister; c++ ) { auto pEntity = m_componentsToUnregister[c].m_pEntity; auto pComponent = m_componentsToUnregister[c].m_pComponent; EE_ASSERT( pEntity != nullptr ); EE_ASSERT( pComponent != nullptr && pComponent->IsInitialized() && pComponent->m_isRegisteredWithWorld ); pSystem->UnregisterComponent( pEntity, pComponent ); } //------------------------------------------------------------------------- size_t const numComponentsToRegister = m_componentsToRegister.size(); for ( auto c = 0u; c < numComponentsToRegister; c++ ) { auto pEntity = m_componentsToRegister[c].m_pEntity; auto pComponent = m_componentsToRegister[c].m_pComponent; EE_ASSERT( pEntity != nullptr && pEntity->IsInitialized() && !pComponent->m_isRegisteredWithWorld ); EE_ASSERT( pComponent != nullptr && pComponent->IsInitialized() ); pSystem->RegisterComponent( pEntity, pComponent ); } } } private: TVector<EntityWorldSystem*> const& m_worldSystems; TVector<EntityModel::EntityComponentPair> const& m_componentsToRegister; TVector<EntityModel::EntityComponentPair> const& m_componentsToUnregister; }; //------------------------------------------------------------------------- { EE_PROFILE_SCOPE_ENTITY( "Component World Registration" ); // Get Components to register/unregister //------------------------------------------------------------------------- TVector<EntityModel::EntityComponentPair> componentsToUnregister; size_t const numComponentsToUnregister = initializationContext.m_componentsToUnregister.size_approx(); componentsToUnregister.resize( numComponentsToUnregister ); size_t numDequeued = initializationContext.m_componentsToUnregister.try_dequeue_bulk( componentsToUnregister.data(), numComponentsToUnregister ); EE_ASSERT( numComponentsToUnregister == numDequeued ); //------------------------------------------------------------------------- TVector<EntityModel::EntityComponentPair> componentsToRegister; size_t const numComponentsToRegister = initializationContext.m_componentsToRegister.size_approx(); componentsToRegister.resize( numComponentsToRegister ); numDequeued = initializationContext.m_componentsToRegister.try_dequeue_bulk( componentsToRegister.data(), numComponentsToRegister ); EE_ASSERT( numComponentsToRegister == numDequeued ); // Run registration task //------------------------------------------------------------------------- if ( ( numComponentsToUnregister + numComponentsToRegister ) > 0 ) { ComponentRegistrationTask componentRegistrationTask( initializationContext.m_worldSystems, componentsToRegister, componentsToUnregister ); initializationContext.m_pTaskSystem->ScheduleTask( &componentRegistrationTask ); initializationContext.m_pTaskSystem->WaitForTask( &componentRegistrationTask ); } // Finalize component registration //------------------------------------------------------------------------- // Remove from type tracking table for ( auto const& pair : componentsToUnregister ) { pair.m_pComponent->m_isRegisteredWithWorld = false; #if EE_DEVELOPMENT_TOOLS EntityComponentTypeMap& componentTypeMap = *initializationContext.m_pComponentTypeMap; auto const castableTypeIDs = initializationContext.m_pTypeRegistry->GetAllCastableTypes( pair.m_pComponent ); for ( auto castableTypeID : castableTypeIDs ) { componentTypeMap[castableTypeID].erase_first_unsorted( pair.m_pComponent ); } #endif } // Add to type tracking table for ( auto const& pair : componentsToRegister ) { pair.m_pComponent->m_isRegisteredWithWorld = true; #if EE_DEVELOPMENT_TOOLS EntityComponentTypeMap& componentTypeMap = *initializationContext.m_pComponentTypeMap; auto const castableTypeIDs = initializationContext.m_pTypeRegistry->GetAllCastableTypes( pair.m_pComponent ); for ( auto castableTypeID : castableTypeIDs ) { componentTypeMap[castableTypeID].emplace_back( pair.m_pComponent ); } #endif } } } //------------------------------------------------------------------------- bool EntityMap::UpdateLoadingAndStateChanges( LoadingContext const& loadingContext, InitializationContext& initializationContext ) { EE_PROFILE_SCOPE_ENTITY( "Map State Update" ); EE_ASSERT( Threading::IsMainThread() && loadingContext.IsValid() && initializationContext.IsValid() ); #if EE_DEVELOPMENT_TOOLS EE_ASSERT( m_entitiesToHotReload.empty() ); EE_ASSERT( m_editedEntities.empty() ); // You are missing a EndComponentEdit call somewhere! #endif //------------------------------------------------------------------------- Threading::RecursiveScopeLock lock( m_mutex ); //------------------------------------------------------------------------- switch ( m_status ) { case Status::Unloading: { ProcessMapUnloading( loadingContext, initializationContext ); } break; case Status::Loading: { ProcessMapLoading( loadingContext ); } break; default: break; } // Process entity removal requests //------------------------------------------------------------------------- ProcessEntityShutdownRequests( initializationContext ); ProcessEntityRegistrationRequests( initializationContext ); ProcessEntityRemovalRequests( loadingContext ); // Update entity load states //------------------------------------------------------------------------- ProcessEntityLoadingAndInitialization( loadingContext, initializationContext ); ProcessEntityRegistrationRequests( initializationContext ); // Return status //------------------------------------------------------------------------- if ( m_status == Status::Loading || !m_entitiesCurrentlyLoading.empty() ) { return false; } return true; } bool EntityMap::HasPendingAddOrRemoveRequests() const { size_t numPendingRequests = ( m_entitiesToLoad.size() + m_entitiesToRemove.size() ); #if EE_DEVELOPMENT_TOOLS numPendingRequests += m_entitiesToHotReload.size(); #endif return numPendingRequests > 0; } //------------------------------------------------------------------------- // Tools //------------------------------------------------------------------------- #if EE_DEVELOPMENT_TOOLS void EntityMap::RenameEntity( Entity* pEntity, StringID newNameID ) { EE_ASSERT( pEntity != nullptr && pEntity->m_mapID == m_ID ); // Lock the map Threading::RecursiveScopeLock lock( m_mutex ); // Remove from lookup map auto nameLookupIter = m_entityNameLookupMap.find( pEntity->m_name ); EE_ASSERT( nameLookupIter != m_entityNameLookupMap.end() ); m_entityNameLookupMap.erase( nameLookupIter ); // Rename pEntity->m_name = GenerateUniqueEntityNameID( newNameID ); // Add to lookup map m_entityNameLookupMap.insert( TPair<StringID, Entity*>( pEntity->m_name, pEntity ) ); } StringID EntityMap::GenerateUniqueEntityNameID( StringID desiredNameID ) const { auto GenerateUniqueName = [] ( InlineString const& baseName, int32_t counterValue ) { InlineString finalName; if ( baseName.length() > 3 ) { // Check if the last three characters are a numeric set, if so then increment the value and replace them if ( isdigit( baseName[baseName.length() - 1] ) && isdigit( baseName[baseName.length() - 2] ) && isdigit( baseName[baseName.length() - 3] ) ) { finalName.sprintf( "%s%03u", baseName.substr( 0, baseName.length() - 3 ).c_str(), counterValue ); return finalName; } } finalName.sprintf( "%s %03u", baseName.c_str(), counterValue ); return finalName; }; //------------------------------------------------------------------------- EE_ASSERT( desiredNameID.IsValid() ); InlineString desiredName = desiredNameID.c_str(); InlineString finalName = desiredName; StringID finalNameID( finalName.c_str() ); uint32_t counter = 0; bool isUniqueName = false; while ( !isUniqueName ) { // Check the lookup map isUniqueName = m_entityNameLookupMap.find( finalNameID ) == m_entityNameLookupMap.end(); // If we found a name clash, generate a new name and try again if ( !isUniqueName ) { finalName = GenerateUniqueName( desiredName, counter ); finalNameID = StringID( finalName.c_str() ); counter++; } } //------------------------------------------------------------------------- return finalNameID; } void EntityMap::BeginComponentEdit( LoadingContext const& loadingContext, InitializationContext& initializationContext, EntityID const& entityID ) { EE_ASSERT( Threading::IsMainThread() ); auto pEntity = FindEntity( entityID ); EE_ASSERT( pEntity != nullptr ); EE_ASSERT( !VectorContains( m_editedEntities, pEntity ) ); // Starting multiple edits for the same entity?! if ( pEntity->IsInitialized() ) { pEntity->Shutdown( initializationContext ); ProcessEntityRegistrationRequests( initializationContext ); } pEntity->UnloadComponents( loadingContext ); m_entitiesCurrentlyLoading.erase_first_unsorted( pEntity ); m_editedEntities.emplace_back( pEntity ); } void EntityMap::EndComponentEdit( LoadingContext const& loadingContext, InitializationContext& initializationContext, EntityID const& entityID ) { EE_ASSERT( Threading::IsMainThread() ); auto pEntity = FindEntity( entityID ); EE_ASSERT( pEntity != nullptr ); EE_ASSERT( !VectorContains( m_entitiesCurrentlyLoading, pEntity ) ); EE_ASSERT( VectorContains( m_editedEntities, pEntity ) ); // Cant end an edit that was never started! pEntity->LoadComponents( loadingContext ); m_entitiesCurrentlyLoading.emplace_back( pEntity ); m_editedEntities.erase_first_unsorted( pEntity ); } //------------------------------------------------------------------------- void EntityMap::HotReload_UnloadEntities( LoadingContext const& loadingContext, InitializationContext& initializationContext, TInlineVector<Resource::ResourceRequesterID, 20> const& usersToReload ) { EE_ASSERT( Threading::IsMainThread() ); EE_ASSERT( !usersToReload.empty() ); EE_ASSERT( m_entitiesToHotReload.empty() ); Threading::RecursiveScopeLock lock( m_mutex ); // Run map loading code to ensure that any destroy entity request (that might be unloading resources are executed!) UpdateLoadingAndStateChanges( loadingContext, initializationContext ); // There should never be any queued registration request at this stage! EE_ASSERT( initializationContext.m_registerForEntityUpdate.size_approx() == 0 && initializationContext.m_unregisterForEntityUpdate.size_approx() == 0 ); EE_ASSERT( initializationContext.m_componentsToRegister.size_approx() == 0 && initializationContext.m_componentsToUnregister.size_approx() == 0 ); // Generate list of entities to be reloaded for ( auto const& requesterID : usersToReload ) { // See if the entity that needs a reload is in this map Entity* pFoundEntity = FindEntity( EntityID( requesterID.GetID() ) ); if ( pFoundEntity != nullptr ) { m_entitiesToHotReload.emplace_back( pFoundEntity ); } } // Request shutdown for any entities that are initialized bool someEntitiesRequireShutdown = false; for ( auto pEntityToHotReload : m_entitiesToHotReload ) { if ( pEntityToHotReload->IsInitialized() ) { pEntityToHotReload->Shutdown( initializationContext ); someEntitiesRequireShutdown = true; } } // Process unregistration requests if ( someEntitiesRequireShutdown ) { ProcessEntityRegistrationRequests( initializationContext ); } // Unload entities for ( auto pEntityToHotReload : m_entitiesToHotReload ) { EE_ASSERT( !pEntityToHotReload->IsInitialized() ); // We might still be loading this entity so remove it from the loading requests m_entitiesCurrentlyLoading.erase_first_unsorted( pEntityToHotReload ); // Request unload of the components (client system needs to ensure that all resource requests are processed) pEntityToHotReload->UnloadComponents( loadingContext ); } } void EntityMap::HotReload_ReloadEntities( LoadingContext const& loadingContext, TInlineVector<Resource::ResourceRequesterID, 20> const& usersToReload ) { EE_ASSERT( Threading::IsMainThread() ); Threading::RecursiveScopeLock lock( m_mutex ); for ( auto pEntityToHotReload : m_entitiesToHotReload ) { EE_ASSERT( pEntityToHotReload->IsUnloaded() ); pEntityToHotReload->LoadComponents( loadingContext ); m_entitiesCurrentlyLoading.emplace_back( pEntityToHotReload ); } m_entitiesToHotReload.clear(); } #endif }
1
0.883877
1
0.883877
game-dev
MEDIA
0.961809
game-dev
0.804753
1
0.804753
proxmox/proxmox-datacenter-manager
3,254
ui/src/renderer.rs
use pdm_api_types::resource::PveSdnResource; use proxmox_yew_comp::MeterLabel; use pwt::{ css::AlignItems, prelude::*, props::ContainerBuilder, widget::{Container, Fa, Row}, }; use proxmox_human_byte::HumanByte; use pdm_client::types::Resource; use crate::pve; pub fn render_resource_name(resource: &Resource, vmid_first: bool) -> String { match resource { Resource::PveStorage(storage) => storage.storage.clone(), Resource::PveQemu(qemu) => pve::utils::render_qemu_name(qemu, vmid_first), Resource::PveLxc(lxc) => pve::utils::render_lxc_name(lxc, vmid_first), Resource::PveNode(node) => node.node.clone(), Resource::PveSdn(sdn) => sdn.name().to_string(), Resource::PbsNode(node) => node.name.clone(), Resource::PbsDatastore(store) => store.name.clone(), } } pub fn render_resource_icon(resource: &Resource) -> Fa { let class = match resource { Resource::PveStorage(_) => "database", Resource::PveQemu(_) => "desktop", Resource::PveLxc(_) => "cube", Resource::PveNode(_) => "building", Resource::PveSdn(_) => "fa-sdn", Resource::PbsNode(_) => "building-o", Resource::PbsDatastore(_) => "floppy-o", }; Fa::new(class) } pub fn render_status_icon(resource: &Resource) -> Container { match resource { Resource::PveStorage(store) => pve::utils::render_storage_status_icon(store), Resource::PveQemu(qemu) => pve::utils::render_qemu_status_icon(qemu), Resource::PveLxc(lxc) => pve::utils::render_lxc_status_icon(lxc), Resource::PveNode(node) => pve::utils::render_node_status_icon(node), Resource::PveSdn(PveSdnResource::Zone(zone)) => pve::utils::render_sdn_status_icon(zone), // FIXME: implement remaining types _ => Container::new().with_child(render_resource_icon(resource)), } } pub(crate) fn status_row_right_icon( title: String, icon: impl Into<Classes>, text: String, ) -> MeterLabel { status_row(title, icon, text).icon_right(true) } pub(crate) fn status_row(title: String, icon: impl Into<Classes>, text: String) -> MeterLabel { MeterLabel::with_zero_optimum(title) .icon_class(classes!(icon.into(), "fa", "fa-fw")) .low(0.8) .high(0.9) .animated(true) .status(text) } pub(crate) fn memory_status_row(used: u64, total: u64) -> MeterLabel { let usage = used as f64 / total as f64; status_row( tr!("Memory usage"), "fa-memory", tr!( "{0}% ({1} of {2})", format!("{:.2}", usage * 100.0), HumanByte::from(used), HumanByte::from(total), ), ) .low(0.9) .high(0.975) .value(usage as f32) } pub(crate) fn separator() -> Container { Container::new().with_child(html! {<hr />}).padding_y(2) } pub(crate) fn render_tree_column(icon: Html, text: String) -> Row { Row::new() .min_width(0) .class(AlignItems::Center) .gap(2) .with_child(icon) .with_child( Container::new() .with_child(text) .style("text-overflow", "ellipsis") .style("overflow", "hidden"), ) }
1
0.924979
1
0.924979
game-dev
MEDIA
0.505536
game-dev
0.849452
1
0.849452
Arakne/Araknemu
8,120
src/main/java/fr/quatrevieux/araknemu/game/admin/player/teleport/Goto.java
/* * This file is part of Araknemu. * * Araknemu 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. * * Araknemu 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 Araknemu. If not, see <https://www.gnu.org/licenses/>. * * Copyright (c) 2017-2020 Vincent Quatrevieux */ package fr.quatrevieux.araknemu.game.admin.player.teleport; import fr.quatrevieux.araknemu.common.account.Permission; import fr.quatrevieux.araknemu.data.value.Position; import fr.quatrevieux.araknemu.game.admin.AbstractCommand; import fr.quatrevieux.araknemu.game.admin.AdminPerformer; import fr.quatrevieux.araknemu.game.admin.exception.AdminException; import fr.quatrevieux.araknemu.game.admin.exception.CommandException; import fr.quatrevieux.araknemu.game.exploration.ExplorationPlayer; import fr.quatrevieux.araknemu.game.exploration.interaction.action.move.TeleportationTarget; import fr.quatrevieux.araknemu.game.exploration.map.ExplorationMap; import fr.quatrevieux.araknemu.game.exploration.map.ExplorationMapService; import fr.quatrevieux.araknemu.game.player.GamePlayer; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Teleport the player to the desired location */ public final class Goto extends AbstractCommand<Goto.Arguments> { private final GamePlayer player; private final ExplorationMapService mapService; private final Map<String, LocationResolver> resolvers = new LinkedHashMap<>(); /** * @param player The teleported player * @param resolvers Position resolvers */ public Goto(GamePlayer player, ExplorationMapService mapService, LocationResolver[] resolvers) { this.player = player; this.mapService = mapService; for (LocationResolver resolver : resolvers) { register(resolver); } } @Override protected void build(Builder builder) { builder .help( formatter -> { formatter .description("Teleport the player to the desired location") .option("TYPE", "Define the target type (available types are defined bellow). If not provided, will try all available resolvers.") .option("TARGET", "Required. The target. This value depends of the type.") ; for (LocationResolver resolver : resolvers.values()) { formatter.option("TYPE: " + resolver.name(), resolver.help()); } formatter .example("goto map 10340", "Teleport to the map id 10340") .example("goto map 10340 cell 45", "Teleport to the map id 10340 at cell 45") .example("goto player John", "Teleport to the John's map") .example("goto position 3;5", "Teleport by geolocation") .example("@John goto map 10340", "Teleport John to map id 10340") .example("@John goto player Alan", "Teleport John to the Alan's map") .example("goto 3;5 cell 42", "Command can works without [type] argument, if not ambiguous") ; } ) .requires(Permission.MANAGE_PLAYER) ; } @Override public String name() { return "goto"; } @Override public void execute(AdminPerformer performer, Arguments arguments) throws AdminException { if ((!player.isExploring() || player.exploration().interactions().busy()) && !arguments.force) { error("The player is busy, and cannot be teleported. Use --force to force the teleportation."); } final TeleportationTarget target = parseTarget(arguments.targets); teleportToTarget(performer, target); performer.success("Teleport {} to {}", player.name(), target); } /** * Parse the target from the command arguments */ private TeleportationTarget parseTarget(List<String> arguments) throws AdminException { final ExplorationMap currentMap = player.isExploring() ? player.exploration().map() : null; TeleportationTarget target = new TeleportationTarget( currentMap != null ? currentMap : mapService.load(player.position().map()), player.position().cell() ); for (int argIndex = 0; argIndex < arguments.size(); ++argIndex) { final String argument = arguments.get(argIndex); if (resolvers.containsKey(argument)) { ++argIndex; if (arguments.size() < argIndex + 1) { error("Missing argument for type " + argument); } try { target = resolvers.get(argument).resolve(arguments.get(argIndex), target); } catch (IllegalArgumentException e) { throw new AdminException(e); } continue; } target = autoResolve(argument, target); } return target.ensureCellWalkable(); } /** * Try to auto resolve the argument * * @param argument The argument to parse * @param target The target * * @throws CommandException If the argument cannot be resolved */ private TeleportationTarget autoResolve(String argument, TeleportationTarget target) throws CommandException { for (LocationResolver resolver : resolvers.values()) { try { return resolver.resolve(argument, target); } catch (IllegalArgumentException e) { // ignore resolve exception } } throw new CommandException(name(), "Cannot resolve the argument or type " + argument); } /** * Perform the teleportation * * @param performer Command performer * @param target The teleportation target */ private void teleportToTarget(AdminPerformer performer, TeleportationTarget target) { if (!player.isExploring()) { performer.info("Player is not in exploration. Define the position for the next exploration session."); player.setPosition(new Position(target.map().id(), target.cell())); return; } final ExplorationPlayer exploration = player.exploration(); if (exploration.interactions().busy()) { performer.info("Player is busy. Stop all there interactions."); exploration.interactions().stop(); } target.apply(exploration); } /** * Add a new location resolver for the command */ private void register(LocationResolver resolver) { resolvers.put(resolver.name(), resolver); } @Override public Arguments createArguments() { return new Arguments(); } @SuppressWarnings("initialization.field.uninitialized") public static final class Arguments { @Option(name = "--force", usage = "Force the teleporation even if the player is busy or in fight.") private boolean force = false; @Argument(metaVar = "TYPE TARGET", multiValued = true) private List<String> targets; public boolean force() { return force; } public void setForce(boolean force) { this.force = force; } public List<String> targets() { return targets; } public void setTargets(List<String> targets) { this.targets = targets; } } }
1
0.908155
1
0.908155
game-dev
MEDIA
0.947369
game-dev
0.975551
1
0.975551
perl11/cperl
1,447
ext/XS-APItest/t/cleanup.t
use warnings; use strict; use Test::More tests => 3; use XS::APItest qw(establish_cleanup); my @events; # unwinding on local return from sub sub aa { push @events, "aa0"; establish_cleanup sub { push @events, "bb0" }; push @events, "aa1"; "aa2"; } sub cc { push @events, "cc0"; push @events, [ "cc1", aa() ]; push @events, "cc2"; "cc3"; } @events = (); push @events, "dd0"; push @events, [ "dd1", cc() ]; is_deeply \@events, [ "dd0", "cc0", "aa0", "aa1", "bb0", [ "cc1", "aa2" ], "cc2", [ "dd1", "cc3" ], ]; # unwinding on local return from format sub ff { push @events, "ff0" } format EE = @<< ((push @events, "ee0"), (establish_cleanup \&ff), (push @events, "ee1"), "ee2") . sub gg { push @events, "gg0"; write(EE); push @events, "gg1"; "gg2"; } @events = (); open EE, ">", \(my $ee); push @events, "hh0"; push @events, [ "hh1", gg() ]; close EE; is_deeply \@events, [ "hh0", "gg0", "ee0", "ee1", "ff0", "gg1", [ "hh1", "gg2" ], ]; # unwinding on die sub pp { my $value = eval { push @events, "pp0"; establish_cleanup sub { push @events, "qq0" }; push @events, "pp1"; die "pp2\n"; push @events, "pp3"; "pp4"; }; [ "pp5", $value, $@ ]; } @events = (); push @events, "rr0"; push @events, [ "rr1", pp() ]; is_deeply \@events, [ "rr0", "pp0", "pp1", "qq0", [ "rr1", [ "pp5", undef, "pp2\n" ] ], ]; 1;
1
0.884553
1
0.884553
game-dev
MEDIA
0.447248
game-dev
0.835781
1
0.835781
hieki-chan/Supermarket-Simulator-Prototype
2,660
Library/PackageCache/com.unity.scriptablebuildpipeline@1.21.23/Editor/Tasks/GenerateSubAssetPathMaps.cs
using System.Collections.Generic; using System.Linq; using UnityEditor.Build.Content; using UnityEditor.Build.Pipeline.Injector; using UnityEditor.Build.Pipeline.Interfaces; using UnityEditor.Build.Pipeline.Utilities; using UnityEditor.Build.Pipeline.WriteTypes; namespace UnityEditor.Build.Pipeline.Tasks { /// <summary> /// Creates sub asset load information. /// </summary> public class GenerateSubAssetPathMaps : IBuildTask { /// <inheritdoc /> public int Version { get { return 1; } } #pragma warning disable 649 [InjectContext] IBundleWriteData m_WriteData; [InjectContext(ContextUsage.In, true)] IBuildExtendedAssetData m_ExtendedAssetData; #pragma warning restore 649 /// <inheritdoc /> public ReturnCode Run() { if (m_ExtendedAssetData == null || m_ExtendedAssetData.ExtendedData.IsNullOrEmpty()) return ReturnCode.SuccessNotRun; Dictionary<string, IWriteOperation> fileToOperation = m_WriteData.WriteOperations.ToDictionary(x => x.Command.internalName, x => x); foreach (var pair in m_ExtendedAssetData.ExtendedData) { GUID asset = pair.Key; string mainFile = m_WriteData.AssetToFiles[asset][0]; var abOp = fileToOperation[mainFile] as AssetBundleWriteOperation; int assetInfoIndex = abOp.Info.bundleAssets.FindIndex(x => x.asset == asset); AssetLoadInfo assetInfo = abOp.Info.bundleAssets[assetInfoIndex]; int offset = 1; foreach (var subAsset in pair.Value.Representations) { var secondaryAssetInfo = CreateSubAssetLoadInfo(assetInfo, subAsset); abOp.Info.bundleAssets.Insert(assetInfoIndex + offset, secondaryAssetInfo); offset++; } } return ReturnCode.Success; } static AssetLoadInfo CreateSubAssetLoadInfo(AssetLoadInfo assetInfo, ObjectIdentifier subAsset) { var subAssetLoadInfo = new AssetLoadInfo(); subAssetLoadInfo.asset = assetInfo.asset; subAssetLoadInfo.address = assetInfo.address; subAssetLoadInfo.referencedObjects = new List<ObjectIdentifier>(assetInfo.referencedObjects); subAssetLoadInfo.includedObjects = new List<ObjectIdentifier>(assetInfo.includedObjects); var index = subAssetLoadInfo.includedObjects.IndexOf(subAsset); subAssetLoadInfo.includedObjects.Swap(0, index); return subAssetLoadInfo; } } }
1
0.873216
1
0.873216
game-dev
MEDIA
0.793655
game-dev
0.921543
1
0.921543
DenizenScript/Denizen
7,050
plugin/src/main/java/com/denizenscript/denizen/scripts/commands/player/ActionBarCommand.java
package com.denizenscript.denizen.scripts.commands.player; import com.denizenscript.denizen.objects.PlayerTag; import com.denizenscript.denizen.tags.BukkitTagContext; import com.denizenscript.denizen.utilities.FormattedTextHelper; import com.denizenscript.denizen.utilities.Utilities; import com.denizenscript.denizencore.exceptions.InvalidArgumentsException; import com.denizenscript.denizencore.objects.Argument; import com.denizenscript.denizencore.objects.ArgumentHelper; import com.denizenscript.denizencore.objects.core.ElementTag; import com.denizenscript.denizencore.objects.core.ListTag; import com.denizenscript.denizencore.objects.core.ScriptTag; import com.denizenscript.denizencore.scripts.ScriptEntry; import com.denizenscript.denizencore.scripts.ScriptRegistry; import com.denizenscript.denizencore.scripts.commands.AbstractCommand; import com.denizenscript.denizencore.scripts.containers.core.FormatScriptContainer; import com.denizenscript.denizencore.tags.TagManager; import com.denizenscript.denizencore.utilities.debugging.Debug; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatMessageType; import java.util.Collections; import java.util.List; public class ActionBarCommand extends AbstractCommand { public ActionBarCommand() { setName("actionbar"); setSyntax("actionbar [<text>] (targets:<player>|...) (format:<script>) (per_player)"); setRequiredArguments(1, 4); setParseArgs(false); isProcedural = false; } // <--[command] // @Name ActionBar // @Syntax actionbar [<text>] (targets:<player>|...) (format:<script>) (per_player) // @Required 1 // @Maximum 4 // @Short Sends a message to a player's action bar. // @group player // // @Description // Sends a message to the target's action bar area. // If no target is specified it will default to the attached player. // Accepts the 'format:<name>' argument, which will reformat the text according to the specified format script. See <@link language Format Script Containers>. // // Optionally use 'per_player' with a list of player targets, to have the tags in the text input be reparsed for each and every player. // So, for example, "- actionbar 'hello <player.name>' targets:<server.online_players>" // would normally show "hello bob" to every player (every player sees the exact same name in the text, ie bob sees "hello bob", steve also sees "hello bob", etc) // but if you use "per_player", each player online would see their own name (so bob sees "hello bob", steve sees "hello steve", etc). // // @Tags // None // // @Usage // Use to send a message to the player's action bar. // - actionbar "Hey there <player.name>!" // // @Usage // Use to send a message to a list of players. // - actionbar "Hey, welcome to the server!" targets:<[thatplayer]>|<[player]>|<[someplayer]> // // @Usage // Use to send a message to a list of players, with a formatted message. // - actionbar "Hey there!" targets:<[thatplayer]>|<[player]> format:ServerChat // --> @Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (Argument arg : ArgumentHelper.interpret(scriptEntry, scriptEntry.getOriginalArguments())) { if (!scriptEntry.hasObject("format") && arg.matchesPrefix("format", "f")) { String formatStr = TagManager.tag(arg.getValue(), scriptEntry.getContext()); FormatScriptContainer format = ScriptRegistry.getScriptContainer(formatStr); if (format == null) { Debug.echoError("Could not find format script matching '" + formatStr + "'"); } scriptEntry.addObject("format", new ScriptTag(format)); } else if (!scriptEntry.hasObject("targets") && arg.matchesPrefix("targets", "target")) { scriptEntry.addObject("targets", ListTag.getListFor(TagManager.tagObject(arg.getValue(), scriptEntry.getContext()), scriptEntry.getContext()).filter(PlayerTag.class, scriptEntry)); } else if (!scriptEntry.hasObject("per_player") && arg.matches("per_player")) { scriptEntry.addObject("per_player", new ElementTag(true)); } else if (!scriptEntry.hasObject("text")) { scriptEntry.addObject("text", arg.getRawElement()); } else { arg.reportUnhandled(); } } if (!scriptEntry.hasObject("text")) { throw new InvalidArgumentsException("Must specify a message!"); } if (!scriptEntry.hasObject("targets") && !Utilities.entryHasPlayer(scriptEntry)) { throw new InvalidArgumentsException("Must specify target(s)."); } if (!scriptEntry.hasObject("targets")) { if (!Utilities.entryHasPlayer(scriptEntry)) { throw new InvalidArgumentsException("Must specify valid player Targets!"); } else { scriptEntry.addObject("targets", Collections.singletonList(Utilities.getEntryPlayer(scriptEntry))); } } } @Override public void execute(ScriptEntry scriptEntry) { List<PlayerTag> targets = (List<PlayerTag>) scriptEntry.getObject("targets"); String text = scriptEntry.getElement("text").asString(); ScriptTag formatObj = scriptEntry.getObjectTag("format"); ElementTag perPlayerObj = scriptEntry.getElement("per_player"); boolean perPlayer = perPlayerObj != null && perPlayerObj.asBoolean(); BukkitTagContext context = (BukkitTagContext) scriptEntry.getContext(); if (!perPlayer) { text = TagManager.tag(text, context); } if (scriptEntry.dbCallShouldDebug()) { Debug.report(scriptEntry, getName(), db("message", text), db("targets", targets), formatObj, perPlayerObj); } FormatScriptContainer format = formatObj == null ? null : (FormatScriptContainer) formatObj.getContainer(); for (PlayerTag player : targets) { if (player != null) { if (!player.isOnline()) { Debug.echoDebug(scriptEntry, "Player is offline, can't send actionbar to them. Skipping."); continue; } String personalText = text; if (perPlayer) { context.player = player; personalText = TagManager.tag(personalText, context); } player.getPlayerEntity().spigot().sendMessage(ChatMessageType.ACTION_BAR, FormattedTextHelper.parse(format != null ? format.getFormattedText(personalText, scriptEntry) : personalText, ChatColor.WHITE)); } else { Debug.echoError("Sent actionbar to non-existent player!?"); } } } }
1
0.906624
1
0.906624
game-dev
MEDIA
0.630182
game-dev
0.94461
1
0.94461
fluency03/leetcode-java
8,417
src/TheMaze490.java
/** * There is a ball in a maze with empty spaces and walls. The ball can go * through empty spaces by rolling up, down, left or right, but it won't stop * rolling until hitting a wall. When the ball stops, it could choose the next * direction. * * Given the ball's start position, the destination and the maze, determine * whether the ball could stop at the destination. * * The maze is represented by a binary 2D array. 1 means the wall and 0 means * the empty space. You may assume that the borders of the maze are all walls. * The start and destination coordinates are represented by row and column * indexes. * * Example 1 * * Input 1: a maze represented by a 2D array * * 0 0 1 0 0 * 0 0 0 0 0 * 0 0 0 1 0 * 1 1 0 1 1 * 0 0 0 0 0 * * Input 2: start coordinate (rowStart, colStart) = (0, 4) * Input 3: destination coordinate (rowDest, colDest) = (4, 4) * * Output: true * Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right. * https://leetcode.com/static/images/problemset/maze_1_example_1.png * * Example 2 * * Input 1: a maze represented by a 2D array * * 0 0 1 0 0 * 0 0 0 0 0 * 0 0 0 1 0 * 1 1 0 1 1 * 0 0 0 0 0 * * Input 2: start coordinate (rowStart, colStart) = (0, 4) * Input 3: destination coordinate (rowDest, colDest) = (3, 2) * * Output: false * Explanation: There is no way for the ball to stop at the destination. * https://leetcode.com/static/images/problemset/maze_1_example_2.png * * Note: * There is only one ball and one destination in the maze. * Both the ball and the destination exist on an empty space, and they will not * be at the same position initially. * The given maze does not contain border (like the red rectangle in the example * pictures), but you could assume the border of the maze are all walls. * The maze contains at least 2 empty spaces, and both the width and height of * the maze won't exceed 100. */ public class TheMaze490 { private boolean[][] visited; public boolean hasPath(int[][] maze, int[] start, int[] destination) { visited = new boolean[maze.length][maze[0].length]; if (hasPath(maze, start, destination, Direction.Left) || hasPath(maze, start, destination, Direction.Right) || hasPath(maze, start, destination, Direction.Top) || hasPath(maze, start, destination, Direction.Down)) return true; return false; } public boolean hasPath(int[][] maze, int[] start, int[] destination, Direction d) { visited[start[0]][start[1]] = true; int[] now = new int[]{start[0], start[1]}; Direction origin = d; while (true) { if (d == Direction.Left) { int nextLeft = now[1] - 1; if (nextLeft < 0 || maze[now[0]][nextLeft] == 1) break; now[1] = nextLeft; // System.out.println(tuple(now)); origin = Direction.Right; } else if (d == Direction.Right) { int nextRight = now[1] + 1; if (nextRight >= maze[0].length || maze[now[0]][nextRight] == 1) break; now[1] = nextRight; origin = Direction.Left; } else if (d == Direction.Top) { int nextTop = now[0] - 1; if (nextTop < 0 || maze[nextTop][now[1]] == 1) break; now[0] = nextTop; origin = Direction.Down; } else { int nextDown = now[0] + 1; if (nextDown >= maze.length || maze[nextDown][now[1]] == 1) break; now[0] = nextDown; origin = Direction.Top; } } if (now[0] == destination[0] && now[1] == destination[1]) return true; if (visited[now[0]][now[1]]) return false; for (Direction nextDir: Direction.values()) { if (nextDir != origin && hasPath(maze, now, destination, nextDir)) return true; } visited[start[0]][start[1]] = false; return false; } public enum Direction { Left, Right, Top, Down } public boolean hasPath2(int[][] maze, int[] start, int[] destination) { int M = maze.length; int N = maze[0].length; return roll(maze, start[0], start[1], destination[0], destination[1], M, N, new boolean[M][N]); } private boolean roll(int[][] maze, int i, int j, int di, int dj, int M, int N, boolean[][] visited) { // if (i < 0 || j < 0 || i >= M || j >= N) return false; if (visited[i][j]) return false; if (i == di && j == dj) return true; visited[i][j] = true; // top int x = i - 1; int y = j; while (x >= 0 && maze[x][y] == 0) x--; if (roll(maze, x+1, y, di, dj, M, N, visited)) { return true; } // bottom x = i + 1; y = j; while (x < M && maze[x][y] == 0) x++; if (roll(maze, x-1, y, di, dj, M, N, visited)) { return true; } // left x = i; y = j - 1; while (y >= 0 && maze[x][y] == 0) y--; if (roll(maze, x, y+1, di, dj, M, N, visited)) { return true; } // right x = i; y = j + 1; while (y < N && maze[x][y] == 0) y++; if (roll(maze, x, y-1, di, dj, M, N, visited)) { return true; } return false; } public boolean hasPath3(int[][] maze, int[] start, int[] destination) { if (maze == null || maze.length == 0 || maze[0].length == 0 || start == null || destination == null) return false; if (start[0] == destination[0] && start[1] == destination[1]) return true; int M = maze.length; int N = maze[0].length; boolean[][] visited = new boolean[M][N]; Queue<int[]> q = new LinkedList<>(); q.add(start); visited[start[0]][start[1]] = true; while (!q.isEmpty()) { int[] curr = q.poll(); if (curr[0] == destination[0] && curr[1] == destination[1]) return true; addNextSteps(maze, q, visited, curr, M, N); } return false; } private void addNextSteps(int[][] maze, Queue<int[]> q, boolean[][] visited, int[] curr, int M, int N) { int i = curr[0]; while (i >= 0 && maze[i][curr[1]] == 0) { i--; } if (!visited[i+1][curr[1]]) { q.add(new int[]{i+1, curr[1]}); visited[i+1][curr[1]] = true; } i = curr[0]; while (i < M && maze[i][curr[1]] == 0) { i++; } if (!visited[i-1][curr[1]]) { q.add(new int[]{i-1, curr[1]}); visited[i-1][curr[1]] = true; } i = curr[1]; while (i >= 0 && maze[curr[0]][i] == 0) { i--; } if (!visited[curr[0]][i+1]) { q.add(new int[]{curr[0], i+1}); visited[curr[0]][i+1] = true; } i = curr[1]; while (i < N && maze[curr[0]][i] == 0) { i++; } if (!visited[curr[0]][i-1]) { q.add(new int[]{curr[0], i-1}); visited[curr[0]][i-1] = true; } } private int[][] DIRECTIONS = new int[][]{{0,1}, {0,-1}, {1,0}, {-1,0}}; public boolean hasPath4(int[][] maze, int[] start, int[] destination) { int M = maze.length; int N = maze[0].length; boolean[][] visited = new boolean[M][N]; Queue<int[]> q = new LinkedList<>(); q.add(start); visited[start[0]][start[1]] = true; while (!q.isEmpty()) { int[] curr = q.poll(); for (int[] dir: DIRECTIONS) { int x = curr[0]+dir[0]; int y = curr[1]+dir[1]; while (x >= 0 && x < M && y >= 0 && y < N && maze[x][y] == 0) { x += dir[0]; y += dir[1]; } x -= dir[0]; y -= dir[1]; if (x == destination[0] && y == destination[1]) return true; if (!visited[x][y]) { q.add(new int[]{x, y}); visited[x][y] = true; } } } return false; } }
1
0.834394
1
0.834394
game-dev
MEDIA
0.666369
game-dev,cli-devtools
0.904283
1
0.904283
bryful/F-s-PluginsProjects
7,478
sputteringRect/sputteringRect.cpp
//----------------------------------------------------------------------------------- /* F's Plugins for VS2010/VS2012 */ //----------------------------------------------------------------------------------- #include "sputteringRect.h" //----------------------------------------------------------------------------- static PF_Err ParamsSetup ( PF_InData *in_data, PF_OutData *out_data, PF_ParamDef *params[], PF_LayerDef *output) { PF_Err err = PF_Err_NONE; PF_ParamDef def; //----------------- AEFX_CLR_STRUCT(def); PF_ADD_SLIDER( UI_SEED, //p[^̖O 0, //l͂ꍇ̍ŏl 32000, //l͂ꍇ̍ől 0, //XC_[̍ŏl 144, //XC_[̍ől 0, //ftHg̒l ID_SEED ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_SLIDER( UI_VALUE, //p[^̖O 0, //l͂ꍇ̍ŏl 32000, //l͂ꍇ̍ől 0, //XC_[̍ŏl 100, //XC_[̍ől 20, //ftHg̒l ID_Y ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_FIXED( UI_OPA_RND, //p[^̖O 0, //l͂ꍇ̍ŏl 5, //l͂ꍇ̍ől 0, //XC_[̍ŏl 2, //XC_[̍ől 1, //ftHg̒l 2, //\鏬̌ 0, 0, ID_OPACITY_RAND ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_POINT( UI_TOPLEFT, 25, // X(%) 25, // Y(c%) FALSE, // TRUEȂ0.0100.0̒lɌ肳 ID_TOPLEFT ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_POINT( UI_BOTTOMRIGHT, 75, // X(%) 75, // Y(c%) FALSE, // TRUEȂ0.0100.0̒lɌ肳 ID_BOTTOMRIGHT ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_SLIDER( UI_POINT_VALUE, //p[^̖O 1, //l͂ꍇ̍ŏl 100, //l͂ꍇ̍ől 1, //XC_[̍ŏl 50, //XC_[̍ől 10, //ftHg̒l ID_POINT_VALUE ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_SLIDER( UI_POINT_LENGTH, //p[^̖O 5, //l͂ꍇ̍ŏl 1000, //l͂ꍇ̍ől 5, //XC_[̍ŏl 200, //XC_[̍ől 50, //ftHg̒l ID_POINT_LENGTH ); //----------------- //|bvAbv AEFX_CLR_STRUCT(def); PF_ADD_POPUP( UI_SIZE1, UI_SIZE_COUNT, //j[̐ UI_SIZE_DFLT, //ftHg UI_SIZE2, ID_SIZE ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_COLOR( UI_COLOR1, PF_MAX_CHAN8, // Red PF_MAX_CHAN8, //Green PF_MAX_CHAN8, //Blue ID_COLOR1 ); //----------------- //gsbN\̊Jn AEFX_CLR_STRUCT(def); def.flags = PF_ParamFlag_START_COLLAPSED; // PF_ADD_TOPIC( UI_COLOR_TOPIC, ID_COLOR_TOPIC ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_SLIDER( UI_COLOR_MAX, //p[^̖O 1, //l͂ꍇ̍ŏl UI_COLOR_MAX_V, //l͂ꍇ̍ől 1, //XC_[̍ŏl UI_COLOR_MAX_V, //XC_[̍ől 20, //ftHg̒l ID_COLOR_MAX ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_COLOR( UI_COLOR2, PF_MAX_CHAN8, // Red PF_MAX_CHAN8, //Green 0, //Blue ID_COLOR2 ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_COLOR( UI_COLOR3, PF_MAX_CHAN8, // Red 0, //Green PF_MAX_CHAN8, //Blue ID_COLOR3 ); //----------------- AEFX_CLR_STRUCT(def); PF_ADD_COLOR( UI_COLOR4, 0, // Red PF_MAX_CHAN8, //Green PF_MAX_CHAN8, //Blue ID_COLOR4 ); //----------------- //gsbN\̏I AEFX_CLR_STRUCT(def); PF_END_TOPIC(ID_COLOR_TOPIC_END); //----------------- //`FbN{bNX AEFX_CLR_STRUCT(def); PF_ADD_CHECKBOX(UI_ORG1, UI_ORG2, FALSE, 0, ID_ORG ); //----------------- out_data->num_params = ID_NUM_PARAMS; return err; } //------------------------------------------------------------------------------------------------- static PF_Err GetParams(CFsAE *ae, ParamInfo *infoP) { PF_Err err = PF_Err_NONE; ERR(ae->GetADD(ID_SEED,&infoP->seed)); ERR(ae->GetADD(ID_Y,&infoP->value)); ERR(ae->GetFIXED(ID_OPACITY_RAND,&infoP->opa)); PF_FixedPoint tl,br; ERR(ae->GetFIXEDPOINT(ID_TOPLEFT,&tl)); ERR(ae->GetFIXEDPOINT(ID_BOTTOMRIGHT,&br)); if (!err){ infoP->rect.left = tl.x >>16; infoP->rect.top = tl.y >>16; infoP->rect.right = br.x >>16; infoP->rect.bottom = br.y >>16; if(infoP->rect.left>infoP->rect.right) swapLong(&infoP->rect.left,&infoP->rect.right); if(infoP->rect.top>infoP->rect.bottom) swapLong(&infoP->rect.top,&infoP->rect.bottom); } ERR(ae->GetADD(ID_POINT_VALUE,&infoP->point_value)); ERR(ae->GetADD(ID_POINT_LENGTH,&infoP->point_length)); if (!err){ infoP->point_length = ae->downScale(infoP->point_length); if (infoP->point_length<2) infoP->point_length = 2; } ERR(ae->GetPOPUP(ID_SIZE,&infoP->size)); ERR(ae->GetADD(ID_COLOR_MAX,&infoP->color_max)); ERR(ae->GetCOLOR(ID_COLOR1,&infoP->colors[0])); ERR(ae->GetCOLOR(ID_COLOR2,&infoP->colors[1])); ERR(ae->GetCOLOR(ID_COLOR3,&infoP->colors[2])); ERR(ae->GetCOLOR(ID_COLOR4,&infoP->colors[3])); ERR(ae->GetCHECKBOX(ID_ORG,&infoP->org)); return err; } //------------------------------------------------------------------------------------------------- static PF_Err Exec (CFsAE *ae , ParamInfo *infoP) { PF_Err err = PF_Err_NONE; if (infoP->org == TRUE) { ERR( ae->CopyInToOut()); }else{ ERR(ae->out->clear()); } if (infoP->value>0){ CFsBuffer buf = ae->NewBuffer(SPD_RAND_MAX*sizeof(A_u_char));// + SPD_RAND_MAX if (buf.alive()==FALSE){ ae->out_data->out_flags |= PF_OutFlag_DISPLAY_ERROR_MESSAGE; err = PF_Err_INTERNAL_STRUCT_DAMAGED; return err; } infoP->sputRandTable = buf.bufA_u_char(); SetupSputData(infoP->size,infoP->sputRandTable); F_SRAND(infoP->seed); switch(ae->pixelFormat()) { case PF_PixelFormat_ARGB128: ERR(MainRender32(ae,infoP)); break; case PF_PixelFormat_ARGB64: ERR(MainRender16(ae,infoP)); break; case PF_PixelFormat_ARGB32: ERR(MainRender8(ae,infoP)); break; } buf.Dispose(); } return err; } //----------------------------------------------------------------------------- static PF_Err Render ( PF_InData *in_data, PF_OutData *out_data, PF_ParamDef *params[], PF_LayerDef *output ) { PF_Err err = PF_Err_NONE; PF_Handle pixelTable = NULL; CFsAE ae(in_data,out_data,params,output,ID_NUM_PARAMS); err =ae.resultErr(); if (!err){ ParamInfo info; ERR(GetParams(&ae,&info)); ERR(Exec(&ae,&info)); } return err; } //----------------------------------------------------------------------------------- /* SmartFXΉ̏ꍇA܂̊֐Ă΂ăp[^̊ls */ #if defined(SUPPORT_SMARTFX) static PF_Err PreRender( PF_InData *in_data, PF_OutData *out_data, PF_PreRenderExtra *extraP) { PF_Err err = PF_Err_NONE; CFsAE ae(in_data,out_data,extraP,sizeof(ParamInfo),ID_NUM_PARAMS); err = ae.resultErr(); if (!err){ ParamInfo *infoP = reinterpret_cast<ParamInfo*>(ae.LockPreRenderData()); if (infoP){ ae.SetHostPreRenderData(); ERR(GetParams(&ae,infoP)); ERR(ae.UnSetPreRenderData()); ae.UnlockPreRenderData(); }else{ err = PF_Err_OUT_OF_MEMORY; } } return err; } #endif //----------------------------------------------------------------------------------- #if defined(SUPPORT_SMARTFX) static PF_Err SmartRender( PF_InData *in_data, PF_OutData *out_data, PF_SmartRenderExtra *extraP) { PF_Err err = PF_Err_NONE, err2 = PF_Err_NONE; CFsAE ae(in_data,out_data,extraP,ID_NUM_PARAMS); err = ae.resultErr(); if (!err){ ParamInfo *infoP = reinterpret_cast<ParamInfo*>(ae.LockPreRenderData()); if (infoP){ ERR(Exec(&ae,infoP)); ERR2(ae.UnsetSmartRender()); ae.UnlockPreRenderData(); }else{ err = PF_Err_OUT_OF_MEMORY; } } return err; } #endif #include "Fs_Entry.h"
1
0.976921
1
0.976921
game-dev
MEDIA
0.207474
game-dev
0.98135
1
0.98135
ElunaLuaEngine/ElunaTrinityWotlk
37,690
src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "icecrown_citadel.h" #include "Containers.h" #include "Group.h" #include "InstanceScript.h" #include "MotionMaster.h" #include "ObjectAccessor.h" #include "Player.h" #include "QuestPools.h" #include "ScriptedCreature.h" #include "ScriptMgr.h" #include "SpellAuraEffects.h" #include "SpellInfo.h" #include "SpellScript.h" #include "TemporarySummon.h" enum DeathwhisperTexts { // Lady Deathwhisper SAY_INTRO_1 = 0, SAY_INTRO_2 = 1, SAY_INTRO_3 = 2, SAY_INTRO_4 = 3, SAY_INTRO_5 = 4, SAY_INTRO_6 = 5, SAY_INTRO_7 = 6, SAY_AGGRO = 7, SAY_PHASE_2 = 8, EMOTE_PHASE_2 = 9, SAY_DOMINATE_MIND = 10, SAY_DARK_EMPOWERMENT = 11, SAY_DARK_TRANSFORMATION = 12, SAY_ANIMATE_DEAD = 13, SAY_KILL = 14, SAY_BERSERK = 15, SAY_DEATH = 16, // Darnavan SAY_DARNAVAN_AGGRO = 0, SAY_DARNAVAN_RESCUED = 1, }; enum DeathwhisperSpells { // Lady Deathwhisper SPELL_MANA_BARRIER = 70842, SPELL_SHADOW_BOLT = 71254, SPELL_DEATH_AND_DECAY = 71001, SPELL_DOMINATE_MIND = 71289, SPELL_DOMINATE_MIND_SCALE = 71290, SPELL_FROSTBOLT = 71420, SPELL_FROSTBOLT_VOLLEY = 72905, SPELL_TOUCH_OF_INSIGNIFICANCE = 71204, SPELL_SUMMON_SHADE = 71363, SPELL_SHADOW_CHANNELING = 43897, SPELL_DARK_TRANSFORMATION_T = 70895, SPELL_DARK_EMPOWERMENT_T = 70896, SPELL_DARK_MARTYRDOM_T = 70897, SPELL_SUMMON_SPIRITS = 72478, // Achievement SPELL_FULL_HOUSE = 72827, // does not exist in dbc but still can be used for criteria check // Both Adds SPELL_TELEPORT_VISUAL = 41236, SPELL_CLEAR_ALL_DEBUFFS = 34098, SPELL_FULL_HEAL = 17683, SPELL_PERMANENT_FEIGN_DEATH = 70628, // Fanatics SPELL_DARK_TRANSFORMATION = 70900, SPELL_NECROTIC_STRIKE = 70659, SPELL_SHADOW_CLEAVE = 70670, SPELL_VAMPIRIC_MIGHT = 70674, SPELL_VAMPIRIC_MIGHT_PROC = 70677, SPELL_FANATIC_S_DETERMINATION = 71235, SPELL_DARK_MARTYRDOM_FANATIC = 71236, SPELL_DARK_MARTYRDOM_FANATIC_25N = 72495, SPELL_DARK_MARTYRDOM_FANATIC_10H = 72496, SPELL_DARK_MARTYRDOM_FANATIC_25H = 72497, // Adherents SPELL_DARK_EMPOWERMENT = 70901, SPELL_FROST_FEVER = 67767, SPELL_DEATHCHILL_BOLT = 70594, SPELL_DEATHCHILL_BLAST = 70906, SPELL_CURSE_OF_TORPOR = 71237, SPELL_SHROUD_OF_THE_OCCULT = 70768, SPELL_ADHERENT_S_DETERMINATION = 71234, SPELL_DARK_MARTYRDOM_ADHERENT = 70903, SPELL_DARK_MARTYRDOM_ADHERENT_25N = 72498, SPELL_DARK_MARTYRDOM_ADHERENT_10H = 72499, SPELL_DARK_MARTYRDOM_ADHERENT_25H = 72500, // Vengeful Shade SPELL_VENGEFUL_BLAST = 71544, SPELL_VENGEFUL_BLAST_PASSIVE = 71494, SPELL_VENGEFUL_BLAST_25N = 72010, SPELL_VENGEFUL_BLAST_10H = 72011, SPELL_VENGEFUL_BLAST_25H = 72012, // Darnavan SPELL_BLADESTORM = 65947, SPELL_CHARGE = 65927, SPELL_INTIMIDATING_SHOUT = 65930, SPELL_MORTAL_STRIKE = 65926, SPELL_SHATTERING_THROW = 65940, SPELL_SUNDER_ARMOR = 65936, }; enum DeathwhisperEvents { // Darnavan EVENT_DARNAVAN_BLADESTORM = 27, EVENT_DARNAVAN_CHARGE = 28, EVENT_DARNAVAN_INTIMIDATING_SHOUT = 29, EVENT_DARNAVAN_MORTAL_STRIKE = 30, EVENT_DARNAVAN_SHATTERING_THROW = 31, EVENT_DARNAVAN_SUNDER_ARMOR = 32, }; enum DeathwhisperPhases { PHASE_ALL = 0, PHASE_INTRO = 1, PHASE_ONE = 2, PHASE_TWO = 3 }; enum DeathwhisperGroups { GROUP_INTRO = 0, GROUP_ONE = 1, GROUP_TWO = 2 }; enum DeathwhisperMisc { NPC_DARNAVAN_10 = 38472, NPC_DARNAVAN_25 = 38485, NPC_DARNAVAN_CREDIT_10 = 39091, NPC_DARNAVAN_CREDIT_25 = 39092, ACTION_COMPLETE_QUEST = -384720, POINT_DESPAWN = 384721, }; enum DeathwhisperActions { ACTION_START_INTRO }; #define NPC_DARNAVAN RAID_MODE<uint32>(NPC_DARNAVAN_10, NPC_DARNAVAN_25, NPC_DARNAVAN_10, NPC_DARNAVAN_25) #define NPC_DARNAVAN_CREDIT RAID_MODE<uint32>(NPC_DARNAVAN_CREDIT_10, NPC_DARNAVAN_CREDIT_25, NPC_DARNAVAN_CREDIT_10, NPC_DARNAVAN_CREDIT_25) #define QUEST_DEPROGRAMMING RAID_MODE<uint32>(QUEST_DEPROGRAMMING_10, QUEST_DEPROGRAMMING_25, QUEST_DEPROGRAMMING_10, QUEST_DEPROGRAMMING_25) uint32 const SummonEntries[2] = {NPC_CULT_FANATIC, NPC_CULT_ADHERENT}; Position const SummonPositions[7] = { {-578.7066f, 2154.167f, 51.01529f, 1.692969f}, // 1 Left Door 1 (Cult Fanatic) {-598.9028f, 2155.005f, 51.01530f, 1.692969f}, // 2 Left Door 2 (Cult Adherent) {-619.2864f, 2154.460f, 51.01530f, 1.692969f}, // 3 Left Door 3 (Cult Fanatic) {-578.6996f, 2269.856f, 51.01529f, 4.590216f}, // 4 Right Door 1 (Cult Adherent) {-598.9688f, 2269.264f, 51.01529f, 4.590216f}, // 5 Right Door 2 (Cult Fanatic) {-619.4323f, 2268.523f, 51.01530f, 4.590216f}, // 6 Right Door 3 (Cult Adherent) {-524.2480f, 2211.920f, 62.90960f, 3.141592f}, // 7 Upper (Random Cultist) }; class DaranavanMoveEvent : public BasicEvent { public: DaranavanMoveEvent(Creature& darnavan) : _darnavan(darnavan) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _darnavan.GetMotionMaster()->MovePoint(POINT_DESPAWN, SummonPositions[6]); return true; } private: Creature& _darnavan; }; // 36855 - Lady Deathwhisper struct boss_lady_deathwhisper : public BossAI { boss_lady_deathwhisper(Creature* creature) : BossAI(creature, DATA_LADY_DEATHWHISPER), _dominateMindCount(RAID_MODE<uint8>(0, 1, 1, 3)) { Initialize(); } void Initialize() { _waveCounter = 0; _nextVengefulShadeTargetGUID.clear(); _cultistQueue.clear(); _darnavanGUID.Clear(); _phase = PHASE_ALL; scheduler.SetValidator([this] { return !(me->HasUnitState(UNIT_STATE_CASTING) && _phase != PHASE_INTRO); }); } void Reset() override { _Reset(); Initialize(); _phase = PHASE_ONE; DoCastSelf(SPELL_SHADOW_CHANNELING); me->SetPower(POWER_MANA, me->GetMaxPower(POWER_MANA)); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, false); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, false); } void DoAction(int32 action) override { if (action != ACTION_START_INTRO) return; Talk(SAY_INTRO_1); _phase = PHASE_INTRO; scheduler.Schedule(10s, GROUP_INTRO, [this](TaskContext context) { switch (context.GetRepeatCounter()) { case 0: Talk(SAY_INTRO_2); context.Repeat(21s); break; case 1: Talk(SAY_INTRO_3); context.Repeat(11s); break; case 2: Talk(SAY_INTRO_4); context.Repeat(9s); break; case 3: Talk(SAY_INTRO_5); context.Repeat(21s); break; case 4: Talk(SAY_INTRO_6); context.Repeat(10s); break; case 5: Talk(SAY_INTRO_7); return; default: break; } }); } void AttackStart(Unit* victim) override { if (me->HasUnitFlag(UNIT_FLAG_NON_ATTACKABLE)) return; if (victim && me->Attack(victim, true) && _phase != PHASE_ONE) me->GetMotionMaster()->MoveChase(victim); } void JustEngagedWith(Unit* who) override { if (!instance->CheckRequiredBosses(DATA_LADY_DEATHWHISPER, who->ToPlayer())) { EnterEvadeMode(EVADE_REASON_SEQUENCE_BREAK); instance->DoCastSpellOnPlayers(LIGHT_S_HAMMER_TELEPORT); return; } _phase = PHASE_ONE; me->SetCombatPulseDelay(5); me->setActive(true); DoZoneInCombat(); scheduler.CancelGroup(GROUP_INTRO); // phase-independent events scheduler .Schedule(10min, [this](TaskContext /*context*/) { DoCastSelf(SPELL_BERSERK); Talk(SAY_BERSERK); }) .Schedule(17s, [this](TaskContext death_and_decay) { if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_DEATH_AND_DECAY); death_and_decay.Repeat(22s, 30s); }); if (GetDifficulty() != RAID_DIFFICULTY_10MAN_NORMAL) scheduler.Schedule(27s, [this](TaskContext dominate_mind) { Talk(SAY_DOMINATE_MIND); std::list<Unit*> targets; SelectTargetList(targets, _dominateMindCount, SelectTargetMethod::Random, 0, 0.0f, true, false, -SPELL_DOMINATE_MIND); for (Unit* target : targets) DoCast(target, SPELL_DOMINATE_MIND); dominate_mind.Repeat(40s, 45s); }); // phase one only scheduler .Schedule(5s, GROUP_ONE, [this](TaskContext wave) { SummonWaveP1(); wave.Repeat(IsHeroic() ? 45s : 60s); }) .Schedule(2s, GROUP_ONE, [this](TaskContext shadow_bolt) { if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_SHADOW_BOLT); shadow_bolt.Repeat(2450ms, 3600ms); }) .Schedule(15s, GROUP_ONE, [this](TaskContext context) { DoImproveCultist(); context.Repeat(25s); }); Talk(SAY_AGGRO); DoStartNoMovement(who); me->RemoveAurasDueToSpell(SPELL_SHADOW_CHANNELING); DoCastSelf(SPELL_MANA_BARRIER, true); instance->SetBossState(DATA_LADY_DEATHWHISPER, IN_PROGRESS); } void JustDied(Unit* killer) override { Talk(SAY_DEATH); std::set<uint32> livingAddEntries; // Full House achievement for (SummonList::iterator itr = summons.begin(); itr != summons.end(); ++itr) if (Unit* unit = ObjectAccessor::GetUnit(*me, *itr)) if (unit->IsAlive() && unit->GetEntry() != NPC_VENGEFUL_SHADE) livingAddEntries.insert(unit->GetEntry()); if (livingAddEntries.size() >= 5) instance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_FULL_HOUSE, 0, me); if (Creature* darnavan = ObjectAccessor::GetCreature(*me, _darnavanGUID)) { if (darnavan->IsAlive()) { darnavan->SetFaction(FACTION_FRIENDLY); darnavan->CombatStop(true); darnavan->GetMotionMaster()->MoveIdle(); darnavan->SetReactState(REACT_PASSIVE); darnavan->m_Events.AddEvent(new DaranavanMoveEvent(*darnavan), darnavan->m_Events.CalculateTime(10s)); darnavan->AI()->Talk(SAY_DARNAVAN_RESCUED); if (!killer) return; if (Player* owner = killer->GetCharmerOrOwnerPlayerOrPlayerItself()) { if (Group* group = owner->GetGroup()) { for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) if (member->IsInMap(owner)) member->KilledMonsterCredit(NPC_DARNAVAN_CREDIT); } else owner->KilledMonsterCredit(NPC_DARNAVAN_CREDIT); } } } _JustDied(); } void EnterEvadeMode(EvadeReason /*why*/) override { scheduler.CancelAll(); summons.DespawnAll(); if (Creature* darnavan = ObjectAccessor::GetCreature(*me, _darnavanGUID)) darnavan->DespawnOrUnsummon(); _DespawnAtEvade(); } void KilledUnit(Unit* victim) override { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void DamageTaken(Unit* /*damageDealer*/, uint32& damage, DamageEffectType /*damageType*/, SpellInfo const* /*spellInfo = nullptr*/) override { // phase transition if (_phase == PHASE_ONE && damage > me->GetPower(POWER_MANA)) { _phase = PHASE_TWO; Talk(SAY_PHASE_2); Talk(EMOTE_PHASE_2); DoStartMovement(me->GetVictim()); ResetThreatList(); damage -= me->GetPower(POWER_MANA); me->SetPower(POWER_MANA, 0); me->RemoveAurasDueToSpell(SPELL_MANA_BARRIER); scheduler.CancelGroup(GROUP_ONE); scheduler .Schedule(12s, GROUP_TWO, [this](TaskContext frostbolt) { DoCastVictim(SPELL_FROSTBOLT); frostbolt.Repeat(); }) .Schedule(20s, GROUP_TWO, [this](TaskContext frostboldVolley) { DoCastAOE(SPELL_FROSTBOLT_VOLLEY); frostboldVolley.Repeat(); }) .Schedule(6s, 9s, GROUP_TWO, [this](TaskContext touch) { if (me->GetVictim()) me->AddAura(SPELL_TOUCH_OF_INSIGNIFICANCE, me->EnsureVictim()); touch.Repeat(); }) .Schedule(12s, GROUP_TWO, [this](TaskContext summonShade) { CastSpellExtraArgs args; args.AddSpellMod(SPELLVALUE_MAX_TARGETS, Is25ManRaid() ? 2 : 1); me->CastSpell(nullptr, SPELL_SUMMON_SPIRITS, args); summonShade.Repeat(); }); // on heroic mode Lady Deathwhisper is immune to taunt effects in phase 2 and continues summoning adds if (IsHeroic()) { me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true); scheduler.Schedule(0s, GROUP_TWO, [this](TaskContext context) { SummonWaveP2(); context.Repeat(45s); }); } } } void SpellHitTarget(WorldObject* target, SpellInfo const* spellInfo) override { if (spellInfo->Id == SPELL_SUMMON_SPIRITS) _nextVengefulShadeTargetGUID.push_back(target->GetGUID()); } void JustSummoned(Creature* summon) override { switch (summon->GetEntry()) { case NPC_DARNAVAN_10: case NPC_DARNAVAN_25: _darnavanGUID = summon->GetGUID(); summon->AI()->AttackStart(SelectTarget(SelectTargetMethod::Random)); return; case NPC_VENGEFUL_SHADE: if (_nextVengefulShadeTargetGUID.empty()) break; summon->AI()->SetGUID(_nextVengefulShadeTargetGUID.front()); _nextVengefulShadeTargetGUID.pop_front(); break; case NPC_CULT_ADHERENT: case NPC_CULT_FANATIC: _cultistQueue.push_back(summon->GetGUID()); summon->AI()->AttackStart(SelectTarget(SelectTargetMethod::Random)); break; default: break; } summons.Summon(summon); } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && _phase != PHASE_INTRO) return; scheduler.Update(diff, [this] { // We should not melee attack when barrier is up if (!me->HasAura(SPELL_MANA_BARRIER)) DoMeleeAttackIfReady(); }); } // summoning function for first phase void SummonWaveP1() { uint8 addIndex = _waveCounter & 1; uint8 addIndexOther = uint8(addIndex ^ 1); // Summon first add, replace it with Darnavan if weekly quest is active if (_waveCounter || !sQuestPoolMgr->IsQuestActive(QUEST_DEPROGRAMMING)) Summon(SummonEntries[addIndex], SummonPositions[addIndex * 3]); else Summon(NPC_DARNAVAN, SummonPositions[addIndex * 3]); Summon(SummonEntries[addIndexOther], SummonPositions[addIndex * 3 + 1]); Summon(SummonEntries[addIndex], SummonPositions[addIndex * 3 + 2]); if (Is25ManRaid()) { Summon(SummonEntries[addIndexOther], SummonPositions[addIndexOther * 3]); Summon(SummonEntries[addIndex], SummonPositions[addIndexOther * 3 + 1]); Summon(SummonEntries[addIndexOther], SummonPositions[addIndexOther * 3 + 2]); Summon(SummonEntries[urand(0, 1)], SummonPositions[6]); } ++_waveCounter; } // summoning function for second phase void SummonWaveP2() { if (Is25ManRaid()) { uint8 addIndex = _waveCounter & 1; Summon(SummonEntries[addIndex], SummonPositions[addIndex * 3]); Summon(SummonEntries[addIndex ^ 1], SummonPositions[addIndex * 3 + 1]); Summon(SummonEntries[addIndex], SummonPositions[addIndex * 3+ 2]); } else Summon(SummonEntries[urand(0, 1)], SummonPositions[6]); ++_waveCounter; } // helper for summoning wave mobs void Summon(uint32 entry, Position const& pos) { if (TempSummon* summon = me->SummonCreature(entry, pos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 10s)) summon->CastSpell(summon, SPELL_TELEPORT_VISUAL); } void SummonedCreatureDies(Creature* summon, Unit* /*killer*/) override { if (summon->GetEntry() == NPC_CULT_ADHERENT || summon->GetEntry() == NPC_CULT_FANATIC) _cultistQueue.remove(summon->GetGUID()); } void DoImproveCultist() { if (_cultistQueue.empty()) return; _cultistGUID = Trinity::Containers::SelectRandomContainerElement(_cultistQueue); _cultistQueue.remove(_cultistGUID); Creature* cultist = ObjectAccessor::GetCreature(*me, _cultistGUID); if (!cultist) return; if (RAND(0,1)) me->CastSpell(cultist, SPELL_DARK_MARTYRDOM_T); else { me->CastSpell(cultist, cultist->GetEntry() == NPC_CULT_FANATIC ? SPELL_DARK_TRANSFORMATION_T : SPELL_DARK_EMPOWERMENT_T, true); Talk(uint8(cultist->GetEntry() == NPC_CULT_FANATIC ? SAY_DARK_TRANSFORMATION : SAY_DARK_EMPOWERMENT)); } } private: ObjectGuid _darnavanGUID; ObjectGuid _cultistGUID; GuidList _cultistQueue; GuidList _nextVengefulShadeTargetGUID; uint32 _waveCounter; uint8 const _dominateMindCount; uint8 _phase; }; /* 37890 - Cult Fanatic 38009 - Reanimated Fanatic 38135 - Deformed Fanatic */ struct npc_cult_fanatic : public ScriptedAI { npc_cult_fanatic(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { } void Reset() override { _scheduler.CancelAll(); _scheduler .SetValidator([this] { return !me->HasUnitState(UNIT_STATE_CASTING); }) .Schedule(17s, [this](TaskContext vampiric_might) { DoCastSelf(SPELL_VAMPIRIC_MIGHT); vampiric_might.Repeat(25s); }) .Schedule(12s, [this](TaskContext shadow_cleave) { DoCastVictim(SPELL_SHADOW_CLEAVE); shadow_cleave.Repeat(14s); }) .Schedule(10s, [this](TaskContext necrotic_strike) { DoCastVictim(SPELL_NECROTIC_STRIKE); necrotic_strike.Repeat(17s); }); } void SpellHit(WorldObject* /*caster*/, SpellInfo const* spellInfo) override { switch (spellInfo->Id) { case SPELL_DARK_TRANSFORMATION_T: me->InterruptNonMeleeSpells(true); DoCastSelf(SPELL_DARK_TRANSFORMATION); break; case SPELL_DARK_TRANSFORMATION: DoCastSelf(SPELL_FULL_HEAL); me->UpdateEntry(NPC_DEFORMED_FANATIC); break; case SPELL_DARK_MARTYRDOM_T: me->SetReactState(REACT_PASSIVE); me->InterruptNonMeleeSpells(true); me->AttackStop(); DoCastSelf(SPELL_DARK_MARTYRDOM_FANATIC); break; case SPELL_DARK_MARTYRDOM_FANATIC: case SPELL_DARK_MARTYRDOM_FANATIC_25N: case SPELL_DARK_MARTYRDOM_FANATIC_10H: case SPELL_DARK_MARTYRDOM_FANATIC_25H: _scheduler .Schedule(2s, [this](TaskContext /*context*/) { me->UpdateEntry(NPC_REANIMATED_FANATIC); DoCastSelf(SPELL_PERMANENT_FEIGN_DEATH); DoCastSelf(SPELL_CLEAR_ALL_DEBUFFS); DoCastSelf(SPELL_FULL_HEAL, true); me->SetUnitFlag(UNIT_FLAG_UNINTERACTIBLE); }) .Schedule(6s, [this](TaskContext /*context*/) { me->RemoveAurasDueToSpell(SPELL_PERMANENT_FEIGN_DEATH); me->RemoveUnitFlag(UNIT_FLAG_UNINTERACTIBLE); me->SetReactState(REACT_AGGRESSIVE); DoZoneInCombat(me); if (Creature* ladyDeathwhisper = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_LADY_DEATHWHISPER))) ladyDeathwhisper->AI()->Talk(SAY_ANIMATE_DEAD); }); break; default: break; } } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && !me->HasAura(SPELL_PERMANENT_FEIGN_DEATH)) return; _scheduler.Update(diff, [this] { DoMeleeAttackIfReady(); }); } protected: TaskScheduler _scheduler; InstanceScript* _instance; }; /* 37949 - Cult Adherent 38010 - Reanimated Adherent 38136 - Empowered Adherent */ struct npc_cult_adherent : public ScriptedAI { npc_cult_adherent(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { } void Reset() override { _scheduler.CancelAll(); _scheduler .SetValidator([this] { return !me->HasUnitState(UNIT_STATE_CASTING); }) .Schedule(5s, [this](TaskContext deathchill) { if (me->GetEntry() == NPC_EMPOWERED_ADHERENT) DoCastVictim(SPELL_DEATHCHILL_BLAST); else DoCastVictim(SPELL_DEATHCHILL_BOLT); deathchill.Repeat(2500ms); }) .Schedule(15s, [this](TaskContext shroud_of_the_occult) { DoCastSelf(SPELL_SHROUD_OF_THE_OCCULT); shroud_of_the_occult.Repeat(10s); }) .Schedule(15s, [this](TaskContext curse_of_torpor) { if (Unit* target = SelectTarget(SelectTargetMethod::Random, 1)) DoCast(target, SPELL_CURSE_OF_TORPOR); curse_of_torpor.Repeat(18s); }); } void SpellHit(WorldObject* /*caster*/, SpellInfo const* spellInfo) override { switch (spellInfo->Id) { case SPELL_DARK_EMPOWERMENT_T: me->UpdateEntry(NPC_EMPOWERED_ADHERENT); break; case SPELL_DARK_MARTYRDOM_T: me->SetReactState(REACT_PASSIVE); me->InterruptNonMeleeSpells(true); me->AttackStop(); DoCastSelf(SPELL_DARK_MARTYRDOM_ADHERENT); break; case SPELL_DARK_MARTYRDOM_ADHERENT: case SPELL_DARK_MARTYRDOM_ADHERENT_25N: case SPELL_DARK_MARTYRDOM_ADHERENT_10H: case SPELL_DARK_MARTYRDOM_ADHERENT_25H: _scheduler .Schedule(2s, [this](TaskContext /*context*/) { me->UpdateEntry(NPC_REANIMATED_ADHERENT); DoCastSelf(SPELL_PERMANENT_FEIGN_DEATH); DoCastSelf(SPELL_CLEAR_ALL_DEBUFFS); DoCastSelf(SPELL_FULL_HEAL, true); me->SetUnitFlag(UNIT_FLAG_UNINTERACTIBLE); }) .Schedule(6s, [this](TaskContext /*context*/) { me->RemoveAurasDueToSpell(SPELL_PERMANENT_FEIGN_DEATH); me->RemoveUnitFlag(UNIT_FLAG_UNINTERACTIBLE); me->SetReactState(REACT_AGGRESSIVE); DoCastSelf(SPELL_SHROUD_OF_THE_OCCULT); DoZoneInCombat(me); if (Creature* ladyDeathwhisper = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_LADY_DEATHWHISPER))) ladyDeathwhisper->AI()->Talk(SAY_ANIMATE_DEAD); }); break; default: break; } } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && !me->HasAura(SPELL_PERMANENT_FEIGN_DEATH)) return; _scheduler.Update(diff); } protected: TaskScheduler _scheduler; InstanceScript* _instance; }; // 38222 - Vengeful Shade struct npc_vengeful_shade : public ScriptedAI { npc_vengeful_shade(Creature* creature) : ScriptedAI(creature) { } void Reset() override { me->SetReactState(REACT_PASSIVE); me->AddAura(SPELL_VENGEFUL_BLAST_PASSIVE, me); _scheduler .Schedule(2s, [this](TaskContext /*context*/) { me->SetReactState(REACT_AGGRESSIVE); me->AI()->AttackStart(ObjectAccessor::GetUnit(*me, _targetGUID)); }) .Schedule(7s, [this](TaskContext /*context*/) { me->KillSelf(); }); } void SetGUID(ObjectGuid const& guid, int32 /*id*/) override { _targetGUID = guid; } void SpellHitTarget(WorldObject* /*target*/, SpellInfo const* spellInfo) override { switch (spellInfo->Id) { case SPELL_VENGEFUL_BLAST: case SPELL_VENGEFUL_BLAST_25N: case SPELL_VENGEFUL_BLAST_10H: case SPELL_VENGEFUL_BLAST_25H: me->KillSelf(); break; default: break; } } void UpdateAI(uint32 diff) override { _scheduler.Update(diff, [this] { DoMeleeAttackIfReady(); }); } private: TaskScheduler _scheduler; ObjectGuid _targetGUID; }; // 38472, 38485 - Darnavan struct npc_darnavan : public ScriptedAI { npc_darnavan(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { _canCharge = true; _canShatter = true; } void Reset() override { _events.Reset(); _events.ScheduleEvent(EVENT_DARNAVAN_BLADESTORM, 10s); _events.ScheduleEvent(EVENT_DARNAVAN_INTIMIDATING_SHOUT, 20s, 25s); _events.ScheduleEvent(EVENT_DARNAVAN_MORTAL_STRIKE, 25s, 30s); _events.ScheduleEvent(EVENT_DARNAVAN_SUNDER_ARMOR, 5s, 8s); Initialize(); } void JustDied(Unit* killer) override { _events.Reset(); if (!killer) return; if (Player* owner = killer->GetCharmerOrOwnerPlayerOrPlayerItself()) { if (Group* group = owner->GetGroup()) { for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) if (member->IsInMap(owner)) member->FailQuest(QUEST_DEPROGRAMMING); } else owner->FailQuest(QUEST_DEPROGRAMMING); } } void MovementInform(uint32 type, uint32 id) override { if (type != POINT_MOTION_TYPE || id != POINT_DESPAWN) return; me->DespawnOrUnsummon(); } void JustEngagedWith(Unit* /*victim*/) override { Talk(SAY_DARNAVAN_AGGRO); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (_canShatter && me->GetVictim() && me->EnsureVictim()->IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL)) { DoCastVictim(SPELL_SHATTERING_THROW); _canShatter = false; _events.ScheduleEvent(EVENT_DARNAVAN_SHATTERING_THROW, 30s); return; } if (_canCharge && !me->IsWithinMeleeRange(me->GetVictim())) { DoCastVictim(SPELL_CHARGE); _canCharge = false; _events.ScheduleEvent(EVENT_DARNAVAN_CHARGE, 20s); return; } while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_DARNAVAN_BLADESTORM: DoCast(SPELL_BLADESTORM); _events.ScheduleEvent(EVENT_DARNAVAN_BLADESTORM, 90s, 100s); break; case EVENT_DARNAVAN_CHARGE: _canCharge = true; break; case EVENT_DARNAVAN_INTIMIDATING_SHOUT: DoCast(SPELL_INTIMIDATING_SHOUT); _events.ScheduleEvent(EVENT_DARNAVAN_INTIMIDATING_SHOUT, 90s, 2min); break; case EVENT_DARNAVAN_MORTAL_STRIKE: DoCastVictim(SPELL_MORTAL_STRIKE); _events.ScheduleEvent(EVENT_DARNAVAN_MORTAL_STRIKE, 15s, 30s); break; case EVENT_DARNAVAN_SHATTERING_THROW: _canShatter = true; break; case EVENT_DARNAVAN_SUNDER_ARMOR: DoCastVictim(SPELL_SUNDER_ARMOR); _events.ScheduleEvent(EVENT_DARNAVAN_SUNDER_ARMOR, 3s, 7s); break; } } DoMeleeAttackIfReady(); } private: EventMap _events; bool _canCharge; bool _canShatter; }; // 70842 - Mana Barrier class spell_deathwhisper_mana_barrier : public AuraScript { PrepareAuraScript(spell_deathwhisper_mana_barrier); void HandlePeriodicTick(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); if (Unit* caster = GetCaster()) { int32 missingHealth = int32(caster->GetMaxHealth() - caster->GetHealth()); caster->ModifyHealth(missingHealth); caster->ModifyPower(POWER_MANA, -missingHealth); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_deathwhisper_mana_barrier::HandlePeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; // 71289 - Dominate Mind class spell_deathwhisper_dominated_mind : public AuraScript { PrepareAuraScript(spell_deathwhisper_dominated_mind); bool Validate(SpellInfo const* /*spell*/) override { return ValidateSpellInfo({ SPELL_DOMINATE_MIND_SCALE }); } void HandleApply(AuraEffect const* /*eff*/, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); target->CastSpell(target, SPELL_DOMINATE_MIND_SCALE, true); } void Register() override { AfterEffectApply += AuraEffectApplyFn(spell_deathwhisper_dominated_mind::HandleApply, EFFECT_0, SPELL_AURA_AOE_CHARM, AURA_EFFECT_HANDLE_REAL); } }; // 72478 - Summon Spirits class spell_deathwhisper_summon_spirits : public SpellScript { PrepareSpellScript(spell_deathwhisper_summon_spirits); bool Validate(SpellInfo const* /*spell*/) override { return ValidateSpellInfo({ SPELL_SUMMON_SHADE }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) { GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_SHADE, true); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_deathwhisper_summon_spirits::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_DUMMY); } }; // 70674 - Vampiric Might class spell_deathwhisper_vampiric_might : public AuraScript { PrepareAuraScript(spell_deathwhisper_vampiric_might); bool Validate(SpellInfo const* /*spell*/) override { return ValidateSpellInfo({ SPELL_VAMPIRIC_MIGHT_PROC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); DamageInfo* damageInfo = eventInfo.GetDamageInfo(); if (!damageInfo || !damageInfo->GetDamage()) return; Unit* target = GetTarget(); uint32 damage = damageInfo->GetDamage(); ApplyPct(damage, aurEff->GetAmount()); CastSpellExtraArgs args(aurEff); args.AddSpellBP0(damage); target->CastSpell(target, SPELL_VAMPIRIC_MIGHT_PROC, args); } void Register() override { OnEffectProc += AuraEffectProcFn(spell_deathwhisper_vampiric_might::HandleProc, EFFECT_1, SPELL_AURA_DUMMY); } }; // 69483 - Dark Reckoning class spell_deathwhisper_dark_reckoning : public AuraScript { PrepareAuraScript(spell_deathwhisper_dark_reckoning); bool Validate(SpellInfo const* spell) override { return ValidateSpellInfo({ spell->GetEffect(EFFECT_0).TriggerSpell }); } void OnPeriodic(AuraEffect const* aurEff) { PreventDefaultAction(); if (Unit* caster = GetCaster()) { uint32 spellId = GetSpellInfo()->GetEffect(EFFECT_0).TriggerSpell; caster->CastSpell(GetTarget(), spellId, aurEff); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_deathwhisper_dark_reckoning::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; class at_lady_deathwhisper_entrance : public OnlyOnceAreaTriggerScript { public: at_lady_deathwhisper_entrance() : OnlyOnceAreaTriggerScript("at_lady_deathwhisper_entrance") { } bool TryHandleOnce(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override { if (InstanceScript* instance = player->GetInstanceScript()) if (instance->GetBossState(DATA_LADY_DEATHWHISPER) != DONE) if (Creature* ladyDeathwhisper = ObjectAccessor::GetCreature(*player, instance->GetGuidData(DATA_LADY_DEATHWHISPER))) ladyDeathwhisper->AI()->DoAction(ACTION_START_INTRO); return true; } }; void AddSC_boss_lady_deathwhisper() { // Creatures RegisterIcecrownCitadelCreatureAI(boss_lady_deathwhisper); RegisterIcecrownCitadelCreatureAI(npc_cult_fanatic); RegisterIcecrownCitadelCreatureAI(npc_cult_adherent); RegisterIcecrownCitadelCreatureAI(npc_vengeful_shade); RegisterIcecrownCitadelCreatureAI(npc_darnavan); // Spells RegisterSpellScript(spell_deathwhisper_mana_barrier); RegisterSpellScript(spell_deathwhisper_dominated_mind); RegisterSpellScript(spell_deathwhisper_summon_spirits); RegisterSpellScript(spell_deathwhisper_vampiric_might); RegisterSpellScript(spell_deathwhisper_dark_reckoning); // AreaTriggers new at_lady_deathwhisper_entrance(); }
1
0.966824
1
0.966824
game-dev
MEDIA
0.983983
game-dev
0.925242
1
0.925242
dermow/TraXile
167,629
TraXile/TrX_CoreLogic.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; using log4net; using Microsoft.Data.Sqlite; namespace TraXile { public delegate void Trx_GenericEventHandler(TrX_CoreLogicGenericEventArgs e); public delegate void TrX_ActivityEventHandler(TrX_CoreLogicActivityEventArgs e); public class TrX_CoreLogicGenericEventArgs : EventArgs { // Core logic private readonly TrX_CoreLogic _logic; public TrX_CoreLogic Logic => _logic; public TrX_CoreLogicGenericEventArgs(TrX_CoreLogic logic) { _logic = logic; } } public class TrX_CoreLogicActivityEventArgs : EventArgs { // Core logic private readonly TrX_CoreLogic _logic; public TrX_CoreLogic Logic => _logic; // Activity private readonly TrX_TrackedActivity _activity; public TrX_TrackedActivity Activity => _activity; public TrX_CoreLogicActivityEventArgs(TrX_CoreLogic logic, TrX_TrackedActivity activity) { _logic = logic; _activity = activity; } } public class TrX_CoreLogic { // Event: initialization of history is finished public event Trx_GenericEventHandler OnHistoryInitialized; // Event: called when an activity is finished public event TrX_ActivityEventHandler OnActivityFinished; // Event: called when tags are changed public event Trx_GenericEventHandler OnTagsUpdated; // Event: Activity started public event TrX_ActivityEventHandler OnActivityStarted; // DateTime format info for enforcing specific calendar info public DateTimeFormatInfo _dateTimeFormatInfo; // Exit switch private bool _exit; // Flag if logic has been started private bool _StartedFlag = false; // Flag if next area is an expedition area private bool _nextAreaIsExp = false; // IP and port of the current instance, for identifiing activity changes private string _currentInstanceEndpoint; // Last known endoint of simulacrum private string _lastSimuEndpoint; // Level of the next area private int _nextAreaLevel; // seed of next area private long _nextAreaSeed; // Hash code of the last known logfile line private int _lastHash = 0; // Flag if history is initialized (logfile read finished) private bool _historyInitialized; // Dictionary of known hashes private Dictionary<int, string> _dict; // List of known player names (used for death calc) private List<string> _knownPlayerNames; // List of lab names private List<string> labs; // Event mapping (Logpattern <-> Event Type) private TrX_EventMapping _eventMapping; // Default mappings private TrX_DefaultMappings _defaultMappings; // EventQ private ConcurrentQueue<TrX_TrackingEvent> _eventQueue; // Thread for logfile parsing private Thread _logParseThread; // Thrad for handling events generated by log parse Thread private Thread _eventThread; // Time of app init start private DateTime _initStartTime; // Time of app init end private DateTime _initEndTime; // DateTime of the current Hideout tracking block private DateTime _hoStart; // Flag if tracking of a hideout block is currently active private bool _trackingHO; // ID list of already parsed Activities private List<string> _parsedActivities; // Log handler private ILog _log; // Path to Client.txt file private string _clientTxtPath; // Property: List of Tags private List<TrX_ActivityTag> _tags; public List<TrX_ActivityTag> Tags => _tags; // Property: Current Activity public TrX_TrackedActivity _currentActivity; public TrX_TrackedActivity CurrentActivity { get { return _currentActivity; } set { _currentActivity = value; } } // Property: Event History private List<TrX_TrackedActivity> _eventHistory; public List<TrX_TrackedActivity> ActivityHistory => _eventHistory; // Property: EventQ initialized private bool _eventQueueInitizalized; public bool EventQueueInitialized => _eventQueueInitizalized; // Property: LogLines total private double _logLinesTotal; public double LogLinesTotal => _logLinesTotal; // Property: LogLines read private double _logLinesRead; public double LogLinesRead => _logLinesRead; // Property: Is current map zana private bool _isMapZana; public bool IsMapZana => _isMapZana; // Property: Is current map vaal area private bool _isMapVaalArea; public bool IsMapVaalArea => _isMapVaalArea; // Property: Is current map black knight fight private bool _isBlackKnightFight; public bool IsBlackKnightFight => _isBlackKnightFight; // Property: Is current map sanctum private bool _isMapSanctum; public bool IsMapSanctum => _isMapSanctum; // Property: Is current map logbook private bool _isMapLogbookSide; public bool IsMapLogbookSide => _isMapLogbookSide; // Property: Is current map labtrial private bool _isMapLabTrial; public bool IsMapLabTrial => _isMapLabTrial; // Property: Is current area abyss area private bool _isMapAbyssArea; public bool IsMapAbyssArea => _isMapAbyssArea; // Property: Current Area private string _currentArea; public string CurrentArea => _currentArea; // Property: Current Area Level private int _currentAreaLevel; private long _currentAreaSeed; public int CurrentAreaLevel => _currentAreaLevel; // Property: Previous activity in overlay private TrX_TrackedActivity _prevActivityOverlay; public TrX_TrackedActivity OverlayPrevActivity => _prevActivityOverlay; // Property: DB Manager private TrX_DataBackend _dataBackend; public TrX_DataBackend Database => _dataBackend; // Property: Statistics manager private TrX_StatsManager _myStats; public TrX_StatsManager Stats => _myStats; // Property: Long stat names private Dictionary<string, string> _statNamesLong; public Dictionary<string, string> StatNamesLong => _statNamesLong; // Property: Path to Client.txt public string ClientTxtPath { get { return _clientTxtPath; } set { _clientTxtPath = value; } } // Property Minimum activity cap private int _timeCapMin = 0; public int MinimumCap { get { return _timeCapMin; } set { _timeCapMin = value; } } /// <summary> /// Main Window Constructor /// </summary> public TrX_CoreLogic(int minTimeCap = 0) { _timeCapMin = minTimeCap; Init(); } /// <summary> /// Do main initialization /// ONLY CALL ONCE! S /// </summary> private void Init() { // Fixing the DateTimeFormatInfo to Gregorian Calendar, to avoid wrong timestamps with other calendars _dateTimeFormatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("en-CA")); _dateTimeFormatInfo.Calendar = new GregorianCalendar(); _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); _eventMapping = new TrX_EventMapping(); _defaultMappings = new TrX_DefaultMappings(); _parsedActivities = new List<string>(); _dict = new Dictionary<int, string>(); _eventQueue = new ConcurrentQueue<TrX_TrackingEvent>(); _eventHistory = new List<TrX_TrackedActivity>(); _knownPlayerNames = new List<string>(); _currentArea = "None"; _eventQueueInitizalized = false; _lastSimuEndpoint = ""; _tags = new List<TrX_ActivityTag>(); _initStartTime = DateTime.Now; _dataBackend = new TrX_DataBackend(TrX_Static.DB_PATH, ref _log); _myStats = new TrX_StatsManager(_dataBackend); InitDefaultTags(); InitNumStats(); ReadKnownPlayers(); LoadTags(); SaveVersion(); _eventQueue.Enqueue(new TrX_TrackingEvent(EVENT_TYPES.APP_STARTED) { EventTime = DateTime.Now, LogLine = "Application started." }); // Since 0.9.2 stats cache is DB only, do first import if file is still existing if (File.Exists(TrX_Static.CACHE_PATH)) { // Import is only needed when last hash is not in kvstore string last = _dataBackend.GetKVStoreValue("last_hash"); last = null; if (string.IsNullOrEmpty(last)) { _log.Info("File 'stats.cache' found wich is deprecated -> importing to database."); string firstLine; firstLine = File.ReadAllLines(TrX_Static.CACHE_PATH).First(); if (!string.IsNullOrEmpty(firstLine)) { try { int hash = Convert.ToInt32(firstLine.Split(';')[1]); _dataBackend.SetKVStoreValue("last_hash", hash.ToString()); _log.Info("Successfully imported stats.cache to database."); File.Delete(TrX_Static.CACHE_PATH); } catch (Exception ex) { _log.Warn("Error importing last hash from file, skipping."); _log.Debug(ex.ToString()); } } } } ReadStatsCache(); if (!_historyInitialized) { ReadActivityLogFromSQLite(); } // Thread for Log Parsing and Enqueuing _logParseThread = new Thread(new ThreadStart(LogParsing)) { Name = "ParserThread", IsBackground = true }; // Thread for Queue processing / Dequeuing _eventThread = new Thread(new ThreadStart(EventHandling)) { Name = "WorkerThread", IsBackground = true }; _log.Info("Core logic initialized."); } public bool CheckForValidClientLogFile(string path) { if (!File.Exists(path)) { _log.Error($"Configured Client.txt not found: {path}"); return false; } return true; } /// <summary> /// Start logfile parsing and event handling /// </summary> public void Start() { _logParseThread.Start(); _eventThread.Start(); _log.Info("Core logic started."); } /// <summary> /// Stop logic /// </summary> /// <param name="timeout">timeout to wait for exit</param> public void Stop(int timeout = 2000) { _exit = true; int i = 0; // Wait for threads to finish while (_eventThread.IsAlive || _logParseThread.IsAlive) { Thread.Sleep(1); i++; if (i > timeout) { break; } } if (_eventThread.IsAlive) { _eventThread.Abort(); } if (_logParseThread.IsAlive) { _logParseThread.Abort(); } } /// <summary> /// Read the statistics cache /// </summary> private bool ReadStatsCache() { SqliteDataReader dataReader; // Read last hash _lastHash = Convert.ToInt32(_dataBackend.GetKVStoreValue("last_hash")); // Read last stat vaules List<string> stats = new List<string>(); foreach (KeyValuePair<string, int> kvp in _myStats.NumericStats) { stats.Add(kvp.Key); } foreach (string s in stats) { dataReader = _dataBackend.GetSQLReader($"select stat_value from tx_stats where stat_name ='{s}' order by timestamp desc limit 1"); while (dataReader.Read()) { _myStats.NumericStats[s] = dataReader.GetInt32(0); } } return true; } /// <summary> /// Write the statistics cache /// </summary> private void SaveStatsCache() { // DB _dataBackend.SetKVStoreValue("last_hash", _lastHash.ToString()); } /// <summary> /// Initialize all default tags /// </summary> private void InitDefaultTags() { List<TrX_ActivityTag> tmpTags; tmpTags = new List<TrX_ActivityTag> { new TrX_ActivityTag("blight") { BackColor = Color.LightGreen, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("delirium") { BackColor = Color.WhiteSmoke, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("einhar") { BackColor = Color.Red, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("incursion") { BackColor = Color.GreenYellow, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("syndicate") { BackColor = Color.Gold, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("zana") { BackColor = Color.Blue, ForeColor = Color.White, ShowInListView = true }, new TrX_ActivityTag("niko") { BackColor = Color.OrangeRed, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("zana-map") { BackColor = Color.Blue, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("seer") { BackColor = Color.Red, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("mist") { BackColor = Color.Red, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("memory") { BackColor = Color.Red, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("expedition") { BackColor = Color.Turquoise, ForeColor = Color.Black, ShowInListView = true }, new TrX_ActivityTag("rog") { BackColor = Color.Turquoise, ForeColor = Color.Black }, new TrX_ActivityTag("gwennen") { BackColor = Color.Turquoise, ForeColor = Color.Black }, new TrX_ActivityTag("dannig") { BackColor = Color.Turquoise, ForeColor = Color.Black }, new TrX_ActivityTag("tujen") { BackColor = Color.Turquoise, ForeColor = Color.Black }, new TrX_ActivityTag("karst") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("tibbs") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("isla") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("tullina") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("niles") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("nenet") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("vinderi") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("gianna") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("huck") { BackColor = Color.IndianRed, ForeColor = Color.Black }, new TrX_ActivityTag("vaal-area") { BackColor = Color.DarkRed, ForeColor = Color.White }, new TrX_ActivityTag("lab-trial") { BackColor = Color.DarkTurquoise, ForeColor = Color.Black }, new TrX_ActivityTag("abyss-depths") { BackColor = Color.ForestGreen, ForeColor = Color.Black }, new TrX_ActivityTag("exp-side-area") { BackColor = Color.Turquoise, ForeColor = Color.Black }, new TrX_ActivityTag("twice-blessed") { BackColor = Color.DarkTurquoise, ForeColor = Color.Black }, new TrX_ActivityTag("harvest") { BackColor = Color.Blue, ForeColor = Color.White }, new TrX_ActivityTag("blueprint") { BackColor = Color.IndianRed, ForeColor = Color.AliceBlue }, new TrX_ActivityTag("sanctum") { BackColor = Color.Purple, ForeColor = Color.White }, new TrX_ActivityTag("ultimatum") { BackColor = Color.MediumVioletRed, ForeColor = Color.White }, new TrX_ActivityTag("ultimatum-win") { BackColor = Color.MediumVioletRed, ForeColor = Color.White }, new TrX_ActivityTag("ultimatum-loss") { BackColor = Color.MediumVioletRed, ForeColor = Color.White }, new TrX_ActivityTag("ultimatum-loss") { BackColor = Color.MediumVioletRed, ForeColor = Color.White }, new TrX_ActivityTag("ultimatum-took-reward") { BackColor = Color.MediumVioletRed, ForeColor = Color.White }, new TrX_ActivityTag("black-knight") { BackColor = Color.DarkBlue, ForeColor = Color.White } }; foreach (TrX_ActivityTag tag in tmpTags) { try { _dataBackend.DoNonQueryNoErrorHandling("insert into tx_tags (tag_id, tag_display, tag_bgcolor, tag_forecolor, tag_type, tag_show_in_lv) values " + $"('{tag.ID}', '{tag.DisplayName}', '{tag.BackColor.ToArgb()}', '{tag.ForeColor.ToArgb()}', 'default', {(tag.ShowInListView ? "1" : "0")})", false); _log.Info($"Default tag '{tag.ID}' added to database"); } catch (SqliteException e) { if (!e.Message.Contains("SQLite Error 19")) { _log.Error(e.ToString()); } } } } /// <summary> /// Load user created tags /// </summary> private void LoadTags() { SqliteDataReader sqlReader; sqlReader = _dataBackend.GetSQLReader("SELECT * FROM tx_tags ORDER BY tag_display ASC"); while (sqlReader.Read()) { string sID = sqlReader.GetString(0); string sType = sqlReader.GetString(4); TrX_ActivityTag tag = new TrX_ActivityTag(sID, sType != "custom") { DisplayName = sqlReader.GetString(1), BackColor = Color.FromArgb(Convert.ToInt32(sqlReader.GetString(2))), ForeColor = Color.FromArgb(Convert.ToInt32(sqlReader.GetString(3))), ShowInListView = sqlReader.GetInt32(5) == 1, SoundEnabled = sqlReader.GetInt32(6) == 1, SoundID = sqlReader.GetString(7) }; _tags.Add(tag); } } /// <summary> /// Find matching tag for given display name /// </summary> /// <param name="s_display_name"></param> /// <returns></returns> public TrX_ActivityTag GetTagByDisplayName(string s_display_name) { foreach (TrX_ActivityTag t in _tags) { if (t.DisplayName == s_display_name) return t; } return null; } /// <summary> /// Initialize the stats /// </summary> private void InitNumStats() { _myStats.NumericStats = new Dictionary<string, int> { { "AreaChanges", 0 }, { "TotalKilledCount", 0 }, { "EinharCaptures", 0 }, { "ExpeditionEncounters", 0 }, { "ExpeditionEncounters_Rog", 0 }, { "ExpeditionEncounters_Tujen", 0 }, { "ExpeditionEncounters_Gwennen", 0 }, { "ExpeditionEncounters_Dannig", 0 }, { "HideoutTimeSec", 0 }, { "LabsFinished", 0 }, { "LabsStarted", 0 }, { "LevelUps", 0 }, { "NamelessSeerEncounters", 0 }, { "ReflectingMistEncounters", 0 }, { "MemoryTears", 0 }, { "TotalMapsDone", 0 }, { "TotalHeistsDone", 0 }, { "SanctumKilledLycia1", 0 }, { "SanctumKilledLycia2", 0 }, { "SimulacrumCleared", 0 }, { "SimulacrumStarted", 0 }, { "Suicides", 0 }, { "TemplesDone", 0 }, { "TrialMasterTookReward", 0 }, { "TrialMasterVictory", 0 }, { "TrialMasterSuccess", 0 }, { "AncestorMatchesWon", 0 }, { "AncestorMatchesLost", 0 }, { "AncestorTournamentsWon", 0 }, { "AncestorTournamentsLost", 0 }, }; _statNamesLong = new Dictionary<string, string> { { "TotalMapsDone", "Total maps done" }, { "TotalHeistsDone", "Total heists done" }, { "TotalKilledCount", "Death count" }, { "EinharCaptures", "Einhar beasts captured" }, { "TrialMasterTookReward", "Ultimatum: took rewards" }, { "TrialMasterVictory", "Ultimatum: cleared all rounds" }, { "TrialMasterSuccess", "Ultimatum: did not fail" }, { "LevelUps", "Level Ups" }, { "NamelessSeerEncounters", "Encounters with The Nameless Seer" }, { "ReflectingMistEncounters", "Encounters with The Reflecting Mist" }, { "MemoryTears", "Memory Tears opened" }, { "SimulacrumStarted", "Simulacrum started" }, { "SimulacrumCleared", "Simulacrum 100% done" }, { "LabsFinished", "Finished labs" }, { "TemplesDone", "Temples done" }, { "LabsStarted", "Labs started" }, { "ExpeditionEncounters", "Expedition encounters" }, { "ExpeditionEncounters_Rog", "Expedition encounters: Rog" }, { "ExpeditionEncounters_Tujen", "Expedition encounters: Tujen" }, { "ExpeditionEncounters_Gwennen", "Expedition encounters: Gwennen" }, { "ExpeditionEncounters_Dannig", "Expedition encounters: Dannig" }, { "HideoutTimeSec", "Hideout time" }, { "Suicides", "Suicides" }, { "SanctumKilledLycia1", "Sanctum: Lycia 1 killed" }, { "SanctumKilledLycia2", "Sanctum: Lycia 2 killed" }, { "AncestorMatchesWon", "Ancestor: Matches won" }, { "AncestorMatchesLost", "Ancestor: Matches lost" }, { "AncestorTournamentsWon", "Ancestor: Tournaments won" }, { "AncestorTournamentsLost", "Ancestor: Tournaments lost" } }; labs = new List<string> { "Unknown", "The Labyrinth", "The Merciless Labyrinth", "The Cruel Labyrinth", "Uber-Lab", "Advanced Uber-Lab" }; foreach (string s in labs) { string sName = s.Replace("'", ""); if (!_myStats.NumericStats.ContainsKey($"LabsCompleted_{sName}")) _myStats.NumericStats.Add($"LabsCompleted_{sName}", 0); if (!_statNamesLong.ContainsKey($"LabsCompleted_{sName}")) _statNamesLong.Add($"LabsCompleted_{sName}", $"Labs completed: {sName}"); } } /// <summary> /// Reset stats /// </summary> public void ResetStats() { ClearStatsDB(); } /// <summary> /// Empty stats DB /// </summary> private void ClearStatsDB() { _dataBackend.DoNonQuery("drop table tx_stats"); _dataBackend.DoNonQuery("create table if not exists tx_stats " + "(timestamp int, " + "stat_name text, " + "stat_value int)"); InitNumStats(); _log.Info("Stats cleared."); } /// <summary> /// Track known players. Needed to find out if death events are for your own /// char or not. If a player name enters your area, It could not be you :) /// </summary> /// <param name="s_name"></param> private void AddKnownPlayerIfNotExists(string s_name) { if (!_knownPlayerNames.Contains(s_name)) { _knownPlayerNames.Add(s_name); _dataBackend.DoNonQuery($"insert into tx_known_players (player_name) VALUES ('{s_name}')"); _log.Info($"KnownPlayerAdded -> name: {s_name}"); } } /// <summary> /// Read list of known players /// </summary> private void ReadKnownPlayers() { SqliteDataReader sqlReader; sqlReader = _dataBackend.GetSQLReader("SELECT * FROM tx_known_players"); while (sqlReader.Read()) { _knownPlayerNames.Add(sqlReader.GetString(0)); } } /// <summary> /// Save activity to database /// </summary> /// <param name="i_ts"></param> /// <param name="s_type"></param> /// <param name="s_area"></param> /// <param name="i_area_level"></param> /// <param name="i_stopwatch"></param> /// <param name="i_death_counter"></param> /// <param name="i_ulti_rounds"></param> /// <param name="b_zana"></param> /// <param name="l_tags"></param> private void SaveToActivityLog(long i_ts, string s_type, string s_area, int i_area_level, int i_stopwatch, int i_death_counter, int i_ulti_rounds, bool b_zana, List<string> l_tags, bool b_success, int i_pause_time = 0) { //replace ' in area s_area = s_area.Replace("'", ""); string sTags = ""; for (int i = 0; i < l_tags.Count; i++) { sTags += l_tags[i]; if (i < (l_tags.Count - 1)) sTags += "|"; } _dataBackend.DoNonQuery("insert into tx_activity_log " + "(timestamp, " + "act_type, " + "act_area, " + "act_area_level, " + "act_stopwatch, " + "act_deathcounter, " + "act_ulti_rounds," + "act_is_zana," + "act_tags," + "act_success," + "act_pause_time) VALUES (" + i_ts.ToString() + ", '" + s_type + "', '" + s_area + "', '" + i_area_level.ToString() + "', " + i_stopwatch + ", " + i_death_counter + ", " + i_ulti_rounds + ", " + (b_zana ? "1" : "0") + ", '" + sTags + "'" + ", " + (b_success ? "1" : "0") + ", " + i_pause_time.ToString() + ")"); _parsedActivities.Add(i_ts.ToString() + "_" + s_area); } /// <summary> /// get activity type object from string /// </summary> /// <param name="s_type"></param> /// <returns></returns> private ACTIVITY_TYPES GetActTypeFromString(string s_type) { ACTIVITY_TYPES returnType; try { returnType = (ACTIVITY_TYPES)Enum.Parse(typeof(ACTIVITY_TYPES), s_type, true); } catch { returnType = ACTIVITY_TYPES.OTHER; } return returnType; } /// <summary> /// Read the activity log from Database /// </summary> private void ReadActivityLogFromSQLite() { SqliteDataReader sqlReader; sqlReader = _dataBackend.GetSQLReader("SELECT * FROM tx_activity_log ORDER BY timestamp DESC"); string[] arrTags; while (sqlReader.Read()) { TimeSpan ts = TimeSpan.FromSeconds(sqlReader.GetInt32(3)); string sType = sqlReader.GetString(1); ACTIVITY_TYPES aType = GetActTypeFromString(sType); TrX_TrackedActivity map; if (aType == ACTIVITY_TYPES.LABYRINTH) { map = new TrX_TrackedActivity { Started = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(sqlReader.GetInt32(0)).ToLocalTime(), TimeStamp = sqlReader.GetInt32(0), CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds), TotalSeconds = Convert.ToInt32(ts.TotalSeconds), Type = aType, Area = sqlReader.GetString(2), DeathCounter = sqlReader.GetInt32(4), TrialMasterCount = sqlReader.GetInt32(5), PausedTime = sqlReader.GetDouble(10) }; } else { map = new TrX_TrackedActivity { Started = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(sqlReader.GetInt32(0)).ToLocalTime(), TimeStamp = sqlReader.GetInt32(0), CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds), TotalSeconds = Convert.ToInt32(ts.TotalSeconds), Type = aType, Area = sqlReader.GetString(2), DeathCounter = sqlReader.GetInt32(4), TrialMasterCount = sqlReader.GetInt32(5), PausedTime = sqlReader.GetDouble(10) }; } try { map.AreaLevel = sqlReader.GetInt32(8); } catch { map.AreaLevel = 0; } try { string sTags = sqlReader.GetString(7); arrTags = sTags.Split('|'); } catch { arrTags = new string[0]; } for (int i = 0; i < arrTags.Length; i++) { map.AddTag(arrTags[i]); } if (!_parsedActivities.Contains(map.UniqueID)) { if (map.TotalSeconds > _timeCapMin) { _eventHistory.Add(map); } _parsedActivities.Add(map.UniqueID); } } _historyInitialized = true; } /// <summary> /// Main method for log parsing thread /// </summary> private void LogParsing() { while (!_exit) { // Wait for Valid log file to start parsing Thread.Sleep(1000); if (CheckForValidClientLogFile(_clientTxtPath)) { ParseLogFile(); } } } /// <summary> /// Get line count from Client.txt. Used for progress calculation /// </summary> /// <returns></returns> private int GetLogFileLineCount() { int iCount = 0; FileStream fs1 = new FileStream(_clientTxtPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); TextReader reader1 = new StreamReader(fs1); while ((reader1.ReadLine()) != null) { iCount++; } reader1.Close(); return iCount; } /// <summary> /// Parse the logfile /// </summary> private void ParseLogFile() { _log.Info($"Started logfile parsing. Last hash was {_lastHash}"); _logLinesTotal = Convert.ToDouble(GetLogFileLineCount()); var fs = new FileStream(_clientTxtPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); bool bNewContent = _lastHash == 0; using (StreamReader reader = new StreamReader(fs)) { string line; int lineHash = 0; DateTime lastEvTime = new DateTime(); // Keep file open while (!_exit) { line = reader.ReadLine(); if (line == null) { if (!_eventQueueInitizalized) { _currentActivity = null; _isMapZana = false; _initEndTime = DateTime.Now; TimeSpan tsInitDuration = (_initEndTime - _initStartTime); _eventQueue.Enqueue(new TrX_TrackingEvent(EVENT_TYPES.APP_READY) { EventTime = DateTime.Now, LogLine = $"Application initialized in {Math.Round(tsInitDuration.TotalSeconds, 2)} seconds." }); _log.Info($"Initialized in {tsInitDuration.TotalSeconds} seconds."); _lastHash = lineHash; // Trigger ready event OnHistoryInitialized(new TrX_CoreLogicGenericEventArgs(this)); SaveStatsCache(); } _eventQueueInitizalized = true; bNewContent = true; Thread.Sleep(100); continue; } lineHash = line.GetHashCode(); if (_dict.ContainsKey(lineHash)) continue; if (lineHash == _lastHash || _lastHash == 0) { bNewContent = true; } if (!bNewContent) { _logLinesRead++; continue; } _lastHash = lineHash; foreach (KeyValuePair<string, EVENT_TYPES> kv in _eventMapping.Mapping) { if (line.Contains(kv.Key)) { if (!_dict.ContainsKey(lineHash)) { TrX_TrackingEvent ev = new TrX_TrackingEvent(kv.Value) { LogLine = line }; try { DateTime dt = DateTime.Parse($"{line.Split(' ')[0]} {line.Split(' ')[1]}", _dateTimeFormatInfo); ev.EventTime = dt; lastEvTime = ev.EventTime; } catch { ev.EventTime = lastEvTime; } _dict.Add(lineHash, "init"); if (!_eventQueueInitizalized) { HandleSingleEvent(ev); } else { _eventQueue.Enqueue(ev); } } } } _logLinesRead++; } } } /// <summary> /// Handle events - Read Queue /// </summary> private void EventHandling() { while (!_exit) { Thread.Sleep(1); if (_eventQueueInitizalized) { while (_eventQueue.TryDequeue(out TrX_TrackingEvent deqEvent)) { HandleSingleEvent(deqEvent); } } } } /// <summary> /// Check if a given area is a Map. /// </summary> /// <param name="sArea"></param> /// <param name="sSourceArea"></param> /// <returns></returns> private bool CheckIfAreaIsMap(string sArea, string sSourceArea = "") { // Laboratory could be map or heist... if (sArea == "Laboratory") { if (sSourceArea == "The Rogue Harbour") { return false; } else { return true; } } foreach (string s in _defaultMappings.MapAreas) { if (s.Trim().Equals(sArea.Trim())) return true; } return false; } /// <summary> /// Check if a given area is a Heist /// </summary> /// <param name="sArea"></param> /// <param name="sSourceArea"></param> /// <returns></returns> private bool CheckIfAreaIsHeist(string sArea, string sSourceArea = "") { // Laboratory could be map or heist... if (sArea == "Laboratory") { if (sSourceArea == "The Rogue Harbour") { return true; } else { return false; } } foreach (string s in _defaultMappings.HeistAreas) { if (s.Trim().Equals(sArea.Trim())) return true; } return false; } private void SplitCurrentActivity() { if (_currentActivity != null) { _log.Debug($"splitting activity {_currentActivity.UniqueID}"); // set same level for next area _nextAreaLevel = _currentActivity.AreaLevel; FinishActivity(_currentActivity, _currentActivity.Area, _currentActivity.Type, DateTime.Now); if (_currentArea != _currentActivity.Area) { _currentActivity.Pause(); } } } /// <summary> /// Process a command entered via ingame chat /// </summary> /// <param name="s_command"></param> private void HandleChatCommand(string s_command) { _log.Info($"ChatCommand -> {s_command}"); string[] spl = s_command.Split(' '); string sMain; string sArgs = ""; try { sMain = spl[0]; if (spl.Length > 1) { sArgs = spl[1]; } TrX_TrackedActivity currentAct = null; if (_currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { currentAct = _currentActivity.SideArea_ZanaMap; } else { currentAct = _currentActivity; } } switch (sMain) { case "tag": if (currentAct != null) { AddTagAutoCreate(sArgs, currentAct); } break; case "untag": if (currentAct != null) { RemoveTagFromActivity(sArgs, currentAct); } break; case "pause": PauseCurrentActivityOrSide(); break; case "resume": ResumeCurrentActivityOrSide(); break; case "split": SplitCurrentActivity(); break; case "counter": string cmdArgs = sArgs; _log.Debug(sArgs); break; case "finish": if (currentAct != null && !_isMapZana) { FinishActivity(_currentActivity, null, ACTIVITY_TYPES.MAP, DateTime.Now); } break; } } catch (Exception ex) { _log.Error($"Error handling chat command '{s_command}' -> {ex.Message}"); _log.Debug(ex.ToString()); } } /// <summary> /// Handle area change. Core logic for nearly all tracking /// </summary> /// <param name="ev"></param> private void HandleAreaChangeEvent(TrX_TrackingEvent ev) { string sSourceArea = _currentArea; string sTargetArea = GetAreaNameFromEvent(ev); string sAreaName = GetAreaNameFromEvent(ev); bool bSourceAreaIsMap = CheckIfAreaIsMap(sSourceArea), bSourceAreaIsVaal = _defaultMappings.VaalSideAreas.Contains(sSourceArea), bSourceAreaIsSanctum = _defaultMappings.SanctumAreas.Contains(sSourceArea), bSourceAreaIsAbyss = _defaultMappings.AbyssalAreas.Contains(sSourceArea), bSourceAreaIsLabTrial = sSourceArea.Contains("Trial of"), bSourceAreaIsLogbookSide = _defaultMappings.LogbookSideAreas.Contains(sSourceArea), bSourceAreaIsBlackKnight = _defaultMappings.BlackKnightAreas.Contains(sSourceArea), bTargetAreaIsMap = CheckIfAreaIsMap(sTargetArea, sSourceArea), bTargetAreaIsHeist = CheckIfAreaIsHeist(sTargetArea, sSourceArea), bTargetAreaIsSimu = false, bTargetAreaMine = _defaultMappings.DelveAreas.Contains(sTargetArea), bTargetAreaIsTane = _defaultMappings.TaneAreas.Contains(sTargetArea), bTargetAreaTemple = _defaultMappings.TempleAreas.Contains(sTargetArea), bTargetAreaIsLab = _defaultMappings.LabyrinthStartAreas.Contains(sTargetArea), bTargetAreaIsMI = _defaultMappings.MavenInvitationAreas.Contains(sTargetArea), bTargetAreaIsAtziri = _defaultMappings.AtziriAreas.Contains(sTargetArea), bTargetAreaIsUberAtziri = _defaultMappings.UberAtziriAreas.Contains(sTargetArea), bTargetAreaIsElder = _defaultMappings.ElderAreas.Contains(sTargetArea), bTargetAreaIsShaper = _defaultMappings.ShaperAreas.Contains(sTargetArea), bTargetAreaIsSirusFight = _defaultMappings.SirusAreas.Contains(sTargetArea), bTargetAreaIsMavenFight = _defaultMappings.MavenFightAreas.Contains(sTargetArea), bTargetAreaIsCampaign = _defaultMappings.CampaignAreas.Contains(sTargetArea), bTargetAreaIsLabTrial = sTargetArea.Contains("Trial of"), bTargetAreaIsAbyssal = _defaultMappings.AbyssalAreas.Contains(sTargetArea), bTargetAreaIsVaal = _defaultMappings.VaalSideAreas.Contains(sTargetArea), bTargetAreaIsLogbook = _defaultMappings.LogbookAreas.Contains(sTargetArea), bTargetAreaIsLogBookSide = _defaultMappings.LogbookSideAreas.Contains(sTargetArea), bTargetAreaIsCata = _defaultMappings.CatarinaFightAreas.Contains(sTargetArea), bTargetAreaIsSafehouse = _defaultMappings.SyndicateSafehouseAreas.Contains(sTargetArea), bTargetAreaIsBreachStone = _defaultMappings.BreachstoneDomainAreas.Contains(sTargetArea), bTargetAreaIsExarch = _defaultMappings.SearingExarchAreas.Contains(sTargetArea), bTargetAreaIsBlackStar = _defaultMappings.BlackStarAreas.Contains(sTargetArea), bTargetAreaIsInfinitetHunger = _defaultMappings.InfiniteHungerAreas.Contains(sTargetArea), bTargetAreaIsEaterOfWorlds = _defaultMappings.EaterOfWorldsAreas.Contains(sTargetArea), bTargetAreaIsLegion = _defaultMappings.TimelessLegionAreas.Contains(sTargetArea), bTargetAreaIsKalandra = _defaultMappings.LakeOfKalandraAreas.Contains(sTargetArea), bTargetAreaIsSanctum = _defaultMappings.SanctumAreas.Contains(sTargetArea), bTargetAreaIsTrialmaster = _defaultMappings.TrialMasterAreas.Contains(sTargetArea), bTargetAreaIsToTa = _defaultMappings.TotAAreas.Contains(sTargetArea), bTargetAreaIsUltimatum = _defaultMappings.UltimatumAreas.Contains(sTargetArea), bTargetAreaIsKingsmarch = _defaultMappings.KingsmarchAreas.Contains(sTargetArea), bTargetAreaIsDread = _defaultMappings.IncarnationOfDreadAreas.Contains(sTargetArea), bTargetAreaIsFear = _defaultMappings.IncarnationOfFearAreas.Contains(sTargetArea), bTargetAreaIsNeglectedFlame = _defaultMappings.NeglectedFlameAreas.Contains(sTargetArea), bTargetAreaIsDeceitfulGod = _defaultMappings.DeceitfulGodAreas.Contains(sTargetArea), bTargetAreaIsCardinalOfFear = _defaultMappings.CardinalOfFearAreas.Contains(sTargetArea), bTargetAreaIsNeglect = _defaultMappings.IncarnationOfNeglectAreas.Contains(sTargetArea), bTargetAreaIsMists = _defaultMappings.KingInTheMistsAreas.Contains(sTargetArea), bTargetAreaIsBlackKnight = _defaultMappings.BlackKnightAreas.Contains(sTargetArea), bTargetAreaIsValerius = _defaultMappings.AdmiralValeriusAreas.Contains(sTargetArea), bTargetAreaIsSasan = _defaultMappings.SasanAreas.Contains(sTargetArea); long lTS = ((DateTimeOffset)ev.EventTime).ToUnixTimeSeconds(); // Sanctum runs after sanctum league are tracked differently -> not started from inside map. bool isOutSideSanctumLeague = (ev.EventTime > new DateTime(2023, 4, 5)); IncrementStat("AreaChanges", ev.EventTime, 1); // Re-Entered? if (_currentActivity != null && _currentActivity.Area == sTargetArea && _currentActivity.InstanceEndpoint == _currentInstanceEndpoint) { _currentActivity.LastTimeEntered = ev.EventTime; _log.Debug($"re-entered activity: {_currentActivity.UniqueID}"); } // Calculate Instance change based statistics: // =========================================== //Moving between two sanctums -handling in sanctum league? if (bSourceAreaIsSanctum && bTargetAreaIsSanctum && !isOutSideSanctumLeague) { return; } // Moving between two sanctums - handling after sanctum league? if (bSourceAreaIsSanctum && bTargetAreaIsSanctum && _currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.SANCTUM) { // Set the level to non-entering-area, so it will not be always level 1 if (sTargetArea != "The Forbidden Sanctum") { _currentActivity.AreaLevel = _nextAreaLevel; } // if moving between sacntums, do no further calculations. return; } // Always show same ara for sanctums / after initial calculations if (bTargetAreaIsSanctum && isOutSideSanctumLeague) { sTargetArea = "The Forbidden Sanctum"; } // Track the very first activity if ((!sTargetArea.Contains("Hideout")) && (!_defaultMappings.CampAreas.Contains(sTargetArea))) { _StartedFlag = false; } // Hideout? if (sTargetArea.Contains("Hideout") && !sTargetArea.Contains("Syndicate")) { if (!_trackingHO) { _hoStart = ev.EventTime; _trackingHO = true; } } else { if (_trackingHO) { int hoSeconds; hoSeconds = Convert.ToInt32((ev.EventTime - _hoStart).TotalSeconds); IncrementStat("HideoutTimeSec", ev.EventTime, hoSeconds); _trackingHO = false; } } if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LABYRINTH) { _currentActivity.LastEnded = ev.EventTime; } if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.DELVE) { _currentActivity.LastEnded = ev.EventTime; } if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.TANES_LABORATORY) { _currentActivity.LastEnded = ev.EventTime; } //Simu? if (_defaultMappings.SimulacrumAreas.Contains(sAreaName)) { bTargetAreaIsSimu = true; if (_currentInstanceEndpoint != _lastSimuEndpoint) { IncrementStat("SimulacrumStarted", ev.EventTime, 1); _lastSimuEndpoint = _currentInstanceEndpoint; _currentActivity = new TrX_TrackedActivity { Area = sTargetArea, Type = ACTIVITY_TYPES.SIMULACRUM, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentInstanceEndpoint }; _prevActivityOverlay = GetLastActivityByType(ACTIVITY_TYPES.SIMULACRUM); _nextAreaLevel = 0; _nextAreaSeed = 0; } } ACTIVITY_TYPES actType = ACTIVITY_TYPES.MAP; if (bTargetAreaIsMap) { actType = ACTIVITY_TYPES.MAP; } else if (bTargetAreaIsHeist) { actType = ACTIVITY_TYPES.HEIST; } else if (bTargetAreaIsSimu) { actType = ACTIVITY_TYPES.SIMULACRUM; } else if (bTargetAreaIsLab) { actType = ACTIVITY_TYPES.LABYRINTH; } else if (bTargetAreaMine) { actType = ACTIVITY_TYPES.DELVE; } else if (bTargetAreaTemple) { actType = ACTIVITY_TYPES.TEMPLE; } else if (bTargetAreaIsMI) { actType = ACTIVITY_TYPES.MAVEN_INVITATION; } else if (bTargetAreaIsAtziri) { actType = ACTIVITY_TYPES.ATZIRI; } else if (bTargetAreaIsUberAtziri) { actType = ACTIVITY_TYPES.UBER_ATZIRI; } else if (bTargetAreaIsShaper) { actType = ACTIVITY_TYPES.SHAPER_FIGHT; } else if (bTargetAreaIsElder) { actType = ACTIVITY_TYPES.ELDER_FIGHT; } else if (bTargetAreaIsMavenFight) { actType = ACTIVITY_TYPES.MAVEN_FIGHT; } else if (bTargetAreaIsSirusFight) { actType = ACTIVITY_TYPES.SIRUS_FIGHT; } else if (bTargetAreaIsCampaign) { actType = ACTIVITY_TYPES.CAMPAIGN; } else if (bTargetAreaIsAbyssal) { actType = ACTIVITY_TYPES.ABYSSAL_DEPTHS; } else if (bTargetAreaIsLabTrial) { actType = ACTIVITY_TYPES.LAB_TRIAL; } else if (bTargetAreaIsSanctum) { actType = ACTIVITY_TYPES.SANCTUM; } else if (bTargetAreaIsVaal) { actType = ACTIVITY_TYPES.VAAL_SIDEAREA; } else if (bTargetAreaIsLogbook) { actType = ACTIVITY_TYPES.LOGBOOK; } else if (bTargetAreaIsLogBookSide) { actType = ACTIVITY_TYPES.LOGBOOK_SIDE; } else if (bTargetAreaIsCata) { actType = ACTIVITY_TYPES.CATARINA_FIGHT; } else if (bTargetAreaIsSafehouse) { actType = ACTIVITY_TYPES.SAFEHOUSE; } else if (bTargetAreaIsBreachStone) { actType = ACTIVITY_TYPES.BREACHSTONE; } else if (bTargetAreaIsExarch) { actType = ACTIVITY_TYPES.SEARING_EXARCH_FIGHT; } else if (bTargetAreaIsBlackStar) { actType = ACTIVITY_TYPES.BLACK_STAR_FIGHT; } else if (bTargetAreaIsInfinitetHunger) { actType = ACTIVITY_TYPES.INFINITE_HUNGER_FIGHT; } else if (bTargetAreaIsEaterOfWorlds) { actType = ACTIVITY_TYPES.EATER_OF_WORLDS_FIGHT; } else if (bTargetAreaIsLegion) { actType = ACTIVITY_TYPES.TIMELESS_LEGION; } else if (bTargetAreaIsKalandra) { actType = ACTIVITY_TYPES.LAKE_OF_KALANDRA; } else if (bTargetAreaIsTrialmaster) { actType = ACTIVITY_TYPES.TRIALMASTER_FIGHT; } else if (bTargetAreaIsTane) { actType = ACTIVITY_TYPES.TANES_LABORATORY; } else if (bTargetAreaIsToTa) { actType = ACTIVITY_TYPES.ANCESTOR_TRIAL; } else if (bTargetAreaIsUltimatum) { actType = ACTIVITY_TYPES.INSCRIBED_ULTIMATUM; } else if (bTargetAreaIsKingsmarch) { actType = ACTIVITY_TYPES.KINGSMARCH; } else if (bTargetAreaIsDread) { actType = ACTIVITY_TYPES.INCARNATION_OF_DREAD_FIGHT; } else if (bTargetAreaIsFear) { actType = ACTIVITY_TYPES.INCARNATION_OF_FEAR_FIGHT; } else if (bTargetAreaIsNeglect) { actType = ACTIVITY_TYPES.INCARNATION_OF_NEGLECT_FIGHT; } else if (bTargetAreaIsNeglectedFlame) { actType = ACTIVITY_TYPES.NEGLECTED_FLAME_FIGHT; } else if (bTargetAreaIsDeceitfulGod) { actType = ACTIVITY_TYPES.DECEITFUL_GOD_FIGHT; } else if (bTargetAreaIsCardinalOfFear) { actType = ACTIVITY_TYPES.CARDINAL_OF_FEAR_FIGHT; } else if (bTargetAreaIsMists) { actType = ACTIVITY_TYPES.KING_IN_THE_MISTS_FIGHT; } else if (bTargetAreaIsBlackKnight) { actType = ACTIVITY_TYPES.BLACK_KNIGHT_FIGHT; } else if (bTargetAreaIsValerius) { actType = ACTIVITY_TYPES.ADMIRAL_VALERIUS_FIGHT; } else if (bTargetAreaIsSasan) { actType = ACTIVITY_TYPES.SASAN_FIGHT; } else { actType = ACTIVITY_TYPES.OTHER; } // Special handling for logbook cemetery + vaal temple if (bTargetAreaIsLogbook && bTargetAreaIsMap) { actType = _nextAreaIsExp ? ACTIVITY_TYPES.LOGBOOK : ACTIVITY_TYPES.MAP; _nextAreaIsExp = false; } //Lab started? if (actType == ACTIVITY_TYPES.LABYRINTH && sSourceArea == "Aspirants Plaza") { string sLabName; switch (_nextAreaLevel) { case 33: sLabName = "The Labyrinth"; break; case 55: sLabName = "The Cruel Labyrinth"; break; case 68: sLabName = "The Merciless Labyrinth"; break; case 75: sLabName = "Uber-Lab"; break; case 83: sLabName = "Advanced Uber-Lab"; break; default: sLabName = "Unknown"; break; } // Finish activity if (_currentActivity != null) { FinishActivity(_currentActivity, null, ACTIVITY_TYPES.MAP, ev.EventTime); } _currentActivity = new TrX_TrackedActivity { Area = sLabName, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentInstanceEndpoint }; _currentActivity.StartStopWatch(); _prevActivityOverlay = GetLastActivityByType(actType); IncrementStat("LabsStarted", ev.EventTime, 1); OnActivityStarted(new TrX_CoreLogicActivityEventArgs(this, _currentActivity)); } //Aspirants Trial entered if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LABYRINTH && sTargetArea == "Aspirants Trial") { (_currentActivity).TrialCount++; } //Lab cancelled? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LABYRINTH) { if (sTargetArea.Contains("Hideout") || _defaultMappings.CampAreas.Contains(sTargetArea)) { FinishActivity(_currentActivity, null, ACTIVITY_TYPES.LABYRINTH, DateTime.Now); } } // Sanctum entered? if (isOutSideSanctumLeague == false && _currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && actType == ACTIVITY_TYPES.SANCTUM) { if (_currentActivity.SideArea_Sanctum == null) { _currentActivity.SideArea_Sanctum = new TrX_TrackedActivity { Area = sTargetArea, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentActivity.InstanceEndpoint }; _currentActivity.AddTag("sanctum"); } _currentActivity.Pause(); _currentActivity.StartPauseTime(ev.EventTime); _currentActivity.SideArea_Sanctum.StartStopWatch(); _currentActivity.SideArea_Sanctum.EndPauseTime(ev.EventTime); _isMapSanctum = true; } else { _isMapSanctum = false; } // Left Sanctum area? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && bSourceAreaIsSanctum) { if (_currentActivity.SideArea_Sanctum != null) { _currentActivity.SideArea_Sanctum.LastEnded = ev.EventTime; _currentActivity.SideArea_Sanctum.StopStopWatch(); _currentActivity.SideArea_Sanctum.StartPauseTime(ev.EventTime); _currentActivity.Resume(); _currentActivity.EndPauseTime(ev.EventTime); } } // Vaal Side area entered? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && actType == ACTIVITY_TYPES.VAAL_SIDEAREA) { if (_currentActivity.SideArea_VaalArea == null) { _currentActivity.SideArea_VaalArea = new TrX_TrackedActivity { Area = sTargetArea, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentActivity.InstanceEndpoint }; _currentActivity.AddTag("vaal-area"); } _currentActivity.Pause(); _currentActivity.StartPauseTime(ev.EventTime); _currentActivity.SideArea_VaalArea.StartStopWatch(); _currentActivity.SideArea_VaalArea.EndPauseTime(ev.EventTime); _isMapVaalArea = true; } else { _isMapVaalArea = false; } // Left Vaal Side area? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && bSourceAreaIsVaal) { if (_currentActivity.SideArea_VaalArea != null) { _currentActivity.SideArea_VaalArea.LastEnded = ev.EventTime; _currentActivity.SideArea_VaalArea.StopStopWatch(); _currentActivity.SideArea_VaalArea.StartPauseTime(ev.EventTime); _currentActivity.Resume(); _currentActivity.EndPauseTime(ev.EventTime); } } // Black Knight Side area entered? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && actType == ACTIVITY_TYPES.BLACK_KNIGHT_FIGHT) { if (_currentActivity.SideArea_BlackKnight == null) { _currentActivity.SideArea_BlackKnight = new TrX_TrackedActivity { Area = sTargetArea, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentActivity.InstanceEndpoint }; _currentActivity.AddTag("black-knight"); } _currentActivity.Pause(); _currentActivity.StartPauseTime(ev.EventTime); _currentActivity.SideArea_BlackKnight.StartStopWatch(); _currentActivity.SideArea_BlackKnight.EndPauseTime(ev.EventTime); _isBlackKnightFight = true; } else { _isBlackKnightFight = false; } // Left Black Knight Fight if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && bSourceAreaIsBlackKnight) { if (_currentActivity.SideArea_BlackKnight != null) { _currentActivity.SideArea_BlackKnight.LastEnded = ev.EventTime; _currentActivity.SideArea_BlackKnight.StopStopWatch(); _currentActivity.SideArea_BlackKnight.StartPauseTime(ev.EventTime); _currentActivity.Resume(); _currentActivity.EndPauseTime(ev.EventTime); } } // Logbook Side area entered? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LOGBOOK && actType == ACTIVITY_TYPES.LOGBOOK_SIDE) { if (_currentActivity.SideArea_LogbookSide == null) { _currentActivity.SideArea_LogbookSide = new TrX_TrackedActivity { Area = sTargetArea, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentActivity.InstanceEndpoint }; _currentActivity.AddTag("exp-side-area"); } _currentActivity.Pause(); _currentActivity.StartPauseTime(ev.EventTime); _currentActivity.SideArea_LogbookSide.StartStopWatch(); _currentActivity.SideArea_LogbookSide.EndPauseTime(ev.EventTime); _isMapLogbookSide = true; } else { _isMapLogbookSide = false; } // Left Logbook Side area? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LOGBOOK && bSourceAreaIsLogbookSide) { if (_currentActivity.SideArea_LogbookSide != null) { _currentActivity.SideArea_LogbookSide.LastEnded = ev.EventTime; _currentActivity.SideArea_LogbookSide.StopStopWatch(); _currentActivity.SideArea_LogbookSide.StartPauseTime(ev.EventTime); _currentActivity.Resume(); _currentActivity.EndPauseTime(ev.EventTime); } } // Abyss Side area entered? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && actType == ACTIVITY_TYPES.ABYSSAL_DEPTHS) { if (_currentActivity.SideArea_AbyssArea == null) { _currentActivity.SideArea_AbyssArea = new TrX_TrackedActivity { Area = sTargetArea, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentActivity.InstanceEndpoint }; _currentActivity.AddTag("abyss-depths"); } _currentActivity.Pause(); _currentActivity.StartPauseTime(ev.EventTime); _currentActivity.SideArea_AbyssArea.StartStopWatch(); _currentActivity.SideArea_AbyssArea.EndPauseTime(ev.EventTime); _isMapAbyssArea = true; } else { _isMapAbyssArea = false; } // Left Abyss Side area? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && bSourceAreaIsAbyss) { if (_currentActivity.SideArea_AbyssArea != null) { _currentActivity.SideArea_AbyssArea.LastEnded = ev.EventTime; _currentActivity.SideArea_AbyssArea.StopStopWatch(); _currentActivity.SideArea_AbyssArea.StartPauseTime(ev.EventTime); _currentActivity.Resume(); _currentActivity.EndPauseTime(ev.EventTime); } } // Lab Side area entered? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && actType == ACTIVITY_TYPES.LAB_TRIAL) { if (_currentActivity.SideArea_LabTrial == null) { _currentActivity.SideArea_LabTrial = new TrX_TrackedActivity { Area = sTargetArea, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentActivity.InstanceEndpoint }; _currentActivity.AddTag("lab-trial"); } _currentActivity.Pause(); _currentActivity.StartPauseTime(ev.EventTime); _currentActivity.SideArea_LabTrial.StartStopWatch(); _currentActivity.SideArea_LabTrial.EndPauseTime(ev.EventTime); _isMapLabTrial = true; } else { _isMapLabTrial = false; } // Left Lab Side area? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP && bSourceAreaIsLabTrial) { if (_currentActivity.SideArea_LabTrial != null) { _currentActivity.SideArea_LabTrial.LastEnded = ev.EventTime; _currentActivity.SideArea_LabTrial.StopStopWatch(); _currentActivity.SideArea_LabTrial.StartPauseTime(ev.EventTime); _currentActivity.Resume(); _currentActivity.EndPauseTime(ev.EventTime); } } // Kingsmarch? if ((_currentActivity == null || _currentActivity.Type != ACTIVITY_TYPES.KINGSMARCH) && actType == ACTIVITY_TYPES.KINGSMARCH) { // Finish activity if (_currentActivity != null) { _currentActivity.LastEnded = ev.EventTime; FinishActivity(_currentActivity, null, ACTIVITY_TYPES.MAP, ev.EventTime); } _currentActivity = new TrX_TrackedActivity { Area = sTargetArea, Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentInstanceEndpoint }; _prevActivityOverlay = GetLastActivityByType(actType); OnActivityStarted(new TrX_CoreLogicActivityEventArgs(this, _currentActivity)); } // End Kingsmarch? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.KINGSMARCH && !bTargetAreaIsKingsmarch) { _currentActivity.LastEnded = ev.EventTime; FinishActivity(_currentActivity, null, ACTIVITY_TYPES.KINGSMARCH, DateTime.Now); } // Delving? if ((_currentActivity == null || _currentActivity.Type != ACTIVITY_TYPES.DELVE) && actType == ACTIVITY_TYPES.DELVE) { // Finish activity if (_currentActivity != null) { FinishActivity(_currentActivity, null, ACTIVITY_TYPES.MAP, ev.EventTime); } _currentActivity = new TrX_TrackedActivity { Area = "Azurite Mine", Type = actType, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentInstanceEndpoint }; _prevActivityOverlay = GetLastActivityByType(actType); OnActivityStarted(new TrX_CoreLogicActivityEventArgs(this, _currentActivity)); } // Tane? if ((_currentActivity == null || _currentActivity.Type != ACTIVITY_TYPES.TANES_LABORATORY) && actType == ACTIVITY_TYPES.TANES_LABORATORY) { // Finish activity if (_currentActivity != null) { FinishActivity(_currentActivity, null, ACTIVITY_TYPES.MAP, ev.EventTime); } _currentActivity = new TrX_TrackedActivity { Area = _defaultMappings.TaneAreas[0], Type = actType, Started = ev.EventTime, AreaLevel = 68, TimeStamp = lTS, InstanceEndpoint = _currentInstanceEndpoint }; _prevActivityOverlay = GetLastActivityByType(actType); OnActivityStarted(new TrX_CoreLogicActivityEventArgs(this, _currentActivity)); } // Update Delve level if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.DELVE && actType == ACTIVITY_TYPES.DELVE) { if (_nextAreaLevel > _currentActivity.AreaLevel) { _currentActivity.AreaLevel = _nextAreaLevel; } } // End Delving? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.DELVE && !bTargetAreaMine) { FinishActivity(_currentActivity, null, ACTIVITY_TYPES.DELVE, DateTime.Now); } // End Tane? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.TANES_LABORATORY && !bTargetAreaIsTane) { FinishActivity(_currentActivity, null, ACTIVITY_TYPES.TANES_LABORATORY, DateTime.Now); } //Campaign ? if (bTargetAreaIsCampaign) { // Do not track first camp visit after portal activity // Do not finish when logging in other char bool bFromActivity = bSourceAreaIsMap || sSourceArea == "Aspirants Trial" || _defaultMappings.SimulacrumAreas.Contains(sSourceArea) || _defaultMappings.LogbookAreas.Contains(sSourceArea) || _defaultMappings.TempleAreas.Contains(sSourceArea) || _defaultMappings.AtziriAreas.Contains(sSourceArea) || _defaultMappings.CatarinaFightAreas.Contains(sSourceArea) || _defaultMappings.ElderAreas.Contains(sSourceArea) || _defaultMappings.MavenFightAreas.Contains(sSourceArea) || _defaultMappings.SyndicateSafehouseAreas.Contains(sSourceArea) || _defaultMappings.ShaperAreas.Contains(sSourceArea) || _defaultMappings.SirusAreas.Contains(sSourceArea) || _defaultMappings.UberAtziriAreas.Contains(sSourceArea) || _defaultMappings.SearingExarchAreas.Contains(sSourceArea) || _defaultMappings.BlackStarAreas.Contains(sSourceArea) || _defaultMappings.EaterOfWorldsAreas.Contains(sSourceArea) || _defaultMappings.InfiniteHungerAreas.Contains(sSourceArea) || _defaultMappings.TimelessLegionAreas.Contains(sSourceArea) || _defaultMappings.TrialMasterAreas.Contains(sSourceArea) || _defaultMappings.UltimatumAreas.Contains(sSourceArea) || _defaultMappings.LakeOfKalandraAreas.Contains(sSourceArea) || _defaultMappings.IncarnationOfDreadAreas.Contains(sSourceArea) || _defaultMappings.IncarnationOfFearAreas.Contains(sSourceArea) || _defaultMappings.IncarnationOfNeglectAreas.Contains(sSourceArea) || _defaultMappings.DeceitfulGodAreas.Contains(sSourceArea) || _defaultMappings.AdmiralValeriusAreas.Contains(sSourceArea) || _defaultMappings.SasanAreas.Contains(sSourceArea); // Do not track first town visit after login if (!_StartedFlag && !bFromActivity) { if (_currentActivity != null) { if (sTargetArea != _currentActivity.Area || _currentInstanceEndpoint != _currentActivity.InstanceEndpoint || _currentAreaSeed != _currentActivity.AreaSeed) { _currentActivity.LastEnded = ev.EventTime; FinishActivity(_currentActivity, sTargetArea, ACTIVITY_TYPES.CAMPAIGN, ev.EventTime); } } else { _currentActivity = new TrX_TrackedActivity { Area = sTargetArea, Type = ACTIVITY_TYPES.CAMPAIGN, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, TimeStamp = lTS, Started = ev.EventTime, InstanceEndpoint = _currentInstanceEndpoint }; _currentActivity.StartStopWatch(); _prevActivityOverlay = GetLastActivityByType(actType); OnActivityStarted(new TrX_CoreLogicActivityEventArgs(this, _currentActivity)); } } else { _StartedFlag = false; } } else { // Pause campaing when entering hideout if (sTargetArea.Contains("Hideout") && _currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.CAMPAIGN) { _currentActivity.LastEnded = ev.EventTime; FinishActivity(_currentActivity, null, ACTIVITY_TYPES.OTHER, ev.EventTime); } } // PAUSE RESUME Handling if (bTargetAreaIsMap || bTargetAreaIsHeist || bTargetAreaIsSimu || bTargetAreaIsCampaign || bTargetAreaIsBreachStone) { if (_currentActivity != null) { if (_defaultMappings.CampAreas.Contains(sSourceArea) || sSourceArea.Contains("Hideout")) { if (sTargetArea == _currentActivity.Area && _currentInstanceEndpoint == _currentActivity.InstanceEndpoint && _currentActivity.AreaSeed == _currentAreaSeed) { _currentActivity.EndPauseTime(ev.EventTime); } } } } // Mechanisms that can be tracked with default logic: // One Area + Own instance bool enteringDefaultTrackableActivity = bTargetAreaIsMap || bTargetAreaIsHeist || bTargetAreaIsSimu || bTargetAreaIsLab || (bTargetAreaIsSanctum && isOutSideSanctumLeague) || bTargetAreaMine || bTargetAreaIsToTa || bTargetAreaIsKingsmarch || bTargetAreaIsTane || bTargetAreaTemple || bTargetAreaIsMI || bTargetAreaIsUberAtziri || bTargetAreaIsAtziri || bTargetAreaIsElder || bTargetAreaIsShaper || bTargetAreaIsMavenFight || bTargetAreaIsSirusFight || bTargetAreaIsLogbook || bTargetAreaIsSafehouse || bTargetAreaIsCata || bTargetAreaIsExarch || bTargetAreaIsBreachStone || bTargetAreaIsBlackStar || bTargetAreaIsEaterOfWorlds || bTargetAreaIsInfinitetHunger || bTargetAreaIsLegion || bTargetAreaIsTrialmaster || bTargetAreaIsUltimatum || bTargetAreaIsKalandra || bTargetAreaIsDread || bTargetAreaIsFear || bTargetAreaIsNeglectedFlame || bTargetAreaIsCardinalOfFear || bTargetAreaIsDeceitfulGod || bTargetAreaIsNeglect || bTargetAreaIsSasan || bTargetAreaIsValerius || bTargetAreaIsMists; // Check if opened activity needs to be opened on Mapdevice bool isMapDeviceActivity = bTargetAreaIsMap || bTargetAreaIsAtziri || bTargetAreaIsCata || bTargetAreaIsElder || bTargetAreaIsShaper || bTargetAreaIsSimu || bTargetAreaIsSafehouse || bTargetAreaIsSirusFight || bTargetAreaTemple || bTargetAreaIsMI || bTargetAreaIsMavenFight || bTargetAreaIsLogbook || bTargetAreaIsExarch || bTargetAreaIsBreachStone || bTargetAreaIsBlackStar || bTargetAreaIsInfinitetHunger || bTargetAreaIsEaterOfWorlds || bTargetAreaIsLegion || bTargetAreaIsTrialmaster || bTargetAreaIsUltimatum || bTargetAreaIsKalandra || bTargetAreaIsNeglectedFlame || bTargetAreaIsCardinalOfFear || bTargetAreaIsDeceitfulGod || bTargetAreaIsDread || bTargetAreaIsFear || bTargetAreaIsNeglect || bTargetAreaIsSasan || bTargetAreaIsValerius || bTargetAreaIsMists; if (enteringDefaultTrackableActivity) { if (_currentActivity == null) { _currentActivity = new TrX_TrackedActivity { Area = sTargetArea, Type = actType, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Started = ev.EventTime, TimeStamp = lTS, InstanceEndpoint = _currentInstanceEndpoint, }; _nextAreaLevel = 0; _nextAreaSeed = 0; _prevActivityOverlay = GetLastActivityByType(actType); OnActivityStarted(new TrX_CoreLogicActivityEventArgs(this, _currentActivity)); } else { if (bTargetAreaIsSimu || bTargetAreaIsMap) { _currentActivity.PortalsUsed++; } } if (!_currentActivity.ManuallyPaused) _currentActivity.StartStopWatch(); if (bSourceAreaIsMap && bTargetAreaIsMap) { if (!_isMapZana) { // entered Zana Map _isMapZana = true; _currentActivity.StopStopWatch(); if (_currentActivity.SideArea_ZanaMap == null) { _currentActivity.SideArea_ZanaMap = new TrX_TrackedActivity { Type = ACTIVITY_TYPES.MAP, Area = sTargetArea, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, Started = ev.EventTime, TimeStamp = lTS, }; _currentActivity.SideArea_ZanaMap.AddTag("zana-map"); _nextAreaLevel = 0; _nextAreaSeed = 0; } if (!_currentActivity.SideArea_ZanaMap.ManuallyPaused) _currentActivity.SideArea_ZanaMap.StartStopWatch(); } else { _isMapZana = false; // leave Zana Map if (_currentActivity.SideArea_ZanaMap != null) { _isMapZana = false; _currentActivity.SideArea_ZanaMap.StopStopWatch(); _currentActivity.SideArea_ZanaMap.LastEnded = ev.EventTime; if (!_currentActivity.ManuallyPaused) _currentActivity.StartStopWatch(); } } } else { _isMapZana = false; //TMP_DEBUG // Do not track Lab-Trials if ((!sSourceArea.Contains("Trial of")) && (_currentActivity.Type != ACTIVITY_TYPES.LABYRINTH) && (_currentActivity.Type != ACTIVITY_TYPES.DELVE) && (_currentActivity.Type != ACTIVITY_TYPES.TANES_LABORATORY)) { if (sTargetArea != _currentActivity.Area || _currentInstanceEndpoint != _currentActivity.InstanceEndpoint || _currentAreaSeed != _currentActivity.AreaSeed) { FinishActivity(_currentActivity, sTargetArea, actType, ev.EventTime); } } } } else // ENTERING AN AREA WHICH IS NOT AN DEFAULT ACTIVITY { // Set endtime when logouts if (_currentActivity != null && _currentActivity.Type != ACTIVITY_TYPES.LABYRINTH && _currentActivity.Type != ACTIVITY_TYPES.CAMPAIGN) { if (_currentActivity.Type == ACTIVITY_TYPES.BREACHSTONE && _defaultMappings.BreachstoneDomainAreas.Contains(sSourceArea)) { _currentActivity.StopStopWatch(); _currentActivity.LastEnded = ev.EventTime; } //TEST: Pause when left the source area if (sSourceArea == _currentActivity.Area || _defaultMappings.CampAreas.Contains(sTargetArea)) { _currentActivity.StopStopWatch(); _currentActivity.LastEnded = ev.EventTime; // PAUSE TIME if (_defaultMappings.PausableActivityTypes.Contains(_currentActivity.Type)) { if (_defaultMappings.CampAreas.Contains(sTargetArea) || (sTargetArea.Contains("Hideout") && !sTargetArea.Contains("Syndicate"))) { _currentActivity.StartPauseTime(ev.EventTime); } } } if (_currentActivity.SideArea_ZanaMap != null) { if (sSourceArea == _currentActivity.SideArea_ZanaMap.Area) { _currentActivity.SideArea_ZanaMap.StopStopWatch(); _currentActivity.SideArea_ZanaMap.LastEnded = ev.EventTime; } } } } _currentArea = sAreaName; } /// <summary> /// Handle player died event /// </summary> /// <param name="ev"></param> private void HandlePlayerDiedEvent(TrX_TrackingEvent ev) { string sPlayerName = ev.LogLine.Split(' ')[8]; if (!_knownPlayerNames.Contains(sPlayerName)) { IncrementStat("TotalKilledCount", ev.EventTime, 1); // Lab? if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LABYRINTH) { _currentActivity.DeathCounter = 1; FinishActivity(_currentActivity, null, ACTIVITY_TYPES.LABYRINTH, DateTime.Now); } if (!_defaultMappings.DeathCountEnabledAreas.Contains(_currentArea)) { return; } if (_currentActivity != null) { if (_isMapZana) { if (_currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.DeathCounter++; _currentActivity.SideArea_ZanaMap.LastEnded = ev.EventTime; } } else if (_isMapVaalArea) { if (_currentActivity.SideArea_VaalArea != null) { _currentActivity.SideArea_VaalArea.DeathCounter++; _currentActivity.SideArea_VaalArea.LastEnded = ev.EventTime; } } else if (_isMapSanctum) { if (_currentActivity.SideArea_Sanctum != null) { _currentActivity.SideArea_Sanctum.DeathCounter++; _currentActivity.SideArea_Sanctum.LastEnded = ev.EventTime; } } else if (_isMapAbyssArea) { if (_currentActivity.SideArea_AbyssArea != null) { _currentActivity.SideArea_AbyssArea.DeathCounter++; _currentActivity.SideArea_AbyssArea.LastEnded = ev.EventTime; } } else if (_isMapLabTrial) { if (_currentActivity.SideArea_LabTrial != null) { _currentActivity.SideArea_LabTrial.DeathCounter++; _currentActivity.SideArea_LabTrial.LastEnded = ev.EventTime; } } else if (_isMapLogbookSide) { if (_currentActivity.SideArea_LogbookSide != null) { _currentActivity.SideArea_LogbookSide.DeathCounter++; _currentActivity.SideArea_LogbookSide.LastEnded = ev.EventTime; } } else { _currentActivity.DeathCounter++; } } } } /// <summary> /// Handle single event. Routes more complex calcs to dedicated methods. /// </summary> /// <param name="ev"></param> /// <param name="bInit"></param> private void HandleSingleEvent(TrX_TrackingEvent ev) { try { switch (ev.EventType) { case EVENT_TYPES.ABNORMAL_DISCONNECT: if (_currentActivity != null) { _log.Info("Abnormal disconnect found in log. Finishing Map."); FinishActivity(_currentActivity, null, ACTIVITY_TYPES.MAP, ev.EventTime); } break; case EVENT_TYPES.POE_CLIENT_START: _StartedFlag = true; if (_currentActivity != null) { // Filter out non trackable ends, like town visits right before app close if (_currentActivity.LastEnded.Year < 2000) { _currentActivity = null; } else { _currentActivity.IsFinished = true; if (_currentActivity.SideArea_ZanaMap != null) { if (_currentActivity.SideArea_ZanaMap.LastEnded.Year < 2000) { _currentActivity.SideArea_ZanaMap = null; } else { _currentActivity.SideArea_ZanaMap.IsFinished = true; } } if (_currentActivity.SideArea_VaalArea != null) { if (_currentActivity.SideArea_VaalArea.LastEnded.Year < 2000) { _currentActivity.SideArea_VaalArea = null; } else { _currentActivity.SideArea_VaalArea.IsFinished = true; } } if (_currentActivity.SideArea_LogbookSide != null) { if (_currentActivity.SideArea_LogbookSide.LastEnded.Year < 2000) { _currentActivity.SideArea_LogbookSide = null; } else { _currentActivity.SideArea_LogbookSide.IsFinished = true; } } if (_currentActivity.SideArea_AbyssArea != null) { if (_currentActivity.SideArea_AbyssArea.LastEnded.Year < 2000) { _currentActivity.SideArea_AbyssArea = null; } else { _currentActivity.SideArea_AbyssArea.IsFinished = true; } } if (_currentActivity.SideArea_LabTrial != null) { if (_currentActivity.SideArea_LabTrial.LastEnded.Year < 2000) { _currentActivity.SideArea_LabTrial = null; } else { _currentActivity.SideArea_LabTrial.IsFinished = true; } } FinishActivity(_currentActivity, null, ACTIVITY_TYPES.MAP, ev.EventTime); } } if (_trackingHO) { _trackingHO = false; } break; case EVENT_TYPES.CHAT_CMD_RECEIVED: string sCmd = ev.LogLine.Split(new string[] { "::" }, StringSplitOptions.None)[1]; if (_eventQueueInitizalized) { HandleChatCommand(sCmd); } break; case EVENT_TYPES.ENTERED_AREA: HandleAreaChangeEvent(ev); break; case EVENT_TYPES.PLAYER_DIED: HandlePlayerDiedEvent(ev); break; case EVENT_TYPES.PLAYER_SUICIDE: IncrementStat("Suicides", ev.EventTime, 1); HandlePlayerDiedEvent(ev); break; case EVENT_TYPES.INSTANCE_CONNECTED: _currentInstanceEndpoint = GetEndpointFromInstanceEvent(ev); break; case EVENT_TYPES.TRIALMASTER_VICTORY: IncrementStat("TrialMasterSuccess", ev.EventTime, 1); IncrementStat("TrialMasterVictory", ev.EventTime, 1); if (_currentActivity != null && (_currentActivity.Type == ACTIVITY_TYPES.MAP || _currentActivity.Type == ACTIVITY_TYPES.CAMPAIGN || _currentActivity.Type == ACTIVITY_TYPES.INSCRIBED_ULTIMATUM)) { _currentActivity.AddTag("ultimatum"); _currentActivity.AddTag("ultimatum-win"); _currentActivity.TrialMasterSuccess = true; _currentActivity.TrialMasterFullFinished = true; } break; case EVENT_TYPES.TRIALMASTER_TOOK_REWARD: IncrementStat("TrialMasterTookReward", ev.EventTime, 1); IncrementStat("TrialMasterSuccess", ev.EventTime, 1); if (_currentActivity != null && (_currentActivity.Type == ACTIVITY_TYPES.MAP || _currentActivity.Type == ACTIVITY_TYPES.CAMPAIGN || _currentActivity.Type == ACTIVITY_TYPES.INSCRIBED_ULTIMATUM)) { _currentActivity.TrialMasterSuccess = true; _currentActivity.TrialMasterFullFinished = false; _currentActivity.AddTag("ultimatum"); _currentActivity.AddTag("ultimatum-took-reward"); } break; case EVENT_TYPES.TRIALMASTER_PLAYER_LOSS: if (_currentActivity != null && (_currentActivity.Type == ACTIVITY_TYPES.MAP || _currentActivity.Type == ACTIVITY_TYPES.CAMPAIGN || _currentActivity.Type == ACTIVITY_TYPES.INSCRIBED_ULTIMATUM)) { _currentActivity.TrialMasterSuccess = false; _currentActivity.TrialMasterFullFinished = false; _currentActivity.AddTag("ultimatum"); _currentActivity.AddTag("ultimatum-loss"); } break; case EVENT_TYPES.TRIALMASTER_ROUND_STARTED: if (_currentActivity != null && (_currentActivity.Type == ACTIVITY_TYPES.MAP || _currentActivity.Type == ACTIVITY_TYPES.CAMPAIGN || _currentActivity.Type == ACTIVITY_TYPES.INSCRIBED_ULTIMATUM)) { _currentActivity.AddTag("ultimatum"); _currentActivity.TrialMasterCount += 1; } break; case EVENT_TYPES.EINHAR_BEAST_CAPTURE: IncrementStat("EinharCaptures", ev.EventTime, 1); break; case EVENT_TYPES.PARTYMEMBER_ENTERED_AREA: AddKnownPlayerIfNotExists(ev.LogLine.Split(' ')[8]); break; case EVENT_TYPES.DELIRIUM_ENCOUNTER: if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("delirium"); } else { _currentActivity.AddTag("delirium"); } } break; case EVENT_TYPES.NAMELESSSEER_ENCOUNTER: IncrementStat("NamelessSeerEncounters", ev.EventTime, 1); if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("seer"); } else { _currentActivity.AddTag("seer"); } } break; case EVENT_TYPES.REFLECTINGMIST_ENCOUNTER: IncrementStat("ReflectingMistEncounters", ev.EventTime, 1); if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("mist"); } else { _currentActivity.AddTag("mist"); } } break; case EVENT_TYPES.MEMORYTEAR_ENCOUNTER: IncrementStat("MemoryTears", ev.EventTime, 1); if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("memory"); } else { _currentActivity.AddTag("memory"); } } break; case EVENT_TYPES.BLIGHT_ENCOUNTER: if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("blight"); } else { _currentActivity.AddTag("blight"); } } break; case EVENT_TYPES.EINHAR_ENCOUNTER: if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("einhar"); } else { _currentActivity.AddTag("einhar"); } } break; case EVENT_TYPES.INCURSION_ENCOUNTER: if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("incursion"); } else { _currentActivity.AddTag("incursion"); } } break; case EVENT_TYPES.NIKO_ENCOUNTER: if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("niko"); } else { _currentActivity.AddTag("niko"); } } break; case EVENT_TYPES.ZANA_ENCOUNTER: if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { _currentActivity.AddTag("zana"); } break; case EVENT_TYPES.SYNDICATE_ENCOUNTER: if (CheckIfAreaIsMap(_currentArea) && _currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { _currentActivity.SideArea_ZanaMap.AddTag("syndicate"); } else { _currentActivity.AddTag("syndicate"); } } break; case EVENT_TYPES.LEVELUP: bool bIsMySelf = true; foreach (string s in _knownPlayerNames) { if (ev.LogLine.Contains(s)) { bIsMySelf = false; break; } } if (bIsMySelf) { IncrementStat("LevelUps", ev.EventTime, 1); } break; case EVENT_TYPES.SIMULACRUM_FULLCLEAR: IncrementStat("SimulacrumCleared", ev.EventTime, 1); break; case EVENT_TYPES.LAB_FINISHED: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LABYRINTH) { IncrementStat("LabsFinished", ev.EventTime, 1); IncrementStat($"LabsCompleted_{_currentActivity.Area}", ev.EventTime, 1); _currentActivity.Success = true; PauseCurrentActivityOrSide(); } break; case EVENT_TYPES.LAB_START_INFO_RECEIVED: break; case EVENT_TYPES.NEXT_AREA_LEVEL_RECEIVED: string sLvl = ev.LogLine.Split(new string[] { "Generating level " }, StringSplitOptions.None)[1] .Split(' ')[0]; string sSeed = ev.LogLine.Split(new string[] { " with seed " }, StringSplitOptions.None)[1]; _nextAreaLevel = Convert.ToInt32(sLvl); _nextAreaSeed = Convert.ToInt64(sSeed); _currentAreaLevel = _nextAreaLevel; _currentAreaSeed = _nextAreaSeed; // Logbook check for cemetery & vaal temple if (ev.LogLine.Contains("Expedition")) { _nextAreaIsExp = true; } break; case EVENT_TYPES.EXP_DANNIG_ENCOUNTER: if (_currentActivity != null && !_currentActivity.HasTag("dannig") && _currentActivity.Type == ACTIVITY_TYPES.MAP) { IncrementStat("ExpeditionEncounters", ev.EventTime, 1); IncrementStat("ExpeditionEncounters_Dannig", ev.EventTime, 1); AddTagAutoCreate("expedition", _currentActivity); _currentActivity.Tags.Add("expedition"); _currentActivity.Tags.Add("dannig"); } break; case EVENT_TYPES.EXP_GWENNEN_ENCOUNTER: if (_currentActivity != null && !_currentActivity.HasTag("gwennen") && _currentActivity.Type == ACTIVITY_TYPES.MAP) { IncrementStat("ExpeditionEncounters", ev.EventTime, 1); IncrementStat("ExpeditionEncounters_Gwennen", ev.EventTime, 1); _currentActivity.Tags.Add("expedition"); _currentActivity.Tags.Add("gwennen"); } break; case EVENT_TYPES.EXP_TUJEN_ENCOUNTER: if (_currentActivity != null && !_currentActivity.HasTag("tujen") && _currentActivity.Type == ACTIVITY_TYPES.MAP) { IncrementStat("ExpeditionEncounters", ev.EventTime, 1); IncrementStat("ExpeditionEncounters_Tujen", ev.EventTime, 1); _currentActivity.Tags.Add("expedition"); _currentActivity.Tags.Add("tujen"); } break; case EVENT_TYPES.EXP_ROG_ENCOUNTER: if (_currentActivity != null && !_currentActivity.HasTag("rog") && _currentActivity.Type == ACTIVITY_TYPES.MAP) { IncrementStat("ExpeditionEncounters", ev.EventTime, 1); IncrementStat("ExpeditionEncounters_Rog", ev.EventTime, 1); _currentActivity.Tags.Add("expedition"); _currentActivity.Tags.Add("rog"); } break; case EVENT_TYPES.HEIST_GIANNA_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("gianna")) { _currentActivity.RougeCont++; _currentActivity.AddTag("gianna"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_HUCK_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("huck")) { _currentActivity.RougeCont++; _currentActivity.AddTag("huck"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_ISLA_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("isla")) { _currentActivity.RougeCont++; _currentActivity.AddTag("isla"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_NENET_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("nenet")) { _currentActivity.RougeCont++; _currentActivity.AddTag("nenet"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_NILES_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("niles")) { _currentActivity.RougeCont++; _currentActivity.AddTag("niles"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_TIBBS_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("tibbs")) { _currentActivity.RougeCont++; _currentActivity.AddTag("tibbs"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_TULLINA_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("tullina")) { _currentActivity.RougeCont++; _currentActivity.AddTag("tullina"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_VINDERI_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("vinderi")) { _currentActivity.RougeCont++; _currentActivity.AddTag("vinderi"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.HEIST_KARST_SPEAK: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.HEIST) { if (CheckIfAreaIsHeist(_currentArea, "The Rogue Harbour")) { if (!_currentActivity.HasTag("karst")) { _currentActivity.RougeCont++; _currentActivity.AddTag("karst"); if (_currentActivity.RougeCont >= 3) { _currentActivity.AddTag("blueprint"); } } } } break; case EVENT_TYPES.NEXT_CEMETERY_IS_LOGBOOK: _nextAreaIsExp = true; break; case EVENT_TYPES.TWICE_BLESSED: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.LABYRINTH) { _currentActivity.AddTag("twice-blessed"); } break; case EVENT_TYPES.HARVEST: if (_currentActivity != null && _currentActivity.Type == ACTIVITY_TYPES.MAP) { _currentActivity.AddTag("harvest"); } break; case EVENT_TYPES.SANCTUM_LYCIA_2_KILLED: IncrementStat("SanctumKilledLycia2", ev.EventTime); break; case EVENT_TYPES.SANCTUM_LYCIA_1_KILLED: IncrementStat("SanctumKilledLycia1", ev.EventTime); break; case EVENT_TYPES.ANCESTOR_MATCH_LOST: IncrementStat("AncestorMatchesLost", ev.EventTime); break; case EVENT_TYPES.ANCESTOR_MATCH_WON: IncrementStat("AncestorMatchesWon", ev.EventTime); break; case EVENT_TYPES.ANCESTOR_TOURNAMENT_LOST: IncrementStat("AncestorTournamentsLost", ev.EventTime); break; case EVENT_TYPES.ANCESTOR_TOURNAMENT_WON: IncrementStat("AncestorTournamentsWon", ev.EventTime); break; case EVENT_TYPES.TRIALMASTER_ENCOUNTERED: if (_currentActivity != null && (_currentActivity.Type == ACTIVITY_TYPES.MAP || _currentActivity.Type == ACTIVITY_TYPES.CAMPAIGN)) { _currentActivity.AddTag("ultimatum"); } break; } if (_eventQueueInitizalized) { SaveStatsCache(); } } catch (Exception ex) { _log.Error($"Error handling event: {ex.Message}."); _log.Debug(ex.ToString()); } } /// <summary> /// Increment a stat with an defined value. Updates the database. /// /// </summary> /// <param name="s_key"></param> /// <param name="dt"></param> /// <param name="i_value">default=1</param> private void IncrementStat(string s_key, DateTime dt, int i_value = 1) { _myStats.IncrementStat(s_key, dt, i_value); } /// <summary> /// Update a stat with a fixed value. Updates the database /// </summary> /// <param name="s_key"></param> /// <param name="dt"></param> /// <param name="i_value"></param> private void SetStat(string s_key, DateTime dt, int i_value) { _myStats.SetStat(s_key, dt, i_value); } /// <summary> /// Extract the instance endpoint from a log line. /// </summary> /// <param name="ev"></param> /// <returns></returns> private string GetEndpointFromInstanceEvent(TrX_TrackingEvent ev) { return ev.LogLine.Split(new String[] { "Connecting to instance server at " }, StringSplitOptions.None)[1]; } /// <summary> /// Get most recent activity with given type /// </summary> /// <param name="type"></param> /// <returns></returns> private TrX_TrackedActivity GetLastActivityByType(ACTIVITY_TYPES type) { List<TrX_TrackedActivity> list = new List<TrX_TrackedActivity>(); foreach (TrX_TrackedActivity act in _eventHistory) { if (act.Type == type) list.Add(act); } if (list.Count > 0) return list[0]; return null; } /// <summary> /// Finishs the current activity. /// </summary> /// <param name="activity"></param> /// <param name="sNextMap">next map to start. Set to null if there is none</param> /// <param name="sNextMapType"></param> /// <param name="dtNextMapStarted"></param> public void FinishActivity(TrX_TrackedActivity activity, string sNextMap, ACTIVITY_TYPES sNextMapType, DateTime dtNextMapStarted, bool stats_only = false) { _log.Debug($"Finishing activity: {activity.UniqueID} | Started: {activity.Started}"); _currentActivity.StopStopWatch(); bool isValid = true; if (!stats_only) { TimeSpan ts = new TimeSpan(); TimeSpan tsZana = new TimeSpan(); TimeSpan tsVaal = new TimeSpan(); TimeSpan tsBlackKnight = new TimeSpan(); TimeSpan tsAbyss = new TimeSpan(); TimeSpan tsLabTrial = new TimeSpan(); TimeSpan tsLogbookSide = new TimeSpan(); TimeSpan tsSanctum = new TimeSpan(); int totalSecondsMainActivity; int totalSecondsZanaMap = 0; int totalSecondsVallSideArea = 0; int totalSecondsBlackKnightSideArea = 0; int totalSecondsSanctum = 0; int totalSecondsAbyss = 0; int totalSecondsLabTrial = 0; int totalSecondsLogBookSide = 0; // Filter out invalid labs (discnnect etc) if (activity.Type == ACTIVITY_TYPES.LABYRINTH) { if (activity.Area == "Unknown") { // no area changes logged for some old lab runs :/ activity.Success = activity.DeathCounter == 0; } // Labs must be successfull or death counter 1 if ((activity.Success != true && activity.DeathCounter == 0) && (activity).TrialCount < 3) { _log.Warn($"Filtered out lab run [time={activity.Started}, area: {activity.Area}]. Reason Success=False AND DeathCounter = 0. Maybe disconnect or game crash while lab."); _currentActivity = null; return; } } // When parsing at startup if (!_eventQueueInitizalized) { ts = (activity.LastEnded - activity.Started); try { totalSecondsMainActivity = Convert.ToInt32(ts.TotalSeconds); totalSecondsMainActivity -= Convert.ToInt32(activity.PausedTime); } catch { totalSecondsMainActivity = 0; } if (activity.SideArea_ZanaMap != null) { tsZana = (activity.SideArea_ZanaMap.LastEnded - activity.SideArea_ZanaMap.Started); } if (activity.SideArea_VaalArea != null) { tsVaal = (activity.SideArea_VaalArea.LastEnded - activity.SideArea_VaalArea.Started); } if (activity.SideArea_BlackKnight != null) { tsBlackKnight = (activity.SideArea_BlackKnight.LastEnded - activity.SideArea_BlackKnight.Started); } if (activity.SideArea_Sanctum != null) { tsSanctum = (activity.SideArea_Sanctum.LastEnded - activity.SideArea_Sanctum.Started); } if (activity.SideArea_LogbookSide != null) { tsLogbookSide = (activity.SideArea_LogbookSide.LastEnded - activity.SideArea_LogbookSide.Started); } if (activity.SideArea_AbyssArea != null) { tsAbyss = (activity.SideArea_AbyssArea.LastEnded - activity.SideArea_AbyssArea.Started); } if (activity.SideArea_LabTrial != null) { tsLabTrial = (activity.SideArea_LabTrial.LastEnded - activity.SideArea_LabTrial.Started); } // Filter out town activities without end date if (activity.LastEnded.Year < 2000) { isValid = false; } // Filter out 0-second town visits if (activity.Type == ACTIVITY_TYPES.CAMPAIGN && totalSecondsMainActivity == 0) { isValid = false; } } else // when tracking live { ts = activity.StopWatchTimeSpan; totalSecondsMainActivity = Convert.ToInt32(ts.TotalSeconds); if (activity.SideArea_ZanaMap != null) { tsZana = activity.SideArea_ZanaMap.StopWatchTimeSpan; } if (activity.SideArea_VaalArea != null) { tsVaal = (activity.SideArea_VaalArea.StopWatchTimeSpan); } if (activity.SideArea_BlackKnight != null) { tsVaal = (activity.SideArea_BlackKnight.StopWatchTimeSpan); } if (activity.SideArea_Sanctum != null) { tsSanctum = (activity.SideArea_Sanctum.StopWatchTimeSpan); } if (activity.SideArea_LogbookSide != null) { tsLogbookSide = (activity.SideArea_LogbookSide.StopWatchTimeSpan); } if (activity.SideArea_AbyssArea != null) { tsAbyss = (activity.SideArea_AbyssArea.StopWatchTimeSpan); } if (activity.SideArea_LabTrial != null) { tsLabTrial = (activity.SideArea_LabTrial.StopWatchTimeSpan); } } // Calculate times totalSecondsZanaMap = Convert.ToInt32(tsZana.TotalSeconds); // historic, no zana side aras totalSecondsVallSideArea = Convert.ToInt32(tsVaal.TotalSeconds); totalSecondsBlackKnightSideArea = Convert.ToInt32(tsBlackKnight.TotalSeconds); totalSecondsLogBookSide = Convert.ToInt32(tsLogbookSide.TotalSeconds); totalSecondsAbyss = Convert.ToInt32(tsAbyss.TotalSeconds); totalSecondsLabTrial = Convert.ToInt32(tsLabTrial.TotalSeconds); totalSecondsSanctum = Convert.ToInt32(tsSanctum.TotalSeconds); if (isValid) { _currentActivity.TotalSeconds = totalSecondsMainActivity; bool greaterThenMinCap = totalSecondsMainActivity > _timeCapMin; if (!_eventHistory.Contains(_currentActivity)) { if (greaterThenMinCap) { _eventHistory.Insert(0, _currentActivity); } } TimeSpan tsMain = TimeSpan.FromSeconds(totalSecondsMainActivity); activity.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsMain.Hours, tsMain.Minutes, tsMain.Seconds); if (!_parsedActivities.Contains(activity.UniqueID)) { // Save to DB SaveToActivityLog(((DateTimeOffset)activity.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.Type), activity.Area, activity.AreaLevel, totalSecondsMainActivity, activity.DeathCounter, activity.TrialMasterCount, false, activity.Tags, activity.Success, Convert.ToInt32(activity.PausedTime)); } if (activity.SideArea_ZanaMap != null) { TimeSpan tsZanaMap = TimeSpan.FromSeconds(totalSecondsZanaMap); activity.SideArea_ZanaMap.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsZanaMap.Hours, tsZanaMap.Minutes, tsZanaMap.Seconds); activity.SideArea_ZanaMap.TotalSeconds = totalSecondsZanaMap; if (greaterThenMinCap) _eventHistory.Insert(0, _currentActivity.SideArea_ZanaMap); if (!_parsedActivities.Contains(activity.SideArea_ZanaMap.UniqueID)) { //Save to DB SaveToActivityLog(((DateTimeOffset)activity.SideArea_ZanaMap.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.SideArea_ZanaMap.Type), activity.SideArea_ZanaMap.Area, activity.SideArea_ZanaMap.AreaLevel, totalSecondsZanaMap, activity.SideArea_ZanaMap.DeathCounter, activity.SideArea_ZanaMap.TrialMasterCount, true, activity.SideArea_ZanaMap .Tags, activity.SideArea_ZanaMap.Success, Convert.ToInt32(activity.SideArea_ZanaMap.PausedTime)); } } if (activity.SideArea_VaalArea != null) { TimeSpan tsVaalMap = TimeSpan.FromSeconds(totalSecondsVallSideArea); activity.SideArea_VaalArea.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsVaalMap.Hours, tsVaalMap.Minutes, tsVaalMap.Seconds); activity.SideArea_VaalArea.TotalSeconds = totalSecondsVallSideArea; if (greaterThenMinCap) _eventHistory.Insert(0, _currentActivity.SideArea_VaalArea); if (!_parsedActivities.Contains(activity.SideArea_VaalArea.UniqueID)) { //Save to DB SaveToActivityLog(((DateTimeOffset)activity.SideArea_VaalArea.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.SideArea_VaalArea.Type), activity.SideArea_VaalArea.Area, activity.SideArea_VaalArea.AreaLevel, totalSecondsVallSideArea, activity.SideArea_VaalArea.DeathCounter, activity.SideArea_VaalArea.TrialMasterCount, true, activity.SideArea_VaalArea .Tags, activity.SideArea_VaalArea.Success, Convert.ToInt32(activity.SideArea_VaalArea.PausedTime)); } } if (activity.SideArea_BlackKnight != null) { TimeSpan tsBlackKnightMap = TimeSpan.FromSeconds(totalSecondsBlackKnightSideArea); activity.SideArea_BlackKnight.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsBlackKnightMap.Hours, tsBlackKnightMap.Minutes, tsBlackKnightMap.Seconds); activity.SideArea_BlackKnight.TotalSeconds = totalSecondsBlackKnightSideArea; if (greaterThenMinCap) _eventHistory.Insert(0, _currentActivity.SideArea_BlackKnight); if (!_parsedActivities.Contains(activity.SideArea_BlackKnight.UniqueID)) { //Save to DB SaveToActivityLog(((DateTimeOffset)activity.SideArea_BlackKnight.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.SideArea_BlackKnight.Type), activity.SideArea_BlackKnight.Area, activity.SideArea_BlackKnight.AreaLevel, totalSecondsBlackKnightSideArea, activity.SideArea_BlackKnight.DeathCounter, activity.SideArea_BlackKnight.TrialMasterCount, true, activity.SideArea_BlackKnight .Tags, activity.SideArea_BlackKnight.Success, Convert.ToInt32(activity.SideArea_BlackKnight.PausedTime)); } } if (activity.SideArea_Sanctum != null) { TimeSpan tsSanctumArea = TimeSpan.FromSeconds(totalSecondsSanctum); activity.SideArea_Sanctum.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsSanctumArea.Hours, tsSanctumArea.Minutes, tsSanctumArea.Seconds); activity.SideArea_Sanctum.TotalSeconds = totalSecondsSanctum; if (greaterThenMinCap) _eventHistory.Insert(0, _currentActivity.SideArea_Sanctum); if (!_parsedActivities.Contains(activity.SideArea_Sanctum.UniqueID)) { //Save to DB SaveToActivityLog(((DateTimeOffset)activity.SideArea_Sanctum.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.SideArea_Sanctum.Type), activity.SideArea_Sanctum.Area, activity.SideArea_Sanctum.AreaLevel, totalSecondsSanctum, activity.SideArea_Sanctum.DeathCounter, activity.SideArea_Sanctum.TrialMasterCount, true, activity.SideArea_Sanctum .Tags, activity.SideArea_Sanctum.Success, Convert.ToInt32(activity.SideArea_Sanctum.PausedTime)); } } if (activity.SideArea_LogbookSide != null) { TimeSpan tsLBSide = TimeSpan.FromSeconds(totalSecondsLogBookSide); activity.SideArea_LogbookSide.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsLBSide.Hours, tsLBSide.Minutes, tsLBSide.Seconds); activity.SideArea_LogbookSide.TotalSeconds = totalSecondsLogBookSide; if (greaterThenMinCap) _eventHistory.Insert(0, _currentActivity.SideArea_LogbookSide); if (!_parsedActivities.Contains(activity.SideArea_LogbookSide.UniqueID)) { //Save to DB SaveToActivityLog(((DateTimeOffset)activity.SideArea_LogbookSide.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.SideArea_LogbookSide.Type), activity.SideArea_LogbookSide.Area, activity.SideArea_LogbookSide.AreaLevel, totalSecondsVallSideArea, activity.SideArea_LogbookSide.DeathCounter, activity.SideArea_LogbookSide.TrialMasterCount, true, activity.SideArea_LogbookSide .Tags, activity.SideArea_LogbookSide.Success, Convert.ToInt32(activity.SideArea_LogbookSide.PausedTime)); } } if (activity.SideArea_AbyssArea != null) { TimeSpan tsAbyssMap = TimeSpan.FromSeconds(totalSecondsAbyss); activity.SideArea_AbyssArea.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsAbyssMap.Hours, tsAbyssMap.Minutes, tsAbyssMap.Seconds); activity.SideArea_AbyssArea.TotalSeconds = totalSecondsAbyss; if (greaterThenMinCap) _eventHistory.Insert(0, _currentActivity.SideArea_AbyssArea); if (!_parsedActivities.Contains(activity.SideArea_AbyssArea.UniqueID)) { //Save to DB SaveToActivityLog(((DateTimeOffset)activity.SideArea_AbyssArea.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.SideArea_AbyssArea.Type), activity.SideArea_AbyssArea.Area, activity.SideArea_AbyssArea.AreaLevel, totalSecondsAbyss, activity.SideArea_AbyssArea.DeathCounter, activity.SideArea_AbyssArea.TrialMasterCount, true, activity.SideArea_AbyssArea .Tags, activity.SideArea_AbyssArea.Success, Convert.ToInt32(activity.SideArea_AbyssArea.PausedTime)); } } if (activity.SideArea_LabTrial != null) { TimeSpan tsLabTrial2 = TimeSpan.FromSeconds(totalSecondsLabTrial); activity.SideArea_LabTrial.CustomStopWatchValue = String.Format("{0:00}:{1:00}:{2:00}", tsLabTrial2.Hours, tsLabTrial2.Minutes, tsLabTrial2.Seconds); if (greaterThenMinCap) _eventHistory.Insert(0, _currentActivity.SideArea_LabTrial); if (!_parsedActivities.Contains(activity.SideArea_LabTrial.UniqueID)) { //Save to DB SaveToActivityLog(((DateTimeOffset)activity.SideArea_LabTrial.Started).ToUnixTimeSeconds(), GetStringFromActType(activity.SideArea_LabTrial.Type), activity.SideArea_LabTrial.Area, activity.SideArea_LabTrial.AreaLevel, totalSecondsLabTrial, activity.SideArea_LabTrial.DeathCounter, activity.SideArea_LabTrial.TrialMasterCount, true, activity.SideArea_LabTrial .Tags, activity.SideArea_LabTrial.Success, Convert.ToInt32(activity.SideArea_LabTrial.PausedTime)); } } // Trigger event if (greaterThenMinCap) { OnActivityFinished(new TrX_CoreLogicActivityEventArgs(this, activity)); } } else { _log.Warn($"Filtered out invalid activity: {activity.UniqueID}, Started: {activity.Started}, LastEnded: {activity.LastEnded}, Type: {activity.Type}, Instance: {activity.InstanceEndpoint}"); } if (activity.Type == ACTIVITY_TYPES.HEIST) { IncrementStat("TotalHeistsDone", activity.Started, 1); } else if (activity.Type == ACTIVITY_TYPES.MAP) { IncrementStat("TotalMapsDone", activity.Started, 1); if (activity.SideArea_ZanaMap != null) { IncrementStat("TotalMapsDone", activity.SideArea_ZanaMap.Started, 1); } } else if (activity.Type == ACTIVITY_TYPES.TEMPLE) { IncrementStat("TemplesDone", activity.Started, 1); } } if (sNextMap != null) { _prevActivityOverlay = GetLastActivityByType(sNextMapType); _currentActivity = new TrX_TrackedActivity { Area = sNextMap, Type = sNextMapType, AreaLevel = _nextAreaLevel, AreaSeed = _nextAreaSeed, InstanceEndpoint = _currentInstanceEndpoint, Started = dtNextMapStarted, TimeStamp = ((DateTimeOffset)dtNextMapStarted).ToUnixTimeSeconds() }; _nextAreaLevel = 0; _nextAreaSeed = 0; _currentActivity.StartStopWatch(); OnActivityStarted(new TrX_CoreLogicActivityEventArgs(this, _currentActivity)); } else { _currentActivity = null; } } /// <summary> /// Simply save the current app version to VERSION.txt /// </summary> private void SaveVersion() { StreamWriter wrt = new StreamWriter(TrX_Static.VERSION_FILE_PATH); wrt.WriteLine(TrX_Static.VERSION); wrt.Close(); } /// <summary> /// Get name of a given Breachstone /// </summary> /// <param name="s_ara"></param> /// <param name="i_area_level"></param> /// <returns></returns> public string GetBreachStoneName(string s_ara, int i_area_level) { string breachLoard = ""; string breachStoneQuality = ""; switch (s_ara) { case "Chayulas Domain": breachLoard = "Chayulas"; switch (i_area_level) { // Normal case 80: breachStoneQuality = ""; break; // Charged case 81: breachStoneQuality = "Charged"; break; // Enriched case 82: breachStoneQuality = "Enriched"; break; // Pure case 83: breachStoneQuality = "Pure"; break; // Flawless case 84: breachStoneQuality = "Flawless"; break; } break; case "Eshs Domain": breachLoard = "Eshs"; switch (i_area_level) { // Normal case 70: breachStoneQuality = ""; break; // Charged case 74: breachStoneQuality = "Charged"; break; // Enriched case 79: breachStoneQuality = "Enriched"; break; // Pure case 81: breachStoneQuality = "Pure"; break; // Flawless case 84: breachStoneQuality = "Flawless"; break; } break; case "Xophs Domain": breachLoard = "Xophs"; switch (i_area_level) { // Normal case 70: breachStoneQuality = ""; break; // Charged case 74: breachStoneQuality = "Charged"; break; // Enriched case 79: breachStoneQuality = "Enriched"; break; // Pure case 81: breachStoneQuality = "Pure"; break; // Flawless case 84: breachStoneQuality = "Flawless"; break; } break; case "Uul-Netols Domain": breachLoard = "Uul-Netols"; switch (i_area_level) { // Normal case 75: breachStoneQuality = ""; break; // Charged case 78: breachStoneQuality = "Charged"; break; // Enriched case 81: breachStoneQuality = "Enriched"; break; // Pure case 82: breachStoneQuality = "Pure"; break; // Flawless case 84: breachStoneQuality = "Flawless"; break; } break; case "Tuls Domain": breachLoard = "Tuls"; switch (i_area_level) { // Normal case 70: breachStoneQuality = ""; break; // Charged case 74: breachStoneQuality = "Charged"; break; // Enriched case 79: breachStoneQuality = "Enriched"; break; // Pure case 81: breachStoneQuality = "Pure"; break; // Flawless case 84: breachStoneQuality = "Flawless"; break; } break; } if (string.IsNullOrEmpty(breachStoneQuality)) { return string.Format("{0} {1}", breachLoard, "Breachstone"); } else { return string.Format("{0} {1} {2}", breachLoard, breachStoneQuality, "Breachstone"); } } public int GetImageIndex(TrX_TrackedActivity map) { int iIndex = 0; // Calculate Image Index if (map.Type == ACTIVITY_TYPES.MAP) { if (map.MapTier > 0 && map.MapTier <= 5) { iIndex = 0; } else if (map.MapTier >= 6 && map.MapTier <= 10) { iIndex = 1; } else if (map.MapTier >= 11) { iIndex = 2; } } else if (map.Type == ACTIVITY_TYPES.TEMPLE) { iIndex = 3; } else if (map.Type == ACTIVITY_TYPES.HEIST) { iIndex = 4; } else if (map.Type == ACTIVITY_TYPES.ABYSSAL_DEPTHS) { iIndex = 5; } else if (map.Type == ACTIVITY_TYPES.LABYRINTH || map.Type == ACTIVITY_TYPES.LAB_TRIAL) { iIndex = 6; } else if (map.Type == ACTIVITY_TYPES.CAMPAIGN) { iIndex = 7; } else if (map.Type == ACTIVITY_TYPES.LOGBOOK || map.Type == ACTIVITY_TYPES.LOGBOOK_SIDE) { iIndex = 8; } else if (map.Type == ACTIVITY_TYPES.VAAL_SIDEAREA) { iIndex = 9; } else if (map.Type == ACTIVITY_TYPES.CATARINA_FIGHT) { iIndex = 10; } else if (map.Type == ACTIVITY_TYPES.SAFEHOUSE) { iIndex = 11; } else if (map.Type == ACTIVITY_TYPES.DELVE) { iIndex = 12; } else if (map.Type == ACTIVITY_TYPES.MAVEN_INVITATION) { iIndex = 13; } else if (map.Type == ACTIVITY_TYPES.SIRUS_FIGHT) { iIndex = 14; } else if (map.Type == ACTIVITY_TYPES.ATZIRI) { iIndex = 15; } else if (map.Type == ACTIVITY_TYPES.UBER_ATZIRI) { iIndex = 16; } else if (map.Type == ACTIVITY_TYPES.ELDER_FIGHT) { iIndex = 17; } else if (map.Type == ACTIVITY_TYPES.SHAPER_FIGHT) { iIndex = 18; } else if (map.Type == ACTIVITY_TYPES.SIMULACRUM) { iIndex = 19; } else if (map.Type == ACTIVITY_TYPES.MAVEN_FIGHT) { iIndex = 20; } else if (map.Type == ACTIVITY_TYPES.INCARNATION_OF_DREAD_FIGHT) // Dread { iIndex = 46; } else if (map.Type == ACTIVITY_TYPES.INCARNATION_OF_FEAR_FIGHT) // Fear { iIndex = 47; } else if (map.Type == ACTIVITY_TYPES.INCARNATION_OF_NEGLECT_FIGHT) // Neglect { iIndex = 48; } else if (map.Type == ACTIVITY_TYPES.BREACHSTONE) { if (map.Area.Contains("Chayula")) { switch (map.AreaLevel) { // Normal case 80: iIndex = 21; break; // Charged case 81: iIndex = 41; break; // Enriched case 82: iIndex = 40; break; // Pure case 83: iIndex = 39; break; // Flawless case 84: iIndex = 38; break; } } else if (map.Area.Contains("Esh")) { switch (map.AreaLevel) { // Normal case 70: iIndex = 22; break; // Charged case 74: iIndex = 45; break; // Enriched case 79: iIndex = 44; break; // Pure case 81: iIndex = 43; break; // Flawless case 84: iIndex = 42; break; } } else if (map.Area.Contains("Xoph")) { switch (map.AreaLevel) { // Normal case 70: iIndex = 23; break; // Charged case 74: iIndex = 37; break; // Enriched case 79: iIndex = 36; break; // Pure case 81: iIndex = 35; break; // Flawless case 84: iIndex = 34; break; } } else if (map.Area.Contains("Uul-Netol")) { switch (map.AreaLevel) { // Normal case 75: iIndex = 24; break; // Charged case 78: iIndex = 33; break; // Enriched case 81: iIndex = 32; break; // Pure case 82: iIndex = 31; break; // Flawless case 84: iIndex = 30; break; } } else if (map.Area.Contains("Tul")) { switch (map.AreaLevel) { // Normal case 70: iIndex = 25; break; // Charged case 74: iIndex = 29; break; // Enriched case 79: iIndex = 28; break; // Pure case 81: iIndex = 27; break; // Flawless case 84: iIndex = 26; break; } } } return iIndex; } /// <summary> /// Convert an activity type to string /// </summary> /// <param name="a_type"></param> /// <returns></returns> private string GetStringFromActType(ACTIVITY_TYPES a_type) { return a_type.ToString().ToLower(); } /// <summary> /// Extract an arae name out of a log line /// </summary> /// <param name="ev"></param> /// <returns></returns> private string GetAreaNameFromEvent(TrX_TrackingEvent ev) { string sArea = ev.LogLine.Split(new string[] { "You have entered" }, StringSplitOptions.None)[1] .Replace(".", "").Trim(); return sArea.Replace("'", ""); } /// <summary> /// Get activity tag object for ID /// </summary> /// <param name="s_id"></param> /// <returns></returns> public TrX_ActivityTag GetTagByID(string s_id) { foreach (TrX_ActivityTag tag in _tags) { if (tag.ID == s_id) return tag; } return null; } /// <summary> /// Export Activity log to CSV /// </summary> /// <param name="sPath"></param> public void WriteActivitiesToCSV(string sPath) { StreamWriter wrt = new StreamWriter(sPath); TrX_TrackedActivity tm; //Write headline string sLine = "time;type;area;area_level;stopwatch;death_counter"; wrt.WriteLine(sLine); for (int i = 0; i < _eventHistory.Count; i++) { tm = _eventHistory[i]; sLine = ""; sLine += tm.Started; sLine += ";" + tm.Type; sLine += ";" + tm.Area; sLine += ";" + tm.AreaLevel; sLine += ";" + tm.StopWatchValue; sLine += ";" + tm.DeathCounter; wrt.WriteLine(sLine); } wrt.Close(); } /// <summary> /// Add a new tag /// </summary> /// <param name="tag"></param> private void AddTag(TrX_ActivityTag tag) { _tags.Add(tag); _dataBackend.DoNonQuery("INSERT INTO tx_tags (tag_id, tag_display, tag_bgcolor, tag_forecolor, tag_type, tag_show_in_lv) VALUES " + "('" + tag.ID + "', '" + tag.DisplayName + "', '" + tag.BackColor.ToArgb() + "', '" + tag.ForeColor.ToArgb() + "', 'custom', " + (tag.ShowInListView ? "1" : "0") + ")"); // Trigger event OnTagsUpdated(new TrX_CoreLogicGenericEventArgs(this)); } /// <summary> /// Add tag. Create if not exists /// </summary> /// <param name="s_id"></param> /// <param name="act"></param> public void AddTagAutoCreate(string s_id, TrX_TrackedActivity act) { int iIndex = GetTagIndex(s_id); TrX_ActivityTag tag; if (true) // TODO { if (iIndex < 0) { tag = new TrX_ActivityTag(s_id, false) { BackColor = Color.White, ForeColor = Color.Black }; AddTag(tag); } else { tag = _tags[iIndex]; } if (!tag.IsDefault) { act.AddTag(tag.ID); string sTags = ""; // Update tags in DB // TODO for (int i = 0; i < act.Tags.Count; i++) { sTags += act.Tags[i]; if (i < (act.Tags.Count - 1)) sTags += "|"; } _dataBackend.DoNonQuery("UPDATE tx_activity_log SET act_tags = '" + sTags + "' WHERE timestamp = " + act.TimeStamp.ToString()); } } } public void RemoveTagFromActivity(string s_id, TrX_TrackedActivity act) { TrX_ActivityTag tag = GetTagByID(s_id); if (tag != null && !tag.IsDefault) { act.RemoveTag(s_id); string sTags = ""; // Update tags in DB // TODO for (int i = 0; i < act.Tags.Count; i++) { sTags += act.Tags[i]; if (i < (act.Tags.Count - 1)) sTags += "|"; _dataBackend.DoNonQuery("UPDATE tx_activity_log SET act_tags = '" + sTags + "' WHERE timestamp = " + act.TimeStamp.ToString()); } } } private int GetTagIndex(string s_id) { for (int i = 0; i < _tags.Count; i++) { if (_tags[i].ID == s_id) { return i; } } return -1; } public void PauseCurrentActivityOrSide() { if (_currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { if (!_currentActivity.SideArea_ZanaMap.ManuallyPaused) { _currentActivity.SideArea_ZanaMap.Pause(); } } else if (_isMapVaalArea && _currentActivity.SideArea_VaalArea != null) { if (!_currentActivity.SideArea_VaalArea.ManuallyPaused) { _currentActivity.SideArea_VaalArea.Pause(); } } else if (_isMapAbyssArea && _currentActivity.SideArea_AbyssArea != null) { if (!_currentActivity.SideArea_AbyssArea.ManuallyPaused) { _currentActivity.SideArea_AbyssArea.Pause(); } } else if (_isMapLabTrial && _currentActivity.SideArea_LabTrial != null) { if (!_currentActivity.SideArea_LabTrial.ManuallyPaused) { _currentActivity.SideArea_LabTrial.Pause(); } } else if (_isMapLogbookSide && _currentActivity.SideArea_LogbookSide != null) { if (!_currentActivity.SideArea_LogbookSide.ManuallyPaused) { _currentActivity.SideArea_LogbookSide.Pause(); } } else { if (!_currentActivity.ManuallyPaused) { _currentActivity.Pause(); } } } } public void ResumeCurrentActivityOrSide() { if (_currentActivity != null) { if (_isMapZana && _currentActivity.SideArea_ZanaMap != null) { if (_currentActivity.SideArea_ZanaMap.ManuallyPaused) { _currentActivity.SideArea_ZanaMap.Resume(); } } else if (_isMapVaalArea && _currentActivity.SideArea_VaalArea != null) { if (_currentActivity.SideArea_VaalArea.ManuallyPaused) { _currentActivity.SideArea_VaalArea.Resume(); } } else if (_isMapAbyssArea && _currentActivity.SideArea_AbyssArea != null) { if (_currentActivity.SideArea_AbyssArea.ManuallyPaused) { _currentActivity.SideArea_AbyssArea.Resume(); } } else if (_isMapLabTrial && _currentActivity.SideArea_LabTrial != null) { if (_currentActivity.SideArea_LabTrial.ManuallyPaused) { _currentActivity.SideArea_LabTrial.Resume(); } } else if (_isMapLogbookSide && _currentActivity.SideArea_LogbookSide != null) { if (_currentActivity.SideArea_LogbookSide.ManuallyPaused) { _currentActivity.SideArea_LogbookSide.Resume(); } } else { if (_currentActivity.ManuallyPaused) { _currentActivity.Resume(); } } } } } }
1
0.979923
1
0.979923
game-dev
MEDIA
0.379387
game-dev
0.779624
1
0.779624
Mercury-Language/mercury
1,235
tests/valid/mostly_uniq_neg.m
%---------------------------------------------------------------------------% % vim: ts=4 sw=4 et ft=mercury %---------------------------------------------------------------------------% % % A regression test, adapted from a bug report by Ralph Becket. % Mercury 0.8.1 and earlier reported a spurious mode error for this code. :- module mostly_uniq_neg. :- interface. :- import_module list. :- import_module store. :- type term(S) == store_mutvar(term_type(S), S). :- type var(S) == term(S). :- type term_type(S) ---> free ; functor(string, int, list(term(S))). :- pred unify(term(S)::in, term_type(S)::in, term(S)::in, term_type(S)::in, store(S)::mdi, store(S)::muo) is semidet. :- implementation. :- pred occurs(var(S)::in, list(term(S))::in, store(S)::mdi, store(S)::muo) is semidet. :- pragma no_inline(occurs/4). occurs(_, _, !S) :- semidet_true. :- pred tr_store_set_mutvar(store_mutvar(T, S)::in, T::in, store(S)::mdi, store(S)::muo) is det. :- pragma no_inline(tr_store_set_mutvar/4). tr_store_set_mutvar(_, _, S, S). unify(T1, free, _T2, functor(Name2, Arity2, Args2), !Store) :- not occurs(T1, Args2, !Store), tr_store_set_mutvar(T1, functor(Name2, Arity2, Args2), !Store).
1
0.559237
1
0.559237
game-dev
MEDIA
0.788665
game-dev
0.671066
1
0.671066
samdauwe/BabylonCpp
1,151
src/BabylonCpp/src/collisions/intersection_info.cpp
#include <babylon/collisions/intersection_info.h> namespace BABYLON { IntersectionInfo::IntersectionInfo() : bu{std::nullopt}, bv{std::nullopt}, distance{0.f}, faceId{0}, subMeshId{0} { } IntersectionInfo::IntersectionInfo(float _distance) : bu{std::nullopt} , bv{std::nullopt} , distance{_distance} , faceId{0} , subMeshId{0} { } IntersectionInfo::IntersectionInfo(float _bu, float _bv, float _distance) : bu{_bu}, bv{_bv}, distance{_distance}, faceId{0}, subMeshId{0} { } IntersectionInfo::IntersectionInfo(const IntersectionInfo& other) = default; IntersectionInfo::IntersectionInfo(IntersectionInfo&& other) = default; IntersectionInfo& IntersectionInfo::operator=(const IntersectionInfo& other) = default; IntersectionInfo& IntersectionInfo::operator=(IntersectionInfo&& other) { if (&other != this) { bu = std::move(other.bu); bv = std::move(other.bv); distance = std::move(other.distance); faceId = std::move(other.faceId); subMeshId = std::move(other.subMeshId); } return *this; } IntersectionInfo::~IntersectionInfo() = default; } // end of namespace BABYLON
1
0.841985
1
0.841985
game-dev
MEDIA
0.327883
game-dev
0.710629
1
0.710629
chukong/quick-cocos2d-x
25,497
lib/cocos2d-x/cocos2dx/CCScheduler.cpp
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCScheduler.h" #include "ccMacros.h" #include "CCDirector.h" #include "support/data_support/utlist.h" #include "support/data_support/ccCArray.h" #include "cocoa/CCArray.h" #include "script_support/CCScriptSupport.h" using namespace std; NS_CC_BEGIN // data structures // A list double-linked list used for "updates with priority" typedef struct _listEntry { struct _listEntry *prev, *next; CCObject *target; // not retained (retained by hashUpdateEntry) int priority; bool paused; bool markedForDeletion; // selector will no longer be called and entry will be removed at end of the next tick } tListEntry; typedef struct _hashUpdateEntry { tListEntry **list; // Which list does it belong to ? tListEntry *entry; // entry in the list CCObject *target; // hash key (retained) UT_hash_handle hh; } tHashUpdateEntry; // Hash Element used for "selectors with interval" typedef struct _hashSelectorEntry { ccArray *timers; CCObject *target; // hash key (retained) unsigned int timerIndex; CCTimer *currentTimer; bool currentTimerSalvaged; bool paused; UT_hash_handle hh; } tHashTimerEntry; // implementation CCTimer CCTimer::CCTimer() : m_pTarget(NULL) , m_fElapsed(-1) , m_bRunForever(false) , m_bUseDelay(false) , m_uTimesExecuted(0) , m_uRepeat(0) , m_fDelay(0.0f) , m_fInterval(0.0f) , m_pfnSelector(NULL) , m_nScriptHandler(0) { } CCTimer* CCTimer::timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector) { CCTimer *pTimer = new CCTimer(); pTimer->initWithTarget(pTarget, pfnSelector, 0.0f, kCCRepeatForever, 0.0f); pTimer->autorelease(); return pTimer; } CCTimer* CCTimer::timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector, float fSeconds) { CCTimer *pTimer = new CCTimer(); pTimer->initWithTarget(pTarget, pfnSelector, fSeconds, kCCRepeatForever, 0.0f); pTimer->autorelease(); return pTimer; } CCTimer* CCTimer::timerWithScriptHandler(int nHandler, float fSeconds) { CCTimer *pTimer = new CCTimer(); pTimer->initWithScriptHandler(nHandler, fSeconds); pTimer->autorelease(); return pTimer; } bool CCTimer::initWithScriptHandler(int nHandler, float fSeconds) { m_nScriptHandler = nHandler; m_fElapsed = -1; m_fInterval = fSeconds; return true; } bool CCTimer::initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector) { return initWithTarget(pTarget, pfnSelector, 0, kCCRepeatForever, 0.0f); } bool CCTimer::initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector, float fSeconds, unsigned int nRepeat, float fDelay) { m_pTarget = pTarget; m_pfnSelector = pfnSelector; m_fElapsed = -1; m_fInterval = fSeconds; m_fDelay = fDelay; m_bUseDelay = (fDelay > 0.0f) ? true : false; m_uRepeat = nRepeat; m_bRunForever = (nRepeat == kCCRepeatForever) ? true : false; return true; } void CCTimer::update(float dt) { if (m_fElapsed == -1) { m_fElapsed = 0; m_uTimesExecuted = 0; } else { if (m_bRunForever && !m_bUseDelay) {//standard timer usage m_fElapsed += dt; if (m_fElapsed >= m_fInterval) { if (m_pTarget && m_pfnSelector) { (m_pTarget->*m_pfnSelector)(m_fElapsed); } if (m_nScriptHandler) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeSchedule(m_nScriptHandler, m_fElapsed); } m_fElapsed = 0; } } else {//advanced usage m_fElapsed += dt; if (m_bUseDelay) { if( m_fElapsed >= m_fDelay ) { if (m_pTarget && m_pfnSelector) { (m_pTarget->*m_pfnSelector)(m_fElapsed); } if (m_nScriptHandler) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeSchedule(m_nScriptHandler, m_fElapsed); } m_fElapsed = m_fElapsed - m_fDelay; m_uTimesExecuted += 1; m_bUseDelay = false; } } else { if (m_fElapsed >= m_fInterval) { if (m_pTarget && m_pfnSelector) { (m_pTarget->*m_pfnSelector)(m_fElapsed); } if (m_nScriptHandler) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeSchedule(m_nScriptHandler, m_fElapsed); } m_fElapsed = 0; m_uTimesExecuted += 1; } } if (!m_bRunForever && m_uTimesExecuted > m_uRepeat) { //unschedule timer CCDirector::sharedDirector()->getScheduler()->unscheduleSelector(m_pfnSelector, m_pTarget); } } } } float CCTimer::getInterval() const { return m_fInterval; } void CCTimer::setInterval(float fInterval) { m_fInterval = fInterval; } SEL_SCHEDULE CCTimer::getSelector() const { return m_pfnSelector; } // implementation of CCScheduler CCScheduler::CCScheduler(void) : m_fTimeScale(1.0f) , m_pUpdatesNegList(NULL) , m_pUpdates0List(NULL) , m_pUpdatesPosList(NULL) , m_pHashForUpdates(NULL) , m_pHashForTimers(NULL) , m_pCurrentTarget(NULL) , m_bCurrentTargetSalvaged(false) , m_bUpdateHashLocked(false) , m_pScriptHandlerEntries(NULL) { } CCScheduler::~CCScheduler(void) { unscheduleAll(); CC_SAFE_RELEASE(m_pScriptHandlerEntries); } void CCScheduler::removeHashElement(_hashSelectorEntry *pElement) { cocos2d::CCObject *target = pElement->target; ccArrayFree(pElement->timers); HASH_DEL(m_pHashForTimers, pElement); free(pElement); // make sure the target is released after we have removed the hash element // otherwise we access invalid memory when the release call deletes the target // and the target calls removeAllSelectors() during its destructor target->release(); } void CCScheduler::scheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget, float fInterval, bool bPaused) { this->scheduleSelector(pfnSelector, pTarget, fInterval, kCCRepeatForever, 0.0f, bPaused); } void CCScheduler::scheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget, float fInterval, unsigned int repeat, float delay, bool bPaused) { CCAssert(pfnSelector, "Argument selector must be non-NULL"); CCAssert(pTarget, "Argument target must be non-NULL"); tHashTimerEntry *pElement = NULL; HASH_FIND_INT(m_pHashForTimers, &pTarget, pElement); if (! pElement) { pElement = (tHashTimerEntry *)calloc(sizeof(*pElement), 1); pElement->target = pTarget; if (pTarget) { pTarget->retain(); } HASH_ADD_INT(m_pHashForTimers, target, pElement); // Is this the 1st element ? Then set the pause level to all the selectors of this target pElement->paused = bPaused; } else { CCAssert(pElement->paused == bPaused, ""); } if (pElement->timers == NULL) { pElement->timers = ccArrayNew(10); } else { for (unsigned int i = 0; i < pElement->timers->num; ++i) { CCTimer *timer = (CCTimer*)pElement->timers->arr[i]; if (pfnSelector == timer->getSelector()) { CCLOG("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer->getInterval(), fInterval); timer->setInterval(fInterval); return; } } ccArrayEnsureExtraCapacity(pElement->timers, 1); } CCTimer *pTimer = new CCTimer(); pTimer->initWithTarget(pTarget, pfnSelector, fInterval, repeat, delay); ccArrayAppendObject(pElement->timers, pTimer); pTimer->release(); } void CCScheduler::unscheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget) { // explicity handle nil arguments when removing an object if (pTarget == 0 || pfnSelector == 0) { return; } //CCAssert(pTarget); //CCAssert(pfnSelector); tHashTimerEntry *pElement = NULL; HASH_FIND_INT(m_pHashForTimers, &pTarget, pElement); if (pElement) { for (unsigned int i = 0; i < pElement->timers->num; ++i) { CCTimer *pTimer = (CCTimer*)(pElement->timers->arr[i]); if (pfnSelector == pTimer->getSelector()) { if (pTimer == pElement->currentTimer && (! pElement->currentTimerSalvaged)) { pElement->currentTimer->retain(); pElement->currentTimerSalvaged = true; } ccArrayRemoveObjectAtIndex(pElement->timers, i, true); // update timerIndex in case we are in tick:, looping over the actions if (pElement->timerIndex >= i) { pElement->timerIndex--; } if (pElement->timers->num == 0) { if (m_pCurrentTarget == pElement) { m_bCurrentTargetSalvaged = true; } else { removeHashElement(pElement); } } return; } } } } void CCScheduler::priorityIn(tListEntry **ppList, CCObject *pTarget, int nPriority, bool bPaused) { tListEntry *pListElement = (tListEntry *)malloc(sizeof(*pListElement)); pListElement->target = pTarget; pListElement->priority = nPriority; pListElement->paused = bPaused; pListElement->next = pListElement->prev = NULL; pListElement->markedForDeletion = false; // empty list ? if (! *ppList) { DL_APPEND(*ppList, pListElement); } else { bool bAdded = false; for (tListEntry *pElement = *ppList; pElement; pElement = pElement->next) { if (nPriority < pElement->priority) { if (pElement == *ppList) { DL_PREPEND(*ppList, pListElement); } else { pListElement->next = pElement; pListElement->prev = pElement->prev; pElement->prev->next = pListElement; pElement->prev = pListElement; } bAdded = true; break; } } // Not added? priority has the higher value. Append it. if (! bAdded) { DL_APPEND(*ppList, pListElement); } } // update hash entry for quick access tHashUpdateEntry *pHashElement = (tHashUpdateEntry *)calloc(sizeof(*pHashElement), 1); pHashElement->target = pTarget; pTarget->retain(); pHashElement->list = ppList; pHashElement->entry = pListElement; HASH_ADD_INT(m_pHashForUpdates, target, pHashElement); } void CCScheduler::appendIn(_listEntry **ppList, CCObject *pTarget, bool bPaused) { tListEntry *pListElement = (tListEntry *)malloc(sizeof(*pListElement)); pListElement->target = pTarget; pListElement->paused = bPaused; pListElement->markedForDeletion = false; DL_APPEND(*ppList, pListElement); // update hash entry for quicker access tHashUpdateEntry *pHashElement = (tHashUpdateEntry *)calloc(sizeof(*pHashElement), 1); pHashElement->target = pTarget; pTarget->retain(); pHashElement->list = ppList; pHashElement->entry = pListElement; HASH_ADD_INT(m_pHashForUpdates, target, pHashElement); } void CCScheduler::scheduleUpdateForTarget(CCObject *pTarget, int nPriority, bool bPaused) { tHashUpdateEntry *pHashElement = NULL; HASH_FIND_INT(m_pHashForUpdates, &pTarget, pHashElement); if (pHashElement) { #if COCOS2D_DEBUG >= 1 CCAssert(pHashElement->entry->markedForDeletion,""); #endif // TODO: check if priority has changed! pHashElement->entry->paused = bPaused; pHashElement->entry->markedForDeletion = false; return; } // most of the updates are going to be 0, that's way there // is an special list for updates with priority 0 if (nPriority == 0) { appendIn(&m_pUpdates0List, pTarget, bPaused); } else if (nPriority < 0) { priorityIn(&m_pUpdatesNegList, pTarget, nPriority, bPaused); } else { // priority > 0 priorityIn(&m_pUpdatesPosList, pTarget, nPriority, bPaused); } } void CCScheduler::removeUpdateFromHash(struct _listEntry *entry) { tHashUpdateEntry *element = NULL; HASH_FIND_INT(m_pHashForUpdates, &entry->target, element); if (element) { // list entry DL_DELETE(*element->list, element->entry); free(element->entry); // hash entry CCObject* pTarget = element->target; HASH_DEL(m_pHashForUpdates, element); free(element); // target#release should be the last one to prevent // a possible double-free. eg: If the [target dealloc] might want to remove it itself from there pTarget->release(); } } void CCScheduler::unscheduleUpdateForTarget(const CCObject *pTarget) { if (pTarget == NULL) { return; } tHashUpdateEntry *pElement = NULL; HASH_FIND_INT(m_pHashForUpdates, &pTarget, pElement); if (pElement) { if (m_bUpdateHashLocked) { pElement->entry->markedForDeletion = true; } else { this->removeUpdateFromHash(pElement->entry); } } } void CCScheduler::unscheduleAll(void) { unscheduleAllWithMinPriority(kCCPrioritySystem); } void CCScheduler::unscheduleAllWithMinPriority(int nMinPriority) { // Custom Selectors tHashTimerEntry *pElement = NULL; tHashTimerEntry *pNextElement = NULL; for (pElement = m_pHashForTimers; pElement != NULL;) { // pElement may be removed in unscheduleAllSelectorsForTarget pNextElement = (tHashTimerEntry *)pElement->hh.next; unscheduleAllForTarget(pElement->target); pElement = pNextElement; } // Updates selectors tListEntry *pEntry, *pTmp; if(nMinPriority < 0) { DL_FOREACH_SAFE(m_pUpdatesNegList, pEntry, pTmp) { if(pEntry->priority >= nMinPriority) { unscheduleUpdateForTarget(pEntry->target); } } } if(nMinPriority <= 0) { DL_FOREACH_SAFE(m_pUpdates0List, pEntry, pTmp) { unscheduleUpdateForTarget(pEntry->target); } } DL_FOREACH_SAFE(m_pUpdatesPosList, pEntry, pTmp) { if(pEntry->priority >= nMinPriority) { unscheduleUpdateForTarget(pEntry->target); } } if (m_pScriptHandlerEntries) { m_pScriptHandlerEntries->removeAllObjects(); } } void CCScheduler::unscheduleAllForTarget(CCObject *pTarget) { // explicit NULL handling if (pTarget == NULL) { return; } // Custom Selectors tHashTimerEntry *pElement = NULL; HASH_FIND_INT(m_pHashForTimers, &pTarget, pElement); if (pElement) { if (ccArrayContainsObject(pElement->timers, pElement->currentTimer) && (! pElement->currentTimerSalvaged)) { pElement->currentTimer->retain(); pElement->currentTimerSalvaged = true; } ccArrayRemoveAllObjects(pElement->timers); if (m_pCurrentTarget == pElement) { m_bCurrentTargetSalvaged = true; } else { removeHashElement(pElement); } } // update selector unscheduleUpdateForTarget(pTarget); } unsigned int CCScheduler::scheduleScriptFunc(unsigned int nHandler, float fInterval, bool bPaused) { CCSchedulerScriptHandle* pEntry = CCSchedulerScriptHandle::create(nHandler, fInterval, bPaused); if (!m_pScriptHandlerEntries) { m_pScriptHandlerEntries = CCArray::createWithCapacity(20); m_pScriptHandlerEntries->retain(); } m_pScriptHandlerEntries->addObject(pEntry); return pEntry->getHandle(); } void CCScheduler::unscheduleScriptEntry(unsigned int uScheduleScriptEntryID) { for (int i = m_pScriptHandlerEntries->count() - 1; i >= 0; i--) { CCSchedulerScriptHandle* pEntry = static_cast<CCSchedulerScriptHandle*>(m_pScriptHandlerEntries->objectAtIndex(i)); if (pEntry->getHandle() == (int)uScheduleScriptEntryID) { pEntry->markedForDeletion(); break; } } } void CCScheduler::resumeTarget(CCObject *pTarget) { CCAssert(pTarget != NULL, ""); // custom selectors tHashTimerEntry *pElement = NULL; HASH_FIND_INT(m_pHashForTimers, &pTarget, pElement); if (pElement) { pElement->paused = false; } // update selector tHashUpdateEntry *pElementUpdate = NULL; HASH_FIND_INT(m_pHashForUpdates, &pTarget, pElementUpdate); if (pElementUpdate) { CCAssert(pElementUpdate->entry != NULL, ""); pElementUpdate->entry->paused = false; } } void CCScheduler::pauseTarget(CCObject *pTarget) { CCAssert(pTarget != NULL, ""); // custom selectors tHashTimerEntry *pElement = NULL; HASH_FIND_INT(m_pHashForTimers, &pTarget, pElement); if (pElement) { pElement->paused = true; } // update selector tHashUpdateEntry *pElementUpdate = NULL; HASH_FIND_INT(m_pHashForUpdates, &pTarget, pElementUpdate); if (pElementUpdate) { CCAssert(pElementUpdate->entry != NULL, ""); pElementUpdate->entry->paused = true; } } bool CCScheduler::isTargetPaused(CCObject *pTarget) { CCAssert( pTarget != NULL, "target must be non nil" ); // Custom selectors tHashTimerEntry *pElement = NULL; HASH_FIND_INT(m_pHashForTimers, &pTarget, pElement); if( pElement ) { return pElement->paused; } // We should check update selectors if target does not have custom selectors tHashUpdateEntry *elementUpdate = NULL; HASH_FIND_INT(m_pHashForUpdates, &pTarget, elementUpdate); if ( elementUpdate ) { return elementUpdate->entry->paused; } return false; // should never get here } CCSet* CCScheduler::pauseAllTargets() { return pauseAllTargetsWithMinPriority(kCCPrioritySystem); } CCSet* CCScheduler::pauseAllTargetsWithMinPriority(int nMinPriority) { CCSet* idsWithSelectors = new CCSet();// setWithCapacity:50]; idsWithSelectors->autorelease(); // Custom Selectors for(tHashTimerEntry *element = m_pHashForTimers; element != NULL; element = (tHashTimerEntry*)element->hh.next) { element->paused = true; idsWithSelectors->addObject(element->target); } // Updates selectors tListEntry *entry, *tmp; if(nMinPriority < 0) { DL_FOREACH_SAFE( m_pUpdatesNegList, entry, tmp ) { if(entry->priority >= nMinPriority) { entry->paused = true; idsWithSelectors->addObject(entry->target); } } } if(nMinPriority <= 0) { DL_FOREACH_SAFE( m_pUpdates0List, entry, tmp ) { entry->paused = true; idsWithSelectors->addObject(entry->target); } } DL_FOREACH_SAFE( m_pUpdatesPosList, entry, tmp ) { if(entry->priority >= nMinPriority) { entry->paused = true; idsWithSelectors->addObject(entry->target); } } return idsWithSelectors; } void CCScheduler::resumeTargets(CCSet* pTargetsToResume) { CCSetIterator iter; for (iter = pTargetsToResume->begin(); iter != pTargetsToResume->end(); ++iter) { resumeTarget(*iter); } } // main loop void CCScheduler::update(float dt) { m_bUpdateHashLocked = true; if (m_fTimeScale != 1.0f) { dt *= m_fTimeScale; } // Iterate over all the Updates' selectors tListEntry *pEntry, *pTmp; // updates with priority < 0 DL_FOREACH_SAFE(m_pUpdatesNegList, pEntry, pTmp) { if ((! pEntry->paused) && (! pEntry->markedForDeletion)) { pEntry->target->update(dt); } } // updates with priority == 0 DL_FOREACH_SAFE(m_pUpdates0List, pEntry, pTmp) { if ((! pEntry->paused) && (! pEntry->markedForDeletion)) { pEntry->target->update(dt); } } // updates with priority > 0 DL_FOREACH_SAFE(m_pUpdatesPosList, pEntry, pTmp) { if ((! pEntry->paused) && (! pEntry->markedForDeletion)) { pEntry->target->update(dt); } } // Iterate over all the custom selectors for (tHashTimerEntry *elt = m_pHashForTimers; elt != NULL; ) { m_pCurrentTarget = elt; m_bCurrentTargetSalvaged = false; if (! m_pCurrentTarget->paused) { // The 'timers' array may change while inside this loop for (elt->timerIndex = 0; elt->timerIndex < elt->timers->num; ++(elt->timerIndex)) { elt->currentTimer = (CCTimer*)(elt->timers->arr[elt->timerIndex]); elt->currentTimerSalvaged = false; elt->currentTimer->update(dt); if (elt->currentTimerSalvaged) { // The currentTimer told the remove itself. To prevent the timer from // accidentally deallocating itself before finishing its step, we retained // it. Now that step is done, it's safe to release it. elt->currentTimer->release(); } elt->currentTimer = NULL; } } // elt, at this moment, is still valid // so it is safe to ask this here (issue #490) elt = (tHashTimerEntry *)elt->hh.next; // only delete currentTarget if no actions were scheduled during the cycle (issue #481) if (m_bCurrentTargetSalvaged && m_pCurrentTarget->timers->num == 0) { removeHashElement(m_pCurrentTarget); } } // Iterate over all the script callbacks if (m_pScriptHandlerEntries) { for (int i = m_pScriptHandlerEntries->count() - 1; i >= 0; i--) { CCSchedulerScriptHandle* pEntry = static_cast<CCSchedulerScriptHandle*>(m_pScriptHandlerEntries->objectAtIndex(i)); if (pEntry->isMarkedForDeletion()) { m_pScriptHandlerEntries->removeObjectAtIndex(i); } else if (!pEntry->isPaused()) { pEntry->getTimer()->update(dt); } } } // delete all updates that are marked for deletion // updates with priority < 0 DL_FOREACH_SAFE(m_pUpdatesNegList, pEntry, pTmp) { if (pEntry->markedForDeletion) { this->removeUpdateFromHash(pEntry); } } // updates with priority == 0 DL_FOREACH_SAFE(m_pUpdates0List, pEntry, pTmp) { if (pEntry->markedForDeletion) { this->removeUpdateFromHash(pEntry); } } // updates with priority > 0 DL_FOREACH_SAFE(m_pUpdatesPosList, pEntry, pTmp) { if (pEntry->markedForDeletion) { this->removeUpdateFromHash(pEntry); } } m_bUpdateHashLocked = false; m_pCurrentTarget = NULL; } NS_CC_END
1
0.981482
1
0.981482
game-dev
MEDIA
0.500305
game-dev
0.898326
1
0.898326
stabix/stabix
4,744
gui_preCPFE/preCPFE_mesh_level.m
% Copyright 2013 Max-Planck-Institut fr Eisenforschung GmbH function preCPFE_mesh_level(ratio) %% Function to set the mesh level gui = guidata(gcf); lvl0 = ... str2num(get(gui.handles.other_setting.mesh_quality_lvl_val, 'String')); lvl = lvl0 + ratio; set(gui.handles.other_setting.mesh_quality_lvl_val, ... 'String', num2str(round(10*lvl)/10)); if ~isempty(strfind(gui.description, 'bicrystal')) || ... ~isempty(strfind(gui.description, 'Scratch')) if (lvl0 > lvl && lvl > 1) || (lvl0 < lvl && lvl < 1) gui.variables.box_elm_nx = ... round(str2num(get(gui.handles.mesh.box_elm_nx_val, 'String'))... / lvl); gui.variables.box_elm_nz = ... round(str2num(get(gui.handles.mesh.box_elm_nz_val, 'String'))... / lvl); gui.variables.box_elm_ny1 = ... round(str2num(get(gui.handles.mesh.box_elm_ny1_val, 'String'))... / lvl); gui.variables.box_elm_ny2 = ... round(str2num(get(gui.handles.mesh.box_elm_ny2_val, 'String'))... / lvl); gui.variables.box_elm_ny3 = ... round(str2num(get(gui.handles.mesh.box_elm_ny3_val, 'String'))... / lvl); elseif (lvl0 < lvl && lvl > 1) || (lvl0 > lvl && lvl < 1) gui.variables.box_elm_nx = ... round(str2num(get(gui.handles.mesh.box_elm_nx_val, 'String'))... * lvl); gui.variables.box_elm_nz = ... round(str2num(get(gui.handles.mesh.box_elm_nz_val, 'String'))... * lvl); gui.variables.box_elm_ny1 = ... round(str2num(get(gui.handles.mesh.box_elm_ny1_val, 'String'))... * lvl); gui.variables.box_elm_ny2 = ... round(str2num(get(gui.handles.mesh.box_elm_ny2_val, 'String'))... * lvl); gui.variables.box_elm_ny3 = ... round(str2num(get(gui.handles.mesh.box_elm_ny3_val, 'String'))... * lvl); else gui.variables.box_elm_nx = ... str2num(get(gui.handles.mesh.box_elm_nx_val, 'String')); gui.variables.box_elm_nz = ... str2num(get(gui.handles.mesh.box_elm_nz_val, 'String')); gui.variables.box_elm_ny1 = ... str2num(get(gui.handles.mesh.box_elm_ny1_val, 'String')); gui.variables.box_elm_ny2 = ... str2num(get(gui.handles.mesh.box_elm_ny2_val, 'String')); gui.variables.box_elm_ny3 = ... str2num(get(gui.handles.mesh.box_elm_ny3_val, 'String')); end set(gui.handles.mesh.box_elm_nx_val, ... 'String', num2str(gui.variables.box_elm_nx)); set(gui.handles.mesh.box_elm_nz_val, ... 'String', num2str(gui.variables.box_elm_nz)); set(gui.handles.mesh.box_elm_ny1_val, ... 'String', num2str(gui.variables.box_elm_ny1)); set(gui.handles.mesh.box_elm_ny2_val, ... 'String', num2str(gui.variables.box_elm_ny2)); set(gui.handles.mesh.box_elm_ny3_val, ... 'String', num2str(gui.variables.box_elm_ny3)); elseif strfind(gui.description, 'single') if (lvl0 > lvl && lvl > 1) || (lvl0 < lvl && lvl < 1) gui.variables.box_elm_nx = ... round(str2num(get(gui.handles.mesh.box_elm_nx_val, 'String'))... / lvl); gui.variables.box_elm_nz = ... round(str2num(get(gui.handles.mesh.box_elm_nz_val, 'String'))... / lvl); gui.variables.radial_divi = ... round(str2num(get(gui.handles.mesh.radial_divi_val, 'String'))... / lvl); elseif (lvl0 < lvl && lvl > 1) || (lvl0 > lvl && lvl < 1) gui.variables.box_elm_nx = ... round(str2num(get(gui.handles.mesh.box_elm_nx_val, 'String'))... * lvl); gui.variables.box_elm_nz = ... round(str2num(get(gui.handles.mesh.box_elm_nz_val, 'String'))... * lvl); gui.variables.radial_divi = ... round(str2num(get(gui.handles.mesh.radial_divi_val, 'String'))... * lvl); else gui.variables.box_elm_nx = ... str2num(get(gui.handles.mesh.box_elm_nx_val, 'String')); gui.variables.box_elm_nz = ... str2num(get(gui.handles.mesh.box_elm_nz_val, 'String')); gui.variables.radial_divi = ... str2num(get(gui.handles.mesh.radial_divi_val, 'String')); end set(gui.handles.mesh.box_elm_nx_val, ... 'String', num2str(gui.variables.box_elm_nx)); set(gui.handles.mesh.box_elm_nz_val, ... 'String', num2str(gui.variables.box_elm_nz)); set(gui.handles.mesh.radial_divi_val, ... 'String', num2str(gui.variables.radial_divi)); end gui.variables.mesh_quality_lvl = lvl; guidata(gcf, gui); end
1
0.712485
1
0.712485
game-dev
MEDIA
0.429323
game-dev
0.671823
1
0.671823
thomashope/native-menu-bar
4,307
examples/lib/sdl2/windows/include/SDL_clipboard.h
/* Simple DirectMedia Layer Copyright (C) 1997-2024 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_clipboard.h * * Include file for SDL clipboard handling */ #ifndef SDL_clipboard_h_ #define SDL_clipboard_h_ #include "SDL_stdinc.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Function prototypes */ /** * Put UTF-8 text into the clipboard. * * \param text the text to store in the clipboard * \returns 0 on success or a negative error code on failure; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GetClipboardText * \sa SDL_HasClipboardText */ extern DECLSPEC int SDLCALL SDL_SetClipboardText(const char *text); /** * Get UTF-8 text from the clipboard, which must be freed with SDL_free(). * * This functions returns empty string if there was not enough memory left for * a copy of the clipboard's content. * * \returns the clipboard text on success or an empty string on failure; call * SDL_GetError() for more information. Caller must call SDL_free() * on the returned pointer when done with it (even if there was an * error). * * \since This function is available since SDL 2.0.0. * * \sa SDL_HasClipboardText * \sa SDL_SetClipboardText */ extern DECLSPEC char * SDLCALL SDL_GetClipboardText(void); /** * Query whether the clipboard exists and contains a non-empty text string. * * \returns SDL_TRUE if the clipboard has text, or SDL_FALSE if it does not. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GetClipboardText * \sa SDL_SetClipboardText */ extern DECLSPEC SDL_bool SDLCALL SDL_HasClipboardText(void); /** * Put UTF-8 text into the primary selection. * * \param text the text to store in the primary selection * \returns 0 on success or a negative error code on failure; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.26.0. * * \sa SDL_GetPrimarySelectionText * \sa SDL_HasPrimarySelectionText */ extern DECLSPEC int SDLCALL SDL_SetPrimarySelectionText(const char *text); /** * Get UTF-8 text from the primary selection, which must be freed with * SDL_free(). * * This functions returns empty string if there was not enough memory left for * a copy of the primary selection's content. * * \returns the primary selection text on success or an empty string on * failure; call SDL_GetError() for more information. Caller must * call SDL_free() on the returned pointer when done with it (even if * there was an error). * * \since This function is available since SDL 2.26.0. * * \sa SDL_HasPrimarySelectionText * \sa SDL_SetPrimarySelectionText */ extern DECLSPEC char * SDLCALL SDL_GetPrimarySelectionText(void); /** * Query whether the primary selection exists and contains a non-empty text * string. * * \returns SDL_TRUE if the primary selection has text, or SDL_FALSE if it * does not. * * \since This function is available since SDL 2.26.0. * * \sa SDL_GetPrimarySelectionText * \sa SDL_SetPrimarySelectionText */ extern DECLSPEC SDL_bool SDLCALL SDL_HasPrimarySelectionText(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_clipboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
1
0.894375
1
0.894375
game-dev
MEDIA
0.680715
game-dev
0.63738
1
0.63738
d-mod/ExtractorSharp
1,812
ExtractorSharp/Command/FileCommand/RecoverFile.cs
using ExtractorSharp.Core.Coder; using ExtractorSharp.Core.Command; using ExtractorSharp.Core.Model; using System.Text.RegularExpressions; namespace ExtractorSharp.Command.FileCommand { /// <summary> /// 恢复文件,将文件恢复为原始文件 /// </summary> class RecoverFile : IMutipleAciton, ICommandMessage { private Album[] currents; private Album[] olds; public bool CanUndo => true; public bool IsChanged => true; public string Name => "RecoverFile"; private string GamePath => Program.Config["GamePath"].Value; public void Do(params object[] args) { currents = args as Album[]; if (currents == null) { return; } olds = new Album[currents.Length]; var i = 0; var dir = NpkCoder.IMAGE_DIR; if (currents.Length > 0) { if (Regex.IsMatch(currents[0].Path, "^sounds/.*\\.ogg$")) { dir = NpkCoder.SOUND_DIR; } } NpkCoder.Compare(GamePath, dir, (a1, a2) => { var old = new Album(); old.Replace(a2);//保存旧文件 a2.Replace(a1); //替换为源文件 olds[i++] = old; }, currents); } public void Redo() { Do(currents); } public void Action(params Album[] array) { NpkCoder.Compare(GamePath, (a1, a2) =>a1.Replace(a2), array); } public void Undo() { if (currents == null) { return; } for (var i = 0; i < currents.Length; i++) { if (olds[i] == null) { continue; } currents[i].Replace(olds[i]); } } } }
1
0.879105
1
0.879105
game-dev
MEDIA
0.854662
game-dev
0.981516
1
0.981516
chainreactors/mal-community
40,822
community-common/modules/powersharppack.lua
-- Invoke-BadPotato local function run_Invoke_BadPotato(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-BadPotato" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-BadPotato.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-BadPotato", run_Invoke_BadPotato, "powersharppack Invoke-BadPotato", "T1059.001") -- Invoke-BetterSafetyKatz local function run_Invoke_BetterSafetyKatz(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-BetterSafetyKatz" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-BetterSafetyKatz.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-BetterSafetyKatz", run_Invoke_BetterSafetyKatz, "powersharppack Invoke-BetterSafetyKatz", "T1059.001") -- Invoke-Carbuncle local function run_Invoke_Carbuncle(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Carbuncle" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Carbuncle.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Carbuncle", run_Invoke_Carbuncle, "powersharppack Invoke-Carbuncle", "T1059.001") -- Invoke-Certify local function run_Invoke_Certify(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Certify" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Certify.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Certify", run_Invoke_Certify, "powersharppack Invoke-Certify", "T1059.001") -- Invoke-DAFT local function run_Invoke_DAFT(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-DAFT" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-DAFT.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-DAFT", run_Invoke_DAFT, "powersharppack Invoke-DAFT", "T1059.001") -- Invoke-DinvokeKatz local function run_Invoke_DinvokeKatz(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-DinvokeKatz" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-DinvokeKatz.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-DinvokeKatz", run_Invoke_DinvokeKatz, "powersharppack Invoke-DinvokeKatz", "T1059.001") -- Invoke-Eyewitness local function run_Invoke_Eyewitness(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Eyewitness" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Eyewitness.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Eyewitness", run_Invoke_Eyewitness, "powersharppack Invoke-Eyewitness", "T1059.001") -- Invoke-FakeLogonScreen local function run_Invoke_FakeLogonScreen(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-FakeLogonScreen" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-FakeLogonScreen.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-FakeLogonScreen", run_Invoke_FakeLogonScreen, "powersharppack Invoke-FakeLogonScreen", "T1059.001") -- Invoke-Farmer local function run_Invoke_Farmer(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Farmer" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Farmer.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Farmer", run_Invoke_Farmer, "powersharppack Invoke-Farmer", "T1059.001") -- Invoke-Get-RBCD-Threaded local function run_Invoke_Get_RBCD_Threaded(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Get-RBCD-Threaded" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Get-RBCD-Threaded.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Get-RBCD-Threaded", run_Invoke_Get_RBCD_Threaded, "powersharppack Invoke-Get-RBCD-Threaded", "T1059.001") -- Invoke-Gopher local function run_Invoke_Gopher(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Gopher" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Gopher.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Gopher", run_Invoke_Gopher, "powersharppack Invoke-Gopher", "T1059.001") -- Invoke-Grouper2 local function run_Invoke_Grouper2(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Grouper2" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Grouper2.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Grouper2", run_Invoke_Grouper2, "powersharppack Invoke-Grouper2", "T1059.001") -- Invoke-Grouper3 local function run_Invoke_Grouper3(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Grouper3" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Grouper3.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Grouper3", run_Invoke_Grouper3, "powersharppack Invoke-Grouper3", "T1059.001") -- Invoke-HandleKatz local function run_Invoke_HandleKatz(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-HandleKatz" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-HandleKatz.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-HandleKatz", run_Invoke_HandleKatz, "powersharppack Invoke-HandleKatz", "T1059.001") -- Invoke-Internalmonologue local function run_Invoke_Internalmonologue(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Internalmonologue" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Internalmonologue.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Internalmonologue", run_Invoke_Internalmonologue, "powersharppack Invoke-Internalmonologue", "T1059.001") -- Invoke-Inveigh local function run_Invoke_Inveigh(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Inveigh" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Inveigh.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Inveigh", run_Invoke_Inveigh, "powersharppack Invoke-Inveigh", "T1059.001") -- Invoke-KrbRelay local function run_Invoke_KrbRelay(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-KrbRelay" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-KrbRelay.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-KrbRelay", run_Invoke_KrbRelay, "powersharppack Invoke-KrbRelay", "T1059.001") -- Invoke-LdapSignCheck local function run_Invoke_LdapSignCheck(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-LdapSignCheck" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-LdapSignCheck.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-LdapSignCheck", run_Invoke_LdapSignCheck, "powersharppack Invoke-LdapSignCheck", "T1059.001") -- Invoke-Lockless local function run_Invoke_Lockless(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Lockless" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Lockless.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Lockless", run_Invoke_Lockless, "powersharppack Invoke-Lockless", "T1059.001") -- Invoke-MalSCCM local function run_Invoke_MalSCCM(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-MalSCCM" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-MalSCCM.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-MalSCCM", run_Invoke_MalSCCM, "powersharppack Invoke-MalSCCM", "T1059.001") -- Invoke-MITM6 local function run_Invoke_MITM6(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-MITM6" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-MITM6.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-MITM6", run_Invoke_MITM6, "powersharppack Invoke-MITM6", "T1059.001") -- Invoke-NanoDump local function run_Invoke_NanoDump(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-NanoDump" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-NanoDump.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-NanoDump", run_Invoke_NanoDump, "powersharppack Invoke-NanoDump", "T1059.001") -- Invoke-OxidResolver local function run_Invoke_OxidResolver(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-OxidResolver" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-OxidResolver.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-OxidResolver", run_Invoke_OxidResolver, "powersharppack Invoke-OxidResolver", "T1059.001") -- Invoke-P0wnedshell local function run_Invoke_P0wnedshell(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-P0wnedshell" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-P0wnedshell.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-P0wnedshell", run_Invoke_P0wnedshell, "powersharppack Invoke-P0wnedshell", "T1059.001") -- Invoke-P0wnedshellx86 local function run_Invoke_P0wnedshellx86(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-P0wnedshellx86" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-P0wnedshellx86.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-P0wnedshellx86", run_Invoke_P0wnedshellx86, "powersharppack Invoke-P0wnedshellx86", "T1059.001") -- Invoke-Postdump local function run_Invoke_Postdump(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Postdump" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Postdump.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Postdump", run_Invoke_Postdump, "powersharppack Invoke-Postdump", "T1059.001") -- Invoke-PPLDump local function run_Invoke_PPLDump(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-PPLDump" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-PPLDump.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-PPLDump", run_Invoke_PPLDump, "powersharppack Invoke-PPLDump", "T1059.001") -- Invoke-Rubeus local function run_Invoke_Rubeus(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Rubeus" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Rubeus.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Rubeus", run_Invoke_Rubeus, "powersharppack Invoke-Rubeus", "T1059.001") -- Invoke-SafetyKatz local function run_Invoke_SafetyKatz(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SafetyKatz" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SafetyKatz.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SafetyKatz", run_Invoke_SafetyKatz, "powersharppack Invoke-SafetyKatz", "T1059.001") -- Invoke-SauronEye local function run_Invoke_SauronEye(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SauronEye" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SauronEye.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SauronEye", run_Invoke_SauronEye, "powersharppack Invoke-SauronEye", "T1059.001") -- Invoke-SCShell local function run_Invoke_SCShell(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SCShell" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SCShell.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SCShell", run_Invoke_SCShell, "powersharppack Invoke-SCShell", "T1059.001") -- Invoke-Seatbelt local function run_Invoke_Seatbelt(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Seatbelt" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Seatbelt.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Seatbelt", run_Invoke_Seatbelt, "powersharppack Invoke-Seatbelt", "T1059.001") -- Invoke-ShadowSpray local function run_Invoke_ShadowSpray(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-ShadowSpray" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-ShadowSpray.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-ShadowSpray", run_Invoke_ShadowSpray, "powersharppack Invoke-ShadowSpray", "T1059.001") -- Invoke-SharpAllowedToAct local function run_Invoke_SharpAllowedToAct(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpAllowedToAct" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpAllowedToAct.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpAllowedToAct", run_Invoke_SharpAllowedToAct, "powersharppack Invoke-SharpAllowedToAct", "T1059.001") -- Invoke-SharpBlock local function run_Invoke_SharpBlock(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpBlock" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpBlock.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpBlock", run_Invoke_SharpBlock, "powersharppack Invoke-SharpBlock", "T1059.001") -- Invoke-SharpBypassUAC local function run_Invoke_SharpBypassUAC(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpBypassUAC" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpBypassUAC.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpBypassUAC", run_Invoke_SharpBypassUAC, "powersharppack Invoke-SharpBypassUAC", "T1059.001") -- Invoke-SharpChrome local function run_Invoke_SharpChrome(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpChrome" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpChrome.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpChrome", run_Invoke_SharpChrome, "powersharppack Invoke-SharpChrome", "T1059.001") -- Invoke-SharpChromium local function run_Invoke_SharpChromium(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpChromium" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpChromium.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpChromium", run_Invoke_SharpChromium, "powersharppack Invoke-SharpChromium", "T1059.001") -- Invoke-SharpClipboard local function run_Invoke_SharpClipboard(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpClipboard" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpClipboard.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpClipboard", run_Invoke_SharpClipboard, "powersharppack Invoke-SharpClipboard", "T1059.001") -- Invoke-SharpCloud local function run_Invoke_SharpCloud(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpCloud" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpCloud.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpCloud", run_Invoke_SharpCloud, "powersharppack Invoke-SharpCloud", "T1059.001") -- Invoke-SharpDPAPI local function run_Invoke_SharpDPAPI(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpDPAPI" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpDPAPI.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpDPAPI", run_Invoke_SharpDPAPI, "powersharppack Invoke-SharpDPAPI", "T1059.001") -- Invoke-SharpDump local function run_Invoke_SharpDump(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpDump" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpDump.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpDump", run_Invoke_SharpDump, "powersharppack Invoke-SharpDump", "T1059.001") -- Invoke-SharPersist local function run_Invoke_SharPersist(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharPersist" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharPersist.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharPersist", run_Invoke_SharPersist, "powersharppack Invoke-SharPersist", "T1059.001") -- Invoke-SharpGPO-RemoteAccessPolicies local function run_Invoke_SharpGPO_RemoteAccessPolicies(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpGPO-RemoteAccessPolicies" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpGPO-RemoteAccessPolicies.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpGPO-RemoteAccessPolicies", run_Invoke_SharpGPO_RemoteAccessPolicies, "powersharppack Invoke-SharpGPO-RemoteAccessPolicies", "T1059.001") -- Invoke-SharpGPOAbuse local function run_Invoke_SharpGPOAbuse(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpGPOAbuse" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpGPOAbuse.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpGPOAbuse", run_Invoke_SharpGPOAbuse, "powersharppack Invoke-SharpGPOAbuse", "T1059.001") -- Invoke-SharpHandler local function run_Invoke_SharpHandler(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpHandler" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpHandler.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpHandler", run_Invoke_SharpHandler, "powersharppack Invoke-SharpHandler", "T1059.001") -- Invoke-SharpHide local function run_Invoke_SharpHide(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpHide" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpHide.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpHide", run_Invoke_SharpHide, "powersharppack Invoke-SharpHide", "T1059.001") -- Invoke-Sharphound2 local function run_Invoke_Sharphound2(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Sharphound2" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Sharphound2.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Sharphound2", run_Invoke_Sharphound2, "powersharppack Invoke-Sharphound2", "T1059.001") -- Invoke-Sharphound3 local function run_Invoke_Sharphound3(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Sharphound3" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Sharphound3.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Sharphound3", run_Invoke_Sharphound3, "powersharppack Invoke-Sharphound3", "T1059.001") -- Invoke-SharpHound4 local function run_Invoke_SharpHound4(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpHound4" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpHound4.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpHound4", run_Invoke_SharpHound4, "powersharppack Invoke-SharpHound4", "T1059.001") -- Invoke-SharpImpersonation local function run_Invoke_SharpImpersonation(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpImpersonation" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpImpersonation.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpImpersonation", run_Invoke_SharpImpersonation, "powersharppack Invoke-SharpImpersonation", "T1059.001") -- Invoke-SharpImpersonationNoSpace local function run_Invoke_SharpImpersonationNoSpace(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpImpersonationNoSpace" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpImpersonationNoSpace.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpImpersonationNoSpace", run_Invoke_SharpImpersonationNoSpace, "powersharppack Invoke-SharpImpersonationNoSpace", "T1059.001") -- Invoke-SharpKatz local function run_Invoke_SharpKatz(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpKatz" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpKatz.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpKatz", run_Invoke_SharpKatz, "powersharppack Invoke-SharpKatz", "T1059.001") -- Invoke-SharpLdapRelayScan local function run_Invoke_SharpLdapRelayScan(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpLdapRelayScan" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpLdapRelayScan.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpLdapRelayScan", run_Invoke_SharpLdapRelayScan, "powersharppack Invoke-SharpLdapRelayScan", "T1059.001") -- Invoke-Sharplocker local function run_Invoke_Sharplocker(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Sharplocker" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Sharplocker.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Sharplocker", run_Invoke_Sharplocker, "powersharppack Invoke-Sharplocker", "T1059.001") -- Invoke-SharpLoginPrompt local function run_Invoke_SharpLoginPrompt(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpLoginPrompt" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpLoginPrompt.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpLoginPrompt", run_Invoke_SharpLoginPrompt, "powersharppack Invoke-SharpLoginPrompt", "T1059.001") -- Invoke-SharpMove local function run_Invoke_SharpMove(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpMove" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpMove.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpMove", run_Invoke_SharpMove, "powersharppack Invoke-SharpMove", "T1059.001") -- Invoke-SharpPrinter local function run_Invoke_SharpPrinter(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpPrinter" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpPrinter.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpPrinter", run_Invoke_SharpPrinter, "powersharppack Invoke-SharpPrinter", "T1059.001") -- Invoke-SharpPrintNightmare local function run_Invoke_SharpPrintNightmare(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpPrintNightmare" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpPrintNightmare.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpPrintNightmare", run_Invoke_SharpPrintNightmare, "powersharppack Invoke-SharpPrintNightmare", "T1059.001") -- Invoke-SharpRDP local function run_Invoke_SharpRDP(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpRDP" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpRDP.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpRDP", run_Invoke_SharpRDP, "powersharppack Invoke-SharpRDP", "T1059.001") -- Invoke-SharpSCCM local function run_Invoke_SharpSCCM(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpSCCM" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpSCCM.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpSCCM", run_Invoke_SharpSCCM, "powersharppack Invoke-SharpSCCM", "T1059.001") -- Invoke-SharpSecDump local function run_Invoke_SharpSecDump(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpSecDump" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpSecDump.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpSecDump", run_Invoke_SharpSecDump, "powersharppack Invoke-SharpSecDump", "T1059.001") -- Invoke-Sharpshares local function run_Invoke_Sharpshares(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Sharpshares" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Sharpshares.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Sharpshares", run_Invoke_Sharpshares, "powersharppack Invoke-Sharpshares", "T1059.001") -- Invoke-SharpSniper local function run_Invoke_SharpSniper(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpSniper" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpSniper.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpSniper", run_Invoke_SharpSniper, "powersharppack Invoke-SharpSniper", "T1059.001") -- Invoke-Sharpsploit_nomimi local function run_Invoke_Sharpsploit_nomimi(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Sharpsploit_nomimi" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Sharpsploit_nomimi.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Sharpsploit_nomimi", run_Invoke_Sharpsploit_nomimi, "powersharppack Invoke-Sharpsploit_nomimi", "T1059.001") -- Invoke-SharpSploit local function run_Invoke_SharpSploit(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpSploit" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpSploit.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpSploit", run_Invoke_SharpSploit, "powersharppack Invoke-SharpSploit", "T1059.001") -- Invoke-SharpSpray local function run_Invoke_SharpSpray(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpSpray" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpSpray.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpSpray", run_Invoke_SharpSpray, "powersharppack Invoke-SharpSpray", "T1059.001") -- Invoke-SharpSSDP local function run_Invoke_SharpSSDP(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpSSDP" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpSSDP.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpSSDP", run_Invoke_SharpSSDP, "powersharppack Invoke-SharpSSDP", "T1059.001") -- Invoke-SharpStay local function run_Invoke_SharpStay(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpStay" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpStay.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpStay", run_Invoke_SharpStay, "powersharppack Invoke-SharpStay", "T1059.001") -- Invoke-SharpUp local function run_Invoke_SharpUp(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpUp" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpUp.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpUp", run_Invoke_SharpUp, "powersharppack Invoke-SharpUp", "T1059.001") -- Invoke-Sharpview local function run_Invoke_Sharpview(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Sharpview" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Sharpview.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Sharpview", run_Invoke_Sharpview, "powersharppack Invoke-Sharpview", "T1059.001") -- Invoke-SharpWatson local function run_Invoke_SharpWatson(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpWatson" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpWatson.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpWatson", run_Invoke_SharpWatson, "powersharppack Invoke-SharpWatson", "T1059.001") -- Invoke-Sharpweb local function run_Invoke_Sharpweb(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Sharpweb" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Sharpweb.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Sharpweb", run_Invoke_Sharpweb, "powersharppack Invoke-Sharpweb", "T1059.001") -- Invoke-SharpWSUS local function run_Invoke_SharpWSUS(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-SharpWSUS" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-SharpWSUS.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-SharpWSUS", run_Invoke_SharpWSUS, "powersharppack Invoke-SharpWSUS", "T1059.001") -- Invoke-Snaffler local function run_Invoke_Snaffler(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Snaffler" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Snaffler.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Snaffler", run_Invoke_Snaffler, "powersharppack Invoke-Snaffler", "T1059.001") -- Invoke-Spoolsample local function run_Invoke_Spoolsample(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Spoolsample" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Spoolsample.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Spoolsample", run_Invoke_Spoolsample, "powersharppack Invoke-Spoolsample", "T1059.001") -- Invoke-StandIn local function run_Invoke_StandIn(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-StandIn" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-StandIn.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-StandIn", run_Invoke_StandIn, "powersharppack Invoke-StandIn", "T1059.001") -- Invoke-StickyNotesExtract local function run_Invoke_StickyNotesExtract(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-StickyNotesExtract" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-StickyNotesExtract.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-StickyNotesExtract", run_Invoke_StickyNotesExtract, "powersharppack Invoke-StickyNotesExtract", "T1059.001") -- Invoke-Thunderfox local function run_Invoke_Thunderfox(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Thunderfox" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Thunderfox.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Thunderfox", run_Invoke_Thunderfox, "powersharppack Invoke-Thunderfox", "T1059.001") -- Invoke-Tokenvator local function run_Invoke_Tokenvator(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Tokenvator" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Tokenvator.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Tokenvator", run_Invoke_Tokenvator, "powersharppack Invoke-Tokenvator", "T1059.001") -- Invoke-UrbanBishop local function run_Invoke_UrbanBishop(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-UrbanBishop" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-UrbanBishop.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-UrbanBishop", run_Invoke_UrbanBishop, "powersharppack Invoke-UrbanBishop", "T1059.001") -- Invoke-Whisker local function run_Invoke_Whisker(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-Whisker" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-Whisker.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-Whisker", run_Invoke_Whisker, "powersharppack Invoke-Whisker", "T1059.001") -- Invoke-winPEAS local function run_Invoke_winPEAS(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-winPEAS" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-winPEAS.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-winPEAS", run_Invoke_winPEAS, "powersharppack Invoke-winPEAS", "T1059.001") -- Invoke-WireTap local function run_Invoke_WireTap(args) local session = active() local arch = session.Os.Arch local function_name = "Invoke-WireTap" local ps_script = script_resource("PowerSharpPack/PowerSharpBinaries/Invoke-WireTap.ps1") return powerpick(session, ps_script, {function_name, unpack(args)}, new_bypass_all()) end command("powersharppack:Invoke-WireTap", run_Invoke_WireTap, "powersharppack Invoke-WireTap", "T1059.001")
1
0.656795
1
0.656795
game-dev
MEDIA
0.42065
game-dev
0.562741
1
0.562741
Sigma-Skidder-Team/SigmaRebase
1,366
src/main/java/net/minecraft/client/renderer/entity/BipedRenderer.java
package net.minecraft.client.renderer.entity; import net.minecraft.client.renderer.entity.layers.ElytraLayer; import net.minecraft.client.renderer.entity.layers.HeadLayer; import net.minecraft.client.renderer.entity.layers.HeldItemLayer; import net.minecraft.client.renderer.entity.model.BipedModel; import net.minecraft.entity.MobEntity; import net.minecraft.util.ResourceLocation; public class BipedRenderer<T extends MobEntity, M extends BipedModel<T>> extends MobRenderer<T, M> { private static final ResourceLocation DEFAULT_RES_LOC = new ResourceLocation("textures/entity/steve.png"); public BipedRenderer(EntityRendererManager renderManagerIn, M modelBipedIn, float shadowSize) { this(renderManagerIn, modelBipedIn, shadowSize, 1.0F, 1.0F, 1.0F); } public BipedRenderer(EntityRendererManager p_i232471_1_, M p_i232471_2_, float p_i232471_3_, float p_i232471_4_, float p_i232471_5_, float p_i232471_6_) { super(p_i232471_1_, p_i232471_2_, p_i232471_3_); this.addLayer(new HeadLayer<>(this, p_i232471_4_, p_i232471_5_, p_i232471_6_)); this.addLayer(new ElytraLayer<>(this)); this.addLayer(new HeldItemLayer<>(this)); } /** * Returns the location of an entity's texture. */ public ResourceLocation getEntityTexture(T entity) { return DEFAULT_RES_LOC; } }
1
0.606506
1
0.606506
game-dev
MEDIA
0.896921
game-dev,graphics-rendering
0.954575
1
0.954575
cyanbun96/qrustyquake
17,246
haiku/SDL3/include/SDL3/SDL_scancode.h
/* Simple DirectMedia Layer Copyright (C) 1997-2025 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. */ /** * # CategoryScancode * * Defines keyboard scancodes. * * Please refer to the Best Keyboard Practices document for details on what * this information means and how best to use it. * * https://wiki.libsdl.org/SDL3/BestKeyboardPractices */ #ifndef SDL_scancode_h_ #define SDL_scancode_h_ #include <SDL3/SDL_stdinc.h> /** * The SDL keyboard scancode representation. * * An SDL scancode is the physical representation of a key on the keyboard, * independent of language and keyboard mapping. * * Values of this type are used to represent keyboard keys, among other places * in the `scancode` field of the SDL_KeyboardEvent structure. * * The values in this enumeration are based on the USB usage page standard: * https://usb.org/sites/default/files/hut1_5.pdf * * \since This enum is available since SDL 3.2.0. */ typedef enum SDL_Scancode { SDL_SCANCODE_UNKNOWN = 0, /** * \name Usage page 0x07 * * These values are from usage page 0x07 (USB keyboard page). */ /* @{ */ SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return * key on ISO keyboards and at the right end * of the QWERTY row on ANSI keyboards. * Produces REVERSE SOLIDUS (backslash) and * VERTICAL LINE in a US layout, REVERSE * SOLIDUS and VERTICAL LINE in a UK Mac * layout, NUMBER SIGN and TILDE in a UK * Windows layout, DOLLAR SIGN and POUND SIGN * in a Swiss German layout, NUMBER SIGN and * APOSTROPHE in a German layout, GRAVE * ACCENT and POUND SIGN in a French Mac * layout, and ASTERISK and MICRO SIGN in a * French Windows layout. */ SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code * instead of 49 for the same key, but all * OSes I've seen treat the two codes * identically. So, as an implementor, unless * your keyboard generates both of those * codes and your OS treats them differently, * you should generate SDL_SCANCODE_BACKSLASH * instead of this code. As a user, you * should not rely on this code because SDL * will never generate it with most (all?) * keyboards. */ SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI * and ISO keyboards). Produces GRAVE ACCENT and * TILDE in a US Windows layout and in US and UK * Mac layouts on ANSI keyboards, GRAVE ACCENT * and NOT SIGN in a UK Windows layout, SECTION * SIGN and PLUS-MINUS SIGN in US and UK Mac * layouts on ISO keyboards, SECTION SIGN and * DEGREE SIGN in a Swiss German layout (Mac: * only on ISO keyboards), CIRCUMFLEX ACCENT and * DEGREE SIGN in a German layout (Mac: only on * ISO keyboards), SUPERSCRIPT TWO and TILDE in a * French Windows layout, COMMERCIAL AT and * NUMBER SIGN in a French Mac layout on ISO * keyboards, and LESS-THAN SIGN and GREATER-THAN * SIGN in a Swiss German, German, or French Mac * layout on ANSI keyboards. */ SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but does send code 73, not 117) */ SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards */ SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO * keyboards have over ANSI ones, * located between left shift and Z. * Produces GRAVE ACCENT and TILDE in a * US or UK Mac layout, REVERSE SOLIDUS * (backslash) and VERTICAL LINE in a * US or UK Windows layout, and * LESS-THAN SIGN and GREATER-THAN SIGN * in a Swiss German, German, or French * layout. */ SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */ SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag, * not a physical key - but some Mac keyboards * do have a power key. */ SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, /**< AL Integrated Help Center */ SDL_SCANCODE_MENU = 118, /**< Menu (show menu) */ SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, /**< AC Stop */ SDL_SCANCODE_AGAIN = 121, /**< AC Redo/Repeat */ SDL_SCANCODE_UNDO = 122, /**< AC Undo */ SDL_SCANCODE_CUT = 123, /**< AC Cut */ SDL_SCANCODE_COPY = 124, /**< AC Copy */ SDL_SCANCODE_PASTE = 125, /**< AC Paste */ SDL_SCANCODE_FIND = 126, /**< AC Find */ SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, /* not sure whether there's a reason to enable these */ /* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */ /* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */ /* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */ SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see footnotes in USB doc */ SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */ SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */ SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */ SDL_SCANCODE_LANG3 = 146, /**< Katakana */ SDL_SCANCODE_LANG4 = 147, /**< Hiragana */ SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */ SDL_SCANCODE_LANG6 = 149, /**< reserved */ SDL_SCANCODE_LANG7 = 150, /**< reserved */ SDL_SCANCODE_LANG8 = 151, /**< reserved */ SDL_SCANCODE_LANG9 = 152, /**< reserved */ SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */ SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, /**< AC Cancel */ SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, /**< alt, option */ SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */ SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, /**< alt gr, option */ SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */ SDL_SCANCODE_MODE = 257, /**< I'm not sure if this is really not covered * by any of the above, but since there's a * special SDL_KMOD_MODE for it I'm adding it here */ /* @} *//* Usage page 0x07 */ /** * \name Usage page 0x0C * * These values are mapped from usage page 0x0C (USB consumer page). * * There are way more keys in the spec than we can represent in the * current scancode range, so pick the ones that commonly come up in * real world usage. */ /* @{ */ SDL_SCANCODE_SLEEP = 258, /**< Sleep */ SDL_SCANCODE_WAKE = 259, /**< Wake */ SDL_SCANCODE_CHANNEL_INCREMENT = 260, /**< Channel Increment */ SDL_SCANCODE_CHANNEL_DECREMENT = 261, /**< Channel Decrement */ SDL_SCANCODE_MEDIA_PLAY = 262, /**< Play */ SDL_SCANCODE_MEDIA_PAUSE = 263, /**< Pause */ SDL_SCANCODE_MEDIA_RECORD = 264, /**< Record */ SDL_SCANCODE_MEDIA_FAST_FORWARD = 265, /**< Fast Forward */ SDL_SCANCODE_MEDIA_REWIND = 266, /**< Rewind */ SDL_SCANCODE_MEDIA_NEXT_TRACK = 267, /**< Next Track */ SDL_SCANCODE_MEDIA_PREVIOUS_TRACK = 268, /**< Previous Track */ SDL_SCANCODE_MEDIA_STOP = 269, /**< Stop */ SDL_SCANCODE_MEDIA_EJECT = 270, /**< Eject */ SDL_SCANCODE_MEDIA_PLAY_PAUSE = 271, /**< Play / Pause */ SDL_SCANCODE_MEDIA_SELECT = 272, /* Media Select */ SDL_SCANCODE_AC_NEW = 273, /**< AC New */ SDL_SCANCODE_AC_OPEN = 274, /**< AC Open */ SDL_SCANCODE_AC_CLOSE = 275, /**< AC Close */ SDL_SCANCODE_AC_EXIT = 276, /**< AC Exit */ SDL_SCANCODE_AC_SAVE = 277, /**< AC Save */ SDL_SCANCODE_AC_PRINT = 278, /**< AC Print */ SDL_SCANCODE_AC_PROPERTIES = 279, /**< AC Properties */ SDL_SCANCODE_AC_SEARCH = 280, /**< AC Search */ SDL_SCANCODE_AC_HOME = 281, /**< AC Home */ SDL_SCANCODE_AC_BACK = 282, /**< AC Back */ SDL_SCANCODE_AC_FORWARD = 283, /**< AC Forward */ SDL_SCANCODE_AC_STOP = 284, /**< AC Stop */ SDL_SCANCODE_AC_REFRESH = 285, /**< AC Refresh */ SDL_SCANCODE_AC_BOOKMARKS = 286, /**< AC Bookmarks */ /* @} *//* Usage page 0x0C */ /** * \name Mobile keys * * These are values that are often used on mobile phones. */ /* @{ */ SDL_SCANCODE_SOFTLEFT = 287, /**< Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom left of the display. */ SDL_SCANCODE_SOFTRIGHT = 288, /**< Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom right of the display. */ SDL_SCANCODE_CALL = 289, /**< Used for accepting phone calls. */ SDL_SCANCODE_ENDCALL = 290, /**< Used for rejecting phone calls. */ /* @} *//* Mobile keys */ /* Add any other keys here. */ SDL_SCANCODE_RESERVED = 400, /**< 400-500 reserved for dynamic keycodes */ SDL_SCANCODE_COUNT = 512 /**< not a key, just marks the number of scancodes for array bounds */ } SDL_Scancode; #endif /* SDL_scancode_h_ */
1
0.784797
1
0.784797
game-dev
MEDIA
0.448842
game-dev
0.580623
1
0.580623
ChengF3ng233/Aluminium
5,401
src/main/java/net/minecraft/world/WorldSettings.java
package net.minecraft.world; import net.minecraft.entity.player.PlayerCapabilities; import net.minecraft.world.storage.WorldInfo; public final class WorldSettings { /** * The seed for the map. */ private final long seed; /** * The EnumGameType. */ private final WorldSettings.GameType theGameType; /** * Switch for the map features. 'true' for enabled, 'false' for disabled. */ private final boolean mapFeaturesEnabled; /** * True if hardcore mode is enabled */ private final boolean hardcoreEnabled; private final WorldType terrainType; /** * True if Commands (cheats) are allowed. */ private boolean commandsAllowed; /** * True if the Bonus Chest is enabled. */ private boolean bonusChestEnabled; private String worldName; public WorldSettings(long seedIn, WorldSettings.GameType gameType, boolean enableMapFeatures, boolean hardcoreMode, WorldType worldTypeIn) { this.worldName = ""; this.seed = seedIn; this.theGameType = gameType; this.mapFeaturesEnabled = enableMapFeatures; this.hardcoreEnabled = hardcoreMode; this.terrainType = worldTypeIn; } public WorldSettings(WorldInfo info) { this(info.getSeed(), info.getGameType(), info.isMapFeaturesEnabled(), info.isHardcoreModeEnabled(), info.getTerrainType()); } /** * Enables the bonus chest. */ public WorldSettings enableBonusChest() { this.bonusChestEnabled = true; return this; } /** * Enables Commands (cheats). */ public WorldSettings enableCommands() { this.commandsAllowed = true; return this; } public WorldSettings setWorldName(String name) { this.worldName = name; return this; } /** * Returns true if the Bonus Chest is enabled. */ public boolean isBonusChestEnabled() { return this.bonusChestEnabled; } /** * Returns the seed for the world. */ public long getSeed() { return this.seed; } /** * Gets the game type. */ public WorldSettings.GameType getGameType() { return this.theGameType; } /** * Returns true if hardcore mode is enabled, otherwise false */ public boolean getHardcoreEnabled() { return this.hardcoreEnabled; } /** * Get whether the map features (e.g. strongholds) generation is enabled or disabled. */ public boolean isMapFeaturesEnabled() { return this.mapFeaturesEnabled; } public WorldType getTerrainType() { return this.terrainType; } /** * Returns true if Commands (cheats) are allowed. */ public boolean areCommandsAllowed() { return this.commandsAllowed; } /** * Gets the GameType by ID */ public static WorldSettings.GameType getGameTypeById(int id) { return WorldSettings.GameType.getByID(id); } public String getWorldName() { return this.worldName; } public enum GameType { NOT_SET(-1, ""), SURVIVAL(0, "survival"), CREATIVE(1, "creative"), ADVENTURE(2, "adventure"), SPECTATOR(3, "spectator"); int id; String name; GameType(int typeId, String nameIn) { this.id = typeId; this.name = nameIn; } public int getID() { return this.id; } public String getName() { return this.name; } public void configurePlayerCapabilities(PlayerCapabilities capabilities) { if (this == CREATIVE) { capabilities.allowFlying = true; capabilities.isCreativeMode = true; capabilities.disableDamage = true; } else if (this == SPECTATOR) { capabilities.allowFlying = true; capabilities.isCreativeMode = false; capabilities.disableDamage = true; capabilities.isFlying = true; } else { capabilities.allowFlying = false; capabilities.isCreativeMode = false; capabilities.disableDamage = false; capabilities.isFlying = false; } capabilities.allowEdit = !this.isAdventure(); } public boolean isAdventure() { return this == ADVENTURE || this == SPECTATOR; } public boolean isCreative() { return this == CREATIVE; } public boolean isSurvivalOrAdventure() { return this == SURVIVAL || this == ADVENTURE; } public static WorldSettings.GameType getByID(int idIn) { for (WorldSettings.GameType worldsettings$gametype : values()) { if (worldsettings$gametype.id == idIn) { return worldsettings$gametype; } } return SURVIVAL; } public static WorldSettings.GameType getByName(String gamemodeName) { for (WorldSettings.GameType worldsettings$gametype : values()) { if (worldsettings$gametype.name.equals(gamemodeName)) { return worldsettings$gametype; } } return SURVIVAL; } } }
1
0.902069
1
0.902069
game-dev
MEDIA
0.965968
game-dev
0.711882
1
0.711882
atframework/atsf4g-co
1,495
src/tools/simulator/lua/cpp/lua_engine/lua_binding_mgr.cpp
#include <cstdlib> #include "lua_engine.h" #include "lua_binding_mgr.h" namespace script { namespace lua { lua_binding_class_mgr_base::lua_binding_class_mgr_base() { lua_binding_mgr::me()->lua_states_.push_back(this); } lua_binding_class_mgr_base::~lua_binding_class_mgr_base() {} lua_binding_mgr::lua_binding_mgr() {} lua_binding_mgr::~lua_binding_mgr() {} int lua_binding_mgr::add_lua_engine(lua_engine *engine) { if (nullptr == engine || nullptr == engine->get_lua_state()) { return -1; } for (func_type &fn : auto_bind_list_) { lua_auto_block block(engine->get_lua_state()); fn(engine->get_lua_state()); } for (auto &cmgr : lua_states_) { cmgr->add_lua_state(engine->get_lua_state()); } return 0; } int lua_binding_mgr::remove_lua_engine(lua_engine *engine) { if (nullptr == engine || nullptr == engine->get_lua_state()) { return -1; } for (auto &cmgr : lua_states_) { cmgr->remove_lua_state(engine->get_lua_state()); } return 0; } int lua_binding_mgr::proc(lua_engine *engine) { lua_State *L = nullptr; if (nullptr != engine) { L = engine->get_lua_state(); } for (auto &mgr : lua_states_) { mgr->proc(L); } return 0; } void lua_binding_mgr::add_bind(func_type fn) { auto_bind_list_.push_back(fn); } lua_binding_wrapper::lua_binding_wrapper(lua_binding_mgr::func_type fn) { lua_binding_mgr::me()->add_bind(fn); } lua_binding_wrapper::~lua_binding_wrapper() {} } // namespace lua } // namespace script
1
0.646269
1
0.646269
game-dev
MEDIA
0.251532
game-dev
0.632991
1
0.632991
HyperMC-Team/OpenRoxy
1,960
src/main/java/Rename/Class270.java
package Rename; /** * @HyperTeam * @author Treasure # 1337 * @date 2024/8/23 * @Description: thanks help for QianXia */ import java.util.ArrayList; import java.util.List; import net.minecraft.block.BlockWeb; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import tech.skidonion.obfuscator.annotations.StringEncryption; @StringEncryption public class Class270 extends Class252 { private final Class257 mode = new Class257("Mode", "Vanilla", "Vanilla", "GrimAC"); private final List<BlockPos> pos = new ArrayList<BlockPos>(); private boolean pass = true; public Class270() { super("Class270", Class263.Movement); } @Class14 public void onUpdate(Class50 event) { if (Class270.mc.thePlayer.isInWeb) { Class270.mc.thePlayer.isInWeb = false; } } @Class14 public void onWorld(Class55 event) { this.pos.clear(); } @Class14 public void onTick(Class52 event) { if (this.isNull()) { return; } if (this.mode.getMode().equals("GrimAC")) { for (int i = -2; i <= 2; ++i) { for (int j = -2; j < 2; ++j) { for (int k = -2; k < 2; ++k) { BlockPos pos = Class270.mc.thePlayer.getPosition().add(i, j, k); if (Class270.mc.theWorld.getBlockState(pos) == null || !(Class270.mc.theWorld.getBlockState(pos).getBlock() instanceof BlockWeb) || this.pos.contains(pos)) continue; mc.getNetHandler().addToSendQueue(new Class365(Class365.Action.START_DESTROY_BLOCK, pos, EnumFacing.DOWN)); mc.getNetHandler().addToSendQueue(new Class365(Class365.Action.STOP_DESTROY_BLOCK, pos, EnumFacing.DOWN)); Class270.mc.theWorld.setBlockToAir(pos); this.pass = true; } } } } } }
1
0.747088
1
0.747088
game-dev
MEDIA
0.929501
game-dev
0.765236
1
0.765236
tangziwen/CubeMiniGame
6,824
CubeEngine/External/Bullet/BulletSoftBody/btSoftBodyData.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_SOFTBODY_FLOAT_DATA #define BT_SOFTBODY_FLOAT_DATA #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletDynamics/Dynamics/btRigidBody.h" struct SoftBodyMaterialData { float m_linearStiffness; float m_angularStiffness; float m_volumeStiffness; int m_flags; }; struct SoftBodyNodeData { SoftBodyMaterialData *m_material; btVector3FloatData m_position; btVector3FloatData m_previousPosition; btVector3FloatData m_velocity; btVector3FloatData m_accumulatedForce; btVector3FloatData m_normal; float m_inverseMass; float m_area; int m_attach; int m_pad; }; struct SoftBodyLinkData { SoftBodyMaterialData *m_material; int m_nodeIndices[2]; // Node pointers float m_restLength; // Rest length int m_bbending; // Bending link }; struct SoftBodyFaceData { btVector3FloatData m_normal; // Normal SoftBodyMaterialData *m_material; int m_nodeIndices[3]; // Node pointers float m_restArea; // Rest area }; struct SoftBodyTetraData { btVector3FloatData m_c0[4]; // gradients SoftBodyMaterialData *m_material; int m_nodeIndices[4]; // Node pointers float m_restVolume; // Rest volume float m_c1; // (4*kVST)/(im0+im1+im2+im3) float m_c2; // m_c1/sum(|g0..3|^2) int m_pad; }; struct SoftRigidAnchorData { btMatrix3x3FloatData m_c0; // Impulse matrix btVector3FloatData m_c1; // Relative anchor btVector3FloatData m_localFrame; // Anchor position in body space btRigidBodyData *m_rigidBody; int m_nodeIndex; // Node pointer float m_c2; // ima*dt }; struct SoftBodyConfigData { int m_aeroModel; // Aerodynamic model (default: V_Point) float m_baumgarte; // Velocities correction factor (Baumgarte) float m_damping; // Damping coefficient [0,1] float m_drag; // Drag coefficient [0,+inf] float m_lift; // Lift coefficient [0,+inf] float m_pressure; // Pressure coefficient [-inf,+inf] float m_volume; // Volume conversation coefficient [0,+inf] float m_dynamicFriction; // Dynamic friction coefficient [0,1] float m_poseMatch; // Pose matching coefficient [0,1] float m_rigidContactHardness; // Rigid contacts hardness [0,1] float m_kineticContactHardness; // Kinetic contacts hardness [0,1] float m_softContactHardness; // Soft contacts hardness [0,1] float m_anchorHardness; // Anchors hardness [0,1] float m_softRigidClusterHardness; // Soft vs rigid hardness [0,1] (cluster only) float m_softKineticClusterHardness; // Soft vs kinetic hardness [0,1] (cluster only) float m_softSoftClusterHardness; // Soft vs soft hardness [0,1] (cluster only) float m_softRigidClusterImpulseSplit; // Soft vs rigid impulse split [0,1] (cluster only) float m_softKineticClusterImpulseSplit; // Soft vs rigid impulse split [0,1] (cluster only) float m_softSoftClusterImpulseSplit; // Soft vs rigid impulse split [0,1] (cluster only) float m_maxVolume; // Maximum volume ratio for pose float m_timeScale; // Time scale int m_velocityIterations; // Velocities solver iterations int m_positionIterations; // Positions solver iterations int m_driftIterations; // Drift solver iterations int m_clusterIterations; // Cluster solver iterations int m_collisionFlags; // Collisions flags }; struct SoftBodyPoseData { btMatrix3x3FloatData m_rot; // Rotation btMatrix3x3FloatData m_scale; // Scale btMatrix3x3FloatData m_aqq; // Base scaling btVector3FloatData m_com; // COM btVector3FloatData *m_positions; // Reference positions float *m_weights; // Weights int m_numPositions; int m_numWeigts; int m_bvolume; // Is valid int m_bframe; // Is frame float m_restVolume; // Rest volume int m_pad; }; struct SoftBodyClusterData { btTransformFloatData m_framexform; btMatrix3x3FloatData m_locii; btMatrix3x3FloatData m_invwi; btVector3FloatData m_com; btVector3FloatData m_vimpulses[2]; btVector3FloatData m_dimpulses[2]; btVector3FloatData m_lv; btVector3FloatData m_av; btVector3FloatData *m_framerefs; int *m_nodeIndices; float *m_masses; int m_numFrameRefs; int m_numNodes; int m_numMasses; float m_idmass; float m_imass; int m_nvimpulses; int m_ndimpulses; float m_ndamping; float m_ldamping; float m_adamping; float m_matching; float m_maxSelfCollisionImpulse; float m_selfCollisionImpulseFactor; int m_containsAnchor; int m_collide; int m_clusterIndex; }; enum btSoftJointBodyType { BT_JOINT_SOFT_BODY_CLUSTER=1, BT_JOINT_RIGID_BODY, BT_JOINT_COLLISION_OBJECT }; struct btSoftBodyJointData { void *m_bodyA; void *m_bodyB; btVector3FloatData m_refs[2]; float m_cfm; float m_erp; float m_split; int m_delete; btVector3FloatData m_relPosition[2];//linear int m_bodyAtype; int m_bodyBtype; int m_jointType; int m_pad; }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btSoftBodyFloatData { btCollisionObjectFloatData m_collisionObjectData; SoftBodyPoseData *m_pose; SoftBodyMaterialData **m_materials; SoftBodyNodeData *m_nodes; SoftBodyLinkData *m_links; SoftBodyFaceData *m_faces; SoftBodyTetraData *m_tetrahedra; SoftRigidAnchorData *m_anchors; SoftBodyClusterData *m_clusters; btSoftBodyJointData *m_joints; int m_numMaterials; int m_numNodes; int m_numLinks; int m_numFaces; int m_numTetrahedra; int m_numAnchors; int m_numClusters; int m_numJoints; SoftBodyConfigData m_config; }; #endif //BT_SOFTBODY_FLOAT_DATA
1
0.867182
1
0.867182
game-dev
MEDIA
0.98074
game-dev
0.5686
1
0.5686
KirillOsenkov/MetadataTools
7,976
src/PETree/PE/Resources.cs
using System.Collections.Generic; using System.Linq; namespace GuiLabs.FileFormat.PE; public class ResourceTable : Node { public override void Parse() { var directory = Add<ResourceDirectory>("Root directory"); Process(directory); AddRemainingPadding(); } private void Process(ResourceDirectory directory, string parentResourceKind = null) { foreach (var idEntry in directory.Children.OfType<IdDirectoryEntry>()) { var offset = idEntry.Offset.ReadUint32(); if ((offset & 0x80000000) != 0) { string resourceKind = parentResourceKind; if (parentResourceKind == null && IdDirectoryEntry.ResourceTypes.TryGetValue(idEntry.Id.Value, out resourceKind)) { idEntry.Text = resourceKind; } var directoryOffset = offset & ~0x80000000; var subdirectory = new ResourceDirectory { Start = Start + (int)directoryOffset }; Add(subdirectory); Process(subdirectory, resourceKind); } else { Resource resource; if (parentResourceKind == "Version") { resource = new VersionResource(); } else if (parentResourceKind == "Manifest") { resource = new NativeManifestResource(); } else { resource = new Resource(); } resource.Start = Start + (int)offset; if (parentResourceKind != null) { resource.Text = parentResourceKind; resource.Type = parentResourceKind; } Add(resource); AddAlignedPadding(4); } } } } public class Resource : Node { public override void Parse() { RVA = AddFourBytes("RVA"); Size = AddFourBytes("Size"); Codepage = AddFourBytes("Codepage"); Zero = AddFourBytes("Zero"); var peFile = Root as PEFile; var start = peFile.ResolveVirtualAddress(RVA.Value); ParseBytes(start); } protected virtual void ParseBytes(int start) { Bytes = new BytesNode() { Start = start, Length = Size.Value, Text = $"{Type} bytes" }; this.Root.Add(Bytes); } public FourBytes RVA { get; set; } public FourBytes Size { get; set; } public FourBytes Codepage { get; set; } public FourBytes Zero { get; set; } public Node Bytes { get; set; } public string Type { get; set; } } public class VersionResource : Resource { protected override void ParseBytes(int start) { VersionHeader = new VersionHeader { Start = start }; Root.Add(VersionHeader); } public VersionHeader VersionHeader { get; set; } } public class NativeManifestResource : Resource { protected override void ParseBytes(int start) { Xml = new Utf8String { Start = start, Length = Size.Value, Text = "Native manifest XML" }; Root.Add(Xml); } public Utf8String Xml { get; set; } } public class VersionHeader : Node { public override void Parse() { Size = AddTwoBytes("Size"); Length = Size.Value; ValueLength = AddTwoBytes("Value length"); Type = AddTwoBytes("Type"); Key = Add<ZeroTerminatedUtf16String>("Key"); Text = Key.Text; AddAlignedPadding(4); if (ValueLength.Value > 0) { if (Key.Text == "VS_VERSION_INFO" && ValueLength.Value == 52) { Value = Add<VSFixedFileInfo>("File info"); } else if (Type.Value == 1) { Value = Add<ZeroTerminatedUtf16String>("Value"); Text = $"{Key.Text} = {Value.Text}"; } else { Value = AddBytes(ValueLength.Value, "Value"); } AddAlignedPadding(4); } while (this.LastChildEnd < End) { Add<VersionHeader>(); } } public TwoBytes Size { get; set; } public TwoBytes ValueLength { get; set; } public TwoBytes Type { get; set; } public ZeroTerminatedUtf16String Key { get; set; } public Node Value { get; set; } } public class VSFixedFileInfo : Node { public override void Parse() { Signature = AddFourBytes("Signature"); StrucVersion = AddFourBytes("StrucVersion"); FileVersionMS = AddFourBytes("FileVersionMS"); FileVersionLS = AddFourBytes("FileVersionLS"); ProductVersionMS = AddFourBytes("ProductVersionMS"); ProductVersionLS = AddFourBytes("ProductVersionLS"); FileFlagsMask = AddFourBytes("FileFlagsMask"); FileFlags = AddFourBytes("FileFlags"); FileOS = AddFourBytes("FileOS"); FileType = AddFourBytes("FileType"); FileSubType = AddFourBytes("FileSubType"); FileDateMS = AddFourBytes("FileDateMS"); FileDateLS = AddFourBytes("FileDateLS"); } public FourBytes Signature { get; set; } public FourBytes StrucVersion { get; set; } public FourBytes FileVersionMS { get; set; } public FourBytes FileVersionLS { get; set; } public FourBytes ProductVersionMS { get; set; } public FourBytes ProductVersionLS { get; set; } public FourBytes FileFlagsMask { get; set; } public FourBytes FileFlags { get; set; } public FourBytes FileOS { get; set; } public FourBytes FileType { get; set; } public FourBytes FileSubType { get; set; } public FourBytes FileDateMS { get; set; } public FourBytes FileDateLS { get; set; } } public class ResourceDirectory : Node { public override void Parse() { ResourceDirectoryTable = Add<ResourceDirectoryTable>("Resource directory table"); int nameCount = ResourceDirectoryTable.NameEntriesAmount.Value; int idCount = ResourceDirectoryTable.IdEntriesAmount.Value; int count = nameCount + idCount; for (int i = 0; i < count; i++) { uint id = Buffer.ReadUInt32(LastChildEnd); if ((id & 0x80000000) == 0) { var idEntry = Add<IdDirectoryEntry>($"Id: {id}"); } } } public ResourceDirectoryTable ResourceDirectoryTable { get; set; } } public class ResourceDirectoryTable : Node { public override void Parse() { Characteristics = AddFourBytes("Characteristics"); TimeDateStamp = AddFourBytes("TimeDate stamp"); MajorVersion = AddTwoBytes("Major version"); MinorVersion = AddTwoBytes("Minor version"); NameEntriesAmount = AddTwoBytes("NameEntriesAmount"); IdEntriesAmount = AddTwoBytes("IdEntriesAmount"); } public FourBytes Characteristics { get; set; } public FourBytes TimeDateStamp { get; set; } public TwoBytes MajorVersion { get; set; } public TwoBytes MinorVersion { get; set; } public TwoBytes NameEntriesAmount { get; set; } public TwoBytes IdEntriesAmount { get; set; } } public class IdDirectoryEntry : Node { public static Dictionary<int, string> ResourceTypes = new() { [1] = "Cursor", [2] = "Bitmap", [3] = "Icon", [4] = "Menu", [5] = "Dialog", [6] = "String", [9] = "Accelerator", [10] = "StringData", [12] = "GroupCursor", [14] = "GroupIcon", [16] = "Version", [24] = "Manifest" }; public override void Parse() { Id = AddFourBytes("Id"); Offset = AddFourBytes("Offset"); } public FourBytes Id { get; set; } public FourBytes Offset { get; set; } }
1
0.878016
1
0.878016
game-dev
MEDIA
0.663646
game-dev
0.913629
1
0.913629
kuaifengle/2d-player-statemachine
1,112
player/states/AIR_ATTACK_1.gd
extends State var attack_time = 0.45 var attack_direction = 0 ## 进入状态 func enter() -> void: attack_direction = 0 parent.is_combo = false state_time = attack_time parent.direction = gameInputControl.get_movemonet_direction() attack_direction = sign(parent.direction.x if !is_zero_approx(parent.direction.x) else parent.get_direction()) animation_player.play("AIR_ATTACK_1") parent.change_attack_shape('AIR_ATTACK_1') if(parent.active_weapon_state != parent.WEAPONS.sword): parent.change_weapons() ## 退出状态 func exit() -> void: animation_player.stop() ## 常规帧 func update(_delta: float) -> void: pass ## 物理帧 func physics_process(delta: float) -> void: state_time -= delta parent.velocity.y = 10 if (gameInputControl.is_attack() && state_time < 0.3 && !parent.is_combo): parent.is_combo = true elif (state_time <= 0): parent.velocity.x = 0 parent.velocity.y = 0 if(parent.is_combo): finished.emit("AIR_ATTACK_2") else: finished.emit("FALL") parent.velocity.x = 40 * attack_direction parent.move_and_slide() ## 按键处理 func handled_input(_event:InputEvent) -> void: pass
1
0.813669
1
0.813669
game-dev
MEDIA
0.981516
game-dev
0.968351
1
0.968351
id-Software/Enemy-Territory
199,125
src/botai/ai_dmnet_mp.c
/* =========================================================================== Wolfenstein: Enemy Territory GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Wolfenstein: Enemy Territory GPL Source Code (“Wolf ET Source Code”). Wolf ET Source Code 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. Wolf ET Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Wolf: ET Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Wolf ET Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ /***************************************************************************** * name: ai_dmnet_mp.c * * desc: Wolf bot AI * * *****************************************************************************/ #include "../game/g_local.h" #include "../game/botlib.h" #include "../game/be_aas.h" #include "../game/be_ea.h" #include "../game/be_ai_char.h" #include "../game/be_ai_chat.h" #include "../game/be_ai_gen.h" #include "../game/be_ai_goal.h" #include "../game/be_ai_move.h" #include "../game/be_ai_weap.h" #include "../botai/botai.h" // #include "ai_main.h" #include "ai_team.h" #include "ai_dmq3.h" #include "ai_cmd.h" #include "ai_dmnet_mp.h" //data file headers #include "chars.h" //characteristics #include "inv.h" //indexes into the inventory #include "syn.h" //synonyms #include "match.h" //string matching types and vars /* ================== BotMP_MoveToGoal ================== */ void BotMP_MoveToGoal( bot_state_t *bs, bot_moveresult_t * result, int movestate, bot_goal_t * goal, int travelflags ) { #ifdef _DEBUG if ( bot_debug.integer == 3 && level.clients[0].sess.spectatorClient == bs->client ) { goal->flags |= GFL_DEBUGPATH; } else { goal->flags &= ~GFL_DEBUGPATH; } #endif // _DEBUG trap_BotMoveToGoal( result, movestate, goal, travelflags ); } /* ================== AIEnter_MP_Intermission() ================== */ void AIEnter_MP_Intermission( bot_state_t *bs ) { //reset the bot state BotResetState( bs ); bs->ainode = AINode_MP_Intermission; bs->ainodeText = "AINode_MP_Intermission"; } /* ================== AINode_MP_Intermission() ================== */ int AINode_MP_Intermission( bot_state_t *bs ) { //if the intermission ended if ( !BotIntermission( bs ) ) { AIEnter_MP_Stand( bs ); } return qtrue; } /* ================== AIEnter_MP_Observer() ================== */ void AIEnter_MP_Observer( bot_state_t *bs ) { //reset the bot state BotResetState( bs ); bs->ainode = AINode_MP_Observer; bs->ainodeText = "AINode_MP_Observer"; } /* ================== AINode_MP_Observer() ================== */ int AINode_MP_Observer( bot_state_t *bs ) { //if the bot left observer mode if ( !BotIsObserver( bs ) ) { AIEnter_MP_Stand( bs ); } return qtrue; } /* ================== AIEnter_MP_Stand() ================== */ void AIEnter_MP_Stand( bot_state_t *bs ) { //bs->standfindenemy_time = trap_AAS_Time() + 1; bs->respawn_time = trap_AAS_Time() + 20; // after this long just standing around, suicide bs->ignore_specialgoal_time = 0; bs->ainode = AINode_MP_Stand; bs->ainodeText = "AINode_MP_Stand"; } /* ================== AINode_MP_Stand() ================== */ int AINode_MP_Stand( bot_state_t *bs ) { bot_goal_t goal; vec3_t pos; // Gordon: pow, so just stand around till scripted if ( BotIsPOW( bs ) ) { return qtrue; } if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } if ( bs->standfindenemy_time < trap_AAS_Time() ) { if ( BotFindEnemyMP( bs, -1, qfalse ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } //bs->standfindenemy_time = trap_AAS_Time() + 1; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } if ( bs->stand_time < trap_AAS_Time() ) { //trap_BotEnterChat(bs->cs, bs->client, bs->chatto); //bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); if ( bs->ainode != AINode_MP_Stand ) { return qfalse; } else if ( !bs->areanum ) { // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } else { // stand for a bit longer bs->stand_time = trap_AAS_Time() + 0.4 + 0.4 * random(); } } else { // look for health/ammo packs if ( BotFindNearbyGoal( bs ) ) { AIEnter_MP_Seek_NBG( bs ); return qfalse; } } // check for dangerous elements VectorCopy( bs->origin, goal.origin ); goal.areanum = bs->areanum; goal.entitynum = bs->client; if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // if we are outside HALF autonomy range, get back there if ( BotGetMovementAutonomyPos( bs, pos ) ) { float halfDist = 0.5 * BotGetMovementAutonomyRange( bs, NULL ); if ( VectorDistanceSquared( bs->origin, pos ) > ( halfDist * halfDist ) ) { AIEnter_MP_MoveToAutonomyRange( bs ); return qfalse; } } // if we have been standing for too long if ( bs->respawn_time < trap_AAS_Time() ) { Cmd_Kill_f( &g_entities[bs->client] ); } // return qtrue; } /* ================== AIEnter_MP_Respawn() ================== */ void AIEnter_MP_Respawn( bot_state_t *bs ) { //reset some states trap_BotResetMoveState( bs->ms ); trap_BotResetGoalState( bs->gs ); trap_BotResetAvoidGoals( bs->gs ); trap_BotResetAvoidReach( bs->ms ); bs->respawn_time = trap_AAS_Time() + 1 + random(); bs->respawnchat_time = 0; // bs->flags &= ~BFL_MISCFLAG; bs->lastClassCheck = 0; //set respawn state bs->respawn_wait = qfalse; bs->ainode = AINode_MP_Respawn; bs->ainodeText = "AINode_MP_Respawn"; } /* ================== AINode_MP_Respawn() ================== */ int AINode_MP_Respawn( bot_state_t *bs ) { qboolean do_respawn = qfalse; gentity_t *ent; int testtime; // RF, only hit jump if reinforcement time is about to run out ent = BotGetEntity( bs->entitynum ); // disabled, if medic has troubles finding us, we'll be waiting forever // if (ent->missionLevel < level.time) { // else medic is heading to us to revive if ( ent->client->sess.sessionTeam == TEAM_AXIS ) { testtime = level.time % g_redlimbotime.integer; if ( testtime > g_redlimbotime.integer - 2000 ) { do_respawn = qtrue; } } else if ( ent->client->sess.sessionTeam == TEAM_ALLIES ) { testtime = level.time % g_bluelimbotime.integer; if ( testtime > g_bluelimbotime.integer - 2000 ) { do_respawn = qtrue; } } // } // if ( bs->lastClassCheck < level.time - 4000 ) { // check for a better class bs->mpClass = BotSuggestClass( bs, bs->mpTeam ); ent->client->sess.latchPlayerType = bs->mpClass; if ( bs->mpClass != ent->client->sess.playerType ) { bs->flags |= BFL_MISCFLAG; } bs->lastClassCheck = level.time + rand() % 1000; // sometimes when we die, we should re-evaluate our weapon selection if ( ( bs->flags & BFL_MISCFLAG ) || ( random() < 0.3 ) ) { bs->mpWeapon = BotSuggestWeapon( bs, bs->sess.sessionTeam ); ent->client->sess.latchPlayerWeapon = bs->mpWeapon; } } if ( bs->respawn_wait ) { if ( !BotIsDead( bs ) ) { // perhaps we should tell everyone who we are if ( bs->flags & BFL_MISCFLAG ) { static int lastCall; if ( lastCall > level.time || lastCall < level.time - 2000 ) { lastCall = level.time; switch ( bs->mpClass ) { case PC_SOLDIER: BotVoiceChatAfterIdleTime( bs->client, "IamSoldier", SAY_TEAM, 1000 + rand() % 5000, BOT_SHOWTEXT, 20000, qfalse ); break; case PC_MEDIC: BotVoiceChatAfterIdleTime( bs->client, "IamMedic", SAY_TEAM, 1000 + rand() % 5000, BOT_SHOWTEXT, 20000, qfalse ); break; case PC_FIELDOPS: BotVoiceChatAfterIdleTime( bs->client, "IamLieutenant", SAY_TEAM, 1000 + rand() % 5000, BOT_SHOWTEXT, 20000, qfalse ); break; case PC_ENGINEER: BotVoiceChatAfterIdleTime( bs->client, "IamEngineer", SAY_TEAM, 1000 + rand() % 5000, BOT_SHOWTEXT, 20000, qfalse ); break; } } } else if ( bs->sess.sessionTeam == level.attackingTeam ) { if ( rand() % 2 ) { BotVoiceChatAfterIdleTime( bs->client, "LetsGo", SAY_TEAM, 1000 + rand() % 2000, qfalse, 20000, qfalse ); } } // BotDefaultNode( bs ); } else { trap_EA_Respawn( bs->client ); // RF, Wolf uses jump if ( do_respawn ) { trap_EA_Jump( bs->client ); } } } else if ( bs->respawn_time < trap_AAS_Time() ) { //wait until respawned bs->respawn_wait = qtrue; //elementary action respawn trap_EA_Respawn( bs->client ); // RF, Wolf uses jump if ( do_respawn ) { trap_EA_Jump( bs->client ); } // if ( bs->respawnchat_time ) { //trap_BotEnterChat(bs->cs, bs->client, bs->chatto); bs->enemy = -1; } } if ( bs->respawnchat_time && bs->respawnchat_time < trap_AAS_Time() - 0.5 ) { trap_EA_Talk( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_Seek_ActivateEntity() ================== */ void AIEnter_MP_Seek_ActivateEntity( bot_state_t *bs ) { bs->ainode = AINode_MP_Seek_ActivateEntity; bs->ainodeText = "AINode_MP_Seek_ActivateEntity"; } /* ================== AINode_MP_Seek_Activate_Entity() ================== */ int AINode_MP_Seek_ActivateEntity( bot_state_t *bs ) { bot_goal_t *goal; vec3_t target, dir; bot_moveresult_t moveresult; if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // if ( bot_grapple.integer ) { bs->tfl |= TFL_GRAPPLEHOOK; } //if in lava or slime the bot should be able to get out if ( BotInLava( bs ) ) { bs->tfl |= TFL_LAVA; } if ( BotInSlime( bs ) ) { bs->tfl |= TFL_SLIME; } //no enemy bs->enemy = -1; // goal = &bs->activategoal; //if the bot has no goal if ( !goal ) { bs->activate_time = 0; } //if the bot touches the current goal else if ( trap_BotTouchingGoal( bs->origin, goal ) ) { BotChooseWeapon( bs ); #ifdef DEBUG BotAI_Print( PRT_MESSAGE, "touched button or trigger\n" ); #endif //DEBUG bs->activate_time = 0; } // if ( bs->activate_time < trap_AAS_Time() ) { AIEnter_MP_Seek_NBG( bs ); return qfalse; } //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); } //check if the bot is blocked BotAIBlocked( bs, &moveresult, qtrue ); // if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else if ( !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( trap_BotMovementViewTarget( bs->ms, goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else { //vectoangles(moveresult.movedir, bs->ideal_viewangles); } bs->ideal_viewangles[2] *= 0.5; } //if the weapon is used for the bot movement if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) { bs->weaponnum = moveresult.weapon; } //if there is an enemy if ( BotFindEnemyMP( bs, -1, qfalse ) ) { if ( BotWantsToRetreat( bs ) ) { //keep the current long term goal and retreat // !!! TODO } else { trap_BotResetLastAvoidReach( bs->ms ); //empty the goal stack trap_BotEmptyGoalStack( bs->gs ); //go fight AIEnter_MP_Battle_Fight( bs ); } } return qtrue; } /* ================== AIEnter_MP_Seek_NBG() ================== */ void AIEnter_MP_Seek_NBG( bot_state_t *bs ) { //level.clients[0].sess.spectatorClient = bs->client; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_Seek_NBG; bs->ainodeText = "AINode_MP_Seek_NBG"; } /* ================== AINode_MP_Seek_NBG() ================== */ int AINode_MP_Seek_NBG( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *ent; // goal = bs->nearbygoal; // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // // should we stop pursuing this target? ent = BotGetEntity( goal.entitynum ); if ( !ent->inuse ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } else if ( ent->s.eType == ET_SUPPLIER ) { if ( !ClientNeedsAmmo( bs->client ) ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } } else if ( ent->s.eType == ET_HEALER ) { if ( BotHealthScale( bs->client ) >= 1.0 ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } } else if ( ent->s.eType == ET_ITEM && ent->touch ) { if ( /*trap_BotTouchingGoal( bs->origin, &goal ) ||*/ ( ent->r.svFlags & SVF_NOCLIENT ) ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } } //choose the best weapon to fight with BotChooseWeapon( bs ); //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); // fail bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } // return qtrue; } /* ================== AIEnter_MP_AvoidDanger() ================== */ void AIEnter_MP_AvoidDanger( bot_state_t *bs ) { int bestarea; // if this is dynamite if ( g_entities[bs->avoid_goal.entitynum].s.eType == ET_MISSILE && g_entities[bs->avoid_goal.entitynum].methodOfDeath == MOD_DYNAMITE ) { if ( !( rand() % 3 ) ) { BotVoiceChatAfterIdleTime( bs->client, "FireInTheHole", SAY_TEAM, 500, qfalse, 3000, qfalse ); } } bs->flags &= ~BFL_MISCFLAG; if ( !( bestarea = trap_AAS_AvoidDangerArea( bs->origin, bs->areanum, bs->avoid_goal.origin, BotPointAreaNum( -1, bs->avoid_goal.origin ), bs->avoid_goal.number + 100, bs->tfl ) ) ) { // no hiding spot, ignore it bs->flags |= BFL_MISCFLAG; } else { trap_AAS_AreaWaypoint( bestarea, bs->avoid_goal.origin ); bs->avoid_goal.areanum = bestarea; } bs->ainode = AINode_MP_AvoidDanger; bs->ainodeText = "AINode_MP_AvoidDanger"; } /* ================== AINode_MP_AvoidDanger() ================== */ int AINode_MP_AvoidDanger( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav; int bestarea; qboolean moved = qfalse; memset( &moveresult, 0, sizeof( moveresult ) ); goal = bs->avoid_goal; // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } //if the target has gone trav = &g_entities[goal.entitynum]; if ( !trav->inuse ) { // just look for a goal bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } else if ( trav->client && trav->health <= 0 ) { // just look for a goal bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } else if ( trav->s.eType == ET_CONSTRUCTIBLE ) { if ( ( g_entities[bs->client].client->lastConstructibleBlockingWarnEnt != goal.entitynum ) || ( ( level.time - g_entities[bs->client].client->lastConstructibleBlockingWarnTime ) > 5000 ) ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } } // if the avoid entity has changed if ( bs->avoid_spawnCount != trav->spawnCount ) { // just look for a goal bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // if the thing we're avoiding is a landmine, then we don't really need to run away from it, just take a few steps // don't need to move, is this a landmine? if ( ( trav->methodOfDeath == MOD_LANDMINE ) && VectorDistanceSquared( bs->origin, trav->r.currentOrigin ) > SQR( 256 ) ) { // we're done running bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // make sure the current goal origin is still safe // is this entity dangerous? if ( trav->client ) { // is this player dangerous? if ( !( trav->client->ps.weapon == WP_PANZERFAUST && trav->client->ps.weaponDelay ) ) { // not dangerous bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } VectorCopy( trav->r.currentOrigin, target ); } else if ( trav->s.eType == ET_CONSTRUCTIBLE ) { } else { if ( trav->s.eType == ET_MISSILE && trav->s.weapon == WP_DYNAMITE ) { VectorCopy( trav->r.currentOrigin, target ); } else { if ( !G_PredictMissile( trav, trav->nextthink - level.time, target, ( trav->s.eFlags & ( EF_BOUNCE | EF_BOUNCE_HALF ) ) ) ) { // not dangerous bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } } if ( ( bs->last_avoiddangerarea < level.time - 200 ) && ( VectorDistanceSquared( target, goal.origin ) < ( SQR( trav->splashRadius + 100 ) ) ) ) { bs->last_avoiddangerarea = level.time + rand() % 200; if ( !( bestarea = trap_AAS_AvoidDangerArea( bs->origin, bs->areanum, target, BotPointAreaNum( -1, target ), trav->splashRadius + 100, bs->tfl ) ) ) { // move away from the danger bs->flags |= BFL_MISCFLAG; } else { trap_AAS_AreaWaypoint( bestarea, bs->avoid_goal.origin ); bs->avoid_goal.areanum = bestarea; goal = bs->avoid_goal; } } } //update goal information // check for emergency targets (flags, etc) //if (BotCheckEmergencyTargets( bs )) { // return qfalse; //} if ( bs->flags & BFL_MISCFLAG ) { moved = qtrue; //initialize the movement state BotSetupForMovement( bs ); // move away from danger VectorSubtract( target, bs->origin, dir ); VectorNormalize( dir ); trap_EA_Move( bs->client, dir, 400 ); // randomly strafe also if ( level.time % 2000 < 1000 ) { trap_EA_MoveLeft( bs->client ); } else { trap_EA_MoveRight( bs->client );} } else { // are we close enough to the goal? if ( VectorDistanceSquared( bs->origin, goal.origin ) > ( 24 * 24 ) ) { // MOVEMENT REQUIRED // moved = qtrue; //choose the best weapon to fight with BotChooseWeapon( bs ); //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } // BotAIBlocked( bs, &moveresult, qtrue ); } } // //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( !moved ) { VectorSubtract( g_entities[goal.entitynum].r.currentOrigin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } // return qtrue; } /* ================== AIEnter_MP_GiveAmmo() ================== */ void AIEnter_MP_GiveAmmo( bot_state_t *bs ) { //level.clients[0].sess.spectatorClient = bs->client; bs->give_health_time = 0; bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_GiveAmmo; bs->ainodeText = "AINode_MP_GiveAmmo"; } /* ================== AINode_MP_GiveAmmo() ================== */ int AINode_MP_GiveAmmo( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav; goal = bs->target_goal; //if we have changed class if ( bs->sess.playerType != PC_FIELDOPS ) { BotDefaultNode( bs ); return qfalse; } //if we have to wait // Gordon: FIXME: this looks wrong if ( bs->cur_ps.classWeaponTime > level.time - 8000 ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } //if the target is dead trav = BotGetEntity( goal.entitynum ); // FIXME: temp hack in dealing with NULL returns from BotGetEntity (??) if ( trav == NULL ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } if ( !trav->inuse || !trav->client || ( trav->client->ps.pm_type != PM_NORMAL ) ) { // let them roam again trav->awaitingHelpTime = 0; // just look for a goal BotDefaultNode( bs ); return qfalse; } // do they have enough ammo now? if ( !ClientNeedsAmmo( trav->s.number ) ) { if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 72 ) ) { // we just helped them bs->last_helped_client = trav->s.number; bs->last_helped_time = level.time; // they should thank us if ( trav->r.svFlags & SVF_BOT ) { BotVoiceChatAfterIdleTime( trav->s.number, "Thanks", SAY_TEAM, 1000 + rand() % 2000, qfalse, 3000 + rand() % 2000, qfalse ); } } // let them roam again trav->awaitingHelpTime = 0; // just look for a goal BotDefaultNode( bs ); return qfalse; } //update goal information VectorCopy( trav->r.currentOrigin, bs->target_goal.origin ); bs->target_goal.areanum = BotPointAreaNum( trav->s.number, trav->r.currentOrigin ); if ( !bs->target_goal.areanum ) { BotDefaultNode( bs ); return qfalse; } goal = bs->target_goal; if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 100 ) && BotEntityVisible( bs->client, bs->eye, bs->viewangles, 360, trav->s.number, NULL ) ) { // make sure other bots dont head for this target also trav->awaitingHelpTime = level.time + 1500; } // are we close enough to the goal? if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 72 ) ) { if ( !bs->give_health_time ) { bs->give_health_time = level.time + 8000; } else if ( bs->give_health_time < level.time ) { BotDefaultNode( bs ); return qfalse; } // make sure other bots dont head for this target also trav->awaitingHelpTime = level.time + 1500; trav->botIgnoreAmmoTime = level.time + 1000; // switch to regen and pump away bs->weaponnum = WP_AMMO; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // aim directly at the dynamite VectorCopy( bs->origin, target ); VectorSubtract( trav->r.currentOrigin, target, dir ); dir[2] *= 0.5; VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // hold fire if ( bs->cur_ps.weapon == WP_AMMO && BotWeaponCharged( bs, WP_AMMO ) ) { trap_EA_Attack( bs->client ); } // return qtrue; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // MOVEMENT REQUIRED // //choose the best weapon to fight with BotChooseWeapon( bs ); //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * ( GetAmmoTableData( bs->cur_ps.weapon ) )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_MedicGiveHealth() ================== */ void AIEnter_MP_MedicGiveHealth( bot_state_t *bs ) { bs->give_health_time = 0; bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_MedicGiveHealth; bs->ainodeText = "AINode_MP_MedicGiveHealth"; } /* ================== AINode_MP_MedicGiveHealth() ================== */ int AINode_MP_MedicGiveHealth( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav; goal = bs->target_goal; //if we have changed class if ( bs->sess.playerType != PC_MEDIC ) { BotDefaultNode( bs ); return qfalse; } if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } //if the target has full health trav = &g_entities[goal.entitynum]; if ( !trav->inuse || !trav->client || ( trav->client->ps.pm_type != PM_NORMAL ) || ( trav->client->ps.pm_flags & PMF_LIMBO ) ) { // let them roam again trav->awaitingHelpTime = 0; // just look for a goal BotDefaultNode( bs ); return qfalse; } if ( BotHealthScale( trav->s.number ) >= 1.0 ) { if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 72 ) ) { // we just helped them bs->last_helped_client = trav->s.number; bs->last_helped_time = level.time; // they should thank us if ( trav->r.svFlags & SVF_BOT ) { BotVoiceChatAfterIdleTime( trav->s.number, "Thanks", SAY_TEAM, 1000 + rand() % 2000, qfalse, 3000 + rand() % 2000, qfalse ); } } // let them roam again trav->awaitingHelpTime = 0; // just look for a goal BotDefaultNode( bs ); return qfalse; } //update goal information VectorCopy( trav->r.currentOrigin, BotGetOrigin( trav->s.number ) ); bs->target_goal.areanum = BotGetArea( trav->s.number ); if ( !bs->target_goal.areanum ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } goal = bs->target_goal; // are we close enough to the goal? if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 72 ) ) { if ( !bs->give_health_time ) { bs->give_health_time = level.time + 8000; } else if ( bs->give_health_time < level.time ) { BotDefaultNode( bs ); return qfalse; } // make sure other bots dont head for this target also trav->awaitingHelpTime = level.time + 1500; trav->botIgnoreHealthTime = level.time + 1000; // switch to regen and pump away bs->weaponnum = WP_MEDKIT; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // aim directly at the player VectorCopy( bs->origin, target ); VectorSubtract( trav->r.currentOrigin, target, dir ); dir[2] *= 0.5; VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // hold fire if ( bs->cur_ps.weapon == WP_MEDKIT && BotWeaponCharged( bs, WP_MEDKIT ) ) { trap_EA_Attack( bs->client ); } return qtrue; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // MOVEMENT REQUIRED // //choose the best weapon to fight with BotChooseWeapon( bs ); //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_MedicRevive() ================== */ void AIEnter_MP_MedicRevive( bot_state_t *bs ) { bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_MedicRevive; bs->ainodeText = "AINode_MP_MedicRevive"; } /* ================== AINode_MP_MedicRevive() ================== */ int AINode_MP_MedicRevive( bot_state_t *bs ) { bot_goal_t goal, target; vec3_t targetpos, dir; bot_moveresult_t moveresult; int range; gentity_t *trav; goal = bs->target_goal; //if we have changed class if ( bs->sess.playerType != PC_MEDIC ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } //if the target is not dead or is in limbo trav = BotGetEntity( goal.entitynum ); if ( // START Gordon changes, 23/8/2002 !trav || // END Gordon changes, 23/8/2002 !trav->inuse || !trav->client || ( trav->client->ps.pm_flags & PMF_LIMBO ) ) { // just look for a goal bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // if someone is close to them, only they should continue reviving if ( g_entities[goal.entitynum].botIgnoreHealthTime >= level.time ) { int list[MAX_CLIENTS], numList; float ourDist, *distances; // // if there are too many defenders, and we are the furthest away, stop defending if ( ( numList = BotNumTeamMatesWithTarget( bs, goal.entitynum, list, MAX_CLIENTS ) ) > 0 ) { ourDist = VectorDistanceSquared( bs->origin, g_entities[goal.entitynum].r.currentOrigin ); if ( !trap_InPVS( bs->origin, g_entities[goal.entitynum].r.currentOrigin ) ) { ourDist += ( 2048 * 2048 ); } distances = BotSortPlayersByDistance( g_entities[goal.entitynum].r.currentOrigin, list, numList ); if ( distances[numList - 1] < ourDist ) { // we are the furthest bs->ignore_specialgoal_time = 0; bs->leader = -1; BotDefaultNode( bs ); return qfalse; } } } // if they are alive if ( trav->client->ps.pm_type != PM_DEAD ) { if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 72 ) ) { // we just helped them bs->last_helped_client = trav->s.number; bs->last_helped_time = level.time; // they should thank us if ( trav->r.svFlags & SVF_BOT ) { BotVoiceChatAfterIdleTime( trav->s.number, "Thanks", SAY_TEAM, 1000 + rand() % 2000, qfalse, 4000 + rand() % 2000, qfalse ); } } // look for someone to heal (like the person we just revived) if ( BotClass_MedicCheckGiveHealth( bs, 200, &target ) ) { bs->target_goal = target; AIEnter_MP_MedicGiveHealth( bs ); return qtrue; } // just look for a goal bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } //update goal information VectorCopy( trav->r.currentOrigin, bs->target_goal.origin ); bs->target_goal.areanum = BotPointAreaNum( trav->s.number, trav->r.currentOrigin ); if ( !bs->target_goal.areanum ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } goal = bs->target_goal; //look for closer revives range = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, goal.areanum, bs->tfl ); // if ( range < 200 && bs->enemy < 0 ) { // switch to regen bs->weaponnum = WP_MEDIC_SYRINGE; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // make sure other bots dont head for this target also g_entities[goal.entitynum].botIgnoreHealthTime = level.time + 500; } // are we close enough to the goal? if ( VectorDistanceSquared( bs->eye, goal.origin ) < SQR( 42 ) ) { // make sure other bots dont head for this target also g_entities[goal.entitynum].botIgnoreHealthTime = level.time + 1500; // crouch down trap_EA_Crouch( bs->client ); // switch to regen and pump away bs->weaponnum = WP_MEDIC_SYRINGE; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // aim directly at the dynamite VectorCopy( bs->origin, targetpos ); targetpos[2] += bs->cur_ps.viewheight; VectorSubtract( trav->r.currentOrigin, targetpos, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // hold fire if ( bs->cur_ps.weapon == WP_MEDIC_SYRINGE ) { trap_EA_Attack( bs->client ); } // return qtrue; } // if ( range > 200 ) { // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } } // // MOVEMENT REQUIRED // //choose the best weapon to fight with BotChooseWeapon( bs ); //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, targetpos ); VectorSubtract( targetpos, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, targetpos ) ) { VectorSubtract( targetpos, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, targetpos ); VectorSubtract( targetpos, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } // return qtrue; } /* ================== AIEnter_MP_PanzerTarget() ================== */ void AIEnter_MP_PanzerTarget( bot_state_t *bs ) { bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_PanzerTarget; bs->ainodeText = "AINode_MP_PanzerTarget"; bs->enemy = ENTITYNUM_WORLD; // fast view } /* ================== AINode_MP_PanzerTarget() ================== */ int AINode_MP_PanzerTarget( bot_state_t *bs ) { vec3_t vec; // if ( BotIsDead( bs ) ) { bs->enemy = -1; AIEnter_MP_Respawn( bs ); return qfalse; } // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } // if ( !BotWeaponWantScale( bs, WP_PANZERFAUST ) ) { bs->enemy = -1; bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } bs->weaponnum = WP_PANZERFAUST; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // // have we fired already? if ( !BotWeaponCharged( bs, bs->weaponnum ) ) { bs->enemy = -1; bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // look at the target VectorSubtract( bs->target_goal.origin, bs->eye, vec ); VectorNormalize( vec ); vectoangles( vec, bs->ideal_viewangles ); // if ( ( bs->cur_ps.weapon == bs->weaponnum ) && ( AngleDifference( bs->ideal_viewangles[YAW], bs->viewangles[YAW] ) < 0.5 ) && ( AngleDifference( bs->ideal_viewangles[PITCH], bs->viewangles[PITCH] ) < 0.5 ) ) { trap_EA_Attack( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_AttackTarget() ================== */ void AIEnter_MP_AttackTarget( bot_state_t *bs ) { bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_AttackTarget; bs->ainodeText = "AINode_MP_AttackTarget"; bs->enemy = bs->target_goal.entitynum; // fast view } /* ================== AINode_MP_AttackTarget() ================== */ int AINode_MP_AttackTarget( bot_state_t *bs ) { vec3_t vec; bot_goal_t goal; gentity_t *check; // goal = bs->target_goal; bs->weaponnum = BotBestTargetWeapon( bs, goal.entitynum ); if ( bs->weaponnum == WP_NONE ) { bs->enemy = -1; BotDefaultNode( bs ); return qfalse; } // if ( BotIsDead( bs ) ) { bs->enemy = -1; AIEnter_MP_Respawn( bs ); return qfalse; } // if ( BotIsObserver( bs ) ) { bs->enemy = -1; AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { bs->enemy = -1; AIEnter_MP_Intermission( bs ); return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { bs->enemy = -1; AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // check = BotGetVisibleDamagableScriptMover( bs ); if ( !check || ( check->s.number != goal.entitynum ) ) { bs->enemy = -1; BotDefaultNode( bs ); return qfalse; } // trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // look at the target VectorSubtract( bs->target_goal.origin, bs->eye, vec ); VectorNormalize( vec ); vectoangles( vec, bs->ideal_viewangles ); // if ( ( bs->cur_ps.weapon == bs->weaponnum ) && ( AngleDifference( bs->ideal_viewangles[YAW], bs->viewangles[YAW] ) < 0.5 ) && ( AngleDifference( bs->ideal_viewangles[PITCH], bs->viewangles[PITCH] ) < 0.5 ) ) { if ( bs->cur_ps.weapon == WP_GRENADE_LAUNCHER || bs->cur_ps.weapon == WP_GRENADE_PINEAPPLE ) { if ( BotSinglePlayer() || BotCoop() ) { // release immediately in single player } else if ( bs->cur_ps.grenadeTimeLeft ) { // release grenade } else { // hold onto it trap_EA_Attack( bs->client ); } } else { trap_EA_Attack( bs->client ); } } // return qtrue; } /* ================== AIEnter_MP_FixMG42() ================== */ void AIEnter_MP_FixMG42( bot_state_t *bs ) { //level.clients[0].sess.spectatorClient = bs->client; bs->arrive_time = level.time; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_FixMG42; bs->ainodeText = "AINode_MP_FixMG42"; } /* ================== AINode_MP_FixMG42() ================== */ int AINode_MP_FixMG42( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *ent; trace_t tr; // goal = bs->target_goal; ent = BotGetEntity( bs->target_goal.entitynum ); // return to this sniper spot if we go off temporarily ent->botIgnoreTime = 0; // if ( ent->melee->takedamage ) { bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { ent->botIgnoreTime = level.time + 5000; // other bots should avoid this spot AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { // return to this sniper spot after we're done ent->botIgnoreTime = 0; return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { // return to this sniper spot after we're done ent->botIgnoreTime = 0; AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // have we been waiting here for too long? if ( bs->arrive_time < level.time - 40000 ) { ent->botIgnoreTime = level.time + 5000; // other bots should avoid this spot if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // // other bots should avoid this spot ent->botIgnoreTime = level.time + 5000; VectorSubtract( bs->origin, goal.origin, dir ); if ( fabs( dir[2] ) < 100 ) { dir[2] = 0; } // is the destination blocked? if ( VectorLengthSquared( dir ) < SQR( 64 ) ) { trap_Trace( &tr, ent->s.origin, NULL, NULL, ent->s.origin, bs->client, MASK_PLAYERSOLID ); if ( tr.startsolid || tr.allsolid ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } } if ( VectorLengthSquared( dir ) > SQR( 8 ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); // bs->arrive_time = level.time; // wait a bit longer //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); if ( BotFindSpecialGoals( bs ) ) { return qfalse; } // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); // fail bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_WAITING ) { //if waiting for something if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { if ( VectorDistanceSquared( bs->origin, goal.origin ) > SQR( 32 ) ) { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; bs->enemyposition_time = 0; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( VectorLengthSquared( moveresult.movedir ) ) { //FIXME: look at cluster portals? vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } } } if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 16 ) ) { // We are at the spot, so start fixing bs->weaponnum = WP_PLIERS; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; bs->enemyposition_time = 0; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { if ( VectorDistanceSquared( bs->origin, bs->enemyorigin ) < SQR( 512 ) ) { // if they are real close, abort sniper mode if ( VectorDistanceSquared( bs->origin, g_entities[bs->enemy].r.currentOrigin ) < SQR( 1024 ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } } else { bs->enemy = -1; } } } else { // face the mg42 and start repairing VectorSubtract( ent->melee->r.currentOrigin, bs->eye, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // hold fire trap_EA_Attack( bs->client ); // dont abort until finished bs->arrive_time = level.time; } } else if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { // reload? trap_EA_Reload( bs->client ); } return qtrue; } /* ================== AIEnter_MP_Battle_MobileMG42 ================== */ void AIEnter_MP_Battle_MobileMG42( bot_state_t *bs ) { BotDebugViewClient( bs->client ); // bs->arrive_time = level.time; bs->lasthealth = g_entities[bs->client].health; bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_Battle_MobileMG42; bs->ainodeText = "AINode_MP_Battle_MobileMG42"; } /* ================== AINode_MP_Battle_MobileMG42() ================== */ int AINode_MP_Battle_MobileMG42( bot_state_t *bs ) { bot_goal_t goal; vec3_t dir, ang; int tookDamage = 0; bs->weaponnum = WP_MOBILE_MG42; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); bs->mobileMG42ProneTime = level.time; // if our health has dropped, abort tookDamage = bs->lasthealth - g_entities[bs->client].health; // bs->lasthealth = g_entities[bs->client].health; if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // if we have run out of ammo if ( !BotGotEnoughAmmoForWeapon( bs, bs->weaponnum ) ) { BotDefaultNode( bs ); return qtrue; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // look for something better to do if ( level.captureFlagMode && BotFlagAtBase( bs->sess.sessionTeam, NULL ) == qfalse ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // have we been waiting here for too long? or been hit too much? if ( tookDamage > 20 || g_entities[bs->client].health < 40 || bs->arrive_time < level.time - 5000 ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } BotAimAtEnemy( bs ); // wait until we are facing them correctly before going prone if ( !( bs->cur_ps.eFlags & EF_PRONE ) && ( fabs( AngleDifference( bs->ideal_viewangles[YAW], bs->viewangles[YAW] ) ) > 5.0f ) ) { return qtrue; } // stay prone trap_EA_Prone( bs->client ); // look for enemies // if we have an enemy, make sure they are still within view limits if ( bs->enemy >= 0 ) { if ( !BotEntityWithinView( bs, bs->enemy ) ) { bs->enemy = -1; } } if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy < 0 ) { // if we still have no enemy, then after a slight pause, allow us to escape prone mode if we find an // enemy outside our view if ( bs->arrive_time < level.time - 1500 ) { BotFindEnemyMP( bs, -1, qtrue ); // if we found one this time, escape prone mode if ( bs->enemy >= 0 ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } } } // if we took damage, check that there isn't a closer enemy we can attack if ( tookDamage > 0 ) { int oldEnemy; // oldEnemy = bs->enemy; bs->enemy = -1; BotFindEnemyMP( bs, -1, qtrue ); if ( bs->enemy >= 0 && bs->enemy != oldEnemy ) { // found someone else to attack AIEnter_MP_Battle_Fight( bs ); return qfalse; } // otherwise continue bs->enemy = oldEnemy; } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; bs->enemyposition_time = 0; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } if ( bs->enemy >= 0 ) { VectorSubtract( entinfo.origin, bs->eye, dir ); VectorNormalize( dir ); vectoangles( dir, ang ); if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 120, bs->enemy, NULL ) ) { // if they are real close, abort mg42 mode if ( VectorDistanceSquared( bs->origin, g_entities[bs->enemy].r.currentOrigin ) < SQR( 400 ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } // bs->arrive_time = level.time; // wait a bit longer //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible trap_EA_Attack( bs->client ); } else { bs->enemy = -1; } } } else { // int spotNum; // // TODO: cycle through visible enemy sniper spots // NOTE: remember last visible enemy positions, so we can stay on them longer than usual if ( bs->enemyposition_time > trap_AAS_Time() - 5.0 ) { VectorSubtract( bs->enemyorigin, bs->origin, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( bs->viewchangetime > level.time ) { // use same angles /* } else if ((spotNum = BotGetRandomVisibleSniperSpot( bs )) > -1) { // look at new spot VectorSubtract( g_entities[spotNum].s.origin, bs->origin, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // bs->viewchangetime = level.time + 1000 + rand()%1500; */ } else { // use mg42 angles VectorCopy( level.clients[bs->client].pmext.mountedWeaponAngles, bs->ideal_viewangles ); // add some random angle bs->ideal_viewangles[YAW] += crandom() * 20.f * 0.45; bs->ideal_viewangles[PITCH] += crandom() * 20.f * 0.15; // bs->viewchangetime = level.time + 1000 + rand() % 1500; } } // // stay mounted bs->flags &= ~BFL_DISMOUNT_MG42; return qtrue; } /* ================== AIEnter_MP_MG42Scan() ================== */ void AIEnter_MP_MG42Scan( bot_state_t *bs ) { //level.clients[0].sess.spectatorClient = bs->client; bs->arrive_time = level.time; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->lasthealth = g_entities[bs->client].health; bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_MG42Scan; bs->ainodeText = "AINode_MP_MG42Scan"; } /* ================== AINode_MP_MG42Scan() ================== */ int AINode_MP_MG42Scan( bot_state_t *bs ) { bot_goal_t goal; vec3_t dir, ang; gentity_t *ent, *mg42; // // set the dismount flag. clear it if we want to stay on bs->flags |= BFL_DISMOUNT_MG42; // goal = bs->target_goal; ent = BotGetEntity( bs->target_goal.entitynum ); mg42 = ent->melee; // ent->botIgnoreTime = 0; // set this now, only reset it to ignore if we want to ignore it // // if it's the wrong one if ( VectorDistanceSquared( bs->origin, ent->r.currentOrigin ) > SQR( 64 ) ) { trap_EA_Activate( bs->client ); return qfalse; } // return to this sniper spot if we go off temporarily ent->botIgnoreTime = 0; // if our health has dropped, abort if ( bs->lasthealth > g_entities[bs->client].health + 40 ) { ent->botIgnoreTime = level.time + 5000; bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // if we are not mounted on an mg42 if ( !( g_entities[bs->client].s.eFlags & EF_MG42_ACTIVE ) ) { bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { // return to this sniper spot after we're done ent->botIgnoreTime = 0; return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { // return to this sniper spot after we're done ent->botIgnoreTime = 0; // AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } /* // check for special class actions if (BotCheckClassActions(bs)) { // return to this sniper spot after we're done ent->missionLevel = 0; return qfalse; } */ // look for something better to do if ( BotFlagAtBase( bs->sess.sessionTeam, NULL ) == qfalse ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // have we been waiting here for too long? if ( bs->arrive_time < level.time - 40000 ) { ent->missionLevel = level.time; // other bots should avoid this spot ent->botIgnoreTime = level.time + 20000; // we should ignore it for a while now if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // if this spot is disabled now if ( mg42->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // // other bots should avoid this spot if ( ent->botIgnoreTime < level.time + 5000 ) { ent->botIgnoreTime = level.time + 5000; } // // look for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; bs->enemyposition_time = 0; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { VectorSubtract( entinfo.origin, mg42->r.currentOrigin, dir ); VectorNormalize( dir ); vectoangles( dir, ang ); if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 120, bs->enemy, NULL ) ) { if ( ( fabs( AngleDifference( ang[PITCH], mg42->s.angles[PITCH] ) ) >= mg42->varc ) || ( fabs( AngleDifference( ang[YAW], mg42->s.angles[YAW] ) ) >= mg42->harc ) ) { ent->botIgnoreTime = level.time + 5000; AIEnter_MP_Battle_Fight( bs ); return qfalse; } // if they are real close, abort mg42 mode if ( VectorDistanceSquared( bs->origin, g_entities[bs->enemy].r.currentOrigin ) < SQR( 512 ) ) { ent->botIgnoreTime = level.time + 5000; AIEnter_MP_Battle_Fight( bs ); return qfalse; } // bs->arrive_time = level.time; // wait a bit longer //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible trap_EA_Attack( bs->client ); } else { bs->enemy = -1; } } } else { // int spotNum; // // TODO: cycle through visible enemy sniper spots // NOTE: remember last visible enemy positions, so we can stay on them longer than usual if ( bs->enemyposition_time > trap_AAS_Time() - 5.0 ) { VectorSubtract( bs->enemyorigin, bs->origin, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( bs->viewchangetime > level.time ) { // use same angles /* } else if ((spotNum = BotGetRandomVisibleSniperSpot( bs )) > -1) { // look at new spot VectorSubtract( g_entities[spotNum].s.origin, bs->origin, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // bs->viewchangetime = level.time + 1000 + rand()%1500; */ } else { vec3_t start, end; trace_t tr; // use mg42 angles VectorCopy( mg42->s.angles, bs->ideal_viewangles ); // add some random angle bs->ideal_viewangles[YAW] += crandom() * mg42->harc * 0.45; bs->ideal_viewangles[PITCH] += crandom() * mg42->varc * 0.15; // // trace out to get the ground AngleVectors( bs->ideal_viewangles, dir, NULL, NULL ); VectorMA( mg42->r.currentOrigin, 48, dir, start ); VectorMA( start, 4096, dir, end ); trap_Trace( &tr, start, NULL, NULL, end, bs->client, MASK_SHOT ); if ( tr.fraction > 0.2 ) { VectorCopy( tr.endpos, start ); VectorCopy( tr.endpos, end ); end[2] -= 1024 * tr.fraction; trap_Trace( &tr, start, NULL, NULL, end, bs->client, MASK_SHOT ); VectorSubtract( tr.endpos, bs->eye, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); } // bs->viewchangetime = level.time + 1000 + rand() % 1500; } } // // stay mounted bs->flags &= ~BFL_DISMOUNT_MG42; // return qtrue; } /* ================== AIEnter_MP_MG42Mount() ================== */ void AIEnter_MP_MG42Mount( bot_state_t *bs ) { //level.clients[0].sess.spectatorClient = bs->client; bs->arrive_time = level.time; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_MG42Mount; bs->ainodeText = "AINode_MP_MG42Mount"; } /* ================== AINode_MP_MG42Mount() ================== */ int AINode_MP_MG42Mount( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *ent; trace_t tr; goal = bs->target_goal; ent = BotGetEntity( bs->target_goal.entitynum ); // return to this sniper spot if we go off temporarily ent->botIgnoreTime = 0; // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // if we have mounted an mg42 if ( g_entities[bs->client].s.eFlags & EF_MG42_ACTIVE ) { // if it's the wrong one if ( VectorDistanceSquared( bs->origin, ent->r.currentOrigin ) > SQR( 64 ) ) { trap_EA_Activate( bs->client ); return qfalse; } AIEnter_MP_MG42Scan( bs ); return qfalse; } // if the mg42 is broken, or being used if ( ent->melee->health <= 0 || ( ent->melee->entstate != STATE_DEFAULT ) || ent->melee->active ) { bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { // AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } /* // check for special class actions if (BotCheckClassActions(bs)) { return qfalse; } */ // look for something better to do if ( BotFindSpecialGoals( bs ) ) { return qfalse; } // have we been waiting here for too long? if ( bs->arrive_time < level.time - 40000 ) { ent->botIgnoreTime = level.time + 15000; // other bots should avoid this spot if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // // other bots should avoid this spot ent->botIgnoreTime = level.time + 5000; // VectorSubtract( bs->origin, goal.origin, dir ); if ( fabs( dir[2] ) < 100 ) { dir[2] = 0; } // is the destination blocked? if ( VectorLengthSquared( dir ) < SQR( 64 ) ) { trap_Trace( &tr, ent->r.currentOrigin, NULL, NULL, ent->r.currentOrigin, bs->client, MASK_PLAYERSOLID ); if ( tr.startsolid || tr.allsolid ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } } if ( VectorLengthSquared( dir ) > SQR( 8 ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); // bs->arrive_time = level.time; // wait a bit longer //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); if ( BotFindSpecialGoals( bs ) ) { return qfalse; } // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); // fail bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { if ( VectorDistanceSquared( bs->origin, goal.origin ) > SQR( 32 ) ) { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; bs->enemyposition_time = 0; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { if ( VectorDistanceSquared( bs->origin, goal.origin ) > SQR( 128 ) || VectorDistanceSquared( bs->origin, g_entities[bs->enemy].r.currentOrigin ) > SQR( 256 ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { // go fight them AIEnter_MP_Battle_Fight( bs ); return qfalse; } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } } } // if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 64 ) ) { vec3_t forward, right, up, offset; // look at the gun AngleVectors( bs->viewangles, forward, right, up ); CalcMuzzlePointForActivate( &g_entities[bs->client], forward, right, up, offset ); VectorSubtract( ent->melee->r.currentOrigin, offset, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); if ( bs->arrive_time < level.time - 500 ) { // randomize the angles a bit to solve some times when a direct sight isn't "enough" if ( rand() % 4 == 0 ) { bs->ideal_viewangles[YAW] += crandom() * 10.0; bs->ideal_viewangles[PITCH] += crandom() * 10.0; } // if we have been waiting longer, move backwards slowly if ( bs->arrive_time < level.time - 2000 ) { VectorInverse( dir ); dir[2] = 0; VectorNormalize( dir ); trap_EA_Move( bs->client, dir, 40 ); } } // hit activate so we mount it if ( rand() % 2 ) { trap_EA_Activate( bs->client ); } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_ScanForLandmines() ================== */ void AIEnter_MP_ScanForLandmines( bot_state_t *bs ) { bs->arrive_time = level.time; bs->altenemy = 0; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_ScanForLandmines; bs->ainodeText = "AINode_MP_ScanForLandmines"; } #define DETECT_RADIUS 225 /* ================== AINode_MP_ScanForLandmines() ================== */ int AINode_MP_ScanForLandmines( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *ent; trace_t tr; goal = bs->target_goal; ent = &g_entities[bs->target_goal.entitynum]; if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); ent->missionLevel = level.time; return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); ent->missionLevel = level.time; return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); ent->missionLevel = level.time; return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { ent->missionLevel = level.time; return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &bs->target_goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes ent->missionLevel = level.time; return qfalse; } // is this spot disabled now? if ( ent->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { if ( BotFindSpecialGoals( bs ) ) { ent->missionLevel = level.time; return qfalse; } } // is the destination blocked? trap_Trace( &tr, ent->s.origin, NULL, NULL, ent->s.origin, bs->client, MASK_PLAYERSOLID ); if ( tr.startsolid || tr.allsolid ) { if ( BotFindSpecialGoals( bs ) ) { ent->missionLevel = level.time; return qfalse; } } VectorSubtract( bs->origin, goal.origin, dir ); if ( fabs( dir[2] ) < 16 ) { dir[2] = 0; } if ( VectorLengthSquared( dir ) > SQR( 32 ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); bs->arrive_time = level.time; // wait a bit longer //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); if ( BotFindSpecialGoals( bs ) ) { return qfalse; } // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); // fail bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_WAITING ) { //if waiting for something if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { if ( VectorDistanceSquared( bs->origin, goal.origin ) > SQR( 32 ) ) { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; bs->enemyposition_time = 0; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( VectorLengthSquared( moveresult.movedir ) ) { //FIXME: look at cluster portals? vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } } } if ( VectorLengthSquared( dir ) < SQR( 32 ) ) { // start zooming if we aren't already bs->weaponnum = WP_BINOCULARS; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->altenemy <= 0 ) { vec3_t target; if ( bs->target_goal.number >= 3 ) { BotChooseWeapon( bs ); BotDefaultNode( bs ); ent->missionLevel = level.time; return qfalse; } // we're going to modify the point we're looking at, based on the current counter number VectorCopy( ent->s.origin2, target ); // if our index is 0 or 2, we move it left switch ( bs->target_goal.number ) { case 0: target[1] += DETECT_RADIUS; break; case 1: target[0] += DETECT_RADIUS; break; case 2: target[0] -= DETECT_RADIUS; target[1] -= DETECT_RADIUS; break; } // look at the proper spot VectorSubtract( target, bs->eye, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); bs->altenemy = AngleNormalize360( RAD2DEG( 2 * tan( DETECT_RADIUS / VectorDistance( bs->eye, target ) ) ) ); // set the time of our next view update bs->viewchangetime = level.time + 100 + rand() % 150; // next target! bs->target_goal.number++; } else if ( bs->viewchangetime < level.time ) { // we're doing a sweep - on the 2nd pass we sweep the reverse direction of the other 2 passes // move viewangle by a bit switch ( bs->target_goal.number ) { case 2: bs->ideal_viewangles[1]--; break; default: bs->ideal_viewangles[1]++; break; } bs->altenemy--; // set the time of our next view update bs->viewchangetime = level.time + 100 + rand() % 150; } } return qtrue; } /* ================== AIEnter_MP_SniperSpot() ================== */ void AIEnter_MP_SniperSpot( bot_state_t *bs ) { bs->arrive_time = level.time; bs->enemyposition_time = 0; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_SniperSpot; bs->ainodeText = "AINode_MP_SniperSpot"; } /* ================== AINode_MP_SniperSpot() ================== */ int AINode_MP_SniperSpot( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *ent; trace_t tr; goal = bs->target_goal; ent = &g_entities[bs->target_goal.entitynum]; // return to this sniper spot if we go off temporarily ent->missionLevel = 0; bs->flags |= BFL_SNIPING; if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { ent->missionLevel = level.time; // other bots should avoid this spot AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { // return to this sniper spot after we're done ent->missionLevel = 0; return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { // return to this sniper spot after we're done ent->missionLevel = 0; // AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // look for something better to do if ( !BotFlagAtBase( bs->sess.sessionTeam, NULL ) ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // have we got enough ammo? if ( !BotCanSnipe( bs, qfalse ) ) { if ( !BotFindSpecialGoals( bs ) ) { BotDefaultNode( bs ); } return qfalse; } // is this spot disabled now? if ( ent->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // // other bots should avoid this spot ent->missionLevel = level.time; // is the destination blocked? trap_Trace( &tr, ent->s.origin, NULL, NULL, ent->s.origin, bs->client, MASK_PLAYERSOLID ); if ( tr.startsolid || tr.allsolid ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } VectorSubtract( bs->origin, goal.origin, dir ); if ( fabs( dir[2] ) < 100 ) { dir[2] = 0; } if ( VectorLengthSquared( dir ) > SQR( 32 ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); bs->arrive_time = level.time; // wait a bit longer //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); if ( BotFindSpecialGoals( bs ) ) { return qfalse; } // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); // fail bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_WAITING ) { //if waiting for something if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { if ( VectorDistanceSquared( bs->origin, goal.origin ) > SQR( 32 ) ) { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; bs->enemyposition_time = 0; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( VectorLengthSquared( moveresult.movedir ) ) { //FIXME: look at cluster portals? vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } } } if ( VectorLengthSquared( dir ) < SQR( 32 ) ) { // have we been waiting here for too long? if ( bs->arrive_time < level.time - 40000 ) { ent->missionLevel = level.time; // other bots should avoid this spot if ( !BotFindSpecialGoals( bs ) ) { BotDefaultNode( bs ); } return qfalse; } // Gordon: crouching spot if ( ent->spawnflags & 2 ) { trap_EA_Crouch( bs->client ); } // We are at the sniper spot, so start sniping bs->weaponnum = BotCanSnipe( bs, qfalse ); trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( EntityIsDead( &entinfo ) ) { bs->enemy = -1; } if ( bs->enemy >= 0 ) { if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 50, bs->enemy, NULL ) ) { // if they are real close, abort sniper mode if ( VectorDistanceSquared( bs->origin, g_entities[bs->enemy].r.currentOrigin ) < SQR( 512 ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } bs->arrive_time = level.time; // wait a bit longer // remember this position bs->enemyposition_time = trap_AAS_Time(); VectorCopy( BotGetOrigin( bs->enemy ), bs->enemyorigin ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon && BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 5, bs->enemy, NULL ) ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } else { int spotNum; if ( bs->arrive_time < level.time - 20000 ) { // if not suggesting sniper, suicide so we can change if ( !BG_IsScopedWeapon( BotSuggestWeapon( bs, bs->sess.sessionTeam ) ) ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } } // NOTE: remember last visible enemy positions, so we can stay on them longer than usual if ( bs->enemyposition_time > trap_AAS_Time() - 5.0 ) { VectorSubtract( bs->enemyorigin, bs->origin, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( bs->viewchangetime > level.time ) { // // use same angles // } else if ( !( rand() % ( 1 + BotGetNumVisibleSniperSpots( bs ) ) ) && ( spotNum = BotGetRandomVisibleSniperSpot( bs ) ) > -1 ) { // look at new spot VectorSubtract( g_entities[spotNum].s.origin, bs->origin, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // bs->viewchangetime = level.time + 1500 + rand() % 3000; } else if ( rand() % 2 && bs->enemyposition_time && ( bs->enemyposition_time > trap_AAS_Time() - 60.0 ) ) { // look at last enemy pos VectorSubtract( bs->enemyorigin, bs->origin, dir ); // if it's not too far away, use non-zoomed view if ( VectorNormalize( dir ) < 3000 ) { // switch to non-zoomed view if ( bs->weaponnum >= WP_BEGINSECONDARY && bs->weaponnum <= WP_LASTSECONDARY ) { bs->weaponnum = weapAlts[bs->weaponnum]; } trap_EA_SelectWeapon( bs->client, bs->weaponnum ); } vectoangles( dir, bs->ideal_viewangles ); bs->viewchangetime = level.time + 2000 + rand() % 2000; } else if ( !VectorCompare( ent->s.angles, vec3_origin ) ) { // just face direction of sniper spot // switch to non-zoomed view if ( bs->weaponnum >= WP_BEGINSECONDARY && bs->weaponnum <= WP_LASTSECONDARY ) { bs->weaponnum = weapAlts[bs->weaponnum]; } trap_EA_SelectWeapon( bs->client, bs->weaponnum ); VectorCopy( ent->s.angles, bs->ideal_viewangles ); // bs->viewchangetime = level.time + 2500 + rand() % 3000; } } } // reload? if ( ( level.time - bs->last_fire > 2000 ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } return qtrue; } /* ================== AIEnter_MP_DefendTarget() ================== */ void AIEnter_MP_DefendTarget( bot_state_t *bs ) { //VectorCopy( bs->origin, bs->aimtarget ); //choose the best weapon to fight with bs->arrive_time = 0; BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_DefendTarget; bs->ainodeText = "AINode_MP_DefendTarget"; } /* ================== AINode_MP_DefendTarget() ================== */ int AINode_MP_DefendTarget( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *ent, *flag; qboolean move; trace_t tr; goal = bs->target_goal; bs->defendgoal = bs->target_goal; if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } /* // check for special class actions if (BotCheckClassActions(bs)) { return qfalse; } */ // look for health/ammo packs if ( BotFindNearbyGoal( bs ) ) { AIEnter_MP_Seek_NBG( bs ); return qfalse; } if ( goal.entitynum < 0 ) { BotDefaultNode( bs ); return qfalse; } // look for better goals if ( BotFindSpecialGoals( bs ) ) { return qfalse; } // if we are defending a leader, and they are not valid anymore, then stop if ( goal.flags & GFL_LEADER ) { // make sure our leader is still valid if ( bs->leader > -1 ) { if ( !g_entities[bs->leader].inuse || !g_entities[bs->leader].client || ( g_entities[bs->leader].client->ps.pm_flags & PMF_LIMBO ) ) { bs->leader = -1; BotDefaultNode( bs ); return qfalse; } else if ( bs->sess.playerType == PC_MEDIC ) { if ( g_entities[bs->leader].health <= 0 && trap_AAS_PointAreaNum( g_entities[bs->leader].r.currentOrigin ) && BotGoalForEntity( bs, bs->leader, &bs->target_goal, BGU_MEDIUM ) ) { // revive g_entities[bs->target_goal.entitynum].missionLevel = level.time + 3000; AIEnter_MP_MedicRevive( bs ); return qfalse; } else if ( BotHealthScale( bs->leader ) <= 0.7 && trap_AAS_PointAreaNum( g_entities[bs->leader].r.currentOrigin ) && BotGoalForEntity( bs, bs->leader, &bs->target_goal, BGU_MEDIUM ) ) { // health stock? // make this our goal g_entities[bs->target_goal.entitynum].missionLevel = level.time + 3000; AIEnter_MP_MedicGiveHealth( bs ); return qfalse; } } else if ( ( VectorLengthSquared( g_entities[bs->leader].client->ps.velocity ) < SQR( 10 ) ) && ( VectorLengthSquared( bs->cur_ps.velocity ) < SQR( 10 ) ) ) { if ( !( g_entities[bs->leader].r.svFlags & SVF_BOT ) ) { BotVoiceChatAfterIdleTime( bs->client, "WhereTo", SAY_BUDDY, 1000 + rand() % 3000, BOT_SHOWTEXT, 12000, qfalse ); } } // if ( !g_entities[bs->leader].inuse || g_entities[bs->leader].health <= 0 || VectorDistanceSquared( g_entities[bs->leader].r.currentOrigin, bs->origin ) > SQR( MAX_BOTLEADER_DIST ) ) { bs->leader = -1; } } // if ( bs->leader == -1 ) { BotDefaultNode( bs ); return qfalse; } } // //if there is an enemy if ( BotFindEnemyMP( bs, -1, qfalse ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); // if we made it to the destination, let us roam to fight people if ( BotCarryingFlag( bs->enemy ) || ( !( goal.flags & GFL_LEADER ) && ( bs->flags & BFL_MISCFLAG ) ) ) { if ( !BotCarryingFlag( bs->enemy ) && VectorLengthSquared( bs->cur_ps.velocity ) && BotWantsToRetreat( bs ) ) { //keep the current long term goal and retreat } else { trap_BotResetLastAvoidReach( bs->ms ); //go fight AIEnter_MP_Battle_Fight( bs ); return qfalse; } } } // if the target has been cleared if ( goal.entitynum < 0 ) { BotDefaultNode( bs ); return qfalse; } // should we stop pursuing this target? ent = &g_entities[bs->target_goal.entitynum]; switch ( ent->s.eType ) { case ET_TRIGGER_FLAGONLY: if ( BotFlagAtBase( bs->sess.sessionTeam, &flag ) == qtrue ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } break; case ET_TRIGGER_FLAGONLY_MULTIPLE: if ( !BotEnemyCarryingFlag( bs->client ) ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } break; case ET_ITEM: if ( !Q_stricmp( ent->classname, "team_CTF_redflag" ) && !( ent->flags & FL_DROPPED_ITEM ) ) { if ( bs->sess.sessionTeam != TEAM_AXIS ) { // this is the enemy flag, so abort "defending" it when it shows up if ( BotFlagAtBase( TEAM_AXIS, NULL ) == qtrue ) { BotDefaultNode( bs ); return qfalse; } else if ( BotCarryingFlag( bs->client ) ) { // we have it! BotDefaultNode( bs ); return qfalse; } } } else if ( !Q_stricmp( ent->classname, "team_CTF_blueflag" ) && !( ent->flags & FL_DROPPED_ITEM ) ) { if ( bs->sess.sessionTeam != TEAM_ALLIES ) { // this is the enemy flag, so abort "defending" it when it shows up if ( BotFlagAtBase( TEAM_ALLIES, NULL ) == qtrue ) { BotDefaultNode( bs ); return qfalse; } else if ( BotCarryingFlag( bs->client ) ) { // we have it! BotDefaultNode( bs ); return qfalse; } } } else if ( ent->touch ) { if ( ent->r.svFlags & SVF_NOCLIENT ) { BotDefaultNode( bs ); return qfalse; } } break; case ET_TRAP: if ( !Q_stricmp( ent->classname, "team_WOLF_checkpoint" ) ) { if ( ent->count == ( bs->sess.sessionTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS ) ) { // the enemy is controlling this checkpoint now BotDefaultNode( bs ); return qfalse; } } break; case ET_TRIGGER_MULTIPLE: // if we are within range, stop here if ( bs->arrive_time < level.time - 5000 ) { if ( ( VectorDistanceSquared( bs->origin, BotGetOrigin( ent->s.number ) ) < SQR( 600 ) ) && trap_InPVS( bs->origin, BotGetOrigin( ent->s.number ) ) ) { // check the trace trap_Trace( &tr, bs->eye, vec3_origin, vec3_origin, BotGetOrigin( ent->s.number ), -1, (MASK_SHOT) &~( CONTENTS_BODY | CONTENTS_CORPSE ) ); if ( tr.entityNum != ENTITYNUM_WORLD ) { VectorCopy( bs->origin, bs->target_goal.origin ); goal = bs->target_goal; bs->arrive_time = level.time; } } } break; case ET_PLAYER: if ( ent->client && ent->health <= 0 ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } break; case ET_ATTRACTOR_HINT: default: // rain break; } // if we are defending a player, and they have moved, get a new sparse defend area if ( ent->client && ( bs->target_goal.number < level.time - 300 ) && !VectorCompare( ent->r.currentOrigin, bs->defendgoal_origin ) ) { int list[MAX_CLIENTS], numList; float ourDist, *distances; // // if there are too many defenders, and we are the furthest away, stop defending if ( BotCarryingFlag( bs->target_goal.entitynum ) ) { if ( ( numList = BotNumTeamMatesWithTarget( bs, goal.entitynum, list, MAX_CLIENTS ) ) > BOT_FLAG_CARRIER_DEFENDERS ) { ourDist = VectorDistanceSquared( bs->origin, g_entities[goal.entitynum].r.currentOrigin ); if ( !trap_InPVS( bs->origin, g_entities[goal.entitynum].r.currentOrigin ) ) { ourDist += 2048 * 2048; } distances = BotSortPlayersByDistance( g_entities[goal.entitynum].r.currentOrigin, list, numList ); if ( distances[numList - 1] < ourDist ) { // we are the furthest bs->ignore_specialgoal_time = 0; bs->leader = -1; BotDefaultNode( bs ); return qfalse; } } } // look for a new defend pos VectorCopy( ent->r.currentOrigin, bs->target_goal.origin ); bs->target_goal.areanum = BotPointAreaNum( ent->s.number, ent->r.currentOrigin ); // BotFindSparseDefendArea( bs, &bs->target_goal, qtrue ); VectorCopy( ent->r.currentOrigin, bs->defendgoal_origin ); bs->target_goal.number = level.time + rand() % 100; goal = bs->target_goal; bs->defendgoal = bs->target_goal; } // // remember the last position we couldnt see the DESTINATION from, so we can look there once we arrive if ( !trap_InPVS( bs->origin, goal.origin ) ) { VectorCopy( bs->origin, bs->aimtarget ); } // // do we need to get closer to the goal? // move = qfalse; if ( !( bs->target_goal.flags & GFL_DEFEND_CLOSE ) ) { if ( !move && VectorDistanceSquared( bs->origin, goal.origin ) > SQR( 384 ) ) { move = qtrue; } if ( !move && trap_InPVS( bs->origin, goal.origin ) ) { trace_t tr; trap_Trace( &tr, bs->origin, NULL, NULL, goal.origin, -1, MASK_SHOT & ~( CONTENTS_BODY | CONTENTS_CORPSE ) ); if ( tr.startsolid || tr.allsolid || tr.fraction < 1.0 ) { move = qtrue; } } } else { if ( !move && VectorDistanceSquared( bs->origin, goal.origin ) > ( ( goal.flags & GFL_LEADER ) ? SQR( 80 ) : SQR( 32 ) ) ) { move = qtrue; } } if ( move ) { //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { if ( goal.flags & GFL_LEADER ) { bs->leader = -1; } //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? //trap_EA_Jump(bs->client); //trap_EA_Move(bs->client, tv(crandom(), crandom(), crandom()), 100+random()*200 ); // fail bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } if ( bs->blockentTime > level.time - 500 && bs->blockent < level.maxclients ) { // if we are within range, then stop here if ( goal.flags & GFL_LEADER ) { if ( ( BotPointWithinMovementAutonomy( bs, &goal, bs->origin ) ) && ( VectorDistanceSquared( bs->origin, g_entities[bs->leader].r.currentOrigin ) < SQR( 512 ) ) ) { VectorCopy( bs->origin, bs->target_goal.origin ); bs->target_goal.areanum = bs->areanum; } } } BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_WAITING ) { //if waiting for something if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { // under special circumstances, we should go into battle mode if ( !BotCarryingFlag( bs->target_goal.entitynum ) && ( ( bs->weaponnum == WP_LUGER ) || ( bs->weaponnum == WP_COLT ) || ( bs->weaponnum == WP_MOBILE_MG42 ) ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } else { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } } else { bs->enemy = -1; } } } if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( VectorLengthSquared( moveresult.movedir ) ) { //FIXME: look at cluster portals? vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; // check for giving ourselves some ammo if ( bs->sess.playerType == PC_FIELDOPS && ClientNeedsAmmo( bs->client ) ) { // switch to regen and pump away bs->weaponnum = WP_AMMO; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_AMMO && BotWeaponCharged( bs, WP_AMMO ) ) { trap_EA_Attack( bs->client ); } } // check for giving ourselves some health if ( bs->sess.playerType == PC_MEDIC && BotHealthScale( bs->client ) < 1.0 ) { // switch to regen and pump away bs->weaponnum = WP_MEDKIT; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_MEDKIT && BotWeaponCharged( bs, WP_MEDKIT ) ) { trap_EA_Attack( bs->client ); } } } } } else { gentity_t *objtarg; // NOTE: dont bother looking for enemies, since we have reached the destination, so we are free to // pursue enemies now // // call for an engineer (if required) if ( ( ent->s.eType == ET_OID_TRIGGER ) && ( objtarg = ent->target_ent ) ) { if ( objtarg->spawnflags & 64 ) { if ( ent->lastHintCheckTime < level.time && rand() % 2 ) { // if there is no dynamite planted here int list[10], numList, i; // numList = BotGetTargetExplosives( bs->sess.sessionTeam, list, 10, qfalse ); for ( i = 0; i < numList; i++ ) { if ( list[i] == ent->s.number ) { break; } } // if this objective doesn ont have armed dynamite if ( numList && i < numList ) { BotVoiceChatAfterIdleTime( bs->client, "NeedEngineer", SAY_TEAM, 500 + rand() % 4000, qfalse, 5000 + rand() % 5000, qfalse ); } } // if we are an engineer, throw out an air-strike if ( bs->sess.playerType == PC_FIELDOPS && ( level.time - bs->cur_ps.classWeaponTime > ( level.lieutenantChargeTime[bs->sess.sessionTeam - 1] * 0.5f ) ) ) { // select smoke grenade bs->weaponnum = WP_SMOKE_MARKER; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // look upwards bs->ideal_viewangles[PITCH] = -70; if ( bs->cur_ps.weapon == bs->weaponnum && bs->viewangles[PITCH] < -60 ) { trap_EA_Attack( bs->client ); } return qtrue; } } } // set flag so we know that we made it to the destination bs->flags |= BFL_MISCFLAG; // // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } else { if ( bs->viewchangetime < level.time ) { // look for a better pos if ( !bs->arrive_time && random() < 0.1 ) { if ( bs->target_goal.entitynum ) { BotFindSparseDefendArea( bs, &bs->target_goal, qfalse ); } } if ( ++bs->viewtype > 1 ) { bs->viewtype = 0; } bs->viewchangetime = level.time + 500 + rand() % 3000; } // if guarding a carrier, look towards the flag goal if ( goal.entitynum > -1 && goal.entitynum < level.maxclients && BotCarryingFlag( goal.entitynum ) ) { bot_goal_t fgoal; gentity_t *flaggoal; qboolean setdir = qfalse; // flaggoal = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY ); if ( !flaggoal ) { flaggoal = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY_MULTIPLE ); } if ( flaggoal ) { if ( BotGoalForEntity( NULL, flaggoal->s.number, &fgoal, BGU_HIGH ) ) { if ( trap_BotMovementViewTarget( bs->ms, &fgoal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); setdir = qtrue; } } } if ( !setdir ) { // look away from the defense object VectorAdd( g_entities[bs->target_goal.entitynum].r.absmax, g_entities[bs->target_goal.entitynum].r.absmin, target ); VectorScale( target, 0.5, target ); VectorSubtract( target, bs->origin, dir ); VectorNormalize( dir ); VectorInverse( dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[PITCH] = 0; } } else if ( bs->viewtype == 0 ) { // face the current aimtarget VectorSubtract( bs->aimtarget, bs->origin, dir ); if ( VectorNormalize( dir ) ) { if ( fabs( dir[2] ) < 0.8 ) { vectoangles( dir, bs->ideal_viewangles ); } bs->ideal_viewangles[PITCH] = 0; } } else if ( bs->target_goal.entitynum > 0 ) { // look at the defense object VectorAdd( g_entities[bs->target_goal.entitynum].r.absmax, g_entities[bs->target_goal.entitynum].r.absmin, target ); VectorScale( target, 0.5, target ); VectorSubtract( target, bs->origin, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[PITCH] = 0; } } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } return qtrue; } /* ================== AIEnter_MP_TouchTarget() ================== */ void AIEnter_MP_TouchTarget( bot_state_t *bs ) { //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_TouchTarget; bs->ainodeText = "AINode_MP_TouchTarget"; } /* ================== AINode_MP_TouchTarget() ================== */ int AINode_MP_TouchTarget( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *ent; qboolean altroute = qfalse; vec3_t mins, maxs; goal = bs->target_goal; if ( bs->alt_goal.number && bs->alt_goal.entitynum == goal.entitynum && bs->alt_goal.number == goal.number ) { if ( ( bs->alt_goal.number < level.time - 12000 ) || ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, bs->target_goal.areanum, bs->tfl ) < 700 ) ) { // stop pursuing altgoal after some time BotClearGoal( &bs->alt_goal ); bs->target_goal.number = 0; goal = bs->target_goal; } else { goal = bs->alt_goal; altroute = qtrue; } } if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } /* // check for special class actions if (BotCheckClassActions(bs)) { return qfalse; } */ // look for health/ammo packs if ( BotFindNearbyGoal( bs ) ) { AIEnter_MP_Seek_NBG( bs ); return qfalse; } // // should we stop pursuing this target? ent = &g_entities[bs->target_goal.entitynum]; if ( ent->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { if ( !BotFindSpecialGoals( bs ) ) { BotDefaultNode( bs ); } return qfalse; } if ( BotFindSpecialGoals( bs ) ) { return qfalse; } if ( ent->s.eType == ET_TRAP && !Q_stricmp( ent->classname, "team_WOLF_checkpoint" ) ) { if ( ent->count == bs->sess.sessionTeam ) { // we have captured it bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } } else if ( ent->s.eType == ET_ITEM && ent->touch ) { if ( ent->r.svFlags & SVF_NOCLIENT ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } } else { if ( ent->s.eType == ET_TRIGGER_MULTIPLE ) { // if ( !ent->r.linked || ent->nextthink > level.time + 1000 ) { BotDefaultNode( bs ); return qfalse; } // if we are currently touching the target, then use this as our spot if ( bs->arrive_time + 3000 < level.time ) { VectorAdd( bs->origin, bs->cur_ps.mins, mins ); VectorAdd( bs->origin, bs->cur_ps.maxs, maxs ); if ( trap_EntityContactCapsule( mins, maxs, ent ) ) { VectorCopy( bs->origin, goal.origin ); bs->arrive_time = level.time; } } // if the current destination is no longer touching the brush, get a new position VectorAdd( goal.origin, bs->cur_ps.mins, mins ); VectorAdd( goal.origin, bs->cur_ps.maxs, maxs ); if ( !trap_EntityContactCapsule( mins, maxs, ent ) || ( rand() % 50 == 0 ) ) { // need a new position if ( !BotGetReachableEntityArea( bs, ent->s.number, &goal ) ) { BotDefaultNode( bs ); return qfalse; } // check this position VectorAdd( goal.origin, bs->cur_ps.mins, mins ); VectorAdd( goal.origin, bs->cur_ps.maxs, maxs ); if ( !trap_EntityContactCapsule( mins, maxs, ent ) ) { BotDefaultNode( bs ); return qfalse; } // this is the new goal bs->target_goal = goal; } } if ( !Q_stricmp( ent->classname, "trigger_flagonly" ) ) { // if we dont have the flag anymore, then stop if ( !BotCarryingFlag( bs->client ) ) { BotDefaultNode( bs ); return qfalse; } } } // VectorCopy( goal.origin, target ); if ( fabs( target[2] - bs->origin[2] ) < 80 ) { target[2] = bs->origin[2]; } if ( altroute && VectorDistanceSquared( goal.origin, bs->origin ) < SQR( 80 ) ) { // made it to the altroute BotClearGoal( &bs->alt_goal ); bs->target_goal.number = 0; goal = bs->target_goal; } // // if we have an enemy, then we should look for an alternate route away from them if ( ( BotCarryingFlag( bs->client ) ) && ( goal.number < level.time - 8000 ) && ( BotNumTeamMatesWithTarget( bs, bs->client, NULL, -1 ) < 2 ) && ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, bs->target_goal.areanum, bs->tfl ) > 1500 ) ) { if ( bs->enemy > -1 ) { aas_altroutegoal_t altroutegoals[40]; int numList, i; bot_goal_t tempgoal; vec3_t edir; // // get the vector towards the enemy VectorSubtract( g_entities[bs->enemy].r.currentOrigin, bs->origin, edir ); VectorNormalize( edir ); // if we are running towards them if ( DotProduct( edir, bs->cur_ps.velocity ) > 0 ) { // dont do this check again for a while bs->alt_goal.number = level.time; bs->target_goal.number = level.time; //initialize the movement state BotSetupForMovement( bs ); // check for an alternate route if ( ( numList = trap_AAS_AlternativeRouteGoals( bs->origin, bs->target_goal.origin, bs->tfl, altroutegoals, 40, 0 ) ) ) { for ( i = 0; i < numList; i++ ) { BotClearGoal( &tempgoal ); tempgoal.areanum = altroutegoals[i].areanum; VectorCopy( altroutegoals[i].origin, tempgoal.origin ); if ( qtrue ) { //trap_BotMovementViewTarget(bs->ms, &goal, bs->tfl, 300, target)) { //VectorSubtract(target, bs->origin, dir); VectorSubtract( tempgoal.origin, bs->origin, dir ); VectorNormalize( dir ); if ( DotProduct( dir, edir ) < 0 ) { // moving away from the enemy //make this the altroutegoal bs->alt_goal = bs->target_goal; trap_AAS_AreaWaypoint( altroutegoals[i].areanum, bs->alt_goal.origin ); bs->alt_goal.areanum = trap_AAS_PointAreaNum( bs->alt_goal.origin ); break; } } } } } } else if ( bs->enemy < 0 ) { int list[MAX_CLIENTS], numList; int i, t; bot_state_t *tbs; // if we have defenders, stop every now and then to let them get infront of us if ( ( bs->stand_time < level.time - 3000 ) && ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, bs->target_goal.areanum, bs->tfl ) > 600 ) && ( numList = BotNumTeamMatesWithTarget( bs, bs->client, list, MAX_CLIENTS ) ) ) { // if one of them has a goal infront of us, and they are not near it, we should pause for a bit for ( i = 0; i < numList; i++ ) { tbs = &botstates[list[i]]; // if ( ( VectorDistanceSquared( tbs->origin, tbs->defendgoal.origin ) < SQR( 1500 ) ) && ( VectorDistanceSquared( tbs->origin, bs->origin ) < SQR( 1024 ) ) && ( trap_InPVS( tbs->origin, bs->origin ) ) && ( trap_AAS_AreaTravelTimeToGoalArea( tbs->defendgoal.areanum, tbs->defendgoal.origin, goal.areanum, bs->tfl ) < trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, bs->target_goal.areanum, bs->tfl ) ) && ( trap_AAS_AreaTravelTimeToGoalArea( tbs->areanum, tbs->origin, goal.areanum, bs->tfl ) - trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, goal.areanum, bs->tfl ) ) ) { t = trap_AAS_AreaTravelTimeToGoalArea( tbs->areanum, tbs->origin, tbs->defendgoal.areanum, bs->tfl ); if ( t > 300 ) { t = 300; } if ( t > 100 ) { bs->stand_time = level.time + 1000 + 5 * t; } } } } } } //choose the best weapon to fight with BotChooseWeapon( bs ); // //initialize the movement state BotSetupForMovement( bs ); // if ( bs->stand_time < level.time ) { qboolean move = qtrue; //move towards the goal if ( ent->s.eType == ET_TRAP && !Q_stricmp( ent->classname, "team_WOLF_checkpoint" ) && ( VectorDistanceSquared( goal.origin, bs->origin ) < SQR( 128 ) ) ) { // move straight torward it VectorAdd( ent->r.absmin, ent->r.absmax, target ); VectorScale( target, 0.5, target ); VectorSubtract( target, bs->origin, dir ); dir[2] = 0; VectorNormalize( dir ); trap_EA_Move( bs->client, dir, 300 ); // randomly jump if ( rand() % 10 == 0 ) { trap_EA_Jump( bs->client ); } move = qfalse; } else if ( ent->s.eType == ET_TRIGGER_MULTIPLE ) { int i; // if we are touching the brush, we dont need to move VectorAdd( bs->origin, bs->cur_ps.mins, mins ); VectorAdd( bs->origin, bs->cur_ps.maxs, maxs ); // make them a bit smaller to be safe for ( i = 0; i < 3; i++ ) { mins[i] += 2; maxs[i] -= 2; } if ( trap_EntityContactCapsule( mins, maxs, ent ) ) { move = qfalse; } } if ( move ) { //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); // fail bs->ainode = NULL; bs->ainodeText = "NULL"; return qtrue; } // BotAIBlocked( bs, &moveresult, qtrue ); } } //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { /* // if we are not going for an urgent goal, go into battle mode if (!BotCarryingFlag(bs->client) && bs->ignore_specialgoal_time < level.time && BotWantsToChase(bs) && (VectorDistanceSquared( goal.origin, bs->origin ) > SQR(384)) && (VectorDistanceSquared( bs->enemyorigin, bs->origin ) < SQR(2048)) && Q_stricmp(g_entities[goal.entitynum].classname, "team_CTF_redflag") && Q_stricmp(g_entities[goal.entitynum].classname, "team_CTF_blueflag")) { AIEnter_MP_Battle_Fight(bs); return qfalse; } */ //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( ent->s.eType == ET_TRIGGER_MULTIPLE && trap_InPVS( bs->origin, goal.origin ) && Distance( bs->origin, goal.origin ) < 512 ) { VectorSubtract( ent->r.currentOrigin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; // check for giving ourselves some ammo if ( bs->sess.playerType == PC_FIELDOPS && ClientNeedsAmmo( bs->client ) ) { // switch to regen and pump away bs->weaponnum = WP_AMMO; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_AMMO && BotWeaponCharged( bs, WP_AMMO ) ) { trap_EA_Attack( bs->client ); } } // check for giving ourselves some health if ( bs->sess.playerType == PC_MEDIC && BotHealthScale( bs->client ) < 1.0 ) { // switch to regen and pump away bs->weaponnum = WP_MEDKIT; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_MEDKIT && BotWeaponCharged( bs, WP_MEDKIT ) ) { trap_EA_Attack( bs->client ); } } } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } return qtrue; } /* ================== AIEnter_MP_SatchelChargeTarget ================== */ void AIEnter_MP_SatchelChargeTarget( bot_state_t *bs ) { bs->target_goal.flags &= ~GFL_NOSLOWAPPROACH; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_SatchelChargeTarget; bs->ainodeText = "AINode_MP_SatchelChargeTarget"; } /* ================== AINode_MP_SatchelChargeTarget ================== */ int AINode_MP_SatchelChargeTarget( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav; int list[10], numList, i; float goalDist; aas_entityinfo_t entinfo; goal = bs->target_goal; //if we have changed class if ( bs->sess.playerType != PC_COVERTOPS ) { BotDefaultNode( bs ); return qfalse; } if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } //if there are 2 bots going for this goal, then we should abort if we are further away goalDist = VectorDistanceSquared( bs->origin, goal.origin ); if ( ( numList = BotNumTeamMatesWithTargetByClass( bs, goal.entitynum, list, 10, PC_ENGINEER ) ) ) { if ( goalDist > SQR( 256 ) ) { goalDist = SQR( 256 ); // only abort if one of our teammates is close to the goal } for ( i = 0; i < numList; i++ ) { if ( botstates[list[i]].ainode == AINode_MP_SatchelChargeTarget ) { if ( VectorDistanceSquared( botstates[list[i]].origin, goal.origin ) < goalDist ) { // make sure other bots dont head for this target also g_entities[goal.entitynum].lastHintCheckTime = level.time + 5000; BotDefaultNode( bs ); return qfalse; } } } } VectorSubtract( bs->origin, goal.origin, dir ); if ( fabs( dir[2] ) < 128 ) { dir[2] = 0; } goalDist = VectorLengthSquared( dir ); // are we close enough to the goal? if ( goalDist < SQR( 32 ) ) { // have we recently dropped some dynamite? for ( trav = G_FindSatchels( NULL ); trav; trav = G_FindSatchels( trav ) ) { if ( !trav->parent || trav->parent->s.number != bs->client ) { continue; } if ( VectorDistanceSquared( bs->origin, trav->r.currentOrigin ) > SQR( 64 ) ) { continue; } // found some! bs->flags |= BFL_MISCFLAG; VectorCopy( trav->r.currentOrigin, bs->target_goal.origin ); bs->target_goal.origin[2] += 24; break; } if ( !trav ) { // no dynamite found, keep trying to plant some if ( bs->flags & BFL_MISCFLAG ) { // it's gone, so reset goal BotDefaultNode( bs ); return qfalse; } if ( BotWeaponCharged( bs, WP_SATCHEL ) ) { // VOICE: cover me! BotVoiceChatAfterIdleTime( bs->client, "CoverMe", SAY_TEAM, 500 + rand() % 1000, qfalse, 10000, qfalse ); // make sure other bots dont head for this target also g_entities[bs->target_goal.entitynum].lastHintCheckTime = level.time + 2000; // crouch down trap_EA_Crouch( bs->client ); // look downwards bs->ideal_viewangles[PITCH] = 70; // select the dynamite bs->weaponnum = WP_SATCHEL; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // hold fire if ( !VectorLengthSquared( bs->velocity ) && fabs( bs->viewangles[PITCH] - bs->ideal_viewangles[PITCH] ) < 2 && bs->cur_ps.weapon == WP_SATCHEL && !bs->cur_ps.grenadeTimeLeft ) { trap_EA_Attack( bs->client ); } return qtrue; } } else if ( ( trav = G_FindSatchel( &g_entities[bs->client] ) ) ) { /* // check for emergency targets (flags, etc) if (BotCheckEmergencyTargets( bs )) { return qfalse; } // check for dangerous elements if (BotDangerousGoal(bs, &goal)) { AIEnter_MP_AvoidDanger(bs); // avoid this danger until it passes return qfalse; } // just look for a goal BotDefaultNode(bs); return qfalse;*/ } } if ( !( bs->flags & BFL_MISCFLAG ) ) { if ( goalDist > SQR( 128 ) ) { // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } //choose the best weapon to fight with BotChooseWeapon( bs ); // are we close enough to the goal? if ( goalDist >= SQR( 32 ) ) { // MOVEMENT REQUIRED // //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } } // return qtrue; } /* ================== AIEnter_MP_DynamiteTarget() ================== */ void AIEnter_MP_DynamiteTarget( bot_state_t *bs ) { bs->toggleHidingTime = level.time; bs->target_goal.flags &= ~GFL_NOSLOWAPPROACH; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_DynamiteTarget; bs->ainodeText = "AINode_MP_DynamiteTarget"; } /* ================== AINode_MP_DynamiteTarget() ================== */ int AINode_MP_DynamiteTarget( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav; int list[10], numList, i; float goalDist; aas_entityinfo_t entinfo; goal = bs->target_goal; //if we have changed class if ( bs->sess.playerType != PC_ENGINEER ) { BotDefaultNode( bs ); return qfalse; } // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } //if there are 2 bots going for this goal, then we should abort if we are further away goalDist = VectorDistanceSquared( bs->origin, goal.origin ); if ( ( numList = BotNumTeamMatesWithTargetByClass( bs, goal.entitynum, list, 10, PC_ENGINEER ) ) ) { if ( goalDist > SQR( 256 ) ) { goalDist = SQR( 256 ); // only abort if one of our teammates is close to the goal } for ( i = 0; i < numList; i++ ) { if ( list[i] == bs->client ) { continue; } if ( botstates[list[i]].ainode == AINode_MP_DynamiteTarget ) { if ( VectorDistanceSquared( botstates[list[i]].origin, goal.origin ) < goalDist ) { // make sure other bots dont head for this target also g_entities[goal.entitynum].lastHintCheckTime = level.time + 5000; BotDefaultNode( bs ); return qfalse; } } } } // //map specific code BotMapScripts( bs ); // VectorSubtract( bs->origin, goal.origin, dir ); if ( fabs( dir[2] ) < 128 ) { dir[2] = 0; } goalDist = VectorLengthSquared( dir ); // are we close enough to the goal? if ( goalDist < SQR( 32 ) ) { // have we recently dropped some dynamite? for ( trav = G_FindDynamite( NULL ); trav; trav = G_FindDynamite( trav ) ) { if ( !trav->parent || trav->parent->s.number != bs->client ) { continue; } if ( VectorDistanceSquared( bs->origin, trav->r.currentOrigin ) > SQR( 100 ) ) { continue; } if ( trav->spawnTime < bs->toggleHidingTime ) { // armed before we started this node continue; } // found some! bs->flags |= BFL_MISCFLAG; VectorCopy( trav->r.currentOrigin, bs->target_goal.origin ); bs->target_goal.origin[2] += 24; break; } if ( !trav ) { // no dynamite found, keep trying to plant some if ( bs->flags & BFL_MISCFLAG ) { // it's gone, so reset goal BotDefaultNode( bs ); return qfalse; } if ( BotWeaponCharged( bs, WP_DYNAMITE ) ) { // VOICE: cover me! BotVoiceChatAfterIdleTime( bs->client, "CoverMe", SAY_TEAM, 500 + rand() % 1000, qfalse, 10000, qfalse ); // make sure other bots dont head for this target also g_entities[bs->target_goal.entitynum].lastHintCheckTime = level.time + 2000; // crouch down trap_EA_Crouch( bs->client ); // look downwards bs->ideal_viewangles[PITCH] = 70; // select the dynamite bs->weaponnum = WP_DYNAMITE; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // hold fire if ( rand() % 2 && !VectorLengthSquared( bs->velocity ) && fabs( bs->viewangles[PITCH] - bs->ideal_viewangles[PITCH] ) < 2 && bs->cur_ps.weapon == WP_DYNAMITE && !bs->cur_ps.grenadeTimeLeft ) { trap_EA_Attack( bs->client ); } return qtrue; } } else if ( trav->s.teamNum >= 4 ) { // the dynamite is not armed // switch to pliers and arm the dynamite bs->weaponnum = WP_PLIERS; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // aim directly at the dynamite VectorCopy( bs->origin, target ); target[2] += bs->cur_ps.viewheight; VectorSubtract( trav->r.currentOrigin, target, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // hold fire if ( bs->cur_ps.weapon == WP_PLIERS ) { trap_EA_Attack( bs->client ); } return qtrue; } else { // the dynamite is armed, get out of here! // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // just look for a goal BotDefaultNode( bs ); // if we are still in dynamite mode, then we may be trying to plant more dynamite at same place bs->toggleHidingTime = level.time; return qfalse; } } // if ( !( bs->flags & BFL_MISCFLAG ) ) { if ( goalDist > SQR( 128 ) ) { // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // //choose the best weapon to fight with BotChooseWeapon( bs ); // // are we close enough to the goal? if ( goalDist >= SQR( 32 ) ) { // MOVEMENT REQUIRED // //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } } // return qtrue; } /* ================== AIEnter_MP_ConstructibleTarget() ================== */ void AIEnter_MP_ConstructibleTarget( bot_state_t *bs ) { bs->target_goal.flags &= ~GFL_NOSLOWAPPROACH; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_ConstructibleTarget; bs->ainodeText = "AINode_MP_ConstructibleTarget"; } /* ================== AINode_MP_ConstructibleTarget() ================== */ int AINode_MP_ConstructibleTarget( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav, *ent, *constructible; int list[10], numList, i; float goalDist; ent = &g_entities[bs->client]; trav = &g_entities[bs->target_goal.entitynum]; constructible = G_ConstructionForTeam( trav, bs->sess.sessionTeam ); goal = bs->target_goal; /* if(bot_profile.integer == 2) { // update this in case it is moving if (bs->lastLeaderMoveTime < level.time - 500) { BotGoalForEntity( bs, goal.entitynum, &goal, BGU_HIGH ); bs->lastLeaderMoveTime = level.time; } }*/ //if we have changed class if ( bs->sess.playerType != PC_ENGINEER ) { BotDefaultNode( bs ); return qfalse; } if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // is this constructible finished building? if ( !BotIsConstructible( bs->sess.sessionTeam, goal.entitynum ) ) { // finished building BotDefaultNode( bs ); return qfalse; } //if there are 2 bots going for this goal, then we should abort if we are further away if ( ( numList = BotNumTeamMatesWithTarget( bs, goal.entitynum, list, 10 ) ) > botgoalMaxCloser[BFG_CONSTRUCT] ) { goalDist = VectorDistanceSquared( bs->origin, goal.origin ); if ( goalDist > SQR( 1024 ) ) { goalDist = SQR( 1024 ); // only abort if one of our teammates is close to the goal } for ( i = 0; i < numList; i++ ) { if ( botstates[list[i]].ainode == AINode_MP_ConstructibleTarget ) { if ( VectorDistanceSquared( botstates[list[i]].origin, goal.origin ) < goalDist ) { // only abort if there is something else to do if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } } } } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // are we close enough to the goal? if ( ent->client->touchingTOI && ent->client->touchingTOI == trav ) { // if the construction has changed level, we should reset the construction flag so we wait for full power again if ( ( bs->flags & BFL_MISCFLAG ) && constructible->count2 && !constructible->s.angles2[0] ) { bs->flags &= ~BFL_MISCFLAG; } // if we haven't started yet, make sure we wait until we have reasonable power before starting if ( !( bs->flags & BFL_MISCFLAG ) ) { if ( bs->cur_ps.classWeaponTime > ( level.time - level.engineerChargeTime[bs->sess.sessionTeam - 1] / 4 ) ) { // just crouch, and look ahead trap_EA_Crouch( bs->client ); bs->ideal_viewangles[PITCH] = 0; // look for things to attack BotFindAndAttackEnemy( bs ); return qtrue; } } // we have started // if we are out of power, wait until it's full before starting again if ( !ReadyToConstruct( ent, constructible, qfalse ) ) { bs->flags &= ~BFL_MISCFLAG; return qtrue; } bs->flags |= BFL_MISCFLAG; // VOICE: cover me! BotVoiceChatAfterIdleTime( bs->client, "CoverMe", SAY_TEAM, 500 + rand() % 1000, qfalse, 10000, qfalse ); // look downwards bs->ideal_viewangles[PITCH] = 70; // select pliers (the all-in-one handyman tool) bs->weaponnum = WP_PLIERS; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // hold fire if ( bs->cur_ps.weapon == WP_PLIERS ) { trap_EA_Attack( bs->client ); } return qtrue; } //choose the best weapon to fight with BotChooseWeapon( bs ); // // MOVEMENT REQUIRED // //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed goalDist = VectorDistanceSquared( bs->origin, goal.origin ); if ( moveresult.failure || ( VectorLengthSquared( bs->cur_ps.velocity ) < SQR( 3 ) && goalDist < ( 128 * 128 ) ) ) { // allow for boxes at construction site that may get in the way //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_WAITING ) { // if waiting for something if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } // return qtrue; } /* ================== AIEnter_MP_PlantMine() ================== */ void AIEnter_MP_PlantMine( bot_state_t *bs ) { bs->target_goal.flags &= ~GFL_NOSLOWAPPROACH; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_PlantMine; bs->ainodeText = "AINode_MP_PlantMine"; } /* ================== AINode_MP_PlantMine() ================== */ int AINode_MP_PlantMine( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav; goal = bs->target_goal; //if we have changed class if ( bs->sess.playerType != PC_ENGINEER ) { BotDefaultNode( bs ); return qfalse; } // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // if I have no landmines, I can't do this if ( !BotGotEnoughAmmoForWeapon( bs, WP_LANDMINE ) ) { BotDefaultNode( bs ); return qfalse; } // are we close enough to the goal? if ( VectorDistanceSquared( bs->origin, goal.origin ) < SQR( 32 ) ) { // VOICE: cover me! BotVoiceChatAfterIdleTime( bs->client, "CoverMe", SAY_TEAM, 500 + rand() % 1000, qfalse, 60000, qfalse ); // crouch down trap_EA_Crouch( bs->client ); // look downwards bs->ideal_viewangles[PITCH] = 70; // have we recently dropped a land mine? trav = NULL; while ( ( trav = G_FindLandmine( trav ) ) ) { if ( !trav->parent || trav->parent->s.number != bs->client ) { continue; } if ( VectorDistanceSquared( bs->target_goal.origin, trav->r.currentOrigin ) > SQR( 100 ) ) { continue; } if ( trav->awaitingHelpTime < level.time - 5000 ) { continue; } if ( G_LandmineArmed( trav ) ) { bs->last_dangerousgoal = 0; // Gordon: force a reset if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } } // found some! bs->flags |= BFL_MISCFLAG; VectorCopy( trav->r.currentOrigin, bs->target_goal.origin ); bs->target_goal.origin[2] += 24; break; } if ( !trav ) { // select the land mine bs->weaponnum = WP_LANDMINE; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // hold fire if ( !VectorLengthSquared( bs->velocity ) && fabs( bs->viewangles[PITCH] - bs->ideal_viewangles[PITCH] ) < 2 && bs->cur_ps.weapon == bs->weaponnum && !bs->cur_ps.grenadeTimeLeft ) { trap_EA_Attack( bs->client ); } } else if ( trav->s.teamNum >= 4 ) { // the dynamite is not armed // switch to pliers and arm the dynamite bs->weaponnum = WP_PLIERS; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // aim directly at the dynamite VectorCopy( bs->origin, target ); target[2] += bs->cur_ps.viewheight; VectorSubtract( trav->r.currentOrigin, target, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // hold fire if ( bs->cur_ps.weapon == WP_PLIERS ) { trap_EA_Attack( bs->client ); } } else { // the dynamite is armed, get out of here! BotDefaultNode( bs ); return qfalse; } return qtrue; } //choose the best weapon to fight with BotChooseWeapon( bs ); // MOVEMENT REQUIRED // //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); BotDefaultNode( bs ); return qfalse; } BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else if ( moveresult.flags & MOVERESULT_WAITING ) { // if waiting for something if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { BotFindAndAttackEnemy( bs ); BotUpdateViewAngles( bs, &goal, moveresult ); } return qtrue; } /* ================== AIEnter_MP_DisarmDynamite() ================== */ void AIEnter_MP_DisarmDynamite( bot_state_t *bs ) { // VOICE: cover me! BotVoiceChatAfterIdleTime( bs->client, "CoverMe", SAY_TEAM, 500 + rand() % 1000, qfalse, 4000, qfalse ); bs->target_goal.flags &= ~GFL_NOSLOWAPPROACH; //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_DisarmDynamite; bs->ainodeText = "AINode_MP_DisarmDynamite"; } /* ================== AINode_MP_DisarmDynamite() ================== */ int AINode_MP_DisarmDynamite( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; gentity_t *trav; float goalDist; goal = bs->target_goal; //if we have changed class if ( bs->sess.playerType != PC_ENGINEER ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } //if there are 2 bots going for this goal, then we should abort if we are further away goalDist = VectorDistanceSquared( bs->origin, goal.origin ); /* if (numList = BotNumTeamMatesWithTarget( bs, goal.entitynum, list, 10 )) { for (i=0; i<numList; i++) { if (list[i] == bs->client) continue; if (botstates[list[i]].ainode == AINode_MP_DisarmDynamite) { if (VectorDistanceSquared( botstates[list[i]].origin, goal.origin ) < goalDist) { // make sure other bots dont head for this target also bs->ignore_specialgoal_time = 0; g_entities[goal.entitynum].missionLevel = level.time + 5000; BotDefaultNode( bs ); return qfalse; } } } } */ // trav = BotGetEntity( goal.entitynum ); // FIXME: temp hack in dealing with NULL returns from BotGetEntity (??) if ( trav == NULL ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } if ( !trav->inuse || trav->s.eType != ET_MISSILE || trav->s.weapon != WP_DYNAMITE ) { // it's gone, so reset goal bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } if ( trav->s.teamNum >= 4 ) { // the dynamite is not armed // make sure other bots dont head for this target also bs->ignore_specialgoal_time = 0; g_entities[goal.entitynum].missionLevel = level.time + 5000; BotDefaultNode( bs ); return qfalse; } // make sure other bots dont head for this target also trav->missionLevel = level.time + 1000; // //map specific code BotMapScripts( bs ); // // are we close enough to the goal? if ( goalDist < SQR( 32 ) ) { // crouch down trap_EA_Crouch( bs->client ); // // switch to pliers and disarm the dynamite bs->weaponnum = WP_PLIERS; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); // aim directly at the dynamite VectorCopy( bs->origin, target ); target[2] += bs->cur_ps.viewheight; VectorSubtract( trav->r.currentOrigin, target, dir ); VectorNormalize( dir ); vectoangles( dir, bs->ideal_viewangles ); // hold fire if ( bs->cur_ps.weapon == WP_PLIERS ) { trap_EA_Attack( bs->client ); } // return qtrue; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } //choose the best weapon to fight with BotChooseWeapon( bs ); // MOVEMENT REQUIRED // //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // jump randomly? trap_EA_Jump( bs->client ); trap_EA_Move( bs->client, tv( crandom(), crandom(), crandom() ), 100 + random() * 200 ); } // BotAIBlocked( bs, &moveresult, qtrue ); //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_Battle_Fight() ================== */ void AIEnter_MP_Battle_Fight( bot_state_t *bs ) { BotClearGoal( &bs->target_goal ); trap_BotResetLastAvoidReach( bs->ms ); bs->ainode = AINode_MP_Battle_Fight; bs->ainodeText = "AINode_MP_Battle_Fight"; } /* ================== AINode_MP_Battle_Fight() ================== */ int AINode_MP_Battle_Fight( bot_state_t *bs ) { int areanum; aas_entityinfo_t entinfo; bot_moveresult_t moveresult; bot_goal_t goal; float enemydist; memset( &moveresult, 0, sizeof( moveresult ) ); if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } //if no enemy if ( bs->enemy < 0 ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // if using MOBILE MG42, conditionally go into special prone mode if ( bs->weaponnum == WP_MOBILE_MG42 ) { if ( VectorDistanceSquared( bs->origin, BotGetOrigin( bs->enemy ) ) > SQR( 700 ) ) { vec3_t dir, ang, mountedWeaponAngles; trace_t tr; vec3_t end; // make sure they are within pitch range VectorSubtract( BotGetOrigin( bs->enemy ), bs->eye, dir ); VectorNormalize( dir ); vectoangles( dir, ang ); // VectorCopy( bs->origin, end ); end[2] -= 40; trap_Trace( &tr, bs->origin, vec3_origin, vec3_origin, end, bs->client, MASK_PLAYERSOLID ); if ( tr.fraction < 1.f ) { vec3_t axis[3], forward, right; AngleVectors( bs->viewangles, forward, right, NULL ); forward[2] = 0; right[2] = 0; PM_ClipVelocity( forward, tr.plane.normal, forward, OVERCLIP ); PM_ClipVelocity( right, tr.plane.normal, right, OVERCLIP ); // VectorNormalize( forward ); VectorNormalize( right ); // VectorCopy( forward, axis[0] ); VectorCopy( right, axis[2] ); CrossProduct( axis[0], axis[2], axis[1] ); AxisToAngles( axis, mountedWeaponAngles ); // make sure these angles are within view limits towards the enemy if ( fabs( AngleDifference( mountedWeaponAngles[PITCH], ang[PITCH] ) ) < 15.f ) { int oldviewheight; // check for obstruction at feet oldviewheight = level.clients[bs->client].ps.viewheight; level.clients[bs->client].ps.viewheight = PRONE_VIEWHEIGHT; if ( BotVisibleFromPos( bs->origin, bs->client, BotGetOrigin( bs->enemy ), bs->enemy, qtrue ) ) { AIEnter_MP_Battle_MobileMG42( bs ); return qfalse; } } } } } // check for dangerous elements VectorCopy( bs->origin, goal.origin ); goal.areanum = bs->areanum; goal.entitynum = bs->client; if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } // BotEntityInfo( bs->enemy, &entinfo ); enemydist = VectorDistanceSquared( bs->origin, entinfo.origin ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->ignore_specialgoal_time = 0; bs->enemydeath_time = 0; bs->enemy = -1; BotDefaultNode( bs ); return qfalse; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } //if the enemy is invisible and not shooting the bot looses track easily if ( EntityIsInvisible( &entinfo ) && !EntityIsShooting( &entinfo ) ) { if ( random() < 0.2 ) { BotDefaultNode( bs ); return qfalse; } } //update the reachability area and origin if possible areanum = BotGetArea( bs->enemy ); //BotPointAreaNum(entinfo.number, entinfo.origin); if ( areanum ) { VectorCopy( entinfo.origin, bs->lastenemyorigin ); bs->lastenemyareanum = areanum; } //update the attack inventory values BotUpdateBattleInventory( bs, bs->enemy ); // get in real close to enemy flag carriers if ( BotCarryingFlag( bs->enemy ) && VectorDistanceSquared( bs->origin, bs->lastenemyorigin ) > SQR( 72 ) ) { if ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, bs->lastenemyareanum, bs->tfl ) ) { AIEnter_MP_Battle_Chase( bs ); return qfalse; } } //if the enemy is not visible, or is too far away if ( ( bs->weaponnum == WP_KNIFE ) || ( enemydist > SQR( BotWeaponRange( bs, bs->weaponnum ) ) ) || !BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { if ( BotWantsToChase( bs ) ) { AIEnter_MP_Battle_Chase( bs ); return qfalse; } else { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qtrue; // wait until next frame, incase this triggers a loop } } //use holdable items BotBattleUseItems( bs ); // if ( bot_grapple.integer ) { bs->tfl |= TFL_GRAPPLEHOOK; } //if in lava or slime the bot should be able to get out if ( BotInLava( bs ) ) { bs->tfl |= TFL_LAVA; } if ( BotInSlime( bs ) ) { bs->tfl |= TFL_SLIME; } // if ( BotCanAndWantsToRocketJump( bs ) ) { bs->tfl |= TFL_ROCKETJUMP; } //choose the best weapon to fight with BotChooseWeapon( bs ); if ( BotMoveWhileFiring( bs->weaponnum ) ) { //do attack movements moveresult = BotAttackMove( bs, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); } // BotAIBlocked( bs, &moveresult, qfalse ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( !BotCheckAttack( bs ) ) { if ( BotWantsToChase( bs ) ) { AIEnter_MP_Battle_Chase( bs ); return qfalse; // chase them immediately } else { BotDefaultNode( bs ); return qtrue; // prevent loop } } //if the bot wants to retreat if ( BotWantsToRetreat( bs ) ) { BotFindSpecialGoals( bs ); return qtrue; } return qtrue; } /* ================== AIEnter_MP_Battle_Chase() ================== */ void AIEnter_MP_Battle_Chase( bot_state_t *bs ) { bs->altenemy = -1; BotClearGoal( &bs->target_goal ); bs->chase_time = trap_AAS_Time(); bs->ainode = AINode_MP_Battle_Chase; bs->ainodeText = "AINode_MP_Battle_Chase"; } /* ================== AINode_MP_Battle_Chase() ================== */ int AINode_MP_Battle_Chase( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; aas_entityinfo_t entinfo; int oldenemy; float enemydist; memset( &moveresult, 0, sizeof( moveresult ) ); if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // RF, if we have a leader, go back to protecting them if ( ( bs->leader > -1 ) && !BotCarryingFlag( bs->enemy ) ) { AIEnter_MP_DefendTarget( bs ); return qfalse; } //if no enemy if ( bs->enemy < 0 ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( !BotCarryingFlag( bs->enemy ) && BotCheckEmergencyTargets( bs ) ) { return qfalse; } //if the enemy is visible BotEntityInfo( bs->enemy, &entinfo ); VectorCopy( entinfo.origin, bs->lastenemyorigin ); enemydist = VectorDistanceSquared( bs->origin, bs->lastenemyorigin ); if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { // update chase org bs->lastenemyareanum = BotPointAreaNum( bs->enemy, entinfo.origin ); bs->chase_time = trap_AAS_Time() + 5.0; // RF, if we are in the air, wait until we land (we may be climbing a ladder) if ( bs->cur_ps.groundEntityNum != ENTITYNUM_NONE || bs->cur_ps.velocity[2] < 0 ) { // get real close to flag carrier if ( ( bs->weaponnum != WP_KNIFE ) && ( ( !BotCarryingFlag( bs->enemy ) && ( enemydist < SQR( BotWeaponRange( bs, bs->weaponnum ) ) ) ) || ( enemydist < SQR( 64 ) ) ) ) { // make sure it is safe to attack if ( BotCheckAttack( bs ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } } else { // attack and keep moving towards them //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } } } // if ( !BotCarryingFlag( bs->enemy ) ) { int oldEnemy; //if there is another enemy oldEnemy = bs->enemy; if ( ( bs->weaponnum != WP_KNIFE ) && BotFindEnemyMP( bs, -1, qfalse ) && ( bs->enemy != oldEnemy ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } } //there is no last enemy area if ( ( bs->weaponnum != WP_KNIFE ) && !bs->lastenemyareanum ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // if ( bot_grapple.integer ) { bs->tfl |= TFL_GRAPPLEHOOK; } //if in lava or slime the bot should be able to get out if ( BotInLava( bs ) ) { bs->tfl |= TFL_LAVA; } if ( BotInSlime( bs ) ) { bs->tfl |= TFL_SLIME; } // if ( BotCanAndWantsToRocketJump( bs ) ) { bs->tfl |= TFL_ROCKETJUMP; } //map specific code BotMapScripts( bs ); //create the chase goal goal.entitynum = bs->enemy; goal.areanum = bs->lastenemyareanum; VectorCopy( bs->lastenemyorigin, goal.origin ); VectorSet( goal.mins, -8, -8, -8 ); VectorSet( goal.maxs, 8, 8, 8 ); // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } //if the last seen enemy spot is reached the enemy could not be found if ( ( bs->weaponnum != WP_KNIFE ) && trap_BotTouchingGoal( bs->origin, &goal ) ) { bs->chase_time = 0; } //if there's no chase time left if ( !bs->chase_time || bs->chase_time < trap_AAS_Time() - 10 ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // BotUpdateBattleInventory( bs, bs->enemy ); //initialize the movement state BotSetupForMovement( bs ); //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { bs->enemy = -1; //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype); // try and find something else to do bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // BotAIBlocked( bs, &moveresult, qfalse ); // if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else { // forget about our current enemy temporarily, so we can shoot at other while pursuing the flag carrier oldenemy = bs->enemy; if ( BotCarryingFlag( oldenemy ) ) { // check for enemies bs->enemy = -1; if ( bs->altenemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } else { bs->enemy = bs->altenemy; } if ( bs->enemy > -1 ) { bs->altenemy = bs->enemy; // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->altenemy = -1; } } else { bs->altenemy = -1; } } // if ( ( bs->altenemy < 0 || !BotCarryingFlag( oldenemy ) ) && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; } // restore the enemy bs->enemy = oldenemy; } //if the weapon is used for the bot movement if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) { bs->weaponnum = moveresult.weapon; } //if the bot is in the area the enemy was last seen in if ( bs->areanum == bs->lastenemyareanum ) { bs->chase_time = 0; } //if the bot wants to retreat (the bot could have been damage during the chase) if ( BotWantsToRetreat( bs ) ) { AIEnter_MP_Battle_Retreat( bs ); return qtrue; } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_Battle_Retreat() ================== */ void AIEnter_MP_Battle_Retreat( bot_state_t *bs ) { bs->ainode = AINode_MP_Battle_Retreat; bs->ainodeText = "AINode_MP_Battle_Retreat"; } /* ================== AINode_MP_Battle_Retreat() ================== */ int AINode_MP_Battle_Retreat( bot_state_t *bs ) { aas_entityinfo_t entinfo; bot_moveresult_t moveresult; int areanum; memset( &moveresult, 0, sizeof( moveresult ) ); if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } //if no enemy if ( bs->enemy < 0 ) { BotDefaultNode( bs ); return qfalse; } // BotEntityInfo( bs->enemy, &entinfo ); if ( EntityIsDead( &entinfo ) ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // if ( bot_grapple.integer ) { bs->tfl |= TFL_GRAPPLEHOOK; } //if in lava or slime the bot should be able to get out if ( BotInLava( bs ) ) { bs->tfl |= TFL_LAVA; } if ( BotInSlime( bs ) ) { bs->tfl |= TFL_SLIME; } //map specific code BotMapScripts( bs ); //update the attack inventory values BotUpdateBattleInventory( bs, bs->enemy ); //if the bot doesn't want to retreat anymore... probably picked up some nice items if ( BotWantsToChase( bs ) ) { //empty the goal stack, when chasing, only the enemy is the goal trap_BotEmptyGoalStack( bs->gs ); //go chase the enemy AIEnter_MP_Battle_Chase( bs ); return qfalse; } //update the last time the enemy was visible if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { bs->enemyvisible_time = trap_AAS_Time(); //update the reachability area and origin if possible areanum = BotPointAreaNum( entinfo.number, entinfo.origin ); if ( areanum && trap_AAS_AreaReachability( areanum ) ) { VectorCopy( entinfo.origin, bs->lastenemyorigin ); bs->lastenemyareanum = areanum; } } //if the enemy is NOT visible for 4 seconds if ( bs->enemyvisible_time < trap_AAS_Time() - 4 ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } //else if the enemy is NOT visible else if ( bs->enemyvisible_time < trap_AAS_Time() ) { //if there is another enemy if ( BotFindEnemyMP( bs, -1, qfalse ) ) { AIEnter_MP_Battle_Fight( bs ); return qfalse; } } // //use holdable items BotBattleUseItems( bs ); // // !!! RF, we should try to move somewhere safe here // //choose the best weapon to fight with BotChooseWeapon( bs ); //if the view is fixed for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEW //|MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } else if ( !( moveresult.flags & MOVERESULT_MOVEMENTVIEWSET ) && !( bs->flags & BFL_IDEALVIEWSET ) ) { BotAimAtEnemy( bs ); } //if the weapon is used for the bot movement if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) { bs->weaponnum = moveresult.weapon; } //attack the enemy if possible BotCheckAttack( bs ); // return qtrue; } /* ================== AIEnter_MP_Script_MoveToMarker() ================== */ void AIEnter_MP_Script_MoveToMarker( bot_state_t *bs ) { //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_Script_MoveToMarker; bs->ainodeText = "AINode_MP_Script_MoveToMarker"; } /* ================== AINode_MP_Script_MoveToMarker() ================== */ int AINode_MP_Script_MoveToMarker( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; g_serverEntity_t *marker; // goal = bs->target_goal; // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( !BotIsPOW( bs ) ) { if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } } // check for dangerous elements if ( !BotIsPOW( bs ) ) { if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } } /* // check for special class actions if (BotCheckClassActions(bs)) { return qfalse; } */ // look for health/ammo packs if ( !BotIsPOW( bs ) ) { if ( BotFindNearbyGoal( bs ) ) { AIEnter_MP_Seek_NBG( bs ); return qfalse; } } if ( !BotIsPOW( bs ) ) { if ( BotFindSpecialGoals( bs ) ) { return qfalse; } } // // should we stop pursuing this target? marker = GetServerEntity( bs->target_goal.entitynum ); if ( !marker || !marker->inuse ) { bs->ignore_specialgoal_time = 0; BotDefaultNode( bs ); return qfalse; } // VectorCopy( goal.origin, target ); if ( fabs( target[2] - bs->origin[2] ) < 80 ) { target[2] = bs->origin[2]; } // //choose the best weapon to fight with BotChooseWeapon( bs ); // //map specific code BotMapScripts( bs ); //initialize the movement state BotSetupForMovement( bs ); // memset( &moveresult, 0, sizeof( moveresult ) ); // if ( VectorDistanceSquared( bs->origin, target ) >= SQR( 12 ) ) { //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); if ( !( bs->flags & BFL_MISCFLAG ) ) { Bot_ScriptLog_Entry( bs, qfalse, NULL, "movement failure" ); bs->flags |= BFL_MISCFLAG; } return qtrue; } else { if ( bs->flags & BFL_MISCFLAG ) { Bot_ScriptLog_Entry( bs, qfalse, NULL, "resumed movement" ); bs->flags &= ~BFL_MISCFLAG; } } // set the movement type if ( bs->script.moveType == BSMT_WALKING ) { trap_EA_Walk( bs->client ); } else if ( bs->script.moveType == BSMT_CROUCHING ) { trap_EA_Crouch( bs->client ); } // BotAIBlocked( bs, &moveresult, qtrue ); } else { // Gordon: TEMP: i doubt this should be here if ( BotIsPOW( bs ) ) { BotDefaultNode( bs ); return qfalse; } } //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; // check for giving ourselves some ammo if ( bs->sess.playerType == PC_FIELDOPS && ClientNeedsAmmo( bs->client ) ) { // switch to regen and pump away bs->weaponnum = WP_AMMO; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_AMMO && BotWeaponCharged( bs, WP_AMMO ) ) { trap_EA_Attack( bs->client ); } } // check for giving ourselves some health if ( bs->sess.playerType == PC_MEDIC && BotHealthScale( bs->client ) < 1.0 ) { // switch to regen and pump away bs->weaponnum = WP_MEDKIT; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_MEDKIT && BotWeaponCharged( bs, WP_MEDKIT ) ) { trap_EA_Attack( bs->client ); } } } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_MoveToAutonomyRange() ================== */ void AIEnter_MP_MoveToAutonomyRange( bot_state_t *bs ) { vec3_t pos; // if ( !BotGetMovementAutonomyPos( bs, pos ) ) { if ( g_developer.integer ) { G_Printf( "AIEnter_MP_MoveToAutonomyRange: autonomy pos unknown\n" ); } } // make the current goal our autonomy spot BotClearGoal( &bs->target_goal ); VectorCopy( pos, bs->target_goal.origin ); bs->target_goal.areanum = BotPointAreaNum( bs->client, pos ); //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->ainode = AINode_MP_MoveToAutonomyRange; bs->ainodeText = "AINode_MP_MoveToAutonomyRange"; } /* ================== AINode_MP_MoveToAutonomyRange() ================== */ int AINode_MP_MoveToAutonomyRange( bot_state_t *bs ) { bot_goal_t goal; vec3_t target, dir; bot_moveresult_t moveresult; // goal = bs->target_goal; // if ( BotIsObserver( bs ) ) { AIEnter_MP_Observer( bs ); return qfalse; } //if in the intermission if ( BotIntermission( bs ) ) { AIEnter_MP_Intermission( bs ); return qfalse; } //respawn if dead if ( BotIsDead( bs ) ) { AIEnter_MP_Respawn( bs ); return qfalse; } // check for emergency targets (flags, etc) if ( BotCheckEmergencyTargets( bs ) ) { return qfalse; } // check for dangerous elements if ( BotDangerousGoal( bs, &goal ) ) { AIEnter_MP_AvoidDanger( bs ); // avoid this danger until it passes return qfalse; } /* // check for special class actions if (BotCheckClassActions(bs)) { return qfalse; } */ // look for health/ammo packs //if (BotFindNearbyGoal( bs )) { // AIEnter_MP_Seek_NBG( bs ); // return qfalse; //} //if (BotFindSpecialGoals(bs)) { // return qfalse; //} // // should we stop pursuing this target? //ent = BotGetEntity( bs->target_goal.entitynum ); //if (!ent->inuse) { // bs->ignore_specialgoal_time = 0; // BotDefaultNode(bs); // return qfalse; //} // VectorCopy( goal.origin, target ); if ( fabs( target[2] - bs->origin[2] ) < 80 ) { target[2] = bs->origin[2]; } // //choose the best weapon to fight with BotChooseWeapon( bs ); // //map specific code BotMapScripts( bs ); //initialize the movement state BotSetupForMovement( bs ); // memset( &moveresult, 0, sizeof( moveresult ) ); // { float halfRange = ( 0.5 * BotGetMovementAutonomyRange( bs, NULL ) ); if ( VectorDistanceSquared( bs->origin, target ) <= SQR( halfRange ) ) { // go back to standing AIEnter_MP_Stand( bs ); return qfalse; } } // //try a direct movement if ( !BotDirectMoveToGoal( bs, &goal, &moveresult ) ) { //move towards the goal BotMP_MoveToGoal( bs, &moveresult, bs->ms, &goal, bs->tfl ); } //if the movement failed if ( moveresult.failure ) { //reset the avoid reach, otherwise bot is stuck in current area trap_BotResetAvoidReach( bs->ms ); if ( !( bs->flags & BFL_MISCFLAG ) ) { Bot_ScriptLog_Entry( bs, qfalse, NULL, "movement failure" ); bs->flags |= BFL_MISCFLAG; } return qtrue; } else { if ( bs->flags & BFL_MISCFLAG ) { Bot_ScriptLog_Entry( bs, qfalse, NULL, "resumed movement" ); bs->flags &= ~BFL_MISCFLAG; } } // set the movement type if ( bs->script.moveType == BSMT_WALKING ) { trap_EA_Walk( bs->client ); } else if ( bs->script.moveType == BSMT_CROUCHING ) { trap_EA_Crouch( bs->client ); } // BotAIBlocked( bs, &moveresult, qtrue ); // //if the viewangles are used for the movement if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) { VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles ); } //if waiting for something else if ( moveresult.flags & MOVERESULT_WAITING ) { if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } } else { // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // if ( bs->enemy < 0 && !( bs->flags & BFL_IDEALVIEWSET ) ) { if ( moveresult.flags & MOVERESULT_DIRECTMOVE ) { VectorSubtract( goal.origin, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } else if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) { VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); } //FIXME: look at cluster portals? else if ( VectorLengthSquared( moveresult.movedir ) ) { vectoangles( moveresult.movedir, bs->ideal_viewangles ); } else if ( random() < bs->thinktime * 0.8 ) { BotRoamGoal( bs, target ); VectorSubtract( target, bs->origin, dir ); vectoangles( dir, bs->ideal_viewangles ); bs->ideal_viewangles[2] *= 0.5; } bs->ideal_viewangles[2] *= 0.5; // check for giving ourselves some ammo if ( bs->sess.playerType == PC_FIELDOPS && ClientNeedsAmmo( bs->client ) ) { // switch to regen and pump away bs->weaponnum = WP_AMMO; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_AMMO && BotWeaponCharged( bs, WP_AMMO ) ) { trap_EA_Attack( bs->client ); } } // check for giving ourselves some health if ( bs->sess.playerType == PC_MEDIC && BotHealthScale( bs->client ) < 1.0 ) { // switch to regen and pump away bs->weaponnum = WP_MEDKIT; trap_EA_SelectWeapon( bs->client, bs->weaponnum ); if ( bs->cur_ps.weapon == WP_MEDKIT && BotWeaponCharged( bs, WP_MEDKIT ) ) { trap_EA_Attack( bs->client ); } } } } // reload? if ( ( bs->last_fire != level.time ) && ( bs->cur_ps.ammoclip[BG_FindClipForWeapon( bs->cur_ps.weapon )] < (int)( 0.8 * GetAmmoTableData( bs->cur_ps.weapon )->maxclip ) ) && bs->cur_ps.ammo[BG_FindAmmoForWeapon( bs->cur_ps.weapon )] ) { trap_EA_Reload( bs->client ); } // return qtrue; } /* ================== AIEnter_MP_NavigateFromVoid() ================== */ void AIEnter_MP_NavigateFromVoid( bot_state_t *bs ) { //choose the best weapon to fight with BotChooseWeapon( bs ); bs->flags &= ~BFL_MISCFLAG; bs->last_SparseDefense = 0; bs->ainode = AINode_MP_NavigateFromVoid; bs->ainodeText = "AINode_MP_NavigateFromVoid"; } /* ================== AINode_MP_NavigateFromVoid() ================== */ int AINode_MP_NavigateFromVoid( bot_state_t *bs ) { const int checkFrames = 40; const float checkFrametime = 0.05; const int randomChecksPerSlice = 5; int i; vec3_t dir, angles; aas_clientmove_t move; qboolean success; float bestDist; vec3_t bestDir; // are we out of the void? if ( bs->areanum ) { BotDefaultNode( bs ); return qfalse; } // try to navigate out of the void // if we have a current direction, validate it if ( bs->flags & BFL_MISCFLAG ) { // we are currently heading in a direction, verify to make sure it's still valid if ( bs->last_attackShout < level.time - 250 ) { VectorCopy( bs->lastLeaderPosition, dir ); success = qfalse; if ( trap_AAS_PredictClientMovement( &move, bs->client, bs->origin, -1, qfalse, dir, vec3_origin, checkFrames, 0, checkFrametime, SE_HITGROUNDDAMAGE | SE_HITGROUNDAREA | SE_STUCK | SE_GAP, -1, qfalse ) ) { switch ( move.stopevent ) { case SE_HITGROUNDAREA: // success! success = qtrue; // keep it valid bs->last_SparseDefense = level.time + 500; break; } } // if ( !success ) { bs->flags &= ~BFL_MISCFLAG; } } } // do we need a new direction? if ( !( bs->flags & BFL_MISCFLAG ) ) { bestDist = -1.0; for ( i = 0; i < randomChecksPerSlice; i++ ) { // choose a random direction VectorClear( angles ); angles[YAW] = rand() % 360; AngleVectors( angles, dir, NULL, NULL ); // how far will this direction get us? success = qfalse; if ( trap_AAS_PredictClientMovement( &move, bs->client, bs->origin, -1, qfalse, dir, vec3_origin, checkFrames, 0, checkFrametime, SE_HITGROUNDDAMAGE | SE_HITGROUNDAREA | SE_STUCK | SE_GAP, -1, qfalse ) ) { switch ( move.stopevent ) { case SE_HITGROUNDAREA: // success! success = qtrue; break; } } // if ( success ) { bs->flags |= BFL_MISCFLAG; bs->last_attackShout = level.time; bs->last_SparseDefense = level.time + 200; VectorCopy( dir, bs->lastLeaderPosition ); break; } else { switch ( move.stopevent ) { case SE_HITGROUNDDAMAGE: case SE_GAP: // bad direction break; default: // Gordon: OPT: bleh.... if ( bestDist < 0 || VectorDistanceSquared( bs->origin, move.endpos ) < SQR( bestDist ) ) { bestDist = VectorDistance( bs->origin, move.endpos ); VectorCopy( dir, bestDir ); } } } } if ( !( bs->flags & BFL_MISCFLAG ) && ( bestDist > 0.0 ) ) { bs->last_SparseDefense = level.time + 200; VectorCopy( bestDir, bs->lastLeaderPosition ); } } // check for enemies if ( bs->enemy < 0 ) { BotFindEnemyMP( bs, -1, qfalse ); } if ( bs->enemy >= 0 ) { aas_entityinfo_t entinfo; BotEntityInfo( bs->enemy, &entinfo ); //if the enemy is dead if ( bs->enemydeath_time ) { if ( bs->enemydeath_time < trap_AAS_Time() - 0.3 ) { bs->enemydeath_time = 0; bs->enemy = -1; } } else { if ( EntityIsDead( &entinfo ) ) { bs->enemydeath_time = trap_AAS_Time(); } } // if ( bs->enemy >= 0 ) { // attack and keep moving if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy, NULL ) ) { //choose the best weapon to fight with BotChooseWeapon( bs ); //aim at the enemy BotAimAtEnemy( bs ); //attack the enemy if possible if ( bs->weaponnum == bs->cur_ps.weapon ) { BotCheckAttack( bs ); } } else { bs->enemy = -1; } } } // do we have a current direction? if ( bs->last_SparseDefense > level.time ) { // continue in that direction trap_EA_Move( bs->client, bs->lastLeaderPosition, 400 ); if ( bs->enemy < 0 ) { vectoangles( bs->lastLeaderPosition, angles ); trap_EA_View( bs->client, angles ); } } return qtrue; }
1
0.943064
1
0.943064
game-dev
MEDIA
0.988672
game-dev
0.988494
1
0.988494
gridengine/gridengine
13,555
source/libs/jgdi/cullconv/src/com/sun/grid/cull/CullDependencies.java
/*___INFO__MARK_BEGIN__*/ /************************************************************************* * * The Contents of this file are made available subject to the terms of * the Sun Industry Standards Source License Version 1.2 * * Sun Microsystems Inc., March, 2001 * * * Sun Industry Standards Source License Version 1.2 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.2 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2001 by Sun Microsystems, Inc. * * All Rights Reserved. * ************************************************************************/ /*___INFO__MARK_END__*/ package com.sun.grid.cull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Logger; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.tools.ant.BuildException; /** * */ public class CullDependencies { private Logger logger = Logger.getLogger("cullconv"); Map<String, Node> nodeMap = new HashMap<String, Node>(); public static final String FILTER_OBJECTS = "objects"; public static final String FILTER_PRIMITIVE_OBJECTS = "primitives"; public static final String FILTER_ROOT_OBJECTS = "root"; public static final String FILTER_PRIMITIVE_ROOT_OBJECTS = "primitive_root"; public static final String FILTER_MAPPED_OBJECTS = "mapped"; public static final String FILTER_MAP_OBJECTS = "map"; public static final String FILTER_DEPEND_OBJECTS = "depend"; public static final String FILTER_EVENT_OBJECTS = "event"; public static final int INCLUDE_ROOT_OBJECTS = 1; public static final int INCLUDE_OBJECTS = 2; public static final int INCLUDE_PRIMITIVE_OBJECTS = 4; public static final int INCLUDE_PRIMITIVE_ROOT_OBJECTS = 8; public static final int INCLUDE_MAPPED_OBJECTS = 16; public static final int INCLUDE_MAP_OBJECTS = 32; public static final int INCLUDE_DEPEND_OBJECTS = 64; public static final int INCLUDE_EVENT_OBJECTS = 128; public static final int INCLUDE_ALL = 65535; private int includeMask; /** Creates a new instance of CullDependencies */ public CullDependencies(CullDefinition culldef, Set<String> nameSet, String objectFilter) throws BuildException { includeMask = 0; if (objectFilter == null) { includeMask = INCLUDE_ALL; } else { StringTokenizer st = new StringTokenizer(objectFilter); while (st.hasMoreTokens()) { String token = st.nextToken(); if (FILTER_OBJECTS.equals(token)) { includeMask |= INCLUDE_OBJECTS; } else if (FILTER_PRIMITIVE_OBJECTS.equals(token)) { includeMask |= INCLUDE_PRIMITIVE_OBJECTS; } else if (FILTER_ROOT_OBJECTS.equals(token)) { includeMask |= INCLUDE_ROOT_OBJECTS; } else if (FILTER_EVENT_OBJECTS.equals(token)) { includeMask |= INCLUDE_EVENT_OBJECTS; } else if (FILTER_DEPEND_OBJECTS.equals(token)) { includeMask |= INCLUDE_DEPEND_OBJECTS; } else if (FILTER_MAPPED_OBJECTS.equals(token)) { includeMask |= INCLUDE_MAPPED_OBJECTS; } else if (FILTER_MAP_OBJECTS.equals(token)) { includeMask |= INCLUDE_MAP_OBJECTS; } else if (FILTER_PRIMITIVE_ROOT_OBJECTS.equals(token)) { includeMask |= INCLUDE_PRIMITIVE_ROOT_OBJECTS; } else { throw new BuildException("Invalid object filter '" + token + "'"); } } } for (String name : nameSet) { CullObject obj = culldef.getCullObject(name); Node node = nodeMap.get(name); if (node == null) { node = new Node(obj); nodeMap.put(name, node); } for (int i = 0; i < obj.getAttrCount(); i++) { CullAttr attr = obj.getAttr(i); String type = attr.getType(); CullObject subobj = culldef.getCullObject(type); if (subobj != null) { node = (Node) nodeMap.get(type); if (node == null) { node = new Node(subobj); nodeMap.put(type, node); } node.addDepend(obj); } } if (obj.getParentObject() != null) { CullObject subobj = obj.getParentObject(); if (subobj != null) { node = (Node) nodeMap.get(subobj.getName()); if (node == null) { node = new Node(subobj); nodeMap.put(subobj.getName(), node); } node.addDepend(obj); } } } } public boolean includeRootObjects() { return (includeMask & INCLUDE_ROOT_OBJECTS) == INCLUDE_ROOT_OBJECTS; } public boolean includeEventObjects() { return (includeMask & INCLUDE_EVENT_OBJECTS) == INCLUDE_EVENT_OBJECTS; } public boolean includeObjects() { return (includeMask & INCLUDE_OBJECTS) == INCLUDE_OBJECTS; } public boolean includePrimitveObjects() { return (includeMask & INCLUDE_PRIMITIVE_OBJECTS) == INCLUDE_PRIMITIVE_OBJECTS; } public boolean includeMappedObjects() { return (includeMask & INCLUDE_MAPPED_OBJECTS) == INCLUDE_MAPPED_OBJECTS; } public boolean includePrimitveRootObjects() { return (includeMask & INCLUDE_PRIMITIVE_ROOT_OBJECTS) == INCLUDE_PRIMITIVE_ROOT_OBJECTS; } public boolean includeMapObjects() { return (includeMask & INCLUDE_MAP_OBJECTS) == INCLUDE_MAP_OBJECTS; } public boolean includeDependObjects() { return (includeMask & INCLUDE_DEPEND_OBJECTS) == INCLUDE_DEPEND_OBJECTS; } public Node getNode(String name) { return (Node) nodeMap.get(name); } public class Node { private CullObject obj; private List<CullObject> dependSet = new ArrayList<CullObject>(); public Node(CullObject obj) { this.obj = obj; } public void addDepend(CullObject obj) { dependSet.add(obj); needed = null; } public int getDependCount() { return dependSet.size(); } private Boolean needed = null; private boolean isNeededArmed = false; public boolean isNeeded() { if (needed == null) { if (isNeededArmed) { needed = Boolean.FALSE; } else { isNeededArmed = true; if (obj.hasEvents() && includeEventObjects()) { needed = Boolean.TRUE; } else if (obj.getType() == CullObject.TYPE_PRIMITIVE && includePrimitveObjects()) { needed = Boolean.TRUE; } else if (obj.getType() == CullObject.TYPE_MAPPED && includeMappedObjects()) { needed = Boolean.TRUE; } else if (obj.getType() == CullObject.TYPE_MAP && includeMapObjects()) { needed = Boolean.TRUE; } else if (obj.isRootObject()) { if (obj.getType() == CullObject.TYPE_PRIMITIVE) { if (includePrimitveRootObjects()) { needed = Boolean.TRUE; } } else { if (includeRootObjects()) { needed = Boolean.TRUE; } } } else if (includeObjects()) { needed = Boolean.TRUE; } if (needed == null) { for (CullObject dependObj : dependSet) { Node node = getNode(dependObj.getName()); if (node != null) { if (node.isNeeded()) { switch (obj.getType()) { case CullObject.TYPE_PRIMITIVE: { if (includePrimitveObjects()) { needed = Boolean.TRUE; } else { needed = Boolean.FALSE; } break; } case CullObject.TYPE_MAPPED: { if (includeMappedObjects()) { needed = Boolean.TRUE; } else { needed = Boolean.FALSE; } break; } case CullObject.TYPE_MAP: { if (includeMapObjects()) { needed = Boolean.TRUE; } else { needed = Boolean.FALSE; } break; } default: { if (includeDependObjects()) { needed = Boolean.TRUE; } } } } } } if (needed == null) { needed = Boolean.FALSE; } } isNeededArmed = false; } } return needed.booleanValue(); } boolean toStringArmed = false; public String toString() { StringBuffer ret = new StringBuffer(); ret.append(obj.getName()); ret.append("("); if (obj.isRootObject()) { ret.append("]"); } CullObject testObj = obj; if (obj.getParentObject() != null) { testObj = obj.getParentObject(); } if (testObj.getType() == CullObject.TYPE_PRIMITIVE) { ret.append("P"); } if (testObj.getType() == CullObject.TYPE_MAPPED) { ret.append("M"); } ret.append(")"); if (!toStringArmed) { toStringArmed = true; if (isNeeded()) { ret.append("*"); } if (!dependSet.isEmpty()) { boolean first = true; ret.append(" --> ["); for (CullObject obj : dependSet) { Node node = getNode(obj.getName()); if (first) { first = false; } else { ret.append(", "); } ret.append(node.toString()); } ret.append("]"); } toStringArmed = false; } return ret.toString(); } } private static DefaultMutableTreeNode findNode(DefaultMutableTreeNode node, CullObject obj) { if (node.getUserObject().equals(obj)) { return node; } DefaultMutableTreeNode ret = null; for (DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getFirstChild(); child != null; child = (DefaultMutableTreeNode) child.getNextSibling()) { ret = findNode(child, obj); if (ret != null) { break; } } return ret; } }
1
0.941973
1
0.941973
game-dev
MEDIA
0.551471
game-dev,graphics-rendering
0.938767
1
0.938767
StranikS-Scan/WorldOfTanks-Decompiled
6,171
source/res/scripts/client/gui/prb_control/entities/base/squad/entity.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/prb_control/entities/base/squad/entity.py from debug_utils import LOG_ERROR from gui.prb_control.ctrl_events import g_prbCtrlEvents from gui.prb_control.entities.base.squad.actions_handler import SquadActionsHandler from gui.prb_control.entities.base.squad.actions_validator import SquadActionsValidator from gui.prb_control.entities.base.squad.ctx import SquadSettingsCtx from gui.prb_control.entities.base.squad.permissions import SquadPermissions from gui.prb_control.entities.base.unit.entity import UnitEntryPoint, UnitEntity from gui.prb_control.events_dispatcher import g_eventDispatcher from gui.Scaleform.daapi.settings.views import VIEW_ALIAS from gui.Scaleform.framework.entities.View import ViewKey from gui.prb_control.items import SelectResult from gui.shared.gui_items.Vehicle import Vehicle from gui.shared.utils.requesters import REQ_CRITERIA from gui.impl.gen.resources import R from helpers import dependency from skeletons.gui.app_loader import IAppLoader from th_async import th_async, th_await class SquadEntryPoint(UnitEntryPoint): def makeDefCtx(self): return SquadSettingsCtx(waitingID='prebattle/create', accountsToInvite=self._accountsToInvite) def join(self, ctx, callback=None): super(SquadEntryPoint, self).join(ctx, callback) LOG_ERROR('Player can join to squad by invite only') if callback: callback(False) class SquadEntity(UnitEntity): __appLoader = dependency.descriptor(IAppLoader) def init(self, ctx=None): self.invalidateVehicleStates() return super(SquadEntity, self).init(ctx) def fini(self, ctx=None, woEvents=False): self.__clearCustomVehicleStates() super(SquadEntity, self).fini(ctx, woEvents) def canKeepMode(self): return False def hasLockedState(self): pInfo = self.getPlayerInfo() return pInfo.isReady and super(SquadEntity, self).hasLockedState() def unit_onUnitRosterChanged(self): rosterSettings = self._createRosterSettings() if rosterSettings != self.getRosterSettings(): self._rosterSettings = rosterSettings self.invalidateVehicleStates() self._vehiclesWatcher.validate() self._invokeListeners('onUnitRosterChanged') g_eventDispatcher.updateUI() def rejoin(self): super(SquadEntity, self).rejoin() self.unit_onUnitRosterChanged() self._actionsHandler.setUnitChanged() def invalidateVehicleStates(self, vehicles=None): state = Vehicle.VEHICLE_STATE.UNSUITABLE_TO_UNIT if vehicles: criteria = REQ_CRITERIA.IN_CD_LIST(vehicles) else: criteria = REQ_CRITERIA.INVENTORY vehicles = self.itemsCache.items.getVehicles(criteria) updatedVehicles = [ intCD for intCD, v in vehicles.iteritems() if self._updateVehicleState(v, state) ] if updatedVehicles: g_prbCtrlEvents.onVehicleClientStateChanged(updatedVehicles) def isBalancedSquadEnabled(self): return False def getSquadLevelBounds(self): pass def showDialog(self, meta, callback, parent=None): self.__showDefaultDialog(meta, callback, parent=parent) def doSelectAction(self, action): name = action.actionName if name in self._showUnitActionNames: g_eventDispatcher.showUnitWindow(self._prbType) if action.accountsToInvite: self._actionsHandler.processInvites(action.accountsToInvite) return SelectResult(True) return super(SquadEntity, self).doSelectAction(action) def loadHangar(self): g_eventDispatcher.loadHangar() @property def _showUnitActionNames(self): pass def _buildPermissions(self, roles, flags, isCurrentPlayer=False, isPlayerReady=False, hasLockedState=False): return SquadPermissions(roles, flags, isCurrentPlayer, isPlayerReady) def setVehicle(self, ctx, callback=None): if self.isParentControlActivated(callback=callback): return super(SquadEntity, self).setVehicle(ctx, callback) def _createActionsHandler(self): return SquadActionsHandler(self) def _createActionsValidator(self): return SquadActionsValidator(self) def _vehicleStateCondition(self, v): return True def _updateVehicleState(self, vehicle, state): invalid = not self._vehicleStateCondition(vehicle) stateSet = vehicle.getCustomState() == state if invalid and not stateSet: vehicle.setCustomState(state) elif not invalid and stateSet: vehicle.clearCustomState() changed = invalid != stateSet return changed def __clearCustomVehicleStates(self): vehicles = self.itemsCache.items.getVehicles(REQ_CRITERIA.INVENTORY) updatedVehicles = [] for intCD, v in vehicles.iteritems(): if v.isCustomStateSet(): v.clearCustomState() updatedVehicles.append(intCD) if updatedVehicles: g_prbCtrlEvents.onVehicleClientStateChanged(updatedVehicles) def __resourceSplitter(self, resourceStr): resourceList = resourceStr.split('/') if not resourceList: return None else: current = R.strings.dialogs.dyn(resourceList[0]) i = 1 while i < len(resourceList): current = current.dyn(resourceList[i]) i += 1 return current @th_async def __showDefaultDialog(self, meta, callback, parent=None): from gui.shared.event_dispatcher import showDynamicButtonInfoDialogBuilder key = meta.getKey() res = self.__resourceSplitter(key) if res: app = self.__appLoader.getApp() if parent is None: parent = app.containerManager.getViewByKey(ViewKey(VIEW_ALIAS.LOBBY)) result = yield th_await(showDynamicButtonInfoDialogBuilder(res, None, '', parent)) callback(result) return
1
0.894959
1
0.894959
game-dev
MEDIA
0.82828
game-dev
0.959138
1
0.959138
AlanMorel/MapleServer2
4,514
MapleServer2/Types/ItemStats/StaticStats.cs
using Maple2Storage.Enums; using Maple2Storage.Types.Metadata; using MapleServer2.Data.Static; using MapleServer2.Tools; using MoonSharp.Interpreter; namespace MapleServer2.Types; public static class StaticStats { public static void GetStats(Item item, int optionId, float optionLevelFactor, out Dictionary<StatAttribute, ItemStat> staticStats) { staticStats = new(); if (optionLevelFactor < 50) { return; } int staticId = ItemMetadataStorage.GetOptionMetadata(item.Id).Static; ItemOptionsStatic staticOptions = ItemOptionStaticMetadataStorage.GetMetadata(staticId, item.Rarity); if (staticOptions == null) { GetDefault(item, staticStats, optionId, optionLevelFactor); return; } foreach (ParserStat stat in staticOptions.Stats) { staticStats[stat.Attribute] = new BasicStat(stat); } foreach (ParserSpecialStat stat in staticOptions.SpecialStats) { staticStats[stat.Attribute] = new SpecialStat(stat); } // TODO: Implement Hidden ndd (defense) and wapmax (Max Weapon Attack) GetDefault(item, staticStats, optionId, optionLevelFactor); } private static void GetDefault(Item item, Dictionary<StatAttribute, ItemStat> stats, int optionId, float optionLevelFactor) { ItemOptionPick baseOptions = ItemOptionPickMetadataStorage.GetMetadata(optionId, item.Rarity); if (baseOptions is null) { return; } Script script = ScriptLoader.GetScript("Functions/calcItemValues"); foreach (StaticPick staticPickFlat in baseOptions.StaticValues) { SetStat(stats, staticPickFlat, item, script, optionLevelFactor); } foreach (StaticPick staticPickRate in baseOptions.StaticRates) { SetStat(stats, staticPickRate, item, script, optionLevelFactor); } } private static void SetStat(Dictionary<StatAttribute, ItemStat> stats, StaticPick staticPick, Item item, Script script, float optionLevelFactor) { if (!stats.ContainsKey(staticPick.Stat)) { stats[staticPick.Stat] = new BasicStat(staticPick.Stat, 0, StatAttributeType.Flat); } float currentStatValue = stats[staticPick.Stat].GetValue(); double statValue = CalculateStat(item, optionLevelFactor, staticPick, script, currentStatValue); stats[staticPick.Stat].SetValue((float) statValue); if (stats[staticPick.Stat].GetValue() <= 0.0000f) { stats.Remove(staticPick.Stat); } } private static double CalculateStat(Item item, float optionLevelFactor, StaticPick staticPick, Script script, float currentStatValue) { Random random = Random.Shared; string calcScript; switch (staticPick.Stat) { case StatAttribute.Hp: calcScript = "static_value_hp"; break; case StatAttribute.Defense: // TODO: this is not calculating correctly calcScript = "static_value_ndd"; break; case StatAttribute.MagicRes: calcScript = "static_value_mar"; break; case StatAttribute.PhysicalRes: calcScript = "static_value_par"; break; case StatAttribute.PhysicalAtk: calcScript = "static_value_pap"; break; case StatAttribute.MagicAtk: calcScript = "static_value_map"; break; case StatAttribute.MaxWeaponAtk: calcScript = "static_value_wapmax"; break; case StatAttribute.PerfectGuard: calcScript = "static_rate_abp"; break; default: return 0; } DynValue result = script.RunFunction(calcScript, currentStatValue, staticPick.DeviationValue, (int) item.Type, (int) item.RecommendJobs.First(), optionLevelFactor, item.Rarity, item.Level); if (result.Tuple.Length < 2) { return 0; } if (result.Tuple[0].Number == 0 && result.Tuple[1].Number == 0) { return 0; } // Get random between min and max values return random.NextDouble() * (result.Tuple[1].Number - result.Tuple[0].Number) + result.Tuple[0].Number; } }
1
0.837104
1
0.837104
game-dev
MEDIA
0.257926
game-dev
0.917883
1
0.917883
Ravesli/OpenGL
3,480
Часть №04. Создание уровней в игре Breakout на C++ и OpenGL/Hello_Window/game.cpp
/******************************************************************* ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #include "game.h" #include "resource_manager.h" #include "sprite_renderer.h" #include "game_object.h" // Данные, относящиеся к состоянию игры SpriteRenderer* Renderer; GameObject* Player; Game::Game(unsigned int width, unsigned int height) : State(GAME_ACTIVE), Keys(), Width(width), Height(height) { } Game::~Game() { delete Renderer; delete Player; } void Game::Init() { // Загрузка шейдеров ResourceManager::LoadShader("../shaders/sprite.vs", "../shaders/sprite.frag", nullptr, "sprite"); // Конфигурирование шейдеров glm::mat4 projection = glm::ortho(0.0f, static_cast<float>(this->Width), static_cast<float>(this->Height), 0.0f, -1.0f, 1.0f); ResourceManager::GetShader("sprite").Use().SetInteger("image", 0); ResourceManager::GetShader("sprite").SetMatrix4("projection", projection); // Установка специфичных для рендеринга элементов управления Renderer = new SpriteRenderer(ResourceManager::GetShader("sprite")); // Загрузка текстур ResourceManager::LoadTexture("../textures/background.jpg", false, "background"); ResourceManager::LoadTexture("../textures/awesomeface.png", true, "face"); ResourceManager::LoadTexture("../textures/block.png", false, "block"); ResourceManager::LoadTexture("../textures/block_solid.png", false, "block_solid"); ResourceManager::LoadTexture("../textures/paddle.png", true, "paddle"); // Загрузка уровней GameLevel one; one.Load("../levels/one.lvl", this->Width, this->Height / 2); GameLevel two; two.Load("../levels/two.lvl", this->Width, this->Height / 2); GameLevel three; three.Load("../levels/three.lvl", this->Width, this->Height / 2); GameLevel four; four.Load("../levels/four.lvl", this->Width, this->Height / 2); this->Levels.push_back(one); this->Levels.push_back(two); this->Levels.push_back(three); this->Levels.push_back(four); this->Level = 0; // Конфигурирование игровых объектов glm::vec2 playerPos = glm::vec2(this->Width / 2.0f - PLAYER_SIZE.x / 2.0f, this->Height - PLAYER_SIZE.y); Player = new GameObject(playerPos, PLAYER_SIZE, ResourceManager::GetTexture("paddle")); } void Game::Update(float dt) { } void Game::ProcessInput(float dt) { if (this->State == GAME_ACTIVE) { float velocity = PLAYER_VELOCITY * dt; // Перемещение ракетки if (this->Keys[GLFW_KEY_A]) { if (Player->Position.x >= 0.0f) Player->Position.x -= velocity; } if (this->Keys[GLFW_KEY_D]) { if (Player->Position.x <= this->Width - Player->Size.x) Player->Position.x += velocity; } } } void Game::Render() { if (this->State == GAME_ACTIVE) { // Отрисовка фона Renderer->DrawSprite(ResourceManager::GetTexture("background"), glm::vec2(0.0f, 0.0f), glm::vec2(this->Width, this->Height), 0.0f); // Отрисовка уровня this->Levels[this->Level].Draw(*Renderer); // Отрисовка ракетки Player->Draw(*Renderer); } }
1
0.798546
1
0.798546
game-dev
MEDIA
0.832747
game-dev,graphics-rendering
0.993936
1
0.993936
Sigma-Skidder-Team/SigmaRemap
1,593
src/main/java/mapped/Class2678.java
package mapped; import net.minecraft.util.math.BlockPos; import java.util.EnumSet; public class Class2678 extends Class2595 { private static String[] field17073; public final VexEntity field17074; public Class2678(VexEntity var1) { this.field17074 = var1; this.method10809(EnumSet.<Class2240>of(Class2240.field14657)); } @Override public boolean method10803() { return !this.field17074.method4228().method20811() && VexEntity.method5283(this.field17074).nextInt(7) == 0; } @Override public boolean method10806() { return false; } @Override public void method10805() { BlockPos var3 = this.field17074.method5271(); if (var3 == null) { var3 = this.field17074.getPosition(); } for (int var4 = 0; var4 < 3; var4++) { BlockPos var5 = var3.add( VexEntity.method5284(this.field17074).nextInt(15) - 7, VexEntity.method5285(this.field17074).nextInt(11) - 5, VexEntity.method5286(this.field17074).nextInt(15) - 7 ); if (this.field17074.world.method7007(var5)) { VexEntity.method5287(this.field17074) .method20813((double)var5.getX() + 0.5, (double)var5.getY() + 0.5, (double)var5.getZ() + 0.5, 0.25); if (this.field17074.getAttackTarget() == null) { this.field17074 .method4227() .method28042((double)var5.getX() + 0.5, (double)var5.getY() + 0.5, (double)var5.getZ() + 0.5, 180.0F, 20.0F); } break; } } } }
1
0.548999
1
0.548999
game-dev
MEDIA
0.28277
game-dev
0.629655
1
0.629655
CloudburstMC/Nukkit
5,273
src/main/java/cn/nukkit/blockentity/BlockEntitySmoker.java
package cn.nukkit.blockentity; import cn.nukkit.block.Block; import cn.nukkit.block.BlockID; import cn.nukkit.event.inventory.FurnaceSmeltEvent; import cn.nukkit.inventory.FurnaceRecipe; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.LevelSoundEventPacket; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import java.util.concurrent.ThreadLocalRandom; public class BlockEntitySmoker extends BlockEntityFurnace { public BlockEntitySmoker(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override public String getName() { return this.hasName() ? this.namedTag.getString("CustomName") : "Smoker"; } @Override public boolean isBlockEntityValid() { int blockID = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); return blockID == Block.SMOKER || blockID == Block.LIT_SMOKER; } private static final IntSet CAN_SMELT = new IntOpenHashSet(new int[]{ Item.RAW_PORKCHOP, Item.RAW_BEEF, Item.RAW_RABBIT, Item.RAW_FISH, Item.RAW_CHICKEN, Item.RAW_MUTTON, Item.RAW_SALMON, Item.POTATO }); @Override public boolean onUpdate() { if (this.closed) { return false; } Item raw = this.inventory.getSmelting(); // TODO: smoker recipes if (!CAN_SMELT.contains(raw.getId())) { if (burnTime > 0) { burnTime--; burnDuration = (int) Math.ceil((float) burnTime / maxTime * 100); if (burnTime == 0) { Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); if (block.getId() == BlockID.LIT_SMOKER) { this.level.setBlock(this, Block.get(BlockID.SMOKER, block.getDamage()), true); } return false; } } cookTime = 0; sendPacket(); return true; } boolean ret = false; Item product = this.inventory.getResult(); FurnaceRecipe smelt = this.server.getCraftingManager().matchFurnaceRecipe(raw); boolean canSmelt = (smelt != null && raw.getCount() > 0 && ((smelt.getResult().equals(product) && product.getCount() < product.getMaxStackSize()) || product.getId() == Item.AIR)); Item fuel; if (burnTime <= 0 && canSmelt && (fuel = this.inventory.getItemFast(1)).getFuelTime() != null && fuel.getCount() > 0) { this.checkFuel(fuel.clone()); } if (burnTime > 0) { burnTime--; burnDuration = (int) Math.ceil((float) burnTime / maxTime * 100); if (this.crackledTime-- <= 0) { this.crackledTime = ThreadLocalRandom.current().nextInt(30, 110); this.getLevel().addLevelSoundEvent(this.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_BLOCK_FURNACE_LIT); } if (smelt != null && canSmelt) { cookTime++; if (cookTime >= 100) { product = Item.get(smelt.getResult().getId(), smelt.getResult().getDamage(), product.isNull() ? 1 : product.getCount() + 1); FurnaceSmeltEvent ev = new FurnaceSmeltEvent(this, raw, product); this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.inventory.setResult(ev.getResult()); this.experience += FURNACE_XP.getOrDefault(ev.getResult().getId(), 0d); raw.setCount(raw.getCount() - 1); if (raw.getCount() == 0) { raw = new ItemBlock(Block.get(BlockID.AIR), 0, 0); } this.inventory.setSmelting(raw); } cookTime -= 100; } } else if (burnTime <= 0) { burnTime = 0; cookTime = 0; burnDuration = 0; } else { cookTime = 0; } ret = true; } else { Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); if (block.getId() == BlockID.LIT_SMOKER) { this.level.setBlock(this, Block.get(BlockID.SMOKER, block.getDamage()), true); } burnTime = 0; cookTime = 0; burnDuration = 0; crackledTime = 0; } sendPacket(); return ret; } @Override public CompoundTag getSpawnCompound() { CompoundTag c = new CompoundTag() .putString("id", BlockEntity.SMOKER) .putInt("x", (int) this.x) .putInt("y", (int) this.y) .putInt("z", (int) this.z) .putShort("BurnDuration", burnDuration) .putShort("BurnTime", burnTime) .putShort("CookTime", cookTime); if (this.hasName()) { c.put("CustomName", this.namedTag.get("CustomName")); } return c; } }
1
0.841789
1
0.841789
game-dev
MEDIA
0.980795
game-dev
0.894768
1
0.894768
quaadgras/graphics.gd
7,840
classdb/AudioEffectBandPassFilter/class.go
// Code generated by the generate package DO NOT EDIT /* Attenuates the frequencies inside of a range around the [AudioEffectFilter.CutoffHz] and cuts frequencies outside of this band. [AudioEffectFilter.CutoffHz]: https://pkg.go.dev/graphics.gd/classdb/AudioEffectFilter#Instance.CutoffHz */ package AudioEffectBandPassFilter import "reflect" import "slices" import "graphics.gd/internal/pointers" import "graphics.gd/internal/callframe" import "graphics.gd/internal/gdextension" import "graphics.gd/internal/noescape" import gd "graphics.gd/internal" import "graphics.gd/internal/gdclass" import "graphics.gd/variant" import "graphics.gd/variant/Angle" import "graphics.gd/variant/Euler" import "graphics.gd/variant/Signal" import "graphics.gd/classdb/AudioEffect" import "graphics.gd/classdb/AudioEffectFilter" import "graphics.gd/classdb/Resource" import "graphics.gd/variant/Array" import "graphics.gd/variant/Callable" import "graphics.gd/variant/Dictionary" import "graphics.gd/variant/Error" import "graphics.gd/variant/Float" import "graphics.gd/variant/Object" import "graphics.gd/variant/Packed" import "graphics.gd/variant/Path" import "graphics.gd/variant/RID" import "graphics.gd/variant/RefCounted" import "graphics.gd/variant/String" var _ Object.ID type _ gdclass.Node var _ gd.Object var _ RefCounted.Instance var _ reflect.Type var _ callframe.Frame var _ = pointers.Cycle var _ = Array.Nil var _ variant.Any var _ Callable.Function var _ Dictionary.Any var _ RID.Any var _ noescape.Variant var _ String.Readable var _ Path.ToNode var _ Packed.Bytes var _ Error.Code var _ Float.X var _ Signal.Any var _ Angle.Radians var _ Euler.Radians var _ gdextension.Object var _ = slices.Delete[[]struct{}, struct{}] /* ID is a typed object ID (reference) to an instance of this class, use it to store references to objects with unknown lifetimes, as an ID will not panic on use if the underlying object has been destroyed. */ type ID Object.ID func (id ID) Instance() (Instance, bool) { return Object.As[Instance](Object.ID(id).Instance()) } /* Extension can be embedded in a new struct to create a Go extension of this class. T must be a type that is embedding this [Extension] as the first field. It is unsafe and invalid to use this type directly, or embedded in any other way. */ type Extension[T gdclass.Interface] struct{ gdclass.Extension[T, Instance] } /* Singleton can be embedded in a new struct to create a Go singleton extension of the class. It will become available as a global inside scripts and any any other Go Extension types will have any *T fields filled in to point at this singleton once they have been instantiated. T must be a type that is embedding this [Singleton] as the first field. It is unsafe and invalid to use this type directly, or embedded in any other way. */ type Singleton[T gdclass.Interface] = Extension[T] // Instance of the class with convieniently typed arguments and results. type Instance [1]gdclass.AudioEffectBandPassFilter var otype gdextension.ObjectType var sname gdextension.StringName var methods struct { } func init() { gd.Links = append(gd.Links, func() { sname = gdextension.Host.Strings.Intern.UTF8("AudioEffectBandPassFilter") otype = gdextension.Host.Objects.Type(sname) gd.LinkMethods(sname, &methods, false) }) gd.RegisterCleanup(func() { noescape.Free(gdextension.TypeStringName, &sname) }) } func (self Instance) ID() ID { return ID(Object.Instance(self.AsObject()).ID()) } // Nil is a nil/null instance of the class. Equivalent to the zero value. var Nil Instance type Any interface { gd.IsClass AsAudioEffectBandPassFilter() Instance } // Advanced exposes a 1:1 low-level instance of the class, undocumented, for those who know what they are doing. type Advanced = class type class [1]gdclass.AudioEffectBandPassFilter func (self class) AsObject() [1]gd.Object { return self[0].AsObject() } func (self *class) SetObject(obj [1]gd.Object) bool { if gdextension.Host.Objects.Cast(gdextension.Object(pointers.Get(obj[0])[0]), otype) != 0 { self[0] = pointers.AsA[gdclass.AudioEffectBandPassFilter](obj[0]) return true } return false } func (self *Instance) SetObject(obj [1]gd.Object) bool { if gdextension.Host.Objects.Cast(gdextension.Object(pointers.Get(obj[0])[0]), otype) != 0 { self[0] = pointers.AsA[gdclass.AudioEffectBandPassFilter](obj[0]) return true } return false } func (self Instance) AsObject() [1]gd.Object { return self[0].AsObject() } func (self *Extension[T]) AsObject() [1]gd.Object { return self.Super().AsObject() } func New() Instance { if !gd.Linked { var placeholder = Instance([1]gdclass.AudioEffectBandPassFilter{pointers.Add[gdclass.AudioEffectBandPassFilter]([3]uint64{})}) gd.StartupFunctions = append(gd.StartupFunctions, func() { if gd.Linked { raw, _ := pointers.End(New().AsObject()[0]) pointers.Set(pointers.AsA[gd.Object](placeholder[0]), raw) gd.RegisterCleanup(func() { if raw := pointers.Get[gd.Object](placeholder.AsObject()[0]); raw[0] != 0 && raw[1] == 0 { gdextension.Host.Objects.Unsafe.Free(gdextension.Object(raw[0])) } }) } }) return placeholder } casted := Instance([1]gdclass.AudioEffectBandPassFilter{pointers.New[gdclass.AudioEffectBandPassFilter]([3]uint64{uint64(gdextension.Host.Objects.Make(sname))})}) casted.AsRefCounted()[0].InitRef() casted.AsObject()[0].Notification(0, false) return casted } func (self class) AsAudioEffectBandPassFilter() Advanced { return Advanced{pointers.AsA[gdclass.AudioEffectBandPassFilter](self[0])} } func (self Instance) AsAudioEffectBandPassFilter() Instance { return Instance{pointers.AsA[gdclass.AudioEffectBandPassFilter](self[0])} } func (self *Extension[T]) AsAudioEffectBandPassFilter() Instance { return self.Super().AsAudioEffectBandPassFilter() } func (self class) AsAudioEffectFilter() AudioEffectFilter.Advanced { return AudioEffectFilter.Advanced{pointers.AsA[gdclass.AudioEffectFilter](self[0])} } func (self *Extension[T]) AsAudioEffectFilter() AudioEffectFilter.Instance { return self.Super().AsAudioEffectFilter() } func (self Instance) AsAudioEffectFilter() AudioEffectFilter.Instance { return AudioEffectFilter.Instance{pointers.AsA[gdclass.AudioEffectFilter](self[0])} } func (self class) AsAudioEffect() AudioEffect.Advanced { return AudioEffect.Advanced{pointers.AsA[gdclass.AudioEffect](self[0])} } func (self *Extension[T]) AsAudioEffect() AudioEffect.Instance { return self.Super().AsAudioEffect() } func (self Instance) AsAudioEffect() AudioEffect.Instance { return AudioEffect.Instance{pointers.AsA[gdclass.AudioEffect](self[0])} } func (self class) AsResource() Resource.Advanced { return Resource.Advanced{pointers.AsA[gdclass.Resource](self[0])} } func (self *Extension[T]) AsResource() Resource.Instance { return self.Super().AsResource() } func (self Instance) AsResource() Resource.Instance { return Resource.Instance{pointers.AsA[gdclass.Resource](self[0])} } func (self class) AsRefCounted() [1]gd.RefCounted { return [1]gd.RefCounted{gd.RefCounted(pointers.AsA[gd.Object](self[0]))} } func (self *Extension[T]) AsRefCounted() [1]gd.RefCounted { return self.Super().AsRefCounted() } func (self Instance) AsRefCounted() [1]gd.RefCounted { return [1]gd.RefCounted{gd.RefCounted(pointers.AsA[gd.Object](self[0]))} } func (self class) Virtual(name string) reflect.Value { switch name { default: return gd.VirtualByName(AudioEffectFilter.Advanced(self.AsAudioEffectFilter()), name) } } func (self Instance) Virtual(name string) reflect.Value { switch name { default: return gd.VirtualByName(AudioEffectFilter.Instance(self.AsAudioEffectFilter()), name) } } func init() { gdclass.Register("AudioEffectBandPassFilter", func(ptr gd.Object) any { return Instance{pointers.AsA[gdclass.AudioEffectBandPassFilter](ptr)} }) }
1
0.827084
1
0.827084
game-dev
MEDIA
0.560445
game-dev
0.890366
1
0.890366
Skitttyy/shoreline-client
2,462
src/main/java/net/shoreline/client/impl/command/BindCommand.java
package net.shoreline.client.impl.command; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.minecraft.command.CommandSource; import net.shoreline.client.api.command.Command; import net.shoreline.client.api.command.ModuleArgumentType; import net.shoreline.client.api.module.Module; import net.shoreline.client.api.module.ToggleModule; import net.shoreline.client.util.KeyboardUtil; import net.shoreline.client.util.chat.ChatUtil; import org.lwjgl.glfw.GLFW; /** * @author linus * @since 1.0 */ public class BindCommand extends Command { /** * */ public BindCommand() { super("Bind", "Keybinds a module", literal("bind")); } @Override public void buildCommand(LiteralArgumentBuilder<CommandSource> builder) { builder.then(argument("module", ModuleArgumentType.module()) .then(argument("key", StringArgumentType.string()) .executes(c -> { Module module = ModuleArgumentType.getModule(c, "module"); if (module instanceof ToggleModule t) { final String key = StringArgumentType.getString(c, "key"); if (key == null) { ChatUtil.error("Invalid key!"); return 0; } int keycode = KeyboardUtil.getKeyCode(key); if (keycode == GLFW.GLFW_KEY_UNKNOWN) { ChatUtil.error("Failed to parse key!"); return 0; } t.keybind(keycode); ChatUtil.clientSendMessage("§7%s§f is now bound to §s%s", module.getName(), key.toUpperCase()); } return 1; })) .executes(c -> { ChatUtil.error("Must provide a module to keybind!"); return 1; })).executes(c -> { ChatUtil.error("Invalid usage! Usage: " + getUsage()); return 1; }); } }
1
0.883068
1
0.883068
game-dev
MEDIA
0.824209
game-dev
0.738292
1
0.738292
peterhaneve/ONIMods
8,991
FoodTooltip/FoodTooltipUtils.cs
/* * Copyright 2024 Peter Han * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using PeterHan.PLib.Core; using System; using System.Collections.Generic; using UnityEngine; using Klei.AI; using TimeSlice = GameUtil.TimeSlice; namespace PeterHan.FoodTooltip { /// <summary> /// Utility functions used in Food Supply Tooltips. /// </summary> internal static class FoodTooltipUtils { /// <summary> /// How many cycles are in the third line of the food consumption tooltips. /// </summary> private const int CYCLES_FOR_SUMMARY = 5; /// <summary> /// Adds the correct descriptors to a plant info screen. /// </summary> /// <param name="crop">The plant to query.</param> /// <param name="descriptors">The location where the descriptors should be placed.</param> internal static void AddCropDescriptors(Crop crop, IList<Descriptor> descriptors) { var db = Db.Get(); if (crop != null && crop.TryGetComponent(out Modifiers modifiers)) { var cropVal = crop.cropVal; float preModifiedAttributeValue = modifiers.GetPreModifiedAttributeValue( db.PlantAttributes.YieldAmount); var maturity = Db.Get().Amounts.Maturity.Lookup(crop); if (maturity != null) // Do not multiply by cropVal.numProduced, it is factored into YieldAmount CreateDescriptors(TagManager.Create(cropVal.cropId), descriptors, maturity.GetDelta() * preModifiedAttributeValue * Constants. SECONDS_PER_CYCLE / maturity.GetMax(), FoodDescriptorTexts.PLANTS); } } /// <summary> /// Adds the correct descriptors to a critter info screen. /// </summary> /// <param name="critter">The critter to query.</param> /// <param name="descriptors">The location where the descriptors should be placed.</param> internal static void AddCritterDescriptors(GameObject critter, IList<Descriptor> descriptors) { IDictionary<string, float> drops; // Check the meat it drops if (critter != null && critter.TryGetComponent(out Butcherable butcher) && (drops = butcher.drops).Count > 0) { GetEggsPerCycle(critter, out float replacement, out float noReplacement); // Find out what it drops when it dies - critters always die so the // no-replacement rate must be positive foreach (var pair in drops) CreateDescriptors(TagManager.Create(pair.Key), descriptors, pair.Value * noReplacement, FoodDescriptorTexts.CRITTERS); // How much omelette can the egg be made into? Babies are excluded here var fertDef = critter.GetDef<FertilityMonitor.Def>(); if (fertDef != null) CreateDescriptors(fertDef.eggPrefab, descriptors, replacement, FoodDescriptorTexts.CRITTERS); } } /// <summary> /// Creates the descriptors for the total kcal yield of each relevant product. /// </summary> /// <param name="drop">The item dropped that could be used in food.</param> /// <param name="descriptors">The location where the descriptors should be placed.</param> /// <param name="dropRate">The quantity dropped per cycle.</param> /// <param name="text">The text to be displayed.</param> private static void CreateDescriptors(Tag drop, ICollection<Descriptor> descriptors, float dropRate, FoodDescriptorText text) { if (text == null) throw new ArgumentNullException(nameof(text)); string dropName = drop.ProperName(); foreach (var food in FoodRecipeCache.Instance.Lookup(drop)) { string foodName = food.Result.ProperName(); if (dropRate > 0.0f) { // Determine total yield in kcal and convert to /cycle string perCycle = GameUtil.AddTimeSliceText(GameUtil.GetFormattedCalories( food.Calories * dropRate * food.Quantity), TimeSlice.PerCycle); descriptors.Add(new Descriptor(text.PerCycle.F(foodName, perCycle, dropName), text.PerCycleTooltip.F(foodName, perCycle, dropName))); } else descriptors.Add(new Descriptor(text.Stifled.F(foodName), text. StifledTooltip)); } } /// <summary> /// Creates the text which describes the calorie delta for one cycle. /// </summary> /// <param name="text">The description text.</param> /// <param name="produced">The kcal produced.</param> /// <param name="consumed">The kcal consumed.</param> /// <returns>The description text with the formatted kcal values substituted.</returns> private static string FormatDeltaTooltip(string text, float produced, float consumed) { return text.F(GameUtil.GetFormattedCalories(produced), GameUtil. GetFormattedCalories(consumed)); } /// <summary> /// Calculates how many calories were produced and consumed in the specified cycle. /// </summary> /// <param name="report">The report to analyze.</param> /// <param name="produced">The location where the produced kcal will be stored.</param> /// <param name="consumed">The location where the consumed kcal will be stored.</param> private static void GetCalorieDeltas(ReportManager.DailyReport report, out float produced, out float consumed) { ReportManager.ReportEntry entry; if ((entry = report?.GetEntry(ReportManager.ReportType.CaloriesCreated)) != null) { // Consumption is negative produced = entry.accPositive; consumed = -entry.accNegative; } else { produced = 0.0f; consumed = 0.0f; } } /// <summary> /// Gets the number of extra eggs, before and after replacement, that a critter can /// lay in its current state. /// </summary> /// <param name="obj">The critter to calculate.</param> /// <param name="noReplacement">The number of eggs laid before death without needing replacement.</param> /// <param name="replacement">The number of extra eggs after replacement laid before death.</param> private static void GetEggsPerCycle(GameObject obj, out float replacement, out float noReplacement) { var amounts = Db.Get().Amounts; var fertility = amounts.Fertility.Lookup(obj); var age = amounts.Age.Lookup(obj); float delta; // Get the reproduction rate and calculate eggs laid before dying // Age is in cycles if (fertility != null && age != null && (delta = fertility.GetDelta()) > 0.0f) { float maxAge = age.GetMax(), totalEggs = maxAge * delta * Constants. SECONDS_PER_CYCLE / fertility.GetMax(); // You cannot lay half an egg noReplacement = Mathf.Floor(totalEggs) / maxAge; replacement = Mathf.Floor(Mathf.Max(0.0f, totalEggs - 1.0f)) / maxAge; } else { replacement = 0.0f; noReplacement = 0.0f; } } /// <summary> /// Shows food consumption and production stats for the current cycle, last cycle, and /// last 5 cycle average. /// </summary> /// <param name="tooltip">The tool tip that should be appended.</param> /// <param name="style">The text style to use for display.</param> internal static void ShowFoodUseStats(ToolTip tooltip, TextStyleSetting style) { var reports = ReportManager.Instance; if (tooltip != null && reports != null) { GetCalorieDeltas(reports.TodaysReport, out float produced, out float consumed); tooltip.AddMultiStringTooltip(FormatDeltaTooltip(FoodTooltipStrings. FOOD_RATE_CURRENT, produced, consumed), style); // Returns null if not present GetCalorieDeltas(reports.YesterdaysReport, out produced, out consumed); tooltip.AddMultiStringTooltip(FormatDeltaTooltip(FoodTooltipStrings. FOOD_RATE_LAST1, produced, consumed), style); int days = 0, cycle = GameUtil.GetCurrentCycle(); float totalProduced = 0.0f, totalConsumed = 0.0f; // Last 5 cycles, arithmetic average foreach (var report in reports.reports) if (report.day >= cycle - CYCLES_FOR_SUMMARY) { GetCalorieDeltas(report, out produced, out consumed); totalProduced += produced; totalConsumed += consumed; days++; } // Do not divide by zero if (days == 0) days = 1; tooltip.AddMultiStringTooltip(FormatDeltaTooltip(FoodTooltipStrings. FOOD_RATE_LAST5, totalProduced / days, totalConsumed / days), style); } } } }
1
0.860851
1
0.860851
game-dev
MEDIA
0.537421
game-dev
0.884027
1
0.884027