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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tgstation/tgstation | 8,634 | code/modules/antagonists/wizard/equipment/spellbook_entries/perks.dm | #define SPELLBOOK_CATEGORY_PERKS "Perks"
/datum/spellbook_entry/perks
desc = "Main node of perks"
category = SPELLBOOK_CATEGORY_PERKS
refundable = FALSE // no refund
requires_wizard_garb = FALSE
/// Icon that will be shown on wizard hud when purchasing a perk.
var/hud_icon
/// Type path to perks hud.
var/atom/movable/screen/perk/hud_to_show = /atom/movable/screen/perk
/datum/spellbook_entry/perks/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
var/datum/antagonist/wizard/wizard_datum = user.mind.has_antag_datum(/datum/antagonist/wizard)
if(wizard_datum)
wizard_datum.perks += src
create_hud_icon(user, wizard_datum)
to_chat(user, span_notice("You got a new perk: [src.name]."))
log_purchase(user.key)
return TRUE
/datum/spellbook_entry/perks/proc/create_compact_button(mob/living/carbon/human/user, datum/antagonist/wizard/wizard_datum)
var/datum/hud/user_hud = user.hud_used
wizard_datum.compact_button = new /atom/movable/screen/perk/more(null, user_hud)
wizard_datum.compact_button.screen_loc = ui_perk_position(0)
user_hud.infodisplay += wizard_datum.compact_button
user_hud.show_hud(user_hud.hud_version)
/datum/spellbook_entry/perks/proc/create_hud_icon(mob/living/carbon/human/user, datum/antagonist/wizard/wizard_datum)
if(user.hud_used)
var/datum/hud/user_hud = user.hud_used
if(isnull(wizard_datum.compact_button))
create_compact_button(user, wizard_datum)
hud_to_show = new hud_to_show(null, user_hud)
hud_to_show.name = name
hud_to_show.icon_state = hud_icon
hud_to_show.screen_loc = ui_perk_position(wizard_datum.perks.len)
user_hud.infodisplay += hud_to_show
user_hud.show_hud(user_hud.hud_version)
wizard_datum.compact_button.perks_on_hud += hud_to_show
else
RegisterSignal(user, COMSIG_MOB_HUD_CREATED, wizard_datum, PROC_REF(on_hud_created))
/datum/spellbook_entry/perks/proc/on_hud_created(mob/living/carbon/human/user, datum/antagonist/wizard/wizard_datum)
SIGNAL_HANDLER
create_hud_icon(user, wizard_datum)
/datum/spellbook_entry/perks/fourhands
name = "Four Hands"
desc = "Gives you even more hands to perform magic"
hud_icon = "fourhands"
/datum/spellbook_entry/perks/fourhands/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
user.change_number_of_hands(4)
/datum/spellbook_entry/perks/wormborn
name = "Worm Born"
desc = "Your soul is infested with mana worms. When you die, you will be reborn as a large worm. \
When the worm dies, it has no such luck. Parasitic infection prevents you from binding your soul to objects."
hud_icon = "wormborn"
no_coexistence_typecache = list(/datum/action/cooldown/spell/lichdom)
/datum/spellbook_entry/perks/wormborn/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
user.AddComponent(/datum/component/wormborn)
/datum/spellbook_entry/perks/dejavu
name = "Déjà vu"
desc = "Every 60 seconds returns you to the place where you were 60 seconds ago with the same amount of health as you had 60 seconds ago."
hud_icon = "dejavu"
/datum/spellbook_entry/perks/dejavu/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
RegisterSignal(user, COMSIG_ENTER_AREA, PROC_REF(give_dejavu))
/datum/spellbook_entry/perks/dejavu/proc/give_dejavu(mob/living/carbon/human/wizard, area/new_area)
SIGNAL_HANDLER
if(istype(new_area, /area/centcom))
return
wizard.AddComponent(/datum/component/dejavu/wizard, 1, 60 SECONDS, TRUE)
UnregisterSignal(wizard, COMSIG_ENTER_AREA)
/datum/spellbook_entry/perks/spell_lottery
name = "Spells Lottery"
desc = "Spells Lottery gives you the chance to get something from the book absolutely free, but you can no longer refund any purchases."
hud_icon = "spellottery"
/datum/spellbook_entry/perks/spell_lottery/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
ADD_TRAIT(user, TRAIT_SPELLS_LOTTERY, REF(src))
/datum/spellbook_entry/perks/gamble
name = "Gamble"
desc = "You get 2 random perks."
hud_icon = "gamble"
/datum/spellbook_entry/perks/gamble/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
var/datum/antagonist/wizard/check_perks = user.mind.has_antag_datum(/datum/antagonist/wizard)
var/perks_allocated = 0
var/list/taking_perks = list()
for(var/datum/spellbook_entry/perks/generate_perk in book.entries)
if(istype(generate_perk, src))
continue
if(check_perks && is_type_in_list(generate_perk, check_perks.perks))
continue
taking_perks += generate_perk
perks_allocated++
if(perks_allocated >= 2)
break
if(taking_perks.len < 1)
to_chat(user, span_warning("Gamble cannot give 2 perks, so points are returned"))
return FALSE
taking_perks = shuffle(taking_perks)
for(var/datum/spellbook_entry/perks/perks_ready in taking_perks)
perks_ready.buy_spell(user, book, log_buy)
/datum/spellbook_entry/perks/heart_eater
name = "Heart Eater"
desc = "Gives you ability to obtain a person's life force by eating their heart. \
By eating someone's heart you can increase your damage resistance or gain random mutation. \
Heart also give strong healing buff."
hud_icon = "hearteater"
/datum/spellbook_entry/perks/heart_eater/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
user.AddComponent(/datum/component/heart_eater)
/datum/spellbook_entry/perks/slime_friends
name = "Slime Friends"
desc = "Slimes are your friends. \
Every 15 seconds you lose some nutriments and summon a random evil slime to fight on your side."
hud_icon = "slimefriends"
/datum/spellbook_entry/perks/slime_friends/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
user.AddComponent(/datum/component/slime_friends)
/datum/spellbook_entry/perks/transparence
name = "Transparence"
desc = "You become a little closer to the world of the dead. \
Projectiles pass through you, but you lose 25% of your health and you are hunted by a terrible curse which wants to return you to the afterlife."
hud_icon = "transparence"
/datum/spellbook_entry/perks/transparence/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
user.maxHealth *= 0.75
user.alpha = 125
ADD_TRAIT(user, TRAIT_UNHITTABLE_BY_PROJECTILES, REF(src))
RegisterSignal(user, COMSIG_ENTER_AREA, PROC_REF(make_stalker))
/datum/spellbook_entry/perks/transparence/proc/make_stalker(mob/living/carbon/human/wizard, area/new_area)
SIGNAL_HANDLER
if(new_area == GLOB.areas_by_type[/area/centcom/wizard_station])
return
wizard.gain_trauma(/datum/brain_trauma/magic/stalker)
UnregisterSignal(wizard, COMSIG_ENTER_AREA)
/datum/spellbook_entry/perks/magnetism
name = "Magnetism"
desc = "You get a small gravity anomaly that orbit around you. \
Nearby things will be attracted to you."
hud_icon = "magnetism"
/datum/spellbook_entry/perks/magnetism/buy_spell(mob/living/carbon/human/user, obj/item/spellbook/book, log_buy)
. = ..()
var/atom/movable/magnitizm = new /obj/effect/wizard_magnetism(get_turf(user))
magnitizm.orbit(user, 20)
/obj/effect/wizard_magnetism
name = "magnetic anomaly"
icon = 'icons/effects/effects.dmi'
icon_state = "shield2"
/// We need to orbit around someone.
var/datum/weakref/owner
/obj/effect/wizard_magnetism/New(loc, ...)
. = ..()
transform *= 0.4
/obj/effect/wizard_magnetism/orbit(atom/new_owner, radius, clockwise, rotation_speed, rotation_segments, pre_rotation)
. = ..()
if(!isliving(new_owner))
return
owner = WEAKREF(new_owner)
RegisterSignal(new_owner, COMSIG_ENTER_AREA, PROC_REF(check_area))
RegisterSignal(new_owner, COMSIG_LIVING_DEATH, PROC_REF(on_owner_death))
/obj/effect/wizard_magnetism/proc/check_area(mob/living/wizard, area/new_area)
SIGNAL_HANDLER
if(new_area == GLOB.areas_by_type[/area/centcom/wizard_station])
return
START_PROCESSING(SSprocessing, src)
UnregisterSignal(wizard, COMSIG_ENTER_AREA)
/obj/effect/wizard_magnetism/proc/on_owner_death()
SIGNAL_HANDLER
stop_orbit()
/obj/effect/wizard_magnetism/process(seconds_per_tick)
if(isnull(owner))
stop_orbit()
return
var/mob/living/wizard = owner.resolve()
var/list/things_in_range = orange(5, wizard) - orange(1, wizard)
for(var/obj/take_object in things_in_range)
if(!take_object.anchored)
step_towards(take_object, wizard)
for(var/mob/living/living_mov in things_in_range)
if(wizard)
if(living_mov == wizard)
continue
if(!living_mov.mob_negates_gravity())
step_towards(living_mov, wizard)
/obj/effect/wizard_magnetism/stop_orbit()
STOP_PROCESSING(SSprocessing, src)
qdel(src)
#undef SPELLBOOK_CATEGORY_PERKS
| 412 | 0.838058 | 1 | 0.838058 | game-dev | MEDIA | 0.837981 | game-dev,desktop-app | 0.953515 | 1 | 0.953515 |
Praytic/youtd2 | 1,232 | src/actions/action.gd | class_name Action
# Wraps Dictionary which needs to be passed through RPC.
# Need to pass Dictionaries through RPC because Godot RPC
# doesn't support passing custom classes.
#
# Parameters -> Action:
# var action: Action = ActionFoo.make(bar, baz)
#
# Action -> Dictionary:
# var serialized_action: Dictionary = action.serialize()
enum Field {
TYPE,
PLAYER_ID,
CHAT_MESSAGE,
TOWER_ID,
POSITION,
UID,
UID_2,
UID_LIST,
BUILDER_ID,
SRC_ITEM_CONTAINER_UID,
DEST_ITEM_CONTAINER_UID,
CLICKED_INDEX,
BUFFGROUP,
BUFFGROUP_MODE,
ELEMENT,
WISDOM_UPGRADES,
}
enum Type {
NONE,
IDLE,
CHAT,
SET_PLAYER_NAME,
BUILD_TOWER,
UPGRADE_TOWER,
TRANSFORM_TOWER,
SELL_TOWER,
SELECT_BUILDER,
SELECT_WISDOM_UPGRADES,
TOGGLE_AUTOCAST,
CONSUME_ITEM,
DROP_ITEM,
MOVE_ITEM,
SWAP_ITEMS,
AUTOFILL,
TRANSMUTE,
RESEARCH_ELEMENT,
ROLL_TOWERS,
START_NEXT_WAVE,
AUTOCAST,
FOCUS_TARGET,
CHANGE_BUFFGROUP,
SELECT_UNIT,
SORT_ITEM_STASH,
}
var _data: Dictionary
#########################
### Built-in ###
#########################
func _init(data: Dictionary):
_data = data
#########################
### Public ###
#########################
func serialize() -> Dictionary:
return _data
| 412 | 0.780831 | 1 | 0.780831 | game-dev | MEDIA | 0.607607 | game-dev | 0.796369 | 1 | 0.796369 |
webbukkit/dynmap | 2,445 | spigot/src/main/java/org/dynmap/bukkit/permissions/NijikokunPermissions.java | package org.dynmap.bukkit.permissions;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.dynmap.Log;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
public class NijikokunPermissions implements PermissionProvider {
String name;
PermissionHandler permissions;
Plugin plugin;
String defworld;
public static NijikokunPermissions create(Server server, String name) {
Plugin permissionsPlugin = server.getPluginManager().getPlugin("Permissions");
if (permissionsPlugin == null)
return null;
server.getPluginManager().enablePlugin(permissionsPlugin);
if(permissionsPlugin.isEnabled() == false)
return null;
Log.info("Using Permissions " + permissionsPlugin.getDescription().getVersion() + " for access control");
return new NijikokunPermissions(permissionsPlugin, name);
}
public NijikokunPermissions(Plugin permissionsPlugin, String name) {
this.name = name;
plugin = permissionsPlugin;
defworld = Bukkit.getServer().getWorlds().get(0).getName();
}
@Override
public boolean has(CommandSender sender, String permission) {
if(permissions == null)
permissions = ((Permissions)plugin).getHandler();
Player player = sender instanceof Player ? (Player) sender : null;
return player != null
? permissions.has(player, name + "." + permission) || permissions.has(player, name + ".*")
: true;
}
@Override
public Set<String> hasOfflinePermissions(String player, Set<String> perms) {
if(permissions == null)
permissions = ((Permissions)plugin).getHandler();
HashSet<String> hasperms = new HashSet<String>();
for (String pp : perms) {
if (permissions.has(defworld, player, name + "." + pp)) {
hasperms.add(pp);
}
}
return hasperms;
}
@Override
public boolean hasOfflinePermission(String player, String perm) {
if(permissions == null)
permissions = ((Permissions)plugin).getHandler();
return permissions.has(defworld, player, name + "." + perm);
}
}
| 412 | 0.731129 | 1 | 0.731129 | game-dev | MEDIA | 0.583392 | game-dev | 0.674831 | 1 | 0.674831 |
SinlessDevil/VisionFieldMesh | 6,493 | Assets/Plugins/Zenject/Source/Binding/Binders/Factory/FactoryFromBinder/FactoryFromBinder1.cs | using System;
using System.Collections.Generic;
#if !NOT_UNITY3D
using UnityEngine;
#endif
using ModestTree;
namespace Zenject
{
[NoReflectionBaking]
public class FactoryFromBinder<TParam1, TContract> : FactoryFromBinderBase
{
public FactoryFromBinder(
DiContainer container, BindInfo bindInfo, FactoryBindInfo factoryBindInfo)
: base(container, typeof(TContract), bindInfo, factoryBindInfo)
{
}
public ConditionCopyNonLazyBinder FromMethod(Func<DiContainer, TParam1, TContract> method)
{
ProviderFunc =
(container) => new MethodProviderWithContainer<TParam1, TContract>(method);
return this;
}
// Shortcut for FromIFactory and also for backwards compatibility
public ConditionCopyNonLazyBinder FromFactory<TSubFactory>()
where TSubFactory : IFactory<TParam1, TContract>
{
return this.FromIFactory(x => x.To<TSubFactory>().AsCached());
}
public FactorySubContainerBinder<TParam1, TContract> FromSubContainerResolve()
{
return FromSubContainerResolve(null);
}
public FactorySubContainerBinder<TParam1, TContract> FromSubContainerResolve(object subIdentifier)
{
return new FactorySubContainerBinder<TParam1, TContract>(
BindContainer, BindInfo, FactoryBindInfo, subIdentifier);
}
}
// These methods have to be extension methods for the UWP build (with .NET backend) to work correctly
// When these are instance methods it takes a really long time then fails with StackOverflowException
public static class FactoryFromBinder1Extensions
{
public static ArgConditionCopyNonLazyBinder FromIFactory<TParam1, TContract>(
this FactoryFromBinder<TParam1, TContract> fromBinder,
Action<ConcreteBinderGeneric<IFactory<TParam1, TContract>>> factoryBindGenerator)
{
Guid factoryId;
factoryBindGenerator(
fromBinder.CreateIFactoryBinder<IFactory<TParam1, TContract>>(out factoryId));
fromBinder.ProviderFunc =
(container) => { return new IFactoryProvider<TParam1, TContract>(container, factoryId); };
return new ArgConditionCopyNonLazyBinder(fromBinder.BindInfo);
}
public static ArgConditionCopyNonLazyBinder FromPoolableMemoryPool<TParam1, TContract>(
this FactoryFromBinder<TParam1, TContract> fromBinder)
// Unfortunately we have to pass the same contract in again to satisfy the generic
// constraints below
where TContract : IPoolable<TParam1, IMemoryPool>
{
return fromBinder.FromPoolableMemoryPool<TParam1, TContract>(x => {});
}
public static ArgConditionCopyNonLazyBinder FromPoolableMemoryPool<TParam1, TContract>(
this FactoryFromBinder<TParam1, TContract> fromBinder,
Action<MemoryPoolInitialSizeMaxSizeBinder<TContract>> poolBindGenerator)
// Unfortunately we have to pass the same contract in again to satisfy the generic
// constraints below
where TContract : IPoolable<TParam1, IMemoryPool>
{
return fromBinder.FromPoolableMemoryPool<TParam1, TContract, PoolableMemoryPool<TParam1, IMemoryPool, TContract>>(poolBindGenerator);
}
#if !NOT_UNITY3D
public static ArgConditionCopyNonLazyBinder FromMonoPoolableMemoryPool<TParam1, TContract>(
this FactoryFromBinder<TParam1, TContract> fromBinder)
// Unfortunately we have to pass the same contract in again to satisfy the generic
// constraints below
where TContract : Component, IPoolable<TParam1, IMemoryPool>
{
return fromBinder.FromMonoPoolableMemoryPool<TParam1, TContract>(x => {});
}
public static ArgConditionCopyNonLazyBinder FromMonoPoolableMemoryPool<TParam1, TContract>(
this FactoryFromBinder<TParam1, TContract> fromBinder,
Action<MemoryPoolInitialSizeMaxSizeBinder<TContract>> poolBindGenerator)
// Unfortunately we have to pass the same contract in again to satisfy the generic
// constraints below
where TContract : Component, IPoolable<TParam1, IMemoryPool>
{
return fromBinder.FromPoolableMemoryPool<TParam1, TContract, MonoPoolableMemoryPool<TParam1, IMemoryPool, TContract>>(poolBindGenerator);
}
#endif
public static ArgConditionCopyNonLazyBinder FromPoolableMemoryPool<TParam1, TContract, TMemoryPool>(
this FactoryFromBinder<TParam1, TContract> fromBinder)
// Unfortunately we have to pass the same contract in again to satisfy the generic
// constraints below
where TContract : IPoolable<TParam1, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, IMemoryPool, TContract>
{
return fromBinder.FromPoolableMemoryPool<TParam1, TContract, TMemoryPool>(x => {});
}
public static ArgConditionCopyNonLazyBinder FromPoolableMemoryPool<TParam1, TContract, TMemoryPool>(
this FactoryFromBinder<TParam1, TContract> fromBinder,
Action<MemoryPoolInitialSizeMaxSizeBinder<TContract>> poolBindGenerator)
// Unfortunately we have to pass the same contract in again to satisfy the generic
// constraints below
where TContract : IPoolable<TParam1, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, IMemoryPool, TContract>
{
// Use a random ID so that our provider is the only one that can find it and so it doesn't
// conflict with anything else
var poolId = Guid.NewGuid();
// Important to use NoFlush otherwise the binding will be finalized early
var binder = fromBinder.BindContainer.BindMemoryPoolCustomInterfaceNoFlush<TContract, TMemoryPool, TMemoryPool>().WithId(poolId);
// Always make it non lazy by default in case the user sets an InitialSize
binder.NonLazy();
poolBindGenerator(binder);
fromBinder.ProviderFunc =
(container) => { return new PoolableMemoryPoolProvider<TParam1, TContract, TMemoryPool>(container, poolId); };
return new ArgConditionCopyNonLazyBinder(fromBinder.BindInfo);
}
}
}
| 412 | 0.786946 | 1 | 0.786946 | game-dev | MEDIA | 0.796114 | game-dev | 0.59876 | 1 | 0.59876 |
SourceEngine-CommunityEdition/source | 4,138 | game/server/te_spritespray.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "basetempentity.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern short g_sModelIndexSmoke; // (in combatweapon.cpp) holds the index for the smoke cloud
//-----------------------------------------------------------------------------
// Purpose: Dispatches Sprite Spray tempentity
//-----------------------------------------------------------------------------
class CTESpriteSpray : public CBaseTempEntity
{
public:
DECLARE_CLASS( CTESpriteSpray, CBaseTempEntity );
CTESpriteSpray( const char *name );
virtual ~CTESpriteSpray( void );
virtual void Test( const Vector& current_origin, const QAngle& current_angles );
DECLARE_SERVERCLASS();
public:
CNetworkVector( m_vecOrigin );
CNetworkVector( m_vecDirection );
CNetworkVar( int, m_nModelIndex );
CNetworkVar( int, m_nSpeed );
CNetworkVar( float, m_fNoise );
CNetworkVar( int, m_nCount );
};
//-----------------------------------------------------------------------------
// Purpose:
// Input : *name -
//-----------------------------------------------------------------------------
CTESpriteSpray::CTESpriteSpray( const char *name ) :
CBaseTempEntity( name )
{
m_vecOrigin.Init();
m_vecDirection.Init();
m_nModelIndex = 0;
m_fNoise = 0;
m_nSpeed = 0;
m_nCount = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTESpriteSpray::~CTESpriteSpray( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *current_origin -
// *current_angles -
//-----------------------------------------------------------------------------
void CTESpriteSpray::Test( const Vector& current_origin, const QAngle& current_angles )
{
// Fill in data
m_nModelIndex = g_sModelIndexSmoke;
m_fNoise = 0.8;
m_nCount = 5;
m_nSpeed = 30;
m_vecOrigin = current_origin;
Vector forward, right;
m_vecOrigin.GetForModify()[2] += 24;
AngleVectors( current_angles, &forward, &right, NULL );
forward[2] = 0.0;
VectorNormalize( forward );
VectorMA( m_vecOrigin, 50.0, forward, m_vecOrigin.GetForModify() );
VectorMA( m_vecOrigin, -25.0, right, m_vecOrigin.GetForModify() );
m_vecDirection.Init( random->RandomInt( -100, 100 ), random->RandomInt( -100, 100 ), random->RandomInt( 0, 100 ) );
CBroadcastRecipientFilter filter;
Create( filter, 0.0 );
}
IMPLEMENT_SERVERCLASS_ST(CTESpriteSpray, DT_TESpriteSpray)
SendPropVector( SENDINFO(m_vecOrigin), -1, SPROP_COORD),
SendPropVector( SENDINFO(m_vecDirection), -1, SPROP_COORD),
SendPropModelIndex(SENDINFO(m_nModelIndex)),
SendPropFloat( SENDINFO(m_fNoise ), 8, SPROP_ROUNDDOWN, 0.0, 2.56 ),
SendPropInt( SENDINFO(m_nSpeed ), 8, SPROP_UNSIGNED ),
SendPropInt( SENDINFO(m_nCount), 8, SPROP_UNSIGNED ),
END_SEND_TABLE()
// Singleton to fire TESpriteSpray objects
static CTESpriteSpray g_TESpriteSpray( "Sprite Spray" );
//-----------------------------------------------------------------------------
// Purpose:
// Input : msg_dest -
// delay -
// *origin -
// *recipient -
// *pos -
// *dir -
// modelindex -
// speed -
// noise -
// count -
//-----------------------------------------------------------------------------
void TE_SpriteSpray( IRecipientFilter& filter, float delay,
const Vector *pos, const Vector *dir, int modelindex, int speed, float noise, int count )
{
g_TESpriteSpray.m_vecOrigin = *pos;
g_TESpriteSpray.m_vecDirection = *dir;
g_TESpriteSpray.m_nModelIndex = modelindex;
g_TESpriteSpray.m_nSpeed = speed;
g_TESpriteSpray.m_fNoise = noise;
g_TESpriteSpray.m_nCount = count;
// Send it over the wire
g_TESpriteSpray.Create( filter, delay );
} | 412 | 0.632512 | 1 | 0.632512 | game-dev | MEDIA | 0.75939 | game-dev,networking | 0.604576 | 1 | 0.604576 |
Sunchit/Coding-Decoded | 1,717 | Leetcode2023/January2023/Java/LFUCache.java | class LFUCache {
private int cap;
// Key , Value
private int min = 1;
Map<Integer,Integer> keyValueMap = new HashMap<>();
// Key , keyFrequencyMap
Map<Integer,Integer> keyFrequencyMap = new HashMap<>();
// keyFrequencyMap, Set of keys in ordered format
// Why ordered so that in case of collision least recently used is keyToBeEvicteded
Map<Integer,LinkedHashSet<Integer>> freqKeysMap = new HashMap<>();
public LFUCache(int capacity) {
cap = capacity;
freqKeysMap.put(1,new LinkedHashSet<>());
}
// O(1)
public int get(int key) {
if(!keyValueMap.containsKey(key)) {
return -1;
}
int frequency = keyFrequencyMap.get(key);
// remove the key from the previous frequency
freqKeysMap.get(frequency).remove(key);
if(frequency==min && freqKeysMap.get(frequency).size()==0) {
min++;
}
if(!freqKeysMap.containsKey(frequency+1)) {
freqKeysMap.put(frequency + 1, new LinkedHashSet<>());
}
// add the key corresponding to freq+1
freqKeysMap.get(frequency+1).add(key);
// increment the frequency by one for the current key
keyFrequencyMap.put(key,frequency+1);
return keyValueMap.get(key);
}
// O(1)
public void put(int key, int value) {
if(cap<=0)
return;
if(keyValueMap.containsKey(key))
{
keyValueMap.put(key,value);
get(key);
return;
}
if(keyValueMap.size()>=cap)
{
int keyToBeEvicted = freqKeysMap.get(min).iterator().next();
freqKeysMap.get(min).remove(keyToBeEvicted);
keyValueMap.remove(keyToBeEvicted);
keyFrequencyMap.remove(keyToBeEvicted);
}
// key is not present in the KeyValueMap
keyValueMap.put(key,value);
keyFrequencyMap.put(key,1);
min = 1;
freqKeysMap.get(1).add(key);
}
}
| 412 | 0.628893 | 1 | 0.628893 | game-dev | MEDIA | 0.270133 | game-dev | 0.822806 | 1 | 0.822806 |
beratkirik/CPP-Programming-for-Financial-Engineering | 3,451 | Practice/Level8/Exercises/5.1/Exercise 2/Exercise 2/Array.cpp | //
// Array.cpp
// Exercise 2
//
// Created by Changheng Chen on 2/10/17.
// Copyright © 2017 Changheng Chen. All rights reserved.
//
#ifndef Array_CPP
#define Array_CPP
#include "SizeMismatchException.hpp"
#include "OutOfBoundsException.hpp"
#include "Array.hpp"
#include <iostream>
using namespace std;
namespace chako
{
namespace Containers
{
// =================================================================
// Static default size of array
template <typename T>
int Array<T>::d_size = 12;
// =================================================================
// Constructors, destructor, and assignment operator
template <typename T>
Array<T>::Array() : m_size(Array<T>::d_size), m_data(new T[Array<T>::d_size])
{ // Default constructor
//cout << "Array default constructor..." << endl;
}
template <typename T>
Array<T>::Array(int size) : m_size(size), m_data(new T[size])
{ // Constructor with size
//cout << "Array constructor with size..." << endl;
}
template <typename T>
Array<T>::Array(const Array<T>& source)
{ // Copy constructor
m_size = source.m_size;
m_data = new T[m_size];
for (int i = 0; i < m_size; i++)
m_data[i] = source.m_data[i];
//cout << "Array copy constructor..." << endl;
}
template <typename T>
Array<T>::~Array()
{ // Destructor
delete [] m_data;
//cout << "By my array..." << endl;
}
template <typename T>
Array<T>& Array<T>::operator = (const Array<T>& source)
{ // Assignment operator
if (this == &source)
return *this;
delete [] m_data;
m_size = source.m_size;
m_data = new T[m_size];
for (int i = 0; i < m_size; i++)
m_data[i] = source.m_data[i];
return *this;
}
// =================================================================
// Getter functions
template <typename T>
int Array<T>::Size() const
{
return m_size;
}
template <typename T>
int Array<T>::DefaultSize() const
{
return d_size;
}
template <typename T>
T& Array<T>::GetElement(int index) const
{
if (index >= m_size || index < 0)
throw OutOfBoundsException(index);
return m_data[index];
}
// Setter function
template <typename T>
void Array<T>::DefaultSize(int size)
{
d_size = size;
}
template <typename T>
void Array<T>::SetElement(int index, const T& p)
{
if (index >= m_size || index < 0)
throw OutOfBoundsException(index);
m_data[index] = p;
}
// Operator overloading
// const chako::T& Array<T>::operator [] (int index) const
template <typename T>
T& Array<T>::operator [] (int index)
{
if (index >= m_size || index < 0)
throw OutOfBoundsException(index);
return m_data[index];
}
}
}
#endif
| 412 | 0.882681 | 1 | 0.882681 | game-dev | MEDIA | 0.253329 | game-dev | 0.972454 | 1 | 0.972454 |
GarageGames/Torque3D | 7,666 | Engine/source/gui/editor/inspector/variableGroup.cpp | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "gui/editor/inspector/variableGroup.h"
#include "gui/editor/inspector/variableField.h"
#include "gui/editor/guiInspector.h"
#include "gui/buttons/guiIconButtonCtrl.h"
#include "console/consoleInternal.h"
extern ExprEvalState gEvalState;
//-----------------------------------------------------------------------------
// GuiInspectorVariableGroup
//-----------------------------------------------------------------------------
//
//
IMPLEMENT_CONOBJECT(GuiInspectorVariableGroup);
ConsoleDocClass( GuiInspectorVariableGroup,
"@brief Inspector support for variable groups in a GuiVariableInspector.\n\n"
"Editor use only.\n\n"
"@internal"
);
GuiInspectorVariableGroup::GuiInspectorVariableGroup()
{
}
GuiInspectorVariableGroup::~GuiInspectorVariableGroup()
{
}
GuiInspectorField* GuiInspectorVariableGroup::constructField( S32 fieldType )
{
return Parent::constructField(fieldType);
}
bool GuiInspectorVariableGroup::inspectGroup()
{
// to prevent crazy resizing, we'll just freeze our stack for a sec..
mStack->freeze(true);
bool bNewItems = false;
if (!mSearchString.equal(""))
{
Vector<String> names;
gEvalState.globalVars.exportVariables(mSearchString, &names, NULL);
for (U32 i = 0; i < names.size(); i++)
{
const String &varName = names[i];
// If the field already exists, just update it
GuiInspectorVariableField *field = dynamic_cast<GuiInspectorVariableField*>(findField(varName));
if (field != NULL)
{
field->updateValue();
continue;
}
bNewItems = true;
field = new GuiInspectorVariableField();
field->init(mParent, this);
field->setInspectorField(NULL, StringTable->insert(varName));
if (field->registerObject())
{
mChildren.push_back(field);
mStack->addObject(field);
}
else
delete field;
}
}
for (U32 i = 0; i < mFields.size(); i++)
{
bNewItems = true;
GuiInspectorField *fieldGui = findField(mFields[i]->mFieldName);
if (fieldGui != NULL)
{
fieldGui->updateValue();
continue;
}
//first and foremost, nab the field type and check if it's a custom field or not.
//If it's not a custom field, proceed below, if it is, hand it off to script to be handled by the component
if (mFields[i]->mFieldType == -1)
{
if (isMethod("onConstructField"))
{
//ensure our stack variable is bound if we need it
Con::evaluatef("%d.stack = %d;", this->getId(), mStack->getId());
Con::executef(this, "onConstructField", mFields[i]->mFieldName,
mFields[i]->mFieldLabel, mFields[i]->mFieldTypeName, mFields[i]->mFieldDescription,
mFields[i]->mDefaultValue, mFields[i]->mDataValues, mFields[i]->mOwnerObject);
}
continue;
}
bNewItems = true;
fieldGui = constructField(mFields[i]->mFieldType);
if (fieldGui == NULL)
fieldGui = new GuiInspectorField();
fieldGui->init(mParent, this);
fieldGui->setSpecialEditField(true);
if (mFields[i]->mOwnerObject)
{
fieldGui->setTargetObject(mFields[i]->mOwnerObject);
}
else
{
//check if we're binding to a global var first, if we have no owner
if (mFields[i]->mFieldName[0] != '$')
{
fieldGui->setTargetObject(mParent);
}
}
fieldGui->setSpecialEditVariableName(mFields[i]->mFieldName);
fieldGui->setSpecialEditCallbackName(mFields[i]->mSetCallbackName);
fieldGui->setInspectorField(NULL, mFields[i]->mFieldLabel);
fieldGui->setDocs(mFields[i]->mFieldDescription);
if(mFields[i]->mSetCallbackName != StringTable->EmptyString())
fieldGui->setSpecialEditCallbackName(mFields[i]->mSetCallbackName);
/*if (mFields[i]->mSetCallbackName != StringTable->EmptyString())
{
fieldGui->on.notify()
}*/
if (fieldGui->registerObject())
{
#ifdef DEBUG_SPEW
Platform::outputDebugString("[GuiInspectorVariableGroup] Adding field '%s'",
field->pFieldname);
#endif
if (mFields[i]->mOwnerObject)
{
String val = mFields[i]->mOwnerObject->getDataField(mFields[i]->mFieldName, NULL);
if(val.isEmpty())
fieldGui->setValue(mFields[i]->mDefaultValue);
else
fieldGui->setValue(val);
}
else
{
fieldGui->setValue(mFields[i]->mDefaultValue);
}
fieldGui->setActive(mFields[i]->mEnabled);
mChildren.push_back(fieldGui);
mStack->addObject(fieldGui);
}
else
{
SAFE_DELETE(fieldGui);
}
}
mStack->freeze(false);
mStack->updatePanes();
// If we've no new items, there's no need to resize anything!
if( bNewItems == false && !mChildren.empty() )
return true;
sizeToContents();
setUpdate();
return true;
}
void GuiInspectorVariableGroup::clearFields()
{
mFields.clear();
}
void GuiInspectorVariableGroup::addField(VariableField* field)
{
bool found = false;
for (U32 i = 0; i < mFields.size(); i++)
{
if (mFields[i]->mFieldName == field->mFieldName)
{
found = true;
break;
}
}
if(!found)
mFields.push_back(field);
}
void GuiInspectorVariableGroup::addInspectorField(GuiInspectorField* field)
{
mStack->addObject(field);
mChildren.push_back(field);
mStack->updatePanes();
}
GuiInspectorField* GuiInspectorVariableGroup::createInspectorField()
{
GuiInspectorField* newField = new GuiInspectorField();
newField->init(mParent, this);
newField->setSpecialEditField(true);
if (newField->registerObject())
{
return newField;
}
return NULL;
}
DefineEngineMethod(GuiInspectorVariableGroup, createInspectorField, GuiInspectorField*, (),, "createInspectorField()")
{
return object->createInspectorField();
}
DefineEngineMethod(GuiInspectorVariableGroup, addInspectorField, void, (GuiInspectorField* field), (nullAsType<GuiInspectorField*>()), "addInspectorField( GuiInspectorFieldObject )")
{
object->addInspectorField(field);
} | 412 | 0.930566 | 1 | 0.930566 | game-dev | MEDIA | 0.420017 | game-dev | 0.938871 | 1 | 0.938871 |
openpool/openpool-core-unity | 1,062 | UnityModule/OpenPool/Assets/UnitySteer/Behaviors/SteerForPointLookAtTarget.cs | using UnityEngine;
using System.Collections;
using UnitySteer;
[AddComponentMenu("UnitySteer/Steer/... for Point and Look-At Target")]
public class SteerForPointLookAtTarget : SteerForPoint {
[SerializeField]
Transform _lookTarget;
[SerializeField]
float _rotateTime = 0.2f;
Transform _transform;
public Transform LookTarget {
get { return _lookTarget; }
set { _lookTarget = value; }
}
public float RotateTime {
get { return _rotateTime; }
set { _rotateTime = value; }
}
void OnEnable() {
_transform = transform;
}
void Update() {
if(_lookTarget == null) {
return;
}
var difference = this.TargetPoint - Vehicle.Position;
float d = difference.sqrMagnitude;
if (d <= Vehicle.SquaredArrivalRadius) {
Quaternion rot = Quaternion.LookRotation(_lookTarget.position - _transform.position);
_transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * 1/_rotateTime);
}
}
protected override Vector3 CalculateForce()
{
return base.CalculateForce();
}
}
| 412 | 0.946978 | 1 | 0.946978 | game-dev | MEDIA | 0.718414 | game-dev,graphics-rendering | 0.959817 | 1 | 0.959817 |
acmeism/RosettaCodeData | 4,811 | Task/Tic-tac-toe/Swift/tic-tac-toe.swift | import Darwin
enum Token : CustomStringConvertible {
case cross, circle
func matches(tokens: [Token?]) -> Bool {
for token in tokens {
guard let t = token, t == self else {
return false
}
}
return true
}
func emptyCell(in tokens: [Token?]) -> Int? {
if tokens[0] == nil
&& tokens[1] == self
&& tokens[2] == self {
return 0
} else
if tokens[0] == self
&& tokens[1] == nil
&& tokens[2] == self {
return 1
} else
if tokens[0] == self
&& tokens[1] == self
&& tokens[2] == nil {
return 2
}
return nil
}
var description: String {
switch self {
case .cross: return "x"
case .circle: return "o"
}
}
}
struct Board {
var cells: [Token?] = [nil, nil, nil, nil, nil, nil, nil, nil, nil]
func cells(atCol col: Int) -> [Token?] {
return [cells[col], cells[col + 3], cells[col + 6]]
}
func cells(atRow row: Int) -> [Token?] {
return [cells[row * 3], cells[row * 3 + 1], cells[row * 3 + 2]]
}
func cellsTopLeft() -> [Token?] {
return [cells[0], cells[4], cells[8]]
}
func cellsBottomLeft() -> [Token?] {
return [cells[6], cells[4], cells[2]]
}
func winner() -> Token? {
let r0 = cells(atRow: 0)
let r1 = cells(atRow: 1)
let r2 = cells(atRow: 2)
let c0 = cells(atCol: 0)
let c1 = cells(atCol: 1)
let c2 = cells(atCol: 2)
let tl = cellsTopLeft()
let bl = cellsBottomLeft()
if Token.cross.matches(tokens: r0)
|| Token.cross.matches(tokens: r1)
|| Token.cross.matches(tokens: r2)
|| Token.cross.matches(tokens: c0)
|| Token.cross.matches(tokens: c1)
|| Token.cross.matches(tokens: c2)
|| Token.cross.matches(tokens: tl)
|| Token.cross.matches(tokens: bl) {
return .cross
} else
if Token.circle.matches(tokens: r0)
|| Token.circle.matches(tokens: r1)
|| Token.circle.matches(tokens: r2)
|| Token.circle.matches(tokens: c0)
|| Token.circle.matches(tokens: c1)
|| Token.circle.matches(tokens: c2)
|| Token.circle.matches(tokens: tl)
|| Token.circle.matches(tokens: bl) {
return .circle
}
return nil
}
func atCapacity() -> Bool {
return cells.filter { $0 == nil }.count == 0
}
mutating func play(token: Token, at location: Int) {
cells[location] = token
}
func findBestLocation(for player: Token) -> Int? {
let r0 = cells(atRow: 0)
let r1 = cells(atRow: 1)
let r2 = cells(atRow: 2)
let c0 = cells(atCol: 0)
let c1 = cells(atCol: 1)
let c2 = cells(atCol: 2)
let tl = cellsTopLeft()
let bl = cellsBottomLeft()
if let cell = player.emptyCell(in: r0) {
return cell
} else if let cell = player.emptyCell(in: r1) {
return cell + 3
} else if let cell = player.emptyCell(in: r2) {
return cell + 6
} else if let cell = player.emptyCell(in: c0) {
return cell * 3
} else if let cell = player.emptyCell(in: c1) {
return cell * 3 + 1
} else if let cell = player.emptyCell(in: c2) {
return cell * 3 + 2
} else if let cell = player.emptyCell(in: tl) {
return cell == 0 ? 0 : (cell == 1 ? 4 : 8)
} else if let cell = player.emptyCell(in: bl) {
return cell == 0 ? 6 : (cell == 1 ? 4 : 2)
}
return nil
}
func findMove() -> Int {
let empties = cells.enumerated().filter { $0.1 == nil }
let r = Int(arc4random()) % empties.count
return empties[r].0
}
}
extension Board : CustomStringConvertible {
var description: String {
var result = "\n---------------\n"
for (idx, cell) in cells.enumerated() {
if let cell = cell {
result += "| \(cell) |"
} else {
result += "| \(idx) |"
}
if (idx + 1) % 3 == 0 {
result += "\n---------------\n"
}
}
return result
}
}
while true {
var board = Board()
print("Who do you want to play as ('o' or 'x'): ", separator: "", terminator: "")
let answer = readLine()?.characters.first ?? "x"
var player: Token = answer == "x" ? .cross : .circle
var pc: Token = player == .cross ? .circle : .cross
print(board)
while true {
print("Choose cell to play on: ", separator: "", terminator: "")
var pos = Int(readLine() ?? "0") ?? 0
while !board.atCapacity() && board.cells[pos] != nil {
print("Invalid move. Choose cell to play on: ", separator: "", terminator: "")
pos = Int(readLine() ?? "0") ?? 0
}
if board.atCapacity() {
print("Draw")
break
}
board.play(token: player, at: pos)
print(board)
if let winner = board.winner() {
print("winner is \(winner)")
break
} else if board.atCapacity() {
print("Draw")
break
}
if let win = board.findBestLocation(for: pc) {
board.play(token: pc, at: win)
} else if let def = board.findBestLocation(for: player) {
board.play(token: pc, at: def)
} else {
board.play(token: pc, at: board.findMove())
}
print(board)
if let winner = board.winner() {
print("winner is \(winner)")
break
}
}
}
| 412 | 0.94881 | 1 | 0.94881 | game-dev | MEDIA | 0.634688 | game-dev | 0.852561 | 1 | 0.852561 |
ShuangYu1145/Faiths-Fix | 3,511 | src/main/java/net/minecraft/item/crafting/RecipeBookCloning.java | package net.minecraft.item.crafting;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemEditableBook;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
public class RecipeBookCloning implements IRecipe
{
/**
* Used to check if a recipe matches current crafting inventory
*/
public boolean matches(InventoryCrafting inv, World worldIn)
{
int i = 0;
ItemStack itemstack = null;
for (int j = 0; j < inv.getSizeInventory(); ++j)
{
ItemStack itemstack1 = inv.getStackInSlot(j);
if (itemstack1 != null)
{
if (itemstack1.getItem() == Items.written_book)
{
if (itemstack != null)
{
return false;
}
itemstack = itemstack1;
}
else
{
if (itemstack1.getItem() != Items.writable_book)
{
return false;
}
++i;
}
}
}
return itemstack != null && i > 0;
}
/**
* Returns an Item that is the result of this recipe
*/
public ItemStack getCraftingResult(InventoryCrafting inv)
{
int i = 0;
ItemStack itemstack = null;
for (int j = 0; j < inv.getSizeInventory(); ++j)
{
ItemStack itemstack1 = inv.getStackInSlot(j);
if (itemstack1 != null)
{
if (itemstack1.getItem() == Items.written_book)
{
if (itemstack != null)
{
return null;
}
itemstack = itemstack1;
}
else
{
if (itemstack1.getItem() != Items.writable_book)
{
return null;
}
++i;
}
}
}
if (itemstack != null && i >= 1 && ItemEditableBook.getGeneration(itemstack) < 2)
{
ItemStack itemstack2 = new ItemStack(Items.written_book, i);
itemstack2.setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy());
itemstack2.getTagCompound().setInteger("generation", ItemEditableBook.getGeneration(itemstack) + 1);
if (itemstack.hasDisplayName())
{
itemstack2.setStackDisplayName(itemstack.getDisplayName());
}
return itemstack2;
}
else
{
return null;
}
}
/**
* Returns the size of the recipe area
*/
public int getRecipeSize()
{
return 9;
}
public ItemStack getRecipeOutput()
{
return null;
}
public ItemStack[] getRemainingItems(InventoryCrafting inv)
{
ItemStack[] aitemstack = new ItemStack[inv.getSizeInventory()];
for (int i = 0; i < aitemstack.length; ++i)
{
ItemStack itemstack = inv.getStackInSlot(i);
if (itemstack != null && itemstack.getItem() instanceof ItemEditableBook)
{
aitemstack[i] = itemstack;
break;
}
}
return aitemstack;
}
}
| 412 | 0.739826 | 1 | 0.739826 | game-dev | MEDIA | 0.997633 | game-dev | 0.861041 | 1 | 0.861041 |
NCAR/lrose-core | 4,365 | codebase/libs/shapelib/src/shapelib/contrib/shpdata.c | /******************************************************************************
* Copyright (c) 1999, Carl Anderson
*
* this code is based in part on the earlier work of Frank Warmerdam
*
* 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.
******************************************************************************
*
* shpdata.c - utility program for testing elements of the libraries
*
*
* $Log: shpdata.c,v $
* Revision 1.1 2000/06/28 13:37:04 rehak
* Initial version of library from http://gdal.velocet.ca/projects/shapelib/
*
* Revision 1.2 1999/05/26 02:56:31 candrsn
* updates to shpdxf, dbfinfo, port from Shapelib 1.1.5 of dbfcat and shpinfo
*
*
*
*/
#include "shapefil.h"
#include "shpgeo.h"
int main( int argc, char ** argv )
{
SHPHandle old_SHP, new_SHP;
DBFHandle old_DBF, new_DBF;
int nShapeType, nEntities, nVertices, nParts, *panParts, i, iPart;
double *padVertices, adBounds[4];
const char *pszPlus;
DBFFieldType idfld_type;
int idfld, nflds;
char kv[257] = "";
char idfldName[120] = "";
char fldName[120] = "";
char shpFileName[120] = "";
char dbfFileName[120] = "";
char *DBFRow = NULL;
int Cpan[2] = { 0,0 };
int byRing = 1;
PT oCentrd, ringCentrd;
SHPObject *psCShape, *cent_pt;
double oArea = 0.0, oLen = 0.0;
if( argc < 2 )
{
printf( "shpdata shp_file \n" );
exit( 1 );
}
old_SHP = SHPOpen (argv[1], "rb" );
old_DBF = DBFOpen (argv[1], "rb");
if( old_SHP == NULL || old_DBF == NULL )
{
printf( "Unable to open old files:%s\n", argv[1] );
exit( 1 );
}
SHPGetInfo( old_SHP, &nEntities, &nShapeType, NULL, NULL );
for( i = 0; i < nEntities; i++ )
{
int res ;
psCShape = SHPReadObject( old_SHP, i );
if ( byRing == 1 ) {
int ring, prevStart, ringDir;
double ringArea;
prevStart = psCShape->nVertices;
for ( ring = (psCShape->nParts - 1); ring >= 0; ring-- ) {
SHPObject *psO;
int j, numVtx, rStart;
rStart = psCShape->panPartStart[ring];
if ( ring == (psCShape->nParts -1) )
{ numVtx = psCShape->nVertices - rStart; }
else
{ numVtx = psCShape->panPartStart[ring+1] - rStart; }
printf ("(shpdata) Ring(%d) (%d for %d) \n", ring, rStart, numVtx);
psO = SHPClone ( psCShape, ring, ring + 1 );
ringDir = SHPRingDir_2d ( psO, 0 );
ringArea = RingArea_2d (psO->nVertices,(double*) psO->padfX,
(double*) psO->padfY);
RingCentroid_2d ( psO->nVertices, (double*) psO->padfX,
(double*) psO->padfY, &ringCentrd, &ringArea);
printf ("(shpdata) Ring %d, %f Area %d dir \n",
ring, ringArea, ringDir );
SHPDestroyObject ( psO );
printf ("(shpdata) End Ring \n");
} /* (ring) [0,nParts */
} /* by ring */
oArea = SHPArea_2d ( psCShape );
oLen = SHPLength_2d ( psCShape );
oCentrd = SHPCentrd_2d ( psCShape );
printf ("(shpdata) Part (%d) %f Area %f length, C (%f,%f)\n",
i, oArea, oLen, oCentrd.x, oCentrd.y );
}
SHPClose( old_SHP );
DBFClose( old_DBF );
printf ("\n");
}
| 412 | 0.970167 | 1 | 0.970167 | game-dev | MEDIA | 0.346936 | game-dev | 0.975799 | 1 | 0.975799 |
GarageGames/Torque3D | 7,598 | Engine/lib/bullet/src/BulletDynamics/Featherstone/btMultiBodyFixedConstraint.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 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.
*/
///This file was written by Erwin Coumans
#include "btMultiBodyFixedConstraint.h"
#include "btMultiBodyLinkCollider.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "BulletDynamics/ConstraintSolver/btGeneric6DofSpring2Constraint.h"
#include "LinearMath/btIDebugDraw.h"
#define BTMBFIXEDCONSTRAINT_DIM 6
btMultiBodyFixedConstraint::btMultiBodyFixedConstraint(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB)
:btMultiBodyConstraint(body,0,link,-1,BTMBFIXEDCONSTRAINT_DIM,false),
m_rigidBodyA(0),
m_rigidBodyB(bodyB),
m_pivotInA(pivotInA),
m_pivotInB(pivotInB),
m_frameInA(frameInA),
m_frameInB(frameInB)
{
m_data.resize(BTMBFIXEDCONSTRAINT_DIM);//at least store the applied impulses
}
btMultiBodyFixedConstraint::btMultiBodyFixedConstraint(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB)
:btMultiBodyConstraint(bodyA,bodyB,linkA,linkB,BTMBFIXEDCONSTRAINT_DIM,false),
m_rigidBodyA(0),
m_rigidBodyB(0),
m_pivotInA(pivotInA),
m_pivotInB(pivotInB),
m_frameInA(frameInA),
m_frameInB(frameInB)
{
m_data.resize(BTMBFIXEDCONSTRAINT_DIM);//at least store the applied impulses
}
void btMultiBodyFixedConstraint::finalizeMultiDof()
{
//not implemented yet
btAssert(0);
}
btMultiBodyFixedConstraint::~btMultiBodyFixedConstraint()
{
}
int btMultiBodyFixedConstraint::getIslandIdA() const
{
if (m_rigidBodyA)
return m_rigidBodyA->getIslandTag();
if (m_bodyA)
{
btMultiBodyLinkCollider* col = m_bodyA->getBaseCollider();
if (col)
return col->getIslandTag();
for (int i=0;i<m_bodyA->getNumLinks();i++)
{
if (m_bodyA->getLink(i).m_collider)
return m_bodyA->getLink(i).m_collider->getIslandTag();
}
}
return -1;
}
int btMultiBodyFixedConstraint::getIslandIdB() const
{
if (m_rigidBodyB)
return m_rigidBodyB->getIslandTag();
if (m_bodyB)
{
btMultiBodyLinkCollider* col = m_bodyB->getBaseCollider();
if (col)
return col->getIslandTag();
for (int i=0;i<m_bodyB->getNumLinks();i++)
{
col = m_bodyB->getLink(i).m_collider;
if (col)
return col->getIslandTag();
}
}
return -1;
}
void btMultiBodyFixedConstraint::createConstraintRows(btMultiBodyConstraintArray& constraintRows, btMultiBodyJacobianData& data, const btContactSolverInfo& infoGlobal)
{
int numDim = BTMBFIXEDCONSTRAINT_DIM;
for (int i=0;i<numDim;i++)
{
btMultiBodySolverConstraint& constraintRow = constraintRows.expandNonInitializing();
constraintRow.m_orgConstraint = this;
constraintRow.m_orgDofIndex = i;
constraintRow.m_relpos1CrossNormal.setValue(0,0,0);
constraintRow.m_contactNormal1.setValue(0,0,0);
constraintRow.m_relpos2CrossNormal.setValue(0,0,0);
constraintRow.m_contactNormal2.setValue(0,0,0);
constraintRow.m_angularComponentA.setValue(0,0,0);
constraintRow.m_angularComponentB.setValue(0,0,0);
constraintRow.m_solverBodyIdA = data.m_fixedBodyId;
constraintRow.m_solverBodyIdB = data.m_fixedBodyId;
// Convert local points back to world
btVector3 pivotAworld = m_pivotInA;
btMatrix3x3 frameAworld = m_frameInA;
if (m_rigidBodyA)
{
constraintRow.m_solverBodyIdA = m_rigidBodyA->getCompanionId();
pivotAworld = m_rigidBodyA->getCenterOfMassTransform()*m_pivotInA;
frameAworld = frameAworld.transpose()*btMatrix3x3(m_rigidBodyA->getOrientation());
} else
{
if (m_bodyA) {
pivotAworld = m_bodyA->localPosToWorld(m_linkA, m_pivotInA);
frameAworld = m_bodyA->localFrameToWorld(m_linkA, frameAworld);
}
}
btVector3 pivotBworld = m_pivotInB;
btMatrix3x3 frameBworld = m_frameInB;
if (m_rigidBodyB)
{
constraintRow.m_solverBodyIdB = m_rigidBodyB->getCompanionId();
pivotBworld = m_rigidBodyB->getCenterOfMassTransform()*m_pivotInB;
frameBworld = frameBworld.transpose()*btMatrix3x3(m_rigidBodyB->getOrientation());
} else
{
if (m_bodyB) {
pivotBworld = m_bodyB->localPosToWorld(m_linkB, m_pivotInB);
frameBworld = m_bodyB->localFrameToWorld(m_linkB, frameBworld);
}
}
btMatrix3x3 relRot = frameAworld.inverse()*frameBworld;
btVector3 angleDiff;
btGeneric6DofSpring2Constraint::matrixToEulerXYZ(relRot,angleDiff);
btVector3 constraintNormalLin(0,0,0);
btVector3 constraintNormalAng(0,0,0);
btScalar posError = 0.0;
if (i < 3) {
constraintNormalLin[i] = -1;
posError = (pivotAworld-pivotBworld).dot(constraintNormalLin);
fillMultiBodyConstraint(constraintRow, data, 0, 0, constraintNormalAng,
constraintNormalLin, pivotAworld, pivotBworld,
posError,
infoGlobal,
-m_maxAppliedImpulse, m_maxAppliedImpulse
);
}
else { //i>=3
constraintNormalAng = frameAworld.getColumn(i%3);
posError = angleDiff[i%3];
fillMultiBodyConstraint(constraintRow, data, 0, 0, constraintNormalAng,
constraintNormalLin, pivotAworld, pivotBworld,
posError,
infoGlobal,
-m_maxAppliedImpulse, m_maxAppliedImpulse, true
);
}
}
}
void btMultiBodyFixedConstraint::debugDraw(class btIDebugDraw* drawer)
{
btTransform tr;
tr.setIdentity();
if (m_rigidBodyA)
{
btVector3 pivot = m_rigidBodyA->getCenterOfMassTransform() * m_pivotInA;
tr.setOrigin(pivot);
drawer->drawTransform(tr, 0.1);
}
if (m_bodyA)
{
btVector3 pivotAworld = m_bodyA->localPosToWorld(m_linkA, m_pivotInA);
tr.setOrigin(pivotAworld);
drawer->drawTransform(tr, 0.1);
}
if (m_rigidBodyB)
{
// that ideally should draw the same frame
btVector3 pivot = m_rigidBodyB->getCenterOfMassTransform() * m_pivotInB;
tr.setOrigin(pivot);
drawer->drawTransform(tr, 0.1);
}
if (m_bodyB)
{
btVector3 pivotBworld = m_bodyB->localPosToWorld(m_linkB, m_pivotInB);
tr.setOrigin(pivotBworld);
drawer->drawTransform(tr, 0.1);
}
}
| 412 | 0.861566 | 1 | 0.861566 | game-dev | MEDIA | 0.97686 | game-dev | 0.989451 | 1 | 0.989451 |
thedarkcolour/Future-MC | 1,103 | src/main/java/thedarkcolour/futuremc/client/gui/GuiBarrel.kt | package thedarkcolour.futuremc.client.gui
import net.minecraft.client.resources.I18n
import net.minecraft.util.ResourceLocation
import org.lwjgl.opengl.GL11
import thedarkcolour.futuremc.container.ContainerBarrel
class GuiBarrel(container: ContainerBarrel) : FGui<ContainerBarrel>(container) {
val te = container.te
init {
ySize = 168
}
override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) {
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f)
mc.textureManager.bindTexture(BACKGROUND)
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, 71)
drawTexturedModalRect(guiLeft, guiTop + 71, 0, 127, xSize, 96)
}
override fun drawGuiContainerForegroundLayer(mouseX: Int, mouseY: Int) {
fontRenderer.drawString(I18n.format("container.barrel"), 8, 6, 4210752)
fontRenderer.drawString(getContainer().playerInv.displayName.unformattedText, 8, ySize - 95, 4210752)
}
companion object {
private val BACKGROUND = ResourceLocation("minecraft:textures/gui/container/generic_54.png")
}
} | 412 | 0.83407 | 1 | 0.83407 | game-dev | MEDIA | 0.922695 | game-dev | 0.5228 | 1 | 0.5228 |
Ormael13/CoCX | 7,804 | classes/classes/Scenes/Areas/HighMountains/Harpy.as | package classes.Scenes.Areas.HighMountains
{
import classes.*;
import classes.BodyParts.Butt;
import classes.BodyParts.Hips;
import classes.BodyParts.LowerBody;
import classes.BodyParts.Wings;
import classes.GlobalFlags.kFLAGS;
import classes.Scenes.Combat.Combat;
import classes.Scenes.SceneLib;
import classes.internals.*;
public class Harpy extends Monster
{
//*Note, special attack one is an idea based on Ceraph.
//About the attack that raises your Lust to 100 if you
//don't "wait" when she unleashes it. Alright, I
//basically used the idea, sorry. But it's a neat idea
//so it should be fitting, right? Or you could just
//dump it out altogether. It'd cause severe damage,
//in the 150 region if you don't wise up.*
protected function harpyUberCharge():void
{
//(Harpy special attack 1, part one)
if (!hasStatusEffect(StatusEffects.Uber)) {
createStatusEffect(StatusEffects.Uber, 0, 0, 0, 0);
outputText("Flapping her wings frantically, she flies away from you and gains height, hanging in the light before you. She lets out a shrill and terrifying cry, narrowing her eyes as she focuses in on you!");
}
//(Harpy special attack 1, part two if PC does anything but "Wait")
else {
if (!Combat.playerWaitsOrDefends()) {
outputText("The harpy lets out a terrible cry and drops, reaching an almost impossible speed as she dives down at you. Her eyes are narrowed like a true bird of prey. You were too busy with your own attack to avoid it! Her claws surge down and pierce your [armor] like paper, driving hard into the flesh beneath and making you cry out in pain. The harpy dumps you onto the ground, your wounds bleeding profusely. ");
var damage:Number = (str + weaponAttack + 320 + rand(20)) * (1 + (player.newGamePlusMod() / 2));
player.takePhysDamage(damage, true);
removeStatusEffect(StatusEffects.Uber);
}
else {
outputText("You stand firm and ready yourself as the crazed harpy hovers above you. Letting out an ear-splitting cry she dives at you with her claws extended, reaching an incredible speed before she levels out. The harpy is heading right for you! Thanks to your ready position, you manage to dive aside just as the harpy reaches you. She clips you slightly, spinning you as you dive for the ground. You hit the ground hard, but look up in time to see her make a rough, graceless landing. Her body rolls until it reached a standstill. The enraged harpy drags herself up and takes flight once more! ");
player.takePhysDamage(100 + rand(10), true);
removeStatusEffect(StatusEffects.Uber);
HP -= 20;
}
}
}
//(Harpy special attack 2, lust increase)
protected function harpyTease():void
{
outputText("The harpy charges at you carelessly, her body striking you with the full weight of her motherly hips. The pair of you go crashing backwards onto the ground. You grapple with her weighty ass, trying your best not to think dirty thoughts, but the way she's maniacally flapping and writhing her curvy body against you makes it impossible! After a brief, groping wrestle on the ground, she pushes you away and takes flight again.");
player.takeLustDamage((25 + rand(player.effectiveSensitivity() / 4)), true);
}
public function hasUber():Boolean {
return hasStatusEffect(StatusEffects.Uber)
}
override public function defeated(hpVictory:Boolean):void
{
SceneLib.mountain.harpyScene.harpyVictoryuuuuu();
}
override public function won(hpVictory:Boolean, pcCameWorms:Boolean):void
{
if (pcCameWorms) {
outputText("\n\nYour foe doesn't seem disgusted enough to leave...");
doNext(SceneLib.combat.endLustLoss);
} else {
SceneLib.mountain.harpyScene.harpyLossU();
}
}
override protected function outputPlayerDodged(dodge:int):void
{
outputText("With another deranged cry the harpy dives at you, swinging her razor-sharp talons through the air with the grace of a ballerina. Your quick reflexes allow you to dodge every vicious slash she makes at you.\n");
}
override public function outputAttack(damage:int):void
{
if (damage <= 0) {
outputText("The harpy dives at you with her foot-talons, but you deflect the attack, grasp onto her leg, and swing her through the air, tossing her away from you before she has a chance to right herself.");
} else {
outputText("The harpy surges forward, bringing her razor-sharp claws down on you, tearing at all the exposed flesh she can reach! <b>(<font color=\"#800000\">" + damage + "</font>)</b>");
}
}
public function Harpy(noInit:Boolean=false)
{
if (noInit) return;
trace("Harpy Constructor!");
this.a = "the ";
this.short = "harpy";
this.imageName = "harpy";
this.long = "You are fighting a tall, deranged harpy. She appears very human, about six feet six inches tall but covered in a fine layer of powder-blue down. Her arms are sinewy and muscular, with a long web connecting them to her ample hips, covered in stringy blue feathers to aid her flight. A larger pair of powdery-blue wings also protrudes from her shoulder blades, flapping idly. She appears quite deranged as she circles you, approaching and backing away erratically. Her face is quite beautiful, with fine lilac makeup adorning the features of a handsome woman, and her lips are traced with rich golden lipstick. As she circles you, squawking frantically and trying to intimidate you, your eyes are drawn to her slender torso and small, pert breasts, each the size of a small fruit and covered in a layer of the softest feathers which ripple and move with the gusts from her wings. As astounding as her breasts are, her egg-bearing hips are even more impressive. They're twice as wide as her torso, with enormous, jiggling buttocks where her huge, meaty thighs are coming up to meet them. Her legs end in three-pronged talons; their shadowy black curves glinting evilly in the light.";
// this.plural = false;
this.createVagina(false, VaginaClass.WETNESS_SLICK, VaginaClass.LOOSENESS_GAPING_WIDE);
this.createStatusEffect(StatusEffects.BonusVCapacity, 40, 0, 0, 0);
createBreastRow(Appearance.breastCupInverse("B"));
this.ass.analLooseness = AssClass.LOOSENESS_TIGHT;
this.ass.analWetness = AssClass.WETNESS_DRY;
this.createStatusEffect(StatusEffects.BonusACapacity,20,0,0,0);
this.tallness = 6*12+6;
this.hips.type = Hips.RATING_INHUMANLY_WIDE;
this.butt.type = Butt.RATING_EXPANSIVE;
this.lowerBody = LowerBody.HARPY;
this.skin.setBaseOnly({color:"pink"});
this.skinDesc = "feathers";
this.hairColor = "blue";
this.hairLength = 16;
initStrTouSpeInte(130, 100, 170, 70);
initWisLibSensCor(80, 90, 40, 80);
this.weaponName = "talons";
this.weaponVerb="slashing talons";
this.weaponAttack = 75;
this.armorName = "feathers";
this.armorDef = 20;
this.armorMDef = 2;
this.bonusHP = 500;
this.bonusLust = 165;
this.lust = 10;
this.lustVuln = .6;
this.level = 35;
this.gems = 45 + rand(10);
this.drop = new ChainedDrop().add(armors.W_ROBES,1/10)
.add(consumables.SKYSEED,1/5)
.elseDrop(consumables.GLDSEED);
if (player.hasPerk(PerkLib.LuststickAdapted)) {
(this.drop as ChainedDrop).add(consumables.LUSTSTK, 1/3)
}
this.wings.type = Wings.HARPY;
this.abilities = [
{ call: eAttack, type: ABILITY_PHYSICAL, range: RANGE_MELEE, tags:[TAG_BODY]},
{ call: harpyTease, type: ABILITY_TEASE, range: RANGE_MELEE, tags:[TAG_BODY]},
{ call: harpyUberCharge, type: ABILITY_PHYSICAL, range: RANGE_MELEE, tags:[TAG_BODY]},
{ call: harpyUberCharge, type: ABILITY_PHYSICAL, range: RANGE_MELEE, tags:[TAG_BODY], condition: hasUber, weight: Infinity}
];
this.createStatusEffect(StatusEffects.Flying,50,0,0,0);
checkMonster();
}
}
}
| 412 | 0.806565 | 1 | 0.806565 | game-dev | MEDIA | 0.996037 | game-dev | 0.945306 | 1 | 0.945306 |
lip6/coriolis | 7,633 | tramontana/src/tramontana/ShortCircuitWidget.h |
// -*- C++ -*-
//
// This file is part of the Coriolis Software.
// Copyright (c) Sorbonne Université 2024-2024.
//
// +-----------------------------------------------------------------+
// | C O R I O L I S |
// | T r a m o n t a n a - Extractor & LVX |
// | |
// | Algorithm : Christian MASSON |
// | First impl. : Yifei WU |
// | Second impl. : Jean-Paul CHAPUT |
// | E-mail : Jean-Paul.Chaput@lip6.fr |
// | =============================================================== |
// | C++ Header : "./tramontana/ShortCircuitWidget.h" |
// +-----------------------------------------------------------------+
#pragma once
#include <set>
#include <QWidget>
#include <QTreeView>
#include <QHeaderView>
#include <QItemDelegate>
#include "hurricane/Commons.h"
#include "hurricane/Bug.h"
namespace Hurricane {
class CellWidget;
}
#include "tramontana/Equipotential.h"
class QModelIndex;
class QLineEdit;
class QLabel;
namespace Tramontana {
using std::string;
using std::set;
using Hurricane::Cell;
using Hurricane::OccurrenceSet;
using Hurricane::CellWidget;
// -------------------------------------------------------------------
// Class : "ShortCircuitAbstractItem".
class ShortCircuitAbstractItem {
public:
static const uint32_t Root = (1 << 0);
static const uint32_t Base = (1 << 1);
static const uint32_t CompA = (1 << 2);
static const uint32_t CompB = (1 << 3);
static const uint32_t Overlap = (1 << 4);
public:
ShortCircuitAbstractItem ( ShortCircuitAbstractItem* );
virtual ~ShortCircuitAbstractItem ();
virtual uint32_t getType () const = 0;
inline ShortCircuitAbstractItem* getParent () const;
virtual ShortCircuitAbstractItem* getChild ( int row ) const = 0;
virtual int getChildCount () const = 0;
virtual int getColumnCount () const = 0;
virtual int getRow () const = 0;
virtual QVariant data ( int column ) const = 0;
virtual Box getBoundingBox () const = 0;
virtual const ShortCircuit* getShortCircuit () const;
void setEqui ( Equipotential* ) const;
virtual std::string _getString () const = 0;
private:
ShortCircuitAbstractItem* _parent;
};
inline ShortCircuitAbstractItem* ShortCircuitAbstractItem::getParent () const { return _parent; }
class ShortCircuitRootItem : public ShortCircuitAbstractItem {
public:
ShortCircuitRootItem ();
virtual ~ShortCircuitRootItem ();
virtual uint32_t getType () const;
virtual ShortCircuitAbstractItem* getChild ( int row ) const;
virtual int getChildCount () const;
virtual int getColumnCount () const;
virtual int getRow () const;
virtual QVariant data ( int column ) const;
void setEqui ( const Equipotential* );
virtual Box getBoundingBox () const;
void clear ();
virtual std::string _getString () const;
private:
const Equipotential* _equipotential;
std::vector<ShortCircuitAbstractItem*> _childs;
};
class ShortCircuitBaseItem : public ShortCircuitAbstractItem {
public:
ShortCircuitBaseItem ( ShortCircuitAbstractItem*, const Equipotential*, size_t );
virtual ~ShortCircuitBaseItem ();
virtual uint32_t getType () const;
virtual ShortCircuitAbstractItem* getChild ( int row ) const;
virtual int getChildCount () const;
virtual int getColumnCount () const;
virtual int getRow () const;
virtual QVariant data ( int column ) const;
virtual Box getBoundingBox () const;
virtual const ShortCircuit* getShortCircuit () const;
virtual std::string _getString () const;
private:
const Equipotential* _equipotential;
std::array<ShortCircuitAbstractItem*,3> _childs;
size_t _shortIndex;
};
class ShortCircuitAttrItem : public ShortCircuitAbstractItem {
public:
ShortCircuitAttrItem ( ShortCircuitAbstractItem*, const ShortCircuit*, uint32_t type );
virtual ~ShortCircuitAttrItem ();
virtual uint32_t getType () const;
virtual ShortCircuitAbstractItem* getChild ( int row ) const;
virtual int getChildCount () const;
virtual int getColumnCount () const;
virtual int getRow () const;
virtual QVariant data ( int column ) const;
virtual Box getBoundingBox () const;
virtual const ShortCircuit* getShortCircuit () const;
virtual std::string _getString () const;
private:
uint32_t _type;
const ShortCircuit* _shortCircuit;
};
// -------------------------------------------------------------------
// Class : "ShortCircuitModel".
class ShortCircuitModel : public QAbstractItemModel {
Q_OBJECT
public:
explicit ShortCircuitModel ( QObject *parent=nullptr);
~ShortCircuitModel ();
Qt::ItemFlags flags ( const QModelIndex& ) const override;
QModelIndex index ( int row, int column, const QModelIndex& parent=QModelIndex()) const override;
QModelIndex parent ( const QModelIndex& ) const override;
int rowCount ( const QModelIndex& parent=QModelIndex()) const override;
int columnCount ( const QModelIndex& parent=QModelIndex()) const override;
QVariant headerData ( int section, Qt::Orientation, int role=Qt::DisplayRole) const override;
QVariant data ( const QModelIndex&, int role) const override;
void setEqui ( const Equipotential* );
void clear ();
private:
ShortCircuitRootItem _rootItem;
};
} // Tramontana namespace.
GETSTRING_POINTER_SUPPORT(Tramontana::ShortCircuitAbstractItem);
IOSTREAM_POINTER_SUPPORT(Tramontana::ShortCircuitAbstractItem);
| 412 | 0.932085 | 1 | 0.932085 | game-dev | MEDIA | 0.495225 | game-dev | 0.924428 | 1 | 0.924428 |
cocos2d/cocos2d-iphone-classic | 3,668 | external/Box2d/Testbed/Tests/Pinball.h | /*
* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef PINBALL_H
#define PINBALL_H
/// This tests bullet collision and provides an example of a gameplay scenario.
/// This also uses a loop shape.
class Pinball : public Test
{
public:
Pinball()
{
// Ground body
b2Body* ground = NULL;
{
b2BodyDef bd;
ground = m_world->CreateBody(&bd);
b2Vec2 vs[5];
vs[0].Set(0.0f, -2.0f);
vs[1].Set(8.0f, 6.0f);
vs[2].Set(8.0f, 20.0f);
vs[3].Set(-8.0f, 20.0f);
vs[4].Set(-8.0f, 6.0f);
b2ChainShape loop;
loop.CreateLoop(vs, 5);
b2FixtureDef fd;
fd.shape = &loop;
fd.density = 0.0f;
ground->CreateFixture(&fd);
}
// Flippers
{
b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f);
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position = p1;
b2Body* leftFlipper = m_world->CreateBody(&bd);
bd.position = p2;
b2Body* rightFlipper = m_world->CreateBody(&bd);
b2PolygonShape box;
box.SetAsBox(1.75f, 0.1f);
b2FixtureDef fd;
fd.shape = &box;
fd.density = 1.0f;
leftFlipper->CreateFixture(&fd);
rightFlipper->CreateFixture(&fd);
b2RevoluteJointDef jd;
jd.bodyA = ground;
jd.localAnchorB.SetZero();
jd.enableMotor = true;
jd.maxMotorTorque = 1000.0f;
jd.enableLimit = true;
jd.motorSpeed = 0.0f;
jd.localAnchorA = p1;
jd.bodyB = leftFlipper;
jd.lowerAngle = -30.0f * b2_pi / 180.0f;
jd.upperAngle = 5.0f * b2_pi / 180.0f;
m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
jd.motorSpeed = 0.0f;
jd.localAnchorA = p2;
jd.bodyB = rightFlipper;
jd.lowerAngle = -5.0f * b2_pi / 180.0f;
jd.upperAngle = 30.0f * b2_pi / 180.0f;
m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
}
// Circle character
{
b2BodyDef bd;
bd.position.Set(1.0f, 15.0f);
bd.type = b2_dynamicBody;
bd.bullet = true;
m_ball = m_world->CreateBody(&bd);
b2CircleShape shape;
shape.m_radius = 0.2f;
b2FixtureDef fd;
fd.shape = &shape;
fd.density = 1.0f;
m_ball->CreateFixture(&fd);
}
m_button = false;
}
void Step(Settings* settings)
{
if (m_button)
{
m_leftJoint->SetMotorSpeed(20.0f);
m_rightJoint->SetMotorSpeed(-20.0f);
}
else
{
m_leftJoint->SetMotorSpeed(-10.0f);
m_rightJoint->SetMotorSpeed(10.0f);
}
Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "Press 'a' to control the flippers");
m_textLine += 15;
}
void Keyboard(unsigned char key)
{
switch (key)
{
case 'a':
case 'A':
m_button = true;
break;
}
}
void KeyboardUp(unsigned char key)
{
switch (key)
{
case 'a':
case 'A':
m_button = false;
break;
}
}
static Test* Create()
{
return new Pinball;
}
b2RevoluteJoint* m_leftJoint;
b2RevoluteJoint* m_rightJoint;
b2Body* m_ball;
bool m_button;
};
#endif
| 412 | 0.92849 | 1 | 0.92849 | game-dev | MEDIA | 0.891674 | game-dev | 0.985807 | 1 | 0.985807 |
Skytils/SkytilsMod | 9,841 | mod/src/main/kotlin/gg/skytils/skytilsmod/features/impl/dungeons/solvers/CreeperSolver.kt | /*
* Skytils - Hypixel Skyblock Quality of Life Mod
* Copyright (C) 2020-2023 Skytils
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package gg.skytils.skytilsmod.features.impl.dungeons.solvers
import com.mojang.blaze3d.opengl.GlStateManager
import gg.essential.universal.UGraphics
import gg.essential.universal.UMatrixStack
import gg.skytils.event.EventSubscriber
import gg.skytils.event.impl.play.WorldUnloadEvent
import gg.skytils.event.impl.render.WorldDrawEvent
import gg.skytils.event.register
import gg.skytils.skytilsmod.Skytils
import gg.skytils.skytilsmod.Skytils.mc
import gg.skytils.skytilsmod._event.DungeonPuzzleDiscoveredEvent
import gg.skytils.skytilsmod.core.tickTimer
import gg.skytils.skytilsmod.listeners.DungeonListener
import gg.skytils.skytilsmod.utils.*
import gg.skytils.skytilsmod.utils.graphics.colors.CommonColors
import com.mojang.blaze3d.systems.RenderSystem
import net.minecraft.entity.mob.CreeperEntity
import net.minecraft.block.Blocks
import net.minecraft.util.math.Box
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import org.lwjgl.opengl.GL11
import java.awt.Color
object CreeperSolver : EventSubscriber {
private val colors = CommonColors.set.copySet()
private val solutionPairs = arrayListOf<Pair<BlockPos, BlockPos>>()
private var creeper: CreeperEntity? = null
private val candidateBlocks = setOf(Blocks.PRISMARINE, Blocks.SEA_LANTERN)
fun onPuzzleDiscovered(event: DungeonPuzzleDiscoveredEvent) {
if (event.puzzle == "Creeper Beams") {
updatePuzzleState()
}
}
fun updatePuzzleState() {
if (this.creeper == null) {
val creeperScan = mc.player?.boundingBox?.expand(14.0, 8.0, 13.0) ?: return
this.creeper = mc.world?.getEntitiesByClass(CreeperEntity::class.java, creeperScan) {
it != null && !it.isInvisible && it.maxHealth == 20f && it.health == 20f && !it.hasCustomName()
}?.firstOrNull()
} else if (solutionPairs.isEmpty()) {
val baseBlock = BlockPos.ofFloored(this.creeper!!.x, 75.0, this.creeper!!.z).toBoundingBox()
val validBox = Box(baseBlock.minX, baseBlock.minY, baseBlock.minZ, baseBlock.maxX, baseBlock.maxY + 2, baseBlock.maxZ)
val roomBB = this.creeper!!.boundingBox.expand(14.0, 10.0, 13.0)
val candidates = BlockPos.iterate(BlockPos(roomBB.minVec), BlockPos(roomBB.maxVec)).filter {
it.y > 68 && mc.world?.getBlockState(it)?.block in candidateBlocks
}
val pairs = candidates.elementPairs()
val usedPositions = mutableSetOf<BlockPos>()
solutionPairs.addAll(pairs.filter { (a, b) ->
if (a in usedPositions || b in usedPositions) return@filter false
checkLineBox(validBox, a.middleVec(), b.middleVec(), Holder(Vec3d(0.0, 0.0, 0.0))).also {
if (it) {
usedPositions.add(a)
usedPositions.add(b)
}
}
})
}
}
init {
tickTimer(20, repeats = true) {
if (Skytils.config.creeperBeamsSolver && Utils.inDungeons && DungeonListener.incompletePuzzles.contains(
"Creeper Beams"
)
) {
updatePuzzleState()
}
}
}
fun onWorldRender(event: WorldDrawEvent) {
if (Skytils.config.creeperBeamsSolver && solutionPairs.isNotEmpty() && !creeper!!.isRemoved && DungeonListener.incompletePuzzles.contains(
"Creeper Beams"
)
) {
val (viewerX, viewerY, viewerZ) = RenderUtil.getViewerPos(event.partialTicks)
GlStateManager._disableCull()
val blendEnabled = GL11.glIsEnabled(GL11.GL_BLEND)
UGraphics.enableBlend()
UGraphics.tryBlendFuncSeparate(770, 771, 1, 0)
val matrixStack = UMatrixStack()
for (i in solutionPairs.indices) {
val (one, two) = solutionPairs[i]
if (mc.world?.getBlockState(one)?.block == Blocks.PRISMARINE && mc.world?.getBlockState(two)?.block == Blocks.PRISMARINE) {
continue
}
val color = Color(colors[i % colors.size].toInt())
val first = Vec3d(one).add(-viewerX, -viewerY, -viewerZ)
val second = Vec3d(two).add(-viewerX, -viewerY, -viewerZ)
val aabb1 = Box(
first.x,
first.y,
first.z,
first.x + 1,
first.y + 1,
first.z + 1
)
val aabb2 = Box(
second.x,
second.y,
second.z,
second.x + 1,
second.y + 1,
second.z + 1
)
RenderUtil.drawFilledBoundingBox(
matrixStack, aabb1.expand(0.01, 0.01, 0.01), color, 0.8f
)
RenderUtil.drawFilledBoundingBox(
matrixStack, aabb2.expand(0.01, 0.01, 0.01), color, 0.8f
)
}
if (!blendEnabled) UGraphics.disableBlend()
GlStateManager._enableCull()
}
}
fun onWorldChange(event: WorldUnloadEvent) {
creeper = null
solutionPairs.clear()
}
/**
* @author qJake
* @link https://stackoverflow.com/a/3235902
* https://creativecommons.org/licenses/by-sa/2.5/
* Modified
*/
private fun checkLineBox(bb: Box, point1: Vec3d, point2: Vec3d, hitVec: Holder<Vec3d>): Boolean {
val minVec = bb.minVec
val maxVec = bb.maxVec
if (point2.x < minVec.x && point1.x < minVec.x) return false
if (point2.x > maxVec.x && point1.x > maxVec.x) return false
if (point2.y < minVec.y && point1.y < minVec.y) return false
if (point2.y > maxVec.y && point1.y > maxVec.y) return false
if (point2.z < minVec.z && point1.z < minVec.z) return false
if (point2.z > maxVec.z && point1.z > maxVec.z) return false
if (bb.contains(point1)) {
hitVec.value = point1
return true
}
if ((getIntersection(
point1.x - minVec.x,
point2.x - minVec.x,
point1,
point2,
hitVec
) && bb.isVecInYZ(hitVec.value))
|| (getIntersection(
point1.y - minVec.y,
point2.y - minVec.y,
point1,
point2,
hitVec
) && bb.isVecInXZ(hitVec.value))
|| (getIntersection(
point1.z - minVec.z,
point2.z - minVec.z,
point1,
point2,
hitVec
) && bb.isVecInXY(hitVec.value))
|| (getIntersection(
point1.x - maxVec.x,
point2.x - maxVec.x,
point1,
point2,
hitVec
) && bb.isVecInYZ(hitVec.value))
|| (getIntersection(
point1.y - maxVec.y,
point2.y - maxVec.y,
point1,
point2,
hitVec
) && bb.isVecInXZ(hitVec.value))
|| (getIntersection(
point1.z - maxVec.z,
point2.z - maxVec.z,
point1,
point2,
hitVec
) && bb.isVecInXY(hitVec.value))
) return true
return false
}
/**
* @author qJake
* @link https://stackoverflow.com/a/3235902
* https://creativecommons.org/licenses/by-sa/2.5/
* Modified
*/
private fun getIntersection(
dist1: Double,
dist2: Double,
point1: Vec3d,
point2: Vec3d,
hitVec: Holder<Vec3d>
): Boolean {
if ((dist1 * dist2) >= 0.0f) return false
if (dist1 == dist2) return false
hitVec.value = point1 + ((point2 - point1) * (-dist1 / (dist2 - dist1)))
return true
}
/**
* Checks if the specified vector is within the YZ dimensions of the bounding box.
*/
private fun Box.isVecInYZ(vec: Vec3d): Boolean {
return vec.y >= this.minY && vec.y <= this.maxY && vec.z >= this.minZ && vec.z <= this.maxZ
}
/**
* Checks if the specified vector is within the XZ dimensions of the bounding box.
*/
private fun Box.isVecInXZ(vec: Vec3d): Boolean {
return vec.x >= this.minX && vec.x <= this.maxX && vec.z >= this.minZ && vec.z <= this.maxZ
}
/**
* Checks if the specified vector is within the XY dimensions of the bounding box.
*/
private fun Box.isVecInXY(vec: Vec3d): Boolean {
return vec.x >= this.minX && vec.x <= this.maxX && vec.y >= this.minY && vec.y <= this.maxY
}
private class Holder<T>(var value: T)
override fun setup() {
register(::onPuzzleDiscovered)
register(::onWorldRender)
register(::onWorldChange)
}
} | 412 | 0.907843 | 1 | 0.907843 | game-dev | MEDIA | 0.844415 | game-dev | 0.933323 | 1 | 0.933323 |
DefinitelyTyped/DefinitelyTyped | 1,425 | types/react-copy-write/index.d.ts | import { Component, JSX } from "react";
// It'd be nice if this could somehow be improved! Perhaps we need variadic
// kinds plus infer keyword? Alternatively unions may solve our issue if we had
// the ability to restrict type widening.
type AnyDeepMemberOfState<T> = any;
type MutateFn<T> = (draft: T, state: Readonly<T>) => void;
type Mutator<T> = (mutator: MutateFn<T>) => void;
type SelectorFn<T> = (state: T) => AnyDeepMemberOfState<T>;
type RenderFn<T> = (...state: Array<Readonly<ReturnType<SelectorFn<T>>>>) => JSX.Element | JSX.Element[] | null;
interface ConsumerPropsBase<T> {
select?: Array<SelectorFn<T>> | undefined;
}
interface ConsumerPropsExplicitRender<T> extends ConsumerPropsBase<T> {
render?: RenderFn<T> | undefined;
}
interface ConsumerPropsImplicitRender<T> extends ConsumerPropsBase<T> {
children?: RenderFn<T> | undefined;
}
type ConsumerProps<T> = ConsumerPropsExplicitRender<T> | ConsumerPropsImplicitRender<T>;
declare class Consumer<T> extends Component<ConsumerProps<T>> {}
interface ProviderProps<T> {
children: JSX.Element | JSX.Element[];
initialState?: Partial<T> | undefined;
}
declare class Provider<T> extends Component<ProviderProps<T>> {}
declare function create<T extends object>(state: T): {
Provider: new() => Provider<T>;
Consumer: new() => Consumer<T>;
createSelector: SelectorFn<T>;
mutate: Mutator<T>;
};
export default create;
| 412 | 0.858998 | 1 | 0.858998 | game-dev | MEDIA | 0.467797 | game-dev | 0.880849 | 1 | 0.880849 |
GAIPS/FAtiMA-Toolkit | 47,717 | Assets/RolePlayCharacter/RolePlayerCharacterAsset.cs | using ActionLibrary;
using AutobiographicMemory;
using AutobiographicMemory.DTOs;
using CommeillFaut;
using EmotionalAppraisal;
using EmotionalAppraisal.DTOs;
using EmotionalAppraisal.OCCModel;
using EmotionalDecisionMaking;
using GAIPS.Rage;
using KnowledgeBase;
using SerializationUtilities;
using SocialImportance;
using System;
using System.Collections.Generic;
using System.Linq;
using WellFormedNames;
using IQueryable = WellFormedNames.IQueryable;
using System.Text.RegularExpressions;
using KnowledgeBase.DTOs;
using Utilities;
namespace RolePlayCharacter
{
[Serializable]
public sealed class RolePlayCharacterAsset : ICustomSerialization
{
[NonSerialized]
private Dictionary<Name, Identity> m_activeIdentities;
private Name culture;
public RolePlayCharacterAsset()
{
m_activeIdentities = new Dictionary<Name, Identity>();
m_kb = new KB(RPCConsts.DEFAULT_CHARACTER_NAME);
m_am = new AM();
m_emotionalState = new ConcreteEmotionalState();
m_goals = new Dictionary<string, Goal>();
m_otherAgents = new Dictionary<Name, AgentEntry>();
BindToRegistry(m_kb);
culture = Name.NIL_SYMBOL;
}
/// <summary>
/// An identifier for the embodiment that is used by the character
/// </summary>
public string BodyName { get; set; }
/// <summary>
/// The name of the character
/// </summary>
public Name CharacterName
{
get { return m_kb.Perspective; }
set { m_kb.SetPerspective(value); }
}
public void AddOrUpdateGoal(GoalDTO goal)
{
m_goals[goal.Name] = new Goal(goal);
}
public IEnumerable<GoalDTO> GetAllGoals()
{
return this.m_goals.Values.Select(g => new GoalDTO
{
Name = g.Name.ToString(),
Likelihood = g.Likelihood,
Significance = g.Significance
});
}
public void RemoveGoals(IEnumerable<GoalDTO> goals)
{
foreach (var goal in goals)
{
this.m_goals.Remove(goal.Name);
}
}
public bool IsPlayer { get; set; }
/// <summary>
/// The name of the action that the character is currently executing
/// </summary>
public Name CurrentActionName { get; set; }
/// <summary>
/// The target of the action that the character is currently executing
/// </summary>
public Name CurrentActionTarget { get; set; }
public IDynamicPropertiesRegistry DynamicPropertiesRegistry => m_kb;
/// <summary>
/// Gets all the recorded events experienced by the asset.
/// </summary>
public IEnumerable<EventDTO> EventRecords
{
get { return this.m_am.RecallAllEvents().Select(e => e.ToDTO()); }
}
/// <summary>
/// The emotional mood of the agent, which can vary from -10 to 10
/// </summary>
public float Mood
{
get { return m_emotionalState.Mood; }
set { m_emotionalState.Mood = value; }
}
public IQueryable Queryable
{
get { return m_kb; }
}
/// <summary>
/// The amount of update ticks this asset as experienced since its initialization
/// </summary>
public ulong Tick
{
get { return m_am.Tick; }
set { m_am.Tick = value; }
}
/// <summary>
/// An identifier for the voice that is used by the character
/// </summary>
public string VoiceName { get; set; }
/// <summary>
/// Creates a new <b>Active Emotion</b> and adds it to the asset's currently experiencing emotions set.
/// </summary>
/// <exception cref="ArgumentException">
/// Thrown if the given emotion is already being experienced by the asset.
/// This can happend if in the given EmotionDTO the pair of parameters <b>Type</b> and <b>CauseEventId</b>
/// are equal to an already existent ActiveEmotion in the asset.
/// </exception>
/// <param name="emotion">The DTO containing the emotion parameters to be used in the active emotion creation process</param>
/// <returns>The DTO representing the actual emotion added to the active emotion set.</returns>
public EmotionDTO AddActiveEmotion(EmotionDTO emotion)
{
return m_emotionalState.AddActiveEmotion(emotion, m_am);
}
/// <summary>
/// Add an Event Record to the asset's autobiographical memory
/// </summary>
/// <param name="eventDTO">The dto containing the information regarding the event to add</param>
/// <returns>The unique identifier associated to the event</returns>
public uint AddEventRecord(EventDTO eventDTO)
{
return this.m_am.RecordEvent(eventDTO).Id;
}
public IEnumerable<IAction> Decide()
{
return this.Decide(Name.UNIVERSAL_SYMBOL);
}
public IEnumerable<IAction> Decide(Name layer)
{
if (m_emotionalDecisionMakingAsset == null) return new List<IAction>();
if (CurrentActionName != null)
return new IAction[]
{
new ActionLibrary.Action(new Name[] {RPCConsts.COMMITED_ACTION_KEY, CurrentActionName},
CurrentActionTarget)
};
var possibleActions = m_emotionalDecisionMakingAsset.Decide(layer);
var maxUtility = float.MinValue;
foreach(var a in possibleActions)
{
if(a.Utility > maxUtility)
{
maxUtility = a.Utility;
}
}
var topActions = possibleActions.Where(a => a.Utility == maxUtility).Shuffle();
var remainder = possibleActions.Where(a => a.Utility != maxUtility);
return topActions.Concat(remainder);
}
/// <summary>
/// Removes and forgets an event
/// </summary>
/// <param name="eventId">The id of the event to forget.</param>
public void ForgetEvent(uint eventId)
{
this.m_am.ForgetEvent(eventId);
}
//This method will replace every belief within [[ ]] by its value
public string ProcessWithBeliefs(string utterance)
{
var tokens = Regex.Split(utterance, @"\[|\]\]");
var result = string.Empty;
bool process = false;
foreach (var t in tokens)
{
if (process)
{
var aux = t.Trim();
if (aux.Contains(" "))
{
result += "[[" + t + "]]";
}
else
{
var beliefValue = this.m_kb.AskProperty((Name)t);
if (beliefValue == null)
result += "[[" + t + "]]";
else
{
result += beliefValue.Value;
}
}
process = false;
}
else if (t == string.Empty)
{
process = true;
continue;
}
else
{
result += t;
}
}
return result;
}
public IEnumerable<EmotionDTO> GetAllActiveEmotions()
{
return m_emotionalState.GetAllEmotions().Select(e => e.ToDto(m_am));
}
public IEnumerable<DynamicPropertyDTO> GetAllDynamicProperties()
{
return m_kb.GetDynamicProperties();
}
public IEnumerable<BeliefDTO> GetAllBeliefs()
{
return m_kb.GetAllBeliefs().Select(b => new BeliefDTO
{
Name = b.Name.ToString(),
Perspective = b.Perspective.ToString(),
Value = b.Value.ToString(),
Certainty = b.Certainty
});
}
/// <summary>
/// Return the value associated to a belief.
/// </summary>
/// <param name="beliefName">The name of the belief to return</param>
/// <returns>The string value of the belief, or null if no belief exists.</returns>
public string GetBeliefValue(string beliefName, string perspective = Name.SELF_STRING)
{
var result = m_kb.AskProperty((Name)beliefName, (Name)perspective)?.Value.ToString();
return result;
}
/// <summary>
/// Return the value associated to a belief and its degree of certainty.
/// </summary>
/// <param name="beliefName">The name of the belief to return</param>
/// <returns>The string value of the belief, or null if no belief exists.</returns>
public ComplexValue GetBeliefValueAndCertainty(string beliefName, string perspective = Name.SELF_STRING)
{
return m_kb.AskProperty((Name)beliefName, (Name)perspective);
}
/// <summary>
/// Returns all the associated information regarding an event
/// </summary>
/// <param name="eventId">The id of the event to retrieve</param>
/// <returns>The dto containing the information of the retrieved event</returns>
public EventDTO GetEventDetails(uint eventId)
{
return this.m_am.RecallEvent(eventId).ToDTO();
}
/// <summary>
/// Retrieves the character's strongest emotion if any.
/// </summary>
public IActiveEmotion GetStrongestActiveEmotion()
{
IEnumerable<IActiveEmotion> currentActiveEmotions = m_emotionalState.GetAllEmotions();
return currentActiveEmotions.MaxValue(a => a.Intensity);
}
public void LoadAssociatedAssets(AssetStorage storage)
{
var charName = CharacterName.ToString();
m_emotionalAppraisalAsset = EmotionalAppraisalAsset.CreateInstance(storage);
m_emotionalDecisionMakingAsset = EmotionalDecisionMakingAsset.CreateInstance(storage);
m_socialImportanceAsset = SocialImportanceAsset.CreateInstance(storage);
m_commeillFautAsset = CommeillFautAsset.CreateInstance(storage);
//Dynamic properties
BindToRegistry(m_kb);
m_emotionalDecisionMakingAsset.RegisterKnowledgeBase(m_kb);
m_commeillFautAsset.RegisterKnowledgeBase(m_kb);
m_socialImportanceAsset.RegisterKnowledgeBase(m_kb);
}
public void Perceive(Name evt)
{
this.Perceive(evt, Name.SELF_SYMBOL);
}
public void Perceive(Name evt, Name observer)
{
this.Perceive(new[] { evt }, observer );
}
public void Perceive(IEnumerable<Name> events)
{
this.Perceive(events, Name.SELF_SYMBOL);
}
public void Perceive(IEnumerable<Name> events, Name observer)
{
m_socialImportanceAsset?.InvalidateCachedSI();
var idx = 0;
foreach (var e in events)
{
if (observer == Name.SELF_SYMBOL)
{
if (RPCConsts.ACTION_START_EVENT_PROTOTYPE.Match(e))
{
var subject = e.GetNTerm(2);
if (subject == this.CharacterName)
{
CurrentActionName = e.GetNTerm(3);
CurrentActionTarget = e.GetNTerm(4);
}
//Add agent
this.AddKnownAgent(subject);
}
if (RPCConsts.ACTION_END_EVENT_PROTOTYPE.Match(e))
{
var actEndEvt = EventHelper.ActionEnd(this.CharacterName.ToString(), CurrentActionName?.ToString(),
CurrentActionTarget?.ToString());
if (actEndEvt.Match(e))
{
CurrentActionName = null;
CurrentActionTarget = null;
}
this.AddKnownAgent(e.GetNTerm(2));
}
}
m_emotionalAppraisalAsset.AppraiseEvents(new[] { e }, observer, m_emotionalState, m_am, m_kb, m_goals);
idx++;
}
}
public void RemoveEmotion(EmotionDTO emotion)
{
m_emotionalState.RemoveEmotion(emotion, m_am);
}
public void ResetEmotionalState()
{
this.m_emotionalState.Clear();
}
public void ActivateIdentity(Identity id)
{
var previous = GetActiveIdentities().Where(x => x.Category == id.Category).FirstOrDefault();
if (previous != null) m_activeIdentities.Remove(previous.Name);
m_activeIdentities[id.Name] = id;
}
public void DeactivateIdentity(Identity id)
{
m_activeIdentities.Remove(id.Name);
}
public IEnumerable<Identity> GetActiveIdentities()
{
return m_activeIdentities.Values;
}
public string SerializeToJSON()
{
var s = new JSONSerializer();
return s.SerializeToJson(this).ToString(true);
}
/// <summary>
/// Updates the character's internal state. Should be called once every game tick.
/// </summary>
public void Update()
{
Tick++;
m_emotionalState.Decay(Tick);
}
/// <summary>
/// Removes a belief from the asset's knowledge base.
/// </summary>
/// <param name="name">The name of the belief to remove.</param>
/// <param name="perspective">The perspective of the belief to remove</param>
public void RemoveBelief(string name, string perspective)
{
var p = (Name)perspective;
m_kb.Tell(Name.BuildName(name), null, p);
}
public void UpdateBelief(string name, string value, float certainty = 1, string perspective = Name.SELF_STRING)
{
m_kb.Tell((Name)name, (Name)value, (Name)perspective, certainty);
}
/// <summary>
/// Updates the associated data regarding a recorded event.
/// </summary>
/// <param name="eventDTO">The dto containing the information regarding the event to update. The Id field of the dto must match the id of the event we want to update.</param>
public void UpdateEventRecord(EventDTO eventDTO)
{
this.m_am.UpdateEvent(eventDTO);
}
public override string ToString()
{
return this.CharacterName.ToString();
}
public string GetInternalStateString()
{
if (this.GetAllActiveEmotions().Any())
{
var em = this.GetStrongestActiveEmotion();
return "M: " + this.Mood.ToString("F2") +
" | S. Em: " + em.EmotionType + "(" + em.Intensity.ToString("F2") + ", " + em.Target + ")";
}
else return "M: " + this.Mood.ToString("F2");
}
public string GetSIRelationsString()
{
var result = string.Empty;
foreach (var target in this.m_otherAgents.Values)
{
var siProperty = "SI(" + target.Name + ")";
var siToTarget = int.Parse(GetBeliefValue(siProperty));
if (siToTarget > 1)
{
result += siProperty + ":" + siToTarget + ", ";
}
}
if (result != string.Empty) return result.Remove(result.Length - 2);
else return result;
}
private static IEnumerable<IAction> TakeBestActions(IEnumerable<IAction> enumerable)
{
float best = float.NegativeInfinity;
foreach (var a in enumerable.OrderByDescending(a => a.Utility))
{
if (a.Utility < best)
break;
yield return a;
best = a.Utility;
}
}
private void AddKnownAgent(Name agentName)
{
if (agentName != this.CharacterName)
{
if (!m_otherAgents.ContainsKey(agentName))
m_otherAgents.Add(agentName, new AgentEntry(agentName));
}
}
public void BindToRegistry(IDynamicPropertiesRegistry registry)
{
registry.RegistDynamicProperty(RPCConsts.MOOD_PROPERTY_NAME, MOOD_DP_DESC, MoodPropertyCalculator);
registry.RegistDynamicProperty(RPCConsts.GOAL_PROPERTY_NAME, GOAL_DP_DESC, GoalPropertyCalculator);
registry.RegistDynamicProperty(RPCConsts.TICK_PROPERTY_NAME, TICK_DP_DESC, TickPropertyCalculator);
registry.RegistDynamicProperty(RPCConsts.STRONGEST_EMOTION_PROPERTY_NAME, STRONGEST_EMOTION_PROPERTY_DP_DESC, StrongestEmotionCalculator);
registry.RegistDynamicProperty(RPCConsts.STRONGEST_EMOTION_FOR_EVENT_PROPERTY_NAME, STRONGEST_EMOTION_FOR_EVENT_PROPERTY_DP_DESC, StrongestEmotionForEventCalculator);
registry.RegistDynamicProperty(RPCConsts.STRONGEST_WELL_BEING_EMOTION_PROPERTY_NAME, STRONGEST_WELL_BEING_EMOTION_PROPERTY_DP_DESC,
StrongestWellBeingEmotionCalculator);
registry.RegistDynamicProperty(RPCConsts.STRONGEST_ATTRIBUTION_PROPERTY_NAME, STRONGEST_ATTRIBUTION_PROPERTY_DP_DESC,
StrongestAttributionEmotionCalculator);
registry.RegistDynamicProperty(RPCConsts.STRONGEST_COMPOUND_PROPERTY_NAME, STRONGEST_COMPOUND_PROPERTY_DP_DESC,
StrongestCompoundEmotionCalculator);
registry.RegistDynamicProperty(EMOTION_INTENSITY_DP_NAME, EMOTION_INTENSITY_DP_DESC, EmotionIntensityPropertyCalculator);
registry.RegistDynamicProperty(IS_AGENT_DP_NAME, IS_AGENT_DP_NAME_DESC, IsAgentPropertyCalculator);
registry.RegistDynamicProperty(ROUND_TO_TENS_DP_NAME, ROUND_TO_TENS_DP_DESC, RoundtoTensMethodCalculator);
registry.RegistDynamicProperty(ROUND_DP_NAME, ROUND_DP_DESC, RoundMethodCalculator);
registry.RegistDynamicProperty(RANDOM_DP_NAME, RANDOM_DP_DESC, RandomCalculator);
registry.RegistDynamicProperty(ID_SALIENT_DP_NAME, ID_SALIENT_DP_DESC, IsSalientPropertyCalculator);
m_am.BindToRegistry(registry);
}
#region RolePlayCharater Fields
public KB m_kb;
private AM m_am;
public CommeillFautAsset m_commeillFautAsset;
public EmotionalAppraisalAsset m_emotionalAppraisalAsset;
public EmotionalDecisionMakingAsset m_emotionalDecisionMakingAsset;
private ConcreteEmotionalState m_emotionalState;
private Dictionary<Name, AgentEntry> m_otherAgents;
public SocialImportanceAsset m_socialImportanceAsset;
public Dictionary<string, Goal> m_goals;
#endregion RolePlayCharater Fields
#region Dynamic Properties
private static readonly string MOOD_DP_DESC = "Returns the Mood value for character [x]";
private static readonly string GOAL_DP_DESC ="Returns the Goal Probability value of SELF character for goal [x]";
private static readonly string TICK_DP_DESC = "Returns the Tick value for character [x]";
private static readonly string STRONGEST_EMOTION_PROPERTY_DP_DESC = "Returns the name of the strongest emotion for character [x]";
private static readonly string STRONGEST_EMOTION_FOR_EVENT_PROPERTY_DP_DESC = "Returns the name of the strongest emotion for [cause] for character [x]";
private static readonly string STRONGEST_WELL_BEING_EMOTION_PROPERTY_DP_DESC = "Returns the name of the strongest well-being emotion for character [x]";
private static readonly string STRONGEST_ATTRIBUTION_PROPERTY_DP_DESC = "Returns the name of the strongest attribution emotion for character [x]";
private static readonly string STRONGEST_COMPOUND_PROPERTY_DP_DESC = "Returns the name of the strongest compound emotion for character [x]";
private static readonly Name EMOTION_INTENSITY_DP_NAME = (Name)"EmotionIntensity";
private static readonly string EMOTION_INTENSITY_DP_DESC = "Returns the emotion intensity of emotion [y] for character [x]";
private static readonly Name IS_AGENT_DP_NAME = (Name)"IsAgent";
private static readonly string IS_AGENT_DP_NAME_DESC = "";
private static readonly Name RANDOM_DP_NAME = (Name)"Random";
private static readonly string RANDOM_DP_DESC = "";
private static readonly Name ROUND_DP_NAME = (Name)"RoundMethod";
private static readonly string ROUND_DP_DESC = "";
private static readonly Name ROUND_TO_TENS_DP_NAME = (Name)"RoundtoTensMethod";
private static readonly string ROUND_TO_TENS_DP_DESC = "";
private static readonly Name ID_SALIENT_DP_NAME = (Name)"IdentitySalient";
private static readonly string ID_SALIENT_DP_DESC = "";
private IEnumerable<DynamicPropertyResult> EmotionIntensityPropertyCalculator(IQueryContext context, Name x, Name y)
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
Name entity = x;
Name emotionName = y;
if (entity.IsVariable)
{
foreach (var entit in context.AskPossibleProperties(entity))
{
if (emotionName.IsVariable)
{
foreach (var emot in GetAllActiveEmotions())
{
foreach (var c in context.Constraints)
{
var sub = new Substitution(entity, entit.Item1);
var sub2 = new Substitution(emotionName, new ComplexValue(Name.BuildName( emot.Type)));
if(c.AddSubstitution(sub))
if(c.AddSubstitution(sub2))
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(emot.Intensity)), c);
}
}
}
else
{
var gottem = GetAllActiveEmotions().Where(d => d.Type == emotionName.ToString());
if (gottem.Any())
{
foreach (var c in context.Constraints)
{
var sub = new Substitution(entity, entit.Item1);
if(c.AddSubstitution(sub))
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(gottem.FirstOrDefault().Intensity)), c);
}
}
}
}
}
else
{
if (emotionName.IsVariable)
{
foreach (var emot in GetAllActiveEmotions())
{
foreach (var c in context.Constraints)
{
var sub2 = new Substitution(emotionName, new ComplexValue(Name.BuildName( emot.Type)));
if(c.AddSubstitution(sub2))
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(emot.Intensity)), c);
}
}
}
else
{
var gottem = GetAllActiveEmotions().Where(d => d.Type == emotionName.ToString());
if(gottem.Any())
foreach (var c in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(gottem.OrderByDescending(i=>i.CauseEventId).FirstOrDefault().Intensity)), c);
}
}
}
}
private IEnumerable<DynamicPropertyResult> GetEmotionsForEntity(IEmotionalState state,
Name emotionName, IQueryable kb, Name perspective, IEnumerable<SubstitutionSet> constraints)
{
if (emotionName.IsVariable)
{
foreach (var emotion in state.GetAllEmotions())
{
var sub = new Substitution(emotionName, new ComplexValue((Name)emotion.EmotionType));
foreach (var c in constraints)
{
if (c.Conflicts(sub))
continue;
var newConstraints = new SubstitutionSet(c);
newConstraints.AddSubstitution(sub);
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(emotion.Intensity)), newConstraints);
}
}
}
else
{
foreach (var resultPair in kb.AskPossibleProperties(emotionName, perspective, constraints))
{
string emotionKey = resultPair.Item1.Value.ToString();
var emotion = state.GetEmotionsByType(emotionKey).OrderByDescending(e => e.Intensity).FirstOrDefault();
float value = emotion?.Intensity ?? 0;
foreach (var c in resultPair.Item2)
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(value)), c);
}
}
}
private IEnumerable<DynamicPropertyResult> IsAgentPropertyCalculator(IQueryContext context, Name x)
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
if (x.IsVariable)
{
var otherAgentsSubstitutions = m_otherAgents.Keys.Append(CharacterName).Select(n => new Substitution(x, new ComplexValue(n)));
foreach (var s in otherAgentsSubstitutions)
{
foreach (var set in context.Constraints)
{
if (set.Conflicts(s))
continue;
var r = new SubstitutionSet(set);
r.AddSubstitution(s);
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(true)), r);
}
}
yield break;
}
if (m_otherAgents.ContainsKey(x) || x == context.Queryable.Perspective)
{
if(context.Constraints.Count() == 0)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(true)), new SubstitutionSet());
}
else
{
foreach (var set in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(true)), set);
}
}
}
else
{
foreach (var set in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(false)), set);
}
}
}
private IEnumerable<DynamicPropertyResult> MoodPropertyCalculator(IQueryContext context, Name x)
// Should only accept SELF, its rpc Name our a variable that should be subbed by its name
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
if(x.IsVariable)
foreach (var resultPair in context.AskPossibleProperties(x))
{
var v = m_emotionalState.Mood;
foreach (var c in resultPair.Item2)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(v)), c);
}
}
else
{
if(x!= Name.SELF_SYMBOL && x != (Name)context.Queryable.Perspective)
yield break;
var v = m_emotionalState.Mood;
foreach (var c in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(v)), c);
}
if(!context.Constraints.Any())
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(v)), new SubstitutionSet());
}
}
private IEnumerable<DynamicPropertyResult> GoalPropertyCalculator(IQueryContext context, Name x)
// Should only accept SELF, its rpc Name our a variable that should be subbed by its name
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
if (x.IsVariable)
foreach (var resultPair in context.AskPossibleProperties(x))
{
foreach (var c in resultPair.Item2)
{
if (m_goals.ContainsKey(x.ToString()))
{
var g = m_goals[x.ToString()].Likelihood;
foreach (var cc in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(g)), cc);
}
if (!context.Constraints.Any())
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(g)), new SubstitutionSet());
}
}
}
else
{
if (m_goals.ContainsKey(x.ToString()))
{
var g = m_goals[x.ToString()].Likelihood;
foreach (var c in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(g)), c);
}
if (!context.Constraints.Any())
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(g)), new SubstitutionSet());
}
}
}
private IEnumerable<DynamicPropertyResult> TickPropertyCalculator(IQueryContext context, Name x)
// Should only accept SELF, its rpc Name our a variable that should be subbed by its name
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
if (x.IsVariable)
foreach (var resultPair in context.AskPossibleProperties(x))
{
var v = m_am.Tick;
foreach (var c in resultPair.Item2)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(v)), c);
}
}
else
{
if (x != Name.SELF_SYMBOL && x != (Name)context.Queryable.Perspective)
yield break;
var v = m_am.Tick;
foreach (var c in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(v)), c);
}
if (!context.Constraints.Any())
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(v)), new SubstitutionSet());
}
}
private IEnumerable<DynamicPropertyResult> IsSalientPropertyCalculator(IQueryContext context, Name identity)
{
foreach (var c in context.Constraints)
{
identity = identity.MakeGround(c);
if (identity.IsGrounded)
{
if (m_activeIdentities.ContainsKey(identity))
{
var id = m_activeIdentities[identity];
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(true), id.Salience), c);
}
else
{
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(false)), c);
}
}
}
}
private IEnumerable<DynamicPropertyResult> RandomCalculator(IQueryContext context, Name min, Name max)
{
var minValue = Convert.ToInt32(min.ToString());
var maxValue = Convert.ToInt32(max.ToString());
Random rand = new Random(Guid.NewGuid().GetHashCode());
var toRet = rand.Next(minValue, maxValue);
var subSet = new SubstitutionSet();
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(toRet)), subSet);
}
private IEnumerable<DynamicPropertyResult> RoundMethodCalculator(IQueryContext context, Name x, Name digits)
{
var y_value = Convert.ToInt32(digits.ToString());
if (x.IsVariable)
{
foreach (var c in context.Constraints)
{
foreach (var sub in c)
{
if (sub.Variable == x)
{
var toRet = Convert.ToDouble(sub.SubValue.ToString());
// Console.WriteLine("Round method calculation for: " + x.ToString() + " the value : " + toRet);
toRet = Math.Round(toRet, y_value);
// Console.WriteLine("Round method calculation for: " + x.ToString() + " rounded value " + sub.Value.ToString() + " digits: " + y_value + " result : " + toRet);
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(toRet)), c);
}
}
}
}
}
private IEnumerable<DynamicPropertyResult> RoundtoTensMethodCalculator(IQueryContext context, Name x, Name digits)
{
var y_value = Convert.ToInt32(digits.ToString());
var toTens = Math.Pow(10, y_value);
if (x.IsVariable)
{
foreach (var c in context.Constraints)
{
foreach (var sub in c)
{
if (sub.Variable == x)
{
var toRet = Convert.ToDouble(sub.SubValue.ToString());
// Console.WriteLine("Round method calculation for: " + x.ToString() + " the value : " + toRet);
toRet = toRet / toTens;
toRet = Math.Round(toRet, 0);
toRet = toRet * toTens;
// Console.WriteLine("Round method calculation for: " + x.ToString() + " rounded value " + sub.Value.ToString()+ " result : " + toRet);
yield return new DynamicPropertyResult(new ComplexValue(Name.BuildName(toRet)), c);
}
}
}
}
}
private IEnumerable<DynamicPropertyResult> StrongestAttributionEmotionCalculator(IQueryContext context, Name x)
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
var emotions = m_emotionalState.GetAllEmotions();
if (!emotions.Any())
{
yield break;
}
var attributionEmotions = emotions.Where(
em => em.EmotionType == OCCEmotionType.Shame.Name
|| em.EmotionType == OCCEmotionType.Pride.Name
|| em.EmotionType == OCCEmotionType.Reproach.Name
|| em.EmotionType == OCCEmotionType.Admiration.Name);
if (!attributionEmotions.Any())
{
yield break;
}
var emo = attributionEmotions.MaxValue(em => em.Intensity);
var emoValue = emo.EmotionType;
if (x.IsVariable)
{
var sub = new Substitution(x, new ComplexValue(context.Queryable.Perspective));
foreach (var c in context.Constraints)
{
if (c.AddSubstitution(sub))
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), c);
}
}
else
{
foreach (var resultPair in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), resultPair);
}
}
}
private IEnumerable<DynamicPropertyResult> StrongestCompoundEmotionCalculator(IQueryContext context, Name x)
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
var emotions = m_emotionalState.GetAllEmotions();
if (!emotions.Any())
{
yield break;
}
var compoundEmotions = emotions.Where(
em => em.EmotionType == OCCEmotionType.Gratification.Name
|| em.EmotionType == OCCEmotionType.Gratitude.Name
|| em.EmotionType == OCCEmotionType.Remorse.Name
|| em.EmotionType == OCCEmotionType.Anger.Name);
if (!compoundEmotions.Any())
{
yield break;
}
var emo = compoundEmotions.MaxValue(em => em.Intensity);
var emoValue = emo.EmotionType;
if (x.IsVariable)
{
var sub = new Substitution(x, new ComplexValue(context.Queryable.Perspective));
foreach (var c in context.Constraints)
{
if (c.AddSubstitution(sub))
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), c);
}
}
else
{
foreach (var cont in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), cont);
}
}
}
private IEnumerable<DynamicPropertyResult> StrongestEmotionCalculator(IQueryContext context, Name x)
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
var emo = m_emotionalState.GetStrongestEmotion();
if (emo == null)
yield break;
var emoValue = emo.EmotionType;
if (x.IsVariable)
{
var sub = new Substitution(x, new ComplexValue(context.Queryable.Perspective));
foreach (var c in context.Constraints)
{
if (c.AddSubstitution(sub))
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), c);
}
}
else
{
foreach (var c in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), c);
}
}
}
private IEnumerable<DynamicPropertyResult> StrongestEmotionForEventCalculator(IQueryContext context, Name x, Name cause)
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
Dictionary<Name, IActiveEmotion> emoList = new Dictionary<Name, IActiveEmotion>();
if (cause.IsVariable) // Event is a variable
{
foreach (var ev in context.AskPossibleProperties(cause))
{
var emo = m_emotionalState.GetStrongestEmotion(cause, m_am);
if (emo != null)
{
var emoValue = emo.EmotionType;
var causeSub = new Substitution(cause, ev.Item1);
if (x.IsVariable)
{
var sub = new Substitution(x, new ComplexValue(context.Queryable.Perspective));
foreach (var c in context.Constraints)
{
if (c.AddSubstitution(causeSub))
if (c.AddSubstitution(sub))
yield return new DynamicPropertyResult(new ComplexValue((Name) emoValue),
c);
}
}
else
{
foreach (var resultPair in context.AskPossibleProperties(x))
{
foreach (var c in resultPair.Item2)
if (c.AddSubstitution(causeSub))
yield return new DynamicPropertyResult(new ComplexValue((Name) emoValue),c);
}
}
}
}
foreach (var eve in this.EventRecords){ // If cause is a variable Im going through all events and emotions associated with them
var sub = new Substitution(cause, new ComplexValue((Name)eve.Event));
var resultingEmotions = this.GetAllActiveEmotions().Where(y => y.CauseEventId == eve.Id);
var emoValue = resultingEmotions.MaxValue(e => e.Intensity);
foreach (var c in context.Constraints)
{
if (c.AddSubstitution(sub))
yield return new DynamicPropertyResult(
new ComplexValue(Name.BuildName(emoValue.Intensity)), c);
}
}
}
else
{
var emo = m_emotionalState.GetStrongestEmotion(cause, m_am);
if (emo == null)
{
yield break;
}
var emoValue = emo.EmotionType;
if (x.IsVariable)
{
var sub = new Substitution(x, new ComplexValue(context.Queryable.Perspective));
foreach (var c in context.Constraints)
{
if (c.AddSubstitution(sub))
yield return new DynamicPropertyResult(new ComplexValue((Name) emoValue), c);
}
}
else
{
foreach (var resultPair in context.AskPossibleProperties(x))
{
foreach (var c in resultPair.Item2)
yield return new DynamicPropertyResult(new ComplexValue((Name) emoValue), c);
}
}
}
}
private IEnumerable<DynamicPropertyResult> StrongestWellBeingEmotionCalculator(IQueryContext context, Name x)
{
if (context.Perspective != Name.SELF_SYMBOL)
yield break;
var emotions = m_emotionalState.GetAllEmotions();
if (!emotions.Any())
{
yield break;
}
var wellBeingEmotions = emotions.Where(
em => em.EmotionType == OCCEmotionType.Joy.Name
|| em.EmotionType == OCCEmotionType.Distress.Name);
if (!wellBeingEmotions.Any())
{
yield break;
}
var emo = wellBeingEmotions.MaxValue(em => em.Intensity);
var emoValue = emo.EmotionType;
if (x.IsVariable)
{
var sub = new Substitution(x, new ComplexValue(context.Queryable.Perspective));
foreach (var c in context.Constraints)
{
if (c.AddSubstitution(sub))
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), c);
}
}
else
{
foreach (var resultPair in context.Constraints)
{
yield return new DynamicPropertyResult(new ComplexValue((Name)emoValue), resultPair);
}
}
}
#endregion Dynamic Properties
/// @cond DEV
#region ICustomSerialization
public void GetObjectData(ISerializationData dataHolder, ISerializationContext context)
{
dataHolder.SetValue("KnowledgeBase", m_kb);
dataHolder.SetValue("BodyName", this.BodyName);
dataHolder.SetValue("VoiceName", this.VoiceName);
dataHolder.SetValue("EmotionalState", m_emotionalState);
dataHolder.SetValue("AutobiographicMemory", m_am);
dataHolder.SetValue("OtherAgents", m_otherAgents);
dataHolder.SetValue("Goals", m_goals.Values.ToArray());
}
public void SetObjectData(ISerializationData dataHolder, ISerializationContext context)
{
m_activeIdentities = new Dictionary<Name, Identity>();
m_kb = dataHolder.GetValue<KB>("KnowledgeBase");
this.BodyName = dataHolder.GetValue<string>("BodyName");
this.VoiceName = dataHolder.GetValue<string>("VoiceName");
m_emotionalState = dataHolder.GetValue<ConcreteEmotionalState>("EmotionalState");
m_goals = new Dictionary<string, Goal>();
var goals = dataHolder.GetValue<Goal[]>("Goals");
if (goals != null)
{
foreach (var g in goals)
{
m_goals.Add(g.Name.ToString(), g);
}
}
m_am = dataHolder.GetValue<AM>("AutobiographicMemory");
m_otherAgents = dataHolder.GetValue<Dictionary<Name, AgentEntry>>("OtherAgents");
if (m_otherAgents == null) { m_otherAgents = new Dictionary<Name, AgentEntry>(); }
BindToRegistry(m_kb);
}
/// @endcond
#endregion ICustomSerialization
}
} | 412 | 0.906595 | 1 | 0.906595 | game-dev | MEDIA | 0.562154 | game-dev,web-backend | 0.908267 | 1 | 0.908267 |
robovines6955/Stampede | 11,255 | FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/external/samples/ConceptGamepadRumble.java | package org.firstinspires.ftc.robotcontroller.external.samples;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.Gamepad;
import com.qualcomm.robotcore.util.ElapsedTime;
/*
* This OpMode illustrates using the rumble feature of many gamepads.
*
* Note: Some gamepads "rumble" better than others.
* The Xbox & PS4 have a left (rumble1) and right (rumble2) rumble motor.
* These two gamepads have two distinct rumble modes: Large on the left, and small on the right
* The Etpark gamepad may only respond to rumble1, and may only run at full power.
* The Logitech F310 gamepad does not have *any* rumble ability.
*
* Moral: You should use this sample to experiment with your specific gamepads to explore their rumble features.
*
* The rumble motors are accessed through the standard gamepad1 and gamepad2 objects.
* Several new methods were added to the Gamepad class in FTC SDK Rev 7
* The key methods are as follows:
*
* .rumble(double rumble1, double rumble2, int durationMs)
* This method sets the rumble power of both motors for a specific time duration.
* Both rumble arguments are motor-power levels in the 0.0 to 1.0 range.
* durationMs is the desired length of the rumble action in milliseconds.
* This method returns immediately.
* Note:
* Use a durationMs of Gamepad.RUMBLE_DURATION_CONTINUOUS to provide a continuous rumble
* Use a power of 0, or duration of 0 to stop a rumble.
*
* .rumbleBlips(int count) allows an easy way to signal the driver with a series of rumble blips.
* Just specify how many blips you want.
* This method returns immediately.
*
* .runRumbleEffect(customRumbleEffect) allows you to run a custom rumble sequence that you have
* built using the Gamepad.RumbleEffect.Builder()
* A "custom effect" is a sequence of steps, where each step can rumble any of the
* rumble motors for a specific period at a specific power level.
* The Custom Effect will play as the (un-blocked) OpMode continues to run
*
* .isRumbling() returns true if there is a rumble effect in progress.
* Use this call to prevent stepping on a current rumble.
*
* .stopRumble() Stop any ongoing rumble or custom rumble effect.
*
* .rumble(int durationMs) Full power rumble for fixed duration.
*
* Note: Whenever a new Rumble command is issued, any currently executing rumble action will
* be truncated, and the new action started immediately. Take these precautions:
* 1) Do Not SPAM the rumble motors by issuing rapid fire commands
* 2) Multiple sources for rumble commands must coordinate to avoid tromping on each other.
*
* This can be achieved several possible ways:
* 1) Only having one source for rumble actions
* 2) Issuing rumble commands on transitions, rather than states.
* e.g. The moment a touch sensor is pressed, rather than the entire time it is being pressed.
* 3) Scheduling rumble commands based on timed events. e.g. 10 seconds prior to endgame
* 4) Rumble on non-overlapping mechanical actions. e.g. arm fully-extended or fully-retracted.
* 5) Use isRumbling() to hold off on a new rumble if one is already in progress.
*
* The examples shown here are representstive of how to invoke a gamepad rumble.
* It is assumed that these will be modified to suit the specific robot and team strategy needs.
*
* ######## Read the telemetry display on the Driver Station Screen for instructions. ######
*
* Ex 1) This example shows a) how to create a custom rumble effect, and then b) how to trigger it based
* on game time. One use for this might be to alert the driver that half-time or End-game is approaching.
*
* Ex 2) This example shows tying the rumble power to a changing sensor value.
* In this case it is the Gamepad trigger, but it could be any sensor output scaled to the 0-1 range.
* Since it takes over the rumble motors, it is only performed when the Left Bumper is pressed.
* Note that this approach MUST include a way to turn OFF the rumble when the button is released.
*
* Ex 3) This example shows a simple way to trigger a 3-blip sequence. In this case it is
* triggered by the gamepad A (Cross) button, but it could be any sensor, like a touch or light sensor.
* Note that this code ensures that it only rumbles once when the input goes true.
*
* Ex 4) This example shows how to trigger a single rumble when an input value gets over a certain value.
* In this case it is reading the Right Trigger, but it could be any variable sensor, like a
* range sensor, or position sensor. The code needs to ensure that it is only triggered once, so
* it waits till the sensor drops back below the threshold before it can trigger again.
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this OpMode to the Driver Station OpMode list.
*/
@Disabled
@TeleOp(name="Concept: Gamepad Rumble", group ="Concept")
public class ConceptGamepadRumble extends LinearOpMode
{
boolean lastA = false; // Use to track the prior button state.
boolean lastLB = false; // Use to track the prior button state.
boolean highLevel = false; // used to prevent multiple level-based rumbles.
boolean secondHalf = false; // Use to prevent multiple half-time warning rumbles.
Gamepad.RumbleEffect customRumbleEffect; // Use to build a custom rumble sequence.
ElapsedTime runtime = new ElapsedTime(); // Use to determine when end game is starting.
final double HALF_TIME = 60.0; // Wait this many seconds before rumble-alert for half-time.
final double TRIGGER_THRESHOLD = 0.75; // Squeeze more than 3/4 to get rumble.
@Override
public void runOpMode()
{
// Example 1. a) start by creating a three-pulse rumble sequence: right, LEFT, LEFT
customRumbleEffect = new Gamepad.RumbleEffect.Builder()
.addStep(0.0, 1.0, 500) // Rumble right motor 100% for 500 mSec
.addStep(0.0, 0.0, 300) // Pause for 300 mSec
.addStep(1.0, 0.0, 250) // Rumble left motor 100% for 250 mSec
.addStep(0.0, 0.0, 250) // Pause for 250 mSec
.addStep(1.0, 0.0, 250) // Rumble left motor 100% for 250 mSec
.build();
telemetry.addData(">", "Press Start");
telemetry.update();
waitForStart();
runtime.reset(); // Start game timer.
// Loop while monitoring buttons for rumble triggers
while (opModeIsActive())
{
// Read and save the current gamepad button states.
boolean currentA = gamepad1.a ;
boolean currentLB = gamepad1.left_bumper ;
// Display the current Rumble status. Just for interest.
telemetry.addData(">", "Are we RUMBLING? %s\n", gamepad1.isRumbling() ? "YES" : "no" );
// ----------------------------------------------------------------------------------------
// Example 1. b) Watch the runtime timer, and run the custom rumble when we hit half-time.
// Make sure we only signal once by setting "secondHalf" flag to prevent further rumbles.
// ----------------------------------------------------------------------------------------
if ((runtime.seconds() > HALF_TIME) && !secondHalf) {
gamepad1.runRumbleEffect(customRumbleEffect);
secondHalf =true;
}
// Display the time remaining while we are still counting down.
if (!secondHalf) {
telemetry.addData(">", "Halftime Alert Countdown: %3.0f Sec \n", (HALF_TIME - runtime.seconds()) );
}
// ----------------------------------------------------------------------------------------
// Example 2. If Left Bumper is being pressed, power the rumble motors based on the two trigger depressions.
// This is useful to see how the rumble feels at various power levels.
// ----------------------------------------------------------------------------------------
if (currentLB) {
// Left Bumper is being pressed, so send left and right "trigger" values to left and right rumble motors.
gamepad1.rumble(gamepad1.left_trigger, gamepad1.right_trigger, Gamepad.RUMBLE_DURATION_CONTINUOUS);
// Show what is being sent to rumbles
telemetry.addData(">", "Squeeze triggers to control rumbles");
telemetry.addData("> : Rumble", "Left: %.0f%% Right: %.0f%%", gamepad1.left_trigger * 100, gamepad1.right_trigger * 100);
} else {
// Make sure rumble is turned off when Left Bumper is released (only one time each press)
if (lastLB) {
gamepad1.stopRumble();
}
// Prompt for manual rumble action
telemetry.addData(">", "Hold Left-Bumper to test Manual Rumble");
telemetry.addData(">", "Press A (Cross) for three blips");
telemetry.addData(">", "Squeeze right trigger slowly for 1 blip");
}
lastLB = currentLB; // remember the current button state for next time around the loop
// ----------------------------------------------------------------------------------------
// Example 3. Blip 3 times at the moment that A (Cross) is pressed. (look for pressed transition)
// BUT !!! Skip it altogether if the Gamepad is already rumbling.
// ----------------------------------------------------------------------------------------
if (currentA && !lastA) {
if (!gamepad1.isRumbling()) // Check for possible overlap of rumbles.
gamepad1.rumbleBlips(3);
}
lastA = currentA; // remember the current button state for next time around the loop
// ----------------------------------------------------------------------------------------
// Example 4. Rumble once when gamepad right trigger goes above the THRESHOLD.
// ----------------------------------------------------------------------------------------
if (gamepad1.right_trigger > TRIGGER_THRESHOLD) {
if (!highLevel) {
gamepad1.rumble(0.9, 0, 200); // 200 mSec burst on left motor.
highLevel = true; // Hold off any more triggers
}
} else {
highLevel = false; // We can trigger again now.
}
// Send the telemetry data to the Driver Station, and then pause to pace the program.
telemetry.update();
sleep(10);
}
}
}
| 412 | 0.872996 | 1 | 0.872996 | game-dev | MEDIA | 0.500426 | game-dev,desktop-app | 0.607006 | 1 | 0.607006 |
Froser/gamemachine | 2,913 | src/3rdparty/bullet3-2.87/src/BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.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_BOX_2D_BOX_2D__COLLISION_ALGORITHM_H
#define BT_BOX_2D_BOX_2D__COLLISION_ALGORITHM_H
#include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
class btPersistentManifold;
///box-box collision detection
class btBox2dBox2dCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
bool m_ownManifold;
btPersistentManifold* m_manifoldPtr;
public:
btBox2dBox2dCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
: btActivatingCollisionAlgorithm(ci) {}
virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
btBox2dBox2dCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);
virtual ~btBox2dBox2dCollisionAlgorithm();
virtual void getAllContactManifolds(btManifoldArray& manifoldArray)
{
if (m_manifoldPtr && m_ownManifold)
{
manifoldArray.push_back(m_manifoldPtr);
}
}
struct CreateFunc :public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
int bbsize = sizeof(btBox2dBox2dCollisionAlgorithm);
void* ptr = ci.m_dispatcher1->allocateCollisionAlgorithm(bbsize);
return new(ptr) btBox2dBox2dCollisionAlgorithm(0,ci,body0Wrap,body1Wrap);
}
};
};
#endif //BT_BOX_2D_BOX_2D__COLLISION_ALGORITHM_H
| 412 | 0.898029 | 1 | 0.898029 | game-dev | MEDIA | 0.986996 | game-dev | 0.68311 | 1 | 0.68311 |
DecentSoftware-eu/DecentHolograms | 1,097 | nms/nms-v1_20_R3/src/main/java/eu/decentsoftware/holograms/nms/v1_20_R3/EntityTypeRegistry.java | package eu.decentsoftware.holograms.nms.v1_20_R3;
import eu.decentsoftware.holograms.nms.api.DecentHologramsNmsException;
import net.minecraft.world.entity.EntityTypes;
import org.bukkit.entity.EntityType;
import java.util.Optional;
final class EntityTypeRegistry {
private static final float SLIME_BASE_HEIGHT = 0.51000005f;
private EntityTypeRegistry() {
throw new IllegalStateException("Utility class");
}
static double getEntityTypeHeight(EntityType entityType) {
if (entityType == EntityType.SLIME) {
// Slime height is 2.04 in NMS, which is incorrect for a size 1 Slime
return SLIME_BASE_HEIGHT;
}
return findEntityTypes(entityType).n().b;
}
static EntityTypes<?> findEntityTypes(EntityType entityType) {
String key = entityType.getKey().getKey();
Optional<EntityTypes<?>> entityTypes = EntityTypes.a(key);
if (entityTypes.isPresent()) {
return entityTypes.get();
}
throw new DecentHologramsNmsException("Invalid entity type: " + entityType);
}
}
| 412 | 0.500337 | 1 | 0.500337 | game-dev | MEDIA | 0.938875 | game-dev | 0.711602 | 1 | 0.711602 |
phillipchain/LoLServer | 1,649 | Content/LeagueSandbox-Scripts/Items/Actives/SightWard.cs | using static LeagueSandbox.GameServer.API.ApiFunctionManager;
using LeagueSandbox.GameServer.Scripting.CSharp;
using GameServerCore.Enums;
using System.Numerics;
using GameServerCore.Scripting.CSharp;
using LeagueSandbox.GameServer.GameObjects.AttackableUnits.AI;
using LeagueSandbox.GameServer.GameObjects.AttackableUnits;
using LeagueSandbox.GameServer.GameObjects.SpellNS;
namespace ItemSpells
{
public class SightWard : ISpellScript
{
Minion ward;
public SpellScriptMetadata ScriptMetadata => new SpellScriptMetadata()
{
TriggersSpellCasts = true,
};
public void OnSpellPreCast(ObjAIBase owner, Spell spell, AttackableUnit target, Vector2 start, Vector2 end)
{
var Cursor = new Vector2(spell.CastInfo.TargetPosition.X, spell.CastInfo.TargetPosition.Z);
var current = new Vector2(owner.Position.X, owner.Position.Y);
var distance = Cursor - current;
Vector2 truecoords;
if (distance.Length() > 500f)
{
distance = Vector2.Normalize(distance);
var range = distance * 500f;
truecoords = current + range;
}
else
{
truecoords = Cursor;
}
ward = AddMinion(owner, "SightWard", "SightWard", truecoords, owner.Team, owner.SkinID, false, true);
ward.SetCollisionRadius(0.0f);
ward.SetStatus(StatusFlags.Ghosted, true);
AddParticle(owner, null, "SightWard.troy", truecoords);
AddBuff("SightWard", 65f, 1, spell, ward, ward);
}
}
} | 412 | 0.921188 | 1 | 0.921188 | game-dev | MEDIA | 0.967555 | game-dev | 0.925566 | 1 | 0.925566 |
magefree/mage | 1,904 | Mage.Sets/src/mage/cards/s/SterlingGrove.java |
package mage.cards.s;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.effects.common.continuous.GainAbilityControlledEffect;
import mage.abilities.effects.common.search.SearchLibraryPutOnLibraryEffect;
import mage.abilities.keyword.ShroudAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Zone;
import mage.filter.common.FilterEnchantmentCard;
import mage.filter.common.FilterEnchantmentPermanent;
import mage.target.common.TargetCardInLibrary;
/**
*
* @author emerald000
*/
public final class SterlingGrove extends CardImpl {
public SterlingGrove(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{G}{W}");
// Other enchantments you control have shroud.
this.addAbility(new SimpleStaticAbility(new GainAbilityControlledEffect(ShroudAbility.getInstance(), Duration.WhileOnBattlefield, new FilterEnchantmentPermanent("enchantments"), true)));
// {1}, Sacrifice Sterling Grove: Search your library for an enchantment card and reveal that card. Shuffle your library, then put the card on top of it.
Ability ability = new SimpleActivatedAbility(new SearchLibraryPutOnLibraryEffect(new TargetCardInLibrary(new FilterEnchantmentCard("enchantment card")), true), new GenericManaCost(1));
ability.addCost(new SacrificeSourceCost());
this.addAbility(ability);
}
private SterlingGrove(final SterlingGrove card) {
super(card);
}
@Override
public SterlingGrove copy() {
return new SterlingGrove(this);
}
}
| 412 | 0.913254 | 1 | 0.913254 | game-dev | MEDIA | 0.978752 | game-dev | 0.981904 | 1 | 0.981904 |
hecrj/zelda | 3,460 | src/entity/mob/ai/chase_evade.cpp | #include "chase_evade.hpp"
ChaseEvade::ChaseEvade(Mob* mob) :
super(mob),
direction_(Dir::random()),
wander_(mob),
period_duration_(50),
current_duration_(0),
alert(false)
{}
bool ChaseEvade::Detected(Entity* destiny_entity){
float diffX = mob_->position().x-destiny_entity->position().x;
float diffY = mob_->position().y-destiny_entity->position().y;
float diffXaux = (diffX>0)?diffX:-diffX;
float diffYaux = (diffY>0)?diffY:-diffY;
const Dir aux = mob_->facing();
if (aux.vector().x==1 && diffYaux > diffXaux && diffX < 0)
return true;
else if (aux.vector().x==-1 && diffYaux > diffXaux && diffX > 0)
return true;
else if (aux.vector().y==-1 && diffXaux > diffYaux && diffY > 0)
return true;
else if (aux.vector().y==1 && diffXaux > diffYaux && diffY < 0)
return true;
else
return false;
}
bool ChaseEvade::Lost(Entity* destiny_entity){
float diffX = mob_->position().x-destiny_entity->position().x;
float diffY = mob_->position().y-destiny_entity->position().y;
const Dir aux = mob_->facing();
if (aux.vector().x==1 && diffX > 0)
return true;
else if (aux.vector().x==-1 && diffX < 0)
return true;
else if (aux.vector().y==-1 && diffY < 0)
return true;
else if (aux.vector().y==1 && diffY > 0)
return true;
else
return false;
}
Dir ChaseEvade::Contrary(Dir aux){
if (aux.vector().x==1)
return Dir::LEFT;
else if (aux.vector().x==-1)
return Dir::RIGHT;
else if (aux.vector().y==1)
return Dir::UP;
else return Dir::DOWN;
}
Dir ChaseEvade::Evade(Dir aux){
if (aux.vector().x==1)
return Dir::UP;
else if (aux.vector().x==-1)
return Dir::DOWN;
else if (aux.vector().y==1)
return Dir::LEFT;
else return Dir::RIGHT;
}
void ChaseEvade::Update(double delta) {
Entity* destiny_entity = mob_->SeekPlayer();
float diffX = mob_->position().x-destiny_entity->position().x;
float diffY = mob_->position().y-destiny_entity->position().y;
float diffXaux = (diffX>0)?diffX:-diffX;
float diffYaux = (diffY>0)?diffY:-diffY;
if (mob_->Distance(destiny_entity) > 150 || (!alert && !Detected(destiny_entity)) || (alert && Lost(destiny_entity))){
alert = false;
wander_.Update(delta);
}
else{
alert = true;
if (current_duration_%10>0)
--current_duration_;
else if (current_duration_>0){
if (diffYaux < mob_->height())
direction_ = (diffX>0)?Dir::LEFT:Dir::RIGHT;
else if (diffXaux < mob_->width())
direction_ = (diffY>0)?Dir::UP:Dir::DOWN;
--current_duration_;
}
else{
if (diffYaux < mob_->height())
direction_ = (diffX>0)?Dir::LEFT:Dir::RIGHT;
else if (diffXaux < mob_->width())
direction_ = (diffY>0)?Dir::UP:Dir::DOWN;
else if (diffYaux > diffXaux/3.0f)
direction_ = (diffY>0)?Dir::UP:Dir::DOWN;
else
direction_ = (diffX>0)?Dir::LEFT:Dir::RIGHT;
current_duration_ = period_duration_;
}
if (!mob_->Move(direction_,delta)){
//mob_->Move(Contrary(direction_),delta);
mob_->Move(Evade(direction_),delta);
}
}
}
void ChaseEvade::Debug() const {
}
| 412 | 0.849938 | 1 | 0.849938 | game-dev | MEDIA | 0.605044 | game-dev | 0.931067 | 1 | 0.931067 |
FingerCaster/UGFExtensions | 1,110 | Assets/Extensions/TimingWheel/ETTaskAsync/ETCancellationToken.cs | using System;
using System.Collections.Generic;
namespace ET
{
public class ETCancellationToken
{
private HashSet<Action> actions = new HashSet<Action>();
public void Add(Action callback)
{
// 如果action是null,绝对不能添加,要抛异常,说明有协程泄漏
this.actions.Add(callback);
}
public void Remove(Action callback)
{
this.actions?.Remove(callback);
}
public bool IsCancel()
{
return this.actions == null;
}
public void Cancel()
{
if (this.actions == null)
{
return;
}
this.Invoke();
}
private void Invoke()
{
HashSet<Action> runActions = this.actions;
this.actions = null;
try
{
foreach (Action action in runActions)
{
action.Invoke();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
} | 412 | 0.600263 | 1 | 0.600263 | game-dev | MEDIA | 0.607038 | game-dev | 0.710122 | 1 | 0.710122 |
ka0un/OPProtector | 1,024 | src/main/java/org/kasun/opprotector/Listners/ListnerManager.java | package org.kasun.opprotector.Listners;
import org.kasun.opprotector.OPProtector;
public class ListnerManager {
OPProtector plugin = OPProtector.getInstance();
public ListnerManager() {
plugin.getServer().getPluginManager().registerEvents(new PlayerJoin(), plugin);
plugin.getServer().getPluginManager().registerEvents(new PlayerMove(), plugin);
plugin.getServer().getPluginManager().registerEvents(new PlayerCommand(), plugin);
plugin.getServer().getPluginManager().registerEvents(new ServerCommand(), plugin);
plugin.getServer().getPluginManager().registerEvents(new PlayerBlockBreak(), plugin);
plugin.getServer().getPluginManager().registerEvents(new PlayerBlockPlace(), plugin);
plugin.getServer().getPluginManager().registerEvents(new PlayerItemDrop(), plugin);
plugin.getServer().getPluginManager().registerEvents(new PlayerLeave(), plugin);
plugin.getServer().getPluginManager().registerEvents(new PlayerMessage(), plugin);
}
}
| 412 | 0.735026 | 1 | 0.735026 | game-dev | MEDIA | 0.609782 | game-dev | 0.853054 | 1 | 0.853054 |
nascentxyz/pyrometer | 37,807 | crates/graph/src/solvers/brute.rs | use crate::{
elem::{Elem, RangeElem},
nodes::{Concrete, ContextVarNode, VarNode},
solvers::{
dl::{DLSolver, SolveStatus},
Atomize, SolverAtom,
},
AnalyzerBackend, GraphBackend, Range, RangeEval, SolcRange,
};
use shared::{GraphError, RangeArena};
use ethers_core::types::U256;
use std::collections::BTreeMap;
pub trait SolcSolver {
fn simplify(&mut self, analyzer: &impl AnalyzerBackend, arena: &mut RangeArena<Elem<Concrete>>);
fn solve(
&mut self,
analyzer: &mut impl AnalyzerBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<AtomicSolveStatus, GraphError>;
fn recurse_check(
&mut self,
idx: usize,
solved_atomics: &mut Vec<usize>,
analyzer: &mut impl AnalyzerBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<bool, GraphError>;
fn check(
&mut self,
solved_for: usize,
lmr: (Elem<Concrete>, Elem<Concrete>, Elem<Concrete>),
solved_atomics: &mut Vec<usize>,
analyzer: &mut impl AnalyzerBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<(bool, Option<HintOrRanges>), GraphError>;
}
pub enum AtomicSolveStatus {
Unsat,
Sat(AtomicSolveMap),
Indeterminate,
}
pub type AtomicSolveMap = BTreeMap<Atomic, Concrete>;
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub struct Atomic {
pub idxs: Vec<ContextVarNode>,
}
#[derive(Clone, Debug)]
pub struct BruteBinSearchSolver {
pub deps: Vec<ContextVarNode>,
pub solves: BTreeMap<Atomic, Elem<Concrete>>,
pub atomics: Vec<Atomic>,
// This is private due to wanting to ensure we construct the ranges correctly via `as_simplified_range`
ranges: BTreeMap<ContextVarNode, SolcRange>,
atomic_ranges: BTreeMap<Atomic, SolcRange>,
pub lmrs: Vec<LMR>,
pub intermediate_ranges: BTreeMap<ContextVarNode, SolcRange>,
pub intermediate_atomic_ranges: BTreeMap<Atomic, SolcRange>,
pub sat: bool,
pub start_idx: usize,
pub successful_passes: usize,
}
#[derive(Clone, Debug)]
pub struct LMR {
pub low: Elem<Concrete>,
pub mid: Elem<Concrete>,
pub high: Elem<Concrete>,
}
impl From<(Elem<Concrete>, Elem<Concrete>, Elem<Concrete>)> for LMR {
fn from((low, mid, high): (Elem<Concrete>, Elem<Concrete>, Elem<Concrete>)) -> Self {
Self { low, mid, high }
}
}
pub enum HintOrRanges {
Higher,
Lower,
Ranges(BTreeMap<ContextVarNode, SolcRange>),
}
impl BruteBinSearchSolver {
pub fn maybe_new(
deps: Vec<ContextVarNode>,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<Option<Self>, GraphError> {
let mut atomic_idxs = vec![];
let mut ranges = BTreeMap::default();
let mut atomic_ranges = BTreeMap::default();
deps.iter().try_for_each(|dep| {
let mut range = dep.range(analyzer)?.unwrap();
if range.unsat(analyzer, arena) {
panic!(
"initial range for {} not sat",
dep.display_name(analyzer).unwrap()
);
}
let r: SolcRange = range.flattened_range(analyzer, arena)?.into_owned().into();
atomic_idxs.extend(r.dependent_on(analyzer, arena));
ranges.insert(*dep, r);
Ok(())
})?;
// Sometimes a storage variable will be split due to a context fork. We recombine them here
atomic_idxs.sort();
atomic_idxs.dedup();
// atomic_idxs.iter().for_each(|dep| {
// println!(
// "atomic dep: {} - {}",
// dep.display_name(analyzer).unwrap(),
// dep.0
// )
// });
// let atomics = atomic_idxs;
let mut storage_atomics: BTreeMap<VarNode, Vec<ContextVarNode>> = BTreeMap::default();
let mut calldata_atomics = vec![];
atomic_idxs.into_iter().try_for_each(|atomic| {
if atomic.is_storage(analyzer)? {
// its a storage variable, get the parent var
if atomic.is_dyn(analyzer)? {
} else {
let entry = storage_atomics
.entry(atomic.maybe_storage_var(analyzer).unwrap())
.or_default();
entry.push(atomic);
entry.sort();
entry.dedup();
}
} else {
calldata_atomics.push(atomic);
}
Ok(())
})?;
let mut atomics: Vec<Atomic> = vec![];
storage_atomics
.into_iter()
.for_each(|(_k, same_atomics)| atomics.push(Atomic { idxs: same_atomics }));
atomics.extend(
calldata_atomics
.into_iter()
.map(|atomic| Atomic { idxs: vec![atomic] })
.collect::<Vec<_>>(),
);
atomics.iter().try_for_each(|atomic| {
let range = atomic.idxs[0].range(analyzer)?.unwrap();
atomic_ranges.insert(atomic.clone(), range);
Ok(())
})?;
if let Some((dep, unsat_range)) = ranges
.iter()
.find(|(_, range)| range.unsat(analyzer, arena))
{
panic!(
"Initial ranges not sat for dep {}: {} {}",
dep.display_name(analyzer).unwrap(),
unsat_range.min,
unsat_range.max
);
}
if ranges.len() != deps.len() {
panic!("HERE");
}
let mut s = Self {
deps,
solves: Default::default(),
atomics,
intermediate_ranges: ranges.clone(),
ranges,
intermediate_atomic_ranges: atomic_ranges.clone(),
atomic_ranges,
lmrs: vec![],
sat: true,
start_idx: 0,
successful_passes: 0,
};
s.reset_lmrs(analyzer, arena);
Ok(Some(s))
}
pub fn lmr(
&self,
atomic: &Atomic,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> (Elem<Concrete>, Elem<Concrete>, Elem<Concrete>) {
let range = &self.atomic_ranges[atomic];
let mut min = range.evaled_range_min(analyzer, arena).unwrap();
min.cache_minimize(analyzer, arena).unwrap();
// println!("min: {}", min.minimize(analyzer).unwrap().to_range_string(false, analyzer, arena).s);
let mut max = range.evaled_range_max(analyzer, arena).unwrap();
max.cache_maximize(analyzer, arena).unwrap();
let mut mid = (min.clone() + max.clone()) / Elem::from(Concrete::from(U256::from(2)));
mid.cache_maximize(analyzer, arena).unwrap();
(min, mid, max)
}
pub fn reset_lmrs(
&mut self,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) {
self.lmrs = vec![];
(0..self.atomic_ranges.len()).for_each(|i| {
self.lmrs
.push(self.lmr(&self.atomics[i], analyzer, arena).into());
});
}
pub fn reset_lmr(
&mut self,
i: usize,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) {
self.lmrs[i] = self.lmr(&self.atomics[i], analyzer, arena).into();
}
pub fn raise_lmr(
&mut self,
i: usize,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> bool {
// move the low to low + mid / 2
// reset the mid
let mut curr_lmr = self.lmrs[i].clone();
curr_lmr.low = (curr_lmr.low + curr_lmr.mid)
/ Elem::from(Concrete::from(U256::from(2)))
.minimize(analyzer, arena)
.unwrap();
curr_lmr.mid = (curr_lmr.low.clone() + curr_lmr.high.clone())
/ Elem::from(Concrete::from(U256::from(2)))
.minimize(analyzer, arena)
.unwrap();
let new_mid_conc = curr_lmr.mid.maximize(analyzer, arena).unwrap();
let old_mid_conc = self.lmrs[i].mid.maximize(analyzer, arena).unwrap();
if matches!(
new_mid_conc.range_ord(&old_mid_conc, arena),
Some(std::cmp::Ordering::Equal)
) {
return false;
}
self.lmrs[i] = curr_lmr;
true
}
pub fn lower_lmr(
&mut self,
i: usize,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> bool {
// println!("lowering mid");
// move the high to high + mid / 2
// reset the mid
let mut curr_lmr = self.lmrs[i].clone();
curr_lmr.high = (curr_lmr.mid.minimize(analyzer, arena).unwrap()
+ curr_lmr.high.minimize(analyzer, arena).unwrap())
/ Elem::from(Concrete::from(U256::from(2)))
.minimize(analyzer, arena)
.unwrap();
curr_lmr.mid = (curr_lmr.low.minimize(analyzer, arena).unwrap()
+ curr_lmr.high.minimize(analyzer, arena).unwrap())
/ Elem::from(Concrete::from(U256::from(2)))
.minimize(analyzer, arena)
.unwrap();
let new_high_conc = curr_lmr.high.minimize(analyzer, arena).unwrap();
let old_high_conc = self.lmrs[i].high.minimize(analyzer, arena).unwrap();
if matches!(
new_high_conc.range_ord(&old_high_conc, arena),
Some(std::cmp::Ordering::Equal)
) {
return false;
}
self.lmrs[i] = curr_lmr;
true
}
pub fn increase_start(&mut self) -> bool {
self.start_idx += 1;
self.start_idx < self.atomic_ranges.len()
}
}
impl SolcSolver for BruteBinSearchSolver {
fn simplify(
&mut self,
_analyzer: &impl AnalyzerBackend,
_arena: &mut RangeArena<Elem<Concrete>>,
) {
}
fn solve(
&mut self,
analyzer: &mut impl AnalyzerBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<AtomicSolveStatus, GraphError> {
// pick a value for a variable. check if it satisfies all dependendies
// if is sat, try to reduce using bin search? Not sure how that will
// affect other dependencies If it doesnt,
// raise or lower
let atoms = self
.ranges
.iter()
.filter_map(|(_dep, range)| {
// println!("dep: {}", dep.display_name(analyzer).unwrap());
// println!("atom: {atom:#?}");
if let Some(atom) = range.min.atomize(analyzer, arena) {
Some(atom)
} else {
range.max.atomize(analyzer, arena)
}
})
.collect::<Vec<SolverAtom>>();
let mut dl_solver = DLSolver::new(atoms, analyzer, arena);
let mut atomic_solves: BTreeMap<_, _>;
match dl_solver.solve_partial(analyzer, arena)? {
SolveStatus::Unsat => {
return Ok(AtomicSolveStatus::Unsat);
}
SolveStatus::Sat {
const_solves,
dl_solves,
} => {
atomic_solves = const_solves
.into_iter()
.filter_map(|(dep, solve)| {
Some((
self.atomics
.iter()
.find(|atomic| atomic.idxs.contains(&dep))?
.clone(),
solve
.maximize(analyzer, arena)
.unwrap()
.maybe_concrete()?
.val,
))
})
.collect();
atomic_solves.extend(
dl_solves
.into_iter()
.filter_map(|(dep, solve)| {
Some((
self.atomics
.iter()
.find(|atomic| atomic.idxs.contains(&dep))?
.clone(),
solve
.maximize(analyzer, arena)
.unwrap()
.maybe_concrete()?
.val,
))
})
.collect::<Vec<_>>(),
);
}
SolveStatus::Indeterminate { const_solves } => {
atomic_solves = const_solves
.into_iter()
.filter_map(|(dep, solve)| {
Some((
self.atomics
.iter()
.find(|atomic| atomic.idxs.contains(&dep))?
.clone(),
solve
.maximize(analyzer, arena)
.unwrap()
.maybe_concrete()?
.val,
))
})
.collect()
}
}
// println!("solved for: {:#?}", atomic_solves);
if atomic_solves.len() == self.atomics.len() {
return Ok(AtomicSolveStatus::Sat(atomic_solves));
} else {
atomic_solves.iter().for_each(|(atomic, val)| {
self.intermediate_ranges.iter_mut().for_each(|(_dep, r)| {
atomic.idxs.iter().for_each(|idx| {
r.replace_dep(idx.0.into(), Elem::from(val.clone()), analyzer, arena)
});
});
});
atomic_solves.clone().into_iter().for_each(|(atomic, val)| {
self.intermediate_atomic_ranges.insert(
atomic,
SolcRange::new(val.clone().into(), val.into(), vec![]),
);
});
}
let mut solved_for = atomic_solves
.keys()
.filter_map(|k| self.atomics.iter().position(|r| r == k))
.collect();
while self.recurse_check(self.start_idx, &mut solved_for, analyzer, arena)? {}
if self.successful_passes == self.atomics.len() {
let mapping = self
.intermediate_atomic_ranges
.iter()
.filter_map(|(name, range)| {
if !range.is_const(analyzer, arena).ok()? {
None
} else {
Some((
name.clone(),
range
.evaled_range_min(analyzer, arena)
.unwrap()
.maybe_concrete()
.unwrap()
.val,
))
}
})
.collect::<BTreeMap<Atomic, Concrete>>();
if mapping.len() == self.intermediate_atomic_ranges.len() {
let all_good = self.ranges.iter().all(|(_dep, range)| {
let mut new_range = range.clone();
self.intermediate_atomic_ranges
.iter()
.for_each(|(atomic, range)| {
atomic.idxs.iter().for_each(|idx| {
new_range.replace_dep(
idx.0.into(),
range.min.clone(),
analyzer,
arena,
);
});
});
new_range.cache_eval(analyzer, arena).unwrap();
// println!("{}, original range: [{}, {}], new range: [{}, {}]", dep.display_name(analyzer).unwrap(), range.min, range.max, new_range.min_cached.clone().unwrap(), new_range.max_cached.clone().unwrap());
new_range.sat(analyzer, arena)
});
if all_good {
Ok(AtomicSolveStatus::Sat(mapping))
} else {
// println!("thought we solved but we didnt");
Ok(AtomicSolveStatus::Indeterminate)
}
} else {
Ok(AtomicSolveStatus::Indeterminate)
}
} else {
Ok(AtomicSolveStatus::Indeterminate)
}
}
fn recurse_check(
&mut self,
i: usize,
solved_atomics: &mut Vec<usize>,
analyzer: &mut impl AnalyzerBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<bool, GraphError> {
// println!("recurse check for: {}", self.atomics[i].idxs[0].display_name(analyzer).unwrap());
if i >= self.lmrs.len() {
return Ok(false);
}
if solved_atomics.contains(&i) {
self.increase_start();
self.successful_passes += 1;
return Ok(true);
}
let _atomic = &self.atomics[i];
let lmr = self.lmrs[i].clone();
match self.check(
i,
(lmr.low, lmr.mid, lmr.high),
solved_atomics,
analyzer,
arena,
)? {
(true, Some(HintOrRanges::Ranges(new_ranges))) => {
// sat, try solving next var with new intermediate ranges
solved_atomics.push(i);
self.intermediate_ranges = new_ranges;
self.successful_passes += 1;
self.increase_start();
Ok(true)
}
(false, Some(HintOrRanges::Higher)) => {
self.successful_passes = 0;
*solved_atomics = vec![];
// unsat, try raising
if self.raise_lmr(i, analyzer, arena) {
self.recurse_check(i, solved_atomics, analyzer, arena)
} else {
// we couldn't solve, try increasing global start
if self.increase_start() {
self.intermediate_ranges = self.ranges.clone();
self.recurse_check(self.start_idx, solved_atomics, analyzer, arena)
} else {
Ok(false)
}
}
}
(false, Some(HintOrRanges::Lower)) => {
// unsat, try lowering
self.successful_passes = 0;
*solved_atomics = vec![];
if self.lower_lmr(i, analyzer, arena) {
self.recurse_check(i, solved_atomics, analyzer, arena)
} else {
// we couldn't solve, try increasing global start
if self.increase_start() {
self.intermediate_ranges = self.ranges.clone();
self.recurse_check(self.start_idx, solved_atomics, analyzer, arena)
} else {
Ok(false)
}
}
}
(false, None) => {
// unsat, try lowering
self.successful_passes = 0;
*solved_atomics = vec![];
if self.lower_lmr(i, analyzer, arena) {
self.recurse_check(i, solved_atomics, analyzer, arena)
} else {
// we couldn't solve, try increasing global start
if self.increase_start() {
self.intermediate_ranges = self.ranges.clone();
self.recurse_check(self.start_idx, solved_atomics, analyzer, arena)
} else {
Ok(false)
}
}
}
_ => unreachable!(),
}
}
fn check(
&mut self,
solved_for_idx: usize,
(low, mid, high): (Elem<Concrete>, Elem<Concrete>, Elem<Concrete>),
solved_atomics: &mut Vec<usize>,
analyzer: &mut impl AnalyzerBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<(bool, Option<HintOrRanges>), GraphError> {
let solved_dep = &self.atomics[solved_for_idx].clone();
fn match_check(
this: &mut BruteBinSearchSolver,
solved_for_idx: usize,
solved_dep: &Atomic,
(low, mid, high): (Elem<Concrete>, Elem<Concrete>, Elem<Concrete>),
low_done: bool,
mut mid_done: bool,
mut high_done: bool,
solved_atomics: &mut Vec<usize>,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<(bool, Option<HintOrRanges>), GraphError> {
let res = if !low_done {
check_for_lmr(
this,
solved_for_idx,
solved_dep,
low.clone(),
solved_atomics,
analyzer,
arena,
)
} else if !mid_done {
check_for_lmr(
this,
solved_for_idx,
solved_dep,
mid.clone(),
solved_atomics,
analyzer,
arena,
)
} else {
check_for_lmr(
this,
solved_for_idx,
solved_dep,
high.clone(),
solved_atomics,
analyzer,
arena,
)
};
match res {
Ok((true, ranges)) => Ok((true, ranges)),
Ok((false, _)) => {
if high_done {
res
} else {
high_done = mid_done;
mid_done = true;
match_check(
this,
solved_for_idx,
solved_dep,
(low, mid, high),
true,
mid_done,
high_done,
solved_atomics,
analyzer,
arena,
)
}
}
Err(e) => Err(e),
}
}
fn check_for_lmr(
this: &mut BruteBinSearchSolver,
solved_for_idx: usize,
solved_dep: &Atomic,
conc: Elem<Concrete>,
solved_atomics: &mut Vec<usize>,
analyzer: &mut impl GraphBackend,
arena: &mut RangeArena<Elem<Concrete>>,
) -> Result<(bool, Option<HintOrRanges>), GraphError> {
// println!("checking: {}, conc: {}, {}", this.atomics[solved_for_idx].idxs[0].display_name(analyzer).unwrap(), conc.maximize(analyzer, arena)?.to_range_string(true, analyzer, arena).s, conc.minimize(analyzer)?.to_range_string(false, analyzer, arena).s);
solved_atomics.push(solved_for_idx);
let mut new_ranges = BTreeMap::default();
this.intermediate_atomic_ranges.insert(
solved_dep.clone(),
SolcRange::new(conc.clone(), conc.clone(), vec![]),
);
let atoms = this
.intermediate_ranges
.iter()
.filter_map(|(_, range)| {
if let Some(atom) = range
.min
.simplify_minimize(analyzer, arena)
.unwrap()
.atomize(analyzer, arena)
{
Some(atom)
} else {
range
.max
.simplify_maximize(analyzer, arena)
.unwrap()
.atomize(analyzer, arena)
}
})
.collect::<Vec<SolverAtom>>();
let mut dl_solver = DLSolver::new(atoms, analyzer, arena);
let mut atomic_solves: BTreeMap<_, _>;
match dl_solver.solve_partial(analyzer, arena)? {
SolveStatus::Unsat => {
// println!("TRUE UNSAT");
return Ok((false, None));
}
SolveStatus::Sat {
const_solves,
dl_solves,
} => {
atomic_solves = const_solves
.into_iter()
.filter_map(|(dep, solve)| {
Some((
this.atomics
.iter()
.find(|atomic| atomic.idxs.contains(&dep))?
.clone(),
solve
.maximize(analyzer, arena)
.unwrap()
.maybe_concrete()?
.val,
))
})
.collect();
atomic_solves.extend(
dl_solves
.into_iter()
.filter_map(|(dep, solve)| {
Some((
this.atomics
.iter()
.find(|atomic| atomic.idxs.contains(&dep))?
.clone(),
solve
.maximize(analyzer, arena)
.unwrap()
.maybe_concrete()?
.val,
))
})
.collect::<Vec<_>>(),
);
}
SolveStatus::Indeterminate { const_solves } => {
atomic_solves = const_solves
.into_iter()
.filter_map(|(dep, solve)| {
Some((
this.atomics
.iter()
.find(|atomic| atomic.idxs.contains(&dep))?
.clone(),
solve
.maximize(analyzer, arena)
.unwrap()
.maybe_concrete()?
.val,
))
})
.collect()
}
}
atomic_solves.iter().for_each(|(atomic, val)| {
this.intermediate_ranges.iter_mut().for_each(|(_dep, r)| {
atomic.idxs.iter().for_each(|idx| {
r.replace_dep(idx.0.into(), Elem::from(val.clone()), analyzer, arena)
});
});
});
atomic_solves.clone().into_iter().for_each(|(atomic, val)| {
this.intermediate_atomic_ranges.insert(
atomic,
SolcRange::new(val.clone().into(), val.into(), vec![]),
);
});
// println!("new solves: {atomic_solves:#?}");
for dep in this.deps.iter() {
let range = this
.intermediate_ranges
.get(dep)
.expect("No range for dep?");
// if dep.display_name(analyzer).unwrap() == "(p2 < (61 * p3)) == true" {
// println!("range: {:#?}\n{:#?}", range.min, range.max);
// println!("simplified range: {:#?}\n{:#?}", range.min.simplify_minimize(&mut vec![], analyzer), range.max.simplify_maximize(&mut vec![], analyzer));
// }
// println!("atomizing dep: {}", dep.display_name(analyzer).unwrap());
// println!("min atomized: {:#?}, max atomized: {:#?}", range.min.simplify_minimize(&mut vec![], analyzer)?.atomize(), range.max.simplify_maximize(&mut vec![], analyzer)?.atomize());
if solved_dep.idxs.contains(dep) {
// println!("FOR SOLVED DEP");
continue;
}
// check that the concrete value doesn't break any
let mut new_range = range.clone();
// check if const now
// if let Some((Some(idx), const_ineq)) = new_range.min.maybe_const_inequality() {
// println!("min const ineq: {} for {}", const_ineq.maybe_concrete().unwrap().val.as_human_string(), ContextVarNode::from(idx).display_name(analyzer).unwrap());
// if let Some(position) = this.atomics.iter().position(|atomic| atomic.idxs.contains(&ContextVarNode::from(idx))) {
// // check and return)
// if !solved_atomics.contains(&position) {
// println!("inner min const ineq");
// return check_for_lmr(this, position, &this.atomics[position].clone(), const_ineq, solved_atomics, analyzer);
// }
// }
// }
// if let Some((Some(idx), const_ineq)) = new_range.max.maybe_const_inequality() {
// println!("max const ineq: {} for {} ({}), {:#?}", const_ineq.maybe_concrete().unwrap().val.as_human_string(), ContextVarNode::from(idx).display_name(analyzer).unwrap(), idx.index(), this.atomics);
// if let Some(position) = this.atomics.iter().position(|atomic| atomic.idxs.contains(&ContextVarNode::from(idx))) {
// // check and return
// if !solved_atomics.contains(&position) {
// println!("inner max const ineq");
// return check_for_lmr(this, position, &this.atomics[position].clone(), const_ineq, solved_atomics, analyzer);
// }
// }
// }
// check if the new range is dependent on the solved variable
let is_dependent_on_solved = new_range
.dependent_on(analyzer, arena)
.iter()
.any(|dep| solved_dep.idxs.contains(dep));
// dont run sat check on non-dependent range
if !is_dependent_on_solved {
new_ranges.insert(*dep, new_range);
continue;
}
// println!("new range for {} dependent_on: {:?}, replacing {:?}, is dependent on solved: {is_dependent_on_solved}", dep.display_name(analyzer).unwrap(), new_range.dependent_on(), solved_dep.idxs);
// println!("dep {}:\n\tinitial range: [{}, {}],\n\tcurr range: [{}, {}]",
// dep.display_name(analyzer).unwrap(),
// dep.evaled_range_min(analyzer, arena)?.unwrap().to_range_string(false, analyzer, arena).s,
// dep.evaled_range_max(analyzer, arena)?.unwrap().to_range_string(true, analyzer, arena).s,
// new_range.evaled_range_min(analyzer, arena)?.to_range_string(false, analyzer, arena).s,
// new_range.evaled_range_max(analyzer, arena)?.to_range_string(true, analyzer, arena).s,
// // new_range.range_min()
// );
// println!("dep {} range: {:#?} {:#?}", dep.display_name(analyzer).unwrap(), new_range.min, new_range.max);
if new_range.unsat(analyzer, arena) {
return Ok((false, None));
// panic!("initial range unsat???")
}
this.atomics[solved_for_idx]
.idxs
.iter()
.for_each(|atomic_alias| {
new_range.replace_dep(atomic_alias.0.into(), conc.clone(), analyzer, arena);
});
new_range.cache_eval(analyzer, arena)?;
// println!("new range: [{}, {}], [{}, {}]",
// new_range.evaled_range_min(analyzer, arena)?.to_range_string(false, analyzer, arena).s,
// new_range.evaled_range_max(analyzer, arena)?.to_range_string(true, analyzer, arena).s,
// new_range.min.to_range_string(false, analyzer, arena).s,
// new_range.max.to_range_string(true, analyzer, arena).s,
// );
if new_range.unsat(analyzer, arena) {
// figure out *where* we need to increase or decrease
// work on the unreplace range for now
let min_is_dependent = !range.min.dependent_on(analyzer, arena).is_empty();
let max_is_dependent = !range.max.dependent_on(analyzer, arena).is_empty();
match (min_is_dependent, max_is_dependent) {
(true, true) => {
// both sides dependent
// println!("both");
}
(false, true) => {
// just max is dependent
// println!("just max");
}
(true, false) => {
// just min is dependent
// println!("just min");
}
(false, false) => {
// panic!("this shouldnt happen");
}
}
// println!("new unsat range: [{}, {}]",
// new_range.evaled_range_min(analyzer, arena)?.to_range_string(false, analyzer, arena).s,
// new_range.evaled_range_max(analyzer, arena)?.to_range_string(true, analyzer, arena).s,
// );
// compare new range to prev range to see if they moved down or up
// panic!("here");
let min_change = new_range
.evaled_range_min(analyzer, arena)?
.range_ord(&range.evaled_range_min(analyzer, arena)?, arena);
let max_change = new_range
.evaled_range_max(analyzer, arena)?
.range_ord(&range.evaled_range_max(analyzer, arena)?, arena);
match (min_change, max_change) {
(Some(std::cmp::Ordering::Less), Some(std::cmp::Ordering::Greater)) => {
// panic!("initial range must have been unsat to start");
}
(Some(std::cmp::Ordering::Greater), Some(std::cmp::Ordering::Less)) => {
// we shrank our range, dont give a hint
// println!("None, dep isnt sat: {}, dep initial range: {}", dep.display_name(analyzer).unwrap(), dep.range_string(analyzer).unwrap().unwrap());
return Ok((false, None));
}
(Some(std::cmp::Ordering::Greater), _) => {
// both grew, try lowering
// println!("Lower, dep isnt sat: {}, dep initial range: {}", dep.display_name(analyzer).unwrap(), dep.range_string(analyzer).unwrap().unwrap());
return Ok((false, Some(HintOrRanges::Lower)));
}
(Some(std::cmp::Ordering::Less), _) => {
// both grew, try lowering
// println!("Higher, dep isnt sat: {}, dep initial range: {}", dep.display_name(analyzer).unwrap(), dep.range_string(analyzer).unwrap().unwrap());
return Ok((false, Some(HintOrRanges::Higher)));
}
// (Some(std::cmp::Ordering::Equal), _) => {
// panic!("here");
// }
// (_, Some(std::cmp::Ordering::Equal)) => {
// panic!("here");
// }
_ => {
// println!("None empty, dep isnt sat: {}, dep initial range: {}", dep.display_name(analyzer).unwrap(), dep.range_string(analyzer).unwrap().unwrap());
return Ok((false, None));
}
}
} else {
new_ranges.insert(*dep, new_range);
}
}
Ok((true, Some(HintOrRanges::Ranges(new_ranges))))
}
match_check(
self,
solved_for_idx,
solved_dep,
(low, mid, high),
false,
false,
false,
solved_atomics,
analyzer,
arena,
)
}
}
| 412 | 0.878992 | 1 | 0.878992 | game-dev | MEDIA | 0.474413 | game-dev,scientific-computing | 0.958443 | 1 | 0.958443 |
hocha113/CalamityOverhaul | 2,110 | Content/Projectiles/Weapons/Ranged/HeldProjs/Vanilla/OnyxBlasterHeldProj.cs | using CalamityOverhaul.Common;
using CalamityOverhaul.Content.RangedModify.Core;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.GameContent;
using Terraria.ID;
namespace CalamityOverhaul.Content.Projectiles.Weapons.Ranged.HeldProjs.Vanilla
{
internal class OnyxBlasterHeldProj : BaseFeederGun
{
public override string Texture => CWRConstant.Placeholder;
public override Texture2D TextureValue => TextureAssets.Item[ItemID.OnyxBlaster].Value;
public override int TargetID => ItemID.OnyxBlaster;
public override void SetRangedProperty() {
FireTime = 18;
KreloadMaxTime = 18;
ShootPosToMouLengValue = 0;
ShootPosNorlLengValue = 0;
HandIdleDistanceX = 18;
HandIdleDistanceY = 0;
GunPressure = 0.3f;
ControlForce = 0.1f;
Recoil = 3.2f;
RangeOfStress = 48;
LoadingAmmoAnimation = LoadingAmmoAnimationEnum.Shotgun;
if (!MagazineSystem) {
FireTime += KreloadMaxTime;
}
}
public override void HanderPlaySound() {
SoundEngine.PlaySound(CWRSound.Gun_Shotgun_Shoot2 with { Volume = 0.4f, Pitch = -0.1f }, Projectile.Center);
}
public override void FiringShoot() {
for (int i = 0; i < 4; i++) {
int proj = Projectile.NewProjectile(Source, ShootPos, ShootVelocity.RotatedByRandom(0.13f) * Main.rand.NextFloat(0.9f, 1.5f)
, ProjectileID.BlackBolt, (int)(WeaponDamage * 0.9f), WeaponKnockback, Owner.whoAmI, 0);
int proj2 = Projectile.NewProjectile(Source2, ShootPos, ShootVelocity.RotatedByRandom(0.11f) * Main.rand.NextFloat(0.9f, 1.2f)
, AmmoTypes, WeaponDamage, WeaponKnockback, Owner.whoAmI, 0);
Main.projectile[proj].timeLeft += Main.rand.Next(30);
Main.projectile[proj2].extraUpdates += 1;
Main.projectile[proj2].scale += Main.rand.NextFloat(0.5f);
}
}
}
}
| 412 | 0.902999 | 1 | 0.902999 | game-dev | MEDIA | 0.994721 | game-dev | 0.88246 | 1 | 0.88246 |
matter-labs/foundry-zksync | 2,324 | crates/cheatcodes/src/evm/mapping.rs | use crate::{Cheatcode, Cheatcodes, Result, Vm::*};
use alloy_primitives::{Address, B256};
use alloy_sol_types::SolValue;
use foundry_common::mapping_slots::MappingSlots;
impl Cheatcode for startMappingRecordingCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.mapping_slots.get_or_insert_default();
Ok(Default::default())
}
}
impl Cheatcode for stopMappingRecordingCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.mapping_slots = None;
Ok(Default::default())
}
}
impl Cheatcode for getMappingLengthCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self { target, mappingSlot } = self;
let result = slot_child(state, target, mappingSlot).map(Vec::len).unwrap_or(0);
Ok((result as u64).abi_encode())
}
}
impl Cheatcode for getMappingSlotAtCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self { target, mappingSlot, idx } = self;
let result = slot_child(state, target, mappingSlot)
.and_then(|set| set.get(idx.saturating_to::<usize>()))
.copied()
.unwrap_or_default();
Ok(result.abi_encode())
}
}
impl Cheatcode for getMappingKeyAndParentOfCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self { target, elementSlot: slot } = self;
let mut found = false;
let mut key = &B256::ZERO;
let mut parent = &B256::ZERO;
if let Some(slots) = mapping_slot(state, target) {
if let Some(key2) = slots.keys.get(slot) {
found = true;
key = key2;
parent = &slots.parent_slots[slot];
} else if let Some((key2, parent2)) = slots.seen_sha3.get(slot) {
found = true;
key = key2;
parent = parent2;
}
}
Ok((found, key, parent).abi_encode_params())
}
}
fn mapping_slot<'a>(state: &'a Cheatcodes, target: &'a Address) -> Option<&'a MappingSlots> {
state.mapping_slots.as_ref()?.get(target)
}
fn slot_child<'a>(
state: &'a Cheatcodes,
target: &'a Address,
slot: &'a B256,
) -> Option<&'a Vec<B256>> {
mapping_slot(state, target)?.children.get(slot)
}
| 412 | 0.933506 | 1 | 0.933506 | game-dev | MEDIA | 0.383345 | game-dev | 0.843909 | 1 | 0.843909 |
axx0/Civ2-clone | 1,989 | RaylibUI/RunGame/Commands/Orders/ImprovementOrder.cs | using Civ2engine;
using Civ2engine.Enums;
using Civ2engine.Terrains;
using Model;
using Model.Constants;
using Model.Core;
using Model.Menu;
using RaylibUI.RunGame.GameModes.Orders;
namespace RaylibUI.RunGame.Commands.Orders;
public class ImprovementOrder : Order
{
private readonly TerrainImprovement _improvement;
private readonly IGame _game;
private readonly LocalPlayer _player;
public ImprovementOrder(TerrainImprovement improvement, GameScreen gameScreen, IGame game) :
base(gameScreen, Shortcut.Parse(improvement.Shortcut), GetCommandName(improvement), improvement.Name)
{
_improvement = improvement;
_game = game;
_player = gameScreen.Player;
}
public override bool Update()
{
if (_player.ActiveUnit == null)
{
return SetCommandState(CommandStatus.Invalid);
}
if (_player.ActiveUnit.AiRole != AiRoleType.Settle)
{
return SetCommandState(CommandStatus.Invalid, errorPopupKeyword: "ONLYSETTLERS");
}
var canBeBuilt = TerrainImprovementFunctions.CanImprovementBeBuiltHere(_player.ActiveTile, _improvement, _player.ActiveUnit.Owner);
return SetCommandState(canBeBuilt.Enabled ? CommandStatus.Normal : CommandStatus.Disabled, canBeBuilt.CommandTitle, canBeBuilt.ErrorPopup);
}
public override void Action()
{
_player.ActiveUnit?.Build(_improvement);
_game.CheckConstruction(_player.ActiveTile, _improvement);
_game.ChooseNextUnit();
}
private static string GetCommandName(TerrainImprovement improvement)
{
var baseId = CommandIds.BuildImprovementOrderNormal;
if (improvement.Negative)
{
baseId = CommandIds.RemoveNegativeImprovementOrder;
}else if (improvement.Foreground)
{
baseId = CommandIds.BuildImprovementOrderForeground;
}
return baseId + "_" + improvement.Name.ToUpperInvariant();
}
} | 412 | 0.709942 | 1 | 0.709942 | game-dev | MEDIA | 0.91904 | game-dev | 0.692831 | 1 | 0.692831 |
blizzhackers/kolbot | 9,885 | d2bs/kolbot/libs/core/Attacks/Assassin.js | /**
* @filename Assassin.js
* @author kolton, theBGuy
* @desc Assassin attack sequence
*
*/
const ClassAttack = {
lastTrapPos: {},
trapRange: 20,
/**
* @param {Monster} unit
* @param {boolean} preattack
* @returns {AttackResult}
*/
doAttack: function (unit, preattack) {
if (!unit) return Attack.Result.SUCCESS;
Config.TeleSwitch && me.switchToPrimary();
let gid = unit.gid;
if (Config.MercWatch && me.needMerc()) {
console.log("mercwatch");
if (Town.visitTown()) {
if (!unit || !copyUnit(unit).x || !Game.getMonster(-1, -1, gid) || unit.dead) {
return Attack.Result.SUCCESS; // lost reference to the mob we were attacking
}
}
}
if (Config.ChargeCast.skill > -1) {
Attack.doChargeCast(unit);
}
if (preattack) {
let preAttackResult = Attack.doPreAttack(unit);
if (preAttackResult !== Attack.Result.NOOP) {
return preAttackResult;
}
}
let mercRevive = 0;
let timedSkill = -1;
let untimedSkill = -1;
let index = (unit.isSpecial || unit.isPlayer) ? 1 : 3;
let classid = unit.classid;
// Cloak of Shadows (Aggressive) - can't be cast again until previous one runs out and next to useless if cast in precast sequence (won't blind anyone)
if (Config.AggressiveCloak && Skill.canUse(sdk.skills.CloakofShadows)
&& !me.skillDelay && !me.getState(sdk.states.CloakofShadows)) {
if (unit.distance < 20) {
Skill.cast(sdk.skills.CloakofShadows, sdk.skills.hand.Right);
} else if (!Attack.getIntoPosition(unit, 20, sdk.collision.Ranged)) {
return Attack.Result.FAILED;
}
}
let checkTraps = this.checkTraps(unit);
if (checkTraps) {
if (unit.distance > this.trapRange || checkCollision(me, unit, sdk.collision.Ranged)) {
if (!Attack.getIntoPosition(unit, this.trapRange, sdk.collision.Ranged)
|| (checkCollision(me, unit, sdk.collision.BlockWall)
&& (getCollision(me.area, unit.x, unit.y) & sdk.collision.BlockWall))) {
return Attack.Result.FAILED;
}
}
this.placeTraps(unit, checkTraps);
}
// Cloak of Shadows (Defensive; default) - can't be cast again until previous one runs out and next to useless if cast in precast sequence (won't blind anyone)
if (!Config.AggressiveCloak && Skill.canUse(sdk.skills.CloakofShadows)
&& unit.distance < 20 && !me.skillDelay && !me.getState(sdk.states.CloakofShadows)) {
Skill.cast(sdk.skills.CloakofShadows, sdk.skills.hand.Right);
}
// Get timed skill
let checkSkill = Attack.getCustomAttack(unit)
? Attack.getCustomAttack(unit)[0]
: Config.AttackSkill[index];
if (Attack.checkResist(unit, checkSkill) && Attack.validSpot(unit.x, unit.y, checkSkill, classid)) {
timedSkill = checkSkill;
} else if (Config.AttackSkill[5] > -1
&& Attack.checkResist(unit, Config.AttackSkill[5])
&& Attack.validSpot(unit.x, unit.y, Config.AttackSkill[5], classid)) {
timedSkill = Config.AttackSkill[5];
}
// Get untimed skill
checkSkill = Attack.getCustomAttack(unit)
? Attack.getCustomAttack(unit)[1]
: Config.AttackSkill[index + 1];
if (Attack.checkResist(unit, checkSkill) && Attack.validSpot(unit.x, unit.y, checkSkill, classid)) {
untimedSkill = checkSkill;
} else if (Config.AttackSkill[6] > -1
&& Attack.checkResist(unit, Config.AttackSkill[6])
&& Attack.validSpot(unit.x, unit.y, Config.AttackSkill[6], classid)) {
untimedSkill = Config.AttackSkill[6];
}
// Low mana timed skill
if (Config.LowManaSkill[0] > -1
&& Skill.getManaCost(timedSkill) > me.mp
&& Attack.checkResist(unit, Config.LowManaSkill[0])) {
timedSkill = Config.LowManaSkill[0];
}
// Low mana untimed skill
if (Config.LowManaSkill[1] > -1
&& Skill.getManaCost(untimedSkill) > me.mp
&& Attack.checkResist(unit, Config.LowManaSkill[1])) {
untimedSkill = Config.LowManaSkill[1];
}
let result = this.doCast(unit, timedSkill, untimedSkill);
if (result === Attack.Result.CANTATTACK && Attack.canTeleStomp(unit)) {
let merc = me.getMerc();
while (unit.attackable) {
if (!unit || !copyUnit(unit).x) {
unit = Misc.poll(() => Game.getMonster(-1, -1, gid), 1000, 80);
}
if (!unit) return Attack.Result.SUCCESS;
if (me.needMerc()) {
if (Config.MercWatch && mercRevive++ < 1) {
Town.visitTown();
} else {
return Attack.Result.CANTATTACK;
}
(merc === undefined || !merc) && (merc = me.getMerc());
}
if (!!merc && getDistance(merc, unit) > 5) {
Pather.moveToUnit(unit);
let spot = Attack.findSafeSpot(unit, 10, 5, 9);
!!spot && !!spot.x && Pather.walkTo(spot.x, spot.y);
}
let closeMob = Attack.getNearestMonster({ skipGid: gid });
!!closeMob && this.doCast(closeMob, timedSkill, untimedSkill);
}
return Attack.Result.SUCCESS;
}
return result;
},
afterAttack: function () {
Precast.doPrecast(false);
},
/**
* @param {Monster} unit
* @param {number} timedSkill
* @param {number} untimedSkill
* @returns {AttackResult}
*/
doCast: function (unit, timedSkill = -1, untimedSkill = -1) {
// No valid skills can be found
if (timedSkill < 0 && untimedSkill < 0) return Attack.Result.CANTATTACK;
// unit became invalidated
if (!unit || !unit.attackable) return Attack.Result.SUCCESS;
Config.TeleSwitch && me.switchToPrimary();
let walk;
let classid = unit.classid;
if (timedSkill > -1 && (!me.skillDelay || !Skill.isTimed(timedSkill))) {
switch (timedSkill) {
case sdk.skills.Whirlwind:
if (unit.distance > Skill.getRange(timedSkill) || checkCollision(me, unit, sdk.collision.BlockWall)) {
if (!Attack.getIntoPosition(unit, Skill.getRange(timedSkill), sdk.collision.BlockWall)) {
return Attack.Result.FAILED;
}
}
!unit.dead && Attack.whirlwind(unit);
return Attack.Result.SUCCESS;
default:
if (Skill.getRange(timedSkill) < 4 && !Attack.validSpot(unit.x, unit.y, timedSkill, classid)) {
return Attack.Result.FAILED;
}
if (unit.distance > Skill.getRange(timedSkill) || checkCollision(me, unit, sdk.collision.Ranged)) {
// Allow short-distance walking for melee skills
walk = (Skill.getRange(timedSkill) < 4
&& unit.distance < 10
&& !checkCollision(me, unit, sdk.collision.BlockWall)
);
if (!Attack.getIntoPosition(unit, Skill.getRange(timedSkill), sdk.collision.Ranged, walk)) {
return Attack.Result.FAILED;
}
}
!unit.dead && Skill.cast(timedSkill, Skill.getHand(timedSkill), unit);
return Attack.Result.SUCCESS;
}
}
if (untimedSkill > -1) {
if (Skill.getRange(untimedSkill) < 4 && !Attack.validSpot(unit.x, unit.y, untimedSkill, classid)) {
return Attack.Result.FAILED;
}
if (unit.distance > Skill.getRange(untimedSkill) || checkCollision(me, unit, sdk.collision.Ranged)) {
// Allow short-distance walking for melee skills
walk = (Skill.getRange(untimedSkill) < 4
&& unit.distance < 10
&& !checkCollision(me, unit, sdk.collision.BlockWall)
);
if (!Attack.getIntoPosition(unit, Skill.getRange(untimedSkill), sdk.collision.Ranged, walk)) {
return Attack.Result.FAILED;
}
}
!unit.dead && Skill.cast(untimedSkill, Skill.getHand(untimedSkill), unit);
return Attack.Result.SUCCESS;
}
Misc.poll(() => !me.skillDelay, 1000, 40);
return Attack.Result.SUCCESS;
},
checkTraps: function (unit) {
if (!Config.UseTraps || !unit) return false;
// getDistance crashes when using an object with x, y props, that's why it's unit.x, unit.y and not unit
// is this still a thing ^^? todo: test it
if (me.getMinionCount(sdk.summons.type.AssassinTrap) === 0 || !this.lastTrapPos.hasOwnProperty("x")
|| getDistance(unit.x, unit.y, this.lastTrapPos.x, this.lastTrapPos.y) > 15) {
return 5;
}
return 5 - me.getMinionCount(sdk.summons.type.AssassinTrap);
},
// todo - either import soloplays immune to trap check or add config option for immune to traps
// since this is the base file probably better to leave the option available rather than hard code it
// check if unit is still attackable after each cast?
placeTraps: function (unit, amount = 5) {
let traps = 0;
this.lastTrapPos = { x: unit.x, y: unit.y };
for (let i = -1; i <= 1; i += 1) {
for (let j = -1; j <= 1; j += 1) {
// used for X formation
if (Math.abs(i) === Math.abs(j)) {
// unit can be an object with x, y props too, that's why having "mode" prop is checked
if (traps >= amount || (unit.hasOwnProperty("mode") && unit.dead)) return true;
// Duriel, Mephisto, Diablo, Baal, other players - why not andy?
if ((unit.hasOwnProperty("classid")
&& [
sdk.monsters.Duriel, sdk.monsters.Mephisto, sdk.monsters.Diablo, sdk.monsters.Baal
].includes(unit.classid))
|| (unit.hasOwnProperty("type") && unit.isPlayer)) {
if (traps >= Config.BossTraps.length) return true;
Skill.cast(Config.BossTraps[traps], sdk.skills.hand.Right, unit.x + i, unit.y + j);
} else {
if (traps >= Config.Traps.length) return true;
Skill.cast(Config.Traps[traps], sdk.skills.hand.Right, unit.x + i, unit.y + j);
}
traps += 1;
}
}
}
return true;
},
};
| 412 | 0.965639 | 1 | 0.965639 | game-dev | MEDIA | 0.963281 | game-dev | 0.877847 | 1 | 0.877847 |
opticks-org/opticks | 5,121 | Dependencies/src/ossim-install/include/ossim/imaging/ossimMetadataFileWriter.h | //*******************************************************************
// Copyright (C) 2003 Storage Area Networks, Inc.
//
// License: MIT
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author: Kenneth Melero (kmelero@sanz.com)
//
//*******************************************************************
// $Id: ossimMetadataFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $
#ifndef ossimMetadataFileWriter_H
#define ossimMetadataFileWriter_H
#include <ossim/base/ossimConstants.h>
#include <ossim/base/ossimConnectableObject.h>
#include <ossim/base/ossimProcessInterface.h>
#include <ossim/base/ossimConnectableObjectListener.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/base/ossimIrect.h>
#include <ossim/base/ossimObjectEvents.h>
#include <ossim/base/ossimProcessProgressEvent.h>
class ossimImageSource;
/**
* ossimMetadataFileWriter
*
* Typical usage something like this:
*
* ossimObject* obj = ossimImageMetaDataWriterRegistry::instance()->
* createObject(ossimString("ossimReadmeFileWriter"));
* if (!obj)
* {
* return;
* }
* ossimMetadataFileWriter* mw = PTR_CAST(ossimMetadataFileWriter, obj);
* if (!mw)
* {
* return;
* }
*
* mw->setFilename(xmlFile);
* mw->loadState(kwl);
* mw->connectMyInputTo(ih.get());
* mw->execute();
* delete mw;
*/
class OSSIMDLLEXPORT ossimMetadataFileWriter :
public ossimConnectableObject,
public ossimProcessInterface,
public ossimConnectableObjectListener
{
public:
ossimMetadataFileWriter();
virtual ossimObject* getObject();
virtual const ossimObject* getObject() const;
virtual void initialize();
virtual bool execute();
virtual void setPercentComplete(double percentComplete);
virtual void setFilename(const ossimFilename& file);
const ossimFilename& getFilename()const;
/**
* Load state method:
*
* This method call base class ossimConnectableObject::loadState then
* looks for its keywords.
*
* @param kwl Keyword list to initialize from.
*
* @param prefix Usually something like: "object1."
*
* @return This method will alway return true as it is intended to be
* used in conjuction with the set methods.
*
* Keywords picked up by loadState:
*
* filename: foo.tfw
*
* (pixel_type should be area or point)
*
* pixel_type: area
*/
virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0);
bool canConnectMyInputTo(ossim_int32 inputIndex,
const ossimConnectableObject* object) const;
virtual void disconnectInputEvent(ossimConnectionEvent& event);
virtual void connectInputEvent(ossimConnectionEvent& event);
virtual void propertyEvent(ossimPropertyEvent& event);
/**
* Ossim uses a concept of "pixel is point" internally.
*
* This means that if you say a tie point is 30.0N -81.0W, the center of
* the pixel at the tie point is 30.0N -81.0W.
*
*/
virtual void setPixelType(ossimPixelType pixelType);
virtual ossimPixelType getPixelType() const;
/**
* Sets the area of interest to write the meta data for.
*
* @param areaOfInterest Sets theAreaOfInterest.
*
* @note By default the writers will use
* "theInputConnection->getBoundingRect()" if theAreaOfInterest has nans.
*/
virtual void setAreaOfInterest(const ossimIrect& areaOfInterest);
/**
* @returns theAreaOfInterest.
*/
virtual ossimIrect getAreaOfInterest() const;
/**
* void getMetadatatypeList(std::vector<ossimString>& metadatatypeList)const
*
* pure virtual
*
* Appends the writers metadata types to the "metadatatypeList".
*
* This is the actual image type name. So for
* example, ossimTiffWorldFileWriter has tiff_world_file type.
*
* @param metadatatypeList stl::vector<ossimString> list to append to.
*
* @note All writers should append to the list, not, clear it and then add
* their types.
*/
virtual void getMetadatatypeList(
std::vector<ossimString>& metadatatypeList)const=0;
/**
* bool hasMetadataType(const ossimString& metadataType) const
*
* @param imageType string representing image type.
*
* @return true if "metadataType" is supported by writer.
*/
virtual bool hasMetadataType(const ossimString& metadataType)const=0;
/*!
* property interface
*/
virtual void setProperty(ossimRefPtr<ossimProperty> property);
virtual ossimRefPtr<ossimProperty> getProperty(const ossimString& name)const;
virtual void getPropertyNames(std::vector<ossimString>& propertyNames)const;
protected:
virtual ~ossimMetadataFileWriter();
/**
* Write out the file.
* @return true on success, false on error.
*/
virtual bool writeFile() = 0;
ossimImageSource* theInputConnection;
ossimFilename theFilename;
ossimPixelType thePixelType;
ossimIrect theAreaOfInterest;
TYPE_DATA
};
#endif /* End of #ifndef ossimMetadataFileWriter_H */
| 412 | 0.951701 | 1 | 0.951701 | game-dev | MEDIA | 0.302073 | game-dev | 0.698816 | 1 | 0.698816 |
alex-courtis/way-displays | 21,773 | tst/tst-layout.c | #include "tst.h"
#include "asserts.h"
#include <cmocka.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <wayland-client-protocol.h>
#include <wayland-util.h>
#include "cfg.h"
#include "displ.h"
#include "global.h"
#include "head.h"
#include "log.h"
#include "mode.h"
#include "slist.h"
#include "wlr-output-management-unstable-v1.h"
#include "layout.h"
struct Mode *__wrap_head_find_mode(struct Head *head) {
check_expected(head);
return mock_type(struct Mode*);
}
wl_fixed_t __wrap_head_auto_scale(struct Head *head) {
check_expected(head);
return mock_type(wl_fixed_t);
}
struct State {
struct Mode *mode;
struct SList *heads;
};
int before_all(void **state) {
return 0;
}
int after_all(void **state) {
return 0;
}
int before_each(void **state) {
cfg = cfg_default();
// only set this when we specifically want to test it
free(cfg->callback_cmd);
cfg->callback_cmd = NULL;
displ = calloc(1, sizeof(struct Displ));
struct State *s = calloc(1, sizeof(struct State));
s->mode = calloc(1, sizeof(struct Mode));
for (int i = 0; i < 10; i++) {
struct Head *head = calloc(1, sizeof(struct Head));
head->desired.enabled = true;
head->desired.mode = s->mode;
slist_append(&s->heads, head);
}
*state = s;
return 0;
}
int after_each(void **state) {
assert_logs_empty();
slist_free(&heads);
assert_nul(displ->delta.head);
assert_int_equal(displ->delta.element, 0);
assert_nul(displ->delta.human);
free(displ);
cfg_destroy();
struct State *s = *state;
slist_free_vals(&s->heads, NULL);
free(s->mode);
free(s);
return 0;
}
void order_heads__exact_partial_regex(void **state) {
struct SList *order_name_desc = NULL;
struct SList *heads = NULL;
struct SList *expected = NULL;
// ORDER
slist_append(&order_name_desc, strdup("exact0"));
slist_append(&order_name_desc, strdup("exact1"));
slist_append(&order_name_desc, strdup("!.*regex.*"));
slist_append(&order_name_desc, strdup("exact1")); // should not repeat
slist_append(&order_name_desc, strdup("partial"));
// heads
struct Head not_specified_1 = { .description = "not specified 1", };
struct Head exact0_partial = { .description = "not an exact0 exact match" };
struct Head partial = { .description = "a partial match" };
struct Head regex_match_1 = { .description = "a regex match" };
struct Head exact1 = { .description = "exact1" };
struct Head exact0 = { .description = "exact0" };
struct Head regex_match_2 = { .description = "another regex match" };
struct Head not_specified_2 = { .description = "not specified 2" };
slist_append(&heads, ¬_specified_1);
slist_append(&heads, &exact0_partial);
slist_append(&heads, &partial);
slist_append(&heads, ®ex_match_1);
slist_append(&heads, &exact1);
slist_append(&heads, &exact0);
slist_append(&heads, ®ex_match_2);
slist_append(&heads, ¬_specified_2);
// expected
slist_append(&expected, &exact0);
slist_append(&expected, &exact0_partial);
slist_append(&expected, &exact1);
slist_append(&expected, ®ex_match_1);
slist_append(&expected, ®ex_match_2);
slist_append(&expected, &partial);
slist_append(&expected, ¬_specified_1);
slist_append(&expected, ¬_specified_2);
struct SList *heads_ordered = order_heads(order_name_desc, heads);
assert_heads_order(heads_ordered, expected);
slist_free_vals(&order_name_desc, NULL);
slist_free(&heads);
slist_free(&expected);
slist_free(&heads_ordered);
}
void order_heads__exact_regex_catchall(void **state) {
struct SList *order_name_desc = NULL;
struct SList *heads = NULL;
struct SList *expected = NULL;
// ORDER
slist_append(&order_name_desc, strdup("exact0"));
slist_append(&order_name_desc, strdup("!.*regex.*"));
slist_append(&order_name_desc, strdup("!.*$"));
slist_append(&order_name_desc, strdup("exact9"));
// heads
struct Head exact9 = { .description = "exact9" };
struct Head not_specified_1 = { .description = "not specified 1", };
struct Head regex_match_1 = { .description = "a regex match" };
struct Head exact0 = { .description = "exact0" };
struct Head regex_match_2 = { .description = "another regex match" };
struct Head not_specified_2 = { .description = "not specified 2" };
slist_append(&heads, ¬_specified_1);
slist_append(&heads, ®ex_match_1);
slist_append(&heads, &exact0);
slist_append(&heads, ®ex_match_2);
slist_append(&heads, ¬_specified_2);
slist_append(&heads, &exact9);
// expected
slist_append(&expected, &exact0);
slist_append(&expected, ®ex_match_1);
slist_append(&expected, ®ex_match_2);
slist_append(&expected, ¬_specified_1);
slist_append(&expected, ¬_specified_2);
slist_append(&expected, &exact9);
struct SList *heads_ordered = order_heads(order_name_desc, heads);
assert_heads_order(heads_ordered, expected);
slist_free_vals(&order_name_desc, NULL);
slist_free(&heads);
slist_free(&expected);
slist_free(&heads_ordered);
}
void order_heads__no_order(void **state) {
struct SList *heads = NULL;
struct Head head = { .name = "head", };
slist_append(&heads, &head);
// null/empty order
struct SList *heads_ordered = order_heads(NULL, heads);
assert_heads_order(heads_ordered, heads);
slist_free(&heads_ordered);
slist_free(&heads);
}
void position_heads__col_left(void **state) {
struct State *s = *state;
struct Head *head;
cfg->arrange = COL;
cfg->align = LEFT;
head = slist_at(s->heads, 0); head->scaled.width = 4; head->scaled.height = 2;
head = slist_at(s->heads, 1); head->scaled.width = 7; head->scaled.height = 3;
head = slist_at(s->heads, 2); head->scaled.width = 2; head->scaled.height = 1;
position_heads(s->heads);
head = slist_at(s->heads, 0); assert_head_position(head, 0, 0);
head = slist_at(s->heads, 1); assert_head_position(head, 0, 2);
head = slist_at(s->heads, 2); assert_head_position(head, 0, 5);
}
void position_heads__col_mid(void **state) {
struct State *s = *state;
struct Head *head;
cfg->arrange = COL;
cfg->align = MIDDLE;
head = slist_at(s->heads, 0); head->scaled.width = 4; head->scaled.height = 2;
head = slist_at(s->heads, 1); head->scaled.width = 7; head->scaled.height = 3;
head = slist_at(s->heads, 2); head->scaled.width = 2; head->scaled.height = 1;
position_heads(s->heads);
head = slist_at(s->heads, 0); assert_head_position(head, 2, 0);
head = slist_at(s->heads, 1); assert_head_position(head, 0, 2);
head = slist_at(s->heads, 2); assert_head_position(head, 3, 5);
}
void position_heads__col_right(void **state) {
struct State *s = *state;
struct Head *head;
cfg->arrange = COL;
cfg->align = RIGHT;
head = slist_at(s->heads, 0); head->scaled.width = 4; head->scaled.height = 2;
head = slist_at(s->heads, 1); head->scaled.width = 7; head->scaled.height = 3;
head = slist_at(s->heads, 2); head->scaled.width = 2; head->scaled.height = 1;
position_heads(s->heads);
head = slist_at(s->heads, 0); assert_head_position(head, 3, 0);
head = slist_at(s->heads, 1); assert_head_position(head, 0, 2);
head = slist_at(s->heads, 2); assert_head_position(head, 5, 5);
}
void position_heads__row_top(void **state) {
struct State *s = *state;
struct Head *head;
cfg->arrange = ROW;
cfg->align = TOP;
head = slist_at(s->heads, 0); head->scaled.width = 4; head->scaled.height = 2;
head = slist_at(s->heads, 1); head->scaled.width = 7; head->scaled.height = 5;
head = slist_at(s->heads, 2); head->scaled.width = 2; head->scaled.height = 1;
position_heads(s->heads);
head = slist_at(s->heads, 0); assert_head_position(head, 0, 0);
head = slist_at(s->heads, 1); assert_head_position(head, 4, 0);
head = slist_at(s->heads, 2); assert_head_position(head, 11, 0);
}
void position_heads__row_mid(void **state) {
struct State *s = *state;
struct Head *head;
cfg->arrange = ROW;
cfg->align = MIDDLE;
head = slist_at(s->heads, 0); head->scaled.width = 4; head->scaled.height = 2;
head = slist_at(s->heads, 1); head->scaled.width = 7; head->scaled.height = 5;
head = slist_at(s->heads, 2); head->scaled.width = 2; head->scaled.height = 1;
position_heads(s->heads);
head = slist_at(s->heads, 0); assert_head_position(head, 0, 2);
head = slist_at(s->heads, 1); assert_head_position(head, 4, 0);
head = slist_at(s->heads, 2); assert_head_position(head, 11, 2);
}
void position_heads__row_bottom(void **state) {
struct State *s = *state;
struct Head *head;
cfg->arrange = ROW;
cfg->align = BOTTOM;
head = slist_at(s->heads, 0); head->scaled.width = 4; head->scaled.height = 2;
head = slist_at(s->heads, 1); head->scaled.width = 7; head->scaled.height = 5;
head = slist_at(s->heads, 2); head->scaled.width = 2; head->scaled.height = 1;
position_heads(s->heads);
head = slist_at(s->heads, 0); assert_head_position(head, 0, 3);
head = slist_at(s->heads, 1); assert_head_position(head, 4, 0);
head = slist_at(s->heads, 2); assert_head_position(head, 11, 4);
}
void desire_enabled__lid_closed_many(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
};
slist_append(&heads, &head0);
struct Head head1 = {
.name = "head1",
.desired.enabled = true,
};
slist_append(&heads, &head1);
expect_string(__wrap_lid_is_closed, name, "head0");
will_return(__wrap_lid_is_closed, true);
desire_enabled(&head0);
assert_false(head0.desired.enabled);
}
void desire_enabled__lid_closed_one(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
};
slist_append(&heads, &head0);
expect_string(__wrap_lid_is_closed, name, "head0");
will_return(__wrap_lid_is_closed, true);
desire_enabled(&head0);
assert_true(head0.desired.enabled);
}
void desire_enabled__lid_closed_one_disabled(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
};
slist_append(&heads, &head0);
slist_append(&cfg->disabled, cfg_disabled_always("![hH]ead[0-9]"));
expect_string(__wrap_lid_is_closed, name, "head0");
will_return(__wrap_lid_is_closed, true);
desire_enabled(&head0);
assert_false(head0.desired.enabled);
}
void desire_enabled__override(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = false,
.overrided_enabled = OverrideTrue,
};
slist_append(&heads, &head0);
slist_append(&cfg->disabled, cfg_disabled_always("![hH]ead[0-9]"));
expect_string(__wrap_lid_is_closed, name, "head0");
will_return(__wrap_lid_is_closed, false);
desire_enabled(&head0);
assert_true(head0.desired.enabled);
assert_true(head0.overrided_enabled == OverrideTrue);
}
void desire_enabled__override_reset(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
.overrided_enabled = OverrideFalse,
};
slist_append(&heads, &head0);
slist_append(&cfg->disabled, cfg_disabled_always("![hH]ead[0-9]"));
expect_string(__wrap_lid_is_closed, name, "head0");
will_return(__wrap_lid_is_closed, false);
desire_enabled(&head0);
assert_false(head0.desired.enabled);
assert_true(head0.overrided_enabled == NoOverride);
}
void desire_mode__disabled(void **state) {
struct Mode mode0 = { 0 };
struct Head head0 = {
.name = "head0",
.desired.enabled = false,
.desired.mode = &mode0,
};
desire_mode(&head0);
assert_ptr_equal(head0.desired.mode, &mode0);
assert_false(head0.desired.enabled);
assert_false(head0.warned_no_mode);
}
void desire_mode__no_mode(void **state) {
struct Mode mode0 = { 0 };
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
.desired.mode = &mode0,
};
expect_value(__wrap_head_find_mode, head, &head0);
will_return(__wrap_head_find_mode, NULL);
desire_mode(&head0);
assert_ptr_equal(head0.desired.mode, &mode0);
assert_false(head0.desired.enabled);
assert_true(head0.warned_no_mode);
}
void desire_mode__no_mode_warned(void **state) {
struct Mode mode0 = { 0 };
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
.desired.mode = &mode0,
.warned_no_mode = true,
};
expect_value(__wrap_head_find_mode, head, &head0);
will_return(__wrap_head_find_mode, NULL);
desire_mode(&head0);
assert_ptr_equal(head0.desired.mode, &mode0);
assert_false(head0.desired.enabled);
assert_true(head0.warned_no_mode);
}
void desire_mode__ok(void **state) {
struct Mode mode0 = { 0 };
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
.desired.mode = &mode0,
};
struct Mode mode1 = { 0 };
expect_value(__wrap_head_find_mode, head, &head0);
will_return(__wrap_head_find_mode, &mode1);
desire_mode(&head0);
assert_ptr_equal(head0.desired.mode, &mode1);
assert_true(head0.desired.enabled);
assert_false(head0.warned_no_mode);
}
void desire_scale__disabled(void **state) {
struct Head head0 = {
.desired.enabled = false,
};
desire_scale(&head0);
}
void desire_scale__no_scaling(void **state) {
struct Head head0 = {
.desired.enabled = true,
};
cfg->scaling = OFF;
cfg->auto_scale = ON;
desire_scale(&head0);
assert_wl_fixed_t_equal_double(head0.desired.scale, 1);
}
void desire_scale__no_auto(void **state) {
struct Head head0 = {
.desired.enabled = true,
};
cfg->scaling = ON;
cfg->auto_scale = OFF;
desire_scale(&head0);
assert_wl_fixed_t_equal_double(head0.desired.scale, 1);
}
void desire_scale__auto(void **state) {
struct Head head0 = {
.desired.enabled = true,
};
cfg->scaling = ON;
cfg->auto_scale = ON;
expect_value(__wrap_head_auto_scale, head, &head0);
will_return(__wrap_head_auto_scale, wl_fixed_from_double(2.5));
desire_scale(&head0);
assert_wl_fixed_t_equal_double(head0.desired.scale, 2.5);
}
void desire_scale__user(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
};
cfg->scaling = ON;
cfg->auto_scale = ON;
slist_append(&cfg->user_scales, cfg_user_scale_init("![Hh]ea.*", 3.5));
slist_append(&cfg->user_scales, cfg_user_scale_init("head1", 7.5));
desire_scale(&head0);
assert_wl_fixed_t_equal_double(head0.desired.scale, 3.5);
}
void desire_transform__disabled(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = false,
.desired.transform = WL_OUTPUT_TRANSFORM_90,
};
slist_append(&cfg->user_transforms, cfg_user_transform_init("head0", WL_OUTPUT_TRANSFORM_180));
desire_transform(&head0);
assert_int_equal(head0.desired.transform, WL_OUTPUT_TRANSFORM_90);
}
void desire_transform__no_transform(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
.desired.transform = WL_OUTPUT_TRANSFORM_90,
};
desire_transform(&head0);
assert_int_equal(head0.desired.transform, WL_OUTPUT_TRANSFORM_NORMAL);
}
void desire_transform__user(void **state) {
struct Head head0 = {
.name = "head0",
.desired.enabled = true,
.desired.transform = WL_OUTPUT_TRANSFORM_90,
};
slist_append(&cfg->user_transforms, cfg_user_transform_init("head9", WL_OUTPUT_TRANSFORM_270));
slist_append(&cfg->user_transforms, cfg_user_transform_init("head0", WL_OUTPUT_TRANSFORM_180));
desire_transform(&head0);
assert_int_equal(head0.desired.transform, WL_OUTPUT_TRANSFORM_180);
}
void desire_adaptive_sync__head_disabled(void **state) {
struct Head head0 = {
.desired.enabled = false,
.desired.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED,
};
desire_adaptive_sync(&head0);
assert_int_equal(head0.desired.adaptive_sync, ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED);
}
void desire_adaptive_sync__failed(void **state) {
struct Head head0 = {
.desired.enabled = true,
.desired.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED,
.adaptive_sync_failed = true,
};
desire_adaptive_sync(&head0);
assert_int_equal(head0.desired.adaptive_sync, ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED);
}
void desire_adaptive_sync__disabled(void **state) {
struct Head head0 = {
.name = "some head",
.desired.enabled = true,
.desired.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED,
};
slist_append(&cfg->adaptive_sync_off_name_desc, strdup("!.*hea"));
desire_adaptive_sync(&head0);
assert_int_equal(head0.desired.adaptive_sync, ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED);
}
void desire_adaptive_sync__enabled(void **state) {
struct Head head0 = {
.desired.enabled = true,
.desired.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED,
};
desire_adaptive_sync(&head0);
assert_int_equal(head0.desired.adaptive_sync, ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED);
}
void handle_success__head_changing_adaptive_sync(void **state) {
struct Head head = {
.desired.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED,
.current.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED,
.adaptive_sync_failed = false,
};
displ->delta.element = VRR_OFF;
displ->delta.head = &head;
expect_value(__wrap_call_back, t, INFO);
expect_string(__wrap_call_back, msg1, "Changes successful");
expect_value(__wrap_call_back, msg2, NULL);
handle_success();
assert_log(INFO, "\nChanges successful\n");
assert_false(head.adaptive_sync_failed);
}
void handle_success__head_changing_adaptive_sync_fail(void **state) {
struct Head head = {
.name = "head",
.model = NULL, // fall back to placeholder
.desired.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED,
.current.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED,
};
displ->delta.element = VRR_OFF;
displ->delta.head = &head;
expect_value(__wrap_print_adaptive_sync_fail, t, WARNING);
expect_value(__wrap_print_adaptive_sync_fail, head, &head);
expect_value(__wrap_call_back_adaptive_sync_fail, t, WARNING);
expect_string(__wrap_call_back_adaptive_sync_fail, head, &head);
handle_success();
assert_true(head.adaptive_sync_failed);
}
void handle_success__head_changing_mode(void **state) {
struct Mode mode = { 0 };
struct Head head = {
.desired.mode = &mode,
};
displ->delta.element = MODE;
displ->delta.head = &head;
expect_value(__wrap_call_back, t, INFO);
expect_string(__wrap_call_back, msg1, "Changes successful");
expect_value(__wrap_call_back, msg2, NULL);
handle_success();
assert_log(INFO, "\nChanges successful\n");
assert_ptr_equal(head.current.mode, &mode);
}
void handle_success__ok(void **state) {
displ->delta.human = strdup("human");
expect_value(__wrap_call_back, t, INFO);
expect_string(__wrap_call_back, msg1, "human");
expect_value(__wrap_call_back, msg2, NULL);
handle_success();
assert_log(INFO, "\nChanges successful\n");
}
void handle_failure__mode(void **state) {
struct Mode mode_cur = { 0 };
struct Mode mode_des = { 0 };
struct Head head = {
.name = "nam",
.current.mode = &mode_cur,
.desired.mode = &mode_des,
};
displ->delta.element = MODE;
displ->delta.head = &head;
expect_value(__wrap_print_mode_fail, t, ERROR);
expect_value(__wrap_print_mode_fail, head, &head);
expect_value(__wrap_print_mode_fail, mode, &mode_des);
expect_value(__wrap_call_back_mode_fail, t, ERROR);
expect_value(__wrap_call_back_mode_fail, head, &head);
expect_value(__wrap_call_back_mode_fail, mode, &mode_des);
handle_failure();
assert_nul(head.current.mode);
assert_ptr_equal(head.desired.mode, &mode_des);
assert_ptr_equal(slist_find_equal_val(head.modes_failed, NULL, &mode_des), &mode_des);
slist_free(&head.modes_failed);
}
void handle_failure__adaptive_sync(void **state) {
struct Head head = {
.name = "nam",
.model = "mod",
.current.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED,
.desired.adaptive_sync = ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED,
};
displ->delta.element = VRR_OFF;
displ->delta.head = &head;
expect_value(__wrap_print_adaptive_sync_fail, t, WARNING);
expect_value(__wrap_print_adaptive_sync_fail, head, &head);
expect_value(__wrap_call_back_adaptive_sync_fail, t, WARNING);
expect_string(__wrap_call_back_adaptive_sync_fail, head, &head);
handle_failure();
assert_true(head.adaptive_sync_failed);
}
void handle_failure__unspecified(void **state) {
displ->delta.human = strdup("human");
expect_value(__wrap_call_back, t, FATAL);
expect_string(__wrap_call_back, msg1, "human");
expect_string(__wrap_call_back, msg2, "\nChanges failed, exiting");
expect_value(__wrap_wd_exit_message, __status, EXIT_FAILURE);
handle_failure();
assert_log(FATAL, "\nChanges failed, exiting\n");
}
int main(void) {
const struct CMUnitTest tests[] = {
TEST(order_heads__exact_partial_regex),
TEST(order_heads__exact_regex_catchall),
TEST(order_heads__no_order),
TEST(position_heads__col_left),
TEST(position_heads__col_mid),
TEST(position_heads__col_right),
TEST(position_heads__row_top),
TEST(position_heads__row_mid),
TEST(position_heads__row_bottom),
TEST(desire_enabled__lid_closed_many),
TEST(desire_enabled__lid_closed_one_disabled),
TEST(desire_enabled__lid_closed_one),
TEST(desire_enabled__override),
TEST(desire_enabled__override_reset),
TEST(desire_mode__disabled),
TEST(desire_mode__no_mode),
TEST(desire_mode__no_mode_warned),
TEST(desire_mode__ok),
TEST(desire_scale__disabled),
TEST(desire_scale__no_scaling),
TEST(desire_scale__no_auto),
TEST(desire_scale__auto),
TEST(desire_scale__user),
TEST(desire_transform__disabled),
TEST(desire_transform__no_transform),
TEST(desire_transform__user),
TEST(desire_adaptive_sync__head_disabled),
TEST(desire_adaptive_sync__failed),
TEST(desire_adaptive_sync__disabled),
TEST(desire_adaptive_sync__enabled),
TEST(handle_success__head_changing_adaptive_sync),
TEST(handle_success__head_changing_adaptive_sync_fail),
TEST(handle_success__head_changing_mode),
TEST(handle_success__ok),
TEST(handle_failure__mode),
TEST(handle_failure__adaptive_sync),
TEST(handle_failure__unspecified),
};
return RUN(tests);
}
| 412 | 0.87844 | 1 | 0.87844 | game-dev | MEDIA | 0.269064 | game-dev | 0.620168 | 1 | 0.620168 |
Kengxxiao/Punishing_GrayRaven_Tab | 3,775 | lua/xui/xuimain/XUiMainLeftMid.lua | XUiMainLeftMid = XClass()
local TextManager = CS.XTextManager
function XUiMainLeftMid:Ctor(rootUi)
self.Transform = rootUi.PanelLeftMid.gameObject.transform
XTool.InitUiObject(self)
self.RootUi = rootUi
--ClickEvent
self.BtnGiftExpire.CallBack = function() self:OnBtnGiftExpire() end
self.BtnYKExpire.CallBack = function() self:OnBtnYKExpire() end
self.BtnAutoFight.CallBack = function() self:OnBtnAutoFight() end
--RedPoint
--Filter
self:CheckFilterFunctions()
self.BtnYKExpire:SetNameByGroup(0,CS.XTextManager.GetText("PurchaseYKExpireDes"))
end
function XUiMainLeftMid:OnEnable()
self.PanelAutoFight.gameObject:SetActive(XDataCenter.AutoFightManager.GetRecordCount() > 0)
XEventManager.AddEventListener(XEventId.EVENT_AUTO_FIGHT_START, self.OnAutoFightStart, self)
XEventManager.AddEventListener(XEventId.EVENT_AUTO_FIGHT_CHANGE, self.OnAutoFightChange, self)
XEventManager.AddEventListener(XEventId.EVENT_AUTO_FIGHT_REMOVE, self.OnAutoFightRemove, self)
-- XEventManager.AddEventListener(XEventId.EVENT_LB_EXPIRE_NOTIFY, self.UpdatePurchaseGift, self)
self:SetPurchaseGiftExpire()
self:UpdateYKExpire()
end
function XUiMainLeftMid:OnDisable()
XEventManager.RemoveEventListener(XEventId.EVENT_AUTO_FIGHT_START, self.OnAutoFightStart, self)
XEventManager.RemoveEventListener(XEventId.EVENT_AUTO_FIGHT_CHANGE, self.OnAutoFightChange, self)
XEventManager.RemoveEventListener(XEventId.EVENT_AUTO_FIGHT_REMOVE, self.OnAutoFightRemove, self)
-- XEventManager.RemoveEventListener(XEventId.EVENT_LB_EXPIRE_NOTIFY, self.UpdatePurchaseGift, self)
self.PanelGiftExpire.gameObject:SetActiveEx(false)
end
function XUiMainLeftMid:CheckFilterFunctions()
self.BtnGiftExpire.gameObject:SetActiveEx(not XFunctionManager.CheckFunctionFitter(XFunctionManager.FunctionName.SkipRecharge))
end
function XUiMainLeftMid:OnBtnGiftExpire(eventData)
XLuaUiManager.Open("UiPurchase", XPurchaseConfigs.TabsConfig.LB)
end
function XUiMainLeftMid:OnBtnYKExpire(eventData)
XLuaUiManager.Open("UiPurchase", XPurchaseConfigs.TabsConfig.YK)
end
function XUiMainLeftMid:OnBtnAutoFight(eventData)
XLuaUiManager.Open("UiAutoFightList")
end
--自动战斗
function XUiMainLeftMid:OnAutoFightStart()
if not self.PanelAutoFight.gameObject.activeSelf then
self.PanelAutoFight.gameObject:SetActive(true)
end
end
--自动战斗
function XUiMainLeftMid:OnAutoFightChange(count)
local active = count > 0
local go = self.ImgAutoFightRedPoint.gameObject
if go.activeSelf == active then
return
end
go:SetActive(active)
end
--自动战斗
function XUiMainLeftMid:OnAutoFightRemove()
local cnt = XDataCenter.AutoFightManager.GetRecordCount()
if cnt > 0 then
return
end
local go = self.PanelAutoFight.gameObject
if go.activeSelf == false then
return
end
go:SetActive(false)
end
-- 礼包
function XUiMainLeftMid:UpdatePurchaseGift(count)
if count == 0 or count == nil then
self.PanelGiftExpire.gameObject:SetActiveEx(false)
else
self.PanelGiftExpire.gameObject:SetActiveEx(true)
if count == 1 then
self.BtnGiftExpire:SetName(TextManager.GetText("PurchaseGiftValitimeTips1"))
else
self.BtnGiftExpire:SetName(TextManager.GetText("PurchaseGiftValitimeTips2"))
end
end
end
-- 月卡
function XUiMainLeftMid:UpdateYKExpire()
local flag = XDataCenter.PurchaseManager.CheckYKContinueBuy()
self.PanelYKExpire.gameObject:SetActiveEx(flag)
end
function XUiMainLeftMid:SetPurchaseGiftExpire()
if self.IsFirstExpire then
return
end
self.IsFirstExpire = true
local count = XDataCenter.PurchaseManager.ExpireCount
self:UpdatePurchaseGift(count)
end | 412 | 0.83828 | 1 | 0.83828 | game-dev | MEDIA | 0.955005 | game-dev | 0.972129 | 1 | 0.972129 |
The-Cataclysm-Preservation-Project/TrinityCore | 6,643 | src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.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 "ScriptMgr.h"
#include "scholomance.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
namespace Scholomance::Kormok
{
enum Spells
{
SPELL_SHADOWBOLT_VOLLEY = 20741,
SPELL_BONE_SHIELD = 27688,
SPELL_SUMMON_BONE_MAGES = 27695,
SPELL_SUMMON_BONE_MAGE_FRONT_LEFT = 27696,
SPELL_SUMMON_BONE_MAGE_FRONT_RIGHT = 27697,
SPELL_SUMMON_BONE_MAGE_BACK_RIGHT = 27698,
SPELL_SUMMON_BONE_MAGE_BACK_LEFT = 27699,
SPELL_SUMMON_BONE_MINIONS = 27687
};
enum Events
{
EVENT_SHADOWBOLT_VOLLEY = 1,
EVENT_BONE_SHIELD,
EVENT_SUMMON_MINIONS
};
class boss_kormok : public CreatureScript
{
public:
boss_kormok() : CreatureScript("boss_kormok") { }
struct boss_kormokAI : public ScriptedAI
{
boss_kormokAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
Mages = false;
}
void Reset() override
{
Initialize();
events.Reset();
}
void JustEngagedWith(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_SHADOWBOLT_VOLLEY, 10000);
events.ScheduleEvent(EVENT_BONE_SHIELD, 2000);
events.ScheduleEvent(EVENT_SUMMON_MINIONS, 15000);
}
void JustSummoned(Creature* summoned) override
{
summoned->AI()->AttackStart(me->GetVictim());
}
void DamageTaken(Unit* /*attacker*/, uint32& damage) override
{
if (me->HealthBelowPctDamaged(25, damage) && !Mages)
{
DoCast(SPELL_SUMMON_BONE_MAGES);
Mages = true;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHADOWBOLT_VOLLEY:
DoCastVictim(SPELL_SHADOWBOLT_VOLLEY);
events.ScheduleEvent(EVENT_SHADOWBOLT_VOLLEY, 15000);
break;
case EVENT_BONE_SHIELD:
DoCastVictim(SPELL_BONE_SHIELD);
events.ScheduleEvent(EVENT_BONE_SHIELD, 45000);
break;
case EVENT_SUMMON_MINIONS:
DoCast(SPELL_SUMMON_BONE_MINIONS);
events.ScheduleEvent(EVENT_SUMMON_MINIONS, 12000);
break;
default:
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
private:
EventMap events;
bool Mages;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetScholomanceAI<boss_kormokAI>(creature);
}
};
uint32 const SummonMageSpells[4] =
{
SPELL_SUMMON_BONE_MAGE_FRONT_LEFT,
SPELL_SUMMON_BONE_MAGE_FRONT_RIGHT,
SPELL_SUMMON_BONE_MAGE_BACK_RIGHT,
SPELL_SUMMON_BONE_MAGE_BACK_LEFT,
};
// 27695 - Summon Bone Mages
class spell_kormok_summon_bone_mages : SpellScriptLoader
{
public:
spell_kormok_summon_bone_mages() : SpellScriptLoader("spell_kormok_summon_bone_mages") { }
class spell_kormok_summon_bone_magesSpellScript : public SpellScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo(SummonMageSpells);
}
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
for (uint32 i = 0; i < 2; ++i)
GetCaster()->CastSpell(GetCaster(), SummonMageSpells[urand(0, 3)], true);
}
void Register() override
{
OnEffectHitTarget.Register(&spell_kormok_summon_bone_magesSpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_kormok_summon_bone_magesSpellScript();
}
};
// 27687 - Summon Bone Minions
class spell_kormok_summon_bone_minions : SpellScriptLoader
{
public:
spell_kormok_summon_bone_minions() : SpellScriptLoader("spell_kormok_summon_bone_minions") { }
class spell_kormok_summon_bone_minionsSpellScript : public SpellScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo({ SPELL_SUMMON_BONE_MINIONS });
}
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
// Possible spells to handle this not found.
for (uint32 i = 0; i < 4; ++i)
GetCaster()->SummonCreature(NPC_BONE_MINION, GetCaster()->GetPositionX() + float(irand(-7, 7)), GetCaster()->GetPositionY() + float(irand(-7, 7)), GetCaster()->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 120000);
}
void Register() override
{
OnEffectHitTarget.Register(&spell_kormok_summon_bone_minionsSpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_kormok_summon_bone_minionsSpellScript();
}
};
}
void AddSC_boss_kormok()
{
using namespace Scholomance;
using namespace Scholomance::Kormok;
new boss_kormok();
new spell_kormok_summon_bone_mages();
new spell_kormok_summon_bone_minions();
}
| 412 | 0.838286 | 1 | 0.838286 | game-dev | MEDIA | 0.976797 | game-dev | 0.88961 | 1 | 0.88961 |
OregonCore/OregonCore | 110,420 | src/game/Player.h | /*
* This file is part of the OregonCore 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 <https://www.gnu.org/licenses/>.
*/
#ifndef _PLAYER_H
#define _PLAYER_H
#include "Common.h"
#include "ItemPrototype.h"
#include "Unit.h"
#include "Item.h"
#include "Database/DatabaseEnv.h"
#include "DBCStores.h"
#include "NPCHandler.h"
#include "QuestDef.h"
#include "Group.h"
#include "Bag.h"
#include "WorldSession.h"
#include "CinematicMgr.h"
#include "Pet.h"
#include "MapReference.h"
#include "Utilities/Util.h" // for Tokens typedef
#include "ReputationMgr.h"
#include<string>
#include<vector>
struct Mail;
class Channel;
class DynamicObject;
class Creature;
class Pet;
class PlayerMenu;
class Transport;
class UpdateMask;
class PlayerSocial;
class OutdoorPvP;
typedef std::deque<Mail*> PlayerMails;
#define PLAYER_MAX_SKILLS 127
#define PLAYER_MAX_DAILY_QUESTS 25
// Note: SPELLMOD_* values is aura types in fact
enum SpellModType
{
SPELLMOD_FLAT = 107, // SPELL_AURA_ADD_FLAT_MODIFIER
SPELLMOD_PCT = 108 // SPELL_AURA_ADD_PCT_MODIFIER
};
// 2^n values, Player::m_isunderwater is a bitmask. These are internal values, they are never send to any client
enum PlayerUnderwaterState
{
UNDERWATER_NONE = 0x00,
UNDERWATER_INWATER = 0x01, // terrain type is water and player is afflicted by it
UNDERWATER_INLAVA = 0x02, // terrain type is lava and player is afflicted by it
UNDERWATER_INSLIME = 0x04, // terrain type is lava and player is afflicted by it
UNDERWATER_INDARKWATER = 0x08, // terrain type is dark water and player is afflicted by it
UNDERWATER_EXIST_TIMERS = 0x10
};
enum BuyBankSlotResult
{
ERR_BANKSLOT_FAILED_TOO_MANY = 0,
ERR_BANKSLOT_INSUFFICIENT_FUNDS = 1,
ERR_BANKSLOT_NOTBANKER = 2,
ERR_BANKSLOT_OK = 3
};
enum PlayerSpellState
{
PLAYERSPELL_UNCHANGED = 0,
PLAYERSPELL_CHANGED = 1,
PLAYERSPELL_NEW = 2,
PLAYERSPELL_REMOVED = 3
};
struct PlayerSpell
{
PlayerSpellState state : 8;
bool active : 1;
bool disabled : 1;
};
// Spell modifier (used for modify other spells)
struct SpellModifier
{
SpellModOp op : 8;
SpellModType type : 8;
int16 charges : 16;
int32 value;
uint64 mask;
uint32 spellId;
uint32 effectId;
Spell const* lastAffected;
};
typedef UNORDERED_MAP<uint16, PlayerSpell> PlayerSpellMap;
typedef std::list<SpellModifier*> SpellModList;
struct SpellCooldown
{
time_t end;
uint16 itemid;
};
typedef std::map<uint32, SpellCooldown> SpellCooldowns;
enum TrainerSpellState
{
TRAINER_SPELL_GREEN = 0,
TRAINER_SPELL_RED = 1,
TRAINER_SPELL_GRAY = 2
};
enum ActionButtonUpdateState
{
ACTIONBUTTON_UNCHANGED = 0,
ACTIONBUTTON_CHANGED = 1,
ACTIONBUTTON_NEW = 2,
ACTIONBUTTON_DELETED = 3
};
struct ActionButton
{
ActionButton() : action(0), type(0), misc(0), uState(ACTIONBUTTON_NEW) {}
ActionButton(uint16 _action, uint8 _type, uint8 _misc) : action(_action), type(_type), misc(_misc), uState(ACTIONBUTTON_NEW) {}
uint16 action;
uint8 type;
uint8 misc;
ActionButtonUpdateState uState;
};
enum ActionButtonType
{
ACTION_BUTTON_SPELL = 0,
ACTION_BUTTON_MACRO = 64,
ACTION_BUTTON_CMACRO = 65,
ACTION_BUTTON_ITEM = 128
};
#define MAX_ACTION_BUTTONS 132 //checked in 2.3.0
typedef std::map<uint8, ActionButton> ActionButtonList;
typedef std::pair<uint16, uint8> CreateSpellPair;
struct PlayerCreateInfoItem
{
PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) {}
uint32 item_id;
uint32 item_amount;
};
typedef std::list<PlayerCreateInfoItem> PlayerCreateInfoItems;
struct PlayerClassLevelInfo
{
PlayerClassLevelInfo() : basehealth(0), basemana(0) {}
uint16 basehealth;
uint16 basemana;
};
struct PlayerClassInfo
{
PlayerClassInfo() : levelInfo(NULL) { }
PlayerClassLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1
};
struct PlayerLevelInfo
{
PlayerLevelInfo()
{
for (int i = 0; i < MAX_STATS; ++i) stats[i] = 0;
}
uint8 stats[MAX_STATS];
};
struct PlayerInfo
{
// existence checked by displayId != 0 // existence checked by displayId != 0
PlayerInfo() : mapId(0), areaId(0), positionX(0.0f), positionY(0.0f), positionZ(0.0f), orientation(0.0f), displayId_m(0), displayId_f(0), levelInfo(nullptr) { }
uint32 mapId;
uint32 areaId;
float positionX;
float positionY;
float positionZ;
float orientation;
uint16 displayId_m;
uint16 displayId_f;
PlayerCreateInfoItems item;
std::list<CreateSpellPair> spell;
std::list<uint16> action[4];
PlayerLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1
};
struct PvPInfo
{
PvPInfo() : inHostileArea(false), inNoPvPArea(false), inFFAPvPArea(false), endTimer(0) {}
bool inHostileArea;
bool inNoPvPArea;
bool inFFAPvPArea;
time_t endTimer;
};
struct DuelInfo
{
DuelInfo() : initiator(NULL), opponent(NULL), startTimer(0), startTime(0), outOfBound(0) {}
Player* initiator;
Player* opponent;
time_t startTimer;
time_t startTime;
time_t outOfBound;
};
struct Areas
{
uint32 areaID;
uint32 areaFlag;
float x1;
float x2;
float y1;
float y2;
};
struct EnchantDuration
{
EnchantDuration() : item(NULL), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) {};
EnchantDuration(Item* _item, EnchantmentSlot _slot, uint32 _leftduration) : item(_item), slot(_slot), leftduration(_leftduration)
{
assert(item);
};
Item* item;
EnchantmentSlot slot;
uint32 leftduration;
};
typedef std::list<EnchantDuration> EnchantDurationList;
typedef std::list<Item*> ItemDurationList;
struct LookingForGroupSlot
{
LookingForGroupSlot() : entry(0), type(0) {}
bool Empty() const
{
return !entry && !type;
}
void Clear()
{
entry = 0;
type = 0;
}
void Set(uint32 _entry, uint32 _type)
{
entry = _entry;
type = _type;
}
bool Is(uint32 _entry, uint32 _type) const
{
return entry == _entry && type == _type;
}
bool canAutoJoin() const
{
return entry && (type == 1 || type == 5);
}
uint32 entry;
uint32 type;
};
#define MAX_LOOKING_FOR_GROUP_SLOT 3
struct LookingForGroup
{
LookingForGroup() {}
bool HaveInSlot(LookingForGroupSlot const& slot) const
{
return HaveInSlot(slot.entry, slot.type);
}
bool HaveInSlot(uint32 _entry, uint32 _type) const
{
for (int i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
if (slots[i].Is(_entry, _type))
return true;
return false;
}
bool canAutoJoin() const
{
for (int i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
if (slots[i].canAutoJoin())
return true;
return false;
}
bool Empty() const
{
for (int i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
if (!slots[i].Empty())
return false;
return more.Empty();
}
LookingForGroupSlot slots[MAX_LOOKING_FOR_GROUP_SLOT];
LookingForGroupSlot more;
std::string comment;
};
enum PlayerMovementType
{
MOVE_ROOT = 1,
MOVE_UNROOT = 2,
MOVE_WATER_WALK = 3,
MOVE_LAND_WALK = 4
};
enum DrunkenState
{
DRUNKEN_SOBER = 0,
DRUNKEN_TIPSY = 1,
DRUNKEN_DRUNK = 2,
DRUNKEN_SMASHED = 3
};
enum PlayerFlags
{
PLAYER_FLAGS_GROUP_LEADER = 0x00000001,
PLAYER_FLAGS_AFK = 0x00000002,
PLAYER_FLAGS_DND = 0x00000004,
PLAYER_FLAGS_GM = 0x00000008,
PLAYER_FLAGS_GHOST = 0x00000010,
PLAYER_FLAGS_RESTING = 0x00000020,
PLAYER_FLAGS_FFA_PVP = 0x00000080,
PLAYER_FLAGS_CONTESTED_PVP = 0x00000100, // Player has been involved in a PvP combat and will be attacked by contested guards
PLAYER_FLAGS_IN_PVP = 0x00000200,
PLAYER_FLAGS_HIDE_HELM = 0x00000400,
PLAYER_FLAGS_HIDE_CLOAK = 0x00000800,
PLAYER_FLAGS_UNK1 = 0x00001000, // played long time
PLAYER_FLAGS_UNK2 = 0x00002000, // played too long time
PLAYER_FLAGS_UNK3 = 0x00008000, // strange visual effect (2.0.1), looks like PLAYER_FLAGS_GHOST flag
PLAYER_FLAGS_SANCTUARY = 0x00010000, // player entered sanctuary
PLAYER_FLAGS_TAXI_BENCHMARK = 0x00020000, // taxi benchmark mode (on/off) (2.0.1)
PLAYER_FLAGS_PVP_TIMER = 0x00040000, // 2.0.8...
};
// used for PLAYER__FIELD_KNOWN_TITLES field (uint64), (1<<bit_index) without (-1)
// can't use enum for uint64 values
#define PLAYER_TITLE_DISABLED UI64LIT(0x0000000000000000)
#define PLAYER_TITLE_NONE UI64LIT(0x0000000000000001)
#define PLAYER_TITLE_PRIVATE UI64LIT(0x0000000000000002) // 1
#define PLAYER_TITLE_CORPORAL UI64LIT(0x0000000000000004) // 2
#define PLAYER_TITLE_SERGEANT_A UI64LIT(0x0000000000000008) // 3
#define PLAYER_TITLE_MASTER_SERGEANT UI64LIT(0x0000000000000010) // 4
#define PLAYER_TITLE_SERGEANT_MAJOR UI64LIT(0x0000000000000020) // 5
#define PLAYER_TITLE_KNIGHT UI64LIT(0x0000000000000040) // 6
#define PLAYER_TITLE_KNIGHT_LIEUTENANT UI64LIT(0x0000000000000080) // 7
#define PLAYER_TITLE_KNIGHT_CAPTAIN UI64LIT(0x0000000000000100) // 8
#define PLAYER_TITLE_KNIGHT_CHAMPION UI64LIT(0x0000000000000200) // 9
#define PLAYER_TITLE_LIEUTENANT_COMMANDER UI64LIT(0x0000000000000400) // 10
#define PLAYER_TITLE_COMMANDER UI64LIT(0x0000000000000800) // 11
#define PLAYER_TITLE_MARSHAL UI64LIT(0x0000000000001000) // 12
#define PLAYER_TITLE_FIELD_MARSHAL UI64LIT(0x0000000000002000) // 13
#define PLAYER_TITLE_GRAND_MARSHAL UI64LIT(0x0000000000004000) // 14
#define PLAYER_TITLE_SCOUT UI64LIT(0x0000000000008000) // 15
#define PLAYER_TITLE_GRUNT UI64LIT(0x0000000000010000) // 16
#define PLAYER_TITLE_SERGEANT_H UI64LIT(0x0000000000020000) // 17
#define PLAYER_TITLE_SENIOR_SERGEANT UI64LIT(0x0000000000040000) // 18
#define PLAYER_TITLE_FIRST_SERGEANT UI64LIT(0x0000000000080000) // 19
#define PLAYER_TITLE_STONE_GUARD UI64LIT(0x0000000000100000) // 20
#define PLAYER_TITLE_BLOOD_GUARD UI64LIT(0x0000000000200000) // 21
#define PLAYER_TITLE_LEGIONNAIRE UI64LIT(0x0000000000400000) // 22
#define PLAYER_TITLE_CENTURION UI64LIT(0x0000000000800000) // 23
#define PLAYER_TITLE_CHAMPION UI64LIT(0x0000000001000000) // 24
#define PLAYER_TITLE_LIEUTENANT_GENERAL UI64LIT(0x0000000002000000) // 25
#define PLAYER_TITLE_GENERAL UI64LIT(0x0000000004000000) // 26
#define PLAYER_TITLE_WARLORD UI64LIT(0x0000000008000000) // 27
#define PLAYER_TITLE_HIGH_WARLORD UI64LIT(0x0000000010000000) // 28
#define PLAYER_TITLE_GLADIATOR UI64LIT(0x0000000020000000) // 29
#define PLAYER_TITLE_DUELIST UI64LIT(0x0000000040000000) // 30
#define PLAYER_TITLE_RIVAL UI64LIT(0x0000000080000000) // 31
#define PLAYER_TITLE_CHALLENGER UI64LIT(0x0000000100000000) // 32
#define PLAYER_TITLE_SCARAB_LORD UI64LIT(0x0000000200000000) // 33
#define PLAYER_TITLE_CONQUEROR UI64LIT(0x0000000400000000) // 34
#define PLAYER_TITLE_JUSTICAR UI64LIT(0x0000000800000000) // 35
#define PLAYER_TITLE_CHAMPION_OF_THE_NAARU UI64LIT(0x0000001000000000) // 36
#define PLAYER_TITLE_MERCILESS_GLADIATOR UI64LIT(0x0000002000000000) // 37
#define PLAYER_TITLE_OF_THE_SHATTERED_SUN UI64LIT(0x0000004000000000) // 38
#define PLAYER_TITLE_HAND_OF_ADAL UI64LIT(0x0000008000000000) // 39
#define PLAYER_TITLE_VENGEFUL_GLADIATOR UI64LIT(0x0000010000000000) // 40
#define KNOWN_TITLES_SIZE 2
#define MAX_TITLE_INDEX (KNOWN_TITLES_SIZE*64) // 2 uint64 fields
// used in PLAYER_FIELD_BYTES values
enum PlayerFieldByteFlags
{
PLAYER_FIELD_BYTE_TRACK_STEALTHED = 0x00000002,
PLAYER_FIELD_BYTE_RELEASE_TIMER = 0x00000008, // Display time till auto release spirit
PLAYER_FIELD_BYTE_NO_RELEASE_WINDOW = 0x00000010 // Display no "release spirit" window at all
};
// used in PLAYER_FIELD_BYTES2 values
enum PlayerFieldByte2Flags
{
PLAYER_FIELD_BYTE2_NONE = 0x00,
PLAYER_FIELD_BYTE2_STEALTH = 0x2000,
PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW = 0x4000
};
enum ActivateTaxiReplies
{
ERR_TAXIOK = 0,
ERR_TAXIUNSPECIFIEDSERVERERROR = 1,
ERR_TAXINOSUCHPATH = 2,
ERR_TAXINOTENOUGHMONEY = 3,
ERR_TAXITOOFARAWAY = 4,
ERR_TAXINOVENDORNEARBY = 5,
ERR_TAXINOTVISITED = 6,
ERR_TAXIPLAYERBUSY = 7,
ERR_TAXIPLAYERALREADYMOUNTED = 8,
ERR_TAXIPLAYERSHAPESHIFTED = 9,
ERR_TAXIPLAYERMOVING = 10,
ERR_TAXISAMENODE = 11,
ERR_TAXINOTSTANDING = 12
};
enum MirrorTimerType
{
FATIGUE_TIMER = 0,
BREATH_TIMER = 1,
FIRE_TIMER = 2
};
#define MAX_TIMERS 3
#define DISABLED_MIRROR_TIMER -1
// 2^n values
enum PlayerExtraFlags
{
// gm abilities
PLAYER_EXTRA_GM_ON = 0x0001,
PLAYER_EXTRA_ACCEPT_WHISPERS = 0x0004,
PLAYER_EXTRA_TAXICHEAT = 0x0008,
PLAYER_EXTRA_GM_INVISIBLE = 0x0010,
PLAYER_EXTRA_GM_CHAT = 0x0020, // Show GM badge in chat messages
// other states
PLAYER_EXTRA_PVP_DEATH = 0x0100 // store PvP death status until corpse creating.
};
// 2^n values
enum AtLoginFlags
{
AT_LOGIN_NONE = 0,
AT_LOGIN_RENAME = 1,
AT_LOGIN_RESET_SPELLS = 2,
AT_LOGIN_RESET_TALENTS = 4,
AT_LOGIN_RESURRECT = 8
};
typedef std::map<uint32, QuestStatusData> QuestStatusMap;
enum QuestSlotOffsets
{
QUEST_ID_OFFSET = 0,
QUEST_STATE_OFFSET = 1,
QUEST_COUNTS_OFFSET = 2,
QUEST_TIME_OFFSET = 3
};
#define MAX_QUEST_OFFSET 4
enum QuestSlotStateMask
{
QUEST_STATE_NONE = 0x0000,
QUEST_STATE_COMPLETE = 0x0001,
QUEST_STATE_FAIL = 0x0002
};
enum SkillUpdateState
{
SKILL_UNCHANGED = 0,
SKILL_CHANGED = 1,
SKILL_NEW = 2,
SKILL_DELETED = 3
};
struct SkillStatusData
{
SkillStatusData(uint8 _pos, SkillUpdateState _uState) : pos(_pos), uState(_uState)
{
}
uint8 pos;
SkillUpdateState uState;
};
typedef UNORDERED_MAP<uint32, SkillStatusData> SkillStatusMap;
class Quest;
class Spell;
class Item;
class WorldSession;
enum PlayerSlots
{
// first slot for item stored (in any way in player m_items data)
PLAYER_SLOT_START = 0,
// last+1 slot for item stored (in any way in player m_items data)
PLAYER_SLOT_END = 118,
PLAYER_SLOTS_COUNT = (PLAYER_SLOT_END - PLAYER_SLOT_START)
};
enum EquipmentSlots
{
EQUIPMENT_SLOT_START = 0,
EQUIPMENT_SLOT_HEAD = 0,
EQUIPMENT_SLOT_NECK = 1,
EQUIPMENT_SLOT_SHOULDERS = 2,
EQUIPMENT_SLOT_BODY = 3,
EQUIPMENT_SLOT_CHEST = 4,
EQUIPMENT_SLOT_WAIST = 5,
EQUIPMENT_SLOT_LEGS = 6,
EQUIPMENT_SLOT_FEET = 7,
EQUIPMENT_SLOT_WRISTS = 8,
EQUIPMENT_SLOT_HANDS = 9,
EQUIPMENT_SLOT_FINGER1 = 10,
EQUIPMENT_SLOT_FINGER2 = 11,
EQUIPMENT_SLOT_TRINKET1 = 12,
EQUIPMENT_SLOT_TRINKET2 = 13,
EQUIPMENT_SLOT_BACK = 14,
EQUIPMENT_SLOT_MAINHAND = 15,
EQUIPMENT_SLOT_OFFHAND = 16,
EQUIPMENT_SLOT_RANGED = 17,
EQUIPMENT_SLOT_TABARD = 18,
EQUIPMENT_SLOT_END = 19
};
enum InventorySlots // 4 slots
{
INVENTORY_SLOT_BAG_0 = 255,
INVENTORY_SLOT_BAG_START = 19,
INVENTORY_SLOT_BAG_END = 23,
};
enum InventoryPackSlots // 16 slots
{
INVENTORY_SLOT_ITEM_START = 23,
INVENTORY_SLOT_ITEM_END = 39
};
enum BankItemSlots // 28 slots
{
BANK_SLOT_ITEM_START = 39,
BANK_SLOT_ITEM_END = 67
};
enum BankBagSlots // 7 slots
{
BANK_SLOT_BAG_START = 67,
BANK_SLOT_BAG_END = 74
};
enum BuyBackSlots // 12 slots
{
// stored in m_buybackitems
BUYBACK_SLOT_START = 74,
BUYBACK_SLOT_END = 86
};
enum KeyRingSlots // 32 slots
{
KEYRING_SLOT_START = 86,
KEYRING_SLOT_END = 118
};
struct ItemPosCount
{
ItemPosCount(uint16 _pos, uint8 _count) : pos(_pos), count(_count) {}
bool isContainedIn(std::vector<ItemPosCount> const& vec) const;
uint16 pos;
uint8 count;
};
typedef std::vector<ItemPosCount> ItemPosCountVec;
enum TradeSlots
{
TRADE_SLOT_COUNT = 7,
TRADE_SLOT_TRADED_COUNT = 6,
TRADE_SLOT_NONTRADED = 6
};
enum TransferAbortReason
{
TRANSFER_ABORT_NONE = 0x0000,
TRANSFER_ABORT_MAX_PLAYERS = 0x0001, // Transfer Aborted: instance is full
TRANSFER_ABORT_NOT_FOUND = 0x0002, // Transfer Aborted: instance not found
TRANSFER_ABORT_TOO_MANY_INSTANCES = 0x0003, // You have entered too many instances recently.
TRANSFER_ABORT_ZONE_IN_COMBAT = 0x0005, // Unable to zone in while an encounter is in progress.
TRANSFER_ABORT_INSUF_EXPAN_LVL1 = 0x0106, // You must have TBC expansion installed to access this area.
TRANSFER_ABORT_DIFFICULTY1 = 0x0007, // Normal difficulty mode is not available for %s.
TRANSFER_ABORT_DIFFICULTY2 = 0x0107, // Heroic difficulty mode is not available for %s.
};
enum InstanceResetWarningType
{
RAID_INSTANCE_WARNING_HOURS = 1, // WARNING! %s is scheduled to reset in %d hour(s).
RAID_INSTANCE_WARNING_MIN = 2, // WARNING! %s is scheduled to reset in %d minute(s)!
RAID_INSTANCE_WARNING_MIN_SOON = 3, // WARNING! %s is scheduled to reset in %d minute(s). Please exit the zone or you will be returned to your bind location!
RAID_INSTANCE_WELCOME = 4 // Welcome to %s. This raid instance is scheduled to reset in %s.
};
class InstanceSave;
// PLAYER_FIELD_ARENA_TEAM_INFO_1_1 offsets
enum ArenaTeamInfoType
{
ARENA_TEAM_ID = 0,
ARENA_TEAM_MEMBER = 1, // 0 - captain, 1 - member
ARENA_TEAM_GAMES_WEEK = 2,
ARENA_TEAM_GAMES_SEASON = 3,
ARENA_TEAM_WINS_SEASON = 4,
ARENA_TEAM_PERSONAL_RATING = 5,
ARENA_TEAM_END = 6
};
enum RestFlag
{
REST_FLAG_IN_TAVERN = 0x1,
REST_FLAG_IN_CITY = 0x2,
REST_FLAG_IN_FACTION_AREA = 0x4, // used with AREA_FLAG_REST_ZONE_*
};
enum DuelCompleteType
{
DUEL_INTERUPTED = 0,
DUEL_WON = 1,
DUEL_FLED = 2
};
enum TeleportToOptions
{
TELE_TO_GM_MODE = 0x01,
TELE_TO_NOT_LEAVE_TRANSPORT = 0x02,
TELE_TO_NOT_LEAVE_COMBAT = 0x04,
TELE_TO_NOT_UNSUMMON_PET = 0x08,
TELE_TO_SPELL = 0x10,
};
// Type of environmental damages
enum EnviromentalDamage
{
DAMAGE_EXHAUSTED = 0,
DAMAGE_DROWNING = 1,
DAMAGE_FALL = 2,
DAMAGE_LAVA = 3,
DAMAGE_SLIME = 4,
DAMAGE_FIRE = 5,
DAMAGE_FALL_TO_VOID = 6 // custom case for fall without durability loss
};
enum PlayerChatTag
{
CHAT_TAG_NONE = 0x00,
CHAT_TAG_AFK = 0x01,
CHAT_TAG_DND = 0x02,
CHAT_TAG_GM = 0x04,
CHAT_TAG_COM = 0x08, // [Unused WotLK] Commentator
CHAT_TAG_DEV = 0x10 // [Unused WotLK]
};
enum PlayedTimeIndex
{
PLAYED_TIME_TOTAL = 0,
PLAYED_TIME_LEVEL = 1
};
#define MAX_PLAYED_TIME_INDEX 2
// used at player loading query list preparing, and later result selection
enum PlayerLoginQueryIndex
{
PLAYER_LOGIN_QUERY_LOADFROM = 0,
PLAYER_LOGIN_QUERY_LOADGROUP = 1,
PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES = 2,
PLAYER_LOGIN_QUERY_LOADAURAS = 3,
PLAYER_LOGIN_QUERY_LOADSPELLS = 4,
PLAYER_LOGIN_QUERY_LOADQUESTSTATUS = 5,
PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS = 6,
PLAYER_LOGIN_QUERY_LOADTUTORIALS = 7, // common for all characters for some account at specific realm
PLAYER_LOGIN_QUERY_LOADREPUTATION = 8,
PLAYER_LOGIN_QUERY_LOADINVENTORY = 9,
PLAYER_LOGIN_QUERY_LOADACTIONS = 10,
PLAYER_LOGIN_QUERY_LOADMAILCOUNT = 11,
PLAYER_LOGIN_QUERY_LOADMAILDATE = 12,
PLAYER_LOGIN_QUERY_LOADSOCIALLIST = 13,
PLAYER_LOGIN_QUERY_LOADHOMEBIND = 14,
PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS = 15,
PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES = 16,
PLAYER_LOGIN_QUERY_LOADGUILD = 17,
PLAYER_LOGIN_QUERY_LOADARENAINFO = 18,
PLAYER_LOGIN_QUERY_LOADBGDATA = 19,
PLAYER_LOGIN_QUERY_LOADSKILLS = 20,
MAX_PLAYER_LOGIN_QUERY
};
enum PlayerDelayedOperations
{
DELAYED_SAVE_PLAYER = 0x01,
DELAYED_RESURRECT_PLAYER = 0x02,
DELAYED_SPELL_CAST_DESERTER = 0x04,
DELAYED_BG_MOUNT_RESTORE = 0x08, // Flag to restore mount state after teleport from BG
DELAYED_BG_TAXI_RESTORE = 0x10, // Flag to restore taxi state after teleport from BG
DELAYED_GROUP_RESTORE = 0x20, // Flag to tell player he's in a group (client would crash if this is sent at loading screen)
DELAYED_END
};
// Player summoning auto-decline time (in secs)
#define MAX_PLAYER_SUMMON_DELAY (2*MINUTE)
#define MAX_MONEY_AMOUNT (0x7FFFFFFF-1)
struct InstancePlayerBind
{
InstanceSave* save;
bool perm;
/* permanent PlayerInstanceBinds are created in Raid/Heroic instances for players
that aren't already permanently bound when they are inside when a boss is killed
or when they enter an instance that the group leader is permanently bound to. */
InstancePlayerBind() : save(NULL), perm(false) {}
};
struct AccessRequirement
{
uint8 levelMin;
uint8 levelMax;
uint32 item;
uint32 item2;
uint32 heroicKey;
uint32 heroicKey2;
uint32 quest;
std::string questFailedText;
uint32 heroicQuest;
std::string heroicQuestFailedText;
};
enum CharDeleteMethod
{
CHAR_DELETE_REMOVE = 0, // Completely remove from the database
CHAR_DELETE_UNLINK = 1 // The character gets unlinked from the account,
// the name gets freed up and appears as deleted ingame
};
enum PlayerRestState
{
REST_STATE_RESTED = 1, // 200% xp
REST_STATE_NORMAL = 2, // 100% xp
REST_STATE_TIRED_1 = 3, // 100% xp
REST_STATE_TIRED_2 = 4, // 50% xp
REST_STATE_EXHAUSTED = 5, // 25% xp
REST_STATE_RAF_LINKED = 6 // 200% xp
};
enum ReferFriendError
{
RAF_ERR_OK = 0x00,
RAF_ERR_BAD_REFERRER = 0x01, // You were not referred by that player
RAF_ERR_LVL_TOO_HIGH = 0x02, // That player's level is too high
RAF_ERR_NO_GRANTABLE_LVLS = 0x03, // You have not earned enough levels to grant any more levels
RAF_ERR_TOO_FAR_AWAY = 0x04, // That player is too far away
RAF_ERR_OPPOSITE_FACTION = 0x05, // No cannot grant level to a character of the opposite faction
RAF_ERR_NOT_RIGHT_NOW = 0x06, // You cannot grant that player a level right now
RAF_ERR_ONLY_UNTIL_60 = 0x07, // You cannot grant levels to players level 60 or higher
RAF_ERR_NO_TARGET = 0x08, // You have no target
RAF_ERR_NOT_IN_PARTY = 0x09, // %s is not in your party
RAF_ERR_ONLY_UNTIL_60_2 = 0x0A, // You cannot summon players above level 60
RAF_ERR_SUMMON_NOT_READY = 0x0B, // You can only summon your friend once per hour
RAF_ERR_BUDDY_OFFLINE = 0x0C // %s is offline and cannot be summoned
};
enum RAFLinkStatus
{
RAF_LINK_NONE = 0,
RAF_LINK_REFERRER = 1,
RAF_LINK_REFERRED = 2
};
enum PlayerCommandStates
{
CHEAT_NONE = 0x00,
CHEAT_GOD = 0x01,
CHEAT_CASTTIME = 0x02,
CHEAT_COOLDOWN = 0x04,
CHEAT_POWER = 0x08,
CHEAT_WATERWALK = 0x10
};
class PlayerTaxi
{
public:
PlayerTaxi();
~PlayerTaxi() {}
// Nodes
void InitTaxiNodesForLevel(uint32 race, uint32 level);
void LoadTaxiMask(const char* data);
void SaveTaxiMask(const char* data);
uint32 GetTaximask(uint8 index) const
{
return m_taximask[index];
}
bool IsTaximaskNodeKnown(uint32 nodeidx) const
{
uint8 field = uint8((nodeidx - 1) / 32);
uint32 submask = 1 << ((nodeidx - 1) % 32);
return (m_taximask[field] & submask) == submask;
}
bool SetTaximaskNode(uint32 nodeidx)
{
uint8 field = uint8((nodeidx - 1) / 32);
uint32 submask = 1 << ((nodeidx - 1) % 32);
if ((m_taximask[field] & submask) != submask)
{
m_taximask[field] |= submask;
return true;
}
else
return false;
}
void AppendTaximaskTo(ByteBuffer& data, bool all);
// Destinations
bool LoadTaxiDestinationsFromString(const std::string& values);
std::string SaveTaxiDestinationsToString();
void ClearTaxiDestinations()
{
m_TaxiDestinations.clear();
}
void AddTaxiDestination(uint32 dest)
{
m_TaxiDestinations.push_back(dest);
}
uint32 GetTaxiSource() const
{
return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front();
}
uint32 GetTaxiDestination() const
{
return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1];
}
uint32 GetCurrentTaxiPath() const;
uint32 NextTaxiDestination()
{
m_TaxiDestinations.pop_front();
return GetTaxiDestination();
}
bool empty() const { return m_TaxiDestinations.empty(); }
private:
TaxiMask m_taximask;
std::deque<uint32> m_TaxiDestinations;
};
class Player;
// Holder for Battleground data
struct BGData
{
BGData() : bgInstanceID(0), bgTypeID(0), bgAfkReportedCount(0), bgAfkReportedTimer(0),
bgTeam(0), mountSpell(0)
{
ClearTaxiPath();
}
uint32 bgInstanceID; // This variable is set to bg->m_InstanceID,
// when player is teleported to BG - (it is battleground's GUID)
uint32 bgTypeID;
std::set<uint32> bgAfkReporter;
uint8 bgAfkReportedCount;
time_t bgAfkReportedTimer;
uint32 bgTeam; // What side the player will be added to
uint32 mountSpell;
uint32 taxiPath[2];
WorldLocation joinPos; // From where player entered BG
void ClearTaxiPath()
{
taxiPath[0] = taxiPath[1] = 0;
}
bool HasTaxiPath() const
{
return taxiPath[0] && taxiPath[1];
}
};
class Player : public Unit, public GridObject<Player>
{
friend class WorldSession;
friend class CinematicMgr;
friend class RegressionTestSuite;
friend void Item::AddToUpdateQueueOf(Player* player);
friend void Item::RemoveFromUpdateQueueOf(Player* player);
public:
explicit Player(WorldSession* session);
~Player() override;
void CleanupsBeforeDelete() override;
static UpdateMask updateVisualBits;
static void InitVisibleBits();
void AddToWorld() override;
void RemoveFromWorld() override;
void SetObjectScale(float scale)
{
Unit::SetObjectScale(scale);
SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, scale * DEFAULT_WORLD_OBJECT_SIZE);
SetFloatValue(UNIT_FIELD_COMBATREACH, scale * DEFAULT_COMBAT_REACH);
}
bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0);
bool TeleportTo(WorldLocation const &loc, uint32 options = 0);
bool TeleportToBGEntryPoint();
void SetSummonPoint(uint32 mapid, float x, float y, float z);
void SummonIfPossible(bool agree);
bool Create(uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId);
void Update(uint32 time) override;
static bool BuildEnumData(QueryResult_AutoPtr result, WorldPacket* data);
void SetInWater(bool apply);
bool IsInWater() const override { return m_isInWater; }
bool IsUnderWater() const override;
bool IsFalling() { return GetPositionZ() < m_lastFallZ; }
bool IsInAreaTriggerRadius(const AreaTriggerEntry* trigger) const;
void SendInitialPacketsBeforeAddToMap();
void SendInitialPacketsAfterAddToMap();
void SendTransferAborted(uint32 mapid, uint16 reason);
void SendInstanceResetWarning(uint32 mapid, uint32 time);
bool CanInteractWithQuestGiver(Object* questGiver);
Creature* GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask);
GameObject* GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const;
void ToggleAFK();
void ToggleDND();
bool isAFK() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); }
bool isDND() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); }
uint8 GetChatTag() const;
std::string autoReplyMsg;
PlayerSocial* GetSocial()
{
return m_social;
}
PlayerTaxi m_taxi;
void InitTaxiNodesForLevel()
{
m_taxi.InitTaxiNodesForLevel(getRace(), getLevel());
}
bool ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id = 0 , Creature* npc = NULL);
bool ActivateTaxiPathTo(uint32 taxi_path_id);
void CleanupAfterTaxiFlight();
void ContinueTaxiFlight();
// mount_id can be used in scripting calls
bool isAcceptWhispers() const
{
return m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS;
}
void SetAcceptWhispers(bool on)
{
if (on) m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS;
else m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS;
}
bool IsGameMaster() const
{
return m_ExtraFlags & PLAYER_EXTRA_GM_ON;
}
void SetGameMaster(bool on);
bool isGMChat() const
{
return GetSession()->GetSecurity() >= SEC_MODERATOR && (m_ExtraFlags & PLAYER_EXTRA_GM_CHAT);
}
void SetGMChat(bool on)
{
if (on) m_ExtraFlags |= PLAYER_EXTRA_GM_CHAT;
else m_ExtraFlags &= ~PLAYER_EXTRA_GM_CHAT;
}
bool isTaxiCheater() const
{
return m_ExtraFlags & PLAYER_EXTRA_TAXICHEAT;
}
void SetTaxiCheater(bool on)
{
if (on) m_ExtraFlags |= PLAYER_EXTRA_TAXICHEAT;
else m_ExtraFlags &= ~PLAYER_EXTRA_TAXICHEAT;
}
bool isGMVisible() const
{
return !(m_ExtraFlags & PLAYER_EXTRA_GM_INVISIBLE);
}
void SetGMVisible(bool on);
void SetPvPDeath(bool on)
{
if (on) m_ExtraFlags |= PLAYER_EXTRA_PVP_DEATH;
else m_ExtraFlags &= ~PLAYER_EXTRA_PVP_DEATH;
}
void GiveXP(uint32 xp, Unit* victim, bool disableRafBonus = false);
void GiveLevel(uint32 level, bool ignoreRAF = false);
void InitStatsForLevel(bool reapplyMods = false);
// .cheat command related
bool GetCommandStatus(uint32 command) const { return _activeCheats & command; }
void SetCommandStatusOn(uint32 command) { _activeCheats |= command; }
void SetCommandStatusOff(uint32 command) { _activeCheats &= ~command; }
// Played Time Stuff
time_t m_logintime;
time_t m_Last_tick;
uint32 m_Played_time[MAX_PLAYED_TIME_INDEX];
uint32 GetTotalPlayedTime()
{
return m_Played_time[PLAYED_TIME_TOTAL];
}
uint32 GetLevelPlayedTime()
{
return m_Played_time[PLAYED_TIME_LEVEL];
}
void ResetTimeSync();
void SendTimeSync();
void setDeathState(DeathState s) override; // overwrite Unit::setDeathState
float GetRestBonus() const { return m_rest_bonus; }
void SetRestBonus(float rest_bonus_new);
bool HasRestFlag(RestFlag restFlag) const { return (_restFlagMask & restFlag) != 0; }
void SetRestFlag(RestFlag restFlag, uint32 triggerId = 0);
void RemoveRestFlag(RestFlag restFlag);
uint32 GetXPRestBonus(uint32 xp);
uint32 GetInnTriggerId() const { return inn_triggerId; }
Pet* GetPet() const;
Pet* SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 despwtime);
void RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent = false);
uint32 GetPhaseMaskForSpawn() const; // used for proper set phase for DB at GM-mode creature/GO spawn
void Say(const std::string& text, const uint32 language);
void Yell(const std::string& text, const uint32 language);
void TextEmote(const std::string& text);
void Whisper(const std::string& text, const uint32 language, uint64 receiver);
void Whisper(const std::string& text, const uint32 language, Player* receiver);
void BuildPlayerChat(WorldPacket* data, uint8 msgtype, const std::string& text, uint32 language) const;
/*********************************************************/
/*** STORAGE SYSTEM ***/
/*********************************************************/
void SetVirtualItemSlot(uint8 i, Item* item);
void SetSheath(SheathState sheathed) override; // overwrite Unit version
uint8 FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) const;
uint32 GetItemCount(uint32 item, bool inBankAlso = false, Item* skipItem = NULL) const;
Item* GetItemByGuid(uint64 guid) const;
Item* GetItemByPos(uint16 pos) const;
Item* GetItemByPos(uint8 bag, uint8 slot) const;
Item* GetWeaponForAttack(WeaponAttackType attackType, bool useable = false) const;
Item* GetShield(bool useable = false) const;
static uint32 GetAttackBySlot(uint8 slot); // MAX_ATTACK if not weapon slot
std::vector<Item* >& GetItemUpdateQueue()
{
return m_itemUpdateQueue;
}
static bool IsInventoryPos(uint16 pos)
{
return IsInventoryPos(pos >> 8, pos & 255);
}
static bool IsInventoryPos(uint8 bag, uint8 slot);
static bool IsEquipmentPos(uint16 pos)
{
return IsEquipmentPos(pos >> 8, pos & 255);
}
static bool IsEquipmentPos(uint8 bag, uint8 slot);
static bool IsBagPos(uint16 pos);
static bool IsBankPos(uint16 pos)
{
return IsBankPos(pos >> 8, pos & 255);
}
static bool IsBankPos(uint8 bag, uint8 slot);
bool IsValidPos(uint16 pos)
{
return IsBankPos(pos >> 8, pos & 255);
}
bool IsValidPos(uint8 bag, uint8 slot);
uint8 GetBankBagSlotCount() const
{
return GetByteValue(PLAYER_BYTES_2, 2);
}
bool HasBankBagSlot(uint8 slot) const;
bool HasItemCount(uint32 item, uint32 count, bool inBankAlso = false) const;
bool HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem = NULL);
bool CanCastNoReagents(SpellEntry const* spellInfo) const;
Item* GetItemOrItemWithGemEquipped(uint32 item) const;
uint8 CanTakeMoreSimilarItems(Item* pItem) const
{
return _CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem);
}
uint8 CanTakeMoreSimilarItems(uint32 entry, uint32 count) const
{
return _CanTakeMoreSimilarItems(entry, count, NULL);
}
uint8 CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = NULL) const
{
return _CanStoreItem(bag, slot, dest, item, count, NULL, false, no_space_count);
}
uint8 CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap = false) const
{
if (!pItem)
return EQUIP_ERR_ITEM_NOT_FOUND;
uint32 count = pItem->GetCount();
return _CanStoreItem(bag, slot, dest, pItem->GetEntry(), count, pItem, swap, NULL);
}
uint8 CanStoreItems(Item** pItem, int count) const;
uint8 CanEquipNewItem(uint8 slot, uint16& dest, uint32 item, bool swap) const;
uint8 CanEquipItem(uint8 slot, uint16& dest, Item* pItem, bool swap, bool not_loading = true) const;
uint8 CanUnequipItems(uint32 item, uint32 count) const;
uint8 CanUnequipItem(uint16 src, bool swap) const;
uint8 CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap, bool not_loading = true) const;
uint8 CanUseItem(Item* pItem, bool not_loading = true) const;
bool HasItemTotemCategory(uint32 TotemCategory) const;
bool CanUseItem(ItemTemplate const* pItem);
uint8 CanUseAmmo(uint32 item) const;
Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0);
Item* StoreItem(ItemPosCountVec const& pos, Item* pItem, bool update);
Item* EquipNewItem(uint16 pos, uint32 item, bool update);
Item* EquipItem(uint16 pos, Item* pItem, bool update);
void AutoUnequipOffhandIfNeed();
bool StoreNewItemInBestSlots(uint32 item_id, uint32 item_count);
uint8 _CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = NULL) const;
uint8 _CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = NULL, bool swap = false, uint32* no_space_count = NULL) const;
void ApplyEquipCooldown(Item* pItem);
void SetAmmo(uint32 item);
void RemoveAmmo();
float GetAmmoDPS() const
{
return m_ammoDPS;
}
bool CheckAmmoCompatibility(const ItemTemplate* ammo_proto) const;
void QuickEquipItem(uint16 pos, Item* pItem);
void VisualizeItem(uint8 slot, Item* pItem);
void SetVisibleItemSlot(uint8 slot, Item* pItem);
Item* BankItem(ItemPosCountVec const& dest, Item* pItem, bool update)
{
return StoreItem(dest, pItem, update);
}
Item* BankItem(uint16 pos, Item* pItem, bool update);
void RemoveItem(uint8 bag, uint8 slot, bool update);
void MoveItemFromInventory(uint8 bag, uint8 slot, bool update);
// in trade, auction, guild bank, mail....
void MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB = false);
// in trade, guild bank, mail....
void RemoveItemDependentAurasAndCasts(Item* pItem);
void DestroyItem(uint8 bag, uint8 slot, bool update);
void DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check = false);
void DestroyItemCount(Item* item, uint32& count, bool update);
void DestroyConjuredItems(bool update);
void DestroyZoneLimitedItem(bool update, uint32 new_zone);
void SplitItem(uint16 src, uint16 dst, uint32 count);
void SwapItem(uint16 src, uint16 dst);
void AddItemToBuyBackSlot(Item* pItem);
Item* GetItemFromBuyBackSlot(uint32 slot);
void RemoveItemFromBuyBackSlot(uint32 slot, bool del);
uint32 GetMaxKeyringSize() const
{
return KEYRING_SLOT_END - KEYRING_SLOT_START;
}
void SendEquipError(uint8 msg, Item* pItem, Item* pItem2);
void SendBuyError(uint8 msg, Creature* pCreature, uint32 item, uint32 param);
void SendSellError(uint8 msg, Creature* pCreature, uint64 guid, uint32 param);
void SendReferFriendError(ReferFriendError err, const char* name = 0);
void AddWeaponProficiency(uint32 newflag)
{
m_WeaponProficiency |= newflag;
}
void AddArmorProficiency(uint32 newflag)
{
m_ArmorProficiency |= newflag;
}
uint32 GetWeaponProficiency() const
{
return m_WeaponProficiency;
}
uint32 GetArmorProficiency() const
{
return m_ArmorProficiency;
}
bool IsInFeralForm() const
{
return m_form == FORM_CAT || m_form == FORM_BEAR || m_form == FORM_DIREBEAR;
}
bool IsUseEquippedWeapon(bool mainhand) const
{
// disarm applied only to mainhand weapon
return !IsInFeralForm() && m_form != FORM_GHOSTWOLF && (!mainhand || !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED));
}
void SendNewItem(Item* item, uint32 count, bool received, bool created, bool broadcast = false);
bool BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot);
float GetReputationPriceDiscount(Creature const* pCreature) const;
Player* GetTrader() const
{
return pTrader;
}
void ClearTrade();
void TradeCancel(bool sendback);
CinematicMgr* GetCinematicMgr() const { return _cinematicMgr; }
Item* GetItemByTradeSlot(uint8 slot) const
{
if (slot < TRADE_SLOT_COUNT && tradeItems[slot])
return GetItemByGuid(tradeItems[slot]);
return NULL;
}
void UpdateEnchantTime(uint32 time);
void UpdateItemDuration(uint32 time, bool realtimeonly = false);
void AddEnchantmentDurations(Item* item);
void RemoveEnchantmentDurations(Item* item);
void RemoveEnchantmentDurationsReferences(Item* item);
void RemoveAllEnchantments(EnchantmentSlot slot, bool arena);
void AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration);
void ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur = true, bool ignore_condition = false);
void ApplyEnchantment(Item* item, bool apply);
void SendEnchantmentDurations();
void AddItemDurations(Item* item);
void RemoveItemDurations(Item* item);
void SendItemDurations();
void LoadCorpse();
void LoadPet();
uint32 GetFullGrantableLevels() const
{
return uint32(m_GrantableLevels);
}
float GetGrantableLevels() const
{
return m_GrantableLevels;
}
void SetGrantableLevels(float amount)
{
if (uint32(m_GrantableLevels = amount) > 0)
SetByteFlag(PLAYER_FIELD_BYTES, 1, 1);
else
RemoveByteFlag(PLAYER_FIELD_BYTES, 1, 1);
}
float GetReferFriendXPMultiplier() const;
bool AddItem(uint32 itemId, uint32 count);
uint32 m_stableSlots;
/*********************************************************/
/*** GOSSIP SYSTEM ***/
/*********************************************************/
void PrepareGossipMenu(WorldObject* source, uint32 menuId = 0, bool showQuests = false);
void SendPreparedGossip(WorldObject* source);
void OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 menuId);
uint32 GetGossipTextId(uint32 menuId, WorldObject* source);
uint32 GetGossipTextId(WorldObject* pSource);
uint32 GetDefaultGossipMenuForSource(WorldObject* pSource);
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
// Return player level when QuestLevel is dynamic (-1)
uint32 GetQuestLevelForPlayer(Quest const* pQuest) const
{
return pQuest && (pQuest->GetQuestLevel() > 0) ? pQuest->GetQuestLevel() : getLevel();
}
void PrepareQuestMenu(uint64 guid);
void SendPreparedQuest(uint64 guid);
bool IsActiveQuest(uint32 quest_id) const;
Quest const* GetNextQuest(uint64 guid, Quest const* pQuest);
bool CanSeeStartQuest(Quest const* pQuest);
bool CanTakeQuest(Quest const* pQuest, bool msg);
bool CanAddQuest(Quest const* pQuest, bool msg);
bool CanCompleteQuest(uint32 quest_id);
bool CanCompleteRepeatableQuest(Quest const* pQuest);
bool CanRewardQuest(Quest const* pQuest, bool msg);
bool CanRewardQuest(Quest const* pQuest, uint32 reward, bool msg);
void AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver);
void AddQuest(Quest const* pQuest, Object* questGiver);
void CompleteQuest(uint32 quest_id);
void IncompleteQuest(uint32 quest_id);
void AbandonQuest(uint32 questId);
void RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, bool announce = true);
void FailQuest(uint32 questId);
bool SatisfyQuestSkill(Quest const* qInfo, bool msg) const;
bool SatisfyQuestLevel(Quest const* qInfo, bool msg);
bool SatisfyQuestLog(bool msg);
bool SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg);
bool SatisfyQuestClass(Quest const* qInfo, bool msg) const;
bool SatisfyQuestRace(Quest const* qInfo, bool msg);
bool SatisfyQuestReputation(Quest const* qInfo, bool msg);
bool SatisfyQuestStatus(Quest const* qInfo, bool msg);
bool SatisfyQuestConditions(Quest const* qInfo, bool msg);
bool SatisfyQuestTimed(Quest const* qInfo, bool msg);
bool SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg);
bool SatisfyQuestNextChain(Quest const* qInfo, bool msg);
bool SatisfyQuestPrevChain(Quest const* qInfo, bool msg);
bool SatisfyQuestDay(Quest const* qInfo, bool msg);
bool GiveQuestSourceItem(Quest const* pQuest);
bool TakeQuestSourceItem(uint32 quest_id, bool msg);
bool GetQuestRewardStatus(uint32 quest_id) const;
QuestStatus GetQuestStatus(uint32 quest_id) const;
void SetQuestStatus(uint32 quest_id, QuestStatus status);
void SetDailyQuestStatus(uint32 quest_id);
void ResetDailyQuestStatus();
uint16 FindQuestSlot(uint32 quest_id) const;
uint32 GetQuestSlotQuestId(uint16 slot) const
{
return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET);
}
uint32 GetQuestSlotState(uint16 slot) const
{
return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET);
}
uint32 GetQuestSlotCounters(uint16 slot)const
{
return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET);
}
uint8 GetQuestSlotCounter(uint16 slot, uint8 counter) const
{
return GetByteValue(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, counter);
}
uint32 GetQuestSlotTime(uint16 slot) const
{
return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET);
}
void SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer = 0)
{
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET, quest_id);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, 0);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, 0);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer);
}
void SetQuestSlotCounter(uint16 slot, uint8 counter, uint8 count)
{
SetByteValue(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, counter, count);
}
void SetQuestSlotState(uint16 slot, uint32 state)
{
SetFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state);
}
void RemoveQuestSlotState(uint16 slot, uint32 state)
{
RemoveFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state);
}
void SetQuestSlotTimer(uint16 slot, uint32 timer)
{
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer);
}
void SwapQuestSlot(uint16 slot1, uint16 slot2)
{
for (int i = 0; i < MAX_QUEST_OFFSET; ++i)
{
uint32 temp1 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i);
uint32 temp2 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i, temp2);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i, temp1);
}
}
uint32 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry);
void AdjustQuestReqItemCount(Quest const* pQuest);
void AreaExploredOrEventHappens(uint32 questId);
void GroupEventHappens(uint32 questId, WorldObject const* pEventObject);
void ItemAddedQuestCheck(uint32 entry, uint32 count);
void ItemRemovedQuestCheck(uint32 entry, uint32 count);
void KilledMonster(CreatureInfo const* cInfo, uint64 guid);
void KilledMonsterCredit(uint32 entry, uint64 guid = 0);
void CastedCreatureOrGO(uint32 entry, uint64 guid, uint32 spell_id);
void TalkedToCreature(uint32 entry, uint64 guid);
void MoneyChanged(uint32 value);
bool HasQuestForItem(uint32 itemid) const;
bool HasQuestForGO(int32 GOId);
void UpdateForQuestsGO();
bool CanShareQuest(uint32 quest_id) const;
void SendQuestComplete(uint32 quest_id);
void SendQuestReward(Quest const* pQuest, uint32 XP, Object* questGiver);
void SendQuestFailed(uint32 quest_id);
void SendQuestTimerFailed(uint32 quest_id);
void SendCanTakeQuestResponse(uint32 msg) const;
void SendQuestConfirmAccept(Quest const* pQuest, Player* pReceiver);
void SendPushToPartyResponse(Player* pPlayer, uint32 msg);
void SendQuestUpdateAddItem(Quest const* pQuest, uint32 item_idx, uint32 count);
void SendQuestUpdateAddCreatureOrGo(Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count);
uint32 GetSharedQuestID() const { return m_sharedQuestId; }
ObjectGuid GetPlayerSharingQuest() const { return m_playerSharingQuest; }
void SetQuestSharingInfo(ObjectGuid guid, uint32 id) { m_playerSharingQuest = guid; m_sharedQuestId = id; }
void ClearQuestSharingInfo() { m_playerSharingQuest = 0; m_sharedQuestId = 0; }
uint32 GetInGameTime() const { return m_ingametime; }
void SetInGameTime(uint32 time) { m_ingametime = time; }
void AddTimedQuest(uint32 questId) { m_timedquests.insert(questId); }
void RemoveTimedQuest(uint32 questId) { m_timedquests.erase(questId); }
/*********************************************************/
/*** LOAD SYSTEM ***/
/*********************************************************/
bool LoadFromDB(uint32 guid, SqlQueryHolder* holder);
void Initialize(uint32 guid);
static bool LoadValuesArrayFromDB(Tokens& data, uint64 guid);
static uint32 GetUInt32ValueFromArray(Tokens const& data, uint16 index);
static float GetFloatValueFromArray(Tokens const& data, uint16 index);
static uint32 GetUInt32ValueFromDB(uint16 index, uint64 guid);
static uint32 GetZoneIdFromDB(uint64 guid);
static uint32 GetLevelFromDB(uint64 guid);
static bool LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, uint64 guid);
/*********************************************************/
/*** SAVE SYSTEM ***/
/*********************************************************/
void SaveToDB();
void SaveInventoryAndGoldToDB(); // fast save function for item/money cheating preventing
void SaveGoldToDB();
void SaveDataFieldToDB();
static bool SaveValuesArrayInDB(Tokens const& data, uint64 guid);
static void SetUInt32ValueInArray(Tokens& data, uint16 index, uint32 value);
static void SetFloatValueInArray(Tokens& data, uint16 index, float value);
static void SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid);
static void SavePositionInDB(uint32 mapid, float x, float y, float z, float o, uint32 zone, uint64 guid);
static void DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars = true, bool deleteFinally = false);
static void DeleteOldCharacters();
static void DeleteOldCharacters(uint32 keepDays);
bool m_mailsLoaded;
bool m_mailsUpdated;
void SetBindPoint(uint64 guid);
void SendTalentWipeConfirm(uint64 guid);
void RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker);
void SendPetSkillWipeConfirm();
void CalcRage(uint32 damage, bool attacker);
void RegenerateAll();
void Regenerate(Powers power);
void RegenerateHealth();
void setRegenTimer(uint32 time)
{
m_regenTimer = time;
}
void setWeaponChangeTimer(uint32 time)
{
m_weaponChangeTimer = time;
}
uint32 GetMoney()
{
return GetUInt32Value (PLAYER_FIELD_COINAGE);
}
void ModifyMoney(int32 d)
{
if (d < 0)
SetMoney (GetMoney() > uint32(-d) ? GetMoney() + d : 0);
else
SetMoney (GetMoney() < uint32(MAX_MONEY_AMOUNT - d) ? GetMoney() + d : MAX_MONEY_AMOUNT);
// "At Gold Limit"
if (GetMoney() >= MAX_MONEY_AMOUNT)
SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, NULL, NULL);
}
void SetMoney(uint32 value)
{
SetUInt32Value (PLAYER_FIELD_COINAGE, value);
MoneyChanged(value);
}
uint32 GetTutorialInt(uint32 intId)
{
ASSERT((intId < 8));
return m_Tutorials[intId];
}
void SetTutorialInt(uint32 intId, uint32 value)
{
ASSERT((intId < 8));
if (m_Tutorials[intId] != value)
{
m_Tutorials[intId] = value;
m_TutorialsChanged = true;
}
}
QuestStatusMap& getQuestStatusMap()
{
return mQuestStatus;
};
Unit *GetSelectedUnit() const;
Player *GetSelectedPlayer() const;
const uint64& GetSelection() const
{
return m_curSelection;
}
void SetSelection(const uint64& guid)
{
m_curSelection = guid;
SetUInt64Value(UNIT_FIELD_TARGET, guid);
}
uint8 GetComboPoints()
{
return m_comboPoints;
}
uint64 GetComboTarget()
{
return m_comboTarget;
}
void AddComboPoints(Unit* target, int8 count);
void ClearComboPoints();
void SendComboPoints();
void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, uint32 item_guid = 0, uint32 item_count = 0);
void SendNewMail();
void UpdateNextMailTimeAndUnreads();
void AddNewMailDeliverTime(time_t deliver_time);
bool IsMailsLoaded() const
{
return m_mailsLoaded;
}
//void SetMail(Mail *m);
void RemoveMail(uint32 id);
void AddMail(Mail* mail)
{
m_mail.push_front(mail); // for call from WorldSession::SendMailTo
}
uint32 GetMailSize()
{
return m_mail.size();
}
Mail* GetMail(uint32 id);
PlayerMails::iterator GetmailBegin()
{
return m_mail.begin();
};
PlayerMails::iterator GetmailEnd()
{
return m_mail.end();
};
/*********************************************************/
/*** MAILED ITEMS SYSTEM ***/
/*********************************************************/
uint8 unReadMails;
time_t m_nextMailDelivereTime;
typedef UNORDERED_MAP<uint32, Item*> ItemMap;
ItemMap mMitems; //template defined in objectmgr.cpp
Item* GetMItem(uint32 id)
{
ItemMap::const_iterator itr = mMitems.find(id);
return itr != mMitems.end() ? itr->second : NULL;
}
void AddMItem(Item* it)
{
ASSERT(it);
//assert deleted, because items can be added before loading
mMitems[it->GetGUIDLow()] = it;
}
bool RemoveMItem(uint32 id)
{
return mMitems.erase(id) ? true : false;
}
void PetSpellInitialize();
void CharmSpellInitialize();
void PossessSpellInitialize();
void SendRemoveControlBar();
bool HasSpell(uint32 spell) const override;
bool HasActiveSpell(uint32 spell) const; // shown in spellbook
TrainerSpellState GetTrainerSpellState(TrainerSpell const* trainer_spell) const;
bool IsSpellFitByClassAndRace(uint32 spell_id) const;
void SendProficiency(ItemClass itemClass, uint32 itemSubclassMask);
void SendInitialSpells();
bool AddSpell(uint32 spell_id, bool active, bool learning = true, bool loading = false, bool disabled = false);
void LearnSpell(uint32 spell_id);
void RemoveSpell(uint32 spell_id, bool disabled = false);
void ResetSpells();
void LearnDefaultSpells(bool loading = false);
void LearnQuestRewardedSpells();
void LearnQuestRewardedSpells(Quest const* quest);
void LearnSpellHighestRank(uint32 spellid);
uint32 GetHighestLearnedRankOf(uint32 spellid) const override;
uint32 GetFreeTalentPoints() const
{
return GetUInt32Value(PLAYER_CHARACTER_POINTS1);
}
void SetFreeTalentPoints(uint32 points)
{
SetUInt32Value(PLAYER_CHARACTER_POINTS1, points);
}
bool ResetTalents(bool no_cost = false);
uint32 ResetTalentsCost() const;
void InitTalentForLevel();
uint32 GetFreePrimaryProfessionPoints() const
{
return GetUInt32Value(PLAYER_CHARACTER_POINTS2);
}
void SetFreePrimaryProfessions(uint16 profs)
{
SetUInt32Value(PLAYER_CHARACTER_POINTS2, profs);
}
void InitPrimaryProfessions();
PlayerSpellMap const& GetSpellMap() const
{
return m_spells;
}
PlayerSpellMap& GetSpellMap()
{
return m_spells;
}
void AddSpellMod(SpellModifier* mod, bool apply);
int32 GetTotalFlatMods(uint32 spellId, SpellModOp op);
int32 GetTotalPctMods(uint32 spellId, SpellModOp op);
bool IsAffectedBySpellmod(SpellEntry const* spellInfo, SpellModifier* mod, Spell const* spell = NULL);
template <class T> T ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell const* spell = NULL);
void RemoveSpellMods(Spell const* spell);
void RestoreSpellMods(Spell const* spell);
bool HasSpellCooldown(uint32 spell_id) const
{
SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
return itr != m_spellCooldowns.end() && itr->second.end > time(NULL);
}
uint32 GetSpellCooldownDelay(uint32 spell_id) const
{
SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
time_t t = time(NULL);
return itr != m_spellCooldowns.end() && itr->second.end > t ? itr->second.end - t : 0;
}
void AddSpellCooldown(uint32 spell_id, uint32 itemid, time_t end_time);
void SendCooldownEvent(SpellEntry const* spellInfo);
void ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) override;
void RemoveSpellCooldown(uint32 spell_id, bool update = false);
void SendClearCooldown(uint32 spell_id, Unit* target);
void RemoveArenaSpellCooldowns();
void RemoveAllSpellCooldown();
void _LoadSpellCooldowns(QueryResult_AutoPtr result);
void _SaveSpellCooldowns();
// global cooldown
void AddGlobalCooldown(SpellEntry const* spellInfo, Spell* spell);
bool HasGlobalCooldown(SpellEntry const* spellInfo) const;
void RemoveGlobalCooldown(SpellEntry const* spellInfo);
void setResurrectRequestData(uint64 guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana)
{
m_resurrectGUID = guid;
m_resurrectMap = mapId;
m_resurrectX = X;
m_resurrectY = Y;
m_resurrectZ = Z;
m_resurrectHealth = health;
m_resurrectMana = mana;
}
void clearResurrectRequestData()
{
setResurrectRequestData(0, 0, 0.0f, 0.0f, 0.0f, 0, 0);
}
bool isRessurectRequestedBy(uint64 guid) const
{
return m_resurrectGUID == guid;
}
bool isRessurectRequested() const
{
return m_resurrectGUID != 0;
}
void ResurectUsingRequestData();
int getCinematic()
{
return m_cinematic;
}
void setCinematic(int cine)
{
m_cinematic = cine;
}
void addActionButton(uint8 button, uint16 action, uint8 type, uint8 misc);
void removeActionButton(uint8 button);
void SendInitialActionButtons();
PvPInfo pvpInfo;
void UpdatePvPState(bool onlyFFA = false);
void SetPvP(bool state)
{
Unit::SetPvP(state);
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->SetPvP(state);
}
void UpdatePvP(bool state, bool override = false);
bool IsFFAPvP() const
{
return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
}
void SetFFAPvP(bool state);
void UpdateZone(uint32 newZone);
void UpdateArea(uint32 newArea);
void UpdateZoneDependentAuras(uint32 zone_id); // zones
void UpdateAreaDependentAuras(uint32 area_id); // subzones
void UpdateAfkReport(time_t currTime);
void UpdatePvPFlag(time_t currTime);
void UpdateContestedPvP(uint32 currTime);
void SetContestedPvPTimer(uint32 newTime)
{
m_contestedPvPTimer = newTime;
}
void ResetContestedPvP()
{
ClearUnitState(UNIT_STATE_ATTACK_PLAYER);
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
m_contestedPvPTimer = 0;
}
/** @todo -maybe move UpdateDuelFlag+DuelComplete to independent DuelHandler.. **/
DuelInfo* duel;
void UpdateDuelFlag(time_t currTime);
void CheckDuelDistance(time_t currTime);
void DuelComplete(DuelCompleteType type);
bool IsGroupVisibleFor(Player const* p) const;
bool IsInSameGroupWith(Player const* p) const;
bool IsInSameRaidWith(Player const* p) const
{
return p == this || (GetGroup() != NULL && GetGroup() == p->GetGroup());
}
void UninviteFromGroup();
static void RemoveFromGroup(Group* group, uint64 guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, uint64 kicker = 0 , const char* reason = NULL);
void RemoveFromGroup(RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT) { RemoveFromGroup(GetGroup(),GetGUID(), method); }
void SendUpdateToOutOfRangeGroupMembers();
void SetInGuild(uint32 GuildId)
{
SetUInt32Value(PLAYER_GUILDID, GuildId);
}
void SetRank(uint32 rankId)
{
SetUInt32Value(PLAYER_GUILDRANK, rankId);
}
void SetGuildIdInvited(uint32 GuildId)
{
m_GuildIdInvited = GuildId;
}
uint32 GetGuildId()
{
return GetUInt32Value(PLAYER_GUILDID);
}
static uint32 GetGuildIdFromDB(uint64 guid);
uint32 GetRank()
{
return GetUInt32Value(PLAYER_GUILDRANK);
}
static uint32 GetRankFromDB(uint64 guid);
int GetGuildIdInvited()
{
return m_GuildIdInvited;
}
static void RemovePetitionsAndSigns(uint64 guid, uint32 type);
// Arena Team
void SetInArenaTeam(uint32 ArenaTeamId, uint8 slot)
{
SetArenaTeamInfoField(slot, ARENA_TEAM_ID, ArenaTeamId);
}
void SetArenaTeamInfoField(uint8 slot, ArenaTeamInfoType type, uint32 value)
{
SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + type, value);
}
uint32 GetArenaTeamId(uint8 slot)
{
return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_ID);
}
uint32 GetArenaPersonalRating(uint8 slot)
{
return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING);
}
static uint32 GetArenaTeamIdFromDB(uint64 guid, uint8 slot);
void SetArenaTeamIdInvited(uint32 ArenaTeamId)
{
m_ArenaTeamIdInvited = ArenaTeamId;
}
uint32 GetArenaTeamIdInvited()
{
return m_ArenaTeamIdInvited;
}
void SetDifficulty(DungeonDifficulty dungeon_difficulty)
{
m_dungeonDifficulty = dungeon_difficulty;
}
DungeonDifficulty GetDifficulty()
{
return m_dungeonDifficulty;
}
bool UpdateSkill(uint32 skill_id, uint32 step);
bool UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step);
bool UpdateCraftSkill(uint32 spellid);
bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1);
bool UpdateFishingSkill();
uint32 GetBaseDefenseSkillValue() const
{
return GetBaseSkillValue(SKILL_DEFENSE);
}
uint32 GetBaseWeaponSkillValue(WeaponAttackType attType) const;
uint32 GetSpellByProto(ItemTemplate* proto);
float GetHealthBonusFromStamina();
float GetManaBonusFromIntellect();
bool UpdateStats(Stats stat) override;
bool UpdateAllStats() override;
void UpdateResistances(uint32 school) override;
void UpdateArmor() override;
void UpdateMaxHealth() override;
void UpdateMaxPower(Powers power) override;
void UpdateAttackPowerAndDamage(bool ranged = false) override;
void UpdateShieldBlockValue();
void UpdateSpellDamageAndHealingBonus();
void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) override;
void UpdateDefenseBonusesMod();
void ApplyRatingMod(CombatRating cr, int32 value, bool apply);
float GetMeleeCritFromAgility();
float GetDodgeFromAgility();
float GetSpellCritFromIntellect();
float OCTRegenHPPerSpirit();
float OCTRegenMPPerSpirit();
float GetRatingMultiplier(CombatRating cr) const;
float GetRatingBonusValue(CombatRating cr) const;
uint32 GetMeleeCritDamageReduction(uint32 damage) const;
uint32 GetRangedCritDamageReduction(uint32 damage) const;
uint32 GetSpellCritDamageReduction(uint32 damage) const;
uint32 GetDotDamageReduction(uint32 damage) const;
float GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const;
void UpdateBlockPercentage();
void UpdateCritPercentage(WeaponAttackType attType);
void UpdateAllCritPercentages();
void UpdateParryPercentage();
void UpdateDodgePercentage();
void UpdateMeleeHitChances();
void UpdateRangedHitChances();
void UpdateSpellHitChances();
void UpdateAllSpellCritChances();
void UpdateSpellCritChance(uint32 school);
void UpdateExpertise(WeaponAttackType attType);
void UpdateManaRegen();
const uint64& GetLootGUID() const
{
return m_lootGuid;
}
void SetLootGUID(const uint64& guid)
{
m_lootGuid = guid;
}
void RemovedInsignia(Player* looterPlr);
WorldSession* GetSession() const
{
return m_session;
}
void SetSession(WorldSession* s)
{
m_session = s;
}
void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const override;
void DestroyForPlayer(Player* target, bool onDeath = false) const override;
void SendDelayResponse(const uint32);
void SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP, bool RafBonus = false);
uint8 LastSwingErrorMsg() const { return m_swingErrorMsg; }
void SwingErrorMsg(uint8 val) { m_swingErrorMsg = val; }
//notifiers
void SendAttackSwingCantAttack();
void SendAttackSwingCancelAttack();
void SendAttackSwingDeadTarget();
void SendAttackSwingNotStanding();
void SendAttackSwingNotInRange();
void SendAttackSwingBadFacingAttack();
void SendAutoRepeatCancel();
void SendExplorationExperience(uint32 Area, uint32 Experience);
void SendDungeonDifficulty(bool IsInGroup);
void ResetInstances(uint8 method);
void SendResetInstanceSuccess(uint32 MapId);
void SendResetInstanceFailed(uint32 reason, uint32 MapId);
void SendResetFailedNotify(uint32 mapid);
bool SetPosition(float x, float y, float z, float orientation, bool teleport = false) override;
bool SetPosition(const Position& pos, bool teleport = false)
{
return SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport);
}
void UpdateUnderwaterState(Map* m, float x, float y, float z);
void SendMessageToSet(WorldPacket *data, bool self) override {SendMessageToSetInRange(data, GetVisibilityRange(), self); };// overwrite Object::SendMessageToSet
void SendMessageToSetInRange(WorldPacket* data, float fist, bool self) override;// overwrite Object::SendMessageToSetInRange
void SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool own_team_only);
Corpse* GetCorpse() const;
void SpawnCorpseBones();
void CreateCorpse();
void KillPlayer();
uint32 GetResurrectionSpellId();
void ResurrectPlayer(float restore_percent, bool applySickness = false);
void BuildPlayerRepop();
void RepopAtGraveyard();
void DurabilityLossAll(double percent, bool inventory);
void DurabilityLoss(Item* item, double percent);
void DurabilityPointsLossAll(int32 points, bool inventory);
void DurabilityPointsLoss(Item* item, int32 points);
void DurabilityPointLossForEquipSlot(EquipmentSlots slot);
uint32 DurabilityRepairAll(bool cost, float discountMod, bool guildBank);
uint32 DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank);
void UpdateMirrorTimers();
void StopMirrorTimers()
{
StopMirrorTimer(FATIGUE_TIMER);
StopMirrorTimer(BREATH_TIMER);
StopMirrorTimer(FIRE_TIMER);
}
void JoinedChannel(Channel* c);
void LeftChannel(Channel* c);
void CleanupChannels();
void UpdateLocalChannels(uint32 newZone);
void LeaveLFGChannel();
void UpdateDefense();
void UpdateWeaponSkill (WeaponAttackType attType);
void UpdateCombatSkills(Unit* victim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence);
void SetSkill(uint32 id, uint16 currVal, uint16 maxVal);
uint16 GetMaxSkillValue(uint32 skill) const; // max + perm. bonus
uint16 GetPureMaxSkillValue(uint32 skill) const; // max
uint16 GetSkillValue(uint32 skill) const; // skill value + perm. bonus + temp bonus
uint16 GetBaseSkillValue(uint32 skill) const; // skill value + perm. bonus
uint16 GetPureSkillValue(uint32 skill) const; // skill value
int16 GetSkillTempBonusValue(uint32 skill) const;
bool HasSkill(uint32 skill) const;
void LearnSkillRewardedSpells(uint32 id);
void LearnSkillRewardedSpells();
WorldLocation& GetTeleportDest()
{
return m_teleport_dest;
}
bool IsBeingTeleported() const
{
return mSemaphoreTeleport_Near || mSemaphoreTeleport_Far;
}
bool IsBeingTeleportedNear() const
{
return mSemaphoreTeleport_Near;
}
bool IsBeingTeleportedFar() const
{
return mSemaphoreTeleport_Far;
}
void SetSemaphoreTeleportNear(bool semphsetting)
{
mSemaphoreTeleport_Near = semphsetting;
}
void SetSemaphoreTeleportFar(bool semphsetting)
{
mSemaphoreTeleport_Far = semphsetting;
}
void ProcessDelayedOperations();
void CheckAreaExploreAndOutdoor(void);
static uint32 TeamForRace(uint8 race);
uint32 GetTeam() const { return m_team; }
TeamId GetTeamId() const
{
return m_team == ALLIANCE ? TEAM_ALLIANCE : TEAM_HORDE;
}
static uint32 getFactionForRace(uint8 race);
void setFactionForRace(uint8 race);
bool IsAtGroupRewardDistance(WorldObject const* pRewardSource) const;
void RewardPlayerAndGroupAtKill(Unit* victim);
void RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource);
bool isHonorOrXPTarget(Unit* victim) const;
ReputationMgr& GetReputationMgr() { return m_reputationMgr; }
ReputationMgr const& GetReputationMgr() const { return m_reputationMgr; }
ReputationRank GetReputationRank(uint32 faction_id) const;
void RewardReputation(Unit* victim, float rate);
void RewardReputation(Quest const* pQuest);
int32 CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest);
void UpdateSkillsForLevel();
void UpdateSkillsToMaxSkillsForLevel(); // for .levelup
void ModifySkillBonus(uint32 skillid, int32 val, bool talent);
/*********************************************************/
/*** PVP SYSTEM ***/
/*********************************************************/
void UpdateHonorFields();
bool RewardHonor(Unit* victim, uint32 groupsize, float honor = -1, bool pvptoken = false);
uint32 GetHonorPoints()
{
return GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY);
}
uint32 GetArenaPoints()
{
return GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY);
}
void ModifyHonorPoints(int32 value);
void ModifyArenaPoints(int32 value, bool update = true);
uint8 GetHighestPvPRankIndex();
uint32 GetMaxPersonalArenaRatingRequirement();
//End of PvP System
void SetDrunkValue(uint16 newDrunkValue, uint32 itemid = 0);
uint16 GetDrunkValue() const
{
return m_drunk;
}
static DrunkenState GetDrunkenstateByValue(uint16 value);
uint32 GetDeathTimer() const
{
return m_deathTimer;
}
uint32 GetCorpseReclaimDelay(bool pvp) const;
void UpdateCorpseReclaimDelay();
int32 CalculateCorpseReclaimDelay(bool load = false);
void SendCorpseReclaimDelay(uint32 delay);
uint32 GetShieldBlockValue() const override; // overwrite Unit version (virtual)
bool CanParry() const
{
return m_canParry;
}
void SetCanParry(bool value);
bool CanBlock() const
{
return m_canBlock;
}
void SetCanBlock(bool value);
void SetRegularAttackTime();
void SetBaseModValue(BaseModGroup modGroup, BaseModType modType, float value)
{
m_auraBaseMod[modGroup][modType] = value;
}
void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply);
float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const;
float GetTotalBaseModValue(BaseModGroup modGroup) const;
float GetTotalPercentageModValue(BaseModGroup modGroup) const
{
return m_auraBaseMod[modGroup][FLAT_MOD] + m_auraBaseMod[modGroup][PCT_MOD];
}
void _ApplyAllStatBonuses();
void _RemoveAllStatBonuses();
void ResetAllPowers();
void _ApplyWeaponDependentAuraMods(Item* item, WeaponAttackType attackType, bool apply);
void _ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attackType, Aura* aura, bool apply);
void _ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType attackType, Aura* aura, bool apply);
void _ApplyItemMods(Item* item, uint8 slot, bool apply);
void _RemoveAllItemMods();
void _ApplyAllItemMods();
void _ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply);
void _ApplyAmmoBonuses();
bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot);
void ToggleMetaGemsActive(uint8 exceptslot, bool apply);
void CorrectMetaGemEnchants(uint8 slot, bool apply);
void InitDataForForm(bool reapplyMods = false);
void ApplyItemEquipSpell(Item* item, bool apply, bool form_change = false);
void ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change = false);
void UpdateEquipSpellsAtFormChange();
void CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, SpellEntry const* spellInfo = NULL);
void CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item* item, ItemTemplate const* proto, SpellEntry const* spell = NULL);
void SendInitWorldStates(bool force = false, uint32 forceZoneId = 0);
void SendUpdateWorldState(uint32 Field, uint32 Value);
void SendDirectMessage(WorldPacket* data);
void SendAuraDurationsForTarget(Unit* target);
PlayerMenu* PlayerTalkClass;
std::vector<ItemSetEffect*> ItemSetEff;
void SendLoot(uint64 guid, LootType loot_type);
void SendLootError(uint64 guid, LootError error);
void SendLootRelease(uint64 guid);
void SendNotifyLootItemRemoved(uint8 lootSlot);
void SendNotifyLootMoneyRemoved();
/*********************************************************/
/*** BATTLEGROUND SYSTEM ***/
/*********************************************************/
bool InBattleground() const
{
return m_bgData.bgInstanceID != 0;
}
bool InArena() const;
uint32 GetBattlegroundId() const
{
return m_bgData.bgInstanceID;
}
Battleground* GetBattleground() const;
static uint32 GetMinLevelForBattlegroundQueueId(uint32 queue_id);
static uint32 GetMaxLevelForBattlegroundQueueId(uint32 queue_id);
uint32 GetBattlegroundQueueIdFromLevel() const;
bool InBattlegroundQueue() const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueType != 0)
return true;
return false;
}
uint32 GetBattlegroundQueueId(uint32 index) const
{
return m_bgBattlegroundQueueID[index].bgQueueType;
}
uint32 GetBattlegroundQueueIndex(uint32 bgQueueType) const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueType == bgQueueType)
return i;
return PLAYER_MAX_BATTLEGROUND_QUEUES;
}
bool IsInvitedForBattlegroundQueueType(uint32 bgQueueType) const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueType == bgQueueType)
return m_bgBattlegroundQueueID[i].invitedToInstance != 0;
return false;
}
bool InBattlegroundQueueForBattlegroundQueueType(uint32 bgQueueType) const
{
return GetBattlegroundQueueIndex(bgQueueType) < PLAYER_MAX_BATTLEGROUND_QUEUES;
}
void SetBattlegroundId(uint32 val)
{
m_bgData.bgInstanceID = val;
}
uint32 AddBattlegroundQueueId(uint32 val)
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
if (m_bgBattlegroundQueueID[i].bgQueueType == 0 || m_bgBattlegroundQueueID[i].bgQueueType == val)
{
m_bgBattlegroundQueueID[i].bgQueueType = val;
m_bgBattlegroundQueueID[i].invitedToInstance = 0;
return i;
}
}
return PLAYER_MAX_BATTLEGROUND_QUEUES;
}
bool HasFreeBattlegroundQueueId()
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueType == 0)
return true;
return false;
}
void RemoveBattlegroundQueueId(uint32 val)
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
if (m_bgBattlegroundQueueID[i].bgQueueType == val)
{
m_bgBattlegroundQueueID[i].bgQueueType = 0;
m_bgBattlegroundQueueID[i].invitedToInstance = 0;
return;
}
}
}
void SetInviteForBattlegroundQueueType(uint32 bgQueueType, uint32 instanceId)
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueType == bgQueueType)
m_bgBattlegroundQueueID[i].invitedToInstance = instanceId;
}
bool IsInvitedForBattlegroundInstance(uint32 instanceId) const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].invitedToInstance == instanceId)
return true;
return false;
}
WorldLocation const& GetBattlegroundEntryPoint() const
{
return m_bgData.joinPos;
}
void SetBattlegroundEntryPoint();
void SetBattlegroundEntryPoint(uint32 Map, float PosX, float PosY, float PosZ, float PosO)
{
m_bgData.joinPos = WorldLocation(Map, PosX, PosY, PosZ, PosO);
}
void SetBGTeam(uint32 team)
{
m_bgData.bgTeam = team;
}
uint32 GetBGTeam() const
{
return m_bgData.bgTeam ? m_bgData.bgTeam : GetTeam();
}
void LeaveBattleground(bool teleportToEntryPoint = true);
bool CanJoinToBattleground() const;
bool CanReportAfkDueToLimit();
void ReportedAfkBy(Player* reporter);
void ClearAfkReports()
{
m_bgData.bgAfkReporter.clear();
}
bool GetBGAccessByLevel(uint32 bgTypeId) const;
bool isTotalImmunity();
bool CanUseBattlegroundObject(GameObject* gameobject);
bool CanCaptureTowerPoint();
/*********************************************************/
/*** OUTDOOR PVP SYSTEM ***/
/*********************************************************/
OutdoorPvP* GetOutdoorPvP() const;
// returns true if the player is in active state for outdoor pvp objective capturing, false otherwise
bool IsOutdoorPvPActive();
/*********************************************************/
/*** ENVIROMENTAL SYSTEM ***/
/*********************************************************/
void EnvironmentalDamage(EnviromentalDamage type, uint32 damage);
/*********************************************************/
/*** FLOOD FILTER SYSTEM ***/
/*********************************************************/
void UpdateSpeakTime();
bool CanSpeak() const;
void ChangeSpeakTime(int utime);
/*********************************************************/
/*** VARIOUS SYSTEMS ***/
/*********************************************************/
uint32 m_lastFallTime;
float m_lastFallZ;
Unit* m_mover;
WorldObject* m_seer;
void SetFallInformation(uint32 time, float z)
{
m_lastFallTime = time;
m_lastFallZ = z;
}
void BuildTeleportAckMsg( WorldPacket* data, float x, float y, float z, float ang) const;
bool isMovingOrTurning() const
{
return HasUnitMovementFlag(MOVEMENTFLAG_TURNING);
}
bool CanFly() const
{
return HasUnitMovementFlag(MOVEMENTFLAG_CAN_FLY);
}
void HandleFallDamage(MovementInfo& movementInfo);
void HandleFallUnderMap();
void SetClientControl(Unit* target, bool allowMove);
void SetMover(Unit* target)
{
//m_mover->m_movedPlayer = NULL;
m_mover = target;
//m_mover->m_movedPlayer = this;
}
void SetSeer(WorldObject* target)
{
m_seer = target;
}
void SetViewpoint(WorldObject* target, bool apply);
WorldObject* GetViewpoint() const;
void StopCastingCharm();
void StopCastingBindSight();
// Transports
Transport* GetTransport() const
{
return m_transport;
}
void SetTransport(Transport* t)
{
m_transport = t;
}
float GetTransOffsetX() const
{
return m_movementInfo.GetTransportPos()->m_positionX;
}
float GetTransOffsetY() const
{
return m_movementInfo.GetTransportPos()->m_positionY;
}
float GetTransOffsetZ() const
{
return m_movementInfo.GetTransportPos()->m_positionZ;
}
float GetTransOffsetO() const
{
return m_movementInfo.GetTransportPos()->GetOrientation();
}
uint32 GetTransTime() const
{
return m_movementInfo.GetTransportTime();
}
uint32 GetSaveTimer() const
{
return m_nextSave;
}
void SetSaveTimer(uint32 timer)
{
m_nextSave = timer;
}
// Recall position
uint32 m_recallMap;
float m_recallX;
float m_recallY;
float m_recallZ;
float m_recallO;
void SaveRecallPosition();
// Homebind coordinates
uint32 m_homebindMapId;
uint16 m_homebindAreaId;
float m_homebindX;
float m_homebindY;
float m_homebindZ;
void SetHomebindToLocation(WorldLocation const& loc, uint32 area_id);
void RelocateToHomebind(uint32& newMap)
{
newMap = m_homebindMapId;
Relocate(m_homebindX, m_homebindY, m_homebindZ);
}
bool TeleportToHomebind(uint32 options = 0)
{
return TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation(), options);
}
WorldLocation GetStartPosition() const;
// currently visible objects at player client
typedef std::set<uint64> ClientGUIDs;
ClientGUIDs m_clientGUIDs;
bool HaveAtClient(WorldObject const* u) const;
bool IsNeverVisible() const override;
bool IsVisibleGloballyFor(Player* pl) const;
void UpdateObjectVisibility(bool forced = true) override;
void UpdateVisibilityForPlayer();
void UpdateVisibilityOf(WorldObject* target);
void UpdateTriggerVisibility();
template<class T>
void UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow);
uint8 m_forced_speed_changes[MAX_MOVE_TYPE];
bool HasAtLoginFlag(AtLoginFlags f) const
{
return m_atLoginFlags & f;
}
void SetAtLoginFlag(AtLoginFlags f)
{
m_atLoginFlags |= f;
}
LookingForGroup m_lookingForGroup;
// Temporarily removed pet cache
uint32 GetTemporaryUnsummonedPetNumber() const
{
return m_temporaryUnsummonedPetNumber;
}
void SetTemporaryUnsummonedPetNumber(uint32 petnumber)
{
m_temporaryUnsummonedPetNumber = petnumber;
}
uint32 GetOldPetSpell() const
{
return m_oldpetspell;
}
void SetOldPetSpell(uint32 petspell)
{
m_oldpetspell = petspell;
}
void UnsummonPetTemporaryIfAny();
void ResummonTemporaryUnsummonedPetIfAny();
// Handle pet status here
PetStatus GetPetStatus() const
{
return m_petStatus;
}
void SetPetStatus(PetStatus status)
{
m_petStatus = status;
}
bool isPetDeadAndRemoved() const
{
return (m_petStatus == PET_STATUS_DEAD_AND_REMOVED);
}
bool isPetDismissed() const
{
return (m_petStatus == PET_STATUS_DISMISSED);
}
bool doesOwnPet() const
{
return (m_petStatus != PET_STATUS_NONE);
}
void SendCinematicStart(uint32 CinematicSequenceId);
/*********************************************************/
/*** INSTANCE SYSTEM ***/
/*********************************************************/
typedef UNORDERED_MAP< uint32 /*mapId*/, InstancePlayerBind > BoundInstancesMap;
void UpdateHomebindTime(uint32 time);
uint32 m_HomebindTimer;
bool m_InstanceValid;
// permanent binds and solo binds by difficulty
BoundInstancesMap m_boundInstances[TOTAL_DIFFICULTIES];
InstancePlayerBind* GetBoundInstance(uint32 mapid, uint8 difficulty);
BoundInstancesMap& GetBoundInstances(uint8 difficulty)
{
return m_boundInstances[difficulty];
}
InstanceSave* GetInstanceSave(uint32 mapid);
void UnbindInstance(uint32 mapid, uint8 difficulty, bool unload = false);
void UnbindInstance(BoundInstancesMap::iterator& itr, uint8 difficulty, bool unload = false);
InstancePlayerBind* BindToInstance(InstanceSave* save, bool permanent, bool load = false);
void SendRaidInfo();
void SendSavedInstances();
bool CheckInstanceValidity(bool /*isLogin*/);
static void ConvertInstancesToGroup(Player* player, Group* group = NULL, uint64 player_guid = 0);
bool Satisfy(AccessRequirement const*, uint32 target_map, bool report = false);
// last used pet number (for BG's)
uint32 GetLastPetNumber() const { return m_lastpetnumber; }
void SetLastPetNumber(uint32 petnumber) { m_lastpetnumber = petnumber; }
/*********************************************************/
/*** GROUP SYSTEM ***/
/*********************************************************/
Group* GetGroupInvite()
{
return m_groupInvite;
}
void SetGroupInvite(Group* group)
{
m_groupInvite = group;
}
Group* GetGroup()
{
return m_group.getTarget();
}
const Group* GetGroup() const
{
return (const Group*)m_group.getTarget();
}
GroupReference& GetGroupRef()
{
return m_group;
}
void SetGroup(Group* group, int8 subgroup = -1);
uint8 GetSubGroup() const
{
return m_group.getSubGroup();
}
uint32 GetGroupUpdateFlag()
{
return m_groupUpdateMask;
}
void SetGroupUpdateFlag(uint32 flag)
{
m_groupUpdateMask |= flag;
}
uint64 GetAuraUpdateMask()
{
return m_auraUpdateMask;
}
void SetAuraUpdateMask(uint8 slot)
{
m_auraUpdateMask |= (uint64(1) << slot);
}
void UnsetAuraUpdateMask(uint8 slot)
{
m_auraUpdateMask &= ~(uint64(1) << slot);
}
Player* GetNextRandomRaidMember(float radius);
PartyResult CanUninviteFromGroup() const;
// Battleground Group System
void SetBattlegroundRaid(Group* group, int8 subgroup = -1);
void RemoveFromBattlegroundRaid();
Group* GetOriginalGroup()
{
return m_originalGroup.getTarget();
}
GroupReference& GetOriginalGroupRef()
{
return m_originalGroup;
}
uint8 GetOriginalSubGroup() const
{
return m_originalGroup.getSubGroup();
}
void SetOriginalGroup(Group* group, int8 subgroup = -1);
void SetPassOnGroupLoot(bool bPassOnGroupLoot) { _passOnGroupLoot = bPassOnGroupLoot; }
bool GetPassOnGroupLoot() const { return _passOnGroupLoot; }
MapReference& GetMapRef()
{
return m_mapRef;
}
// Set map to player and add reference
void SetMap(Map* map) override;
void ResetMap() override;
bool isAllowedToLoot(const Creature* creature);
DeclinedName const* GetDeclinedNames() const
{
return m_declinedname;
}
bool HasTitle(uint32 bitIndex);
bool HasTitle(CharTitlesEntry const* title)
{
return HasTitle(title->bit_index);
}
void SetTitle(CharTitlesEntry const* title, bool lost = false);
bool IsLoading() const;
RAFLinkStatus GetRAFStatus() const
{
return m_rafLink;
}
void SetRAFStatus(RAFLinkStatus status)
{
m_rafLink = status;
}
bool SetFeatherFall(bool apply, bool packetOnly = false) override;
bool SetHover(bool apply, bool packetOnly = false) override;
bool SetCanFly(bool apply, bool packetOnly = false) override;
bool SetLevitate(bool apply, bool packetOnly = false) override;
bool SetWaterWalking(bool enable, bool packetOnly = false) override;
void ScheduleDelayedOperation(uint32 operation)
{
if (operation < DELAYED_END)
m_DelayedOperations |= operation;
}
protected:
uint32 m_contestedPvPTimer;
/*********************************************************/
/*** BATTLEGROUND SYSTEM ***/
/*********************************************************/
/*
this is an array of BG queues (BgTypeIDs) in which is player
*/
struct BgBattlegroundQueueID_Rec
{
uint32 bgQueueType;
uint32 invitedToInstance;
};
BgBattlegroundQueueID_Rec m_bgBattlegroundQueueID[PLAYER_MAX_BATTLEGROUND_QUEUES];
BGData m_bgData;
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
//We allow only one timed quest active at the same time. Below can then be simple value instead of set.
std::set<uint32> m_timedquests;
uint64 m_playerSharingQuest;
uint32 m_sharedQuestId;
uint32 m_ingametime;
/*********************************************************/
/*** LOAD SYSTEM ***/
/*********************************************************/
void _LoadActions(QueryResult_AutoPtr result);
void _LoadAuras(QueryResult_AutoPtr result, uint32 timediff);
void _LoadBoundInstances(QueryResult_AutoPtr result);
void _LoadInventory(QueryResult_AutoPtr result, uint32 timediff);
void _LoadMailInit(QueryResult_AutoPtr resultUnread, QueryResult_AutoPtr resultDelivery);
void _LoadMail();
void _LoadMailedItems(Mail* mail);
void _LoadQuestStatus(QueryResult_AutoPtr result);
void _LoadDailyQuestStatus(QueryResult_AutoPtr result);
void _LoadGroup(QueryResult_AutoPtr result);
void _LoadSkills(QueryResult_AutoPtr result);
void _LoadSpells(QueryResult_AutoPtr result);
void _LoadTutorials(QueryResult_AutoPtr result);
void _LoadFriendList(QueryResult_AutoPtr result);
bool _LoadHomeBind(QueryResult_AutoPtr result);
void _LoadDeclinedNames(QueryResult_AutoPtr result);
void _LoadArenaTeamInfo(QueryResult_AutoPtr result);
void _LoadBGData(QueryResult_AutoPtr result);
/*********************************************************/
/*** SAVE SYSTEM ***/
/*********************************************************/
void _SaveActions();
void _SaveAuras();
void _SaveInventory();
void _SaveMail();
void _SaveQuestStatus();
void _SaveDailyQuestStatus();
void _SaveSkills();
void _SaveSpells();
void _SaveTutorials();
void _SaveBGData();
void _SetCreateBits(UpdateMask* updateMask, Player* target) const override;
void _SetUpdateBits(UpdateMask* updateMask, Player* target) const override;
/*********************************************************/
/*** ENVIRONMENTAL SYSTEM ***/
/*********************************************************/
void HandleSobering();
void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen);
void StopMirrorTimer(MirrorTimerType Type);
bool HasMirrorTimerFlag(uint32 flag) const { return m_MirrorTimerFlags & flag; }
void HandleDrowning(uint32 time_diff);
int32 getMaxTimer(MirrorTimerType timer);
/*********************************************************/
/*** HONOR SYSTEM ***/
/*********************************************************/
time_t m_lastHonorUpdateTime;
void outDebugValues() const;
bool _removeSpell(uint16 spell_id);
uint64 m_lootGuid;
uint32 m_team;
uint32 m_nextSave;
time_t m_speakTime;
uint32 m_speakCount;
DungeonDifficulty m_dungeonDifficulty;
uint32 m_atLoginFlags;
Item* m_items[PLAYER_SLOTS_COUNT];
uint32 m_currentBuybackSlot;
std::vector<Item*> m_itemUpdateQueue;
bool m_itemUpdateQueueBlocked;
uint32 m_ExtraFlags;
uint64 m_curSelection;
uint64 m_comboTarget;
int8 m_comboPoints;
QuestStatusMap mQuestStatus;
SkillStatusMap mSkillStatus;
uint32 m_GuildIdInvited;
uint32 m_ArenaTeamIdInvited;
PlayerMails m_mail;
PlayerSpellMap m_spells;
SpellCooldowns m_spellCooldowns;
std::map<uint32, uint32> m_globalCooldowns; // whole start recovery category stored in one
ActionButtonList m_actionButtons;
float m_auraBaseMod[BASEMOD_END][MOD_END];
SpellModList m_spellMods[MAX_SPELLMOD];
int32 m_SpellModRemoveCount;
EnchantDurationList m_enchantDuration;
ItemDurationList m_itemDuration;
uint64 m_resurrectGUID;
uint32 m_resurrectMap;
float m_resurrectX, m_resurrectY, m_resurrectZ;
uint32 m_resurrectHealth, m_resurrectMana;
WorldSession* m_session;
typedef std::list<Channel*> JoinedChannelsList;
JoinedChannelsList m_channels;
int m_cinematic;
Player* pTrader;
bool acceptTrade;
uint64 tradeItems[TRADE_SLOT_COUNT];
uint32 tradeGold;
time_t m_nextThinkTime;
uint32 m_Tutorials[8];
bool m_TutorialsChanged;
bool m_DailyQuestChanged;
time_t m_lastDailyQuestTime;
uint32 m_regenTimer;
uint32 m_drunkTimer;
uint16 m_drunk;
uint32 m_weaponChangeTimer;
uint32 m_zoneUpdateId;
uint32 m_zoneUpdateTimer;
uint32 m_areaUpdateId;
uint32 m_deathTimer;
time_t m_deathExpireTime;
uint32 m_WeaponProficiency;
uint32 m_ArmorProficiency;
bool m_canParry;
bool m_canBlock;
uint8 m_swingErrorMsg;
float m_ammoDPS;
////////////////////Rest System/////////////////////
time_t _restTime;
uint32 inn_triggerId;
float m_rest_bonus;
uint32 _restFlagMask;
////////////////////Rest System/////////////////////
// Transports
Transport* m_transport;
uint32 m_resetTalentsCost;
time_t m_resetTalentsTime;
uint32 m_usedTalentCount;
// Social
PlayerSocial* m_social;
// Groups
GroupReference m_group;
GroupReference m_originalGroup;
Group* m_groupInvite;
uint32 m_groupUpdateMask;
uint64 m_auraUpdateMask;
bool _passOnGroupLoot;
// last used pet number (for BG's)
uint32 m_lastpetnumber;
// Player summoning
time_t m_summon_expire;
uint32 m_summon_mapid;
float m_summon_x;
float m_summon_y;
float m_summon_z;
DeclinedName* m_declinedname;
bool CanAlwaysSee(WorldObject const* obj) const override;
bool IsAlwaysDetectableFor(WorldObject const* seer) const override;
private:
// internal common parts for CanStore/StoreItem functions
uint8 _CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const;
uint8 _CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const;
uint8 _CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const;
Item* _StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update);
CinematicMgr* _cinematicMgr;
LiquidTypeEntry const* _lastLiquid;
int32 m_MirrorTimer[MAX_TIMERS];
uint8 m_MirrorTimerFlags;
uint8 m_MirrorTimerFlagsLast;
float m_GrantableLevels;
bool m_isInWater;
bool m_wasOutdoors;
ReputationMgr m_reputationMgr;
void SetCanDelayTeleport(bool setting)
{
m_bCanDelayTeleport = setting;
}
bool IsHasDelayedTeleport() const
{
// we should not execute delayed teleports for now dead players but has been alive at teleport
// because we don't want player's ghost teleported from graveyard
return m_bHasDelayedTeleport && (IsAlive() || !m_bHasBeenAliveAtDelayedTeleport);
}
bool SetDelayedTeleportFlagIfCan()
{
m_bHasDelayedTeleport = m_bCanDelayTeleport;
m_bHasBeenAliveAtDelayedTeleport = IsAlive();
return m_bHasDelayedTeleport;
}
bool IsInstanceLoginGameMasterException() const;
MapReference m_mapRef;
void UpdateCharmedAI();
UnitAI* i_AI;
uint32 m_timeSyncCounter;
uint32 m_timeSyncTimer;
uint32 m_timeSyncClient;
uint32 m_timeSyncServer;
// Current teleport data
WorldLocation m_teleport_dest;
uint32 m_teleport_options;
bool mSemaphoreTeleport_Near;
bool mSemaphoreTeleport_Far;
uint32 m_DelayedOperations;
bool m_bCanDelayTeleport;
bool m_bHasDelayedTeleport;
bool m_bHasBeenAliveAtDelayedTeleport;
RAFLinkStatus m_rafLink;
// Temporary removed pet cache
uint32 m_temporaryUnsummonedPetNumber;
uint32 m_oldpetspell;
// Status of your currently controlled pet
PetStatus m_petStatus;
uint32 _activeCheats;
};
void AddItemsSetItem(Player* player, Item* item);
void RemoveItemsSetItem(Player* player, ItemTemplate const* proto);
// "the bodies of template functions must be made available in a header file"
template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell const* spell)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return 0;
float totalpct = 1.0f;
int32 totalflat = 0;
for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
{
SpellModifier* mod = *itr;
if (!IsAffectedBySpellmod(spellInfo, mod, spell))
continue;
if (mod->type == SPELLMOD_FLAT)
totalflat += mod->value;
else if (mod->type == SPELLMOD_PCT)
{
// skip percent mods for null basevalue (most important for spell mods with charges)
if (basevalue == T(0))
continue;
// special case (skip >10sec spell casts for instant cast setting)
if (mod->op == SPELLMOD_CASTING_TIME && basevalue >= T(10 * IN_MILLISECONDS) && mod->value <= -100)
continue;
totalpct += CalculatePct(1.0f, (float)mod->value);
}
if (mod->charges > 0)
{
if (!(spellInfo->SpellFamilyName == 8 && spellInfo->SpellFamilyFlags & 0x200000000LL))
--mod->charges;
if (mod->charges == 0)
{
mod->charges = -1;
mod->lastAffected = spell;
if (!mod->lastAffected)
mod->lastAffected = FindCurrentSpellBySpellId(spellId);
++m_SpellModRemoveCount;
}
}
}
float diff = (float)basevalue * (totalpct - 1.0f) + (float)totalflat;
basevalue = T((float)basevalue + diff);
return T(diff);
}
#endif
| 412 | 0.962317 | 1 | 0.962317 | game-dev | MEDIA | 0.935818 | game-dev | 0.93155 | 1 | 0.93155 |
ShortTailLab/ph-open | 25,978 | Classes/PvESkill.cpp | //
// PvESkill.cpp
// HelloCpp
//
// Created by Zeyang Li on 5/20/13.
//
//
#include "PvESkill.h"
#include "EnemyControl.h"
#include "Board.h"
namespace PH
{
//---------------------------------------------
//------------- Damage Skills -----------------
//---------------------------------------------
static TaskPtr DamageCommon(BoardLayer* layer,
HeroControl* hc,
boost::function<float (EnemyControlPtr)> f,
bool isArea,
float& totalDamage)
{
TaskBatchPtr areaBatch = TaskBatch::make();
totalDamage = 0.0f;
EnemyControlList targets = layer->getEnemiesInAttackOrder(hc->getColor(),
isArea);
float delay = 0.0f;
for(EnemyControlPtr ec : targets)
{
float finalAttack = f(ec);
float finalDamage;
areaBatch << layer->calcDamageForTarget(finalAttack,
hc->getColor(),
ec,
finalDamage,
false,
delay + 0.5f);
totalDamage += finalDamage;
areaBatch << layer->createAttackSequence(hc,
ec,
finalDamage,
hc->getColor(),
delay);
float acDelay = -0.15f+delay+calOrbDelay(hc->center(), ec->center());
TaskPtr hit = layer->dealDamageToOneWithAnim(finalDamage, ec, acDelay);
areaBatch << TaskSequence::make(createDelay(layer, 0.5),
hit);
delay += 0.2f;
}
//layer->removeDeadEnemies();
return areaBatch;
}
static TaskPtr DamageCommon(BoardLayer* layer,
HeroControl* hc,
boost::function<float (EnemyControlPtr)> f,
bool isArea)
{
float totalDamage = 0.0f;
return DamageCommon(layer, hc, f, isArea, totalDamage);
}
TaskPtr PvEActive::DamageByValue(PH::BoardLayer *layer,
HeroControl* hc,
float damage,
bool isArea)
{
return DamageCommon(layer,
hc,
[damage](EnemyControlPtr ec){return damage;},
isArea);
}
TaskPtr PvEActive::DamageByFactorFromColor(BoardLayer* layer,
HeroControl* hc,
float factor,
GemUtils::GemColor color,
bool isArea)
{
TaskBatchPtr batch = TaskBatch::make();
// account for attack factors
float damage = 0.0f;
for(HeroControl* hhh : layer->mPlayer->team)
{
if(hhh->getColor() == color || color == GemUtils::AllColor)
{
float skillMod;
batch << layer->mPlayer->getAttackFactor(hc, skillMod, [](){return rand();});
damage += hhh->attack * (factor * skillMod);
}
}
return batch << DamageByValue(layer, hc, damage, isArea);
}
TaskPtr PvEActive::DamageByFactor(BoardLayer* layer, HeroControl* hc, float factor, bool isArea)
{
TaskBatchPtr batch = TaskBatch::make();
float skillMod;
batch << layer->mPlayer->getAttackFactor(hc, skillMod, [](){return rand();});
float damage = hc->attack * (factor * skillMod);
return batch << DamageByValue(layer, hc, damage, isArea);
}
TaskPtr PvEActive::Damage(PH::BoardLayer *layer,
PH::HeroControl *hc,
GemUtils::GemColor color,
float damage,
bool isArea,
bool ignoreArmor)
{
TaskBatchPtr areaBatch = TaskBatch::make();
EnemyControlList targets = layer->getEnemiesInAttackOrder(hc->getColor(),
isArea);
float delay = 0.0f;
for(EnemyControlPtr ec : targets)
{
float finalDamage = 0.f;
areaBatch << layer->calcDamageForTarget(damage,
color,
ec,
finalDamage,
ignoreArmor,
delay + 0.5f);
areaBatch << layer->createAttackSequence(hc,
ec,
finalDamage,
color,
delay);
float acDelay = -0.15f+delay+calOrbDelay(hc->center(), ec->center());
TaskPtr hit = layer->dealDamageToOneWithAnim(finalDamage, ec, -delay+acDelay);
areaBatch << TaskSequence::make(createDelay(layer, 0.5),
hit);
delay += 0.2f;
}
//layer->removeDeadEnemies();
return areaBatch;
}
TaskPtr PvEActive::DamageByFactorWithoutArmor(BoardLayer * layer,
HeroControl * hc,
GemUtils::GemColor color,
float factor,
bool isArea)
{
TaskBatchPtr areaBatch = TaskBatch::make();
EnemyControlList targets = layer->getEnemiesInAttackOrder(hc->getColor(),
isArea);
float delay = 0.0f;
float skillMod;
areaBatch << layer->mPlayer->getAttackFactor(hc, skillMod, [](){return rand();});
const float finalAttack = hc->attack * ( factor * skillMod );
for(EnemyControlPtr ec : targets)
{
float finalDamage = 0.f;
areaBatch << layer->calcDamageForTarget(finalAttack,
hc->getColor(),
ec,
finalDamage,
true,
delay + 0.5f);
areaBatch << layer->createAttackSequence(hc,
ec,
finalDamage,
color,
delay);
float acDelay = -0.15f+delay+calOrbDelay(hc->center(), ec->center());
TaskPtr hit = layer->dealDamageToOneWithAnim(finalDamage, ec, acDelay);
areaBatch << TaskSequence::make(createDelay(layer, 0.5),
hit);
delay += 0.2f;
}
return areaBatch;
}
// This skill does not account for hero color
TaskPtr PvEActive::DamageByEnemyHealthFactor(BoardLayer* layer,
HeroControl* hc,
float factor,
bool isArea)
{
TaskBatchPtr areaBatch = TaskBatch::make();
EnemyControlList targets = layer->getEnemiesInAttackOrder(hc->getColor(),
isArea);
float delay = 0.0f;
for(EnemyControlPtr ec : targets)
{
float finalDamage = ec->getHealth() * factor;
areaBatch << createFloatText(layer, finalDamage, ec->center(), hc->getColor(), delay+0.5f);
areaBatch << layer->createAttackSequence(hc,
ec,
finalDamage,
hc->getColor(),
delay);
float acDelay = -0.15f+delay+calOrbDelay(hc->center(), ec->center());
TaskPtr hit = layer->dealDamageToOneWithAnim(finalDamage, ec, acDelay);
areaBatch << TaskSequence::make(createDelay(layer, 0.5),
hit);
delay += 0.2f;
}
//layer->removeDeadEnemies();
return areaBatch;
}
TaskPtr PvEActive::DamageByPlayerHealthFactor(BoardLayer* layer,
HeroControl* hc,
float factor,
bool isArea)
{
float damage = factor * layer->mPlayer->getMaxHealth();
return DamageByValue(layer, hc, damage, isArea);
}
TaskPtr PvEActive::DamageBySelfDamageFactor(BoardLayer* layer,
HeroControl* hc,
float healthFactor,
float attackFactor,
bool isArea)
{
float hit = layer->mPlayer->getHealth() * healthFactor;
TaskPtr hitAnim = layer->mPlayer->hit(hit, layer);
TaskPtr attackAnim = DamageByValue(layer, hc, hit * attackFactor, isArea);
return TaskBatch::make() << hitAnim << attackAnim;
}
TaskPtr PvEActive::DamageFromHealthGem(BoardLayer* layer,
HeroControl* hc,
float factor,
bool isArea)
{
TaskSequencePtr seq = TaskSequence::make();
int healthCount = 0;
GemGrid & grid = layer->mBoardControl->getGrid();
for(int i=0; i<grid.size(); i++)
{
GemPtr gem = grid(i);
if(gem->color() == GemUtils::Health)
{
if (gem == NULL)
continue;
seq << TaskSound::make("sound/v/gem_sweep.mp3");
seq << gem->sweep(layer->mBoardControl.get());
healthCount++;
}
}
seq << DamageByFactor(layer, hc, healthCount*factor, isArea);
seq << layer->mBoardControl->fillBoard([=](){return layer->randGemWeighted();},
false);
return seq;
}
TaskPtr PvEActive::DamageByGems(PH::BoardLayer *layer,
PH::HeroControl *hc,
float factor,
GemUtils::GemColor gemColor,
GemUtils::GemColor attColor,
bool isArea)
{
auto batch = TaskBatch::make();
int count = 0;
GemGrid & grid = layer->mBoardControl->getGrid();
for(int i=0; i < grid.size(); i++)
{
GemPtr gem = grid(i);
if(gem->color() == gemColor)
{
if (gem == NULL)
continue;
auto seq = TaskSequence::make();
seq << TaskSound::make("sound/v/gem_sweep.mp3");
seq << gem->sweep(layer->mBoardControl.get());
batch << seq;
count++;
}
}
return TaskSequence::make()
<< batch
<< PvEActive::DamageByFactorWithoutArmor(layer,
hc,
attColor,
factor*count,
isArea)
<< layer->mBoardControl->fillBoard([=](){return layer->randGemWeighted();},
false);
}
TaskPtr PvEActive::DamageAndHealByFactor(BoardLayer * layer,
PH::HeroControl *hc,
float factor,
bool isArea)
{
TaskSequencePtr seq = TaskSequence::make();
float skillMod = 0;
seq << layer->mPlayer->getAttackFactor(hc, skillMod, [](){return rand();});
float damage = hc->attack * (factor * skillMod);
auto batch = TaskBatch::make();
float finalDamage = 0.f;
batch << DamageCommon(layer,
hc,
[damage](EnemyControlPtr ec){return damage;},
isArea,
finalDamage);
batch << ActiveSkill::HealByValue(layer, hc, layer->mPlayer, finalDamage);
return seq << batch;
}
//----------------------------------------------------
//--------------- Turn Based Skills ------------------
//----------------------------------------------------
static TaskPtr CastTurnBasedSkill(BoardLayer* layer,
HeroControl* hc,
boost::function<TaskPtr (EnemyControlPtr ec)> f,
bool isArea = true)
{
TaskBatchPtr batch = TaskBatch::make();
EnemyControlList targets = layer->getEnemiesInAttackOrder(hc->getColor(),
isArea);
for(EnemyControlPtr ec : targets)
{
TaskPtr anim = f(ec);
batch << anim;
}
//layer->removeDeadEnemies();
return batch;
}
static TaskPtr CastTurnBasedSkillByColor(BoardLayer * layer,
HeroControl * hc,
boost::function<TaskPtr (EnemyControlPtr ec)> f,
GemUtils::GemColor color = GemUtils::AllColor)
{
TaskBatchPtr batch = TaskBatch::make();
EnemyControlList targets = layer->getEnemiesByColor(color);
for( EnemyControlPtr ec : targets )
{
TaskPtr anim = f(ec);
batch << anim;
}
//layer->removeDeadEnemies();
return batch;
}
TaskPtr PvEActive::DamageByFactorAndEnemyHealth(PH::BoardLayer *layer,
PH::HeroControl *hc,
float factor, float healthRatio,
float damageFactor, bool isArea)
{
TaskSequencePtr seq = TaskSequence::make();
float skillMod = 0;
seq << layer->mPlayer->getAttackFactor(hc, skillMod, [](){return rand();});
float atk = hc->attack * ( factor * skillMod );
return CastTurnBasedSkill(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
TaskBatchPtr batch = TaskBatch::make();
float finalAttack = atk;
if(ec->healthRatio() < healthRatio)
{
finalAttack += (hc->attack * damageFactor);
}
float finalDamage = 0.f;
batch << layer->calcDamageForTarget(finalAttack,
hc->getColor(),
ec,
finalDamage,
false,
0.5f);
batch << layer->createAttackSequence(hc,
ec,
finalDamage,
hc->getColor(),
0.f);
batch << layer->dealDamageToOneWithAnim(finalDamage, ec, 0.5f);
return batch;
}, isArea);
}
//----------------------------------------------------
//--------------- Multiple Attacks -------------------
//----------------------------------------------------
TaskPtr PvEActive::MultipleAttacksByFactor(BoardLayer* layer,
HeroControl* hc,
int count,
float factor,
bool isArea)
{
TaskBatchPtr batch = TaskBatch::make();
for(int i=0; i<count; i++)
{
TaskSequencePtr seq = TaskSequence::make();
seq << createDelay(layer, 0.2f * i);
seq << DamageByFactor(layer, hc, factor, isArea);
batch << seq;
}
return batch;
}
TaskPtr PvEActive::LeechByFactor(BoardLayer *layer,
HeroControl* hc,
float attackFactor,
float leechFactor)
{
TaskBatchPtr batch = TaskBatch::make();
float skillMod;
batch << layer->mPlayer->getAttackFactor(hc, skillMod, [](){return rand();});
float damage = hc->attack * (attackFactor * skillMod);
float totalDamage = 0.0f;
batch << DamageCommon(layer,
hc,
[=](EnemyControlPtr ec){return damage;},
true,
totalDamage);
float healAmount = totalDamage * leechFactor;
batch << ActiveSkill::HealByValue(layer, hc, layer->mPlayer, healAmount);
return batch;
}
TaskPtr PvEActive::AmplifyDamageByFactor(PH::BoardLayer *layer,
PH::HeroControl *hc,
int duration, float factor, GemUtils::GemColor color,
bool isArea)
{
return CastTurnBasedSkill(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
FloatBuffPtr buff = FloatBuff::make(color, duration, "加深", factor);
return ec->buffGroup.attachBuff(EnemyControl::kGroup_PostTurn, "amplifyDamage", layer, buff);
}, isArea);
}
TaskPtr PvEActive::PoisonByValue(BoardLayer* layer, HeroControl* hc, int duration, float val)
{
return CastTurnBasedSkill(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
TaskSequencePtr seq = TaskSequence::make();
seq << createOrb(layer, hc->center(), ec->center());
FloatBuffPtr buff = FloatBuff::make(GemUtils::Dark, duration, "蛊毒", val);
seq << ec->buffGroup.attachBuff(EnemyControl::kGroup_PostTurn, "poison", layer, buff);
return seq;
});
}
TaskPtr PvEActive::PoisonByFactor(PH::BoardLayer *layer, PH::HeroControl *hc, int duration, float factor)
{
float val = hc->attack * factor;
return PoisonByValue(layer, hc, duration, val);
}
TaskPtr PvEActive::Blind(BoardLayer* layer, HeroControl* hc, int duration, bool toAll)
{
return CastTurnBasedSkill(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
TaskSequencePtr seq = TaskSequence::make();
seq << createOrb(layer, hc->center(), ec->center());
BuffPtr buff = IBuff::make(GemUtils::AllColor, duration, "致盲");
seq << ec->buffGroup.attachBuff(EnemyControl::kGroup_PreTurn, "blind", layer, buff);
return seq;
});
}
TaskPtr PvEActive::Silence(BoardLayer* layer, HeroControl* hc, int duration, bool toAll)
{
return CastTurnBasedSkill(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
TaskSequencePtr seq = TaskSequence::make();
seq << createOrb(layer, hc->center(), ec->center());
BuffPtr buff = IBuff::make(GemUtils::AllColor, duration, "封印");
seq << ec->buffGroup.attachBuff(EnemyControl::kGroup_PostTurn, "silence", layer, buff);
return seq;
}, toAll);
}
TaskPtr PvEActive::ReduceEnemyArmorByFactor(PH::BoardLayer *layer, PH::HeroControl *hc, int duration, float factor)
{
return CastTurnBasedSkill(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
TaskSequencePtr seq = TaskSequence::make();
seq << createOrb(layer, hc->center(), ec->center());
FloatBuffPtr buff = FloatBuff::make(GemUtils::AllColor, duration, "弱防", factor);
seq << ec->buffGroup.attachBuff(EnemyControl::kGroup_PostTurn, "armorFactor", layer, buff);
return seq;
});
}
TaskPtr PvEActive::WeakenEnemyAttackByFactor(PH::BoardLayer * layer,
PH::HeroControl * hc,
int duration,
float factor,
bool isArea)
{
// set property only to display a label,
return CastTurnBasedSkill(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
TaskSequencePtr seq = TaskSequence::make();
seq << createOrb(layer, hc->center(), ec->center(), 0.0f);
FloatBuffPtr buff = FloatBuff::make(GemUtils::AllColor, duration, "弱攻", factor);
seq << ec->buffGroup.attachBuff(EnemyControl::kGroup_PostTurn, "attackFactor", layer, buff);
return seq;
}, isArea);
}
TaskPtr PvEActive::ReduceAttackFactorByColor(PH::BoardLayer *layer,
PH::HeroControl *hc,
int duration, float factor,
GemUtils::GemColor color)
{
return CastTurnBasedSkillByColor(layer, hc,
[=](EnemyControlPtr ec) -> TaskPtr
{
auto seq = TaskSequence::make();
seq << createOrb(layer, hc->center(), ec->center(), 0.f);
auto buff = FloatBuff::make(GemUtils::AllColor, duration, "弱攻", factor);
seq << ec->buffGroup.attachBuff(EnemyControl::kGroup_PostTurn,
"attackFactor",
layer, buff);
return seq;
}, color);
}
TaskPtr PvEActive::ExtendEnemyWaitTurn(PH::BoardLayer* layer,
PH::HeroControl * hc,
int val,
GemUtils::GemColor color)
{
return CastTurnBasedSkillByColor(layer, hc, [=](EnemyControlPtr ec) -> TaskPtr
{
return TaskBatch::make()
<< ec->setReadyInTurnWithAnim(val+ec->getReadyInTurn());
}, color);
}
TaskPtr PvEActive::TransformAllGem(BoardLayer* layer)
{
auto fadeOutTask = TaskBatch::make();
auto & grid = layer->mBoardControl->getGrid();
float delay = 0.01f;
for(int i=0; i<grid.size(); i++)
{
GemPtr fromGem = grid(i);
auto seq = TaskSequence::make();
seq << createDelay(layer, delay);
seq << fromGem->sweep(layer->mBoardControl.get());
fadeOutTask << seq;
delay += 0.02;
}
return TaskSequence::make()
<< TaskSound::make("sound/v/evolve_success.mp3")
<< fadeOutTask
<< layer->mBoardControl->fillBoard([=](){return layer->randGemWeighted();},
false);
}
TaskPtr PvEActive::BloodForBlood(PH::BoardLayer *layer,
PH::HeroControl *hc,
float ratio,
float factor,
bool isArea)
{
TaskBatchPtr batch = TaskBatch::make();
// account for attack factors
float damage = 0.0f;
if (ratio <= 0.f)
damage = layer->mPlayer->getHealth() - 1;
else
damage = ratio * layer->mPlayer->getHealth();
batch << layer->mPlayer->hit(damage, layer);
batch << DamageByValue(layer, hc, damage*factor, isArea);
return batch;
}
TaskPtr PvEActive::EyeForEye(PH::BoardLayer *layer,
PH::HeroControl *hc,
float attacker, float defender,
bool isArea)
{
TaskBatchPtr batch = TaskBatch::make();
float val = layer->mPlayer->getHealth()*attacker;
if(attacker <= 0.f)
val = layer->mPlayer->getHealth()*attacker - 1;
batch << layer->mPlayer->hit(val, layer);
batch << DamageByEnemyHealthFactor(layer, hc, defender, isArea);
return batch;
}
}
| 412 | 0.959413 | 1 | 0.959413 | game-dev | MEDIA | 0.953956 | game-dev | 0.982738 | 1 | 0.982738 |
hogwarts-mp/mod | 118,201 | code/client/src/sdk/Runtime/CoreUObject/Private/UObject/GarbageCollection.cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*=============================================================================
UnObjGC.cpp: Unreal object garbage collection code.
=============================================================================*/
#include "UObject/GarbageCollection.h"
#include "HAL/ThreadSafeBool.h"
#include "Misc/TimeGuard.h"
#include "HAL/IConsoleManager.h"
#include "Misc/App.h"
#include "Misc/CoreDelegates.h"
#include "UObject/ScriptInterface.h"
#include "UObject/UObjectAllocator.h"
#include "UObject/UObjectBase.h"
#include "UObject/Object.h"
#include "UObject/Class.h"
#include "UObject/UObjectIterator.h"
#include "UObject/UnrealType.h"
#include "UObject/LinkerLoad.h"
#include "UObject/GCObject.h"
#include "UObject/GCScopeLock.h"
#include "HAL/ExceptionHandling.h"
#include "UObject/UObjectClusters.h"
#include "HAL/LowLevelMemTracker.h"
#include "UObject/GarbageCollectionVerification.h"
#include "UObject/Package.h"
#include "Async/ParallelFor.h"
#include "ProfilingDebugging/CsvProfiler.h"
#include "HAL/Runnable.h"
#include "HAL/RunnableThread.h"
#include "UObject/FieldPathProperty.h"
/*-----------------------------------------------------------------------------
Garbage collection.
-----------------------------------------------------------------------------*/
// FastReferenceCollector uses PERF_DETAILED_PER_CLASS_GC_STATS
#include "UObject/FastReferenceCollector.h"
DEFINE_LOG_CATEGORY(LogGarbage);
/** Object count during last mark phase */
FThreadSafeCounter GObjectCountDuringLastMarkPhase;
/** Whether incremental object purge is in progress */
bool GObjIncrementalPurgeIsInProgress = false;
/** Whether GC is currently routing BeginDestroy to objects */
bool GObjUnhashUnreachableIsInProgress = false;
/** Time the GC started, needs to be reset on return from being in the background on some OSs */
double GCStartTime = 0.;
/** Whether FinishDestroy has already been routed to all unreachable objects. */
static bool GObjFinishDestroyHasBeenRoutedToAllObjects = false;
/**
* Array that we'll fill with indices to objects that are still pending destruction after
* the first GC sweep (because they weren't ready to be destroyed yet.)
*/
static TArray<UObject *> GGCObjectsPendingDestruction;
/** Number of objects actually still pending destruction */
static int32 GGCObjectsPendingDestructionCount = 0;
/** Whether we need to purge objects or not. */
static bool GObjPurgeIsRequired = false;
/** Current object index for incremental purge. */
static int32 GObjCurrentPurgeObjectIndex = 0;
/** Current object index for incremental purge. */
static bool GObjCurrentPurgeObjectIndexNeedsReset = true;
/** Contains a list of objects that stayed marked as unreachable after the last reachability analysis */
static TArray<FUObjectItem*> GUnreachableObjects;
static FCriticalSection GUnreachableObjectsCritical;
static int32 GUnrechableObjectIndex = 0;
/** Helpful constant for determining how many token slots we need to store a pointer **/
static const uint32 GNumTokensPerPointer = sizeof(void*) / sizeof(uint32); //-V514
FThreadSafeBool GIsGarbageCollecting(false);
/**
* Call back into the async loading code to inform of the destruction of serialized objects
*/
void NotifyUnreachableObjects(const TArrayView<FUObjectItem*>& UnreachableObjects);
/** Locks all UObject hash tables when performing GC */
class FGCScopeLock
{
/** Previous value of the GetGarbageCollectingFlag() */
bool bPreviousGabageCollectingFlagValue;
public:
/**
* We're storing the value of GetGarbageCollectingFlag in the constructor, it's safe as only
* one thread is ever going to be setting it and calling this code - the game thread.
**/
FORCEINLINE FGCScopeLock()
: bPreviousGabageCollectingFlagValue(GIsGarbageCollecting)
{
LockUObjectHashTables();
GIsGarbageCollecting = true;
}
FORCEINLINE ~FGCScopeLock()
{
GIsGarbageCollecting = bPreviousGabageCollectingFlagValue;
UnlockUObjectHashTables();
}
};
FGCCSyncObject::FGCCSyncObject()
{
GCUnlockedEvent = FPlatformProcess::GetSynchEventFromPool(true);
}
FGCCSyncObject::~FGCCSyncObject()
{
FPlatformProcess::ReturnSynchEventToPool(GCUnlockedEvent);
GCUnlockedEvent = nullptr;
}
FGCCSyncObject* GGCSingleton;
void FGCCSyncObject::Create()
{
struct FSingletonOwner
{
FGCCSyncObject Singleton;
FSingletonOwner() { GGCSingleton = &Singleton; }
~FSingletonOwner() { GGCSingleton = nullptr; }
};
static const FSingletonOwner MagicStaticSingleton;
}
FGCCSyncObject& FGCCSyncObject::Get()
{
FGCCSyncObject* Singleton = GGCSingleton;
check(Singleton);
return *Singleton;
}
#define UE_LOG_FGCScopeGuard_LockAsync_Time 0
FGCScopeGuard::FGCScopeGuard()
{
#if UE_LOG_FGCScopeGuard_LockAsync_Time
const double StartTime = FPlatformTime::Seconds();
#endif
FGCCSyncObject::Get().LockAsync();
#if UE_LOG_FGCScopeGuard_LockAsync_Time
const double ElapsedTime = FPlatformTime::Seconds() - StartTime;
if (FPlatformProperties::RequiresCookedData() && ElapsedTime > 0.001)
{
// Note this is expected to take roughly the time it takes to collect garbage and verify GC assumptions, so up to 300ms in development
UE_LOG(LogGarbage, Warning, TEXT("%f ms for acquiring ASYNC lock"), ElapsedTime * 1000);
}
#endif
}
FGCScopeGuard::~FGCScopeGuard()
{
FGCCSyncObject::Get().UnlockAsync();
}
bool IsGarbageCollectionLocked()
{
return FGCCSyncObject::Get().IsAsyncLocked();
}
// Minimum number of objects to spawn a GC sub-task for
static int32 GMinDesiredObjectsPerSubTask = 128;
static FAutoConsoleVariableRef CVarMinDesiredObjectsPerSubTask(
TEXT("gc.MinDesiredObjectsPerSubTask"),
GMinDesiredObjectsPerSubTask,
TEXT("Minimum number of objects to spawn a GC sub-task for."),
ECVF_Default
);
static int32 GIncrementalBeginDestroyEnabled = 1;
static FAutoConsoleVariableRef CIncrementalBeginDestroyEnabled(
TEXT("gc.IncrementalBeginDestroyEnabled"),
GIncrementalBeginDestroyEnabled,
TEXT("If true, the engine will destroy objects incrementally using time limit each frame"),
ECVF_Default
);
int32 GMultithreadedDestructionEnabled = 0;
static FAutoConsoleVariableRef CMultithreadedDestructionEnabled(
TEXT("gc.MultithreadedDestructionEnabled"),
GMultithreadedDestructionEnabled,
TEXT("If true, the engine will free objects' memory from a worker thread"),
ECVF_Default
);
#if PERF_DETAILED_PER_CLASS_GC_STATS
/** Map from a UClass' FName to the number of objects that were purged during the last purge phase of this class. */
static TMap<const FName,uint32> GClassToPurgeCountMap;
/** Map from a UClass' FName to the number of "Disregard For GC" object references followed for all instances. */
static TMap<const FName,uint32> GClassToDisregardedObjectRefsMap;
/** Map from a UClass' FName to the number of regular object references followed for all instances. */
static TMap<const FName,uint32> GClassToRegularObjectRefsMap;
/** Map from a UClass' FName to the number of cycles spent with GC. */
static TMap<const FName,uint32> GClassToCyclesMap;
/** Number of disregarded object refs for current object. */
static uint32 GCurrentObjectDisregardedObjectRefs;
/** Number of regulard object refs for current object. */
static uint32 GCurrentObjectRegularObjectRefs;
/**
* Helper structure used for sorting class to count map.
*/
struct FClassCountInfo
{
FName ClassName;
uint32 InstanceCount;
};
/**
* Helper function to log the various class to count info maps.
*
* @param LogText Text to emit between number and class
* @param ClassToCountMap TMap from a class' FName to "count"
* @param NumItemsToList Number of items to log
* @param TotalCount Total count, if 0 will be calculated
*/
static void LogClassCountInfo( const TCHAR* LogText, TMap<const FName,uint32>& ClassToCountMap, int32 NumItemsToLog, uint32 TotalCount )
{
// Array of class name and counts.
TArray<FClassCountInfo> ClassCountArray;
ClassCountArray.Empty( ClassToCountMap.Num() );
// Figure out whether we need to calculate the total count.
bool bNeedToCalculateCount = false;
if( TotalCount == 0 )
{
bNeedToCalculateCount = true;
}
// Copy TMap to TArray for sorting purposes (and to calculate count if needed).
for( TMap<const FName,uint32>::TIterator It(ClassToCountMap); It; ++It )
{
FClassCountInfo ClassCountInfo;
ClassCountInfo.ClassName = It.Key();
ClassCountInfo.InstanceCount = It.Value();
ClassCountArray.Add( ClassCountInfo );
if( bNeedToCalculateCount )
{
TotalCount += ClassCountInfo.InstanceCount;
}
}
// Sort array by instance count.
struct FCompareFClassCountInfo
{
FORCEINLINE bool operator()( const FClassCountInfo& A, const FClassCountInfo& B ) const
{
return B.InstanceCount < A.InstanceCount;
}
};
ClassCountArray.Sort( FCompareFClassCountInfo() );
// Log top NumItemsToLog class counts
for( int32 Index=0; Index<FMath::Min(NumItemsToLog,ClassCountArray.Num()); Index++ )
{
const FClassCountInfo& ClassCountInfo = ClassCountArray[Index];
const float Percent = 100.f * ClassCountInfo.InstanceCount / TotalCount;
const FString PercentString = (TotalCount > 0) ? FString::Printf(TEXT("%6.2f%%"), Percent) : FString(TEXT(" N/A "));
UE_LOG(LogGarbage, Log, TEXT("%5d [%s] %s Class %s"), ClassCountInfo.InstanceCount, *PercentString, LogText, *ClassCountInfo.ClassName.ToString() );
}
// Empty the map for the next run.
ClassToCountMap.Empty();
};
#endif
/**
* Helper class for destroying UObjects on a worker thread
*/
class FAsyncPurge : public FRunnable
{
/** Thread to run the worker FRunnable on. Destroys objects. */
volatile FRunnableThread* Thread;
/** Id of the worker thread */
uint32 AsyncPurgeThreadId;
/** Stops this thread */
FThreadSafeCounter StopTaskCounter;
/** Event that triggers the UObject destruction */
FEvent* BeginPurgeEvent;
/** Event that signales the UObject destruction is finished */
FEvent* FinishedPurgeEvent;
/** Current index into the global unreachable objects array (GUnreachableObjects) of the object being destroyed */
int32 ObjCurrentPurgeObjectIndex;
/** Number of objects deferred to the game thread to destroy */
int32 NumObjectsToDestroyOnGameThread;
/** Number of objectsalready destroyed on the game thread */
int32 NumObjectsDestroyedOnGameThread;
/** Current index into the global unreachable objects array (GUnreachableObjects) of the object being destroyed on the game thread */
int32 ObjCurrentPurgeObjectIndexOnGameThread;
/** Number of unreachable objects the last time single-threaded tick was called */
int32 LastUnreachableObjectsCount;
/** Stats for the number of objects destroyed */
int32 ObjectsDestroyedSinceLastMarkPhase;
/** [PURGE/GAME THREAD] Destroys objects that are unreachable */
template <bool bMultithreaded> // Having this template argument lets the compiler strip unnecessary checks
bool TickDestroyObjects(bool bUseTimeLimit, float TimeLimit, double StartTime)
{
const int32 TimeLimitEnforcementGranularityForDeletion = 100;
int32 ProcessedObjectsCount = 0;
bool bFinishedDestroyingObjects = true;
while (ObjCurrentPurgeObjectIndex < GUnreachableObjects.Num())
{
FUObjectItem* ObjectItem = GUnreachableObjects[ObjCurrentPurgeObjectIndex];
check(ObjectItem->IsUnreachable());
UObject* Object = (UObject*)ObjectItem->Object;
check(Object->HasAllFlags(RF_FinishDestroyed | RF_BeginDestroyed));
if (!bMultithreaded || Object->IsDestructionThreadSafe())
{
// Can't lock once for the entire batch here as it could hold the lock for too long
GUObjectArray.LockInternalArray();
Object->~UObject();
GUObjectArray.UnlockInternalArray();
GUObjectAllocator.FreeUObject(Object);
GUnreachableObjects[ObjCurrentPurgeObjectIndex] = nullptr;
}
else
{
FPlatformMisc::MemoryBarrier();
++NumObjectsToDestroyOnGameThread;
}
++ProcessedObjectsCount;
++ObjectsDestroyedSinceLastMarkPhase;
++ObjCurrentPurgeObjectIndex;
// Time slicing when running on the game thread
if (!bMultithreaded && bUseTimeLimit && (ProcessedObjectsCount == TimeLimitEnforcementGranularityForDeletion) && (ObjCurrentPurgeObjectIndex < GUnreachableObjects.Num()))
{
ProcessedObjectsCount = 0;
if ((FPlatformTime::Seconds() - StartTime) > TimeLimit)
{
bFinishedDestroyingObjects = false;
break;
}
}
}
return bFinishedDestroyingObjects;
}
/** [GAME THREAD] Destroys objects that are unreachable and couldn't be destroyed on the worker thread */
bool TickDestroyGameThreadObjects(bool bUseTimeLimit, float TimeLimit, double StartTime)
{
const int32 TimeLimitEnforcementGranularityForDeletion = 100;
int32 ProcessedObjectsCount = 0;
bool bFinishedDestroyingObjects = true;
// Lock once for the entire batch
GUObjectArray.LockInternalArray();
// Cache the number of objects to destroy locally. The number may grow later but that's ok, we'll catch up to it in the next tick
const int32 LocalNumObjectsToDestroyOnGameThread = NumObjectsToDestroyOnGameThread;
while (NumObjectsDestroyedOnGameThread < LocalNumObjectsToDestroyOnGameThread && ObjCurrentPurgeObjectIndexOnGameThread < GUnreachableObjects.Num())
{
FUObjectItem* ObjectItem = GUnreachableObjects[ObjCurrentPurgeObjectIndexOnGameThread];
if (ObjectItem)
{
GUnreachableObjects[ObjCurrentPurgeObjectIndexOnGameThread] = nullptr;
UObject* Object = (UObject*)ObjectItem->Object;
Object->~UObject();
GUObjectAllocator.FreeUObject(Object);
++ProcessedObjectsCount;
++NumObjectsDestroyedOnGameThread;
if (bUseTimeLimit && (ProcessedObjectsCount == TimeLimitEnforcementGranularityForDeletion) && NumObjectsDestroyedOnGameThread < LocalNumObjectsToDestroyOnGameThread)
{
ProcessedObjectsCount = 0;
if ((FPlatformTime::Seconds() - StartTime) > TimeLimit)
{
bFinishedDestroyingObjects = false;
break;
}
}
}
++ObjCurrentPurgeObjectIndexOnGameThread;
}
GUObjectArray.UnlockInternalArray();
// Make sure that when we reach the end of GUnreachableObjects array, there's no objects to destroy left
check(!bFinishedDestroyingObjects || NumObjectsDestroyedOnGameThread == LocalNumObjectsToDestroyOnGameThread);
// Note that even though NumObjectsToDestroyOnGameThread may have been incremented by now or still hasn't but it will be
// after we report we're done with all objects, it doesn't matter since we don't care about the result of this function in MT mode
return bFinishedDestroyingObjects;
}
/** Waits for the worker thread to finish destroying objects */
void WaitForAsyncDestructionToFinish()
{
FinishedPurgeEvent->Wait();
}
public:
/**
* Constructor
* @param bMultithreaded if true, the destruction of objects will happen on a worker thread
*/
FAsyncPurge(bool bMultithreaded)
: Thread(nullptr)
, AsyncPurgeThreadId(0)
, BeginPurgeEvent(nullptr)
, FinishedPurgeEvent(nullptr)
, ObjCurrentPurgeObjectIndex(0)
, NumObjectsToDestroyOnGameThread(0)
, NumObjectsDestroyedOnGameThread(0)
, ObjCurrentPurgeObjectIndexOnGameThread(0)
, LastUnreachableObjectsCount(0)
, ObjectsDestroyedSinceLastMarkPhase(0)
{
BeginPurgeEvent = FPlatformProcess::GetSynchEventFromPool(true);
FinishedPurgeEvent = FPlatformProcess::GetSynchEventFromPool(true);
FinishedPurgeEvent->Trigger();
if (bMultithreaded)
{
check(FPlatformProcess::SupportsMultithreading());
FPlatformAtomics::InterlockedExchangePtr((void**)&Thread, FRunnableThread::Create(this, TEXT("FAsyncPurge"), 0, TPri_BelowNormal));
}
else
{
AsyncPurgeThreadId = GGameThreadId;
}
}
virtual ~FAsyncPurge()
{
check(IsFinished());
delete Thread;
Thread = nullptr;
FPlatformProcess::ReturnSynchEventToPool(BeginPurgeEvent);
FPlatformProcess::ReturnSynchEventToPool(FinishedPurgeEvent);
BeginPurgeEvent = nullptr;
FinishedPurgeEvent = nullptr;
}
/** Returns true if the destruction process is finished */
FORCEINLINE bool IsFinished() const
{
if (Thread)
{
return FinishedPurgeEvent->Wait(0, true) && NumObjectsToDestroyOnGameThread == NumObjectsDestroyedOnGameThread;
}
else
{
return (ObjCurrentPurgeObjectIndex >= LastUnreachableObjectsCount && NumObjectsToDestroyOnGameThread == NumObjectsDestroyedOnGameThread);
}
}
/** [MAIN THREAD] Adds objects to the purge queue */
void BeginPurge()
{
check(IsFinished()); // In single-threaded mode we need to be finished or the condition below will hang
if (FinishedPurgeEvent->Wait())
{
FinishedPurgeEvent->Reset();
ObjCurrentPurgeObjectIndex = 0;
ObjectsDestroyedSinceLastMarkPhase = 0;
NumObjectsToDestroyOnGameThread = 0;
NumObjectsDestroyedOnGameThread = 0;
ObjCurrentPurgeObjectIndexOnGameThread = 0;
BeginPurgeEvent->Trigger();
}
}
/** [GAME THREAD] Ticks the purge process on the game thread */
void TickPurge(bool bUseTimeLimit, float TimeLimit, double StartTime)
{
bool bCanStartDestroyingGameThreadObjects = true;
if (!Thread)
{
// If we're running single-threaded we need to tick the main loop here too
LastUnreachableObjectsCount = GUnreachableObjects.Num();
bCanStartDestroyingGameThreadObjects = TickDestroyObjects<false>(bUseTimeLimit, TimeLimit, StartTime);
}
if (bCanStartDestroyingGameThreadObjects)
{
do
{
// Deal with objects that couldn't be destroyed on the worker thread. This will do nothing when running single-threaded
bool bFinishedDestroyingObjectsOnGameThread = TickDestroyGameThreadObjects(bUseTimeLimit, TimeLimit, StartTime);
if (!Thread && bFinishedDestroyingObjectsOnGameThread)
{
// This only gets triggered here in single-threaded mode
FinishedPurgeEvent->Trigger();
}
} while (!bUseTimeLimit && !IsFinished());
}
}
/** Returns the number of objects already destroyed */
int32 GetObjectsDestroyedSinceLastMarkPhase() const
{
return ObjectsDestroyedSinceLastMarkPhase;
}
/** Resets the number of objects already destroyed */
void ResetObjectsDestroyedSinceLastMarkPhase()
{
ObjectsDestroyedSinceLastMarkPhase = 0;
}
/**
* Returns true if this function is called from the async destruction thread.
* It will also return true if we're running single-threaded and this function is called on the game thread
*/
bool IsInAsyncPurgeThread() const
{
return AsyncPurgeThreadId == FPlatformTLS::GetCurrentThreadId();
}
/* Returns true if it can run multi-threaded destruction */
bool IsMultithreaded() const
{
return !!Thread;
}
//~ Begin FRunnable Interface.
virtual bool Init()
{
return true;
}
virtual uint32 Run()
{
AsyncPurgeThreadId = FPlatformTLS::GetCurrentThreadId();
while (StopTaskCounter.GetValue() == 0)
{
if (BeginPurgeEvent->Wait(15, true))
{
BeginPurgeEvent->Reset();
TickDestroyObjects<true>(/* bUseTimeLimit = */ false, /* TimeLimit = */ 0.0f, /* StartTime = */ 0.0);
FinishedPurgeEvent->Trigger();
}
}
FinishedPurgeEvent->Trigger();
return 0;
}
virtual void Stop()
{
StopTaskCounter.Increment();
}
//~ End FRunnable Interface
void VerifyAllObjectsDestroyed()
{
for (FUObjectItem* ObjectItem : GUnreachableObjects)
{
UE_CLOG(ObjectItem, LogGarbage, Fatal, TEXT("Object 0x%016llx has not been destroyed during async purge"), (int64)(PTRINT)ObjectItem->Object);
}
}
};
static FAsyncPurge* GAsyncPurge = nullptr;
/**
* Returns true if this function is called from the async destruction thread.
* It will also return true if we're running single-threaded and this function is called on the game thread
*/
bool IsInGarbageCollectorThread()
{
return GAsyncPurge ? GAsyncPurge->IsInAsyncPurgeThread() : IsInGameThread();
}
/** Called on shutdown to free GC memory */
void ShutdownGarbageCollection()
{
FGCArrayPool::Get().Cleanup();
delete GAsyncPurge;
GAsyncPurge = nullptr;
}
/**
* Handles UObject references found by TFastReferenceCollector
*/
#if UE_WITH_GC
template <EFastReferenceCollectorOptions Options>
class FGCReferenceProcessor
{
public:
constexpr static FORCEINLINE bool IsParallel()
{
return !!(Options & EFastReferenceCollectorOptions::Parallel);
}
constexpr static FORCEINLINE bool IsWithClusters()
{
return !!(Options & EFastReferenceCollectorOptions::WithClusters);
}
FGCReferenceProcessor()
{
}
void SetCurrentObject(UObject* InObject)
{
}
FORCEINLINE int32 GetMinDesiredObjectsPerSubTask() const
{
return GMinDesiredObjectsPerSubTask;
}
void UpdateDetailedStats(UObject* CurrentObject, uint32 DeltaCycles)
{
#if PERF_DETAILED_PER_CLASS_GC_STATS
// Keep track of how many refs we encountered for the object's class.
const FName& ClassName = CurrentObject->GetClass()->GetFName();
// Refs to objects that reside in permanent object pool.
uint32 ClassDisregardedObjRefs = GClassToDisregardedObjectRefsMap.FindRef(ClassName);
GClassToDisregardedObjectRefsMap.Add(ClassName, ClassDisregardedObjRefs + GCurrentObjectDisregardedObjectRefs);
// Refs to regular objects.
uint32 ClassRegularObjRefs = GClassToRegularObjectRefsMap.FindRef(ClassName);
GClassToRegularObjectRefsMap.Add(ClassName, ClassRegularObjRefs + GCurrentObjectRegularObjectRefs);
// Track per class cycle count spent in GC.
uint32 ClassCycles = GClassToCyclesMap.FindRef(ClassName);
GClassToCyclesMap.Add(ClassName, ClassCycles + DeltaCycles);
// Reset current counts.
GCurrentObjectDisregardedObjectRefs = 0;
GCurrentObjectRegularObjectRefs = 0;
#endif
}
void LogDetailedStatsSummary()
{
#if PERF_DETAILED_PER_CLASS_GC_STATS
LogClassCountInfo(TEXT("references to regular objects from"), GClassToRegularObjectRefsMap, 20, 0);
LogClassCountInfo(TEXT("references to permanent objects from"), GClassToDisregardedObjectRefsMap, 20, 0);
LogClassCountInfo(TEXT("cycles for GC"), GClassToCyclesMap, 20, 0);
#endif
}
/** Marks all objects that can't be directly in a cluster but are referenced by it as reachable */
static FORCENOINLINE bool MarkClusterMutableObjectsAsReachable(FUObjectCluster& Cluster, TArray<UObject*>& ObjectsToSerialize)
{
check(IsWithClusters());
// This is going to be the return value and basically means that we ran across some pending kill objects
bool bAddClusterObjectsToSerialize = false;
for (int32& ReferencedMutableObjectIndex : Cluster.MutableObjects)
{
if (ReferencedMutableObjectIndex >= 0) // Pending kill support
{
FUObjectItem* ReferencedMutableObjectItem = GUObjectArray.IndexToObjectUnsafeForGC(ReferencedMutableObjectIndex);
if (IsParallel())
{
if (!ReferencedMutableObjectItem->IsPendingKill())
{
if (ReferencedMutableObjectItem->IsUnreachable())
{
if (ReferencedMutableObjectItem->ThisThreadAtomicallyClearedRFUnreachable())
{
// Needs doing because this is either a normal unclustered object (clustered objects are never unreachable) or a cluster root
ObjectsToSerialize.Add(static_cast<UObject*>(ReferencedMutableObjectItem->Object));
// So is this a cluster root maybe?
if (ReferencedMutableObjectItem->GetOwnerIndex() < 0)
{
MarkReferencedClustersAsReachable(ReferencedMutableObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
else if (ReferencedMutableObjectItem->GetOwnerIndex() > 0 && !ReferencedMutableObjectItem->HasAnyFlags(EInternalObjectFlags::ReachableInCluster))
{
// This is a clustered object that maybe hasn't been processed yet
if (ReferencedMutableObjectItem->ThisThreadAtomicallySetFlag(EInternalObjectFlags::ReachableInCluster))
{
// Needs doing, we need to get its cluster root and process it too
FUObjectItem* ReferencedMutableObjectsClusterRootItem = GUObjectArray.IndexToObjectUnsafeForGC(ReferencedMutableObjectItem->GetOwnerIndex());
if (ReferencedMutableObjectsClusterRootItem->IsUnreachable())
{
// The root is also maybe unreachable so process it and all the referenced clusters
if (ReferencedMutableObjectsClusterRootItem->ThisThreadAtomicallyClearedRFUnreachable())
{
MarkReferencedClustersAsReachable(ReferencedMutableObjectsClusterRootItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
}
}
else
{
// Pending kill support for clusters (multi-threaded case)
ReferencedMutableObjectIndex = -1;
bAddClusterObjectsToSerialize = true;
}
}
else if (!ReferencedMutableObjectItem->IsPendingKill())
{
if (ReferencedMutableObjectItem->IsUnreachable())
{
// Needs doing because this is either a normal unclustered object (clustered objects are never unreachable) or a cluster root
ReferencedMutableObjectItem->ClearFlags(EInternalObjectFlags::Unreachable);
ObjectsToSerialize.Add(static_cast<UObject*>(ReferencedMutableObjectItem->Object));
// So is this a cluster root?
if (ReferencedMutableObjectItem->GetOwnerIndex() < 0)
{
MarkReferencedClustersAsReachable(ReferencedMutableObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
else if (ReferencedMutableObjectItem->GetOwnerIndex() > 0 && !ReferencedMutableObjectItem->HasAnyFlags(EInternalObjectFlags::ReachableInCluster))
{
// This is a clustered object that hasn't been processed yet
ReferencedMutableObjectItem->SetFlags(EInternalObjectFlags::ReachableInCluster);
// If the root is also unreachable, process it and all its referenced clusters
FUObjectItem* ReferencedMutableObjectsClusterRootItem = GUObjectArray.IndexToObjectUnsafeForGC(ReferencedMutableObjectItem->GetOwnerIndex());
if (ReferencedMutableObjectsClusterRootItem->IsUnreachable())
{
ReferencedMutableObjectsClusterRootItem->ClearFlags(EInternalObjectFlags::Unreachable);
MarkReferencedClustersAsReachable(ReferencedMutableObjectsClusterRootItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
else
{
// Pending kill support for clusters (single-threaded case)
ReferencedMutableObjectIndex = -1;
bAddClusterObjectsToSerialize = true;
}
}
}
return bAddClusterObjectsToSerialize;
}
/** Marks all clusters referenced by another cluster as reachable */
static FORCENOINLINE void MarkReferencedClustersAsReachable(int32 ClusterIndex, TArray<UObject*>& ObjectsToSerialize)
{
check(IsWithClusters());
// If we run across some PendingKill objects we need to add all objects from this cluster
// to ObjectsToSerialize so that we can properly null out all the references.
// It also means this cluster will have to be dissolved because we may no longer guarantee all cross-cluster references are correct.
bool bAddClusterObjectsToSerialize = false;
FUObjectCluster& Cluster = GUObjectClusters[ClusterIndex];
// Also mark all referenced objects from outside of the cluster as reachable
for (int32& ReferncedClusterIndex : Cluster.ReferencedClusters)
{
if (ReferncedClusterIndex >= 0) // Pending Kill support
{
FUObjectItem* ReferencedClusterRootObjectItem = GUObjectArray.IndexToObjectUnsafeForGC(ReferncedClusterIndex);
if (!ReferencedClusterRootObjectItem->IsPendingKill())
{
// This condition should get collapsed by the compiler based on the template argument
if (IsParallel())
{
if (ReferencedClusterRootObjectItem->IsUnreachable())
{
ReferencedClusterRootObjectItem->ThisThreadAtomicallyClearedFlag( EInternalObjectFlags::Unreachable);
}
}
else
{
ReferencedClusterRootObjectItem->ClearFlags(EInternalObjectFlags::Unreachable);
}
}
else
{
// Pending kill support for clusters
ReferncedClusterIndex = -1;
bAddClusterObjectsToSerialize = true;
}
}
}
if (MarkClusterMutableObjectsAsReachable(Cluster, ObjectsToSerialize))
{
bAddClusterObjectsToSerialize = true;
}
if (bAddClusterObjectsToSerialize)
{
// We need to process all cluster objects to handle PendingKill objects we nulled out (-1) from the cluster.
for (int32 ClusterObjectIndex : Cluster.Objects)
{
FUObjectItem* ClusterObjectItem = GUObjectArray.IndexToObjectUnsafeForGC(ClusterObjectIndex);
UObject* ClusterObject = static_cast<UObject*>(ClusterObjectItem->Object);
ObjectsToSerialize.Add(ClusterObject);
}
Cluster.bNeedsDissolving = true;
GUObjectClusters.SetClustersNeedDissolving();
}
}
/**
* Handles object reference, potentially NULL'ing
*
* @param Object Object pointer passed by reference
* @param ReferencingObject UObject which owns the reference (can be NULL)
* @param bAllowReferenceElimination Whether to allow NULL'ing the reference if RF_PendingKill is set
*/
FORCEINLINE void HandleObjectReference(TArray<UObject*>& ObjectsToSerialize, const UObject * const ReferencingObject, UObject*& Object, const bool bAllowReferenceElimination)
{
// Disregard NULL objects and perform very fast check to see whether object is part of permanent
// object pool and should therefore be disregarded. The check doesn't touch the object and is
// cache friendly as it's just a pointer compare against to globals.
const bool IsInPermanentPool = GUObjectAllocator.ResidesInPermanentPool(Object);
#if PERF_DETAILED_PER_CLASS_GC_STATS
if (IsInPermanentPool)
{
GCurrentObjectDisregardedObjectRefs++;
}
#endif
if (Object == nullptr || IsInPermanentPool)
{
return;
}
const int32 ObjectIndex = GUObjectArray.ObjectToIndex(Object);
FUObjectItem* ObjectItem = GUObjectArray.IndexToObjectUnsafeForGC(ObjectIndex);
// Remove references to pending kill objects if we're allowed to do so.
if (ObjectItem->IsPendingKill() && bAllowReferenceElimination)
{
//checkSlow(ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot) == false);
checkSlow(ObjectItem->GetOwnerIndex() <= 0)
// Null out reference.
Object = NULL;
}
// Add encountered object reference to list of to be serialized objects if it hasn't already been added.
else if (ObjectItem->IsUnreachable())
{
if (IsParallel())
{
// Mark it as reachable.
if (ObjectItem->ThisThreadAtomicallyClearedRFUnreachable())
{
// Objects that are part of a GC cluster should never have the unreachable flag set!
checkSlow(ObjectItem->GetOwnerIndex() <= 0);
if (!IsWithClusters() || !ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot))
{
// Add it to the list of objects to serialize.
ObjectsToSerialize.Add(Object);
}
else
{
// This is a cluster root reference so mark all referenced clusters as reachable
MarkReferencedClustersAsReachable(ObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
else
{
#if ENABLE_GC_DEBUG_OUTPUT
// this message is to help track down culprits behind "Object in PIE world still referenced" errors
if (GIsEditor && !GIsPlayInEditorWorld && ReferencingObject != nullptr && !ReferencingObject->HasAnyFlags(RF_Transient) && Object->RootPackageHasAnyFlags(PKG_PlayInEditor))
{
UPackage* ReferencingPackage = ReferencingObject->GetOutermost();
if (!ReferencingPackage->HasAnyPackageFlags(PKG_PlayInEditor) && !ReferencingPackage->HasAnyFlags(RF_Transient))
{
UE_LOG(LogGarbage, Warning, TEXT("GC detected illegal reference to PIE object from content [possibly via [todo]]:"));
UE_LOG(LogGarbage, Warning, TEXT(" PIE object: %s"), *Object->GetFullName());
UE_LOG(LogGarbage, Warning, TEXT(" NON-PIE object: %s"), *ReferencingObject->GetFullName());
}
}
#endif
// Mark it as reachable.
ObjectItem->ClearUnreachable();
// Objects that are part of a GC cluster should never have the unreachable flag set!
checkSlow(ObjectItem->GetOwnerIndex() <= 0);
if (!IsWithClusters() || !ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot))
{
// Add it to the list of objects to serialize.
ObjectsToSerialize.Add(Object);
}
else
{
// This is a cluster root reference so mark all referenced clusters as reachable
MarkReferencedClustersAsReachable(ObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
else if (IsWithClusters() && (ObjectItem->GetOwnerIndex() > 0 && !ObjectItem->HasAnyFlags(EInternalObjectFlags::ReachableInCluster)))
{
bool bNeedsDoing = true;
if (IsParallel())
{
bNeedsDoing = ObjectItem->ThisThreadAtomicallySetFlag(EInternalObjectFlags::ReachableInCluster);
}
else
{
ObjectItem->SetFlags(EInternalObjectFlags::ReachableInCluster);
}
if (bNeedsDoing)
{
// Make sure cluster root object is reachable too
const int32 OwnerIndex = ObjectItem->GetOwnerIndex();
FUObjectItem* RootObjectItem = GUObjectArray.IndexToObjectUnsafeForGC(OwnerIndex);
checkSlow(RootObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot));
if (IsParallel())
{
if (RootObjectItem->ThisThreadAtomicallyClearedRFUnreachable())
{
// Make sure all referenced clusters are marked as reachable too
MarkReferencedClustersAsReachable(RootObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
else if (RootObjectItem->IsUnreachable())
{
RootObjectItem->ClearFlags(EInternalObjectFlags::Unreachable);
// Make sure all referenced clusters are marked as reachable too
MarkReferencedClustersAsReachable(RootObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
#if PERF_DETAILED_PER_CLASS_GC_STATS
GCurrentObjectRegularObjectRefs++;
#endif
}
/**
* Handles UObject reference from the token stream.
*
* @param ObjectsToSerialize An array of remaining objects to serialize.
* @param ReferencingObject Object referencing the object to process.
* @param Object Object being referenced.
* @param TokenIndex Index to the token stream where the reference was found.
* @param bAllowReferenceElimination True if reference elimination is allowed.
*/
FORCEINLINE void HandleTokenStreamObjectReference(TArray<UObject*>& ObjectsToSerialize, UObject* ReferencingObject, UObject*& Object, const int32 TokenIndex, bool bAllowReferenceElimination)
{
#if ENABLE_GC_OBJECT_CHECKS
if (Object)
{
if (
#if DO_POINTER_CHECKS_ON_GC
!IsPossiblyAllocatedUObjectPointer(Object) ||
#endif
!Object->IsValidLowLevelFast())
{
FString TokenDebugInfo;
if (UClass *Class = (ReferencingObject ? ReferencingObject->GetClass() : nullptr))
{
FTokenInfo TokenInfo = Class->ReferenceTokenStream.GetTokenInfo(TokenIndex);
TokenDebugInfo = FString::Printf(TEXT("ReferencingObjectClass: %s, Property Name: %s, Offset: %d"),
*Class->GetFullName(), *TokenInfo.Name.GetPlainNameString(), TokenInfo.Offset);
}
else
{
// This means this objects is most likely being referenced by AddReferencedObjects
TokenDebugInfo = TEXT("Native Reference");
}
UE_LOG(LogGarbage, Fatal, TEXT("Invalid object in GC: 0x%016llx, ReferencingObject: %s, %s, TokenIndex: %d"),
(int64)(PTRINT)Object,
ReferencingObject ? *ReferencingObject->GetFullName() : TEXT("NULL"),
*TokenDebugInfo, TokenIndex);
}
}
#endif // ENABLE_GC_OBJECT_CHECKS
HandleObjectReference(ObjectsToSerialize, ReferencingObject, Object, bAllowReferenceElimination);
}
};
template <EFastReferenceCollectorOptions Options>
FGCCollector<Options>::FGCCollector(FGCReferenceProcessor<Options>& InProcessor, FGCArrayStruct& InObjectArrayStruct)
: ReferenceProcessor(InProcessor)
, ObjectArrayStruct(InObjectArrayStruct)
, bAllowEliminatingReferences(true)
{
}
template <EFastReferenceCollectorOptions Options>
FORCEINLINE void FGCCollector<Options>::InternalHandleObjectReference(UObject*& Object, const UObject* ReferencingObject, const FProperty* ReferencingProperty)
{
#if ENABLE_GC_OBJECT_CHECKS
if (Object && !Object->IsValidLowLevelFast())
{
UE_LOG(LogGarbage, Fatal, TEXT("Invalid object in GC: 0x%016llx, ReferencingObject: %s, ReferencingProperty: %s"),
(int64)(PTRINT)Object,
ReferencingObject ? *ReferencingObject->GetFullName() : TEXT("NULL"),
ReferencingProperty ? *ReferencingProperty->GetFullName() : TEXT("NULL"));
}
#endif // ENABLE_GC_OBJECT_CHECKS
ReferenceProcessor.HandleObjectReference(ObjectArrayStruct.ObjectsToSerialize, const_cast<UObject*>(ReferencingObject), Object, bAllowEliminatingReferences);
}
template <EFastReferenceCollectorOptions Options>
void FGCCollector<Options>::HandleObjectReference(UObject*& Object, const UObject* ReferencingObject, const FProperty* ReferencingProperty)
{
InternalHandleObjectReference(Object, ReferencingObject, ReferencingProperty);
}
template <EFastReferenceCollectorOptions Options>
void FGCCollector<Options>::HandleObjectReferences(UObject** InObjects, const int32 ObjectNum, const UObject* InReferencingObject, const FProperty* InReferencingProperty)
{
for (int32 ObjectIndex = 0; ObjectIndex < ObjectNum; ++ObjectIndex)
{
UObject*& Object = InObjects[ObjectIndex];
InternalHandleObjectReference(Object, InReferencingObject, InReferencingProperty);
}
}
#endif // UE_WITH_GC
/*----------------------------------------------------------------------------
FReferenceFinder.
----------------------------------------------------------------------------*/
FReferenceFinder::FReferenceFinder(TArray<UObject*>& InObjectArray, UObject* InOuter, bool bInRequireDirectOuter, bool bInShouldIgnoreArchetype, bool bInSerializeRecursively, bool bInShouldIgnoreTransient)
: ObjectArray(InObjectArray)
, LimitOuter(InOuter)
, SerializedProperty(nullptr)
, bRequireDirectOuter(bInRequireDirectOuter)
, bShouldIgnoreArchetype(bInShouldIgnoreArchetype)
, bSerializeRecursively(false)
, bShouldIgnoreTransient(bInShouldIgnoreTransient)
{
bSerializeRecursively = bInSerializeRecursively && LimitOuter != NULL;
if (InOuter)
{
// If the outer is specified, try to set the SerializedProperty based on its linker.
auto OuterLinker = InOuter->GetLinker();
if (OuterLinker)
{
SerializedProperty = OuterLinker->GetSerializedProperty();
}
}
}
void FReferenceFinder::FindReferences(UObject* Object, UObject* InReferencingObject, FProperty* InReferencingProperty)
{
check(Object != NULL);
if (!Object->GetClass()->IsChildOf(UClass::StaticClass()))
{
FVerySlowReferenceCollectorArchiveScope CollectorScope(GetVerySlowReferenceCollectorArchive(), InReferencingObject, SerializedProperty);
Object->SerializeScriptProperties(CollectorScope.GetArchive());
}
Object->CallAddReferencedObjects(*this);
}
void FReferenceFinder::HandleObjectReference( UObject*& InObject, const UObject* InReferencingObject /*= NULL*/, const FProperty* InReferencingProperty /*= NULL*/ )
{
// Avoid duplicate entries.
if ( InObject != NULL )
{
if ( LimitOuter == NULL || (InObject->GetOuter() == LimitOuter || (!bRequireDirectOuter && InObject->IsIn(LimitOuter))) )
{
// Many places that use FReferenceFinder expect the object to not be const.
UObject* Object = const_cast<UObject*>(InObject);
// do not attempt to serialize objects that have already been
if ( ObjectArray.Contains( Object ) == false )
{
check( Object->IsValidLowLevel() );
ObjectArray.Add( Object );
}
// check this object for any potential object references
if ( bSerializeRecursively == true && !SerializedObjects.Find(Object) )
{
SerializedObjects.Add(Object);
FindReferences(Object, const_cast<UObject*>(InReferencingObject), const_cast<FProperty*>(InReferencingProperty));
}
}
}
}
/**
* Implementation of parallel realtime garbage collector using recursive subdivision
*
* The approach is to create an array of uint32 tokens for each class that describe object references. This is done for
* script exposed classes by traversing the properties and additionally via manual function calls to emit tokens for
* native only classes in the construction singleton IMPLEMENT_INTRINSIC_CLASS.
* A third alternative is a AddReferencedObjects callback per object which
* is used to deal with object references from types that aren't supported by the reflectable type system.
* interface doesn't make sense to implement for.
*/
#if UE_WITH_GC
class FRealtimeGC : public FGarbageCollectionTracer
{
typedef void(FRealtimeGC::*MarkObjectsFn)(TArray<UObject*>&, const EObjectFlags);
typedef void(FRealtimeGC::*ReachabilityAnalysisFn)(FGCArrayStruct*);
/** Pointers to functions used for Marking objects as unreachable */
MarkObjectsFn MarkObjectsFunctions[4];
/** Pointers to functions used for Reachability Analysis */
ReachabilityAnalysisFn ReachabilityAnalysisFunctions[4];
template <EFastReferenceCollectorOptions CollectorOptions>
void PerformReachabilityAnalysisOnObjectsInternal(FGCArrayStruct* ArrayStruct)
{
FGCReferenceProcessor<CollectorOptions> ReferenceProcessor;
// NOTE: we want to run with automatic token stream generation off as it should be already generated at this point,
// BUT we want to be ignoring Noop tokens as they're only pointing either at null references or at objects that never get GC'd (native classes)
TFastReferenceCollector<
FGCReferenceProcessor<CollectorOptions>,
FGCCollector<CollectorOptions>,
FGCArrayPool,
CollectorOptions
> ReferenceCollector(ReferenceProcessor, FGCArrayPool::Get());
ReferenceCollector.CollectReferences(*ArrayStruct);
}
/** Calculates GC function index based on current settings */
static FORCEINLINE int32 GetGCFunctionIndex(bool bParallel, bool bWithClusters)
{
return (int32(bParallel) | (int32(bWithClusters) << 1));
}
public:
/** Default constructor, initializing all members. */
FRealtimeGC()
{
MarkObjectsFunctions[GetGCFunctionIndex(false, false)] = &FRealtimeGC::MarkObjectsAsUnreachable<false, false>;
MarkObjectsFunctions[GetGCFunctionIndex(true, false)] = &FRealtimeGC::MarkObjectsAsUnreachable<true, false>;
MarkObjectsFunctions[GetGCFunctionIndex(false, true)] = &FRealtimeGC::MarkObjectsAsUnreachable<false, true>;
MarkObjectsFunctions[GetGCFunctionIndex(true, true)] = &FRealtimeGC::MarkObjectsAsUnreachable<true, true>;
ReachabilityAnalysisFunctions[GetGCFunctionIndex(false, false)] = &FRealtimeGC::PerformReachabilityAnalysisOnObjectsInternal<EFastReferenceCollectorOptions::None | EFastReferenceCollectorOptions::None>;
ReachabilityAnalysisFunctions[GetGCFunctionIndex(true, false)] = &FRealtimeGC::PerformReachabilityAnalysisOnObjectsInternal<EFastReferenceCollectorOptions::Parallel | EFastReferenceCollectorOptions::None>;
ReachabilityAnalysisFunctions[GetGCFunctionIndex(false, true)] = &FRealtimeGC::PerformReachabilityAnalysisOnObjectsInternal<EFastReferenceCollectorOptions::None | EFastReferenceCollectorOptions::WithClusters>;
ReachabilityAnalysisFunctions[GetGCFunctionIndex(true, true)] = &FRealtimeGC::PerformReachabilityAnalysisOnObjectsInternal<EFastReferenceCollectorOptions::Parallel | EFastReferenceCollectorOptions::WithClusters>;
}
/**
* Marks all objects that don't have KeepFlags and EInternalObjectFlags::GarbageCollectionKeepFlags as unreachable
* This function is a template to speed up the case where we don't need to assemble the token stream (saves about 6ms on PS4)
*/
template <bool bParallel, bool bWithClusters>
void MarkObjectsAsUnreachable(TArray<UObject*>& ObjectsToSerialize, const EObjectFlags KeepFlags)
{
const EInternalObjectFlags FastKeepFlags = EInternalObjectFlags::GarbageCollectionKeepFlags;
const int32 MaxNumberOfObjects = GUObjectArray.GetObjectArrayNum() - GUObjectArray.GetFirstGCIndex();
const int32 NumThreads = FMath::Max(1, FTaskGraphInterface::Get().GetNumWorkerThreads());
const int32 NumberOfObjectsPerThread = (MaxNumberOfObjects / NumThreads) + 1;
TLockFreePointerListFIFO<FUObjectItem, PLATFORM_CACHE_LINE_SIZE> ClustersToDissolveList;
TLockFreePointerListFIFO<FUObjectItem, PLATFORM_CACHE_LINE_SIZE> KeepClusterRefsList;
FGCArrayStruct** ObjectsToSerializeArrays = new FGCArrayStruct*[NumThreads];
for (int32 ThreadIndex = 0; ThreadIndex < NumThreads; ++ThreadIndex)
{
ObjectsToSerializeArrays[ThreadIndex] = FGCArrayPool::Get().GetArrayStructFromPool();
}
// Iterate over all objects. Note that we iterate over the UObjectArray and usually check only internal flags which
// are part of the array so we don't suffer from cache misses as much as we would if we were to check ObjectFlags.
ParallelFor(NumThreads, [ObjectsToSerializeArrays, &ClustersToDissolveList, &KeepClusterRefsList, FastKeepFlags, KeepFlags, NumberOfObjectsPerThread, NumThreads, MaxNumberOfObjects](int32 ThreadIndex)
{
int32 FirstObjectIndex = ThreadIndex * NumberOfObjectsPerThread + GUObjectArray.GetFirstGCIndex();
int32 NumObjects = (ThreadIndex < (NumThreads - 1)) ? NumberOfObjectsPerThread : (MaxNumberOfObjects - (NumThreads - 1) * NumberOfObjectsPerThread);
int32 LastObjectIndex = FMath::Min(GUObjectArray.GetObjectArrayNum() - 1, FirstObjectIndex + NumObjects - 1);
int32 ObjectCountDuringMarkPhase = 0;
TArray<UObject*>& LocalObjectsToSerialize = ObjectsToSerializeArrays[ThreadIndex]->ObjectsToSerialize;
for (int32 ObjectIndex = FirstObjectIndex; ObjectIndex <= LastObjectIndex; ++ObjectIndex)
{
FUObjectItem* ObjectItem = &GUObjectArray.GetObjectItemArrayUnsafe()[ObjectIndex];
if (ObjectItem->Object)
{
UObject* Object = (UObject*)ObjectItem->Object;
// We can't collect garbage during an async load operation and by now all unreachable objects should've been purged.
checkf(!ObjectItem->HasAnyFlags(EInternalObjectFlags::Unreachable|EInternalObjectFlags::PendingConstruction), TEXT("%s"), *Object->GetFullName());
// Keep track of how many objects are around.
ObjectCountDuringMarkPhase++;
if (bWithClusters)
{
ObjectItem->ClearFlags(EInternalObjectFlags::ReachableInCluster);
}
// Special case handling for objects that are part of the root set.
if (ObjectItem->IsRootSet())
{
// IsValidLowLevel is extremely slow in this loop so only do it in debug
checkSlow(Object->IsValidLowLevel());
// We cannot use RF_PendingKill on objects that are part of the root set.
#if DO_GUARD_SLOW
checkCode(if (ObjectItem->IsPendingKill()) { UE_LOG(LogGarbage, Fatal, TEXT("Object %s is part of root set though has been marked RF_PendingKill!"), *Object->GetFullName()); });
#endif
if (bWithClusters)
{
if (ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot) || ObjectItem->GetOwnerIndex() > 0)
{
KeepClusterRefsList.Push(ObjectItem);
}
}
LocalObjectsToSerialize.Add(Object);
}
// Regular objects or cluster root objects
else if (!bWithClusters || ObjectItem->GetOwnerIndex() <= 0)
{
bool bMarkAsUnreachable = true;
// Internal flags are super fast to check and is used by async loading and must have higher precedence than PendingKill
if (ObjectItem->HasAnyFlags(FastKeepFlags))
{
bMarkAsUnreachable = false;
}
// If KeepFlags is non zero this is going to be very slow due to cache misses
else if (!ObjectItem->IsPendingKill() && KeepFlags != RF_NoFlags && Object->HasAnyFlags(KeepFlags))
{
bMarkAsUnreachable = false;
}
else if (ObjectItem->IsPendingKill() && bWithClusters && ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot))
{
ClustersToDissolveList.Push(ObjectItem);
}
// Mark objects as unreachable unless they have any of the passed in KeepFlags set and it's not marked for elimination..
if (!bMarkAsUnreachable)
{
// IsValidLowLevel is extremely slow in this loop so only do it in debug
checkSlow(Object->IsValidLowLevel());
LocalObjectsToSerialize.Add(Object);
if (bWithClusters)
{
if (ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot))
{
KeepClusterRefsList.Push(ObjectItem);
}
}
}
else
{
ObjectItem->SetFlags(EInternalObjectFlags::Unreachable);
}
}
// Cluster objects
else if (bWithClusters && ObjectItem->GetOwnerIndex() > 0)
{
// treat cluster objects with FastKeepFlags the same way as if they are in the root set
if (ObjectItem->HasAnyFlags(FastKeepFlags))
{
KeepClusterRefsList.Push(ObjectItem);
LocalObjectsToSerialize.Add(Object);
}
}
}
}
GObjectCountDuringLastMarkPhase.Add(ObjectCountDuringMarkPhase);
}, !bParallel);
// Collect all objects to serialize from all threads and put them into a single array
{
int32 NumObjectsToSerialize = 0;
for (int32 ThreadIndex = 0; ThreadIndex < NumThreads; ++ThreadIndex)
{
NumObjectsToSerialize += ObjectsToSerializeArrays[ThreadIndex]->ObjectsToSerialize.Num();
}
ObjectsToSerialize.Reserve(NumObjectsToSerialize);
for (int32 ThreadIndex = 0; ThreadIndex < NumThreads; ++ThreadIndex)
{
ObjectsToSerialize.Append(ObjectsToSerializeArrays[ThreadIndex]->ObjectsToSerialize);
FGCArrayPool::Get().ReturnToPool(ObjectsToSerializeArrays[ThreadIndex]);
}
delete[] ObjectsToSerializeArrays;
}
if (bWithClusters)
{
TArray<FUObjectItem*> ClustersToDissolve;
ClustersToDissolveList.PopAll(ClustersToDissolve);
for (FUObjectItem* ObjectItem : ClustersToDissolve)
{
// Check if the object is still a cluster root - it's possible one of the previous
// DissolveClusterAndMarkObjectsAsUnreachable calls already dissolved its cluster
if (ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot))
{
GUObjectClusters.DissolveClusterAndMarkObjectsAsUnreachable(ObjectItem);
GUObjectClusters.SetClustersNeedDissolving();
}
}
}
if (bWithClusters)
{
TArray<FUObjectItem*> KeepClusterRefs;
KeepClusterRefsList.PopAll(KeepClusterRefs);
for (FUObjectItem* ObjectItem : KeepClusterRefs)
{
if (ObjectItem->GetOwnerIndex() > 0)
{
checkSlow(!ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot));
bool bNeedsDoing = !ObjectItem->HasAnyFlags(EInternalObjectFlags::ReachableInCluster);
if (bNeedsDoing)
{
ObjectItem->SetFlags(EInternalObjectFlags::ReachableInCluster);
// Make sure cluster root object is reachable too
const int32 OwnerIndex = ObjectItem->GetOwnerIndex();
FUObjectItem* RootObjectItem = GUObjectArray.IndexToObjectUnsafeForGC(OwnerIndex);
checkSlow(RootObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot));
// if it is reachable via keep flags we will do this below (or maybe already have)
if (RootObjectItem->IsUnreachable())
{
RootObjectItem->ClearFlags(EInternalObjectFlags::Unreachable);
// Make sure all referenced clusters are marked as reachable too
FGCReferenceProcessor<EFastReferenceCollectorOptions::WithClusters>::MarkReferencedClustersAsReachable(RootObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
else
{
checkSlow(ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot));
// this thing is definitely not marked unreachable, so don't test it here
// Make sure all referenced clusters are marked as reachable too
FGCReferenceProcessor<EFastReferenceCollectorOptions::WithClusters>::MarkReferencedClustersAsReachable(ObjectItem->GetClusterIndex(), ObjectsToSerialize);
}
}
}
}
/**
* Performs reachability analysis.
*
* @param KeepFlags Objects with these flags will be kept regardless of being referenced or not
*/
void PerformReachabilityAnalysis(EObjectFlags KeepFlags, bool bForceSingleThreaded, bool bWithClusters)
{
LLM_SCOPE(ELLMTag::GC);
SCOPED_NAMED_EVENT(FRealtimeGC_PerformReachabilityAnalysis, FColor::Red);
DECLARE_SCOPE_CYCLE_COUNTER(TEXT("FRealtimeGC::PerformReachabilityAnalysis"), STAT_FArchiveRealtimeGC_PerformReachabilityAnalysis, STATGROUP_GC);
/** Growing array of objects that require serialization */
FGCArrayStruct* ArrayStruct = FGCArrayPool::Get().GetArrayStructFromPool();
TArray<UObject*>& ObjectsToSerialize = ArrayStruct->ObjectsToSerialize;
// Reset object count.
GObjectCountDuringLastMarkPhase.Reset();
// Make sure GC referencer object is checked for references to other objects even if it resides in permanent object pool
if (FPlatformProperties::RequiresCookedData() && FGCObject::GGCObjectReferencer && GUObjectArray.IsDisregardForGC(FGCObject::GGCObjectReferencer))
{
ObjectsToSerialize.Add(FGCObject::GGCObjectReferencer);
}
{
const double StartTime = FPlatformTime::Seconds();
(this->*MarkObjectsFunctions[GetGCFunctionIndex(!bForceSingleThreaded, bWithClusters)])(ObjectsToSerialize, KeepFlags);
UE_LOG(LogGarbage, Verbose, TEXT("%f ms for MarkObjectsAsUnreachable Phase (%d Objects To Serialize)"), (FPlatformTime::Seconds() - StartTime) * 1000, ObjectsToSerialize.Num());
}
{
const double StartTime = FPlatformTime::Seconds();
PerformReachabilityAnalysisOnObjects(ArrayStruct, bForceSingleThreaded, bWithClusters);
UE_LOG(LogGarbage, Verbose, TEXT("%f ms for Reachability Analysis"), (FPlatformTime::Seconds() - StartTime) * 1000);
}
// Allowing external systems to add object roots. This can't be done through AddReferencedObjects
// because it may require tracing objects (via FGarbageCollectionTracer) multiple times
FCoreUObjectDelegates::TraceExternalRootsForReachabilityAnalysis.Broadcast(*this, KeepFlags, bForceSingleThreaded);
FGCArrayPool::Get().ReturnToPool(ArrayStruct);
#if UE_BUILD_DEBUG
FGCArrayPool::Get().CheckLeaks();
#endif
}
virtual void PerformReachabilityAnalysisOnObjects(FGCArrayStruct* ArrayStruct, bool bForceSingleThreaded, bool bWithClusters) override
{
(this->*ReachabilityAnalysisFunctions[GetGCFunctionIndex(!bForceSingleThreaded, bWithClusters)])(ArrayStruct);
}
};
#endif // UE_WITH_GC
// Allow parallel GC to be overridden to single threaded via console command.
static int32 GAllowParallelGC = 1;
static FAutoConsoleVariableRef CVarAllowParallelGC(
TEXT("gc.AllowParallelGC"),
GAllowParallelGC,
TEXT("Used to control parallel GC."),
ECVF_Default
);
/** Returns true if Garbage Collection should be forced to run on a single thread */
static bool ShouldForceSingleThreadedGC()
{
const bool bForceSingleThreadedGC = !FApp::ShouldUseThreadingForPerformance() || !FPlatformProcess::SupportsMultithreading() ||
#if PLATFORM_SUPPORTS_MULTITHREADED_GC
(FPlatformMisc::NumberOfCores() < 2 || GAllowParallelGC == 0 || PERF_DETAILED_PER_CLASS_GC_STATS);
#else //PLATFORM_SUPPORTS_MULTITHREADED_GC
true;
#endif //PLATFORM_SUPPORTS_MULTITHREADED_GC
return bForceSingleThreadedGC;
}
void AcquireGCLock()
{
const double StartTime = FPlatformTime::Seconds();
FGCCSyncObject::Get().GCLock();
const double ElapsedTime = FPlatformTime::Seconds() - StartTime;
if (FPlatformProperties::RequiresCookedData() && ElapsedTime > 0.001)
{
UE_LOG(LogGarbage, Warning, TEXT("%f ms for acquiring GC lock"), ElapsedTime * 1000);
}
}
void ReleaseGCLock()
{
FGCCSyncObject::Get().GCUnlock();
}
/** Locks GC within a scope but only if it hasn't been locked already */
struct FConditionalGCLock
{
bool bNeedsUnlock;
FConditionalGCLock()
: bNeedsUnlock(false)
{
if (!FGCCSyncObject::Get().IsGCLocked())
{
AcquireGCLock();
bNeedsUnlock = true;
}
}
~FConditionalGCLock()
{
if (bNeedsUnlock)
{
ReleaseGCLock();
}
}
};
static bool IncrementalDestroyGarbage(bool bUseTimeLimit, float TimeLimit);
/**
* Incrementally purge garbage by deleting all unreferenced objects after routing Destroy.
*
* Calling code needs to be EXTREMELY careful when and how to call this function as
* RF_Unreachable cannot change on any objects unless any pending purge has completed!
*
* @param bUseTimeLimit whether the time limit parameter should be used
* @param TimeLimit soft time limit for this function call
*/
void IncrementalPurgeGarbage(bool bUseTimeLimit, float TimeLimit)
{
#if !UE_WITH_GC
return;
#else
SCOPED_NAMED_EVENT(IncrementalPurgeGarbage, FColor::Red);
DECLARE_SCOPE_CYCLE_COUNTER(TEXT("IncrementalPurgeGarbage"), STAT_IncrementalPurgeGarbage, STATGROUP_GC);
CSV_SCOPED_TIMING_STAT_EXCLUSIVE(GarbageCollection);
if (GExitPurge)
{
GObjPurgeIsRequired = true;
GUObjectArray.DisableDisregardForGC();
GObjCurrentPurgeObjectIndexNeedsReset = true;
}
// Early out if there is nothing to do.
if (!GObjPurgeIsRequired)
{
return;
}
bool bCompleted = false;
struct FResetPurgeProgress
{
bool& bCompletedRef;
FResetPurgeProgress(bool& bInCompletedRef)
: bCompletedRef(bInCompletedRef)
{
// Incremental purge is now in progress.
GObjIncrementalPurgeIsInProgress = true;
FPlatformMisc::MemoryBarrier();
}
~FResetPurgeProgress()
{
if (bCompletedRef)
{
GObjIncrementalPurgeIsInProgress = false;
FPlatformMisc::MemoryBarrier();
}
}
} ResetPurgeProgress(bCompleted);
{
// Lock before settting GCStartTime as it could be slow to lock if async loading is in progress
// but we still want to perform some GC work otherwise we'd be keeping objects in memory for a long time
FConditionalGCLock ScopedGCLock;
// Keep track of start time to enforce time limit unless bForceFullPurge is true;
GCStartTime = FPlatformTime::Seconds();
bool bTimeLimitReached = false;
if (GUnrechableObjectIndex < GUnreachableObjects.Num())
{
bTimeLimitReached = UnhashUnreachableObjects(bUseTimeLimit, TimeLimit);
if (GUnrechableObjectIndex >= GUnreachableObjects.Num())
{
FScopedCBDProfile::DumpProfile();
}
}
if (!bTimeLimitReached)
{
bCompleted = IncrementalDestroyGarbage(bUseTimeLimit, TimeLimit);
}
}
#endif // !UE_WITH_GC
}
#if UE_WITH_GC
bool IncrementalDestroyGarbage(bool bUseTimeLimit, float TimeLimit)
{
const bool bMultithreadedPurge = !ShouldForceSingleThreadedGC() && GMultithreadedDestructionEnabled;
if (!GAsyncPurge)
{
GAsyncPurge = new FAsyncPurge(bMultithreadedPurge);
}
else if (GAsyncPurge->IsMultithreaded() != bMultithreadedPurge)
{
check(GAsyncPurge->IsFinished());
delete GAsyncPurge;
GAsyncPurge = new FAsyncPurge(bMultithreadedPurge);
}
bool bCompleted = false;
bool bTimeLimitReached = false;
// Keep track of time it took to destroy objects for stats
double IncrementalDestroyGarbageStartTime = FPlatformTime::Seconds();
// Depending on platform FPlatformTime::Seconds might take a noticeable amount of time if called thousands of times so we avoid
// enforcing the time limit too often, especially as neither Destroy nor actual deletion should take significant
// amounts of time.
const int32 TimeLimitEnforcementGranularityForDestroy = 10;
const int32 TimeLimitEnforcementGranularityForDeletion = 100;
// Set 'I'm garbage collecting' flag - might be checked inside UObject::Destroy etc.
FGCScopeLock GCLock;
if( !GObjFinishDestroyHasBeenRoutedToAllObjects && !bTimeLimitReached )
{
check(GUnrechableObjectIndex >= GUnreachableObjects.Num());
// Try to dispatch all FinishDestroy messages to unreachable objects. We'll iterate over every
// single object and destroy any that are ready to be destroyed. The objects that aren't yet
// ready will be added to a list to be processed afterwards.
int32 TimeLimitTimePollCounter = 0;
int32 FinishDestroyTimePollCounter = 0;
if (GObjCurrentPurgeObjectIndexNeedsReset)
{
GObjCurrentPurgeObjectIndex = 0;
GObjCurrentPurgeObjectIndexNeedsReset = false;
}
while (GObjCurrentPurgeObjectIndex < GUnreachableObjects.Num())
{
FUObjectItem* ObjectItem = GUnreachableObjects[GObjCurrentPurgeObjectIndex];
checkSlow(ObjectItem);
//@todo UE4 - A prefetch was removed here. Re-add it. It wasn't right anyway, since it was ten items ahead and the consoles on have 8 prefetch slots
check(ObjectItem->IsUnreachable());
{
UObject* Object = static_cast<UObject*>(ObjectItem->Object);
// Object should always have had BeginDestroy called on it and never already be destroyed
check( Object->HasAnyFlags( RF_BeginDestroyed ) && !Object->HasAnyFlags( RF_FinishDestroyed ) );
// Only proceed with destroying the object if the asynchronous cleanup started by BeginDestroy has finished.
if(Object->IsReadyForFinishDestroy())
{
#if PERF_DETAILED_PER_CLASS_GC_STATS
// Keep track of how many objects of a certain class we're purging.
const FName& ClassName = Object->GetClass()->GetFName();
int32 InstanceCount = GClassToPurgeCountMap.FindRef( ClassName );
GClassToPurgeCountMap.Add( ClassName, ++InstanceCount );
#endif
// Send FinishDestroy message.
Object->ConditionalFinishDestroy();
}
else
{
// The object isn't ready for FinishDestroy to be called yet. This is common in the
// case of a graphics resource that is waiting for the render thread "release fence"
// to complete. Just calling IsReadyForFinishDestroy may begin the process of releasing
// a resource, so we don't want to block iteration while waiting on the render thread.
// Add the object index to our list of objects to revisit after we process everything else
GGCObjectsPendingDestruction.Add(Object);
GGCObjectsPendingDestructionCount++;
}
}
// We've processed the object so increment our global iterator. It's important to do this before
// we test for the time limit so that we don't process the same object again next tick!
++GObjCurrentPurgeObjectIndex;
// Only check time limit every so often to avoid calling FPlatformTime::Seconds too often.
const bool bPollTimeLimit = ((TimeLimitTimePollCounter++) % TimeLimitEnforcementGranularityForDestroy == 0);
if( bUseTimeLimit && bPollTimeLimit && ((FPlatformTime::Seconds() - GCStartTime) > TimeLimit) )
{
bTimeLimitReached = true;
break;
}
}
// Have we finished the first round of attempting to call FinishDestroy on unreachable objects?
if (GObjCurrentPurgeObjectIndex >= GUnreachableObjects.Num())
{
double MaxTimeForFinishDestroy = 10.00;
bool bFinishDestroyTimeExtended = false;
FString FirstObjectNotReadyWhenTimeExtended;
int32 StartObjectsPendingDestructionCount = GGCObjectsPendingDestructionCount;
// We've finished iterating over all unreachable objects, but we need still need to handle
// objects that were deferred.
int32 LastLoopObjectsPendingDestructionCount = GGCObjectsPendingDestructionCount;
while( GGCObjectsPendingDestructionCount > 0 )
{
int32 CurPendingObjIndex = 0;
while( CurPendingObjIndex < GGCObjectsPendingDestructionCount )
{
// Grab the actual object for the current pending object list iteration
UObject* Object = GGCObjectsPendingDestruction[ CurPendingObjIndex ];
// Object should never have been added to the list if it failed this criteria
check( Object != NULL && Object->IsUnreachable() );
// Object should always have had BeginDestroy called on it and never already be destroyed
check( Object->HasAnyFlags( RF_BeginDestroyed ) && !Object->HasAnyFlags( RF_FinishDestroyed ) );
// Only proceed with destroying the object if the asynchronous cleanup started by BeginDestroy has finished.
if( Object->IsReadyForFinishDestroy() )
{
#if PERF_DETAILED_PER_CLASS_GC_STATS
// Keep track of how many objects of a certain class we're purging.
const FName& ClassName = Object->GetClass()->GetFName();
int32 InstanceCount = GClassToPurgeCountMap.FindRef( ClassName );
GClassToPurgeCountMap.Add( ClassName, ++InstanceCount );
#endif
// Send FinishDestroy message.
Object->ConditionalFinishDestroy();
// Remove the object index from our list quickly (by swapping with the last object index).
// NOTE: This is much faster than calling TArray.RemoveSwap and avoids shrinking allocations
{
// Swap the last index into the current index
GGCObjectsPendingDestruction[ CurPendingObjIndex ] = GGCObjectsPendingDestruction[ GGCObjectsPendingDestructionCount - 1 ];
// Decrement the object count
GGCObjectsPendingDestructionCount--;
}
}
else
{
// We'll revisit this object the next time around. Move on to the next.
CurPendingObjIndex++;
}
// Only check time limit every so often to avoid calling FPlatformTime::Seconds too often.
const bool bPollTimeLimit = ((TimeLimitTimePollCounter++) % TimeLimitEnforcementGranularityForDestroy == 0);
if( bUseTimeLimit && bPollTimeLimit && ((FPlatformTime::Seconds() - GCStartTime) > TimeLimit) )
{
bTimeLimitReached = true;
break;
}
}
if( bUseTimeLimit )
{
// A time limit is set and we've completed a full iteration over all leftover objects, so
// go ahead and bail out even if we have more time left or objects left to process. It's
// likely in this case that we're waiting for the render thread.
break;
}
else if( GGCObjectsPendingDestructionCount > 0 )
{
if (FPlatformProperties::RequiresCookedData())
{
const bool bPollTimeLimit = ((FinishDestroyTimePollCounter++) % TimeLimitEnforcementGranularityForDestroy == 0);
#if PLATFORM_IOS || PLATFORM_ANDROID
if(bPollTimeLimit && !bFinishDestroyTimeExtended && (FPlatformTime::Seconds() - GCStartTime) > MaxTimeForFinishDestroy )
{
MaxTimeForFinishDestroy = 30.0;
bFinishDestroyTimeExtended = true;
#if USE_HITCH_DETECTION
GHitchDetected = true;
#endif
FirstObjectNotReadyWhenTimeExtended = GetFullNameSafe(GGCObjectsPendingDestruction[0]);
}
else
#endif
// Check if we spent too much time on waiting for FinishDestroy without making any progress
if (LastLoopObjectsPendingDestructionCount == GGCObjectsPendingDestructionCount && bPollTimeLimit &&
((FPlatformTime::Seconds() - GCStartTime) > MaxTimeForFinishDestroy))
{
UE_LOG(LogGarbage, Warning, TEXT("Spent more than %.2fs on routing FinishDestroy to objects (objects in queue: %d)"), MaxTimeForFinishDestroy, GGCObjectsPendingDestructionCount);
UObject* LastObjectNotReadyForFinishDestroy = nullptr;
for (int32 ObjectIndex = 0; ObjectIndex < GGCObjectsPendingDestructionCount; ++ObjectIndex)
{
UObject* Obj = GGCObjectsPendingDestruction[ObjectIndex];
bool bReady = Obj->IsReadyForFinishDestroy();
UE_LOG(LogGarbage, Warning, TEXT(" [%d]: %s, IsReadyForFinishDestroy: %s"),
ObjectIndex,
*GetFullNameSafe(Obj),
bReady ? TEXT("true") : TEXT("false"));
if (!bReady)
{
LastObjectNotReadyForFinishDestroy = Obj;
}
}
#if PLATFORM_DESKTOP
ensureMsgf(0, TEXT("Spent to much time waiting for FinishDestroy for %d object(s) (last object: %s), check log for details"),
GGCObjectsPendingDestructionCount,
*GetFullNameSafe(LastObjectNotReadyForFinishDestroy));
#else
//for non-desktop platforms, make this a warning so that we can die inside of an object member call.
//this will give us a greater chance of getting useful memory inside of the platform minidump.
UE_LOG(LogGarbage, Warning, TEXT("Spent to much time waiting for FinishDestroy for %d object(s) (last object: %s), check log for details"),
GGCObjectsPendingDestructionCount,
*GetFullNameSafe(LastObjectNotReadyForFinishDestroy));
if (LastObjectNotReadyForFinishDestroy)
{
LastObjectNotReadyForFinishDestroy->AbortInsideMemberFunction();
}
else
{
//go through the standard fatal error path if LastObjectNotReadyForFinishDestroy is null.
//this could happen in the current code flow, in the odd case where an object finished readying just in time for the loop above.
UE_LOG(LogGarbage, Fatal, TEXT("LastObjectNotReadyForFinishDestroy is NULL."));
}
#endif
}
}
// Sleep before the next pass to give the render thread some time to release fences.
FPlatformProcess::Sleep( 0 );
}
LastLoopObjectsPendingDestructionCount = GGCObjectsPendingDestructionCount;
}
// Have all objects been destroyed now?
if( GGCObjectsPendingDestructionCount == 0 )
{
if (bFinishDestroyTimeExtended)
{
FString Msg = FString::Printf(TEXT("Additional time was required to finish routing FinishDestroy, spent %.2fs on routing FinishDestroy to %d objects. 1st obj not ready: '%s'."), (FPlatformTime::Seconds() - GCStartTime), StartObjectsPendingDestructionCount, *FirstObjectNotReadyWhenTimeExtended);
UE_LOG(LogGarbage, Warning, TEXT("%s"), *Msg );
FCoreDelegates::OnGCFinishDestroyTimeExtended.Broadcast(Msg);
}
// Release memory we used for objects pending destruction, leaving some slack space
GGCObjectsPendingDestruction.Empty( 256 );
// Destroy has been routed to all objects so it's safe to delete objects now.
GObjFinishDestroyHasBeenRoutedToAllObjects = true;
GObjCurrentPurgeObjectIndexNeedsReset = true;
}
}
}
if (GObjFinishDestroyHasBeenRoutedToAllObjects && !bTimeLimitReached)
{
// Perform actual object deletion.
int32 ProcessCount = 0;
if (GObjCurrentPurgeObjectIndexNeedsReset)
{
GAsyncPurge->BeginPurge();
// Reset the reset flag but don't reset the actual index yet for stat purposes
GObjCurrentPurgeObjectIndexNeedsReset = false;
}
GAsyncPurge->TickPurge(bUseTimeLimit, TimeLimit, GCStartTime);
if (GAsyncPurge->IsFinished())
{
#if UE_BUILD_DEBUG
GAsyncPurge->VerifyAllObjectsDestroyed();
#endif
bCompleted = true;
// Incremental purge is finished, time to reset variables.
GObjFinishDestroyHasBeenRoutedToAllObjects = false;
GObjPurgeIsRequired = false;
GObjCurrentPurgeObjectIndexNeedsReset = true;
// Log status information.
const int32 PurgedObjectCountSinceLastMarkPhase = GAsyncPurge->GetObjectsDestroyedSinceLastMarkPhase();
UE_LOG(LogGarbage, Log, TEXT("GC purged %i objects (%i -> %i) in %.3fms"), PurgedObjectCountSinceLastMarkPhase,
GObjectCountDuringLastMarkPhase.GetValue(),
GObjectCountDuringLastMarkPhase.GetValue() - PurgedObjectCountSinceLastMarkPhase,
(FPlatformTime::Seconds() - IncrementalDestroyGarbageStartTime) * 1000);
#if PERF_DETAILED_PER_CLASS_GC_STATS
LogClassCountInfo( TEXT("objects of"), GClassToPurgeCountMap, 10, PurgedObjectCountSinceLastMarkPhase);
#endif
GAsyncPurge->ResetObjectsDestroyedSinceLastMarkPhase();
}
}
if (bUseTimeLimit && !bCompleted)
{
UE_LOG(LogGarbage, Log, TEXT("%.3f ms for incrementally purging unreachable objects (FinishDestroyed: %d, Destroyed: %d / %d)"),
(FPlatformTime::Seconds() - IncrementalDestroyGarbageStartTime) * 1000,
GObjCurrentPurgeObjectIndex,
GAsyncPurge->GetObjectsDestroyedSinceLastMarkPhase(),
GUnreachableObjects.Num());
}
return bCompleted;
}
#endif // UE_WITH_GC
/**
* Returns whether an incremental purge is still pending/ in progress.
*
* @return true if incremental purge needs to be kicked off or is currently in progress, false othwerise.
*/
bool IsIncrementalPurgePending()
{
return GObjIncrementalPurgeIsInProgress || GObjPurgeIsRequired;
}
// This counts how many times GC was skipped
static int32 GNumAttemptsSinceLastGC = 0;
// Number of times GC can be skipped.
static int32 GNumRetriesBeforeForcingGC = 10;
static FAutoConsoleVariableRef CVarNumRetriesBeforeForcingGC(
TEXT("gc.NumRetriesBeforeForcingGC"),
GNumRetriesBeforeForcingGC,
TEXT("Maximum number of times GC can be skipped if worker threads are currently modifying UObject state."),
ECVF_Default
);
// Force flush streaming on GC console variable
static int32 GFlushStreamingOnGC = 0;
static FAutoConsoleVariableRef CVarFlushStreamingOnGC(
TEXT("gc.FlushStreamingOnGC"),
GFlushStreamingOnGC,
TEXT("If enabled, streaming will be flushed each time garbage collection is triggered."),
ECVF_Default
);
void GatherUnreachableObjects(bool bForceSingleThreaded)
{
DECLARE_SCOPE_CYCLE_COUNTER(TEXT("CollectGarbageInternal.GatherUnreachableObjects"), STAT_CollectGarbageInternal_GatherUnreachableObjects, STATGROUP_GC);
const double StartTime = FPlatformTime::Seconds();
GUnreachableObjects.Reset();
GUnrechableObjectIndex = 0;
int32 MaxNumberOfObjects = GUObjectArray.GetObjectArrayNum() - (GExitPurge ? 0 : GUObjectArray.GetFirstGCIndex());
int32 NumThreads = FMath::Max(1, FTaskGraphInterface::Get().GetNumWorkerThreads());
int32 NumberOfObjectsPerThread = (MaxNumberOfObjects / NumThreads) + 1;
TArray<FUObjectItem*> ClusterItemsToDestroy;
int32 ClusterObjects = 0;
// Iterate over all objects. Note that we iterate over the UObjectArray and usually check only internal flags which
// are part of the array so we don't suffer from cache misses as much as we would if we were to check ObjectFlags.
ParallelFor(NumThreads, [&ClusterItemsToDestroy, NumberOfObjectsPerThread, NumThreads, MaxNumberOfObjects](int32 ThreadIndex)
{
int32 FirstObjectIndex = ThreadIndex * NumberOfObjectsPerThread + (GExitPurge ? 0 : GUObjectArray.GetFirstGCIndex());
int32 NumObjects = (ThreadIndex < (NumThreads - 1)) ? NumberOfObjectsPerThread : (MaxNumberOfObjects - (NumThreads - 1) * NumberOfObjectsPerThread);
int32 LastObjectIndex = FMath::Min(GUObjectArray.GetObjectArrayNum() - 1, FirstObjectIndex + NumObjects - 1);
TArray<FUObjectItem*> ThisThreadUnreachableObjects;
TArray<FUObjectItem*> ThisThreadClusterItemsToDestroy;
for (int32 ObjectIndex = FirstObjectIndex; ObjectIndex <= LastObjectIndex; ++ObjectIndex)
{
FUObjectItem* ObjectItem = &GUObjectArray.GetObjectItemArrayUnsafe()[ObjectIndex];
if (ObjectItem->IsUnreachable())
{
ThisThreadUnreachableObjects.Add(ObjectItem);
if (ObjectItem->HasAnyFlags(EInternalObjectFlags::ClusterRoot))
{
// We can't mark cluster objects as unreachable here as they may be currently being processed on another thread
ThisThreadClusterItemsToDestroy.Add(ObjectItem);
}
}
}
if (ThisThreadUnreachableObjects.Num())
{
FScopeLock UnreachableObjectsLock(&GUnreachableObjectsCritical);
GUnreachableObjects.Append(ThisThreadUnreachableObjects);
ClusterItemsToDestroy.Append(ThisThreadClusterItemsToDestroy);
}
}, bForceSingleThreaded);
{
// @todo: if GUObjectClusters.FreeCluster() was thread safe we could do this in parallel too
for (FUObjectItem* ClusterRootItem : ClusterItemsToDestroy)
{
#if UE_GCCLUSTER_VERBOSE_LOGGING
UE_LOG(LogGarbage, Log, TEXT("Destroying cluster (%d) %s"), ClusterRootItem->GetClusterIndex(), *static_cast<UObject*>(ClusterRootItem->Object)->GetFullName());
#endif
ClusterRootItem->ClearFlags(EInternalObjectFlags::ClusterRoot);
const int32 ClusterIndex = ClusterRootItem->GetClusterIndex();
FUObjectCluster& Cluster = GUObjectClusters[ClusterIndex];
for (int32 ClusterObjectIndex : Cluster.Objects)
{
FUObjectItem* ClusterObjectItem = GUObjectArray.IndexToObjectUnsafeForGC(ClusterObjectIndex);
ClusterObjectItem->SetOwnerIndex(0);
if (!ClusterObjectItem->HasAnyFlags(EInternalObjectFlags::ReachableInCluster))
{
ClusterObjectItem->SetFlags(EInternalObjectFlags::Unreachable);
ClusterObjects++;
GUnreachableObjects.Add(ClusterObjectItem);
}
}
GUObjectClusters.FreeCluster(ClusterIndex);
}
}
UE_LOG(LogGarbage, Log, TEXT("%f ms for Gather Unreachable Objects (%d objects collected including %d cluster objects from %d clusters)"),
(FPlatformTime::Seconds() - StartTime) * 1000,
GUnreachableObjects.Num(),
ClusterObjects,
ClusterItemsToDestroy.Num());
}
/**
* Deletes all unreferenced objects, keeping objects that have any of the passed in KeepFlags set
*
* @param KeepFlags objects with those flags will be kept regardless of being referenced or not
* @param bPerformFullPurge if true, perform a full purge after the mark pass
*/
void CollectGarbageInternal(EObjectFlags KeepFlags, bool bPerformFullPurge)
{
#if !UE_WITH_GC
return;
#else
if (GIsInitialLoad)
{
// During initial load classes may not yet have their GC token streams assembled
UE_LOG(LogGarbage, Log, TEXT("Skipping CollectGarbage() call during initial load. It's not safe."));
return;
}
SCOPE_TIME_GUARD(TEXT("Collect Garbage"));
SCOPED_NAMED_EVENT(CollectGarbageInternal, FColor::Red);
CSV_EVENT_GLOBAL(TEXT("GC"));
CSV_SCOPED_TIMING_STAT_EXCLUSIVE(GarbageCollection);
LLM_SCOPE(ELLMTag::GC);
FGCCSyncObject::Get().ResetGCIsWaiting();
#if defined(WITH_CODE_GUARD_HANDLER) && WITH_CODE_GUARD_HANDLER
void CheckImageIntegrityAtRuntime();
CheckImageIntegrityAtRuntime();
#endif
DECLARE_SCOPE_CYCLE_COUNTER( TEXT( "CollectGarbageInternal" ), STAT_CollectGarbageInternal, STATGROUP_GC );
STAT_ADD_CUSTOMMESSAGE_NAME( STAT_NamedMarker, TEXT( "GarbageCollection - Begin" ) );
// We can't collect garbage while there's a load in progress. E.g. one potential issue is Import.XObject
check(!IsLoading());
// Reset GC skip counter
GNumAttemptsSinceLastGC = 0;
// Flush streaming before GC if requested
if (GFlushStreamingOnGC)
{
if (IsAsyncLoading())
{
UE_LOG(LogGarbage, Log, TEXT("CollectGarbageInternal() is flushing async loading"));
}
FGCCSyncObject::Get().GCUnlock();
FlushAsyncLoading();
FGCCSyncObject::Get().GCLock();
}
// Route callbacks so we can ensure that we are e.g. not in the middle of loading something by flushing
// the async loading, etc...
FCoreUObjectDelegates::GetPreGarbageCollectDelegate().Broadcast();
GLastGCFrame = GFrameCounter;
{
// Set 'I'm garbage collecting' flag - might be checked inside various functions.
// This has to be unlocked before we call post GC callbacks
FGCScopeLock GCLock;
UE_LOG(LogGarbage, Log, TEXT("Collecting garbage%s"), IsAsyncLoading() ? TEXT(" while async loading") : TEXT(""));
// Make sure previous incremental purge has finished or we do a full purge pass in case we haven't kicked one
// off yet since the last call to garbage collection.
if (GObjIncrementalPurgeIsInProgress || GObjPurgeIsRequired)
{
IncrementalPurgeGarbage(false);
FMemory::Trim();
}
check(!GObjIncrementalPurgeIsInProgress);
check(!GObjPurgeIsRequired);
// This can happen if someone disables clusters from the console (gc.CreateGCClusters)
if (!GCreateGCClusters && GUObjectClusters.GetNumAllocatedClusters())
{
GUObjectClusters.DissolveClusters(true);
}
#if VERIFY_DISREGARD_GC_ASSUMPTIONS
// Only verify assumptions if option is enabled. This avoids false positives in the Editor or commandlets.
if ((GUObjectArray.DisregardForGCEnabled() || GUObjectClusters.GetNumAllocatedClusters()) && GShouldVerifyGCAssumptions)
{
DECLARE_SCOPE_CYCLE_COUNTER(TEXT("CollectGarbageInternal.VerifyGCAssumptions"), STAT_CollectGarbageInternal_VerifyGCAssumptions, STATGROUP_GC);
const double StartTime = FPlatformTime::Seconds();
VerifyGCAssumptions();
VerifyClustersAssumptions();
UE_LOG(LogGarbage, Log, TEXT("%f ms for Verify GC Assumptions"), (FPlatformTime::Seconds() - StartTime) * 1000);
}
#endif
// Fall back to single threaded GC if processor count is 1 or parallel GC is disabled
// or detailed per class gc stats are enabled (not thread safe)
// Temporarily forcing single-threaded GC in the editor until Modify() can be safely removed from HandleObjectReference.
const bool bForceSingleThreadedGC = ShouldForceSingleThreadedGC();
// Run with GC clustering code enabled only if clustering is enabled and there's actual allocated clusters
const bool bWithClusters = !!GCreateGCClusters && GUObjectClusters.GetNumAllocatedClusters();
// Perform reachability analysis.
{
const double StartTime = FPlatformTime::Seconds();
FRealtimeGC TagUsedRealtimeGC;
TagUsedRealtimeGC.PerformReachabilityAnalysis(KeepFlags, bForceSingleThreadedGC, bWithClusters);
UE_LOG(LogGarbage, Log, TEXT("%f ms for GC"), (FPlatformTime::Seconds() - StartTime) * 1000);
}
// Reconstruct clusters if needed
if (GUObjectClusters.ClustersNeedDissolving())
{
const double StartTime = FPlatformTime::Seconds();
GUObjectClusters.DissolveClusters();
UE_LOG(LogGarbage, Log, TEXT("%f ms for dissolving GC clusters"), (FPlatformTime::Seconds() - StartTime) * 1000);
}
// Fire post-reachability analysis hooks
FCoreUObjectDelegates::PostReachabilityAnalysis.Broadcast();
{
GatherUnreachableObjects(bForceSingleThreadedGC);
NotifyUnreachableObjects(GUnreachableObjects);
// This needs to happen after GatherUnreachableObjects since GatherUnreachableObjects can mark more (clustered) objects as unreachable
FGCArrayPool::Get().ClearWeakReferences(bPerformFullPurge);
if (bPerformFullPurge || !GIncrementalBeginDestroyEnabled)
{
UnhashUnreachableObjects(/**bUseTimeLimit = */ false);
FScopedCBDProfile::DumpProfile();
}
}
// Set flag to indicate that we are relying on a purge to be performed.
GObjPurgeIsRequired = true;
// Perform a full purge by not using a time limit for the incremental purge. The Editor always does a full purge.
if (bPerformFullPurge || GIsEditor)
{
IncrementalPurgeGarbage(false);
}
if (bPerformFullPurge)
{
ShrinkUObjectHashTables();
}
// Destroy all pending delete linkers
DeleteLoaders();
// Trim allocator memory
FMemory::Trim();
}
// Route callbacks to verify GC assumptions
FCoreUObjectDelegates::GetPostGarbageCollect().Broadcast();
STAT_ADD_CUSTOMMESSAGE_NAME( STAT_NamedMarker, TEXT( "GarbageCollection - End" ) );
#endif // UE_WITH_GC
}
bool IsIncrementalUnhashPending()
{
return GUnrechableObjectIndex < GUnreachableObjects.Num();
}
bool UnhashUnreachableObjects(bool bUseTimeLimit, float TimeLimit)
{
DECLARE_SCOPE_CYCLE_COUNTER(TEXT("UnhashUnreachableObjects"), STAT_UnhashUnreachableObjects, STATGROUP_GC);
TGuardValue<bool> GuardObjUnhashUnreachableIsInProgress(GObjUnhashUnreachableIsInProgress, true);
FCoreUObjectDelegates::PreGarbageCollectConditionalBeginDestroy.Broadcast();
// Unhash all unreachable objects.
const double StartTime = FPlatformTime::Seconds();
const int32 TimeLimitEnforcementGranularityForBeginDestroy = 10;
int32 Items = 0;
int32 TimePollCounter = 0;
const bool bFirstIteration = (GUnrechableObjectIndex == 0);
while (GUnrechableObjectIndex < GUnreachableObjects.Num())
{
//@todo UE4 - A prefetch was removed here. Re-add it. It wasn't right anyway, since it was ten items ahead and the consoles on have 8 prefetch slots
FUObjectItem* ObjectItem = GUnreachableObjects[GUnrechableObjectIndex++];
{
UObject* Object = static_cast<UObject*>(ObjectItem->Object);
FScopedCBDProfile Profile(Object);
// Begin the object's asynchronous destruction.
Object->ConditionalBeginDestroy();
}
Items++;
const bool bPollTimeLimit = ((TimePollCounter++) % TimeLimitEnforcementGranularityForBeginDestroy == 0);
if (bUseTimeLimit && bPollTimeLimit && ((FPlatformTime::Seconds() - StartTime) > TimeLimit))
{
break;
}
}
const bool bTimeLimitReached = (GUnrechableObjectIndex < GUnreachableObjects.Num());
if (!bUseTimeLimit)
{
UE_LOG(LogGarbage, Log, TEXT("%f ms for %sunhashing unreachable objects (%d objects unhashed)"),
(FPlatformTime::Seconds() - StartTime) * 1000,
bUseTimeLimit ? TEXT("incrementally ") : TEXT(""),
Items,
GUnrechableObjectIndex, GUnreachableObjects.Num());
}
else if (!bTimeLimitReached)
{
// When doing incremental unhashing log only the first and last iteration (this was the last one)
UE_LOG(LogGarbage, Log, TEXT("Finished unhashing unreachable objects (%d objects unhashed)."), GUnreachableObjects.Num());
}
else if (bFirstIteration)
{
// When doing incremental unhashing log only the first and last iteration (this was the first one)
UE_LOG(LogGarbage, Log, TEXT("Starting unhashing unreachable objects (%d objects to unhash)."), GUnreachableObjects.Num());
}
FCoreUObjectDelegates::PostGarbageCollectConditionalBeginDestroy.Broadcast();
// Return true if time limit has been reached
return bTimeLimitReached;
}
void CollectGarbage(EObjectFlags KeepFlags, bool bPerformFullPurge)
{
// No other thread may be performing UObject operations while we're running
AcquireGCLock();
// Perform actual garbage collection
CollectGarbageInternal(KeepFlags, bPerformFullPurge);
// Other threads are free to use UObjects
ReleaseGCLock();
}
bool TryCollectGarbage(EObjectFlags KeepFlags, bool bPerformFullPurge)
{
// No other thread may be performing UObject operations while we're running
bool bCanRunGC = FGCCSyncObject::Get().TryGCLock();
if (!bCanRunGC)
{
if (GNumRetriesBeforeForcingGC > 0 && GNumAttemptsSinceLastGC > GNumRetriesBeforeForcingGC)
{
// Force GC and block main thread
UE_LOG(LogGarbage, Warning, TEXT("TryCollectGarbage: forcing GC after %d skipped attempts."), GNumAttemptsSinceLastGC);
GNumAttemptsSinceLastGC = 0;
AcquireGCLock();
bCanRunGC = true;
}
}
if (bCanRunGC)
{
// Perform actual garbage collection
CollectGarbageInternal(KeepFlags, bPerformFullPurge);
// Other threads are free to use UObjects
ReleaseGCLock();
}
else
{
GNumAttemptsSinceLastGC++;
}
return bCanRunGC;
}
void UObject::CallAddReferencedObjects(FReferenceCollector& Collector)
{
GetClass()->CallAddReferencedObjects(this, Collector);
}
void UObject::AddReferencedObjects(UObject* This, FReferenceCollector& Collector)
{
#if WITH_EDITOR
//@todo UE4 - This seems to be required and it should not be. Seems to be related to the texture streamer.
FLinkerLoad* LinkerLoad = This->GetLinker();
if (LinkerLoad)
{
LinkerLoad->AddReferencedObjects(Collector);
}
// Required by the unified GC when running in the editor
if (GIsEditor)
{
UObject* LoadOuter = This->GetOuter();
UClass* Class = This->GetClass();
UPackage* Package = This->GetExternalPackageInternal();
Collector.AllowEliminatingReferences(false);
Collector.AddReferencedObject(LoadOuter, This);
Collector.AddReferencedObject(Package, This);
Collector.AllowEliminatingReferences(true);
Collector.AddReferencedObject(Class, This);
}
#endif
}
bool UObject::IsDestructionThreadSafe() const
{
return false;
}
/*-----------------------------------------------------------------------------
Implementation of realtime garbage collection helper functions in
FProperty, UClass, ...
-----------------------------------------------------------------------------*/
/**
* Returns true if this property, or in the case of e.g. array or struct properties any sub- property, contains a
* UObject reference.
*
* @return true if property (or sub- properties) contain a UObject reference, false otherwise
*/
bool FProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
return false;
}
/**
* Returns true if this property, or in the case of e.g. array or struct properties any sub- property, contains a
* UObject reference.
*
* @return true if property (or sub- properties) contain a UObject reference, false otherwise
*/
bool FArrayProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
check(Inner);
return Inner->ContainsObjectReference(EncounteredStructProps, InReferenceType);
}
/**
* Returns true if this property, or in the case of e.g. array or struct properties any sub- property, contains a
* UObject reference.
*
* @return true if property (or sub- properties) contain a UObject reference, false otherwise
*/
bool FMapProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
check(KeyProp);
check(ValueProp);
return KeyProp->ContainsObjectReference(EncounteredStructProps, InReferenceType) || ValueProp->ContainsObjectReference(EncounteredStructProps, InReferenceType);
}
/**
* Returns true if this property, or in the case of e.g. array or struct properties any sub- property, contains a
* UObject reference.
*
* @return true if property (or sub- properties) contain a UObject reference, false otherwise
*/
bool FSetProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
check(ElementProp);
return ElementProp->ContainsObjectReference(EncounteredStructProps, InReferenceType);
}
/**
* Returns true if this property, or in the case of e.g. array or struct properties any sub- property, contains a
* UObject reference.
*
* @return true if property (or sub- properties) contain a UObject reference, false otherwise
*/
bool FStructProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
if (EncounteredStructProps.Contains(this))
{
return false;
}
else
{
if (!Struct)
{
UE_LOG(LogGarbage, Warning, TEXT("Broken FStructProperty does not have a UStruct: %s"), *GetFullName() );
}
else if (Struct->StructFlags & STRUCT_AddStructReferencedObjects)
{
return true;
}
else
{
EncounteredStructProps.Add(this);
FProperty* Property = Struct->PropertyLink;
while( Property )
{
if (Property->ContainsObjectReference(EncounteredStructProps, InReferenceType))
{
EncounteredStructProps.RemoveSingleSwap(this);
return true;
}
Property = Property->PropertyLinkNext;
}
EncounteredStructProps.RemoveSingleSwap(this);
}
return false;
}
}
bool FFieldPathProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
return !!(InReferenceType & EPropertyObjectReferenceType::Strong);
}
// Returns true if this property contains a weak UObject reference.
bool FDelegateProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
return !!(InReferenceType & EPropertyObjectReferenceType::Weak);
}
// Returns true if this property contains a weak UObject reference.
bool FMulticastDelegateProperty::ContainsObjectReference(TArray<const FStructProperty*>& EncounteredStructProps, EPropertyObjectReferenceType InReferenceType /*= EPropertyObjectReferenceType::Strong*/) const
{
return !!(InReferenceType & EPropertyObjectReferenceType::Weak);
}
/**
* Scope helper structure to emit tokens for fixed arrays in the case of ArrayDim (passed in count) being > 1.
*/
struct FGCReferenceFixedArrayTokenHelper
{
/**
* Constructor, emitting necessary tokens for fixed arrays if count > 1 and also keeping track of count so
* destructor can do the same.
*
* @param InReferenceTokenStream Token stream to emit tokens to
* @param InOffset offset into object/ struct
* @param InCount array count
* @param InStride array type stride (e.g. sizeof(struct) or sizeof(UObject*))
* @param InProperty the property this array represents
*/
FGCReferenceFixedArrayTokenHelper(UClass& OwnerClass, int32 InOffset, int32 InCount, int32 InStride, const FProperty& InProperty)
: ReferenceTokenStream(&OwnerClass.ReferenceTokenStream)
, Count(InCount)
{
if( InCount > 1 )
{
OwnerClass.EmitObjectReference(InOffset, InProperty.GetFName(), GCRT_FixedArray);
OwnerClass.ReferenceTokenStream.EmitStride(InStride);
OwnerClass.ReferenceTokenStream.EmitCount(InCount);
}
}
/** Destructor, emitting return if ArrayDim > 1 */
~FGCReferenceFixedArrayTokenHelper()
{
if( Count > 1 )
{
ReferenceTokenStream->EmitReturn();
}
}
private:
/** Reference token stream used to emit to */
FGCReferenceTokenStream* ReferenceTokenStream;
/** Size of fixed array */
int32 Count;
};
/**
* Emits tokens used by realtime garbage collection code to passed in ReferenceTokenStream. The offset emitted is relative
* to the passed in BaseOffset which is used by e.g. arrays of structs.
*/
void FProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
}
/**
* Emits tokens used by realtime garbage collection code to passed in OwnerClass' ReferenceTokenStream. The offset emitted is relative
* to the passed in BaseOffset which is used by e.g. arrays of structs.
*/
void FObjectProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, sizeof(UObject*), *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_Object);
}
void FWeakObjectProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, sizeof(FWeakObjectPtr), *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_WeakObject);
}
void FLazyObjectProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, sizeof(FLazyObjectPtr), *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_LazyObject);
}
void FSoftObjectProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, sizeof(FSoftObjectPtr), *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_SoftObject);
}
void FDelegateProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, this->ElementSize, *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_Delegate);
}
void FMulticastDelegateProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, this->ElementSize, *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_MulticastDelegate);
}
/**
* Emits tokens used by realtime garbage collection code to passed in OwnerClass' ReferenceTokenStream. The offset emitted is relative
* to the passed in BaseOffset which is used by e.g. arrays of structs.
*/
void FArrayProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
if (Inner->ContainsObjectReference(EncounteredStructProps, EPropertyObjectReferenceType::Strong | EPropertyObjectReferenceType::Weak))
{
bool bUsesFreezableAllocator = EnumHasAnyFlags(ArrayFlags, EArrayPropertyFlags::UsesMemoryImageAllocator);
if( Inner->IsA(FStructProperty::StaticClass()) )
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), bUsesFreezableAllocator ? GCRT_ArrayStructFreezable : GCRT_ArrayStruct);
OwnerClass.ReferenceTokenStream.EmitStride(Inner->ElementSize);
const uint32 SkipIndexIndex = OwnerClass.ReferenceTokenStream.EmitSkipIndexPlaceholder();
Inner->EmitReferenceInfo(OwnerClass, 0, EncounteredStructProps);
const uint32 SkipIndex = OwnerClass.ReferenceTokenStream.EmitReturn();
OwnerClass.ReferenceTokenStream.UpdateSkipIndexPlaceholder(SkipIndexIndex, SkipIndex);
}
else if( Inner->IsA(FObjectProperty::StaticClass()) )
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), bUsesFreezableAllocator ? GCRT_ArrayObjectFreezable : GCRT_ArrayObject);
}
else if( Inner->IsA(FInterfaceProperty::StaticClass()) )
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), bUsesFreezableAllocator ? GCRT_ArrayStructFreezable : GCRT_ArrayStruct);
OwnerClass.ReferenceTokenStream.EmitStride(Inner->ElementSize);
const uint32 SkipIndexIndex = OwnerClass.ReferenceTokenStream.EmitSkipIndexPlaceholder();
OwnerClass.EmitObjectReference(0, GetFName(), GCRT_Object);
const uint32 SkipIndex = OwnerClass.ReferenceTokenStream.EmitReturn();
OwnerClass.ReferenceTokenStream.UpdateSkipIndexPlaceholder(SkipIndexIndex, SkipIndex);
}
else if (Inner->IsA(FFieldPathProperty::StaticClass()))
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_ArrayAddFieldPathReferencedObject);
}
else if (Inner->IsA(FWeakObjectProperty::StaticClass()))
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_ArrayWeakObject);
}
else if (Inner->IsA(FLazyObjectProperty::StaticClass()))
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_ArrayLazyObject);
}
else if (Inner->IsA(FSoftObjectProperty::StaticClass()))
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_ArraySoftObject);
}
else if (Inner->IsA(FDelegateProperty::StaticClass()))
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_ArrayDelegate);
}
else if (Inner->IsA(FMulticastDelegateProperty::StaticClass()))
{
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_ArrayMulticastDelegate);
}
else
{
UE_LOG(LogGarbage, Fatal, TEXT("Encountered unknown property containing object or name reference: %s in %s"), *Inner->GetFullName(), *GetFullName() );
}
}
}
/**
* Emits tokens used by realtime garbage collection code to passed in OwnerClass' ReferenceTokenStream. The offset emitted is relative
* to the passed in BaseOffset which is used by e.g. arrays of structs.
*/
void FMapProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
if (ContainsObjectReference(EncounteredStructProps, EPropertyObjectReferenceType::Strong | EPropertyObjectReferenceType::Weak))
{
// TMap reference tokens are processed by GC in a similar way to an array of structs
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_AddTMapReferencedObjects);
OwnerClass.ReferenceTokenStream.EmitPointer((const void*)this);
const uint32 SkipIndexIndex = OwnerClass.ReferenceTokenStream.EmitSkipIndexPlaceholder();
if (KeyProp->ContainsObjectReference(EncounteredStructProps, EPropertyObjectReferenceType::Strong | EPropertyObjectReferenceType::Weak))
{
KeyProp->EmitReferenceInfo(OwnerClass, 0, EncounteredStructProps);
}
if (ValueProp->ContainsObjectReference(EncounteredStructProps, EPropertyObjectReferenceType::Strong | EPropertyObjectReferenceType::Weak))
{
ValueProp->EmitReferenceInfo(OwnerClass, 0, EncounteredStructProps);
}
const uint32 SkipIndex = OwnerClass.ReferenceTokenStream.EmitReturn();
OwnerClass.ReferenceTokenStream.UpdateSkipIndexPlaceholder(SkipIndexIndex, SkipIndex);
}
}
/**
* Emits tokens used by realtime garbage collection code to passed in OwnerClass' ReferenceTokenStream. The offset emitted is relative
* to the passed in BaseOffset which is used by e.g. arrays of structs.
*/
void FSetProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
if (ContainsObjectReference(EncounteredStructProps, EPropertyObjectReferenceType::Strong | EPropertyObjectReferenceType::Weak))
{
// TSet reference tokens are processed by GC in a similar way to an array of structs
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_AddTSetReferencedObjects);
OwnerClass.ReferenceTokenStream.EmitPointer((const void*)this);
const uint32 SkipIndexIndex = OwnerClass.ReferenceTokenStream.EmitSkipIndexPlaceholder();
ElementProp->EmitReferenceInfo(OwnerClass, 0, EncounteredStructProps);
const uint32 SkipIndex = OwnerClass.ReferenceTokenStream.EmitReturn();
OwnerClass.ReferenceTokenStream.UpdateSkipIndexPlaceholder(SkipIndexIndex, SkipIndex);
}
}
/**
* Emits tokens used by realtime garbage collection code to passed in ReferenceTokenStream. The offset emitted is relative
* to the passed in BaseOffset which is used by e.g. arrays of structs.
*/
void FStructProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
check(Struct);
if (Struct->StructFlags & STRUCT_AddStructReferencedObjects)
{
UScriptStruct::ICppStructOps* CppStructOps = Struct->GetCppStructOps();
check(CppStructOps); // else should not have STRUCT_AddStructReferencedObjects
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, ElementSize, *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_AddStructReferencedObjects);
void *FunctionPtr = (void*)CppStructOps->AddStructReferencedObjects();
OwnerClass.ReferenceTokenStream.EmitPointer(FunctionPtr);
}
// Check if the struct has any properties that reference UObjects
bool bHasPropertiesWithObjectReferences = false;
if (Struct->PropertyLink)
{
// Can't use ContainObjectReference here as it also checks for STRUCT_AddStructReferencedObjects but we only care about property exposed refs
EncounteredStructProps.Add(this);
for (FProperty* Property = Struct->PropertyLink; Property && !bHasPropertiesWithObjectReferences; Property = Property->PropertyLinkNext)
{
bHasPropertiesWithObjectReferences = Property->ContainsObjectReference(EncounteredStructProps, EPropertyObjectReferenceType::Strong | EPropertyObjectReferenceType::Weak);
}
EncounteredStructProps.RemoveSingleSwap(this);
}
// If the struct has UObject properties (and only if) emit tokens for them
if (bHasPropertiesWithObjectReferences)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, ElementSize, *this);
FProperty* Property = Struct->PropertyLink;
while (Property)
{
Property->EmitReferenceInfo(OwnerClass, BaseOffset + GetOffset_ForGC(), EncounteredStructProps);
Property = Property->PropertyLinkNext;
}
}
}
/**
* Emits tokens used by realtime garbage collection code to passed in ReferenceTokenStream. The offset emitted is relative
* to the passed in BaseOffset which is used by e.g. arrays of structs.
*/
void FInterfaceProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, sizeof(FScriptInterface), *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_Object);
}
void FFieldPathProperty::EmitReferenceInfo(UClass& OwnerClass, int32 BaseOffset, TArray<const FStructProperty*>& EncounteredStructProps)
{
static_assert(sizeof(FFieldPath) == sizeof(TFieldPath<FProperty>), "TFieldPath should have the same size as the underlying FFieldPath");
FGCReferenceFixedArrayTokenHelper FixedArrayHelper(OwnerClass, BaseOffset + GetOffset_ForGC(), ArrayDim, sizeof(FFieldPath), *this);
OwnerClass.EmitObjectReference(BaseOffset + GetOffset_ForGC(), GetFName(), GCRT_AddFieldPathReferencedObject);
}
void UClass::EmitObjectReference(int32 Offset, const FName& DebugName, EGCReferenceType Kind)
{
FGCReferenceInfo ObjectReference(Kind, Offset);
ReferenceTokenStream.EmitReferenceInfo(ObjectReference, DebugName);
}
void UClass::EmitObjectArrayReference(int32 Offset, const FName& DebugName)
{
check(HasAnyClassFlags(CLASS_Intrinsic));
EmitObjectReference(Offset, DebugName, GCRT_ArrayObject);
}
uint32 UClass::EmitStructArrayBegin(int32 Offset, const FName& DebugName, int32 Stride)
{
check(HasAnyClassFlags(CLASS_Intrinsic));
EmitObjectReference(Offset, DebugName, GCRT_ArrayStruct);
ReferenceTokenStream.EmitStride(Stride);
const uint32 SkipIndexIndex = ReferenceTokenStream.EmitSkipIndexPlaceholder();
return SkipIndexIndex;
}
/**
* Realtime garbage collection helper function used to indicate the end of an array of structs. The
* index following the current one will be written to the passed in SkipIndexIndex in order to be
* able to skip tokens for empty dynamic arrays.
*
* @param SkipIndexIndex
*/
void UClass::EmitStructArrayEnd( uint32 SkipIndexIndex )
{
check( HasAnyClassFlags( CLASS_Intrinsic ) );
const uint32 SkipIndex = ReferenceTokenStream.EmitReturn();
ReferenceTokenStream.UpdateSkipIndexPlaceholder( SkipIndexIndex, SkipIndex );
}
void UClass::EmitFixedArrayBegin(int32 Offset, const FName& DebugName, int32 Stride, int32 Count)
{
check(HasAnyClassFlags(CLASS_Intrinsic));
EmitObjectReference(Offset, DebugName, GCRT_FixedArray);
ReferenceTokenStream.EmitStride(Stride);
ReferenceTokenStream.EmitCount(Count);
}
/**
* Realtime garbage collection helper function used to indicated the end of a fixed array.
*/
void UClass::EmitFixedArrayEnd()
{
check( HasAnyClassFlags( CLASS_Intrinsic ) );
ReferenceTokenStream.EmitReturn();
}
void UClass::EmitExternalPackageReference()
{
#if WITH_EDITOR
static const FName TokenName("ExternalPackageToken");
ReferenceTokenStream.EmitReferenceInfo(FGCReferenceInfo(GCRT_ExternalPackage, 0), TokenName);
#endif
}
struct FScopeLockIfNotNative
{
FCriticalSection& ScopeCritical;
const bool bNotNative;
FScopeLockIfNotNative(FCriticalSection& InScopeCritical, bool bIsNotNative)
: ScopeCritical(InScopeCritical)
, bNotNative(bIsNotNative)
{
if (bNotNative)
{
ScopeCritical.Lock();
}
}
~FScopeLockIfNotNative()
{
if (bNotNative)
{
ScopeCritical.Unlock();
}
}
};
void UClass::AssembleReferenceTokenStream(bool bForce)
{
// Lock for non-native classes
FScopeLockIfNotNative ReferenceTokenStreamLock(ReferenceTokenStreamCritical, !(ClassFlags & CLASS_Native));
UE_CLOG(!IsInGameThread() && !IsGarbageCollectionLocked(), LogGarbage, Fatal, TEXT("AssembleReferenceTokenStream for %s called on a non-game thread while GC is not locked."), *GetFullName());
if (!HasAnyClassFlags(CLASS_TokenStreamAssembled) || bForce)
{
if (bForce)
{
ReferenceTokenStream.Empty();
ClassFlags &= ~CLASS_TokenStreamAssembled;
}
TArray<const FStructProperty*> EncounteredStructProps;
// Iterate over properties defined in this class
for( TFieldIterator<FProperty> It(this,EFieldIteratorFlags::ExcludeSuper); It; ++It)
{
FProperty* Property = *It;
Property->EmitReferenceInfo(*this, 0, EncounteredStructProps);
}
if (UClass* SuperClass = GetSuperClass())
{
// We also need to lock the super class stream in case something (like PostLoad) wants to reconstruct it on GameThread
FScopeLockIfNotNative SuperClassReferenceTokenStreamLock(SuperClass->ReferenceTokenStreamCritical, !(SuperClass->ClassFlags & CLASS_Native));
// Make sure super class has valid token stream.
SuperClass->AssembleReferenceTokenStream();
if (!SuperClass->ReferenceTokenStream.IsEmpty())
{
// Prepend super's stream. This automatically handles removing the EOS token.
ReferenceTokenStream.PrependStream(SuperClass->ReferenceTokenStream);
}
}
else
{
UObjectBase::EmitBaseReferences(this);
}
{
check(ClassAddReferencedObjects != NULL);
const bool bKeepOuter = true;//GetFName() != NAME_Package;
const bool bKeepClass = true;//!HasAnyInternalFlags(EInternalObjectFlags::Native) || IsA(UDynamicClass::StaticClass());
ClassAddReferencedObjectsType AddReferencedObjectsFn = nullptr;
#if !WITH_EDITOR
// In no-editor builds UObject::ARO is empty, thus only classes
// which implement their own ARO function need to have the ARO token generated.
if (ClassAddReferencedObjects != &UObject::AddReferencedObjects)
{
AddReferencedObjectsFn = ClassAddReferencedObjects;
}
#else
AddReferencedObjectsFn = ClassAddReferencedObjects;
#endif
ReferenceTokenStream.Fixup(AddReferencedObjectsFn, bKeepOuter, bKeepClass);
}
if (ReferenceTokenStream.IsEmpty())
{
return;
}
// Emit end of stream token.
static const FName EOSDebugName("EndOfStreamToken");
EmitObjectReference(0, EOSDebugName, GCRT_EndOfStream);
// Shrink reference token stream to proper size.
ReferenceTokenStream.Shrink();
check(!HasAnyClassFlags(CLASS_TokenStreamAssembled)); // recursion here is probably bad
ClassFlags |= CLASS_TokenStreamAssembled;
}
}
/**
* Prepends passed in stream to existing one.
*
* @param Other stream to concatenate
*/
void FGCReferenceTokenStream::PrependStream( const FGCReferenceTokenStream& Other )
{
// Remove embedded EOS token if needed.
FGCReferenceInfo EndOfStream(GCRT_EndOfStream, 0);
int32 NumTokensToPrepend = (Other.Tokens.Num() && Other.Tokens.Last() == EndOfStream) ? (Other.Tokens.Num() - 1) : Other.Tokens.Num();
TArray<uint32> TempTokens;
TempTokens.Reserve(NumTokensToPrepend + Tokens.Num());
#if ENABLE_GC_OBJECT_CHECKS
check(TokenDebugInfo.Num() == Tokens.Num());
check(Other.TokenDebugInfo.Num() == Other.Tokens.Num());
TArray<FName> TempTokenDebugInfo;
TempTokenDebugInfo.Reserve(NumTokensToPrepend + TokenDebugInfo.Num());
#endif // ENABLE_GC_OBJECT_CHECKS
for (int32 TokenIndex = 0; TokenIndex < NumTokensToPrepend; ++TokenIndex)
{
TempTokens.Add(Other.Tokens[TokenIndex]);
#if ENABLE_GC_OBJECT_CHECKS
TempTokenDebugInfo.Add(Other.TokenDebugInfo[TokenIndex]);
#endif // ENABLE_GC_OBJECT_CHECKS
}
TempTokens.Append(Tokens);
Tokens = MoveTemp(TempTokens);
#if ENABLE_GC_OBJECT_CHECKS
TempTokenDebugInfo.Append(TokenDebugInfo);
TokenDebugInfo = MoveTemp(TempTokenDebugInfo);
#endif // ENABLE_GC_OBJECT_CHECKS
}
void FGCReferenceTokenStream::Fixup(void (*AddReferencedObjectsPtr)(UObject*, class FReferenceCollector&), bool bKeepOuterToken, bool bKeepClassToken)
{
bool bReplacedARO = false;
// Try to find exiting ARO pointer and replace it (to avoid removing and readding tokens).
for (int32 TokenStreamIndex = 0; TokenStreamIndex < Tokens.Num(); ++TokenStreamIndex)
{
uint32 TokenIndex = (uint32)TokenStreamIndex;
FGCReferenceInfo Token = Tokens[TokenIndex];
// Read token type and skip additional data if present.
switch (Token.Type)
{
case GCRT_ArrayStruct:
case GCRT_ArrayStructFreezable:
{
// Skip stride and move to Skip Info
TokenIndex += 2;
const FGCSkipInfo SkipInfo = ReadSkipInfo(TokenIndex);
// Set the TokenIndex to the skip index - 1 because we're going to
// increment in the for loop anyway.
TokenIndex = SkipInfo.SkipIndex - 1;
}
break;
case GCRT_FixedArray:
{
// Skip stride
TokenIndex++;
// Skip count
TokenIndex++;
}
break;
case GCRT_AddStructReferencedObjects:
{
// Skip pointer
TokenIndex += GNumTokensPerPointer;
}
break;
case GCRT_AddReferencedObjects:
{
// Store the pointer after the ARO token.
if (AddReferencedObjectsPtr)
{
StorePointer(&Tokens[TokenIndex + 1], (const void*)AddReferencedObjectsPtr);
}
bReplacedARO = true;
TokenIndex += GNumTokensPerPointer;
}
break;
case GCRT_AddTMapReferencedObjects:
case GCRT_AddTSetReferencedObjects:
{
// Skip pointer
TokenIndex += GNumTokensPerPointer;
TokenIndex += 1; // GCRT_EndOfPointer;
// Move to Skip Info
TokenIndex += 1;
const FGCSkipInfo SkipInfo = ReadSkipInfo(TokenIndex);
// Set the TokenIndex to the skip index - 1 because we're going to
// increment in the for loop anyway.
TokenIndex = SkipInfo.SkipIndex - 1;
}
break;
case GCRT_Class:
case GCRT_NoopClass:
{
if (bKeepClassToken)
{
Token.Type = GCRT_Class;
}
else
{
Token.Type = GCRT_NoopClass;
}
Tokens[TokenIndex] = Token;
}
break;
case GCRT_PersistentObject:
case GCRT_NoopPersistentObject:
{
if (bKeepOuterToken)
{
Token.Type = GCRT_PersistentObject;
}
else
{
Token.Type = GCRT_NoopPersistentObject;
}
Tokens[TokenIndex] = Token;
}
break;
case GCRT_Optional:
{
// Move to Skip Info
TokenIndex++;
const FGCSkipInfo SkipInfo = ReadSkipInfo(TokenIndex);
// Set the TokenIndex to the skip index - 1 because we're going to
// increment in the for loop anyway.
TokenIndex = SkipInfo.SkipIndex - 1;
}
break;
case GCRT_None:
case GCRT_Object:
case GCRT_ExternalPackage:
case GCRT_ArrayObject:
case GCRT_ArrayObjectFreezable:
case GCRT_AddFieldPathReferencedObject:
case GCRT_ArrayAddFieldPathReferencedObject:
case GCRT_EndOfPointer:
case GCRT_EndOfStream:
case GCRT_WeakObject:
case GCRT_ArrayWeakObject:
case GCRT_LazyObject:
case GCRT_ArrayLazyObject:
case GCRT_SoftObject:
case GCRT_ArraySoftObject:
case GCRT_Delegate:
case GCRT_ArrayDelegate:
case GCRT_MulticastDelegate:
case GCRT_ArrayMulticastDelegate:
break;
default:
UE_LOG(LogGarbage, Fatal, TEXT("Unknown token type (%u) when trying to add ARO token."), (uint32)Token.Type);
break;
};
TokenStreamIndex = (int32)TokenIndex;
}
// ARO is not in the token stream yet.
if (!bReplacedARO && AddReferencedObjectsPtr)
{
static const FName TokenName("AROToken");
EmitReferenceInfo(FGCReferenceInfo(GCRT_AddReferencedObjects, 0), TokenName);
EmitPointer((const void*)AddReferencedObjectsPtr);
}
}
int32 FGCReferenceTokenStream::EmitReferenceInfo(FGCReferenceInfo ReferenceInfo, const FName& DebugName)
{
int32 TokenIndex = Tokens.Add(ReferenceInfo);
#if ENABLE_GC_OBJECT_CHECKS
check(TokenDebugInfo.Num() == TokenIndex);
TokenDebugInfo.Add(DebugName);
#endif
return TokenIndex;
}
/**
* Emit placeholder for aray skip index, updated in UpdateSkipIndexPlaceholder
*
* @return the index of the skip index, used later in UpdateSkipIndexPlaceholder
*/
uint32 FGCReferenceTokenStream::EmitSkipIndexPlaceholder()
{
uint32 TokenIndex = Tokens.Add(E_GCSkipIndexPlaceholder);
#if ENABLE_GC_OBJECT_CHECKS
static const FName TokenName("SkipIndexPlaceholder");
check(TokenDebugInfo.Num() == TokenIndex);
TokenDebugInfo.Add(TokenName);
#endif
return TokenIndex;
}
/**
* Updates skip index place holder stored and passed in skip index index with passed
* in skip index. The skip index is used to skip over tokens in the case of an empty
* dynamic array.
*
* @param SkipIndexIndex index where skip index is stored at.
* @param SkipIndex index to store at skip index index
*/
void FGCReferenceTokenStream::UpdateSkipIndexPlaceholder( uint32 SkipIndexIndex, uint32 SkipIndex )
{
check( SkipIndex > 0 && SkipIndex <= (uint32)Tokens.Num() );
const FGCReferenceInfo& ReferenceInfo = Tokens[SkipIndex-1];
check( ReferenceInfo.Type != GCRT_None );
check( Tokens[SkipIndexIndex] == E_GCSkipIndexPlaceholder );
check( SkipIndexIndex < SkipIndex );
check( ReferenceInfo.ReturnCount >= 1 );
FGCSkipInfo SkipInfo;
SkipInfo.SkipIndex = SkipIndex - SkipIndexIndex;
// We need to subtract 1 as ReturnCount includes return from this array.
SkipInfo.InnerReturnCount = ReferenceInfo.ReturnCount - 1;
Tokens[SkipIndexIndex] = SkipInfo;
}
/**
* Emit count
*
* @param Count count to emit
*/
int32 FGCReferenceTokenStream::EmitCount( uint32 Count )
{
int32 TokenIndex = Tokens.Add( Count );
#if ENABLE_GC_OBJECT_CHECKS
static const FName TokenName("CountToken");
check(TokenDebugInfo.Num() == TokenIndex);
TokenDebugInfo.Add(TokenName);
#endif
return TokenIndex;
}
int32 FGCReferenceTokenStream::EmitPointer( void const* Ptr )
{
const int32 StoreIndex = Tokens.Num();
Tokens.AddUninitialized(GNumTokensPerPointer);
StorePointer(&Tokens[StoreIndex], Ptr);
#if ENABLE_GC_OBJECT_CHECKS
static const FName TokenName("PointerToken");
check(TokenDebugInfo.Num() == StoreIndex);
for (int32 PointerTokenIndex = 0; PointerTokenIndex < GNumTokensPerPointer; ++PointerTokenIndex)
{
TokenDebugInfo.Add(TokenName);
}
#endif
// Now inser the end of pointer marker, this will mostly be used for storing ReturnCount value
// if the pointer was stored at the end of struct array stream.
static const FName EndOfPointerTokenName("EndOfPointerToken");
EmitReferenceInfo(FGCReferenceInfo(GCRT_EndOfPointer, 0), EndOfPointerTokenName);
return StoreIndex;
}
/**
* Emit stride
*
* @param Stride stride to emit
*/
int32 FGCReferenceTokenStream::EmitStride( uint32 Stride )
{
int32 TokenIndex = Tokens.Add( Stride );
#if ENABLE_GC_OBJECT_CHECKS
static const FName TokenName("StrideToken");
check(TokenDebugInfo.Num() == TokenIndex);
TokenDebugInfo.Add(TokenName);
#endif
return TokenIndex;
}
/**
* Increase return count on last token.
*
* @return index of next token
*/
uint32 FGCReferenceTokenStream::EmitReturn()
{
FGCReferenceInfo ReferenceInfo = Tokens.Last();
check(ReferenceInfo.Type != GCRT_None);
ReferenceInfo.ReturnCount++;
Tokens.Last() = ReferenceInfo;
return Tokens.Num();
}
#if ENABLE_GC_OBJECT_CHECKS
FTokenInfo FGCReferenceTokenStream::GetTokenInfo(int32 TokenIndex) const
{
FTokenInfo DebugInfo;
DebugInfo.Offset = FGCReferenceInfo(Tokens[TokenIndex]).Offset;
DebugInfo.Name = TokenDebugInfo[TokenIndex];
return DebugInfo;
}
#endif
FGCArrayPool* FGCArrayPool::GetGlobalSingleton()
{
static FAutoConsoleCommandWithOutputDevice GCDumpPoolCommand(
TEXT("gc.DumpPoolStats"),
TEXT("Dumps count and size of GC Pools"),
FConsoleCommandWithOutputDeviceDelegate::CreateStatic(&FGCArrayPool::DumpStats)
);
static FGCArrayPool* GlobalSingleton = nullptr;
if (!GlobalSingleton)
{
GlobalSingleton = new FGCArrayPool();
}
return GlobalSingleton;
}
| 412 | 0.863097 | 1 | 0.863097 | game-dev | MEDIA | 0.652904 | game-dev | 0.899343 | 1 | 0.899343 |
ImLegiitXD/Dream-Advanced | 3,541 | dll/back/1.20/net/minecraft/client/particle/FallingDustParticle.java | package net.minecraft.client.particle;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.BlockParticleOption;
import net.minecraft.util.Mth;
import net.minecraft.world.level.block.FallingBlock;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class FallingDustParticle extends TextureSheetParticle {
private final float rotSpeed;
private final SpriteSet sprites;
FallingDustParticle(ClientLevel p_106610_, double p_106611_, double p_106612_, double p_106613_, float p_106614_, float p_106615_, float p_106616_, SpriteSet p_106617_) {
super(p_106610_, p_106611_, p_106612_, p_106613_);
this.sprites = p_106617_;
this.rCol = p_106614_;
this.gCol = p_106615_;
this.bCol = p_106616_;
float f = 0.9F;
this.quadSize *= 0.67499995F;
int i = (int)(32.0D / (Math.random() * 0.8D + 0.2D));
this.lifetime = (int)Math.max((float)i * 0.9F, 1.0F);
this.setSpriteFromAge(p_106617_);
this.rotSpeed = ((float)Math.random() - 0.5F) * 0.1F;
this.roll = (float)Math.random() * ((float)Math.PI * 2F);
}
public ParticleRenderType getRenderType() {
return ParticleRenderType.PARTICLE_SHEET_OPAQUE;
}
public float getQuadSize(float p_106631_) {
return this.quadSize * Mth.clamp(((float)this.age + p_106631_) / (float)this.lifetime * 32.0F, 0.0F, 1.0F);
}
public void tick() {
this.xo = this.x;
this.yo = this.y;
this.zo = this.z;
if (this.age++ >= this.lifetime) {
this.remove();
} else {
this.setSpriteFromAge(this.sprites);
this.oRoll = this.roll;
this.roll += (float)Math.PI * this.rotSpeed * 2.0F;
if (this.onGround) {
this.oRoll = this.roll = 0.0F;
}
this.move(this.xd, this.yd, this.zd);
this.yd -= (double)0.003F;
this.yd = Math.max(this.yd, (double)-0.14F);
}
}
@OnlyIn(Dist.CLIENT)
public static class Provider implements ParticleProvider<BlockParticleOption> {
private final SpriteSet sprite;
public Provider(SpriteSet p_106634_) {
this.sprite = p_106634_;
}
@Nullable
public Particle createParticle(BlockParticleOption p_106636_, ClientLevel p_106637_, double p_106638_, double p_106639_, double p_106640_, double p_106641_, double p_106642_, double p_106643_) {
BlockState blockstate = p_106636_.getState();
if (!blockstate.isAir() && blockstate.getRenderShape() == RenderShape.INVISIBLE) {
return null;
} else {
BlockPos blockpos = BlockPos.containing(p_106638_, p_106639_, p_106640_);
int i = Minecraft.getInstance().getBlockColors().getColor(blockstate, p_106637_, blockpos);
if (blockstate.getBlock() instanceof FallingBlock) {
i = ((FallingBlock)blockstate.getBlock()).getDustColor(blockstate, p_106637_, blockpos);
}
float f = (float)(i >> 16 & 255) / 255.0F;
float f1 = (float)(i >> 8 & 255) / 255.0F;
float f2 = (float)(i & 255) / 255.0F;
return new FallingDustParticle(p_106637_, p_106638_, p_106639_, p_106640_, f, f1, f2, this.sprite);
}
}
}
} | 412 | 0.715126 | 1 | 0.715126 | game-dev | MEDIA | 0.932068 | game-dev | 0.891855 | 1 | 0.891855 |
kettingpowered/Ketting-1-20-x | 1,403 | patches/minecraft/net/minecraft/world/inventory/PlayerEnderChestContainer.java.patch | --- a/net/minecraft/world/inventory/PlayerEnderChestContainer.java
+++ b/net/minecraft/world/inventory/PlayerEnderChestContainer.java
@@ -11,9 +_,27 @@
public class PlayerEnderChestContainer extends SimpleContainer {
@Nullable
private EnderChestBlockEntity activeChest;
+ // CraftBukkit start
+ private Player owner; //Ketting - not final
+
+ public org.bukkit.inventory.InventoryHolder getBukkitOwner() {
+ if (owner == null) owner = org.kettingpowered.ketting.utils.InventoryViewHelper.getContainerOwner();
+ if (owner == null) return org.kettingpowered.ketting.craftbukkit.CraftStubInventoryHolder.INSTANCE;
+ return owner.getBukkitEntity();
+ }
+
+ @Override
+ public org.bukkit.Location getLocation() {
+ return this.activeChest != null ? org.bukkit.craftbukkit.v1_20_R1.util.CraftLocation.toBukkit(this.activeChest.getBlockPos(), this.activeChest.getLevel().getWorld()) : null;
+ }
public PlayerEnderChestContainer() {
+ this(null);//Ketting - keep compat
+ }
+ public PlayerEnderChestContainer(@Nullable Player owner) {
super(27);
+ this.owner = owner==null?org.kettingpowered.ketting.utils.InventoryViewHelper.getContainerOwner():owner; //Ketting - idk rn, if the InventoryViewHelper.getContainerOwner() is really correct rn.
+ // CraftBukkit end
}
public void setActiveChest(EnderChestBlockEntity p_40106_) {
| 412 | 0.604403 | 1 | 0.604403 | game-dev | MEDIA | 0.993045 | game-dev | 0.611318 | 1 | 0.611318 |
Spaghetticode-Boon-Tobias/RETROLauncher | 45,032 | RETROLauncher/System/Respaldo/RetroarchPS2_PAL/Nintendo Super Famicom/retroarch/retroarch.cfg | accessibility_enable = "false"
accessibility_narrator_speech_speed = "5"
ai_service_enable = "false"
ai_service_mode = "1"
ai_service_pause = "false"
ai_service_poll_delay = "0"
ai_service_source_lang = "0"
ai_service_target_lang = "0"
ai_service_text_padding = "5"
ai_service_text_position = "0"
all_users_control_menu = "false"
always_reload_core_on_run_content = "true"
app_icon = "default"
apply_cheats_after_load = "false"
apply_cheats_after_toggle = "false"
aspect_ratio_index = "12"
assets_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/assets"
audio_block_frames = "0"
audio_device = ""
audio_driver = "ps2"
audio_dsp_plugin = ""
audio_enable = "true"
audio_enable_menu = "false"
audio_enable_menu_bgm = "false"
audio_enable_menu_cancel = "false"
audio_enable_menu_notice = "false"
audio_enable_menu_ok = "false"
audio_enable_menu_scroll = "false"
audio_fastforward_mute = "false"
audio_fastforward_speedup = "false"
audio_filter_dir = "default"
audio_latency = "128"
audio_max_timing_skew = "0.050000"
audio_mixer_mute_enable = "true"
audio_mixer_volume = "0.000000"
audio_mute_enable = "false"
audio_out_rate = "24000"
audio_rate_control = "false"
audio_rate_control_delta = "0.005000"
audio_resampler = "sinc"
audio_resampler_quality = "1"
audio_sync = "true"
audio_volume = "0.000000"
auto_overrides_enable = "false"
auto_remaps_enable = "true"
auto_screenshot_filename = "true"
auto_shaders_enable = "true"
autosave_interval = "0"
block_sram_overwrite = "false"
bluetooth_driver = "null"
builtin_imageviewer_enable = "false"
builtin_mediaplayer_enable = "false"
bundle_assets_dst_path = ""
bundle_assets_dst_path_subdir = ""
bundle_assets_extract_enable = "false"
bundle_assets_extract_last_version = "0"
bundle_assets_extract_version_current = "0"
bundle_assets_src_path = ""
cache_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/temp"
camera_allow = "false"
camera_device = ""
camera_driver = "null"
cheat_database_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/cheats"
check_firmware_before_loading = "false"
cloud_sync_destructive = "false"
cloud_sync_driver = ""
cloud_sync_enable = "false"
cloud_sync_sync_configs = "true"
cloud_sync_sync_saves = "true"
cloud_sync_sync_system = "false"
cloud_sync_sync_thumbs = "false"
config_save_on_exit = "true"
content_database_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/database/rdb"
content_favorites_directory = "default"
content_favorites_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/content_favorites.lpl"
content_favorites_size = "0"
content_history_directory = "default"
content_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/content_history.lpl"
content_history_size = "200"
content_image_history_directory = "default"
content_image_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/content_image_history.lpl"
content_music_history_directory = "default"
content_music_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/content_music_history.lpl"
content_runtime_log = "false"
content_runtime_log_aggregate = "false"
content_show_add = "false"
content_show_add_entry = "0"
content_show_contentless_cores = "2"
content_show_explore = "false"
content_show_favorites = "false"
content_show_history = "false"
content_show_music = "false"
content_show_playlists = "false"
content_show_settings = "true"
content_show_settings_password = ""
content_video_directory = "default"
content_video_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/content_video_history.lpl"
core_assets_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/downloads"
core_info_cache_enable = "true"
core_info_savestate_bypass = "true"
core_option_category_enable = "true"
core_options_path = ""
core_set_supports_no_game_enable = "true"
core_updater_auto_backup = "false"
core_updater_auto_backup_history_size = "1"
core_updater_auto_extract_archive = "true"
core_updater_buildbot_assets_url = "http://buildbot.libretro.com/assets/"
core_updater_buildbot_cores_url = ""
core_updater_show_experimental_cores = "false"
crt_switch_center_adjust = "0"
crt_switch_hires_menu = "false"
crt_switch_porch_adjust = "0"
crt_switch_resolution = "0"
crt_switch_resolution_super = "2560"
crt_switch_resolution_use_custom_refresh_rate = "false"
crt_switch_timings = ""
crt_video_refresh_rate = "54.500000"
current_resolution_id = "1"
custom_viewport_height = "0"
custom_viewport_width = "0"
custom_viewport_x = "0"
custom_viewport_y = "0"
desktop_menu_enable = "true"
discord_allow = "false"
driver_switch_enable = "true"
dynamic_wallpapers_directory = "default"
enable_device_vibration = "false"
fastforward_frameskip = "false"
fastforward_ratio = "0.000000"
filter_by_current_core = "false"
flicker_filter_enable = "false"
flicker_filter_index = "0"
fps_show = "false"
fps_update_interval = "256"
frame_time_counter_reset_after_fastforwarding = "false"
frame_time_counter_reset_after_load_state = "false"
frame_time_counter_reset_after_save_state = "false"
framecount_show = "false"
frontend_log_level = "1"
game_specific_options = "true"
gamemode_enable = "true"
gamma_correction = "0"
global_core_options = "false"
history_list_enable = "false"
initial_disk_change_enable = "false"
input_ai_service = "nul"
input_ai_service_axis = "nul"
input_ai_service_btn = "nul"
input_ai_service_mbtn = "nul"
input_allow_turbo_dpad = "false"
input_analog_deadzone = "0.000000"
input_analog_sensitivity = "1.000000"
input_audio_mute = "f9"
input_audio_mute_axis = "nul"
input_audio_mute_btn = "nul"
input_audio_mute_mbtn = "nul"
input_auto_game_focus = "0"
input_auto_mouse_grab = "false"
input_autodetect_enable = "true"
input_axis_threshold = "0.500000"
input_bind_hold = "0"
input_bind_timeout = "3"
input_cheat_index_minus = "t"
input_cheat_index_minus_axis = "nul"
input_cheat_index_minus_btn = "nul"
input_cheat_index_minus_mbtn = "nul"
input_cheat_index_plus = "y"
input_cheat_index_plus_axis = "nul"
input_cheat_index_plus_btn = "nul"
input_cheat_index_plus_mbtn = "nul"
input_cheat_toggle = "u"
input_cheat_toggle_axis = "nul"
input_cheat_toggle_btn = "nul"
input_cheat_toggle_mbtn = "nul"
input_close_content = "nul"
input_close_content_axis = "nul"
input_close_content_btn = "nul"
input_close_content_mbtn = "nul"
input_descriptor_hide_unbound = "false"
input_descriptor_label_show = "true"
input_desktop_menu_toggle = "f5"
input_desktop_menu_toggle_axis = "nul"
input_desktop_menu_toggle_btn = "nul"
input_desktop_menu_toggle_mbtn = "nul"
input_device_p1 = "0"
input_device_p2 = "0"
input_device_p3 = "0"
input_device_p4 = "0"
input_disk_eject_toggle = "nul"
input_disk_eject_toggle_axis = "nul"
input_disk_eject_toggle_btn = "nul"
input_disk_eject_toggle_mbtn = "nul"
input_disk_next = "nul"
input_disk_next_axis = "nul"
input_disk_next_btn = "nul"
input_disk_next_mbtn = "nul"
input_disk_prev = "nul"
input_disk_prev_axis = "nul"
input_disk_prev_btn = "nul"
input_disk_prev_mbtn = "nul"
input_driver = "ps2"
input_duty_cycle = "3"
input_enable_hotkey = "nul"
input_enable_hotkey_axis = "nul"
input_enable_hotkey_btn = "nul"
input_enable_hotkey_mbtn = "nul"
input_exit_emulator = "escape"
input_exit_emulator_axis = "nul"
input_exit_emulator_btn = "nul"
input_exit_emulator_mbtn = "nul"
input_fps_toggle = "f3"
input_fps_toggle_axis = "nul"
input_fps_toggle_btn = "nul"
input_fps_toggle_mbtn = "nul"
input_frame_advance = "k"
input_frame_advance_axis = "nul"
input_frame_advance_btn = "nul"
input_frame_advance_mbtn = "nul"
input_game_focus_toggle = "scroll_lock"
input_game_focus_toggle_axis = "nul"
input_game_focus_toggle_btn = "nul"
input_game_focus_toggle_mbtn = "nul"
input_grab_mouse_toggle = "f11"
input_grab_mouse_toggle_axis = "nul"
input_grab_mouse_toggle_btn = "nul"
input_grab_mouse_toggle_mbtn = "nul"
input_halt_replay = "nul"
input_halt_replay_axis = "nul"
input_halt_replay_btn = "nul"
input_halt_replay_mbtn = "nul"
input_hold_fast_forward = "l"
input_hold_fast_forward_axis = "nul"
input_hold_fast_forward_btn = "nul"
input_hold_fast_forward_mbtn = "nul"
input_hold_slowmotion = "e"
input_hold_slowmotion_axis = "nul"
input_hold_slowmotion_btn = "nul"
input_hold_slowmotion_mbtn = "nul"
input_hotkey_block_delay = "5"
input_hotkey_device_merge = "false"
input_joypad_driver = "ps2"
input_keyboard_layout = ""
input_load_state = "f4"
input_load_state_axis = "nul"
input_load_state_btn = "nul"
input_load_state_mbtn = "nul"
input_max_users = "4"
input_menu_toggle = "f1"
input_menu_toggle_axis = "nul"
input_menu_toggle_btn = "nul"
input_menu_toggle_gamepad_combo = "10"
input_menu_toggle_mbtn = "nul"
input_netplay_fade_chat_toggle = "nul"
input_netplay_fade_chat_toggle_axis = "nul"
input_netplay_fade_chat_toggle_btn = "nul"
input_netplay_fade_chat_toggle_mbtn = "nul"
input_netplay_game_watch = "i"
input_netplay_game_watch_axis = "nul"
input_netplay_game_watch_btn = "nul"
input_netplay_game_watch_mbtn = "nul"
input_netplay_host_toggle = "nul"
input_netplay_host_toggle_axis = "nul"
input_netplay_host_toggle_btn = "nul"
input_netplay_host_toggle_mbtn = "nul"
input_netplay_ping_toggle = "nul"
input_netplay_ping_toggle_axis = "nul"
input_netplay_ping_toggle_btn = "nul"
input_netplay_ping_toggle_mbtn = "nul"
input_netplay_player_chat = "tilde"
input_netplay_player_chat_axis = "nul"
input_netplay_player_chat_btn = "nul"
input_netplay_player_chat_mbtn = "nul"
input_osk_toggle = "nul"
input_osk_toggle_axis = "nul"
input_osk_toggle_btn = "nul"
input_osk_toggle_mbtn = "nul"
input_overlay_next = "nul"
input_overlay_next_axis = "nul"
input_overlay_next_btn = "nul"
input_overlay_next_mbtn = "nul"
input_pause_toggle = "p"
input_pause_toggle_axis = "nul"
input_pause_toggle_btn = "nul"
input_pause_toggle_mbtn = "nul"
input_play_replay = "nul"
input_play_replay_axis = "nul"
input_play_replay_btn = "nul"
input_play_replay_mbtn = "nul"
input_player1_a = "x"
input_player1_a_axis = "nul"
input_player1_a_btn = "nul"
input_player1_a_mbtn = "nul"
input_player1_analog_dpad_mode = "0"
input_player1_b = "z"
input_player1_b_axis = "nul"
input_player1_b_btn = "nul"
input_player1_b_mbtn = "nul"
input_player1_device_reservation_type = "0"
input_player1_down = "down"
input_player1_down_axis = "nul"
input_player1_down_btn = "nul"
input_player1_down_mbtn = "nul"
input_player1_gun_aux_a = "nul"
input_player1_gun_aux_a_axis = "nul"
input_player1_gun_aux_a_btn = "nul"
input_player1_gun_aux_a_mbtn = "nul"
input_player1_gun_aux_b = "nul"
input_player1_gun_aux_b_axis = "nul"
input_player1_gun_aux_b_btn = "nul"
input_player1_gun_aux_b_mbtn = "nul"
input_player1_gun_aux_c = "nul"
input_player1_gun_aux_c_axis = "nul"
input_player1_gun_aux_c_btn = "nul"
input_player1_gun_aux_c_mbtn = "nul"
input_player1_gun_dpad_down = "nul"
input_player1_gun_dpad_down_axis = "nul"
input_player1_gun_dpad_down_btn = "nul"
input_player1_gun_dpad_down_mbtn = "nul"
input_player1_gun_dpad_left = "nul"
input_player1_gun_dpad_left_axis = "nul"
input_player1_gun_dpad_left_btn = "nul"
input_player1_gun_dpad_left_mbtn = "nul"
input_player1_gun_dpad_right = "nul"
input_player1_gun_dpad_right_axis = "nul"
input_player1_gun_dpad_right_btn = "nul"
input_player1_gun_dpad_right_mbtn = "nul"
input_player1_gun_dpad_up = "nul"
input_player1_gun_dpad_up_axis = "nul"
input_player1_gun_dpad_up_btn = "nul"
input_player1_gun_dpad_up_mbtn = "nul"
input_player1_gun_offscreen_shot = "nul"
input_player1_gun_offscreen_shot_axis = "nul"
input_player1_gun_offscreen_shot_btn = "nul"
input_player1_gun_offscreen_shot_mbtn = "2"
input_player1_gun_select = "nul"
input_player1_gun_select_axis = "nul"
input_player1_gun_select_btn = "nul"
input_player1_gun_select_mbtn = "nul"
input_player1_gun_start = "nul"
input_player1_gun_start_axis = "nul"
input_player1_gun_start_btn = "nul"
input_player1_gun_start_mbtn = "nul"
input_player1_gun_trigger = "nul"
input_player1_gun_trigger_axis = "nul"
input_player1_gun_trigger_btn = "nul"
input_player1_gun_trigger_mbtn = "1"
input_player1_joypad_index = "0"
input_player1_l = "q"
input_player1_l2 = "nul"
input_player1_l2_axis = "nul"
input_player1_l2_btn = "nul"
input_player1_l2_mbtn = "nul"
input_player1_l3 = "nul"
input_player1_l3_axis = "nul"
input_player1_l3_btn = "nul"
input_player1_l3_mbtn = "nul"
input_player1_l_axis = "nul"
input_player1_l_btn = "nul"
input_player1_l_mbtn = "nul"
input_player1_l_x_minus = "nul"
input_player1_l_x_minus_axis = "nul"
input_player1_l_x_minus_btn = "nul"
input_player1_l_x_minus_mbtn = "nul"
input_player1_l_x_plus = "nul"
input_player1_l_x_plus_axis = "nul"
input_player1_l_x_plus_btn = "nul"
input_player1_l_x_plus_mbtn = "nul"
input_player1_l_y_minus = "nul"
input_player1_l_y_minus_axis = "nul"
input_player1_l_y_minus_btn = "nul"
input_player1_l_y_minus_mbtn = "nul"
input_player1_l_y_plus = "nul"
input_player1_l_y_plus_axis = "nul"
input_player1_l_y_plus_btn = "nul"
input_player1_l_y_plus_mbtn = "nul"
input_player1_left = "left"
input_player1_left_axis = "nul"
input_player1_left_btn = "nul"
input_player1_left_mbtn = "nul"
input_player1_mouse_index = "0"
input_player1_r = "w"
input_player1_r2 = "nul"
input_player1_r2_axis = "nul"
input_player1_r2_btn = "nul"
input_player1_r2_mbtn = "nul"
input_player1_r3 = "nul"
input_player1_r3_axis = "nul"
input_player1_r3_btn = "nul"
input_player1_r3_mbtn = "nul"
input_player1_r_axis = "nul"
input_player1_r_btn = "nul"
input_player1_r_mbtn = "nul"
input_player1_r_x_minus = "nul"
input_player1_r_x_minus_axis = "nul"
input_player1_r_x_minus_btn = "nul"
input_player1_r_x_minus_mbtn = "nul"
input_player1_r_x_plus = "nul"
input_player1_r_x_plus_axis = "nul"
input_player1_r_x_plus_btn = "nul"
input_player1_r_x_plus_mbtn = "nul"
input_player1_r_y_minus = "nul"
input_player1_r_y_minus_axis = "nul"
input_player1_r_y_minus_btn = "nul"
input_player1_r_y_minus_mbtn = "nul"
input_player1_r_y_plus = "nul"
input_player1_r_y_plus_axis = "nul"
input_player1_r_y_plus_btn = "nul"
input_player1_r_y_plus_mbtn = "nul"
input_player1_reserved_device = ""
input_player1_right = "right"
input_player1_right_axis = "nul"
input_player1_right_btn = "nul"
input_player1_right_mbtn = "nul"
input_player1_select = "rshift"
input_player1_select_axis = "nul"
input_player1_select_btn = "nul"
input_player1_select_mbtn = "nul"
input_player1_start = "enter"
input_player1_start_axis = "nul"
input_player1_start_btn = "nul"
input_player1_start_mbtn = "nul"
input_player1_turbo = "nul"
input_player1_turbo_axis = "nul"
input_player1_turbo_btn = "nul"
input_player1_turbo_mbtn = "nul"
input_player1_up = "up"
input_player1_up_axis = "nul"
input_player1_up_btn = "nul"
input_player1_up_mbtn = "nul"
input_player1_x = "s"
input_player1_x_axis = "nul"
input_player1_x_btn = "nul"
input_player1_x_mbtn = "nul"
input_player1_y = "a"
input_player1_y_axis = "nul"
input_player1_y_btn = "nul"
input_player1_y_mbtn = "nul"
input_player2_a = "nul"
input_player2_a_axis = "nul"
input_player2_a_btn = "nul"
input_player2_a_mbtn = "nul"
input_player2_analog_dpad_mode = "0"
input_player2_b = "nul"
input_player2_b_axis = "nul"
input_player2_b_btn = "nul"
input_player2_b_mbtn = "nul"
input_player2_device_reservation_type = "0"
input_player2_down = "nul"
input_player2_down_axis = "nul"
input_player2_down_btn = "nul"
input_player2_down_mbtn = "nul"
input_player2_gun_aux_a = "nul"
input_player2_gun_aux_a_axis = "nul"
input_player2_gun_aux_a_btn = "nul"
input_player2_gun_aux_a_mbtn = "nul"
input_player2_gun_aux_b = "nul"
input_player2_gun_aux_b_axis = "nul"
input_player2_gun_aux_b_btn = "nul"
input_player2_gun_aux_b_mbtn = "nul"
input_player2_gun_aux_c = "nul"
input_player2_gun_aux_c_axis = "nul"
input_player2_gun_aux_c_btn = "nul"
input_player2_gun_aux_c_mbtn = "nul"
input_player2_gun_dpad_down = "nul"
input_player2_gun_dpad_down_axis = "nul"
input_player2_gun_dpad_down_btn = "nul"
input_player2_gun_dpad_down_mbtn = "nul"
input_player2_gun_dpad_left = "nul"
input_player2_gun_dpad_left_axis = "nul"
input_player2_gun_dpad_left_btn = "nul"
input_player2_gun_dpad_left_mbtn = "nul"
input_player2_gun_dpad_right = "nul"
input_player2_gun_dpad_right_axis = "nul"
input_player2_gun_dpad_right_btn = "nul"
input_player2_gun_dpad_right_mbtn = "nul"
input_player2_gun_dpad_up = "nul"
input_player2_gun_dpad_up_axis = "nul"
input_player2_gun_dpad_up_btn = "nul"
input_player2_gun_dpad_up_mbtn = "nul"
input_player2_gun_offscreen_shot = "nul"
input_player2_gun_offscreen_shot_axis = "nul"
input_player2_gun_offscreen_shot_btn = "nul"
input_player2_gun_offscreen_shot_mbtn = "2"
input_player2_gun_select = "nul"
input_player2_gun_select_axis = "nul"
input_player2_gun_select_btn = "nul"
input_player2_gun_select_mbtn = "nul"
input_player2_gun_start = "nul"
input_player2_gun_start_axis = "nul"
input_player2_gun_start_btn = "nul"
input_player2_gun_start_mbtn = "nul"
input_player2_gun_trigger = "nul"
input_player2_gun_trigger_axis = "nul"
input_player2_gun_trigger_btn = "nul"
input_player2_gun_trigger_mbtn = "1"
input_player2_joypad_index = "1"
input_player2_l = "nul"
input_player2_l2 = "nul"
input_player2_l2_axis = "nul"
input_player2_l2_btn = "nul"
input_player2_l2_mbtn = "nul"
input_player2_l3 = "nul"
input_player2_l3_axis = "nul"
input_player2_l3_btn = "nul"
input_player2_l3_mbtn = "nul"
input_player2_l_axis = "nul"
input_player2_l_btn = "nul"
input_player2_l_mbtn = "nul"
input_player2_l_x_minus = "nul"
input_player2_l_x_minus_axis = "nul"
input_player2_l_x_minus_btn = "nul"
input_player2_l_x_minus_mbtn = "nul"
input_player2_l_x_plus = "nul"
input_player2_l_x_plus_axis = "nul"
input_player2_l_x_plus_btn = "nul"
input_player2_l_x_plus_mbtn = "nul"
input_player2_l_y_minus = "nul"
input_player2_l_y_minus_axis = "nul"
input_player2_l_y_minus_btn = "nul"
input_player2_l_y_minus_mbtn = "nul"
input_player2_l_y_plus = "nul"
input_player2_l_y_plus_axis = "nul"
input_player2_l_y_plus_btn = "nul"
input_player2_l_y_plus_mbtn = "nul"
input_player2_left = "nul"
input_player2_left_axis = "nul"
input_player2_left_btn = "nul"
input_player2_left_mbtn = "nul"
input_player2_mouse_index = "1"
input_player2_r = "nul"
input_player2_r2 = "nul"
input_player2_r2_axis = "nul"
input_player2_r2_btn = "nul"
input_player2_r2_mbtn = "nul"
input_player2_r3 = "nul"
input_player2_r3_axis = "nul"
input_player2_r3_btn = "nul"
input_player2_r3_mbtn = "nul"
input_player2_r_axis = "nul"
input_player2_r_btn = "nul"
input_player2_r_mbtn = "nul"
input_player2_r_x_minus = "nul"
input_player2_r_x_minus_axis = "nul"
input_player2_r_x_minus_btn = "nul"
input_player2_r_x_minus_mbtn = "nul"
input_player2_r_x_plus = "nul"
input_player2_r_x_plus_axis = "nul"
input_player2_r_x_plus_btn = "nul"
input_player2_r_x_plus_mbtn = "nul"
input_player2_r_y_minus = "nul"
input_player2_r_y_minus_axis = "nul"
input_player2_r_y_minus_btn = "nul"
input_player2_r_y_minus_mbtn = "nul"
input_player2_r_y_plus = "nul"
input_player2_r_y_plus_axis = "nul"
input_player2_r_y_plus_btn = "nul"
input_player2_r_y_plus_mbtn = "nul"
input_player2_reserved_device = ""
input_player2_right = "nul"
input_player2_right_axis = "nul"
input_player2_right_btn = "nul"
input_player2_right_mbtn = "nul"
input_player2_select = "nul"
input_player2_select_axis = "nul"
input_player2_select_btn = "nul"
input_player2_select_mbtn = "nul"
input_player2_start = "nul"
input_player2_start_axis = "nul"
input_player2_start_btn = "nul"
input_player2_start_mbtn = "nul"
input_player2_turbo = "nul"
input_player2_turbo_axis = "nul"
input_player2_turbo_btn = "nul"
input_player2_turbo_mbtn = "nul"
input_player2_up = "nul"
input_player2_up_axis = "nul"
input_player2_up_btn = "nul"
input_player2_up_mbtn = "nul"
input_player2_x = "nul"
input_player2_x_axis = "nul"
input_player2_x_btn = "nul"
input_player2_x_mbtn = "nul"
input_player2_y = "nul"
input_player2_y_axis = "nul"
input_player2_y_btn = "nul"
input_player2_y_mbtn = "nul"
input_player3_a = "nul"
input_player3_a_axis = "nul"
input_player3_a_btn = "nul"
input_player3_a_mbtn = "nul"
input_player3_analog_dpad_mode = "0"
input_player3_b = "nul"
input_player3_b_axis = "nul"
input_player3_b_btn = "nul"
input_player3_b_mbtn = "nul"
input_player3_device_reservation_type = "0"
input_player3_down = "nul"
input_player3_down_axis = "nul"
input_player3_down_btn = "nul"
input_player3_down_mbtn = "nul"
input_player3_gun_aux_a = "nul"
input_player3_gun_aux_a_axis = "nul"
input_player3_gun_aux_a_btn = "nul"
input_player3_gun_aux_a_mbtn = "nul"
input_player3_gun_aux_b = "nul"
input_player3_gun_aux_b_axis = "nul"
input_player3_gun_aux_b_btn = "nul"
input_player3_gun_aux_b_mbtn = "nul"
input_player3_gun_aux_c = "nul"
input_player3_gun_aux_c_axis = "nul"
input_player3_gun_aux_c_btn = "nul"
input_player3_gun_aux_c_mbtn = "nul"
input_player3_gun_dpad_down = "nul"
input_player3_gun_dpad_down_axis = "nul"
input_player3_gun_dpad_down_btn = "nul"
input_player3_gun_dpad_down_mbtn = "nul"
input_player3_gun_dpad_left = "nul"
input_player3_gun_dpad_left_axis = "nul"
input_player3_gun_dpad_left_btn = "nul"
input_player3_gun_dpad_left_mbtn = "nul"
input_player3_gun_dpad_right = "nul"
input_player3_gun_dpad_right_axis = "nul"
input_player3_gun_dpad_right_btn = "nul"
input_player3_gun_dpad_right_mbtn = "nul"
input_player3_gun_dpad_up = "nul"
input_player3_gun_dpad_up_axis = "nul"
input_player3_gun_dpad_up_btn = "nul"
input_player3_gun_dpad_up_mbtn = "nul"
input_player3_gun_offscreen_shot = "nul"
input_player3_gun_offscreen_shot_axis = "nul"
input_player3_gun_offscreen_shot_btn = "nul"
input_player3_gun_offscreen_shot_mbtn = "2"
input_player3_gun_select = "nul"
input_player3_gun_select_axis = "nul"
input_player3_gun_select_btn = "nul"
input_player3_gun_select_mbtn = "nul"
input_player3_gun_start = "nul"
input_player3_gun_start_axis = "nul"
input_player3_gun_start_btn = "nul"
input_player3_gun_start_mbtn = "nul"
input_player3_gun_trigger = "nul"
input_player3_gun_trigger_axis = "nul"
input_player3_gun_trigger_btn = "nul"
input_player3_gun_trigger_mbtn = "1"
input_player3_joypad_index = "2"
input_player3_l = "nul"
input_player3_l2 = "nul"
input_player3_l2_axis = "nul"
input_player3_l2_btn = "nul"
input_player3_l2_mbtn = "nul"
input_player3_l3 = "nul"
input_player3_l3_axis = "nul"
input_player3_l3_btn = "nul"
input_player3_l3_mbtn = "nul"
input_player3_l_axis = "nul"
input_player3_l_btn = "nul"
input_player3_l_mbtn = "nul"
input_player3_l_x_minus = "nul"
input_player3_l_x_minus_axis = "nul"
input_player3_l_x_minus_btn = "nul"
input_player3_l_x_minus_mbtn = "nul"
input_player3_l_x_plus = "nul"
input_player3_l_x_plus_axis = "nul"
input_player3_l_x_plus_btn = "nul"
input_player3_l_x_plus_mbtn = "nul"
input_player3_l_y_minus = "nul"
input_player3_l_y_minus_axis = "nul"
input_player3_l_y_minus_btn = "nul"
input_player3_l_y_minus_mbtn = "nul"
input_player3_l_y_plus = "nul"
input_player3_l_y_plus_axis = "nul"
input_player3_l_y_plus_btn = "nul"
input_player3_l_y_plus_mbtn = "nul"
input_player3_left = "nul"
input_player3_left_axis = "nul"
input_player3_left_btn = "nul"
input_player3_left_mbtn = "nul"
input_player3_mouse_index = "2"
input_player3_r = "nul"
input_player3_r2 = "nul"
input_player3_r2_axis = "nul"
input_player3_r2_btn = "nul"
input_player3_r2_mbtn = "nul"
input_player3_r3 = "nul"
input_player3_r3_axis = "nul"
input_player3_r3_btn = "nul"
input_player3_r3_mbtn = "nul"
input_player3_r_axis = "nul"
input_player3_r_btn = "nul"
input_player3_r_mbtn = "nul"
input_player3_r_x_minus = "nul"
input_player3_r_x_minus_axis = "nul"
input_player3_r_x_minus_btn = "nul"
input_player3_r_x_minus_mbtn = "nul"
input_player3_r_x_plus = "nul"
input_player3_r_x_plus_axis = "nul"
input_player3_r_x_plus_btn = "nul"
input_player3_r_x_plus_mbtn = "nul"
input_player3_r_y_minus = "nul"
input_player3_r_y_minus_axis = "nul"
input_player3_r_y_minus_btn = "nul"
input_player3_r_y_minus_mbtn = "nul"
input_player3_r_y_plus = "nul"
input_player3_r_y_plus_axis = "nul"
input_player3_r_y_plus_btn = "nul"
input_player3_r_y_plus_mbtn = "nul"
input_player3_reserved_device = ""
input_player3_right = "nul"
input_player3_right_axis = "nul"
input_player3_right_btn = "nul"
input_player3_right_mbtn = "nul"
input_player3_select = "nul"
input_player3_select_axis = "nul"
input_player3_select_btn = "nul"
input_player3_select_mbtn = "nul"
input_player3_start = "nul"
input_player3_start_axis = "nul"
input_player3_start_btn = "nul"
input_player3_start_mbtn = "nul"
input_player3_turbo = "nul"
input_player3_turbo_axis = "nul"
input_player3_turbo_btn = "nul"
input_player3_turbo_mbtn = "nul"
input_player3_up = "nul"
input_player3_up_axis = "nul"
input_player3_up_btn = "nul"
input_player3_up_mbtn = "nul"
input_player3_x = "nul"
input_player3_x_axis = "nul"
input_player3_x_btn = "nul"
input_player3_x_mbtn = "nul"
input_player3_y = "nul"
input_player3_y_axis = "nul"
input_player3_y_btn = "nul"
input_player3_y_mbtn = "nul"
input_player4_a = "nul"
input_player4_a_axis = "nul"
input_player4_a_btn = "nul"
input_player4_a_mbtn = "nul"
input_player4_analog_dpad_mode = "0"
input_player4_b = "nul"
input_player4_b_axis = "nul"
input_player4_b_btn = "nul"
input_player4_b_mbtn = "nul"
input_player4_device_reservation_type = "0"
input_player4_down = "nul"
input_player4_down_axis = "nul"
input_player4_down_btn = "nul"
input_player4_down_mbtn = "nul"
input_player4_gun_aux_a = "nul"
input_player4_gun_aux_a_axis = "nul"
input_player4_gun_aux_a_btn = "nul"
input_player4_gun_aux_a_mbtn = "nul"
input_player4_gun_aux_b = "nul"
input_player4_gun_aux_b_axis = "nul"
input_player4_gun_aux_b_btn = "nul"
input_player4_gun_aux_b_mbtn = "nul"
input_player4_gun_aux_c = "nul"
input_player4_gun_aux_c_axis = "nul"
input_player4_gun_aux_c_btn = "nul"
input_player4_gun_aux_c_mbtn = "nul"
input_player4_gun_dpad_down = "nul"
input_player4_gun_dpad_down_axis = "nul"
input_player4_gun_dpad_down_btn = "nul"
input_player4_gun_dpad_down_mbtn = "nul"
input_player4_gun_dpad_left = "nul"
input_player4_gun_dpad_left_axis = "nul"
input_player4_gun_dpad_left_btn = "nul"
input_player4_gun_dpad_left_mbtn = "nul"
input_player4_gun_dpad_right = "nul"
input_player4_gun_dpad_right_axis = "nul"
input_player4_gun_dpad_right_btn = "nul"
input_player4_gun_dpad_right_mbtn = "nul"
input_player4_gun_dpad_up = "nul"
input_player4_gun_dpad_up_axis = "nul"
input_player4_gun_dpad_up_btn = "nul"
input_player4_gun_dpad_up_mbtn = "nul"
input_player4_gun_offscreen_shot = "nul"
input_player4_gun_offscreen_shot_axis = "nul"
input_player4_gun_offscreen_shot_btn = "nul"
input_player4_gun_offscreen_shot_mbtn = "2"
input_player4_gun_select = "nul"
input_player4_gun_select_axis = "nul"
input_player4_gun_select_btn = "nul"
input_player4_gun_select_mbtn = "nul"
input_player4_gun_start = "nul"
input_player4_gun_start_axis = "nul"
input_player4_gun_start_btn = "nul"
input_player4_gun_start_mbtn = "nul"
input_player4_gun_trigger = "nul"
input_player4_gun_trigger_axis = "nul"
input_player4_gun_trigger_btn = "nul"
input_player4_gun_trigger_mbtn = "1"
input_player4_joypad_index = "3"
input_player4_l = "nul"
input_player4_l2 = "nul"
input_player4_l2_axis = "nul"
input_player4_l2_btn = "nul"
input_player4_l2_mbtn = "nul"
input_player4_l3 = "nul"
input_player4_l3_axis = "nul"
input_player4_l3_btn = "nul"
input_player4_l3_mbtn = "nul"
input_player4_l_axis = "nul"
input_player4_l_btn = "nul"
input_player4_l_mbtn = "nul"
input_player4_l_x_minus = "nul"
input_player4_l_x_minus_axis = "nul"
input_player4_l_x_minus_btn = "nul"
input_player4_l_x_minus_mbtn = "nul"
input_player4_l_x_plus = "nul"
input_player4_l_x_plus_axis = "nul"
input_player4_l_x_plus_btn = "nul"
input_player4_l_x_plus_mbtn = "nul"
input_player4_l_y_minus = "nul"
input_player4_l_y_minus_axis = "nul"
input_player4_l_y_minus_btn = "nul"
input_player4_l_y_minus_mbtn = "nul"
input_player4_l_y_plus = "nul"
input_player4_l_y_plus_axis = "nul"
input_player4_l_y_plus_btn = "nul"
input_player4_l_y_plus_mbtn = "nul"
input_player4_left = "nul"
input_player4_left_axis = "nul"
input_player4_left_btn = "nul"
input_player4_left_mbtn = "nul"
input_player4_mouse_index = "3"
input_player4_r = "nul"
input_player4_r2 = "nul"
input_player4_r2_axis = "nul"
input_player4_r2_btn = "nul"
input_player4_r2_mbtn = "nul"
input_player4_r3 = "nul"
input_player4_r3_axis = "nul"
input_player4_r3_btn = "nul"
input_player4_r3_mbtn = "nul"
input_player4_r_axis = "nul"
input_player4_r_btn = "nul"
input_player4_r_mbtn = "nul"
input_player4_r_x_minus = "nul"
input_player4_r_x_minus_axis = "nul"
input_player4_r_x_minus_btn = "nul"
input_player4_r_x_minus_mbtn = "nul"
input_player4_r_x_plus = "nul"
input_player4_r_x_plus_axis = "nul"
input_player4_r_x_plus_btn = "nul"
input_player4_r_x_plus_mbtn = "nul"
input_player4_r_y_minus = "nul"
input_player4_r_y_minus_axis = "nul"
input_player4_r_y_minus_btn = "nul"
input_player4_r_y_minus_mbtn = "nul"
input_player4_r_y_plus = "nul"
input_player4_r_y_plus_axis = "nul"
input_player4_r_y_plus_btn = "nul"
input_player4_r_y_plus_mbtn = "nul"
input_player4_reserved_device = ""
input_player4_right = "nul"
input_player4_right_axis = "nul"
input_player4_right_btn = "nul"
input_player4_right_mbtn = "nul"
input_player4_select = "nul"
input_player4_select_axis = "nul"
input_player4_select_btn = "nul"
input_player4_select_mbtn = "nul"
input_player4_start = "nul"
input_player4_start_axis = "nul"
input_player4_start_btn = "nul"
input_player4_start_mbtn = "nul"
input_player4_turbo = "nul"
input_player4_turbo_axis = "nul"
input_player4_turbo_btn = "nul"
input_player4_turbo_mbtn = "nul"
input_player4_up = "nul"
input_player4_up_axis = "nul"
input_player4_up_btn = "nul"
input_player4_up_mbtn = "nul"
input_player4_x = "nul"
input_player4_x_axis = "nul"
input_player4_x_btn = "nul"
input_player4_x_mbtn = "nul"
input_player4_y = "nul"
input_player4_y_axis = "nul"
input_player4_y_btn = "nul"
input_player4_y_mbtn = "nul"
input_poll_type_behavior = "2"
input_preempt_toggle = "nul"
input_preempt_toggle_axis = "nul"
input_preempt_toggle_btn = "nul"
input_preempt_toggle_mbtn = "nul"
input_quit_gamepad_combo = "0"
input_record_replay = "nul"
input_record_replay_axis = "nul"
input_record_replay_btn = "nul"
input_record_replay_mbtn = "nul"
input_recording_toggle = "nul"
input_recording_toggle_axis = "nul"
input_recording_toggle_btn = "nul"
input_recording_toggle_mbtn = "nul"
input_remap_binds_enable = "true"
input_remap_sort_by_controller_enable = "false"
input_remapping_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/config/remaps"
input_replay_slot_decrease = "nul"
input_replay_slot_decrease_axis = "nul"
input_replay_slot_decrease_btn = "nul"
input_replay_slot_decrease_mbtn = "nul"
input_replay_slot_increase = "nul"
input_replay_slot_increase_axis = "nul"
input_replay_slot_increase_btn = "nul"
input_replay_slot_increase_mbtn = "nul"
input_reset = "h"
input_reset_axis = "nul"
input_reset_btn = "nul"
input_reset_mbtn = "nul"
input_rewind = "r"
input_rewind_axis = "nul"
input_rewind_btn = "nul"
input_rewind_mbtn = "nul"
input_rumble_gain = "100"
input_runahead_toggle = "nul"
input_runahead_toggle_axis = "nul"
input_runahead_toggle_btn = "nul"
input_runahead_toggle_mbtn = "nul"
input_save_state = "f2"
input_save_state_axis = "nul"
input_save_state_btn = "nul"
input_save_state_mbtn = "nul"
input_screenshot = "f8"
input_screenshot_axis = "nul"
input_screenshot_btn = "nul"
input_screenshot_mbtn = "nul"
input_sensors_enable = "true"
input_shader_next = "m"
input_shader_next_axis = "nul"
input_shader_next_btn = "nul"
input_shader_next_mbtn = "nul"
input_shader_prev = "n"
input_shader_prev_axis = "nul"
input_shader_prev_btn = "nul"
input_shader_prev_mbtn = "nul"
input_shader_toggle = "comma"
input_shader_toggle_axis = "nul"
input_shader_toggle_btn = "nul"
input_shader_toggle_mbtn = "nul"
input_state_slot_decrease = "f6"
input_state_slot_decrease_axis = "nul"
input_state_slot_decrease_btn = "nul"
input_state_slot_decrease_mbtn = "nul"
input_state_slot_increase = "f7"
input_state_slot_increase_axis = "nul"
input_state_slot_increase_btn = "nul"
input_state_slot_increase_mbtn = "nul"
input_streaming_toggle = "nul"
input_streaming_toggle_axis = "nul"
input_streaming_toggle_btn = "nul"
input_streaming_toggle_mbtn = "nul"
input_toggle_fast_forward = "space"
input_toggle_fast_forward_axis = "nul"
input_toggle_fast_forward_btn = "nul"
input_toggle_fast_forward_mbtn = "nul"
input_toggle_fullscreen = "f"
input_toggle_fullscreen_axis = "nul"
input_toggle_fullscreen_btn = "nul"
input_toggle_fullscreen_mbtn = "nul"
input_toggle_slowmotion = "nul"
input_toggle_slowmotion_axis = "nul"
input_toggle_slowmotion_btn = "nul"
input_toggle_slowmotion_mbtn = "nul"
input_toggle_statistics = "nul"
input_toggle_statistics_axis = "nul"
input_toggle_statistics_btn = "nul"
input_toggle_statistics_mbtn = "nul"
input_toggle_vrr_runloop = "nul"
input_toggle_vrr_runloop_axis = "nul"
input_toggle_vrr_runloop_btn = "nul"
input_toggle_vrr_runloop_mbtn = "nul"
input_touch_scale = "1"
input_turbo_default_button = "0"
input_turbo_mode = "0"
input_turbo_period = "6"
input_volume_down = "subtract"
input_volume_down_axis = "nul"
input_volume_down_btn = "nul"
input_volume_down_mbtn = "nul"
input_volume_up = "add"
input_volume_up_axis = "nul"
input_volume_up_btn = "nul"
input_volume_up_mbtn = "nul"
joypad_autoconfig_dir = ""
keyboard_gamepad_enable = "true"
keyboard_gamepad_mapping_type = "1"
kiosk_mode_enable = "false"
kiosk_mode_password = ""
led_driver = "null"
libretro_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//cores"
libretro_info_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//info"
libretro_log_level = "1"
load_dummy_on_core_shutdown = "false"
location_allow = "false"
location_driver = "null"
log_dir = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/logs"
log_to_file = "false"
log_to_file_timestamp = "false"
log_verbosity = "false"
memory_show = "false"
memory_update_interval = "256"
menu_battery_level_enable = "false"
menu_core_enable = "true"
menu_disable_info_button = "true"
menu_disable_left_analog = "false"
menu_disable_right_analog = "true"
menu_disable_search_button = "true"
menu_driver = "rgui"
menu_dynamic_wallpaper_enable = "false"
menu_enable_widgets = "false"
menu_footer_opacity = "1.000000"
menu_framebuffer_opacity = "0.900000"
menu_header_opacity = "1.000000"
menu_horizontal_animation = "true"
menu_icon_thumbnails = "0"
menu_insert_disk_resume = "true"
menu_left_thumbnails = "0"
menu_linear_filter = "true"
menu_mouse_enable = "false"
menu_navigation_browser_filter_supported_extensions_enable = "true"
menu_navigation_wraparound_enable = "true"
menu_pause_libretro = "true"
menu_pointer_enable = "false"
menu_rgui_full_width_layout = "true"
menu_rgui_shadows = "false"
menu_rgui_transparency = "true"
menu_savestate_resume = "false"
menu_scale_factor = "1.000000"
menu_screensaver_timeout = "0"
menu_scroll_delay = "256"
menu_scroll_fast = "false"
menu_show_advanced_settings = "true"
menu_show_configurations = "false"
menu_show_core_updater = "false"
menu_show_help = "false"
menu_show_information = "false"
menu_show_latency = "false"
menu_show_load_content = "false"
menu_show_load_content_animation = "false"
menu_show_load_core = "false"
menu_show_online_updater = "false"
menu_show_overlays = "false"
menu_show_quit_retroarch = "false"
menu_show_reboot = "true"
menu_show_restart_retroarch = "true"
menu_show_rewind = "false"
menu_show_shutdown = "false"
menu_show_sublabels = "true"
menu_swap_ok_cancel_buttons = "true"
menu_swap_scroll_buttons = "false"
menu_throttle_framerate = "true"
menu_thumbnail_upscale_threshold = "0"
menu_thumbnails = "0"
menu_ticker_smooth = "true"
menu_ticker_speed = "2.000000"
menu_ticker_type = "1"
menu_timedate_date_separator = "0"
menu_timedate_enable = "false"
menu_timedate_style = "11"
menu_unified_controls = "false"
menu_use_preferred_system_color_theme = "false"
menu_wallpaper = ""
menu_wallpaper_opacity = "1.000000"
menu_widget_scale_auto = "true"
menu_widget_scale_factor = "1.000000"
midi_driver = "null"
midi_input = "OFF"
midi_output = "OFF"
midi_volume = "100"
notification_show_autoconfig = "false"
notification_show_cheats_applied = "false"
notification_show_config_override_load = "false"
notification_show_disk_control = "false"
notification_show_fast_forward = "true"
notification_show_patch_applied = "true"
notification_show_refresh_rate = "false"
notification_show_remap_load = "false"
notification_show_save_state = "true"
notification_show_screenshot = "false"
notification_show_screenshot_duration = "0"
notification_show_screenshot_flash = "0"
notification_show_set_initial_disk = "false"
notification_show_when_menu_is_alive = "true"
pause_nonactive = "true"
pause_on_disconnect = "false"
perfcnt_enable = "false"
playlist_allow_non_png = "false"
playlist_compression = "false"
playlist_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/playlists"
playlist_entry_remove_enable = "2"
playlist_entry_rename = "false"
playlist_fuzzy_archive_match = "false"
playlist_portable_paths = "false"
playlist_show_entry_idx = "false"
playlist_show_history_icons = "1"
playlist_show_inline_core_name = "2"
playlist_show_sublabels = "false"
playlist_sort_alphabetical = "true"
playlist_sublabel_last_played_style = "1"
playlist_sublabel_runtime_type = "0"
playlist_use_filename = "false"
playlist_use_old_format = "false"
preemptive_frames_enable = "false"
preemptive_frames_hide_warnings = "false"
quick_menu_show_add_to_favorites = "false"
quick_menu_show_add_to_playlist = "false"
quick_menu_show_cheats = "true"
quick_menu_show_close_content = "false"
quick_menu_show_controls = "true"
quick_menu_show_core_options_flush = "false"
quick_menu_show_information = "false"
quick_menu_show_options = "true"
quick_menu_show_replay = "false"
quick_menu_show_reset_core_association = "false"
quick_menu_show_restart_content = "true"
quick_menu_show_resume_content = "true"
quick_menu_show_save_content_dir_overrides = "false"
quick_menu_show_save_core_overrides = "false"
quick_menu_show_save_game_overrides = "false"
quick_menu_show_save_load_state = "true"
quick_menu_show_savestate_submenu = "true"
quick_menu_show_set_core_association = "false"
quick_menu_show_shaders = "false"
quick_menu_show_start_recording = "false"
quick_menu_show_start_streaming = "false"
quick_menu_show_take_screenshot = "false"
quick_menu_show_undo_save_load_state = "false"
quit_on_close_content = "0"
quit_press_twice = "false"
record_driver = "null"
recording_config_directory = ""
recording_output_directory = ""
remap_save_on_exit = "false"
replay_auto_index = "true"
replay_checkpoint_interval = "0"
replay_max_keep = "0"
replay_slot = "0"
resampler_directory = ""
rewind_buffer_size = "20971520"
rewind_buffer_size_step = "10"
rewind_enable = "false"
rewind_granularity = "1"
rgui_aspect_ratio = "11"
rgui_aspect_ratio_lock = "0"
rgui_background_filler_thickness_enable = "false"
rgui_border_filler_enable = "true"
rgui_border_filler_thickness_enable = "false"
rgui_browser_directory = "default"
rgui_config_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/config"
rgui_extended_ascii = "false"
rgui_inline_thumbnails = "false"
rgui_internal_upscale_level = "0"
rgui_menu_color_theme = "9"
rgui_menu_theme_preset = ""
rgui_particle_effect = "0"
rgui_particle_effect_screensaver = "true"
rgui_particle_effect_speed = "1.000000"
rgui_show_start_screen = "false"
rgui_swap_thumbnails = "false"
rgui_switch_icons = "true"
rgui_thumbnail_delay = "256"
rgui_thumbnail_downscaler = "0"
run_ahead_enabled = "false"
run_ahead_frames = "1"
run_ahead_hide_warnings = "false"
run_ahead_secondary_instance = "true"
runtime_log_directory = "default"
save_file_compression = "true"
savefile_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/savefiles"
savefiles_in_content_dir = "false"
savestate_auto_index = "false"
savestate_auto_load = "false"
savestate_auto_save = "false"
savestate_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/savestates"
savestate_file_compression = "true"
savestate_max_keep = "0"
savestate_thumbnail_enable = "false"
savestates_in_content_dir = "false"
scan_serial_and_crc = "false"
scan_without_core_match = "false"
screen_brightness = "100"
screen_orientation = "0"
screenshot_directory = "default"
screenshots_in_content_dir = "false"
settings_show_accessibility = "false"
settings_show_achievements = "false"
settings_show_ai_service = "false"
settings_show_audio = "false"
settings_show_configuration = "false"
settings_show_core = "false"
settings_show_directory = "false"
settings_show_drivers = "false"
settings_show_file_browser = "false"
settings_show_frame_throttle = "false"
settings_show_input = "false"
settings_show_latency = "false"
settings_show_logging = "false"
settings_show_network = "false"
settings_show_onscreen_display = "false"
settings_show_playlists = "false"
settings_show_power_management = "false"
settings_show_recording = "false"
settings_show_saving = "false"
settings_show_user = "false"
settings_show_user_interface = "true"
settings_show_video = "true"
show_hidden_files = "false"
slowmotion_ratio = "3.000000"
soft_filter_enable = "false"
soft_filter_index = "0"
sort_savefiles_by_content_enable = "false"
sort_savefiles_enable = "false"
sort_savestates_by_content_enable = "false"
sort_savestates_enable = "false"
sort_screenshots_by_content_enable = "false"
state_slot = "0"
statistics_show = "false"
suspend_screensaver_enable = "true"
sustained_performance_mode = "false"
system_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/system"
systemfiles_in_content_dir = "false"
thumbnails_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Super Famicom//retroarch/thumbnails"
ui_companion_enable = "false"
ui_companion_start_on_boot = "true"
ui_companion_toggle = "false"
ui_menubar_enable = "true"
use_last_start_directory = "false"
vibrate_on_keypress = "false"
video_adaptive_vsync = "false"
video_allow_rotate = "true"
video_aspect_ratio = "1.253300"
video_aspect_ratio_auto = "false"
video_autoswitch_pal_threshold = "54.500000"
video_autoswitch_refresh_rate = "0"
video_bfi_dark_frames = "1"
video_black_frame_insertion = "0"
video_context_driver = ""
video_crop_overscan = "true"
video_ctx_scaling = "false"
video_disable_composition = "false"
video_driver = "ps2"
video_filter = ""
video_filter_dir = "default"
video_font_enable = "true"
video_font_path = ""
video_font_size = "16.000000"
video_force_aspect = "true"
video_force_srgb_disable = "false"
video_frame_delay = "0"
video_frame_delay_auto = "false"
video_frame_rest = "false"
video_fullscreen = "false"
video_fullscreen_x = "0"
video_fullscreen_y = "0"
video_gpu_record = "false"
video_gpu_screenshot = "true"
video_hard_sync = "false"
video_hard_sync_frames = "0"
video_hdr_display_contrast = "5.000000"
video_hdr_enable = "false"
video_hdr_expand_gamut = "true"
video_hdr_max_nits = "1000.000000"
video_hdr_paper_white_nits = "200.000000"
video_max_frame_latency = "1"
video_max_swapchain_images = "3"
video_message_color = "f6f6f6"
video_message_pos_x = "0.050000"
video_message_pos_y = "0.050000"
video_monitor_index = "0"
video_msg_bgcolor_blue = "0"
video_msg_bgcolor_enable = "true"
video_msg_bgcolor_green = "0"
video_msg_bgcolor_opacity = "1.000000"
video_msg_bgcolor_red = "0"
video_notch_write_over_enable = "false"
video_post_filter_record = "false"
video_record_config = ""
video_record_quality = "2"
video_record_scale_factor = "1"
video_record_threads = "2"
video_refresh_rate = "54.500000"
video_rotation = "0"
video_scale = "3"
video_scale_integer = "false"
video_scale_integer_axis = "0"
video_scale_integer_overscale = "false"
video_scale_integer_scaling = "0"
video_scan_subframes = "false"
video_shader_delay = "0"
video_shader_dir = "default"
video_shader_enable = "true"
video_shader_preset_save_reference_enable = "true"
video_shader_remember_last_dir = "false"
video_shader_subframes = "1"
video_shader_watch_files = "false"
video_shared_context = "false"
video_smooth = "false"
video_stream_config = ""
video_stream_port = "56400"
video_stream_quality = "11"
video_stream_scale_factor = "1"
video_stream_url = ""
video_swap_interval = "1"
video_threaded = "false"
video_viewport_bias_x = "0.500000"
video_viewport_bias_y = "0.500000"
video_vsync = "false"
video_waitable_swapchains = "true"
video_window_auto_height_max = "1080"
video_window_auto_width_max = "1920"
video_window_custom_size_enable = "false"
video_window_offset_x = "0"
video_window_offset_y = "0"
video_window_opacity = "100"
video_window_save_positions = "false"
video_window_show_decorations = "true"
video_windowed_fullscreen = "true"
video_windowed_position_height = "720"
video_windowed_position_width = "1280"
video_windowed_position_x = "0"
video_windowed_position_y = "0"
vrr_runloop_enable = "true"
wifi_driver = "null"
wifi_enabled = "true"
xmb_font = ""
| 412 | 0.695493 | 1 | 0.695493 | game-dev | MEDIA | 0.554548 | game-dev,desktop-app | 0.824789 | 1 | 0.824789 |
beyond-aion/aion-server | 2,660 | game-server/data/handlers/quest/gelkmaros/_21075FatedHeartbreak.java | package quest.gelkmaros;
import static com.aionemu.gameserver.model.DialogAction.*;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.AbstractQuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
/**
* @author Cheatkiller
*/
public class _21075FatedHeartbreak extends AbstractQuestHandler {
public _21075FatedHeartbreak() {
super(21075);
}
@Override
public void register() {
qe.registerQuestNpc(799409).addOnQuestStart(questId);
qe.registerQuestNpc(799409).addOnTalkEvent(questId);
qe.registerQuestNpc(798392).addOnTalkEvent(questId);
qe.registerQuestNpc(799410).addOnTalkEvent(questId);
qe.registerQuestNpc(204138).addOnTalkEvent(questId);
}
@Override
public boolean onDialogEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
int dialogActionId = env.getDialogActionId();
int targetId = env.getTargetId();
if (qs == null || qs.isStartable()) {
if (targetId == 799409) {
if (dialogActionId == QUEST_SELECT) {
return sendQuestDialog(env, 4762);
} else {
return sendQuestStartDialog(env);
}
}
} else if (qs.getStatus() == QuestStatus.START) {
if (targetId == 798392) {
if (dialogActionId == QUEST_SELECT) {
return sendQuestDialog(env, 1011);
} else if (dialogActionId == SETPRO1) {
giveQuestItem(env, 182207917, 1);
return defaultCloseDialog(env, 0, 1);
} else if (dialogActionId == SETPRO2) {
giveQuestItem(env, 182207917, 1);
return defaultCloseDialog(env, 0, 2);
}
} else if (targetId == 799410) {
if (dialogActionId == QUEST_SELECT) {
if (qs.getQuestVarById(0) == 1)
return sendQuestDialog(env, 1352);
} else if (dialogActionId == SET_SUCCEED) {
qs.setRewardGroup(0);
removeQuestItem(env, 182207917, 1);
return defaultCloseDialog(env, 1, 1, true, false);
}
} else if (targetId == 204138) {
if (dialogActionId == QUEST_SELECT) {
if (qs.getQuestVarById(0) == 2)
return sendQuestDialog(env, 1693);
} else if (dialogActionId == SET_SUCCEED) {
qs.setRewardGroup(1);
removeQuestItem(env, 182207917, 1);
return defaultCloseDialog(env, 2, 2, true, false);
}
}
} else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 799409) {
if (dialogActionId == USE_OBJECT) {
return sendQuestDialog(env, 10002);
}
return sendQuestEndDialog(env);
}
}
return false;
}
}
| 412 | 0.790767 | 1 | 0.790767 | game-dev | MEDIA | 0.970946 | game-dev | 0.917981 | 1 | 0.917981 |
kenjinp/hello-worlds | 8,751 | apps/docs/examples/tectonics/partitioning/AABB.ts | import { Matrix4, Plane, Sphere, Vector3 } from "three"
const vector = new Vector3()
const center = new Vector3()
const size = new Vector3()
const points = [
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
]
/**
* Class representing an axis-aligned bounding box (AABB).
* orginially from https://github.com/Mugen87/yuka/blob/master/src/math/AABB.js
* @author {@link https://github.com/Mugen87|Mugen87}
*/
class AABB {
/**
* Constructs a new AABB with the given values.
*
* @param {Vector3} min - The minimum bounds of the AABB.
* @param {Vector3} max - The maximum bounds of the AABB.
*/
constructor(public min = new Vector3(), public max = new Vector3()) {}
/**
* Sets the given values to this AABB.
*
* @param {Vector3} min - The minimum bounds of the AABB.
* @param {Vector3} max - The maximum bounds of the AABB.
* @return {AABB} A reference to this AABB.
*/
set(min: Vector3, max: Vector3) {
this.min = min
this.max = max
return this
}
/**
* Copies all values from the given AABB to this AABB.
*
* @param {AABB} aabb - The AABB to copy.
* @return {AABB} A reference to this AABB.
*/
copy(aabb: AABB) {
this.min.copy(aabb.min)
this.max.copy(aabb.max)
return this
}
/**
* Creates a new AABB and copies all values from this AABB.
*
* @return {AABB} A new AABB.
*/
clone() {
return new AABB().copy(this)
}
/**
* Ensures the given point is inside this AABB and stores
* the result in the given vector.
*
* @param {Vector3} point - A point in 3D space.
* @param {Vector3} result - The result vector.
* @return {Vector3} The result vector.
*/
clampPoint(point: Vector3, result: Vector3) {
result.copy(point).clamp(this.min, this.max)
return result
}
/**
* Returns true if the given point is inside this AABB.
*
* @param {Vector3} point - A point in 3D space.
* @return {Boolean} The result of the containments test.
*/
containsPoint(point: Vector3) {
return point.x < this.min.x ||
point.x > this.max.x ||
point.y < this.min.y ||
point.y > this.max.y ||
point.z < this.min.z ||
point.z > this.max.z
? false
: true
}
/**
* Expands this AABB by the given point. So after this method call,
* the given point lies inside the AABB.
*
* @param {Vector3} point - A point in 3D space.
* @return {AABB} A reference to this AABB.
*/
expand(point: Vector3) {
this.min.min(point)
this.max.max(point)
return this
}
/**
* Computes the center point of this AABB and stores it into the given vector.
*
* @param {Vector3} result - The result vector.
* @return {Vector3} The result vector.
*/
getCenter(result: Vector3) {
return result.addVectors(this.min, this.max).multiplyScalar(0.5)
}
/**
* Computes the size (width, height, depth) of this AABB and stores it into the given vector.
*
* @param {Vector3} result - The result vector.
* @return {Vector3} The result vector.
*/
getSize(result: Vector3) {
return result.subVectors(this.max, this.min)
}
/**
* Returns true if the given AABB intersects this AABB.
*
* @param {AABB} aabb - The AABB to test.
* @return {Boolean} The result of the intersection test.
*/
intersectsAABB(aabb: AABB) {
return aabb.max.x < this.min.x ||
aabb.min.x > this.max.x ||
aabb.max.y < this.min.y ||
aabb.min.y > this.max.y ||
aabb.max.z < this.min.z ||
aabb.min.z > this.max.z
? false
: true
}
/**
* Returns true if the given bounding sphere intersects this AABB.
*
* @param {BoundingSphere} sphere - The bounding sphere to test.
* @return {Boolean} The result of the intersection test.
*/
intersectsBoundingSphere(sphere: Sphere) {
// find the point on the AABB closest to the sphere center
this.clampPoint(sphere.center, vector)
// if that point is inside the sphere, the AABB and sphere intersect.
return (
vector.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius
)
}
/**
* Returns true if the given plane intersects this AABB.
*
* Reference: Testing Box Against Plane in Real-Time Collision Detection
* by Christer Ericson (chapter 5.2.3)
*
* @param {Plane} plane - The plane to test.
* @return {Boolean} The result of the intersection test.
*/
intersectsPlane(plane: Plane) {
const normal = plane.normal
this.getCenter(center)
size.subVectors(this.max, center) // positive extends
// compute the projection interval radius of b onto L(t) = c + t * plane.normal
const r =
size.x * Math.abs(normal.x) +
size.y * Math.abs(normal.y) +
size.z * Math.abs(normal.z)
// compute distance of box center from plane
const s = plane.distanceToPoint(center)
return Math.abs(s) <= r
}
/**
* Returns the normal for a given point on this AABB's surface.
*
* @param {Vector3} point - The point on the surface
* @param {Vector3} result - The result vector.
* @return {Vector3} The result vector.
*/
getNormalFromSurfacePoint(point: Vector3, result: Vector3) {
// from https://www.gamedev.net/forums/topic/551816-finding-the-aabb-surface-normal-from-an-intersection-point-on-aabb/
result.set(0, 0, 0)
let distance
let minDistance = Infinity
this.getCenter(center)
this.getSize(size)
// transform point into local space of AABB
vector.copy(point).sub(center)
// x-axis
distance = Math.abs(size.x - Math.abs(vector.x))
if (distance < minDistance) {
minDistance = distance
result.set(1 * Math.sign(vector.x), 0, 0)
}
// y-axis
distance = Math.abs(size.y - Math.abs(vector.y))
if (distance < minDistance) {
minDistance = distance
result.set(0, 1 * Math.sign(vector.y), 0)
}
// z-axis
distance = Math.abs(size.z - Math.abs(vector.z))
if (distance < minDistance) {
result.set(0, 0, 1 * Math.sign(vector.z))
}
return result
}
/**
* Sets the values of the AABB from the given center and size vector.
*
* @param {Vector3} center - The center point of the AABB.
* @param {Vector3} size - The size of the AABB per axis.
* @return {AABB} A reference to this AABB.
*/
fromCenterAndSize(center: Vector3, size: Vector3) {
vector.copy(size).multiplyScalar(0.5) // compute half size
this.min.copy(center).sub(vector)
this.max.copy(center).add(vector)
return this
}
/**
* Computes an AABB that encloses the given set of points.
*
* @param {Array<Vector3>} points - An array of 3D vectors representing points in 3D space.
* @return {AABB} A reference to this AABB.
*/
fromPoints(points: Vector3[]) {
this.min.set(Infinity, Infinity, Infinity)
this.max.set(-Infinity, -Infinity, -Infinity)
for (let i = 0, l = points.length; i < l; i++) {
this.expand(points[i])
}
return this
}
/**
* Transforms this AABB with the given 4x4 transformation matrix.
*
* @param {Matrix4} matrix - The 4x4 transformation matrix.
* @return {AABB} A reference to this AABB.
*/
applyMatrix4(matrix: Matrix4) {
const min = this.min
const max = this.max
points[0].set(min.x, min.y, min.z).applyMatrix4(matrix)
points[1].set(min.x, min.y, max.z).applyMatrix4(matrix)
points[2].set(min.x, max.y, min.z).applyMatrix4(matrix)
points[3].set(min.x, max.y, max.z).applyMatrix4(matrix)
points[4].set(max.x, min.y, min.z).applyMatrix4(matrix)
points[5].set(max.x, min.y, max.z).applyMatrix4(matrix)
points[6].set(max.x, max.y, min.z).applyMatrix4(matrix)
points[7].set(max.x, max.y, max.z).applyMatrix4(matrix)
return this.fromPoints(points)
}
/**
* Returns true if the given AABB is deep equal with this AABB.
*
* @param {AABB} aabb - The AABB to test.
* @return {Boolean} The result of the equality test.
*/
equals(aabb: AABB) {
return aabb.min.equals(this.min) && aabb.max.equals(this.max)
}
/**
* Transforms this instance into a JSON object.
*
* @return {Object} The JSON object.
*/
toJSON() {
return {
type: this.constructor.name,
min: this.min.toArray(new Array()),
max: this.max.toArray(new Array()),
}
}
/**
* Restores this instance from the given JSON object.
*
* @param {Object} json - The JSON object.
* @return {AABB} A reference to this AABB.
*/
fromJSON(json) {
this.min.fromArray(json.min)
this.max.fromArray(json.max)
return this
}
}
export { AABB }
| 412 | 0.926836 | 1 | 0.926836 | game-dev | MEDIA | 0.59301 | game-dev,graphics-rendering | 0.993578 | 1 | 0.993578 |
AionGermany/aion-germany | 4,294 | AL-Game-5.8/src/com/aionemu/gameserver/model/items/storage/PlayerStorage.java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.items.storage;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.item.ItemPacketService.ItemAddType;
import com.aionemu.gameserver.services.item.ItemPacketService.ItemDeleteType;
import com.aionemu.gameserver.services.item.ItemPacketService.ItemUpdateType;
/**
* @author ATracer
*/
public class PlayerStorage extends Storage {
private Player actor;
/**
* @param storageType
*/
public PlayerStorage(StorageType storageType) {
super(storageType);
}
@Override
public final void setOwner(Player actor) {
this.actor = actor;
}
@Override
public void onLoadHandler(Item item) {
if (item.isEquipped()) {
actor.getEquipment().onLoadHandler(item);
}
else {
super.onLoadHandler(item);
}
}
@Override
public void increaseKinah(long amount) {
increaseKinah(amount, actor);
}
@Override
public void increaseKinah(long amount, ItemUpdateType updateType) {
increaseKinah(amount, updateType, actor);
}
@Override
public boolean tryDecreaseKinah(long amount) {
return tryDecreaseKinah(amount, actor);
}
@Override
public boolean tryDecreaseKinah(long amount, ItemUpdateType updateType) {
return tryDecreaseKinah(amount, updateType, actor);
}
@Override
public void decreaseKinah(long amount) {
decreaseKinah(amount, actor);
}
@Override
public void decreaseKinah(long amount, ItemUpdateType updateType) {
decreaseKinah(amount, updateType, actor);
}
@Override
public long increaseItemCount(Item item, long count) {
return increaseItemCount(item, count, actor);
}
@Override
public long increaseItemCount(Item item, long count, ItemUpdateType updateType) {
return increaseItemCount(item, count, updateType, actor);
}
@Override
public long decreaseItemCount(Item item, long count) {
return decreaseItemCount(item, count, actor);
}
@Override
public long decreaseItemCount(Item item, long count, ItemUpdateType updateType) {
return decreaseItemCount(item, count, updateType, actor);
}
@Override
public long decreaseItemCount(Item item, long count, ItemUpdateType updateType, QuestStatus questStatus) {
return decreaseItemCount(item, count, updateType, questStatus, actor);
}
@Override
public Item add(Item item) {
return add(item, actor);
}
@Override
public Item add(Item item, ItemAddType addType) {
return add(item, addType, actor);
}
@Override
public Item put(Item item) {
return put(item, actor);
}
@Override
public Item delete(Item item) {
return delete(item, actor);
}
@Override
public Item delete(Item item, ItemDeleteType deleteType) {
return delete(item, deleteType, actor);
}
@Override
public boolean decreaseByItemId(int itemId, long count) {
return decreaseByItemId(itemId, count, actor);
}
@Override
public boolean decreaseByItemId(int itemId, long count, QuestStatus questStatus) {
return decreaseByItemId(itemId, count, questStatus, actor);
}
@Override
public boolean decreaseByObjectId(int itemObjId, long count) {
return decreaseByObjectId(itemObjId, count, actor);
}
@Override
public boolean decreaseByObjectId(int itemObjId, long count, QuestStatus questStatus) {
return decreaseByObjectId(itemObjId, count, questStatus, actor);
}
@Override
public boolean decreaseByObjectId(int itemObjId, long count, ItemUpdateType updateType) {
return decreaseByObjectId(itemObjId, count, updateType, actor);
}
}
| 412 | 0.872787 | 1 | 0.872787 | game-dev | MEDIA | 0.976354 | game-dev | 0.93075 | 1 | 0.93075 |
devshareacademy/phaser-zelda-like-tutorial | 2,134 | src/components/state-machine/states/character/boss/drow/boss-drow-teleport-state.ts | import * as Phaser from 'phaser';
import { CharacterGameObject } from '../../../../../../game-objects/common/character-game-object';
import { BaseCharacterState } from '../../base-character-state';
import { CHARACTER_STATES } from '../../character-states';
import {
ENEMY_BOSS_TELEPORT_STATE_FINISHED_DELAY,
ENEMY_BOSS_TELEPORT_STATE_INITIAL_DELAY,
} from '../../../../../../common/config';
import { DIRECTION } from '../../../../../../common/common';
export class BossDrowTeleportState extends BaseCharacterState {
#possibleTeleportLocations: Phaser.Math.Vector2[];
constructor(gameObject: CharacterGameObject, possibleTeleportLocations: Phaser.Math.Vector2[]) {
super(CHARACTER_STATES.TELEPORT_STATE, gameObject);
this.#possibleTeleportLocations = possibleTeleportLocations;
}
public onEnter(): void {
this._gameObject.invulnerableComponent.invulnerable = true;
const timeEvent = this._gameObject.scene.time.addEvent({
delay: ENEMY_BOSS_TELEPORT_STATE_INITIAL_DELAY,
callback: () => {
if (timeEvent.getOverallProgress() === 1) {
this.#handleTeleportFinished();
return;
}
this._gameObject.direction = DIRECTION.DOWN;
this._gameObject.animationComponent.playAnimation(`IDLE_${this._gameObject.direction}`);
const location =
this.#possibleTeleportLocations[timeEvent.repeatCount % this.#possibleTeleportLocations.length];
this._gameObject.setPosition(location.x, location.y);
},
callbackScope: this,
repeat: this.#possibleTeleportLocations.length * 3 - 1,
});
}
#handleTeleportFinished(): void {
this._gameObject.visible = false;
this._gameObject.scene.time.delayedCall(ENEMY_BOSS_TELEPORT_STATE_FINISHED_DELAY, () => {
const randomLocation = Phaser.Utils.Array.GetRandom(this.#possibleTeleportLocations);
this._gameObject.setPosition(randomLocation.x, randomLocation.y);
this._gameObject.visible = true;
this._gameObject.invulnerableComponent.invulnerable = false;
this._stateMachine.setState(CHARACTER_STATES.PREPARE_ATTACK_STATE);
});
}
}
| 412 | 0.936065 | 1 | 0.936065 | game-dev | MEDIA | 0.990683 | game-dev | 0.9766 | 1 | 0.9766 |
CobbleSword/BurritoSpigot | 7,087 | BurritoSpigot-Server/nms-patches/BlockCocoa.patch | --- a/net/minecraft/server/BlockCocoa.java
+++ b/net/minecraft/server/BlockCocoa.java
@@ -2,13 +2,15 @@
import java.util.Random;
+import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit
+
public class BlockCocoa extends BlockDirectional implements IBlockFragilePlantElement {
public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 2);
public BlockCocoa() {
super(Material.PLANT);
- this.j(this.blockStateList.getBlockData().set(BlockCocoa.FACING, EnumDirection.NORTH).set(BlockCocoa.AGE, 0));
+ this.j(this.blockStateList.getBlockData().set(BlockCocoa.FACING, EnumDirection.NORTH).set(BlockCocoa.AGE, Integer.valueOf(0)));
this.a(true);
}
@@ -16,10 +18,13 @@
if (!this.e(world, blockposition, iblockdata)) {
this.f(world, blockposition, iblockdata);
} else if (world.random.nextInt(5) == 0) {
- int i = (Integer) iblockdata.get(BlockCocoa.AGE);
+ int i = ((Integer) iblockdata.get(BlockCocoa.AGE)).intValue();
if (i < 2) {
- world.setTypeAndData(blockposition, iblockdata.set(BlockCocoa.AGE, i + 1), 2);
+ // CraftBukkit start
+ IBlockData data = iblockdata.set(AGE, Integer.valueOf(i + 1));
+ CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, toLegacyData(data));
+ // CraftBukkit end
}
}
@@ -48,23 +53,26 @@
public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) {
IBlockData iblockdata = iblockaccess.getType(blockposition);
EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockCocoa.FACING);
- int i = (Integer) iblockdata.get(BlockCocoa.AGE);
+ int i = ((Integer) iblockdata.get(BlockCocoa.AGE)).intValue();
int j = 4 + i * 2;
int k = 5 + i * 2;
float f = (float) j / 2.0F;
- switch (enumdirection) {
- case SOUTH:
- this.a((8.0F - f) / 16.0F, (12.0F - (float) k) / 16.0F, (15.0F - (float) j) / 16.0F, (8.0F + f) / 16.0F, 0.75F, 0.9375F);
- break;
- case NORTH:
- this.a((8.0F - f) / 16.0F, (12.0F - (float) k) / 16.0F, 0.0625F, (8.0F + f) / 16.0F, 0.75F, (1.0F + (float) j) / 16.0F);
- break;
- case WEST:
- this.a(0.0625F, (12.0F - (float) k) / 16.0F, (8.0F - f) / 16.0F, (1.0F + (float) j) / 16.0F, 0.75F, (8.0F + f) / 16.0F);
- break;
- case EAST:
- this.a((15.0F - (float) j) / 16.0F, (12.0F - (float) k) / 16.0F, (8.0F - f) / 16.0F, 0.9375F, 0.75F, (8.0F + f) / 16.0F);
+ switch (BlockCocoa.SyntheticClass_1.a[enumdirection.ordinal()]) {
+ case 1:
+ this.a((8.0F - f) / 16.0F, (12.0F - (float) k) / 16.0F, (15.0F - (float) j) / 16.0F, (8.0F + f) / 16.0F, 0.75F, 0.9375F);
+ break;
+
+ case 2:
+ this.a((8.0F - f) / 16.0F, (12.0F - (float) k) / 16.0F, 0.0625F, (8.0F + f) / 16.0F, 0.75F, (1.0F + (float) j) / 16.0F);
+ break;
+
+ case 3:
+ this.a(0.0625F, (12.0F - (float) k) / 16.0F, (8.0F - f) / 16.0F, (1.0F + (float) j) / 16.0F, 0.75F, (8.0F + f) / 16.0F);
+ break;
+
+ case 4:
+ this.a((15.0F - (float) j) / 16.0F, (12.0F - (float) k) / 16.0F, (8.0F - f) / 16.0F, 0.9375F, 0.75F, (8.0F + f) / 16.0F);
}
}
@@ -80,7 +88,7 @@
enumdirection = EnumDirection.NORTH;
}
- return this.getBlockData().set(BlockCocoa.FACING, enumdirection.opposite()).set(BlockCocoa.AGE, 0);
+ return this.getBlockData().set(BlockCocoa.FACING, enumdirection.opposite()).set(BlockCocoa.AGE, Integer.valueOf(0));
}
public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) {
@@ -96,7 +104,7 @@
}
public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) {
- int j = (Integer) iblockdata.get(BlockCocoa.AGE);
+ int j = ((Integer) iblockdata.get(BlockCocoa.AGE)).intValue();
byte b0 = 1;
if (j >= 2) {
@@ -114,7 +122,7 @@
}
public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) {
- return (Integer) iblockdata.get(BlockCocoa.AGE) < 2;
+ return ((Integer) iblockdata.get(BlockCocoa.AGE)).intValue() < 2;
}
public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) {
@@ -122,22 +130,57 @@
}
public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) {
- world.setTypeAndData(blockposition, iblockdata.set(BlockCocoa.AGE, (Integer) iblockdata.get(BlockCocoa.AGE) + 1), 2);
+ // CraftBukkit start
+ IBlockData data = iblockdata.set(AGE, Integer.valueOf(((Integer) iblockdata.get(AGE)).intValue() + 1));
+ CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, toLegacyData(data));
+ // CraftBukkit end
}
public IBlockData fromLegacyData(int i) {
- return this.getBlockData().set(BlockCocoa.FACING, EnumDirection.fromType2(i)).set(BlockCocoa.AGE, (i & 15) >> 2);
+ return this.getBlockData().set(BlockCocoa.FACING, EnumDirection.fromType2(i)).set(BlockCocoa.AGE, Integer.valueOf((i & 15) >> 2));
}
public int toLegacyData(IBlockData iblockdata) {
byte b0 = 0;
int i = b0 | ((EnumDirection) iblockdata.get(BlockCocoa.FACING)).b();
- i |= (Integer) iblockdata.get(BlockCocoa.AGE) << 2;
+ i |= ((Integer) iblockdata.get(BlockCocoa.AGE)).intValue() << 2;
return i;
}
protected BlockStateList getStateList() {
- return new BlockStateList(this, new IBlockState[]{BlockCocoa.FACING, BlockCocoa.AGE});
+ return new BlockStateList(this, new IBlockState[] { BlockCocoa.FACING, BlockCocoa.AGE});
+ }
+
+ static class SyntheticClass_1 {
+
+ static final int[] a = new int[EnumDirection.values().length];
+
+ static {
+ try {
+ BlockCocoa.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 1;
+ } catch (NoSuchFieldError nosuchfielderror) {
+ ;
+ }
+
+ try {
+ BlockCocoa.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 2;
+ } catch (NoSuchFieldError nosuchfielderror1) {
+ ;
+ }
+
+ try {
+ BlockCocoa.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3;
+ } catch (NoSuchFieldError nosuchfielderror2) {
+ ;
+ }
+
+ try {
+ BlockCocoa.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4;
+ } catch (NoSuchFieldError nosuchfielderror3) {
+ ;
+ }
+
+ }
}
}
| 412 | 0.965508 | 1 | 0.965508 | game-dev | MEDIA | 0.781821 | game-dev | 0.989861 | 1 | 0.989861 |
ServUO/ServUO | 9,415 | Scripts/Mobiles/Named/Meraktus.cs | using System;
using System.Collections;
using Server.Engines.CannedEvil;
using Server.Items;
namespace Server.Mobiles
{
[CorpseName("the remains of Meraktus")]
public class Meraktus : BaseChampion
{
public override ChampionSkullType SkullType
{
get
{
return ChampionSkullType.Pain;
}
}
public override Type[] UniqueList
{
get
{
return new Type[] { typeof(Subdue) };
}
}
public override Type[] SharedList
{
get
{
return new Type[]
{
typeof(RoyalGuardSurvivalKnife),
typeof(TheMostKnowledgePerson),
typeof(OblivionsNeedle)
};
}
}
public override Type[] DecorativeList
{
get
{
return new Type[]
{
typeof(ArtifactLargeVase),
typeof(ArtifactVase),
typeof(MinotaurStatueDeed)
};
}
}
public override MonsterStatuetteType[] StatueTypes
{
get
{
return new MonsterStatuetteType[]
{
MonsterStatuetteType.Minotaur
};
}
}
[Constructable]
public Meraktus()
: base(AIType.AI_Melee)
{
Name = "Meraktus";
Title = "the Tormented";
Body = 263;
BaseSoundID = 680;
Hue = 0x835;
SetStr(1419, 1438);
SetDex(309, 413);
SetInt(129, 131);
SetHits(4100, 4200);
SetDamage(16, 30);
SetDamageType(ResistanceType.Physical, 100);
SetResistance(ResistanceType.Physical, 65, 90);
SetResistance(ResistanceType.Fire, 65, 70);
SetResistance(ResistanceType.Cold, 50, 60);
SetResistance(ResistanceType.Poison, 40, 60);
SetResistance(ResistanceType.Energy, 50, 55);
SetSkill(SkillName.Anatomy, 0);
SetSkill(SkillName.MagicResist, 107.0, 111.3);
SetSkill(SkillName.Tactics, 107.0, 117.0);
SetSkill(SkillName.Wrestling, 100.0, 105.0);
Fame = 70000;
Karma = -70000;
VirtualArmor = 28; // Don't know what it should be
for (int i = 0; i < Utility.RandomMinMax(0, 1); i++)
{
PackItem(Loot.RandomScroll(0, Loot.ArcanistScrollTypes.Length, SpellbookType.Arcanist));
}
NoKillAwards = true;
if (Core.ML)
{
PackResources(8);
PackTalismans(5);
}
Timer.DelayCall(TimeSpan.FromSeconds(1), new TimerCallback(SpawnTormented));
SetWeaponAbility(WeaponAbility.Dismount);
}
public virtual void PackResources(int amount)
{
for (int i = 0; i < amount; i++)
switch (Utility.Random(6))
{
case 0:
PackItem(new Blight());
break;
case 1:
PackItem(new Scourge());
break;
case 2:
PackItem(new Taint());
break;
case 3:
PackItem(new Putrefaction());
break;
case 4:
PackItem(new Corruption());
break;
case 5:
PackItem(new Muculent());
break;
}
}
public virtual void PackTalismans(int amount)
{
int count = Utility.Random(amount);
for (int i = 0; i < count; i++)
PackItem(new RandomTalisman());
}
public override void OnDeath(Container c)
{
base.OnDeath(c);
if (Core.ML)
{
c.DropItem(new MalletAndChisel());
switch (Utility.Random(3))
{
case 0:
c.DropItem(new MinotaurHedge());
break;
case 1:
c.DropItem(new BonePile());
break;
case 2:
c.DropItem(new LightYarn());
break;
}
if (Utility.RandomBool())
c.DropItem(new TormentedChains());
if (Utility.RandomDouble() < 0.025)
c.DropItem(new CrimsonCincture());
}
}
public override void GenerateLoot()
{
if (Core.ML)
{
AddLoot(LootPack.AosSuperBoss, 5); // Need to verify
}
}
public override int GetAngerSound()
{
return 0x597;
}
public override int GetIdleSound()
{
return 0x596;
}
public override int GetAttackSound()
{
return 0x599;
}
public override int GetHurtSound()
{
return 0x59a;
}
public override int GetDeathSound()
{
return 0x59c;
}
public override int Meat
{
get
{
return 2;
}
}
public override int Hides
{
get
{
return 10;
}
}
public override HideType HideType
{
get
{
return HideType.Regular;
}
}
public override Poison PoisonImmune
{
get
{
return Poison.Regular;
}
}
public override int TreasureMapLevel
{
get
{
return 3;
}
}
public override bool BardImmune
{
get
{
return true;
}
}
public override bool Unprovokable
{
get
{
return true;
}
}
public override bool Uncalmable
{
get
{
return true;
}
}
public override void OnGaveMeleeAttack(Mobile defender)
{
base.OnGaveMeleeAttack(defender);
if (0.2 >= Utility.RandomDouble())
Earthquake();
}
public void Earthquake()
{
Map map = Map;
if (map == null)
return;
ArrayList targets = new ArrayList();
IPooledEnumerable eable = GetMobilesInRange(8);
foreach (Mobile m in eable)
{
if (m == this || !CanBeHarmful(m))
continue;
if (m is BaseCreature && (((BaseCreature)m).Controlled || ((BaseCreature)m).Summoned || ((BaseCreature)m).Team != Team))
targets.Add(m);
else if (m.Player)
targets.Add(m);
}
eable.Free();
PlaySound(0x2F3);
for (int i = 0; i < targets.Count; ++i)
{
Mobile m = (Mobile)targets[i];
if (m != null && !m.Deleted && m is PlayerMobile)
{
PlayerMobile pm = m as PlayerMobile;
if (pm != null && pm.Mounted)
{
pm.SetMountBlock(BlockMountType.DismountRecovery, TimeSpan.FromSeconds(10), true);
}
}
double damage = m.Hits * 0.6;//was .6
if (damage < 10.0)
damage = 10.0;
else if (damage > 75.0)
damage = 75.0;
DoHarmful(m);
AOS.Damage(m, this, (int)damage, 100, 0, 0, 0, 0);
if (m.Alive && m.Body.IsHuman && !m.Mounted)
m.Animate(20, 7, 1, true, false, 0); // take hit
}
}
public Meraktus(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
#region SpawnHelpers
public void SpawnTormented()
{
BaseCreature spawna = new TormentedMinotaur();
spawna.MoveToWorld(Location, Map);
BaseCreature spawnb = new TormentedMinotaur();
spawnb.MoveToWorld(Location, Map);
BaseCreature spawnc = new TormentedMinotaur();
spawnc.MoveToWorld(Location, Map);
BaseCreature spawnd = new TormentedMinotaur();
spawnd.MoveToWorld(Location, Map);
}
#endregion
}
}
| 412 | 0.996369 | 1 | 0.996369 | game-dev | MEDIA | 0.986329 | game-dev | 0.997647 | 1 | 0.997647 |
Fluorohydride/ygopro-scripts | 1,103 | c74923978.lua | --強制接収
function c74923978.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_DISCARD)
e1:SetCondition(c74923978.condition)
c:RegisterEffect(e1)
--handes
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(74923978,0))
e2:SetCategory(CATEGORY_HANDES)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_DISCARD)
e2:SetCondition(c74923978.condition)
e2:SetTarget(c74923978.target)
e2:SetOperation(c74923978.operation)
c:RegisterEffect(e2)
end
function c74923978.cfilter(c,tp)
return c:IsPreviousControler(tp)
end
function c74923978.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c74923978.cfilter,1,nil,tp)
end
function c74923978.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local ct=eg:FilterCount(c74923978.cfilter,nil,tp)
e:SetLabel(ct)
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,ct)
end
function c74923978.operation(e,tp,eg,ep,ev,re,r,rp)
local ct=e:GetLabel()
Duel.DiscardHand(1-tp,nil,ct,ct,REASON_EFFECT+REASON_DISCARD)
end
| 412 | 0.890515 | 1 | 0.890515 | game-dev | MEDIA | 0.80041 | game-dev | 0.952858 | 1 | 0.952858 |
pkmn/ps | 1,981 | sim/test/sim/moves/reflecttype.js | 'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('Reflect Type', () => {
afterEach(() => {
battle.destroy();
});
it('should fail when used against a Pokemon whose type is "???"', () => {
battle = common.createBattle();
battle.setPlayer('p1', { team: [{ species: 'Arcanine', ability: 'intimidate', moves: ['burnup'] }] });
battle.setPlayer('p2', { team: [{ species: 'Latias', ability: 'levitate', item: 'laggingtail', moves: ['reflecttype'] }] });
assert.constant(() => battle.p2.active[0].getTypes(), () => battle.makeChoices('move burnup', 'move reflecttype'));
});
it('should ignore the "???" type when used against a Pokemon whose type contains "???" and a non-added type', () => {
battle = common.createBattle();
battle.setPlayer('p1', { team: [{ species: 'Latias', ability: 'levitate', item: 'laggingtail', moves: ['reflecttype', 'trickortreat'] }] });
battle.setPlayer('p2', { team: [{ species: 'Moltres', ability: 'pressure', moves: ['burnup'] }] });
battle.makeChoices('move reflecttype', 'move burnup');
assert.equal(battle.p1.active[0].getTypes().join('/'), 'Flying');
battle.makeChoices('move trickortreat', 'move burnup');
battle.makeChoices('move reflecttype', 'move burnup');
assert.equal(battle.p1.active[0].getTypes().join('/'), 'Flying/Ghost');
});
it('should turn the "???" type into "Normal" when used against a Pokemon whose type is only "???" and an added type', () => {
battle = common.createBattle();
battle.setPlayer('p1', { team: [{ species: 'Latias', ability: 'levitate', item: 'laggingtail', moves: ['reflecttype', 'trickortreat'] }] });
battle.setPlayer('p2', { team: [{ species: 'Arcanine', ability: 'intimidate', moves: ['burnup'] }] });
battle.makeChoices('move trickortreat', 'move burnup');
battle.makeChoices('move reflecttype', 'move burnup');
assert.equal(battle.p1.active[0].getTypes().join('/'), 'Normal/Ghost');
});
});
| 412 | 0.718608 | 1 | 0.718608 | game-dev | MEDIA | 0.763107 | game-dev | 0.578578 | 1 | 0.578578 |
Wizard-Of-Chaos/ExShock_code | 3,123 | src/utilities/Config.h | #pragma once
#ifndef CONFIG_H
#define CONFIG_H
#include "BaseHeader.h"
#include "GvReader.h"
#include "InputComponent.h"
#include <unordered_map>
#include <vector>
const extern std::map <std::string, E_DRIVER_TYPE> drivers;
class GameStateController;
/*
* Holds the configuration for the game - things like fullscreen, the resolution, filtering, shadows, and other
* graphics stuff.
*/
enum class SETTING_LEVEL
{
LOW,
MED,
HIGH,
SETTINGLEVEL_MAX
};
enum class DIFFICULTY_LEVEL
{
GAMES_JOURNALIST = 1,
LOW = 2,
NORMAL = 3,
HIGH = 4,
UNFAIR = 5,
DIFFICULTY_MAXVAL = 6
};
enum VIDEO_TOGGLE
{
TOG_FULLSCREEN,
TOG_VSYNC,
TOG_ALIASING,
TOG_FILTER,
TOG_ANISOTROPIC,
TOG_BUMP,
TOG_MAX
};
enum DIFFICULTY
{
DIF_PLAYER_DMG,
DIF_ENEMY_DMG,
DIF_AI_INT,
DIF_AIM,
DIF_RESOLVE,
DIF_WINGNUM,
DIF_MAX
};
enum GAME_TOGGLE
{
GTOG_LIN_SPACE_FRICTION,
GTOG_ANG_SPACE_FRICTION,
GTOG_CONST_THRUST,
GTOG_FRIENDLY_FIRE,
GTOG_IMPACT,
GTOG_BANTER,
GTOG_MAX
};
extern const std::map<DIFFICULTY, std::string> difficultyNames;
extern const std::map<DIFFICULTY_LEVEL, std::string> difLevelNames;
extern const std::map<DIFFICULTY_LEVEL, u32> aiBehaviorDifficulties;
extern const std::map<DIFFICULTY_LEVEL, f32> aiResolveDifficulties;
extern const std::map<DIFFICULTY_LEVEL, f32> aiAimDifficulties;
extern const std::map<DIFFICULTY_LEVEL, u32> aiNumDifficulties;
extern const std::map<std::string, VIDEO_TOGGLE> videoToggleNames;
extern const std::map<GAME_TOGGLE, std::string> gameToggleNames;
extern const std::map<EKEY_CODE, std::wstring> keyDesc;
extern const std::map<INPUT, std::wstring> inputNames;
//Returns the key description (i.e. a string for the key like "K") for the given input.
std::wstring getKeyDesc(INPUT in);
//Returns the key-code for the given input.
EKEY_CODE key(INPUT in);
struct VideoConfig
{
VideoConfig();
void loadConfig(std::string filename);
void saveConfig(std::string filename);
E_DRIVER_TYPE driver;
SETTING_LEVEL particleLevel;
SETTING_LEVEL renderDist;
bool toggles[TOG_MAX];
bool useScreenRes;
int resX;
int resY;
};
struct KeyConfig
{
KeyConfig();
void loadConfig(std::string filename);
void saveConfig(std::string filename);
const bool keyBound(EKEY_CODE which) const {
for (u32 i = 0; i < IN_MAX_ENUM; ++i) {
if (key[i] == which) return true;
}
return false;
}
const INPUT boundTo(EKEY_CODE which) const {
if (!keyBound(which)) return IN_MAX_ENUM;
for (u32 i = 0; i < IN_MAX_ENUM; ++i) {
if (key[i] == which) return (INPUT)i;
}
return IN_MAX_ENUM;
}
EKEY_CODE key[IN_MAX_ENUM];
};
struct GameConfig
{
GameConfig() {
for (u32 i = 0; i < DIF_MAX; ++i) {
difficulties[i] = DIFFICULTY_LEVEL::NORMAL;
}
for (u32 i = 0; i < GTOG_MAX; ++i) {
u32 thr = (u32)GTOG_CONST_THRUST;
if (i == thr) continue;
toggles[i] = true;
}
}
void loadConfig(std::string filename);
void saveConfig(std::string filename);
DIFFICULTY_LEVEL difficulties[DIF_MAX];
bool toggles[GTOG_MAX];
s32 volumes[4] = { 100, 100, 70, 70 };
void setAudioGains();
};
struct Config
{
VideoConfig vid;
KeyConfig keys;
GameConfig game;
};
#endif | 412 | 0.794602 | 1 | 0.794602 | game-dev | MEDIA | 0.612515 | game-dev | 0.542802 | 1 | 0.542802 |
Poobslag/turbofat | 10,061 | project/src/main/world/overworld-ui.gd | class_name OverworldUi
extends CanvasLayer
## UI elements for the overworld.
##
## This includes chats, buttons and debug messages.
signal chat_started
signal chat_ended
## emitted when we launch a creature's talk animation
signal chatter_talked(chatter)
## emitted when a chat event is played containing metadata
##
## Parameters:
## 'meta_item': (String) Single meta item
signal chat_event_meta_played(meta_item)
## emitted when creatures enter or exit a conversation
signal visible_chatters_changed
## emitted when we present the player with a chat choice
signal showed_chat_choices
export (NodePath) var overworld_environment_path: NodePath setget set_overworld_environment_path
## Characters involved in the current conversation. This includes the player, sensei and any other participants. We
## try to keep them all in frame and facing each other.
var chatters := []
## true if there is an active chat tree
var chatting := false
var _show_version := true setget set_show_version, is_show_version
## These two fields store details for the upcoming level. We store the level details during the chat sequence
## and launch the level when the chat window closes.
var _current_chat_tree: ChatTree
var _overworld_environment: OverworldEnvironment
onready var _chat_ui := $ChatUi
func _ready() -> void:
_refresh_overworld_environment_path()
_update_visible()
func set_overworld_environment_path(new_overworld_environment_path: NodePath) -> void:
overworld_environment_path = new_overworld_environment_path
_refresh_overworld_environment_path()
## Plays the specified chat tree.
##
## Parameters:
## 'new_chat_tree': The chat tree to play.
func start_chat(new_chat_tree: ChatTree) -> void:
_current_chat_tree = new_chat_tree
chatters = _find_creatures_in_chat_tree(new_chat_tree)
chatting = true
# We always add the player and target to the list of chatters. The player might talk to someone who says a
# one-liner, but the camera should still include the player. The player might also 'talk' to an inanimate object
# which doesn't talk back, but the camera should still include the object.
if _overworld_environment.player:
chatters.append(_overworld_environment.player)
_update_visible()
# emit 'chat_started' event first to prepare chatters before emoting
emit_signal("chat_started")
# reset state variables
$ChatUi.play_chat_tree(_current_chat_tree)
func set_show_version(new_show_version: bool) -> void:
_show_version = new_show_version
_update_visible()
func is_show_version() -> bool:
return _show_version
## Calculates the bounding box of the characters involved in the current conversation.
##
## Parameters:
## 'include': (Optional) characters in the current conversation will only be included if they are in this list.
##
## 'exclude': (Optional) Characters in the current conversation will be excluded if they are in this list.
##
## Returns:
## The smallest rectangle including all characters in the current conversation. If no characters meet this criteria,
## this returns an zero-size rectangle at (0, 0).
func get_chatter_bounding_box(include: Array = [], exclude: Array = []) -> Rect2:
var bounding_box: Rect2
for chatter in chatters:
if include and not chatter in include:
continue
if exclude and chatter in exclude:
continue
if not chatter.visible:
continue
var adjusted_chatter_position: Vector2 = chatter.position
if "elevation" in chatter:
adjusted_chatter_position += chatter.elevation * Vector2.UP * Global.CREATURE_SCALE
if bounding_box:
var chat_extents: Vector2 = chatter.chat_extents if "chat_extents" in chatter else Vector2.ZERO
var chatter_box := Rect2(adjusted_chatter_position - chat_extents / 2, chat_extents)
bounding_box = bounding_box.merge(chatter_box)
else:
bounding_box = Rect2(adjusted_chatter_position, Vector2.ZERO)
return bounding_box
func _refresh_overworld_environment_path() -> void:
if not is_inside_tree():
return
if not _chat_ui:
return
_overworld_environment = \
get_node(overworld_environment_path) if overworld_environment_path else null
_chat_ui.overworld_environment_path = \
_chat_ui.get_path_to(_overworld_environment) if overworld_environment_path else NodePath()
func _find_creatures_in_chat_tree(chat_tree: ChatTree) -> Array:
var creatures := []
# calculate which creature ids are involved in this chat
var chatter_ids := {}
for chat_events_obj in chat_tree.events.values():
var chat_events: Array = chat_events_obj
for chat_event_obj in chat_events:
var chat_event: ChatEvent = chat_event_obj
chatter_ids[chat_event.who] = true
# find the creatures associated with the creature ids
for chatter_id in chatter_ids:
var chatter: Creature = _overworld_environment.get_creature_by_id(chatter_id)
if chatter and not creatures.has(chatter):
creatures.append(chatter)
return creatures
## Updates the different UI components to be visible/invisible based on the UI's current state.
func _update_visible() -> void:
$ChatUi.visible = true if chatting else false
$Labels/SoutheastLabels/VersionLabel.visible = _show_version and not chatting
## Applies the specified ChatEvent metadata to the scene.
##
## ChatEvents can include metadata making creatures appear, disappear, laugh or turn around. This method locates the
## creature referenced by the metadata and performs the appropriate action.
##
## Parameters:
## 'chat_event': (Unused) Chat event whose metadata should be applied. This is unused by OverworldUi but can be
## utilized by subclasses who extend this method.
##
## 'meta_item': The metadata item to apply.
func _apply_chat_event_meta(_chat_event: ChatEvent, meta_item: String) -> void:
var meta_item_split := meta_item.split(" ")
match(meta_item_split[0]):
"next_scene":
# schedule another cutscene to happen after this cutscene
var next_scene_key := meta_item_split[1]
var next_scene_chat_tree: ChatTree = ChatLibrary.chat_tree_for_key(next_scene_key)
# insert the chat tree to ensure it happens before any enqueued levels
PlayerData.cutscene_queue.insert_cutscene(0, next_scene_chat_tree)
"creature_enter":
var creature_id := meta_item_split[1]
var creature: Creature = _overworld_environment.get_creature_by_id(creature_id)
creature.fade_in()
emit_signal("visible_chatters_changed")
"creature_exit":
var creature_id := meta_item_split[1]
var creature: Creature = _overworld_environment.get_creature_by_id(creature_id)
creature.fade_out()
if not creature.is_connected("fade_out_finished", self, "_on_Creature_fade_out_finished"):
creature.connect("fade_out_finished", self, "_on_Creature_fade_out_finished", [creature])
"creature_mood":
var creature_id: String = meta_item_split[1]
var creature: Creature = _overworld_environment.get_creature_by_id(creature_id)
var mood: int = int(meta_item_split[2])
creature.play_mood(mood)
"creature_orientation":
var creature_id: String = meta_item_split[1]
var creature: Creature = _overworld_environment.get_creature_by_id(creature_id)
var orientation: int = int(meta_item_split[2])
creature.set_orientation(orientation)
"end_day":
_advance_to_fresh_career_day()
"play_credits":
# the credits lead directly into the main menu, so we immediately end the current career day and advance
# the calendar.
_advance_to_fresh_career_day()
PlayerData.cutscene_queue.insert_credits(0)
emit_signal("chat_event_meta_played", meta_item)
## If the current career day has begin, immediately end it advance the calendar.
##
## This is used during the credits sequence to ensure the player starts fresh after viewing the credits.
func _advance_to_fresh_career_day() -> void:
if PlayerData.career.is_career_mode() and PlayerData.career.hours_passed > 0:
PlayerData.career.hours_passed = Careers.HOURS_PER_CAREER_DAY
PlayerData.career.advance_calendar()
PlayerSave.schedule_save()
func _on_ChatUi_chat_finished() -> void:
chatting = false
PlayerData.chat_history.add_history_item(_current_chat_tree.chat_key)
CurrentCutscene.clear_launched_cutscene()
if not CurrentCutscene.chat_tree \
and Breadcrumb.trail.size() >= 2 and Breadcrumb.trail[1] in [Global.SCENE_CUTSCENE_DEMO]:
# go back to CutsceneDemo after playing the cutscene
if PlayerData.cutscene_queue.is_front_cutscene():
PlayerData.cutscene_queue.replace_trail()
else:
SceneTransition.pop_trail()
elif PlayerData.career.is_career_mode():
# launch the next scene in career mode after playing the cutscene
PlayerData.career.push_career_trail()
# save data to record the cutscene as viewed
PlayerSave.schedule_save()
else:
push_warning("Unexpected state after chat finished: %s" % [Breadcrumb.trail])
SceneTransition.pop_trail()
emit_signal("chat_ended")
func _on_ChatUi_chat_event_played(chat_event: ChatEvent) -> void:
for meta_item in chat_event.meta:
# Apply the chat event's metadata. This can make creatures appear, disappear, laugh or turn around
_apply_chat_event_meta(chat_event, meta_item)
# update the chatter's mood
var chatter: Creature = _overworld_environment.get_creature_by_id(chat_event.who)
if chatter and chatter.has_method("play_mood"):
chatter.call("play_mood", chat_event.mood)
if chatter and StringUtils.has_non_parentheses_letter(chat_event.text):
chatter.talk()
emit_signal("chatter_talked", chatter)
func _on_Creature_fade_out_finished(_creature: Creature) -> void:
if _creature.is_connected("fade_out_finished", self, "_on_Creature_fade_out_finished"):
_creature.disconnect("fade_out_finished", self, "_on_Creature_fade_out_finished")
emit_signal("visible_chatters_changed")
func _on_ChatUi_showed_choices() -> void:
emit_signal("showed_chat_choices")
func _on_SettingsMenu_quit_pressed() -> void:
SceneTransition.pop_trail()
func _on_SettingsButton_pressed() -> void:
$SettingsMenu.show()
func _on_OverworldWorld_overworld_environment_changed(value: OverworldEnvironment) -> void:
set_overworld_environment_path(get_path_to(value))
| 412 | 0.935058 | 1 | 0.935058 | game-dev | MEDIA | 0.825276 | game-dev | 0.915077 | 1 | 0.915077 |
Secrets-of-Sosaria/World | 2,830 | Data/Scripts/Custom/animal broker/Rewards/Rare Colors/FrostBluePetDye.cs | using Server.Targeting;
using System;
using Server;
using Server.Gumps;
using Server.Network;
using Server.Menus;
using Server.Menus.Questions;
using Server.Mobiles;
using System.Collections;
namespace Server.Items
{
public class FrostBluePetDye : Item
{
[Constructable]
public FrostBluePetDye() : base( 0xE2B )
{
Weight = 1.0;
Movable = true;
Hue = 1152;
Name="pet dye (Frost Blue)";
}
public FrostBluePetDye( Serial serial ) : base( serial )
{
}
public override void OnDoubleClick( Mobile from )
{
if ( !IsChildOf( from.Backpack ) )
{
from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
}
else if( from.InRange( this.GetWorldLocation(), 1 ) )
{
from.SendMessage( "What do you wish to dye?" );
from.Target = new FrostBlueDyeTarget( this );
}
else
{
from.SendLocalizedMessage( 500446 ); // That is too far away.
}
}
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();
}
private class FrostBlueDyeTarget : Target
{
private Mobile m_Owner;
private FrostBluePetDye m_Powder;
public FrostBlueDyeTarget( FrostBluePetDye charge ) : base ( 10, false, TargetFlags.None )
{
m_Powder=charge;
}
protected override void OnTarget( Mobile from, object target )
{
if ( target == from )
from.SendMessage( "This can only be used on pets." );
else if ( target is PlayerMobile )
from.SendMessage( "You cannot dye them." );
else if ( target is Item )
from.SendMessage( "You cannot dye that." );
else if ( target is BaseCreature )
{
BaseCreature c = (BaseCreature)target;
if ( c.BodyValue == 400 || c.BodyValue == 401 && c.Controlled == false )
{
from.SendMessage( "You cannot dye them." );
}
else if ( c.ControlMaster != from && c.Controlled == false )
{
from.SendMessage( "This is not your pet." );
}
else if ( c.Controlled == true && c.ControlMaster == from)
{
c.Hue = 1152;
from.SendMessage( 53, "Your pet has now been dyed." );
from.PlaySound( 0x23E );
m_Powder.Delete();
}
}
}
}
}
}
| 412 | 0.766366 | 1 | 0.766366 | game-dev | MEDIA | 0.953865 | game-dev | 0.889727 | 1 | 0.889727 |
spoutcraft/Spoutcraft | 17,344 | src/main/java/org/spoutcraft/client/SpoutClient.java | /*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011 SpoutcraftDev <http://spoutcraft.org/>
* Spoutcraft is licensed under the GNU Lesser General Public License.
*
* Spoutcraft 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.
*
* Spoutcraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.spoutcraft.client;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Logger;
import org.newdawn.slick.util.Log;
import org.newdawn.slick.util.LogSystem;
import net.minecraft.src.Minecraft;
import net.minecraft.src.AbstractClientPlayer;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityClientPlayerMP;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.Packet;
import net.minecraft.src.WorldClient;
import org.spoutcraft.api.Client;
import org.spoutcraft.api.Spoutcraft;
import org.spoutcraft.api.gui.Keyboard;
import org.spoutcraft.api.gui.RenderDelegate;
import org.spoutcraft.api.gui.WidgetManager;
import org.spoutcraft.api.inventory.MaterialManager;
import org.spoutcraft.api.keyboard.KeyBindingManager;
import org.spoutcraft.api.material.MaterialData;
import org.spoutcraft.api.player.BiomeManager;
import org.spoutcraft.api.player.SkyManager;
import org.spoutcraft.api.property.PropertyObject;
import org.spoutcraft.client.config.Configuration;
import org.spoutcraft.client.config.MipMapUtils;
import org.spoutcraft.client.controls.SimpleKeyBindingManager;
import org.spoutcraft.client.entity.CraftEntity;
import org.spoutcraft.client.gui.MCRenderDelegate;
import org.spoutcraft.client.gui.SimpleKeyManager;
import org.spoutcraft.client.gui.SimpleWidgetManager;
import org.spoutcraft.client.gui.minimap.MinimapConfig;
import org.spoutcraft.client.gui.server.ServerManager;
import org.spoutcraft.client.inventory.SimpleMaterialManager;
import org.spoutcraft.client.io.CRCManager;
import org.spoutcraft.client.io.CustomTextureManager;
import org.spoutcraft.client.io.FileDownloadThread;
import org.spoutcraft.client.io.FileUtil;
import org.spoutcraft.client.io.DownloadAssets;
import org.spoutcraft.client.packet.CustomPacket;
import org.spoutcraft.client.packet.PacketEntityInformation;
import org.spoutcraft.client.packet.PacketManager;
import org.spoutcraft.client.player.ClientPlayer;
import org.spoutcraft.client.player.SimpleBiomeManager;
import org.spoutcraft.client.player.SimpleSkyManager;
public class SpoutClient extends PropertyObject implements Client {
private static SpoutClient instance = null;
private static final Thread dataMiningThread = new DataMiningThread();
private static final String version = "Spoutcraft 1.6.4 / b21";
public static final String spoutcraftVersion = "1.6.4";
public static final String spoutcraftBuild = " - b21";
private final SimpleSkyManager skyManager = new SimpleSkyManager();
private final PacketManager packetManager = new PacketManager();
private final BiomeManager biomeManager = new SimpleBiomeManager();
private final MaterialManager materialManager = new SimpleMaterialManager();
private final RenderDelegate render = new MCRenderDelegate();
private final ServerManager serverManager = new ServerManager();
private final KeyBindingManager bindingManager = new SimpleKeyBindingManager();
private final Logger log = Logger.getLogger(SpoutClient.class.getName());
private long tick = 0;
private long inWorldTicks = 0;
private Thread clipboardThread = null;
private long server = -1L;
public ClientPlayer player = null;
private boolean cheatsky = false;
private boolean forcesky = false;
private boolean showsky = true;
private boolean cheatclearwater = false;
private boolean forceclearwater = false;
private boolean showclearwater = true;
private boolean cheatstars = false;
private boolean forcestars = true;
private boolean showstars = true;
private boolean cheatweather = false;
private boolean forceweather = true;
private boolean showweather = true;
private boolean time = false;
private boolean coords = false;
private boolean entitylabel = false;
private boolean cheatvoidfog = false;
private boolean forcevoidfog = true;
private boolean showvoidfog = true;
private boolean flySpeed = false;
private Mode clientMode = Mode.Menu;
private String addonFolder = Minecraft.getMinecraft().mcDataDir + File.separator + "addons";
private final WidgetManager widgetManager = new SimpleWidgetManager();
private final HashMap<String, Boolean> permissions = new HashMap<String, Boolean>();
private boolean active = false;
public boolean xrayMode = false;
public static int[] visibleBlocks = new int[] {133, 132, 131, 120, 129, 122, 120, 119, 118, 117, 116, 115, 111, 103, 100, 151, 152, 153, 154, 155, 158, 99, 98, 96, 95, 89, 85, 74, 73, 72, 71, 70, 66, 65, 59, 57, 56, 54, 52, 51, 50, 48, 46, 44, 43, 42, 41, 40, 39, 34, 33, 30, 29, 28, 27, 26, 25, 22, 21, 18, 17, 16, 15, 14, 11, 10, 9, 8, 5};
private SpoutClient() {
instance = this;
if (!Thread.currentThread().getName().equals("Minecraft main thread")) {
throw new SecurityException("Main thread name mismatch");
}
serverManager.init();
((SimpleKeyBindingManager)bindingManager).load();
Log.setVerbose(false);
Log.setLogSystem(new SilencedLogSystem());
DownloadAssets.getHttpAssets();
}
private class SilencedLogSystem implements LogSystem {
@Override
public void debug(String debug) {}
@Override
public void error(Throwable t) {}
@Override
public void error(String error) {}
@Override
public void error(String error, Throwable t) {}
@Override
public void info(String info) {}
@Override
public void warn(String warn) {}
@Override
public void warn(String warn, Throwable t) {}
}
static {
dataMiningThread.start();
Packet.addIdClassMapping(195, true, true, CustomPacket.class);
Configuration.read();
Keyboard.setKeyManager(new SimpleKeyManager());
FileUtil.migrateOldFiles();
}
public static SpoutClient getInstance() {
if (instance == null) {
Spoutcraft.setClient(new SpoutClient());
}
return instance;
}
public static String getClientVersion() {
return version;
}
public static boolean hasAvailableRAM() {
return Runtime.getRuntime().maxMemory() > 756L;
}
public long getServerVersion() {
return server;
}
public static String getSpoutcraftVersion() {
return spoutcraftVersion;
}
public static String getSpoutcraftBuild() {
return spoutcraftBuild;
}
public SkyManager getSkyManager() {
return skyManager;
}
public PacketManager getPacketManager() {
return packetManager;
}
public ClientPlayer getActivePlayer() {
return player;
}
public BiomeManager getBiomeManager() {
return biomeManager;
}
public MaterialManager getMaterialManager() {
return materialManager;
}
public net.minecraft.src.World getRawWorld() {
if (getHandle() == null) {
return null;
}
return getHandle().theWorld;
}
public boolean isSkyCheat() {
return cheatsky || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isForceSky() {
return forcesky || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isShowSky() {
return showsky || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isClearWaterCheat() {
return cheatclearwater || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isForceClearWater() {
return forceclearwater || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isShowClearWater() {
return showclearwater || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isStarsCheat() {
return cheatstars || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isForceStars() {
return forcestars || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isShowStars() {
return showstars || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isWeatherCheat() {
return cheatweather || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isForceWeather() {
return forceweather || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isShowWeather() {
return showweather || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isTimeCheat() {
return time || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isCoordsCheat() {
return coords || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isEntityLabelCheat() {
return entitylabel || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isFlySpeedCheat() {
return flySpeed || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isVoidFogCheat() {
return cheatvoidfog || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isForceVoidFog() {
return forcevoidfog || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public boolean isShowVoidFog() {
return showvoidfog || !getHandle().isMultiplayerWorld() || !isSpoutEnabled();
}
public void setVisualCheats(boolean tsky, boolean fsky, boolean ssky, boolean tclearwater, boolean fclearwater, boolean sclearwater, boolean tstars, boolean fstars, boolean sstars, boolean tweather, boolean fweather, boolean sweather, boolean ttime, boolean tcoords, boolean tentitylabel, boolean tvoidfog, boolean fvoidfog, boolean svoidfog, boolean tflyspeed) {
this.cheatsky = tsky;
this.forcesky = fsky;
this.showsky = ssky;
this.cheatclearwater = tclearwater;
this.forceclearwater = fclearwater;
this.showclearwater = sclearwater;
this.cheatstars = tstars;
this.forcestars = fstars;
this.showstars = sstars;
this.cheatweather = tweather;
this.forceweather = fweather;
this.showweather = sweather;
this.time = ttime;
this.coords = tcoords;
this.entitylabel = tentitylabel;
this.cheatvoidfog = tvoidfog;
this.forcevoidfog = fvoidfog;
this.showvoidfog = svoidfog;
this.flySpeed = tflyspeed;
if (!isTimeCheat()) {
Configuration.setTime(0);
}
if (cheatweather) {
Configuration.cheatweather = true;
} else {
Configuration.cheatweather = false;
}
if (cheatsky) {
Configuration.cheatsky = true;
} else {
Configuration.cheatsky = false;
}
if (cheatstars) {
Configuration.cheatstars = true;
} else {
Configuration.cheatstars = false;
}
if (cheatvoidfog) {
Configuration.cheatvoidFog = true;
} else {
Configuration.cheatvoidFog = false;
}
if (cheatclearwater) {
Configuration.cheatclearWater = true;
} else {
Configuration.cheatclearWater = false;
}
if (isForceWeather()) {
if (isShowWeather()) {
Configuration.setWeather(true);
} else {
Configuration.setWeather(false);
}
}
if (isForceStars()) {
if (isShowStars()) {
Configuration.setStars(true);
} else {
Configuration.setStars(false);
}
}
if (isForceSky()) {
if (isShowSky()) {
Configuration.setSky(true);
} else {
Configuration.setSky(false);
}
}
if (isForceClearWater()) {
if (isShowClearWater()) {
Configuration.setClearWater(true);
} else {
Configuration.setClearWater(false);
}
}
if (isForceWeather()) {
if (isShowWeather()) {
Configuration.setWeather(true);
} else {
Configuration.setWeather(false);
}
}
if (isForceVoidFog()) {
if (isShowVoidFog()) {
Configuration.setVoidFog(true);
} else {
Configuration.setVoidFog(false);
}
}
}
public boolean isSpoutEnabled() {
return server >= 0;
}
public void setSpoutVersion(long version) {
server = version;
}
public boolean isSpoutActive() {
return active;
}
public void setSpoutActive(boolean active) {
this.active = active;
}
public void onTick() {
tick++;
Configuration.onTick();
getHandle().mcProfiler.startSection("httpdownloads");
FileDownloadThread.getInstance().onTick();
getHandle().mcProfiler.endStartSection("packet_decompression");
PacketDecompressionThread.onTick();
getHandle().mcProfiler.endStartSection("widgets");
player.getMainScreen().onTick();
getHandle().mcProfiler.endStartSection("mipmapping");
MipMapUtils.onTick();
getHandle().mcProfiler.endStartSection("special_effects");
if (Minecraft.getMinecraft().theWorld != null) {
Minecraft.getMinecraft().theWorld.doColorfulStuff();
inWorldTicks++;
}
getHandle().mcProfiler.endStartSection("entity_info");
if (isSpoutEnabled()) {
LinkedList<CraftEntity> processed = new LinkedList<CraftEntity>();
Iterator<Entity> i = Entity.toProcess.iterator();
while (i.hasNext()) {
Entity next = i.next();
if (next.spoutEnty != null) {
processed.add((CraftEntity) next.spoutEnty);
}
}
Entity.toProcess.clear();
if (processed.size() > 0) {
getPacketManager().sendSpoutPacket(new PacketEntityInformation(processed));
}
}
getHandle().mcProfiler.endSection();
}
public long getTick() {
return tick;
}
public long getInWorldTicks() {
return inWorldTicks;
}
public void onWorldExit() {
FileUtil.deleteTempDirectory();
CustomTextureManager.resetTextures();
CRCManager.clear();
if (clipboardThread != null) {
clipboardThread.interrupt();
clipboardThread = null;
}
Minecraft.getMinecraft().sndManager.stopMusic();
PacketDecompressionThread.endThread();
MaterialData.reset();
FileDownloadThread.preCacheCompleted.lazySet(0);
server = -1L;
inWorldTicks = 0L;
MaterialData.reset();
MinimapConfig.getInstance().getServerWaypoints().clear();
}
public void onWorldEnter() {
if (player == null) {
player = ClientPlayer.getInstance();
player.setPlayer(getHandle().thePlayer);
getHandle().thePlayer.spoutEnty = player;
}
if (player.getHandle() instanceof EntityClientPlayerMP && isSpoutEnabled()) {
clipboardThread = new ClipboardThread((EntityClientPlayerMP)player.getHandle());
clipboardThread.start();
} else if (clipboardThread != null) {
clipboardThread.interrupt();
clipboardThread = null;
}
PacketDecompressionThread.startThread();
MipMapUtils.initializeMipMaps();
MipMapUtils.update();
player.getMainScreen().toggleSurvivalHUD(!Minecraft.getMinecraft().playerController.isInCreativeMode());
inWorldTicks = 0L;
MinimapConfig.getInstance().getServerWaypoints().clear();
}
public static Minecraft getHandle() {
return Minecraft.getMinecraft();
}
public AbstractClientPlayer getAbstractPlayerFromId(int id) {
if (getHandle().thePlayer.entityId == id) {
return getHandle().thePlayer;
}
WorldClient world = (WorldClient)getHandle().theWorld;
Entity e = world.getEntityByID(id);
if (e instanceof AbstractClientPlayer) {
return (AbstractClientPlayer) e;
}
return null;
}
public EntityPlayer getPlayerFromId(int id) {
if (getHandle().thePlayer.entityId == id) {
return getHandle().thePlayer;
}
WorldClient world = (WorldClient)getHandle().theWorld;
Entity e = world.getEntityByID(id);
if (e instanceof EntityPlayer) {
return (EntityPlayer) e;
}
return null;
}
public Entity getEntityFromId(int id) {
if (getHandle().thePlayer.entityId == id) {
return getHandle().thePlayer;
}
WorldClient world = (WorldClient)getHandle().theWorld;
return world.getEntityByID(id);
}
public Logger getLogger() {
return log;
}
public ServerManager getServerManager() {
return instance.serverManager;
}
public Mode getMode() {
return clientMode;
}
public void setMode(Mode clientMode) {
this.clientMode = clientMode;
}
public String getName() {
return "Spoutcraft";
}
public RenderDelegate getRenderDelegate() {
return render;
}
public File getUpdateFolder() {
return new File(Minecraft.getMinecraft().mcDataDir, "addons" + File.separator + "updates");
}
public String getVersion() {
return version;
}
public KeyBindingManager getKeyBindingManager() {
return bindingManager;
}
public File getAddonFolder() {
return new File(addonFolder);
}
public File getAudioCache() {
return getTemporaryCache();
}
public File getTemporaryCache() {
return FileUtil.getTempDir();
}
public File getTextureCache() {
return getTemporaryCache();
}
public File getTexturePackFolder() {
return FileUtil.getTexturePackDir();
}
public File getStatsFolder() {
return FileUtil.getStatsDir();
}
public WidgetManager getWidgetManager() {
return widgetManager;
}
@Override
public boolean hasPermission(String node) {
Boolean allow = permissions.get(node);
if (allow != null) {
return allow;
} else {
return true;
}
}
public void setPermission(String node, boolean allow) {
permissions.put(node, allow);
}
public void clearPermissions() {
permissions.clear();
}
}
| 412 | 0.938362 | 1 | 0.938362 | game-dev | MEDIA | 0.964913 | game-dev | 0.872075 | 1 | 0.872075 |
IAFEnvoy/IceAndFire-Fabric | 6,380 | src/main/java/com/iafenvoy/iceandfire/entity/block/BlockEntityJar.java | package com.iafenvoy.iceandfire.entity.block;
import com.iafenvoy.iceandfire.StaticVariables;
import com.iafenvoy.iceandfire.entity.EntityPixie;
import com.iafenvoy.iceandfire.registry.IafBlockEntities;
import com.iafenvoy.iceandfire.registry.IafEntities;
import com.iafenvoy.iceandfire.registry.IafParticles;
import com.iafenvoy.iceandfire.registry.IafSounds;
import com.iafenvoy.uranus.ServerHelper;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.inventory.Inventories;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket;
import net.minecraft.sound.SoundCategory;
import net.minecraft.util.Hand;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.Random;
import java.util.UUID;
public class BlockEntityJar extends BlockEntity {
private static final float PARTICLE_WIDTH = 0.3F;
private static final float PARTICLE_HEIGHT = 0.6F;
private final Random rand;
public boolean hasPixie;
public boolean prevHasProduced;
public boolean hasProduced;
public boolean tamedPixie;
public UUID pixieOwnerUUID;
public int pixieType;
public int ticksExisted;
public DefaultedList<ItemStack> pixieItems = DefaultedList.ofSize(1, ItemStack.EMPTY);
public float rotationYaw;
public float prevRotationYaw;
public BlockEntityJar(BlockPos pos, BlockState state) {
super(IafBlockEntities.PIXIE_JAR, pos, state);
this.rand = new Random();
this.hasPixie = true;
}
public BlockEntityJar(BlockPos pos, BlockState state, boolean empty) {
super(IafBlockEntities.PIXIE_JAR, pos, state);
this.rand = new Random();
this.hasPixie = !empty;
}
public static void tick(World level, BlockPos pos, BlockState state, BlockEntityJar entityJar) {
entityJar.ticksExisted++;
if (level.isClient && entityJar.hasPixie) {
level.addParticle(IafParticles.PIXIE_DUST,
pos.getX() + 0.5F + (double) (entityJar.rand.nextFloat() * PARTICLE_WIDTH * 2F) - PARTICLE_WIDTH,
pos.getY() + (double) (entityJar.rand.nextFloat() * PARTICLE_HEIGHT),
pos.getZ() + 0.5F + (double) (entityJar.rand.nextFloat() * PARTICLE_WIDTH * 2F) - PARTICLE_WIDTH, EntityPixie.PARTICLE_RGB[entityJar.pixieType][0], EntityPixie.PARTICLE_RGB[entityJar.pixieType][1], EntityPixie.PARTICLE_RGB[entityJar.pixieType][2]);
}
if (entityJar.ticksExisted % 24000 == 0 && !entityJar.hasProduced && entityJar.hasPixie) {
entityJar.hasProduced = true;
if (!level.isClient) {
PacketByteBuf buf = PacketByteBufs.create().writeBlockPos(pos);
buf.writeBoolean(entityJar.hasProduced);
ServerHelper.sendToAll(StaticVariables.UPDATE_PIXIE_JAR, buf);
}
}
if (entityJar.hasPixie && entityJar.hasProduced != entityJar.prevHasProduced && entityJar.ticksExisted > 5) {
if (!level.isClient) {
PacketByteBuf buf = PacketByteBufs.create().writeBlockPos(pos);
buf.writeBoolean(entityJar.hasProduced);
ServerHelper.sendToAll(StaticVariables.UPDATE_PIXIE_JAR, buf);
} else
level.playSound(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5, IafSounds.PIXIE_HURT, SoundCategory.BLOCKS, 1, 1, false);
}
entityJar.prevRotationYaw = entityJar.rotationYaw;
if (entityJar.rand.nextInt(30) == 0)
entityJar.rotationYaw = (entityJar.rand.nextFloat() * 360F) - 180F;
if (entityJar.hasPixie && entityJar.ticksExisted % 40 == 0 && entityJar.rand.nextInt(6) == 0 && level.isClient)
level.playSound(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5, IafSounds.PIXIE_IDLE, SoundCategory.BLOCKS, 1, 1, false);
entityJar.prevHasProduced = entityJar.hasProduced;
}
@Override
public void writeNbt(NbtCompound compound) {
compound.putBoolean("HasPixie", this.hasPixie);
compound.putInt("PixieType", this.pixieType);
compound.putBoolean("HasProduced", this.hasProduced);
compound.putBoolean("TamedPixie", this.tamedPixie);
if (this.pixieOwnerUUID != null)
compound.putUuid("PixieOwnerUUID", this.pixieOwnerUUID);
compound.putInt("TicksExisted", this.ticksExisted);
Inventories.writeNbt(compound, this.pixieItems);
}
@Override
public BlockEntityUpdateS2CPacket toUpdatePacket() {
return BlockEntityUpdateS2CPacket.create(this);
}
@Override
public void readNbt(NbtCompound compound) {
this.hasPixie = compound.getBoolean("HasPixie");
this.pixieType = compound.getInt("PixieType");
this.hasProduced = compound.getBoolean("HasProduced");
this.ticksExisted = compound.getInt("TicksExisted");
this.tamedPixie = compound.getBoolean("TamedPixie");
if (compound.containsUuid("PixieOwnerUUID"))
this.pixieOwnerUUID = compound.getUuid("PixieOwnerUUID");
this.pixieItems = DefaultedList.ofSize(1, ItemStack.EMPTY);
Inventories.readNbt(compound, this.pixieItems);
super.readNbt(compound);
}
public void releasePixie() {
EntityPixie pixie = new EntityPixie(IafEntities.PIXIE, this.world);
pixie.updatePositionAndAngles(this.pos.getX() + 0.5F, this.pos.getY() + 1F, this.pos.getZ() + 0.5F, new Random().nextInt(360), 0);
pixie.setStackInHand(Hand.MAIN_HAND, this.pixieItems.get(0));
pixie.setColor(this.pixieType);
assert this.world != null;
this.world.spawnEntity(pixie);
this.hasPixie = false;
this.pixieType = 0;
pixie.ticksUntilHouseAI = 500;
pixie.setTamed(this.tamedPixie);
pixie.setOwnerUuid(this.pixieOwnerUUID);
if (!this.world.isClient) {
PacketByteBuf buf = PacketByteBufs.create().writeBlockPos(this.pos);
buf.writeBoolean(false).writeInt(0);
ServerHelper.sendToAll(StaticVariables.UPDATE_PIXIE_HOUSE, buf);
}
}
}
| 412 | 0.917689 | 1 | 0.917689 | game-dev | MEDIA | 0.990882 | game-dev | 0.962294 | 1 | 0.962294 |
MahmoudNofaal/CCharp | 2,075 | CCharp/_18_Inheritance.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CCharp;
public class _18_Inheritance
{
public static void Ex01()
{
///INHERITANCE
///A technique which let aquire all properties and behaboirs its
/// parent type automatically.
///
/// WHY INHERITANCE
/// - REUSABILITY -قابلةلأعادة الاستخدام-
/// - MAINTAINABILITY -قابلة للصيانة-
/// - EXTENSIBILITYVICALLY -قابلة للتمدد-
///
/// - .NET DOES NOT SUPPORT MULTIPLE INHERITANCE
var l = new Lion("Simba", 5);
var e = new Eagle("Eagle1", 2);
l.Eat();
l.Roar();
e.Eat();
e.Fly();
}
public static void Ex02()
{
var animals = new List<Animal02>
{
new Dog("Duddy"),
new Animal02("Animal")
};
foreach(var a in animals)
{
a.MakeSound();
}
}
}
class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public Animal(string name, int age)
{
this.Name = name;
this.Age = age;
}
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
}
class Lion : Animal
{
public Lion(string name, int age) : base(name, age)
{
}
public void Roar()
{
Console.WriteLine($"{Name} roars loadly!");
}
}
class Eagle : Animal
{
public Eagle(string name, int age) : base(name, age)
{
}
public void Fly()
{
Console.WriteLine($"{Name} is flying!");
}
}
class Animal02
{
public string Name { get; set; }
public Animal02(string name)
{
this.Name=name;
}
///VIRTUAL METHOD, THAT CAN BE CUSTOMIZED BY THE DERIVED CLASS
public virtual void MakeSound()
{
Console.WriteLine($"{Name} makes a generic sound!");
}
}
class Dog : Animal02
{
public Dog(string name) : base(name)
{
}
///OVERRIDE THE DEFAULT BEHAVOIR
public override void MakeSound()
{
Console.WriteLine($"{Name} barks: Woof!");
}
}
| 412 | 0.708729 | 1 | 0.708729 | game-dev | MEDIA | 0.688926 | game-dev | 0.524363 | 1 | 0.524363 |
defold/defold | 2,648 | external/box2d/Box2D/src/island.h | // SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "array.h"
#include <stdbool.h>
#include <stdint.h>
typedef struct b2Contact b2Contact;
typedef struct b2Joint b2Joint;
typedef struct b2World b2World;
// Deterministic solver
//
// Collide all awake contacts
// Use bit array to emit start/stop touching events in defined order, per thread. Try using contact index, assuming contacts are
// created in a deterministic order. bit-wise OR together bit arrays and issue changes:
// - start touching: merge islands - temporary linked list - mark root island dirty - wake all - largest island is root
// - stop touching: increment constraintRemoveCount
// Persistent island for awake bodies, joints, and contacts
// https://en.wikipedia.org/wiki/Component_(graph_theory)
// https://en.wikipedia.org/wiki/Dynamic_connectivity
// map from int to solver set and index
typedef struct b2Island
{
// index of solver set stored in b2World
// may be B2_NULL_INDEX
int setIndex;
// island index within set
// may be B2_NULL_INDEX
int localIndex;
int islandId;
int headBody;
int tailBody;
int bodyCount;
int headContact;
int tailContact;
int contactCount;
int headJoint;
int tailJoint;
int jointCount;
// Union find
// todo this could go away if islands are merged immediately with b2LinkJoint and b2LinkContact
int parentIsland;
// Keeps track of how many contacts have been removed from this island.
// This is used to determine if an island is a candidate for splitting.
int constraintRemoveCount;
} b2Island;
// This is used to move islands across solver sets
typedef struct b2IslandSim
{
int islandId;
} b2IslandSim;
b2Island* b2CreateIsland( b2World* world, int setIndex );
void b2DestroyIsland( b2World* world, int islandId );
// Link contacts into the island graph when it starts having contact points
void b2LinkContact( b2World* world, b2Contact* contact );
// Unlink contact from the island graph when it stops having contact points
void b2UnlinkContact( b2World* world, b2Contact* contact );
// Link a joint into the island graph when it is created
void b2LinkJoint( b2World* world, b2Joint* joint, bool mergeIslands );
// Unlink a joint from the island graph when it is destroyed
void b2UnlinkJoint( b2World* world, b2Joint* joint );
void b2MergeAwakeIslands( b2World* world );
void b2SplitIsland( b2World* world, int baseId );
void b2SplitIslandTask( int startIndex, int endIndex, uint32_t threadIndex, void* context );
void b2ValidateIsland( b2World* world, int islandId );
B2_ARRAY_INLINE( b2Island, b2Island )
B2_ARRAY_INLINE( b2IslandSim, b2IslandSim )
| 412 | 0.53643 | 1 | 0.53643 | game-dev | MEDIA | 0.792569 | game-dev | 0.86374 | 1 | 0.86374 |
ccerhan/LibSVMsharp | 5,007 | LibSVMsharp/SVMProblem.cs | using LibSVMsharp.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace LibSVMsharp
{
public class SVMProblem
{
public SVMProblem()
{
Y = new List<double>();
X = new List<SVMNode[]>();
}
public int Length { get { return Y.Count; } }
public List<double> Y { get; private set; }
public List<SVMNode[]> X { get; private set; }
public void Add(SVMNode[] x, double y)
{
if (x.Length > 0)
{
SVMNode[] nodes = x.OrderBy(a => a.Index).ToArray();
X.Add(nodes);
Y.Add(y);
}
}
public void RemoveAt(int index)
{
if (index < Length)
{
Y.RemoveAt(index);
X.RemoveAt(index);
}
}
public void Insert(int index, SVMNode[] x, double y)
{
if (x.Length > 0)
{
SVMNode[] nodes = x.OrderBy(a => a.Index).ToArray();
X.Insert(index, x);
Y.Insert(index, y);
}
}
public SVMProblem Clone()
{
SVMProblem y = new SVMProblem();
for (int i = 0; i < Length; i++)
{
SVMNode[] nodes = X[i].Select(x => x.Clone()).ToArray();
y.Add(nodes, Y[i]);
}
return y;
}
public static SVMProblem Convert(svm_problem x)
{
double[] y_array = new double[x.l];
Marshal.Copy(x.y, y_array, 0, y_array.Length);
List<SVMNode[]> x_array = new List<SVMNode[]>();
IntPtr i_ptr_x = x.x;
for (int i = 0; i < x.l; i++)
{
IntPtr ptr_nodes = (IntPtr)Marshal.PtrToStructure(i_ptr_x, typeof(IntPtr));
SVMNode[] nodes = SVMNode.Convert(ptr_nodes);
x_array.Add(nodes);
i_ptr_x = IntPtr.Add(i_ptr_x, Marshal.SizeOf(typeof(IntPtr)));
}
SVMProblem y = new SVMProblem();
for (int i = 0; i < x.l; i++)
{
y.Add(x_array[i], y_array[i]);
}
return y;
}
public static SVMProblem Convert(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return null;
svm_problem x = (svm_problem)Marshal.PtrToStructure(ptr, typeof(svm_problem));
return SVMProblem.Convert(x);
}
public static IntPtr Allocate(SVMProblem x)
{
if (x == null || x.X == null || x.Y == null || x.Length < 1)
{
return IntPtr.Zero;
}
svm_problem y = new svm_problem();
y.l = x.Length;
// Allocate problem.y
y.y = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * x.Y.Count);
Marshal.Copy(x.Y.ToArray(), 0, y.y, x.Y.Count);
// Allocate problem.x
y.x = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * x.X.Count);
IntPtr i_ptr_x = y.x;
for (int i = 0; i < x.X.Count; i++)
{
// Prepare each node array
// 1) All nodes containing zero value is removed
// 2) A node which index is -1 is added to the end
List<SVMNode> temp = x.X[i].Where(a => a.Value != 0).ToList();
temp.Add(new SVMNode(-1, 0));
SVMNode[] nodes = temp.ToArray();
// Allocate node array
IntPtr ptr_nodes = SVMNode.Allocate(nodes);
Marshal.StructureToPtr(ptr_nodes, i_ptr_x, true);
i_ptr_x = IntPtr.Add(i_ptr_x, Marshal.SizeOf(typeof(IntPtr)));
}
// Allocate the problem
int size = Marshal.SizeOf(y);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(y, ptr, true);
return ptr;
}
public static void Free(svm_problem x)
{
Marshal.FreeHGlobal(x.y);
x.y = IntPtr.Zero;
IntPtr i_ptr_x = x.x;
for (int i = 0; i < x.l; i++)
{
IntPtr ptr_nodes = (IntPtr)Marshal.PtrToStructure(i_ptr_x, typeof(IntPtr));
SVMNode.Free(ptr_nodes);
i_ptr_x = IntPtr.Add(i_ptr_x, Marshal.SizeOf(typeof(IntPtr)));
}
Marshal.FreeHGlobal(x.x);
x.x = IntPtr.Zero;
}
public static void Free(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return;
svm_problem x = (svm_problem)Marshal.PtrToStructure(ptr, typeof(svm_problem));
SVMProblem.Free(x);
Marshal.DestroyStructure(ptr, typeof(svm_problem));
Marshal.FreeHGlobal(ptr);
ptr = IntPtr.Zero;
}
}
}
| 412 | 0.968122 | 1 | 0.968122 | game-dev | MEDIA | 0.208202 | game-dev | 0.980616 | 1 | 0.980616 |
AnkiTools/AnkiSharp | 18,051 | Anki.cs | using AnkiSharp.Helpers;
using AnkiSharp.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.SQLite;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Info = System.Tuple<string, string, AnkiSharp.Models.FieldList>;
namespace AnkiSharp
{
public class Anki
{
#region MEMBERS
private SQLiteConnection _conn;
private MediaInfo _mediaInfo;
private string _name;
private Assembly _assembly;
private string _path;
private string _collectionFilePath;
private List<AnkiItem> _ankiItems;
private Queue<CardMetadata> _cardsMetadatas;
private List<RevLogMetadata> _revLogMetadatas;
/// <summary>
/// Key : string which represent Mid
/// Value : Tuple string, string, FieldList which represent repectively the format, the css and the field list
/// </summary>
OrderedDictionary _infoPerMid;
#endregion
#region CTOR
/// <summary>
/// Creates a Anki object
/// </summary>
/// <param name="name">Specify the name of apkg file and deck</param>
/// <param name="path">Where to save your apkg file</param>
public Anki(string name, MediaInfo info = null, string path = null)
{
_cardsMetadatas = new Queue<CardMetadata>();
_revLogMetadatas = new List<RevLogMetadata>();
_assembly = Assembly.GetExecutingAssembly();
_mediaInfo = info;
if (path == null)
_path = Path.Combine(Path.GetDirectoryName(_assembly.Location), "tmp");
else
_path = path;
if (Directory.Exists(_path) == false)
Directory.CreateDirectory(_path);
Init(_path, name);
}
/// <summary>
/// Create anki object from an Apkg file
/// </summary>
/// <param name="name">Specify the name of apkg file and deck</param>
/// <param name="file">Apkg file</param>
public Anki(string name, ApkgFile file, MediaInfo info = null)
{
_cardsMetadatas = new Queue<CardMetadata>();
_revLogMetadatas = new List<RevLogMetadata>();
_assembly = Assembly.GetExecutingAssembly();
_path = Path.Combine(Path.GetDirectoryName(_assembly.Location), "tmp");
_mediaInfo = info;
if (Directory.Exists(_path) == false)
Directory.CreateDirectory(_path);
Init(_path, name);
_collectionFilePath = Path.Combine(_path, "collection.db");
ReadApkgFile(file.Path());
}
#endregion
#region FUNCTIONS
#region SETTERS
public void SetFields(params string[] values)
{
FieldList fields = new FieldList();
foreach (var value in values)
{
if (value.Contains("hint:") || value.Contains("type:"))
continue;
fields.Add(new Field(value));
}
var currentDefault = _infoPerMid["DEFAULT"] as Info;
var newDefault = new Info(currentDefault.Item1, currentDefault.Item2, fields);
_infoPerMid["DEFAULT"] = newDefault;
}
public void SetCss(string css)
{
var currentDefault = _infoPerMid["DEFAULT"] as Info;
var newDefault = new Info(currentDefault.Item1, css, currentDefault.Item3);
_infoPerMid["DEFAULT"] = newDefault;
}
public void SetFormat(string format)
{
var currentDefault = _infoPerMid["DEFAULT"] as Info;
var newDefault = new Info(format, currentDefault.Item2, currentDefault.Item3);
_infoPerMid["DEFAULT"] = newDefault;
}
#endregion
#region PUBLIC
/// <summary>
/// Create a apkg file with all the words
/// </summary>
public void CreateApkgFile(string path)
{
CreateDbFile();
CreateMediaFile();
ExecuteSQLiteCommands();
CreateZipFile(path);
}
/// <summary>
/// Creates an AnkiItem and add it to the Anki object
/// </summary>
public void AddItem(params string[] properties)
{
var mid = "";
IDictionaryEnumerator myEnumerator = _infoPerMid.GetEnumerator();
while (myEnumerator.MoveNext())
{
if (IsRightFieldList((myEnumerator.Value as Info).Item3, properties))
{
mid = myEnumerator.Key.ToString();
break;
}
}
if (mid == "" || (_infoPerMid.Contains(mid) && properties.Length != (_infoPerMid[mid] as Info).Item3.Count))
throw new ArgumentException("Number of fields provided is not the same as the one expected");
AnkiItem item = new AnkiItem((_infoPerMid[mid] as Info).Item3, properties)
{
Mid = mid
};
if (ContainsItem(item) == true)
return;
_ankiItems.Add(item);
}
/// <summary>
/// Add AnkiItem to the Anki object
/// </summary>
public void AddItem(AnkiItem item)
{
if (item.Mid == "")
item.Mid = "DEFAULT";
if (_infoPerMid.Contains(item.Mid) && item.Count != (_infoPerMid[item.Mid] as Info).Item3.Count)
throw new ArgumentException("Number of fields provided is not the same as the one expected");
else if (ContainsItem(item) == true)
return;
_ankiItems.Add(item);
}
/// <summary>
/// Tell if the anki object contains an AnkiItem (strict comparison)
/// </summary>
public bool ContainsItem(AnkiItem item)
{
int matching = 1;
foreach (var ankiItem in _ankiItems)
{
if (item == ankiItem)
++matching;
}
return matching == item.Count ? true : false;
}
/// <summary>
/// Tell if the anki object contains an AnkiItem (user defined comparison)
/// </summary>
public bool ContainsItem(Func<AnkiItem, bool> comparison)
{
foreach (var ankiItem in _ankiItems)
{
if (comparison(ankiItem))
return true;
}
return false;
}
public AnkiItem CreateAnkiItem(params string[] properties)
{
FieldList list = null;
IDictionaryEnumerator myEnumerator = _infoPerMid.GetEnumerator();
while (myEnumerator.MoveNext())
{
if (IsRightFieldList((myEnumerator.Value as Info).Item3, properties))
{
list = (myEnumerator.Value as Info).Item3;
break;
}
}
return new AnkiItem(list, properties);
}
#endregion
#region PRIVATE
private void CreateDbFile(string name = "collection.db")
{
_collectionFilePath = Path.Combine(_path, name);
if (File.Exists(_collectionFilePath) == true)
File.Delete(_collectionFilePath);
File.Create(_collectionFilePath).Close();
}
private void Init(string path, string name)
{
_infoPerMid = new OrderedDictionary();
_name = name;
_ankiItems = new List<AnkiItem>();
_assembly = Assembly.GetExecutingAssembly();
_path = path;
var css = GeneralHelper.ReadResource("AnkiSharp.AnkiData.CardStyle.css");
var fields = new FieldList
{
new Field("Front"),
new Field("Back")
};
_infoPerMid.Add("DEFAULT", new Info("", css, fields));
}
private bool IsRightFieldList(FieldList list, string[] properties)
{
if (list.Count != properties.Length)
return false;
return true;
}
private void CreateZipFile(string path)
{
string anki2FilePath = Path.Combine(_path, "collection.anki2");
string mediaFilePath = Path.Combine(_path, "media");
File.Move(_collectionFilePath, anki2FilePath);
string zipPath = Path.Combine(path, _name + ".apkg");
if (File.Exists(zipPath) == true)
File.Delete(zipPath);
ZipFile.CreateFromDirectory(_path, zipPath);
File.Delete(anki2FilePath);
File.Delete(mediaFilePath);
int i = 0;
string currentFile = Path.Combine(_path, i.ToString());
while (File.Exists(currentFile))
{
File.Delete(currentFile);
++i;
currentFile = Path.Combine(_path, i.ToString());
}
}
private string CreateCol()
{
Collection collection = new Collection(_infoPerMid, _ankiItems, _name);
SQLiteHelper.ExecuteSQLiteCommand(_conn, collection.Query);
return collection.DeckId;
}
private void CreateNotesAndCards(string id_deck, Anki anki = null)
{
Anki currentAnki = anki ?? (this);
foreach (var ankiItem in currentAnki._ankiItems)
{
Note note = new Note(currentAnki._infoPerMid, currentAnki._mediaInfo, ankiItem);
SQLiteHelper.ExecuteSQLiteCommand(currentAnki._conn, note.Query);
Card card = new Card(_cardsMetadatas, note, id_deck);
SQLiteHelper.ExecuteSQLiteCommand(currentAnki._conn, card.Query);
}
}
private void AddRevlogMetadata()
{
if (_revLogMetadatas.Count != 0)
{
string insertRevLog = "";
foreach (var revlogMetadata in _revLogMetadatas)
{
insertRevLog = "INSERT INTO revlog VALUES(" + revlogMetadata.id + ", " + revlogMetadata.cid + ", " + revlogMetadata.usn + ", " + revlogMetadata.ease + ", " + revlogMetadata.ivl + ", " + revlogMetadata.lastIvl + ", " + revlogMetadata.factor + ", " + revlogMetadata.time + ", " + revlogMetadata.type + ")";
SQLiteHelper.ExecuteSQLiteCommand(_conn, insertRevLog);
}
}
}
private void ExecuteSQLiteCommands(Anki anki = null)
{
try
{
_conn = new SQLiteConnection(@"Data Source=" + _collectionFilePath + ";Version=3;");
_conn.Open();
var column = GeneralHelper.ReadResource("AnkiSharp.SqLiteCommands.ColumnTable.txt");
var notes = GeneralHelper.ReadResource("AnkiSharp.SqLiteCommands.NotesTable.txt");
var cards = GeneralHelper.ReadResource("AnkiSharp.SqLiteCommands.CardsTable.txt");
var revLogs = GeneralHelper.ReadResource("AnkiSharp.SqLiteCommands.RevLogTable.txt");
var graves = GeneralHelper.ReadResource("AnkiSharp.SqLiteCommands.GravesTable.txt");
var indexes = GeneralHelper.ReadResource("AnkiSharp.SqLiteCommands.Indexes.txt");
SQLiteHelper.ExecuteSQLiteCommand(_conn, column);
SQLiteHelper.ExecuteSQLiteCommand(_conn, notes);
SQLiteHelper.ExecuteSQLiteCommand(_conn, cards);
SQLiteHelper.ExecuteSQLiteCommand(_conn, revLogs);
SQLiteHelper.ExecuteSQLiteCommand(_conn, graves);
SQLiteHelper.ExecuteSQLiteCommand(_conn, indexes);
var id_deck = CreateCol();
CreateNotesAndCards(id_deck, anki);
AddRevlogMetadata();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
_conn.Close();
_conn.Dispose();
SQLiteConnection.ClearAllPools();
}
}
private void CreateMediaFile()
{
string mediaFilePath = Path.Combine(_path, "media");
if (File.Exists(mediaFilePath))
File.Delete(mediaFilePath);
using (FileStream fs = File.Create(mediaFilePath))
{
string data = "{";
int i = 0;
if (_mediaInfo != null)
{
foreach (var item in _ankiItems)
{
if (_mediaInfo.extension == ".gif" && _mediaInfo.cultureInfo.Name == "zh-CN")
StrokeOrderHelper.DownloadImage(Path.Combine(_path, i.ToString()), item[_mediaInfo.field].ToString());
else if (_mediaInfo.extension == ".wav")
SynthetizerHelper.CreateAudio(Path.Combine(_path, i.ToString()), item[_mediaInfo.field].ToString(), _mediaInfo.cultureInfo, _mediaInfo.audioFormat);
data += "\"" + i.ToString() + "\": \"" + item[_mediaInfo.field] + _mediaInfo.extension + "\"";
if (i < _ankiItems.Count() - 1)
data += ", ";
i++;
}
}
data += "}";
byte[] info = new UTF8Encoding(true).GetBytes(data);
fs.Write(info, 0, info.Length);
fs.Close();
}
}
private void ReadApkgFile(string path)
{
if (File.Exists(Path.Combine(_path, "collection.db")))
File.Delete(Path.Combine(_path, "collection.db"));
if (File.Exists(Path.Combine(_path, "media")))
File.Delete(Path.Combine(_path, "media"));
ZipFile.ExtractToDirectory(path, _path);
string anki2File = Path.Combine(_path, "collection.anki2");
File.Move(anki2File, _collectionFilePath);
_conn = new SQLiteConnection(@"Data Source=" + _collectionFilePath + ";Version=3;");
try
{
_conn.Open();
Mapper mapper = Mapper.Instance;
var cardMetadatas = Mapper.MapSQLiteReader(_conn, "SELECT id, mod, type, queue, due, ivl, factor, reps, lapses, left, odue, odid FROM cards");
foreach (var cardMetadata in cardMetadatas)
{
_cardsMetadatas.Enqueue(cardMetadata.ToObject<CardMetadata>());
}
SQLiteDataReader reader = SQLiteHelper.ExecuteSQLiteCommandRead(_conn, "SELECT notes.flds, notes.mid FROM notes");
List<double> mids = new List<double>();
string[] splitted = null;
List<string[]> result = new List<string[]>();
while (reader.Read())
{
splitted = reader.GetString(0).Split('\x1f');
var currentMid = reader.GetInt64(1);
if (mids.Contains(currentMid) == false)
mids.Add(currentMid);
result.Add(splitted);
}
reader.Close();
reader = SQLiteHelper.ExecuteSQLiteCommandRead(_conn, "SELECT models FROM col");
JObject models = null;
while (reader.Read())
{
models = JObject.Parse(reader.GetString(0));
}
AddFields(models, mids);
reader.Close();
var revLogMetadatas = Mapper.MapSQLiteReader(_conn, "SELECT * FROM revlog");
foreach (var revLogMetadata in revLogMetadatas)
{
_revLogMetadatas.Add(revLogMetadata.ToObject<RevLogMetadata>());
}
foreach (var res in result)
{
AddItem(res);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
_conn.Close();
_conn.Dispose();
SQLiteConnection.ClearAllPools();
}
}
private void AddFields(JObject models, List<double> mids)
{
var regex = new Regex("{{hint:(.*?)}}|{{type:(.*?)}}|{{(.*?)}}");
foreach (var mid in mids)
{
var qfmt = models["" + mid]["tmpls"].First["qfmt"].ToString().Replace("\"", "");
var afmt = models["" + mid]["tmpls"].First["afmt"].ToString();
var css = models["" + mid]["css"].ToString();
afmt = afmt.Replace("{{FrontSide}}", qfmt);
var matches = regex.Matches(afmt);
FieldList fields = new FieldList();
foreach (Match match in matches)
{
if (match.Value.Contains("type:") || match.Value.Contains("hint:"))
continue;
var value = match.Value;
var field = new Field(value.Replace("{{", "").Replace("}}", ""));
fields.Add(field);
}
_infoPerMid.Add("" + mid, new Info(afmt.Replace("\n", "\\n"), css.Replace("\n", "\\n"), fields));
}
}
#endregion
#endregion
}
}
| 412 | 0.97806 | 1 | 0.97806 | game-dev | MEDIA | 0.360763 | game-dev,desktop-app | 0.978532 | 1 | 0.978532 |
tgstation/TerraGov-Marine-Corps | 2,065 | code/modules/buildmode/submodes/variable_edit.dm | /datum/buildmode_mode/varedit
key = "edit"
/// The name of the variable to modifiy
var/var_name = null
/// The value to modify to
var/var_value = null
/datum/buildmode_mode/varedit/Destroy()
var_name = null
var_value = null
return ..()
/datum/buildmode_mode/varedit/show_help(client/user)
to_chat(user, custom_boxed_message("purple_box",\
"[span_bold("Select var(type) & value")] -> Right Mouse Button on buildmode button\n\
[span_bold("Set var(type) & value")] -> Left Mouse Button on turf/obj/mob\n\
[span_bold("Reset var's value")] -> Right Mouse Button on turf/obj/mob"))
/datum/buildmode_mode/varedit/change_settings(client/user)
var_name = input(user, "Enter variable name:" ,"Name", "name")
if(!vv_varname_lockcheck(var_name))
return
var/temp_value = user.vv_get_value()
if(isnull(temp_value["class"]))
var_name = null
var_value = null
to_chat(user, span_notice("Variable unset."))
return
var_value = temp_value["value"]
/datum/buildmode_mode/varedit/handle_click(client/user, params, obj/object)
var/list/modifiers = params2list(params)
if(isnull(var_name))
to_chat(user, span_warning("Choose a variable to modify first."))
return
if(LAZYACCESS(modifiers, LEFT_CLICK))
if(!object.vars.Find(var_name))
to_chat(user, span_warning("[initial(object.name)] does not have a var called '[var_name]'"))
return
if(object.vv_edit_var(var_name, var_value) == FALSE)
to_chat(user, span_warning("Your edit was rejected by the object."))
return
log_admin("Build Mode: [key_name(user)] modified [object.name]'s [var_name] to [var_value]")
if(LAZYACCESS(modifiers, RIGHT_CLICK))
if(!object.vars.Find(var_name))
to_chat(user, span_warning("[initial(object.name)] does not have a var called '[var_name]'"))
return
var/reset_value = initial(object.vars[var_name])
if(object.vv_edit_var(var_name, reset_value) == FALSE)
to_chat(user, span_warning("Your edit was rejected by the object."))
return
log_admin("Build Mode: [key_name(user)] modified [object.name]'s [var_name] to [reset_value]")
| 412 | 0.797889 | 1 | 0.797889 | game-dev | MEDIA | 0.440288 | game-dev | 0.712818 | 1 | 0.712818 |
CraftTweaker/CraftTweaker | 2,587 | neoforge/src/main/java/com/blamejared/crafttweaker/impl/event/CTModEventHandler.java | package com.blamejared.crafttweaker.impl.event;
import com.blamejared.crafttweaker.api.CraftTweakerConstants;
import com.blamejared.crafttweaker.api.tag.CraftTweakerTagRegistry;
import com.blamejared.crafttweaker.gametest.CraftTweakerGameTests;
import com.blamejared.crafttweaker.impl.network.packet.ClientBoundPackets;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.tags.TagManager;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.data.event.GatherDataEvent;
import net.neoforged.neoforge.event.RegisterGameTestsEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import net.neoforged.neoforge.network.registration.PayloadRegistrar;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@EventBusSubscriber(modid = CraftTweakerConstants.MOD_ID, bus = EventBusSubscriber.Bus.MOD)
public class CTModEventHandler {
@SubscribeEvent
public static void registerPackets(RegisterPayloadHandlersEvent event) {
PayloadRegistrar registrar = event.registrar(CraftTweakerConstants.MOD_ID)
.versioned(CraftTweakerConstants.NETWORK_VERSION_STRING);
for(ClientBoundPackets msg : ClientBoundPackets.values()) {
registrar.playToClient(msg.type(), msg.streamCodec(), (payload, context) -> context.enqueueWork(payload::handle));
}
}
@SubscribeEvent
public static void onRegisterGameTests(RegisterGameTestsEvent event) {
event.register(CraftTweakerGameTests.class);
}
/**
* Creates a fake tag registry for mods using CraftTweaker in their own DataGen.
*/
@SubscribeEvent(priority = EventPriority.HIGHEST)
public static void gatherData(GatherDataEvent event) {
if(event.includeServer()) {
List<TagManager.LoadResult<?>> loadResults = new ArrayList<>();
for(RegistryDataLoader.RegistryData<?> data : RegistryDataLoader.WORLDGEN_REGISTRIES) {
loadResults.add(new TagManager.LoadResult<>(data.key(), new HashMap<>()));
}
for(Registry<?> registry : BuiltInRegistries.REGISTRY) {
loadResults.add(new TagManager.LoadResult<>(registry.key(), new HashMap<>()));
}
CraftTweakerTagRegistry.INSTANCE.bind(loadResults);
}
}
}
| 412 | 0.917227 | 1 | 0.917227 | game-dev | MEDIA | 0.96956 | game-dev | 0.846645 | 1 | 0.846645 |
Fluorohydride/ygopro-scripts | 1,163 | c24707869.lua | --ブライト・フューチャー
function c24707869.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_DRAW)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c24707869.target)
e1:SetOperation(c24707869.activate)
c:RegisterEffect(e1)
end
function c24707869.filter(c)
return c:IsFaceup() and c:IsRace(RACE_PSYCHO)
end
function c24707869.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c24707869.filter(chkc) end
if chk==0 then return Duel.IsPlayerCanDraw(tp,1)
and Duel.IsExistingTarget(c24707869.filter,tp,LOCATION_REMOVED,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectTarget(tp,c24707869.filter,tp,LOCATION_REMOVED,0,2,2,nil)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c24707869.activate(e,tp,eg,ep,ev,re,r,rp)
local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
if tg:GetCount()~=2 then return end
Duel.SendtoGrave(tg,REASON_EFFECT+REASON_RETURN)
Duel.Draw(tp,1,REASON_EFFECT)
end
| 412 | 0.888579 | 1 | 0.888579 | game-dev | MEDIA | 0.974358 | game-dev | 0.902785 | 1 | 0.902785 |
modernuo/ModernUO | 5,525 | Projects/UOContent/Engines/ML Quests/Definitions/WarriorsOfTheGemKeeper.cs | using System;
using Server.Engines.MLQuests.Objectives;
using Server.Engines.MLQuests.Rewards;
using Server.Items;
namespace Server.Engines.MLQuests.Definitions
{
public class WarriorsOfTheGemkeeper : MLQuest
{
public WarriorsOfTheGemkeeper()
{
Activated = true;
Title = 1074536; // Warriors of the Gemkeeper
Description =
1074537; // Here we honor the Gemkeeper's Apprentice and seek to aid her efforts against the humans responsible for the death of her teacher - and the destruction of the elven way of life. Our tales speak of a fierce race of servants of the Gemkeeper, the men-bulls whose battle-skill was renowned. It is desireable to discover the fate of these noble creatures after the Rupture. Will you seek information?
RefusalMessage = 1074063; // Fine then, I'm shall find another to run my errands then.
InProgressMessage =
1074540; // I care not how you get the information. Kill as many humans as you must ... but find the fate of the minotaurs. Perhaps another of the Gemkeeper's servants has the knowledge we seek.
CompletionMessage = 1074542; // What have you found?
Objectives.Add(new CollectObjective(1, typeof(FragmentOfAMap), "fragment of a map"));
Rewards.Add(new DummyReward(1074876)); // Knowledge of the legendary minotaur.
}
public override Type NextQuest => typeof(CloseEnough);
}
public class CloseEnough : MLQuest
{
public CloseEnough()
{
Activated = true;
Title = 1074544; // Close Enough
Description =
1074546; // Ah ha! You see here ... and over here ... The map fragment places the city of the bull-men, Labyrinth, on that piece of Sosaria that was thrown into the sky. Hmmm, I would have you go there and seek out these warriors to see if they might join our cause. But, legend speaks of a mighty barrier to prevent invasion of the city. Take this map to Canir and explain the problem. Perhaps she can devise a solution.
RefusalMessage = 1074063; // Fine then, I'm shall find another to run my errands then.
InProgressMessage = 1074548; // Canir is nearby, run and speak with her.
CompletionMessage = 1074549; // Yes? What do you want? I'm very busy.
Objectives.Add(new DeliverObjective(typeof(FragmentOfAMapDelivery), 1, "fragment of a map", typeof(Canir)));
Rewards.Add(new DummyReward(1074876)); // Knowledge of the legendary minotaur.
}
public override Type NextQuest => typeof(TakingTheBullByTheHorns);
public override bool IsChainTriggered => true;
}
public class TakingTheBullByTheHorns : MLQuest
{
public TakingTheBullByTheHorns()
{
Activated = true;
Title = 1074551; // Taking the Bull by the Horns
Description =
1074553; // Interesting. I believe I have a way. I will need some materials to infuse you with the essence of a bull-man, so you can fool their defenses. The most similar beast to the original Baratarian bull that the minotaur were bred from is undoubtedly the mighty Gaman, native to the Lands of the Feudal Lords. I need horns, in great quantity to undertake this magic.
RefusalMessage = 1074554; // Oh come now, don't be afraid. The magic won't harm you.
InProgressMessage =
1074555; // I cannot grant you the ability to pass through the bull-men's defenses without the gaman horns.
CompletionMessage =
1074556; // You've returned at last! Give me just a moment to examine what you've brought and I can perform the magic that will allow you enter the Labyrinth.
Objectives.Add(new CollectObjective(20, typeof(GamanHorns), "gaman horns"));
Rewards.Add(new DummyReward(1074876)); // Knowledge of the legendary minotaur.
}
public override Type NextQuest => typeof(EmissaryToTheMinotaur);
public override bool IsChainTriggered => true;
}
public class EmissaryToTheMinotaur : MLQuest
{
public EmissaryToTheMinotaur()
{
Activated = true;
Title = 1074824; // Emissary to the Minotaur
Description =
1074825; // *whew* It is done! The fierce essence of the bull has been infused into your aura. You are able now to breach the ancient defenses of the city. Go forth and seek the minotaur -- and then return with wonderous tales and evidence of your visit to the Labyrinth.
RefusalMessage =
1074827; // As you wish. I can't understand why you'd pass up such a remarkable opportunity. Think of the adventures you would have.
InProgressMessage =
1074828; // You won't reach the minotaur city by loitering around here! What are you waiting for? You need to get to Malas and find the access point for the island. You'll be renowned for your discovery!
CompletionMessage =
1074829; // Oh! You've returned at last! I can't wait to hear the tales ... but first, let me see those artifacts. You've certainly earned this reward.
Objectives.Add(new CollectObjective(3, typeof(MinotaurArtifact), "minotaur artifacts"));
Rewards.Add(ItemReward.Strongbox);
}
public override bool IsChainTriggered => true;
}
}
| 412 | 0.727938 | 1 | 0.727938 | game-dev | MEDIA | 0.964888 | game-dev | 0.781096 | 1 | 0.781096 |
oot-pc-port/oot-pc-port | 2,235 | asm/non_matchings/overlays/actors/ovl_En_Blkobj/func_809C21A0.s | glabel func_809C21A0
/* 00140 809C21A0 27BDFFC8 */ addiu $sp, $sp, 0xFFC8 ## $sp = FFFFFFC8
/* 00144 809C21A4 AFBF0034 */ sw $ra, 0x0034($sp)
/* 00148 809C21A8 AFB00030 */ sw $s0, 0x0030($sp)
/* 0014C 809C21AC 8C8E0004 */ lw $t6, 0x0004($a0) ## 00000004
/* 00150 809C21B0 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 00154 809C21B4 31CF0040 */ andi $t7, $t6, 0x0040 ## $t7 = 00000000
/* 00158 809C21B8 55E00013 */ bnel $t7, $zero, .L809C2208
/* 0015C 809C21BC 8FBF0034 */ lw $ra, 0x0034($sp)
/* 00160 809C21C0 C6040028 */ lwc1 $f4, 0x0028($s0) ## 00000028
/* 00164 809C21C4 8E070024 */ lw $a3, 0x0024($s0) ## 00000024
/* 00168 809C21C8 24A41C24 */ addiu $a0, $a1, 0x1C24 ## $a0 = 00001C24
/* 0016C 809C21CC E7A40010 */ swc1 $f4, 0x0010($sp)
/* 00170 809C21D0 C606002C */ lwc1 $f6, 0x002C($s0) ## 0000002C
/* 00174 809C21D4 AFA00018 */ sw $zero, 0x0018($sp)
/* 00178 809C21D8 24060033 */ addiu $a2, $zero, 0x0033 ## $a2 = 00000033
/* 0017C 809C21DC E7A60014 */ swc1 $f6, 0x0014($sp)
/* 00180 809C21E0 8618008A */ lh $t8, 0x008A($s0) ## 0000008A
/* 00184 809C21E4 AFA00024 */ sw $zero, 0x0024($sp)
/* 00188 809C21E8 AFA00020 */ sw $zero, 0x0020($sp)
/* 0018C 809C21EC 0C00C7D4 */ jal Actor_Spawn
## ActorSpawn
/* 00190 809C21F0 AFB8001C */ sw $t8, 0x001C($sp)
/* 00194 809C21F4 3C05809C */ lui $a1, %hi(func_809C2218) ## $a1 = 809C0000
/* 00198 809C21F8 24A52218 */ addiu $a1, $a1, %lo(func_809C2218) ## $a1 = 809C2218
/* 0019C 809C21FC 0C270818 */ jal func_809C2060
/* 001A0 809C2200 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 001A4 809C2204 8FBF0034 */ lw $ra, 0x0034($sp)
.L809C2208:
/* 001A8 809C2208 8FB00030 */ lw $s0, 0x0030($sp)
/* 001AC 809C220C 27BD0038 */ addiu $sp, $sp, 0x0038 ## $sp = 00000000
/* 001B0 809C2210 03E00008 */ jr $ra
/* 001B4 809C2214 00000000 */ nop
| 412 | 0.757615 | 1 | 0.757615 | game-dev | MEDIA | 0.915909 | game-dev | 0.507798 | 1 | 0.507798 |
ServUO/ServUO | 1,583 | Scripts/Items/Artifacts/Equipment/Weapons/ArcticDeathDealer.cs | using System;
namespace Server.Items
{
public class ArcticDeathDealer : WarMace
{
public override bool IsArtifact { get { return true; } }
[Constructable]
public ArcticDeathDealer()
{
Hue = 0x480;
WeaponAttributes.HitHarm = 33;
WeaponAttributes.HitLowerAttack = 40;
Attributes.WeaponSpeed = 20;
Attributes.WeaponDamage = 40;
WeaponAttributes.ResistColdBonus = 10;
}
public ArcticDeathDealer(Serial serial)
: base(serial)
{
}
public override int LabelNumber
{
get
{
return 1063481;
}
}
public override int InitMinHits
{
get
{
return 255;
}
}
public override int InitMaxHits
{
get
{
return 255;
}
}
public override void GetDamageTypes(Mobile wielder, out int phys, out int fire, out int cold, out int pois, out int nrgy, out int chaos, out int direct)
{
cold = 50;
phys = 50;
pois = fire = nrgy = chaos = direct = 0;
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | 412 | 0.857702 | 1 | 0.857702 | game-dev | MEDIA | 0.93085 | game-dev | 0.663692 | 1 | 0.663692 |
historicalsource/journey | 14,566 | voyage.zabstr |
<BEGIN-SEGMENT BOAT>
<OBJECT BOAT-TWIN-ISLES (LOC BOAT) (SDESC "Twin Isles") (8DESC "TwinIsle") (
FLAGS DONT-TAKE) (KBD 84) (ACTION <ACOND () (<EQUAL? ,ACTION ,EXAMINE-COMMAND>
<UPDATE-MOVE> <PRINTI
"Far off, near the southern horizon, we could see the Twin Isles of Estril
and Lethor. Between them, the sea itself grew dim and lost definition."> <CRLF>
<CRLF> <PRINTI "\"What do you make of that?\" "> <WPRINTD ,ACTOR> <PRINTI
" asked one of the crewmen working
nearby."> <CRLF> <CRLF> <PRINTI
"\"Why, that's the Misty Isle,\" he responded, surprised that this was not
common knowledge. \"Sorry's the man that loses his way and enters those
sinister seas.\"">)>)>
<DEFINE-ROUTINE ANONF-359>
<OBJECT BOAT-CREW (LOC BOAT) (SDESC "crew") (FLAGS DONT-TAKE) (KBD 67) (EXBITS
PRAXIXBIT) (ACTION <ACOND () (<EQUAL? ,ACTION ,EXAMINE-COMMAND> <UPDATE-MOVE> <
PRINTI "Praxix, having never been to sea, was fascinated by the crew of the ">
<WPRINTD ,CHOSEN-BOAT> <PRINTI
". There were perhaps half a dozen of them, and each
was busily addressing himself to the various tasks and chores of
the seafaring life.">)>)>
<DEFINE-ROUTINE ANONF-360>
<OBJECT BOAT-CAPTAIN (LOC BOAT) (SDESC "captain") (FLAGS DONT-TAKE DONT-EXAMINE
) (KBD 67) (ACTION <ACOND () (<AND <EQUAL? ,ACTION ,USE-MIX-COMMAND> <EQUAL? ,
MIXTURE ,BEND-WILL-SPELL>> <COND (<EQUAL? ,CHOSEN-BOAT ,SOUTH-SEAS> <PRINTI
"I am certain now that Praxix "> <COND (<FSET? ,BEND-WILL-SPELL ,TRAPPED> <
PRINTI "sensed the treachery that lurked within the captain, for he cast the will
bending spell at him. But Praxix was grappling with a will more
powerful than his own - the will of the "> <PRINT ,BAD-GUY> <PRINTI
" himself. It was a losing
battle - Praxix'">) (T <PRINTI
"did not anticipate the effect of the mixture he cast upon the captain. At first,
nothing happened, but soon Praxix'">)> <PRINTI
" body soon began to writhe, and he clutched at his head as if to keep it
from splitting apart. And then, with a horrible scream, he fell to the ground
in a heap. I said nothing of this to the others, so overcome was I with
fear."> <CRLF> <CRLF> <FSET ,STORMY-SEAS ,TRAPPED> <MOVE-TO ,STORMY-SEAS>) (T <
PRINTI "Perhaps Praxix was bored, but he decided to cast one of his mixtures at
the captain. Happily, the captain didn't complain about the cloud of dust
that had been thrown in his face, though he did cough and sneeze a bit
for a while afterwards. As for the mixture itself, it seemed to have no
useful effect.">)>)>)>
<DEFINE-ROUTINE ANONF-361>
<OBJECT BOAT-SKY (LOC BOAT) (SDESC "sky") (FLAGS DONT-TAKE) (KBD 83) (EXBITS <+
,PRAXIXBIT ,HURTHBIT>) (ACTION <ACOND () (<EQUAL? ,ACTION ,EXAMINE-COMMAND> <
UPDATE-MOVE> <PRINTI
"Above us and to the south, the sky was a brilliant blue. But a
fast-moving storm was approaching rapidly from the north. Every so
often, bolts of lightning danced among the clouds."> <CRLF> <CRLF> <PRINTI
"\"Looks like rain,\" "> <WPRINTD ,ACTOR> <PRINTI
" said, in what turned out to be one of
the great understatements of our journey.">)>)>
<DEFINE-ROUTINE ANONF-362>
<COMMAND RELAX>
<ROOM BOAT (TRAVEL-COMMANDS RELAX-COMMAND NUL-COMMAND NUL-COMMAND) (CAST-LIMIT
INF) (GRAPHIC G-BOAT) (FLAGS ENCLOSED) (ENTER <EXECUTE () <SAVE-SPELL ,
FIRE-SPELL> <SAVE-SPELL ,TREMOR-SPELL> <TELL CR CR
"We were welcomed aboard by Captain "> <TELL-CAPTAIN> <TELL ", who"> <COND (<
NOT ,CAPTAIN> <PRINTI ", surprisingly sober,">)> <TELL
" informed us that
the ship was ready to sail. It was nearly an hour before the sails were
raised and we were underway, but a favoring wind carried us swiftly to
the south. Soon, the faint outline of the Twin Isles appeared at the
horizon."> <COND (<EQUAL? ,CHOSEN-BOAT ,SOUTH-SEAS> <FSET ,HERE ,FORBIDDING> <
CHECK-FOREBODING>)>>) (ACTION <ACOND () (<EQUAL? ,ACTION ,RELAX-COMMAND> <
MOVE-TO ,STORMY-SEAS>) (<EQUAL? ,ACTION ,CAST-COMMAND> <COND (<EQUAL? ,
ACTION-OBJECT ,WIND-SPELL> <REMOVE ,HYE-BOAT> <PRINTI
"Praxix, feeling himself a captive, sought to amuse himself by casting
his wind spell. It was lucky that he used only a small amount of air
essence, for the resulting gale nearly capsized our craft, causing great
concern from the captain and crew."> <CRLF> <CRLF> <PRINTI
"\"Promise you won't tell!\" Praxix said, seeing that I had observed the
whole thing.">) (<OR <EQUAL? ,ACTION-OBJECT ,RAIN-SPELL> <EQUAL? ,ACTION-OBJECT
,LIGHTNING-SPELL>> <REMOVE ,HYE-VOYAGE> <UNUSE-ESSENCES> <PRINTI
"Later, Praxix confided in me that he had considered casting the \""> <WPRINTD
,ACTION-OBJECT> <PRINTI
"\" spell, but one look at the approaching clouds convinced him that
he could add nothing to what nature had in store.">) (<EQUAL? ,ACTION-OBJECT ,
LEVITATE-SPELL> <REMOVE ,HYE-BOAT> <PRINTI
"Bored to distraction by this ocean voyage, Praxix decided to get a
better look around, and cast his elevation spell on himself. Fifty
feet above decks, he gazed out toward the Twin Isles, much to the
surprise of the captain and crew, who had never seen such a magical
display before."> <CRLF> <CRLF> <PRINTI
"\"Do you think it wise to flaunt your powers, Praxix?\" Bergon asked,
irritated at the Wizard's display."> <CRLF> <CRLF> <PRINTI
"\"I suppose you are right,\" Praxix replied, \"but being at sea makes me
rather nervous.\"">)>) (<EQUAL? ,ACTION ,SCOUT-COMMAND> <UPDATE-FSET ,HERE ,
DONT-SCOUT> <FSET ,HERE ,SCOUTED> <MAKE-BUSY ,ACTOR ,GONE-COMMAND> <WPRINTD ,
ACTOR> <PRINTI " then went off to explore the boat; in fact, there was little else to
do.">)>)>
<DEFINE-ROUTINE ANONF-363>
<DEFINE-ROUTINE ANONF-364>
<OBJECT STORMY-SEAS-BOAT (LOC STORMY-SEAS) (SDESC "boat") (KBD 66) (FLAGS
DONT-TAKE) (EXBITS <+ ,PRAXIXBIT ,ESHERBIT>) (ACTION <ACOND () (<EQUAL? ,ACTION
,EXAMINE-COMMAND> <UPDATE-MOVE> <PRINTI
"The boat was badly damaged by the storm; the mizzenmast had collapsed
and fallen into the ocean; the main mast still stood, though it was
heavily weakened and nearly ready to collapse under its own weight. The
main sail, though torn, was serviceable, but the rudder had been destroyed,
making steering all but impossible."> <CRLF> <CRLF> <PRINTI
"\"What a mess,\" said "> <WPRINTD ,ACTOR> <PRINTI
", who had not yet recovered from the
shock."> <CRLF> <CRLF> <PRINTI
"\"What are we to do?\" I asked, \"Not only the air is still, but - see
here - the ocean itself is perfectly still and glassy. I think I understand
why it is that people never return from this place.\"">)>)>
<DEFINE-ROUTINE ANONF-365>
<COMMAND (CLIMB-MAST CLIMB)>
<GLOBAL SPOTTED-ISLAND? <>>
<GLOBAL TRIED-CASTING-WIND? <>>
<ROOM STORMY-SEAS (TRAVEL-COMMANDS NUL-COMMAND NUL-COMMAND NUL-COMMAND) (
CAST-LIMIT INF) (ENTER TELL-STORM) (FLAGS DANGEROUS DONT-SCOUT) (CLOCK <EXECUTE
() <COND (<NOT <CHECK-ESSENCES ,WIND-SPELL>> <CRLF> <CRLF> <PRINTI
"The boat floated in the unrelenting mist for many days, without even a hint
of movement. Praxix, sadly, could do nothing, having run entirely out of air
essence. But then, on the third day at sea, another storm rose up and tossed
the boat violently, flinging it into a submerged reef."> <ILL-WIND #
ZLOCAL!-IZILCH TRUE-VALUE>)>>) (ACTION <ACOND () (<EQUAL? ,ACTION ,
CLIMB-MAST-COMMAND> <REMOVE-TRAVEL-COMMAND> <COND (,TRIED-CASTING-WIND? <PRINTI
"I tried to locate the Misty Isle">) (T <PRINTI
"I tried to gain some view of our situation">)> <PRINTI
" by climbing the mast, but it shook so badly as I clambered up that I became
frightened and returned to the deck."> <CRLF> <CRLF> <PRINTI
"\"A wise decision,\" Praxix said, \"You will do us no good by falling from
the mast.\"">) (<EQUAL? ,ACTION ,PROCEED-COMMAND> <ILL-WIND>) (<EQUAL? ,ACTION
,STOP-COMMAND> <PRINTI
"Thinking it better to hold off for the moment, Praxix put his
air essence away and considered what to do next."> <END-OPTION>) (<EQUAL? ,
ACTION ,CAST-COMMAND> <COND (<EQUAL? ,ACTION-OBJECT ,FAR-VISION-SPELL> <PRINTI
"It was reasonable to give Praxix' flare spell a try, but his fireball
was enveloped by the gloom almost as it left his fingertips.">) (<EQUAL? ,
ACTION-OBJECT ,WIND-SPELL> <COND (,SPOTTED-ISLAND? <PRINTI
"Using my fix on the island as a reference, Praxix cast his wind spell
into the air. The wind blew fiercely, as the "> <WPRINTD ,CHOSEN-BOAT> <PRINTI
" made
its way through the fog. It was only minutes later when we escaped
the fog; an island was ahead..."> <CRLF> <CRLF> <PRINTI
"\"The Misty Isle,\" said Praxix, \"And, wouldn't you know it - it's
not even misty!\""> <CRLF> <CRLF> <COND (,DEMON-SEARCHING? <DEMON-TELL>) (T <
ISLAND-ENDING>)>) (,TRIED-CASTING-WIND? <REMOVE ,HYE-MIST> <ILL-WIND>) (T <SET
TRIED-CASTING-WIND? #ZLOCAL!-IZILCH TRUE-VALUE> <PRINTI
"Praxix started to remove the air essence from his pouch, but
was struck with a dilemma."> <CRLF> <CRLF> <PRINTI
"\"From which direction shall the wind blow?\" he asked me, not
expecting an answer."> <CRLF> <CRLF> <PRINTI
"I answered anyway, trying to make light of our desperate situation.
\"Onshore,\" I said."> <OPTION ,PRAXIX ,PROCEED-COMMAND ,STOP-COMMAND>)>) (<AND
<EQUAL? ,ACTION-OBJECT ,LEVITATE-SPELL> <NOT ,SPOTTED-ISLAND?>> <SET
SPOTTED-ISLAND? #ZLOCAL!-IZILCH TRUE-VALUE> <PRINTI
"Praxix whipped up a large batch of his elevation spell and cast it
at me. I had risen only a few dozen feet before I lost sight of the deck,
and then I climbed a while longer, terrified by the gray nothingness
that surrounded me. And then, I cleared the mist and was suspended in
the clear afternoon air. Before me, an island stood, basking in the
warmth of a cloudless sky."> <CRLF> <CRLF> <PRINTI
"Slowly, I descended to the deck, indicating to Praxix in which direction
the island lay."> <CRLF> <CRLF> <REMOVE-TRAVEL-COMMAND ,HERE ,
CLIMB-MAST-COMMAND> <PRINTI
"\"Well, well,\" he said, \"We may survive this voyage after all!\"">)>)>)>
<DEFINE-ROUTINE ANONF-366>
<DEFINE-ROUTINE ANONF-367>
<DEFINE-ROUTINE ILL-WIND>
<COMMAND STOP>
<DEFINE-ROUTINE TELL-STORM>
<DEFINE-ROUTINE TELL-CAPTAIN>
<CONSTANT WAVE-SAVE
" Tossed with me into the tumult, it had split in two, its larger piece intact
and floating on the waves. Grabbing hold of that precious flotsam, I pulled myself
up and fell unconscious atop it. The next day, the storm having passed, I was found
by passing fishermen and taken back to Zan where, after a few sleepless nights, I
booked passage to Lendros, and my home in the plains.">
<OBJECT PRAXIX-POUCH (SDESC "Praxix' pouch") (12DESC "pouch") (8DESC "pouch") (
KBD 80) (FLAGS DONT-EXAMINE) (ACTION <ACOND () (<EQUAL? ,ACTION ,
PICK-UP-COMMAND> <UPDATE-FSET ,PRAXIX-POUCH ,DONT-TAKE> <SET TAG-HOLDING-POUCH
#ZLOCAL!-IZILCH TRUE-VALUE> <TRAVEL-COMMANDS ,TAG ,MIX-COMMAND> <PRINTI
"Lying beside Praxix was his pouch of magical powders, and, as
discreetly as I could, I picked them up. Inside the pouch were a number
of smaller bags. Of these, only the reagents were simple to recognize. But
the others numbered "> <PRINT #ZLOCAL!-IZILCH STACK> <PRINTI
", not four as I had expected.
Each of these bags held a powder, and these powders were of different colors and
consistencies."> <CRLF> <CRLF> <PRINTI
"I tried to think what Praxix would do, what he was trying to do, when he was
struck down by this messenger of evil. "> <COND (<FSET? ,LIGHTNING-SPELL ,SEEN>
<PRINTI "And then it occurred to me: lightning, which">)> <COND (<NOT <FSET? ,
LIGHTNING-SPELL ,SEEN>> <PRINTI
"I thought about the various spells that Praxix had cast during our
journey, but none seemed powerful enough. Perhaps Praxix had a spell
to call forth a bolt of lightning, but even so, I had no idea of which
combination of essences would produce it?">) (<FSET? ,LIGHTNING-SPELL ,
INCAPACITATED> <PRINTI
", I remembered, was a mixture
of fire and water essences, with just a pinch of earth essence.
The only problem was: which essence was which?">) (T <PRINTI
" I suspected would be the
combination of fire and water essences. The only problem was: which essence
was which?"> <COND (<FSET? ,TALE-MAGIC ,SEEN> <PRINTI
" And was there a third essence involved, as Praxix said was
sometimes the case?">)> <RTRUE>)>)>)>
<DEFINE-ROUTINE ANONF-368>
<GLOBAL TAG-HOLDING-POUCH <>>
<OBJECT DEMON-DEMON (TIME 0) (ACTION <EXECUTE () <COND (<AND <EQUAL? ,ACTION ,
EXAMINE-COMMAND> <EQUAL? ,ACTION-OBJECT ,PRAXIX-OBJECT>> <RTRUE>)> <SETG
DEMON-COUNT <ADD ,DEMON-COUNT 1>> <TELL CR CR> <COND (<ZERO? ,DEMON-COUNT> <
PRINTI "\"We know who you are, and we know what you seek,\" the demon continued,
\"but you will be needing a lesson in manners.\"">) (<EQUAL? ,DEMON-COUNT 1> <
PRINTI "\"Let me see,\" the demon went on, \"Who, do you suppose, should receive
this lesson?\"">) (<EQUAL? ,DEMON-COUNT 2> <SETG DEMON-VICTIM <FIRST-IN-PARTY ,
HURTH ,ESHER ,MINAR ,BERGON>> <PRINTI
"\"Praxix will not do,\" the demon spat, \"I would not like
to be accused of destroying one so defenseless. No, I believe the
honor should go to "> <WPRINTD ,DEMON-VICTIM> <PRINTI ".\"">) (<EQUAL? ,
DEMON-COUNT 3> <PRINTI "\""> <WPRINTD ,DEMON-VICTIM> <PRINTI
", rise!\" the demon ordered, and, face contorted
hideously, the demon's victim stood and approached the foul monster.">) (T <
PARTY-REMOVE ,DEMON-VICTIM> <PRINTI
"And then, the demon stretched out his arm, hand open, at "> <WPRINTD ,
DEMON-VICTIM> <PRINTI " and, as he slowly closed his hand, it seemed that "> <
WPRINTD ,DEMON-VICTIM> <PRINTI
" was
being squeezed mercilessly; he screamed in agony as he demon's fist closed
ever tighter. Moments later, he was dead, crushed by this awful monster."> <
CRLF> <CRLF> <PRINTI
"\"The same fate, or worse, awaits all those who seek to defy the "> <PRINT ,
BAD-GUY> <PRINTI
". This is but a taste of what is to follow.\" Then, he swung his arm to his
side and opened his clenched fist; "> <WPRINTD ,DEMON-VICTIM> <PRINTI
"'s body was flung from
the boat and into the ocean waters."> <CRLF> <CRLF> <PRINTI
"Mounting the awful creature that had borne him here, he flew off into
the distant north."> <COND (<NOT ,TAG-HOLDING-POUCH> <HINT ,HINT-POUCH>)> <
END-DEMON>)>>)>
<DEFINE-ROUTINE ANONF-369>
<GLOBAL DEMON-VICTIM <>>
<DEFINE-ROUTINE DEMON-TELL>
<OBJECT PRAXIX-OBJECT (SDESC "Praxix") (FLAGS DONT-TAKE) (EXBITS ESHERBIT) (
ACTION <ACOND () (<EQUAL? ,ACTION ,EXAMINE-COMMAND> <UPDATE-MOVE> <WPRINTD ,
ACTOR> <PRINTI " went over to where Praxix lay and examined him thoroughly."> <
CRLF> <CRLF> <PRINTI "\"He's not hurt badly,\" he said."> <CRLF> <CRLF> <PRINTI
"\"How very thoughful you are, "> <WPRINTD ,ACTOR> <PRINTI
",\" the demon boomed. \"But do not concern
yourself, for I shall not kill your Wizard friend - at least not yet. But now to
business.\"">)>)>
<DEFINE-ROUTINE ANONF-370>
<DEFINE-ROUTINE END-DEMON> | 412 | 0.623566 | 1 | 0.623566 | game-dev | MEDIA | 0.458198 | game-dev | 0.636889 | 1 | 0.636889 |
MegaMek/megamek | 10,141 | megamek/src/megamek/common/MPCalculationSetting.java | /*
* Copyright (C) 2023-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMek 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.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megamek.common;
/**
* This class represents a setting used to calculate walk, run, jump or sprint MP. The setting contains info on whether
* to include gravity, MASC, weather, current heat and other circumstances in the MP calculation. All
* MPCalculationSettings can be used for all calculations though some settings may have no special effect; e.g. checking
* for submerged jump jets will not ever change the walk MP result. The baseline setting for in-game calculations is
* {@link #STANDARD}.
* <p>
* This class is immutable.
*/
public record MPCalculationSetting(boolean ignoreGravity, boolean ignoreHeat, boolean ignoreModularArmor,
boolean ignoreChainDrape, boolean ignoreMASC, boolean ignoreMyomerBooster, boolean ignoreDWP,
boolean ignoreBurden, boolean ignoreCargo, boolean ignoreWeather, boolean singleMASC,
boolean ignoreSubmergedJumpJets, boolean ignoreGrounded, boolean ignoreOptionalRules, boolean ignoreConversion,
boolean forceTSM) {
/**
* The standard in-game setting, taking into account every circumstance except submerged jump jets (in this setting,
* submerged jump jets will not reduce the result of jump MP calculation).
*/
public static final MPCalculationSetting STANDARD = new Builder().build();
/** A setting that excludes heat effects on MP. */
public static final MPCalculationSetting NO_HEAT = new Builder().noHeat().build();
/** A setting that excludes myomer booster effects on BA/PM. */
public static final MPCalculationSetting NO_MYOMER_BOOSTER = new Builder().noMyomerBooster().build();
/** A setting that excludes MASC effects on run MP. */
public static final MPCalculationSetting NO_MASC = new Builder().noMASC().build();
/**
* A setting that excludes gravity effects on MP. (Use: e.g. gravity-related PSRs)
*/
public static final MPCalculationSetting NO_GRAVITY = new Builder().noGravity().build();
/** A setting that includes the effect of at most a single MASC on run MP. */
public static final MPCalculationSetting ONE_MASC = new Builder().singleMASC().build();
/** A setting that excludes the effects of being grounded for Aero's. */
public static final MPCalculationSetting NO_GROUNDED = new Builder().noGrounded().build();
/**
* A setting for checking if a unit moved too fast under the effects of low gravity.
*/
public static final MPCalculationSetting SAFE_MOVE = new Builder().noGravity()
.noHeat()
.noModularArmor()
.noChainDrape()
.build();
/**
* A setting for testing if a unit is permanently immobilized. It excludes transient effects such as being grounded
* for Aero's and the effects of heat and cargo.
*/
public static final MPCalculationSetting PERM_IMMOBILIZED = new Builder().noGrounded().noHeat().noCargo().build();
/** A setting that reduces calculated jump MP for submerged jump jets. */
public static final MPCalculationSetting DEDUCT_SUBMERGED_JJ = new Builder().deductSubmergedJumpJets().build();
/**
* A setting for finding full MP on BA, disregarding burdened status and DWP (Use: printing BA record sheets).
*/
public static final MPCalculationSetting BA_UNBURDENED = new Builder().noHeat().baNoBurden().noDWP().build();
/**
* The setting for Alpha Strike conversion, excluding scenario circumstances as well as myomer boosters, DWP, BA
* burden and modular armor.
*/
public static final MPCalculationSetting AS_CONVERSION = new Builder().noGravity().noWeather()
.noHeat().noCargo().baNoBurden().noMyomerBooster().noDWP().noModularArmor().noChainDrape().noGrounded()
.noConversion().noOptionalRules().build();
/**
* The setting for Battle Value calculation, excluding scenario circumstances and heat as well as myomer boosters,
* DWP, MASC, Cargo and Bombs and grounded state of Aero's.
*/
public static final MPCalculationSetting BV_CALCULATION = new Builder().noGravity()
.noWeather()
.noHeat()
.noCargo()
.noDWP()
.noGrounded()
.noOptionalRules()
.noConversion()
.noModularArmor()
.forceTSM()
.baNoBurden()
.build();
private static class Builder {
private boolean ignoreGravity = false;
private boolean ignoreHeat = false;
private boolean ignoreModularArmor = false;
private boolean ignoreChainDrape = false;
private boolean ignoreBADWP = false;
private boolean ignoreMyomerBooster = false;
private boolean ignoreMASC = false;
private boolean ignoreBABurden = false;
private boolean ignoreCargo = false;
private boolean ignoreWeather = false;
private boolean singleMASC = false;
private boolean ignoreSubmergedJumpJets = true;
private boolean ignoreGrounded = false;
private boolean ignoreOptionalRules = false;
private boolean ignoreConversion = false;
private boolean forceTSM = false;
MPCalculationSetting build() {
return new MPCalculationSetting(ignoreGravity, ignoreHeat, ignoreModularArmor, ignoreChainDrape, ignoreMASC,
ignoreMyomerBooster, ignoreBADWP, ignoreBABurden, ignoreCargo, ignoreWeather, singleMASC,
ignoreSubmergedJumpJets, ignoreGrounded, ignoreOptionalRules, ignoreConversion, forceTSM);
}
/** Disregards the effects of the current heat of the unit. */
private Builder noHeat() {
ignoreHeat = true;
return this;
}
/** Disregards the effects of gravity. */
private Builder noGravity() {
ignoreGravity = true;
return this;
}
/** Disregards the effects of MASC systems. */
private Builder noMASC() {
ignoreMASC = true;
singleMASC = false;
return this;
}
/** Disregards the effects of DWP on BA. */
private Builder noDWP() {
ignoreBADWP = true;
return this;
}
/**
* Disregards the effects of being burdened by equipment that can be jettisoned on BA.
*/
private Builder baNoBurden() {
ignoreBABurden = true;
return this;
}
/** Disregards the effects of myomer boosters on BA and PM. */
private Builder noMyomerBooster() {
ignoreMyomerBooster = true;
return this;
}
/**
* Disregards the effects of carried or towed cargo and units, including bomb load.
*/
private Builder noCargo() {
ignoreCargo = true;
return this;
}
/**
* Disregards the effects of wind, temperature and other planetary conditions (but not gravity).
*/
private Builder noWeather() {
ignoreWeather = true;
return this;
}
/** Disregards the effects of modular armor. */
private Builder noModularArmor() {
ignoreModularArmor = true;
return this;
}
/** Disregards the effects of a chain drape */
private Builder noChainDrape() {
ignoreChainDrape = true;
return this;
}
/** Allows the effects of at most one MASC system if the unit has any MASC. */
private Builder singleMASC() {
singleMASC = true;
ignoreMASC = false;
return this;
}
/**
* Reduces jump MP for submerged jump jets. Does not affect any other MP calculation.
*/
private Builder deductSubmergedJumpJets() {
ignoreSubmergedJumpJets = false;
return this;
}
/**
* Ignores the effects of flying units being grounded (considers them airborne).
*/
private Builder noGrounded() {
ignoreGrounded = true;
return this;
}
/**
* Ignores some baseline movement-enhancing optional rules (Use: BV calculation).
*/
private Builder noOptionalRules() {
ignoreOptionalRules = true;
return this;
}
/**
* Ignores the current conversion state of the entity and considers it to be in its base state.
*/
private Builder noConversion() {
ignoreConversion = true;
return this;
}
/**
* Applies the effects of TSM (if the entity has it!) regardless of the current heat of the entity (Use: BV
* calculation).
*/
private Builder forceTSM() {
forceTSM = true;
return this;
}
}
}
| 412 | 0.561948 | 1 | 0.561948 | game-dev | MEDIA | 0.867462 | game-dev | 0.742506 | 1 | 0.742506 |
pascalabcnet/pascalabcnet | 3,327 | Utils/NodesGeneratorNew/Scintilla/Sources/ScintillaNET/WhitespaceStringConverter.cs | #region Using Directives
using System;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
#endregion Using Directives
namespace ScintillaNET
{
public class WhitespaceStringConverter : TypeConverter
{
#region Fields
private static readonly Regex rr = new Regex("\\{0x([0123456789abcdef]{1,4})\\}", RegexOptions.IgnoreCase);
#endregion Fields
#region Methods
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(char) || sourceType == typeof(string))
return true;
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(char) || destinationType == typeof(string))
return true;
return false;
}
private string ConvertFrom(string value)
{
Match m = rr.Match(value);
while (m.Success)
{
int val = int.Parse(m.Value.Substring(3, m.Length - 4), NumberStyles.AllowHexSpecifier);
value = value.Replace(m.Value, ((char)val).ToString());
m = rr.Match(value);
}
value = value.Replace("{TAB}", "\t").Replace("{LF}", "\r").Replace("{CR}", "\n").Replace("{SPACE}", " ");
return value;
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string val = ConvertFrom(value.ToString());
if (context.PropertyDescriptor.ComponentType == typeof(char))
return val[0];
return val;
}
private string ConvertTo(string nativeString)
{
StringBuilder sb = new StringBuilder();
foreach (char c in nativeString)
{
if ((int)c > 32)
{
sb.Append(c);
continue;
}
switch ((int)c)
{
case 9:
sb.Append("{TAB}");
break;
case 10:
sb.Append("{LF}");
break;
case 13:
sb.Append("{CR}");
break;
case 32:
sb.Append("{SPACE}");
break;
default:
sb.Append("{0x" + ((int)c).ToString("x4") + "}");
break;
}
}
return sb.ToString();
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
string val = ConvertTo(value.ToString());
if (destinationType == typeof(char))
return val[0];
return val;
}
public override bool IsValid(ITypeDescriptorContext context, object value)
{
return true;
}
#endregion Methods
}
}
| 412 | 0.94697 | 1 | 0.94697 | game-dev | MEDIA | 0.234835 | game-dev | 0.86133 | 1 | 0.86133 |
LiteLDev/LeviLamina | 2,238 | src-server/mc/world/redstone/circuit/components/SidePoweredComponent.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated inclusion list
#include "mc/world/redstone/circuit/components/CapacitorComponent.h"
#include "mc/world/redstone/circuit/components/CircuitComponentList.h"
// auto generated forward declare list
// clang-format off
class BaseCircuitComponent;
class BlockPos;
class CircuitSceneGraph;
class CircuitTrackingInfo;
// clang-format on
class SidePoweredComponent : public ::CapacitorComponent {
public:
// member variables
// NOLINTBEGIN
::ll::TypedStorage<8, 24, ::CircuitComponentList> mSideComponents;
// NOLINTEND
public:
// virtual functions
// NOLINTBEGIN
// vIndex: 0
virtual ~SidePoweredComponent() /*override*/;
// vIndex: 26
virtual uchar getPoweroutDirection() const /*override*/;
// vIndex: 12
virtual bool
allowConnection(::CircuitSceneGraph& graph, ::CircuitTrackingInfo const& info, bool& bDirectlyPowered) /*override*/;
// vIndex: 6
virtual bool canConsumePowerAnyDirection() const /*override*/;
// vIndex: 7
virtual bool canConsumerPower() const /*override*/;
// vIndex: 10
virtual void removeSource(::BlockPos const& posSource, ::BaseCircuitComponent const* pComponent) /*override*/;
// vIndex: 23
virtual void removeFromAnySourceList(::BaseCircuitComponent const* component) /*override*/;
// NOLINTEND
public:
// member functions
// NOLINTBEGIN
MCAPI void _removeSideSource(::BlockPos const& posSource);
// NOLINTEND
public:
// destructor thunk
// NOLINTBEGIN
MCAPI void $dtor();
// NOLINTEND
public:
// virtual function thunks
// NOLINTBEGIN
MCFOLD uchar $getPoweroutDirection() const;
MCFOLD bool $allowConnection(::CircuitSceneGraph& graph, ::CircuitTrackingInfo const& info, bool& bDirectlyPowered);
MCFOLD bool $canConsumePowerAnyDirection() const;
MCFOLD bool $canConsumerPower() const;
MCAPI void $removeSource(::BlockPos const& posSource, ::BaseCircuitComponent const* pComponent);
MCAPI void $removeFromAnySourceList(::BaseCircuitComponent const* component);
// NOLINTEND
public:
// vftables
// NOLINTBEGIN
MCAPI static void** $vftable();
// NOLINTEND
};
| 412 | 0.946946 | 1 | 0.946946 | game-dev | MEDIA | 0.326593 | game-dev | 0.572735 | 1 | 0.572735 |
Flo56958/MineTinker | 6,339 | src/main/java/de/flo56958/minetinker/modifiers/types/Building.java | package de.flo56958.minetinker.modifiers.types;
import de.flo56958.minetinker.MineTinker;
import de.flo56958.minetinker.api.events.MTPlayerInteractEvent;
import de.flo56958.minetinker.data.ToolType;
import de.flo56958.minetinker.modifiers.PlayerConfigurableModifier;
import de.flo56958.minetinker.utils.ConfigurationManager;
import de.flo56958.minetinker.utils.LanguageManager;
import de.flo56958.minetinker.utils.data.DataHandler;
import de.flo56958.minetinker.utils.playerconfig.PlayerConfigurationManager;
import de.flo56958.minetinker.utils.playerconfig.PlayerConfigurationOption;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.type.Slab;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Building extends PlayerConfigurableModifier implements Listener {
private static Building instance;
private boolean useDurability;
private boolean giveExpOnUse;
private int expAmount;
private Building() {
super(MineTinker.getPlugin());
customModelData = 10_069;
}
public static Building instance() {
synchronized (Building.class) {
if (instance == null)
instance = new Building();
}
return instance;
}
@Override
public String getKey() {
return "Building";
}
@Override
public List<ToolType> getAllowedTools() {
return Arrays.asList(ToolType.AXE, ToolType.PICKAXE, ToolType.SHOVEL, ToolType.HOE, ToolType.SHEARS);
}
@Override
public void reload() {
FileConfiguration config = getConfig();
config.options().copyDefaults(true);
config.addDefault("Allowed", true);
config.addDefault("MaxLevel", 1);
config.addDefault("SlotCost", 1);
config.addDefault("Color", "%GREEN%");
config.addDefault("ModifierItemMaterial", Material.GRASS_BLOCK.name());
config.addDefault("UseDurability", true);
config.addDefault("GiveExpOnUse", true);
config.addDefault("ExpAmount", 1);
config.addDefault("EnchantCost", 15);
config.addDefault("Enchantable", true);
config.addDefault("MinimumToolLevelRequirement", 1);
config.addDefault("Recipe.Enabled", false);
ConfigurationManager.saveConfig(config);
ConfigurationManager.loadConfig("Modifiers" + File.separator, getFileName());
init();
this.useDurability = config.getBoolean("UseDurability", true);
this.giveExpOnUse = config.getBoolean("GiveExpOnUse", true);
this.expAmount = config.getInt("ExpAmount", 1);
}
@EventHandler(ignoreCancelled = true)
public void onPlace(@NotNull final MTPlayerInteractEvent event) {
if (event.getEvent().getAction() != Action.RIGHT_CLICK_BLOCK) return;
final Player player = event.getPlayer();
if (!player.hasPermission(getUsePermission())) return;
final ItemStack tool = event.getTool();
if (!modManager.hasMod(tool, this)) return;
if (!PlayerConfigurationManager.getInstance().getBoolean(player, ENABLED)) return;
final Block block = event.getEvent().getClickedBlock();
if (block == null) return;
if (block.isPassable() || block.isLiquid()) return; // do not do passable blocks
final Block toFill = block.getRelative(event.getEvent().getBlockFace());
if (!toFill.isPassable() && !toFill.isLiquid() && !toFill.isEmpty()) return;
final boolean isDoubleSlab = block.getBlockData() instanceof Slab slab && slab.getType() == Slab.Type.DOUBLE;
ItemStack toPlace = null;
if (player.getGameMode() == GameMode.CREATIVE) {
toPlace = new ItemStack(block.getType(), 2); // in case of double slabs
} else {
for (final ItemStack stack : event.getPlayer().getInventory().getContents()) {
if (stack == null) continue;
if (block.getType() != stack.getType()) continue;
if (stack.hasItemMeta()) continue; // use only normal blocks
if (isDoubleSlab && stack.getAmount() < 2) continue;
toPlace = stack;
break;
}
if (toPlace == null) return;
// check Tool durability
if (this.useDurability && !DataHandler.triggerItemDamage(player, tool, 1)) return;
}
if (!DataHandler.playerPlaceBlock(player, toPlace, toFill, block, block.getState(), block.getBlockData()))
return; // TODO: restore durability
if (this.giveExpOnUse)
modManager.addExp(player, tool, this.expAmount, true);
if (PlayerConfigurationManager.getInstance().getBoolean(player, SOLVE_PLAYER_OVERLAP)) {
// Teleport player one block up if he is inside the block
final BoundingBox blockBB = toFill.getBoundingBox();
final BoundingBox playerBB = player.getBoundingBox();
if (blockBB.overlaps(playerBB)) {
final BoundingBox intersection = blockBB.intersection(playerBB);
// Intersection size * block diff = push vector
final Vector diff = toFill.getLocation().subtract(block.getLocation()).toVector();
final Vector intersectionSize = intersection.getMax().subtract(intersection.getMin());
final Vector push = intersectionSize.multiply(diff);
player.teleport(player.getLocation().add(push));
}
}
event.getEvent().setUseInteractedBlock(Event.Result.DENY); // prevent vanilla behavior by cancelling the event
toPlace.setAmount(toPlace.getAmount() - (isDoubleSlab ? 2 : 1));
}
private final PlayerConfigurationOption ENABLED =
new PlayerConfigurationOption(this, "enabled", PlayerConfigurationOption.Type.BOOLEAN,
LanguageManager.getString("Modifier.Homing.PCO_enabled"), true);
private final PlayerConfigurationOption SOLVE_PLAYER_OVERLAP =
new PlayerConfigurationOption(this, "solve-player-overlap", PlayerConfigurationOption.Type.BOOLEAN,
LanguageManager.getString("Modifier.Building.PCO_solve_player_overlap"), true);
@Override
public List<PlayerConfigurationOption> getPCIOptions() {
final ArrayList<PlayerConfigurationOption> playerConfigurationOptions = new ArrayList<>(List.of(ENABLED, SOLVE_PLAYER_OVERLAP));
playerConfigurationOptions.sort(Comparator.comparing(PlayerConfigurationOption::displayName));
return playerConfigurationOptions;
}
}
| 412 | 0.941288 | 1 | 0.941288 | game-dev | MEDIA | 0.977479 | game-dev | 0.971594 | 1 | 0.971594 |
mastercomfig/tf2-patches-old | 17,772 | src/game/client/hl1/hl1_hud_weaponselection.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "weapon_selection.h"
#include "iclientmode.h"
#include "ammodef.h"
#include "input.h"
#include <KeyValues.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <vgui/ISystem.h>
#include <vgui_controls/Panel.h>
#include <string.h>
#define HL1_MAX_WEAPON_SLOTS 5
//-----------------------------------------------------------------------------
// Purpose: hl2 weapon selection hud element
//-----------------------------------------------------------------------------
class CHudWeaponSelection : public CBaseHudWeaponSelection, public vgui::Panel
{
DECLARE_CLASS_SIMPLE( CHudWeaponSelection, vgui::Panel );
public:
CHudWeaponSelection(const char *pElementName );
bool ShouldDraw();
void CycleToNextWeapon( void );
void CycleToPrevWeapon( void );
C_BaseCombatWeapon *GetWeaponInSlot( int iSlot, int iSlotPos );
void SelectWeaponSlot( int iSlot );
C_BaseCombatWeapon *GetSelectedWeapon( void )
{
return m_hSelectedWeapon;
}
void VidInit( void );
C_BaseCombatWeapon *GetNextActivePos( int iSlot, int iSlotPos );
protected:
void Paint();
void ApplySchemeSettings(vgui::IScheme *pScheme);
private:
C_BaseCombatWeapon *FindNextWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition);
C_BaseCombatWeapon *FindPrevWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition);
void FastWeaponSwitch( int iWeaponSlot );
void DrawAmmoBar( C_BaseCombatWeapon *pWeapon, int x, int y, int nWidth, int nHeight );
int DrawBar( int x, int y, int width, int height, float f );
void SetSelectedWeapon( C_BaseCombatWeapon *pWeapon )
{
m_hSelectedWeapon = pWeapon;
}
CHudTexture *icon_buckets[ HL1_MAX_WEAPON_SLOTS ];
CHudTexture *icon_selection;
Color m_clrReddish;
Color m_clrGreenish;
};
DECLARE_HUDELEMENT( CHudWeaponSelection );
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CHudWeaponSelection::CHudWeaponSelection( const char *pElementName ) : CBaseHudWeaponSelection(pElementName), BaseClass(NULL, "HudWeaponSelection")
{
vgui::Panel *pParent = g_pClientMode->GetViewport();
SetParent( pParent );
}
void CHudWeaponSelection::VidInit()
{
Reset();
for ( int i = 0; i < HL1_MAX_WEAPON_SLOTS; i++ )
{
char szNumString[ 10 ];
sprintf( szNumString, "bucket%d", i );
icon_buckets[ i ] = gHUD.GetIcon( szNumString );
}
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the panel should draw
//-----------------------------------------------------------------------------
bool CHudWeaponSelection::ShouldDraw()
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
{
if ( IsInSelectionMode() )
{
HideSelection();
}
return false;
}
bool bret = CBaseHudWeaponSelection::ShouldDraw();
if ( !bret )
return false;
return ( m_bSelectionVisible ) ? true : false;
}
//-------------------------------------------------------------------------
// Purpose: draws the selection area
//-------------------------------------------------------------------------
void CHudWeaponSelection::Paint()
{
if (!ShouldDraw())
return;
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
// find and display our current selection
C_BaseCombatWeapon *pSelectedWeapon = GetSelectedWeapon();
if ( !pSelectedWeapon )
return;
int iActiveSlot = (pSelectedWeapon ? pSelectedWeapon->GetSlot() : -1);
int xpos = 10;
// iterate over all the weapon slots
for ( int i = 0; i < HL1_MAX_WEAPON_SLOTS; i++ )
{
int nWidth;
int r1, g1, b1, a1;
(gHUD.m_clrYellowish).GetColor( r1, g1, b1, a1 );
int ypos = 10;
icon_buckets[ i ]->DrawSelf( xpos, ypos, Color( r1, g1, b1, 255 ) );
ypos = icon_buckets[ i ]->Height() + 10;
if ( i == iActiveSlot )
{
bool bFirstItem = true;
nWidth = icon_buckets[ i ]->Width();
for ( int slotpos = 0; slotpos < MAX_WEAPON_POSITIONS; slotpos++ )
{
C_BaseCombatWeapon *pWeapon = GetWeaponInSlot( i, slotpos );
if ( !pWeapon )
continue;
// icons use old system, drawing in screen space
if ( pWeapon->GetSpriteActive() )
{
int r, g, b, a;
(gHUD.m_clrYellowish).GetColor( r, g, b, a );
if (pWeapon == pSelectedWeapon)
{
pWeapon->GetSpriteActive()->DrawSelf( xpos, ypos, Color( r, g, b, a ) );
if ( !icon_selection )
{
icon_selection = gHUD.GetIcon( "selection" );
}
if ( icon_selection )
{
icon_selection->DrawSelf( xpos, ypos, Color( r, g, b, a ) );
}
}
else
{
if ( pWeapon->HasAmmo() )
{
a = 192;
}
else
{
m_clrReddish.GetColor( r, g, b, a );
a = 128;
}
if ( pWeapon->GetSpriteInactive() )
{
pWeapon->GetSpriteInactive()->DrawSelf( xpos, ypos, Color( r, g, b, a ) );
}
}
}
// Draw Ammo Bar
DrawAmmoBar( pWeapon, xpos + 10, ypos, 20, 4 );
ypos += pWeapon->GetSpriteActive()->Height() + 5;
if ( bFirstItem )
{
nWidth = pWeapon->GetSpriteActive()->Width();
bFirstItem = false;
}
}
}
else
{
// Draw Row of weapons.
for ( int iPos = 0; iPos < MAX_WEAPON_POSITIONS; iPos++ )
{
int r2, g2, b2, a2;
C_BaseCombatWeapon *pWeapon = GetWeaponInSlot( i, iPos );
if ( !pWeapon )
continue;
if ( pWeapon->HasAmmo() )
{
(gHUD.m_clrYellowish).GetColor( r2, g2, b2, a2 );
a2 = 128;
}
else
{
m_clrReddish.GetColor( r2, g2, b2, a2 );
a2 = 96;
}
Color clrBox( r2, g2, b2, a2 );
vgui::surface()->DrawSetColor( clrBox );
vgui::surface()->DrawFilledRect( xpos, ypos, xpos + icon_buckets[ i ]->Width(), ypos + icon_buckets[ i ]->Height() );
ypos += icon_buckets[ i ]->Height() + 5;
}
nWidth = icon_buckets[ i ]->Width();
}
// advance position
xpos += nWidth + 5;
}
}
void CHudWeaponSelection::DrawAmmoBar( C_BaseCombatWeapon *pWeapon, int x, int y, int nWidth, int nHeight )
{
if ( pWeapon->GetPrimaryAmmoType() != -1 )
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
int nAmmoCount = pPlayer->GetAmmoCount( pWeapon->GetPrimaryAmmoType() );
if ( !nAmmoCount )
return;
float flPct = (float)nAmmoCount / (float)GetAmmoDef()->MaxCarry( pWeapon->GetPrimaryAmmoType() );
x = DrawBar( x, y, nWidth, nHeight, flPct );
// Do we have secondary ammo too?
if ( pWeapon->GetSecondaryAmmoType() != -1 )
{
flPct = (float)pPlayer->GetAmmoCount( pWeapon->GetSecondaryAmmoType() ) / (float)GetAmmoDef()->MaxCarry( pWeapon->GetSecondaryAmmoType() );
x += 5; //!!!
DrawBar( x, y, nWidth, nHeight, flPct );
}
}
}
int CHudWeaponSelection::DrawBar( int x, int y, int nWidth, int nHeight, float flPct )
{
Color clrBar;
int r, g, b, a;
if ( flPct < 0 )
{
flPct = 0;
}
else if ( flPct > 1 )
{
flPct = 1;
}
if ( flPct )
{
int nBarWidth = flPct * nWidth;
// Always show at least one pixel if we have ammo.
if (nBarWidth <= 0)
nBarWidth = 1;
m_clrGreenish.GetColor( r, g, b, a );
clrBar.SetColor( r, g, b, 255 );
vgui::surface()->DrawSetColor( clrBar );
vgui::surface()->DrawFilledRect( x, y, x + nBarWidth, y + nHeight );
x += nBarWidth;
nWidth -= nBarWidth;
}
(gHUD.m_clrYellowish).GetColor( r, g, b, a );
clrBar.SetColor( r, g, b, 128 );
vgui::surface()->DrawSetColor( clrBar );
vgui::surface()->DrawFilledRect( x, y, x + nWidth, y + nHeight );
return ( x + nWidth );
}
//-----------------------------------------------------------------------------
// Purpose: hud scheme settings
//-----------------------------------------------------------------------------
void CHudWeaponSelection::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
SetPaintBackgroundEnabled(false);
// set our size
int screenWide, screenTall;
int x, y;
GetPos(x, y);
GetHudSize(screenWide, screenTall);
SetBounds(0, y, screenWide, screenTall - y);
m_clrReddish = pScheme->GetColor( "Reddish", Color( 255, 16, 16, 255 ) );
m_clrGreenish = pScheme->GetColor( "Greenish", Color( 255, 16, 16, 255 ) );
}
//-----------------------------------------------------------------------------
// Purpose: Returns the next available weapon item in the weapon selection
//-----------------------------------------------------------------------------
C_BaseCombatWeapon *CHudWeaponSelection::FindNextWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition)
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return NULL;
C_BaseCombatWeapon *pNextWeapon = NULL;
// search all the weapons looking for the closest next
int iLowestNextSlot = HL1_MAX_WEAPON_SLOTS;
int iLowestNextPosition = MAX_WEAPON_POSITIONS;
for ( int i = 0; i < MAX_WEAPONS; i++ )
{
C_BaseCombatWeapon *pWeapon = pPlayer->GetWeapon(i);
if ( !pWeapon )
continue;
if ( pWeapon->CanBeSelected() )
{
int weaponSlot = pWeapon->GetSlot(), weaponPosition = pWeapon->GetPosition();
// see if this weapon is further ahead in the selection list
if ( weaponSlot > iCurrentSlot || (weaponSlot == iCurrentSlot && weaponPosition > iCurrentPosition) )
{
// see if this weapon is closer than the current lowest
if ( weaponSlot < iLowestNextSlot || (weaponSlot == iLowestNextSlot && weaponPosition < iLowestNextPosition) )
{
iLowestNextSlot = weaponSlot;
iLowestNextPosition = weaponPosition;
pNextWeapon = pWeapon;
}
}
}
}
return pNextWeapon;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the prior available weapon item in the weapon selection
//-----------------------------------------------------------------------------
C_BaseCombatWeapon *CHudWeaponSelection::FindPrevWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition)
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return NULL;
C_BaseCombatWeapon *pPrevWeapon = NULL;
// search all the weapons looking for the closest next
int iLowestPrevSlot = -1;
int iLowestPrevPosition = -1;
for ( int i = 0; i < MAX_WEAPONS; i++ )
{
C_BaseCombatWeapon *pWeapon = pPlayer->GetWeapon(i);
if ( !pWeapon )
continue;
if ( pWeapon->CanBeSelected() )
{
int weaponSlot = pWeapon->GetSlot(), weaponPosition = pWeapon->GetPosition();
// see if this weapon is further ahead in the selection list
if ( weaponSlot < iCurrentSlot || (weaponSlot == iCurrentSlot && weaponPosition < iCurrentPosition) )
{
// see if this weapon is closer than the current lowest
if ( weaponSlot > iLowestPrevSlot || (weaponSlot == iLowestPrevSlot && weaponPosition > iLowestPrevPosition) )
{
iLowestPrevSlot = weaponSlot;
iLowestPrevPosition = weaponPosition;
pPrevWeapon = pWeapon;
}
}
}
}
return pPrevWeapon;
}
//-----------------------------------------------------------------------------
// Purpose: Moves the selection to the next item in the menu
//-----------------------------------------------------------------------------
void CHudWeaponSelection::CycleToNextWeapon( void )
{
// Get the local player.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
C_BaseCombatWeapon *pNextWeapon = NULL;
if ( IsInSelectionMode() )
{
// find the next selection spot
C_BaseCombatWeapon *pWeapon = GetSelectedWeapon();
if ( !pWeapon )
return;
pNextWeapon = FindNextWeaponInWeaponSelection( pWeapon->GetSlot(), pWeapon->GetPosition() );
}
else
{
// open selection at the current place
pNextWeapon = pPlayer->GetActiveWeapon();
if ( pNextWeapon )
{
pNextWeapon = FindNextWeaponInWeaponSelection( pNextWeapon->GetSlot(), pNextWeapon->GetPosition() );
}
}
if ( !pNextWeapon )
{
// wrap around back to start
pNextWeapon = FindNextWeaponInWeaponSelection(-1, -1);
}
if ( pNextWeapon )
{
SetSelectedWeapon( pNextWeapon );
if( hud_fastswitch.GetInt() > 0 )
{
SelectWeapon();
}
else if ( !IsInSelectionMode() )
{
OpenSelection();
}
// Play the "cycle to next weapon" sound
pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" );
}
}
//-----------------------------------------------------------------------------
// Purpose: Moves the selection to the previous item in the menu
//-----------------------------------------------------------------------------
void CHudWeaponSelection::CycleToPrevWeapon( void )
{
// Get the local player.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
C_BaseCombatWeapon *pNextWeapon = NULL;
if ( IsInSelectionMode() )
{
// find the next selection spot
C_BaseCombatWeapon *pWeapon = GetSelectedWeapon();
if ( !pWeapon )
return;
pNextWeapon = FindPrevWeaponInWeaponSelection( pWeapon->GetSlot(), pWeapon->GetPosition() );
}
else
{
// open selection at the current place
pNextWeapon = pPlayer->GetActiveWeapon();
if ( pNextWeapon )
{
pNextWeapon = FindPrevWeaponInWeaponSelection( pNextWeapon->GetSlot(), pNextWeapon->GetPosition() );
}
}
if ( !pNextWeapon )
{
// wrap around back to end of weapon list
pNextWeapon = FindPrevWeaponInWeaponSelection( HL1_MAX_WEAPON_SLOTS, MAX_WEAPON_POSITIONS );
}
if ( pNextWeapon )
{
SetSelectedWeapon( pNextWeapon );
if( hud_fastswitch.GetInt() > 0 )
{
SelectWeapon();
}
else if ( !IsInSelectionMode() )
{
OpenSelection();
}
// Play the "cycle to next weapon" sound
pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" );
}
}
//-----------------------------------------------------------------------------
// Purpose: returns the weapon in the specified slot
//-----------------------------------------------------------------------------
C_BaseCombatWeapon *CHudWeaponSelection::GetWeaponInSlot( int iSlot, int iSlotPos )
{
C_BasePlayer *player = C_BasePlayer::GetLocalPlayer();
if ( !player )
return NULL;
for ( int i = 0; i < MAX_WEAPONS; i++ )
{
C_BaseCombatWeapon *pWeapon = player->GetWeapon(i);
if ( pWeapon == NULL )
continue;
if ( pWeapon->GetSlot() == iSlot && pWeapon->GetPosition() == iSlotPos )
return pWeapon;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Moves selection to the specified slot
//-----------------------------------------------------------------------------
void CHudWeaponSelection::SelectWeaponSlot( int iSlot )
{
// iSlot is one higher than it should be, since it's the number key, not the 0-based index into the weapons
--iSlot;
// Get the local player.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
// Don't try and read past our possible number of slots
if ( iSlot > HL1_MAX_WEAPON_SLOTS )
return;
// Make sure the player's allowed to switch weapons
if ( pPlayer->IsAllowedToSwitchWeapons() == false )
return;
// do a fast switch if set
if ( hud_fastswitch.GetBool() )
{
FastWeaponSwitch( iSlot );
return;
}
int slotPos = 0;
C_BaseCombatWeapon *pActiveWeapon = GetSelectedWeapon();
// start later in the list
if ( IsInSelectionMode() && pActiveWeapon && pActiveWeapon->GetSlot() == iSlot )
{
slotPos = pActiveWeapon->GetPosition() + 1;
}
// find the weapon in this slot
pActiveWeapon = GetNextActivePos( iSlot, slotPos );
if ( !pActiveWeapon )
{
pActiveWeapon = GetNextActivePos( iSlot, 0 );
}
if ( pActiveWeapon != NULL )
{
SetSelectedWeapon( pActiveWeapon );
if( hud_fastswitch.GetInt() > 0 )
{
// only one active item in bucket, so change directly to weapon
SelectWeapon();
}
else if ( !IsInSelectionMode() )
{
// open the weapon selection
OpenSelection();
}
}
pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" );
}
//-----------------------------------------------------------------------------
// Purpose: Opens the next weapon in the slot
//-----------------------------------------------------------------------------
void CHudWeaponSelection::FastWeaponSwitch( int iWeaponSlot )
{
// get the slot the player's weapon is in
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
// see where we should start selection
int iPosition = -1;
C_BaseCombatWeapon *pActiveWeapon = pPlayer->GetActiveWeapon();
if ( pActiveWeapon && pActiveWeapon->GetSlot() == iWeaponSlot )
{
// start after this weapon
iPosition = pActiveWeapon->GetPosition();
}
C_BaseCombatWeapon *pNextWeapon = NULL;
// search for the weapon after the current one
pNextWeapon = FindNextWeaponInWeaponSelection(iWeaponSlot, iPosition);
// make sure it's in the same bucket
if ( !pNextWeapon || pNextWeapon->GetSlot() != iWeaponSlot )
{
// just look for any weapon in this slot
pNextWeapon = FindNextWeaponInWeaponSelection(iWeaponSlot, -1);
}
// see if we found a weapon that's different from the current and in the selected slot
if ( pNextWeapon && pNextWeapon != pActiveWeapon && pNextWeapon->GetSlot() == iWeaponSlot )
{
// select the new weapon
::input->MakeWeaponSelection( pNextWeapon );
}
else if ( pNextWeapon != pActiveWeapon )
{
// error sound
pPlayer->EmitSound( "Player.DenyWeaponSelection" );
}
}
C_BaseCombatWeapon *CHudWeaponSelection::GetNextActivePos( int iSlot, int iSlotPos )
{
if ( iSlot >= HL1_MAX_WEAPON_SLOTS )
return NULL;
return CBaseHudWeaponSelection::GetNextActivePos( iSlot, iSlotPos );
}
| 412 | 0.946171 | 1 | 0.946171 | game-dev | MEDIA | 0.981017 | game-dev | 0.949606 | 1 | 0.949606 |
CrucibleMC/Crucible | 12,427 | forge/src/main/java/net/minecraftforge/common/config/ConfigCategory.java | /**
* This software is provided under the terms of the Minecraft Forge Public
* License v1.0.
*/
package net.minecraftforge.common.config;
import static net.minecraftforge.common.config.Configuration.COMMENT_SEPARATOR;
import static net.minecraftforge.common.config.Configuration.NEW_LINE;
import static net.minecraftforge.common.config.Configuration.allowedProperties;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import cpw.mods.fml.client.config.GuiConfigEntries.IConfigEntry;
public class ConfigCategory implements Map<String, Property>
{
private String name;
private String comment;
private String languagekey;
private ArrayList<ConfigCategory> children = new ArrayList<ConfigCategory>();
private Map<String, Property> properties = new TreeMap<String, Property>();
private int propNumber = 0;
public final ConfigCategory parent;
private boolean changed = false;
private boolean requiresWorldRestart = false;
private boolean showInGui = true;
private boolean requiresMcRestart = false;
private Class<? extends IConfigEntry> customEntryClass = null;
private List<String> propertyOrder = null;
public ConfigCategory(String name)
{
this(name, null);
}
public ConfigCategory(String name, ConfigCategory parent)
{
this.name = name;
this.parent = parent;
if (parent != null)
{
parent.children.add(this);
}
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof ConfigCategory)
{
ConfigCategory cat = (ConfigCategory)obj;
return name.equals(cat.name) && children.equals(cat.children);
}
return false;
}
public String getName()
{
return name;
}
public String getQualifiedName()
{
return getQualifiedName(name, parent);
}
public static String getQualifiedName(String name, ConfigCategory parent)
{
return (parent == null ? name : parent.getQualifiedName() + Configuration.CATEGORY_SPLITTER + name);
}
public ConfigCategory getFirstParent()
{
return (parent == null ? this : parent.getFirstParent());
}
public boolean isChild()
{
return parent != null;
}
public Map<String, Property> getValues()
{
return ImmutableMap.copyOf(properties);
}
public List<Property> getOrderedValues()
{
if (this.propertyOrder != null)
{
ArrayList<Property> set = new ArrayList<Property>();
for (String key : this.propertyOrder)
if (properties.containsKey(key))
set.add(properties.get(key));
return ImmutableList.copyOf(set);
}
else
return ImmutableList.copyOf(properties.values());
}
public ConfigCategory setConfigEntryClass(Class<? extends IConfigEntry> clazz)
{
this.customEntryClass = clazz;
return this;
}
public Class<? extends IConfigEntry> getConfigEntryClass()
{
return this.customEntryClass;
}
public ConfigCategory setLanguageKey(String languagekey)
{
this.languagekey = languagekey;
return this;
}
public String getLanguagekey()
{
if (this.languagekey != null)
return this.languagekey;
else
return getQualifiedName();
}
public void setComment(String comment)
{
this.comment = comment;
}
public String getComment()
{
return this.comment;
}
/**
* Sets the flag for whether or not this category can be edited while a world is running. Care should be taken to ensure
* that only properties that are truly dynamic can be changed from the in-game options menu. Only set this flag to
* true if all child properties/categories are unable to be modified while a world is running.
*/
public ConfigCategory setRequiresWorldRestart(boolean requiresWorldRestart)
{
this.requiresWorldRestart = requiresWorldRestart;
return this;
}
/**
* Returns whether or not this category is able to be edited while a world is running using the in-game Mod Options screen
* as well as the Mods list screen, or only from the Mods list screen.
*/
public boolean requiresWorldRestart()
{
return this.requiresWorldRestart;
}
/**
* Sets whether or not this ConfigCategory should be allowed to show on config GUIs.
* Defaults to true.
*/
public ConfigCategory setShowInGui(boolean showInGui)
{
this.showInGui = showInGui;
return this;
}
/**
* Gets whether or not this ConfigCategory should be allowed to show on config GUIs.
* Defaults to true unless set to false.
*/
public boolean showInGui()
{
return showInGui;
}
/**
* Sets whether or not this ConfigCategory requires Minecraft to be restarted when changed.
* Defaults to false. Only set this flag to true if ALL child properties/categories require
* Minecraft to be restarted when changed. Setting this flag will also prevent modification
* of the child properties/categories while a world is running.
*/
public ConfigCategory setRequiresMcRestart(boolean requiresMcRestart)
{
this.requiresMcRestart = this.requiresWorldRestart = requiresMcRestart;
return this;
}
/**
* Gets whether or not this ConfigCategory requires Minecraft to be restarted when changed.
* Defaults to false unless set to true.
*/
public boolean requiresMcRestart()
{
return this.requiresMcRestart;
}
public ConfigCategory setPropertyOrder(List<String> propertyOrder)
{
this.propertyOrder = propertyOrder;
for (String s : properties.keySet())
if (!propertyOrder.contains(s))
propertyOrder.add(s);
return this;
}
public List<String> getPropertyOrder()
{
if (this.propertyOrder != null)
return ImmutableList.copyOf(this.propertyOrder);
else
return ImmutableList.copyOf(properties.keySet());
}
public boolean containsKey(String key)
{
return properties.containsKey(key);
}
public Property get(String key)
{
return properties.get(key);
}
private void write(BufferedWriter out, String... data) throws IOException
{
write(out, true, data);
}
private void write(BufferedWriter out, boolean new_line, String... data) throws IOException
{
for (int x = 0; x < data.length; x++)
{
out.write(data[x]);
}
if (new_line) out.write(NEW_LINE);
}
public void write(BufferedWriter out, int indent) throws IOException
{
String pad0 = getIndent(indent);
String pad1 = getIndent(indent + 1);
String pad2 = getIndent(indent + 2);
if (comment != null && !comment.isEmpty())
{
write(out, pad0, COMMENT_SEPARATOR);
write(out, pad0, "# ", name);
write(out, pad0, "#--------------------------------------------------------------------------------------------------------#");
Splitter splitter = Splitter.onPattern("\r?\n");
for (String line : splitter.split(comment))
{
write(out, pad0, "# ", line);
}
write(out, pad0, COMMENT_SEPARATOR, NEW_LINE);
}
String displayName = name;
if (!allowedProperties.matchesAllOf(name))
{
displayName = '"' + name + '"';
}
write(out, pad0, displayName, " {");
Property[] props = getOrderedValues().toArray(new Property[] {});
for (int x = 0; x < props.length; x++)
{
Property prop = props[x];
if (prop.comment != null && !prop.comment.isEmpty())
{
if (x != 0)
{
out.newLine();
}
Splitter splitter = Splitter.onPattern("\r?\n");
for (String commentLine : splitter.split(prop.comment))
{
write(out, pad1, "# ", commentLine);
}
}
String propName = prop.getName();
if (!allowedProperties.matchesAllOf(propName))
{
propName = '"' + propName + '"';
}
if (prop.isList())
{
char type = prop.getType().getID();
write(out, pad1, String.valueOf(type), ":", propName, " <");
for (String line : prop.getStringList())
{
write(out, pad2, line);
}
write(out, pad1, " >");
}
else if (prop.getType() == null)
{
write(out, pad1, propName, "=", prop.getString());
}
else
{
char type = prop.getType().getID();
write(out, pad1, String.valueOf(type), ":", propName, "=", prop.getString());
}
}
if (children.size() > 0)
out.newLine();
for (ConfigCategory child : children)
{
child.write(out, indent + 1);
}
write(out, pad0, "}", NEW_LINE);
}
private String getIndent(int indent)
{
StringBuilder buf = new StringBuilder("");
for (int x = 0; x < indent; x++)
{
buf.append(" ");
}
return buf.toString();
}
public boolean hasChanged()
{
if (changed) return true;
for (Property prop : properties.values())
{
if (prop.hasChanged()) return true;
}
return false;
}
void resetChangedState()
{
changed = false;
for (Property prop : properties.values())
{
prop.resetChangedState();
}
}
//Map bouncer functions for compatibility with older mods, to be removed once all mods stop using it.
@Override public int size(){ return properties.size(); }
@Override public boolean isEmpty() { return properties.isEmpty(); }
@Override public boolean containsKey(Object key) { return properties.containsKey(key); }
@Override public boolean containsValue(Object value){ return properties.containsValue(value); }
@Override public Property get(Object key) { return properties.get(key); }
@Override public Property put(String key, Property value)
{
changed = true;
if (this.propertyOrder != null && !this.propertyOrder.contains(key))
this.propertyOrder.add(key);
return properties.put(key, value);
}
@Override public Property remove(Object key)
{
changed = true;
return properties.remove(key);
}
@Override public void putAll(Map<? extends String, ? extends Property> m)
{
changed = true;
if (this.propertyOrder != null)
for (String key : m.keySet())
if (!this.propertyOrder.contains(key))
this.propertyOrder.add(key);
properties.putAll(m);
}
@Override public void clear()
{
changed = true;
properties.clear();
}
@Override public Set<String> keySet() { return properties.keySet(); }
@Override public Collection<Property> values() { return properties.values(); }
@Override //Immutable copy, changes will NOT be reflected in this category
public Set<java.util.Map.Entry<String, Property>> entrySet()
{
return ImmutableSet.copyOf(properties.entrySet());
}
public Set<ConfigCategory> getChildren(){ return ImmutableSet.copyOf(children); }
public void removeChild(ConfigCategory child)
{
if (children.contains(child))
{
children.remove(child);
changed = true;
}
}
} | 412 | 0.957784 | 1 | 0.957784 | game-dev | MEDIA | 0.478628 | game-dev | 0.965373 | 1 | 0.965373 |
Eaglercraft-Archive/EaglercraftX-1.8-workspace | 7,241 | src/game/java/net/minecraft/item/crafting/RecipeFireworks.java | package net.minecraft.item.crafting;
import java.util.ArrayList;
import com.google.common.collect.Lists;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
/**+
* 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 RecipeFireworks implements IRecipe {
private ItemStack field_92102_a;
/**+
* Used to check if a recipe matches current crafting inventory
*/
public boolean matches(InventoryCrafting inventorycrafting, World var2) {
this.field_92102_a = null;
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int i1 = 0;
int j1 = 0;
for (int k1 = 0; k1 < inventorycrafting.getSizeInventory(); ++k1) {
ItemStack itemstack = inventorycrafting.getStackInSlot(k1);
if (itemstack != null) {
if (itemstack.getItem() == Items.gunpowder) {
++j;
} else if (itemstack.getItem() == Items.firework_charge) {
++l;
} else if (itemstack.getItem() == Items.dye) {
++k;
} else if (itemstack.getItem() == Items.paper) {
++i;
} else if (itemstack.getItem() == Items.glowstone_dust) {
++i1;
} else if (itemstack.getItem() == Items.diamond) {
++i1;
} else if (itemstack.getItem() == Items.fire_charge) {
++j1;
} else if (itemstack.getItem() == Items.feather) {
++j1;
} else if (itemstack.getItem() == Items.gold_nugget) {
++j1;
} else {
if (itemstack.getItem() != Items.skull) {
return false;
}
++j1;
}
}
}
i1 = i1 + k + j1;
if (j <= 3 && i <= 1) {
if (j >= 1 && i == 1 && i1 == 0) {
this.field_92102_a = new ItemStack(Items.fireworks);
if (l > 0) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
NBTTagCompound nbttagcompound3 = new NBTTagCompound();
NBTTagList nbttaglist = new NBTTagList();
for (int k2 = 0; k2 < inventorycrafting.getSizeInventory(); ++k2) {
ItemStack itemstack3 = inventorycrafting.getStackInSlot(k2);
if (itemstack3 != null && itemstack3.getItem() == Items.firework_charge
&& itemstack3.hasTagCompound() && itemstack3.getTagCompound().hasKey("Explosion", 10)) {
nbttaglist.appendTag(itemstack3.getTagCompound().getCompoundTag("Explosion"));
}
}
nbttagcompound3.setTag("Explosions", nbttaglist);
nbttagcompound3.setByte("Flight", (byte) j);
nbttagcompound1.setTag("Fireworks", nbttagcompound3);
this.field_92102_a.setTagCompound(nbttagcompound1);
}
return true;
} else if (j == 1 && i == 0 && l == 0 && k > 0 && j1 <= 1) {
this.field_92102_a = new ItemStack(Items.firework_charge);
NBTTagCompound nbttagcompound = new NBTTagCompound();
NBTTagCompound nbttagcompound2 = new NBTTagCompound();
byte b0 = 0;
ArrayList arraylist = Lists.newArrayList();
for (int l1 = 0; l1 < inventorycrafting.getSizeInventory(); ++l1) {
ItemStack itemstack2 = inventorycrafting.getStackInSlot(l1);
if (itemstack2 != null) {
if (itemstack2.getItem() == Items.dye) {
arraylist.add(Integer.valueOf(ItemDye.dyeColors[itemstack2.getMetadata() & 15]));
} else if (itemstack2.getItem() == Items.glowstone_dust) {
nbttagcompound2.setBoolean("Flicker", true);
} else if (itemstack2.getItem() == Items.diamond) {
nbttagcompound2.setBoolean("Trail", true);
} else if (itemstack2.getItem() == Items.fire_charge) {
b0 = 1;
} else if (itemstack2.getItem() == Items.feather) {
b0 = 4;
} else if (itemstack2.getItem() == Items.gold_nugget) {
b0 = 2;
} else if (itemstack2.getItem() == Items.skull) {
b0 = 3;
}
}
}
int[] aint1 = new int[arraylist.size()];
for (int l2 = 0; l2 < aint1.length; ++l2) {
aint1[l2] = ((Integer) arraylist.get(l2)).intValue();
}
nbttagcompound2.setIntArray("Colors", aint1);
nbttagcompound2.setByte("Type", b0);
nbttagcompound.setTag("Explosion", nbttagcompound2);
this.field_92102_a.setTagCompound(nbttagcompound);
return true;
} else if (j == 0 && i == 0 && l == 1 && k > 0 && k == i1) {
ArrayList arraylist1 = Lists.newArrayList();
for (int i2 = 0; i2 < inventorycrafting.getSizeInventory(); ++i2) {
ItemStack itemstack1 = inventorycrafting.getStackInSlot(i2);
if (itemstack1 != null) {
if (itemstack1.getItem() == Items.dye) {
arraylist1.add(Integer.valueOf(ItemDye.dyeColors[itemstack1.getMetadata() & 15]));
} else if (itemstack1.getItem() == Items.firework_charge) {
this.field_92102_a = itemstack1.copy();
this.field_92102_a.stackSize = 1;
}
}
}
int[] aint = new int[arraylist1.size()];
for (int j2 = 0; j2 < aint.length; ++j2) {
aint[j2] = ((Integer) arraylist1.get(j2)).intValue();
}
if (this.field_92102_a != null && this.field_92102_a.hasTagCompound()) {
NBTTagCompound nbttagcompound4 = this.field_92102_a.getTagCompound().getCompoundTag("Explosion");
if (nbttagcompound4 == null) {
return false;
} else {
nbttagcompound4.setIntArray("FadeColors", aint);
return true;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
/**+
* Returns an Item that is the result of this recipe
*/
public ItemStack getCraftingResult(InventoryCrafting var1) {
return this.field_92102_a.copy();
}
/**+
* Returns the size of the recipe area
*/
public int getRecipeSize() {
return 10;
}
public ItemStack getRecipeOutput() {
return this.field_92102_a;
}
public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) {
ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()];
for (int i = 0; i < aitemstack.length; ++i) {
ItemStack itemstack = inventorycrafting.getStackInSlot(i);
if (itemstack != null && itemstack.getItem().hasContainerItem()) {
aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem());
}
}
return aitemstack;
}
} | 412 | 0.870254 | 1 | 0.870254 | game-dev | MEDIA | 0.999794 | game-dev | 0.953912 | 1 | 0.953912 |
coolsnowwolf/luci | 3,988 | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-res-feature.lua | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
cbimap = Map("asterisk", "asterisk", "")
featuremap = cbimap:section(TypedSection, "featuremap", "Feature Key maps", "")
featuremap.anonymous = true
featuremap.addremove = true
atxfer = featuremap:option(Value, "atxfer", "Attended transfer key", "")
atxfer.rmempty = true
blindxfer = featuremap:option(Value, "blindxfer", "Blind transfer key", "")
blindxfer.rmempty = true
disconnect = featuremap:option(Value, "disconnect", "Key to Disconnect call", "")
disconnect.rmempty = true
parkcall = featuremap:option(Value, "parkcall", "Key to Park call", "")
parkcall.rmempty = true
featurepark = cbimap:section(TypedSection, "featurepark", "Parking Feature", "")
featurepark.anonymous = true
parkenabled = featurepark:option(Flag, "parkenabled", "Enable Parking", "")
adsipark = featurepark:option(Flag, "adsipark", "ADSI Park", "")
adsipark.rmempty = true
adsipark:depends({ parkenabled = "1" })
atxfernoanswertimeout = featurepark:option(Value, "atxfernoanswertimeout", "Attended transfer timeout (sec)", "")
atxfernoanswertimeout.rmempty = true
atxfernoanswertimeout:depends({ parkenabled = "1" })
automon = featurepark:option(Value, "automon", "One touch record key", "")
automon.rmempty = true
automon:depends({ parkenabled = "1" })
context = featurepark:option(Value, "context", "Name of call context for parking", "")
context.rmempty = true
context:depends({ parkenabled = "1" })
courtesytone = featurepark:option(Value, "courtesytone", "Sound file to play to parked caller", "")
courtesytone.rmempty = true
courtesytone:depends({ parkenabled = "1" })
featuredigittimeout = featurepark:option(Value, "featuredigittimeout", "Max time (ms) between digits for feature activation", "")
featuredigittimeout.rmempty = true
featuredigittimeout:depends({ parkenabled = "1" })
findslot = featurepark:option(ListValue, "findslot", "Method to Find Parking slot", "")
findslot:value("first", "First available slot")
findslot:value("next", "Next free parking space")
findslot.rmempty = true
findslot:depends({ parkenabled = "1" })
parkedmusicclass = featurepark:option(ListValue, "parkedmusicclass", "Music on Hold class for the parked channel", "")
parkedmusicclass.titleref = luci.dispatcher.build_url( "admin", "services", "asterisk" )
parkedmusicclass:depends({ parkenabled = "1" })
cbimap.uci:foreach( "asterisk", "moh", function(s) parkedmusicclass:value(s['.name']) end )
parkedplay = featurepark:option(ListValue, "parkedplay", "Play courtesy tone to", "")
parkedplay:value("caller", "Caller")
parkedplay:value("parked", "Parked user")
parkedplay:value("both", "Both")
parkedplay.rmempty = true
parkedplay:depends({ parkenabled = "1" })
parkext = featurepark:option(Value, "parkext", "Extension to dial to park", "")
parkext.rmempty = true
parkext:depends({ parkenabled = "1" })
parkingtime = featurepark:option(Value, "parkingtime", "Parking time (secs)", "")
parkingtime.rmempty = true
parkingtime:depends({ parkenabled = "1" })
parkpos = featurepark:option(Value, "parkpos", "Range of extensions for call parking", "")
parkpos.rmempty = true
parkpos:depends({ parkenabled = "1" })
pickupexten = featurepark:option(Value, "pickupexten", "Pickup extension", "")
pickupexten.rmempty = true
pickupexten:depends({ parkenabled = "1" })
transferdigittimeout = featurepark:option(Value, "transferdigittimeout", "Seconds to wait between digits when transferring", "")
transferdigittimeout.rmempty = true
transferdigittimeout:depends({ parkenabled = "1" })
xferfailsound = featurepark:option(Value, "xferfailsound", "sound when attended transfer is complete", "")
xferfailsound.rmempty = true
xferfailsound:depends({ parkenabled = "1" })
xfersound = featurepark:option(Value, "xfersound", "Sound when attended transfer fails", "")
xfersound.rmempty = true
xfersound:depends({ parkenabled = "1" })
return cbimap
| 412 | 0.837026 | 1 | 0.837026 | game-dev | MEDIA | 0.388021 | game-dev | 0.506138 | 1 | 0.506138 |
RCInet/LastEpoch_Mods | 5,910 | LastEpoch_Hud/Scripts/Mods/Items/Items_Req_Set.cs | using HarmonyLib;
using Il2Cpp;
namespace LastEpoch_Hud.Scripts.Mods.Items
{
public class Items_Req_Set
{
/*public struct req_structure
{
public byte set_id;
public System.Collections.Generic.List<int> set_bonuses;
public System.Collections.Generic.List<byte> set_description;
}
public static bool need_update = false;
public static void Enable()
{
if (((CanRun()) && (!req_removed)) || ((!CanRun()) && (req_removed)))
{
need_update = true;
}
}*/
//private static bool req_removed = false;
//private static System.Collections.Generic.List<req_structure> backup = null;
/*private static void Backup()
{
if (CanRun())
{
backup = new System.Collections.Generic.List<req_structure>();
foreach (SetBonusesList.Entry set_bonuses in Refs_Manager.set_bonuses_list.entries)
{
System.Collections.Generic.List<int> bonuses = new System.Collections.Generic.List<int>();
if (!set_bonuses.mods.IsNullOrDestroyed())
{
foreach (SetBonus set_bonus in set_bonuses.mods) { bonuses.Add(set_bonus.setRequirement); }
}
System.Collections.Generic.List<byte> descriptions = new System.Collections.Generic.List<byte>();
if (!set_bonuses.tooltipDescriptions.IsNullOrDestroyed())
{
foreach (ItemTooltipDescription item_tooltip_description in set_bonuses.tooltipDescriptions)
{
descriptions.Add(item_tooltip_description.setRequirement);
}
}
req_structure req = new req_structure
{
set_id = set_bonuses.setID,
set_description = descriptions,
set_bonuses = bonuses
};
descriptions.Clear();
bonuses.Clear();
backup.Add(req);
}
}
}
private static void Remove()
{
if ((CanRun()) && (!backup.IsNullOrDestroyed()))
{
Main.logger_instance?.Msg("Remove set req");
foreach (SetBonusesList.Entry set_bonuses in Refs_Manager.set_bonuses_list.entries)
{
foreach (SetBonus set_bonus in set_bonuses.mods)
{
set_bonus.setRequirement = 0;
}
foreach (ItemTooltipDescription item_tooltip_description in set_bonuses.tooltipDescriptions)
{
item_tooltip_description.setRequirement = 0;
}
}
req_removed = true;
}
}
private static void Reset()
{
if ((CanRun()) && (!backup.IsNullOrDestroyed()))
{
Main.logger_instance?.Msg("Reset set req");
foreach (SetBonusesList.Entry set_bonuses in Refs_Manager.set_bonuses_list.entries)
{
bool backup_found = false;
int i = 0;
foreach (req_structure backup_req in backup)
{
if (backup_req.set_id == set_bonuses.setID)
{
backup_found = true;
break;
}
i++;
}
if (backup_found)
{
int k = 0;
if (!backup[i].set_bonuses.IsNullOrDestroyed())
{
foreach (SetBonus set_bonus in set_bonuses.mods)
{
if (k < backup[i].set_bonuses.Count)
{
set_bonus.setRequirement = backup[i].set_bonuses[k];
}
k++;
}
}
k = 0;
if (!backup[i].set_description.IsNullOrDestroyed())
{
foreach (ItemTooltipDescription item_tooltip_description in set_bonuses.tooltipDescriptions)
{
if (k < backup[i].set_description.Count)
{
item_tooltip_description.setRequirement = backup[i].set_description[k];
}
k++;
}
}
}
}
req_removed = false;
}
}*/
private static bool CanRun()
{
if (!Save_Manager.instance.IsNullOrDestroyed()) //&& (!Refs_Manager.set_bonuses_list.IsNullOrDestroyed()))
{
if (Save_Manager.instance.initialized) // && (!Refs_Manager.set_bonuses_list.entries.IsNullOrDestroyed()))
{ return Save_Manager.instance.data.Items.Req.set; }
else { return false; }
}
else { return false; }
}
[HarmonyPatch(typeof(ItemContainersManager), "getGearCountForSetID")]
public class getGearCountForSetID
{
[HarmonyPostfix]
static void Postfix(ref int __result)
{
if (CanRun()) { __result = 10; }
}
}
}
}
| 412 | 0.965362 | 1 | 0.965362 | game-dev | MEDIA | 0.831519 | game-dev | 0.901441 | 1 | 0.901441 |
SonicEraZoR/Portal-Base | 3,906 | sp/src/game/server/te_beaments.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "basetempentity.h"
#include "te_basebeam.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern short g_sModelIndexSmoke; // (in combatweapon.cpp) holds the index for the smoke cloud
//-----------------------------------------------------------------------------
// Purpose: Dispatches a beam between two entities
//-----------------------------------------------------------------------------
class CTEBeamEnts : public CTEBaseBeam
{
public:
DECLARE_CLASS( CTEBeamEnts, CTEBaseBeam );
DECLARE_SERVERCLASS();
CTEBeamEnts( const char *name );
virtual ~CTEBeamEnts( void );
virtual void Test( const Vector& current_origin, const QAngle& current_angles );
public:
CNetworkVar( int, m_nStartEntity );
CNetworkVar( int, m_nEndEntity );
};
//-----------------------------------------------------------------------------
// Purpose:
// Input : *name -
//-----------------------------------------------------------------------------
CTEBeamEnts::CTEBeamEnts( const char *name ) :
CTEBaseBeam( name )
{
m_nStartEntity = 0;
m_nEndEntity = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTEBeamEnts::~CTEBeamEnts( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *current_origin -
// *current_angles -
//-----------------------------------------------------------------------------
void CTEBeamEnts::Test( const Vector& current_origin, const QAngle& current_angles )
{
m_nStartEntity = 1;
m_nEndEntity = 0;
m_nModelIndex = g_sModelIndexSmoke;
m_nStartFrame = 0;
m_nFrameRate = 10;
m_fLife = 2.0;
m_fWidth = 1.0;
m_fAmplitude = 1;
r = 127;
g = 63;
b = 0;
a = 150;
m_nSpeed = 1;
CBroadcastRecipientFilter filter;
Create( filter, 0.0 );
}
IMPLEMENT_SERVERCLASS_ST(CTEBeamEnts, DT_TEBeamEnts)
SendPropInt( SENDINFO(m_nStartEntity), 24, SPROP_UNSIGNED ),
SendPropInt( SENDINFO(m_nEndEntity), 24, SPROP_UNSIGNED ),
END_SEND_TABLE()
// Singleton to fire TEBeamEnts objects
static CTEBeamEnts g_TEBeamEnts( "BeamEnts" );
//-----------------------------------------------------------------------------
// Purpose:
// Input : msg_dest -
// delay -
// *origin -
// *recipient -
// int start -
// end -
// modelindex -
// startframe -
// framerate -
// msg_dest -
// delay -
// origin -
// recipient -
//-----------------------------------------------------------------------------
void TE_BeamEnts( IRecipientFilter& filter, float delay,
int start, int end, int modelindex, int haloindex, int startframe, int framerate,
float life, float width, float endWidth, int fadeLength, float amplitude, int r, int g, int b, int a, int speed )
{
g_TEBeamEnts.m_nStartEntity = (start & 0x0FFF) | ((1 & 0xF)<<12);
g_TEBeamEnts.m_nEndEntity = (end & 0x0FFF) | ((1 & 0xF)<<12);
g_TEBeamEnts.m_nModelIndex = modelindex;
g_TEBeamEnts.m_nHaloIndex = haloindex;
g_TEBeamEnts.m_nStartFrame = startframe;
g_TEBeamEnts.m_nFrameRate = framerate;
g_TEBeamEnts.m_fLife = life;
g_TEBeamEnts.m_fWidth = width;
g_TEBeamEnts.m_fEndWidth = endWidth;
g_TEBeamEnts.m_nFadeLength = fadeLength;
g_TEBeamEnts.m_fAmplitude = amplitude;
g_TEBeamEnts.m_nSpeed = speed;
g_TEBeamEnts.r = r;
g_TEBeamEnts.g = g;
g_TEBeamEnts.b = b;
g_TEBeamEnts.a = a;
// Send it over the wire
g_TEBeamEnts.Create( filter, delay );
} | 412 | 0.617621 | 1 | 0.617621 | game-dev | MEDIA | 0.636328 | game-dev | 0.665867 | 1 | 0.665867 |
magefree/mage | 1,343 | Mage.Sets/src/mage/cards/l/LoreSeeker.java |
package mage.cards.l;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.InfoEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import java.util.UUID;
/**
*
* @author tiera3 - based on PrizefighterConstruct and CanalDredger
* note - draftmatters ability not implemented
*/
public final class LoreSeeker extends CardImpl {
public LoreSeeker(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{2}");
this.subtype.add(SubType.CONSTRUCT);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// TODO: Draft specific abilities not implemented
// Reveal Lore Seeker as you draft it. After you draft Lore Seeker, you may add a booster pack to the draft.
this.addAbility(new SimpleStaticAbility(Zone.ALL, new InfoEffect("Reveal {this} as you draft it. "
+ "After you draft {this}, you may add a booster pack to the draft - not implemented.")));
}
private LoreSeeker(final LoreSeeker card) {
super(card);
}
@Override
public LoreSeeker copy() {
return new LoreSeeker(this);
}
}
| 412 | 0.875986 | 1 | 0.875986 | game-dev | MEDIA | 0.900546 | game-dev | 0.974732 | 1 | 0.974732 |
ProjectEQ/projecteqquests | 10,992 | stillmoonb/encounters/kessdonas_perch.lua | -- Kessdona the Enlightened
local dz_task_id = 0
local all_manashards_dead = false;
local active_manashard_hp = 100;
local number_of_correct_protector_kills = 0;
local kess_hp_lock_percent = 80;
local protector_order = math.random(1,4);
local protector_table = {
[1] = {339115,339111,339111,339111},
[2] = {339111,339115,339111,339111},
[3] = {339111,339111,339115,339111},
[4] = {339111,339111,339111,339115}
};
local protector_locs = {
[1] = {0,0,1287.83,6356.93,754.18,407.5},
[2] = {0,0,1299.33,6423.52,755.13,433.3},
[3] = {0,0,1202.17,6478.35,754.83,222.0},
[4] = {0,0,1126.67,6409.48,753.60,189.5}
};
local box = require("aa_box")
local Kess = box();
Kess:add(1554.17, 6653.29);
Kess:add(1115.40, 6631.73);
Kess:add(1107.08, 6266.73);
Kess:add(1486.47, 6230.15);
function Kess_Combat(e) -- Set all variables back to default if party wipes and I am not in combat.
if e.joined then -- Keep track of my location every 3 seconds. If I am not in my box, put me there.
eq.stop_timer("fail");
eq.stop_timer("respawn");
eq.set_timer("oobcheck", 3 * 1000);
eq.set_timer("charm", 90 * 1000);
eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Kessdona the Enlightened says, 'You did not venture to this place for reflection and understanding, did you?'")
else
eq.set_timer("fail", 30 * 1000); -- set a 30s fail condition if I am not in combat.
eq.set_timer("respawn", 40 * 1000);
end
end
function Kess_Spawn(e)
reset_event(e);
end
function reset_event(e)
eq.spawn2(339109,0,0,1257.17,6330.92,747.16,462.3); -- Spawn 1 active manashard guardian.
eq.spawn2(339108,0,0,1158.62,6328.01,745.01,28.5); -- NPC: inactive_manashard_guardian
eq.spawn2(339118,0,0,1128.33,6414.53,744.35,129.5); -- NPC: inactive_manashard_guardian
eq.spawn2(339119,0,0,1156.67,6486.17,745.00,196.3); -- NPC: inactive_manashard_guardian
eq.spawn2(339120,0,0,1229.06,6507.49,754.67,235.3); -- NPC: inactive_manashard_guardian
eq.spawn2(339121,0,0,1305.75,6458.83,752.10,329.0); -- NPC: inactive_manashard_guardian
eq.set_next_hp_event(90); -- Set something to happen at 90%.
-- New Variables
all_manashards_dead = false;
active_manashard_hp = 100;
number_of_correct_protector_kills = 0;
kess_hp_lock_percent = 80;
end
function spawn_protectors(e)
protector_order = math.random(1,4);
eq.spawn2(protector_table[protector_order][1],unpack(protector_locs[1]));
eq.spawn2(protector_table[protector_order][2],unpack(protector_locs[2]));
eq.spawn2(protector_table[protector_order][3],unpack(protector_locs[3]));
eq.spawn2(protector_table[protector_order][4],unpack(protector_locs[4]));
eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Kessdona the Enlightened draws on strength from her protectors and regenerates. One of the four protectors must be the focus. Perhaps someone attuned to nature could isolate which?")
end
function Kess_HP(e)
if e.hp_event == 90 and not all_manashards_dead then -- If I hit 90% and not all manashards are dead then process heal routine.
e.self:SetHP(e.self:GetMaxHP() * 0.96); -- Set HP to 96 % - This is what we saw on live
e.self:SendBeginCast(6546,0); -- Spell Cast Appearance (This will prevent cheesing the event similar to Fear Golems)
active_manashard_hp = active_manashard_hp - 20; -- Drop Active Manashard HP by 20%
eq.signal(339109,1); -- Signal to the active manashard that I have healed.
eq.set_next_hp_event(90); -- Set this to happen again at 90%.
elseif e.hp_event == 80 and number_of_correct_protector_kills == 0 then -- If my HP is 80% and I have not locked my HP yet.
eq.set_timer("Lock",1000); -- Lock my HP at this value.
spawn_protectors(e);
elseif e.hp_event == 60 and number_of_correct_protector_kills == 1 then -- If my HP is 60% and I have not locked my HP yet.
eq.set_timer("Lock",1000); -- Lock my HP here
spawn_protectors(e);
elseif e.hp_event == 40 and number_of_correct_protector_kills == 2 then -- If my HP is 40% and I have not locked my HP yet.
eq.set_timer("Lock",1000); -- Lock my HP here
spawn_protectors(e);
elseif e.hp_event == 20 and number_of_correct_protector_kills == 3 then -- If my HP is 20% and I have not locked my HP yet.
eq.set_timer("Lock",1000); -- Lock my HP here
spawn_protectors(e);
end
end
function Fake_Death(e)
eq.signal(339110,2); -- Let Kessdona know I was the incorrect one to be killed.
eq.depop_all(339111); -- Depop all of myself
eq.depop_all(339115); -- Depop the correct target.
end
function Correct_Death(e) -- If I died.
number_of_correct_protector_kills = number_of_correct_protector_kills + 1;
if kess_hp_lock_percent >= 40 then
kess_hp_lock_percent = kess_hp_lock_percent - 20;
end
eq.depop_all(339111); -- Depop all incorrect targets
eq.depop_all(339115); -- Depop all of myself (Probably not needed, since only 1 of me)
eq.signal(339110,3); -- Let Kessdona know I was the correct one to be killed.
end
function Kess_Signal(e)
if e.signal == 1 then -- Let Kessdona know that 6 depleted guardians have died, and to set the next HP event to 80%.
eq.set_next_hp_event(80);
elseif e.signal == 2 then -- Incorrect Protector Killed -- Reset Phase
if number_of_correct_protector_kills == 0 then
e.self:SetHP(e.self:GetMaxHP());
eq.stop_timer('Lock');
eq.set_next_hp_event(80);
elseif number_of_correct_protector_kills == 1 then
e.self:SetHP(e.self:GetMaxHP());
eq.stop_timer('Lock');
eq.set_next_hp_event(60);
elseif number_of_correct_protector_kills == 2 then
e.self:SetHP(e.self:GetMaxHP());
eq.stop_timer('Lock');
eq.set_next_hp_event(40);
elseif number_of_correct_protector_kills == 3 then
e.self:SetHP(e.self:GetMaxHP());
eq.stop_timer('Lock');
eq.set_next_hp_event(20);
end
elseif e.signal == 3 then -- Correct Protector Killed - Next Phase
if number_of_correct_protector_kills == 1 then
eq.stop_timer('Lock');
eq.set_next_hp_event(60);
elseif number_of_correct_protector_kills == 2 then
eq.stop_timer('Lock');
eq.set_next_hp_event(40);
elseif number_of_correct_protector_kills == 3 then
eq.stop_timer('Lock');
eq.set_next_hp_event(20);
elseif number_of_correct_protector_kills == 4 then
eq.stop_timer('Lock');
all_protectors_killed = true;
end
end
end
function Kess_Timer(e)
if e.timer == "oobcheck" and not Kess:contains(e.self:GetX(), e.self:GetY()) then -- If I am not inside this box - respawn me back at spawn point.
e.self:GotoBind();
e.self:WipeHateList();
elseif e.timer == "Lock" then -- HP Lock Routine
if number_of_correct_protector_kills == 0 then
e.self:SetHP(e.self:GetMaxHP() * 0.80); -- Lock my HP at 80%
elseif number_of_correct_protector_kills >= 1 then
if kess_hp_lock_percent >= 20 then
e.self:SetHP(e.self:GetMaxHP() * (kess_hp_lock_percent / 100.0)); -- Lock at hp multiples based on correct protector kills
end
end
elseif e.timer == "fail" then -- If I am not in combat after 30 seconds.
eq.stop_timer('fail'); -- Stop the timer from repeating.
eq.depop(339109);
eq.depop(339108);
eq.depop(339118);
eq.depop(339119);
eq.depop(339120);
eq.depop(339121);
eq.depop(339111);
eq.depop(339115);
eq.depop(339116);
elseif e.timer == "respawn" then
eq.depop(339110);
eq.spawn2(339110,0,0,1227,6338.75,744.19,73.0); -- Respawn myself
eq.stop_timer('respawn');
elseif e.timer == "charm" then
local cl = eq.get_entity_list():GetShuffledClientList();
local count = 0;
for client in cl.entries do
if client.valid then
e.self:CastedSpellFinished(6544, client);
count = count + 1;
end
if count == 3 then
break;
end
end
end
end
function Active_Manashard_Signal(e)
if e.signal == 1 then
if active_manashard_hp == 0 then -- All healing phases completed
e.self:SetHP(e.self:GetMaxHP() * (5 / 100.0)); -- Set my HP to 5% and activate all other golems
make_attackable(e.self, true);
eq.depop(339108);
eq.depop(339118);
eq.depop(339119);
eq.depop(339120);
eq.depop(339121);
-- Spawn depleted manashard guardian with 5% HP
eq.spawn2(339116,0,0,1257.17,6330.92,747.16,462.3):AddToHateList(eq.get_entity_list():GetRandomClient(),1);
eq.spawn2(339116,0,0,1158.62,6328.01,745.01,28.5):AddToHateList(eq.get_entity_list():GetRandomClient(),1);
eq.spawn2(339116,0,0,1128.33,6414.53,744.35,129.5):AddToHateList(eq.get_entity_list():GetRandomClient(),1);
eq.spawn2(339116,0,0,1156.67,6486.17,745.00,196.3):AddToHateList(eq.get_entity_list():GetRandomClient(),1);
eq.spawn2(339116,0,0,1229.06,6507.49,754.67,235.3):AddToHateList(eq.get_entity_list():GetRandomClient(),1);
else
e.self:SetHP(e.self:GetMaxHP() * (active_manashard_hp / 100.0)); -- Remove 20% of my HP
end
end
end
function Depleted_Manashard_Spawn(e)
e.self:SetHP(e.self:GetMaxHP() * 0.05);
eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "The animated guardian charges forth to attack, having depleted its mana reserves.")
end
function Depleted_Manashard_Death(e)
if not eq.get_entity_list():IsMobSpawnedByNpcTypeID(339116) and not eq.get_entity_list():IsMobSpawnedByNpcTypeID(339109) then
all_manashards_dead = true
eq.signal(339110,1); -- let Kessdona know so she can begin phase 2.
end
end
function Kess_Death(e)
eq.spawn2(339117,0,0,e.self:GetX(),e.self:GetY(),e.self:GetZ(),e.self:GetHeading()); -- Spawn a chest with loot at my location upon death.
eq.update_task_activity(dz_task_id, 2, 1);
end
function Kess_BeginCast(e)
if e.spell:ID() == 6543 then
eq.zone_emote(MT.Yellow, "Kessdona rears back and fills her lungs, preparing to exhale a cone of disintegrating flame.");
end
end
function make_attackable(mob, attackable)
mob:SetSpecialAbility(SpecialAbility.immune_melee, attackable and 0 or 1)
mob:SetSpecialAbility(SpecialAbility.immune_magic, attackable and 0 or 1)
mob:SetSpecialAbility(SpecialAbility.immune_aggro, attackable and 0 or 1)
mob:SetSpecialAbility(SpecialAbility.immune_aggro_on, attackable and 0 or 1)
mob:SetSpecialAbility(SpecialAbility.no_harm_from_client, attackable and 0 or 1)
end
function event_encounter_load(e)
dz_task_id = eq.get_dz_task_id();
eq.register_npc_event(Event.spawn, 339110, Kess_Spawn);
eq.register_npc_event(Event.cast_begin, 339110, Kess_BeginCast);
eq.register_npc_event(Event.hp, 339110, Kess_HP);
eq.register_npc_event(Event.combat, 339110, Kess_Combat);
eq.register_npc_event(Event.timer, 339110, Kess_Timer);
eq.register_npc_event(Event.death_complete, 339110, Kess_Death);
eq.register_npc_event(Event.signal, 339109, Active_Manashard_Signal);
eq.register_npc_event(Event.spawn, 339116, Depleted_Manashard_Spawn);
eq.register_npc_event(Event.death_complete, 339116, Depleted_Manashard_Death);
eq.register_npc_event(Event.signal, 339110, Kess_Signal);
eq.register_npc_event(Event.death_complete, 339111, Fake_Death);
eq.register_npc_event(Event.death_complete, 339115, Correct_Death);
end
| 412 | 0.98187 | 1 | 0.98187 | game-dev | MEDIA | 0.975213 | game-dev | 0.916216 | 1 | 0.916216 |
Sigma-Skidder-Team/SigmaRebase | 9,946 | src/main/java/net/minecraft/entity/item/ExperienceOrbEntity.java | package net.minecraft.entity.item;
import java.util.Map.Entry;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.Enchantments;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.MoverType;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.IPacket;
import net.minecraft.network.play.server.SSpawnExperienceOrbPacket;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.DamageSource;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
public class ExperienceOrbEntity extends Entity
{
public int xpColor;
public int xpOrbAge;
public int delayBeforeCanPickup;
private int xpOrbHealth = 5;
private int xpValue;
private PlayerEntity closestPlayer;
private int xpTargetColor;
public ExperienceOrbEntity(World worldIn, double x, double y, double z, int expValue)
{
this(EntityType.EXPERIENCE_ORB, worldIn);
this.setPosition(x, y, z);
this.rotationYaw = (float)(this.rand.nextDouble() * 360.0D);
this.setMotion((this.rand.nextDouble() * (double)0.2F - (double)0.1F) * 2.0D, this.rand.nextDouble() * 0.2D * 2.0D, (this.rand.nextDouble() * (double)0.2F - (double)0.1F) * 2.0D);
this.xpValue = expValue;
}
public ExperienceOrbEntity(EntityType <? extends ExperienceOrbEntity > p_i50382_1_, World entity)
{
super(p_i50382_1_, entity);
}
protected boolean canTriggerWalking()
{
return false;
}
protected void registerData()
{
}
/**
* Called to update the entity's position/logic.
*/
public void tick()
{
super.tick();
if (this.delayBeforeCanPickup > 0)
{
--this.delayBeforeCanPickup;
}
this.prevPosX = this.getPosX();
this.prevPosY = this.getPosY();
this.prevPosZ = this.getPosZ();
if (this.areEyesInFluid(FluidTags.WATER))
{
this.applyFloatMotion();
}
else if (!this.hasNoGravity())
{
this.setMotion(this.getMotion().add(0.0D, -0.03D, 0.0D));
}
if (this.world.getFluidState(this.getPosition()).isTagged(FluidTags.LAVA))
{
this.setMotion((double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F), (double)0.2F, (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F));
this.playSound(SoundEvents.ENTITY_GENERIC_BURN, 0.4F, 2.0F + this.rand.nextFloat() * 0.4F);
}
if (!this.world.hasNoCollisions(this.getBoundingBox()))
{
this.pushOutOfBlocks(this.getPosX(), (this.getBoundingBox().minY + this.getBoundingBox().maxY) / 2.0D, this.getPosZ());
}
double d0 = 8.0D;
if (this.xpTargetColor < this.xpColor - 20 + this.getEntityId() % 100)
{
if (this.closestPlayer == null || this.closestPlayer.getDistanceSq(this) > 64.0D)
{
this.closestPlayer = this.world.getClosestPlayer(this, 8.0D);
}
this.xpTargetColor = this.xpColor;
}
if (this.closestPlayer != null && this.closestPlayer.isSpectator())
{
this.closestPlayer = null;
}
if (this.closestPlayer != null)
{
Vector3d vector3d = new Vector3d(this.closestPlayer.getPosX() - this.getPosX(), this.closestPlayer.getPosY() + (double)this.closestPlayer.getEyeHeight() / 2.0D - this.getPosY(), this.closestPlayer.getPosZ() - this.getPosZ());
double d1 = vector3d.lengthSquared();
if (d1 < 64.0D)
{
double d2 = 1.0D - Math.sqrt(d1) / 8.0D;
this.setMotion(this.getMotion().add(vector3d.normalize().scale(d2 * d2 * 0.1D)));
}
}
this.move(MoverType.SELF, this.getMotion());
float f = 0.98F;
if (this.onGround)
{
f = this.world.getBlockState(new BlockPos(this.getPosX(), this.getPosY() - 1.0D, this.getPosZ())).getBlock().getSlipperiness() * 0.98F;
}
this.setMotion(this.getMotion().mul((double)f, 0.98D, (double)f));
if (this.onGround)
{
this.setMotion(this.getMotion().mul(1.0D, -0.9D, 1.0D));
}
++this.xpColor;
++this.xpOrbAge;
if (this.xpOrbAge >= 6000)
{
this.remove();
}
}
private void applyFloatMotion()
{
Vector3d vector3d = this.getMotion();
this.setMotion(vector3d.x * (double)0.99F, Math.min(vector3d.y + (double)5.0E-4F, (double)0.06F), vector3d.z * (double)0.99F);
}
/**
* Plays the {@link #getSplashSound() splash sound}, and the {@link ParticleType#WATER_BUBBLE} and {@link
* ParticleType#WATER_SPLASH} particles.
*/
protected void doWaterSplashEffect()
{
}
/**
* Called when the entity is attacked.
*/
public boolean attackEntityFrom(DamageSource source, float amount)
{
if (this.isInvulnerableTo(source))
{
return false;
}
else
{
this.markVelocityChanged();
this.xpOrbHealth = (int)((float)this.xpOrbHealth - amount);
if (this.xpOrbHealth <= 0)
{
this.remove();
}
return false;
}
}
public void writeAdditional(CompoundNBT compound)
{
compound.putShort("Health", (short)this.xpOrbHealth);
compound.putShort("Age", (short)this.xpOrbAge);
compound.putShort("Value", (short)this.xpValue);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readAdditional(CompoundNBT compound)
{
this.xpOrbHealth = compound.getShort("Health");
this.xpOrbAge = compound.getShort("Age");
this.xpValue = compound.getShort("Value");
}
/**
* Called by a player entity when they collide with an entity
*/
public void onCollideWithPlayer(PlayerEntity entityIn)
{
if (!this.world.isRemote)
{
if (this.delayBeforeCanPickup == 0 && entityIn.xpCooldown == 0)
{
entityIn.xpCooldown = 2;
entityIn.onItemPickup(this, 1);
Entry<EquipmentSlotType, ItemStack> entry = EnchantmentHelper.getRandomEquippedWithEnchantment(Enchantments.MENDING, entityIn, ItemStack::isDamaged);
if (entry != null)
{
ItemStack itemstack = entry.getValue();
if (!itemstack.isEmpty() && itemstack.isDamaged())
{
int i = Math.min(this.xpToDurability(this.xpValue), itemstack.getDamage());
this.xpValue -= this.durabilityToXp(i);
itemstack.setDamage(itemstack.getDamage() - i);
}
}
if (this.xpValue > 0)
{
entityIn.giveExperiencePoints(this.xpValue);
}
this.remove();
}
}
}
private int durabilityToXp(int durability)
{
return durability / 2;
}
private int xpToDurability(int xp)
{
return xp * 2;
}
/**
* Returns the XP value of this XP orb.
*/
public int getXpValue()
{
return this.xpValue;
}
/**
* Returns a number from 1 to 10 based on how much XP this orb is worth. This is used by RenderXPOrb to determine
* what texture to use.
*/
public int getTextureByXP()
{
if (this.xpValue >= 2477)
{
return 10;
}
else if (this.xpValue >= 1237)
{
return 9;
}
else if (this.xpValue >= 617)
{
return 8;
}
else if (this.xpValue >= 307)
{
return 7;
}
else if (this.xpValue >= 149)
{
return 6;
}
else if (this.xpValue >= 73)
{
return 5;
}
else if (this.xpValue >= 37)
{
return 4;
}
else if (this.xpValue >= 17)
{
return 3;
}
else if (this.xpValue >= 7)
{
return 2;
}
else
{
return this.xpValue >= 3 ? 1 : 0;
}
}
/**
* Get a fragment of the maximum experience points value for the supplied value of experience points value.
*/
public static int getXPSplit(int expValue)
{
if (expValue >= 2477)
{
return 2477;
}
else if (expValue >= 1237)
{
return 1237;
}
else if (expValue >= 617)
{
return 617;
}
else if (expValue >= 307)
{
return 307;
}
else if (expValue >= 149)
{
return 149;
}
else if (expValue >= 73)
{
return 73;
}
else if (expValue >= 37)
{
return 37;
}
else if (expValue >= 17)
{
return 17;
}
else if (expValue >= 7)
{
return 7;
}
else
{
return expValue >= 3 ? 3 : 1;
}
}
/**
* Returns true if it's possible to attack this entity with an item.
*/
public boolean canBeAttackedWithItem()
{
return false;
}
public IPacket<?> createSpawnPacket()
{
return new SSpawnExperienceOrbPacket(this);
}
}
| 412 | 0.909638 | 1 | 0.909638 | game-dev | MEDIA | 0.972107 | game-dev | 0.970567 | 1 | 0.970567 |
gabrieldechichi/dmotion | 7,144 | Editor/PropertyDrawers/AnimationParameterPropertyDrawer.cs | using System;
using System.Linq;
using DMotion.Authoring;
using Unity.Entities.Editor;
using UnityEditor;
using UnityEngine;
namespace DMotion.Editor
{
[CustomPropertyDrawer(typeof(AnimationParameterAsset))]
internal class AnimationParameterPropertyDrawer : PropertyDrawer
{
private EnumTypePopupSelector enumTypePopupSelector;
public AnimationParameterPropertyDrawer()
{
enumTypePopupSelector = new EnumTypePopupSelector();
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var parameterAsset = property.objectReferenceValue as AnimationParameterAsset;
var stateMachineAsset = property.serializedObject.targetObject as StateMachineAsset;
if (parameterAsset != null && stateMachineAsset != null)
{
if (IsAnimatorEntitySelected(stateMachineAsset))
{
DrawParameterPlaymode(position, parameterAsset, stateMachineAsset);
}
else
{
using (new EditorGUI.DisabledScope(Application.isPlaying))
{
DrawPropertyEditorMode(position, parameterAsset, stateMachineAsset, property);
}
}
}
}
private static void DrawParameterPlaymode(Rect position, AnimationParameterAsset parameterAsset,
StateMachineAsset stateMachineAsset)
{
if (EntitySelectionProxyUtils.TryExtractEntitySelectionProxy(out var selectedEntity))
{
var label = new GUIContent(parameterAsset.name);
switch (parameterAsset)
{
case BoolParameterAsset:
{
var parameterIndex = stateMachineAsset.Parameters.OfType<BoolParameterAsset>()
.FindIndex(p => parameterAsset == p);
var boolParameters = selectedEntity.GetBuffer<BoolParameter>();
var boolParameter = boolParameters[parameterIndex];
boolParameter.Value = EditorGUI.Toggle(position, label, boolParameter.Value);
boolParameters[parameterIndex] = boolParameter;
break;
}
case IntParameterAsset:
{
var parameterIndex = stateMachineAsset.Parameters.OfType<IntParameterAsset>()
.FindIndex(p => parameterAsset == p);
var intParameters = selectedEntity.GetBuffer<IntParameter>();
var intParameter = intParameters[parameterIndex];
if (parameterAsset is EnumParameterAsset enumParameterAsset)
{
intParameter.Value = EditorGUIUtils.GenericEnumPopup(position,
enumParameterAsset.EnumType.Type,
intParameter.Value);
}
else
{
intParameter.Value = EditorGUI.IntField(position, label, intParameter.Value);
}
intParameters[parameterIndex] = intParameter;
break;
}
case FloatParameterAsset:
{
var parameterIndex = stateMachineAsset.Parameters.OfType<FloatParameterAsset>()
.FindIndex(p => parameterAsset == p);
var floatParameters = selectedEntity.GetBuffer<FloatParameter>();
var floatParameter = floatParameters[parameterIndex];
floatParameter.Value = EditorGUI.FloatField(position, label, floatParameter.Value);
floatParameters[parameterIndex] = floatParameter;
break;
}
default:
throw new NotImplementedException(
$"No handling for type {parameterAsset.GetType().Name}");
}
}
}
private bool IsAnimatorEntitySelected(StateMachineAsset myStateMachineAsset)
{
return Application.isPlaying &&
EntitySelectionProxyUtils.TryExtractEntitySelectionProxy(out var entitySelectionProxy) &&
entitySelectionProxy.Exists && entitySelectionProxy.HasComponent<AnimationStateMachineDebug>()
&& entitySelectionProxy
.GetManagedComponent<AnimationStateMachineDebug>()
.StateMachineAsset ==
myStateMachineAsset;
}
private void DrawPropertyEditorMode(Rect position, AnimationParameterAsset parameterAsset,
StateMachineAsset stateMachine,
SerializedProperty property)
{
using (var c = new EditorGUI.ChangeCheckScope())
{
var labelWidth = EditorGUIUtility.labelWidth;
var deleteButtonWidth = EditorGUIUtility.singleLineHeight;
var typeWidth = position.width - labelWidth - deleteButtonWidth;
var rects = position.HorizontalLayout(labelWidth, typeWidth, deleteButtonWidth).ToArray();
//label
{
var newName = EditorGUI.DelayedTextField(rects[0], parameterAsset.name);
if (newName != parameterAsset.name)
{
parameterAsset.name = newName;
EditorUtility.SetDirty(parameterAsset);
AssetDatabase.SaveAssetIfDirty(parameterAsset);
AssetDatabase.Refresh();
}
}
//type
{
if (parameterAsset is EnumParameterAsset enumParameterAsset)
{
enumTypePopupSelector.DrawSelectionPopup(rects[1],
GUIContent.none,
enumParameterAsset.EnumType.Type,
newType =>
{
enumParameterAsset.EnumType.Type = newType;
EditorUtility.SetDirty(enumParameterAsset);
});
}
else
{
EditorGUI.LabelField(rects[1], $"({parameterAsset.ParameterTypeName})");
}
}
//delete
{
if (GUI.Button(rects[2], "-"))
{
stateMachine.DeleteParameter(parameterAsset);
property.serializedObject.ApplyModifiedProperties();
property.serializedObject.Update();
}
}
}
}
}
} | 412 | 0.87831 | 1 | 0.87831 | game-dev | MEDIA | 0.902117 | game-dev | 0.865218 | 1 | 0.865218 |
ProgramForFun/Icy | 6,364 | Icy/Assets/Plugins/UniTask/Runtime/Linq/Max.cs | using System;
using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks.Internal;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static UniTask<TSource> MaxAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
return Max.MaxAsync(source, cancellationToken);
}
public static UniTask<TResult> MaxAsync<TSource, TResult>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, TResult> selector, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(source, nameof(selector));
return Max.MaxAsync(source, selector, cancellationToken);
}
public static UniTask<TResult> MaxAwaitAsync<TSource, TResult>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<TResult>> selector, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(source, nameof(selector));
return Max.MaxAwaitAsync(source, selector, cancellationToken);
}
public static UniTask<TResult> MaxAwaitWithCancellationAsync<TSource, TResult>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<TResult>> selector, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(source, nameof(selector));
return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken);
}
}
internal static partial class Max
{
public static async UniTask<TSource> MaxAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
TSource value = default;
var comparer = Comparer<TSource>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = e.Current;
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = e.Current;
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
public static async UniTask<TResult> MaxAsync<TSource, TResult>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, TResult> selector, CancellationToken cancellationToken)
{
TResult value = default;
var comparer = Comparer<TResult>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = selector(e.Current);
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = selector(e.Current);
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
public static async UniTask<TResult> MaxAwaitAsync<TSource, TResult>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<TResult>> selector, CancellationToken cancellationToken)
{
TResult value = default;
var comparer = Comparer<TResult>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = await selector(e.Current);
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = await selector(e.Current);
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
public static async UniTask<TResult> MaxAwaitWithCancellationAsync<TSource, TResult>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<TResult>> selector, CancellationToken cancellationToken)
{
TResult value = default;
var comparer = Comparer<TResult>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = await selector(e.Current, cancellationToken);
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = await selector(e.Current, cancellationToken);
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
}
} | 412 | 0.894199 | 1 | 0.894199 | game-dev | MEDIA | 0.531091 | game-dev | 0.859403 | 1 | 0.859403 |
CraftTweaker/CraftTweaker | 1,613 | common/src/main/java/com/blamejared/crafttweaker/natives/block/entity/ExpandDecoratedPotPattern.java | package com.blamejared.crafttweaker.natives.block.entity;
import com.blamejared.crafttweaker.api.annotation.ZenRegister;
import com.blamejared.crafttweaker.platform.Services;
import com.blamejared.crafttweaker_annotations.annotations.Document;
import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
import com.blamejared.crafttweaker_annotations.annotations.TaggableElement;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.entity.DecoratedPotPattern;
import org.openzen.zencode.java.ZenCodeType;
@ZenRegister
@Document("vanilla/api/block/entity/DecoratedPotPattern")
@NativeTypeRegistration(value = DecoratedPotPattern.class, zenCodeName = "crafttweaker.api.block.entity.DecoratedPotPattern")
@TaggableElement("minecraft:decorated_pot_pattern")
public class ExpandDecoratedPotPattern {
/**
* Gets the location of the asset used by the pot pattern.
*
* @return The pot pattern asset ID.
*/
@ZenCodeType.Method
@ZenCodeType.Getter("assetId")
public static ResourceLocation assetId(DecoratedPotPattern internal) {
return internal.assetId();
}
/**
* Gets the command string for the pot pattern.
*
* @return The command string for the pot pattern.
*/
@ZenCodeType.Getter("commandString")
public static String getCommandString(DecoratedPotPattern internal) {
return "<decoratedpotpattern:" + Services.REGISTRY.keyOrThrow(Registries.DECORATED_POT_PATTERN, internal) + ">";
}
} | 412 | 0.587554 | 1 | 0.587554 | game-dev | MEDIA | 0.988982 | game-dev | 0.502034 | 1 | 0.502034 |
CalamityTeam/CalamityModPublic | 5,470 | Items/ColdheartIcicle.cs | using CalamityMod.NPCs.Crags;
using CalamityMod.NPCs.Other;
using CalamityMod.Particles;
using CalamityMod.Rarities;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items
{
[LegacyName("AlicornonaStick")]
public class ColdheartIcicle : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Misc";
public override void SetDefaults()
{
Item.width = 42;
Item.height = 50;
Item.holdStyle = 6;
Item.value = 0;
Item.rare = ModContent.RarityType<CalamityRed>();
}
public override void HoldStyle(Player player, Rectangle heldItemFrame)
{
player.itemRotation = player.direction == -1 ? -MathHelper.PiOver4 : MathHelper.PiOver4;
player.itemLocation = player.GetBackHandPosition(Player.CompositeArmStretchAmount.Full, player.direction * MathHelper.PiOver4) + Vector2.UnitX * player.direction * 14;
}
public override void HoldItemFrame(Player player)
{
player.SetCompositeArmBack(true, Player.CompositeArmStretchAmount.Full, -player.direction * MathHelper.PiOver4);
}
public override void HoldItem(Player player)
{
int offset = player.direction == 1 ? 5 : -Item.width - 5;
Rectangle itemRect = new Rectangle((int)player.Center.X + offset, (int)player.position.Y - 10, Item.width, Item.height);
foreach (NPC npc in Main.ActiveNPCs)
{
if (!npc.dontTakeDamage && npc.type != ModContent.NPCType<THELORDE>())
{
if (itemRect.Intersects(npc.getRect()))
{
int damage = npc.SimpleStrikeNPC((int)(npc.lifeMax / 200), player.direction, true);
SoundEngine.PlaySound(Projectiles.Summon.CnidarianJellyfishOnTheString.SlapSound with { Volume = 2, MaxInstances = 200 }, npc.Center);
if (Main.netMode != NetmodeID.Server)
{
BloodShed(itemRect, npc, damage, player);
}
}
}
}
}
public void BloodShed(Rectangle hitBox, NPC target, int damage, Player player)
{
// this is violence but exaggerated
float damageInterpolant = Utils.GetLerpValue(950f, 2000f, damage, true);
Vector2 impactPoint = Vector2.Lerp(hitBox.Center.ToVector2(), target.Center, 0.65f);
Vector2 bloodSpawnPosition = target.Center + Main.rand.NextVector2Circular(target.width, target.height) * 0.04f;
Vector2 splatterDirection = (new Vector2(bloodSpawnPosition.X * player.direction, bloodSpawnPosition.Y)).SafeNormalize(Vector2.UnitY);
// Emit blood if the target is organic.
if (target.Organic())
{
for (int i = 0; i < 16; i++)
{
int bloodLifetime = Main.rand.Next(22, 36);
float bloodScale = Main.rand.NextFloat(0.6f, 0.8f);
Color bloodColor = Color.Lerp(Color.Red, Color.DarkRed, Main.rand.NextFloat());
bloodColor = Color.Lerp(bloodColor, new Color(51, 22, 94), Main.rand.NextFloat(0.65f));
if (Main.rand.NextBool(20))
bloodScale *= 2f;
Vector2 bloodVelocity = splatterDirection.RotatedByRandom(0.81f) * Main.rand.NextFloat(11f, 23f);
bloodVelocity.Y -= 12f;
BloodParticle blood = new BloodParticle(bloodSpawnPosition, bloodVelocity, bloodLifetime, bloodScale, bloodColor);
GeneralParticleHandler.SpawnParticle(blood);
}
for (int i = 0; i < 9; i++)
{
float bloodScale = Main.rand.NextFloat(0.2f, 0.33f);
Color bloodColor = Color.Lerp(Color.Red, Color.DarkRed, Main.rand.NextFloat(0.5f, 1f));
Vector2 bloodVelocity = splatterDirection.RotatedByRandom(0.9f) * Main.rand.NextFloat(9f, 14.5f);
BloodParticle2 blood = new BloodParticle2(bloodSpawnPosition, bloodVelocity, 20, bloodScale, bloodColor);
GeneralParticleHandler.SpawnParticle(blood);
}
}
// Emit sparks if the target is not organic.
else
{
for (int i = 0; i < 16; i++)
{
int sparkLifetime = Main.rand.Next(22, 36);
float sparkScale = Main.rand.NextFloat(0.8f, 1f) + damageInterpolant * 0.85f;
Color sparkColor = Color.Lerp(Color.Silver, Color.Gold, Main.rand.NextFloat(0.7f));
sparkColor = Color.Lerp(sparkColor, Color.Orange, Main.rand.NextFloat());
if (Main.rand.NextBool(10))
sparkScale *= 2f;
Vector2 sparkVelocity = splatterDirection.RotatedByRandom(0.6f) * Main.rand.NextFloat(12f, 25f);
sparkVelocity.Y -= 6f;
SparkParticle spark = new SparkParticle(impactPoint, sparkVelocity, true, sparkLifetime, sparkScale, sparkColor);
GeneralParticleHandler.SpawnParticle(spark);
}
}
}
}
}
| 412 | 0.931709 | 1 | 0.931709 | game-dev | MEDIA | 0.987289 | game-dev | 0.916856 | 1 | 0.916856 |
PazerOP/tf2_bot_detector | 2,959 | tf2_bot_detector/SteamID.cpp | #include "SteamID.h"
#include "Util/RegexUtils.h"
#include <mh/text/format.hpp>
#include <nlohmann/json.hpp>
#include <regex>
#include <stdexcept>
using namespace std::string_literals;
using namespace tf2_bot_detector;
SteamID::SteamID(const std::string_view& str)
{
ID64 = 0;
// Steam3
static std::regex s_SteamID3Regex(R"regex(\[([a-zA-Z]):(\d):(\d+)(?::(\d+))?\])regex", std::regex::optimize);
if (std::match_results<std::string_view::const_iterator> result;
std::regex_match(str.begin(), str.end(), result, s_SteamID3Regex))
{
const char firstChar = *result[1].first;
switch (firstChar)
{
case 'U': Type = SteamAccountType::Individual; break;
case 'M': Type = SteamAccountType::Multiseat; break;
case 'G': Type = SteamAccountType::GameServer; break;
case 'A': Type = SteamAccountType::AnonGameServer; break;
case 'P': Type = SteamAccountType::Pending; break;
case 'C': Type = SteamAccountType::ContentServer; break;
case 'g': Type = SteamAccountType::Clan; break;
case 'a': Type = SteamAccountType::AnonUser; break;
case 'T':
case 'L':
case 'c':
Type = SteamAccountType::Chat; break;
case 'I':
Type = SteamAccountType::Invalid;
return; // We're totally done trying to parse
default:
throw std::invalid_argument(mh::format("Invalid SteamID3: Unknown SteamAccountType '{}'", firstChar));
}
{
uint32_t universe;
if (auto parseResult = from_chars(result[2], universe); !parseResult)
throw std::invalid_argument(mh::format("Out-of-range value for SteamID3 universe: {}", result[2].str()));
Universe = static_cast<SteamAccountUniverse>(universe);
}
{
uint32_t id;
if (auto parseResult = from_chars(result[3], id); !parseResult)
throw std::invalid_argument(mh::format("Out-of-range value for SteamID3 ID: {}", result[3].str()));
ID = id;
}
if (result[4].matched)
{
uint32_t instance;
if (auto parseResult = from_chars(result[4], instance); !parseResult)
throw std::invalid_argument(mh::format("Out-of-range value for SteamID3 account instance: {}", result[4].str()));
Instance = static_cast<SteamAccountInstance>(instance);
}
else
{
Instance = SteamAccountInstance::Desktop;
}
return;
}
// Steam64
if (std::all_of(str.begin(), str.end(), [](char c) { return std::isdigit(c) || std::isspace(c); }))
{
uint64_t result;
if (auto parseResult = mh::from_chars(str, result); !parseResult)
throw std::invalid_argument(mh::format("Out-of-range SteamID64: {}", str));
ID64 = result;
return;
}
throw std::invalid_argument("SteamID string does not match any known formats");
}
std::string SteamID::str() const
{
return mh::format("{}", *this);
}
void tf2_bot_detector::to_json(nlohmann::json& j, const SteamID& d)
{
j = d.str();
}
void tf2_bot_detector::from_json(const nlohmann::json& j, SteamID& d)
{
if (j.is_number_unsigned())
d = SteamID(j.get<uint64_t>());
else
d = SteamID(j.get<std::string_view>());
}
| 412 | 0.718232 | 1 | 0.718232 | game-dev | MEDIA | 0.424932 | game-dev | 0.671872 | 1 | 0.671872 |
ProjectIgnis/CardScripts | 2,903 | official/c95824983.lua | --電気海月-フィサリア-
--Electric Jellyfish
--Scripted by Hatter
local s,id=GetID()
function s.initial_effect(c)
--Special Summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,id)
e1:SetCost(s.spcost)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--Negate
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_DISABLE+CATEGORY_ATKCHANGE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_CHAINING)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,{id,1})
e2:SetCondition(s.negcon)
e2:SetTarget(s.negtg)
e2:SetOperation(s.negop)
c:RegisterEffect(e2)
end
s.listed_names={CARD_UMI}
function s.spcostfilter(c,tp)
return c:IsCode(CARD_UMI) and c:IsAbleToGraveAsCost() and (c:IsFaceup() or not c:IsOnField())
and Duel.GetMZoneCount(tp,c)>0
end
function s.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.spcostfilter,tp,LOCATION_HAND|LOCATION_DECK|LOCATION_ONFIELD,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,s.spcostfilter,tp,LOCATION_HAND|LOCATION_DECK|LOCATION_ONFIELD,0,1,1,nil,tp)
Duel.SendtoGrave(g,REASON_COST)
end
function s.spfilter(c,e,tp)
return c:IsAttribute(ATTRIBUTE_WATER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if #g>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function s.negcon(e,tp,eg,ep,ev,re,r,rp)
return rp==1-tp and Duel.IsChainDisablable(ev) and (re:IsSpellEffect() or re:IsMonsterEffect())
and (Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsCode,CARD_UMI),tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) or Duel.IsEnvironment(CARD_UMI))
end
function s.negtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE,eg,1,0,0)
end
function s.negop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.NegateEffect(ev) and c:IsFaceup() and c:IsRelateToEffect(e)
and Duel.SelectYesNo(tp,aux.Stringid(id,2)) then
Duel.BreakEffect()
--Gain ATK/DEF
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(600)
e1:SetReset(RESET_EVENT|RESETS_STANDARD_DISABLE)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e2)
end
end | 412 | 0.935618 | 1 | 0.935618 | game-dev | MEDIA | 0.968354 | game-dev | 0.967157 | 1 | 0.967157 |
trungvose/angular-tetris | 8,146 | src/app/containers/angular-tetris/angular-tetris.component.ts | import { ClockComponent } from '@angular-tetris/components/clock/clock.component';
import { GithubComponent } from '@angular-tetris/components/github/github.component';
import { HoldComponent } from '@angular-tetris/components/hold/hold.component';
import { KeyboardComponent } from '@angular-tetris/components/keyboard/keyboard.component';
import { LevelComponent } from '@angular-tetris/components/level/level.component';
import { LogoComponent } from '@angular-tetris/components/logo/logo.component';
import { MatrixComponent } from '@angular-tetris/components/matrix/matrix.component';
import { NextComponent } from '@angular-tetris/components/next/next.component';
import { PauseComponent } from '@angular-tetris/components/pause/pause.component';
import { PointComponent } from '@angular-tetris/components/point/point.component';
import { ScreenDecorationComponent } from '@angular-tetris/components/screen-decoration/screen-decoration.component';
import { SoundComponent } from '@angular-tetris/components/sound/sound.component';
import { StartLineComponent } from '@angular-tetris/components/start-line/start-line.component';
import { TetrisKeyboard } from '@angular-tetris/interface/keyboard';
import { SoundManagerService } from '@angular-tetris/services/sound-manager.service';
import { KeyboardService } from '@angular-tetris/state/keyboard/keyboard.service';
import { TetrisService } from '@angular-tetris/state/tetris/tetris.service';
import { TetrisStateService } from '@angular-tetris/state/tetris/tetris.state';
import { AsyncPipe, NgIf } from '@angular/common';
import {
ChangeDetectionStrategy,
Component,
ElementRef,
HostListener,
OnInit,
Renderer2,
inject
} from '@angular/core';
const KeyUp = 'document:keyup';
const KeyDown = 'document:keydown';
@Component({
selector: 'angular-tetris', // eslint-disable-line @angular-eslint/component-selector
standalone: true,
imports: [
NgIf,
AsyncPipe,
ClockComponent,
GithubComponent,
HoldComponent,
KeyboardComponent,
LevelComponent,
LogoComponent,
MatrixComponent,
NextComponent,
PauseComponent,
PointComponent,
ScreenDecorationComponent,
SoundComponent,
StartLineComponent
],
templateUrl: './angular-tetris.component.html',
styleUrls: ['./angular-tetris.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AngularTetrisComponent implements OnInit {
private tetrisState = inject(TetrisStateService);
private tetrisService = inject(TetrisService);
private keyboardService = inject(KeyboardService);
private soundManager = inject(SoundManagerService);
private el = inject(ElementRef);
private render = inject(Renderer2);
drop = this.keyboardService.drop;
isShowLogo$ = this.tetrisState.isShowLogo$;
filling: number;
@HostListener('window:resize', ['$event'])
resize() {
const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;
const ratio = height / width;
let scale = 1;
if (ratio < 1.5) {
scale = height / 960;
} else {
scale = width / 640;
this.filling = (height - 960 * scale) / scale / 3;
const paddingTop = Math.floor(this.filling) + 42;
const paddingBottom = Math.floor(this.filling);
const marginTop = Math.floor(-480 - this.filling * 1.5);
this.setPaddingMargin(paddingTop, paddingBottom, marginTop);
}
this.render.setStyle(this.el.nativeElement, 'transform', `scale(${scale - 0.01})`);
}
@HostListener('window:beforeunload', ['$event'])
unloadHandler(event: Event) {
if (this.hasCurrent) {
event.preventDefault();
event.returnValue = true;
}
}
@HostListener(`${KeyDown}.${TetrisKeyboard.Left}`)
keyDownLeft() {
this.soundManager.move();
this.keyboardService.setKeỵ({
left: true
});
if (this.hasCurrent) {
this.tetrisService.moveLeft();
} else {
this.tetrisService.decreaseLevel();
}
}
@HostListener(`${KeyUp}.${TetrisKeyboard.Left}`)
keyUpLeft() {
this.keyboardService.setKeỵ({
left: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.Right}`)
keyDownRight() {
this.soundManager.move();
this.keyboardService.setKeỵ({
right: true
});
if (this.hasCurrent) {
this.tetrisService.moveRight();
} else {
this.tetrisService.increaseLevel();
}
}
@HostListener(`${KeyUp}.${TetrisKeyboard.Right}`)
keyUpRight() {
this.keyboardService.setKeỵ({
right: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.Up}`)
keyDownUp() {
this.soundManager.rotate();
this.keyboardService.setKeỵ({
up: true
});
if (this.hasCurrent) {
this.tetrisService.rotate();
} else {
this.tetrisService.increaseStartLine();
}
}
@HostListener(`${KeyUp}.${TetrisKeyboard.Up}`)
keyUpUp() {
this.keyboardService.setKeỵ({
up: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.Down}`)
keyDownDown() {
this.soundManager.move();
this.keyboardService.setKeỵ({
down: true
});
if (this.hasCurrent) {
this.tetrisService.moveDown();
} else {
this.tetrisService.decreaseStartLine();
}
}
@HostListener(`${KeyUp}.${TetrisKeyboard.Down}`)
keyUpDown() {
this.keyboardService.setKeỵ({
down: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.Space}`)
keyDownSpace() {
this.keyboardService.setKeỵ({
drop: true
});
if (this.hasCurrent) {
this.soundManager.fall();
this.tetrisService.drop();
return;
}
this.soundManager.start();
this.tetrisService.start();
}
@HostListener(`${KeyUp}.${TetrisKeyboard.Space}`)
keyUpSpace() {
this.keyboardService.setKeỵ({
drop: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.C}`)
keyDownHold() {
this.soundManager.move();
this.keyboardService.setKeỵ({
hold: true
});
this.tetrisService.holdPiece();
}
@HostListener(`${KeyUp}.${TetrisKeyboard.C}`)
keyUpHold() {
this.keyboardService.setKeỵ({
hold: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.S}`)
keyDownSound() {
this.soundManager.move();
this.tetrisService.toggleSound();
this.keyboardService.setKeỵ({
sound: true
});
}
@HostListener(`${KeyUp}.${TetrisKeyboard.S}`)
keyUpSound() {
this.keyboardService.setKeỵ({
sound: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.P}`)
keyDownPause() {
this.soundManager.move();
this.keyboardService.setKeỵ({
pause: true
});
if (this.tetrisState.canStartGame()) {
this.tetrisService.resume();
} else {
this.tetrisService.pause();
}
}
@HostListener(`${KeyUp}.${TetrisKeyboard.P}`)
keyUpPause() {
this.keyboardService.setKeỵ({
pause: false
});
}
@HostListener(`${KeyDown}.${TetrisKeyboard.R}`)
keyDownReset() {
this.soundManager.move();
this.keyboardService.setKeỵ({
reset: true
});
this.tetrisService.pause();
setTimeout(() => {
if (confirm('You are having a good game. Are you sure you want to reset?')) {
this.tetrisService.reset();
} else {
this.tetrisService.resume();
}
this.keyUpReset();
});
}
@HostListener(`${KeyUp}.${TetrisKeyboard.R}`)
keyUpReset() {
this.keyboardService.setKeỵ({
reset: false
});
}
get hasCurrent() {
return this.tetrisState.hasCurrent();
}
ngOnInit(): void {
setTimeout(() => {
this.resize();
});
}
keyboardMouseDown(key: string) {
this[`keyDown${key}`]();
}
keyboardMouseUp(key: string) {
this[`keyUp${key}`]();
}
private setPaddingMargin(paddingTop: number, paddingBottom: number, marginTop: number) {
this.render.setStyle(this.el.nativeElement, 'padding-top', `${paddingTop}px`);
this.render.setStyle(this.el.nativeElement, 'padding-bottom', `${paddingBottom}px`);
this.render.setStyle(this.el.nativeElement, 'margin-top', `${marginTop}px`);
}
}
| 412 | 0.684684 | 1 | 0.684684 | game-dev | MEDIA | 0.882821 | game-dev | 0.86635 | 1 | 0.86635 |
monadgroup/axiom | 3,103 | editor/model/actions/DeleteObjectAction.cpp | #include "DeleteObjectAction.h"
#include "../IdentityReferenceMapper.h"
#include "../ModelObject.h"
#include "../ModelRoot.h"
#include "../PoolOperators.h"
#include "../serialize/ModelObjectSerializer.h"
#include "../serialize/ProjectSerializer.h"
using namespace AxiomModel;
DeleteObjectAction::DeleteObjectAction(const QUuid &uuid, QByteArray buffer, AxiomModel::ModelRoot *root)
: Action(ActionType::DELETE_OBJECT, root), _uuid(uuid), _buffer(std::move(buffer)) {}
std::unique_ptr<DeleteObjectAction> DeleteObjectAction::create(const QUuid &uuid, QByteArray buffer,
AxiomModel::ModelRoot *root) {
return std::make_unique<DeleteObjectAction>(uuid, std::move(buffer), root);
}
std::unique_ptr<DeleteObjectAction> DeleteObjectAction::create(const QUuid &uuid, AxiomModel::ModelRoot *root) {
return create(uuid, QByteArray(), root);
}
void DeleteObjectAction::forward(bool) {
auto sortedItems = heapSort(getLinkedItems(_uuid));
QDataStream stream(&_buffer, QIODevice::WriteOnly);
ModelObjectSerializer::serializeChunk(stream, QUuid(), sortedItems);
// We can't just iterate over a collection of ModelObjects and call remove() on them,
// as objects also delete their children.
// Instead, we build a list of UUIDs to delete, create a Sequence of them, and iterate
// until that's empty.
// We'll also need a list of parent UUIDs to build transactions later, so we can do that here.
QSet<QUuid> usedIds;
for (const auto &itm : sortedItems) {
usedIds.insert(itm->uuid());
}
auto itemsToDelete =
findAll(AxiomCommon::dynamicCast<ModelObject *>(root()->pool().sequence().sequence()), usedIds);
// remove all items
while (!itemsToDelete.empty()) {
(*itemsToDelete.begin())->remove();
}
}
void DeleteObjectAction::backward() {
QDataStream stream(&_buffer, QIODevice::ReadOnly);
IdentityReferenceMapper ref;
auto addedObjects =
ModelObjectSerializer::deserializeChunk(stream, ProjectSerializer::schemaVersion, root(), QUuid(), &ref, false);
_buffer.clear();
}
std::vector<ModelObject *> DeleteObjectAction::getLinkedItems(const QUuid &seed) const {
auto dependents = AxiomCommon::collect(
findDependents(AxiomCommon::dynamicCast<ModelObject *>(root()->pool().sequence().sequence()), seed));
auto links = AxiomCommon::flatten(
AxiomCommon::map(AxiomCommon::refSequence(&dependents), [](ModelObject *obj) { return obj->links(); }));
auto linkDependents = AxiomCommon::collect(AxiomCommon::flatten(
AxiomCommon::map(links, [this](ModelObject *obj) { return getLinkedItems(obj->uuid()); })));
std::vector<ModelObject *> subSequences;
subSequences.reserve(links.size() + linkDependents.size());
std::back_insert_iterator<std::vector<ModelObject *>> iter(subSequences);
std::copy(dependents.begin(), dependents.end(), iter);
std::copy(linkDependents.begin(), linkDependents.end(), iter);
return AxiomCommon::collect(distinctByUuid(std::move(subSequences)));
}
| 412 | 0.963159 | 1 | 0.963159 | game-dev | MEDIA | 0.294274 | game-dev | 0.949968 | 1 | 0.949968 |
salutesh/DayZ-Expansion-Scripts | 1,728 | DayZExpansion/Vehicles/Scripts/4_World/DayZExpansion_Vehicles/Classes/UserActionsComponent/Actions/Continuous/ExpansionActionRotateRotors.c | class CAContinuousExpansionRotateRotors: CAContinuousBase
{
override bool IsContinuousAction()
{
return true;
}
override int Execute(ActionData action_data)
{
return UA_INITIALIZE; //! Makes it stay in "loading" circle w/o progress
}
}
class ExpansionActionRotateRotorsCB: ActionContinuousBaseCB
{
override void CreateActionComponent()
{
m_ActionData.m_ActionComponent = new CAContinuousExpansionRotateRotors;
}
}
class ExpansionActionRotateRotors: ActionContinuousBase
{
void ExpansionActionRotateRotors()
{
m_CallbackClass = ExpansionActionRotateRotorsCB;
m_CommandUID = DayZPlayerConstants.CMD_ACTIONFB_INTERACT;
m_FullBody = true;
m_StanceMask = DayZPlayerConstants.STANCEMASK_ALL;
m_Text = "[ADMIN] Rotate Rotors";
}
override typename GetInputType()
{
return ContinuousInteractActionInput;
}
override void CreateConditionComponents()
{
m_ConditionItem = new CCINone;
m_ConditionTarget = new CCTCursor;
}
override bool IsLocal()
{
return true;
}
override bool ActionCondition(PlayerBase player, ActionTarget target, ItemBase item)
{
if (item)
return false;
if (!target.GetParentOrObject().IsInherited(ExpansionHelicopterScript))
return false;
if (!GetPermissionsManager().IsAdminToolsToggledOn())
return false;
return true;
}
override void OnStartClient(ActionData action_data)
{
ExpansionHelicopterScript heli;
if (Class.CastTo(heli, action_data.m_Target.GetParentOrObject()))
{
heli.Expansion_RotateRotors(0.051333);
}
}
override void OnEndClient(ActionData action_data)
{
ExpansionHelicopterScript heli;
if (Class.CastTo(heli, action_data.m_Target.GetParentOrObject()))
{
heli.Expansion_RotateRotors(0.0);
}
}
}
| 412 | 0.924732 | 1 | 0.924732 | game-dev | MEDIA | 0.980428 | game-dev | 0.956594 | 1 | 0.956594 |
aumuell/open-inventor | 3,505 | libSoXt/include/SoXtMinMaxSlider.h | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
// -*- C++ -*-
/*
* Copyright (C) 1990-93 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Description:
| A component class that creates a more functionally extensive
| slider than that given by motif.
|
| Author(s) : Paul Isaacs
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#ifndef SO_XT_MIN_MAX_SLIDER_
#define SO_XT_MIN_MAX_SLIDER_
#include <Inventor/Xt/SoXtSliderSetBase.h>
#define DEFAULT_SLIDER_DECIMAL_POINTS 2
#define DEFAULT_SLIDER_SCALE_MINIMUM -1000
#define DEFAULT_SLIDER_SCALE_MAXIMUM 1000
class SoXtSliderTool;
class SoXtMultiSlider;
class SoXtMinMaxSlider : public SoXtSliderSetBase
{
public:
SoXtMinMaxSlider(
Widget parent = NULL,
const char *name = NULL,
SbBool buildInsideParent = TRUE,
int startingMin = DEFAULT_SLIDER_SCALE_MINIMUM,
int startingMax = DEFAULT_SLIDER_SCALE_MAXIMUM);
~SoXtMinMaxSlider();
float getSliderValue();
float getSliderMin();
float getSliderMax();
void setSliderValue( float theVal );
void setSliderMin( float theMin );
void setSliderMax( float theMax );
short getNumDecimals();
// internal:
static void sliderCallback(Widget w, void *client_data, void *call_data );
void setSliderTool( SoXtSliderTool *newOne ) { _sliderTool = newOne; };
void setMultiSlider( SoXtMultiSlider *newOne ) { _multiSlider = newOne; };
protected:
Widget buildWidget(Widget parent);
private:
int _startingMin;
int _startingMax;
float convertSliderToFloat( int sliderValue );
int convertFloatToSlider( float floatValue );
SoXtSliderTool *_sliderTool;
SoXtMultiSlider *_multiSlider;
};
#endif /* SO_XT_MIN_MAX_SLIDER_ */
| 412 | 0.642404 | 1 | 0.642404 | game-dev | MEDIA | 0.398327 | game-dev | 0.562487 | 1 | 0.562487 |
Isetta-Team/Isetta-Engine | 1,595 | Isetta/IsettaTestbed/Halves/Bullet.cpp | /*
* Copyright (c) 2018 Isetta
*/
#include "Bullet.h"
#include "GameManager.h"
#include "Zombie.h"
namespace Isetta {
class MeshComponent;
float Bullet::flySpeed = 50;
// Bullet is pooled by player. Reactive is called when a player get a bullet
// from pool
void Bullet::Reactivate(const Math::Vector3& pos, const Math::Vector3& flyDir) {
dir = flyDir.Normalized();
transform->SetWorldPos(pos);
transform->LookAt(transform->GetWorldPos() + dir);
}
void Bullet::OnEnable() {
if (!initialized) {
// initialize bullet for the first time
entity->AddComponent<MeshComponent>("Halves/Bullet/Bullet.scene.xml");
audio = entity->AddComponent<AudioSource>(
AudioClip::Load("Halves/Sound/bullet-impact.wav"));
initialized = true;
}
elapsedTime = 0.f;
}
void Bullet::Update() {
if (!entity->GetActive()) return;
transform->TranslateWorld(dir * Time::GetDeltaTime() * flySpeed);
elapsedTime += Time::GetDeltaTime();
// if the bullet been alive too long, destroy it for performance
if (elapsedTime > lifeTime) {
entity->SetActive(false);
}
// detect hitting zombie. This code is written before we had collisions
for (const auto& zombie : GameManager::zombies) {
if (!zombie->GetActive()) continue;
float disSqrd = (zombie->transform->GetWorldPos() +
1.5 * Math::Vector3::up - transform->GetWorldPos())
.SqrMagnitude();
if (disSqrd < 1.f) {
zombie->GetComponent<Zombie>()->TakeDamage(damage);
entity->SetActive(false);
audio->Play();
}
}
}
} // namespace Isetta
| 412 | 0.9256 | 1 | 0.9256 | game-dev | MEDIA | 0.987427 | game-dev | 0.954267 | 1 | 0.954267 |
Megabit/Blazorise | 1,387 | Source/Blazorise/Components/Bar/BarMenu.razor.cs | #region Using directives
using Blazorise.States;
using Blazorise.Utilities;
using Microsoft.AspNetCore.Components;
#endregion
namespace Blazorise;
/// <summary>
/// The main part of the <see cref="Bar"/>, hidden on touch devices, visible on desktop.
/// </summary>
public partial class BarMenu : BaseComponent
{
#region Members
private BarState parentBarState;
#endregion
#region Methods
/// <inheritdoc/>
protected override void BuildClasses( ClassBuilder builder )
{
builder.Append( ClassProvider.BarMenu( ParentBarState?.Mode ?? BarMode.Horizontal ) );
builder.Append( ClassProvider.BarMenuShow( ParentBarState?.Mode ?? BarMode.Horizontal, ParentBarState?.Visible ?? false ) );
base.BuildClasses( builder );
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the reference to the parent <see cref="BarMenu"/> component.
/// </summary>
[Parameter] public RenderFragment ChildContent { get; set; }
/// <summary>
/// Cascaded <see cref="Bar"/> component state object.
/// </summary>
[CascadingParameter]
protected BarState ParentBarState
{
get => parentBarState;
set
{
if ( parentBarState == value )
return;
parentBarState = value;
DirtyClasses();
}
}
#endregion
} | 412 | 0.850688 | 1 | 0.850688 | game-dev | MEDIA | 0.573012 | game-dev | 0.794655 | 1 | 0.794655 |
classilla/tenfourfox | 1,861 | js/src/tests/test262/ch13/13.2/S13.2_A4_T2.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* When Function object(F) is constructed the following steps from 9 to 11 take place
* 9.Create a new object as would be constructed by the expression new Object().
* 10. Set the constructor property of Result(9) to F. This property is given attributes { DontEnum }.
* 11. Set the "prototype" property of F to Result(9).
*
* @path ch13/13.2/S13.2_A4_T2.js
* @description Checking prototype, prototype.constructor properties and {DontEnum} property of a constructor.
* Using "var __gunc = function(){}" as a FunctionDeclaration
*/
var __gunc = function(){};
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (typeof __gunc.prototype !== 'object') {
$ERROR('#1: typeof __gunc.prototype === \'object\'. Actual: typeof __gunc.prototype ==='+typeof __gunc.prototype);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__gunc.prototype.constructor !== __gunc) {
$ERROR('#2: __gunc.prototype.constructor === __gunc. Actual: __gunc.prototype.constructor ==='+__gunc.prototype.constructor);
}
//
//////////////////////////////////////////////////////////////////////////////
var __constructor_was__enumed;
for (__prop in __gunc.prototype){
if (__prop === 'constructor')
__constructor_was__enumed = true;
}
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
if (__constructor_was__enumed) {
$ERROR('#3: __constructor_was__enumed === false. Actual: __constructor_was__enumed ==='+__constructor_was__enumed);
}
//
//////////////////////////////////////////////////////////////////////////////
| 412 | 0.611946 | 1 | 0.611946 | game-dev | MEDIA | 0.673937 | game-dev | 0.714217 | 1 | 0.714217 |
CleanroomMC/Cleanroom | 3,953 | src/main/java/net/minecraftforge/fml/common/FMLContextQuery.java | package net.minecraftforge.fml.common;
import com.google.common.base.Strings;
import net.minecraft.launchwrapper.Launch;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.relauncher.MixinBooterPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.extensibility.MixinContextQuery;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Set;
public final class FMLContextQuery extends MixinContextQuery {
private static final FMLContextQuery INSTANCE = new FMLContextQuery();
public static void init() { }
private final ASMDataTable asmDataTable;
private FMLContextQuery() {
super();
ASMDataTable asmDataTable = null;
try {
Field modApiManager$dataTable = ModAPIManager.class.getDeclaredField("dataTable");
modApiManager$dataTable.setAccessible(true);
asmDataTable = (ASMDataTable) modApiManager$dataTable.get(ModAPIManager.INSTANCE);
} catch (ReflectiveOperationException e) {
FMLLog.log.fatal("Not able to reflect ModAPIManager#dataTable", e);
}
this.asmDataTable = asmDataTable;
}
private static String getResourceName(IMixinConfig config) {
String resource = Launch.classLoader.getResource(config.getName()).getPath();
if (resource.contains("!/")) {
String filePath = resource.split("!/")[0];
String[] parts = filePath.split("/");
if (parts.length != 0) {
return parts[parts.length - 1];
}
}
return null;
}
@Override
public String getOwner(IMixinConfig config) {
if (this.asmDataTable == null) {
return getSanitizedModIdFromResource(config);
} else {
return getCandidates(config).stream()
.map(ModCandidate::getContainedMods)
.flatMap(Collection::stream)
.map(ModContainer::getModId)
.filter(modId -> !Strings.isNullOrEmpty(modId))
.findFirst()
.orElseGet(() -> getSanitizedModIdFromResource(config));
}
}
@Override
public String getLocation(IMixinConfig config) {
if (this.asmDataTable == null) {
return getSanitizedModIdFromResource(config);
} else {
return getCandidates(config).stream()
.map(ModCandidate::getClassPathRoot)
.map(File::getName)
.findFirst()
.orElse(null);
}
}
private Set<ModCandidate> getCandidates(IMixinConfig config) {
String pkg = config.getMixinPackage();
pkg = pkg.charAt(pkg.length() - 1) == '.' ? pkg.substring(0, pkg.length() - 1) : pkg;
return this.asmDataTable.getCandidatesFor(pkg);
}
private String getSanitizedModIdFromResource(IMixinConfig config) {
String baseModId = getResourceName(config);
if (baseModId == null) {
return null;
}
if (baseModId.endsWith(".jar") || baseModId.endsWith(".zip")) {
baseModId = baseModId.substring(0, baseModId.length() - 4);
}
// Wipe Minecraft Versioning
baseModId = baseModId.replaceAll("1\\.12(\\.2)?", "");
StringBuilder sanitizedModId = new StringBuilder();
for (int i = 0; i < baseModId.length(); i++) {
char character = baseModId.charAt(i);
if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (i > 0 && character >= '0' && character <= '9')) {
sanitizedModId.append(character);
} else {
sanitizedModId.append('_');
}
}
return sanitizedModId.toString();
}
} | 412 | 0.974378 | 1 | 0.974378 | game-dev | MEDIA | 0.895442 | game-dev | 0.975372 | 1 | 0.975372 |
oxyplot/oxyplot-avalonia | 6,364 | Source/OxyPlot.Avalonia/Annotations/TextAnnotation.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="TextAnnotation.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// This is a Avalonia wrapper of OxyPlot.TextAnnotation
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using Avalonia;
namespace OxyPlot.Avalonia
{
using global::Avalonia.Layout;
using global::Avalonia.Media;
/// <summary>
/// This is a Avalonia wrapper of OxyPlot.TextAnnotation
/// </summary>
public class TextAnnotation : TextualAnnotation
{
/// <summary>
/// Identifies the <see cref="Background"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> BackgroundProperty = AvaloniaProperty.Register<TextAnnotation, Color>(nameof(Background), MoreColors.Undefined);
/// <summary>
/// Identifies the <see cref="Offset"/> dependency property.
/// </summary>
public static readonly StyledProperty<Vector> OffsetProperty = AvaloniaProperty.Register<TextAnnotation, Vector>(nameof(Offset), default);
/// <summary>
/// Identifies the <see cref="Padding"/> dependency property.
/// </summary>
public static readonly StyledProperty<Thickness> PaddingProperty = AvaloniaProperty.Register<TextAnnotation, Thickness>(nameof(Padding), new Thickness(4));
/// <summary>
/// Identifies the <see cref="Stroke"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> StrokeProperty = AvaloniaProperty.Register<TextAnnotation, Color>(nameof(Stroke), Colors.Black);
/// <summary>
/// Identifies the <see cref="StrokeThickness"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> StrokeThicknessProperty = AvaloniaProperty.Register<TextAnnotation, double>(nameof(StrokeThickness), 1.0);
/// <summary>
/// Initializes static members of the <see cref = "TextAnnotation" /> class.
/// </summary>
static TextAnnotation()
{
TextColorProperty.OverrideDefaultValue<TextAnnotation>(MoreColors.Automatic);
TextColorProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
TextHorizontalAlignmentProperty.OverrideDefaultValue<TextAnnotation>(HorizontalAlignment.Right);
TextHorizontalAlignmentProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
TextVerticalAlignmentProperty.OverrideDefaultValue<TextAnnotation>(VerticalAlignment.Top);
TextVerticalAlignmentProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
BackgroundProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
OffsetProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
PaddingProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
StrokeProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
StrokeThicknessProperty.Changed.AddClassHandler<TextAnnotation>(AppearanceChanged);
}
/// <summary>
/// Initializes a new instance of the <see cref = "TextAnnotation" /> class.
/// </summary>
public TextAnnotation()
{
InternalAnnotation = new Annotations.TextAnnotation();
}
/// <summary>
/// Gets or sets the fill color of the background rectangle.
/// </summary>
public Color Background
{
get
{
return GetValue(BackgroundProperty);
}
set
{
SetValue(BackgroundProperty, value);
}
}
/// <summary>
/// Gets or sets the position offset (screen coordinates).
/// </summary>
public Vector Offset
{
get
{
return GetValue(OffsetProperty);
}
set
{
SetValue(OffsetProperty, value);
}
}
/// <summary>
/// Gets or sets the padding of the background rectangle.
/// </summary>
public Thickness Padding
{
get
{
return GetValue(PaddingProperty);
}
set
{
SetValue(PaddingProperty, value);
}
}
/// <summary>
/// Gets or sets the stroke color of the background rectangle.
/// </summary>
public Color Stroke
{
get
{
return GetValue(StrokeProperty);
}
set
{
SetValue(StrokeProperty, value);
}
}
/// <summary>
/// Gets or sets the stroke thickness of the background rectangle.
/// </summary>
public double StrokeThickness
{
get
{
return GetValue(StrokeThicknessProperty);
}
set
{
SetValue(StrokeThicknessProperty, value);
}
}
/// <summary>
/// Creates the internal annotation object.
/// </summary>
/// <returns>The annotation.</returns>
public override Annotations.Annotation CreateModel()
{
SynchronizeProperties();
return InternalAnnotation;
}
/// <summary>
/// Synchronizes the properties.
/// </summary>
public override void SynchronizeProperties()
{
base.SynchronizeProperties();
var a = (Annotations.TextAnnotation)InternalAnnotation;
a.TextHorizontalAlignment = HorizontalAlignment.ToHorizontalAlignment();
a.Background = Background.ToOxyColor();
a.Offset = Offset.ToScreenVector();
a.TextVerticalAlignment = VerticalAlignment.ToVerticalAlignment();
a.Padding = Padding.ToOxyThickness();
a.Stroke = Stroke.ToOxyColor();
a.StrokeThickness = StrokeThickness;
}
}
} | 412 | 0.893973 | 1 | 0.893973 | game-dev | MEDIA | 0.477058 | game-dev,desktop-app | 0.904873 | 1 | 0.904873 |
MehVahdJukaar/Supplementaries | 6,647 | common/src/main/java/net/mehvahdjukaar/supplementaries/common/block/blocks/NetheriteTrapdoorBlock.java | package net.mehvahdjukaar.supplementaries.common.block.blocks;
import net.mehvahdjukaar.supplementaries.common.block.ILavaAndWaterLoggable;
import net.mehvahdjukaar.supplementaries.common.block.ModBlockProperties;
import net.mehvahdjukaar.supplementaries.common.block.tiles.KeyLockableTile;
import net.mehvahdjukaar.supplementaries.common.utils.MiscUtils;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.TrapDoorBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockSetType;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.Half;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Optional;
public class NetheriteTrapdoorBlock extends TrapDoorBlock implements ILavaAndWaterLoggable, EntityBlock {
public static final BooleanProperty LAVALOGGED = ModBlockProperties.LAVALOGGED;
public NetheriteTrapdoorBlock(Properties properties) {
super(properties.lightLevel(state -> state.getValue(LAVALOGGED) ? 15 : 0), BlockSetType.IRON);
this.registerDefaultState(this.defaultBlockState().setValue(FACING, Direction.NORTH)
.setValue(OPEN, false).setValue(HALF, Half.BOTTOM).setValue(POWERED, false)
.setValue(WATERLOGGED, false).setValue(LAVALOGGED, false));
}
@Override
public SoundType getSoundType(BlockState state) {
return SoundType.NETHERITE_BLOCK;
}
@Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) {
if (worldIn.getBlockEntity(pos) instanceof KeyLockableTile tile) {
if (tile.handleAction(player, handIn, "trapdoor")) {
state = state.cycle(OPEN);
worldIn.setBlock(pos, state, 2);
if (state.getValue(WATERLOGGED)) {
worldIn.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn));
}
//TODO: replace with proper sound event
boolean open = state.getValue(OPEN);
this.playSound(player, worldIn, pos, open);
worldIn.gameEvent(player, open ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos);
}
}
return InteractionResult.sidedSuccess(worldIn.isClientSide);
}
@Override
public void neighborChanged(BlockState state, Level worldIn, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) {
if (state.getValue(WATERLOGGED)) {
worldIn.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn));
} else if (state.getValue(LAVALOGGED)) {
worldIn.scheduleTick(pos, Fluids.LAVA, Fluids.LAVA.getTickDelay(worldIn));
}
}
@Override
public BlockState getStateForPlacement(BlockPlaceContext context) {
BlockState state = super.getStateForPlacement(context);
if (state == null) return null;
FluidState fluidstate = context.getLevel().getFluidState(context.getClickedPos());
state = state.setValue(LAVALOGGED, fluidstate.getType() == Fluids.LAVA);
return state.setValue(OPEN, false).setValue(POWERED, false);
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) {
return new KeyLockableTile(pPos, pState);
}
@Override
public BlockState updateShape(BlockState pState, Direction direction, BlockState pFacingState, LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pFacingPos) {
if (pState.getValue(LAVALOGGED)) {
pLevel.scheduleTick(pCurrentPos, Fluids.LAVA, Fluids.LAVA.getTickDelay(pLevel));
}
return super.updateShape(pState, direction, pFacingState, pLevel, pCurrentPos, pFacingPos);
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(LAVALOGGED);
}
@Override
public FluidState getFluidState(BlockState state) {
return state.getValue(LAVALOGGED) ? Fluids.LAVA.getSource(false) : super.getFluidState(state);
}
@Override
public boolean canPlaceLiquid(BlockGetter p_204510_1_, BlockPos p_204510_2_, BlockState p_204510_3_, Fluid p_204510_4_) {
return ILavaAndWaterLoggable.super.canPlaceLiquid(p_204510_1_, p_204510_2_, p_204510_3_, p_204510_4_);
}
@Override
public boolean placeLiquid(LevelAccessor p_204509_1_, BlockPos p_204509_2_, BlockState p_204509_3_, FluidState p_204509_4_) {
return ILavaAndWaterLoggable.super.placeLiquid(p_204509_1_, p_204509_2_, p_204509_3_, p_204509_4_);
}
@Override
public void appendHoverText(ItemStack stack, BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) {
super.appendHoverText(stack, worldIn, tooltip, flagIn);
if (!MiscUtils.showsHints(worldIn, flagIn)) return;
tooltip.add(Component.translatable("message.supplementaries.key.lockable").withStyle(ChatFormatting.ITALIC).withStyle(ChatFormatting.GRAY));
}
@Override
public ItemStack pickupBlock(LevelAccessor pLevel, BlockPos pPos, BlockState pState) {
return ILavaAndWaterLoggable.super.pickupBlock(pLevel, pPos, pState);
}
@Override
public Optional<SoundEvent> getPickupSound() {
return super.getPickupSound();
}
}
| 412 | 0.855758 | 1 | 0.855758 | game-dev | MEDIA | 0.999091 | game-dev | 0.960232 | 1 | 0.960232 |
OpenXcom/OpenXcom | 14,042 | src/Geoscape/MonthlyReportState.cpp | /*
* Copyright 2010-2016 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MonthlyReportState.h"
#include <sstream>
#include "../Engine/Game.h"
#include "../Mod/Mod.h"
#include "../Engine/LocalizedText.h"
#include "../Interface/TextButton.h"
#include "../Interface/Window.h"
#include "../Interface/Text.h"
#include "../Savegame/SavedGame.h"
#include "../Savegame/GameTime.h"
#include "PsiTrainingState.h"
#include "../Savegame/Region.h"
#include "../Savegame/Country.h"
#include "../Mod/RuleCountry.h"
#include "Globe.h"
#include "../Engine/Options.h"
#include "../Engine/Unicode.h"
#include "../Menu/CutsceneState.h"
#include "../Savegame/Base.h"
#include "../Battlescape/CommendationState.h"
#include "../Savegame/SoldierDiary.h"
#include "../Menu/SaveGameState.h"
#include "../Mod/RuleInterface.h"
namespace OpenXcom
{
/**
* Initializes all the elements in the Monthly Report screen.
* @param game Pointer to the core game.
* @param psi Show psi training afterwards?
* @param globe Pointer to the globe.
*/
MonthlyReportState::MonthlyReportState(bool psi, Globe *globe) : _psi(psi), _gameOver(false), _ratingTotal(0), _fundingDiff(0), _lastMonthsRating(0), _happyList(0), _sadList(0), _pactList(0)
{
_globe = globe;
// Create objects
_window = new Window(this, 320, 200, 0, 0);
_btnOk = new TextButton(50, 12, 135, 180);
_btnBigOk = new TextButton(120, 18, 100, 174);
_txtTitle = new Text(300, 17, 16, 8);
_txtMonth = new Text(130, 9, 16, 24);
_txtRating = new Text(160, 9, 146, 24);
_txtIncome = new Text(300, 9, 16, 32);
_txtMaintenance = new Text(130, 9, 16, 40);
_txtBalance = new Text(160, 9, 146, 40);
_txtDesc = new Text(280, 132, 16, 48);
_txtFailure = new Text(290, 160, 15, 10);
// Set palette
setInterface("monthlyReport");
add(_window, "window", "monthlyReport");
add(_btnOk, "button", "monthlyReport");
add(_btnBigOk, "button", "monthlyReport");
add(_txtTitle, "text1", "monthlyReport");
add(_txtMonth, "text1", "monthlyReport");
add(_txtRating, "text1", "monthlyReport");
add(_txtIncome, "text1", "monthlyReport");
add(_txtMaintenance, "text1", "monthlyReport");
add(_txtBalance, "text1", "monthlyReport");
add(_txtDesc, "text2", "monthlyReport");
add(_txtFailure, "text2", "monthlyReport");
centerAllSurfaces();
// Set up objects
_window->setBackground(_game->getMod()->getSurface("BACK13.SCR"));
_btnOk->setText(tr("STR_OK"));
_btnOk->onMouseClick((ActionHandler)&MonthlyReportState::btnOkClick);
_btnOk->onKeyboardPress((ActionHandler)&MonthlyReportState::btnOkClick, Options::keyOk);
_btnOk->onKeyboardPress((ActionHandler)&MonthlyReportState::btnOkClick, Options::keyCancel);
_btnBigOk->setText(tr("STR_OK"));
_btnBigOk->onMouseClick((ActionHandler)&MonthlyReportState::btnOkClick);
_btnBigOk->onKeyboardPress((ActionHandler)&MonthlyReportState::btnOkClick, Options::keyOk);
_btnBigOk->onKeyboardPress((ActionHandler)&MonthlyReportState::btnOkClick, Options::keyCancel);
_btnBigOk->setVisible(false);
_txtTitle->setBig();
_txtTitle->setText(tr("STR_XCOM_PROJECT_MONTHLY_REPORT"));
_txtFailure->setBig();
_txtFailure->setAlign(ALIGN_CENTER);
_txtFailure->setVerticalAlign(ALIGN_MIDDLE);
_txtFailure->setWordWrap(true);
_txtFailure->setText(tr("STR_YOU_HAVE_FAILED"));
_txtFailure->setVisible(false);
calculateChanges();
int month = _game->getSavedGame()->getTime()->getMonth() - 1, year = _game->getSavedGame()->getTime()->getYear();
if (month == 0)
{
month = 12;
year--;
}
std::string m;
switch (month)
{
case 1: m = "STR_JAN"; break;
case 2: m = "STR_FEB"; break;
case 3: m = "STR_MAR"; break;
case 4: m = "STR_APR"; break;
case 5: m = "STR_MAY"; break;
case 6: m = "STR_JUN"; break;
case 7: m = "STR_JUL"; break;
case 8: m = "STR_AUG"; break;
case 9: m = "STR_SEP"; break;
case 10: m = "STR_OCT"; break;
case 11: m = "STR_NOV"; break;
case 12: m = "STR_DEC"; break;
default: m = "";
}
_txtMonth->setText(tr("STR_MONTH").arg(tr(m)).arg(year));
// Calculate rating
int difficulty_threshold = _game->getMod()->getDefeatScore() + 100 * _game->getSavedGame()->getDifficultyCoefficient();
std::string rating = tr("STR_RATING_TERRIBLE");
if (_ratingTotal > difficulty_threshold - 300)
{
rating = tr("STR_RATING_POOR");
}
if (_ratingTotal > difficulty_threshold)
{
rating = tr("STR_RATING_OK");
}
if (_ratingTotal > 0)
{
rating = tr("STR_RATING_GOOD");
}
if (_ratingTotal > 500)
{
rating = tr("STR_RATING_EXCELLENT");
}
_txtRating->setText(tr("STR_MONTHLY_RATING").arg(_ratingTotal).arg(rating));
std::ostringstream ss;
ss << tr("STR_INCOME") << "> " << Unicode::TOK_COLOR_FLIP << Unicode::formatFunding(_game->getSavedGame()->getCountryFunding());
ss << " (";
if (_fundingDiff > 0)
ss << '+';
ss << Unicode::formatFunding(_fundingDiff) << ")";
_txtIncome->setText(ss.str());
std::ostringstream ss2;
ss2 << tr("STR_MAINTENANCE") << "> " << Unicode::TOK_COLOR_FLIP << Unicode::formatFunding(_game->getSavedGame()->getBaseMaintenance());
_txtMaintenance->setText(ss2.str());
std::ostringstream ss3;
ss3 << tr("STR_BALANCE") << "> " << Unicode::TOK_COLOR_FLIP << Unicode::formatFunding(_game->getSavedGame()->getFunds());
_txtBalance->setText(ss3.str());
_txtDesc->setWordWrap(true);
// calculate satisfaction
std::ostringstream ss5;
std::string satisFactionString = tr("STR_COUNCIL_IS_DISSATISFIED");
bool resetWarning = true;
if (_ratingTotal > difficulty_threshold)
{
satisFactionString = tr("STR_COUNCIL_IS_GENERALLY_SATISFIED");
}
if (_ratingTotal > 500)
{
satisFactionString = tr("STR_COUNCIL_IS_VERY_PLEASED");
}
if (_lastMonthsRating <= difficulty_threshold && _ratingTotal <= difficulty_threshold)
{
satisFactionString = tr("STR_YOU_HAVE_NOT_SUCCEEDED");
_pactList.erase(_pactList.begin(), _pactList.end());
_happyList.erase(_happyList.begin(), _happyList.end());
_sadList.erase(_sadList.begin(), _sadList.end());
_gameOver = true;
}
ss5 << satisFactionString;
if (!_gameOver)
{
if (_game->getSavedGame()->getFunds() <= _game->getMod()->getDefeatFunds())
{
if (_game->getSavedGame()->getWarned())
{
ss5.str("");
ss5 << tr("STR_YOU_HAVE_NOT_SUCCEEDED");
_pactList.erase(_pactList.begin(), _pactList.end());
_happyList.erase(_happyList.begin(), _happyList.end());
_sadList.erase(_sadList.begin(), _sadList.end());
_gameOver = true;
}
else
{
ss5 << "\n\n" << tr("STR_COUNCIL_REDUCE_DEBTS");
_game->getSavedGame()->setWarned(true);
resetWarning = false;
}
}
}
if (resetWarning && _game->getSavedGame()->getWarned())
{
_game->getSavedGame()->setWarned(false);
}
ss5 << countryList(_happyList, "STR_COUNTRY_IS_PARTICULARLY_PLEASED", "STR_COUNTRIES_ARE_PARTICULARLY_HAPPY");
ss5 << countryList(_sadList, "STR_COUNTRY_IS_UNHAPPY_WITH_YOUR_ABILITY", "STR_COUNTRIES_ARE_UNHAPPY_WITH_YOUR_ABILITY");
ss5 << countryList(_pactList, "STR_COUNTRY_HAS_SIGNED_A_SECRET_PACT", "STR_COUNTRIES_HAVE_SIGNED_A_SECRET_PACT");
_txtDesc->setText(ss5.str());
}
/**
*
*/
MonthlyReportState::~MonthlyReportState()
{
}
/**
* Make sure the game is over.
*/
void MonthlyReportState::init()
{
State::init();
if (_gameOver)
{
_game->getSavedGame()->setEnding(END_LOSE);
}
}
/**
* Returns to the previous screen.
* @param action Pointer to an action.
*/
void MonthlyReportState::btnOkClick(Action *)
{
if (!_gameOver)
{
_game->popState();
// Award medals for service time
// Iterate through all your bases
for (std::vector<Base*>::iterator b = _game->getSavedGame()->getBases()->begin(); b != _game->getSavedGame()->getBases()->end(); ++b)
{
// Iterate through all your soldiers
for (std::vector<Soldier*>::iterator s = (*b)->getSoldiers()->begin(); s != (*b)->getSoldiers()->end(); ++s)
{
Soldier *soldier = _game->getSavedGame()->getSoldier((*s)->getId());
// Award medals to eligible soldiers
soldier->getDiary()->addMonthlyService();
if (soldier->getDiary()->manageCommendations(_game->getMod(), _game->getSavedGame()->getMissionStatistics()))
{
_soldiersMedalled.push_back(soldier);
}
}
}
if (!_soldiersMedalled.empty())
{
_game->pushState(new CommendationState(_soldiersMedalled));
}
if (_psi)
{
_game->pushState(new PsiTrainingState);
}
// Autosave
if (_game->getSavedGame()->isIronman())
{
_game->pushState(new SaveGameState(OPT_GEOSCAPE, SAVE_IRONMAN, _palette));
}
else if (Options::autosave)
{
_game->pushState(new SaveGameState(OPT_GEOSCAPE, SAVE_AUTO_GEOSCAPE, _palette));
}
}
else
{
if (_txtFailure->getVisible())
{
_game->pushState(new CutsceneState(CutsceneState::LOSE_GAME));
if (_game->getSavedGame()->isIronman())
{
_game->pushState(new SaveGameState(OPT_GEOSCAPE, SAVE_IRONMAN, _palette));
}
}
else
{
_window->setColor(_game->getMod()->getInterface("monthlyReport")->getElement("window")->color2);
_txtTitle->setVisible(false);
_txtMonth->setVisible(false);
_txtRating->setVisible(false);
_txtIncome->setVisible(false);
_txtMaintenance->setVisible(false);
_txtBalance->setVisible(false);
_txtDesc->setVisible(false);
_btnOk->setVisible(false);
_btnBigOk->setVisible(true);
_txtFailure->setVisible(true);
_game->getMod()->playMusic("GMLOSE");
}
}
}
/**
* Update all our activity counters, gather all our scores,
* get our countries to make sign pacts, adjust their fundings,
* assess their satisfaction, and finally calculate our overall
* total score, with thanks to Volutar for the formulas.
*/
void MonthlyReportState::calculateChanges()
{
// initialize all our variables.
_lastMonthsRating = 0;
int xcomSubTotal = 0;
int xcomTotal = 0;
int alienTotal = 0;
int monthOffset = _game->getSavedGame()->getFundsList().size() - 2;
int lastMonthOffset = _game->getSavedGame()->getFundsList().size() - 3;
if (lastMonthOffset < 0)
lastMonthOffset += 2;
// update activity meters, calculate a total score based on regional activity
// and gather last month's score
for (std::vector<Region*>::iterator k = _game->getSavedGame()->getRegions()->begin(); k != _game->getSavedGame()->getRegions()->end(); ++k)
{
(*k)->newMonth();
if ((*k)->getActivityXcom().size() > 2)
_lastMonthsRating += (*k)->getActivityXcom().at(lastMonthOffset)-(*k)->getActivityAlien().at(lastMonthOffset);
xcomSubTotal += (*k)->getActivityXcom().at(monthOffset);
alienTotal += (*k)->getActivityAlien().at(monthOffset);
}
// apply research bonus AFTER calculating our total, because this bonus applies to the council ONLY,
// and shouldn't influence each country's decision.
// the council is more lenient after the first month
if (_game->getSavedGame()->getMonthsPassed() > 1)
_game->getSavedGame()->getResearchScores().at(monthOffset) += 400;
xcomTotal = _game->getSavedGame()->getResearchScores().at(monthOffset) + xcomSubTotal;
if (_game->getSavedGame()->getResearchScores().size() > 2)
_lastMonthsRating += _game->getSavedGame()->getResearchScores().at(lastMonthOffset);
// now that we have our totals we can send the relevant info to the countries
// and have them make their decisions weighted on the council's perspective.
const RuleAlienMission *infiltration = _game->getMod()->getRandomMission(OBJECTIVE_INFILTRATION, _game->getSavedGame()->getMonthsPassed());
int pactScore = 0;
if (infiltration)
{
pactScore = infiltration->getPoints();
}
for (std::vector<Country*>::iterator k = _game->getSavedGame()->getCountries()->begin(); k != _game->getSavedGame()->getCountries()->end(); ++k)
{
// add them to the list of new pact members
// this is done BEFORE initiating a new month
// because the _newPact flag will be reset in the
// process
if ((*k)->getNewPact())
{
_pactList.push_back((*k)->getRules()->getType());
}
// determine satisfaction level, sign pacts, adjust funding
// and update activity meters,
(*k)->newMonth(xcomTotal, alienTotal, pactScore);
// and after they've made their decisions, calculate the difference, and add
// them to the appropriate lists.
_fundingDiff += (*k)->getFunding().back()-(*k)->getFunding().at((*k)->getFunding().size()-2);
switch((*k)->getSatisfaction())
{
case 1:
_sadList.push_back((*k)->getRules()->getType());
break;
case 3:
_happyList.push_back((*k)->getRules()->getType());
break;
default:
break;
}
}
//calculate total.
_ratingTotal = xcomTotal - alienTotal;
}
/**
* Builds a sentence from a list of countries, adding the appropriate
* separators and pluralization.
* @param countries List of country string IDs.
* @param singular String ID to append at the end if the list is singular.
* @param plural String ID to append at the end if the list is plural.
*/
std::string MonthlyReportState::countryList(const std::vector<std::string> &countries, const std::string &singular, const std::string &plural)
{
std::ostringstream ss;
if (!countries.empty())
{
ss << "\n\n";
if (countries.size() == 1)
{
ss << tr(singular).arg(tr(countries.front()));
}
else
{
LocalizedText list = tr(countries.front());
std::vector<std::string>::const_iterator i;
for (i = countries.begin() + 1; i < countries.end() - 1; ++i)
{
list = tr("STR_COUNTRIES_COMMA").arg(list).arg(tr(*i));
}
list = tr("STR_COUNTRIES_AND").arg(list).arg(tr(*i));
ss << tr(plural).arg(list);
}
}
return ss.str();
}
}
| 412 | 0.948129 | 1 | 0.948129 | game-dev | MEDIA | 0.824765 | game-dev | 0.991929 | 1 | 0.991929 |
CalamityTeam/CalamityModPublic | 3,389 | Projectiles/Ranged/OpalChargedStrike.cs | using CalamityMod.Particles;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Ranged
{
public class OpalChargedStrike : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Ranged";
public override void SetStaticDefaults()
{
ProjectileID.Sets.TrailCacheLength[Projectile.type] = 8;
ProjectileID.Sets.TrailingMode[Projectile.type] = 0;
}
public override void SetDefaults()
{
Projectile.width = Projectile.height = 30;
Projectile.friendly = true;
Projectile.alpha = 55;
Projectile.penetrate = 3;
Projectile.timeLeft = 300;
Projectile.DamageType = DamageClass.Ranged;
Projectile.Calamity().pointBlankShotDuration = CalamityGlobalProjectile.DefaultPointBlankDuration;
Projectile.extraUpdates = 3;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 50;
Projectile.tileCollide = false; // Custom tile collision since the hitbox is large
}
public override void AI()
{
if (Collision.SolidCollision(Projectile.Center, 5, 5))
Projectile.Kill();
if (Main.rand.NextBool(3))
{
Dust dust = Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(7, 7), 162);
dust.scale = 1.3f;
dust.velocity = -Projectile.velocity * 0.4f;
}
Player Owner = Main.player[Projectile.owner];
float playerDist = Vector2.Distance(Owner.Center, Projectile.Center);
if (Projectile.timeLeft % 2 == 0 && playerDist < 1400f && Projectile.timeLeft < 290)
{
SparkParticle spark = new SparkParticle(Projectile.Center - Projectile.velocity * 3f, -Projectile.velocity * 0.05f, false, 9, 2f, Color.OrangeRed * 0.25f);
GeneralParticleHandler.SpawnParticle(spark);
}
Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2;
}
public override bool PreDraw(ref Color lightColor)
{
CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1);
return false;
}
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(BuffID.OnFire, 300);
}
public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers)
{
if (Projectile.numHits > 0)
Projectile.damage = (int)(Projectile.damage * 0.80f);
if (Projectile.damage < 1)
Projectile.damage = 1;
}
public override void OnKill(int timeLeft)
{
for (int i = 0; i <= 8; i++)
{
Dust dust = Dust.NewDustPerfect(Projectile.position, 162, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(30f)) / 2, 0, default, Main.rand.NextFloat(1.6f, 2.3f));
dust.noGravity = false;
}
}
public override bool? CanDamage() => base.CanDamage();
}
}
| 412 | 0.920268 | 1 | 0.920268 | game-dev | MEDIA | 0.995227 | game-dev | 0.982474 | 1 | 0.982474 |
Dreaming381/Latios-Framework-Add-Ons | 25,931 | AddOns/MecanimV1/Systems/MecanimStateMachineUpdateSystem.cs | using Unity.Burst;
using Unity.Burst.Intrinsics;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using AnimatorControllerParameterType = UnityEngine.AnimatorControllerParameterType;
using static Unity.Entities.SystemAPI;
namespace Latios.Mecanim.Systems
{
[RequireMatchingQueriesForUpdate]
[DisableAutoCreation]
[BurstCompile]
public partial struct MecanimStateMachineUpdateSystem : ISystem
{
EntityQuery m_query;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
m_query = state.Fluent()
.With<MecanimController>(false)
.With<MecanimLayerStateMachineStatus>(false)
.With<MecanimParameter>(false)
.With<TimedMecanimClipInfo>(false).Build();
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
state.Dependency = new Job
{
deltaTime = Time.DeltaTime,
controllerHandle = GetComponentTypeHandle<MecanimController>(false),
parameterHandle = GetBufferTypeHandle<MecanimParameter>(false),
layerHandle = GetBufferTypeHandle<MecanimLayerStateMachineStatus>(false),
previousFrameClipInfoHandle = GetBufferTypeHandle<TimedMecanimClipInfo>(false)
}.ScheduleParallel(m_query, state.Dependency);
}
[BurstCompile]
public partial struct Job : IJobChunk
{
public float deltaTime;
[ReadOnly]
public ComponentTypeHandle<MecanimController> controllerHandle;
public BufferTypeHandle<MecanimLayerStateMachineStatus> layerHandle;
public BufferTypeHandle<MecanimParameter> parameterHandle;
public BufferTypeHandle<TimedMecanimClipInfo> previousFrameClipInfoHandle;
[BurstCompile]
public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
var controllers = chunk.GetNativeArray(ref controllerHandle);
var layersBuffers = chunk.GetBufferAccessor(ref layerHandle);
var parametersBuffers = chunk.GetBufferAccessor(ref parameterHandle);
var previousFrameClipInfoBuffers = chunk.GetBufferAccessor(ref previousFrameClipInfoHandle);
var enumerator = new ChunkEntityEnumerator(useEnabledMask, chunkEnabledMask, chunk.Count);
while (enumerator.NextEntityIndex(out var indexInChunk))
{
var controller = controllers[indexInChunk];
ref var controllerBlob = ref controller.controller.Value;
var parameters = parametersBuffers[indexInChunk].AsNativeArray();
ref var parameterBlobs = ref controllerBlob.parameters;
var layers = layersBuffers[indexInChunk].AsNativeArray();
var previousFrameClipInfo = previousFrameClipInfoBuffers[indexInChunk].AsNativeArray();
var deltaTime = this.deltaTime * controller.speed;
float inertialBlendMaxTime = float.MaxValue;
bool needsInertialBlend = false;
for (int layerIndex = 0; layerIndex < layers.Length; layerIndex++)
{
var layer = layers[layerIndex];
ref var layerBlob = ref controllerBlob.layers[layerIndex];
layer.timeInState += deltaTime;
// Finish active transition and update previous clip info time fragments
if (layer.previousStateIndex >= 0 && layer.transitionEndTimeInState <= layer.timeInState)
{
for (int i = 0; i < previousFrameClipInfo.Length; i++)
{
var clipInfo = previousFrameClipInfo[i];
if (clipInfo.layerIndex == layerIndex && clipInfo.stateIndex == layer.previousStateIndex)
{
clipInfo.timeFragment = layer.timeInState - layer.transitionEndTimeInState;
previousFrameClipInfo[i] = clipInfo;
}
}
layer.previousStateIndex = -1;
layer.currentTransitionIndex = -1;
layer.currentTransitionIsAnyState = false;
}
else
{
for (int i = 0; i < previousFrameClipInfo.Length; i++)
{
var clipInfo = previousFrameClipInfo[i];
if (clipInfo.layerIndex == layerIndex)
{
clipInfo.timeFragment = deltaTime;
previousFrameClipInfo[i] = clipInfo;
}
}
}
// Only evaluate non-interrupting transitions if we are not already transitioning
if (!layer.isInTransition)
{
bool didLocalTransition = false;
// Check current state transitions
ref var currentState = ref layerBlob.states[layer.currentStateIndex];
for (short i = 0; i < currentState.transitions.Length; i++)
{
ref var transition = ref currentState.transitions[i];
// Early out if we have an exit time and we haven't reached it yet
ref var state = ref layerBlob.states[layer.currentStateIndex];
float normalizedTimeInState = (layer.timeInState % state.averageDuration) / state.averageDuration;
if (transition.hasExitTime && transition.exitTime > normalizedTimeInState)
continue;
// Evaluate conditions
if (ConditionsMet(layer, ref layerBlob, ref transition, parameters, ref parameterBlobs, deltaTime))
{
PerformTransition(ref layer, ref layerBlob, ref transition, i, false);
ConsumeTriggers(ref transition, ref parameters, ref parameterBlobs);
didLocalTransition = true;
break;
}
}
// Check any state transitions
if (!didLocalTransition)
{
for (short i = 0; i < layerBlob.anyStateTransitions.Length; i++)
{
ref var transition = ref layerBlob.anyStateTransitions[i];
// If we have no conditions, we can only transition if we are done
if (transition.conditions.Length == 0)
{
if (layer.currentStateIndex == -1)
{
PerformTransition(ref layer, ref layerBlob, ref transition, i, true);
ConsumeTriggers(ref transition, ref parameters, ref parameterBlobs);
break;
}
}
else if (ConditionsMet(layer, ref layerBlob, ref transition, parameters, ref parameterBlobs, deltaTime))
{
PerformTransition(ref layer, ref layerBlob, ref transition, i, true);
ConsumeTriggers(ref transition, ref parameters, ref parameterBlobs);
break;
}
}
}
}
else
{
// Check if we can interrupt the current transition
if (layer.currentTransitionIsAnyState)
{
ref var currentTransition = ref layerBlob.anyStateTransitions[layer.currentTransitionIndex];
needsInertialBlend |= TryInterruptTransition(ref layer,
ref layerBlob,
ref currentTransition,
ref parameters,
ref parameterBlobs,
ref inertialBlendMaxTime);
}
else if (layer.currentTransitionIndex >= 0)
{
ref var currentTransition = ref layerBlob.states[layer.previousStateIndex].transitions[layer.currentTransitionIndex];
needsInertialBlend |= TryInterruptTransition(ref layer,
ref layerBlob,
ref currentTransition,
ref parameters,
ref parameterBlobs,
ref inertialBlendMaxTime);
}
}
layers[layerIndex] = layer;
}
if (needsInertialBlend)
{
if (controller.triggerStartInertialBlend)
{
// User triggered inertial blend
controller.newInertialBlendDuration = math.min(controller.newInertialBlendDuration, inertialBlendMaxTime);
}
else
{
controller.newInertialBlendDuration = inertialBlendMaxTime;
}
controller.triggerStartInertialBlend = true;
}
}
}
// See the following resources:
// https://www.gamedeveloper.com/design/unlocking-unity-animator-s-interruption-full-power
// https://docs.unity3d.com/Manual/class-Transition.html#TransitionInterruption
// https://blog.unity.com/technology/wait-ive-changed-my-mind-state-machine-transition-interruptions
//
// As discussed in the Unity blog, when an interruption happens, it captures the static pose
// of the current transition blend and then blends between that and the new state.
// Capturing a pose is really tricky for us since we update the pose information separately.
// However, no one in their right mind is going to author animations specific to how Unity
// does interruptions on blended transitions using the static poses. So instead of trying
// to match how Unity handles this, let's use the superior technique of inertial blending,
// which is built into optimized skeletons and we can easily add support for exposed skeletons.
private bool TryInterruptTransition(ref MecanimLayerStateMachineStatus layer,
ref MecanimControllerLayerBlob layerBlob,
ref MecanimStateTransitionBlob currentTransition,
ref NativeArray<MecanimParameter> parameters,
ref BlobArray<MecanimParameterBlob> parameterBlobs,
ref float maxTransitionDuration)
{
switch (currentTransition.interruptionSource)
{
case MecanimStateTransitionBlob.InterruptionSource.Source:
{
ref var anyTransitions = ref layerBlob.anyStateTransitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref anyTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration, -1))
return true;
ref var sourceStateTransitions = ref layerBlob.states[currentTransition.originStateIndex].transitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref sourceStateTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration,
layer.currentTransitionIndex))
return true;
break;
}
case MecanimStateTransitionBlob.InterruptionSource.Destination:
{
ref var anyTransitions = ref layerBlob.anyStateTransitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref anyTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration, -1))
return true;
ref var destinationStateTransitions = ref layerBlob.states[currentTransition.destinationStateIndex].transitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref destinationStateTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration, -1))
return true;
break;
}
case MecanimStateTransitionBlob.InterruptionSource.SourceThenDestination:
{
ref var anyTransitions = ref layerBlob.anyStateTransitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref anyTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration, -1))
return true;
ref var sourceStateTransitions = ref layerBlob.states[currentTransition.originStateIndex].transitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref sourceStateTransitions, ref parameters, ref parameterBlobs,
ref maxTransitionDuration, layer.currentTransitionIndex))
return true;
ref var destinationStateTransitions = ref layerBlob.states[currentTransition.destinationStateIndex].transitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref destinationStateTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration, -1))
return true;
break;
}
case MecanimStateTransitionBlob.InterruptionSource.DestinationThenSource:
{
ref var anyTransitions = ref layerBlob.anyStateTransitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref anyTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration, -1))
return true;
ref var destinationStateTransitions = ref layerBlob.states[currentTransition.destinationStateIndex].transitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref destinationStateTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration, -1))
return true;
ref var sourceStateTransitions = ref layerBlob.states[currentTransition.originStateIndex].transitions;
if (TryInterruptFromState(ref layer, ref layerBlob, ref sourceStateTransitions, ref parameters, ref parameterBlobs, ref maxTransitionDuration,
layer.currentTransitionIndex))
return true;
break;
}
}
return false;
}
private bool TryInterruptFromState(ref MecanimLayerStateMachineStatus layer,
ref MecanimControllerLayerBlob layerBlob,
ref BlobArray<MecanimStateTransitionBlob> interruptingTransitions,
ref NativeArray<MecanimParameter> parameters,
ref BlobArray<MecanimParameterBlob> parameterBlobs,
ref float transitionMaxDuration,
short orderedTransitionStopIndex)
{
var transitionCount = math.select(interruptingTransitions.Length, orderedTransitionStopIndex, orderedTransitionStopIndex >= 0);
for (short i = 0; i < transitionCount; i++)
{
ref var interruptingTransition = ref interruptingTransitions[i];
if (ConditionsMet(layer, ref layerBlob, ref interruptingTransition, parameters, ref parameterBlobs, deltaTime))
{
PerformTransition(ref layer, ref layerBlob, ref interruptingTransition, i, false, true);
ConsumeTriggers(ref interruptingTransition, ref parameters, ref parameterBlobs);
transitionMaxDuration = math.min(transitionMaxDuration, interruptingTransition.duration);
return true;
}
}
return false;
}
private void PerformTransition(ref MecanimLayerStateMachineStatus layer,
ref MecanimControllerLayerBlob layerBlob,
ref MecanimStateTransitionBlob transitionBlob,
short stateTransitionIndex,
bool isAnyStateTransition,
bool needsInertialBlend = false)
{
layer.previousStateIndex = layer.currentStateIndex;
layer.previousStateExitTime = layer.timeInState;
layer.currentTransitionIndex = stateTransitionIndex;
layer.currentTransitionIsAnyState = isAnyStateTransition;
layer.currentStateIndex = transitionBlob.destinationStateIndex != -1 ? transitionBlob.destinationStateIndex : layerBlob.defaultStateIndex; // "Exit" state
ref var destinationState = ref layerBlob.states[layer.currentStateIndex];
ref var lastState = ref layerBlob.states[layer.previousStateIndex];
layer.timeInState = transitionBlob.offset * destinationState.averageDuration;
layer.transitionEndTimeInState = transitionBlob.hasFixedDuration ?
transitionBlob.duration :
lastState.averageDuration * transitionBlob.duration;
layer.transitionIsInertialBlend = needsInertialBlend;
}
private bool ConditionsMet(in MecanimLayerStateMachineStatus layer,
ref MecanimControllerLayerBlob layerBlob,
ref MecanimStateTransitionBlob transitionBlob,
in NativeArray<MecanimParameter> parameters,
ref BlobArray<MecanimParameterBlob> parameterBlobs,
float deltaTime)
{
bool conditionsMet = true;
for (int j = 0; j < transitionBlob.conditions.Length && conditionsMet; j++)
{
ref var condition = ref transitionBlob.conditions[j];
var parameter = parameters[condition.parameterIndex];
ref var parameterData = ref parameterBlobs[condition.parameterIndex];
if (parameterData.parameterType == AnimatorControllerParameterType.Trigger)
{
conditionsMet = parameter.triggerParam;
continue;
}
switch (condition.mode)
{
case MecanimConditionBlob.ConditionType.Equals:
if (parameterData.parameterType == AnimatorControllerParameterType.Int)
{
// Todo: We should probably bake threshold as a union of int and float
// so that we don't have to do this cast
conditionsMet = parameter.intParam == (int)condition.threshold;
}
else
{
conditionsMet = MecanimInternalUtilities.Approximately(parameter.floatParam, condition.threshold);
}
break;
case MecanimConditionBlob.ConditionType.NotEqual:
if (parameterData.parameterType == AnimatorControllerParameterType.Int)
{
conditionsMet = parameter.intParam != (int)condition.threshold;
}
else
{
conditionsMet = !MecanimInternalUtilities.Approximately(parameter.floatParam, condition.threshold);
}
break;
case MecanimConditionBlob.ConditionType.Greater:
if (parameterData.parameterType == AnimatorControllerParameterType.Int)
{
conditionsMet = parameter.intParam > (int)condition.threshold;
}
else
{
conditionsMet = parameter.floatParam > condition.threshold;
}
break;
case MecanimConditionBlob.ConditionType.Less:
if (parameterData.parameterType == AnimatorControllerParameterType.Int)
{
conditionsMet = parameter.intParam < (int)condition.threshold;
}
else
{
conditionsMet = parameter.floatParam < condition.threshold;
}
break;
case MecanimConditionBlob.ConditionType.If:
conditionsMet = parameter.boolParam;
break;
case MecanimConditionBlob.ConditionType.IfNot:
conditionsMet = !parameter.boolParam;
break;
}
}
if (transitionBlob.hasExitTime)
{
ref var state = ref layerBlob.states[layer.currentStateIndex];
float normalizedTimeInState = (layer.timeInState % state.averageDuration) / state.averageDuration;
var normalizedDeltaTime = deltaTime / state.averageDuration;
conditionsMet &= transitionBlob.exitTime > normalizedTimeInState - normalizedDeltaTime && transitionBlob.exitTime <= normalizedTimeInState;
}
return conditionsMet;
}
private void ConsumeTriggers(ref MecanimStateTransitionBlob transitionBlob,
ref NativeArray<MecanimParameter> parameters,
ref BlobArray<MecanimParameterBlob> paramterBlobs)
{
for (int i = 0; i < transitionBlob.conditions.Length; i++)
{
ref var condition = ref transitionBlob.conditions[i];
var parameterIndex = condition.parameterIndex;
if (paramterBlobs[parameterIndex].parameterType == AnimatorControllerParameterType.Trigger)
parameters[parameterIndex] = new MecanimParameter { triggerParam = false };
}
}
}
}
} | 412 | 0.908576 | 1 | 0.908576 | game-dev | MEDIA | 0.60829 | game-dev,graphics-rendering | 0.95117 | 1 | 0.95117 |
Rz-C/Mohist | 1,378 | src/main/java/net/minecraftforge/event/entity/player/PlayerSetSpawnEvent.java | /*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.entity.player;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraftforge.eventbus.api.Cancelable;
import org.jetbrains.annotations.Nullable;
/**
* This event is fired when a player's spawn point is set or reset.<br>
* The event can be canceled, which will prevent the spawn point from being changed.
*/
@Cancelable
public class PlayerSetSpawnEvent extends PlayerEvent
{
private final ResourceKey<Level> spawnLevel;
private final boolean forced;
@Nullable
private final BlockPos newSpawn;
public PlayerSetSpawnEvent(Player player, ResourceKey<Level> spawnLevel, @Nullable BlockPos newSpawn, boolean forced)
{
super(player);
this.spawnLevel = spawnLevel;
this.newSpawn = newSpawn;
this.forced = forced;
}
public boolean isForced()
{
return forced;
}
/**
* The new spawn position, or null if the spawn position is being reset.
*/
@Nullable
public BlockPos getNewSpawn()
{
return newSpawn;
}
public ResourceKey<Level> getSpawnLevel()
{
return spawnLevel;
}
}
| 412 | 0.777353 | 1 | 0.777353 | game-dev | MEDIA | 0.993676 | game-dev | 0.646244 | 1 | 0.646244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.