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
Dimbreath/AzurLaneData
2,710
zh-CN/controller/command/state/loadcontextcommand.lua
slot0 = class("LoadContextCommand", pm.SimpleCommand) slot0.queue = {} function slot0.execute(slot0, slot1) slot0:load(slot1:getBody()) end function slot0.load(slot0, slot1) table.insert(uv0.queue, slot1) if #uv0.queue == 1 then slot0:loadNext() end end function slot0.loadNext(slot0) if #uv0.queue > 0 then if uv0.queue[1].type == LOAD_TYPE_SCENE then slot0:loadScene(slot1.context, slot1.prevContext, function () if uv0.callback then uv0.callback() end table.remove(uv1.queue, 1) uv2:loadNext() end) elseif slot1.type == LOAD_TYPE_LAYER then slot0:loadLayer(slot1.context, slot1.parentContext, slot2) end end end function slot0.loadScene(slot0, slot1, slot2, slot3) slot5 = pg.SceneMgr.GetInstance() slot6, slot7 = nil slot8 = {} slot2 = slot2 or getProxy(ContextProxy):getCurrentContext() seriesAsync({ function (slot0) pg.UIMgr.GetInstance():LoadingOn() if uv0 ~= nil then uv1:extendData({ fromMediatorName = uv0.mediator.__cname }) uv2:removeLayerMediator(uv3.facade, uv0, function (slot0) uv0 = slot0 uv1() end) else slot0() end end, function (slot0) uv0:prepare(uv1.facade, uv2, function (slot0) uv0 = slot0 uv1() end) end, function (slot0) uv0:prepareLayer(uv1.facade, nil, uv2, function (slot0) uv0 = slot0 uv1() end) end, function (slot0) if uv0.cleanStack then uv1:cleanContext() end uv1:pushContext(uv0) slot0() end, function (slot0) if uv0 then table.eachAsync(uv0, function (slot0, slot1, slot2) uv0:remove(slot1.mediator:getViewComponent(), function () uv0.context:onContextRemoved() uv1() end) end, slot0) else slot0() end end, function (slot0) uv0:enter({ uv1 }, slot0) end, function (slot0) uv0:enter(uv1, slot0) end, function () if uv0 then uv0() end pg.UIMgr.GetInstance():LoadingOff() uv1:sendNotification(GAME.LOAD_SCENE_DONE, uv2.scene) end }) end function slot0.loadLayer(slot0, slot1, slot2, slot3) slot4 = pg.SceneMgr.GetInstance() slot5 = {} seriesAsync({ function (slot0) pg.UIMgr.GetInstance():LoadingOn() uv0:prepareLayer(uv1.facade, uv2, uv3, function (slot0) for slot4, slot5 in ipairs(slot0) do table.insert(uv0, slot5) end uv1() end) end, function (slot0) uv0:enter(uv1, slot0) end, function () if uv0 then uv0() end pg.UIMgr.GetInstance():LoadingOff() end }) end function slot0.LoadLayerOnTopContext(slot0) pg.m02:sendNotification(GAME.LOAD_LAYERS, { parentContext = getProxy(ContextProxy):getCurrentContext(), context = slot0 }) end return slot0
1
0.525873
1
0.525873
game-dev
MEDIA
0.426548
game-dev
0.834988
1
0.834988
malaybaku/VMagicMirror
9,784
VMagicMirror/Assets/Baku/VMagicMirror/Scripts/Buddy/ApiImplements/AvatarMotionEventApiImplement.cs
using System; using System.Threading; using Cysharp.Threading.Tasks; using R3; namespace Baku.VMagicMirror.Buddy { public class AvatarMotionEventApiImplement : PresenterBase { private readonly ReactiveProperty<string> _leftHandTargetType = new(); public ReadOnlyReactiveProperty<string> LeftHandTargetType => _leftHandTargetType; private readonly ReactiveProperty<string> _rightHandTargetType = new(); public ReadOnlyReactiveProperty<string> RightHandTargetType => _rightHandTargetType; private readonly Subject<string> _keyboardKeyDown = new(); /// <summary> /// アバターがキーボードのタイピング動作を開始すると発火する。 /// - ユーザーがキーボードを押した場合でも、アバターが実際に動いてなければ発火しない。 /// - キー名はごく一部(ENTERとか)だけが取得でき、大体のキーは空文字列になる (主にプライバシー観点がモチベ) /// TODO: 左手と右手どっちが動いたかくらいは教えたいかも? /// </summary> public Observable<string> KeyboardKeyDown => _keyboardKeyDown; private readonly Subject<Unit> _touchPadMouseButtonDown = new(); /// <summary> /// タッチパッドが表示された状態でアバターがクリック動作をしたとき、押し込みに対して発火する。どのボタンをクリックしたかは公開されない /// </summary> public Observable<Unit> TouchPadMouseButtonDown => _touchPadMouseButtonDown; private readonly Subject<Unit> _penTabletMouseButtonDown = new(); /// <summary> /// ペンタブレットが表示された状態でアバターがクリック動作をしたとき、押し込みに対して発火する。どのボタンをクリックしたかは公開されない /// </summary> public Observable<Unit> PenTabletMouseButtonDown => _penTabletMouseButtonDown; private readonly Subject<(ReactedHand, GamepadKey)> _gamepadButtonDown = new(); /// <summary> /// ゲームパッドが表示された状態で何らかのゲームパッドのボタンを押すと、押し込みに対して発火する。 /// スティック入力に対しては発火しない /// </summary> public Observable<(ReactedHand, GamepadKey)> GamepadButtonDown => _gamepadButtonDown; private readonly Subject<GamepadKey> _arcadeStickButtonDown = new(); /// <summary> /// アーケードスティックが表示された状態でゲームパッドのボタンを押すと、押し込みに対して発火する。 /// スティックには反応せず、かつアーケードスティック上で対応していないボタンを押した場合も反応しない /// </summary> public Observable<GamepadKey> ArcadeStickButtonDown => _arcadeStickButtonDown; private readonly BuddySettingsRepository _buddySettingsRepository; private readonly BodyMotionModeController _bodyMotionModeController; private readonly HandIKIntegrator _handIKIntegrator; private readonly CancellationTokenSource _cts = new(); private bool InteractionApiEnabled => _buddySettingsRepository.InteractionApiEnabled.CurrentValue; public AvatarMotionEventApiImplement( BuddySettingsRepository buddySettingsRepository, BodyMotionModeController bodyMotionModeController, HandIKIntegrator handIKIntegrator ) { _buddySettingsRepository = buddySettingsRepository; _bodyMotionModeController = bodyMotionModeController; _handIKIntegrator = handIKIntegrator; } public override void Initialize() { // TODO: 「clap中」を完全に無視したほうがいいかもしれない (空文字じゃなくてnullを入れてWhere句で弾く…とかのworkaroundを取ると行けそう) _buddySettingsRepository.InteractionApiEnabled .CombineLatest( _handIKIntegrator.LeftTargetType, _bodyMotionModeController.MotionMode, (outputActive, type, mode) => !outputActive ? HandTargetType.Unknown : mode != BodyMotionMode.Default ? HandTargetType.Unknown : type ) .Select(ConvertHandTargetTypeToString) .DistinctUntilChanged() .Where(v => v != null) .Subscribe(targetTypeName => _leftHandTargetType.Value = targetTypeName) .AddTo(this); _buddySettingsRepository.InteractionApiEnabled .CombineLatest( _handIKIntegrator.RightTargetType, _bodyMotionModeController.MotionMode, (outputActive, type, mode) => !outputActive ? HandTargetType.Unknown : mode != BodyMotionMode.Default ? HandTargetType.Unknown : type ) .Select(ConvertHandTargetTypeToString) .DistinctUntilChanged() .Where(v => v != null) .Subscribe(targetTypeName => _rightHandTargetType.Value = targetTypeName) .AddTo(this); InitializeAsync(_cts.Token).Forget(); } private async UniTaskVoid InitializeAsync(CancellationToken cancellationToken) { // NOTE: 1Frame目で絶対に起動したい…というほどの処理でもないので、単に待つことでHandIKIntegratorの初期化完了を待つ await UniTask.NextFrame(cancellationToken); // 基本的なイベント監視のアプローチ // - 個々のIKGeneratorの自己申告を見る // - 体の動作モード + 手IKのモードの実態を見ることで、そのモーションが本当に適用されてそうかを見に行く // - こっちはイベントハンドラっぽい関数の中で随時やってる _handIKIntegrator.Typing.KeyDownMotionStarted .Where(_ => InteractionApiEnabled) .Subscribe(value => OnKeyboardKeyDownMotionStarted(value.hand, value.key)) .AddTo(this); _handIKIntegrator.MouseMove.MouseClickMotionStarted .Where(CanRaiseMouseClickMotionStartEvent) .Subscribe(_ => _touchPadMouseButtonDown.OnNext(Unit.Default)) .AddTo(this); _handIKIntegrator.PenTabletHand.MouseClickMotionStarted .Where(CanRaiseMouseClickMotionStartEvent) .Subscribe(_ => _penTabletMouseButtonDown.OnNext(Unit.Default)) .AddTo(this); _handIKIntegrator.GamepadHand.ButtonDownMotionStarted .Where(_ => InteractionApiEnabled) .Subscribe(v => OnGamepadButtonDownMotionStarted(v.hand, v.key)) .AddTo(this); _handIKIntegrator.ArcadeStickHand.ButtonDownMotionStarted .Where(_ => InteractionApiEnabled) .Subscribe(OnArcadeStickButtonDownMotionStarted) .AddTo(this); } public override void Dispose() { base.Dispose(); _cts?.Cancel(); _cts?.Dispose(); } private void OnKeyboardKeyDownMotionStarted(ReactedHand hand, string keyName) { if (hand == ReactedHand.None || _bodyMotionModeController.MotionMode.CurrentValue != BodyMotionMode.Default) { return; } var actualTarget = hand == ReactedHand.Left ? _handIKIntegrator.LeftTargetType.CurrentValue : _handIKIntegrator.RightTargetType.CurrentValue; if (actualTarget != HandTargetType.Keyboard) { return; } // ENTERキーだけ教える & 他はキー名はヒミツ var eventKeyName = keyName.ToLower() == "enter" ? "Enter" : ""; _keyboardKeyDown.OnNext(eventKeyName); } private bool CanRaiseMouseClickMotionStartEvent(string eventName) { if (!InteractionApiEnabled) { return false; } if (eventName is not (MouseButtonEventNames.LDown or MouseButtonEventNames.RDown or MouseButtonEventNames.MDown) ) { return false; } if (_bodyMotionModeController.MotionMode.CurrentValue != BodyMotionMode.Default) { return false; } return true; } private void OnGamepadButtonDownMotionStarted(ReactedHand hand, GamepadKey key) { if (_bodyMotionModeController.MotionMode.CurrentValue != BodyMotionMode.Default) { return; } if (!IsValidKey(key)) { return; } _gamepadButtonDown.OnNext((hand, key)); } private void OnArcadeStickButtonDownMotionStarted(GamepadKey key) { if (_bodyMotionModeController.MotionMode.CurrentValue != BodyMotionMode.Default) { return; } if (!IsValidKey(key)) { return; } _arcadeStickButtonDown.OnNext(key); } private static bool IsValidKey(GamepadKey key) => key is not GamepadKey.Unknown; private static string ConvertHandTargetTypeToString(HandTargetType type) { return type switch { // 右手でのみ使う値がいくつかある HandTargetType.Mouse => "Mouse", HandTargetType.Presentation => "Presentation", HandTargetType.PenTablet => "PenTablet", // ここから下は両手で発生しうる HandTargetType.Keyboard => "Keyboard", HandTargetType.Gamepad => "Gamepad", HandTargetType.ArcadeStick => "ArcadeStick", HandTargetType.CarHandle => "CarHandle", HandTargetType.MidiController => "MidiController", HandTargetType.ImageBaseHand => "HandTracking", // NOTE: いちおう定義してるが、BodyMotionModeで弾いてるので通過しないはず… HandTargetType.AlwaysDown => "AlwaysDown", // HACK: clapはそもそも「遷移した」という事自体を無視してほしいので、空ではなくnullにしてRxの処理上で特別扱いする HandTargetType.ClapMotion => null, // NOTE: VMCPの適用中も「不明」くらいの扱いにする HandTargetType.VMCPReceiveResult => "", // 未知のも基本的には無視でOK _ => "", }; } } }
1
0.931983
1
0.931983
game-dev
MEDIA
0.880324
game-dev
0.613507
1
0.613507
bjakja/Kainote
2,809
Thirdparty/xy-VSFilter-xy_sub_filter_rc5/src/filters/BaseClasses/cache.h
//------------------------------------------------------------------------------ // File: Cache.h // // Desc: DirectShow base classes - efines a non-MFC generic cache class. // // Copyright (c) 1992-2002 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ /* This class implements a simple cache. A cache object is instantiated with the number of items it is to hold. An item is a pointer to an object derived from CBaseObject (helps reduce memory leaks). The cache can then have objects added to it and removed from it. The cache size is fixed at construction time and may therefore run out or be flooded. If it runs out it returns a NULL pointer, if it fills up it also returns a NULL pointer instead of a pointer to the object just inserted */ /* Making these classes inherit from CBaseObject does nothing for their functionality but it allows us to check there are no memory leaks */ /* WARNING Be very careful when using this class, what it lets you do is store and retrieve objects so that you can minimise object creation which in turns improves efficiency. However the object you store is exactly the same as the object you get back which means that it short circuits the constructor initialisation phase. This means any class variables the object has (eg pointers) are highly likely to be invalid. Therefore ensure you reinitialise the object before using it again */ #ifndef __CACHE__ #define __CACHE__ class CCache : CBaseObject { /* Make copy constructor and assignment operator inaccessible */ CCache(const CCache &refCache); CCache &operator=(const CCache &refCache); private: /* These are initialised in the constructor. The first variable points to an array of pointers, each of which points to a CBaseObject derived object. The m_iCacheSize is the static fixed size for the cache and the m_iUsed defines the number of places filled with objects at any time. We fill the array of pointers from the start (ie m_ppObjects[0] first) and then only add and remove objects from the end position, so in this respect the array of object pointers should be treated as a stack */ CBaseObject **m_ppObjects; const INT m_iCacheSize; INT m_iUsed; public: CCache(TCHAR *pName,INT iItems); virtual ~CCache(); /* Add an item to the cache */ CBaseObject *AddToCache(CBaseObject *pObject); /* Remove an item from the cache */ CBaseObject *RemoveFromCache(); /* Delete all the objects held in the cache */ void RemoveAll(void); /* Return the cache size which is set during construction */ INT GetCacheSize(void) const {return m_iCacheSize;}; }; #endif /* __CACHE__ */
1
0.842591
1
0.842591
game-dev
MEDIA
0.134175
game-dev
0.621403
1
0.621403
MJRLegends/ExtraPlanets
9,899
src/main/java/com/mjr/extraplanets/blocks/fluid/ExtraPlanets_Fluids.java
package com.mjr.extraplanets.blocks.fluid; import com.mjr.extraplanets.Constants; import com.mjr.extraplanets.blocks.ExtraPlanets_Blocks; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.material.MaterialLiquid; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import micdoodle8.mods.galacticraft.core.items.ItemBlockGC; public class ExtraPlanets_Fluids { public static Block GLOWSTONE; public static Fluid GLOWSTONE_FLUID; public static Block MAGMA; public static Fluid MAGMA_FLUID; public static Block NITROGEN; public static Fluid NITROGEN_FLUID; public static Block FROZEN_WATER; public static Fluid FROZEN_WATER_FLUID; public static Block SALT; public static Fluid SALT_FLUID; public static Block RADIO_ACTIVE_WATER; public static Fluid RADIO_ACTIVE_WATER_FLUID; public static Block CLEAN_WATER; public static Fluid CLEAN_WATER_FLUID; public static Block INFECTED_WATER; public static Fluid INFECTED_WATER_FLUID; public static Block METHANE; public static Fluid METHANE_FLUID; public static Block NITROGEN_ICE; public static Fluid NITROGEN_ICE_FLUID; public static Block LIQUID_HYDROCARBON; public static Fluid LIQUID_HYDROCARBON_FLUID; public static Block LIQUID_CHOCOLATE; public static Fluid LIQUID_CHOCOLATE_FLUID; public static Block LIQUID_CARAMEL; public static Fluid LIQUID_CARAMEL_FLUID; public static Material GLOWSTONE_MATERIAL = new MaterialLiquid(MapColor.YELLOW); public static Material MAGMA_MATERIAL = new MaterialLiquid(MapColor.NETHERRACK); public static Material NITROGEN_MATERIAL = new MaterialLiquid(MapColor.LIGHT_BLUE); public static Material FROZEN_WATER_MATERIAL = new MaterialLiquid(MapColor.DIAMOND); public static Material SALT_MATERIAL = new MaterialLiquid(MapColor.GRAY); public static Material METHANE_MATERIAL = new MaterialLiquid(MapColor.GRASS); public static Material CHOCOLATE_MATERIAL = new MaterialLiquid(MapColor.BROWN); public static void init() { initFluidBlocks(); try { registerFluidBlocks(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } public static void initFluid() { GLOWSTONE_FLUID = new Fluid("glowstone_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/glowstone_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/glowstone_flow")).setBlock(GLOWSTONE) .setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(GLOWSTONE_FLUID); FluidRegistry.enableUniversalBucket(); FluidRegistry.addBucketForFluid(GLOWSTONE_FLUID); MAGMA_FLUID = new Fluid("magma_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/magma_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/magma_flow")).setBlock(MAGMA).setDensity(800) .setViscosity(1500); FluidRegistry.registerFluid(MAGMA_FLUID); FluidRegistry.addBucketForFluid(MAGMA_FLUID); NITROGEN_FLUID = new Fluid("nitrogen_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/nitrogen_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/nitrogen_flow")).setBlock(NITROGEN).setDensity(800) .setViscosity(1500); FluidRegistry.registerFluid(NITROGEN_FLUID); FluidRegistry.addBucketForFluid(NITROGEN_FLUID); FROZEN_WATER_FLUID = new Fluid("frozen_water_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/frozen_water_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/frozen_water_flow")) .setBlock(FROZEN_WATER).setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(FROZEN_WATER_FLUID); FluidRegistry.addBucketForFluid(FROZEN_WATER_FLUID); SALT_FLUID = new Fluid("salt_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/salt_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/salt_flow")).setBlock(SALT).setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(SALT_FLUID); FluidRegistry.addBucketForFluid(SALT_FLUID); RADIO_ACTIVE_WATER_FLUID = new Fluid("radioactive_water_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/radioactive_water_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/radioactive_water_flow")) .setBlock(RADIO_ACTIVE_WATER).setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(RADIO_ACTIVE_WATER_FLUID); FluidRegistry.addBucketForFluid(RADIO_ACTIVE_WATER_FLUID); CLEAN_WATER_FLUID = new Fluid("clean_water_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/clean_water_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/clean_water_flow")).setBlock(CLEAN_WATER) .setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(CLEAN_WATER_FLUID); FluidRegistry.addBucketForFluid(CLEAN_WATER_FLUID); INFECTED_WATER_FLUID = new Fluid("infected_water_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/infected_water_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/infected_water_flow")) .setBlock(INFECTED_WATER).setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(INFECTED_WATER_FLUID); FluidRegistry.addBucketForFluid(INFECTED_WATER_FLUID); METHANE_FLUID = new Fluid("methane_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/methane_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/methane_flow")).setBlock(METHANE).setDensity(800) .setViscosity(1500); FluidRegistry.registerFluid(METHANE_FLUID); FluidRegistry.addBucketForFluid(METHANE_FLUID); NITROGEN_ICE_FLUID = new Fluid("nitrogen_ice_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/nitrogen_ice_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/nitrogen_ice_flow")) .setBlock(NITROGEN_ICE).setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(NITROGEN_ICE_FLUID); FluidRegistry.addBucketForFluid(NITROGEN_ICE_FLUID); LIQUID_HYDROCARBON_FLUID = new Fluid("liquid_hydrocarbon_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/liquid_hydrocarbon_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/liquid_hydrocarbon_flow")).setBlock(LIQUID_HYDROCARBON).setDensity(800).setViscosity(1500); FluidRegistry.registerFluid(LIQUID_HYDROCARBON_FLUID); FluidRegistry.addBucketForFluid(LIQUID_HYDROCARBON_FLUID); LIQUID_CHOCOLATE_FLUID = new Fluid("liquid_chocolate_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/liquid_chocolate_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/liquid_chocolate_flow")) .setBlock(LIQUID_CHOCOLATE).setDensity(1000).setViscosity(300); FluidRegistry.registerFluid(LIQUID_CHOCOLATE_FLUID); FluidRegistry.addBucketForFluid(LIQUID_CHOCOLATE_FLUID); LIQUID_CARAMEL_FLUID = new Fluid("liquid_caramel_fluid", new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/liquid_caramel_still"), new ResourceLocation(Constants.TEXTURE_PREFIX + "blocks/fluids/liquid_caramel_flow")) .setBlock(LIQUID_CARAMEL).setDensity(1000).setViscosity(300); FluidRegistry.registerFluid(LIQUID_CARAMEL_FLUID); FluidRegistry.addBucketForFluid(LIQUID_CARAMEL_FLUID); } private static void initFluidBlocks() { GLOWSTONE = new FluidBlockEP(GLOWSTONE_FLUID, "glowstone", GLOWSTONE_MATERIAL).setLightLevel(1.0F); MAGMA = new FluidBlockEP(MAGMA_FLUID, "magma", MAGMA_MATERIAL) { @Override public String getUnlocalizedName() { return "tile.magma_block"; } }; NITROGEN = new FluidBlockEP(NITROGEN_FLUID, "nitrogen", NITROGEN_MATERIAL); FROZEN_WATER = new FluidBlockEP(FROZEN_WATER_FLUID, "frozen_water", FROZEN_WATER_MATERIAL); SALT = new FluidBlockEP(SALT_FLUID, "salt", SALT_MATERIAL); RADIO_ACTIVE_WATER = new FluidBlockEP(RADIO_ACTIVE_WATER_FLUID, "radioactive_water", FROZEN_WATER_MATERIAL); CLEAN_WATER = new FluidBlockEP(CLEAN_WATER_FLUID, "clean_water", Material.WATER); INFECTED_WATER = new FluidBlockEP(INFECTED_WATER_FLUID, "infected_water", FROZEN_WATER_MATERIAL); METHANE = new FluidBlockEP(METHANE_FLUID, "methane", METHANE_MATERIAL); NITROGEN_ICE = new FluidBlockEP(NITROGEN_ICE_FLUID, "nitrogen_ice", NITROGEN_MATERIAL); LIQUID_HYDROCARBON = new FluidBlockEP(LIQUID_HYDROCARBON_FLUID, "liquid_hydrocarbon", FROZEN_WATER_MATERIAL); LIQUID_CHOCOLATE = new FluidBlockEP(LIQUID_CHOCOLATE_FLUID, "liquid_chocolate", CHOCOLATE_MATERIAL); LIQUID_CARAMEL = new FluidBlockEP(LIQUID_CARAMEL_FLUID, "liquid_caramel", CHOCOLATE_MATERIAL); } private static void registerFluidBlocks() throws NoSuchMethodException { ExtraPlanets_Blocks.registerBlock(GLOWSTONE, ItemBlockGC.class, "glowstone"); ExtraPlanets_Blocks.registerBlock(MAGMA, ItemBlockGC.class, "magma"); ExtraPlanets_Blocks.registerBlock(NITROGEN, ItemBlockGC.class, "nitrogen"); ExtraPlanets_Blocks.registerBlock(FROZEN_WATER, ItemBlockGC.class, "frozen_water"); ExtraPlanets_Blocks.registerBlock(SALT, ItemBlockGC.class, "salt"); ExtraPlanets_Blocks.registerBlock(RADIO_ACTIVE_WATER, ItemBlockGC.class, "radioactive_water"); ExtraPlanets_Blocks.registerBlock(CLEAN_WATER, ItemBlockGC.class, "clean_water"); ExtraPlanets_Blocks.registerBlock(INFECTED_WATER, ItemBlockGC.class, "infected_water"); ExtraPlanets_Blocks.registerBlock(METHANE, ItemBlockGC.class, "methane"); ExtraPlanets_Blocks.registerBlock(NITROGEN_ICE, ItemBlockGC.class, "nitrogen_ice"); ExtraPlanets_Blocks.registerBlock(LIQUID_HYDROCARBON, ItemBlockGC.class, "liquid_hydrocarbon"); ExtraPlanets_Blocks.registerBlock(LIQUID_CHOCOLATE, ItemBlockGC.class, "liquid_chocolate"); ExtraPlanets_Blocks.registerBlock(LIQUID_CARAMEL, ItemBlockGC.class, "liquid_caramel"); } }
1
0.663894
1
0.663894
game-dev
MEDIA
0.813429
game-dev
0.747646
1
0.747646
mcclure/bitbucket-backup
20,084
repos/lesbian/contents/source/program.cpp
/* * Program.cpp * PolycodeTemplate * * Created by Andi McClure on 11/22/11. * Copyright 2011 Run Hello. All rights reserved. * */ #include "program.h" #include "svgloader.h" #include "tinyxml.h" #include "terminal.h" #include "physfs.h" #if 0 // Hyperverbal #define HYPERERR ERR #else #define HYPERERR EAT #endif // Halt on failure? #if _DEBUG #define BAIL 1 #else #define BAIL 0 #endif #define ONCLICK_ON_DOWN 1 #define ONCLICK_ON_UP 1 room_auto *room_auto::_singleton = NULL; class roomloader : public svgloader { protected: room_auto *owner; Object *overlay; const char *Attribute(TiXmlElement *xml, string attr); int QueryIntAttribute(TiXmlElement *xml, string attr, int &value); int QueryDoubleAttribute(TiXmlElement *xml, string attr, double &value); virtual bool loadRootXml(TiXmlElement *xml, const svgtransform &parent_transform); virtual bool localAddChild(ScreenEntity *shape, TiXmlElement *xml, svgtype kind, const svgtransform &transform); virtual bool addChild(ScreenEntity *shape, TiXmlElement *xml, svgtype kind, const svgtransform &transform); virtual bool addStoredFunc(hash_map<void *,storedfunc *> &lookup, void *shape, TiXmlElement *xml, const char *attrName); public: roomloader(room_auto *_owner, Object *_overlay = NULL, Screen *__screen = NULL) : svgloader(__screen), owner(_owner), overlay(_overlay) {} }; #if PHYSICS2D class physics_svgloader : public roomloader { protected: virtual PhysicsScreen *createScreen(); virtual bool addChild(ScreenEntity *shape, TiXmlElement *xml, svgtype kind, const svgtransform &transform); public: physics_svgloader(room_auto *_owner, Object *_overlay = NULL, PhysicsScreen *__screen = NULL); PhysicsScreen *physics() { return (PhysicsScreen *)screen(); } }; #endif room_auto::room_auto(const string &_spec, bool _fake) : automaton(), screen(NULL), scene(NULL), spec(_spec), fake(_fake), bailed(false), clickHandler(false), a(NULL), b(NULL) { } room_auto::~room_auto() { clear_stored_functions(); if (_singleton == this) _singleton = NULL; } void room_auto::bail() { bailed = true; clear_stored_functions(); } void room_auto::add_update_function(const string &text) { storedfunc *function = terminal_auto::singleton()->compile(text); if (function) onUpdate.push_back( function ); else if (BAIL) bail(); } void room_auto::clear_stored_functions() { for(handler_iter i = onCollide.begin(); i != onCollide.end(); i++) delete i->second; onCollide.clear(); for(handler_iter i = onClick.begin(); i != onClick.end(); i++) delete i->second; onClick.clear(); for(int c = 0; c < onUpdate.size(); c++) delete onUpdate[c]; onUpdate.clear(); } void room_auto::insert() { automaton::insert(); cor->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN); // Handle esc _singleton = this; if (fake) return; Object overlay; // Iterate over spec string, "split" on commas int file_start = -1; for(int c = 0; c <= spec.size(); c++) { // Notice: spec.size inclusive if (c == spec.size() || spec[c] == '\n' || spec[c] == '\r' || spec[c] == ',') { if (file_start >= 0) { string filename = spec.substr(file_start, c-file_start); loadFromFile(overlay, filename); // This is the only important part file_start = -1; } } else { if (file_start < 0) file_start = c; } } if (bailed) // Make sure we didn't bail, then accidentally add more functions clear_stored_functions(); Clear(overlay); // Free memory if (!onLoad.empty()) { terminal_auto::singleton()->inject_global("global_ticks", ticks); terminal_auto::singleton()->inject_global("ticks", frame); for(int c = 0; c < onLoad.size(); c++) { bool success = terminal_auto::singleton()->execute(onLoad[c]); if (BAIL && !success) { bail(); break; } } onLoad.clear(); // Will never be used again (valid assumption?) } } void room_auto::die() { if (done) return; for(int c = 0; c < onClose.size(); c++) { terminal_auto::singleton()->execute(onClose[c]); // Don't bother clearing, we're dying } automaton::die(); cor->getInput()->removeAllHandlers(); // Remove EVERYTHING, not just our listeners, in case Lua did something CoreServices::getInstance()->setupBasicListeners(); terminal_auto::singleton()->setup_events(); // Let terminal_auto restore its own listeners } void room_auto::tick() { if (done) return; automaton::tick(); terminal_auto::singleton()->inject_global("global_ticks", ticks); terminal_auto::singleton()->inject_global("ticks", frame); for(int c = 0; c < onUpdate.size(); c++) { bool success = onUpdate[c]->execute(); if (BAIL && !success) { bail(); break; } } } void room_auto::rebirth(bool fake) { CoreServices::getInstance()->getMaterialManager()->reloadProgramsAndTextures(); die(); (new room_auto(spec, fake))->insert(); } void room_auto::handleEvent(Event *e) { if (done) return; if(e->getDispatcher() == cor->getInput()) { InputEvent *inputEvent = (InputEvent*)e; bool down = false; switch(e->getEventCode()) { case InputEvent::EVENT_KEYDOWN: { int code = inputEvent->keyCode(); if (!IS_MODIFIER(code)) { if (code == KEY_ESCAPE) { if (debugMode) rebirth(); else Quit(); } else if (code == KEY_F8) { time_t rawtime; struct tm * timeinfo; char name[256]; time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime(name, 256, PROGDIR "Screenshot %Y-%m-%d %H.%M.%S.png", timeinfo); ERR("SAVETO: %s\n", name); Image *i = CoreServices::getInstance()->getRenderer()->renderScreenToImage(); i->savePNG(name); delete i; } } } break; case InputEvent::EVENT_MOUSEDOWN: down = true; // Handle onClick case InputEvent::EVENT_MOUSEUP: { int mouseButton = inputEvent->getMouseButton(); Vector2 pos = inputEvent->getMousePosition(); if (down) clickTrack.clear(); for(handler_iter i = onClick.begin(); i != onClick.end(); i++) { ScreenEntity *child = (ScreenEntity *)i->first; if (child->hitTest(pos.x,pos.y)) { if (down) clickTrack[child] = child; else if (!clickTrack.count(child)) // Skip ups that weren't downs continue; // To simplify things, maybe some programs only ever care about one? if ((!ONCLICK_ON_DOWN && down) || (!ONCLICK_ON_UP && !down)) continue; terminal_auto::singleton()->inject_global("oc_down", down); terminal_auto::singleton()->inject_global("oc_x", pos.x); terminal_auto::singleton()->inject_global("oc_y", pos.y); bool success = i->second->execute(); if (BAIL && !success) { bail(); break; } } } if (!down) clickTrack.clear(); } break; } } else if (e->getDispatcher() == screen) { #if PHYSICS2D PhysicsScreenEvent *pe = (PhysicsScreenEvent*)e; switch(e->getEventCode()) { case PhysicsScreenEvent::EVENT_NEW_SHAPE_COLLISION: { if (onCollide.count(pe->entity1)) { terminal_auto::singleton()->inject_global("impact", pe->impactStrength); doCollide(pe->entity1, pe->entity2, true); } if (onCollide.count(pe->entity2)) { terminal_auto::singleton()->inject_global("impact", pe->impactStrength); doCollide(pe->entity2, pe->entity1, false); } } } #endif } else if (e->getDispatcher() == scene) { #if PHYSICS3D PhysicsSceneEvent *pe = (PhysicsSceneEvent*)e; switch(e->getEventCode()) { case PhysicsSceneEvent::COLLISION_EVENT: { if (onCollide.count(pe->entityA)) { terminal_auto::singleton()->inject_global("impact", pe->appliedImpulse); doCollide(pe->entityA->getSceneEntity(), pe->entityB->getSceneEntity(), true); } if (onCollide.count(pe->entityB)) { terminal_auto::singleton()->inject_global("impact", pe->appliedImpulse); doCollide(pe->entityB->getSceneEntity(), pe->entityA->getSceneEntity(), false); } } } #endif } } void room_auto::needClickHandler() { if (!clickHandler) { cor->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEDOWN); cor->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEUP); clickHandler = true; } } void room_auto::doCollide(Entity *acting, Entity *against, bool) { // Assumes count > 0 a = acting; b = against; bool success = onCollide[acting]->execute(); if (BAIL && !success) bail(); a = NULL; b = NULL; } void room_auto::loadFromFile(Object &overlay, const string &filename) { if (endsWith(filename, ".xml")) { overlay.loadFromXML(String(filename)); // TODO: Clears; shouldn't. } else if (endsWith(filename, ".svg")) { screen_has_class("Screen"); // Guarantee SOME screen loadSvgFromFile(overlay, filename, screen, screenClass); } else if (PHYSFS_isDirectory(filename.c_str())) { loadFromTree(overlay, filename); // TODO: Clears; shouldn't. loadFromOverlay(overlay); } else { ERR("ERROR: Don't know how to load '%s\n", filename.c_str()); } } void room_auto::loadSvgFromFile(Object &overlay, const string &filename, Screen *into, const string &loadClass, bool readBackground) { roomloader *svg; if (loadClass == "PhysicsScreen") { #if PHYSICS2D svg = new physics_svgloader(this, &overlay, (PhysicsScreen *)into); #endif } else { svg = new roomloader(this, &overlay, into); } svg->readBackground = readBackground; svg->load(filename); delete svg; } void room_auto::loadFromOverlay(Object &overlay) { ObjectEntry *temp; if (temp = overlay.root["onLoad"]) { onLoad.push_back( temp->stringVal.getSTLString() ); } if (temp = overlay.root["onUpdate"]) { add_update_function( temp->stringVal.getSTLString() ); } if (temp = overlay.root["onClose"]) { onClose.push_back( temp->stringVal.getSTLString() ); } if (temp = overlay.root["screen"]) { screen_has_class(temp->stringVal.getSTLString()); } if (temp = overlay.root["scene"]) { scene_has_class(temp->stringVal.getSTLString()); } } inline bool is_whitespace(const char &c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } void strip_whitespace(string &target) { // In python this would just be name = name.strip() int leading,trailing; for(leading = 0; leading < target.size() && is_whitespace(target[leading]); leading++); for(trailing = 0; trailing < target.size() && is_whitespace(target[target.size()-trailing-1]); trailing++); if (leading || trailing) target = target.substr(leading, target.size()-leading-trailing); } void room_auto::screen_has_class(string name) { if (screen) return; strip_whitespace(name); if (name == "Screen") { screen = new Screen(); #if PHYSICS2D } else if (name == "PhysicsScreen") { screen = new PhysicsScreen(); screen->addEventListener(this, PhysicsScreenEvent::EVENT_NEW_SHAPE_COLLISION); #endif } if (screen) { screen->rootEntity.ownsChildren = true; owned_screen.push_back(screen); screenClass = name; } } void room_auto::scene_has_class(string name) { if (scene) return; strip_whitespace(name); if (name == "Scene") { scene = new Scene(); #if PHYSICS3D } else { if (name == "CollisionScene") scene = new CollisionScene(); else if (name == "PhysicsScene") scene = new PhysicsScene(); scene->addEventListener(this, PhysicsSceneEvent::COLLISION_EVENT); #endif } if (scene) { scene->ownsChildren = true; owned_screen.push_back(scene); sceneClass = name; } } // I sure do wish I had a way to read into a tree of dictionary ObjectEntries without all these ifs. const char *roomloader::Attribute(TiXmlElement *xml, string attr) { string xmlAttr = "polycode:" + attr; const char *result = xml->Attribute(xmlAttr.c_str()); if (!result && overlay) { // XML takes precedence over overlay ObjectEntry *co = overlay->root["entity"]; const char *id = xml->Attribute("id"); if (co && id) { ObjectEntry *eo = (*co)[id]; if (eo) { ObjectEntry *vo = (*eo)[attr]; if (vo) { result = vo->stringVal.c_str(); } } } } return result; } int roomloader::QueryIntAttribute(TiXmlElement *xml, string attr, int &value) { return TIXML_NO_ATTRIBUTE; // TODO } int roomloader::QueryDoubleAttribute(TiXmlElement *xml, string attr, double &value) { return TIXML_NO_ATTRIBUTE; // TODO } bool roomloader::loadRootXml(TiXmlElement *xml, const svgtransform &parent_transform) { const char *temp = xml->Attribute("polycode:onLoad"); if (temp) owner->onLoad.push_back(temp); temp = xml->Attribute("polycode:onUpdate"); if (temp) owner->add_update_function( temp ); temp = xml->Attribute("polycode:onClose"); if (temp) owner->onClose.push_back(temp); return svgloader::loadRootXml(xml, parent_transform); } bool roomloader::addStoredFunc(hash_map<void *,storedfunc *> &lookup, void *shape, TiXmlElement *xml, const char *attrName) { const char *text = Attribute(xml, attrName); storedfunc *func = text ? terminal_auto::singleton()->compile(text) : NULL; if (func) lookup[shape] = func; return func; } bool roomloader::localAddChild(ScreenEntity *shape, TiXmlElement *xml, svgtype kind, const svgtransform &transform) { addStoredFunc(owner->onCollide, shape, xml, "onCollide"); if (addStoredFunc(owner->onClick, shape, xml, "onClick")) owner->needClickHandler(); int isStatic = true; xml->QueryIntAttribute("polycode:isStatic", &isStatic); const char *id = xml->Attribute("id"); if (id) { if (!PHYSICS2D || !isStatic || string("text") == xml->Value()) { owner->obj[id] = shape; } owner->obj_name[shape] = id; } int isVisible; if (TIXML_SUCCESS == xml->QueryIntAttribute("polycode:isVisible", &isVisible)) shape->visible = isVisible; return true; } bool roomloader::addChild(ScreenEntity *shape, TiXmlElement *xml, svgtype kind, const svgtransform &transform) { svgloader::addChild(shape, xml, kind, transform); localAddChild(shape, xml, kind, transform); return true; } #if PHYSICS2D // TODO: Maybe should return a Scene not a Screen physics_svgloader::physics_svgloader(room_auto *_owner, Object *_overlay, PhysicsScreen *__screen) : roomloader(_owner, _overlay, __screen) {} PhysicsScreen *physics_svgloader::createScreen() { return new PhysicsScreen(); } bool physics_svgloader::addChild(ScreenEntity *shape, TiXmlElement *xml, svgtype kind, const svgtransform &transform) { int physicsType = 0; int isFloater = 0; xml->QueryIntAttribute("polycode:isFloater", &isFloater); if (isFloater) kind = svg_floater; switch (kind) { case svg_rect: physicsType = PhysicsScreenEntity::ENTITY_RECT; break; case svg_circle: physicsType = PhysicsScreenEntity::ENTITY_CIRCLE; break; case svg_mesh: physicsType = PhysicsScreenEntity::ENTITY_MESH; break; case svg_floater: roomloader::addChild(shape,xml,kind,transform); return true; default: return false; } int isStatic = true; double friction = 0.25; double density = 1; double restitution = 0.25; int fixedRotation = false; int isSensor = false; xml->QueryIntAttribute("polycode:isStatic", &isStatic); xml->QueryDoubleAttribute("polycode:friction", &friction); xml->QueryDoubleAttribute("polycode:density", &density); xml->QueryDoubleAttribute("polycode:restitution", &restitution); xml->QueryIntAttribute("polycode:fixedRotation", &fixedRotation); xml->QueryIntAttribute("polycode:isSensor", &isSensor); physics()->addPhysicsChild(shape, physicsType, isStatic, friction, density, restitution, isSensor, fixedRotation); roomloader::localAddChild(shape, xml, kind, transform); // Add information but DON'T call screen->addChild return true; } #endif save_file::save_file() : priority(0) {} #define SAVEFILE_NAME ( PROGDIR "save.xml" ) void save_file::load() { Object f; ObjectEntry *t; f.loadFromXML(SAVEFILE_NAME); t = f.root["priority"]; if (t) priority = t->intVal; t = f.root["file"]; if (t) file = t->stringVal.getSTLString(); } void save_file::save() { Object f; f.root.name = "luanauts_save"; f.root.addChild("priority", priority); f.root.addChild("file", file); f.saveToXML(SAVEFILE_NAME); } void getBaseName(string &basename) { while (basename.size() && basename[basename.size()-1] == '/') // Strip all /s from the end basename = basename.substr(0,basename.size()-1); size_t slash = basename.rfind("/"); // Strip everything left of rightmost / if (slash != string::npos) basename = basename.substr(slash+1); size_t dot = basename.rfind("."); // Strip everything right of rightmost . if (dot != string::npos) basename = basename.substr(0, dot); } void loadFromTree(ObjectEntry &o, const string &path) { if (path.empty()) // An empty string is almost certainly a mistake. return; const char *cpath = path.c_str(); string basename = path; getBaseName(basename); o.name = String(basename); HYPERERR("Node '%s':", basename.c_str()); if (PHYSFS_isDirectory(cpath)) { o.type = ObjectEntry::CONTAINER_ENTRY; char **rc = PHYSFS_enumerateFiles(cpath); HYPERERR("recurse [\n"); for (char **i = rc; *i != NULL; i++) { // For directories, iterate files and recurse. ObjectEntry *e = new ObjectEntry; string recurseName = path + "/" + *i; loadFromTree(*e, recurseName); o.addChild(e); } HYPERERR("]\n"); PHYSFS_freeList(rc); } else { o.type = ObjectEntry::STRING_ENTRY; // TODO: Load numbers, too #define LOADTREE_CHUNK 1024 PHYSFS_file* efile = PHYSFS_openRead(cpath); if (!efile) { o.type = ObjectEntry::UNKNOWN_ENTRY; // Best practice? ERR("ERROR: PhysFS failed to open file: %s\n", cpath); return; } char temp[LOADTREE_CHUNK]; int length_read; while (0 < (length_read = PHYSFS_read (efile, temp, 1, LOADTREE_CHUNK))) { o.stringVal += String(temp, length_read); } HYPERERR("value '%s'\n", o.stringVal.c_str()); PHYSFS_close(efile); } } void loadFromTree(Object &o, const string &path) { Clear(o); loadFromTree(o.root, path); } bool endsWith(const string &str, const string &suffix) { int sufsize = suffix.size(); int strsize = str.size(); if (strsize < sufsize) return false; return str.substr(strsize-sufsize) == suffix; } #define CHUNKSIZE 1024 string filedump(const string &path) { PHYSFS_file *f = PHYSFS_openRead(path.c_str()); if (f) { string result; char chunk[CHUNKSIZE+1]; int chunkread = 0; do { chunkread = PHYSFS_read(f, chunk, 1, CHUNKSIZE); if (chunkread < 0) chunkread = 0; chunk[chunkread] = '\0'; result += chunk; } while (chunkread >= CHUNKSIZE); PHYSFS_close(f); return result; } return string(); } string filedrain(FILE *f) { if (f) { string result; char chunk[CHUNKSIZE+1]; int chunkread = 0; do { chunkread = fread(chunk, 1, CHUNKSIZE, f); if (chunkread < 0) chunkread = 0; chunk[chunkread] = '\0'; result += chunk; } while (chunkread >= CHUNKSIZE); fclose(f); return result; } return string(); } // If you absolutely MUST avoid physfs string filedump_external(const string &path) { FILE *f = fopen(path.c_str(), "r"); return filedrain(f); } int intCheck(ObjectEntry *o, const string &key, int def) { o = objCheck(o, key); if (o && (o->type == ObjectEntry::INT_ENTRY || o->type == ObjectEntry::BOOL_ENTRY || o->type == ObjectEntry::FLOAT_ENTRY)) return o->intVal; return def; } int intCheckPure(ObjectEntry *o, const string &key, int def) { o = objCheck(o, key); if (o && (o->type == ObjectEntry::INT_ENTRY || o->type == ObjectEntry::BOOL_ENTRY)) return o->intVal; return def; } Number numCheck(ObjectEntry *o, const string &key, Number def) { o = objCheck(o, key); if (o && (o->type == ObjectEntry::FLOAT_ENTRY || o->type == ObjectEntry::BOOL_ENTRY || o->type == ObjectEntry::INT_ENTRY)) return o->NumberVal; return def;} string strCheck(ObjectEntry *o, const string &key) { o = objCheck(o, key); if (o && (o->type == ObjectEntry::STRING_ENTRY || o->type == ObjectEntry::BOOL_ENTRY || o->type == ObjectEntry::INT_ENTRY || o->type == ObjectEntry::FLOAT_ENTRY)) return o->stringVal.contents; return string(); } ObjectEntry *objCheck(ObjectEntry *o, const string &key) { if (o && !key.empty()) o = (*o)[key]; return o; } save_file save;
1
0.967932
1
0.967932
game-dev
MEDIA
0.722458
game-dev
0.980446
1
0.980446
R2NorthstarTools/NorthstarProton
20,571
lsteamclient/steamworks_sdk_135/isteaminventory.h
//====== Copyright 1996-2014 Valve Corporation, All rights reserved. ======= // // Purpose: interface to Steam Inventory // //============================================================================= #ifndef ISTEAMINVENTORY_H #define ISTEAMINVENTORY_H #ifdef _WIN32 #pragma once #endif #include "isteamclient.h" // callbacks #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error isteamclient.h must be included #endif // Every individual instance of an item has a globally-unique ItemInstanceID. // This ID is unique to the combination of (player, specific item instance) // and will not be transferred to another player or re-used for another item. typedef uint64 SteamItemInstanceID_t; static const SteamItemInstanceID_t k_SteamItemInstanceIDInvalid = ~(SteamItemInstanceID_t)0; // Types of items in your game are identified by a 32-bit "item definition number". // Valid definition numbers are between 1 and 999999999; numbers less than or equal to // zero are invalid, and numbers greater than or equal to one billion (1x10^9) are // reserved for internal Steam use. typedef int32 SteamItemDef_t; enum ESteamItemFlags { // Item status flags - these flags are permanently attached to specific item instances k_ESteamItemNoTrade = 1 << 0, // This item is account-locked and cannot be traded or given away. // Action confirmation flags - these flags are set one time only, as part of a result set k_ESteamItemRemoved = 1 << 8, // The item has been destroyed, traded away, expired, or otherwise invalidated k_ESteamItemConsumed = 1 << 9, // The item quantity has been decreased by 1 via ConsumeItem API. // All other flag bits are currently reserved for internal Steam use at this time. // Do not assume anything about the state of other flags which are not defined here. }; struct SteamItemDetails_t { SteamItemInstanceID_t m_itemId; SteamItemDef_t m_iDefinition; uint16 m_unQuantity; uint16 m_unFlags; // see ESteamItemFlags }; typedef int32 SteamInventoryResult_t; static const SteamInventoryResult_t k_SteamInventoryResultInvalid = -1; //----------------------------------------------------------------------------- // Purpose: Steam Inventory query and manipulation API //----------------------------------------------------------------------------- class ISteamInventory { public: // INVENTORY ASYNC RESULT MANAGEMENT // // Asynchronous inventory queries always output a result handle which can be used with // GetResultStatus, GetResultItems, etc. A SteamInventoryResultReady_t callback will // be triggered when the asynchronous result becomes ready (or fails). // // Find out the status of an asynchronous inventory result handle. Possible values: // k_EResultPending - still in progress // k_EResultOK - done, result ready // k_EResultExpired - done, result ready, maybe out of date (see DeserializeResult) // k_EResultInvalidParam - ERROR: invalid API call parameters // k_EResultServiceUnavailable - ERROR: service temporarily down, you may retry later // k_EResultLimitExceeded - ERROR: operation would exceed per-user inventory limits // k_EResultFail - ERROR: unknown / generic error METHOD_DESC(Find out the status of an asynchronous inventory result handle.) virtual EResult GetResultStatus( SteamInventoryResult_t resultHandle ) = 0; // Copies the contents of a result set into a flat array. The specific // contents of the result set depend on which query which was used. METHOD_DESC(Copies the contents of a result set into a flat array. The specific contents of the result set depend on which query which was used.) virtual bool GetResultItems( SteamInventoryResult_t resultHandle, OUT_ARRAY_COUNT( punOutItemsArraySize,Output array) SteamItemDetails_t *pOutItemsArray, uint32 *punOutItemsArraySize ) = 0; // Returns the server time at which the result was generated. Compare against // the value of IClientUtils::GetServerRealTime() to determine age. METHOD_DESC(Returns the server time at which the result was generated. Compare against the value of IClientUtils::GetServerRealTime() to determine age.) virtual uint32 GetResultTimestamp( SteamInventoryResult_t resultHandle ) = 0; // Returns true if the result belongs to the target steam ID, false if the // result does not. This is important when using DeserializeResult, to verify // that a remote player is not pretending to have a different user's inventory. METHOD_DESC(Returns true if the result belongs to the target steam ID or false if the result does not. This is important when using DeserializeResult to verify that a remote player is not pretending to have a different users inventory.) virtual bool CheckResultSteamID( SteamInventoryResult_t resultHandle, CSteamID steamIDExpected ) = 0; // Destroys a result handle and frees all associated memory. METHOD_DESC(Destroys a result handle and frees all associated memory.) virtual void DestroyResult( SteamInventoryResult_t resultHandle ) = 0; // INVENTORY ASYNC QUERY // // Captures the entire state of the current user's Steam inventory. // You must call DestroyResult on this handle when you are done with it. // Returns false and sets *pResultHandle to zero if inventory is unavailable. // Note: calls to this function are subject to rate limits and may return // cached results if called too frequently. It is suggested that you call // this function only when you are about to display the user's full inventory, // or if you expect that the inventory may have changed. METHOD_DESC(Captures the entire state of the current users Steam inventory.) virtual bool GetAllItems( SteamInventoryResult_t *pResultHandle ) = 0; // Captures the state of a subset of the current user's Steam inventory, // identified by an array of item instance IDs. The results from this call // can be serialized and passed to other players to "prove" that the current // user owns specific items, without exposing the user's entire inventory. // For example, you could call GetItemsByID with the IDs of the user's // currently equipped cosmetic items and serialize this to a buffer, and // then transmit this buffer to other players upon joining a game. METHOD_DESC(Captures the state of a subset of the current users Steam inventory identified by an array of item instance IDs.) virtual bool GetItemsByID( SteamInventoryResult_t *pResultHandle, ARRAY_COUNT( unCountInstanceIDs ) const SteamItemInstanceID_t *pInstanceIDs, uint32 unCountInstanceIDs ) = 0; // RESULT SERIALIZATION AND AUTHENTICATION // // Serialized result sets contain a short signature which can't be forged // or replayed across different game sessions. A result set can be serialized // on the local client, transmitted to other players via your game networking, // and deserialized by the remote players. This is a secure way of preventing // hackers from lying about posessing rare/high-value items. // Serializes a result set with signature bytes to an output buffer. Pass // NULL as an output buffer to get the required size via punOutBufferSize. // The size of a serialized result depends on the number items which are being // serialized. When securely transmitting items to other players, it is // recommended to use "GetItemsByID" first to create a minimal result set. // Results have a built-in timestamp which will be considered "expired" after // an hour has elapsed. See DeserializeResult for expiration handling. virtual bool SerializeResult( SteamInventoryResult_t resultHandle, OUT_BUFFER_COUNT(punOutBufferSize) void *pOutBuffer, uint32 *punOutBufferSize ) = 0; // Deserializes a result set and verifies the signature bytes. Returns false // if bRequireFullOnlineVerify is set but Steam is running in Offline mode. // Otherwise returns true and then delivers error codes via GetResultStatus. // // The bRESERVED_MUST_BE_FALSE flag is reserved for future use and should not // be set to true by your game at this time. // // DeserializeResult has a potential soft-failure mode where the handle status // is set to k_EResultExpired. GetResultItems() still succeeds in this mode. // The "expired" result could indicate that the data may be out of date - not // just due to timed expiration (one hour), but also because one of the items // in the result set may have been traded or consumed since the result set was // generated. You could compare the timestamp from GetResultTimestamp() to // ISteamUtils::GetServerRealTime() to determine how old the data is. You could // simply ignore the "expired" result code and continue as normal, or you // could challenge the player with expired data to send an updated result set. virtual bool DeserializeResult( SteamInventoryResult_t *pOutResultHandle, BUFFER_COUNT(punOutBufferSize) const void *pBuffer, uint32 unBufferSize, bool bRESERVED_MUST_BE_FALSE = false ) = 0; // INVENTORY ASYNC MODIFICATION // // GenerateItems() creates one or more items and then generates a SteamInventoryCallback_t // notification with a matching nCallbackContext parameter. This API is insecure, and could // be abused by hacked clients. It is, however, very useful as a development cheat or as // a means of prototyping item-related features for your game. The use of GenerateItems can // be restricted to certain item definitions or fully blocked via the Steamworks website. // If punArrayQuantity is not NULL, it should be the same length as pArrayItems and should // describe the quantity of each item to generate. virtual bool GenerateItems( SteamInventoryResult_t *pResultHandle, ARRAY_COUNT(unArrayLength) const SteamItemDef_t *pArrayItemDefs, ARRAY_COUNT(unArrayLength) const uint32 *punArrayQuantity, uint32 unArrayLength ) = 0; // GrantPromoItems() checks the list of promotional items for which the user may be eligible // and grants the items (one time only). On success, the result set will include items which // were granted, if any. If no items were granted because the user isn't eligible for any // promotions, this is still considered a success. METHOD_DESC(GrantPromoItems() checks the list of promotional items for which the user may be eligible and grants the items (one time only).) virtual bool GrantPromoItems( SteamInventoryResult_t *pResultHandle ) = 0; // AddPromoItem() / AddPromoItems() are restricted versions of GrantPromoItems(). Instead of // scanning for all eligible promotional items, the check is restricted to a single item // definition or set of item definitions. This can be useful if your game has custom UI for // showing a specific promo item to the user. virtual bool AddPromoItem( SteamInventoryResult_t *pResultHandle, SteamItemDef_t itemDef ) = 0; virtual bool AddPromoItems( SteamInventoryResult_t *pResultHandle, ARRAY_COUNT(unArrayLength) const SteamItemDef_t *pArrayItemDefs, uint32 unArrayLength ) = 0; // ConsumeItem() removes items from the inventory, permanently. They cannot be recovered. // Not for the faint of heart - if your game implements item removal at all, a high-friction // UI confirmation process is highly recommended. Similar to GenerateItems, punArrayQuantity // can be NULL or else an array of the same length as pArrayItems which describe the quantity // of each item to destroy. ConsumeItem can be restricted to certain item definitions or // fully blocked via the Steamworks website to minimize support/abuse issues such as the // clasic "my brother borrowed my laptop and deleted all of my rare items". METHOD_DESC(ConsumeItem() removes items from the inventory permanently.) virtual bool ConsumeItem( SteamInventoryResult_t *pResultHandle, SteamItemInstanceID_t itemConsume, uint32 unQuantity ) = 0; // ExchangeItems() is an atomic combination of GenerateItems and DestroyItems. It can be // used to implement crafting recipes or transmutations, or items which unpack themselves // into other items. Like GenerateItems, this is a flexible and dangerous API which is // meant for rapid prototyping. You can configure restrictions on ExchangeItems via the // Steamworks website, such as limiting it to a whitelist of input/output combinations // corresponding to recipes. // (Note: although GenerateItems may be hard or impossible to use securely in your game, // ExchangeItems is perfectly reasonable to use once the whitelists are set accordingly.) virtual bool ExchangeItems( SteamInventoryResult_t *pResultHandle, ARRAY_COUNT(unArrayGenerateLength) const SteamItemDef_t *pArrayGenerate, ARRAY_COUNT(unArrayGenerateLength) const uint32 *punArrayGenerateQuantity, uint32 unArrayGenerateLength, ARRAY_COUNT(unArrayDestroyLength) const SteamItemInstanceID_t *pArrayDestroy, ARRAY_COUNT(unArrayDestroyLength) const uint32 *punArrayDestroyQuantity, uint32 unArrayDestroyLength ) = 0; // TransferItemQuantity() is intended for use with items which are "stackable" (can have // quantity greater than one). It can be used to split a stack into two, or to transfer // quantity from one stack into another stack of identical items. To split one stack into // two, pass k_SteamItemInstanceIDInvalid for itemIdDest and a new item will be generated. virtual bool TransferItemQuantity( SteamInventoryResult_t *pResultHandle, SteamItemInstanceID_t itemIdSource, uint32 unQuantity, SteamItemInstanceID_t itemIdDest ) = 0; // TIMED DROPS AND PLAYTIME CREDIT // // Applications which use timed-drop mechanics should call SendItemDropHeartbeat() when // active gameplay begins, and at least once every two minutes afterwards. The backend // performs its own time calculations, so the precise timing of the heartbeat is not // critical as long as you send at least one heartbeat every two minutes. Calling the // function more often than that is not harmful, it will simply have no effect. Note: // players may be able to spoof this message by hacking their client, so you should not // attempt to use this as a mechanism to restrict playtime credits. It is simply meant // to distinguish between being in any kind of gameplay situation vs the main menu or // a pre-game launcher window. (If you are stingy with handing out playtime credit, it // will only encourage players to run bots or use mouse/kb event simulators.) // // Playtime credit accumulation can be capped on a daily or weekly basis through your // Steamworks configuration. // METHOD_DESC(Applications which use timed-drop mechanics should call SendItemDropHeartbeat() when active gameplay begins and at least once every two minutes afterwards.) virtual void SendItemDropHeartbeat() = 0; // Playtime credit must be consumed and turned into item drops by your game. Only item // definitions which are marked as "playtime item generators" can be spawned. The call // will return an empty result set if there is not enough playtime credit for a drop. // Your game should call TriggerItemDrop at an appropriate time for the user to receive // new items, such as between rounds or while the player is dead. Note that players who // hack their clients could modify the value of "dropListDefinition", so do not use it // to directly control rarity. It is primarily useful during testing and development, // where you may wish to perform experiments with different types of drops. METHOD_DESC(Playtime credit must be consumed and turned into item drops by your game.) virtual bool TriggerItemDrop( SteamInventoryResult_t *pResultHandle, SteamItemDef_t dropListDefinition ) = 0; // IN-GAME TRADING // // TradeItems() implements limited in-game trading of items, if you prefer not to use // the overlay or an in-game web browser to perform Steam Trading through the website. // You should implement a UI where both players can see and agree to a trade, and then // each client should call TradeItems simultaneously (+/- 5 seconds) with matching // (but reversed) parameters. The result is the same as if both players performed a // Steam Trading transaction through the web. Each player will get an inventory result // confirming the removal or quantity changes of the items given away, and the new // item instance id numbers and quantities of the received items. // (Note: new item instance IDs are generated whenever an item changes ownership.) virtual bool TradeItems( SteamInventoryResult_t *pResultHandle, CSteamID steamIDTradePartner, ARRAY_COUNT(nArrayGiveLength) const SteamItemInstanceID_t *pArrayGive, ARRAY_COUNT(nArrayGiveLength) const uint32 *pArrayGiveQuantity, uint32 nArrayGiveLength, ARRAY_COUNT(nArrayGetLength) const SteamItemInstanceID_t *pArrayGet, ARRAY_COUNT(nArrayGetLength) const uint32 *pArrayGetQuantity, uint32 nArrayGetLength ) = 0; // ITEM DEFINITIONS // // Item definitions are a mapping of "definition IDs" (integers between 1 and 1000000) // to a set of string properties. Some of these properties are required to display items // on the Steam community web site. Other properties can be defined by applications. // Use of these functions is optional; there is no reason to call LoadItemDefinitions // if your game hardcodes the numeric definition IDs (eg, purple face mask = 20, blue // weapon mod = 55) and does not allow for adding new item types without a client patch. // // LoadItemDefinitions triggers the automatic load and refresh of item definitions. // Every time new item definitions are available (eg, from the dynamic addition of new // item types while players are still in-game), a SteamInventoryDefinitionUpdate_t // callback will be fired. METHOD_DESC(LoadItemDefinitions triggers the automatic load and refresh of item definitions.) virtual bool LoadItemDefinitions() = 0; // GetItemDefinitionIDs returns the set of all defined item definition IDs (which are // defined via Steamworks configuration, and not necessarily contiguous integers). // If pItemDefIDs is null, the call will return true and *punItemDefIDsArraySize will // contain the total size necessary for a subsequent call. Otherwise, the call will // return false if and only if there is not enough space in the output array. virtual bool GetItemDefinitionIDs( OUT_ARRAY_COUNT(punItemDefIDsArraySize,List of item definition IDs) SteamItemDef_t *pItemDefIDs, DESC(Size of array is passed in and actual size used is returned in this param) uint32 *punItemDefIDsArraySize ) = 0; // GetItemDefinitionProperty returns a string property from a given item definition. // Note that some properties (for example, "name") may be localized and will depend // on the current Steam language settings (see ISteamApps::GetCurrentGameLanguage). // Property names are always composed of ASCII letters, numbers, and/or underscores. // Pass a NULL pointer for pchPropertyName to get a comma - separated list of available // property names. virtual bool GetItemDefinitionProperty( SteamItemDef_t iDefinition, const char *pchPropertyName, OUT_STRING_COUNT(punValueBufferSize) char *pchValueBuffer, uint32 *punValueBufferSize ) = 0; }; #define STEAMINVENTORY_INTERFACE_VERSION "STEAMINVENTORY_INTERFACE_V001" // SteamInventoryResultReady_t callbacks are fired whenever asynchronous // results transition from "Pending" to "OK" or an error state. There will // always be exactly one callback per handle. struct SteamInventoryResultReady_t { enum { k_iCallback = k_iClientInventoryCallbacks + 0 }; SteamInventoryResult_t m_handle; EResult m_result; }; // SteamInventoryFullUpdate_t callbacks are triggered when GetAllItems // successfully returns a result which is newer / fresher than the last // known result. (It will not trigger if the inventory hasn't changed, // or if results from two overlapping calls are reversed in flight and // the earlier result is already known to be stale/out-of-date.) // The normal ResultReady callback will still be triggered immediately // afterwards; this is an additional notification for your convenience. struct SteamInventoryFullUpdate_t { enum { k_iCallback = k_iClientInventoryCallbacks + 1 }; SteamInventoryResult_t m_handle; }; // A SteamInventoryDefinitionUpdate_t callback is triggered whenever // item definitions have been updated, which could be in response to // LoadItemDefinitions() or any other async request which required // a definition update in order to process results from the server. struct SteamInventoryDefinitionUpdate_t { enum { k_iCallback = k_iClientInventoryCallbacks + 2 }; }; #pragma pack( pop ) #endif // ISTEAMCONTROLLER_H
1
0.859945
1
0.859945
game-dev
MEDIA
0.592589
game-dev,networking
0.887097
1
0.887097
hornyyy/Osu-Toy
11,117
osu.Game/Screens/Play/GameplayClockContainer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using osu.Framework; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Configuration; namespace osu.Game.Screens.Play { /// <summary> /// Encapsulates gameplay timing logic and provides a <see cref="Play.GameplayClock"/> for children. /// </summary> public class GameplayClockContainer : Container { private readonly WorkingBeatmap beatmap; [NotNull] private ITrack track; public readonly BindableBool IsPaused = new BindableBool(); /// <summary> /// The decoupled clock used for gameplay. Should be used for seeks and clock control. /// </summary> private readonly DecoupleableInterpolatingFramedClock adjustableClock; private readonly double gameplayStartTime; private readonly bool startAtGameplayStart; private readonly double firstHitObjectTime; public readonly BindableNumber<double> UserPlaybackRate = new BindableDouble(1) { Default = 1, MinValue = 0.5, MaxValue = 2, Precision = 0.1, }; /// <summary> /// The final clock which is exposed to underlying components. /// </summary> public GameplayClock GameplayClock => localGameplayClock; [Cached(typeof(GameplayClock))] private readonly LocalGameplayClock localGameplayClock; private Bindable<double> userAudioOffset; private readonly FramedOffsetClock userOffsetClock; private readonly FramedOffsetClock platformOffsetClock; /// <summary> /// Creates a new <see cref="GameplayClockContainer"/>. /// </summary> /// <param name="beatmap">The beatmap being played.</param> /// <param name="gameplayStartTime">The suggested time to start gameplay at.</param> /// <param name="startAtGameplayStart"> /// Whether <paramref name="gameplayStartTime"/> should be used regardless of when storyboard events and hitobjects are supposed to start. /// </param> public GameplayClockContainer(WorkingBeatmap beatmap, double gameplayStartTime, bool startAtGameplayStart = false) { this.beatmap = beatmap; this.gameplayStartTime = gameplayStartTime; this.startAtGameplayStart = startAtGameplayStart; track = beatmap.Track; firstHitObjectTime = beatmap.Beatmap.HitObjects.First().StartTime; RelativeSizeAxes = Axes.Both; adjustableClock = new DecoupleableInterpolatingFramedClock { IsCoupled = false }; // Lazer's audio timings in general doesn't match stable. This is the result of user testing, albeit limited. // This only seems to be required on windows. We need to eventually figure out why, with a bit of luck. platformOffsetClock = new HardwareCorrectionOffsetClock(adjustableClock) { Offset = RuntimeInfo.OS == RuntimeInfo.Platform.Windows ? 15 : 0 }; // the final usable gameplay clock with user-set offsets applied. userOffsetClock = new HardwareCorrectionOffsetClock(platformOffsetClock); // the clock to be exposed via DI to children. localGameplayClock = new LocalGameplayClock(userOffsetClock); GameplayClock.IsPaused.BindTo(IsPaused); IsPaused.BindValueChanged(onPauseChanged); } private void onPauseChanged(ValueChangedEvent<bool> isPaused) { if (isPaused.NewValue) this.TransformBindableTo(pauseFreqAdjust, 0, 200, Easing.Out).OnComplete(_ => adjustableClock.Stop()); else this.TransformBindableTo(pauseFreqAdjust, 1, 200, Easing.In); } private double totalOffset => userOffsetClock.Offset + platformOffsetClock.Offset; /// <summary> /// Duration before gameplay start time required before skip button displays. /// </summary> public const double MINIMUM_SKIP_TIME = 1000; private readonly BindableDouble pauseFreqAdjust = new BindableDouble(1); [BackgroundDependencyLoader] private void load(OsuConfigManager config) { userAudioOffset = config.GetBindable<double>(OsuSetting.AudioOffset); userAudioOffset.BindValueChanged(offset => userOffsetClock.Offset = offset.NewValue, true); // sane default provided by ruleset. double startTime = gameplayStartTime; if (!startAtGameplayStart) { startTime = Math.Min(0, startTime); // if a storyboard is present, it may dictate the appropriate start time by having events in negative time space. // this is commonly used to display an intro before the audio track start. startTime = Math.Min(startTime, beatmap.Storyboard.FirstEventTime); // some beatmaps specify a current lead-in time which should be used instead of the ruleset-provided value when available. // this is not available as an option in the live editor but can still be applied via .osu editing. if (beatmap.BeatmapInfo.AudioLeadIn > 0) startTime = Math.Min(startTime, firstHitObjectTime - beatmap.BeatmapInfo.AudioLeadIn); } Seek(startTime); adjustableClock.ProcessFrame(); } public void Restart() { Task.Run(() => { track.Seek(0); track.Stop(); Schedule(() => { adjustableClock.ChangeSource(track); updateRate(); if (!IsPaused.Value) Start(); }); }); } public void Start() { if (!adjustableClock.IsRunning) { // Seeking the decoupled clock to its current time ensures that its source clock will be seeked to the same time // This accounts for the audio clock source potentially taking time to enter a completely stopped state Seek(GameplayClock.CurrentTime); adjustableClock.Start(); } IsPaused.Value = false; } /// <summary> /// Skip forward to the next valid skip point. /// </summary> public void Skip() { if (GameplayClock.CurrentTime > gameplayStartTime - MINIMUM_SKIP_TIME) return; double skipTarget = gameplayStartTime - MINIMUM_SKIP_TIME; if (GameplayClock.CurrentTime < 0 && skipTarget > 6000) // double skip exception for storyboards with very long intros skipTarget = 0; Seek(skipTarget); } /// <summary> /// Seek to a specific time in gameplay. /// <remarks> /// Adjusts for any offsets which have been applied (so the seek may not be the expected point in time on the underlying audio track). /// </remarks> /// </summary> /// <param name="time">The destination time to seek to.</param> public void Seek(double time) { // remove the offset component here because most of the time we want the seek to be aligned to gameplay, not the audio track. // we may want to consider reversing the application of offsets in the future as it may feel more correct. adjustableClock.Seek(time - totalOffset); // manually process frame to ensure GameplayClock is correctly updated after a seek. userOffsetClock.ProcessFrame(); } public void Stop() { IsPaused.Value = true; } /// <summary> /// Changes the backing clock to avoid using the originally provided track. /// </summary> public void StopUsingBeatmapClock() { removeSourceClockAdjustments(); track = new TrackVirtual(track.Length); adjustableClock.ChangeSource(track); } protected override void Update() { if (!IsPaused.Value) { userOffsetClock.ProcessFrame(); } base.Update(); } private bool speedAdjustmentsApplied; private void updateRate() { if (speedAdjustmentsApplied) return; track.AddAdjustment(AdjustableProperty.Frequency, pauseFreqAdjust); track.AddAdjustment(AdjustableProperty.Tempo, UserPlaybackRate); localGameplayClock.MutableNonGameplayAdjustments.Add(pauseFreqAdjust); localGameplayClock.MutableNonGameplayAdjustments.Add(UserPlaybackRate); speedAdjustmentsApplied = true; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); removeSourceClockAdjustments(); } private void removeSourceClockAdjustments() { if (!speedAdjustmentsApplied) return; track.RemoveAdjustment(AdjustableProperty.Frequency, pauseFreqAdjust); track.RemoveAdjustment(AdjustableProperty.Tempo, UserPlaybackRate); localGameplayClock.MutableNonGameplayAdjustments.Remove(pauseFreqAdjust); localGameplayClock.MutableNonGameplayAdjustments.Remove(UserPlaybackRate); speedAdjustmentsApplied = false; } private class LocalGameplayClock : GameplayClock { public readonly List<Bindable<double>> MutableNonGameplayAdjustments = new List<Bindable<double>>(); public override IEnumerable<Bindable<double>> NonGameplayAdjustments => MutableNonGameplayAdjustments; public LocalGameplayClock(FramedOffsetClock underlyingClock) : base(underlyingClock) { } } private class HardwareCorrectionOffsetClock : FramedOffsetClock { // we always want to apply the same real-time offset, so it should be adjusted by the difference in playback rate (from realtime) to achieve this. // base implementation already adds offset at 1.0 rate, so we only add the difference from that here. public override double CurrentTime => base.CurrentTime + Offset * (Rate - 1); public HardwareCorrectionOffsetClock(IClock source, bool processSource = true) : base(source, processSource) { } } } }
1
0.763992
1
0.763992
game-dev
MEDIA
0.660182
game-dev,audio-video-media
0.863683
1
0.863683
ChengF3ng233/Untitled
1,382
src/main/java/net/minecraft/client/audio/SoundCategory.java
package net.minecraft.client.audio; import com.google.common.collect.Maps; import lombok.Getter; import java.util.Map; @Getter public enum SoundCategory { MASTER("master", 0), MUSIC("music", 1), RECORDS("record", 2), WEATHER("weather", 3), BLOCKS("block", 4), MOBS("hostile", 5), ANIMALS("neutral", 6), PLAYERS("player", 7), AMBIENT("ambient", 8); private static final Map<String, SoundCategory> NAME_CATEGORY_MAP = Maps.newHashMap(); private static final Map<Integer, SoundCategory> ID_CATEGORY_MAP = Maps.newHashMap(); static { for (SoundCategory soundcategory : values()) { if (NAME_CATEGORY_MAP.containsKey(soundcategory.getCategoryName()) || ID_CATEGORY_MAP.containsKey(soundcategory.getCategoryId())) { throw new Error("Clash in Sound Category ID & Name pools! Cannot insert " + soundcategory); } NAME_CATEGORY_MAP.put(soundcategory.getCategoryName(), soundcategory); ID_CATEGORY_MAP.put(soundcategory.getCategoryId(), soundcategory); } } private final String categoryName; private final int categoryId; SoundCategory(String name, int id) { this.categoryName = name; this.categoryId = id; } public static SoundCategory getCategory(String name) { return NAME_CATEGORY_MAP.get(name); } }
1
0.744113
1
0.744113
game-dev
MEDIA
0.554577
game-dev
0.838132
1
0.838132
ReikaKalseki/DragonAPI
2,539
ModInteract/ItemHandlers/DartItemHandler.java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.DragonAPI.ModInteract.ItemHandlers; import java.lang.reflect.Field; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import Reika.DragonAPI.DragonAPICore; import Reika.DragonAPI.ModList; import Reika.DragonAPI.Base.ModHandlerBase; public final class DartItemHandler extends ModHandlerBase { private static final DartItemHandler instance = new DartItemHandler(); public final Item wrenchID; public final Item meatID; private DartItemHandler() { super(); Item idwrench = null; Item idmeat = null; if (this.hasMod()) { try { Class item = Class.forName("bluedart.core.Config"); Field wrench = item.getField("forceWrenchID"); idwrench = (Item)wrench.get(null); Field meat = item.getField("rawLambchopID"); idmeat = (Item)meat.get(null); } catch (ClassNotFoundException e) { DragonAPICore.logError("DartCraft Item class not found! Cannot read its items!"); e.printStackTrace(); this.logFailure(e); } catch (NoSuchFieldException e) { DragonAPICore.logError("DartCraft item field not found! "+e.getMessage()); e.printStackTrace(); this.logFailure(e); } catch (SecurityException e) { DragonAPICore.logError("Cannot read DartCraft items (Security Exception)! "+e.getMessage()); e.printStackTrace(); this.logFailure(e); } catch (IllegalArgumentException e) { DragonAPICore.logError("Illegal argument for reading DartCraft items!"); e.printStackTrace(); this.logFailure(e); } catch (IllegalAccessException e) { DragonAPICore.logError("Illegal access exception for reading DartCraft items!"); e.printStackTrace(); this.logFailure(e); } } else { this.noMod(); } wrenchID = idwrench; meatID = idmeat; } public static DartItemHandler getInstance() { return instance; } @Override public boolean initializedProperly() { return wrenchID != null && meatID != null; } @Override public ModList getMod() { return ModList.DARTCRAFT; } public boolean isWrench(ItemStack held) { if (held == null) return false; if (!this.initializedProperly()) return false; return held.getItem() == wrenchID; } }
1
0.927178
1
0.927178
game-dev
MEDIA
0.983229
game-dev
0.94021
1
0.94021
sinojelly/mockcpp
2,878
tests/3rdparty/testngpp/tests/3rdparty/testngppst/src/mem_checker/static_mem_pool.cpp
// -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- // vim:tabstop=4:shiftwidth=4:expandtab: /* * Copyright (C) 2004-2008 Wu Yongwei <adah at users dot sourceforge dot net> * * 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 acknowledgement 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 is part of Stones of Nvwa: * http://sourceforge.net/projects/nvwa * */ /** * @file static_mem_pool.cpp * * Non-template and non-inline code for the `static' memory pool. * * @version 1.7, 2006/08/26 * @author Wu Yongwei * */ #include <algorithm> #include <mem_checker/cont_ptr_utils.h> #include <mem_checker/static_mem_pool.h> static_mem_pool_set::static_mem_pool_set() { _STATIC_MEM_POOL_TRACE(false, "The static_mem_pool_set is created"); } static_mem_pool_set::~static_mem_pool_set() { std::for_each(_M_memory_pool_set.rbegin(), _M_memory_pool_set.rend(), delete_object()); _STATIC_MEM_POOL_TRACE(false, "The static_mem_pool_set is destroyed"); } /** * Creates the singleton instance of #static_mem_pool_set. * * @return reference to the instance of #static_mem_pool_set */ static_mem_pool_set& static_mem_pool_set::instance() { lock __guard; static static_mem_pool_set _S_instance; return _S_instance; } /** * Asks all static memory pools to recycle unused memory blocks back to * the system. The caller should get the lock to prevent other * operations to #static_mem_pool_set during its execution. */ void static_mem_pool_set::recycle() { _STATIC_MEM_POOL_TRACE(false, "Memory pools are being recycled"); container_type::iterator __end = _M_memory_pool_set.end(); for (container_type::iterator __i = _M_memory_pool_set.begin(); __i != __end; ++__i) { (*__i)->recycle(); } } /** * Adds a new memory pool to #static_mem_pool_set. * * @param __memory_pool_p pointer to the memory pool to add */ void static_mem_pool_set::add(mem_pool_base* __memory_pool_p) { lock __guard; _M_memory_pool_set.push_back(__memory_pool_p); }
1
0.942261
1
0.942261
game-dev
MEDIA
0.174957
game-dev
0.534
1
0.534
OpenZWave/open-zwave
3,265
cpp/src/platform/FileOps.h
//----------------------------------------------------------------------------- // // FileOps.h // // Cross-platform File Operations // // Copyright (c) 2012 Greg Satz <satz@iranger.com> // All rights reserved. // // SOFTWARE NOTICE AND LICENSE // // This file is part of OpenZWave. // // OpenZWave 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. // // OpenZWave 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 OpenZWave. If not, see <http://www.gnu.org/licenses/>. // //----------------------------------------------------------------------------- #ifndef _FileOps_H #define _FileOps_H #include <stdarg.h> #include <string> #include "Defs.h" namespace OpenZWave { namespace Internal { namespace Platform { class FileOpsImpl; /** \brief Implements platform-independent File Operations. * \ingroup Platform */ class FileOps { public: /** * Create a FileOps cross-platform singleton. * \return a pointer to the file operations object. * \see Destroy. */ static FileOps* Create(); /** * Destroys the FileOps singleton. * \see Create. */ static void Destroy(); /** * FolderExists. Check for the existence of a folder. * \param string. Folder name. * \return Bool value indicating existence. */ static bool FolderExists(const string &_folderName); /** * FileExists. Check for the existence of a file. * \param string. file name. * \return Bool value indicating existence. */ static bool FileExists(const string &_fileName); /** * FileWriteable. Check if we can write to a file. * \param string. file name. * \return Bool value indicating write permissions. */ static bool FileWriteable(const string &_fileName); /** * FileRotate. Rotate a File * \param string. file name. * \return Bool value indicating write permissions. */ static bool FileRotate(const string &_fileName); /** * FileCopy. Copy a File * \param string. source file name. * \param string. destination file name * \return Bool value indicating success. */ static bool FileCopy(const string &_fileName, const string &_destinationfile); /** * FolderCreate. Create a Folder * \param string. folder name * \return Bool value indicating success. */ static bool FolderCreate(const string &_folderName); private: FileOps(); ~FileOps(); static FileOpsImpl* m_pImpl; // Pointer to an object that encapsulates the platform-specific implementation of the FileOps. static FileOps* s_instance; }; } // namespace Platform } // namespace Internal } // namespace OpenZWave #endif //_FileOps_H
1
0.841872
1
0.841872
game-dev
MEDIA
0.381863
game-dev
0.563765
1
0.563765
glKarin/com.n0n3m4.diii4a
2,391
Q3E/src/main/jni/jk/code/game/wp_melee.cpp
/* =========================================================================== Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "g_local.h" #include "b_local.h" #include "g_functions.h" #include "wp_saber.h" #include "w_local.h" void WP_Melee( gentity_t *ent ) //--------------------------------------------------------- { gentity_t *tr_ent; trace_t tr; vec3_t mins, maxs, end; int damage = ent->s.number ? (g_spskill->integer*2)+1 : 3; float range = ent->s.number ? 64 : 32; VectorMA( muzzle, range, forwardVec, end ); VectorSet( maxs, 6, 6, 6 ); VectorScale( maxs, -1, mins ); gi.trace ( &tr, muzzle, mins, maxs, end, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); if ( tr.entityNum >= ENTITYNUM_WORLD ) { if ( tr.entityNum == ENTITYNUM_WORLD ) { G_PlayEffect( G_EffectIndex( "melee/punch_impact" ), tr.endpos, forwardVec ); } return; } tr_ent = &g_entities[tr.entityNum]; if ( ent->client && !PM_DroidMelee( ent->client->NPC_class ) ) { if ( ent->s.number || ent->alt_fire ) { damage *= Q_irand( 2, 3 ); } else { damage *= Q_irand( 1, 2 ); } } if ( tr_ent && tr_ent->takedamage ) { int dflags = DAMAGE_NO_KNOCKBACK; G_PlayEffect( G_EffectIndex( "melee/punch_impact" ), tr.endpos, forwardVec ); //G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); if ( ent->NPC && (ent->NPC->aiFlags&NPCAI_HEAVY_MELEE) ) { //4x damage for heavy melee class damage *= 4; dflags &= ~DAMAGE_NO_KNOCKBACK; dflags |= DAMAGE_DISMEMBER; } G_Damage( tr_ent, ent, ent, forwardVec, tr.endpos, damage, dflags, MOD_MELEE ); } }
1
0.878312
1
0.878312
game-dev
MEDIA
0.983206
game-dev
0.861628
1
0.861628
RobertSkalko/Age-of-Exile
5,349
src/main/java/com/robertx22/age_of_exile/mixin_methods/OnItemInteract.java
package com.robertx22.age_of_exile.mixin_methods; import com.robertx22.age_of_exile.database.data.currency.base.ICurrencyItemEffect; import com.robertx22.age_of_exile.database.data.currency.loc_reqs.LocReqContext; import com.robertx22.age_of_exile.mmorpg.registers.common.items.SlashItems; import com.robertx22.age_of_exile.saveclasses.item_classes.GearItemData; import com.robertx22.age_of_exile.saveclasses.stat_soul.StatSoulData; import com.robertx22.age_of_exile.saveclasses.stat_soul.StatSoulItem; import com.robertx22.age_of_exile.uncommon.datasaving.Gear; import com.robertx22.age_of_exile.uncommon.datasaving.StackSaving; import com.robertx22.age_of_exile.uncommon.interfaces.data_items.ISalvagable; import com.robertx22.age_of_exile.uncommon.utilityclasses.PlayerUtils; import com.robertx22.age_of_exile.vanilla_mc.items.misc.SalvagedDustItem; import com.robertx22.library_of_exile.utils.SoundUtils; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.container.ClickType; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.SoundEvents; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; public class OnItemInteract { public static void on(Container screen, int i, int j, ClickType slotActionType, PlayerEntity player, CallbackInfoReturnable<ItemStack> ci) { if (slotActionType != ClickType.PICKUP) { return; } ItemStack cursor = player.inventory.getCarried(); if (!cursor.isEmpty()) { Slot slot = null; try { slot = screen.slots.get(i); } catch (Exception e) { } if (slot == null) { return; } ItemStack stack = slot.getItem(); boolean success = false; if (stack.isDamaged() && cursor.getItem() instanceof SalvagedDustItem) { GearItemData gear = Gear.Load(stack); if (gear == null) { return; } SalvagedDustItem essence = (SalvagedDustItem) cursor.getItem(); SoundUtils.playSound(player, SoundEvents.ANVIL_USE, 1, 1); int repair = essence.durabilityRepair; if (gear.getTier() > essence.tier.tier) { repair /= 5; } stack.setDamageValue(stack.getDamageValue() - repair); success = true; } else if (cursor.getItem() instanceof StatSoulItem) { StatSoulData data = StackSaving.STAT_SOULS.loadFrom(cursor); if (data != null) { if (data.canInsertIntoStack(stack)) { data.insertAsUnidentifiedOn(stack); success = true; } } } else if (cursor.getItem() instanceof ICurrencyItemEffect) { LocReqContext ctx = new LocReqContext(player, stack, cursor); if (ctx.effect.canItemBeModified(ctx)) { ItemStack result = ctx.effect.modifyItem(ctx).stack; stack.shrink(1); slot.set(result); success = true; } } else if (cursor.getItem() == SlashItems.SALVAGE_HAMMER.get()) { ISalvagable data = ISalvagable.load(stack); if (data == null && stack.getItem() instanceof ISalvagable) { data = (ISalvagable) stack.getItem(); } if (data != null) { SoundUtils.playSound(player, SoundEvents.ANVIL_USE, 1, 1); stack.shrink(1); data.getSalvageResult(stack) .forEach(x -> PlayerUtils.giveItem(x, player)); ci.setReturnValue(ItemStack.EMPTY); ci.cancel(); return; } } else if (cursor.getItem() == SlashItems.SOCKET_EXTRACTOR.get()) { GearItemData gear = Gear.Load(stack); if (gear != null) { if (gear.sockets != null && gear.sockets.sockets.size() > 0) { try { ItemStack gem = new ItemStack(gear.sockets.sockets.get(0) .getGem() .getItem()); gear.sockets.sockets.remove(0); Gear.Save(stack, gear); PlayerUtils.giveItem(gem, player); } catch (Exception e) { e.printStackTrace(); } ci.setReturnValue(ItemStack.EMPTY); ci.cancel(); return; } } } if (success) { SoundUtils.ding(player.level, player.blockPosition()); SoundUtils.playSound(player.level, player.blockPosition(), SoundEvents.ANVIL_USE, 1, 1); cursor.shrink(1); ci.setReturnValue(ItemStack.EMPTY); ci.cancel(); } } } }
1
0.974404
1
0.974404
game-dev
MEDIA
0.969376
game-dev
0.994509
1
0.994509
Fluorohydride/ygopro-scripts
3,176
c16024176.lua
--花札衛-松に鶴- function c16024176.initial_effect(c) c:EnableReviveLimit() --spsummon from hand local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_FIELD) e1:SetRange(LOCATION_HAND) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetCondition(c16024176.hspcon) e1:SetTarget(c16024176.hsptg) e1:SetOperation(c16024176.hspop) c:RegisterEffect(e1) --draw(spsummon) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(16024176,0)) e2:SetCategory(CATEGORY_DRAW+CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetTarget(c16024176.target) e2:SetOperation(c16024176.operation) c:RegisterEffect(e2) --draw(battle) local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_DRAW) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_PHASE+PHASE_BATTLE) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetCondition(c16024176.drcon) e3:SetTarget(c16024176.drtg) e3:SetOperation(c16024176.drop) c:RegisterEffect(e3) end function c16024176.hspfilter(c,tp) return c:IsSetCard(0xe6) and c:IsLevel(1) and not c:IsCode(16024176) and Duel.GetMZoneCount(tp,c)>0 and (c:IsControler(tp) or c:IsFaceup()) end function c16024176.hspcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.CheckReleaseGroupEx(tp,c16024176.hspfilter,1,REASON_SPSUMMON,false,nil,tp) end function c16024176.hsptg(e,tp,eg,ep,ev,re,r,rp,chk,c) local g=Duel.GetReleaseGroup(tp,false,REASON_SPSUMMON):Filter(c16024176.hspfilter,nil,tp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local tc=g:SelectUnselect(nil,tp,false,true,1,1) if tc then e:SetLabelObject(tc) return true else return false end end function c16024176.hspop(e,tp,eg,ep,ev,re,r,rp,c) local g=e:GetLabelObject() Duel.Release(g,REASON_SPSUMMON) end function c16024176.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c16024176.operation(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) if Duel.Draw(p,d,REASON_EFFECT)~=0 then local tc=Duel.GetOperatedGroup():GetFirst() Duel.ConfirmCards(1-tp,tc) Duel.BreakEffect() if tc:IsType(TYPE_MONSTER) and tc:IsSetCard(0xe6) then if tc:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.SelectYesNo(tp,aux.Stringid(16024176,1)) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end else Duel.SendtoGrave(tc,REASON_EFFECT) end Duel.ShuffleHand(tp) end end function c16024176.drcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetBattledGroupCount()>0 end function c16024176.drtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c16024176.drop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end
1
0.842115
1
0.842115
game-dev
MEDIA
0.979054
game-dev
0.941696
1
0.941696
guilds-plugin/Guilds
3,480
src/main/kotlin/me/glaremasters/guilds/arena/ArenaHandler.kt
/* * MIT License * * Copyright (c) 2023 Glare * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.glaremasters.guilds.arena import me.glaremasters.guilds.Guilds import java.util.* /** * The `ArenaHandler` class manages and holds all the [Arena] objects. * * @property guilds The [Guilds] object which holds the [ArenaHandler]. * @property arenas The map of [Arena] objects, with their names as the key. */ class ArenaHandler(private val guilds: Guilds) { private val arenas = mutableMapOf<String, Arena>() /** * Adds a [Arena] to the map of arenas. * * @param arena The [Arena] to be added. */ fun addArena(arena: Arena) { arenas[arena.name.lowercase(Locale.getDefault())] = arena } /** * Removes a [Arena] from the map of arenas. * * @param arena The [Arena] to be removed. */ fun removeArena(arena: Arena) { arenas.remove(arena.name) } /** * Returns a collection of all the [Arena] objects in the map. * * @return The collection of [Arena] objects. */ fun getArenas(): Collection<Arena> { return arenas.values } /** * Returns an [Optional] object containing the [Arena] object with the given name. * * @param name The name of the [Arena]. * @return An [Optional] object containing the [Arena] object. */ fun getArena(name: String): Optional<Arena> { return Optional.ofNullable(arenas[name.lowercase(Locale.getDefault())]) } /** * Returns an [Optional] object containing the first [Arena] object which is not in use. * * @return An [Optional] object containing the [Arena] object. */ fun getAvailableArena(): Optional<Arena> { return Optional.ofNullable(arenas.values.shuffled().firstOrNull { !it.inUse }) } /** * Returns a list of the names of all the [Arena] objects in the map. * * @return The list of arena names. */ fun arenaNames(): List<String> { return getArenas().map { it.name } } /** * Loads all the [Arena] objects from the database and adds them to the map of arenas. */ fun loadArenas() { guilds.database.arenaAdapter.allArenas.forEach(this::addArena) } /** * Saves all the [Arena] objects in the map to the database. */ fun saveArenas() { guilds.database.arenaAdapter.saveArenas(arenas.values) } }
1
0.79819
1
0.79819
game-dev
MEDIA
0.89336
game-dev
0.720524
1
0.720524
4ian/GDevelop
1,280
GDevelop.js/types/gdeventsbasedbehavior.js
// Automatically generated by GDevelop.js/scripts/generate-types.js declare class gdEventsBasedBehavior extends gdAbstractEventsBasedEntity { constructor(): void; setName(name: string): gdEventsBasedBehavior; setFullName(fullName: string): gdEventsBasedBehavior; setDescription(description: string): gdEventsBasedBehavior; setPrivate(isPrivate: boolean): gdEventsBasedBehavior; setObjectType(fullName: string): gdEventsBasedBehavior; getObjectType(): string; setQuickCustomizationVisibility(visibility: QuickCustomization_Visibility): gdEventsBasedBehavior; getQuickCustomizationVisibility(): QuickCustomization_Visibility; getSharedPropertyDescriptors(): gdPropertiesContainer; static getPropertyActionName(propertyName: string): string; static getPropertyConditionName(propertyName: string): string; static getPropertyExpressionName(propertyName: string): string; static getPropertyToggleActionName(propertyName: string): string; static getSharedPropertyActionName(propertyName: string): string; static getSharedPropertyConditionName(propertyName: string): string; static getSharedPropertyExpressionName(propertyName: string): string; static getSharedPropertyToggleActionName(propertyName: string): string; delete(): void; ptr: number; };
1
0.83638
1
0.83638
game-dev
MEDIA
0.340428
game-dev
0.729071
1
0.729071
magefree/mage
1,920
Mage.Sets/src/mage/cards/e/EtherswornAdjudicator.java
package mage.cards.e; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.effects.common.UntapSourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.StaticFilters; import mage.target.Target; import mage.target.TargetPermanent; import java.util.UUID; /** * @author Loki */ public final class EtherswornAdjudicator extends CardImpl { public EtherswornAdjudicator(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{4}{U}"); this.subtype.add(SubType.VEDALKEN); this.subtype.add(SubType.KNIGHT); this.power = new MageInt(4); this.toughness = new MageInt(4); // Flying this.addAbility(FlyingAbility.getInstance()); // {1}{W}{B}, {T}: Destroy target creature or enchantment. Ability ability = new SimpleActivatedAbility(new DestroyTargetEffect(), new ManaCostsImpl<>("{1}{W}{B}")); ability.addCost(new TapSourceCost()); Target target = new TargetPermanent(StaticFilters.FILTER_PERMANENT_CREATURE_OR_ENCHANTMENT); ability.addTarget(target); this.addAbility(ability); // {2}{U}: Untap Ethersworn Adjudicator. this.addAbility(new SimpleActivatedAbility(new UntapSourceEffect(), new ManaCostsImpl<>("{2}{U}"))); } private EtherswornAdjudicator(final EtherswornAdjudicator card) { super(card); } @Override public EtherswornAdjudicator copy() { return new EtherswornAdjudicator(this); } }
1
0.95304
1
0.95304
game-dev
MEDIA
0.974731
game-dev
0.996492
1
0.996492
fwbrasil/activate
2,624
activate-core/src/main/scala/net/fwbrasil/activate/entity/EntityContext.scala
package net.fwbrasil.activate.entity import net.fwbrasil.radon.transaction.TransactionContext import net.fwbrasil.activate.entity.id.EntityIdContext import net.fwbrasil.activate.cache.LiveCache import net.fwbrasil.activate.cache.CacheType import net.fwbrasil.activate.ActivateContext import net.fwbrasil.activate.entity.map.EntityMapContext import net.fwbrasil.activate.cache.CustomCache import net.fwbrasil.activate.entity.id.CustomID import net.fwbrasil.activate.entity.id.UUID import net.fwbrasil.activate.util.Reflection._ trait EntityContext extends ValueContext with TransactionContext with LazyListContext with EntityIdContext with EntityMapContext { this: ActivateContext => type Alias = net.fwbrasil.activate.entity.InternalAlias @scala.annotation.meta.field type Var[A] = net.fwbrasil.activate.entity.Var[A] type EntityMap[E <: BaseEntity] = net.fwbrasil.activate.entity.map.EntityMap[E] type MutableEntityMap[E <: BaseEntity] = net.fwbrasil.activate.entity.map.MutableEntityMap[E] type Encoder[A, B] = net.fwbrasil.activate.entity.Encoder[A, B] type BaseEntity = net.fwbrasil.activate.entity.BaseEntity type Entity = net.fwbrasil.activate.entity.Entity type EntityWithCustomID[ID] = net.fwbrasil.activate.entity.EntityWithCustomID[ID] type EntityWithGeneratedID[ID] = net.fwbrasil.activate.entity.EntityWithGeneratedID[ID] protected def liveCacheType = CacheType.softReferences protected def customCaches: List[CustomCache[_]] = List() protected[activate] val liveCache = new LiveCache(this, liveCacheType, customCaches.asInstanceOf[List[CustomCache[BaseEntity]]]) protected[activate] def entityMaterialized(entity: BaseEntity) = {} protected[activate] def hidrateEntities(entities: Iterable[BaseEntity])(implicit context: ActivateContext) = for (entity <- entities) { initializeBitmaps(entity) entity.invariants entity.initializeListeners context.transactional(context.transient) { initializeLazyFlags(entity) } context.liveCache.toCache(entity) } private def initializeLazyFlags(entity: net.fwbrasil.activate.entity.BaseEntity): Unit = { val metadata = EntityHelper.getEntityMetadata(entity.getClass) val lazyFlags = metadata.propertiesMetadata.filter(p => p.isLazyFlag && p.isTransient) for (propertyMetadata <- lazyFlags) { val ref = new Var(propertyMetadata, entity, true) propertyMetadata.varField.set(entity, ref) } } }
1
0.786584
1
0.786584
game-dev
MEDIA
0.438065
game-dev
0.615824
1
0.615824
greggman/doodles
3,264
js/threejs/r105/js/nodes/utils/VelocityNode.js
/** * @author sunag / http://www.sunag.com.br/ */ import { Vector3Node } from '../inputs/Vector3Node.js'; function VelocityNode( target, params ) { Vector3Node.call( this ); this.params = {}; this.velocity = new THREE.Vector3(); this.setTarget( target ); this.setParams( params ); } VelocityNode.prototype = Object.create( Vector3Node.prototype ); VelocityNode.prototype.constructor = VelocityNode; VelocityNode.prototype.nodeType = "Velocity"; VelocityNode.prototype.getReadonly = function ( builder ) { return false; }; VelocityNode.prototype.setParams = function ( params ) { switch ( this.params.type ) { case "elastic": delete this.moment; delete this.speed; delete this.springVelocity; delete this.lastVelocity; break; } this.params = params || {}; switch ( this.params.type ) { case "elastic": this.moment = new THREE.Vector3(); this.speed = new THREE.Vector3(); this.springVelocity = new THREE.Vector3(); this.lastVelocity = new THREE.Vector3(); break; } }; VelocityNode.prototype.setTarget = function ( target ) { if ( this.target ) { delete this.position; delete this.oldPosition; } this.target = target; if ( target ) { this.position = target.getWorldPosition( this.position || new THREE.Vector3() ); this.oldPosition = this.position.clone(); } }; VelocityNode.prototype.updateFrameVelocity = function ( frame ) { if ( this.target ) { this.position = this.target.getWorldPosition( this.position || new THREE.Vector3() ); this.velocity.subVectors( this.position, this.oldPosition ); this.oldPosition.copy( this.position ); } }; VelocityNode.prototype.updateFrame = function ( frame ) { this.updateFrameVelocity( frame ); switch ( this.params.type ) { case "elastic": // convert to real scale: 0 at 1 values var deltaFps = frame.delta * ( this.params.fps || 60 ); var spring = Math.pow( this.params.spring, deltaFps ), damping = Math.pow( this.params.damping, deltaFps ); // fix relative frame-rate this.velocity.multiplyScalar( Math.exp( - this.params.damping * deltaFps ) ); // elastic this.velocity.add( this.springVelocity ); this.velocity.add( this.speed.multiplyScalar( damping ).multiplyScalar( 1 - spring ) ); // speed this.speed.subVectors( this.velocity, this.lastVelocity ); // spring velocity this.springVelocity.add( this.speed ); this.springVelocity.multiplyScalar( spring ); // moment this.moment.add( this.springVelocity ); // damping this.moment.multiplyScalar( damping ); this.lastVelocity.copy( this.velocity ); this.value.copy( this.moment ); break; default: this.value.copy( this.velocity ); } }; VelocityNode.prototype.copy = function ( source ) { Vector3Node.prototype.copy.call( this, source ); if ( source.target ) object.setTarget( source.target ); object.setParams( source.params ); }; VelocityNode.prototype.toJSON = function ( meta ) { var data = this.getJSONNode( meta ); if ( ! data ) { data = this.createJSONNode( meta ); if ( this.target ) data.target = this.target.uuid; // clone params data.params = JSON.parse( JSON.stringify( this.params ) ); } return data; }; export { VelocityNode };
1
0.734858
1
0.734858
game-dev
MEDIA
0.622805
game-dev,graphics-rendering
0.97165
1
0.97165
Rz-C/Mohist
2,590
src/main/java/org/bukkit/craftbukkit/v1_20_R1/inventory/CraftShapedRecipe.java
package org.bukkit.craftbukkit.v1_20_R1.inventory; import net.minecraft.core.NonNullList; import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.Ingredient; import org.bukkit.NamespacedKey; import org.bukkit.craftbukkit.v1_20_R1.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.ShapedRecipe; import java.util.Map; public class CraftShapedRecipe extends ShapedRecipe implements CraftRecipe { // TODO: Could eventually use this to add a matches() method or some such private net.minecraft.world.item.crafting.ShapedRecipe recipe; public CraftShapedRecipe(NamespacedKey key, ItemStack result) { super(key, result); } public CraftShapedRecipe(ItemStack result, net.minecraft.world.item.crafting.ShapedRecipe recipe) { this(CraftNamespacedKey.fromMinecraft(recipe.getId()), result); this.recipe = recipe; } public static CraftShapedRecipe fromBukkitRecipe(ShapedRecipe recipe) { if (recipe instanceof CraftShapedRecipe) { return (CraftShapedRecipe) recipe; } CraftShapedRecipe ret = new CraftShapedRecipe(recipe.getKey(), recipe.getResult()); ret.setGroup(recipe.getGroup()); ret.setCategory(recipe.getCategory()); String[] shape = recipe.getShape(); ret.shape(shape); Map<Character, RecipeChoice> ingredientMap = recipe.getChoiceMap(); for (char c : ingredientMap.keySet()) { RecipeChoice stack = ingredientMap.get(c); if (stack != null) { ret.setIngredient(c, stack); } } return ret; } @Override public void addToCraftingManager() { String[] shape = this.getShape(); Map<Character, org.bukkit.inventory.RecipeChoice> ingred = this.getChoiceMap(); int width = shape[0].length(); NonNullList<Ingredient> data = NonNullList.withSize(shape.length * width, Ingredient.EMPTY); for (int i = 0; i < shape.length; i++) { String row = shape[i]; for (int j = 0; j < row.length(); j++) { data.set(i * width + j, toNMS(ingred.get(row.charAt(j)), false)); } } MinecraftServer.getServer().getRecipeManager().addRecipe(new net.minecraft.world.item.crafting.ShapedRecipe(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), CraftRecipe.getCategory(this.getCategory()), width, shape.length, data, CraftItemStack.asNMSCopy(this.getResult()))); } }
1
0.61878
1
0.61878
game-dev
MEDIA
0.997803
game-dev
0.787964
1
0.787964
DaFuqs/Spectrum
1,209
src/main/java/de/dafuqs/spectrum/compat/REI/plugins/PotionWorkshopCraftingDisplay.java
package de.dafuqs.spectrum.compat.REI.plugins; import de.dafuqs.revelationary.api.advancements.*; import de.dafuqs.spectrum.api.recipe.*; import de.dafuqs.spectrum.compat.REI.*; import de.dafuqs.spectrum.recipe.potion_workshop.*; import me.shedaniel.rei.api.common.category.*; import net.minecraft.client.*; import net.minecraft.world.item.crafting.*; public class PotionWorkshopCraftingDisplay extends PotionWorkshopRecipeDisplay { protected final IngredientStack baseIngredient; protected final boolean consumeBaseIngredient; /** * When using the REI recipe functionality * * @param recipe The recipe */ public PotionWorkshopCraftingDisplay(RecipeHolder<PotionWorkshopCraftingRecipe> recipe) { super(recipe); this.baseIngredient = recipe.value().getBaseIngredient(); this.consumeBaseIngredient = recipe.value().consumesBaseIngredient(); } @Override public CategoryIdentifier<?> getCategoryIdentifier() { return SpectrumPlugins.POTION_WORKSHOP_CRAFTING; } @Override public boolean isUnlocked() { Minecraft client = Minecraft.getInstance(); return AdvancementHelper.hasAdvancement(client.player, PotionWorkshopRecipe.UNLOCK_IDENTIFIER) && super.isUnlocked(); } }
1
0.709877
1
0.709877
game-dev
MEDIA
0.99033
game-dev
0.723075
1
0.723075
hebohang/HEngine
4,877
Engine/Source/ThirdParty/bullet3/examples/Utils/b3Quickprof.h
/* Copyright (c) 2003-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. */ /*************************************************************************************************** ** ** Real-Time Hierarchical Profiling for Game Programming Gems 3 ** ** by Greg Hjelstrom & Byon Garrabrant ** ***************************************************************************************************/ // Credits: The Clock class was inspired by the Timer classes in // Ogre (www.ogre3d.org). #ifndef B3_QUICK_PROF_H #define B3_QUICK_PROF_H //To disable built-in profiling, please comment out next line //#define B3_NO_PROFILE 1 #ifndef B3_NO_PROFILE #include <stdio.h> //@todo remove this, backwards compatibility #include "Bullet3Common/b3Scalar.h" #include "Bullet3Common/b3AlignedAllocator.h" #include <new> #include "b3Clock.h" ///A node in the Profile Hierarchy Tree class b3ProfileNode { public: b3ProfileNode(const char* name, b3ProfileNode* parent); ~b3ProfileNode(void); b3ProfileNode* Get_Sub_Node(const char* name); b3ProfileNode* Get_Parent(void) { return Parent; } b3ProfileNode* Get_Sibling(void) { return Sibling; } b3ProfileNode* Get_Child(void) { return Child; } void CleanupMemory(); void Reset(void); void Call(void); bool Return(void); const char* Get_Name(void) { return Name; } int Get_Total_Calls(void) { return TotalCalls; } float Get_Total_Time(void) { return TotalTime; } void* GetUserPointer() const { return m_userPtr; } void SetUserPointer(void* ptr) { m_userPtr = ptr; } protected: const char* Name; int TotalCalls; float TotalTime; unsigned long int StartTime; int RecursionCounter; b3ProfileNode* Parent; b3ProfileNode* Child; b3ProfileNode* Sibling; void* m_userPtr; }; ///An iterator to navigate through the tree class b3ProfileIterator { public: // Access all the children of the current parent void First(void); void Next(void); bool Is_Done(void); bool Is_Root(void) { return (CurrentParent->Get_Parent() == 0); } void Enter_Child(int index); // Make the given child the new parent void Enter_Largest_Child(void); // Make the largest child the new parent void Enter_Parent(void); // Make the current parent's parent the new parent // Access the current child const char* Get_Current_Name(void) { return CurrentChild->Get_Name(); } int Get_Current_Total_Calls(void) { return CurrentChild->Get_Total_Calls(); } float Get_Current_Total_Time(void) { return CurrentChild->Get_Total_Time(); } void* Get_Current_UserPointer(void) { return CurrentChild->GetUserPointer(); } void Set_Current_UserPointer(void* ptr) { CurrentChild->SetUserPointer(ptr); } // Access the current parent const char* Get_Current_Parent_Name(void) { return CurrentParent->Get_Name(); } int Get_Current_Parent_Total_Calls(void) { return CurrentParent->Get_Total_Calls(); } float Get_Current_Parent_Total_Time(void) { return CurrentParent->Get_Total_Time(); } protected: b3ProfileNode* CurrentParent; b3ProfileNode* CurrentChild; b3ProfileIterator(b3ProfileNode* start); friend class b3ProfileManager; }; ///The Manager for the Profile system class b3ProfileManager { public: static void Start_Profile(const char* name); static void Stop_Profile(void); static void CleanupMemory(void) { Root.CleanupMemory(); } static void Reset(void); static void Increment_Frame_Counter(void); static int Get_Frame_Count_Since_Reset(void) { return FrameCounter; } static float Get_Time_Since_Reset(void); static b3ProfileIterator* Get_Iterator(void) { return new b3ProfileIterator(&Root); } static void Release_Iterator(b3ProfileIterator* iterator) { delete (iterator); } static void dumpRecursive(b3ProfileIterator* profileIterator, int spacing); static void dumpAll(); static void dumpRecursive(FILE* f, b3ProfileIterator* profileIterator, int spacing); static void dumpAll(FILE* f); private: static b3ProfileNode Root; static b3ProfileNode* CurrentNode; static int FrameCounter; static unsigned long int ResetTime; }; #else #endif //#ifndef B3_NO_PROFILE #endif //B3_QUICK_PROF_H
1
0.931852
1
0.931852
game-dev
MEDIA
0.324155
game-dev
0.925922
1
0.925922
PrashantMohta/HollowKnight.CustomKnight
1,860
CustomKnight/Skin/Settings/SkinConfig.cs
using Newtonsoft.Json; using Satchel.JsonConverters; namespace CustomKnight { /// <summary> /// Author side configuration for a skin /// </summary> public class SkinConfig { /// <summary> /// Should enable the filter over defender's crest effect /// </summary> public bool dungFilter = true; /// <summary> /// Should disable the filter applied on the wraiths sheet /// </summary> public bool wraithsFilter = false; /// <summary> /// Color that flashes when Melody is triggered /// </summary> [JsonConverter(typeof(ColorConverter))] public Color brummColor = new Color(1, 1, 1, 1); /// <summary> /// Color that flashes when the player heals /// </summary> [JsonConverter(typeof(ColorConverter))] public Color flashColor = new Color(1, 1, 1); /// <summary> /// Color that flashes when an enemy is under the effect of defender's crest /// </summary> [JsonConverter(typeof(ColorConverter))] public Color dungFlash = new Color(0.45f, 0.27f, 0f); /// <summary> /// Should the mod try to auto-detect Alts? should be disabled on authored skins /// </summary> public bool detectAlts = true; /// <summary> /// default filename to List of available alternate filenames /// </summary> public Dictionary<string, List<string>> alternates = new Dictionary<string, List<string>>(); /// <summary> /// Ctor /// </summary> public SkinConfig() { foreach (var kvp in SkinManager.Skinables) { var name = kvp.Value.name + ".png"; alternates[name] = new List<string> { name }; } } } }
1
0.859997
1
0.859997
game-dev
MEDIA
0.941782
game-dev
0.864871
1
0.864871
kem0x/raider3.5
1,060
Raider/SDK/FN_CollectionBookWidget_classes.hpp
#pragma once // Fortnite (3.1) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass CollectionBookWidget.CollectionBookWidget_C // 0x0008 (0x0428 - 0x0420) class UCollectionBookWidget_C : public UFortCollectionBookWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0420(0x0008) (Transient, DuplicateTransient) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass CollectionBookWidget.CollectionBookWidget_C"); return ptr; } void Construct(); void SlotItemComplete(class UFortAccountItem* ItemSlotted, const struct FName& SlotId); void Destruct(); void OnActivated(); void ExecuteUbergraph_CollectionBookWidget(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
1
0.839004
1
0.839004
game-dev
MEDIA
0.717958
game-dev,desktop-app
0.662545
1
0.662545
MCRcortex/voxy
9,215
src/main/java/me/cortex/voxy/common/util/HierarchicalBitSet.java
package me.cortex.voxy.common.util; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import java.util.Random; public class HierarchicalBitSet { public static final int SET_FULL = -1; private final int limit; private int cnt; //If a bit is 1 it means all children are also set private long A = 0; private final long[] B = new long[64]; private final long[] C = new long[64*64]; private final long[] D = new long[64*64*64]; public HierarchicalBitSet(int limit) {//Fixed size of 64^4 this.limit = limit; if (limit > (1<<(6*4))) { throw new IllegalArgumentException("Limit greater than capacity"); } } private int endId = -1; public HierarchicalBitSet() { this(1<<(6*4)); } public int allocateNext() { if (this.A==-1) { return -1; } if (this.cnt+1>this.limit) { return -1;//Limit reached } int idx = Long.numberOfTrailingZeros(~this.A); long bp = this.B[idx]; idx = Long.numberOfTrailingZeros(~bp) + 64*idx; long cp = this.C[idx]; idx = Long.numberOfTrailingZeros(~cp) + 64*idx; long dp = this.D[idx]; idx = Long.numberOfTrailingZeros(~dp) + 64*idx; int ret = idx; //if (this.isSet(ret)) { // throw new IllegalStateException(); //} dp |= 1L<<(idx&0x3f); this.D[idx>>6] = dp; if (dp==-1) { idx >>= 6; cp |= 1L<<(idx&0x3f); this.C[idx>>6] = cp; if (cp==-1) { idx >>= 6; bp |= 1L<<(idx&0x3f); this.B[idx>>6] = bp; if (bp==-1) { idx >>= 6; this.A |= 1L<<(idx&0x3f); } } } this.cnt++; this.endId += ret==(this.endId+1)?1:0; return ret; } private void set(int idx) { //if (this.isSet(idx)) { // throw new IllegalStateException(); //} this.endId += idx==(this.endId+1)?1:0; long dp = this.D[idx>>6] |= 1L<<(idx&0x3f); if (dp==-1) { idx >>= 6; long cp = (this.C[idx>>6] |= 1L<<(idx&0x3f)); if (cp==-1) { idx >>= 6; long bp = this.B[idx>>6] |= 1L<<(idx&0x3f); if (bp==-1) { idx >>= 6; this.A |= 1L<<(idx&0x3f); } } } this.cnt++; } //Returns the next free index from idx private int findNextFree(int idx) { int pos; do { pos = Long.numberOfTrailingZeros((~this.A) & -(1L << (idx >> 18))); idx = Math.max(pos << 18, idx); pos = Long.numberOfTrailingZeros((~this.B[idx >> 18]) & -(1L << ((idx >> 12) & 0x3F))); idx = Math.max((pos + ((idx >> 18) << 6)) << 12, idx); if (pos == 64) continue;//Try again pos = Long.numberOfTrailingZeros((~this.C[idx >> 12]) & -(1L << ((idx >> 6) & 0x3F))); idx = Math.max((pos + ((idx >> 12) << 6)) << 6, idx); if (pos == 64) continue;//Try again pos = Long.numberOfTrailingZeros(((~this.D[idx >> 6]) & -(1L << (idx & 0x3F)))); idx = Math.max(pos + ((idx >> 6) << 6), idx); } while (pos == 64); //TODO: fixme: this is due to the fact of the acceleration structure return idx; } //TODO: FIXME: THIS IS SLOW AS SHIT public int allocateNextConsecutiveCounted(int count) { if (count > 64) { throw new IllegalStateException("Count to large for current implementation which has fastpath"); } if (this.A==-1) { return -1; } if (this.cnt+count>=this.limit) { return -2;//Limit reached } long chkMsk = ((1L<<count)-1); int i = this.findNextFree(0); while (true) { long fusedValue = this.D[i>>6]>>>(i&63); if (64-(i&63) < count) { fusedValue |= this.D[(i>>6)+1] << (64-(i&63)); } if ((fusedValue&chkMsk) != 0) { //Space does not contain enough empty value i += Long.numberOfTrailingZeros(fusedValue);//Skip as much as possible (i.e. skip to the next 1 bit) i = this.findNextFree(i); continue; } //TODO: optimize this laziness // (can do it by first setting/updating the lower D index and propagating, then the upper D index (if it has/needs one)) for (int j = 0; j < count; j++) { this.set(j + i); } return i; } } public boolean free(int idx) { long v = this.D[idx>>6]; boolean wasSet = (v&(1L<<(idx&0x3f)))!=0; this.cnt -= wasSet?1:0; if (wasSet && idx == this.endId) { //Need to go back until we find the endIdx bit for (this.endId--; this.endId>=0 && !this.isSet(this.endId); this.endId--); //this.endId++; } this.D[idx>>6] = v&~(1L<<(idx&0x3f)); idx >>= 6; this.C[idx>>6] &= ~(1L<<(idx&0x3f)); idx >>= 6; this.B[idx>>6] &= ~(1L<<(idx&0x3f)); idx >>= 6; this.A &= ~(1L<<(idx&0x3f)); return wasSet; } public int getCount() { return this.cnt; } public int getLimit() { return this.limit; } public boolean isSet(int idx) { return (this.D[idx>>6]&(1L<<(idx&0x3f)))!=0; } public int getMaxIndex() { return this.endId; } public static void main3(String[] args) { var h = new HierarchicalBitSet(1<<19); for (int i = 0; i < 1<<19; i++) { if (h.allocateNext() != i) { throw new IllegalStateException("At:" + i); } if (h.endId != i) { throw new IllegalStateException(); } } for (int i = 0; i < 1<<18; i++) { if (!h.free(i)) { throw new IllegalStateException(); } } for (int i = (1<<19)-1; i != (1<<18)-1; i--) { if (h.endId != i) { throw new IllegalStateException(); } if (!h.free(i)) { throw new IllegalStateException(); } } if (h.endId != -1) { throw new IllegalStateException(); } } public static void main2(String[] args) { var h = new HierarchicalBitSet(); for (int i = 0; i < 64*32; i++) { h.set(i); } h.set(0); { int i = 0; while (i<64*32) { int j = h.findNextFree(i); if (h.isSet(j)) { throw new IllegalStateException(); } for (int k = i; k < j; k++) { if (!h.isSet(k)) { throw new IllegalStateException(); } } i = j + 1; } } var r = new Random(0); for (int i = 0; i < 500; i++) { h.free(r.nextInt(64*32)); } h.allocateNextConsecutiveCounted(10); } public static void main(String[] args) { for (int i = 0; i < 100; i++) { var r = new Random(i*12345L); var h = new HierarchicalBitSet(); IntSet set = new IntOpenHashSet(10000); for (int j = 0; j < 100_000; j++) { int q = h.allocateNext(); if (q != j || !set.add(q)) { throw new IllegalStateException(); } } for (int j = 0; j < 100_000; j++) { int op = r.nextInt(5); int extra = r.nextInt(8)+1; if (op == 0) { int v = h.allocateNext(); if (v < 0) { throw new IllegalStateException(); } if (!set.add(v)) { throw new IllegalStateException(); } } else if (op == 1) { int base = h.allocateNextConsecutiveCounted(extra); if (base < 0) { throw new IllegalStateException(); } for (int q = 0; q < extra; q++) { if (!set.add(q+base)) { throw new IllegalStateException(); } } } else if (op < 5 && !set.isEmpty()) { int rr = r.nextInt(set.size()); var s = set.iterator(); if (rr != 0) { s.skip(rr); } int q = s.nextInt(); s.remove(); if (!h.free(q)) { throw new IllegalStateException(); } } } } } }
1
0.947526
1
0.947526
game-dev
MEDIA
0.353848
game-dev
0.98789
1
0.98789
BlesseNtumble/GalaxySpace
4,041
src/main/java/galaxyspace/core/client/jei/assembler/AssemblerRecipeCategory.java
package galaxyspace.core.client.jei.assembler; import java.util.List; import javax.annotation.Nonnull; import galaxyspace.GalaxySpace; import galaxyspace.core.GSBlocks; import galaxyspace.core.client.jei.GSRecipeCategories; import galaxyspace.core.client.jei.GalaxySpaceJEI; import galaxyspace.core.configs.GSConfigCore; import galaxyspace.core.util.GSConstants; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IDrawableAnimated; import mezz.jei.api.gui.IDrawableStatic; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import mezz.jei.api.recipe.IRecipeWrapper; import micdoodle8.mods.galacticraft.core.util.ConfigManagerCore; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; public class AssemblerRecipeCategory implements IRecipeCategory { @Nonnull private final IDrawable backgroundTop, background, backgroundBottom, slot, blankArrow; @Nonnull private final String localizedName; @Nonnull private final IDrawableAnimated progressBar; public AssemblerRecipeCategory(IGuiHelper guiHelper) { ResourceLocation gui = GSConfigCore.enableModernGUI ? GSConstants.GUI_MACHINE_MODERN : GSConstants.GUI_MACHINE_CLASSIC; this.backgroundTop = guiHelper.createDrawable(gui, 0, 0, 176, 12); this.background = guiHelper.createDrawable(gui, 0, 0, 176, 92); this.backgroundBottom = guiHelper.createDrawable(gui, 0, 31, 176, 30); this.slot = guiHelper.createDrawable(gui, 0, 62, 18, 18); this.blankArrow = guiHelper.createDrawable(gui, 181, 109, 36, 15); this.localizedName = GSBlocks.ASSEMBLER.getLocalizedName();//GCCoreUtil.translate("tile.machine.3.name"); //ResourceLocation resourceLocation, int u, int v, int width, int height IDrawableStatic progressBarDrawable = guiHelper.createDrawable(gui, 181, 125, 36, 16);//guiHelper.createDrawable(compressorTex, 180, 15, 52, 17); this.progressBar = guiHelper.createAnimatedDrawable(progressBarDrawable, 70, IDrawableAnimated.StartDirection.LEFT, false); } @Nonnull @Override public String getUid() { return GSRecipeCategories.ASSEMBLER; } @Nonnull @Override public String getTitle() { return this.localizedName; } @Nonnull @Override public IDrawable getBackground() { return this.background; } @Override public void drawExtras(@Nonnull Minecraft minecraft) { this.backgroundBottom.draw(minecraft, 0, 57); for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) this.slot.draw(minecraft, i * 19 + 10, j * 19 + 20); this.slot.draw(minecraft, 139, 39); this.blankArrow.draw(minecraft, 85, 39); this.progressBar.draw(minecraft, 85, 38); } @Override public void setRecipe(IRecipeLayout recipeLayout, IRecipeWrapper recipeWrapper, IIngredients ingredients) { IGuiItemStackGroup itemstacks = recipeLayout.getItemStacks(); for (int j = 0; j < 9; j++) { itemstacks.init(j, true, j % 3 * 19 + 10, j / 3 * 19 + 20); } itemstacks.init(9, false, 139, 39); if (ConfigManagerCore.quickMode) { List<ItemStack> output = ingredients.getOutputs(ItemStack.class).get(0); ItemStack stackOutput = output.get(0); if (stackOutput.getItem().getTranslationKey(stackOutput).contains("compressed")) { ItemStack stackDoubled = stackOutput.copy(); stackDoubled.setCount(stackOutput.getCount() * 2); output.set(0, stackDoubled); } } itemstacks.set(ingredients); } @Override public String getModName() { return GalaxySpace.NAME; } }
1
0.886732
1
0.886732
game-dev
MEDIA
0.967343
game-dev
0.936918
1
0.936918
EngineHub/CraftBook
9,804
src/main/java/com/sk89q/craftbook/bukkit/commands/TopLevelCommands.java
package com.sk89q.craftbook.bukkit.commands; import java.io.File; import java.io.IOException; import com.sk89q.craftbook.mechanics.headdrops.HeadDropsCommands; import com.sk89q.craftbook.util.ItemSyntax; import com.sk89q.minecraft.util.commands.CommandException; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import com.sk89q.craftbook.bukkit.CraftBookPlugin; import com.sk89q.craftbook.bukkit.ReportWriter; import com.sk89q.craftbook.bukkit.util.CraftBookBukkitUtil; import com.sk89q.craftbook.mechanics.area.AreaCommands; import com.sk89q.craftbook.mechanics.cauldron.CauldronCommands; import com.sk89q.craftbook.mechanics.crafting.RecipeCommands; import com.sk89q.craftbook.mechanics.ic.ICCommands; import com.sk89q.craftbook.mechanics.items.CommandItemCommands; import com.sk89q.craftbook.mechanics.signcopier.SignEditCommands; import com.sk89q.craftbook.mechanics.variables.VariableCommands; import com.sk89q.craftbook.util.PastebinPoster; import com.sk89q.craftbook.util.PastebinPoster.PasteCallback; import com.sk89q.craftbook.util.developer.ExternalUtilityManager; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissionsException; import com.sk89q.minecraft.util.commands.NestedCommand; import org.bukkit.entity.Player; public class TopLevelCommands { public TopLevelCommands(CraftBookPlugin plugin) { } @Command(aliases = {"craftbook", "cb"}, desc = "CraftBook Plugin commands") @NestedCommand(Commands.class) public void craftBookCmds(CommandContext context, CommandSender sender) { } @Command(aliases = {"area", "togglearea"}, desc = "Commands to manage Craftbook Areas") @NestedCommand(AreaCommands.class) public void area(CommandContext context, CommandSender sender) { } @Command(aliases = {"headdrops"}, desc = "Commands to manage Craftbook Head Drops") @NestedCommand(HeadDropsCommands.class) public void headdrops(CommandContext context, CommandSender sender) { } @Command(aliases = {"recp", "recps"}, desc = "Commands to manage Craftbook Custom Recipes") @NestedCommand(RecipeCommands.class) public void recipe(CommandContext context, CommandSender sender) { } @Command(aliases = {"comitems", "commanditems", "citems", "commanditem"}, desc = "Commands to manage Craftbook Command Items") @NestedCommand(CommandItemCommands.class) public void commandItems(CommandContext context, CommandSender sender) { } @Command(aliases = {"cauldron"}, desc = "Commands to manage the Craftbook Cauldron") @NestedCommand(CauldronCommands.class) public void cauldron(CommandContext context, CommandSender sender) { } @Command(aliases = {"sign", "signcopy", "signpaste", "signedit"}, desc = "Commands to manage the Sign Copier") @NestedCommand(SignEditCommands.class) public void signedit(CommandContext context, CommandSender sender) { } @Command(aliases = {"ic", "circuit"}, desc = "Commands to manage Craftbook IC's") @NestedCommand(ICCommands.class) public void icCmd(CommandContext context, CommandSender sender) { } public static class Commands { public Commands(CraftBookPlugin plugin) { } @Command(aliases = {"var"}, desc = "Variable commands") @NestedCommand(VariableCommands.class) public void variableCmds(CommandContext context, CommandSender sender) { } @Command(aliases = "reload", desc = "Reloads the CraftBook Common config") @CommandPermissions("craftbook.reload") public void reload(CommandContext context, CommandSender sender) { try { CraftBookPlugin.inst().reloadConfiguration(); } catch (Throwable e) { CraftBookBukkitUtil.printStacktrace(e); sender.sendMessage("An error occured while reloading the CraftBook config."); return; } sender.sendMessage("The CraftBook config has been reloaded."); } @Command(aliases = "about", desc = "Gives info about craftbook.") public void about(CommandContext context, CommandSender sender) { String ver = CraftBookPlugin.inst().getDescription().getVersion(); if(CraftBookPlugin.getVersion() != null) { ver = CraftBookPlugin.getVersion(); } sender.sendMessage(ChatColor.YELLOW + "CraftBook version " + ver); sender.sendMessage(ChatColor.YELLOW + "Founded by sk89q, and currently developed by Me4502 & Dark_Arc"); } @Command(aliases = {"iteminfo", "itemsyntax"}, desc = "Provides item syntax for held item.") public void itemInfo(CommandContext context, CommandSender sender) throws CommandException { if(!(sender instanceof Player)) { throw new CommandException("Only players can use this command!"); } if (((Player) sender).getInventory().getItemInMainHand() != null) { sender.sendMessage(ChatColor.YELLOW + "Main hand: " + ItemSyntax.getStringFromItem(((Player) sender).getInventory().getItemInMainHand())); } if (((Player) sender).getInventory().getItemInOffHand() != null) { sender.sendMessage(ChatColor.YELLOW + "Off hand: " + ItemSyntax.getStringFromItem(((Player) sender).getInventory().getItemInOffHand())); } } @Command(aliases = {"cbid", "craftbookid"}, desc = "Gets the players CBID.") public void cbid(CommandContext context, CommandSender sender) throws CommandException { if(!(sender instanceof Player)) { throw new CommandException("Only players can use this command!"); } sender.sendMessage("CraftBook ID: " + CraftBookPlugin.inst().wrapPlayer((Player) sender).getCraftBookId()); } @Command(aliases = {"report"}, desc = "Writes a report on CraftBook", flags = "pi", max = 0) @CommandPermissions({"craftbook.report"}) public void report(CommandContext args, final CommandSender sender) throws CommandException { File dest = new File(CraftBookPlugin.inst().getDataFolder(), "report.txt"); ReportWriter report = new ReportWriter(CraftBookPlugin.inst()); if(args.hasFlag('i')) report.appendFlags("i"); report.generate(); try { report.write(dest); sender.sendMessage(ChatColor.YELLOW + "CraftBook report written to " + dest.getAbsolutePath()); } catch (IOException e) { throw new CommandException("Failed to write report: " + e.getMessage()); } if (args.hasFlag('p')) { CraftBookPlugin.inst().checkPermission(sender, "craftbook.report.pastebin"); sender.sendMessage(ChatColor.YELLOW + "Now uploading to Pastebin..."); PastebinPoster.paste(report.toString(), new PasteCallback() { @Override public void handleSuccess(String url) { // Hope we don't have a thread safety issue here sender.sendMessage(ChatColor.YELLOW + "CraftBook report (1 hour): " + url); } @Override public void handleError(String err) { // Hope we don't have a thread safety issue here sender.sendMessage(ChatColor.YELLOW + "CraftBook report pastebin error: " + err); } }); } } @Command(aliases = {"dev"}, desc = "Advanced developer commands") @CommandPermissions({"craftbook.developer"}) public void dev(CommandContext args, final CommandSender sender) throws CommandPermissionsException { if(args.argsLength() > 1 && args.getString(0).equalsIgnoreCase("util")) { try { ExternalUtilityManager.performExternalUtility(args.getString(1), args.getSlice(1)); sender.sendMessage(ChatColor.YELLOW + "Performed utility successfully!"); } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Failed to perform utility: See console for details!"); } } } @Command(aliases = {"enable"}, desc = "Enable a mechanic") @CommandPermissions({"craftbook.enable-mechanic"}) public void enable(CommandContext args, final CommandSender sender) throws CommandPermissionsException { if(args.argsLength() > 0) { if(CraftBookPlugin.inst().enableMechanic(args.getString(0))) sender.sendMessage(ChatColor.YELLOW + "Sucessfully enabled " + args.getString(0)); else sender.sendMessage(ChatColor.RED + "Failed to load " + args.getString(0)); } } @Command(aliases = {"disable"}, desc = "Disable a mechanic") @CommandPermissions({"craftbook.disable-mechanic"}) public void disable(CommandContext args, final CommandSender sender) throws CommandPermissionsException { if(args.argsLength() > 0) { if(CraftBookPlugin.inst().disableMechanic(args.getString(0))) sender.sendMessage(ChatColor.YELLOW + "Sucessfully disabled " + args.getString(0)); else sender.sendMessage(ChatColor.RED + "Failed to remove " + args.getString(0)); } } } }
1
0.903559
1
0.903559
game-dev
MEDIA
0.925619
game-dev
0.969572
1
0.969572
localcc/PalworldModdingKit
5,655
Source/Pal/Public/PalLoggedinPlayerSaveDataRecordData.h
#pragma once #include "CoreMinimal.h" #include "UObject/NoExportTypes.h" #include "PalPlayerSaveDataRecordDataFoundTreasureMapPoint.h" #include "PalLoggedinPlayerSaveDataRecordData.generated.h" USTRUCT(BlueprintType) struct FPalLoggedinPlayerSaveDataRecordData { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> TowerBossDefeatFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> TowerBossDefeatCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> NormalBossDefeatFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> RaidBossDefeatCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> SpecificBossDefeatFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 BossDefeatCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 PredatorDefeatCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 TribeCaptureCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> PalCaptureCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> PalCaptureBonusCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> PalButcherCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> PaldeckUnlockFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 PalCaptureCountBonusCount_Tier1; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 PalCaptureCountBonusCount_Tier2; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 PalCaptureCountBonusCount_Tier3; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 PalCaptureBonusExpTableIndex; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 NpcBonusExpTableIndex; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> RelicObtainForInstanceFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 RelicPossessNum; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> NoteObtainForInstanceFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> NPCTalkIdCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> FastTravelPointUnlockFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TArray<FGuid> BuildingObjectMapObjectInstanceIds; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> CraftItemCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 NormalDungeonClearCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 FixedDungeonClearCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 OilrigClearCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> PalRankupCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> FindAreaFlagMap; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 AreaBonusExpTableIndex; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> ArenaSoloClearCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TArray<FGuid> CompletedEmoteNPCIDArray; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> NPCTalkCountMap; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> InvokeNPCNetworkEventMap; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FGuid, FPalPlayerSaveDataRecordDataFoundTreasureMapPoint> FoundTreasureMapPointMap; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, int32> FishingCountMap; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 CampConqueredCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 FoundTreasureCount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> NpcItemTradeFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> PalDisplayNPCDataTableProgress; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<FName, bool> NPCAchivementRewardFlag; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bFirstFishingComplete; PAL_API FPalLoggedinPlayerSaveDataRecordData(); };
1
0.888138
1
0.888138
game-dev
MEDIA
0.898521
game-dev
0.688846
1
0.688846
BrowserBox/BrowserBox
8,789
client/dino.js
import termkit from 'terminal-kit'; import { spawn } from 'child_process'; import { promises as fs } from 'fs'; import path from 'path'; import os from 'os'; const term = termkit.terminal; // Map color names to terminal-kit color methods const colorMap = { blue: term.blue, magenta: term.magenta, green: term.green, darkGreen: term.green, // terminal-kit doesn't have a direct darkGreen, so we'll use green yellow: term.yellow, gray: term.gray, white: term.white, brightWhite: term.brightWhite, red: term.red }; // High score file path const highScoreDir = path.join(os.homedir(), '.config', 'dosaygo', 'kernel'); const highScoreFile = path.join(highScoreDir, 'dino.score'); // Load high score from file async function loadHighScore() { try { await fs.mkdir(highScoreDir, { recursive: true }); // Create directory if it doesn't exist const data = await fs.readFile(highScoreFile, 'utf8'); const json = JSON.parse(data); return json.highScore || 0; } catch (err) { if (err.code === 'ENOENT') return 0; // File doesn't exist, start with 0 console.error('Error loading high score:', err); return 0; } } // Save high score to file async function saveHighScore(highScore) { try { await fs.mkdir(highScoreDir, { recursive: true }); // Create directory if it doesn't exist await fs.writeFile(highScoreFile, JSON.stringify({ highScore }), 'utf8'); } catch (err) { console.error('Error saving high score:', err); } } export async function dinoGame(onExit, {noCap = true} = {}) { // Initialize terminal term.fullscreen(true); term.windowTitle('Dino Game'); term.clear(); if (!noCap) { term.grabInput({ mouse: 'button' }); } // Spawn boop.js for sound effects const soundProcess = spawn('node', ['boop.js'], { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'], windowsHide: true }); soundProcess.unref(); // Game state const groundY = term.height - 5; let dinoY = groundY; const jumpHeight = 15; const superJumpHeight = jumpHeight * 2; let isJumping = false; let isFalling = false; let jumpFrame = 0; let jumpStartY = groundY; let currentJumpHeight = jumpHeight; let currentJumpDuration = 24; const jumpDuration = 24; const superJumpDuration = 32; const fallSpeed = 1; let hasSuperJumped = false; let cacti = []; let score = 0; let highScore = await loadHighScore(); let gameOver = false; let frameCount = 0; const baseFrameRate = 30; let speed = 1; let dinoFrameIndex = 0; // For sprite animation const animationSpeed = 3; // Switch frames every 5 ticks // Ground texture let groundTexture = Array(term.width).fill('').map(() => { const rand = Math.random(); return rand < 0.2 ? '.' : rand < 0.4 ? ',' : rand < 0.6 ? '-' : '_'; }); let groundOffset = 0; // Parallax clouds const clouds = [ { x: 20, y: 3, speed: 0.2, symbol: '☁', color: 'gray' }, { x: 40, y: 5, speed: 0.5, symbol: '☁', color: 'white' }, { x: 60, y: 7, speed: 0.8, symbol: '☁', color: 'brightWhite' } ]; // Dino sprite with animation frames const dinoFrames = [ // Frame 1: Forward leg stride [ ' ○▓ ', // Head with eye ' ▓* ', // Scale detail '██▓▓█ ', // Sleek body ' ▓ ', ' ▒ ', // Back leg forward ' ░ ' // Front leg extended ], // Frame 2: Backward leg stride [ ' ○▓ ', ' ▓* ', '██▓▓█ ', ' ▓ ', ' ▒ ', // Back leg back ' ░ ' // Front leg retracted ], // Frame 3: Mid-stride [ ' ○▓ ', ' ▓* ', '██▓▓█ ', ' ▓ ', ' ▒ ▒ ', // Legs even ' ' // Clean ground ] ]; // Cactus sprite base const cactusBase = [ ' █ ', ' █ ', '███ ', ' █ ', ' █ ' ]; // Game loop const gameFrame = () => { if (gameOver) return; term.clear(); speed = 1 + frameCount * 0.001; groundOffset = (groundOffset + speed) % term.width; const shiftedTexture = [...groundTexture.slice(Math.round(groundOffset)), ...groundTexture.slice(0, Math.round(groundOffset))]; // Update Dino position if (isJumping) { let progress = jumpFrame / currentJumpDuration; let height = 4 * currentJumpHeight * progress * (1 - progress); dinoY = Math.max(1, jumpStartY - height); jumpFrame++; if (jumpFrame >= currentJumpDuration) { isJumping = false; if (dinoY > groundY) { isFalling = true; } else { dinoY = groundY; currentJumpHeight = jumpHeight; currentJumpDuration = jumpDuration; hasSuperJumped = false; } } } else if (isFalling) { dinoY += fallSpeed * speed; if (dinoY >= groundY) { dinoY = groundY; isFalling = false; currentJumpHeight = jumpHeight; currentJumpDuration = jumpDuration; hasSuperJumped = false; } } // Update clouds clouds.forEach(cloud => { cloud.x -= cloud.speed * speed; if (cloud.x < -5) cloud.x = term.width + 5; }); // Spawn cacti if (frameCount % (Math.floor(Math.random() * 40) + 20) === 0) { const height = Math.floor(Math.random() * 5) + 3; const cactusSprite = cactusBase.slice(-height); cacti.push({ x: term.width - 1, sprite: cactusSprite }); } // Update cacti cacti = cacti.map(c => ({ x: c.x - 1.5 * speed, sprite: c.sprite })).filter(c => c.x >= -5); // Collision detection const dinoX = 11; const dinoBottom = dinoY; for (const cactus of cacti) { if (cactus.x >= dinoX && cactus.x <= dinoX + 4) { if (dinoBottom >= groundY - cactus.sprite.length + 1) { clearInterval(gameLoop); saveHighScore(highScore); soundProcess.send('gameOver'); gameFrame(); gameOver = true; term.moveTo(Math.floor(term.width / 2) - 5, Math.floor(term.height / 2)); term.red('Game Over'); term.moveTo(1, term.height - 1); term.white('Press R to restart, Q to quit'); return; } } } score += speed * 0.1; highScore = Math.max(highScore, Math.floor(score)); // Drawing clouds.forEach(cloud => { term.moveTo(Math.round(cloud.x), cloud.y); colorMap[cloud.color](cloud.symbol); }); term.moveTo(1, groundY + 1); term.gray(shiftedTexture.join('')); const currentDino = dinoFrames[dinoFrameIndex]; currentDino.forEach((line, index) => { term.moveTo(dinoX, Math.round(dinoY) - currentDino.length + 1 + index); const color = index % 2 === 0 ? colorMap.blue : colorMap.magenta; color(line); }); cacti.forEach(c => { c.sprite.forEach((line, index) => { term.moveTo(Math.round(c.x), groundY - c.sprite.length + 1 + index); const colorName = index % 3 === 0 ? 'green' : index % 3 === 1 ? 'darkGreen' : 'yellow'; colorMap[colorName](line); }); }); term.moveTo(term.width - 20, 1); term.white(`HI ${highScore.toString().padStart(5, '0')} ${Math.floor(score).toString().padStart(5, '0')}`); // Update animation frame if (!isJumping && !isFalling) { if (frameCount % animationSpeed === 0) { dinoFrameIndex = (dinoFrameIndex + 1) % dinoFrames.length; } } else { dinoFrameIndex = 2; // Mid-stride for jumping } frameCount++; }; const gameLoop = setInterval(gameFrame, 1000 / baseFrameRate); // Handle input return new Promise(resolve => { term.on('key', (key) => { if (gameOver) { if (key === 'r' || key === 'R') { // Restart the game term.clear(); resolve(dinoGame(onExit)); } else if (key === 'q' || key === 'Q' || key === 'CTRL_C') { // Quit and return to browser soundProcess.kill(); clearInterval(gameLoop); term.clear(); term.off('key'); // Remove game-specific key handler if (onExit) onExit(); resolve(); } return; } if (key === ' ') { if (!isJumping && !isFalling) { isJumping = true; jumpFrame = 0; currentJumpHeight = jumpHeight; currentJumpDuration = jumpDuration; jumpStartY = groundY; soundProcess.send('jump'); } else if (isJumping && !hasSuperJumped) { isJumping = true; jumpFrame = 0; currentJumpHeight = superJumpHeight; currentJumpDuration = superJumpDuration; jumpStartY = dinoY; hasSuperJumped = true; soundProcess.send('jump'); } } }); }); } //dinoGame(() => process.exit(0), {noCap: false});
1
0.70854
1
0.70854
game-dev
MEDIA
0.693253
game-dev
0.97526
1
0.97526
CloudburstMC/Nukkit
1,277
src/main/java/cn/nukkit/inventory/FurnaceInventory.java
package cn.nukkit.inventory; import cn.nukkit.blockentity.BlockEntityFurnace; import cn.nukkit.item.Item; /** * @author MagicDroidX * Nukkit Project */ public class FurnaceInventory extends ContainerInventory { public FurnaceInventory(BlockEntityFurnace furnace) { super(furnace, InventoryType.FURNACE); } public FurnaceInventory(BlockEntityFurnace furnace, InventoryType type) { super(furnace, type); // For blast furnace } @Override public BlockEntityFurnace getHolder() { return (BlockEntityFurnace) this.holder; } public Item getResult() { return this.getItem(2); } public Item getFuel() { return this.getItem(1); } public Item getSmelting() { return this.getItem(0); } public boolean setResult(Item item) { return this.setItem(2, item); } public boolean setFuel(Item item) { return this.setItem(1, item); } public boolean setSmelting(Item item) { return this.setItem(0, item); } @Override public void onSlotChange(int index, Item before, boolean send) { super.onSlotChange(index, before, send); this.getHolder().scheduleUpdate(); this.getHolder().chunk.setChanged(); } }
1
0.863775
1
0.863775
game-dev
MEDIA
0.985984
game-dev
0.645979
1
0.645979
miniwebkit/src
2,541
WebCore/plugins/MimeTypeArray.cpp
/* * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2008 Apple 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 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "MimeTypeArray.h" #include "AtomicString.h" #include "Frame.h" #include "Page.h" #include "Plugin.h" #include "PluginData.h" namespace WebCore { MimeTypeArray::MimeTypeArray(Frame* frame) : m_frame(frame) { } MimeTypeArray::~MimeTypeArray() { } unsigned MimeTypeArray::length() const { PluginData* data = getPluginData(); if (!data) return 0; return data->mimes().size(); } PassRefPtr<MimeType> MimeTypeArray::item(unsigned index) { PluginData* data = getPluginData(); if (!data) return 0; const Vector<MimeClassInfo*>& mimes = data->mimes(); if (index >= mimes.size()) return 0; return MimeType::create(data, index).get(); } bool MimeTypeArray::canGetItemsForName(const AtomicString& propertyName) { PluginData *data = getPluginData(); if (!data) return 0; const Vector<MimeClassInfo*>& mimes = data->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) { if (mimes[i]->type == propertyName) return true; } return false; } PassRefPtr<MimeType> MimeTypeArray::namedItem(const AtomicString& propertyName) { PluginData *data = getPluginData(); if (!data) return 0; const Vector<MimeClassInfo*>& mimes = data->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) { if (mimes[i]->type == propertyName) return MimeType::create(data, i).get(); } return 0; } PluginData* MimeTypeArray::getPluginData() const { if (!m_frame) return 0; Page* p = m_frame->page(); if (!p) return 0; return p->pluginData(); } } // namespace WebCore
1
0.559993
1
0.559993
game-dev
MEDIA
0.209406
game-dev
0.512851
1
0.512851
7oSkaaa/LeetCode_DailyChallenge_2023
1,787
05- May/04- Dota2 Senate/04- Dota2 Senate (Omar Sanad).cpp
// author : Omar Sanad // In this problem, very simple, in each turn of R ((If not banned)), he has to ban the first D he encounters. // in each turn of D ((If not banned)), he has to ban the first R he encounters. class Solution { public: string predictPartyVictory(string senate) { // declare two queues one for the letter R and the other for the letter D queue < int > RR, DD; // push the indecies of the two letters in the queue, to know the turns of each person for (int i = 0; i < senate.size(); i++) if (senate[i] == 'D') DD.push(i); else RR.push(i); // declare a timer variable to know whose turn is it now.... int currTimer = senate.size(); // iterate untill one party is out of people while (RR.size() and DD.size()) { // if it is the R turn, then he will ban the first D he encounters if (RR.front() < DD.front()) { RR.push(++currTimer); // we will add this person at the last. RR.pop(); // then remove him from the front DD.pop(); // we will remove this banned person of the D party } // else if it is the D turn, then he will ban the first R he encounters else{ DD.push(++currTimer); // we will add this person at the last. DD.pop(); // then remove him from the front. RR.pop(); // we will remove this banned person of the R party } } // if all the remaining not banned people are from D party return "Dire" // else if they are from R party return "Radiant" return DD.size() ? "Dire" : "Radiant"; } };
1
0.692039
1
0.692039
game-dev
MEDIA
0.59509
game-dev
0.864408
1
0.864408
ChaoticOnyx/OnyxBay
10,549
code/game/objects/effects/spiders.dm
//generic procs copied from obj/effect/alien /obj/structure/spider name = "web" desc = "It's stringy and sticky." icon = 'icons/effects/effects.dmi' anchored = 1 density = 0 var/health = 15 //similar to weeds, but only barfed out by nurses manually /obj/structure/spider/ex_act(severity) switch(severity) if(1.0) qdel(src) if(2.0) if (prob(50)) qdel(src) if(3.0) if (prob(5)) qdel(src) return /obj/structure/spider/attackby(obj/item/W, mob/user) user.setClickCooldown(DEFAULT_ATTACK_COOLDOWN) if(W.attack_verb.len) visible_message("<span class='warning'>\The [src] have been [pick(W.attack_verb)] with \the [W][(user ? " by [user]." : ".")]</span>") else visible_message("<span class='warning'>\The [src] have been attacked with \the [W][(user ? " by [user]." : ".")]</span>") var/damage = W.force / 4.0 if(isWelder(W)) var/obj/item/weldingtool/WT = W if(WT.use_tool(src, user, amount = 10)) damage = 15 health -= damage healthcheck() /obj/structure/spider/bullet_act(obj/item/projectile/Proj) ..() health -= Proj.get_structure_damage() healthcheck() /obj/structure/spider/proc/healthcheck() if(health <= 0) qdel(src) /obj/structure/spider/fire_act(datum/gas_mixture/air, exposed_temperature, exposed_volume) if(exposed_temperature > (300 CELSIUS)) health -= 5 healthcheck() /obj/structure/spider/stickyweb icon_state = "stickyweb1" ///Whether or not the web is a sealed web var/sealed = FALSE /obj/structure/spider/stickyweb/Initialize() . = ..() if(prob(50)) icon_state = "stickyweb2" /obj/structure/spider/stickyweb/sealed name = "sealed web" desc = "A solid thick wall of web, airtight enough to block air flow." icon_state = "sealedweb" sealed = TRUE can_atmos_pass = ATMOS_PASS_NO density = TRUE opacity = TRUE /obj/structure/spider/stickyweb/sealed/attack_generic(mob/user, damage, attack_verb, wallbreaker) if(istype (user, /mob/living/simple_animal/hostile/giant_spider)) user.visible_message(SPAN_WARNING("[user] begins to claw through the [src]!"), "You begin to claw through the [src].") if(do_after(user, 50, target = src, , luck_check_type = LUCK_CHECK_COMBAT)) user.visible_message(SPAN_WARNING("[user] ruptures [src] open!"), "You succesfully claw through the [src].") health = 0 healthcheck () return return ..() /obj/structure/spider/stickyweb/CanPass(atom/movable/mover, turf/target) if(sealed) return FALSE if(istype(mover, /mob/living/simple_animal/hostile/giant_spider)) return TRUE else if(istype(mover, /mob/living)) if(istype(mover.pulledby, /mob/living/simple_animal/hostile/giant_spider)) return TRUE if(prob(70)) to_chat(mover, "<span class='warning'>You get stuck in \the [src] for a moment.</span>") return FALSE return TRUE else if(istype(mover, /obj/item/projectile)) return prob(30) /obj/structure/spider/spiderling name = "spiderling" desc = "It never stays still for long." icon_state = "guard" anchored = 0 layer = BELOW_OBJ_LAYER health = 3 var/mob/living/simple_animal/hostile/giant_spider/greater_form var/last_itch = 0 var/amount_grown = -1 var/obj/machinery/atmospherics/unary/vent_pump/entry_vent var/travelling_in_vent = 0 var/dormant = FALSE // If dormant, does not add the spiderling to the process list unless it's also growing var/growth_chance = 50 // % chance of beginning growth, and eventually become a beautiful death machine var/directive = "" //Message from the mother var/faction = "spiders" var/shift_range = 6 /obj/structure/spider/spiderling/Initialize(mapload, atom/parent) . = ..() pixel_x = rand(-shift_range, shift_range) pixel_y = rand(-shift_range, shift_range) if(prob(growth_chance)) amount_grown = 1 dormant = FALSE if(dormant) register_signal(src, SIGNAL_MOVED, nameof(.proc/disturbed)) else set_next_think(world.time) get_light_and_color(parent) /obj/structure/spider/spiderling/hunter greater_form = /mob/living/simple_animal/hostile/giant_spider/hunter icon_state = "hunter" /obj/structure/spider/spiderling/nurse greater_form = /mob/living/simple_animal/hostile/giant_spider/nurse icon_state = "nurse" /obj/structure/spider/spiderling/midwife greater_form = /mob/living/simple_animal/hostile/giant_spider/midwife icon_state = "hunter" /obj/structure/spider/spiderling/viper greater_form = /mob/living/simple_animal/hostile/giant_spider/viper icon_state = "hunter" /obj/structure/spider/spiderling/tarantula greater_form = /mob/living/simple_animal/hostile/giant_spider/tarantula /obj/structure/spider/spiderling/mundane growth_chance = 0 // Just a simple, non-mutant spider greater_form = /mob/living/simple_animal/hostile/giant_spider /obj/structure/spider/spiderling/mundane/dormant dormant = TRUE // It lies in wait, hoping you will walk face first into its web /obj/structure/spider/spiderling/Destroy() if(dormant) unregister_signal(src, SIGNAL_MOVED) . = ..() /obj/structure/spider/spiderling/attackby(obj/item/W, mob/user) ..() if(health > 0) disturbed() /obj/structure/spider/spiderling/Crossed(mob/living/L) if(dormant && istype(L) && L.mob_size > MOB_TINY) disturbed() /obj/structure/spider/spiderling/proc/disturbed() if(!dormant) return dormant = FALSE unregister_signal(src, SIGNAL_MOVED) set_next_think(world.time) /obj/structure/spider/spiderling/Bump(atom/user) if(istype(user, /obj/structure/table)) forceMove(user.loc) else ..() /obj/structure/spider/spiderling/proc/die() visible_message("<span class='alert'>[src] dies!</span>") new /obj/effect/decal/cleanable/spiderling_remains(loc) qdel(src) /obj/structure/spider/spiderling/healthcheck() if(health <= 0) die() /obj/structure/spider/spiderling/think() if(travelling_in_vent) if(istype(src.loc, /turf)) travelling_in_vent = 0 entry_vent = null else if(entry_vent) if(get_dist(src, entry_vent) <= 1) if(entry_vent.network && entry_vent.network.normal_members.len) var/list/vents = list() for(var/obj/machinery/atmospherics/unary/vent_pump/temp_vent in entry_vent.network.normal_members) vents.Add(temp_vent) if(!vents.len) entry_vent = null set_next_think(world.time + 1 SECOND) return var/obj/machinery/atmospherics/unary/vent_pump/exit_vent = pick(vents) /*if(prob(50)) src.visible_message("<B>[src] scrambles into the ventillation ducts!</B>")*/ spawn(rand(20,60)) forceMove(exit_vent) var/travel_time = round(get_dist(loc, exit_vent.loc) / 2) spawn(travel_time) if(!exit_vent || exit_vent.welded) forceMove(entry_vent) entry_vent = null set_next_think(world.time + 1 SECOND) return if(prob(50)) var/msg = SPAN("notice", "You hear something squeezing through the ventilation ducts.") visible_message(msg, msg) sleep(travel_time) if(!exit_vent || exit_vent.welded) forceMove(entry_vent) entry_vent = null set_next_think(world.time + 1 SECOND) return forceMove(exit_vent.loc) entry_vent = null var/area/new_area = get_area(loc) if(new_area) new_area.Entered(src) else entry_vent = null //================= else if(prob(33)) var/list/nearby = oview(10, src) if(nearby.len) var/target_atom = pick(nearby) walk_to(src, target_atom, 5) if(prob(40)) src.visible_message(SPAN_NOTICE("\The [src] skitters[pick(" away"," around","")].")) else if(prob(10)) //vent crawl! for(var/obj/machinery/atmospherics/unary/vent_pump/v in view(7,src)) if(!v.welded) entry_vent = v walk_to(src, entry_vent, 5) break if(isturf(loc)) if(amount_grown >= 100) if(!greater_form) if(prob(3)) greater_form = pick(/mob/living/simple_animal/hostile/giant_spider/tarantula, /mob/living/simple_animal/hostile/giant_spider/viper, /mob/living/simple_animal/hostile/giant_spider/midwife) else greater_form = pick(/mob/living/simple_animal/hostile/giant_spider, /mob/living/simple_animal/hostile/giant_spider/hunter, /mob/living/simple_animal/hostile/giant_spider/nurse) var/mob/living/simple_animal/hostile/giant_spider/S = new greater_form(src.loc) notify_ghosts("[capitalize(S.name)] is now available to possess!", source = S, action = NOTIFY_POSSES, posses_mob = TRUE) S.faction = faction S.directive = directive qdel(src) return else if(isorgan(loc)) if(!amount_grown) amount_grown = 1 var/obj/item/organ/external/O = loc if(!O.owner || O.owner.is_ic_dead() || amount_grown > 80) amount_grown = 20 //reset amount_grown so that people have some time to react to spiderlings before they grow big O.implants -= src forceMove(O.owner ? O.owner.loc : O.loc) visible_message("<span class='warning'>\A [src] emerges from inside [O.owner ? "[O.owner]'s [O.name]" : "\the [O]"]!</span>") if(O.owner) O.owner.apply_damage(1, BRUTE, O.organ_tag) else if(prob(1)) O.owner.apply_damage(5, TOX, O.organ_tag) if(world.time > last_itch + 30 SECONDS) last_itch = world.time to_chat(O.owner, "<span class='notice'>Your [O.name] itches...</span>") else if(prob(1)) src.visible_message("<span class='notice'>\The [src] skitters.</span>") if(amount_grown > 0) amount_grown += rand(0,2) set_next_think(world.time + 1 SECOND) /obj/effect/decal/cleanable/spiderling_remains name = "spiderling remains" desc = "Green squishy mess." icon = 'icons/effects/effects.dmi' icon_state = "greenshatter" anchored = 1 layer = BLOOD_LAYER /obj/structure/spider/cocoon name = "cocoon" desc = "Something wrapped in silky spider web." icon_state = "cocoon1" health = 60 /obj/structure/spider/cocoon/Initialize() . = ..() icon_state = pick("cocoon1", "cocoon2", "cocoon3") /obj/structure/spider/cocoon/proc/mob_breakout(mob/living/user)// For God's sake, don't make it a closet var/breakout_time = 600 user.last_special = world.time + 100 to_chat(user, SPAN_NOTICE("You struggle against the tight bonds... (This will take about [time2text(breakout_time)].)")) visible_message(SPAN_NOTICE("You see something struggling and writhing in \the [src]!")) if(do_after(user,(breakout_time), target = src, luck_check_type = LUCK_CHECK_COMBAT)) if(!user || user.stat != CONSCIOUS || user.loc != src) return qdel(src) /obj/structure/spider/cocoon/Destroy() var/turf/T = get_turf(src) src.visible_message(SPAN_WARNING("\The [src] splits open.")) for(var/atom/movable/A in contents) A.forceMove(T) return ..()
1
0.971508
1
0.971508
game-dev
MEDIA
0.655859
game-dev
0.99617
1
0.99617
magefree/mage
5,944
Mage/src/main/java/mage/abilities/keyword/ImpendingAbility.java
package mage.abilities.keyword; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.condition.Condition; import mage.abilities.condition.common.SourceHasCounterCondition; import mage.abilities.costs.AlternativeSourceCostsImpl; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.decorator.ConditionalOneShotEffect; import mage.abilities.effects.ContinuousEffectImpl; import mage.abilities.effects.common.AddContinuousEffectToGame; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.effects.common.counter.RemoveCounterSourceEffect; import mage.abilities.triggers.BeginningOfEndStepTriggeredAbility; import mage.constants.*; import mage.counters.CounterType; import mage.game.Game; import mage.game.permanent.Permanent; import mage.util.CardUtil; import java.util.stream.Collectors; /** * "Impending N–[cost]" is a keyword that represents multiple abilities. * The official rules are as follows: * (a) You may choose to pay [cost] rather than pay this spell's mana cost. * (b) If you chose to pay this spell's impending cost, it enters the battlefield with N time counters on it. * (c) As long as this permanent has a time counter on it, if it was cast for its impending cost, it's not a creature. * (d) At the beginning of your end step, if this permanent was cast for its impending cost, remove a time counter from it. Then if it has no time counters on it, it loses impending. * * @author TheElk801 */ public class ImpendingAbility extends AlternativeSourceCostsImpl { private static final String IMPENDING_KEYWORD = "Impending"; private static final String IMPENDING_REMINDER = "If you cast this spell for its impending cost, " + "it enters with %s time counters and isn't a creature until the last is removed. " + "At the beginning of your end step, remove a time counter from it."; private static final Condition counterCondition = new SourceHasCounterCondition(CounterType.TIME, ComparisonType.EQUAL_TO, 0); public ImpendingAbility(int amount, String manaString) { super(IMPENDING_KEYWORD + ' ' + amount, String.format(IMPENDING_REMINDER, CardUtil.numberToText(amount)), new ManaCostsImpl<>(manaString), IMPENDING_KEYWORD); this.setRuleAtTheTop(true); this.addSubAbility(new EntersBattlefieldAbility(new ConditionalOneShotEffect( new AddCountersSourceEffect(CounterType.TIME.createInstance(amount)), ImpendingCondition.instance, "" ), "").setRuleVisible(false)); this.addSubAbility(new SimpleStaticAbility(new ImpendingAbilityTypeEffect()).setRuleVisible(false)); Ability ability = new BeginningOfEndStepTriggeredAbility( TargetController.YOU, new RemoveCounterSourceEffect(CounterType.TIME.createInstance()), false, ImpendingCondition.instance ); ability.addEffect(new ConditionalOneShotEffect( new AddContinuousEffectToGame(new ImpendingAbilityRemoveEffect()), counterCondition, "Then if it has no time counters on it, it loses impending" )); this.addSubAbility(ability.setRuleVisible(false)); } private ImpendingAbility(final ImpendingAbility ability) { super(ability); } @Override public ImpendingAbility copy() { return new ImpendingAbility(this); } public static String getActivationKey() { return getActivationKey(IMPENDING_KEYWORD); } } enum ImpendingCondition implements Condition { instance; @Override public boolean apply(Game game, Ability source) { return CardUtil.checkSourceCostsTagExists(game, source, ImpendingAbility.getActivationKey()); } } class ImpendingAbilityTypeEffect extends ContinuousEffectImpl { ImpendingAbilityTypeEffect() { super(Duration.WhileOnBattlefield, Layer.TypeChangingEffects_4, SubLayer.NA, Outcome.Detriment); staticText = "As long as this permanent has a time counter on it, if it was cast for its impending cost, it's not a creature."; } private ImpendingAbilityTypeEffect(final ImpendingAbilityTypeEffect effect) { super(effect); } @Override public ImpendingAbilityTypeEffect copy() { return new ImpendingAbilityTypeEffect(this); } @Override public boolean apply(Game game, Ability source) { if (!ImpendingCondition.instance.apply(game, source)) { return false; } Permanent permanent = source.getSourcePermanentIfItStillExists(game); if (permanent.getCounters(game).getCount(CounterType.TIME) < 1) { return false; } permanent.removeCardType(game, CardType.CREATURE); permanent.removeAllCreatureTypes(game); return true; } } class ImpendingAbilityRemoveEffect extends ContinuousEffectImpl { ImpendingAbilityRemoveEffect() { super(Duration.Custom, Layer.AbilityAddingRemovingEffects_6, SubLayer.NA, Outcome.LoseAbility); } private ImpendingAbilityRemoveEffect(final ImpendingAbilityRemoveEffect effect) { super(effect); } @Override public ImpendingAbilityRemoveEffect copy() { return new ImpendingAbilityRemoveEffect(this); } @Override public boolean apply(Game game, Ability source) { Permanent permanent = source.getSourcePermanentIfItStillExists(game); if (permanent == null) { discard(); return false; } permanent.removeAbilities( permanent .getAbilities(game) .stream() .filter(ImpendingAbility.class::isInstance) .collect(Collectors.toList()), source.getSourceId(), game ); return true; } }
1
0.981094
1
0.981094
game-dev
MEDIA
0.836645
game-dev
0.998909
1
0.998909
FashionFreedom/Seamly2D
5,127
src/libs/xerces-c/msvc/include/xercesc/validators/schema/identity/FieldActivator.hpp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ #if !defined(XERCESC_INCLUDE_GUARD_FIELDACTIVATOR_HPP) #define XERCESC_INCLUDE_GUARD_FIELDACTIVATOR_HPP /** * This class is responsible for activating fields within a specific scope; * the caller merely requests the fields to be activated. */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/ValueHashTableOf.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Forward Declaration // --------------------------------------------------------------------------- class IdentityConstraint; class XPathMatcher; class ValueStoreCache; class IC_Field; class XPathMatcherStack; class VALIDATORS_EXPORT FieldActivator : public XMemory { public: // ----------------------------------------------------------------------- // Constructors/Destructor // ----------------------------------------------------------------------- FieldActivator(ValueStoreCache* const valueStoreCache, XPathMatcherStack* const matcherStack, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); FieldActivator(const FieldActivator& other); ~FieldActivator(); // ----------------------------------------------------------------------- // Operator methods // ----------------------------------------------------------------------- FieldActivator& operator =(const FieldActivator& other); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- bool getMayMatch(IC_Field* const field); // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- void setValueStoreCache(ValueStoreCache* const other); void setMatcherStack(XPathMatcherStack* const matcherStack); void setMayMatch(IC_Field* const field, bool value); // ----------------------------------------------------------------------- // Activation methods // ----------------------------------------------------------------------- /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. */ void startValueScopeFor(const IdentityConstraint* const ic, const int initialDepth); /** * Request to activate the specified field. This method returns the * matcher for the field. */ XPathMatcher* activateField(IC_Field* const field, const int initialDepth); /** * Ends the value scope for the specified identity constraint. */ void endValueScopeFor(const IdentityConstraint* const ic, const int initialDepth); private: // ----------------------------------------------------------------------- // Data // ----------------------------------------------------------------------- ValueStoreCache* fValueStoreCache; XPathMatcherStack* fMatcherStack; ValueHashTableOf<bool, PtrHasher>* fMayMatch; MemoryManager* fMemoryManager; }; // --------------------------------------------------------------------------- // FieldActivator: Getter methods // --------------------------------------------------------------------------- inline bool FieldActivator::getMayMatch(IC_Field* const field) { return fMayMatch->get(field); } // --------------------------------------------------------------------------- // FieldActivator: Setter methods // --------------------------------------------------------------------------- inline void FieldActivator::setValueStoreCache(ValueStoreCache* const other) { fValueStoreCache = other; } inline void FieldActivator::setMatcherStack(XPathMatcherStack* const matcherStack) { fMatcherStack = matcherStack; } inline void FieldActivator::setMayMatch(IC_Field* const field, bool value) { fMayMatch->put(field, value); } XERCES_CPP_NAMESPACE_END #endif /** * End of file FieldActivator.hpp */
1
0.784223
1
0.784223
game-dev
MEDIA
0.566652
game-dev
0.814777
1
0.814777
gecube/opencaesar3
1,343
source/game/gamedate.cpp
// This file is part of openCaesar3. // // openCaesar3 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. // // openCaesar3 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 openCaesar3. If not, see <http://www.gnu.org/licenses/>. #include "gamedate.hpp" class GameDate::Impl { public: DateTime lastDateUpdate; DateTime current; }; DateTime GameDate::current() { return instance()._d->current; } GameDate& GameDate::instance() { static GameDate inst; return inst; } void GameDate::timeStep( unsigned int time ) { if( time % 110 == 1 ) { // every X seconds GameDate& inst = instance(); inst._d->current.appendMonth( 1 ); } } void GameDate::init( const DateTime& date ) { instance()._d->current = date; instance()._d->lastDateUpdate = date; } GameDate::GameDate() : _d( new Impl ) { _d->current = DateTime( -350, 0, 0 ); } GameDate::~GameDate() { }
1
0.788316
1
0.788316
game-dev
MEDIA
0.658664
game-dev
0.617217
1
0.617217
ElsevierSoftwareX/SOFTX_2018_143
9,999
OpenFOAM/src/dynamicMesh/polyTopoChange/polyTopoChange/addObject/polyAddFace.H
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2015 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::polyAddFace Description A face addition data class. A face can be inflated either from a point or from another face and can either be in internal or a boundary face. \*---------------------------------------------------------------------------*/ #ifndef polyAddFace_H #define polyAddFace_H // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "label.H" #include "face.H" #include "topoAction.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class polyAddFace Declaration \*---------------------------------------------------------------------------*/ class polyAddFace : public topoAction { // Private data //- Face identifier face face_; //- Face owner label owner_; //- Face neighbour label neighbour_; //- Master point ID for faces blown up from points label masterPointID_; //- Master edge ID for faces blown up from edges label masterEdgeID_; //- Master face ID for faces blown up from faces label masterFaceID_; //- Does the face flux need to be flipped bool flipFaceFlux_; //- Boundary patch ID label patchID_; //- Face zone ID label zoneID_; //- Face zone flip bool zoneFlip_; public: // Static data members //- Runtime type information TypeName("addFace"); // Constructors //- Construct null. Used for constructing lists polyAddFace() : face_(0), owner_(-1), neighbour_(-1), masterPointID_(-1), masterEdgeID_(-1), masterFaceID_(-1), flipFaceFlux_(false), patchID_(-1), zoneID_(-1), zoneFlip_(false) {} //- Construct from components polyAddFace ( const face& f, const label owner, const label neighbour, const label masterPointID, const label masterEdgeID, const label masterFaceID, const bool flipFaceFlux, const label patchID, const label zoneID, const bool zoneFlip ) : face_(f), owner_(owner), neighbour_(neighbour), masterPointID_(masterPointID), masterEdgeID_(masterEdgeID), masterFaceID_(masterFaceID), flipFaceFlux_(flipFaceFlux), patchID_(patchID), zoneID_(zoneID), zoneFlip_(zoneFlip) { if (face_.size() < 3) { FatalErrorInFunction << "This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (min(face_) < 0) { FatalErrorInFunction << "This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (min(owner_, neighbour_) >= 0 && owner_ == neighbour_) { FatalErrorInFunction << "This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (neighbour_ >= 0 && patchID >= 0) { FatalErrorInFunction << ". This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (owner_ < 0 && zoneID < 0) { FatalErrorInFunction << "This is not allowed.\n" << "Face: " << face_ << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (zoneID_ == -1 && zoneFlip) { FatalErrorInFunction << "belong to zone. This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } } //- Construct and return a clone virtual autoPtr<topoAction> clone() const { return autoPtr<topoAction>(new polyAddFace(*this)); } // Default Destructor // Member Functions //- Return face const face& newFace() const { return face_; } //- Return owner cell label owner() const { return owner_; } //- Return neighour cell label neighbour() const { return neighbour_; } //- Is the face mastered by a point bool isPointMaster() const { return masterPointID_ >= 0; } //- Is the face mastered by an edge bool isEdgeMaster() const { return masterEdgeID_ >= 0; } //- Is the face mastered by another face bool isFaceMaster() const { return masterFaceID_ >= 0; } //- Is the face appended with no master bool appended() const { return !isPointMaster() && !isEdgeMaster() && !isFaceMaster(); } //- Return master point ID label masterPointID() const { return masterPointID_; } //- Return master edge ID label masterEdgeID() const { return masterEdgeID_; } //- Return master face ID label masterFaceID() const { return masterFaceID_; } //- Does the face flux need to be flipped bool flipFaceFlux() const { return flipFaceFlux_; } //- Does the face belong to a boundary patch? bool isInPatch() const { return patchID_ >= 0; } //- Boundary patch ID label patchID() const { return patchID_; } //- Does the face belong to a zone? bool isInZone() const { return zoneID_ >= 0; } //- Is the face only a zone face (i.e. not belonging to a cell) bool onlyInZone() const { return zoneID_ >= 0 && owner_ < 0 && neighbour_ < 0; } //- Face zone ID label zoneID() const { return zoneID_; } //- Face zone flip label zoneFlip() const { return zoneFlip_; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
1
0.666921
1
0.666921
game-dev
MEDIA
0.833235
game-dev
0.676758
1
0.676758
bevyengine/bevy
15,838
crates/bevy_text/src/text_access.rs
use bevy_color::Color; use bevy_ecs::{ component::Mutable, prelude::*, system::{Query, SystemParam}, }; use crate::{TextColor, TextFont, TextSpan}; /// Helper trait for using the [`TextReader`] and [`TextWriter`] system params. pub trait TextSpanAccess: Component<Mutability = Mutable> { /// Gets the text span's string. fn read_span(&self) -> &str; /// Gets mutable reference to the text span's string. fn write_span(&mut self) -> &mut String; } /// Helper trait for the root text component in a text block. pub trait TextRoot: TextSpanAccess + From<String> {} /// Helper trait for the text span components in a text block. pub trait TextSpanComponent: TextSpanAccess + From<String> {} /// Scratch buffer used to store intermediate state when iterating over text spans. #[derive(Resource, Default)] pub struct TextIterScratch { stack: Vec<(&'static Children, usize)>, } impl TextIterScratch { fn take<'a>(&mut self) -> Vec<(&'a Children, usize)> { core::mem::take(&mut self.stack) .into_iter() .map(|_| -> (&Children, usize) { unreachable!() }) .collect() } fn recover(&mut self, mut stack: Vec<(&Children, usize)>) { stack.clear(); self.stack = stack .into_iter() .map(|_| -> (&'static Children, usize) { unreachable!() }) .collect(); } } /// System parameter for reading text spans in a text block. /// /// `R` is the root text component. #[derive(SystemParam)] pub struct TextReader<'w, 's, R: TextRoot> { // This is a local to avoid system ambiguities when TextReaders run in parallel. scratch: Local<'s, TextIterScratch>, roots: Query< 'w, 's, ( &'static R, &'static TextFont, &'static TextColor, Option<&'static Children>, ), >, spans: Query< 'w, 's, ( &'static TextSpan, &'static TextFont, &'static TextColor, Option<&'static Children>, ), >, } impl<'w, 's, R: TextRoot> TextReader<'w, 's, R> { /// Returns an iterator over text spans in a text block, starting with the root entity. pub fn iter(&mut self, root_entity: Entity) -> TextSpanIter<'_, R> { let stack = self.scratch.take(); TextSpanIter { scratch: &mut self.scratch, root_entity: Some(root_entity), stack, roots: &self.roots, spans: &self.spans, } } /// Gets a text span within a text block at a specific index in the flattened span list. pub fn get( &mut self, root_entity: Entity, index: usize, ) -> Option<(Entity, usize, &str, &TextFont, Color)> { self.iter(root_entity).nth(index) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. pub fn get_text(&mut self, root_entity: Entity, index: usize) -> Option<&str> { self.get(root_entity, index).map(|(_, _, text, _, _)| text) } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. pub fn get_font(&mut self, root_entity: Entity, index: usize) -> Option<&TextFont> { self.get(root_entity, index).map(|(_, _, _, font, _)| font) } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. pub fn get_color(&mut self, root_entity: Entity, index: usize) -> Option<Color> { self.get(root_entity, index) .map(|(_, _, _, _, color)| color) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn text(&mut self, root_entity: Entity, index: usize) -> &str { self.get_text(root_entity, index).unwrap() } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn font(&mut self, root_entity: Entity, index: usize) -> &TextFont { self.get_font(root_entity, index).unwrap() } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn color(&mut self, root_entity: Entity, index: usize) -> Color { self.get_color(root_entity, index).unwrap() } } /// Iterator returned by [`TextReader::iter`]. /// /// Iterates all spans in a text block according to hierarchy traversal order. /// Does *not* flatten interspersed ghost nodes. Only contiguous spans are traversed. // TODO: Use this iterator design in UiChildrenIter to reduce allocations. pub struct TextSpanIter<'a, R: TextRoot> { scratch: &'a mut TextIterScratch, root_entity: Option<Entity>, /// Stack of (children, next index into children). stack: Vec<(&'a Children, usize)>, roots: &'a Query< 'a, 'a, ( &'static R, &'static TextFont, &'static TextColor, Option<&'static Children>, ), >, spans: &'a Query< 'a, 'a, ( &'static TextSpan, &'static TextFont, &'static TextColor, Option<&'static Children>, ), >, } impl<'a, R: TextRoot> Iterator for TextSpanIter<'a, R> { /// Item = (entity in text block, hierarchy depth in the block, span text, span style). type Item = (Entity, usize, &'a str, &'a TextFont, Color); fn next(&mut self) -> Option<Self::Item> { // Root if let Some(root_entity) = self.root_entity.take() { if let Ok((text, text_font, color, maybe_children)) = self.roots.get(root_entity) { if let Some(children) = maybe_children { self.stack.push((children, 0)); } return Some((root_entity, 0, text.read_span(), text_font, color.0)); } return None; } // Span loop { let (children, idx) = self.stack.last_mut()?; loop { let Some(child) = children.get(*idx) else { break; }; // Increment to prep the next entity in this stack level. *idx += 1; let entity = *child; let Ok((span, text_font, color, maybe_children)) = self.spans.get(entity) else { continue; }; let depth = self.stack.len(); if let Some(children) = maybe_children { self.stack.push((children, 0)); } return Some((entity, depth, span.read_span(), text_font, color.0)); } // All children at this stack entry have been iterated. self.stack.pop(); } } } impl<'a, R: TextRoot> Drop for TextSpanIter<'a, R> { fn drop(&mut self) { // Return the internal stack. let stack = core::mem::take(&mut self.stack); self.scratch.recover(stack); } } /// System parameter for reading and writing text spans in a text block. /// /// `R` is the root text component, and `S` is the text span component on children. #[derive(SystemParam)] pub struct TextWriter<'w, 's, R: TextRoot> { // This is a resource because two TextWriters can't run in parallel. scratch: ResMut<'w, TextIterScratch>, roots: Query< 'w, 's, ( &'static mut R, &'static mut TextFont, &'static mut TextColor, ), Without<TextSpan>, >, spans: Query< 'w, 's, ( &'static mut TextSpan, &'static mut TextFont, &'static mut TextColor, ), Without<R>, >, children: Query<'w, 's, &'static Children>, } impl<'w, 's, R: TextRoot> TextWriter<'w, 's, R> { /// Gets a mutable reference to a text span within a text block at a specific index in the flattened span list. pub fn get( &mut self, root_entity: Entity, index: usize, ) -> Option<( Entity, usize, Mut<'_, String>, Mut<'_, TextFont>, Mut<'_, TextColor>, )> { // Root if index == 0 { let (text, font, color) = self.roots.get_mut(root_entity).ok()?; return Some(( root_entity, 0, text.map_unchanged(|t| t.write_span()), font, color, )); } // Prep stack. let mut stack: Vec<(&Children, usize)> = self.scratch.take(); if let Ok(children) = self.children.get(root_entity) { stack.push((children, 0)); } // Span let mut count = 1; let (depth, entity) = 'l: loop { let Some((children, idx)) = stack.last_mut() else { self.scratch.recover(stack); return None; }; loop { let Some(child) = children.get(*idx) else { // All children at this stack entry have been iterated. stack.pop(); break; }; // Increment to prep the next entity in this stack level. *idx += 1; if !self.spans.contains(*child) { continue; }; count += 1; if count - 1 == index { let depth = stack.len(); self.scratch.recover(stack); break 'l (depth, *child); } if let Ok(children) = self.children.get(*child) { stack.push((children, 0)); break; } } }; // Note: We do this outside the loop due to borrow checker limitations. let (text, font, color) = self.spans.get_mut(entity).unwrap(); Some(( entity, depth, text.map_unchanged(|t| t.write_span()), font, color, )) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. pub fn get_text(&mut self, root_entity: Entity, index: usize) -> Option<Mut<'_, String>> { self.get(root_entity, index).map(|(_, _, text, ..)| text) } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. pub fn get_font(&mut self, root_entity: Entity, index: usize) -> Option<Mut<'_, TextFont>> { self.get(root_entity, index).map(|(_, _, _, font, _)| font) } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. pub fn get_color(&mut self, root_entity: Entity, index: usize) -> Option<Mut<'_, TextColor>> { self.get(root_entity, index) .map(|(_, _, _, _, color)| color) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn text(&mut self, root_entity: Entity, index: usize) -> Mut<'_, String> { self.get_text(root_entity, index).unwrap() } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn font(&mut self, root_entity: Entity, index: usize) -> Mut<'_, TextFont> { self.get_font(root_entity, index).unwrap() } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn color(&mut self, root_entity: Entity, index: usize) -> Mut<'_, TextColor> { self.get_color(root_entity, index).unwrap() } /// Invokes a callback on each span in a text block, starting with the root entity. pub fn for_each( &mut self, root_entity: Entity, mut callback: impl FnMut(Entity, usize, Mut<String>, Mut<TextFont>, Mut<TextColor>), ) { self.for_each_until(root_entity, |a, b, c, d, e| { (callback)(a, b, c, d, e); true }); } /// Invokes a callback on each span's string value in a text block, starting with the root entity. pub fn for_each_text(&mut self, root_entity: Entity, mut callback: impl FnMut(Mut<String>)) { self.for_each(root_entity, |_, _, text, _, _| { (callback)(text); }); } /// Invokes a callback on each span's [`TextFont`] in a text block, starting with the root entity. pub fn for_each_font(&mut self, root_entity: Entity, mut callback: impl FnMut(Mut<TextFont>)) { self.for_each(root_entity, |_, _, _, font, _| { (callback)(font); }); } /// Invokes a callback on each span's [`TextColor`] in a text block, starting with the root entity. pub fn for_each_color( &mut self, root_entity: Entity, mut callback: impl FnMut(Mut<TextColor>), ) { self.for_each(root_entity, |_, _, _, _, color| { (callback)(color); }); } /// Invokes a callback on each span in a text block, starting with the root entity. /// /// Traversal will stop when the callback returns `false`. // TODO: find a way to consolidate get and for_each_until, or provide a real iterator. Lifetime issues are challenging here. pub fn for_each_until( &mut self, root_entity: Entity, mut callback: impl FnMut(Entity, usize, Mut<String>, Mut<TextFont>, Mut<TextColor>) -> bool, ) { // Root let Ok((text, font, color)) = self.roots.get_mut(root_entity) else { return; }; if !(callback)( root_entity, 0, text.map_unchanged(|t| t.write_span()), font, color, ) { return; } // Prep stack. let mut stack: Vec<(&Children, usize)> = self.scratch.take(); if let Ok(children) = self.children.get(root_entity) { stack.push((children, 0)); } // Span loop { let depth = stack.len(); let Some((children, idx)) = stack.last_mut() else { self.scratch.recover(stack); return; }; loop { let Some(child) = children.get(*idx) else { // All children at this stack entry have been iterated. stack.pop(); break; }; // Increment to prep the next entity in this stack level. *idx += 1; let entity = *child; let Ok((text, font, color)) = self.spans.get_mut(entity) else { continue; }; if !(callback)( entity, depth, text.map_unchanged(|t| t.write_span()), font, color, ) { self.scratch.recover(stack); return; } if let Ok(children) = self.children.get(entity) { stack.push((children, 0)); break; } } } } }
1
0.862034
1
0.862034
game-dev
MEDIA
0.491523
game-dev
0.943657
1
0.943657
Athlaeos/ValhallaMMO
3,591
core/src/main/java/me/athlaeos/valhallammo/crafting/dynamicitemmodifiers/implementations/item_misc/SmithingQualityAdd.java
package me.athlaeos.valhallammo.crafting.dynamicitemmodifiers.implementations.item_misc; import me.athlaeos.valhallammo.crafting.dynamicitemmodifiers.DynamicItemModifier; import me.athlaeos.valhallammo.crafting.dynamicitemmodifiers.ModifierCategoryRegistry; import me.athlaeos.valhallammo.crafting.dynamicitemmodifiers.ModifierContext; import me.athlaeos.valhallammo.dom.Pair; import me.athlaeos.valhallammo.item.ItemBuilder; import me.athlaeos.valhallammo.item.SmithingItemPropertyManager; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.*; public class SmithingQualityAdd extends DynamicItemModifier { private int quality = 0; public SmithingQualityAdd(String name) { super(name); } @Override public void processItem(ModifierContext context) { int quality = SmithingItemPropertyManager.getQuality(context.getItem().getMeta()); int newQuality = Math.max(0, quality + this.quality); SmithingItemPropertyManager.setQuality(context.getItem(), newQuality); } @Override public void onButtonPress(InventoryClickEvent e, int button) { if (button == 12) quality = quality + ((e.isLeftClick() ? 1 : -1) * (e.isShiftClick() ? 10 : 1)); } @Override public Map<Integer, ItemStack> getButtons() { return new Pair<>(12, new ItemBuilder(Material.PAPER) .name("&eHow much quality to add?") .lore("&fAdds &e" + quality + "&f quality to the item", "", "&fFor example, an item with 100", "&fquality is converted to &e" + (100 + quality), "&6Click to add/subtract 1", "&6Shift-Click to add/subtract 10") .get()).map(new HashSet<>()); } @Override public ItemStack getModifierIcon() { return new ItemBuilder(Material.NETHER_STAR).get(); } @Override public String getDisplayName() { return "&eSmithing Quality (ADD)"; } @Override public String getDescription() { return "&fAdds a set amount of quality to the item"; } @Override public String getActiveDescription() { return "&fAdds &e" + quality + "&f quality to the item's existing quality"; } @Override public Collection<String> getCategories() { return Set.of(ModifierCategoryRegistry.ITEM_MISC.id()); } public void setQuality(int quality) { this.quality = quality; } @Override public DynamicItemModifier copy() { SmithingQualityAdd m = new SmithingQualityAdd(getName()); m.setQuality(this.quality); m.setPriority(this.getPriority()); return m; } @Override public String parseCommand(CommandSender executor, String[] args) { if (args.length != 1) return "One numbers is expected: an integer"; try { quality = Integer.parseInt(args[0]); } catch (NumberFormatException ignored){ return "One numbers is expected: an integer. It was not a number"; } return null; } @Override public List<String> commandSuggestions(CommandSender executor, int currentArg) { if (currentArg == 0) return List.of("<quality_to_add>"); return null; } @Override public int commandArgsRequired() { return 1; } }
1
0.900303
1
0.900303
game-dev
MEDIA
0.930396
game-dev
0.936758
1
0.936758
arnaud-neny/rePlayer
7,104
source/Replays/Psycle/psycle/src/psycle/host/LuaArray.hpp
// This source is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2, or (at your option) any later version. // copyright 2007-2010 members of the psycle project http://psycle.sourceforge.net #pragma once #include <psycle/host/detail/project.hpp> #include <vector> #include <map> #include <string> #include <universalis/os/aligned_alloc.hpp> #include <psycle/helpers/value_mapper.hpp> #include <psycle/helpers/dsp.hpp> #include "LuaHelper.hpp" namespace psycle { namespace host { // array wrapper (shared : float*, // notshared: universalis::os::aligned_memory_alloc(16,..) class PSArray { public: PSArray() { ptr_ = base_ = 0; shared_ = can_aligned_ = false; baselen_ = len_ = cap_ = 0; } PSArray(int len, float v); PSArray(double start, double stop, double step); PSArray(float* ptr, int len) : ptr_(ptr), base_(ptr), cap_(0), len_(len), baselen_(len), shared_(1), can_aligned_(is_aligned(ptr)) {} PSArray(PSArray& a1, PSArray& a2); PSArray(const PSArray& other); PSArray& operator=(PSArray rhs) { swap(rhs); return *this; } #if defined _MSC_VER >= 1600 PSArray(PSArray&& other) { swap(other); } #endif ~PSArray() { if (!shared_ && base_) universalis::os::aligned_memory_dealloc(base_); } void swap(PSArray& rhs); void set_val(int i, float val) { ptr_[i] = val; } float get_val(int i) const { return ptr_[i]; } void set_len(int len) {len_ = len; } int len() const { return len_; } bool copyfrom(PSArray& src); int copyfrom(PSArray& src, int pos); void resize(int newsize); std::string tostring() const; void clear(); void fillzero(int pos) { fill(0, pos); } void fill(float val); void fill(float val, int pos); void mul(float multi); void mul(PSArray& src); void mix(PSArray& src, float multi); void add(float addend); void add(PSArray& src); void sub(PSArray& src); void sqrt() { for (int i = 0; i < len_; ++i) ptr_[i] = ::sqrt(ptr_[i]); } void sqrt(PSArray& src); void sin() { for (int i = 0; i < len_; ++i) ptr_[i] = ::sin(ptr_[i]); } void cos() { for (int i = 0; i < len_; ++i) ptr_[i] = ::cos(ptr_[i]); } void tan() { for (int i = 0; i < len_; ++i) ptr_[i] = ::tan(ptr_[i]); } void floor() { for (int i = 0; i < len_; ++i) ptr_[i] = ::floor(ptr_[i]); } void ceil() { for (int i = 0; i < len_; ++i) ptr_[i] = ::ceil(ptr_[i]); } void abs() { for (int i = 0; i < len_; ++i) ptr_[i] = ::abs(ptr_[i]); } void pow(float exp) { for (int i = 0; i < len_; ++i) ptr_[i] = ::pow(ptr_[i], exp); } void sgn() { for (int i = 0; i < len_; ++i) { ptr_[i] = (ptr_[i] > 0) ? 1 : ((ptr_[i] < 0) ? -1 : 0); } } float* data() { return ptr_; } template<class T> void do_op(T&); void rsum(double lv); void margin(int start, int end) { ptr_ = base_ + start; assert(end >= start && start >= 0 && end <=baselen_); len_ = end-start; can_aligned_ = is_aligned(ptr_); } void offset(int offset) { base_ += offset; ptr_ += offset; can_aligned_ = is_aligned(ptr_); } void clearmargin() { ptr_ = base_; len_ = baselen_; can_aligned_ = is_aligned(ptr_); } inline bool canaligned() const { return can_aligned_; } private: static inline bool is_aligned(const void * pointer) { return (uintptr_t)pointer % 16u == 0; } float* ptr_, *base_; int cap_; int len_; int baselen_; int shared_; bool can_aligned_; }; typedef std::vector<PSArray> psybuffer; struct LuaArrayBind { static int open(lua_State* L); static PSArray* create_copy_array(lua_State* L, int idx=1); static const char* meta; static int array_index(lua_State *L); static int array_new_index(lua_State *L); static int array_new(lua_State *L); static int array_new_from_table(lua_State *L); static int array_arange(lua_State *L); static int array_copy(lua_State* L); static int array_tostring(lua_State *L); static int array_gc(lua_State* L); // array methods static int array_size(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::len); } static int array_resize(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::resize); } static int array_margin(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::margin); } static int array_clearmargin(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::clearmargin); } static int array_concat(lua_State* L); static int array_fillzero(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::clear); } static int array_method_fill(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::fill); } static int array_method_add(lua_State* L); static int array_method_sub(lua_State* L); static int array_method_mix(lua_State* L); static int array_method_mul(lua_State* L); static int array_method_div(lua_State* L); static int array_method_rsum(lua_State* L); // x(n)=x(0)+..+x(n-1) static int array_method_and(lua_State* L); // binary and static int array_method_or(lua_State* L); static int array_method_xor(lua_State* L); static int array_method_sleft(lua_State* L); static int array_method_sright(lua_State* L); static int array_method_bnot(lua_State* L); static int array_method_min(lua_State* L); static int array_method_max(lua_State* L); static int array_method_ceil(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::ceil); } static int array_method_floor(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::floor); } static int array_method_abs(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::abs); } static int array_method_sgn(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::sgn); } static int array_method_random(lua_State* L); static int array_method_sin(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::sin); } static int array_method_cos(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::cos); } static int array_method_tan(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::tan); } static int array_method_sqrt(lua_State* L) { LUAEXPORTML(L, meta, &PSArray::sqrt); } static int array_method_from_table(lua_State* L); static int array_method_to_table(lua_State* L); // ops static int array_add(lua_State* L); static int array_sub(lua_State* L); static int array_mul(lua_State* L); static int array_div(lua_State* L); static int array_mod(lua_State* L); static int array_op_pow(lua_State* L); static int array_unm(lua_State* L); static int array_sum(lua_State* L); static int array_rsum(lua_State* L); // x(n)=x(0)+..+x(n-1) // funcs static int array_sin(lua_State* L); static int array_cos(lua_State* L); static int array_tan(lua_State* L); static int array_sqrt(lua_State* L); static int array_random(lua_State* L); static int array_pow(lua_State* L); }; } // namespace } // namespace
1
0.880567
1
0.880567
game-dev
MEDIA
0.233606
game-dev
0.596019
1
0.596019
darklordabc/Legends-of-Dota-Redux
6,287
src/game/scripts/vscripts/abilities/nextgeneration/hero_veera/pursuit.lua
require('lib/physics') function PursuitAttack (keys) local caster = keys.caster local target = keys.target local ability = keys.ability local baseDamage = ability:GetLevelSpecialValueFor("base_damage", ability:GetLevel() - 1) local movementDamage = ability:GetLevelSpecialValueFor("movement_damage", ability:GetLevel() - 1) / 100 pursuitMovementDamage = (caster:GetMoveSpeedModifier(caster:GetBaseMoveSpeed(), false) - caster:GetBaseMoveSpeed()) * movementDamage if pursuitMovementDamage < 0 then pursuitMovementDamage = 0 end pursuitDamage = baseDamage + pursuitMovementDamage pursuitTarget = target end function CheckOrb(keys) local caster = keys.caster local target = keys.target local ability = keys.ability if ability:IsCooldownReady() then ability:ApplyDataDrivenModifier(caster, caster, "modifier_pursuit_orb", {Duration = 0.9}) end end function CheckPursuit( keys ) local caster = keys.caster local target = pursuitTarget local ability = keys.ability local caster_loc = caster:GetAbsOrigin() local target_loc = target:GetAbsOrigin() local distance = (caster_loc - target_loc):Length2D() ability:CreateVisibilityNode(target_loc, 30, 0.15) if distance < 300 then if caster:IsDisarmed() or target:IsUnselectable() or target:IsAttackImmune() or target:IsInvulnerable() or not target:IsAlive() then caster:RemoveModifierByName("modifier_pursuit_buff") pursuitTarget:RemoveModifierByName("modifier_pursuit_vision") end end end function SetPursuitDamage( keys ) local caster = keys.caster local target = keys.target local ability = keys.ability local duration = ability:GetSpecialValueFor("duration") local creepDuration = ability:GetSpecialValueFor("creep_duration") local baseDamage = ability:GetLevelSpecialValueFor("base_damage", ability:GetLevel() - 1) local movementDamage = ability:GetLevelSpecialValueFor("movement_damage", ability:GetLevel() - 1) / 100 if target:IsHero() then ability:ApplyDataDrivenModifier(caster,target,"modifier_pursuit_debuff",{Duration = duration}) else ability:ApplyDataDrivenModifier(caster,target,"modifier_pursuit_debuff",{Duration = creepDuration}) end pursuitMovementDamage = (caster:GetMoveSpeedModifier(caster:GetBaseMoveSpeed(), false) - caster:GetBaseMoveSpeed()) * movementDamage if pursuitMovementDamage < 0 then pursuitMovementDamage = 0 end target.pursuitDamage = baseDamage + pursuitMovementDamage end function PursuitDamage( keys ) local caster = keys.caster local target = keys.target local ability = keys.ability if target.pursuitDamage == nil then target.pursuitDamage = 20 end DamageTable = {} DamageTable.victim = target DamageTable.attacker = caster DamageTable.damage = target.pursuitDamage DamageTable.damage_type = ability:GetAbilityDamageType() DamageTable.ability = ability ApplyDamage(DamageTable) --[[local amount = target.pursuitDamage local armor = target:GetPhysicalArmorValue() local damageReduction = ((0.02 * armor) / (1 + 0.02 * armor)) amount = amount - (amount * damageReduction) local lens_count = 0 for i=0,5 do local item = caster:GetItemInSlot(i) if item ~= nil and item:GetName() == "item_aether_lens" then lens_count = lens_count + 1 end end amount = amount * (1 + (.08 * lens_count) + (.01 * caster:GetIntellect()/16) ) amount = math.floor(amount) PopupNumbers(target, "crit", Vector(204, 0, 0), 2.0, amount, nil, POPUP_SYMBOL_POST_DROP)]] end function RollInitiate( keys ) local caster = keys.caster local ability = keys.ability local leap_speed = caster:GetMoveSpeedModifier(caster:GetBaseMoveSpeed(), false) + 150 local casterAngles = caster:GetAngles() -- Clears any current command caster:Stop() caster:SetForceAttackTarget(nil) local start_position = GetGroundPosition(caster:GetAbsOrigin() , caster) -- Physics local direction = caster:GetForwardVector() local velocity = leap_speed * 3.0 local end_time = 0.6 local time_elapsed = 0 local time = 0.3 local jump = 48 local flip = 360 Physics:Unit(caster) caster:PreventDI(true) caster:SetAutoUnstuck(false) caster:SetNavCollisionType(PHYSICS_NAV_NOTHING) caster:FollowNavMesh(false) caster:SetPhysicsVelocity(-direction * velocity) -- Dodge projectiles -- Move the unit Timers:CreateTimer(0, function() local ground_position = GetGroundPosition(caster:GetAbsOrigin() , caster) time_elapsed = time_elapsed + 0.03 local yaw = casterAngles.x - ((time_elapsed * 3) * flip) GridNav:DestroyTreesAroundPoint(caster:GetAbsOrigin(), 150, false) caster:SetAngles(yaw, casterAngles.y, casterAngles.z ) if flip > 0 then flip = flip - 9 else flip = 0 end if time_elapsed < 0.3 then caster:SetAbsOrigin(caster:GetAbsOrigin() + Vector(0,0,jump)) ProjectileManager:ProjectileDodge(caster) jump = jump - 2.4 else caster:SetAbsOrigin(caster:GetAbsOrigin() - Vector(0,0,jump)) -- Going down jump = jump * 1.06 end if caster:GetAbsOrigin().z - ground_position.z <= 0 then caster:SetAbsOrigin(GetGroundPosition(caster:GetAbsOrigin() , caster)) end if time_elapsed > end_time and caster:GetAbsOrigin().z - ground_position.z <= 0 then FindClearSpaceForUnit(caster, caster:GetAbsOrigin(), false) caster:SetAngles(0, casterAngles.y, casterAngles.z ) caster:SetPhysicsAcceleration(Vector(0,0,0)) caster:SetPhysicsVelocity(Vector(0,0,0)) caster:OnPhysicsFrame(nil) caster:PreventDI(false) caster:SetNavCollisionType(PHYSICS_NAV_SLIDE) caster:SetAutoUnstuck(true) caster:FollowNavMesh(true) caster:SetPhysicsFriction(.05) return nil end return 0.03 end) end function RemoveForceAttack( keys ) keys.caster:SetForceAttackTarget(nil) end function StartCooldown(keys) local caster = keys.caster local ability = keys.ability local cooldown = ability:GetCooldown(ability:GetLevel() - 1) local mana = ability:GetManaCost(ability:GetLevel() - 1) if caster:HasModifier("modifier_thrill_active") then local cooldownReduction = 1 - (caster:FindAbilityByName("veera_thrill_of_the_hunt"):GetSpecialValueFor("cooldown_reduction") / 100) cooldown = cooldown * cooldownReduction end ability:StartCooldown(cooldown) caster:SpendMana(mana, ability) end
1
0.810874
1
0.810874
game-dev
MEDIA
0.997317
game-dev
0.934305
1
0.934305
Opentrons/opentrons
4,591
app/src/organisms/ErrorRecoveryFlows/RecoveryTakeover.tsx
import { useState } from 'react' import { useTranslation } from 'react-i18next' import { RUN_STATUS_AWAITING_RECOVERY, RUN_STATUS_AWAITING_RECOVERY_BLOCKED_BY_OPEN_DOOR, RUN_STATUS_AWAITING_RECOVERY_PAUSED, } from '@opentrons/api-client' import { AlertPrimaryButton, COLORS, Flex, Icon, SPACING, StyledText, } from '@opentrons/components' import { TakeoverModal } from '/app/organisms/TakeoverModal/TakeoverModal' import { useUpdateClientDataRecovery } from '/app/resources/client_data' import { BANNER_TEXT_CONTAINER_STYLE, BANNER_TEXT_CONTENT_STYLE, } from './constants' import { RecoveryInterventionModal } from './shared' import type { ClientDataRecovery, UseUpdateClientDataRecoveryResult, } from '/app/resources/client_data' import type { ErrorRecoveryFlowsProps } from '.' // The takeover view, functionally similar to MaintenanceRunTakeover export function RecoveryTakeover(props: { intent: ClientDataRecovery['intent'] runStatus: ErrorRecoveryFlowsProps['runStatus'] robotName: string isOnDevice: boolean }): JSX.Element { const { runStatus } = props const { t } = useTranslation('error_recovery') const { clearClientData } = useUpdateClientDataRecovery() // TODO(jh, 07-29-24): This is likely sufficient for most edge cases, but this does not account for // all terminal commands as it should. Revisit this. const isTerminateDisabled = !( runStatus === RUN_STATUS_AWAITING_RECOVERY || runStatus === RUN_STATUS_AWAITING_RECOVERY_BLOCKED_BY_OPEN_DOOR || runStatus === RUN_STATUS_AWAITING_RECOVERY_PAUSED ) const buildRecoveryTakeoverProps = ( intent: ClientDataRecovery['intent'] ): RecoveryTakeoverProps => { switch (intent) { case 'canceling': return { title: t('robot_is_canceling_run'), isRunStatusAwaitingRecovery: isTerminateDisabled, clearClientData, ...props, } case 'recovering': default: return { title: t('robot_is_in_recovery_mode'), isRunStatusAwaitingRecovery: isTerminateDisabled, clearClientData, ...props, } } } return ( <RecoveryTakeoverComponent {...buildRecoveryTakeoverProps(props.intent)} /> ) } interface RecoveryTakeoverProps { title: string /* Do not let other users terminate activity if run is not awaiting recovery. Ex, the run is "recovery canceling." */ isRunStatusAwaitingRecovery: boolean robotName: string isOnDevice: boolean clearClientData: UseUpdateClientDataRecoveryResult['clearClientData'] } export function RecoveryTakeoverComponent( props: RecoveryTakeoverProps ): JSX.Element { return props.isOnDevice ? ( <RecoveryTakeoverODD {...props} /> ) : ( <RecoveryTakeoverDesktop {...props} /> ) } export function RecoveryTakeoverODD({ title, clearClientData, isRunStatusAwaitingRecovery, }: RecoveryTakeoverProps): JSX.Element { const [showConfirmation, setShowConfirmation] = useState(false) return ( <TakeoverModal title={title} confirmTerminate={clearClientData} setShowConfirmTerminateModal={setShowConfirmation} showConfirmTerminateModal={showConfirmation} terminateInProgress={isRunStatusAwaitingRecovery} /> ) } export function RecoveryTakeoverDesktop({ title, robotName, clearClientData, isRunStatusAwaitingRecovery, }: RecoveryTakeoverProps): JSX.Element { const { t } = useTranslation('error_recovery') const buildTitleHeadingDesktop = (): JSX.Element => { return ( <StyledText desktopStyle="bodyLargeSemiBold"> {t('error_on_robot', { robot: robotName })} </StyledText> ) } return ( <RecoveryInterventionModal titleHeading={buildTitleHeadingDesktop()} desktopType={'desktop-small'} isOnDevice={false} > <Flex css={BANNER_TEXT_CONTAINER_STYLE}> <Flex css={BANNER_TEXT_CONTENT_STYLE}> <Icon name="alert-circle" color={COLORS.red50} size={SPACING.spacing40} /> <StyledText desktopStyle="headingSmallBold">{title}</StyledText> <StyledText desktopStyle="bodyDefaultRegular"> {t('another_app_controlling_robot')} </StyledText> </Flex> <Flex marginLeft="auto"> <AlertPrimaryButton onClick={clearClientData} disabled={isRunStatusAwaitingRecovery} > {t('terminate_remote_activity')} </AlertPrimaryButton> </Flex> </Flex> </RecoveryInterventionModal> ) }
1
0.95681
1
0.95681
game-dev
MEDIA
0.341866
game-dev
0.97216
1
0.97216
happyhavoc/th06
4,375
src/main.cpp
#define _WIN32_WINNT 0x0500 #include <windows.h> #include <D3DX8.h> #include <stdio.h> #include "AnmManager.hpp" #include "Chain.hpp" #include "FileSystem.hpp" #include "GameErrorContext.hpp" #include "GameWindow.hpp" #include "SoundPlayer.hpp" #include "Stage.hpp" #include "Supervisor.hpp" #include "ZunResult.hpp" #include "i18n.hpp" #include "utils.hpp" using namespace th06; #pragma var_order(renderResult, testCoopLevelRes, msg, testResetRes, waste1, waste2, waste3, waste4, waste5, waste6) int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { i32 renderResult = 0; i32 testCoopLevelRes; i32 testResetRes; MSG msg; i32 waste1, waste2, waste3, waste4, waste5, waste6; if (utils::CheckForRunningGameInstance()) { g_GameErrorContext.Flush(); return 1; } g_Supervisor.hInstance = hInstance; if (g_Supervisor.LoadConfig(TH_CONFIG_FILE) != ZUN_SUCCESS) { g_GameErrorContext.Flush(); return -1; } if (GameWindow::InitD3dInterface()) { g_GameErrorContext.Flush(); return 1; } SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &g_GameWindow.screenSaveActive, 0); SystemParametersInfo(SPI_GETLOWPOWERACTIVE, 0, &g_GameWindow.lowPowerActive, 0); SystemParametersInfo(SPI_GETPOWEROFFACTIVE, 0, &g_GameWindow.powerOffActive, 0); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, NULL, SPIF_SENDCHANGE); SystemParametersInfo(SPI_SETLOWPOWERACTIVE, 0, NULL, SPIF_SENDCHANGE); SystemParametersInfo(SPI_SETPOWEROFFACTIVE, 0, NULL, SPIF_SENDCHANGE); restart: GameWindow::CreateGameWindow(hInstance); if (GameWindow::InitD3dRendering()) { g_GameErrorContext.Flush(); return 1; } g_SoundPlayer.InitializeDSound(g_GameWindow.window); Controller::GetJoystickCaps(); Controller::ResetKeyboard(); g_AnmManager = new AnmManager(); if (Supervisor::RegisterChain() != ZUN_SUCCESS) { goto stop; } if (!g_Supervisor.cfg.windowed) { ShowCursor(FALSE); } g_GameWindow.curFrame = 0; while (!g_GameWindow.isAppClosing) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { testCoopLevelRes = g_Supervisor.d3dDevice->TestCooperativeLevel(); if (testCoopLevelRes == D3D_OK) { renderResult = g_GameWindow.Render(); if (renderResult != 0) { goto stop; } } else if (testCoopLevelRes == D3DERR_DEVICENOTRESET) { g_AnmManager->ReleaseSurfaces(); testResetRes = g_Supervisor.d3dDevice->Reset(&g_Supervisor.presentParameters); if (testResetRes != 0) { goto stop; } GameWindow::InitD3dDevice(); g_Supervisor.unk198 = 3; } } } stop: g_Chain.Release(); g_SoundPlayer.Release(); delete g_AnmManager; g_AnmManager = NULL; if (g_Supervisor.d3dDevice != NULL) { g_Supervisor.d3dDevice->Release(); g_Supervisor.d3dDevice = NULL; } ShowWindow(g_GameWindow.window, 0); MoveWindow(g_GameWindow.window, 0, 0, 0, 0, 0); DestroyWindow(g_GameWindow.window); if (renderResult == 2) { g_GameErrorContext.ResetContext(); GameErrorContext::Log(&g_GameErrorContext, TH_ERR_OPTION_CHANGED_RESTART); if (!g_Supervisor.cfg.windowed) { ShowCursor(TRUE); } goto restart; } FileSystem::WriteDataToFile(TH_CONFIG_FILE, &g_Supervisor.cfg, sizeof(g_Supervisor.cfg)); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, g_GameWindow.screenSaveActive, NULL, SPIF_SENDCHANGE); SystemParametersInfo(SPI_SETLOWPOWERACTIVE, g_GameWindow.lowPowerActive, NULL, SPIF_SENDCHANGE); SystemParametersInfo(SPI_SETPOWEROFFACTIVE, g_GameWindow.powerOffActive, NULL, SPIF_SENDCHANGE); if (g_Supervisor.d3dIface != NULL) { g_Supervisor.d3dIface->Release(); g_Supervisor.d3dIface = NULL; } ShowCursor(TRUE); g_GameErrorContext.Flush(); return 0; }
1
0.948046
1
0.948046
game-dev
MEDIA
0.768561
game-dev
0.96915
1
0.96915
mekanism/Mekanism
4,016
src/api/java/mekanism/api/recipes/CombinerRecipe.java
package mekanism.api.recipes; import java.util.List; import java.util.function.BiPredicate; import mekanism.api.MekanismAPI; import mekanism.api.annotations.NothingNullByDefault; import mekanism.api.recipes.ingredients.ItemStackIngredient; import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeInput; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; import net.neoforged.neoforge.registries.DeferredHolder; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; /** * Main Input: ItemStack * <br> * Secondary/Extra Input: ItemStack * <br> * Output: ItemStack * * @apiNote Combiners and Combining Factories can process this recipe type. */ @NothingNullByDefault public abstract class CombinerRecipe extends MekanismRecipe<RecipeInput> implements BiPredicate<@NotNull ItemStack, @NotNull ItemStack> { private static final Holder<Item> COMBINER = DeferredHolder.create(Registries.ITEM, ResourceLocation.fromNamespaceAndPath(MekanismAPI.MEKANISM_MODID, "combiner")); @Override public abstract boolean test(ItemStack input, ItemStack extra); /** * Gets the main input ingredient. */ public abstract ItemStackIngredient getMainInput(); /** * Gets the secondary input ingredient. */ public abstract ItemStackIngredient getExtraInput(); @NotNull @Override public ItemStack assemble(RecipeInput input, HolderLookup.Provider provider) { if (!isIncomplete() && input.size() == 2) { ItemStack mainInput = input.getItem(0); ItemStack extraInput = input.getItem(1); if (test(mainInput, extraInput)) { return getOutput(mainInput, extraInput); } } return ItemStack.EMPTY; } @Override public boolean matches(RecipeInput input, Level level) { //Don't match incomplete recipes or ones that don't match return !isIncomplete() && input.size() == 2 && test(input.getItem(0), input.getItem(1)); } @Override public boolean canCraftInDimensions(int width, int height) { return width * height > 1; } /** * Gets a new output based on the given inputs. * * @param input Specific input. * @param extra Specific secondary/extra input. * * @return New output. * * @apiNote While Mekanism does not currently make use of the inputs, it is important to support it and pass the proper value in case any addons define input based * outputs where things like NBT may be different. * @implNote The passed in inputs should <strong>NOT</strong> be modified. */ @Contract(value = "_, _ -> new", pure = true) public abstract ItemStack getOutput(@NotNull ItemStack input, @NotNull ItemStack extra); @NotNull @Override public abstract ItemStack getResultItem(@NotNull HolderLookup.Provider provider); /** * For JEI, gets the output representations to display. * * @return Representation of the output, <strong>MUST NOT</strong> be modified. */ public abstract List<ItemStack> getOutputDefinition(); @Override public boolean isIncomplete() { return getMainInput().hasNoMatchingInstances() || getExtraInput().hasNoMatchingInstances(); } @Override public void logMissingTags() { getMainInput().logMissingTags(); getExtraInput().logMissingTags(); } @Override public final RecipeType<CombinerRecipe> getType() { return MekanismRecipeTypes.TYPE_COMBINING.value(); } @Override public String getGroup() { return "combiner"; } @Override public ItemStack getToastSymbol() { return new ItemStack(COMBINER); } }
1
0.817063
1
0.817063
game-dev
MEDIA
0.993295
game-dev
0.725947
1
0.725947
lo-th/Ammo.lab
16,182
demos/mecanum - Copie.js
var settings = { massChassis: 100, massAxis: 20, massArmtop: 20, massArmlow: 20, } function demo() { physic.set({ fps:60, substep:8, gravity:[0,-10,0], }) view.moveCam({ theta:45, phi:20, distance:25, target:[0,2,0] }); view.load ( ['mecanum.sea'], afterLoad, true, true ); }; function afterLoad () { view.addJoystick(); physic.add({type:'plane'});// infinie plane // physic terrain shape /*add ({ type:'terrain', uv:50, pos : [ 0, -10, 0 ], // terrain position size : [ 1000, 10, 1000 ], // terrain size in meter sample : [ 512, 512 ], // number of subdivision frequency : [0.016,0.05,0.2], // frequency of noise level : [ 1, 0.2, 0.05 ], // influence of octave expo: 3, flipEdge : true, // inverse the triangle hdt : 'PHY_FLOAT', // height data type PHY_FLOAT, PHY_UCHAR, PHY_SHORT friction: 1, restitution: 0.2, });*/ //return // make meca material initMaterials(); // mecanum buggy buildMecanum(); //follow ('chassis', {distance:20, theta:-90}); view.update = update; } function initMaterials () { // note: material is not recreated on code edit mat['meca1'] = view.material({ name:'meca1', roughness: 0.4, metalness: 0.6, map: view.texture( 'meca_chassis.jpg' ), }); mat['meca2'] = view.material({ name:'meca2', roughness: 0.7, metalness: 0.3, map: view.texture( 'meca_wheel.jpg' ), normalMap: view.texture( 'meca_wheel_n.jpg' ) }); mat['meca3'] = view.material({ name:'meca3', roughness: 0.2, metalness: 0.8, map: view.texture( 'meca_tools.jpg' ), }); // debug mat['red'] = view.material({ name:'red', roughness: 0.2, metalness: 0.8, color: 0xff0000, }); mat['green'] = view.material({ name:'green', roughness: 0.2, metalness: 0.8, color: 0x00FF00, }); mat['blue'] = view.material({ name:'blue', roughness: 0.2, metalness: 0.8, color: 0x0055FF, }); } function update() { var d; var ts = user.key[1] * acc; var rs = user.key[0] * acc; // speed = user.key[0] * 5 + user.key[1] * 5; var i = 4, r=[]; while(i--){ if(Math.abs(ts)>Math.abs(rs)){ s = ts;// translation //if(i==0 || i==3) s*=-1; } else { s = rs;// rotation if(i==1 || i==3) s*=-1; } //r.push( [ 'jh'+i, 'motor', [ s, 100] ] ); r.push( { name:'jh'+i, type:'motor', targetVelocity:s, maxMotor:100 } ); } // apply forces to bodys physic.forces( r ); }; var mat = {}; // ! \\ set car speed and direction var acc = 5; var speed = 0; var translation = false; var rotation = true; // ----------------------- // MECANUM BUGGY // // 3 ----- 1 :R // | >>> ) // 2 ----- 0 :L // // ----------------------- var size = 0.05; var debug = true; var geo = view.getGeo(); var mat = view.getMat(); //var useSteering = false; //var steeringAxis = [1,1,1,1]; var steeringAxis = [0,0,0,0]; // center of mass position y var decalY = 62.5 * size; var buggyGroup = 8; var buggyMask = -1;//1|2; var noCollision = 32; function buildMecanum () { // chassis physic.add({ name:'chassis', type:'convex', shape:view.getGeometry( 'mecanum', 'meca_chassis_shape' ), mass:settings.massChassis, size:[size], pos:[0, decalY, 0], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_chassis' ), material:debug ? undefined : mat.meca1, state:4, group:buggyGroup, mask:buggyMask, friction: 0.5, restitution: 0, //linear:0.5, //angular:1, }); physic.add({type:'box', name:'boyA', mass:100, pos:[0,15,0], size:[5] }); // wheelAxis var i = 4; while(i--){ wheelAxis( i ); // add suspensions spring ( i ); // add wheels wheel( i ); } }; function wheelAxis ( n ) { var rot = [10, 0, 0]; var ext2; var front = 1; var gr = undefined; var gr2 = undefined; var side = 1; if(n==1 || n==3) side = -1; var front = 1; if(n==2 || n==3) front = -1; switch(n){ case 0 : ext2 = '_av'; gr = [0,0,180]; break; case 1 : ext2 = '_av'; gr = [180,0,180]; gr2 = [0,180,0]; break; case 2 : ext2 = '_ar'; break; case 3 : ext2 = '_ar'; gr = [180,0,0]; gr2 = [0,180,0]; break; } var pos0 = [120*front, 50, 60*side ].map(function(x) { return x * size; }); var pos1 = [120*front, 84, 54.5*side ].map(function(x) { return x * size; }); var pos2 = [120*front, 50, 91*side ].map(function(x) { return x * size; }); var pos3 = [120*front, 50, 91*side ].map(function(x) { return x * size; }); var decal0 = [-40*side, -40*side].map(function(x) { return x * size; }); var decal1 = [-31.5*side, -31.5*side].map(function(x) { return x * size; }); var decal2 = [8*side, -5.957*side].map(function(x) { return x * size; }); physic.add({ name:'armlow'+n, type:'hardbox', mass:settings.massArmlow, size:[28*size, 10*size, 80*size], //size:[28*size, 7*size, 80*size], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_paddel' ), material:debug ? mat.green : mat.meca3, geoRot:gr, geoSize:[size], pos:pos0, state:4, group:buggyGroup, mask:noCollision, //linear:0.5, angular:1, }); physic.add({ name:'armtop'+n, type:'hardbox', mass:settings.massArmTop, size:[28*size, 10*size, 80*size], //size:[10*size, 10*size, 63*size], //size:[3*size, 5*size, 63*size], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_padtop' ), material:debug ? mat.green : mat.meca3, geoSize:[size], pos:pos1, //rot:rot, state:4, group:buggyGroup, mask:noCollision, //linear:0.5, angular:1, }); if( steeringAxis[n] ){ physic.add({ name:'axis'+ n, type:'box', mass:settings.massAxis*0.5, size:[23*size, 23*size, 23*size], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_axis_av' ), material:debug ? undefined : mat.meca3, geoRot:gr2, geoSize:[size], pos:pos2, state:4, group:buggyGroup, mask:noCollision, angular:1, }); physic.add({ name:'axis_s_'+ n, type:'box', mass:settings.massAxis*0.5, friction:0.1, size:[23*size, 23*size, 23*size], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_axis_av2' ), material:debug ? undefined : mat.meca3, geoRot:gr2, geoSize:[size], pos:pos3, state:4, group:buggyGroup, mask:buggyMask, angular:1, }); physic.add({ name:'j_steering_'+n, type:'joint_hinge', body1:'axis'+n, body2:'axis_s_'+n, pos1:[0,0,0], pos2:[0,0,0], axe1:[0,1,0], axe2:[0,1,0], //limit:[0, 0], //motor:[true, 3, 10], }); } else { physic.add({ name:'axis'+n, type:'hardbox', mass:settings.massAxis, friction:0.1, size:[23*size, 23*size, 23*size], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_axis_ar' ), material:debug ? mat.blue : mat.meca3, geoRot:gr2, geoSize:[size], pos:pos2, state:4, group:buggyGroup, mask:buggyMask, }); } // joint to chassis physic.add({ name:'ax_1_'+n, type:'joint_hinge', body1:'chassis', body2:'armlow'+n, pos1:[pos0[0], pos0[1]-decalY, pos0[2]+decal0[0] ], pos2:[ 0, 0, decal0[1]], axe1:[1,0,0], axe2:[1,0,0], }); physic.add({ name:'ax_2_'+n, type:'joint_hinge', body1:'chassis', body2:'armtop'+n, pos1:[pos1[0], pos1[1]-decalY, pos1[2]+decal1[0] ], pos2:[ 0, 0, decal1[1]], axe1:[1,0,0], axe2:[1,0,0], }); // joint to axis physic.add({ name:'ax_1e_'+n, type:'joint_hinge', body1:'axis'+n, body2:'armlow'+n, pos1:[0, -14*size, decal2[0] ], pos2:[ 0, 0, -decal0[1]], axe1:[1,0,0], axe2:[1,0,0], }); physic.add({ name:'ax_2e_'+n, type:'joint_hinge', body1:'axis'+n, body2:'armtop'+n, pos1:[0, 23*size, decal2[1] ], pos2:[ 0, 0, -decal1[1]], axe1:[1,0,0], axe2:[1,0,0], }); }; // SPRING function spring ( n ) { var side = 1; if(n==1 || n==3) side = -1; var front = 1; if(n==2 || n==3) front = -1; var p1 = [136.5*front, 102, 24*side].map(function(x) { return x * size; }); var p2 = [16.5*front, 0, 15*side].map(function(x) { return x * size; }); var gr = [0,0,0]; if(side==-1) gr = [0,180,0]; var gr2 = [0,0,0]; if(side==-1) gr2 = [0,180,0]; // mass var massTop = 2; var massLow = 2; // object physic.add({ name:'bA'+n, type:'hardbox', mass:massTop, size:[17*size, 17*size, 22*size], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_stop' ), material:debug ? mat.red : mat.meca3, geoSize:[size], geoRot:gr, state:4, pos:p1, group:buggyGroup, mask:noCollision, }); physic.add({ name:'bB'+n, type:'hardbox', mass:massLow, size:[17*size, 17*size, 22*size], //size:[10*size, 10*size, 10*size], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_slow' ), material:debug ? mat.red : mat.meca3, geoSize:[size], geoRot:gr2, state:4, pos:[p1[0]+p2[0], 50*size, p1[2]+p2[2]], group:buggyGroup, mask:noCollision, }); // joint physic.add({ name:'jj_1e_'+n, type:'joint_hinge', body1:'chassis', body2:'bA'+n, pos1:[p1[0], p1[1]-decalY, p1[2]], pos2:[0,0,0], axe1:[1,0,0], axe2:[1,0,0], }); physic.add({ name:'jj_2e_'+n, type:'joint_hinge', body1:'armlow'+n, body2:'bB'+n, pos1:p2, pos2:[0,0,0], axe1:[1,0,0], axe2:[1,0,0], }); // spring joint var springRange = 5*size; var springRestLen = -85*size; physic.add({ type:'joint_spring_dof', name:'jj'+n, body1:'bA'+n, body2:'bB'+n, pos1:[0, 0, 0], pos2:[0, 0, (springRestLen-springRange)*side], angLower: [0, 0, 0], angUpper: [0, 0, 0], linLower: [ 0, 0, -springRange ], linUpper: [ 0, 0, springRange ], useA:true, // index means 0:translationX, 1:translationY, 2:translationZ spring:[0,0,2,0,0,0],//stiffness damping:[0,0,2000,0,0,0],//[2,40000],// period 1 sec for !kG body //stiffness:[2,0.01], //feedback:true, }); } function wheel ( n ) { // mass var massWheel = 10; var massRoller = 10/8; var ext; var wSpeed = speed; var pz; if(n==1 || n==3) pz=-19*size; else pz = 19*size; var wpos = [120*size, 50*size, 109.5*size]; var position = [0,0,0]; if(n==0) position = [wpos[0],wpos[1],wpos[2]] if(n==1) position = [wpos[0],wpos[1],-wpos[2]] if(n==2) position = [-wpos[0],wpos[1],wpos[2]] if(n==3) position = [-wpos[0],wpos[1],-wpos[2]] if(n==0 || n==3){ ext='L'; } else{ ext='R'; } if(translation){ if(n==0 || n==3) wSpeed*=-1; } if(rotation){ if(n==1 || n==3) wSpeed*=-1; } physic.add({ name:'axe'+n, //type:'box', //size:[56*size, 56*size, 14*size], type:'convex', shape:view.getGeometry( 'mecanum', 'meca_wheel_shape' ), size:[size], mass:massWheel, friction:0.1, //rot:[0,0,90], //material:'tmp1', geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_wheel_' + ext ), material:debug ? undefined : mat.meca2, //geoSize:[size], //geoRot:[0,R,0], //geoScale:GR, //, //size:[size], pos:position, state:4, group:buggyGroup, mask:buggyMask, //linear:1, //angular:1, }); // roller *8 var radius = 39*size; var i = 8, angle, y, x, z; var axis = []; var axe = []; while(i--){ angle = -(45*i)*Math.torad; x = (radius * Math.cos(angle)); y = (radius * Math.sin(angle)); z = position[2]; if(ext=='R'){ if(i==0) { axe = [-45, 0, 0 ]; axis = [0,1,1]; } if(i==1) { axe = [-35.264, 30, -35.264 ]; axis = [0.783,0.783,1]; } if(i==2) { axe = [0, 45, -90 ]; axis = [1,0,1]; } if(i==3) { axe = [35.264, 30, 215.264 ]; axis = [0.783,-0.783,1]; } if(i==4) { axe = [45, 0, -180 ]; axis = [0,-1,1]; } if(i==5) { axe = [35.264, -30, -215.264 ]; axis = [-0.783,-0.783,1]; } if(i==6) { axe = [0, -45, -270 ]; axis = [-1,0,1]; } if(i==7) { axe = [-35.264, -30, 35.264 ]; axis = [-0.783,0.783,1]; } } else { if(i==0) { axe = [45, 0, 0 ]; axis = [0,-1,1]; } if(i==1) { axe = [35.264, -30, 35.264 ]; axis = [-0.783,-0.783,1]; } if(i==2) { axe = [0, -45, -90 ]; axis = [-1,0,1]; } if(i==3) { axe = [-35.264, -30, -215.264 ]; axis = [-0.783,0.783,1]; } if(i==4) { axe = [-45, 0, -180 ]; axis = [0,1,1]; } if(i==5) { axe = [-35.264, 30, 215.264 ]; axis = [0.783,0.783,1]; } if(i==6) { axe = [0, 45, -270 ]; axis = [1,0,1]; } if(i==7) { axe = [35.264, 30, -35.264 ]; axis = [0.783,-0.783,1]; } } physic.add({ name:n+'_rr_'+i, type:'convex', shape:view.getGeometry( 'mecanum', 'meca_roller_shape' ), mass:massRoller, //friction:0.7, friction:0.7, size:[size], rot:axe, pos:[x+ position[0], y+ position[1], z], geometry:debug ? undefined : view.getGeometry( 'mecanum', 'meca_roller' ), material:debug ? undefined : mat.meca2, state:4, //margin:0.01, group:buggyGroup, mask:buggyMask, }) physic.add({ name:'jr'+i+n, type:'joint_hinge', body1:'axe'+n, body2:n+'_rr_'+i, pos1:[ x, y, 0], pos2:[ 0, 0, 0], axe1: axis, axe2:[0,0,1], //motor:[true, -speed, 100], }) } // joint wheels var link = 'axis'+n; if(steeringAxis[n]) link = 'axis_s_'+n; physic.add({ name:'jh'+n, type:'joint_hinge', body1:link, body2:'axe'+n, pos1:[ 0, 0, pz], pos2:[ 0, 0, 0], axe1:[0,0,1], axe2:[0,0,1], motor:[true, wSpeed, 100], collision:true, }) }
1
0.736126
1
0.736126
game-dev
MEDIA
0.691756
game-dev,web-frontend
0.892453
1
0.892453
ScRichard/GOTHAJ_RECODE_UNRELEASED
2,174
net/minecraft/client/model/ModelSheep1.java
package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntitySheep; public class ModelSheep1 extends ModelQuadruped { private float headRotationAngleX; public ModelSheep1() { super(12, 0.0F); this.head = new ModelRenderer(this, 0, 0); this.head.addBox(-3.0F, -4.0F, -4.0F, 6, 6, 6, 0.6F); this.head.setRotationPoint(0.0F, 6.0F, -8.0F); this.body = new ModelRenderer(this, 28, 8); this.body.addBox(-4.0F, -10.0F, -7.0F, 8, 16, 6, 1.75F); this.body.setRotationPoint(0.0F, 5.0F, 2.0F); float f = 0.5F; this.leg1 = new ModelRenderer(this, 0, 16); this.leg1.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); this.leg1.setRotationPoint(-3.0F, 12.0F, 7.0F); this.leg2 = new ModelRenderer(this, 0, 16); this.leg2.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); this.leg2.setRotationPoint(3.0F, 12.0F, 7.0F); this.leg3 = new ModelRenderer(this, 0, 16); this.leg3.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); this.leg3.setRotationPoint(-3.0F, 12.0F, -5.0F); this.leg4 = new ModelRenderer(this, 0, 16); this.leg4.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); this.leg4.setRotationPoint(3.0F, 12.0F, -5.0F); } public void setLivingAnimations(EntityLivingBase entitylivingbaseIn, float p_78086_2_, float p_78086_3_, float partialTickTime) { super.setLivingAnimations(entitylivingbaseIn, p_78086_2_, p_78086_3_, partialTickTime); this.head.rotationPointY = 6.0F + ((EntitySheep)entitylivingbaseIn).getHeadRotationPointY(partialTickTime) * 9.0F; this.headRotationAngleX = ((EntitySheep)entitylivingbaseIn).getHeadRotationAngleX(partialTickTime); } public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) { super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); this.head.rotateAngleX = this.headRotationAngleX; } }
1
0.645283
1
0.645283
game-dev
MEDIA
0.80659
game-dev,graphics-rendering
0.668656
1
0.668656
magefree/mage
2,115
Mage.Sets/src/mage/cards/p/PainwrackerOni.java
package mage.cards.p; import java.util.UUID; import mage.MageInt; import mage.abilities.triggers.BeginningOfUpkeepTriggeredAbility; import mage.abilities.condition.Condition; import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition; import mage.abilities.decorator.ConditionalOneShotEffect; import mage.abilities.effects.common.SacrificeControllerEffect; import mage.abilities.keyword.FearAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.ComparisonType; import mage.constants.SubType; import mage.filter.StaticFilters; import mage.filter.common.FilterControlledPermanent; /** * * @author LevelX */ public final class PainwrackerOni extends CardImpl { private static final FilterControlledPermanent filter = new FilterControlledPermanent("Ogre"); static { filter.add(SubType.OGRE.getPredicate()); } private static final Condition condition = new PermanentsOnTheBattlefieldCondition(filter, ComparisonType.EQUAL_TO, 0); public PainwrackerOni (UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{B}{B}"); this.subtype.add(SubType.DEMON, SubType.SPIRIT); this.power = new MageInt(5); this.toughness = new MageInt(4); // Fear (This creature can't be blocked except by artifact creatures and/or black creatures.) this.addAbility(FearAbility.getInstance()); // At the beginning of your upkeep, sacrifice a creature if you don't control an Ogre. this.addAbility(new BeginningOfUpkeepTriggeredAbility( new ConditionalOneShotEffect( new SacrificeControllerEffect(StaticFilters.FILTER_PERMANENT_CREATURE, 1, null), condition, "sacrifice a creature if you don't control an Ogre" ) )); } private PainwrackerOni(final PainwrackerOni card) { super(card); } @Override public PainwrackerOni copy() { return new PainwrackerOni(this); } }
1
0.937831
1
0.937831
game-dev
MEDIA
0.939767
game-dev
0.984131
1
0.984131
lkosson/reportviewercore
3,378
Microsoft.ReportViewer.Common/Microsoft.ReportingServices.RdlObjectModel.Serialization/PropertyMapping.cs
using System; using System.Reflection; namespace Microsoft.ReportingServices.RdlObjectModel.Serialization { internal class PropertyMapping : MemberMapping { internal enum PropertyTypeCode { None, Object, ContainedObject, Boolean, Integer, Size, Enum, ValueType } private PropertyInfo m_property; private int m_index; private PropertyTypeCode m_typeCode; private IPropertyDefinition m_definition; public PropertyInfo Property => m_property; public int Index { get { return m_index; } set { m_index = value; } } public PropertyTypeCode TypeCode { get { return m_typeCode; } set { m_typeCode = value; } } public IPropertyDefinition Definition { get { return m_definition; } set { m_definition = value; } } public PropertyMapping(Type propertyType, string name, string ns, PropertyInfo property) : base(propertyType, name, ns, !property.CanWrite) { m_property = property; } public override void SetValue(object obj, object value) { if (m_typeCode != 0) { IPropertyStore propertyStore = ((ReportObject)obj).PropertyStore; if (m_definition != null) { m_definition.Validate(obj, value); } switch (m_typeCode) { default: propertyStore.SetObject(m_index, value); break; case PropertyTypeCode.ContainedObject: propertyStore.SetObject(m_index, (IContainedObject)value); break; case PropertyTypeCode.Boolean: propertyStore.SetBoolean(m_index, (bool)value); break; case PropertyTypeCode.Integer: case PropertyTypeCode.Enum: propertyStore.SetInteger(m_index, (int)value); break; case PropertyTypeCode.Size: propertyStore.SetSize(m_index, (ReportSize)value); break; } } else { m_property.SetValue(obj, value, null); } } public override object GetValue(object obj) { if (m_typeCode != 0) { IPropertyStore propertyStore = ((ReportObject)obj).PropertyStore; switch (m_typeCode) { default: return propertyStore.GetObject(m_index); case PropertyTypeCode.Boolean: return propertyStore.GetBoolean(m_index); case PropertyTypeCode.Integer: return propertyStore.GetInteger(m_index); case PropertyTypeCode.Size: return propertyStore.GetSize(m_index); case PropertyTypeCode.Enum: { int integer = propertyStore.GetInteger(m_index); return Enum.ToObject(Type, integer); } case PropertyTypeCode.ValueType: { object obj2 = propertyStore.GetObject(m_index); if (obj2 == null) { obj2 = Activator.CreateInstance(Type); } return obj2; } } } return m_property.GetValue(obj, null); } public override bool HasValue(object obj) { if (m_typeCode != 0) { IPropertyStore propertyStore = ((ReportObject)obj).PropertyStore; switch (m_typeCode) { default: return propertyStore.ContainsObject(m_index); case PropertyTypeCode.Boolean: return propertyStore.ContainsBoolean(m_index); case PropertyTypeCode.Integer: case PropertyTypeCode.Enum: return propertyStore.ContainsInteger(m_index); case PropertyTypeCode.Size: return propertyStore.ContainsSize(m_index); } } return m_property.GetValue(obj, null) != null; } } }
1
0.829467
1
0.829467
game-dev
MEDIA
0.393834
game-dev,desktop-app
0.951773
1
0.951773
galister/WlxOverlay
4,405
Core/Interactions/Internal/InteractionData.cs
using WlxOverlay.Backend; using WlxOverlay.Numerics; using WlxOverlay.Overlays; namespace WlxOverlay.Core.Interactions.Internal; internal class InteractionData { public readonly BaseOverlay Overlay; public readonly List<PointerHit> HitsThisFrame = new(2); public PointerData? PrimaryPointer; public InteractionData(BaseOverlay overlay) { Overlay = overlay; } public void Begin() { HitsThisFrame.Clear(); } public bool TestInteraction(PointerData pointer, out PointerHit hitData) { if (Overlay._overlay != null) { var ok = Overlay._overlay.TestInteraction(pointer.Pointer, out hitData); if (ok) hitData.modifier = pointer.Mode; return ok; } hitData = null!; return false; } #region Pointer Interaction private void EnsurePrimary(PointerData data) { if (PrimaryPointer != null) { if (PrimaryPointer.Pointer == data.Pointer) return; PrimaryPointer.TryDrop(this); } PrimaryPointer = data; } internal void OnPointerHover(PointerData pointer, PointerHit hitData) { PrimaryPointer ??= pointer; HitsThisFrame.Add(hitData); hitData.isPrimary = PrimaryPointer.Pointer == pointer.Pointer; if (Overlay is IInteractable interactable) interactable.OnPointerHover(hitData); } internal void OnPointerLeft(LeftRight hand) { if (PrimaryPointer?.Pointer.Hand == hand) PrimaryPointer = null; if (Overlay is IInteractable interactable) interactable.OnPointerLeft(hand); } internal void OnPointerDown(PointerData pointer, PointerHit hitData) { EnsurePrimary(pointer); hitData.isPrimary = true; if (Overlay is IInteractable interactable) interactable.OnPointerDown(hitData); } internal void OnPointerUp(PointerHit hitData) { if (Overlay is IInteractable interactable) interactable.OnPointerUp(hitData); } internal void OnScroll(PointerHit hitData, float value) { if (Overlay is IInteractable interactable) interactable.OnScroll(hitData, value); } #endregion #region Grab Interaction /// <summary> /// Default spawn point, relative to HMD /// </summary> private Vector3 _grabOffset; internal void OnGrabbed(PointerData pointer, PointerHit hitData) { if (PrimaryPointer != null && pointer != PrimaryPointer) PrimaryPointer.TryDrop(this); PrimaryPointer = pointer; _grabOffset = PrimaryPointer.Pointer.Transform.AffineInverse() * Overlay.Transform.origin; if (Overlay is IGrabbable grabbable) grabbable.OnGrabbed(hitData); } internal void OnGrabHeld() { if (PrimaryPointer == null) return; Overlay.Transform.origin = PrimaryPointer!.Pointer.Transform.TranslatedLocal(_grabOffset).origin; Overlay.OnOrientationChanged(); } internal void OnDropped() { Overlay.SavedSpawnPosition = XrBackend.Current.Input.HmdTransform.AffineInverse() * Overlay.Transform.origin; if (Overlay is IGrabbable grabbable) grabbable.OnDropped(); } internal void OnClickWhileHeld() { OnGrabHeld(); if (Overlay is IGrabbable grabbable) grabbable.OnClickWhileHeld(); } internal void OnAltClickWhileHeld() { OnGrabHeld(); if (Overlay is IGrabbable grabbable) grabbable.OnAltClickWhileHeld(); } internal void OnScrollSize(float value) { var oldScale = Overlay.LocalScale; Overlay.LocalScale *= Vector3.One - Vector3.One * Mathf.Pow(value, 3) * 2; if (Overlay.LocalScale.x < 0.35f) Overlay.LocalScale = oldScale; if (Overlay.LocalScale.x > 10f) Overlay.LocalScale = oldScale; } internal void OnScrollDistance(float value) { var newGrabOffset = _grabOffset + _grabOffset.Normalized() * Mathf.Pow(value, 3); var distance = newGrabOffset.Length(); if (distance < 0.3f && value < 0 || distance > 10f && value > 0) return; _grabOffset = newGrabOffset; } #endregion }
1
0.879062
1
0.879062
game-dev
MEDIA
0.867075
game-dev
0.940499
1
0.940499
ellermister/MapleStory
5,394
scripts/npc/2042000.js
var status = 0; function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == 1) status++; else cm.dispose(); if (status == 0 && mode == 1) { var selStr = "Sign up for 껪\r\n#L100#Trade Maple Coin.#l"; var found = false; for (var i = 0; i < 9; i++){ if (getCPQField(i+1) != "") { selStr += "\r\n#b#L" + i + "# " + getCPQField(i+1) + "#l#k"; found = true; } } if (cm.getParty() == null) { cm.sendSimple("㲻һ\r\n#L100#Ҷҽ#l"); } else { if (cm.isLeader()) { if (found) { cm.sendSimple(selStr); } else { cm.sendSimple("Ŀǰûз.\r\n#L100#Ҷҽ.#l"); } } else { cm.sendSimple("㷽쵼˺˵.\r\n#L100#Ҷҽ.#l"); } } } else if (status == 1) { if (selection == 100) { cm.sendSimple("#b#L0#50 Ҷ= spiegelmann#l\r\n#L1#30 Ҷ= spiegelmannʯ#l\r\n#L2#50 ķҶӲ = spiegelmann#l#k"); } else if (selection >= 0 && selection < 9) { var mapid = 980000000+((selection+1)*100); if (cm.getEventManager("cpq").getInstance("cpq"+mapid) == null) { if ((cm.getParty() != null && 1 < cm.getParty().getMembers().size() && cm.getParty().getMembers().size() < (selection == 4 || selection == 5 || selection == 8 ? 4 : 3)) || cm.getPlayer().isGM()) { if (checkLevelsAndMap(30, 255) == 1) { cm.sendOk("ĶDzʵˮƽ."); cm.dispose(); } else if (checkLevelsAndMap(30, 255) == 2) { cm.sendOk("ľۻᶼͼ."); cm.dispose(); } else { cm.getEventManager("cpq").startInstance(""+mapid, cm.getPlayer()); cm.dispose(); } } else { cm.sendOk("㷽ʵĴС."); } } else if (cm.getParty() != null && cm.getEventManager("cpq").getInstance("cpq"+mapid).getPlayerCount() == cm.getParty().getMembers().size()) { if (checkLevelsAndMap(30, 255) == 1) { cm.sendOk("ĶDzʵˮƽ."); cm.dispose(); } else if (checkLevelsAndMap(30, 255) == 2) { cm.sendOk("ľۻᶼͼ."); cm.dispose(); } else { //Send challenge packet here var owner = cm.getChannelServer().getPlayerStorage().getCharacterByName(cm.getEventManager("cpq").getInstance("cpq"+mapid).getPlayers().get(0).getParty().getLeader().getName()); owner.addCarnivalRequest(cm.getCarnivalChallenge(cm.getChar())); //if (owner.getConversation() != 1) { cm.openNpc(owner.getClient(), 2042001); //} cm.sendOk("սѷ."); cm.dispose(); } } else { cm.sendOk("˫껪ͬijԱ."); cm.dispose(); } } else { cm.dispose(); } } else if (status == 2) { if (selection == 0) { if (!cm.haveItem(4001129,50)) { cm.sendOk("ûиƷ."); } else if (!cm.canHold(1122007,1)) { cm.sendOk("Please make room"); } else { cm.gainItem(1122007,1); cm.gainItem(4001129,-50); } cm.dispose(); } else if (selection == 1) { if (!cm.haveItem(4001129,30)) { cm.sendOk("ûиƷ."); } else if (!cm.canHold(2041211,1)) { cm.sendOk("Please make room"); } else { cm.gainItem(2041211,1); cm.gainItem(4001129,-30); } cm.dispose(); } else if (selection == 2) { if (!cm.haveItem(4001254,50)) { cm.sendOk("ûиƷ."); } else if (!cm.canHold(1122058,1)) { cm.sendOk("Please make room"); } else { cm.gainItem(1122058,1); cm.gainItem(4001254,-50); } cm.dispose(); } } } function checkLevelsAndMap(lowestlevel, highestlevel) { var party = cm.getParty().getMembers(); var mapId = cm.getMapId(); var valid = 0; var inMap = 0; var it = party.iterator(); while (it.hasNext()) { var cPlayer = it.next(); if (!(cPlayer.getLevel() >= lowestlevel && cPlayer.getLevel() <= highestlevel) && cPlayer.getJobId() != 900) { valid = 1; } if (cPlayer.getMapid() != mapId) { valid = 2; } } return valid; } function getCPQField(fieldnumber) { var status = ""; var event1 = cm.getEventManager("cpq"); if (event1 != null) { var event = event1.getInstance("cpq"+(980000000+(fieldnumber*100))); if (event == null && fieldnumber != 5 && fieldnumber != 6 && fieldnumber != 9) { status = "Carnival Field "+fieldnumber+"(2v2)"; } else if (event == null) { status = "Carnival Field "+fieldnumber+"(3v3)"; } else if (event != null && (event.getProperty("started").equals("false"))) { var averagelevel = 0; for (i = 0; i < event.getPlayerCount(); i++) { averagelevel += event.getPlayers().get(i).getLevel(); } averagelevel /= event.getPlayerCount(); status = event.getPlayers().get(0).getParty().getLeader().getName()+"/"+event.getPlayerCount()+"users/Avg. Level "+averagelevel; } } return status; }
1
0.638414
1
0.638414
game-dev
MEDIA
0.876942
game-dev
0.847537
1
0.847537
SourceEngine-CommunityEdition/source
3,188
utils/scenemanager/multiplerequest.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "resource.h" #include "MultipleRequest.h" #include "workspacemanager.h" static CMultipleParams g_Params; //----------------------------------------------------------------------------- // Purpose: // Input : hwndDlg - // uMsg - // wParam - // lParam - // Output : static BOOL CALLBACK //----------------------------------------------------------------------------- static BOOL CALLBACK MultipleRequestDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch(uMsg) { case WM_INITDIALOG: // Insert code here to put the string (to find and replace with) // into the edit controls. // ... { g_Params.PositionSelf( hwndDlg ); SetDlgItemText( hwndDlg, IDC_PROMPT, g_Params.m_szPrompt ); SetWindowText( hwndDlg, g_Params.m_szDialogTitle ); SetFocus( GetDlgItem( hwndDlg, IDC_INPUTSTRING ) ); SendMessage( GetDlgItem( hwndDlg, IDC_INPUTSTRING ), EM_SETSEL, 0, MAKELONG(0, 0xffff) ); } return FALSE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_YESALL: EndDialog( hwndDlg, CMultipleParams::YES_ALL ); break; case IDC_YES: EndDialog( hwndDlg, CMultipleParams::YES ); break; case IDC_NOSINGLE: EndDialog( hwndDlg, CMultipleParams::NO ); break; case IDC_NOALL: EndDialog( hwndDlg, CMultipleParams::NO_ALL ); break; //case IDCANCEL: // EndDialog( hwndDlg, CMultipleParams::CANCEL ); // break; } return TRUE; } return FALSE; } static int g_MRContext = 1; static int g_MRCurrentContext; static int g_MRLastResult = -1; void MultipleRequestChangeContext() { ++g_MRContext; } //----------------------------------------------------------------------------- // Purpose: // Input : *view - // *actor - // Output : int //----------------------------------------------------------------------------- int _MultipleRequest( CMultipleParams *params ) { int retval = -1; if ( g_MRCurrentContext == g_MRContext && g_MRLastResult != -1 ) { if ( g_MRLastResult == CMultipleParams::YES_ALL ) { retval = 0; } if ( g_MRLastResult == CMultipleParams::NO_ALL ) { retval = 1; } } if ( retval == -1 ) { g_Params = *params; retval = DialogBox( (HINSTANCE)GetModuleHandle( 0 ), MAKEINTRESOURCE( IDD_MULTIPLEQUESTION ), (HWND)GetWorkspaceManager()->getHandle(), (DLGPROC)MultipleRequestDialogProc ); *params = g_Params; } g_MRCurrentContext = g_MRContext; g_MRLastResult = retval; switch ( retval ) { case CMultipleParams::YES_ALL: case CMultipleParams::YES: return 0; case CMultipleParams::NO_ALL: case CMultipleParams::NO: return 1; default: case CMultipleParams::CANCEL: return 2; } Assert( 0 ); return 1; } int MultipleRequest( char const *prompt ) { CMultipleParams params; memset( &params, 0, sizeof( params ) ); Q_strcpy( params.m_szDialogTitle, g_appTitle ); Q_strncpy( params.m_szPrompt, prompt, sizeof( params.m_szPrompt ) ); return _MultipleRequest( &params ); }
1
0.940438
1
0.940438
game-dev
MEDIA
0.410329
game-dev,desktop-app
0.89538
1
0.89538
bungaku-moe/NikkeViewerEX
4,354
Assets/Spine Runtimes/Spine-4.0/spine-csharp-4.0/BoneData.cs
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; namespace Spine { public class BoneData { internal int index; internal string name; internal BoneData parent; internal float length; internal float x, y, rotation, scaleX = 1, scaleY = 1, shearX, shearY; internal TransformMode transformMode = TransformMode.Normal; internal bool skinRequired; /// <summary>The index of the bone in Skeleton.Bones</summary> public int Index { get { return index; } } /// <summary>The name of the bone, which is unique across all bones in the skeleton.</summary> public string Name { get { return name; } } /// <summary>May be null.</summary> public BoneData Parent { get { return parent; } } public float Length { get { return length; } set { length = value; } } /// <summary>Local X translation.</summary> public float X { get { return x; } set { x = value; } } /// <summary>Local Y translation.</summary> public float Y { get { return y; } set { y = value; } } /// <summary>Local rotation.</summary> public float Rotation { get { return rotation; } set { rotation = value; } } /// <summary>Local scaleX.</summary> public float ScaleX { get { return scaleX; } set { scaleX = value; } } /// <summary>Local scaleY.</summary> public float ScaleY { get { return scaleY; } set { scaleY = value; } } /// <summary>Local shearX.</summary> public float ShearX { get { return shearX; } set { shearX = value; } } /// <summary>Local shearY.</summary> public float ShearY { get { return shearY; } set { shearY = value; } } /// <summary>The transform mode for how parent world transforms affect this bone.</summary> public TransformMode TransformMode { get { return transformMode; } set { transformMode = value; } } ///<summary>When true, <see cref="Skeleton.UpdateWorldTransform()"/> only updates this bone if the <see cref="Skeleton.Skin"/> contains this /// bone.</summary> /// <seealso cref="Skin.Bones"/> public bool SkinRequired { get { return skinRequired; } set { skinRequired = value; } } /// <param name="parent">May be null.</param> public BoneData (int index, string name, BoneData parent) { if (index < 0) throw new ArgumentException("index must be >= 0", "index"); if (name == null) throw new ArgumentNullException("name", "name cannot be null."); this.index = index; this.name = name; this.parent = parent; } override public string ToString () { return name; } } [Flags] public enum TransformMode { //0000 0 Flip Scale Rotation Normal = 0, // 0000 OnlyTranslation = 7, // 0111 NoRotationOrReflection = 1, // 0001 NoScale = 2, // 0010 NoScaleOrReflection = 6, // 0110 } }
1
0.803899
1
0.803899
game-dev
MEDIA
0.744949
game-dev
0.653034
1
0.653034
MATTYOneInc/AionEncomBase_Java8
4,503
AL-Game/data/scripts/system/handlers/quest/verteron/_1162AltenosWeddingRing.java
/* * This file is part of aion-unique <aion-unique.org>. * * aion-unique 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-unique 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-unique. If not, see <http://www.gnu.org/licenses/>. */ package quest.verteron; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestDialog; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; /** * @author Balthazar. redone DainAvenger */ public class _1162AltenosWeddingRing extends QuestHandler { private final static int questId = 1162; private int rewardId; public _1162AltenosWeddingRing() { super(questId); } @Override public void register() { qe.registerQuestNpc(203095).addOnQuestStart(questId); qe.registerQuestNpc(203095).addOnTalkEvent(questId); qe.registerQuestNpc(203093).addOnTalkEvent(questId); qe.registerQuestNpc(700005).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(final QuestEnv env) { final Player player = env.getPlayer(); int targetId = 0; if (env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 203095) { if (env.getDialog() == QuestDialog.START_DIALOG) return sendQuestDialog(env, 1011); else return sendQuestStartDialog(env); } } if (qs == null) return false; if (qs.getStatus() == QuestStatus.START) { switch (targetId) { case 700005: { switch (env.getDialog()) { case USE_OBJECT: return sendQuestDialog(env, 3739); case STEP_TO_1: if (player.getInventory().getItemCountByItemId(182200563) == 0) { giveQuestItem(env, 182200563, 1); changeQuestStep(env, 0, 1, false); return closeDialogWindow(env); } } } case 203095: switch (env.getDialog()) { case START_DIALOG: { return sendQuestDialog(env, 1352); } case CHECK_COLLECTED_ITEMS: if (QuestService.collectItemCheck(env, true)) { rewardId = 0; changeQuestStep(env, 1, 1, true); return sendQuestDialog(env, 5); } else { return sendQuestDialog(env, 1693); } case STEP_TO_2: return closeDialogWindow(env); } case 203093: switch (env.getDialog()) { case START_DIALOG: { return sendQuestDialog(env, 2034); } case CHECK_COLLECTED_ITEMS: if (QuestService.collectItemCheck(env, true)) { rewardId = 1; qs.setStatus(QuestStatus.REWARD); changeQuestStep(env, 1, 11, false); return sendQuestDialog(env, 6); } else { return sendQuestDialog(env, 2375); } case STEP_TO_2: return closeDialogWindow(env); } } } else if (qs == null || qs.getStatus() == QuestStatus.REWARD) { if (targetId == 203095 && qs.getQuestVarById(0) == 1) { if (env.getDialogId() == 1009) { return sendQuestDialog(env, 5); } else return sendQuestEndDialog(env, rewardId); } if (targetId == 203093 && qs.getQuestVarById(0) == 11) { if (env.getDialogId() == 1009) { return sendQuestDialog(env, 6); } else return sendQuestEndDialog(env, rewardId); } } return false; } }
1
0.899719
1
0.899719
game-dev
MEDIA
0.912668
game-dev
0.951725
1
0.951725
notmario/MoreFluff
14,823
other/superboss.lua
function init() G.get_new_superboss = function() local superboss_pool = {} for k, v in pairs(G.P_BLINDS) do if v.debuff.superboss or v.debuff.akyrs_blind_difficulty == "expert" then if k ~= "bl_akyrs_expert_inflation" then superboss_pool[k] = true end end end local _, boss = pseudorandom_element(superboss_pool, pseudoseed('boss')) return boss end SMODS.Voucher { key = "superboss_ticket", atlas = "mf_vouchers", pos = { x = 3, y = 0 }, no_collection = true, cost = 0, loc_vars = function(self) return { vars = { G.GAME.win_ante or 8, (G.GAME.win_ante and G.GAME.round_resets.ante) and math.floor( G.GAME.round_resets.ante + (G.GAME.win_ante - G.GAME.round_resets.ante % G.GAME.win_ante) ) or 8, }, } end, redeem = function(self, card) G.GAME.superboss_active = true -- Increase ante scaling G.GAME.modifiers.scaling = G.GAME.modifiers.scaling or 1 G.GAME.modifiers.bonus_scaling = 3 G.GAME.modifiers.scaling = G.GAME.modifiers.scaling + G.GAME.modifiers.bonus_scaling G.GAME.round_resets.blind_choices.Small = "bl_mf_bigger_blind" G.GAME.round_resets.blind_choices.Big = get_new_boss() G.GAME.round_resets.blind_choices.Boss = G.get_new_superboss() ease_background_colour_blind(G.STATE, 'Small Blind') end, requires = {"v_mf_impossiblevoucher"}, } SMODS.Blind { key = "bigger_blind", name = "Bigger Blind", atlas = "mf_blinds", pos = {x=0,y=0}, dollars = 6, mult = 1, boss_colour = HEX('793aab'), no_collection = true, in_pool = function(self) return false end } SMODS.Blind { key = "violet_vessel_dx", name = "Violet Vessel DX", atlas = "mf_blinds", pos = {x=0,y=1}, discovered = true, dollars = 10, mult = 24, boss_colour = HEX('ac3232'), debuff = { -- if you have aiko installed it gets more difficult lolollolol superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, boss = { min=9, max=10, showdown = true }, disable = function(self) G.GAME.blind.chips = G.GAME.blind.chips/8 G.GAME.blind.chip_text = number_format(G.GAME.blind.chips) end, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "cerulean_bell_dx", name = "Cerulean Bell DX", atlas = "mf_blinds", pos = {x=0,y=2}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, force_select_count = 3, }, loc_vars = function(self) return { vars = { self.debuff.force_select_count } } end, disable = function(self) for k, v in ipairs(G.playing_cards) do v.ability.forced_selection = nil end end, drawn_to_hand = function(self) local any_forced = nil for k, v in ipairs(G.hand.cards) do if v.ability.forced_selection then any_forced = true end end if not any_forced then G.hand:unhighlight_all() local cb_dx_pool = {} for _, card in pairs(G.hand.cards) do cb_dx_pool[#cb_dx_pool + 1] = card end for _ = 1, self.debuff.force_select_count do if #cb_dx_pool == 0 then break end local forced_card = pseudorandom_element(cb_dx_pool, pseudoseed('cerulean_bell_dx')) -- table.remove(cb_dx_pool, forced_card) for i = 1,#cb_dx_pool do if cb_dx_pool[i] == forced_card then table.remove(cb_dx_pool, i) break end end forced_card.ability.forced_selection = true G.hand:add_to_highlighted(forced_card) end end end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "needle_dx", name = "The Needle DX", atlas = "mf_blinds", pos = {x=0,y=3}, discovered = true, dollars = 10, mult = 1, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, disable = function(self) ease_hands_played(G.GAME.blind.hands_sub) ease_discard(G.GAME.blind.discards_sub) G.GAME.current_round.discards_used = G.GAME.current_round.discards_used - G.GAME.blind.discards_sub end, set_blind = function(self) G.GAME.blind.hands_sub = G.GAME.round_resets.hands - 1 ease_hands_played(-G.GAME.blind.hands_sub) G.GAME.blind.discards_sub = G.GAME.round_resets.discards - 1 ease_discard(-G.GAME.blind.discards_sub) G.GAME.current_round.discards_used = G.GAME.current_round.discards_used + G.GAME.blind.discards_sub end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "manacle_dx", name = "The Manacle DX", atlas = "mf_blinds", pos = {x=0,y=4}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, disable = function(self) if not G.GAME.blind.disabled then G.hand:change_size(3) G.FUNCS.draw_from_deck_to_hand(3) end end, defeat = function(self) if not G.GAME.blind.disabled then G.hand:change_size(3) end end, set_blind = function(self) G.hand:change_size(-3) end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "pillar_dx", name = "The Pillar DX", atlas = "mf_blinds", pos = {x=0,y=5}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, set_blind = function(self) for _, card in pairs(G.playing_cards) do if card.ability.mf_played_this_game and pseudorandom('pillar_dx') < 1 / 2 then card.ability.mf_played_this_game = false end end end, recalc_debuff = function(self, card, from_blind) if not G.GAME.blind.disabled and card.area ~= G.jokers then if card.ability.mf_played_this_game then return true end end return false end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "serpent_dx", name = "The Serpent DX", atlas = "mf_blinds", pos = {x=0,y=6}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "club_dx", name = "The Club DX", atlas = "mf_blinds", pos = {x=0,y=7}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, recalc_debuff = function(self, card, from_blind) if not G.GAME.blind.disabled and card.area ~= G.jokers then if not card:is_suit("Clubs") then return true end end return false end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "goad_dx", name = "The Goad DX", atlas = "mf_blinds", pos = {x=0,y=8}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, recalc_debuff = function(self, card, from_blind) if not G.GAME.blind.disabled and card.area ~= G.jokers then if not card:is_suit("Spades") then return true end end return false end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "window_dx", name = "The Window DX", atlas = "mf_blinds", pos = {x=0,y=9}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, recalc_debuff = function(self, card, from_blind) if not G.GAME.blind.disabled and card.area ~= G.jokers then if not card:is_suit("Diamonds") then return true end end return false end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "head_dx", name = "The Head DX", atlas = "mf_blinds", pos = {x=0,y=10}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, recalc_debuff = function(self, card, from_blind) if not G.GAME.blind.disabled and card.area ~= G.jokers then if not card:is_suit("Hearts") then return true end end return false end, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "arm_dx", name = "The Arm DX", atlas = "mf_blinds", pos = {x=0,y=11}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, boss = { min=9, max=10, showdown = true }, debuff_hand = function(self, cards, hand, handname, check) if G.GAME.blind.disabled then return end G.GAME.blind.triggered = false if to_number(G.GAME.hands[handname].level) > 0 then G.GAME.blind.triggered = true if not check then level_up_hand(nil, handname, nil, -G.GAME.hands[handname].level) end end end, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "wheel_dx", name = "The Wheel DX", atlas = "mf_blinds", pos = {x=0,y=12}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, boss = { min=9, max=10, showdown = true }, stay_flipped = function(self, area, card) if not G.GAME.blind.disabled then if area == G.hand then for _, other_card in pairs(G.hand.cards) do if other_card.facing == "front" then return true end end end end return false end, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "house_dx", name = "The House DX", atlas = "mf_blinds", pos = {x=0,y=13}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, boss = { min=9, max=10, showdown = true }, drawn_to_hand = function(self) if not G.GAME.blind.has_discarded then for _, v in ipairs(G.hand.cards) do G.hand.highlighted[#G.hand.highlighted+1] = v v:highlight(true) end G.FUNCS.discard_cards_from_highlighted(nil, true) G.GAME.blind.has_discarded = true end end, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "psychic_dx", name = "The Psychic DX", atlas = "mf_blinds", pos = {x=0,y=14}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, h_size_le = 4, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, boss = { min=9, max=10, showdown = true }, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Blind { key = "hook_dx", name = "The Hook DX", atlas = "mf_blinds", pos = {x=0,y=15}, discovered = true, dollars = 10, mult = 3, boss_colour = HEX('ac3232'), debuff = { superboss = true, akyrs_blind_difficulty = "dx", akyrs_cannot_be_disabled = true, }, boss = { min=9, max=10, showdown = true }, drawn_to_hand = function(self) if G.GAME.blind.should_discard then for _, v in ipairs(G.hand.cards) do G.hand.highlighted[#G.hand.highlighted+1] = v v:highlight(true) end G.FUNCS.discard_cards_from_highlighted(nil, true) G.GAME.blind.should_discard = false end end, press_play = function(self) G.GAME.blind.should_discard = true end, in_pool = function(self) return G.GAME.round_resets.ante > G.GAME.win_ante end } SMODS.Challenge { key = "superboss_always", rules = { custom = { { id = "mf_superboss_active" }, { id = "scaling", value = 4 }, { id = "bonus_scaling", value = 4 }, }, modifiers = { { id = "dollars", value = 14 }, }, }, consumeables = { { id = "c_judgement" }, }, } end return init
1
0.892251
1
0.892251
game-dev
MEDIA
0.960339
game-dev,testing-qa
0.870244
1
0.870244
StranikS-Scan/WorldOfTanks-Decompiled
1,913
source/res/frontline/scripts/client/frontline_personality.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: frontline/scripts/client/frontline_personality.py from account_helpers.AccountSettings import AccountSettings, KEY_SETTINGS from frontline_common.constants import ACCOUNT_DEFAULT_SETTINGS from constants import ARENA_GUI_TYPE, PREBATTLE_TYPE, QUEUE_TYPE, ARENA_BONUS_TYPE from constants_utils import AbstractBattleMode from gui.override_scaleform_views_manager import g_overrideScaleFormViewsConfig from gui.prb_control.settings import PREBATTLE_ACTION_NAME from gui.Scaleform.genConsts.EPICBATTLES_ALIASES import EPICBATTLES_ALIASES LOBBY_EXT_PACKAGES = ['frontline.gui.Scaleform.daapi.view.lobby', 'frontline.gui.Scaleform.daapi.view.lobby.hangar'] class ClientFrontlineBattleMode(AbstractBattleMode): _PREBATTLE_TYPE = PREBATTLE_TYPE.EPIC _QUEUE_TYPE = QUEUE_TYPE.EPIC _ARENA_BONUS_TYPE = ARENA_BONUS_TYPE.EPIC_BATTLE _ARENA_GUI_TYPE = ARENA_GUI_TYPE.EPIC_BATTLE _CLIENT_PRB_ACTION_NAME = PREBATTLE_ACTION_NAME.EPIC _CLIENT_BANNER_ENTRY_POINT_ALIAS = EPICBATTLES_ALIASES.EPIC_BATTLES_ENTRY_POINT @property def _client_bannerEntryPointValidatorMethod(self): from frontline.gui.Scaleform.daapi.view.lobby.hangar.entry_point import isEpicBattlesEntryPointAvailable return isEpicBattlesEntryPointAvailable @property def _client_bannerEntryPointLUIRule(self): from gui.limited_ui.lui_rules_storage import LuiRules return LuiRules.EPIC_BATTLES_ENTRY_POINT def preInit(): battleMode = ClientFrontlineBattleMode(__name__) battleMode.registerBannerEntryPointValidatorMethod() battleMode.registerBannerEntryPointLUIRule() def init(): AccountSettings.overrideDefaultSettings(KEY_SETTINGS, ACCOUNT_DEFAULT_SETTINGS) g_overrideScaleFormViewsConfig.initExtensionLobbyPackages(__name__, LOBBY_EXT_PACKAGES) def start(): pass def fini(): pass
1
0.825918
1
0.825918
game-dev
MEDIA
0.902347
game-dev
0.903427
1
0.903427
HabitRPG/habitica-ios
2,053
Habitica API Client/Habitica API Client/Models/Content/APIQuest.swift
// // APIQuest.swift // Habitica API Client // // Created by Phillip Thelen on 12.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class APIQuest: QuestProtocol, Decodable { var isSubscriberItem: Bool = false var completion: String? var category: String? var boss: QuestBossProtocol? var collect: [QuestCollectProtocol]? var key: String? var text: String? var notes: String? var value: Float = 0 var itemType: String? var drop: QuestDropProtocol? var colors: QuestColorsProtocol? var eventStart: Date? var eventEnd: Date? var isValid: Bool = true public var isManaged: Bool = false enum CodingKeys: String, CodingKey { case key case text case notes case boss case collect case value case completion case category case drop case colors case event } public required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) key = try? values.decode(String.self, forKey: .key) text = try? values.decode(String.self, forKey: .text) notes = try? values.decode(String.self, forKey: .notes) value = (try? values.decode(Float.self, forKey: .value)) ?? 0 boss = try? values.decode(APIQuestBoss.self, forKey: .boss) collect = try? values.decode([String: APIQuestCollect].self, forKey: .collect).map({ (key, questCollect) in questCollect.key = key return questCollect }) completion = try? values.decode(String.self, forKey: .completion) category = try? values.decode(String.self, forKey: .category) drop = try? values.decode(APIQuestDrop.self, forKey: .drop) colors = try? values.decode(APIQuestColors.self, forKey: .colors) let event = try? values.decode(APIEvent.self, forKey: .event) eventStart = event?.start eventEnd = event?.end } }
1
0.936024
1
0.936024
game-dev
MEDIA
0.645124
game-dev
0.93881
1
0.93881
erwincoumans/experiments
2,855
bullet2/BulletCollision/CollisionShapes/btConvex2dShape.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_CONVEX_2D_SHAPE_H #define BT_CONVEX_2D_SHAPE_H #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types ///The btConvex2dShape allows to use arbitrary convex shapes as 2d convex shapes, with the Z component assumed to be 0. ///For 2d boxes, the btBox2dShape is recommended. ATTRIBUTE_ALIGNED16(class) btConvex2dShape : public btConvexShape { btConvexShape* m_childConvexShape; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btConvex2dShape( btConvexShape* convexChildShape); virtual ~btConvex2dShape(); virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; btConvexShape* getChildShape() { return m_childConvexShape; } const btConvexShape* getChildShape() const { return m_childConvexShape; } virtual const char* getName()const { return "Convex2dShape"; } /////////////////////////// ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void setLocalScaling(const btVector3& scaling) ; virtual const btVector3& getLocalScaling() const ; virtual void setMargin(btScalar margin); virtual btScalar getMargin() const; virtual int getNumPreferredPenetrationDirections() const; virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const; }; #endif //BT_CONVEX_2D_SHAPE_H
1
0.953012
1
0.953012
game-dev
MEDIA
0.990108
game-dev
0.709688
1
0.709688
doyubkim/fluid-engine-dev
3,532
include/jet/grid_boundary_condition_solver3.h
// Copyright (c) 2018 Doyub Kim // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #ifndef INCLUDE_JET_GRID_BOUNDARY_CONDITION_SOLVER3_H_ #define INCLUDE_JET_GRID_BOUNDARY_CONDITION_SOLVER3_H_ #include <jet/collider3.h> #include <jet/constants.h> #include <jet/face_centered_grid3.h> #include <jet/scalar_field3.h> #include <memory> namespace jet { //! //! \brief Abstract base class for 3-D boundary condition solver for grids. //! //! This is a helper class to constrain the 3-D velocity field with given //! collider object. It also determines whether to open any domain boundaries. //! To control the friction level, tune the collider parameter. //! class GridBoundaryConditionSolver3 { public: //! Default constructor. GridBoundaryConditionSolver3(); //! Default destructor. virtual ~GridBoundaryConditionSolver3(); //! Returns associated collider. const Collider3Ptr& collider() const; //! //! \brief Applies new collider and build the internals. //! //! This function is called to apply new collider and build the internal //! cache. To provide a hint to the cache, info for the expected velocity //! grid that will be constrained is provided. //! //! \param newCollider New collider to apply. //! \param gridSize Size of the velocity grid to be constrained. //! \param gridSpacing Grid spacing of the velocity grid to be constrained. //! \param gridOrigin Origin of the velocity grid to be constrained. //! void updateCollider( const Collider3Ptr& newCollider, const Size3& gridSize, const Vector3D& gridSpacing, const Vector3D& gridOrigin); //! Returns the closed domain boundary flag. int closedDomainBoundaryFlag() const; //! Sets the closed domain boundary flag. void setClosedDomainBoundaryFlag(int flag); //! //! Constrains the velocity field to conform the collider boundary. //! //! \param velocity Input and output velocity grid. //! \param extrapolationDepth Number of inner-collider grid cells that //! velocity will get extrapolated. //! virtual void constrainVelocity( FaceCenteredGrid3* velocity, unsigned int extrapolationDepth = 5) = 0; //! Returns the signed distance field of the collider. virtual ScalarField3Ptr colliderSdf() const = 0; //! Returns the velocity field of the collider. virtual VectorField3Ptr colliderVelocityField() const = 0; protected: //! Invoked when a new collider is set. virtual void onColliderUpdated( const Size3& gridSize, const Vector3D& gridSpacing, const Vector3D& gridOrigin) = 0; //! Returns the size of the velocity grid to be constrained. const Size3& gridSize() const; //! Returns the spacing of the velocity grid to be constrained. const Vector3D& gridSpacing() const; //! Returns the origin of the velocity grid to be constrained. const Vector3D& gridOrigin() const; private: Collider3Ptr _collider; Size3 _gridSize; Vector3D _gridSpacing; Vector3D _gridOrigin; int _closedDomainBoundaryFlag = kDirectionAll; }; //! Shared pointer type for the GridBoundaryConditionSolver3. typedef std::shared_ptr<GridBoundaryConditionSolver3> GridBoundaryConditionSolver3Ptr; } // namespace jet #endif // INCLUDE_JET_GRID_BOUNDARY_CONDITION_SOLVER3_H_
1
0.898963
1
0.898963
game-dev
MEDIA
0.931891
game-dev
0.901335
1
0.901335
Photon-GitHub/AntiCheatAddition
2,118
src/main/java/de/photon/anticheataddition/util/minecraft/world/region/Region.java
package de.photon.anticheataddition.util.minecraft.world.region; import com.google.common.base.Preconditions; import de.photon.anticheataddition.util.mathematics.AxisAlignedBB; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.jetbrains.annotations.NotNull; public record Region(@NotNull World world, @NotNull AxisAlignedBB regionBox) { public Region { Preconditions.checkNotNull(world, "Tried to define region with unknown world"); } public Region(final World world, final double x1, final double z1, final double x2, final double z2) { this(world, new AxisAlignedBB(Double.min(x1, x2), Double.MIN_VALUE, Double.min(z1, z2), // Double.max(x1, x2), Double.MAX_VALUE, Double.max(z1, z2))); } /** * Parses a {@link Region} from a {@link String} of the following format: * [affected_world] [x1] [z1] [x2] [z2] */ public static Region parseRegion(@NotNull final String stringToParse) { // Split the String, the ' ' char is gone after that process. final String[] parts = stringToParse.split(" "); return new Region(Bukkit.getServer().getWorld(parts[0]), Double.parseDouble(parts[1]), Double.parseDouble(parts[2]), Double.parseDouble(parts[3]), Double.parseDouble(parts[4])); } /** * Determines whether a {@link Location} is inside this {@link Region} * * @param location the {@link Location} that should be checked if it lies inside this {@link Region} * * @return if the given {@link Location} is inside this {@link Region}. */ public boolean isInsideRegion(@NotNull final Location location) { return this.world.equals(location.getWorld()) && regionBox.isVectorInside(location.toVector()); } }
1
0.819489
1
0.819489
game-dev
MEDIA
0.588259
game-dev
0.72642
1
0.72642
shxzu/Simp
1,234
src/main/java/net/minecraft/item/ItemSeeds.java
package net.minecraft.item; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; public class ItemSeeds extends Item { private final Block crops; private final Block soilBlockID; public ItemSeeds(Block crops, Block soil) { this.crops = crops; this.soilBlockID = soil; this.setCreativeTab(CreativeTabs.tabMaterials); } public boolean onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) { if (side != EnumFacing.UP) { return false; } else if (!playerIn.canPlayerEdit(pos.offset(side), side, stack)) { return false; } else if (worldIn.getBlockState(pos).getBlock() == this.soilBlockID && worldIn.isAirBlock(pos.up())) { worldIn.setBlockState(pos.up(), this.crops.getDefaultState()); --stack.stackSize; return true; } else { return false; } } }
1
0.735942
1
0.735942
game-dev
MEDIA
0.999657
game-dev
0.810306
1
0.810306
amethyst/rustrogueliketutorial
3,394
chapter-30-dla/src/melee_combat_system.rs
use specs::prelude::*; use super::{CombatStats, WantsToMelee, Name, SufferDamage, gamelog::GameLog, MeleePowerBonus, DefenseBonus, Equipped, particle_system::ParticleBuilder, Position, HungerClock, HungerState}; pub struct MeleeCombatSystem {} impl<'a> System<'a> for MeleeCombatSystem { #[allow(clippy::type_complexity)] type SystemData = ( Entities<'a>, WriteExpect<'a, GameLog>, WriteStorage<'a, WantsToMelee>, ReadStorage<'a, Name>, ReadStorage<'a, CombatStats>, WriteStorage<'a, SufferDamage>, ReadStorage<'a, MeleePowerBonus>, ReadStorage<'a, DefenseBonus>, ReadStorage<'a, Equipped>, WriteExpect<'a, ParticleBuilder>, ReadStorage<'a, Position>, ReadStorage<'a, HungerClock> ); fn run(&mut self, data : Self::SystemData) { let (entities, mut log, mut wants_melee, names, combat_stats, mut inflict_damage, melee_power_bonuses, defense_bonuses, equipped, mut particle_builder, positions, hunger_clock) = data; for (entity, wants_melee, name, stats) in (&entities, &wants_melee, &names, &combat_stats).join() { if stats.hp > 0 { let mut offensive_bonus = 0; for (_item_entity, power_bonus, equipped_by) in (&entities, &melee_power_bonuses, &equipped).join() { if equipped_by.owner == entity { offensive_bonus += power_bonus.power; } } let hc = hunger_clock.get(entity); if let Some(hc) = hc { if hc.state == HungerState::WellFed { offensive_bonus += 1; } } let target_stats = combat_stats.get(wants_melee.target).unwrap(); if target_stats.hp > 0 { let target_name = names.get(wants_melee.target).unwrap(); let mut defensive_bonus = 0; for (_item_entity, defense_bonus, equipped_by) in (&entities, &defense_bonuses, &equipped).join() { if equipped_by.owner == wants_melee.target { defensive_bonus += defense_bonus.defense; } } let pos = positions.get(wants_melee.target); if let Some(pos) = pos { particle_builder.request(pos.x, pos.y, rltk::RGB::named(rltk::ORANGE), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('‼'), 200.0); } let damage = i32::max(0, (stats.power + offensive_bonus) - (target_stats.defense + defensive_bonus)); if damage == 0 { log.entries.push(format!("{} is unable to hurt {}", &name.name, &target_name.name)); } else { log.entries.push(format!("{} hits {}, for {} hp.", &name.name, &target_name.name, damage)); SufferDamage::new_damage(&mut inflict_damage, wants_melee.target, damage); } } } } wants_melee.clear(); } }
1
0.906046
1
0.906046
game-dev
MEDIA
0.840932
game-dev
0.900005
1
0.900005
dfelinto/blender
3,108
extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.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_RAYCAST_TRI_CALLBACK_H #define BT_RAYCAST_TRI_CALLBACK_H #include "BulletCollision/CollisionShapes/btTriangleCallback.h" #include "LinearMath/btTransform.h" struct btBroadphaseProxy; class btConvexShape; class btTriangleRaycastCallback : public btTriangleCallback { public: //input btVector3 m_from; btVector3 m_to; //@BP Mod - allow backface filtering and unflipped normals enum EFlags { kF_None = 0, kF_FilterBackfaces = 1 << 0, kF_KeepUnflippedNormal = 1 << 1, // Prevents returned face normal getting flipped when a ray hits a back-facing triangle ///SubSimplexConvexCastRaytest is the default, even if kF_None is set. kF_UseSubSimplexConvexCastRaytest = 1 << 2, // Uses an approximate but faster ray versus convex intersection algorithm kF_UseGjkConvexCastRaytest = 1 << 3, kF_DisableHeightfieldAccelerator = 1 << 4, //don't use the heightfield raycast accelerator. See https://github.com/bulletphysics/bullet3/pull/2062 kF_Terminator = 0xFFFFFFFF }; unsigned int m_flags; btScalar m_hitFraction; btTriangleRaycastCallback(const btVector3& from, const btVector3& to, unsigned int flags = 0); virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex); virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex) = 0; }; class btTriangleConvexcastCallback : public btTriangleCallback { public: const btConvexShape* m_convexShape; btTransform m_convexShapeFrom; btTransform m_convexShapeTo; btTransform m_triangleToWorld; btScalar m_hitFraction; btScalar m_triangleCollisionMargin; btScalar m_allowedPenetration; btTriangleConvexcastCallback(const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin); virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex); virtual btScalar reportHit(const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex) = 0; }; #endif //BT_RAYCAST_TRI_CALLBACK_H
1
0.90982
1
0.90982
game-dev
MEDIA
0.994669
game-dev
0.976013
1
0.976013
oiuv/mud
1,192
kungfu/skill/xiyang-neigong/powerup.c
// powerup.c 西洋内功 #include <ansi.h> inherit F_CLEAN_UP; void remove_effect(object me, int amount); int exert(object me, object target) { int skill; if (target != me) return notify_fail("你只能用西洋内功来提升自己的战斗力。\n"); if ((int)me->query("neili") < 100 ) return notify_fail("你的内力不够。\n"); if ((int)me->query_temp("powerup")) return notify_fail("你已经在运功中了。\n"); skill = me->query_skill("force"); me->add("neili", -90); me->receive_damage("qi", 0); message_combatd(HIG "$N" HIG "口中“荷荷”大叫,浑身的肌肉如同" "充了气一般忽然膨胀起来,威势摄人!\n" NOR, me); me->add_temp("apply/attack", skill / 3); me->add_temp("apply/defense", skill / 3); me->set_temp("powerup", 1); me->start_call_out((: call_other, __FILE__, "remove_effect", me, skill/3 :), skill); if (me->is_fighting()) me->start_busy(3); return 1; } void remove_effect(object me, int amount) { if ((int)me->query_temp("powerup")) { me->add_temp("apply/attack", -amount); me->add_temp("apply/defense", - amount); me->delete_temp("powerup"); tell_object(me, "你的西洋内功运行完毕,将内力收回丹田。\n"); } }
1
0.613548
1
0.613548
game-dev
MEDIA
0.941891
game-dev
0.849226
1
0.849226
Cadiboo/NoCubes
2,510
forge/src/main/java/io/github/cadiboo/nocubes/forge/ClientPlatform.java
package io.github.cadiboo.nocubes.forge; import io.github.cadiboo.nocubes.NoCubes; import io.github.cadiboo.nocubes.config.NoCubesConfigImpl; import io.github.cadiboo.nocubes.network.C2SRequestUpdateSmoothable; import io.github.cadiboo.nocubes.network.NoCubesNetworkForge; import io.github.cadiboo.nocubes.platform.IClientPlatform; import net.minecraft.ChatFormatting; import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.Direction; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.fml.config.ConfigTracker; import net.minecraftforge.fml.config.ModConfig; import java.io.File; import java.util.List; import java.util.function.Consumer; public class ClientPlatform implements IClientPlatform { @Override public void updateClientVisuals(boolean render) { NoCubesConfigImpl.Client.updateRender(render); } @Override public void sendC2SRequestUpdateSmoothable(boolean newValue, BlockState[] states) { NoCubesNetworkForge.CHANNEL.sendToServer(new C2SRequestUpdateSmoothable(newValue, states)); } @Override public void loadDefaultServerConfig() { NoCubesConfigImpl.Hacks.loadDefaultServerConfig(); } @Override public void receiveSyncedServerConfig(byte[] configData) { NoCubesConfigImpl.Hacks.receiveSyncedServerConfig(configData); } @Override public Component clientConfigComponent() { var configFile = new File(ConfigTracker.INSTANCE.getConfigFileName(NoCubes.MOD_ID, ModConfig.Type.CLIENT)); return Component.literal(configFile.getName()) .withStyle(ChatFormatting.UNDERLINE) .withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, configFile.getAbsolutePath()))); } @Override public void forEachRenderLayer(BlockState state, Consumer<RenderType> action) { var layers = ItemBlockRenderTypes.getRenderLayers(state); for (var layer : layers) { action.accept(layer); } } @Override public List<BakedQuad> getQuads(BakedModel model, BlockState state, Direction direction, RandomSource random, Object modelData, RenderType layer) { return model.getQuads(state, direction, random, (ModelData) modelData, layer); } }
1
0.799778
1
0.799778
game-dev
MEDIA
0.951005
game-dev
0.739097
1
0.739097
RE-SS3D/SS3D
2,703
Assets/Scripts/SS3D/Systems/Furniture/DragInteraction.cs
using SS3D.Data.Generated; using SS3D.Interactions; using SS3D.Interactions.Extensions; using SS3D.Systems.Entities; using SS3D.Systems.Entities.Humanoid; using SS3D.Systems.Inventory.Containers; using UnityEngine; namespace SS3D.Systems.Furniture { /// <summary> /// Interaction used to drag heavy stuff around the map. /// </summary> public class DragInteraction : Interaction { /// <summary> /// If the interaction should be range limited /// </summary> public bool RangeCheck { get; set; } = true; public override string GetName(InteractionEvent interactionEvent) { if (interactionEvent.Target.GetGameObject().TryGetComponent<Draggable>(out var draggable)) { return draggable.Dragged ? "Drop" : "Drag"; } return null; } public override Sprite GetIcon(InteractionEvent interactionEvent) { return InteractionIcons.Discard; } public override bool CanInteract(InteractionEvent interactionEvent) { if (RangeCheck && !InteractionExtensions.RangeCheck(interactionEvent)) { return false; } if (!IsInFront(interactionEvent.Source.GetComponentInParent<Entity>().gameObject.transform, interactionEvent.Target.GetGameObject().transform, 20f)) { return false; } if (interactionEvent.Source is not Hand) return false; return true; } public override bool Start(InteractionEvent interactionEvent, InteractionReference reference) { if (!interactionEvent.Target.GetGameObject().TryGetComponent<Draggable>(out var draggable)) { return false; } draggable.SetDrag(!draggable.Dragged, interactionEvent.Source.GetComponentInParent<Entity>().gameObject.transform); interactionEvent.Source.GetComponentInParent<HumanoidLivingController>().IsDragging = draggable.Dragged; return false; } bool IsInFront(Transform transformToCheck, Transform target, float toleranceAngle) { // Calculate direction from the transform to the target Vector3 directionToTarget = (target.position - transformToCheck.position).normalized; // Calculate the angle between the transform's forward direction and direction to target float angle = Vector3.Angle(transformToCheck.forward, directionToTarget); // Check if the angle is within the tolerance range return angle <= toleranceAngle; } } }
1
0.751818
1
0.751818
game-dev
MEDIA
0.956901
game-dev
0.777619
1
0.777619
kbengine/kbengine
2,476
kbe/src/server/cellapp/proximity_controller.cpp
// Copyright 2008-2018 Yolo Technologies, Inc. All Rights Reserved. https://www.comblockengine.com #include "trap_trigger.h" #include "entity.h" #include "proximity_controller.h" #include "entity_coordinate_node.h" namespace KBEngine{ //------------------------------------------------------------------------------------- ProximityController::ProximityController(Entity* pEntity, float xz, float y, int32 userarg, uint32 id): Controller(CONTROLLER_TYPE_PROXIMITY, pEntity, userarg, id), pTrapTrigger_(NULL), xz_(xz), y_(y) { pTrapTrigger_ = new TrapTrigger(static_cast<EntityCoordinateNode*>(pEntity->pEntityCoordinateNode()), this, xz, y); pTrapTrigger_->install(); } //------------------------------------------------------------------------------------- ProximityController::ProximityController(Entity* pEntity): Controller(pEntity), pTrapTrigger_(NULL), xz_(0.f), y_(0.f) { } //------------------------------------------------------------------------------------- ProximityController::~ProximityController() { pTrapTrigger_->uninstall(); delete pTrapTrigger_; } //------------------------------------------------------------------------------------- void ProximityController::addToStream(KBEngine::MemoryStream& s) { Controller::addToStream(s); s << xz_ << y_; } //------------------------------------------------------------------------------------- void ProximityController::createFromStream(KBEngine::MemoryStream& s) { Controller::createFromStream(s); s >> xz_ >> y_; } //------------------------------------------------------------------------------------- bool ProximityController::reinstall(CoordinateNode* pCoordinateNode) { // cellappתʱܳ // ΪʹProximityController::ProximityController(Entity* pEntity) if(pTrapTrigger_ == NULL) { pTrapTrigger_ = new TrapTrigger(static_cast<EntityCoordinateNode*>(pCoordinateNode), this, xz_, y_); } return pTrapTrigger_->reinstall(pCoordinateNode); } //------------------------------------------------------------------------------------- void ProximityController::onEnter(Entity* pEntity, float xz, float y) { pEntity_->onEnterTrap(pEntity, xz, y, id(), userarg()); } //------------------------------------------------------------------------------------- void ProximityController::onLeave(Entity* pEntity, float xz, float y) { pEntity_->onLeaveTrap(pEntity, xz, y, id(), userarg()); } //------------------------------------------------------------------------------------- }
1
0.899883
1
0.899883
game-dev
MEDIA
0.869606
game-dev
0.715604
1
0.715604
SinlessDevil/UnityGridLevelEditor
11,691
Assets/Plugins/Zenject/Source/Editor/SceneParentLoading/SceneParentAutomaticLoader.cs
using System; using System.Collections.Generic; using ModestTree; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; namespace Zenject.Internal { [InitializeOnLoad] public static class SceneParentAutomaticLoader { static SceneParentAutomaticLoader() { EditorApplication.playModeStateChanged += OnPlayModeStateChanged; } static void OnPlayModeStateChanged(PlayModeStateChange state) { if (state == PlayModeStateChange.ExitingEditMode) { try { ValidateMultiSceneSetupAndLoadDefaultSceneParents(); } catch (Exception e) { EditorApplication.isPlaying = false; throw new ZenjectException( "Failure occurred when attempting to load default scene parent contracts!", e); } } else if (state == PlayModeStateChange.EnteredEditMode) { // It would be cool to restore the initial scene set up here but in order to do this // we would have to make sure that the user saves the scene before running which // would be too annoying, so just leave any changes we've made alone } } public static void ValidateMultiSceneSetupAndLoadDefaultSceneParents() { var defaultContractsMap = LoadDefaultContractsMap(); // NOTE: Even if configs is empty we still want to do the below logic to validate the // multi scene setup var sceneInfos = GetLoadedZenjectSceneInfos(); var contractMap = GetCurrentSceneContractsMap(sceneInfos); foreach (var sceneInfo in sceneInfos) { ProcessScene(sceneInfo, contractMap, defaultContractsMap); } } static Dictionary<string, LoadedSceneInfo> GetCurrentSceneContractsMap( List<LoadedSceneInfo> sceneInfos) { var contractMap = new Dictionary<string, LoadedSceneInfo>(); foreach (var info in sceneInfos) { AddToContractMap(contractMap, info); } return contractMap; } static void ProcessScene( LoadedSceneInfo sceneInfo, Dictionary<string, LoadedSceneInfo> contractMap, Dictionary<string, string> defaultContractsMap) { if (sceneInfo.SceneContext != null) { Assert.IsNull(sceneInfo.DecoratorContext); ProcessSceneParents(sceneInfo, contractMap, defaultContractsMap); } else { Assert.IsNotNull(sceneInfo.DecoratorContext); ProcessSceneDecorators(sceneInfo, contractMap, defaultContractsMap); } } static void ProcessSceneDecorators( LoadedSceneInfo sceneInfo, Dictionary<string, LoadedSceneInfo> contractMap, Dictionary<string, string> defaultContractsMap) { var decoratedContractName = sceneInfo.DecoratorContext.DecoratedContractName; LoadedSceneInfo decoratedSceneInfo; if (contractMap.TryGetValue(decoratedContractName, out decoratedSceneInfo)) { ValidateDecoratedSceneMatch(sceneInfo, decoratedSceneInfo); return; } decoratedSceneInfo = LoadDefaultSceneForContract( sceneInfo, decoratedContractName, defaultContractsMap); EditorSceneManager.MoveSceneAfter(decoratedSceneInfo.Scene, sceneInfo.Scene); ValidateDecoratedSceneMatch(sceneInfo, decoratedSceneInfo); ProcessScene(decoratedSceneInfo, contractMap, defaultContractsMap); } static void ProcessSceneParents( LoadedSceneInfo sceneInfo, Dictionary<string, LoadedSceneInfo> contractMap, Dictionary<string, string> defaultContractsMap) { foreach (var parentContractName in sceneInfo.SceneContext.ParentContractNames) { LoadedSceneInfo parentInfo; if (contractMap.TryGetValue(parentContractName, out parentInfo)) { ValidateParentChildMatch(parentInfo, sceneInfo); continue; } parentInfo = LoadDefaultSceneForContract(sceneInfo, parentContractName, defaultContractsMap); AddToContractMap(contractMap, parentInfo); EditorSceneManager.MoveSceneBefore(parentInfo.Scene, sceneInfo.Scene); ValidateParentChildMatch(parentInfo, sceneInfo); ProcessScene(parentInfo, contractMap, defaultContractsMap); } } static LoadedSceneInfo LoadDefaultSceneForContract( LoadedSceneInfo sceneInfo, string contractName, Dictionary<string, string> defaultContractsMap) { string scenePath; if (!defaultContractsMap.TryGetValue(contractName, out scenePath)) { throw Assert.CreateException( "Could not fill contract '{0}' for scene '{1}'. No scenes with that contract name are loaded, and could not find a match in any default scene contract configs to auto load one either." .Fmt(contractName, sceneInfo.Scene.name)); } Scene scene; try { scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); } catch (Exception e) { throw new ZenjectException( "Error while attempting to load contracts for scene '{0}'".Fmt(sceneInfo.Scene.name), e); } return CreateLoadedSceneInfo(scene); } static void ValidateDecoratedSceneMatch( LoadedSceneInfo decoratorInfo, LoadedSceneInfo decoratedInfo) { var decoratorIndex = GetSceneIndex(decoratorInfo.Scene); var decoratedIndex = GetSceneIndex(decoratedInfo.Scene); var activeIndex = GetSceneIndex(EditorSceneManager.GetActiveScene()); Assert.That(decoratorIndex < decoratedIndex, "Decorator scene '{0}' must be loaded before decorated scene '{1}'. Please drag the decorator scene to be placed above the other scene in the scene hierarchy.", decoratorInfo.Scene.name, decoratedInfo.Scene.name); if (activeIndex > decoratorIndex) { EditorSceneManager.SetActiveScene(decoratorInfo.Scene); } } static void ValidateParentChildMatch( LoadedSceneInfo parentSceneInfo, LoadedSceneInfo sceneInfo) { var parentIndex = GetSceneIndex(parentSceneInfo.Scene); var childIndex = GetSceneIndex(sceneInfo.Scene); var activeIndex = GetSceneIndex(EditorSceneManager.GetActiveScene()); Assert.That(parentIndex < childIndex, "Parent scene '{0}' must be loaded before child scene '{1}'. Please drag it to be placed above its child in the scene hierarchy.", parentSceneInfo.Scene.name, sceneInfo.Scene.name); if (activeIndex > parentIndex) { EditorSceneManager.SetActiveScene(parentSceneInfo.Scene); } } static int GetSceneIndex(Scene scene) { for (int i = 0; i < EditorSceneManager.sceneCount; i++) { if (EditorSceneManager.GetSceneAt(i) == scene) { return i; } } throw Assert.CreateException(); } static Dictionary<string, string> LoadDefaultContractsMap() { var configs = Resources.LoadAll<DefaultSceneContractConfig>(DefaultSceneContractConfig.ResourcePath); var map = new Dictionary<string, string>(); foreach (var config in configs) { foreach (var info in config.DefaultContracts) { if (info.ContractName.Trim().IsEmpty()) { Log.Warn("Found empty contract name in default scene contract config at path '{0}'", AssetDatabase.GetAssetPath(config)); continue; } Assert.That(!map.ContainsKey(info.ContractName), "Found duplicate contract '{0}' in default scene contract config at '{1}'! Default contract already specified", info.ContractName, AssetDatabase.GetAssetPath(config)); map.Add(info.ContractName, AssetDatabase.GetAssetPath(info.Scene)); } } return map; } static LoadedSceneInfo CreateLoadedSceneInfo(Scene scene) { var info = TryCreateLoadedSceneInfo(scene); Assert.IsNotNull(info, "Expected scene '{0}' to be a zenject scene", scene.name); return info; } static LoadedSceneInfo TryCreateLoadedSceneInfo(Scene scene) { var sceneContext = ZenUnityEditorUtil.TryGetSceneContextForScene(scene); var decoratorContext = ZenUnityEditorUtil.TryGetDecoratorContextForScene(scene); if (sceneContext == null && decoratorContext == null) { return null; } var info = new LoadedSceneInfo { Scene = scene }; if (sceneContext != null) { Assert.IsNull(decoratorContext, "Found both SceneContext and SceneDecoratorContext in scene '{0}'", scene.name); info.SceneContext = sceneContext; } else { Assert.IsNotNull(decoratorContext); info.DecoratorContext = decoratorContext; } return info; } static List<LoadedSceneInfo> GetLoadedZenjectSceneInfos() { var result = new List<LoadedSceneInfo>(); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { var scene = EditorSceneManager.GetSceneAt(i); var info = TryCreateLoadedSceneInfo(scene); if (info != null) { result.Add(info); } } return result; } static void AddToContractMap( Dictionary<string, LoadedSceneInfo> contractMap, LoadedSceneInfo info) { if (info.SceneContext == null) { return; } foreach (var contractName in info.SceneContext.ContractNames) { LoadedSceneInfo currentInfo; if (contractMap.TryGetValue(contractName, out currentInfo)) { throw Assert.CreateException( "Found multiple scene contracts with name '{0}'. Scene '{1}' and scene '{2}'", contractName, currentInfo.Scene.name, info.Scene.name); } contractMap.Add(contractName, info); } } public class LoadedSceneInfo { public SceneContext SceneContext; public SceneDecoratorContext DecoratorContext; public Scene Scene; } } }
1
0.771511
1
0.771511
game-dev
MEDIA
0.762809
game-dev
0.857525
1
0.857525
DrewKestell/BloogBot
1,259
ShadowPriestBot/HealSelfState.cs
using BloogBot.AI; using BloogBot.Game; using BloogBot.Game.Objects; using System.Collections.Generic; namespace ShadowPriestBot { class HealSelfState : IBotState { const string LesserHeal = "Lesser Heal"; const string Heal = "Heal"; const string Renew = "Renew"; readonly Stack<IBotState> botStates; readonly LocalPlayer player; readonly string healingSpell; public HealSelfState(Stack<IBotState> botStates, IDependencyContainer container) { this.botStates = botStates; player = ObjectManager.Player; if (player.KnowsSpell(Heal)) healingSpell = Heal; else healingSpell = LesserHeal; } public void Update() { if (player.IsCasting) return; if (player.HealthPercent > 70 || player.Mana < player.GetManaCost(healingSpell)) { if (player.KnowsSpell(Renew) && player.Mana > player.GetManaCost(Renew)) player.LuaCall($"CastSpellByName('{Renew}',1)"); botStates.Pop(); return; } player.LuaCall($"CastSpellByName('{healingSpell}',1)"); } } }
1
0.706713
1
0.706713
game-dev
MEDIA
0.885643
game-dev
0.501737
1
0.501737
UnrealMultiple/TShockPlugin
1,036
src/AutoTeam/Configuration.cs
using LazyAPI.Attributes; using LazyAPI.ConfigFiles; namespace AutoTeam; [Config] public class Configuration : JsonConfigBase<Configuration> { protected override string Filename => "AutoTeam"; [LocalizedPropertyName(CultureType.Chinese, "开启插件")] [LocalizedPropertyName(CultureType.English, "Enable")] public bool Enabled { get; set; } = true; [LocalizedPropertyName(CultureType.Chinese, "组对应的队伍")] [LocalizedPropertyName(CultureType.English, "GroupTemp")] public Dictionary<string, string> GroupTeamMap { get; set; } = new Dictionary<string, string>(); public string GetTeamForGroup(string groupName) { return this.GroupTeamMap.TryGetValue(groupName, out var team) ? team : GetString("未配置"); } protected override void SetDefault() { this.GroupTeamMap = new Dictionary<string, string> { {"guest", "pink"}, {"default", "蓝队"}, {"owner", "红队"}, {"admin", "green"}, {"vip", "none"} }; } }
1
0.761609
1
0.761609
game-dev
MEDIA
0.281957
game-dev
0.631312
1
0.631312
AdaCore/spark2014
1,116
testsuite/gnatprove/tests/tetris/README.md
This program implements a simple version of the game of Tetris. An invariant of the game is stated in function `Valid_Configuration`, that all procedures of the unit must maintain. This invariant depends on the state of the game which if updated by every procedure. Both the invariant and the state of the game are encoded as Ghost Code. The invariant expresses two properties: - A falling piece never exits the game board, and it does not overlap with pieces that have already fallen. - After a piece has fallen, the complete lines it may create are removed from the game board. GNATprove proves all checks on the full version of this program found in `tetris_functional.adb`. Intermediate versions of the program show the initial code without any contracts in `tetris_initial.adb`, the code with contracts for data dependencies in `tetris_flow.adb` and the code with contracts to guard against run-time errors in `tetris_integrity.adb`. The complete program, including the BSP to run it on the ATMEL SAM4S board, is available on the [AdaCore blog](http://blog.adacore.com/tetris-in-spark-on-arm-cortex-m4).
1
0.753857
1
0.753857
game-dev
MEDIA
0.840418
game-dev,testing-qa
0.505185
1
0.505185
InsiderAnh/StellarProtect
6,376
Common/src/main/java/io/github/insideranh/stellarprotect/trackers/BlockTracker.java
package io.github.insideranh.stellarprotect.trackers; import org.bukkit.Material; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BlockTracker { private static final byte[] bitCache = new byte[Material.values().length]; private static final byte TOGGLEABLE_FLAG = 1; // 00000001 private static final byte PLACEABLE_FLAG = 2; // 00000010 private static final byte VINE_FLAG = 4; // 00000100 private static final byte SCULK_FLAG = 8; // 00001000 private static final byte CHORUS_FLAG = 16; // 00010000 private static final byte BAMBOO_FLAG = 32; // 00100000 private static final byte AMETHYST_FLAG = 64; // 01000000 private static boolean initialized = false; public static void initializeCache() { if (initialized) return; Arrays.fill(bitCache, (byte) 0); List<String> toggleableList = new ArrayList<>(); String[] doorMats = {"ACACIA", "BIRCH", "DARK_OAK", "JUNGLE", "OAK", "SPRUCE", "CHERRY", "BAMBOO", "MANGROVE", "CRIMSON", "WARPED", "IRON"}; String[] fenceMats = {"ACACIA", "BIRCH", "DARK_OAK", "JUNGLE", "OAK", "SPRUCE", "CHERRY", "BAMBOO", "MANGROVE", "CRIMSON", "WARPED"}; String[] buttonMats = {"ACACIA", "BIRCH", "DARK_OAK", "JUNGLE", "OAK", "SPRUCE", "CHERRY", "BAMBOO", "MANGROVE", "CRIMSON", "WARPED", "STONE", "POLISHED_BLACKSTONE"}; String[] plateMats = {"ACACIA", "BIRCH", "DARK_OAK", "JUNGLE", "OAK", "SPRUCE", "CHERRY", "BAMBOO", "MANGROVE", "CRIMSON", "WARPED", "STONE", "POLISHED_BLACKSTONE", "LIGHT_WEIGHTED", "HEAVY_WEIGHTED"}; for (String mat : doorMats) { toggleableList.add(mat + "_DOOR"); toggleableList.add(mat + "_TRAPDOOR"); } for (String mat : fenceMats) toggleableList.add(mat + "_FENCE_GATE"); for (String mat : buttonMats) toggleableList.add(mat + "_BUTTON"); for (String mat : plateMats) toggleableList.add(mat + "_PRESSURE_PLATE"); toggleableList.add("LEVER"); toggleableList.add("TRIPWIRE_HOOK"); toggleableList.add("REDSTONE_TORCH"); toggleableList.add("REDSTONE_WALL_TORCH"); toggleableList.add("DAYLIGHT_DETECTOR"); toggleableList.add("REPEATER"); toggleableList.add("COMPARATOR"); List<String> placeableList = new ArrayList<>(); placeableList.add("COMPOSTER"); placeableList.add("CHISELED_BOOKSHELF"); placeableList.add("CAMPFIRE"); placeableList.add("SOUL_CAMPFIRE"); placeableList.add("LECTERN"); placeableList.add("JUKEBOX"); placeableList.add("CAULDRON"); placeableList.add("WATER_CAULDRON"); placeableList.add("LAVA_CAULDRON"); placeableList.add("POWDER_SNOW_CAULDRON"); List<String> VINES = new ArrayList<>(); VINES.add("VINE"); VINES.add("TWISTING_VINES"); VINES.add("WEEPING_VINES"); List<String> SCULK = new ArrayList<>(); SCULK.add("SCULK"); SCULK.add("SCULK_VEIN"); List<String> CHORUS = new ArrayList<>(); CHORUS.add("CHORUS_FLOWER"); List<String> BAMBOO = new ArrayList<>(); BAMBOO.add("BAMBOO"); List<String> AMETHYST = new ArrayList<>(); AMETHYST.add("SMALL_AMETHYST_BUD"); for (String block : toggleableList) { try { Material material = Material.valueOf(block); bitCache[material.ordinal()] |= TOGGLEABLE_FLAG; } catch (IllegalArgumentException ignored) { } } for (String block : placeableList) { try { Material material = Material.valueOf(block); bitCache[material.ordinal()] |= PLACEABLE_FLAG; } catch (IllegalArgumentException ignored) { } } for (String block : VINES) { try { Material material = Material.valueOf(block); bitCache[material.ordinal()] |= VINE_FLAG; } catch (IllegalArgumentException ignored) { } } for (String block : SCULK) { try { Material material = Material.valueOf(block); bitCache[material.ordinal()] |= SCULK_FLAG; } catch (IllegalArgumentException ignored) { } } for (String block : CHORUS) { try { Material material = Material.valueOf(block); bitCache[material.ordinal()] |= CHORUS_FLAG; } catch (IllegalArgumentException ignored) { } } for (String block : BAMBOO) { try { Material material = Material.valueOf(block); bitCache[material.ordinal()] |= BAMBOO_FLAG; } catch (IllegalArgumentException ignored) { } } for (String block : AMETHYST) { try { Material material = Material.valueOf(block); bitCache[material.ordinal()] |= AMETHYST_FLAG; } catch (IllegalArgumentException ignored) { } } initialized = true; } public static boolean isToggleableState(Material material) { int ordinal = material.ordinal(); return (bitCache[ordinal] & TOGGLEABLE_FLAG) != 0; } public static boolean isPlaceableState(Material material) { int ordinal = material.ordinal(); return (bitCache[ordinal] & PLACEABLE_FLAG) != 0; } public static boolean isSculkState(Material material) { int ordinal = material.ordinal(); return (bitCache[ordinal] & SCULK_FLAG) != 0; } public static boolean isVineState(Material material) { int ordinal = material.ordinal(); return (bitCache[ordinal] & VINE_FLAG) != 0; } public static boolean isChorusState(Material material) { int ordinal = material.ordinal(); return (bitCache[ordinal] & CHORUS_FLAG) != 0; } public static boolean isAmethystState(Material material) { int ordinal = material.ordinal(); return (bitCache[ordinal] & AMETHYST_FLAG) != 0; } public static boolean isBambooState(Material material) { int ordinal = material.ordinal(); return (bitCache[ordinal] & BAMBOO_FLAG) != 0; } }
1
0.655589
1
0.655589
game-dev
MEDIA
0.886642
game-dev
0.826323
1
0.826323
b1inkie/dst-api
11,618
scripts_619045/components/birdspawner.lua
-------------------------------------------------------------------------- --[[ BirdSpawner class definition ]] -------------------------------------------------------------------------- return Class(function(self, inst) assert(TheWorld.ismastersim, "BirdSpawner should not exist on client") -------------------------------------------------------------------------- --[[ Constants ]] -------------------------------------------------------------------------- --Note: in winter, 'robin' is replaced with 'robin_winter' automatically local BIRD_TYPES = { --[WORLD_TILES.IMPASSABLE] = { "" }, --[WORLD_TILES.ROAD] = { "crow" }, [WORLD_TILES.ROCKY] = { "crow" }, [WORLD_TILES.DIRT] = { "crow" }, [WORLD_TILES.SAVANNA] = { "robin", "crow" }, [WORLD_TILES.GRASS] = { "robin" }, [WORLD_TILES.FOREST] = { "robin", "crow" }, [WORLD_TILES.MARSH] = { "crow" }, [WORLD_TILES.OCEAN_COASTAL] = {"puffin"}, [WORLD_TILES.OCEAN_COASTAL_SHORE] = {"puffin"}, [WORLD_TILES.OCEAN_SWELL] = {"puffin"}, [WORLD_TILES.OCEAN_ROUGH] = {"puffin"}, [WORLD_TILES.OCEAN_BRINEPOOL] = {"puffin"}, [WORLD_TILES.OCEAN_HAZARDOUS] = {"puffin"}, [WORLD_TILES.OCEAN_WATERLOG] = {}, } -------------------------------------------------------------------------- --[[ Member variables ]] -------------------------------------------------------------------------- --Public self.inst = inst --Private local _activeplayers = {} local _scheduledtasks = {} local _worldstate = TheWorld.state local _map = TheWorld.Map local _groundcreep = TheWorld.GroundCreep local _updating = false local _birds = {} local _maxbirds = TUNING.BIRD_SPAWN_MAX local _minspawndelay = TUNING.BIRD_SPAWN_DELAY.min local _maxspawndelay = TUNING.BIRD_SPAWN_DELAY.max local _timescale = 1 -------------------------------------------------------------------------- --[[ Private member functions ]] -------------------------------------------------------------------------- local function CalcValue(player, basevalue, modifier) local ret = basevalue local attractor = player and player.components.birdattractor if attractor then ret = ret + attractor.spawnmodifier:CalculateModifierFromKey(modifier) end return ret end local BIRD_MUST_TAGS = { "bird" } local function SpawnBirdForPlayer(player, reschedule) local pt = player:GetPosition() local ents = TheSim:FindEntities(pt.x, pt.y, pt.z, 64, BIRD_MUST_TAGS) if #ents < CalcValue(player, _maxbirds, "maxbirds") then local spawnpoint = self:GetSpawnPoint(pt) if spawnpoint ~= nil then self:SpawnBird(spawnpoint) end end _scheduledtasks[player] = nil reschedule(player) end local function ScheduleSpawn(player, initialspawn) if _scheduledtasks[player] == nil then local mindelay = CalcValue(player, _minspawndelay, "mindelay") local maxdelay = CalcValue(player, _maxspawndelay, "maxdelay") local lowerbound = initialspawn and 0 or mindelay local upperbound = initialspawn and (maxdelay - mindelay) or maxdelay _scheduledtasks[player] = player:DoTaskInTime(GetRandomMinMax(lowerbound, upperbound) * _timescale, SpawnBirdForPlayer, ScheduleSpawn) end end local function CancelSpawn(player) if _scheduledtasks[player] ~= nil then _scheduledtasks[player]:Cancel() _scheduledtasks[player] = nil end end local function ToggleUpdate(force) if not _worldstate.isnight and _maxbirds > 0 then if not _updating then _updating = true for i, v in ipairs(_activeplayers) do ScheduleSpawn(v, true) end elseif force then for i, v in ipairs(_activeplayers) do CancelSpawn(v) ScheduleSpawn(v, true) end end elseif _updating then _updating = false for i, v in ipairs(_activeplayers) do CancelSpawn(v) end end end local SCARECROW_TAGS = { "scarecrow" } local CARNIVAL_EVENT_ONEOF_TAGS = { "carnivaldecor", "carnivaldecor_ranker" } local function PickBird(spawnpoint) local bird = "crow" if TheNet:GetServerGameMode() == "quagmire" then bird = "quagmire_pigeon" else local tile = _map:GetTileAtPoint(spawnpoint:Get()) if BIRD_TYPES[tile] ~= nil then bird = GetRandomItem(BIRD_TYPES[tile]) end if IsSpecialEventActive(SPECIAL_EVENTS.CARNIVAL) and bird ~= "crow" and IsLandTile(tile) then local x, y, z = spawnpoint:Get() if TheSim:CountEntities(x, y, z, TUNING.BIRD_CANARY_LURE_DISTANCE, nil, nil, CARNIVAL_EVENT_ONEOF_TAGS) > 0 then bird = "crow" end elseif bird == "crow" then local x, y, z = spawnpoint:Get() if TheSim:CountEntities(x, y, z, TUNING.BIRD_CANARY_LURE_DISTANCE, SCARECROW_TAGS) > 0 then bird = "canary" end end end return _worldstate.iswinter and bird == "robin" and "robin_winter" or bird end local SCARYTOPREY_TAGS = { "scarytoprey" } local function IsDangerNearby(x, y, z) local ents = TheSim:FindEntities(x, y, z, 8, SCARYTOPREY_TAGS) return next(ents) ~= nil end local function AutoRemoveTarget(inst, target) if _birds[target] ~= nil and target:IsAsleep() then target:Remove() end end -------------------------------------------------------------------------- --[[ Private event handlers ]] -------------------------------------------------------------------------- local function OnTargetSleep(target) inst:DoTaskInTime(0, AutoRemoveTarget, target) end local function OnIsRaining(inst, israining) _timescale = israining and TUNING.BIRD_RAIN_FACTOR or 1 end local function OnPlayerJoined(src, player) for i, v in ipairs(_activeplayers) do if v == player then return end end table.insert(_activeplayers, player) if _updating then ScheduleSpawn(player, true) end end local function OnPlayerLeft(src, player) for i, v in ipairs(_activeplayers) do if v == player then CancelSpawn(player) table.remove(_activeplayers, i) return end end end -------------------------------------------------------------------------- --[[ Initialization ]] -------------------------------------------------------------------------- --Initialize variables for i, v in ipairs(AllPlayers) do table.insert(_activeplayers, v) end --Register events inst:WatchWorldState("israining", OnIsRaining) inst:WatchWorldState("isnight", function() ToggleUpdate() end) inst:ListenForEvent("ms_playerjoined", OnPlayerJoined, TheWorld) inst:ListenForEvent("ms_playerleft", OnPlayerLeft, TheWorld) -------------------------------------------------------------------------- --[[ Post initialization ]] -------------------------------------------------------------------------- function self:OnPostInit() OnIsRaining(inst, _worldstate.israining) ToggleUpdate(true) end -------------------------------------------------------------------------- --[[ Public member functions ]] -------------------------------------------------------------------------- function self:SetSpawnTimes() --depreciated end function self:SetMaxBirds() --depreciated end function self:ToggleUpdate() ToggleUpdate(true) end function self:SpawnModeNever() --depreciated end function self:SpawnModeLight() --depreciated end function self:SpawnModeMed() --depreciated end function self:SpawnModeHeavy() --depreciated end local BIRDBLOCKER_TAGS = {"birdblocker"} function self:GetSpawnPoint(pt) --We have to use custom test function because birds can't land on creep local function TestSpawnPoint(offset) local spawnpoint_x, spawnpoint_y, spawnpoint_z = (pt + offset):Get() local allow_water = true local moonstorm = false if TheWorld.net.components.moonstorms and next(TheWorld.net.components.moonstorms:GetMoonstormNodes()) then local node_index = TheWorld.Map:GetNodeIdAtPoint(spawnpoint_x, 0, spawnpoint_z) local nodes = TheWorld.net.components.moonstorms._moonstorm_nodes:value() for i, node in pairs(nodes) do if node == node_index then moonstorm = true break end end end return _map:IsPassableAtPoint(spawnpoint_x, spawnpoint_y, spawnpoint_z, allow_water) and not _groundcreep:OnCreep(spawnpoint_x, spawnpoint_y, spawnpoint_z) and #(TheSim:FindEntities(spawnpoint_x, 0, spawnpoint_z, 4, BIRDBLOCKER_TAGS)) == 0 and not moonstorm end local theta = math.random() * TWOPI local radius = 6 + math.random() * 6 local resultoffset = FindValidPositionByFan(theta, radius, 12, TestSpawnPoint) if resultoffset ~= nil then return pt + resultoffset end end function self:SpawnBird(spawnpoint, ignorebait) local prefab = PickBird(spawnpoint) if prefab == nil then return end local bird = SpawnPrefab(prefab) if math.random() < .5 then bird.Transform:SetRotation(180) end if bird:HasTag("bird") then spawnpoint.y = 15 end --see if there's bait nearby that we might spawn into if bird.components.eater and not ignorebait then local bait = TheSim:FindEntities(spawnpoint.x, 0, spawnpoint.z, 15) for k, v in pairs(bait) do local x, y, z = v.Transform:GetWorldPosition() if bird.components.eater:CanEat(v) and not v:IsInLimbo() and v.components.bait and not (v.components.inventoryitem and v.components.inventoryitem:IsHeld()) and not IsDangerNearby(x, y, z) and (bird.components.floater ~= nil or _map:IsPassableAtPoint(x, y, z)) then spawnpoint.x, spawnpoint.z = x, z bird.bufferedaction = BufferedAction(bird, v, ACTIONS.EAT) break elseif v.components.trap and v.components.trap.isset and (not v.components.trap.targettag or bird:HasTag(v.components.trap.targettag)) and not v.components.trap.issprung and math.random() < TUNING.BIRD_TRAP_CHANCE and not IsDangerNearby(x, y, z) then spawnpoint.x, spawnpoint.z = x, z break end end end bird.Physics:Teleport(spawnpoint:Get()) return bird end function self.StartTrackingFn(target) if _birds[target] == nil then _birds[target] = target.persists == true target.persists = false inst:ListenForEvent("entitysleep", OnTargetSleep, target) end end function self:StartTracking(target) self.StartTrackingFn(target) end function self.StopTrackingFn(target) local restore = _birds[target] if restore ~= nil then target.persists = restore _birds[target] = nil inst:RemoveEventCallback("entitysleep", OnTargetSleep, target) end end function self:StopTracking(target) self.StopTrackingFn(target) end -------------------------------------------------------------------------- --[[ Debug ]] -------------------------------------------------------------------------- function self:GetDebugString() local numbirds = 0 for k, v in pairs(_birds) do numbirds = numbirds + 1 end return string.format("birds:%d/%d", numbirds, _maxbirds) end -------------------------------------------------------------------------- --[[ End ]] -------------------------------------------------------------------------- end)
1
0.931011
1
0.931011
game-dev
MEDIA
0.98923
game-dev
0.944709
1
0.944709
leniad/dsp-emulator
21,148
src/arcade/twincobra_hw.pas
unit twincobra_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,nz80,main_engine,controls_engine,gfx_engine,tms32010,ym_3812, rom_engine,pal_engine,sound_engine; function iniciar_twincobra:boolean; implementation const //Twin Cobra twincobr_rom:array[0..3] of tipo_roms=( (n:'b30-01';l:$10000;p:0;crc:$07f64d13),(n:'b30-03';l:$10000;p:1;crc:$41be6978), (n:'tc15';l:$8000;p:$20000;crc:$3a646618),(n:'tc13';l:$8000;p:$20001;crc:$d7d1e317)); twincobr_snd_rom:tipo_roms=(n:'tc12';l:$8000;p:0;crc:$e37b3c44); twincobr_char:array[0..2] of tipo_roms=( (n:'tc11';l:$4000;p:0;crc:$0a254133),(n:'tc03';l:$4000;p:$4000;crc:$e9e2d4b1), (n:'tc04';l:$4000;p:$8000;crc:$a599d845)); twincobr_sprites:array[0..3] of tipo_roms=( (n:'tc20';l:$10000;p:0;crc:$cb4092b8),(n:'tc19';l:$10000;p:$10000;crc:$9cb8675e), (n:'tc18';l:$10000;p:$20000;crc:$806fb374),(n:'tc17';l:$10000;p:$30000;crc:$4264bff8)); twincobr_fg_tiles:array[0..3] of tipo_roms=( (n:'tc01';l:$10000;p:0;crc:$15b3991d),(n:'tc02';l:$10000;p:$10000;crc:$d9e2e55d), (n:'tc06';l:$10000;p:$20000;crc:$13daeac8),(n:'tc05';l:$10000;p:$30000;crc:$8cc79357)); twincobr_bg_tiles:array[0..3] of tipo_roms=( (n:'tc07';l:$8000;p:0;crc:$b5d48389),(n:'tc08';l:$8000;p:$8000;crc:$97f20fdc), (n:'tc09';l:$8000;p:$10000;crc:$170c01db),(n:'tc10';l:$8000;p:$18000;crc:$44f5accd)); twincobr_mcu_rom:array[0..1] of tipo_roms=( (n:'dsp_22.bin';l:$800;p:0;crc:$79389a71),(n:'dsp_21.bin';l:$800;p:1;crc:$2d135376)); twincobr_dip_a:array [0..3] of def_dip2=( (mask:2;name:'Flip Screen';number:2;val2:(0,2);name2:('Off','On')), (mask:8;name:'Demo Sounds';number:2;val2:(8,0);name2:('Off','On')), (mask:$30;name:'Coin A';number:4;val4:($30,$20,$10,0);name4:('4C 1C','3C 1C','2C 1C','1C 1C')), (mask:$c0;name:'Coin B';number:4;val4:(0,$40,$80,$c0);name4:('1C 2C','1C 3C','1C 4C','1C 6C'))); twincobr_dip_b:array [0..3] of def_dip2=( (mask:3;name:'Difficulty';number:4;val4:(1,0,2,3);name4:('Easy','Normal','Hard','Very Hard')), (mask:$c;name:'Bonus Life';number:4;val4:(0,4,8,$c);name4:('50K 200K 150K+','70K 270K 200K+','50K','100K')), (mask:$30;name:'Lives';number:4;val4:($30,0,$20,$10);name4:('2','3','4','5')), (mask:$40;name:'Dip Switch Display';number:2;val2:(0,$40);name2:('Off','On'))); //Flying Shark fshark_rom:array[0..1] of tipo_roms=( (n:'b02_18-1.m8';l:$10000;p:0;crc:$04739e02),(n:'b02_17-1.p8';l:$10000;p:1;crc:$fd6ef7a8)); fshark_snd_rom:tipo_roms=(n:'b02_16.l5';l:$8000;p:0;crc:$cdd1a153); fshark_char:array[0..2] of tipo_roms=( (n:'b02_07-1.h11';l:$4000;p:0;crc:$e669f80e),(n:'b02_06-1.h10';l:$4000;p:$4000;crc:$5e53ae47), (n:'b02_05-1.h8';l:$4000;p:$8000;crc:$a8b05bd0)); fshark_sprites:array[0..3] of tipo_roms=( (n:'b02_01.d15';l:$10000;p:0;crc:$2234b424),(n:'b02_02.d16';l:$10000;p:$10000;crc:$30d4c9a8), (n:'b02_03.d17';l:$10000;p:$20000;crc:$64f3d88f),(n:'b02_04.d20';l:$10000;p:$30000;crc:$3b23a9fc)); fshark_fg_tiles:array[0..3] of tipo_roms=( (n:'b02_12.h20';l:$8000;p:0;crc:$733b9997),(n:'b02_15.h24';l:$8000;p:$8000;crc:$8b70ef32), (n:'b02_14.h23';l:$8000;p:$10000;crc:$f711ba7d),(n:'b02_13.h21';l:$8000;p:$18000;crc:$62532cd3)); fshark_bg_tiles:array[0..3] of tipo_roms=( (n:'b02_08.h13';l:$8000;p:0;crc:$ef0cf49c),(n:'b02_11.h18';l:$8000;p:$8000;crc:$f5799422), (n:'b02_10.h16';l:$8000;p:$10000;crc:$4bd099ff),(n:'b02_09.h15';l:$8000;p:$18000;crc:$230f1582)); fshark_mcu_rom:array[0..7] of tipo_roms=( (n:'82s137-1.mcu';l:$400;p:0;crc:$cc5b3f53),(n:'82s137-2.mcu';l:$400;p:$400;crc:$47351d55), (n:'82s137-3.mcu';l:$400;p:$800;crc:$70b537b9),(n:'82s137-4.mcu';l:$400;p:$c00;crc:$6edb2de8), (n:'82s137-5.mcu';l:$400;p:$1000;crc:$f35b978a),(n:'82s137-6.mcu';l:$400;p:$1400;crc:$0459e51b), (n:'82s137-7.mcu';l:$400;p:$1800;crc:$cbf3184b),(n:'82s137-8.mcu';l:$400;p:$1c00;crc:$8246a05c)); fshark_dip_a:array [0..4] of def_dip2=( (mask:1;name:'Cabinet';number:2;val2:(1,0);name2:('Upright','Cocktail')), (mask:2;name:'Flip Screen';number:2;val2:(0,2);name2:('Off','On')), (mask:8;name:'Demo Sounds';number:2;val2:(8,0);name2:('Off','On')), (mask:$30;name:'Coin A';number:4;val4:($30,$20,$10,0);name4:('4C 1C','3C 1C','2C 1C','1C 1C')), (mask:$c0;name:'Coin B';number:4;val4:(0,$40,$80,$c0);name4:('1C 2C','1C 3C','1C 4C','1C 6C'))); fshark_dip_b:array [0..4] of def_dip2=( (mask:3;name:'Difficulty';number:4;val4:(1,0,2,3);name4:('Easy','Normal','Hard','Very Hard')), (mask:$c;name:'Bonus Life';number:4;val4:(0,4,8,$c);name4:('50K 200K 150K+','70K 270K 200K+','50K','100K')), (mask:$30;name:'Lives';number:4;val4:($30,0,$20,$10);name4:('2','3','1','5')), (mask:$40;name:'Dip Switch Display';number:2;val2:(0,$40);name2:('Off','On')), (mask:$80;name:'Allow Continue';number:2;val2:(0,$80);name2:('No','Yes'))); var rom:array[0..$17fff] of word; ram,bg_ram:array[0..$1fff] of word; display_on,int_enable,twincobr_dsp_bio,dsp_execute:boolean; txt_ram,sprite_ram:array[0..$7ff] of word; fg_ram:array[0..$fff] of word; txt_offs,bg_offs,fg_offs,bg_bank,fg_bank:word; main_ram_seg,dsp_addr_w:dword; txt_scroll_x,txt_scroll_y,bg_scroll_x,bg_scroll_y,fg_scroll_x,fg_scroll_y:word; procedure update_video_twincobr; procedure draw_sprites(priority:word); var f,atrib,x,y,nchar,color:word; flipx,flipy:boolean; begin for f:=0 to $1ff do begin atrib:=sprite_ram[1+(f shl 2)]; if ((atrib and $c00)=priority) then begin x:=sprite_ram[3+(f shl 2)] shr 7; if (x and $1ff)>$100 then continue; nchar:=(sprite_ram[(f shl 2)]) and $7ff; color:=atrib and $3f; y:=512-(((sprite_ram[2+(f shl 2)]) shr 7)+144) and $1ff; flipy:=(atrib and $100)<>0; flipx:=(atrib and $200)<>0; if flipy then y:=y+14; put_gfx_sprite(nchar,color shl 4,flipx,flipy,3); actualiza_gfx_sprite((x-16) and $1ff,(y-32) and $1ff,4,3); end; end; end; var f,color,nchar,x,y,atrib:word; begin if display_on then begin for f:=$7ff downto 0 do begin //Chars atrib:=txt_ram[f]; color:=(atrib and $F800) shr 11; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=(f shr 6) shl 3; y:=(63-(f and $3f)) shl 3; nchar:=atrib and $7ff; put_gfx_trans(x,y,nchar,(color shl 3)+$600,1,0); gfx[0].buffer[f]:=false; end; end; for f:=0 to $fff do begin atrib:=bg_ram[f+bg_bank]; color:=(atrib and $F000) shr 12; if (gfx[2].buffer[f+bg_bank] or buffer_color[color+$30]) then begin //background x:=(f shr 6) shl 3; y:=(63-(f and $3f)) shl 3; nchar:=atrib and $fff; put_gfx(x,y,nchar,(color shl 4)+$400,3,2); gfx[2].buffer[f+bg_bank]:=false; end; atrib:=fg_ram[f]; color:=(atrib and $F000) shr 12; if (gfx[1].buffer[f] or buffer_color[color+$20]) then begin //foreground x:=(f shr 6) shl 3; y:=(63-(f and $3f)) shl 3; nchar:=(atrib and $fff)+fg_bank; put_gfx_trans(x,y,nchar,(color shl 4)+$500,2,1); gfx[1].buffer[f]:=false; end; end; scroll_x_y(3,4,bg_scroll_x+30,512-bg_scroll_y+137); draw_sprites($400); scroll_x_y(2,4,fg_scroll_x+30,512-fg_scroll_y+137); draw_sprites($800); scroll_x_y(1,4,256-txt_scroll_x-30,512-txt_scroll_y+137); draw_sprites($c00); end else fill_full_screen(4,$7ff); actualiza_trozo_final(0,0,240,320,4); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_twincobr; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 or 1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or 2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.left[0] then marcade.in0:=(marcade.in0 or 4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or 8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); //P1 if arcade_input.up[1] then marcade.in1:=(marcade.in1 or 1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.down[1] then marcade.in1:=(marcade.in1 or 2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.left[1] then marcade.in1:=(marcade.in1 or 4) else marcade.in1:=(marcade.in1 and $fb); if arcade_input.right[1] then marcade.in1:=(marcade.in1 or 8) else marcade.in1:=(marcade.in1 and $f7); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 or $20) else marcade.in1:=(marcade.in1 and $df); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); //SYSTEM if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or 8) else marcade.in2:=(marcade.in2 and $f7); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.start[0] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); if arcade_input.start[1] then marcade.in2:=(marcade.in2 or $40) else marcade.in2:=(marcade.in2 and $bf); end; end; procedure twincobra_principal; var f:word; begin init_controls(false,false,false,true); while EmuStatus=EsRunning do begin for f:=0 to 285 do begin case f of 0:marcade.in2:=marcade.in2 and $7f; 240:begin marcade.in2:=marcade.in2 or $80; if int_enable then begin m68000_0.irq[4]:=HOLD_LINE; int_enable:=false; end; update_video_twincobr; end; end; m68000_0.run(frame_main); frame_main:=frame_main+m68000_0.tframes-m68000_0.contador; z80_0.run(frame_snd); frame_snd:=frame_snd+z80_0.tframes-z80_0.contador; tms32010_0.run(frame_mcu); frame_mcu:=frame_mcu+tms32010_0.tframes-tms32010_0.contador; end; eventos_twincobr; video_sync; end; end; //Main CPU function twincobr_getword(direccion:dword):word; begin case direccion of 0..$2ffff:twincobr_getword:=rom[direccion shr 1]; $30000..$33fff:twincobr_getword:=ram[(direccion and $3fff) shr 1]; $40000..$40fff:twincobr_getword:=sprite_ram[(direccion and $fff) shr 1]; $50000..$50dff:twincobr_getword:=buffer_paleta[(direccion and $fff) shr 1]; $78000:twincobr_getword:=marcade.dswa; $78002:twincobr_getword:=marcade.dswb; $78004:twincobr_getword:=marcade.in0; $78006:twincobr_getword:=marcade.in1; $78008:twincobr_getword:=marcade.in2; $7e000:twincobr_getword:=txt_ram[txt_offs]; $7e002:twincobr_getword:=bg_ram[bg_offs+bg_bank]; $7e004:twincobr_getword:=fg_ram[fg_offs]; $7a000..$7afff:twincobr_getword:=mem_snd[$8000+((direccion and $fff) shr 1)]; end; end; procedure twincobr_putword(direccion:dword;valor:word); procedure cambiar_color(numero,valor:word); var color:tcolor; begin color.b:=pal5bit(valor shr 10); color.g:=pal5bit(valor shr 5); color.r:=pal5bit(valor); set_pal_color(color,numero); case numero of 1024..1279:buffer_color[((numero shr 4) and $f)+$30]:=true; 1280..1535:buffer_color[((numero shr 4) and $f)+$20]:=true; 1536..1791:buffer_color[(numero shr 3) and $1f]:=true; end; end; begin case direccion of 0..$2ffff:; $30000..$33fff:ram[(direccion and $3fff) shr 1]:=valor; $3ffe0..$3ffef:; $40000..$40fff:sprite_ram[(direccion and $fff) shr 1]:=valor; $50000..$50dff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; cambiar_color((direccion and $ffe) shr 1,valor); end; $60000..$60003:; $70000:txt_scroll_y:=valor; $70002:txt_scroll_x:=valor; $70004:txt_offs:=valor and $7ff; $72000:bg_scroll_y:=valor; $72002:bg_scroll_x:=valor; $72004:bg_offs:=valor and $fff; $74000:fg_scroll_y:=valor; $74002:fg_scroll_x:=valor; $74004:fg_offs:=valor and $fff; $76000..$76003:; $7800a:case (valor and $ff) of 0:begin // This means assert the INT line to the DSP */ tms32010_0.change_halt(CLEAR_LINE); m68000_0.change_halt(ASSERT_LINE); tms32010_0.change_irq(ASSERT_LINE); end; 1:begin // This means inhibit the INT line to the DSP */ tms32010_0.change_irq(CLEAR_LINE); tms32010_0.change_halt(ASSERT_LINE); end; end; $7800c:case (valor and $ff) of 4:int_enable:=false; 5:int_enable:=true; 6,7:; 8:bg_bank:=0; 9:bg_bank:=$1000; $a:fg_bank:=0; $b:fg_bank:=$1000; $c:begin // This means assert the INT line to the DSP */ tms32010_0.change_halt(CLEAR_LINE); m68000_0.change_halt(ASSERT_LINE); tms32010_0.change_irq(ASSERT_LINE); end; $d:begin // This means inhibit the INT line to the DSP */ tms32010_0.change_irq(CLEAR_LINE); tms32010_0.change_halt(ASSERT_LINE); end; $e:display_on:=false; $f:display_on:=true; end; $7e000:if txt_ram[txt_offs]<>valor then begin txt_ram[txt_offs]:=valor; gfx[0].buffer[txt_offs]:=true; end; $7e002:if bg_ram[bg_offs+bg_bank]<>valor then begin bg_ram[bg_offs+bg_bank]:=valor; gfx[2].buffer[bg_offs+bg_bank]:=true; end; $7e004:if fg_ram[fg_offs]<>valor then begin fg_ram[fg_offs]:=valor; gfx[1].buffer[fg_offs]:=true; end; $7a000..$7afff:mem_snd[$8000+((direccion and $fff) shr 1)]:=valor and $ff; end; end; function twincobr_snd_getbyte(direccion:word):byte; begin if direccion<$8800 then twincobr_snd_getbyte:=mem_snd[direccion]; end; procedure twincobr_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$87ff:mem_snd[direccion]:=valor; end; end; function twincobr_snd_inbyte(puerto:word):byte; begin case (puerto and $ff) of 0:twincobr_snd_inbyte:=ym3812_0.status; $10:twincobr_snd_inbyte:=marcade.in2; $20,$30:twincobr_snd_inbyte:=0; $40:twincobr_snd_inbyte:=marcade.dswa; $50:twincobr_snd_inbyte:=marcade.dswb; end; end; procedure twincobr_snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of 0:ym3812_0.control(valor); 1:ym3812_0.write(valor); end; end; procedure snd_irq(irqstate:byte); begin z80_0.change_irq(irqstate); end; function twincobr_dsp_r:word; begin // DSP can read data from main CPU RAM via DSP IO port 1 case main_ram_seg of $30000,$40000,$50000:twincobr_dsp_r:=twincobr_getword(main_ram_seg+dsp_addr_w); else twincobr_dsp_r:=0; end; end; procedure twincobr_dsp_w(valor:word); begin // Data written to main CPU RAM via DSP IO port 1 dsp_execute:=false; case main_ram_seg of $30000:begin if ((dsp_addr_w<3) and (valor=0)) then dsp_execute:=true; twincobr_putword(main_ram_seg+dsp_addr_w,valor); end; $40000,$50000:twincobr_putword(main_ram_seg+dsp_addr_w,valor); end; end; procedure twincobr_dsp_addrsel_w(valor:word); begin main_ram_seg:=((valor and $e000) shl 3); dsp_addr_w:=((valor and $1fff) shl 1); end; procedure twincobr_dsp_bio_w(valor:word); begin twincobr_dsp_bio:=(valor and $8000)=0; if (valor=0) then begin if dsp_execute then begin m68000_0.change_halt(CLEAR_LINE); dsp_execute:=false; end; twincobr_dsp_bio:=true; end; end; function twincobr_bio_r:boolean; begin twincobr_bio_r:=twincobr_dsp_bio; end; procedure twincobr_update_sound; begin ym3812_0.update; end; //Main procedure reset_twincobra; begin m68000_0.reset; z80_0.reset; tms32010_0.reset; frame_main:=m68000_0.tframes; frame_snd:=z80_0.tframes; frame_mcu:=tms32010_0.tframes; ym3812_0.reset; txt_scroll_y:=457; txt_scroll_x:=226; bg_scroll_x:=40; bg_scroll_y:=0; fg_scroll_x:=0; fg_scroll_y:=0; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; txt_offs:=0; bg_offs:=0; fg_offs:=0; bg_bank:=0; fg_bank:=0; int_enable:=false; display_on:=true; twincobr_dsp_bio:=false; dsp_execute:=false; main_ram_seg:=0; dsp_addr_w:=0; end; function iniciar_twincobra:boolean; var memoria_temp:array[0..$3ffff] of byte; temp_rom:array[0..$fff] of word; f:word; const pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); procedure convert_chars; begin init_gfx(0,8,8,2048); gfx[0].trans[0]:=true; gfx_set_desc_data(3,0,8*8,0*2048*8*8,1*2048*8*8,2*2048*8*8); convert_gfx(0,0,@memoria_temp,@ps_x,@pc_y,false,true); end; procedure convert_tiles(ngfx:byte;ntiles:word); begin init_gfx(ngfx,8,8,ntiles); gfx[ngfx].trans[0]:=true; gfx_set_desc_data(4,0,8*8,0*ntiles*8*8,1*ntiles*8*8,2*ntiles*8*8,3*ntiles*8*8); convert_gfx(ngfx,0,@memoria_temp,@ps_x,@pc_y,false,true); end; procedure convert_sprites; begin init_gfx(3,16,16,2048); gfx[3].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0*2048*32*8,1*2048*32*8,2*2048*32*8,3*2048*32*8); convert_gfx(3,0,@memoria_temp,@ps_x,@ps_y,false,true); end; begin iniciar_twincobra:=false; llamadas_maquina.bucle_general:=twincobra_principal; llamadas_maquina.reset:=reset_twincobra; llamadas_maquina.fps_max:=(28000000/4)/(446*286); llamadas_maquina.scanlines:=286; iniciar_audio(false); screen_init(1,256,512,true); screen_init(2,512,512,true); screen_init(3,512,512); screen_init(4,512,512,false,true); iniciar_video(240,320); //Main CPU m68000_0:=cpu_m68000.create(24000000 div 4); m68000_0.change_ram16_calls(twincobr_getword,twincobr_putword); //Sound CPU z80_0:=cpu_z80.create(3500000); z80_0.change_ram_calls(twincobr_snd_getbyte,twincobr_snd_putbyte); z80_0.change_io_calls(twincobr_snd_inbyte,twincobr_snd_outbyte); z80_0.init_sound(twincobr_update_sound); //TMS MCU tms32010_0:=cpu_tms32010.create(14000000); tms32010_0.change_io_calls(twincobr_bio_r,nil,twincobr_dsp_r,nil,nil,nil,nil,nil,nil,twincobr_dsp_addrsel_w,twincobr_dsp_w,nil,twincobr_dsp_bio_w,nil,nil,nil,nil); //Sound Chips ym3812_0:=ym3812_chip.create(YM3812_FM,3500000); ym3812_0.change_irq_calls(snd_irq); case main_vars.tipo_maquina of 146:begin //cargar roms if not(roms_load16w(@rom,twincobr_rom)) then exit; //cargar ROMS sonido if not(roms_load(@mem_snd,twincobr_snd_rom)) then exit; //cargar ROMS MCU if not(roms_load16b(tms32010_0.get_rom_addr,twincobr_mcu_rom)) then exit; //convertir chars if not(roms_load(@memoria_temp,twincobr_char)) then exit; convert_chars; //convertir tiles fg if not(roms_load(@memoria_temp,twincobr_fg_tiles)) then exit; convert_tiles(1,8192); //convertir tiles bg if not(roms_load(@memoria_temp,twincobr_bg_tiles)) then exit; convert_tiles(2,4096); //convertir tiles sprites if not(roms_load(@memoria_temp,twincobr_sprites)) then exit; convert_sprites; init_dips(1,twincobr_dip_a,0); init_dips(2,twincobr_dip_b,0); end; 147:begin //cargar roms if not(roms_load16w(@rom,fshark_rom)) then exit; //cargar ROMS sonido if not(roms_load(@mem_snd,fshark_snd_rom)) then exit; //cargar ROMS MCU if not(roms_load(@memoria_temp,fshark_mcu_rom)) then exit; for f:=0 to $3ff do begin temp_rom[f]:=(((memoria_temp[f] and $f) shl 4+(memoria_temp[f+$400] and $f)) shl 8) or (memoria_temp[f+$800] and $f) shl 4+(memoria_temp[f+$c00] and $f); end; for f:=0 to $3ff do begin temp_rom[f+$400]:=(((memoria_temp[f+$1000] and $f) shl 4+(memoria_temp[f+$1400] and $f)) shl 8) or (memoria_temp[f+$1800] and $f) shl 4+(memoria_temp[f+$1c00] and $f); end; copymemory(tms32010_0.get_rom_addr,@temp_rom,$1000); //convertir chars if not(roms_load(@memoria_temp,fshark_char)) then exit; convert_chars; //convertir tiles fg if not(roms_load(@memoria_temp,fshark_fg_tiles)) then exit; convert_tiles(1,4096); //convertir tiles bg if not(roms_load(@memoria_temp,fshark_bg_tiles)) then exit; convert_tiles(2,4096); //convertir tiles sprites if not(roms_load(@memoria_temp,fshark_sprites)) then exit; convert_sprites; init_dips(1,fshark_dip_a,1); init_dips(2,fshark_dip_b,$80); end; end; //final reset_twincobra; iniciar_twincobra:=true; end; end.
1
0.781034
1
0.781034
game-dev
MEDIA
0.580147
game-dev
0.87863
1
0.87863
Redot-Engine/redot-engine
4,492
editor/debugger/editor_debugger_inspector.h
/**************************************************************************/ /* editor_debugger_inspector.h */ /**************************************************************************/ /* This file is part of: */ /* REDOT ENGINE */ /* https://redotengine.org */ /**************************************************************************/ /* Copyright (c) 2024-present Redot Engine contributors */ /* (see REDOT_AUTHORS.md) */ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #pragma once #include "core/variant/typed_dictionary.h" #include "editor/inspector/editor_inspector.h" class SceneDebuggerObject; class EditorDebuggerRemoteObjects : public Object { GDCLASS(EditorDebuggerRemoteObjects, Object); private: bool _set_impl(const StringName &p_name, const Variant &p_value, const String &p_field); protected: bool _set(const StringName &p_name, const Variant &p_value); bool _get(const StringName &p_name, Variant &r_ret) const; void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); public: TypedArray<uint64_t> remote_object_ids; String type_name; List<PropertyInfo> prop_list; HashMap<StringName, TypedDictionary<uint64_t, Variant>> prop_values; bool _hide_script_from_inspector() { return true; } bool _hide_metadata_from_inspector() { return true; } void set_property_field(const StringName &p_property, const Variant &p_value, const String &p_field); String get_title(); Variant get_variant(const StringName &p_name); void clear() { prop_list.clear(); prop_values.clear(); } void update() { notify_property_list_changed(); } }; class EditorDebuggerInspector : public EditorInspector { GDCLASS(EditorDebuggerInspector, EditorInspector); private: LocalVector<EditorDebuggerRemoteObjects *> remote_objects_list; HashSet<Ref<Resource>> remote_dependencies; EditorDebuggerRemoteObjects *variables = nullptr; void _object_selected(ObjectID p_object); void _objects_edited(const String &p_prop, const TypedDictionary<uint64_t, Variant> &p_values, const String &p_field); protected: void _notification(int p_what); static void _bind_methods(); public: EditorDebuggerInspector(); ~EditorDebuggerInspector(); // Remote Object cache EditorDebuggerRemoteObjects *set_objects(const Array &p_array); void clear_remote_inspector(); void clear_cache(); void invalidate_selection_from_cache(const TypedArray<uint64_t> &p_ids); // Stack Dump variables String get_stack_variable(const String &p_var); void add_stack_variable(const Array &p_arr, int p_offset = -1); void clear_stack_variables(); };
1
0.917323
1
0.917323
game-dev
MEDIA
0.450611
game-dev
0.665156
1
0.665156
runuo/runuo
2,245
Scripts/Engines/Ethics/Hero/Mobiles/HolySteed.cs
using System; using Server; using Server.Ethics; using Server.Mobiles; namespace Server.Mobiles { [CorpseName( "a holy corpse" )] public class HolySteed : BaseMount { public override bool IsDispellable { get{ return false; } } public override bool IsBondable { get { return false; } } public override bool HasBreath { get { return true; } } public override bool CanBreath { get { return true; } } [Constructable] public HolySteed() : base( "a silver steed", 0x75, 0x3EA8, AIType.AI_Melee, FightMode.Aggressor, 10, 1, 0.2, 0.4 ) { SetStr( 496, 525 ); SetDex( 86, 105 ); SetInt( 86, 125 ); SetHits( 298, 315 ); SetDamage( 16, 22 ); SetDamageType( ResistanceType.Physical, 40 ); SetDamageType( ResistanceType.Fire, 40 ); SetDamageType( ResistanceType.Energy, 20 ); SetResistance( ResistanceType.Physical, 55, 65 ); SetResistance( ResistanceType.Fire, 30, 40 ); SetResistance( ResistanceType.Cold, 30, 40 ); SetResistance( ResistanceType.Poison, 30, 40 ); SetResistance( ResistanceType.Energy, 20, 30 ); SetSkill( SkillName.MagicResist, 25.1, 30.0 ); SetSkill( SkillName.Tactics, 97.6, 100.0 ); SetSkill( SkillName.Wrestling, 80.5, 92.5 ); Fame = 14000; Karma = 14000; VirtualArmor = 60; Tamable = false; ControlSlots = 1; } public override FoodType FavoriteFood { get { return FoodType.FruitsAndVegies | FoodType.GrainsAndHay; } } public HolySteed( Serial serial ) : base( serial ) { } public override string ApplyNameSuffix( string suffix ) { if ( suffix.Length == 0 ) suffix = Ethic.Hero.Definition.Adjunct.String; else suffix = String.Concat( suffix, " ", Ethic.Hero.Definition.Adjunct.String ); return base.ApplyNameSuffix( suffix ); } public override void OnDoubleClick( Mobile from ) { if ( Ethic.Find( from ) != Ethic.Hero ) from.SendMessage( "You may not ride this steed." ); else base.OnDoubleClick( from ); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
1
0.734501
1
0.734501
game-dev
MEDIA
0.958923
game-dev
0.628757
1
0.628757
Eukaryot/sonic3air
3,502
framework/external/sdl/SDL2/src/filesystem/os2/SDL_sysfilesystem.c
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_FILESYSTEM_OS2 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* System dependent filesystem routines */ #include "../../core/os2/SDL_os2.h" #include "SDL_error.h" #include "SDL_filesystem.h" #define INCL_DOSFILEMGR #define INCL_DOSPROCESS #define INCL_DOSMODULEMGR #define INCL_DOSERRORS #include <os2.h> char *SDL_GetBasePath(void) { PTIB tib; PPIB pib; ULONG ulRC = DosGetInfoBlocks(&tib, &pib); PCHAR pcEnd; CHAR acBuf[CCHMAXPATH]; if (ulRC != NO_ERROR) { SDL_SetError("Can't get process information block (E%lu)", ulRC); return NULL; } ulRC = DosQueryModuleName(pib->pib_hmte, sizeof(acBuf), acBuf); if (ulRC != NO_ERROR) { SDL_SetError("Can't query the module name (E%lu)", ulRC); return NULL; } pcEnd = SDL_strrchr(acBuf, '\\'); if (pcEnd != NULL) pcEnd[1] = '\0'; else { if (acBuf[1] == ':') /* e.g. "C:FOO" */ acBuf[2] = '\0'; else { SDL_SetError("No path in module name"); return NULL; } } return OS2_SysToUTF8(acBuf); } char *SDL_GetPrefPath(const char *org, const char *app) { PSZ pszPath; CHAR acBuf[CCHMAXPATH]; int lPosApp, lPosOrg; PSZ pszApp, pszOrg; if (!app) { SDL_InvalidParamError("app"); return NULL; } pszPath = SDL_getenv("HOME"); if (!pszPath) { pszPath = SDL_getenv("ETC"); if (!pszPath) { SDL_SetError("HOME or ETC environment not set"); return NULL; } } if (!org) { lPosApp = SDL_snprintf(acBuf, sizeof(acBuf) - 1, "%s", pszPath); } else { pszOrg = OS2_UTF8ToSys(org); if (!pszOrg) { SDL_OutOfMemory(); return NULL; } lPosApp = SDL_snprintf(acBuf, sizeof(acBuf) - 1, "%s\\%s", pszPath, pszOrg); SDL_free(pszOrg); } if (lPosApp < 0) return NULL; DosCreateDir(acBuf, NULL); pszApp = OS2_UTF8ToSys(app); if (!pszApp) { SDL_OutOfMemory(); return NULL; } lPosOrg = SDL_snprintf(&acBuf[lPosApp], sizeof(acBuf) - lPosApp - 1, "\\%s", pszApp); SDL_free(pszApp); if (lPosOrg < 0) return NULL; DosCreateDir(acBuf, NULL); *((PUSHORT)&acBuf[lPosApp + lPosOrg]) = (USHORT)'\0\\'; return OS2_SysToUTF8(acBuf); } #endif /* SDL_FILESYSTEM_OS2 */ /* vi: set ts=4 sw=4 expandtab: */
1
0.948869
1
0.948869
game-dev
MEDIA
0.353455
game-dev,os-kernel
0.936436
1
0.936436
gdquest-demos/godot-open-rpg
1,200
src/field/cutscenes/popups/moving_interaction_popup.gd
@tool ## An [InteractionPopup] that follows a moving [Gamepiece]. ## ## This [code]Popup[/code] must be a child of a [Gamepiece] to function. ## ## Note that other popup types will jump to the occupied cell of the ancestor [Gamepiece], whereas ## MovingInteractionPopups sync their position to that of the gamepiece's graphical representation. extends InteractionPopup @onready var _gp: = get_parent() as Gamepiece func _ready() -> void: super._ready() # Do not follow anything in editor or if this object's parent is not of the correct type. if Engine.is_editor_hint() or not _gp: set_process(false) func _get_configuration_warnings() -> PackedStringArray: if not _gp: return ["This popup must be a child of a Gamepiece node!"] return [] func _notification(what: int) -> void: if what == NOTIFICATION_PARENTED: _gp = get_parent() as Gamepiece update_configuration_warnings() # Every process frame the popup sets its position to that of the graphical representation of the # gamepiece, appearing to follow the gamepiece around the field while still playing nicely with the # physics/interaction system. func _process(_delta: float) -> void: position = _gp.follower.position
1
0.867474
1
0.867474
game-dev
MEDIA
0.879279
game-dev
0.845273
1
0.845273
Ferra13671/BThack
5,234
src/main/java/com/ferra13671/BThack/core/Client/Systems/ConfigSystem/ConfigSystem.java
package com.ferra13671.BThack.core.Client.Systems.ConfigSystem; import com.ferra13671.BThack.managers.managers.Setting.Settings.Setting; import com.ferra13671.BThack.core.Client.Client; import com.ferra13671.BThack.managers.managers.Thread.ThreadManager; import com.ferra13671.BThack.managers.Managers; import com.ferra13671.BThack.api.Module.Module; import com.ferra13671.BThack.api.Plugin.Plugin; import com.ferra13671.BThack.api.Plugin.PluginSystem; import com.ferra13671.SimpleLanguageSystem.LanguageSystem; import com.ferra13671.TextureUtils.PathMode; import com.google.gson.*; import org.apache.commons.io.FilenameUtils; import java.io.*; import java.nio.file.Paths; import java.util.*; import static com.ferra13671.BThack.core.Client.Systems.FileSystem.JsonUtils.*; public final class ConfigSystem { private static volatile boolean saving = false; public static void saveConfigThreaded() { if (saving) return; saving = true; ThreadManager.startNewThread((thread -> saveConfig())); saving = false; } public static void saveConfig() { saving = true; SubConfigs.getSubConfigs().forEach(SubConfig::save); saving = false; } public static void loadConfig() { SubConfigs.getSubConfigs().forEach(SubConfig::load); } public static List<String> getAllConfigs() { List<String> results = new ArrayList<>(); File folder = Paths.get("BThack/Configs").toFile(); File[] files = folder.listFiles(); if (files == null) return results; for (File file : files) { if (Objects.equals(FilenameUtils.getExtension(file.getName()), "json")) { results.add(file.getName().replace(".json", "")); } } return results; } public static void saveConfigFile(String fileName) throws IOException { ConfigUtils.saveInJson(fileName, "Configs", jsonObject -> { for (Module module : Client.getAllModules()) { JsonObject moduleObject = new JsonObject(); JsonObject settingObject = new JsonObject(); add(moduleObject, "Name", module.getName()); add(moduleObject, "Enabled", module.isEnabled()); add(moduleObject, "Bind", module.getKey()); add(moduleObject, "Visible", module.isVisible()); if (Managers.SETTINGS_MANAGER.getSettingsByModule(module) != null) { for (Setting<?> s : Managers.SETTINGS_MANAGER.getSettingsByModule(module)) { s.save(settingObject); } } add(moduleObject, "Settings", settingObject); add(jsonObject, module.getName(), moduleObject); } }); } public static void loadConfigFile(String fileName) throws IOException { ConfigUtils.loadFromJson(fileName, "Configs", jsonObject -> { for (Module module : Client.getAllModules()) { if (jsonObject.get(module.getName()) != null) { JsonObject moduleObject = jsonObject.get(module.getName()).getAsJsonObject(); if (equalsNull(moduleObject, "Name", "Enabled", "Bind", "Visible")) continue; JsonObject settingObject = moduleObject.get("Settings").getAsJsonObject(); if (Managers.SETTINGS_MANAGER.getSettingsByModule(module) != null) { for (Setting<?> s : Managers.SETTINGS_MANAGER.getSettingsByModule(module)) { JsonElement settingValueObject; settingValueObject = settingObject.get(s.getName()); if (settingValueObject != null) { try { s.load(settingObject, settingValueObject); } catch (Exception e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } } } module.setEnabledQuietly(moduleObject.get("Enabled").getAsBoolean()); module.setKey(moduleObject.get("Bind").getAsInt()); module.setVisible(moduleObject.get("Visible").getAsBoolean()); } } }, () -> {} ); } public static void loadLanguages() { LanguageSystem.loadTranslations(ConfigUtils.newInputStream("assets/bthack/langs/EN.lng", PathMode.INSIDEJAR), "EN"); LanguageSystem.loadTranslations(ConfigUtils.newInputStream("assets/bthack/langs/RU.lng", PathMode.INSIDEJAR), "RU"); LanguageSystem.loadTranslations(ConfigUtils.newInputStream("assets/bthack/langs/PL.lng", PathMode.INSIDEJAR), "PL"); PluginSystem.getLoadedPlugins().forEach(Plugin::onLoadLanguages); } }
1
0.962922
1
0.962922
game-dev
MEDIA
0.221016
game-dev
0.93078
1
0.93078
NativeScript/ios-jsc
17,502
src/NativeScript/ObjC/ObjCPrototype.mm
// // ObjCPrototype.mm // NativeScript // // Created by Yavor Georgiev on 17.07.14. // Copyright (c) 2014 г. Telerik. All rights reserved. // #include "ObjCPrototype.h" #include "Interop.h" #include "JSErrors.h" #include "Metadata.h" #include "ObjCConstructorBase.h" #include "ObjCFastEnumerationIterator.h" #include "ObjCMethodCall.h" #include "ObjCMethodCallback.h" #include "ObjCTypes.h" #include "SymbolLoader.h" #include "TypeFactory.h" #include <JavaScriptCore/BuiltinNames.h> #include <JavaScriptCore/runtime/GetterSetter.h> #include <objc/runtime.h> #include "StopwatchLogger.h" namespace NativeScript { using namespace JSC; using namespace Metadata; const unsigned ObjCPrototype::StructureFlags = OverridesGetOwnPropertySlot | Base::StructureFlags; const ClassInfo ObjCPrototype::s_info = { "ObjCPrototype", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(ObjCPrototype) }; WTF::String ObjCPrototype::className(const JSObject* object, VM& vm) { auto execState = object->globalObject(vm)->globalExec(); auto constructor = object->get(execState, vm.propertyNames->constructor); auto constructorName = constructor.get(execState, vm.propertyNames->name); return constructorName.toWTFString(execState) + "Prototype"; } static EncodedJSValue JSC_HOST_CALL getIterator(ExecState* execState) { id object = toObject(execState, execState->thisValue()); GlobalObject* globalObject = jsCast<GlobalObject*>(execState->lexicalGlobalObject()); auto iterator = ObjCFastEnumerationIterator::create(execState->vm(), globalObject, globalObject->fastEnumerationIteratorStructure(), object); return JSValue::encode(iterator.get()); } void ObjCPrototype::finishCreation(VM& vm, JSGlobalObject* globalObject, const BaseClassMeta* metadata) { Base::finishCreation(vm); this->_metadata = metadata; if ([objc_getClass(metadata->name()) instancesRespondToSelector:@selector(countByEnumeratingWithState:objects:count:)]) { this->putDirect(vm, vm.propertyNames->iteratorSymbol, JSFunction::create(vm, globalObject, 0, vm.propertyNames->builtinNames().valuesPublicName().string(), getIterator), static_cast<unsigned>(PropertyAttribute::DontEnum)); } } bool ObjCPrototype::shouldSkipOwnProperty(ExecState* execState, PropertyName propertyName, const PropertyMeta* propertyMeta) { JSValue basePrototype = this->getPrototypeDirect(execState->vm()); PropertySlot baseSlot(basePrototype, PropertySlot::InternalMethodType::Get); if (basePrototype.getPropertySlot(execState, propertyName, baseSlot)) { if (baseSlot.isAccessor()) { auto thisGetter = propertyMeta->hasGetter(); auto thisSetter = propertyMeta->hasSetter(); auto baseGetter = !baseSlot.getterSetter()->isGetterNull(); auto baseSetter = !baseSlot.getterSetter()->isSetterNull(); if ((!thisGetter || baseGetter) && (!thisSetter || baseSetter)) { // condition is equivalent to (thisGetter => baseGetter) && (thisSetter => baseSetter), where '=>' means 'logically implies' // I.e., If base class provides the same or more accessors than what we've found, return false and use its property via the prototype chain return true; } } } return false; } //const char StopwatchLabel_getOwnPropertySlot[] = "ObjCPrototype::getOwnPropertySlot"; bool ObjCPrototype::getOwnPropertySlot(JSObject* object, ExecState* execState, PropertyName propertyName, PropertySlot& propertySlot) { NS_TRY { //StopwatchLogger<StopwatchLabel_getOwnPropertySlot> stopwatch("(unset)"); if (Base::getOwnPropertySlot(object, execState, propertyName, propertySlot)) { return true; } if (UNLIKELY(!propertyName.publicName())) { return false; } ObjCPrototype* prototype = jsCast<ObjCPrototype*>(object); if (UNLIKELY(propertyName == prototype->_definingPropertyName)) { // We're currently defining it, it's still not defined return false; } GlobalObject* globalObject = jsCast<GlobalObject*>(prototype->globalObject()); // Check for property if (auto propertyMeta = prototype->_metadata->instanceProperty(propertyName.publicName(), prototype->klasses(), true, prototype->additionalProtocols())) { if (prototype->shouldSkipOwnProperty(execState, propertyName, propertyMeta)) { return false; } prototype->_definingPropertyName = propertyName; prototype->defineNativeProperty(execState->vm(), globalObject, propertyMeta); prototype->_definingPropertyName = PropertyName(nullptr); //stopwatch.message << "(prop) " << prototype->metadata()->jsName() << "." << propertyMeta->jsName(); return Base::getOwnPropertySlot(object, execState, propertyName, propertySlot); } else { // Check for base class property which is implemented in inheritor as a workaround // to inaccurate header information in iOS SDKs (https://github.com/NativeScript/ios-runtime/pull/1092) if (prototype->metadata()->type() == MetaType::Interface) { if (auto baseMeta = static_cast<const InterfaceMeta*>(prototype->metadata())->baseMeta()) { if (auto propertyMeta = baseMeta->instanceProperty(propertyName.publicName(), prototype->klasses(), true, prototype->additionalProtocols())) { JSObject* basePrototype = prototype->getPrototype(execState->vm(), execState).toObject(execState); PropertySlot tempPropSlot(JSValue(basePrototype), PropertySlot::InternalMethodType::GetOwnProperty); if (basePrototype->methodTable(execState->vm())->getOwnPropertySlot(basePrototype, execState, propertyName, tempPropSlot)) { // basePrototype has the property defined return false and let the prototype chain handle it return false; } prototype->_definingPropertyName = propertyName; prototype->defineNativeProperty(execState->vm(), globalObject, propertyMeta); prototype->_definingPropertyName = PropertyName(nullptr); //stopwatch.message << "(base prop) " << prototype->metadata()->jsName() << "." << propertyMeta->jsName(); return Base::getOwnPropertySlot(object, execState, propertyName, propertySlot); } } } MembersCollection methods = prototype->_metadata->getInstanceMethods(propertyName.publicName(), prototype->klasses(), true, prototype->additionalProtocols()); if (methods.size() > 0) { SymbolLoader::instance().ensureModule((*methods.begin())->topLevelModule()); auto method = ObjCMethodWrapper::create(globalObject->vm(), globalObject, globalObject->objCMethodWrapperStructure(), methods); object->putDirect(execState->vm(), propertyName, method.get()); propertySlot.setValue(object, static_cast<unsigned>(PropertyAttribute::None), method.get()); //stopwatch.message << "(method) " << prototype->metadata()->jsName() << "." << (*methods.begin())->jsName(); return true; } } //stopwatch.message << "(not found) " << prototype->metadata()->jsName() << "." << propertyName.publicName()->utf8().data(); } NS_CATCH_THROW_TO_JS(execState) return false; } bool ObjCPrototype::put(JSCell* cell, ExecState* execState, PropertyName propertyName, JSValue value, PutPropertySlot& propertySlot) { NS_TRY { ObjCPrototype* prototype = jsCast<ObjCPrototype*>(cell); if (value.isCell()) { auto method = value.asCell(); Class klass = jsCast<ObjCConstructorBase*>(prototype->get(execState, execState->vm().propertyNames->constructor))->klasses().realClass(); overrideObjcMethodCalls(execState, prototype, propertyName, method, prototype->_metadata, MemberType::InstanceMethod, klass, ProtocolMetas()); } return Base::put(cell, execState, propertyName, value, propertySlot); } NS_CATCH_THROW_TO_JS(execState) return false; } bool ObjCPrototype::defineOwnProperty(JSObject* object, ExecState* execState, PropertyName propertyName, const PropertyDescriptor& propertyDescriptor, bool shouldThrow) { NS_TRY { ObjCPrototype* prototype = jsCast<ObjCPrototype*>(object); VM& vm = execState->vm(); const auto& klasses = prototype->klasses(); // Unknown (if present) is the actual object type - swizzle its selector instead of the public class' one const auto& klass = klasses.realClass(); if (const PropertyMeta* propertyMeta = prototype->_metadata->instanceProperty(propertyName.publicName(), klasses, true, prototype->additionalProtocols())) { if (!propertyDescriptor.isAccessorDescriptor()) { WTFCrash(); } PropertyDescriptor nativeProperty; prototype->getOwnPropertyDescriptor(execState, propertyName, nativeProperty); if (const MethodMeta* meta = propertyMeta->getter()) { ObjCMethodCallback* methodCallback = createProtectedMethodCallback(execState, propertyDescriptor.getter().asCell(), meta); std::string compilerEncoding = getCompilerEncoding(execState->lexicalGlobalObject(), meta); IMP nativeImp = class_replaceMethod(klass, meta->selector(), reinterpret_cast<IMP>(methodCallback->functionPointer()), compilerEncoding.c_str()); SEL nativeSelector = sel_registerName(makeString("__", meta->selectorAsString()).utf8().data()); class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); if (ObjCMethodWrapper* nativeMethod = jsDynamicCast<ObjCMethodWrapper*>(vm, nativeProperty.getter())) { static_cast<ObjCMethodCall*>(nativeMethod->onlyFuncInContainer())->setSelector(nativeSelector); } } if (const MethodMeta* meta = propertyMeta->setter()) { ObjCMethodCallback* methodCallback = createProtectedMethodCallback(execState, propertyDescriptor.setter().asCell(), meta); std::string compilerEncoding = getCompilerEncoding(execState->lexicalGlobalObject(), meta); IMP nativeImp = class_replaceMethod(klass, meta->selector(), reinterpret_cast<IMP>(methodCallback->functionPointer()), compilerEncoding.c_str()); SEL nativeSelector = sel_registerName(makeString("__", meta->selectorAsString()).utf8().data()); class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); if (ObjCMethodWrapper* nativeMethod = jsDynamicCast<ObjCMethodWrapper*>(vm, nativeProperty.setter())) { static_cast<ObjCMethodCall*>(nativeMethod->onlyFuncInContainer())->setSelector(nativeSelector); } } } return Base::defineOwnProperty(object, execState, propertyName, propertyDescriptor, shouldThrow); } NS_CATCH_THROW_TO_JS(execState) return false; } void ObjCPrototype::getOwnPropertyNames(JSObject* object, ExecState* execState, PropertyNameArray& propertyNames, EnumerationMode enumerationMode) { NS_TRY { ObjCPrototype* prototype = jsCast<ObjCPrototype*>(object); const auto& klasses = prototype->klasses(); std::vector<const BaseClassMeta*> baseClassMetaStack; baseClassMetaStack.push_back(prototype->_metadata); while (!baseClassMetaStack.empty()) { const BaseClassMeta* baseClassMeta = baseClassMetaStack.back(); baseClassMetaStack.pop_back(); for (Metadata::ArrayOfPtrTo<MethodMeta>::iterator it = baseClassMeta->instanceMethods->begin(); it != baseClassMeta->instanceMethods->end(); it++) { if ((*it)->isAvailableInClasses(klasses, /*isStatic*/ false)) propertyNames.add(Identifier::fromString(execState, (*it)->jsName())); } for (Metadata::ArrayOfPtrTo<PropertyMeta>::iterator it = baseClassMeta->instanceProps->begin(); it != baseClassMeta->instanceProps->end(); it++) { auto propertyName = Identifier::fromString(execState, (*it)->jsName()); if ((*it)->isAvailableInClasses(klasses, /*isStatic*/ false) && !prototype->shouldSkipOwnProperty(execState, propertyName, (*it).valuePtr())) propertyNames.add(propertyName); } for (Metadata::Array<Metadata::String>::iterator it = baseClassMeta->protocols->begin(); it != baseClassMeta->protocols->end(); it++) { const ProtocolMeta* protocolMeta = MetaFile::instance()->globalTableJs()->findProtocol((*it).valuePtr()); if (protocolMeta != nullptr) baseClassMetaStack.push_back(protocolMeta); } } Base::getOwnPropertyNames(object, execState, propertyNames, enumerationMode); } NS_CATCH_THROW_TO_JS(execState) } void ObjCPrototype::defineNativeProperty(VM& vm, GlobalObject* globalObject, const PropertyMeta* propertyMeta) { SymbolLoader::instance().ensureModule(propertyMeta->topLevelModule()); const MethodMeta* getter = (propertyMeta->hasGetter() && propertyMeta->getter()->isAvailable()) ? propertyMeta->getter() : nullptr; const MethodMeta* setter = (propertyMeta->hasSetter() && propertyMeta->setter()->isAvailable()) ? propertyMeta->setter() : nullptr; PropertyDescriptor descriptor; descriptor.setConfigurable(true); Strong<ObjCMethodWrapper> strongGetter; Strong<ObjCMethodWrapper> strongSetter; if (getter) { MembersCollection getters = { getter }; strongGetter = ObjCMethodWrapper::create(vm, globalObject, globalObject->objCMethodWrapperStructure(), getters); descriptor.setGetter(strongGetter.get()); } if (setter) { MembersCollection setters = { setter }; strongSetter = ObjCMethodWrapper::create(vm, globalObject, globalObject->objCMethodWrapperStructure(), setters); descriptor.setSetter(strongSetter.get()); } Base::defineOwnProperty(this, globalObject->globalExec(), Identifier::fromString(globalObject->globalExec(), propertyMeta->jsName()), descriptor, false); } void ObjCPrototype::materializeProperties(VM& vm, GlobalObject* globalObject) { #if 0 // The cycle here works around an issue with incorrect public headers of some iOS system frameworks. // In particular: // * UIBarItem doesn't define 6 of its declared properties (enabled, image, imageInsets, // landscapeImagePhone, landscapeImagePhoneInsets and title) but its inheritors UIBarButtonItem and // UITabBarItem do // * MTLRenderPassAttachmentDescriptor doesn't define 11 of its properties but it's inheritors // MTLRenderPassDepthAttachmentDescriptor, MTLRenderPassColorAttachmentDescriptor and // MTLRenderPassStencilAttachmentDescriptor do. // As a result we were not providing their implementation in JS before we started looking for missing // properties in the base class. This additional overhead increased the time spent in materializeProperties // from ~5.3 sec to ~7.5 sec (~40%) when running TestRunner with ApiIterator test enabled in RelWithDebInfo configuration // on an iPhone 6s device and from 3.0-3.2 to 4.4 sec (~40%) on an iPhone X const BaseClassMeta* meta = this->metadata(); Class klass = this->klass(); while (meta) { std::vector<const PropertyMeta*> properties = meta->instancePropertiesWithProtocols(nullptr); for (const PropertyMeta* propertyMeta : properties) { bool shouldDefine = false; if (klass == this->klass()) { // Property is coming from this class, define it if available shouldDefine = propertyMeta->isAvailableInClass(klass, false); } else { // Property is coming from a base class, define it as our property if isn't available there, but we've got it shouldDefine = !propertyMeta->isAvailableInClass(klass, false) && propertyMeta->isAvailableInClass(this->klass(), false); // addedProps += shouldDefine ? 1 : 0; } if (shouldDefine) { this->defineNativeProperty(vm, globalObject, propertyMeta); } } if (klass == this->klass() && meta->type() == Interface) { meta = static_cast<const InterfaceMeta*>(meta)->baseMeta(); klass = meta ? objc_getClass(meta->name()) : nullptr; } else { // Check only properties from the direct base class and then stop. // All the cases that we need to fix are like that so we don't have // to pay the additional overhead of looking intothe whole inheritance chain. meta = nullptr; } } #endif } }
1
0.929929
1
0.929929
game-dev
MEDIA
0.418564
game-dev
0.746373
1
0.746373
goblint/analyzer
1,188
tests/regression/37-congruence/07-refinements-o.c
// PARAM: --enable ana.int.congruence #include <goblint.h> void unsignedCase() { unsigned int top; unsigned int i = 0; if(top % 17 == 3) { __goblint_check(top%17 ==3); if(top %17 != 3) { i = 12; } else { } } __goblint_check(i ==0); if(top % 17 == 0) { __goblint_check(top%17 == 0); if(top %17 != 0) { i = 12; } } __goblint_check(i == 0); if(top % 3 == 17) { // This is unreachable in the concrete! __goblint_check(top%17 == 3); //UNKNOWN! } } int main() { int top; int i = 0; if(top % 17 == 3) { __goblint_check(top%17 ==3); //TODO (Refine top to be positive above, and reuse information in %) if(top %17 != 3) { i = 12; } else { } } __goblint_check(i ==0); //TODO i = 0; if(top % 17 == 0) { __goblint_check(top%17 == 0); if(top %17 != 0) { i = 12; } } __goblint_check(i == 0); if(top % 3 == 17) { // This is unreachable in the concrete! __goblint_check(top%17 == 3); //UNKNOWN! } unsignedCase(); }
1
0.660391
1
0.660391
game-dev
MEDIA
0.572162
game-dev
0.6701
1
0.6701
b-crawl/bcrawl
24,291
crawl-ref/source/monster.h
#pragma once #include <functional> #include "actor.h" #include "beh-type.h" #include "enchant-type.h" #include "mon-ench.h" #include "montravel-target-type.h" #include "potion-type.h" #include "seen-context-type.h" #include "spl-util.h" #include "xp-tracking-type.h" const int KRAKEN_TENTACLE_RANGE = 3; #define TIDE_CALL_TURN "tide-call-turn" #define MAX_DAMAGE_COUNTER 10000 #define ZOMBIE_BASE_AC_KEY "zombie_base_ac" #define ZOMBIE_BASE_EV_KEY "zombie_base_ev" #define MON_SPEED_KEY "speed" #define CUSTOM_SPELLS_KEY "custom_spells" #define SEEN_SPELLS_KEY "seen_spells" #define KNOWN_MAX_HP_KEY "known_max_hp" #define VAULT_HD_KEY "vault_hd" #define FAKE_BLINK_KEY "fake_blink" #define CEREBOV_DISARMED_KEY "cerebov_disarmed" /// has a given hound already used up its howl? #define DOOM_HOUND_HOWLED_KEY "doom_hound_howled" #define DROPPER_MID_KEY "dropper_mid" #define MAP_KEY "map" typedef map<enchant_type, mon_enchant> mon_enchant_list; struct monsterentry; class monster : public actor { public: monster(); monster(const monster& other); ~monster(); monster& operator = (const monster& other); void reset(); public: // Possibly some of these should be moved into the hash table string mname; int hit_points; int max_hit_points; int speed; int speed_increment; coord_def target; coord_def firing_pos; coord_def patrol_point; mutable montravel_target_type travel_target; vector<coord_def> travel_path; FixedVector<short, NUM_MONSTER_SLOTS> inv; monster_spells spells; mon_attitude_type attitude; beh_type behaviour; unsigned short foe; int8_t ench_countdown; mon_enchant_list enchantments; FixedBitVector<NUM_ENCHANTMENTS> ench_cache; monster_flags_t flags; // bitfield of boolean flags xp_tracking_type xp_tracking; unsigned int experience; monster_type base_monster; // zombie base monster, draconian colour union { // These must all be the same size! unsigned int number; ///< General purpose number variable int blob_size; ///< num of slimes/masses in this one int num_heads; ///< Hydra-like head number int ballisto_activity; ///< How active is this ballistomycete? int spore_cooldown; ///< Can this make ballistos (if 0) int mangrove_pests; ///< num of animals in shambling mangrove int prism_charge; ///< Turns this prism has existed int battlecharge; ///< Charges of battlesphere int move_spurt; ///< Sixfirhy/jiangshi/kraken black magic mid_t tentacle_connect;///< mid of monster this tentacle is // connected to: for segments, this is the // tentacle; for tentacles, the head. }; int colour; mid_t summoner; int foe_memory; // how long to 'remember' foe x,y // once they go out of sight. god_type god; // What god the monster worships, if // any. unique_ptr<ghost_demon> ghost; // Ghost information. seen_context_type seen_context; // Non-standard context for // AI_SEE_MONSTER int damage_friendly; // Damage taken, x2 you, x1 pets, x0 else. int damage_total; uint32_t client_id; // for ID of monster_info between turns static uint32_t last_client_id; bool went_unseen_this_turn; coord_def unseen_pos; public: void set_new_monster_id(); uint32_t get_client_id() const; void reset_client_id(); void ensure_has_client_id(); void set_hit_dice(int new_hd); mon_attitude_type temp_attitude() const override; mon_attitude_type real_attitude() const override { return attitude; } // Returns true if the monster is named with a proper name, or is // a player ghost. bool is_named() const; // Does this monster have a base name, i.e. is base_name() != name(). // See base_name() for details. bool has_base_name() const; const monsterentry *find_monsterentry() const; void init_experience(); void mark_summoned(int longevity, bool mark_items_summoned, int summon_type = 0, bool abj = true); bool is_summoned(int* duration = nullptr, int* summon_type = nullptr) const override; bool is_perm_summoned() const override; bool has_action_energy() const; void drain_action_energy(); void check_redraw(const coord_def &oldpos, bool clear_tiles = true) const; void apply_location_effects(const coord_def &oldpos, killer_type killer = KILL_NONE, int killernum = -1) override; void self_destruct() override; void moveto(const coord_def& c, bool clear_net = true) override; bool move_to_pos(const coord_def &newpos, bool clear_net = true, bool force = false) override; bool swap_with(monster* other); bool blink_to(const coord_def& c, bool quiet = false) override; bool blink_to(const coord_def& c, bool quiet, bool jump); kill_category kill_alignment() const override; int foe_distance() const; bool needs_berserk(bool check_spells = true, bool ignore_distance = false) const; // Has a hydra-like variable number of attacks based on num_heads. bool has_hydra_multi_attack() const; int heads() const override; bool has_multitargeting() const; // Has the 'priest' flag. bool is_priest() const; // Has the 'fighter' flag. bool is_fighter() const; // Has the 'archer' flag. bool is_archer() const; // Is an actual wizard-type spellcaster (it can be silenced, Trog // will dislike it, etc.). bool is_actual_spellcaster() const; // Has ENCH_SHAPESHIFTER or ENCH_GLOWING_SHAPESHIFTER. bool is_shapeshifter() const; #ifdef DEBUG_DIAGNOSTICS bool has_ench(enchant_type ench) const; // same but validated #else bool has_ench(enchant_type ench) const { return ench_cache[ench]; } #endif bool has_ench(enchant_type ench, enchant_type ench2) const; mon_enchant get_ench(enchant_type ench, enchant_type ench2 = ENCH_NONE) const; bool add_ench(const mon_enchant &); void update_ench(const mon_enchant &); bool del_ench(enchant_type ench, bool quiet = false, bool effect = true); bool lose_ench_duration(const mon_enchant &e, int levels); bool lose_ench_levels(const mon_enchant &e, int lev, bool infinite = false); void lose_energy(energy_use_type et, int div = 1, int mult = 1) override; void gain_energy(energy_use_type et, int div = 1, int mult = 1) override; void scale_hp(int num, int den); bool gain_exp(int exp, int max_levels_to_gain = 2); void react_to_damage(const actor *oppressor, int damage, beam_type flavour); void add_enchantment_effect(const mon_enchant &me, bool quiet = false); void remove_enchantment_effect(const mon_enchant &me, bool quiet = false); void apply_enchantments(); void apply_enchantment(const mon_enchant &me); bool can_drink() const; bool can_drink_potion(potion_type ptype) const; bool should_drink_potion(potion_type ptype) const; bool drink_potion_effect(potion_type pot_eff, bool card = false); bool can_evoke_jewellery(jewellery_type jtype) const; bool should_evoke_jewellery(jewellery_type jtype) const; bool evoke_jewellery_effect(jewellery_type jtype); void timeout_enchantments(int levels); bool is_travelling() const; bool is_patrolling() const; bool needs_abyss_transit() const; void set_transit(const level_id &destination); bool is_trap_safe(const coord_def& where, bool just_check = false) const; bool is_location_safe(const coord_def &place); bool find_place_to_live(bool near_player = false); bool find_home_near_place(const coord_def &c); bool find_home_near_player(); bool find_home_anywhere(); // The map that placed this monster. bool has_originating_map() const; string originating_map() const; void set_originating_map(const string &); void set_ghost(const ghost_demon &ghost); void ghost_init(bool need_pos = true); void ghost_demon_init(); void uglything_init(bool only_mutate = false); void uglything_mutate(colour_t force_colour = COLOUR_UNDEF); void destroy_inventory(); void load_ghost_spells(); brand_type ghost_brand() const; bool has_ghost_brand() const; actor *get_foe() const; // actor interface int mindex() const override; int get_hit_dice() const override; int get_experience_level() const override; god_type deity() const override; bool alive() const override; bool defined() const { return alive(); } bool swimming() const override; bool submerged() const override; bool can_drown() const; bool floundering_at(const coord_def p) const; bool floundering() const override; bool extra_balanced_at(const coord_def p) const; bool extra_balanced() const override; bool can_pass_through_feat(dungeon_feature_type grid) const override; bool is_habitable_feat(dungeon_feature_type actual_grid) const override; bool shove(const char* name = "") override; size_type body_size(size_part_type psize = PSIZE_TORSO, bool base = false) const override; brand_type damage_brand(int which_attack = -1) override; int damage_type(int which_attack = -1) override; random_var attack_delay(const item_def *projectile = nullptr, bool rescale = true) const override; int has_claws(bool allow_tran = true) const override; int wearing(equipment_type slot, int type, bool calc_unid = true) const override; int wearing_ego(equipment_type slot, int type, bool calc_unid = true) const override; int scan_artefacts(artefact_prop_type which_property, bool calc_unid = true, vector<item_def> *_unused_matches = nullptr) const override; item_def *slot_item(equipment_type eq, bool include_melded=false) const override; item_def *mslot_item(mon_inv_type sl) const; item_def *weapon(int which_attack = -1) const override; item_def *launcher() const; item_def *melee_weapon() const; item_def *missiles() const; item_def *shield() const override; hands_reqd_type hands_reqd(const item_def &item, bool base = false) const override; bool can_wield(const item_def &item, bool ignore_curse = false, bool ignore_brand = false, bool ignore_shield = false, bool ignore_transform = false) const override; bool could_wield(const item_def &item, bool ignore_brand = false, bool ignore_transform = false, bool quiet = true) const override; void wield_melee_weapon(maybe_bool msg = MB_MAYBE); void swap_weapons(maybe_bool msg = MB_MAYBE); bool pickup_item(item_def &item, bool msg, bool force); bool drop_item(mon_inv_type eslot, bool msg); bool unequip(item_def &item, bool msg, bool force = false); void steal_item_from_player(); item_def* take_item(int steal_what, mon_inv_type mslot, bool is_stolen = false); item_def* disarm(); bool can_use_missile(const item_def &item) const; bool likes_wand(const item_def &item) const; string name(description_level_type type, bool force_visible = false, bool force_article = false) const override; // Base name of the monster, bypassing any mname setting. For an orc priest // named Arbolt, name() will return "Arbolt", but base_name() will return // "orc priest". string base_name(description_level_type type, bool force_visible = false) const; // Full name of the monster. For an orc priest named Arbolt, full_name() // will return "Arbolt the orc priest". string full_name(description_level_type type) const; string pronoun(pronoun_type pro, bool force_visible = false) const override; string conj_verb(const string &verb) const override; string hand_name(bool plural, bool *can_plural = nullptr) const override; string foot_name(bool plural, bool *can_plural = nullptr) const override; string arm_name(bool plural, bool *can_plural = nullptr) const override; bool fumbles_attack() override; int skill(skill_type skill, int scale = 1, bool real = false, bool drained = true, bool temp = true) const override; void attacking(actor *other, bool ranged) override; bool can_go_frenzy() const; bool can_go_berserk() const override; bool go_berserk(bool intentional, bool potion = false) override; bool go_frenzy(actor *source); bool berserk() const override; bool berserk_or_insane() const; bool can_mutate() const override; bool can_safely_mutate(bool temp = true) const override; bool can_polymorph() const override; bool can_bleed(bool allow_tran = true) const override; bool is_stationary() const override; bool malmutate(const string &/*reason*/) override; void corrupt(); bool polymorph(int pow) override; void banish(actor *agent, const string &who = "", const int power = 0, bool force = false) override; void expose_to_element(beam_type element, int strength = 0, bool slow_cold_blood = true) override; monster_type mons_species(bool zombie_base = false) const override; mon_holy_type holiness(bool /*temp*/ = true) const override; bool undead_or_demonic() const override; bool is_holy() const override; bool is_nonliving(bool /*temp*/ = true) const override; int how_unclean(bool check_god = true) const; int known_chaos(bool check_spells_god = false) const; int how_chaotic(bool check_spells_god = false) const override; bool is_unbreathing() const override; bool is_insubstantial() const override; bool res_hellfire() const override; int res_fire() const override; int res_steam() const override; int res_cold() const override; int res_elec() const override; int res_poison(bool temp = true) const override; int res_rotting(bool /*temp*/ = true) const override; int res_water_drowning() const override; bool res_sticky_flame() const override; int res_holy_energy() const override; int res_negative_energy(bool intrinsic_only = false) const override; bool res_torment() const override; int res_acid(bool calc_unid = true) const override; bool res_tornado() const override; bool res_petrify(bool /*temp*/ = true) const override; int res_constrict() const override; int res_magic(bool calc_unid = true) const override; bool no_tele(bool calc_unid = true, bool permit_id = true, bool blink = false) const override; bool res_corr(bool calc_unid = true, bool items = true) const override; bool antimagic_susceptible() const override; bool stasis(bool calc_unid = true, bool items = true) const override; bool cloud_immune(bool calc_unid = true, bool items = true) const override; bool airborne() const override; bool can_cling_to_walls() const override; bool is_banished() const override; bool is_web_immune() const override; bool invisible() const override; bool can_see_invisible(bool calc_unid = true) const override; bool visible_to(const actor *looker) const override; bool near_foe() const; reach_type reach_range() const override; bool nightvision() const override; bool is_icy() const override; bool is_fiery() const override; bool is_skeletal() const override; bool is_spiny() const; bool paralysed() const override; bool cannot_move() const override; bool cannot_act() const override; bool confused() const override; bool confused_by_you() const; bool caught() const override; bool asleep() const override; bool backlit(bool self_halo = true) const override; bool umbra() const override; int halo_radius() const override; int silence_radius() const override; int liquefying_radius() const override; int umbra_radius() const override; bool petrified() const override; bool petrifying() const override; bool liquefied_ground() const override; int natural_regen_rate() const; int off_level_regen_rate() const; bool friendly() const; bool neutral() const; bool good_neutral() const; bool strict_neutral() const; bool wont_attack() const override; bool pacified() const; bool has_spells() const; bool has_spell(spell_type spell) const override; mon_spell_slot_flags spell_slot_flags(spell_type spell) const; bool has_unclean_spell() const; bool has_chaotic_spell() const; bool has_corpse_violating_spell() const; bool has_attack_flavour(int flavour) const; bool has_damage_type(int dam_type); int constriction_damage(bool direct) const override; bool constriction_does_damage(bool direct) const override; bool can_throw_large_rocks() const override; bool can_speak(); bool is_silenced() const; int base_armour_class() const; int armour_class(bool calc_unid = true) const override; int gdr_perc() const override { return 0; } int base_evasion() const; int evasion(ev_ignore_type evit = EV_IGNORE_NONE, const actor* /*attacker*/ = nullptr) const override; bool poison(actor *agent, int amount = 1, bool force = false) override; bool sicken(int strength) override; void paralyse(actor *, int str, string source = "") override; void petrify(actor *, bool force = false) override; bool fully_petrify(actor *foe, bool quiet = false) override; void slow_down(actor *, int str) override; void confuse(actor *, int strength) override; bool drain_exp(actor *, bool quiet = false, int pow = 3) override; bool rot(actor *, int amount, bool quiet = false, bool no_cleanup = false) override; void splash_with_acid(const actor* evildoer, int /*acid_strength*/ = -1, bool /*allow_corrosion*/ = true, const char* /*hurt_msg*/ = nullptr) override; bool corrode_equipment(const char* corrosion_source = "the acid", int degree = 1) override; int hurt(const actor *attacker, int amount, beam_type flavour = BEAM_MISSILE, kill_method_type kill_type = KILLED_BY_MONSTER, string source = "", string aux = "", bool cleanup_dead = true, bool attacker_effects = true) override; bool heal(int amount) override; void blame_damage(const actor *attacker, int amount); void blink() override; void teleport(bool right_now = false, bool wizard_tele = false) override; bool shift(coord_def p = coord_def(0, 0)); void suicide(int hp_target = -1); void put_to_sleep(actor *attacker, int power = 0, bool hibernate = false) override; void weaken(actor *attacker, int pow) override; void check_awaken(int disturbance) override; int beam_resists(bolt &beam, int hurted, bool doEffects, string source = "") override; int stat_hp() const override { return hit_points; } int stat_maxhp() const override { return max_hit_points; } int stealth() const override { return 0; } bool shielded() const override; int shield_bonus() const override; int shield_block_penalty() const override; void shield_block_succeeded(actor *foe) override; int shield_bypass_ability(int tohit) const override; int missile_deflection() const override; void ablate_deflection() override; // Combat-related class methods int unadjusted_body_armour_penalty() const override { return 0; } int adjusted_body_armour_penalty(int) const override { return 0; } int adjusted_shield_penalty(int) const override { return 0; } int armour_tohit_penalty(bool, int) const override { return 0; } int shield_tohit_penalty(bool, int) const override { return 0; } bool is_player() const override { return false; } monster* as_monster() override { return this; } player* as_player() override { return nullptr; } const monster* as_monster() const override { return this; } const player* as_player() const override { return nullptr; } // Hacks, with a capital H. void check_speed(); void upgrade_type(monster_type after, bool adjust_hd, bool adjust_hp); string describe_enchantments() const; int action_energy(energy_use_type et) const; bool do_shaft() override; bool has_spell_of_type(spschool_flag_type discipline) const; void bind_melee_flags(); void bind_spell_flags(); void calc_speed(); bool attempt_escape(int attempts = 1); void struggle_against_net(); bool has_usable_tentacle() const override; bool check_clarity(bool silent) const; bool is_child_tentacle() const; bool is_child_tentacle_of(const monster* mons) const; bool is_child_monster() const; bool is_parent_monster_of(const monster* mons) const; bool is_child_tentacle_segment() const; bool is_illusion() const; bool is_divine_companion() const; // Jumping spiders (jump instead of blink) bool is_jumpy() const; int spell_hd(spell_type spell = SPELL_NO_SPELL) const; void remove_summons(bool check_attitude = false); void note_spell_cast(spell_type spell); bool clear_far_engulf() override; bool search_slots(function<bool (const mon_spell_slot &)> func) const; bool has_facet(int facet) const; bool angered_by_attacks() const; private: int hit_dice; private: bool pickup(item_def &item, mon_inv_type slot, bool msg); void pickup_message(const item_def &item); bool pickup_wand(item_def &item, bool msg, bool force = false); bool pickup_scroll(item_def &item, bool msg); bool pickup_potion(item_def &item, bool msg, bool force = false); bool pickup_gold(item_def &item, bool msg); bool pickup_launcher(item_def &launcher, bool msg, bool force = false); bool pickup_melee_weapon(item_def &item, bool msg); bool pickup_weapon(item_def &item, bool msg, bool force); bool pickup_armour(item_def &item, bool msg, bool force); bool pickup_jewellery(item_def &item, bool msg, bool force); bool pickup_misc(item_def &item, bool msg, bool force); bool pickup_missile(item_def &item, bool msg, bool force); void equip_message(item_def &item); void equip_weapon_message(item_def &item); void equip_armour_message(item_def &item); void equip_jewellery_message(item_def &item); void unequip_weapon(item_def &item, bool msg); void unequip_armour(item_def &item, bool msg); void unequip_jewellery(item_def &item, bool msg); void init_with(const monster& mons); bool level_up(); bool level_up_change(); int armour_bonus(const item_def &item, bool calc_unid = true) const; void id_if_worn(mon_inv_type mslot, object_class_type base_type, int sub_type) const; bool decay_enchantment(enchant_type en, bool decay_degree = true); bool wants_weapon(const item_def &item) const; bool wants_armour(const item_def &item) const; bool wants_jewellery(const item_def &item) const; void lose_pickup_energy(); bool check_set_valid_home(const coord_def &place, coord_def &chosen, int &nvalid) const; bool search_spells(function<bool (spell_type)> func) const; bool is_cloud_safe(const coord_def &place) const; };
1
0.767586
1
0.767586
game-dev
MEDIA
0.922264
game-dev
0.845356
1
0.845356
cryptiklemur/fluent-behavior-tree
2,069
src/Node/ParallelNode.ts
import BehaviorTreeStatus from "../BehaviorTreeStatus"; import StateData from "../StateData"; import BehaviorTreeNodeInterface from "./BehaviorTreeNodeInterface"; import ParentBehaviorTreeNodeInterface from "./ParentBehaviorTreeNodeInterface"; /** * Runs child's nodes in parallel. * * @property {string} name - The name of the node. * @property {number} requiredToFail - Number of child failures required to terminate with failure. * @property {number} requiredToSucceed - Number of child successes required to terminate with success. */ export default class ParallelNode implements ParentBehaviorTreeNodeInterface { /** * List of child nodes. * * @type {BehaviorTreeNodeInterface[]} */ private children: BehaviorTreeNodeInterface[] = []; public constructor( public readonly name: string, public readonly requiredToFail: number, public readonly requiredToSucceed: number, ) { } public async tick(state: StateData): Promise<BehaviorTreeStatus> { const statuses: BehaviorTreeStatus[] = await Promise.all(this.children.map((c) => this.tickChildren(state, c))); const succeeded = statuses.filter((x) => x === BehaviorTreeStatus.Success).length; const failed = statuses.filter((x) => x === BehaviorTreeStatus.Failure).length; if (this.requiredToSucceed > 0 && succeeded >= this.requiredToSucceed) { return BehaviorTreeStatus.Success; } if (this.requiredToFail > 0 && failed >= this.requiredToFail) { return BehaviorTreeStatus.Failure; } return BehaviorTreeStatus.Running; } public addChild(child: BehaviorTreeNodeInterface): void { this.children.push(child); } private async tickChildren(state: StateData, child: BehaviorTreeNodeInterface): Promise<BehaviorTreeStatus> { try { return await child.tick(state); } catch (e) { return BehaviorTreeStatus.Failure; } } }
1
0.929424
1
0.929424
game-dev
MEDIA
0.240484
game-dev
0.942376
1
0.942376
SirPlease/L4D2-Competitive-Rework
15,415
addons/sourcemod/scripting/l4d2_charge_target_fix.sp
#pragma semicolon 1 #pragma newdecls required #include <sourcemod> #include <dhooks> #include <left4dhooks> #define PLUGIN_VERSION "1.10" public Plugin myinfo = { name = "[L4D2] Charger Target Fix", author = "Forgetest", description = "Fix multiple issues with charger targets.", version = PLUGIN_VERSION, url = "https://github.com/Target5150/MoYu_Server_Stupid_Plugins" }; #define GAMEDATA_FILE "l4d2_charge_target_fix" #define FUNCTION_NAME "CCharge::HandleCustomCollision" #define KEY_ANIMSTATE "CTerrorPlayer::m_PlayerAnimState" #define KEY_FLAG_CHARGED "CTerrorPlayerAnimState::m_bCharged" int m_PlayerAnimState, m_bCharged; enum AnimStateFlag // mid-way start from m_bCharged { AnimState_WallSlammed = 2, AnimState_GroundSlammed = 3, } methodmap AnimState { public AnimState(int client) { int ptr = GetEntData(client, m_PlayerAnimState, 4); if (ptr == 0) ThrowError("Invalid pointer to \"CTerrorPlayer::CTerrorPlayerAnimState\" (client %d).", client); return view_as<AnimState>(ptr); } public bool GetFlag(AnimStateFlag flag) { return view_as<bool>(LoadFromAddress(view_as<Address>(this) + view_as<Address>(m_bCharged) + view_as<Address>(flag), NumberType_Int8)); } } #define FSOLID_NOT_SOLID 0x0004 // Are we currently not solid? #define KNOCKDOWN_DURATION_CHARGER 2.5 int g_iChargeVictim[MAXPLAYERS+1] = {-1, ...}, g_iChargeAttacker[MAXPLAYERS+1] = {-1, ...}; bool g_bNotSolid[MAXPLAYERS+1]; enum { CHARGER_COLLISION_PUMMEL = 1, CHARGER_COLLISION_GETUP = (1 << 1) }; int g_iChargerCollision; float g_flKnockdownWindow; public void OnPluginStart() { GameData gd = new GameData(GAMEDATA_FILE); if (!gd) SetFailState("Missing gamedata \""...GAMEDATA_FILE..."\""); m_PlayerAnimState = GameConfGetOffset(gd, KEY_ANIMSTATE); if (m_PlayerAnimState == -1) SetFailState("Missing offset \""...KEY_ANIMSTATE..."\""); m_bCharged = GameConfGetOffset(gd, KEY_FLAG_CHARGED); if (m_bCharged == -1) SetFailState("Missing offset \""...KEY_FLAG_CHARGED..."\""); DynamicDetour hDetour = DynamicDetour.FromConf(gd, FUNCTION_NAME); if (!hDetour) SetFailState("Missing detour setup \""...FUNCTION_NAME..."\""); if (!hDetour.Enable(Hook_Pre, DTR_CCharge__HandleCustomCollision)) SetFailState("Failed to detour \""...FUNCTION_NAME..."\""); delete hDetour; delete gd; CreateConVarHook("z_charge_pinned_collision", "3", "Enable collision to Infected Team on Survivors pinned by charger.\n" ... "1 = Enable collision during pummel, 2 = Enable collision during get-up, 3 = Both, 0 = No collision at all.", FCVAR_SPONLY, true, 0.0, true, 3.0, CvarChg_ChargerCollision); CreateConVarHook("charger_knockdown_getup_window", "0.1", "Duration between knockdown timer ends and get-up finishes.\n" ... "The higher value is set, the earlier Survivors become collideable when getting up from charger.", FCVAR_SPONLY, true, 0.0, true, 4.0, CvarChg_KnockdownWindow); HookEvent("round_start", Event_RoundStart); HookEvent("player_incapacitated", Event_PlayerIncap); HookEvent("player_death", Event_PlayerDeath); HookEvent("charger_carry_start", Event_ChargerCarryStart); HookEvent("charger_carry_end", Event_ChargerCarryEnd); HookEvent("charger_pummel_end", Event_ChargerPummelEnd); HookEvent("charger_killed", Event_ChargerKilled); HookEvent("player_bot_replace", Event_PlayerBotReplace); HookEvent("bot_player_replace", Event_BotPlayerReplace); } // Fix charger grabbing victims of other chargers MRESReturn DTR_CCharge__HandleCustomCollision(int ability, DHookReturn hReturn, DHookParam hParams) { if (!GetEntProp(ability, Prop_Send, "m_hasBeenUsed")) return MRES_Ignored; int charger = GetEntPropEnt(ability, Prop_Send, "m_owner"); if (charger == -1) return MRES_Ignored; int touch = hParams.Get(1); if (!touch || touch > MaxClients) return MRES_Ignored; if (g_iChargeAttacker[touch] == -1) // free for attacks return MRES_Ignored; if (g_iChargeAttacker[touch] == charger) // about to slam my victim return MRES_Ignored; // basically invalid calls at here, block hReturn.Value = 0; return MRES_Supercede; } void CvarChg_ChargerCollision(ConVar convar, const char[] oldValue, const char[] newValue) { g_iChargerCollision = convar.IntValue; } void CvarChg_KnockdownWindow(ConVar convar, const char[] oldValue, const char[] newValue) { g_flKnockdownWindow = convar.FloatValue; } // Fix anomaly pummel that usually happens when a Charger is carrying someone and round restarts void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { for (int i = 1; i <= MaxClients; ++i) { // clear our stuff g_bNotSolid[i] = false; g_iChargeVictim[i] = -1; g_iChargeAttacker[i] = -1; if (IsClientInGame(i)) { // ~ CDirector::RestartScenario() // ~ CDirector::Restart() // ~ ForEachTerrorPlayer<RestartCleanup>() // ~ CTerrorPlayer::CleanupPlayerState() // ~ CTerrorPlayer::OnCarryEnded( (bClearBoth = true), (bSkipPummel = false), (bIsAttacker = true) ) // ~ CTerrorPlayer::QueuePummelVictim( m_carryVictim.Get(), -1.0 ) // CTerrorPlayer::UpdatePound() SetEntPropEnt(i, Prop_Send, "m_pummelVictim", -1); SetEntPropEnt(i, Prop_Send, "m_pummelAttacker", -1); // perhaps unnecessary L4D2_SetQueuedPummelStartTime(i, -1.0); L4D2_SetQueuedPummelVictim(i, -1); L4D2_SetQueuedPummelAttacker(i, -1); } } } // Remove collision on Survivor going incapped because `CTerrorPlayer::IsGettingUp` returns false in this case // Thanks to @Alan on discord for reporting. void Event_PlayerIncap(Event event, const char[] name, bool dontBroadcast) { if (g_iChargerCollision & CHARGER_COLLISION_PUMMEL) return; int client = GetClientOfUserId(event.GetInt("userid")); if (!client || !IsClientInGame(client)) return; if (GetClientTeam(client) != 2) return; int queuedPummelAttacker = L4D2_GetQueuedPummelAttacker(client); if (queuedPummelAttacker == -1 || !L4D2_IsInQueuedPummel(queuedPummelAttacker)) { if (GetEntPropEnt(client, Prop_Send, "m_pummelAttacker") == -1) return; } SetPlayerSolid(client, false); g_bNotSolid[client] = true; } // Clear arrays if the victim dies to slams void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { int client = GetClientOfUserId(event.GetInt("userid")); if (!client || !IsClientInGame(client)) return; int attacker = g_iChargeAttacker[client]; if (attacker == -1) return; if (L4D2_IsInQueuedPummel(attacker) && L4D2_GetQueuedPummelVictim(attacker) == client) { int ability = GetEntPropEnt(attacker, Prop_Send, "m_customAbility"); SetEntPropFloat(ability, Prop_Send, "m_nextActivationTimer", 0.2, 0); SetEntPropFloat(ability, Prop_Send, "m_nextActivationTimer", L4D2_GetQueuedPummelStartTime(attacker) + 0.2, 1); } if (g_bNotSolid[client]) { SetPlayerSolid(client, true); g_bNotSolid[client] = false; } g_iChargeVictim[attacker] = -1; g_iChargeAttacker[client] = -1; } void Event_ChargerCarryStart(Event event, const char[] name, bool dontBroadcast) { int victim = GetClientOfUserId(event.GetInt("victim")); if (!victim || !IsClientInGame(victim)) return; int attacker = GetClientOfUserId(event.GetInt("userid")); if (!attacker || !IsClientInGame(attacker)) return; SetEntPropFloat(victim, Prop_Send, "m_jumpSupressedUntil", GetGameTime() + 0.5); } void Event_ChargerCarryEnd(Event event, const char[] name, bool dontBroadcast) { int victim = GetClientOfUserId(event.GetInt("victim")); if (!victim || !IsClientInGame(victim)) return; int attacker = GetClientOfUserId(event.GetInt("userid")); if (!attacker || !IsClientInGame(attacker)) return; SetEntPropFloat(victim, Prop_Send, "m_jumpSupressedUntil", GetGameTime() + 0.3); } // Calls if charger has started pummelling. void Event_ChargerPummelEnd(Event event, const char[] name, bool dontBroadcast) { int client = GetClientOfUserId(event.GetInt("userid")); if (!client) return; int victimId = event.GetInt("victim"); int victim = GetClientOfUserId(victimId); if (!victim || !IsClientInGame(victim)) return; if (~g_iChargerCollision & CHARGER_COLLISION_GETUP) { KnockdownPlayer(victim, KNOCKDOWN_CHARGER); ExtendKnockdown(victim, false); } if (g_bNotSolid[victim]) { SetPlayerSolid(victim, true); g_bNotSolid[victim] = false; } // Normal processes don't need special care g_iChargeVictim[client] = -1; g_iChargeAttacker[victim] = -1; } // Calls if charger has slammed and before pummel, or simply is cleared before slam. void Event_ChargerKilled(Event event, const char[] name, bool dontBroadcast) { int client = GetClientOfUserId(event.GetInt("userid")); if (!client || !IsClientInGame(client)) return; int victim = g_iChargeVictim[client]; if (victim == -1) return; if (~g_iChargerCollision & CHARGER_COLLISION_GETUP) { KnockdownPlayer(victim, KNOCKDOWN_CHARGER); // a small delay to be compatible with `l4d2_getup_fixes` RequestFrame(OnNextFrame_LongChargeKnockdown, GetClientUserId(victim)); } if (g_bNotSolid[victim]) { SetPlayerSolid(victim, true); g_bNotSolid[victim] = false; } g_iChargeVictim[client] = -1; g_iChargeAttacker[victim] = -1; } void OnNextFrame_LongChargeKnockdown(int userid) { int client = GetClientOfUserId(userid); if (!client || !IsClientInGame(client)) return; ExtendKnockdown(client, true); } void ExtendKnockdown(int client, bool isLongCharge) { float flExtendTime = 0.0; if (!isLongCharge) { float flAnimTime = 85 / 30.0; flExtendTime = flAnimTime - KNOCKDOWN_DURATION_CHARGER - g_flKnockdownWindow; } else { AnimState pAnim = AnimState(client); float flAnimTime = 0.0; if (((flAnimTime = 116 / 30.0), !pAnim.GetFlag(AnimState_WallSlammed)) && ((flAnimTime = 119 / 30.0), !pAnim.GetFlag(AnimState_GroundSlammed))) { ExtendKnockdown(client, false); return; } float flElaspedAnimTime = flAnimTime * GetEntPropFloat(client, Prop_Send, "m_flCycle"); flExtendTime = flAnimTime - flElaspedAnimTime - KNOCKDOWN_DURATION_CHARGER - g_flKnockdownWindow; } if (flExtendTime >= 0.1) CreateTimer(flExtendTime, Timer_ExtendKnockdown, GetClientUserId(client), TIMER_FLAG_NO_MAPCHANGE); } Action Timer_ExtendKnockdown(Handle timer, int userid) { int client = GetClientOfUserId(userid); if (!client || !IsClientInGame(client)) return Plugin_Stop; KnockdownPlayer(client, KNOCKDOWN_CHARGER); return Plugin_Stop; } void Event_PlayerBotReplace(Event event, const char[] name, bool dontBroadcast) { HandlePlayerReplace(GetClientOfUserId(event.GetInt("bot")), GetClientOfUserId(event.GetInt("player"))); } void Event_BotPlayerReplace(Event event, const char[] name, bool dontBroadcast) { HandlePlayerReplace(GetClientOfUserId(event.GetInt("player")), GetClientOfUserId(event.GetInt("bot"))); } void HandlePlayerReplace(int replacer, int replacee) { if (!replacer || !IsClientInGame(replacer)) return; if (!replacee) replacee = -1; if (GetClientTeam(replacer) == 3) { if (g_iChargeVictim[replacee] != -1) { g_iChargeVictim[replacer] = g_iChargeVictim[replacee]; g_iChargeAttacker[g_iChargeVictim[replacee]] = replacer; g_iChargeVictim[replacee] = -1; if (L4D2_IsInQueuedPummel(replacee)) { float flQueuedPummelTime = L4D2_GetQueuedPummelStartTime(replacee); L4D2_SetQueuedPummelStartTime(replacer, flQueuedPummelTime); L4D2_SetQueuedPummelAttacker(g_iChargeVictim[replacer], replacer); L4D2_SetQueuedPummelVictim(replacer, g_iChargeVictim[replacer]); L4D2_SetQueuedPummelStartTime(replacee, -1.0); L4D2_SetQueuedPummelVictim(replacee, -1); } } } else { if (g_iChargeAttacker[replacee] != -1) { g_iChargeAttacker[replacer] = g_iChargeAttacker[replacee]; g_iChargeVictim[g_iChargeAttacker[replacee]] = replacer; g_iChargeAttacker[replacee] = -1; } if (g_bNotSolid[replacee]) { g_bNotSolid[replacer] = true; g_bNotSolid[replacee] = false; } } } public Action L4D_OnPouncedOnSurvivor(int victim, int attacker) { if (g_iChargeAttacker[victim] == -1) return Plugin_Continue; return Plugin_Handled; } public Action L4D2_OnJockeyRide(int victim, int attacker) { if (g_iChargeAttacker[victim] == -1) return Plugin_Continue; return Plugin_Handled; } public Action L4D_OnGrabWithTongue(int victim, int attacker) { if (g_iChargeAttacker[victim] == -1) return Plugin_Continue; return Plugin_Handled; } public void L4D2_OnStartCarryingVictim_Post(int victim, int attacker) { if (!victim || !IsClientInGame(victim)) return; if (!IsPlayerAlive(victim)) return; g_iChargeVictim[attacker] = victim; g_iChargeAttacker[victim] = attacker; } public void L4D2_OnSlammedSurvivor_Post(int victim, int attacker, bool bWallSlam, bool bDeadlyCharge) { if (!victim || !IsClientInGame(victim)) return; if (!IsPlayerAlive(victim)) return; g_iChargeVictim[attacker] = victim; g_iChargeAttacker[victim] = attacker; if (~g_iChargerCollision & CHARGER_COLLISION_PUMMEL) { Handle timer = CreateTimer(1.0, Timer_KnockdownRepeat, GetClientUserId(victim), TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE); TriggerTimer(timer); } if (!IsPlayerAlive(attacker)) // compatibility with competitive 1v1 { Event event = CreateEvent("charger_killed"); event.SetInt("userid", GetClientUserId(attacker)); Event_ChargerKilled(event, "charger_killed", false); event.Cancel(); } int jockey = GetEntPropEnt(victim, Prop_Send, "m_jockeyAttacker"); if (jockey != -1) { Dismount(jockey); } int smoker = GetEntPropEnt(victim, Prop_Send, "m_tongueOwner"); if (smoker != -1) { L4D_Smoker_ReleaseVictim(victim, smoker); } } Action Timer_KnockdownRepeat(Handle timer, int userid) { int client = GetClientOfUserId(userid); if (!client || !IsClientInGame(client)) return Plugin_Stop; if (GetClientTeam(client) != 2) return Plugin_Stop; if (!IsPlayerAlive(client) || L4D_IsPlayerIncapacitated(client)) return Plugin_Stop; int queuedPummelAttacker = L4D2_GetQueuedPummelAttacker(client); if (queuedPummelAttacker == -1 || !L4D2_IsInQueuedPummel(queuedPummelAttacker)) { if (GetEntPropEnt(client, Prop_Send, "m_pummelAttacker") == -1) return Plugin_Stop; } KnockdownPlayer(client, KNOCKDOWN_CHARGER); return Plugin_Continue; } void KnockdownPlayer(int client, int reason) { SetEntProp(client, Prop_Send, "m_knockdownReason", reason); SetEntPropFloat(client, Prop_Send, "m_knockdownTimer", GetGameTime(), 0); } void SetPlayerSolid(int client, bool solid) { int flags = GetEntProp(client, Prop_Data, "m_usSolidFlags"); SetEntProp(client, Prop_Data, "m_usSolidFlags", solid ? (flags & ~FSOLID_NOT_SOLID) : (flags | FSOLID_NOT_SOLID)); } void Dismount(int client) { int flags = GetCommandFlags("dismount"); SetCommandFlags("dismount", flags & ~FCVAR_CHEAT); FakeClientCommand(client, "dismount"); SetCommandFlags("dismount", flags); } ConVar CreateConVarHook(const char[] name, const char[] defaultValue, const char[] description="", int flags=0, bool hasMin=false, float min=0.0, bool hasMax=false, float max=0.0, ConVarChanged callback) { ConVar cv = CreateConVar(name, defaultValue, description, flags, hasMin, min, hasMax, max); Call_StartFunction(INVALID_HANDLE, callback); Call_PushCell(cv); Call_PushNullString(); Call_PushNullString(); Call_Finish(); cv.AddChangeHook(callback); return cv; }
1
0.992446
1
0.992446
game-dev
MEDIA
0.906431
game-dev
0.991796
1
0.991796
luna-rs/luna
2,544
src/main/java/io/luna/game/event/impl/ObjectClickEvent.java
package io.luna.game.event.impl; import io.luna.game.model.Entity; import io.luna.game.model.mob.Player; import io.luna.game.model.object.GameObject; /** * An object-click based event. Not intended for interception. * * @author lare96 */ public class ObjectClickEvent extends PlayerEvent implements ControllableEvent, InteractableEvent { /** * An event sent when a player clicks an object's first index. * * @author lare96 */ public static final class ObjectFirstClickEvent extends ObjectClickEvent { /** * Creates a new {@link ObjectFirstClickEvent}. */ public ObjectFirstClickEvent(Player player, GameObject gameObject) { super(player, gameObject); } } /** * An event sent when a player clicks an object's second index. * * @author lare96 */ public static final class ObjectSecondClickEvent extends ObjectClickEvent { /** * Creates a new {@link ObjectSecondClickEvent}. */ public ObjectSecondClickEvent(Player player, GameObject gameObject) { super(player, gameObject); } } /** * An event sent when a player clicks an object's third index. * * @author lare96 */ public static final class ObjectThirdClickEvent extends ObjectClickEvent { /** * Creates a new {@link ObjectThirdClickEvent}. */ public ObjectThirdClickEvent(Player player, GameObject gameObject) { super(player, gameObject); } } /** * The clicked object. */ public GameObject gameObject; /** * Creates a new {@link ObjectClickEvent}. * * @param player The player. * @param gameObject The clicked object. */ private ObjectClickEvent(Player player, GameObject gameObject) { super(player); this.gameObject = gameObject; } @Override public Entity target() { return gameObject; } /** * @return The object identifier. */ public final int getId() { return gameObject.getId(); } /** * @return The object's x coordinate. */ public final int getX() { return gameObject.getPosition().getX(); } /** * @return The object's y coordinate. */ public final int getY() { return gameObject.getPosition().getY(); } /** * @return The clicked object. */ public GameObject getGameObject() { return gameObject; } }
1
0.717989
1
0.717989
game-dev
MEDIA
0.750369
game-dev
0.647313
1
0.647313
ProjectIgnis/CardScripts
1,481
official/c52639377.lua
--魔界闘士 バルムンク --Underworld Fighter Balmung local s,id=GetID() function s.initial_effect(c) --synchro summon Synchro.AddProcedure(c,nil,1,1,Synchro.NonTuner(nil),1,99) c:EnableReviveLimit() --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetCode(EVENT_TO_GRAVE) e1:SetCondition(s.spcon) e1:SetTarget(s.sptg) e1:SetOperation(s.spop) c:RegisterEffect(e1) end function s.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_EFFECT) and e:GetHandler():IsReason(REASON_DESTROY) end function s.spfilter(c,e,tp) return c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and s.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(s.spfilter,tp,LOCATION_GRAVE,0,1,e:GetHandler(),e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_GRAVE,0,1,1,e:GetHandler(),e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function s.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
1
0.97739
1
0.97739
game-dev
MEDIA
0.978727
game-dev
0.969439
1
0.969439
MickWest/sitrec
1,962
src/ConvertColorInputs.js
import {Color} from "three"; import {assert} from "./assert"; import {CNodeConstant} from "./nodes/CNode"; import {NodeMan} from "./Globals"; // convertColorInput is a helper function that converts a color input to a CNodeConstant export function convertColorInput(v, name, id="unnamedColorInput") { if (v[name] !== undefined) { let ob = v[name]; // if it's the name of a node, get the node // will transparently handle ob already being a node if (NodeMan.exists(ob)) { ob = NodeMan.get(ob); v[name] = ob; // force the color node back into the v parameter return; } // if it's not a CNodeConstant, or derived (like GNodeGUIColor) convert it to one if (!(ob instanceof CNodeConstant)) { var colorObject = ob; if (!(colorObject instanceof Color)) { if (typeof colorObject === "string" || typeof colorObject === "number") { // if it's a 9 character hex string (e.g. from a KML) like #FF00C050, // convert it to a 7 character hex string (#00C050, as three.js doesn't like the alpha channel // in hex strings if (typeof colorObject === "string" && colorObject.length === 9) { colorObject = "#" + colorObject.slice(3) } // hex string or number colorObject = new Color(colorObject) } else if (Array.isArray(colorObject)) { colorObject = new Color(colorObject[0], colorObject[1], colorObject[2]) } else { assert(0, "CNode color input not understood"); console.log("CNode color input not understood") } } v[name] = new CNodeConstant({id: id + "_" + name + "_colorInput", value: colorObject, pruneIfUnused: true}) } } }
1
0.531777
1
0.531777
game-dev
MEDIA
0.338103
game-dev
0.854773
1
0.854773
The-Legion-Preservation-Project/LegionCore-7.3.5
43,394
src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * 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/>. */ // Known bugs: // Gormok - Snobolled (creature at back) #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "trial_of_the_crusader.h" #include "Vehicle.h" #include "Player.h" #include "SpellScript.h" enum Yells { // Gormok EMOTE_SNOBOLLED = 0, // Acidmaw & Dreadscale EMOTE_ENRAGE = 0, // Icehowl EMOTE_TRAMPLE_START = 0, EMOTE_TRAMPLE_CRASH = 1, EMOTE_TRAMPLE_FAIL = 2 }; enum Equipment { EQUIP_MAIN = 50760, EQUIP_OFFHAND = 48040, EQUIP_RANGED = 47267, EQUIP_DONE = EQUIP_NO_CHANGE }; enum Model { MODEL_ACIDMAW_STATIONARY = 29815, MODEL_ACIDMAW_MOBILE = 29816, MODEL_DREADSCALE_STATIONARY = 26935, MODEL_DREADSCALE_MOBILE = 24564 }; enum BeastSummons { NPC_SNOBOLD_VASSAL = 34800, NPC_FIRE_BOMB = 34854, NPC_SLIME_POOL = 35176, MAX_SNOBOLDS = 4 }; enum BossSpells { //Gormok SPELL_IMPALE = 66331, SPELL_STAGGERING_STOMP = 67648, SPELL_RISING_ANGER = 66636, //Snobold SPELL_SNOBOLLED = 66406, SPELL_BATTER = 66408, SPELL_FIRE_BOMB = 66313, SPELL_FIRE_BOMB_1 = 66317, SPELL_FIRE_BOMB_DOT = 66318, SPELL_HEAD_CRACK = 66407, //Acidmaw & Dreadscale SPELL_ACID_SPIT = 66880, SPELL_PARALYTIC_SPRAY = 66901, SPELL_ACID_SPEW = 66819, SPELL_PARALYTIC_BITE = 66824, SPELL_SWEEP_0 = 66794, SUMMON_SLIME_POOL = 66883, SPELL_FIRE_SPIT = 66796, SPELL_MOLTEN_SPEW = 66821, SPELL_BURNING_BITE = 66879, SPELL_BURNING_SPRAY = 66902, SPELL_SWEEP_1 = 67646, SPELL_EMERGE_0 = 66947, SPELL_SUBMERGE_0 = 66948, SPELL_ENRAGE = 68335, SPELL_SLIME_POOL_EFFECT = 66882, //In 60s it diameter grows from 10y to 40y (r=r+0.25 per second) //Icehowl SPELL_FEROCIOUS_BUTT = 66770, SPELL_MASSIVE_CRASH = 66683, SPELL_WHIRL = 67345, SPELL_ARCTIC_BREATH = 66689, SPELL_TRAMPLE = 66734, SPELL_FROTHING_RAGE = 66759, SPELL_STAGGERED_DAZE = 66758 }; enum MyActions { ACTION_ENABLE_FIRE_BOMB = 1, ACTION_DISABLE_FIRE_BOMB = 2 }; enum Events { // Gormok EVENT_IMPALE = 1, EVENT_STAGGERING_STOMP = 2, EVENT_THROW = 3, // Snobold EVENT_FIRE_BOMB = 4, EVENT_BATTER = 5, EVENT_HEAD_CRACK = 6, // Acidmaw & Dreadscale EVENT_BITE = 7, EVENT_SPEW = 8, EVENT_SLIME_POOL = 9, EVENT_SPIT = 10, EVENT_SPRAY = 11, EVENT_SWEEP = 12, EVENT_SUBMERGE = 13, EVENT_EMERGE = 14, EVENT_SUMMON_ACIDMAW = 15, // Icehowl EVENT_FEROCIOUS_BUTT = 16, EVENT_MASSIVE_CRASH = 17, EVENT_WHIRL = 18, EVENT_ARCTIC_BREATH = 19, EVENT_TRAMPLE = 20 }; enum Phases { PHASE_MOBILE = 1, PHASE_STATIONARY = 2, PHASE_SUBMERGED = 3 }; class boss_gormok : public CreatureScript { public: boss_gormok() : CreatureScript("boss_gormok") { } struct boss_gormokAI : public BossAI { boss_gormokAI(Creature* creature) : BossAI(creature, BOSS_BEASTS) { } void Reset() override { events.ScheduleEvent(EVENT_IMPALE, urand(8*IN_MILLISECONDS, 10*IN_MILLISECONDS)); events.ScheduleEvent(EVENT_STAGGERING_STOMP, 15*IN_MILLISECONDS); events.ScheduleEvent(EVENT_THROW, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS)); summons.DespawnAll(); } void EnterEvadeMode() override { instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); ScriptedAI::EnterEvadeMode(); } void MovementInform(uint32 type, uint32 pointId) override { if (type != POINT_MOTION_TYPE) return; switch (pointId) { case 0: instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_AGGRESSIVE); me->SetInCombatWithZone(); break; default: break; } } void JustDied(Unit* /*killer*/) override { instance->SetData(TYPE_NORTHREND_BEASTS, GORMOK_DONE); } void JustReachedHome() override { instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); instance->SetData(TYPE_NORTHREND_BEASTS, FAIL); me->DespawnOrUnsummon(); } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); me->SetInCombatWithZone(); instance->SetData(TYPE_NORTHREND_BEASTS, GORMOK_IN_PROGRESS); for (uint8 i = 0; i < MAX_SNOBOLDS; i++) { if (Creature* pSnobold = DoSpawnCreature(NPC_SNOBOLD_VASSAL, 0, 0, 0, 0, TEMPSUMMON_CORPSE_DESPAWN, 0)) { pSnobold->EnterVehicle(me, i); pSnobold->SetInCombatWithZone(); pSnobold->AI()->DoAction(ACTION_ENABLE_FIRE_BOMB); } } } void DamageTaken(Unit* /*who*/, uint32& damage, DamageEffectType dmgType) override { // despawn the remaining passengers on death if (damage >= me->GetHealth()) for (uint8 i = 0; i < MAX_SNOBOLDS; ++i) if (Unit* pSnobold = me->GetVehicleKit()->GetPassenger(i)) pSnobold->ToCreature()->DespawnOrUnsummon(); } 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_IMPALE: DoCastVictim(SPELL_IMPALE); events.ScheduleEvent(EVENT_IMPALE, urand(8*IN_MILLISECONDS, 10*IN_MILLISECONDS)); return; case EVENT_STAGGERING_STOMP: DoCastVictim(SPELL_STAGGERING_STOMP); events.ScheduleEvent(EVENT_STAGGERING_STOMP, 15*IN_MILLISECONDS); return; case EVENT_THROW: for (uint8 i = 0; i < MAX_SNOBOLDS; ++i) { if (Unit* pSnobold = me->GetVehicleKit()->GetPassenger(i)) { pSnobold->ExitVehicle(); pSnobold->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); pSnobold->ToCreature()->SetReactState(REACT_AGGRESSIVE); pSnobold->ToCreature()->AI()->DoAction(ACTION_DISABLE_FIRE_BOMB); pSnobold->CastSpell(me, SPELL_RISING_ANGER, true); Talk(EMOTE_SNOBOLLED); break; } } events.ScheduleEvent(EVENT_THROW, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS)); return; default: return; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new boss_gormokAI(creature); } }; class npc_snobold_vassal : public CreatureScript { public: npc_snobold_vassal() : CreatureScript("npc_snobold_vassal") { } struct npc_snobold_vassalAI : public ScriptedAI { npc_snobold_vassalAI(Creature* creature) : ScriptedAI(creature) { _targetGUID.Clear(); _targetDied = false; _instance = creature->GetInstanceScript(); _instance->SetData(DATA_SNOBOLD_COUNT, INCREASE); } void Reset() override { _events.ScheduleEvent(EVENT_BATTER, 5*IN_MILLISECONDS); _events.ScheduleEvent(EVENT_HEAD_CRACK, 25*IN_MILLISECONDS); _targetGUID.Clear(); _targetDied = false; //Workaround for Snobold me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); } void EnterEvadeMode() override { ScriptedAI::EnterEvadeMode(); } void EnterCombat(Unit* who) override { _targetGUID = who->GetGUID(); me->TauntApply(who); DoCast(who, SPELL_SNOBOLLED); } void DamageTaken(Unit* pDoneBy, uint32 &uiDamage, DamageEffectType dmgType) override { if (pDoneBy->GetGUID() == _targetGUID) uiDamage = 0; } void MovementInform(uint32 type, uint32 pointId) override { if (type != POINT_MOTION_TYPE) return; switch (pointId) { case 0: if (_targetDied) me->DespawnOrUnsummon(); break; default: break; } } void JustDied(Unit* /*killer*/) override { if (Unit* target = ObjectAccessor::GetPlayer(*me, _targetGUID)) if (target->IsAlive()) target->RemoveAurasDueToSpell(SPELL_SNOBOLLED); _instance->SetData(DATA_SNOBOLD_COUNT, DECREASE); } void DoAction(const int32 action) override { switch (action) { case ACTION_ENABLE_FIRE_BOMB: _events.ScheduleEvent(EVENT_FIRE_BOMB, urand(5*IN_MILLISECONDS, 30*IN_MILLISECONDS)); break; case ACTION_DISABLE_FIRE_BOMB: _events.CancelEvent(EVENT_FIRE_BOMB); break; default: break; } } void UpdateAI(uint32 diff) override { if (!UpdateVictim() || _targetDied) return; if (Unit* target = ObjectAccessor::GetPlayer(*me, _targetGUID)) { if (!target->IsAlive()) { Unit* gormok = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_GORMOK)); if (gormok && gormok->IsAlive()) { SetCombatMovement(false); _targetDied = true; // looping through Gormoks seats for (uint8 i = 0; i < MAX_SNOBOLDS; i++) { if (!gormok->GetVehicleKit()->GetPassenger(i)) { me->EnterVehicle(gormok, i); DoAction(ACTION_ENABLE_FIRE_BOMB); break; } } } else if (Unit* target2 = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true)) { _targetGUID = target2->GetGUID(); me->GetMotionMaster()->MoveJump(target2->GetPositionX(), target2->GetPositionY(), target2->GetPositionZ(), 15.0f, 15.0f, EVENT_JUMP); } } } _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_FIRE_BOMB: if (me->GetVehicleBase()) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, -me->GetVehicleBase()->GetCombatReach(), true)) me->CastSpell(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), SPELL_FIRE_BOMB, true); _events.ScheduleEvent(EVENT_FIRE_BOMB, 20*IN_MILLISECONDS); return; case EVENT_HEAD_CRACK: // commented out while SPELL_SNOBOLLED gets fixed //if (Unit* target = ObjectAccessor::GetPlayer(*me, m_uiTargetGUID)) DoCastVictim(SPELL_HEAD_CRACK); _events.ScheduleEvent(EVENT_HEAD_CRACK, 30*IN_MILLISECONDS); return; case EVENT_BATTER: // commented out while SPELL_SNOBOLLED gets fixed //if (Unit* target = ObjectAccessor::GetPlayer(*me, m_uiTargetGUID)) DoCastVictim(SPELL_BATTER); _events.ScheduleEvent(EVENT_BATTER, 10*IN_MILLISECONDS); return; default: return; } } // do melee attack only when not on Gormoks back if (!me->GetVehicleBase()) DoMeleeAttackIfReady(); } private: EventMap _events; InstanceScript* _instance; ObjectGuid _targetGUID; bool _targetDied; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_snobold_vassalAI(creature); } }; class npc_firebomb : public CreatureScript { public: npc_firebomb() : CreatureScript("npc_firebomb") { } struct npc_firebombAI : public ScriptedAI { npc_firebombAI(Creature* creature) : ScriptedAI(creature) { _instance = creature->GetInstanceScript(); } void Reset() override { DoCast(me, SPELL_FIRE_BOMB_DOT, true); SetCombatMovement(false); me->SetReactState(REACT_PASSIVE); me->SetDisplayId(me->GetCreatureTemplate()->Modelid[1]); } void UpdateAI(uint32 /*diff*/) override { if (_instance->GetData(TYPE_NORTHREND_BEASTS) != GORMOK_IN_PROGRESS) me->DespawnOrUnsummon(); } private: InstanceScript* _instance; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_firebombAI(creature); } }; struct boss_jormungarAI : public BossAI { boss_jormungarAI(Creature* creature) : BossAI(creature, BOSS_BEASTS) { OtherWormEntry = 0; ModelStationary = 0; ModelMobile = 0; BiteSpell = 0; SpewSpell = 0; SpitSpell = 0; SpraySpell = 0; Phase = PHASE_MOBILE; Enraged = false; WasMobile = false; } void Reset() override { Enraged = false; events.ScheduleEvent(EVENT_SPIT, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); events.ScheduleEvent(EVENT_SPRAY, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); events.ScheduleEvent(EVENT_SWEEP, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); events.ScheduleEvent(EVENT_BITE, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_MOBILE); events.ScheduleEvent(EVENT_SPEW, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_MOBILE); events.ScheduleEvent(EVENT_SLIME_POOL, 15*IN_MILLISECONDS, 0, PHASE_MOBILE); } void JustDied(Unit* /*killer*/) override { if (Creature* otherWorm = ObjectAccessor::GetCreature(*me, instance->GetGuidData(OtherWormEntry))) { if (!otherWorm->IsAlive()) { instance->SetData(TYPE_NORTHREND_BEASTS, SNAKES_DONE); me->DespawnOrUnsummon(); otherWorm->DespawnOrUnsummon(); } else instance->SetData(TYPE_NORTHREND_BEASTS, SNAKES_SPECIAL); } } void JustReachedHome() override { // prevent losing 2 attempts at once on heroics if (instance->GetData(TYPE_NORTHREND_BEASTS) != FAIL) instance->SetData(TYPE_NORTHREND_BEASTS, FAIL); me->DespawnOrUnsummon(); } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) instance->SetData(DATA_TRIBUTE_TO_IMMORTALITY_ELIGIBLE, 0); } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); me->SetInCombatWithZone(); instance->SetData(TYPE_NORTHREND_BEASTS, SNAKES_IN_PROGRESS); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; if (!Enraged && instance->GetData(TYPE_NORTHREND_BEASTS) == SNAKES_SPECIAL) { me->RemoveAurasDueToSpell(SPELL_SUBMERGE_0); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); DoCast(SPELL_ENRAGE); Enraged = true; Talk(EMOTE_ENRAGE); } events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_EMERGE: Emerge(); return; case EVENT_SUBMERGE: Submerge(); return; case EVENT_BITE: DoCastVictim(BiteSpell); events.ScheduleEvent(EVENT_BITE, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_MOBILE); return; case EVENT_SPEW: DoCastAOE(SpewSpell); events.ScheduleEvent(EVENT_SPEW, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_MOBILE); return; case EVENT_SLIME_POOL: DoCast(me, SUMMON_SLIME_POOL); events.ScheduleEvent(EVENT_SLIME_POOL, 30*IN_MILLISECONDS, 0, PHASE_MOBILE); return; case EVENT_SUMMON_ACIDMAW: if (Creature* acidmaw = me->SummonCreature(NPC_ACIDMAW, ToCCommonLoc[9].GetPositionX(), ToCCommonLoc[9].GetPositionY(), ToCCommonLoc[9].GetPositionZ(), 5, TEMPSUMMON_MANUAL_DESPAWN)) { acidmaw->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); acidmaw->SetReactState(REACT_AGGRESSIVE); acidmaw->SetInCombatWithZone(); acidmaw->CastSpell(acidmaw, SPELL_EMERGE_0); } return; case EVENT_SPRAY: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true)) DoCast(target, SpraySpell); events.ScheduleEvent(EVENT_SPRAY, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); return; case EVENT_SWEEP: DoCastAOE(SPELL_SWEEP_0); events.ScheduleEvent(EVENT_SWEEP, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); return; default: return; } } if (events.IsInPhase(PHASE_MOBILE)) DoMeleeAttackIfReady(); if (events.IsInPhase(PHASE_STATIONARY)) DoSpellAttackIfReady(SpitSpell); } void Submerge() { DoCast(me, SPELL_SUBMERGE_0); me->RemoveAurasDueToSpell(SPELL_EMERGE_0); me->SetInCombatWithZone(); events.SetPhase(PHASE_SUBMERGED); events.ScheduleEvent(EVENT_EMERGE, 5*IN_MILLISECONDS, 0, PHASE_SUBMERGED); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->GetMotionMaster()->MovePoint(0, ToCCommonLoc[1].GetPositionX()+ frand(-40.0f, 40.0f), ToCCommonLoc[1].GetPositionY() + frand(-40.0f, 40.0f), ToCCommonLoc[1].GetPositionZ(), false); WasMobile = !WasMobile; } void Emerge() { DoCast(me, SPELL_EMERGE_0); me->SetDisplayId(ModelMobile); me->RemoveAurasDueToSpell(SPELL_SUBMERGE_0); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->GetMotionMaster()->Clear(); // if the worm was mobile before submerging, make him stationary now if (WasMobile) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); SetCombatMovement(false); me->SetDisplayId(ModelStationary); events.SetPhase(PHASE_STATIONARY); events.ScheduleEvent(EVENT_SUBMERGE, 45*IN_MILLISECONDS, 0, PHASE_STATIONARY); events.ScheduleEvent(EVENT_SPIT, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); events.ScheduleEvent(EVENT_SPRAY, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); events.ScheduleEvent(EVENT_SWEEP, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); } else { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); SetCombatMovement(true); me->GetMotionMaster()->MoveChase(me->getVictim()); me->SetDisplayId(ModelMobile); events.SetPhase(PHASE_MOBILE); events.ScheduleEvent(EVENT_SUBMERGE, 45*IN_MILLISECONDS, 0, PHASE_MOBILE); events.ScheduleEvent(EVENT_BITE, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_MOBILE); events.ScheduleEvent(EVENT_SPEW, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_MOBILE); events.ScheduleEvent(EVENT_SLIME_POOL, 15*IN_MILLISECONDS, 0, PHASE_MOBILE); } } protected: uint32 OtherWormEntry; uint32 ModelStationary; uint32 ModelMobile; uint32 BiteSpell; uint32 SpewSpell; uint32 SpitSpell; uint32 SpraySpell; Phases Phase; bool Enraged; bool WasMobile; }; class boss_acidmaw : public CreatureScript { public: boss_acidmaw() : CreatureScript("boss_acidmaw") { } struct boss_acidmawAI : public boss_jormungarAI { boss_acidmawAI(Creature* creature) : boss_jormungarAI(creature) { } void Reset() override { boss_jormungarAI::Reset(); BiteSpell = SPELL_PARALYTIC_BITE; SpewSpell = SPELL_ACID_SPEW; SpitSpell = SPELL_ACID_SPIT; SpraySpell = SPELL_PARALYTIC_SPRAY; ModelStationary = MODEL_ACIDMAW_STATIONARY; ModelMobile = MODEL_ACIDMAW_MOBILE; OtherWormEntry = NPC_DREADSCALE; WasMobile = true; Emerge(); } }; CreatureAI* GetAI(Creature* creature) const override { return new boss_acidmawAI (creature); } }; class boss_dreadscale : public CreatureScript { public: boss_dreadscale() : CreatureScript("boss_dreadscale") { } struct boss_dreadscaleAI : public boss_jormungarAI { boss_dreadscaleAI(Creature* creature) : boss_jormungarAI(creature) { } void Reset() override { boss_jormungarAI::Reset(); BiteSpell = SPELL_BURNING_BITE; SpewSpell = SPELL_MOLTEN_SPEW; SpitSpell = SPELL_FIRE_SPIT; SpraySpell = SPELL_BURNING_SPRAY; ModelStationary = MODEL_DREADSCALE_STATIONARY; ModelMobile = MODEL_DREADSCALE_MOBILE; OtherWormEntry = NPC_ACIDMAW; events.SetPhase(PHASE_MOBILE); events.ScheduleEvent(EVENT_SUMMON_ACIDMAW, 3*IN_MILLISECONDS); events.ScheduleEvent(EVENT_SUBMERGE, 45*IN_MILLISECONDS, 0, PHASE_MOBILE); WasMobile = false; } void MovementInform(uint32 type, uint32 pointId) override { if (type != POINT_MOTION_TYPE) return; switch (pointId) { case 0: instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_AGGRESSIVE); me->SetInCombatWithZone(); break; default: break; } } void EnterEvadeMode() override { instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); boss_jormungarAI::EnterEvadeMode(); } void JustReachedHome() override { instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); boss_jormungarAI::JustReachedHome(); } }; CreatureAI* GetAI(Creature* creature) const override { return new boss_dreadscaleAI(creature); } }; class npc_slime_pool : public CreatureScript { public: npc_slime_pool() : CreatureScript("npc_slime_pool") { } struct npc_slime_poolAI : public ScriptedAI { npc_slime_poolAI(Creature* creature) : ScriptedAI(creature) { Initialize(); _instance = creature->GetInstanceScript(); } void Initialize() { _cast = false; } void Reset() override { Initialize(); me->SetReactState(REACT_PASSIVE); } void UpdateAI(uint32 /*diff*/) override { if (!_cast) { _cast = true; DoCast(me, SPELL_SLIME_POOL_EFFECT); } if (_instance->GetData(TYPE_NORTHREND_BEASTS) != SNAKES_IN_PROGRESS && _instance->GetData(TYPE_NORTHREND_BEASTS) != SNAKES_SPECIAL) me->DespawnOrUnsummon(); } private: InstanceScript* _instance; bool _cast; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_slime_poolAI(creature); } }; class spell_gormok_fire_bomb : public SpellScriptLoader { public: spell_gormok_fire_bomb() : SpellScriptLoader("spell_gormok_fire_bomb") { } class spell_gormok_fire_bomb_SpellScript : public SpellScript { PrepareSpellScript(spell_gormok_fire_bomb_SpellScript); void TriggerFireBomb(SpellEffIndex /*effIndex*/) { if (const WorldLocation* pos = GetExplTargetDest()) { if (Unit* caster = GetCaster()) caster->SummonCreature(NPC_FIRE_BOMB, pos->GetPositionX(), pos->GetPositionY(), pos->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 30*IN_MILLISECONDS); } } void Register() override { OnEffectHit += SpellEffectFn(spell_gormok_fire_bomb_SpellScript::TriggerFireBomb, EFFECT_0, SPELL_EFFECT_TRIGGER_MISSILE); } }; SpellScript* GetSpellScript() const override { return new spell_gormok_fire_bomb_SpellScript(); } }; class boss_icehowl : public CreatureScript { public: boss_icehowl() : CreatureScript("boss_icehowl") { } struct boss_icehowlAI : public BossAI { boss_icehowlAI(Creature* creature) : BossAI(creature, BOSS_BEASTS) { Initialize(); } void Initialize() { _movementStarted = false; _movementFinish = false; _trampleCast = false; _trampleTargetGUID.Clear(); _trampleTargetX = 0; _trampleTargetY = 0; _trampleTargetZ = 0; _stage = 0; } void Reset() override { events.ScheduleEvent(EVENT_FEROCIOUS_BUTT, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS)); events.ScheduleEvent(EVENT_ARCTIC_BREATH, urand(15*IN_MILLISECONDS, 25*IN_MILLISECONDS)); events.ScheduleEvent(EVENT_WHIRL, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS)); events.ScheduleEvent(EVENT_MASSIVE_CRASH, 30*IN_MILLISECONDS); Initialize(); } void JustDied(Unit* /*killer*/) override { _JustDied(); instance->SetData(TYPE_NORTHREND_BEASTS, ICEHOWL_DONE); } void MovementInform(uint32 type, uint32 pointId) override { if (type != POINT_MOTION_TYPE && type != EFFECT_MOTION_TYPE) return; switch (pointId) { case 0: if (_stage != 0) { if (me->GetDistance2d(ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY()) < 6.0f) // Middle of the room _stage = 1; else { // Landed from Hop backwards (start trample) if (ObjectAccessor::GetPlayer(*me, _trampleTargetGUID)) _stage = 4; else _stage = 6; } } break; case 1: // Finish trample _movementFinish = true; break; case 2: instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_AGGRESSIVE); me->SetInCombatWithZone(); break; default: break; } } void EnterEvadeMode() override { instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); ScriptedAI::EnterEvadeMode(); } void JustReachedHome() override { instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); instance->SetData(TYPE_NORTHREND_BEASTS, FAIL); me->DespawnOrUnsummon(); } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) { instance->SetData(DATA_TRIBUTE_TO_IMMORTALITY_ELIGIBLE, 0); } } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); instance->SetData(TYPE_NORTHREND_BEASTS, ICEHOWL_IN_PROGRESS); } void SpellHitTarget(Unit* target, SpellInfo const* spell) override { if (spell->Id == SPELL_TRAMPLE && target->GetTypeId() == TYPEID_PLAYER) { if (!_trampleCast) { DoCast(me, SPELL_FROTHING_RAGE, true); _trampleCast = true; } } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_stage) { case 0: { while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FEROCIOUS_BUTT: DoCastVictim(SPELL_FEROCIOUS_BUTT); events.ScheduleEvent(EVENT_FEROCIOUS_BUTT, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS)); return; case EVENT_ARCTIC_BREATH: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true)) DoCast(target, SPELL_ARCTIC_BREATH); return; case EVENT_WHIRL: DoCastAOE(SPELL_WHIRL); events.ScheduleEvent(EVENT_WHIRL, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS)); return; case EVENT_MASSIVE_CRASH: me->GetMotionMaster()->MoveJump(ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY(), ToCCommonLoc[1].GetPositionZ(), 20.0f, 20.0f, 0); // 1: Middle of the room SetCombatMovement(false); me->AttackStop(); _stage = 7; //Invalid (Do nothing more than move) return; default: break; } } DoMeleeAttackIfReady(); break; } case 1: DoCastAOE(SPELL_MASSIVE_CRASH); me->StopMoving(); me->AttackStop(); _stage = 2; break; case 2: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true)) { me->StopMoving(); me->AttackStop(); _trampleTargetGUID = target->GetGUID(); me->SetTarget(_trampleTargetGUID); _trampleCast = false; SetCombatMovement(false); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveIdle(); events.ScheduleEvent(EVENT_TRAMPLE, 4*IN_MILLISECONDS); _stage = 3; } else _stage = 6; break; case 3: while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_TRAMPLE: { if (Unit* target = ObjectAccessor::GetPlayer(*me, _trampleTargetGUID)) { me->StopMoving(); me->AttackStop(); _trampleCast = false; _movementStarted = true; _trampleTargetX = target->GetPositionX(); _trampleTargetY = target->GetPositionY(); _trampleTargetZ = target->GetPositionZ(); // 2: Hop Backwards me->GetMotionMaster()->MoveJump(2*me->GetPositionX() - _trampleTargetX, 2*me->GetPositionY() - _trampleTargetY, me->GetPositionZ(), 30.0f, 20.0f, 0); _stage = 7; //Invalid (Do nothing more than move) } else _stage = 6; break; } default: break; } } break; case 4: me->StopMoving(); me->AttackStop(); if (Player* target = ObjectAccessor::GetPlayer(*me, _trampleTargetGUID)) Talk(EMOTE_TRAMPLE_START, target->GetGUID()); me->GetMotionMaster()->MoveCharge(_trampleTargetX, _trampleTargetY, _trampleTargetZ, 42, 1); me->SetTarget(ObjectGuid::Empty); _stage = 5; break; case 5: if (_movementFinish) { DoCastAOE(SPELL_TRAMPLE); _movementFinish = false; _stage = 6; return; } if (events.ExecuteEvent() == EVENT_TRAMPLE) { Map::PlayerList const &lPlayers = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr) { if (Unit* player = itr->getSource()) { if (player->IsAlive() && player->IsWithinDistInMap(me, 6.0f)) { DoCastAOE(SPELL_TRAMPLE); events.ScheduleEvent(EVENT_TRAMPLE, 4*IN_MILLISECONDS); break; } } } } break; case 6: if (!_trampleCast) { DoCast(me, SPELL_STAGGERED_DAZE); Talk(EMOTE_TRAMPLE_CRASH); } else { DoCast(me, SPELL_FROTHING_RAGE, true); Talk(EMOTE_TRAMPLE_FAIL); } _movementStarted = false; me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL); SetCombatMovement(true); me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveChase(me->getVictim()); AttackStart(me->getVictim()); events.ScheduleEvent(EVENT_MASSIVE_CRASH, 40*IN_MILLISECONDS); events.ScheduleEvent(EVENT_ARCTIC_BREATH, urand(15*IN_MILLISECONDS, 25*IN_MILLISECONDS)); _stage = 0; break; default: break; } } private: float _trampleTargetX, _trampleTargetY, _trampleTargetZ; ObjectGuid _trampleTargetGUID; bool _movementStarted; bool _movementFinish; bool _trampleCast; uint8 _stage; }; CreatureAI* GetAI(Creature* creature) const override { return new boss_icehowlAI(creature); } }; void AddSC_boss_northrend_beasts() { new boss_gormok(); new npc_snobold_vassal(); new npc_firebomb(); new spell_gormok_fire_bomb(); new boss_acidmaw(); new boss_dreadscale(); new npc_slime_pool(); new boss_icehowl(); }
1
0.976692
1
0.976692
game-dev
MEDIA
0.996394
game-dev
0.952274
1
0.952274
ouxianghui/janus-client
31,329
3rd/webrtc/include/third_party/protobuf/src/google/protobuf/arena.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This file defines an Arena allocator for better allocation performance. #ifndef GOOGLE_PROTOBUF_ARENA_H__ #define GOOGLE_PROTOBUF_ARENA_H__ #include <limits> #include <type_traits> #include <utility> #ifdef max #undef max // Visual Studio defines this macro #endif #if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS // Work around bugs in MSVC <typeinfo> header when _HAS_EXCEPTIONS=0. #include <exception> #include <typeinfo> namespace std { using type_info = ::type_info; } #else #include <typeinfo> #endif #include <type_traits> #include <google/protobuf/arena_impl.h> #include <google/protobuf/port.h> #include <google/protobuf/port_def.inc> #ifdef SWIG #error "You cannot SWIG proto headers" #endif namespace google { namespace protobuf { struct ArenaOptions; // defined below } // namespace protobuf } // namespace google namespace google { namespace protobuf { class Arena; // defined below class Message; // defined in message.h class MessageLite; template <typename Key, typename T> class Map; namespace arena_metrics { void EnableArenaMetrics(ArenaOptions* options); } // namespace arena_metrics namespace internal { struct ArenaStringPtr; // defined in arenastring.h class LazyField; // defined in lazy_field.h class EpsCopyInputStream; // defined in parse_context.h template <typename Type> class GenericTypeHandler; // defined in repeated_field.h // Templated cleanup methods. template <typename T> void arena_destruct_object(void* object) { reinterpret_cast<T*>(object)->~T(); } template <typename T> void arena_delete_object(void* object) { delete reinterpret_cast<T*>(object); } inline void arena_free(void* object, size_t size) { #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) ::operator delete(object, size); #else (void)size; ::operator delete(object); #endif } } // namespace internal // ArenaOptions provides optional additional parameters to arena construction // that control its block-allocation behavior. struct ArenaOptions { // This defines the size of the first block requested from the system malloc. // Subsequent block sizes will increase in a geometric series up to a maximum. size_t start_block_size; // This defines the maximum block size requested from system malloc (unless an // individual arena allocation request occurs with a size larger than this // maximum). Requested block sizes increase up to this value, then remain // here. size_t max_block_size; // An initial block of memory for the arena to use, or NULL for none. If // provided, the block must live at least as long as the arena itself. The // creator of the Arena retains ownership of the block after the Arena is // destroyed. char* initial_block; // The size of the initial block, if provided. size_t initial_block_size; // A function pointer to an alloc method that returns memory blocks of size // requested. By default, it contains a ptr to the malloc function. // // NOTE: block_alloc and dealloc functions are expected to behave like // malloc and free, including Asan poisoning. void* (*block_alloc)(size_t); // A function pointer to a dealloc method that takes ownership of the blocks // from the arena. By default, it contains a ptr to a wrapper function that // calls free. void (*block_dealloc)(void*, size_t); ArenaOptions() : start_block_size(kDefaultStartBlockSize), max_block_size(kDefaultMaxBlockSize), initial_block(NULL), initial_block_size(0), block_alloc(&::operator new), block_dealloc(&internal::arena_free), on_arena_init(NULL), on_arena_reset(NULL), on_arena_destruction(NULL), on_arena_allocation(NULL) {} private: // Hooks for adding external functionality such as user-specific metrics // collection, specific debugging abilities, etc. // Init hook (if set) will always be called at Arena init time. Init hook may // return a pointer to a cookie to be stored in the arena. Reset and // destruction hooks will then be called with the same cookie pointer. This // allows us to save an external object per arena instance and use it on the // other hooks (Note: If init hook returns NULL, the other hooks will NOT be // called on this arena instance). // on_arena_reset and on_arena_destruction also receive the space used in the // arena just before the reset. void* (*on_arena_init)(Arena* arena); void (*on_arena_reset)(Arena* arena, void* cookie, uint64 space_used); void (*on_arena_destruction)(Arena* arena, void* cookie, uint64 space_used); // type_info is promised to be static - its lifetime extends to // match program's lifetime (It is given by typeid operator). // Note: typeid(void) will be passed as allocated_type every time we // intentionally want to avoid monitoring an allocation. (i.e. internal // allocations for managing the arena) void (*on_arena_allocation)(const std::type_info* allocated_type, uint64 alloc_size, void* cookie); // Constants define default starting block size and max block size for // arena allocator behavior -- see descriptions above. static const size_t kDefaultStartBlockSize = 256; static const size_t kDefaultMaxBlockSize = 8192; friend void arena_metrics::EnableArenaMetrics(ArenaOptions*); friend class Arena; friend class ArenaOptionsTestFriend; }; // Support for non-RTTI environments. (The metrics hooks API uses type // information.) #if PROTOBUF_RTTI #define RTTI_TYPE_ID(type) (&typeid(type)) #else #define RTTI_TYPE_ID(type) (NULL) #endif // Arena allocator. Arena allocation replaces ordinary (heap-based) allocation // with new/delete, and improves performance by aggregating allocations into // larger blocks and freeing allocations all at once. Protocol messages are // allocated on an arena by using Arena::CreateMessage<T>(Arena*), below, and // are automatically freed when the arena is destroyed. // // This is a thread-safe implementation: multiple threads may allocate from the // arena concurrently. Destruction is not thread-safe and the destructing // thread must synchronize with users of the arena first. // // An arena provides two allocation interfaces: CreateMessage<T>, which works // for arena-enabled proto2 message types as well as other types that satisfy // the appropriate protocol (described below), and Create<T>, which works for // any arbitrary type T. CreateMessage<T> is better when the type T supports it, // because this interface (i) passes the arena pointer to the created object so // that its sub-objects and internal allocations can use the arena too, and (ii) // elides the object's destructor call when possible. Create<T> does not place // any special requirements on the type T, and will invoke the object's // destructor when the arena is destroyed. // // The arena message allocation protocol, required by // CreateMessage<T>(Arena* arena, Args&&... args), is as follows: // // - The type T must have (at least) two constructors: a constructor callable // with `args` (without `arena`), called when a T is allocated on the heap; // and a constructor callable with `Arena* arena, Args&&... args`, called when // a T is allocated on an arena. If the second constructor is called with a // NULL arena pointer, it must be equivalent to invoking the first // (`args`-only) constructor. // // - The type T must have a particular type trait: a nested type // |InternalArenaConstructable_|. This is usually a typedef to |void|. If no // such type trait exists, then the instantiation CreateMessage<T> will fail // to compile. // // - The type T *may* have the type trait |DestructorSkippable_|. If this type // trait is present in the type, then its destructor will not be called if and // only if it was passed a non-NULL arena pointer. If this type trait is not // present on the type, then its destructor is always called when the // containing arena is destroyed. // // This protocol is implemented by all arena-enabled proto2 message classes as // well as protobuf container types like RepeatedPtrField and Map. The protocol // is internal to protobuf and is not guaranteed to be stable. Non-proto types // should not rely on this protocol. class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final { public: // Arena constructor taking custom options. See ArenaOptions below for // descriptions of the options available. explicit Arena(const ArenaOptions& options) : impl_(options) { Init(options); } // Block overhead. Use this as a guide for how much to over-allocate the // initial block if you want an allocation of size N to fit inside it. // // WARNING: if you allocate multiple objects, it is difficult to guarantee // that a series of allocations will fit in the initial block, especially if // Arena changes its alignment guarantees in the future! static const size_t kBlockOverhead = internal::ArenaImpl::kBlockHeaderSize + internal::ArenaImpl::kSerialArenaSize; // Default constructor with sensible default options, tuned for average // use-cases. Arena() : impl_(ArenaOptions()) { Init(ArenaOptions()); } ~Arena() { if (hooks_cookie_) { CallDestructorHooks(); } } void Init(const ArenaOptions& options) { on_arena_allocation_ = options.on_arena_allocation; on_arena_reset_ = options.on_arena_reset; on_arena_destruction_ = options.on_arena_destruction; // Call the initialization hook if (options.on_arena_init != NULL) { hooks_cookie_ = options.on_arena_init(this); } else { hooks_cookie_ = NULL; } } // API to create proto2 message objects on the arena. If the arena passed in // is NULL, then a heap allocated object is returned. Type T must be a message // defined in a .proto file with cc_enable_arenas set to true, otherwise a // compilation error will occur. // // RepeatedField and RepeatedPtrField may also be instantiated directly on an // arena with this method. // // This function also accepts any type T that satisfies the arena message // allocation protocol, documented above. template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) { static_assert( InternalHelper<T>::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal() // because protobuf generated classes specialize CreateMaybeMessage() and we // need to use that specialization for code size reasons. return Arena::CreateMaybeMessage<T>(arena, std::forward<Args>(args)...); } // API to create any objects on the arena. Note that only the object will // be created on the arena; the underlying ptrs (in case of a proto2 message) // will be still heap allocated. Proto messages should usually be allocated // with CreateMessage<T>() instead. // // Note that even if T satisfies the arena message construction protocol // (InternalArenaConstructable_ trait and optional DestructorSkippable_ // trait), as described above, this function does not follow the protocol; // instead, it treats T as a black-box type, just as if it did not have these // traits. Specifically, T's constructor arguments will always be only those // passed to Create<T>() -- no additional arena pointer is implicitly added. // Furthermore, the destructor will always be called at arena destruction time // (unless the destructor is trivial). Hence, from T's point of view, it is as // if the object were allocated on the heap (except that the underlying memory // is obtained from the arena). template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* Create(Arena* arena, Args&&... args) { return CreateNoMessage<T>(arena, is_arena_constructable<T>(), std::forward<Args>(args)...); } // Create an array of object type T on the arena *without* invoking the // constructor of T. If `arena` is null, then the return value should be freed // with `delete[] x;` (or `::operator delete[](x);`). // To ensure safe uses, this function checks at compile time // (when compiled as C++11) that T is trivially default-constructible and // trivially destructible. template <typename T> PROTOBUF_ALWAYS_INLINE static T* CreateArray(Arena* arena, size_t num_elements) { static_assert(std::is_pod<T>::value, "CreateArray requires a trivially constructible type"); static_assert(std::is_trivially_destructible<T>::value, "CreateArray requires a trivially destructible type"); GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; if (arena == NULL) { return static_cast<T*>(::operator new[](num_elements * sizeof(T))); } else { return arena->CreateInternalRawArray<T>(num_elements); } } // Returns the total space allocated by the arena, which is the sum of the // sizes of the underlying blocks. This method is relatively fast; a counter // is kept as blocks are allocated. uint64 SpaceAllocated() const { return impl_.SpaceAllocated(); } // Returns the total space used by the arena. Similar to SpaceAllocated but // does not include free space and block overhead. The total space returned // may not include space used by other threads executing concurrently with // the call to this method. uint64 SpaceUsed() const { return impl_.SpaceUsed(); } // Frees all storage allocated by this arena after calling destructors // registered with OwnDestructor() and freeing objects registered with Own(). // Any objects allocated on this arena are unusable after this call. It also // returns the total space used by the arena which is the sums of the sizes // of the allocated blocks. This method is not thread-safe. PROTOBUF_NOINLINE uint64 Reset() { // Call the reset hook if (on_arena_reset_ != NULL) { on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated()); } return impl_.Reset(); } // Adds |object| to a list of heap-allocated objects to be freed with |delete| // when the arena is destroyed or reset. template <typename T> PROTOBUF_NOINLINE void Own(T* object) { OwnInternal(object, std::is_convertible<T*, Message*>()); } // Adds |object| to a list of objects whose destructors will be manually // called when the arena is destroyed or reset. This differs from Own() in // that it does not free the underlying memory with |delete|; hence, it is // normally only used for objects that are placement-newed into // arena-allocated memory. template <typename T> PROTOBUF_NOINLINE void OwnDestructor(T* object) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_destruct_object<T>); } } // Adds a custom member function on an object to the list of destructors that // will be manually called when the arena is destroyed or reset. This differs // from OwnDestructor() in that any member function may be specified, not only // the class destructor. PROTOBUF_NOINLINE void OwnCustomDestructor(void* object, void (*destruct)(void*)) { impl_.AddCleanup(object, destruct); } // Retrieves the arena associated with |value| if |value| is an arena-capable // message, or NULL otherwise. If possible, the call resolves at compile time. // Note that we can often devirtualize calls to `value->GetArena()` so usually // calling this method is unnecessary. template <typename T> PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) { return GetArenaInternal(value); } template <typename T> class InternalHelper { template <typename U> static char DestructorSkippable(const typename U::DestructorSkippable_*); template <typename U> static double DestructorSkippable(...); typedef std::integral_constant< bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) == sizeof(char) || std::is_trivially_destructible<T>::value> is_destructor_skippable; template <typename U> static char ArenaConstructable( const typename U::InternalArenaConstructable_*); template <typename U> static double ArenaConstructable(...); typedef std::integral_constant<bool, sizeof(ArenaConstructable<T>( static_cast<const T*>(0))) == sizeof(char)> is_arena_constructable; template <typename U, typename std::enable_if< std::is_same<Arena*, decltype(std::declval<const U>() .GetArena())>::value, int>::type = 0> static char HasGetArena(decltype(&U::GetArena)); template <typename U> static double HasGetArena(...); typedef std::integral_constant<bool, sizeof(HasGetArena<T>(nullptr)) == sizeof(char)> has_get_arena; template <typename... Args> static T* Construct(void* ptr, Args&&... args) { return new (ptr) T(std::forward<Args>(args)...); } static Arena* GetArena(const T* p) { return p->GetArena(); } friend class Arena; }; // Helper typetraits that indicates support for arenas in a type T at compile // time. This is public only to allow construction of higher-level templated // utilities. // // is_arena_constructable<T>::value is true if the message type T has arena // support enabled, and false otherwise. // // is_destructor_skippable<T>::value is true if the message type T has told // the arena that it is safe to skip the destructor, and false otherwise. // // This is inside Arena because only Arena has the friend relationships // necessary to see the underlying generated code traits. template <typename T> struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {}; template <typename T> struct is_destructor_skippable : InternalHelper<T>::is_destructor_skippable { }; private: template <typename T> struct has_get_arena : InternalHelper<T>::has_get_arena {}; template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena, Args&&... args) { static_assert( InternalHelper<T>::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); if (arena == NULL) { return new T(nullptr, std::forward<Args>(args)...); } else { return arena->DoCreateMessage<T>(std::forward<Args>(args)...); } } // This specialization for no arguments is necessary, because its behavior is // slightly different. When the arena pointer is nullptr, it calls T() // instead of T(nullptr). template <typename T> PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena) { static_assert( InternalHelper<T>::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); if (arena == NULL) { return new T(); } else { return arena->DoCreateMessage<T>(); } } template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, Args&&... args) { if (arena == NULL) { return new T(std::forward<Args>(args)...); } else { return arena->DoCreate<T>(std::is_trivially_destructible<T>::value, std::forward<Args>(args)...); } } void CallDestructorHooks(); void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const; inline void AllocHook(const std::type_info* allocated_type, size_t n) const { if (PROTOBUF_PREDICT_FALSE(hooks_cookie_ != NULL)) { OnArenaAllocation(allocated_type, n); } } // Allocate and also optionally call on_arena_allocation callback with the // allocated type info when the hooks are in place in ArenaOptions and // the cookie is not null. template <typename T> PROTOBUF_ALWAYS_INLINE void* AllocateInternal(bool skip_explicit_ownership) { static_assert(alignof(T) <= 8, "T is overaligned, see b/151247138"); const size_t n = internal::AlignUpTo8(sizeof(T)); AllocHook(RTTI_TYPE_ID(T), n); // Monitor allocation if needed. if (skip_explicit_ownership) { return AllocateAlignedNoHook(n); } else { return impl_.AllocateAlignedAndAddCleanup( n, &internal::arena_destruct_object<T>); } } // CreateMessage<T> requires that T supports arenas, but this private method // works whether or not T supports arenas. These are not exposed to user code // as it can cause confusing API usages, and end up having double free in // user code. These are used only internally from LazyField and Repeated // fields, since they are designed to work in all mode combinations. template <typename Msg, typename... Args> PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena, std::true_type, Args&&... args) { return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...); } template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena, std::false_type, Args&&... args) { return CreateInternal<T>(arena, std::forward<Args>(args)...); } template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena, Args&&... args) { return DoCreateMaybeMessage<T>(arena, is_arena_constructable<T>(), std::forward<Args>(args)...); } template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena, std::true_type, Args&&... args) { // User is constructing with Create() despite the fact that T supports arena // construction. In this case we have to delegate to CreateInternal(), and // we can't use any CreateMaybeMessage() specialization that may be defined. return CreateInternal<T>(arena, std::forward<Args>(args)...); } template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena, std::false_type, Args&&... args) { // User is constructing with Create() and the type does not support arena // construction. In this case we can delegate to CreateMaybeMessage() and // use any specialization that may be available for that. return CreateMaybeMessage<T>(arena, std::forward<Args>(args)...); } // Just allocate the required size for the given type assuming the // type has a trivial constructor. template <typename T> PROTOBUF_ALWAYS_INLINE T* CreateInternalRawArray(size_t num_elements) { GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements); // Monitor allocation if needed. AllocHook(RTTI_TYPE_ID(T), n); return static_cast<T*>(AllocateAlignedNoHook(n)); } template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE T* DoCreate(bool skip_explicit_ownership, Args&&... args) { return new (AllocateInternal<T>(skip_explicit_ownership)) T(std::forward<Args>(args)...); } template <typename T, typename... Args> PROTOBUF_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { return InternalHelper<T>::Construct( AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value), this, std::forward<Args>(args)...); } // CreateInArenaStorage is used to implement map field. Without it, // Map need to call generated message's protected arena constructor, // which needs to declare Map as friend of generated message. template <typename T, typename... Args> static void CreateInArenaStorage(T* ptr, Arena* arena, Args&&... args) { CreateInArenaStorageInternal(ptr, arena, typename is_arena_constructable<T>::type(), std::forward<Args>(args)...); RegisterDestructorInternal( ptr, arena, typename InternalHelper<T>::is_destructor_skippable::type()); } template <typename T, typename... Args> static void CreateInArenaStorageInternal(T* ptr, Arena* arena, std::true_type, Args&&... args) { InternalHelper<T>::Construct(ptr, arena, std::forward<Args>(args)...); } template <typename T, typename... Args> static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */, std::false_type, Args&&... args) { new (ptr) T(std::forward<Args>(args)...); } template <typename T> static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */, std::true_type) {} template <typename T> static void RegisterDestructorInternal(T* ptr, Arena* arena, std::false_type) { arena->OwnDestructor(ptr); } // These implement Own(), which registers an object for deletion (destructor // call and operator delete()). The second parameter has type 'true_type' if T // is a subtype of Message and 'false_type' otherwise. Collapsing // all template instantiations to one for generic Message reduces code size, // using the virtual destructor instead. template <typename T> PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object<Message>); } } template <typename T> PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object<T>); } } // Implementation for GetArena(). Only message objects with // InternalArenaConstructable_ tags can be associated with an arena, and such // objects must implement a GetArena() method. template <typename T, typename std::enable_if< is_arena_constructable<T>::value, int>::type = 0> PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { return InternalHelper<T>::GetArena(value); } template <typename T, typename std::enable_if<!is_arena_constructable<T>::value && has_get_arena<T>::value, int>::type = 0> PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { return value->GetArena(); } template <typename T, typename std::enable_if<!is_arena_constructable<T>::value && !has_get_arena<T>::value, int>::type = 0> PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { (void)value; return nullptr; } // For friends of arena. void* AllocateAligned(size_t n) { AllocHook(NULL, n); return AllocateAlignedNoHook(internal::AlignUpTo8(n)); } template<size_t Align> void* AllocateAlignedTo(size_t n) { static_assert(Align > 0, "Alignment must be greater than 0"); static_assert((Align & (Align - 1)) == 0, "Alignment must be power of two"); if (Align <= 8) return AllocateAligned(n); // TODO(b/151247138): if the pointer would have been aligned already, // this is wasting space. We should pass the alignment down. uintptr_t ptr = reinterpret_cast<uintptr_t>(AllocateAligned(n + Align - 8)); ptr = (ptr + Align - 1) & -Align; return reinterpret_cast<void*>(ptr); } void* AllocateAlignedNoHook(size_t n); internal::ArenaImpl impl_; void (*on_arena_allocation_)(const std::type_info* allocated_type, uint64 alloc_size, void* cookie); void (*on_arena_reset_)(Arena* arena, void* cookie, uint64 space_used); void (*on_arena_destruction_)(Arena* arena, void* cookie, uint64 space_used); // The arena may save a cookie it receives from the external on_init hook // and then use it when calling the on_reset and on_destruction hooks. void* hooks_cookie_; template <typename Type> friend class internal::GenericTypeHandler; friend struct internal::ArenaStringPtr; // For AllocateAligned. friend class internal::LazyField; // For CreateMaybeMessage. friend class internal::EpsCopyInputStream; // For parser performance friend class MessageLite; template <typename Key, typename T> friend class Map; }; // Defined above for supporting environments without RTTI. #undef RTTI_TYPE_ID } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_ARENA_H__
1
0.827479
1
0.827479
game-dev
MEDIA
0.525328
game-dev
0.543198
1
0.543198
Ideefixze/TutorialUnityMultiplayer
2,333
MultiplayerArchitectureUnity/Library/PackageCache/com.unity.textmeshpro@3.0.1/Scripts/Editor/GlyphMetricsPropertyDrawer.cs
using UnityEngine; using UnityEngine.TextCore; using UnityEditor; using System.Collections; namespace TMPro.EditorUtilities { [CustomPropertyDrawer(typeof(GlyphMetrics))] public class GlyphMetricsPropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty prop_Width = property.FindPropertyRelative("m_Width"); SerializedProperty prop_Height = property.FindPropertyRelative("m_Height"); SerializedProperty prop_HoriBearingX = property.FindPropertyRelative("m_HorizontalBearingX"); SerializedProperty prop_HoriBearingY = property.FindPropertyRelative("m_HorizontalBearingY"); SerializedProperty prop_HoriAdvance = property.FindPropertyRelative("m_HorizontalAdvance"); // We get Rect since a valid position may not be provided by the caller. Rect rect = new Rect(position.x, position.y, position.width, 49); EditorGUI.LabelField(new Rect(rect.x, rect.y - 2.5f, rect.width, 18), new GUIContent("Glyph Metrics")); EditorGUIUtility.labelWidth = 50f; EditorGUIUtility.fieldWidth = 15f; //GUI.enabled = false; float width = (rect.width - 75f) / 2; EditorGUI.PropertyField(new Rect(rect.x + width * 0, rect.y + 20, width - 5f, 18), prop_Width, new GUIContent("W:")); EditorGUI.PropertyField(new Rect(rect.x + width * 1, rect.y + 20, width - 5f, 18), prop_Height, new GUIContent("H:")); //GUI.enabled = true; width = (rect.width - 75f) / 3; EditorGUI.BeginChangeCheck(); EditorGUI.PropertyField(new Rect(rect.x + width * 0, rect.y + 40, width - 5f, 18), prop_HoriBearingX, new GUIContent("BX:")); EditorGUI.PropertyField(new Rect(rect.x + width * 1, rect.y + 40, width - 5f, 18), prop_HoriBearingY, new GUIContent("BY:")); EditorGUI.PropertyField(new Rect(rect.x + width * 2, rect.y + 40, width - 5f, 18), prop_HoriAdvance, new GUIContent("AD:")); if (EditorGUI.EndChangeCheck()) { } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 65f; } } }
1
0.884419
1
0.884419
game-dev
MEDIA
0.839477
game-dev
0.815322
1
0.815322
mokemokechicken/reversi-alpha-zero
5,621
src/spike/reversi_solver_cython.pyx
from time import time from .bitboard_cython import bit_count, find_correct_moves, calc_flip # CONST DEF BLACK = 1 DEF WHITE = 2 # TYPE cdef struct SolveResult: int move int score cdef struct Env: unsigned long long own unsigned long long enemy int next_player unsigned long long legal_moves int finished int parent_action int best_move int best_score int next_search_action # cdef Env create_env(unsigned long long own, unsigned long long enemy, int next_player): # legal_moves = find_correct_moves(own, enemy) # return Env(own, enemy, next_player, legal_moves, 0, -1, best_move=-1, best_score=-100, next_search_action=0) # cdef class ReversiSolver: cdef dict cache cdef float start_time cdef int timeout cdef int last_is_exactly def __init__(self): self.cache = {} self.start_time = 0 self.timeout = 0 self.last_is_exactly = 0 def solve(self, black, white, next_player: int, timeout=30, exactly=False): """ :param black: :param white: :param next_player: 1=Black, 2=White :param timeout: :param exactly: :return: """ self.timeout = int(timeout) self.start_time = time() if not self.last_is_exactly and exactly: self.cache = {} self.last_is_exactly = exactly result = self.find_winning_move_and_score(black, white, next_player, exactly) if result.move < 0: return None, None else: return result.move, result.score cdef SolveResult find_winning_move_and_score(self, unsigned long long black, unsigned long long white, int next_player, int exactly): cdef Env* child_env = NULL cdef Env* env cdef Env* next_env cdef EnvStack stack = EnvStack() cdef unsigned long long next_own, next_enemy cdef int root_next_player = next_player cdef Env* root_env if next_player == BLACK: root_env = stack.add(black, white, next_player) else: root_env = stack.add(white, black, next_player) while stack.size(): if time() - self.start_time > self.timeout: return SolveResult(-1, -100) env = stack.top() cache_key = (env.own, env.enemy, env.next_player) if cache_key in self.cache: obj = <SolveResult>self.cache[cache_key] env.best_move = obj.move env.best_score = obj.score child_env = stack.pop() child_env.finished = 1 continue if child_env and child_env.finished: child_env.finished = 0 child_score = child_env.best_score if child_env.next_player != env.next_player: child_score = -child_score if env.best_score < child_score: # print(("=" * stack.size()) + f"> update best score ({child_env.parent_action},{child_score})") env.best_move = child_env.parent_action env.best_score = child_score action = next_action(env) # print(("=" * stack.size()) + f"> ID={env.id} NP={env.next_player}:{action} best=({env.best_move},{env.best_score})") if action == -1 or (not exactly and env.best_score > 0): child_env = stack.pop() child_env.finished = 1 self.cache[cache_key] = SolveResult(move=env.best_move, score=env.best_score) continue flipped = calc_flip(action, env.own, env.enemy) next_own = (env.own ^ flipped) | (1 << action) next_enemy = env.enemy ^ flipped if find_correct_moves(next_enemy, next_own) > 0: next_env = stack.add(next_enemy, next_own, 3 - env.next_player) # next_player: 2 => 1, 1 => 2 next_env.parent_action = action elif find_correct_moves(next_own, next_enemy) > 0: next_env = stack.add(next_own, next_enemy, env.next_player) next_env.parent_action = action else: score = bit_count(next_own) - bit_count(next_enemy) if env.best_score < score: env.best_move = action env.best_score = score return SolveResult(root_env.best_move, root_env.best_score) cdef int next_action(Env *env): for i in range(env.next_search_action, 64): if env.legal_moves & (1 << i): env.next_search_action = i+1 return i return -1 cdef class EnvStack: cdef Env stack[64] cdef int pos def __init__(self): self.pos = 0 cdef Env* add(self, unsigned long long own, unsigned long long enemy, int next_player): cdef Env* env = &self.stack[self.pos] env.own = own env.enemy = enemy env.next_player = next_player env.legal_moves = find_correct_moves(own, enemy) env.finished = 0 env.parent_action = -1 env.best_move = -1 env.best_score = -100 env.next_search_action = 0 self.pos += 1 return env cdef Env* top(self): return &(self.stack[self.pos - 1]) cdef Env* pop(self): ret = self.top() self.pos -= 1 # print(f"pop: {ret.id} from pos: {self.pos}") return ret cdef int size(self): return self.pos cdef debug(self): for i in range(self.pos): print(f"{i}: {self.stack[i].id}")
1
0.905044
1
0.905044
game-dev
MEDIA
0.355435
game-dev
0.755678
1
0.755678
long-war-2/lwotc
40,757
LongWarOfTheChosen/Src/LW_XModBase/Classes/XMBAbility.uc
//--------------------------------------------------------------------------------------- // FILE: XMBAbility.uc // AUTHOR: xylthixlm // // This class provides additional helpers for defining ability templates. Simply // declare your ability sets to extend XMBAbility instead of X2Ability, and then use // whatever helpers you need. // // USAGE // // class X2Ability_MyClassAbilitySet extends XMBAbility; // // INSTALLATION // // Install the XModBase core as described in readme.txt. Copy this file, and any files // listed as dependencies, into your mod's Classes/ folder. You may edit this file. // // DEPENDENCIES // // Core // XMBCondition_CoverType.uc // XMBCondition_HeightAdvantage.uc // XMBCondition_ReactionFire.uc // XMBCondition_Dead.uc //--------------------------------------------------------------------------------------- class XMBAbility extends X2Ability; // Used by ActionPointCost and related functions enum EActionPointCost { eCost_Free, // No action point cost, but you must have an action point available. eCost_Single, // Costs a single action point. eCost_SingleConsumeAll, // Costs a single action point, ends the turn. eCost_Double, // Costs two action points. eCost_DoubleConsumeAll, // Costs two action points, ends the turn. eCost_Weapon, // Costs as much as a weapon shot. eCost_WeaponConsumeAll, // Costs as much as a weapon shot, ends the turn. eCost_Overwatch, // No action point cost, but displays as ending the turn. Used for // abilities that have an X2Effect_ReserveActionPoints or similar. eCost_None, // No action point cost. For abilities which may be triggered during // the enemy turn. You should use eCost_Free for activated abilities. }; // Predefined conditions for use with XMBEffect_ConditionalBonus and similar effects. // Careful, these objects should NEVER be modified - only constructed by default. // They can be freely used by any ability template, but NEVER modified by them. // Cover conditions. Only work as target conditions, not shooter conditions. var const XMBCondition_CoverType FullCoverCondition; // The target is in full cover var const XMBCondition_CoverType HalfCoverCondition; // The target is in half cover var const XMBCondition_CoverType NoCoverCondition; // The target is not in cover var const XMBCondition_CoverType FlankedCondition; // The target is not in cover and can be flanked // Height advantage conditions. Only work as target conditions, not shooter conditions. var const XMBCondition_HeightAdvantage HeightAdvantageCondition; // The target is higher than the shooter var const XMBCondition_HeightAdvantage HeightDisadvantageCondition; // The target is lower than the shooter // Reaction fire conditions. Only work as target conditions, not shooter conditions. Nonsensical // if used on an X2AbilityTemplate, since it will always be either reaction fire or not. var const XMBCondition_ReactionFire ReactionFireCondition; // The attack is reaction fire // Liveness conditions. Work as target or shooter conditions. var const XMBCondition_Dead DeadCondition; // The target is dead // Result conditions. Only work as target conditions, not shooter conditions. Doesn't work if used // on an X2AbilityTemplate since the hit result isn't known when selecting targets. var const XMBCondition_AbilityHitResult HitCondition; // The ability hits (including crits and grazes) var const XMBCondition_AbilityHitResult MissCondition; // The ability misses var const XMBCondition_AbilityHitResult CritCondition; // The ability crits var const XMBCondition_AbilityHitResult GrazeCondition; // The ability grazes // Matching weapon conditions. Only work as target conditions. Doesn't work if used on an // X2AbilityTemplate. var const XMBCondition_MatchingWeapon MatchingWeaponCondition; // The ability matches the weapon of the // ability defining the condition var const XMBCondition_AbilityProperty MeleeCondition; var const XMBCondition_AbilityProperty RangedCondition; // Unit property conditions. var const X2Condition_UnitProperty LivingFriendlyTargetProperty; // The target is alive and an ally. // Use this for ShotHUDPriority to have the priority calculated automatically var const int AUTO_PRIORITY; // This is an implementation detail. It holds templates added via AddSecondaryAbility(). var array<X2AbilityTemplate> ExtraTemplates; // Checks if a conditional effect shouldn't have a bonus marker when active because it will always be active. static function bool AlwaysRelevant(XMBEffect_ConditionalBonus Effect) { if (Effect.AbilityTargetConditions.Length > 0 && class'XMBEffect_ConditionalBonus'.static.AllConditionsAreUnitConditions(Effect.AbilityTargetConditions)) return false; if (Effect.AbilityShooterConditions.Length > 0) return false; if (Effect.ScaleValue != none) return false; return true; } // Helper method for quickly defining a non-pure passive. Works like PurePassive, except it also // takes an X2Effect_Persistent. static function X2AbilityTemplate Passive(name DataName, string IconImage, optional bool bCrossClassEligible = false, optional X2Effect Effect = none) { local X2AbilityTemplate Template; local XMBEffect_ConditionalBonus ConditionalBonusEffect; local XMBEffect_ConditionalStatChange ConditionalStatChangeEffect; local X2Effect_Persistent PersistentEffect; `CREATE_X2ABILITY_TEMPLATE(Template, DataName); Template.IconImage = IconImage; Template.AbilitySourceName = 'eAbilitySource_Perk'; Template.eAbilityIconBehaviorHUD = EAbilityIconBehavior_NeverShow; Template.Hostility = eHostility_Neutral; Template.AbilityToHitCalc = default.DeadEye; Template.AbilityTargetStyle = default.SelfTarget; Template.AbilityTriggers.AddItem(default.UnitPostBeginPlayTrigger); PersistentEffect = X2Effect_Persistent(Effect); ConditionalBonusEffect = XMBEffect_ConditionalBonus(Effect); ConditionalStatChangeEffect = XMBEffect_ConditionalStatChange(Effect); if (ConditionalBonusEffect != none && !AlwaysRelevant(ConditionalBonusEffect)) { ConditionalBonusEffect.BuildPersistentEffect(1, true, false, false); ConditionalBonusEffect.SetDisplayInfo(ePerkBuff_Bonus, Template.LocFriendlyName, Template.LocHelpText, Template.IconImage, true,,Template.AbilitySourceName); ConditionalBonusEffect.bHideWhenNotRelevant = true; PersistentEffect = new class'X2Effect_Persistent'; PersistentEffect.EffectName = name(DataName $ "_Passive"); } else if (ConditionalStatChangeEffect != none) { ConditionalStatChangeEffect.BuildPersistentEffect(1, true, false, false); ConditionalStatChangeEffect.SetDisplayInfo(ePerkBuff_Bonus, Template.LocFriendlyName, Template.LocHelpText, Template.IconImage, true,,Template.AbilitySourceName); PersistentEffect = new class'X2Effect_Persistent'; PersistentEffect.EffectName = name(DataName $ "_Passive"); } else if (PersistentEffect == none) { PersistentEffect = new class'X2Effect_Persistent'; } PersistentEffect.BuildPersistentEffect(1, true, false, false); PersistentEffect.SetDisplayInfo(ePerkBuff_Passive, Template.LocFriendlyName, Template.LocLongDescription, Template.IconImage, true,,Template.AbilitySourceName); Template.AddTargetEffect(PersistentEffect); if (Effect != PersistentEffect && Effect != none) Template.AddTargetEffect(Effect); Template.BuildNewGameStateFn = TypicalAbility_BuildGameState; // NOTE: No visualization on purpose! Template.bCrossClassEligible = bCrossClassEligible; return Template; } // Helper function for quickly defining an ability that triggers on an event and targets the unit // itself. Note that this does not add a passive ability icon, so you should pair it with a // Passive or PurePassive that defines the icon, or use AddIconPassive. The IconImage argument is // still used as the icon for effects created by this ability. static function X2AbilityTemplate SelfTargetTrigger(name DataName, string IconImage, optional bool bCrossClassEligible = false, optional X2Effect Effect = none, optional name EventID = '', optional AbilityEventFilter Filter = eFilter_Unit) { local X2AbilityTemplate Template; local XMBAbilityTrigger_EventListener EventListener; `CREATE_X2ABILITY_TEMPLATE(Template, DataName); Template.AbilitySourceName = 'eAbilitySource_Perk'; Template.eAbilityIconBehaviorHUD = eAbilityIconBehavior_NeverShow; Template.Hostility = eHostility_Neutral; Template.IconImage = IconImage; Template.AbilityToHitCalc = default.DeadEye; Template.AbilityTargetStyle = default.SelfTarget; if (EventID == '') EventID = DataName; // XMBAbilityTrigger_EventListener doesn't use ListenerData.EventFn EventListener = new class'XMBAbilityTrigger_EventListener'; EventListener.ListenerData.Deferral = ELD_OnStateSubmitted; EventListener.ListenerData.EventID = EventID; EventListener.ListenerData.Filter = Filter; EventListener.bSelfTarget = true; Template.AbilityTriggers.AddItem(EventListener); Template.AbilityShooterConditions.AddItem(default.LivingShooterProperty); if (Effect != none) { if (X2Effect_Persistent(Effect) != none) X2Effect_Persistent(Effect).SetDisplayInfo(ePerkBuff_Bonus, Template.LocFriendlyName, Template.LocLongDescription, Template.IconImage, true, , Template.AbilitySourceName); Template.AddTargetEffect(Effect); } Template.BuildNewGameStateFn = TypicalAbility_BuildGameState; Template.BuildVisualizationFn = TypicalAbility_BuildVisualization; Template.bSkipFireAction = true; Template.bCrossClassEligible = bCrossClassEligible; return Template; } // Helper function for creating an activated ability that targets the user. static function X2AbilityTemplate SelfTargetActivated(name DataName, string IconImage, optional bool bCrossClassEligible = false, optional X2Effect Effect = none, optional int ShotHUDPriority = default.AUTO_PRIORITY, optional EActionPointCost Cost = eCost_Single) { local X2AbilityTemplate Template; `CREATE_X2ABILITY_TEMPLATE(Template, DataName); Template.DisplayTargetHitChance = false; Template.AbilitySourceName = 'eAbilitySource_Perk'; Template.eAbilityIconBehaviorHUD = eAbilityIconBehavior_AlwaysShow; Template.Hostility = eHostility_Neutral; Template.IconImage = IconImage; Template.ShotHUDPriority = ShotHUDPriority; Template.AbilityConfirmSound = "TacticalUI_ActivateAbility"; Template.AbilityToHitCalc = default.DeadEye; Template.AbilityTargetStyle = default.SelfTarget; Template.AbilityTriggers.AddItem(default.PlayerInputTrigger); if (Cost != eCost_None) { Template.AbilityCosts.AddItem(ActionPointCost(Cost)); } Template.AbilityShooterConditions.AddItem(default.LivingShooterProperty); if (Effect != none) { if (X2Effect_Persistent(Effect) != none) X2Effect_Persistent(Effect).SetDisplayInfo(ePerkBuff_Bonus, Template.LocFriendlyName, Template.LocLongDescription, Template.IconImage, true, , Template.AbilitySourceName); Template.AddTargetEffect(Effect); } Template.BuildNewGameStateFn = TypicalAbility_BuildGameState; Template.BuildVisualizationFn = TypicalAbility_BuildVisualization; Template.bSkipFireAction = true; Template.bCrossClassEligible = bCrossClassEligible; return Template; } // Helper function for creating a typical weapon attack. static function X2AbilityTemplate Attack(name DataName, string IconImage, optional bool bCrossClassEligible = false, optional X2Effect Effect = none, optional int ShotHUDPriority = default.AUTO_PRIORITY, optional EActionPointCost Cost = eCost_SingleConsumeAll, optional int iAmmo = 1) { local X2AbilityTemplate Template; local X2Condition_Visibility VisibilityCondition; // Macro to do localisation and stuffs `CREATE_X2ABILITY_TEMPLATE(Template, DataName); // Icon Properties Template.IconImage = IconImage; Template.ShotHUDPriority = ShotHUDPriority; Template.eAbilityIconBehaviorHUD = eAbilityIconBehavior_AlwaysShow; Template.DisplayTargetHitChance = true; Template.AbilitySourceName = 'eAbilitySource_Perk'; Template.Hostility = eHostility_Offensive; Template.AbilityTriggers.AddItem(default.PlayerInputTrigger); Template.AddShooterEffectExclusions(); VisibilityCondition = new class'X2Condition_Visibility'; VisibilityCondition.bRequireGameplayVisible = true; VisibilityCondition.bAllowSquadsight = true; Template.AbilityTargetConditions.AddItem(VisibilityCondition); Template.AbilityTargetConditions.AddItem(default.LivingHostileTargetProperty); Template.AbilityShooterConditions.AddItem(default.LivingShooterProperty); // Don't allow the ability to be used while the unit is disoriented, burning, unconscious, etc. Template.AddShooterEffectExclusions(); Template.AbilityTargetStyle = default.SimpleSingleTarget; if (Cost != eCost_None) { Template.AbilityCosts.AddItem(ActionPointCost(Cost)); } if (iAmmo > 0) { AddAmmoCost(Template, iAmmo); } Template.bAllowAmmoEffects = true; Template.bAllowBonusWeaponEffects = true; Template.bAllowFreeFireWeaponUpgrade = true; if (Effect != none) { if (X2Effect_Persistent(Effect) != none) X2Effect_Persistent(Effect).SetDisplayInfo(ePerkBuff_Penalty, Template.LocFriendlyName, Template.LocLongDescription, Template.IconImage, true, , Template.AbilitySourceName); Template.AddTargetEffect(Effect); } else { // Put holo target effect first because if the target dies from this shot, it will be too late to notify the effect. Template.AddTargetEffect(class'X2Ability_GrenadierAbilitySet'.static.HoloTargetEffect()); // Various Soldier ability specific effects - effects check for the ability before applying Template.AddTargetEffect(class'X2Ability_GrenadierAbilitySet'.static.ShredderDamageEffect()); Template.AddTargetEffect(default.WeaponUpgradeMissDamage); } Template.AbilityToHitCalc = default.SimpleStandardAim; Template.AbilityToHitOwnerOnMissCalc = default.SimpleStandardAim; Template.TargetingMethod = class'X2TargetingMethod_OverTheShoulder'; Template.bUsesFiringCamera = true; Template.CinescriptCameraType = "StandardGunFiring"; Template.AssociatedPassives.AddItem('HoloTargeting'); Template.BuildNewGameStateFn = TypicalAbility_BuildGameState; Template.BuildVisualizationFn = TypicalAbility_BuildVisualization; Template.BuildInterruptGameStateFn = TypicalAbility_BuildInterruptGameState; Template.bDisplayInUITooltip = false; Template.bDisplayInUITacticalText = false; Template.bCrossClassEligible = bCrossClassEligible; return Template; } static function X2AbilityTemplate MeleeAttack(name DataName, string IconImage, optional bool bCrossClassEligible = false, optional X2Effect Effect = none, optional int ShotHUDPriority = default.AUTO_PRIORITY, optional EActionPointCost Cost = eCost_SingleConsumeAll) { local X2AbilityTemplate Template; `CREATE_X2ABILITY_TEMPLATE(Template, DataName); Template.AbilitySourceName = 'eAbilitySource_Perk'; Template.eAbilityIconBehaviorHUD = EAbilityIconBehavior_AlwaysShow; Template.BuildNewGameStateFn = TypicalAbility_BuildGameState; Template.BuildVisualizationFn = TypicalAbility_BuildVisualization; Template.CinescriptCameraType = "Ranger_Reaper"; Template.IconImage = IconImage; Template.ShotHUDPriority = ShotHUDPriority; if (Cost != eCost_None) { Template.AbilityCosts.AddItem(ActionPointCost(Cost)); } Template.AbilityToHitCalc = new class'X2AbilityToHitCalc_StandardMelee'; Template.AbilityTargetStyle = new class'X2AbilityTarget_MovingMelee'; Template.TargetingMethod = class'X2TargetingMethod_MeleePath'; Template.AbilityTriggers.AddItem(default.PlayerInputTrigger); Template.AbilityTriggers.AddItem(new class'X2AbilityTrigger_EndOfMove'); Template.AbilityTargetConditions.AddItem(default.LivingHostileTargetProperty); Template.AbilityTargetConditions.AddItem(default.MeleeVisibilityCondition); Template.AbilityShooterConditions.AddItem(default.LivingShooterProperty); // Don't allow the ability to be used while the unit is disoriented, burning, unconscious, etc. Template.AddShooterEffectExclusions(); if (Effect != none) { Template.AddTargetEffect(Effect); } else { Template.AddTargetEffect(new class'X2Effect_ApplyWeaponDamage'); } Template.bAllowBonusWeaponEffects = true; Template.bSkipMoveStop = true; // Voice events // Template.SourceMissSpeech = 'SwordMiss'; Template.BuildNewGameStateFn = TypicalMoveEndAbility_BuildGameState; Template.BuildInterruptGameStateFn = TypicalMoveEndAbility_BuildInterruptGameState; Template.bCrossClassEligible = bCrossClassEligible; return Template; } // Helper function for creating an ability that targets a visible enemy and has 100% hit chance. static function X2AbilityTemplate TargetedDebuff(name DataName, string IconImage, optional bool bCrossClassEligible = false, optional X2Effect Effect = none, optional int ShotHUDPriority = default.AUTO_PRIORITY, optional EActionPointCost Cost = eCost_Single) { local X2AbilityTemplate Template; `CREATE_X2ABILITY_TEMPLATE(Template, DataName); Template.ShotHUDPriority = ShotHUDPriority; Template.IconImage = IconImage; Template.eAbilityIconBehaviorHUD = eAbilityIconBehavior_AlwaysShow; Template.AbilitySourceName = 'eAbilitySource_Perk'; Template.Hostility = eHostility_Offensive; if (Cost != eCost_None) { Template.AbilityCosts.AddItem(ActionPointCost(Cost)); } Template.AbilityShooterConditions.AddItem(default.LivingShooterProperty); Template.AbilityTargetConditions.AddItem(default.GameplayVisibilityCondition); Template.AbilityTargetConditions.AddItem(default.LivingHostileTargetProperty); // Don't allow the ability to be used while the unit is disoriented, burning, unconscious, etc. Template.AddShooterEffectExclusions(); // 100% chance to hit Template.AbilityToHitCalc = default.DeadEye; Template.AbilityTargetStyle = default.SimpleSingleTarget; Template.AbilityTriggers.AddItem(default.PlayerInputTrigger); if (Effect != none) { if (X2Effect_Persistent(Effect) != none) X2Effect_Persistent(Effect).SetDisplayInfo(ePerkBuff_Penalty, Template.LocFriendlyName, Template.LocLongDescription, Template.IconImage, true, , Template.AbilitySourceName); Template.AddTargetEffect(Effect); } Template.BuildNewGameStateFn = TypicalAbility_BuildGameState; Template.BuildVisualizationFn = TypicalAbility_BuildVisualization; // Use an animation of pointing at the target, rather than the weapon animation. Template.CustomFireAnim = 'HL_SignalPoint'; Template.bCrossClassEligible = bCrossClassEligible; return Template; } // Helper function for creating an ability that targets an ally (or the user). static function X2AbilityTemplate TargetedBuff(name DataName, string IconImage, optional bool bCrossClassEligible = false, optional X2Effect Effect = none, optional int ShotHUDPriority = default.AUTO_PRIORITY, optional EActionPointCost Cost = eCost_Single) { local X2AbilityTemplate Template; `CREATE_X2ABILITY_TEMPLATE(Template, DataName); Template.ShotHUDPriority = ShotHUDPriority; Template.IconImage = IconImage; Template.eAbilityIconBehaviorHUD = eAbilityIconBehavior_AlwaysShow; Template.AbilitySourceName = 'eAbilitySource_Perk'; Template.Hostility = eHostility_Defensive; if (Cost != eCost_None) { Template.AbilityCosts.AddItem(ActionPointCost(Cost)); } Template.AbilityShooterConditions.AddItem(default.LivingShooterProperty); Template.AbilityTargetConditions.AddItem(default.LivingFriendlyTargetProperty); Template.AbilityShooterConditions.AddItem(default.LivingShooterProperty); // Don't allow the ability to be used while the unit is disoriented, burning, unconscious, etc. Template.AddShooterEffectExclusions(); // 100% chance to hit Template.AbilityToHitCalc = default.DeadEye; Template.AbilityTargetStyle = default.SimpleSingleTarget; Template.AbilityTriggers.AddItem(default.PlayerInputTrigger); if (Effect != none) { if (X2Effect_Persistent(Effect) != none) X2Effect_Persistent(Effect).SetDisplayInfo(ePerkBuff_Bonus, Template.LocFriendlyName, Template.LocLongDescription, Template.IconImage, true, , Template.AbilitySourceName); Template.AddTargetEffect(Effect); } Template.BuildNewGameStateFn = TypicalAbility_BuildGameState; Template.BuildVisualizationFn = TypicalAbility_BuildVisualization; // Use an animation of pointing at the target, rather than the weapon animation. Template.CustomFireAnim = 'HL_SignalPoint'; Template.bCrossClassEligible = bCrossClassEligible; return Template; } // Helper function for creating an ability that affects all friendly units. static function X2AbilityTemplate SquadPassive(name DataName, string IconImage, bool bCrossClassEligible, X2Effect_Persistent Effect) { local X2AbilityTemplate Template, TriggerTemplate; local X2Condition_UnitEffectsWithAbilitySource Condition; local XMBAbilityTrigger_EventListener EventListener; // Create a normal passive, which triggers when the unit enters play. This // also provides the icon for the ability. Template = Passive(DataName, IconImage, bCrossClassEligible, none); Effect.BuildPersistentEffect(1, true, false, false); // The passive applies the effect to all friendly units at the start of play. Template.AbilityMultiTargetStyle = new class'X2AbilityMultiTarget_AllAllies'; Template.AddMultiTargetEffect(Effect); Condition = new class'X2Condition_UnitEffectsWithAbilitySource'; Condition.AddExcludeEffect(Effect.EffectName, 'AA_UnitIsImmune'); Effect.TargetConditions.AddItem(Condition); // Create a triggered ability which will apply the effect to friendly units // that are created after play begins. TriggerTemplate = TargetedBuff(name(DataName $ "_OnUnitBeginPlay"), IconImage, false, Effect,, eCost_None); // The triggered ability shouldn't have a fire visualization added TriggerTemplate.bSkipFireAction = true; // Remove the default input trigger added by TargetedBuff() TriggerTemplate.AbilityTriggers.Length = 0; // Don't show the ability as activatable in the HUD TriggerTemplate.eAbilityIconBehaviorHUD = eAbilityIconBehavior_NeverShow; // Set up a trigger that will fire whenever another unit enters the battle // XMBAbilityTrigger_EventListener doesn't use ListenerData.EventFn EventListener = new class'XMBAbilityTrigger_EventListener'; EventListener.ListenerData.Deferral = ELD_OnStateSubmitted; EventListener.ListenerData.EventID = 'OnUnitBeginPlay'; EventListener.ListenerData.Filter = eFilter_None; EventListener.bSelfTarget = false; TriggerTemplate.AbilityTriggers.AddItem(EventListener); // Add the triggered ability as a secondary ability AddSecondaryAbility(Template, TriggerTemplate); return Template; } static function AddSecondaryEffect(X2AbilityTemplate Template, X2Effect Effect) { if (X2Effect_Persistent(Effect) != none) X2Effect_Persistent(Effect).SetDisplayInfo(ePerkBuff_Bonus, Template.LocFriendlyName, Template.LocHelpText, Template.IconImage, true, , Template.AbilitySourceName); if (XMBEffect_ConditionalBonus(Effect) != none) XMBEffect_ConditionalBonus(Effect).bHideWhenNotRelevant = true; Template.AddTargetEffect(Effect); } // Hides the icon of an ability. For use with secondary abilities added in AdditionaAbilities that // shouldn't get their own icon. static function HidePerkIcon(X2AbilityTemplate Template) { local X2Effect Effect; Template.eAbilityIconBehaviorHUD = eAbilityIconBehavior_NeverShow; foreach Template.AbilityTargetEffects(Effect) { if (X2Effect_Persistent(Effect) != none) X2Effect_Persistent(Effect).bDisplayInUI = false; } } // Helper function for creating an X2AbilityCost_ActionPoints. static function X2AbilityCost_ActionPoints ActionPointCost(EActionPointCost Cost) { local X2AbilityCost_ActionPoints AbilityCost; AbilityCost = new class'X2AbilityCost_ActionPoints'; switch (Cost) { case eCost_Free: AbilityCost.iNumPoints = 1; AbilityCost.bFreeCost = true; break; case eCost_Single: AbilityCost.iNumPoints = 1; break; case eCost_SingleConsumeAll: AbilityCost.iNumPoints = 1; AbilityCost.bConsumeAllPoints = true; break; case eCost_Double: AbilityCost.iNumPoints = 2; break; case eCost_DoubleConsumeAll: AbilityCost.iNumPoints = 2; AbilityCost.bConsumeAllPoints = true; break; case eCost_Weapon: AbilityCost.iNumPoints = 0; AbilityCost.bAddWeaponTypicalCost = true; break; case eCost_WeaponConsumeAll: AbilityCost.iNumPoints = 0; AbilityCost.bAddWeaponTypicalCost = true; AbilityCost.bConsumeAllPoints = true; break; case eCost_Overwatch: AbilityCost.iNumPoints = 1; AbilityCost.bConsumeAllPoints = true; AbilityCost.bFreeCost = true; break; case eCost_None: AbilityCost.iNumPoints = 0; break; } return AbilityCost; } // Helper function for adding a cooldown to an ability. This takes an internal cooldown duration, // which is one turn longer than the cooldown displayed in ability help text because it includes // the turn the ability was applied. static function AddCooldown(X2AbilityTemplate Template, int iNumTurns) { local X2AbilityCooldown AbilityCooldown; AbilityCooldown = new class'X2AbilityCooldown'; AbilityCooldown.iNumTurns = iNumTurns; Template.AbilityCooldown = AbilityCooldown; } // Helper function for adding an ammo cost to an ability. static function AddAmmoCost(X2AbilityTemplate Template, int iAmmo) { local X2AbilityCost_Ammo AmmoCost; AmmoCost = new class'X2AbilityCost_Ammo'; AmmoCost.iAmmo = iAmmo; Template.AbilityCosts.AddItem(AmmoCost); } // Helper function for giving an ability a limited number of charges. static function AddCharges(X2AbilityTemplate Template, int InitialCharges) { local X2AbilityCharges Charges; local X2AbilityCost_Charges ChargeCost; Charges = new class 'X2AbilityCharges'; Charges.InitialCharges = InitialCharges; Template.AbilityCharges = Charges; ChargeCost = new class'X2AbilityCost_Charges'; ChargeCost.NumCharges = 1; Template.AbilityCosts.AddItem(ChargeCost); } // Helper function for making an ability trigger whenever another unit moves in the unit's vision. // This is usually used for overwatch-type abilities. static function AddMovementTrigger(X2AbilityTemplate Template) { /* local X2AbilityTrigger_Event Trigger; Trigger = new class'X2AbilityTrigger_Event'; Trigger.EventObserverClass = class'X2TacticalGameRuleset_MovementObserver'; Trigger.MethodName = 'InterruptGameState'; Template.AbilityTriggers.AddItem(Trigger); */ local X2AbilityTrigger_EventListener Trigger; Trigger = new class'X2AbilityTrigger_EventListener'; Trigger.ListenerData.EventID = 'ObjectMoved'; Trigger.ListenerData.Deferral = ELD_OnStateSubmitted; Trigger.ListenerData.Filter = eFilter_None; Trigger.ListenerData.EventFn = class'XComGameState_Ability'.static.TypicalOverwatchListener; Template.AbilityTriggers.AddItem(Trigger); } // Helper function for making an ability trigger whenever another unit acts in the unit's vision. // This is usually used for overwatch-type abilities. static function AddAttackTrigger(X2AbilityTemplate Template) { /* local X2AbilityTrigger_Event Trigger; Trigger = new class'X2AbilityTrigger_Event'; Trigger.EventObserverClass = class'X2TacticalGameRuleset_AttackObserver'; Trigger.MethodName = 'InterruptGameState'; Template.AbilityTriggers.AddItem(Trigger); */ local X2AbilityTrigger_EventListener EventListener; EventListener = new class'X2AbilityTrigger_EventListener'; EventListener.ListenerData.EventID = 'AbilityActivated'; EventListener.ListenerData.Deferral = ELD_OnStateSubmitted; EventListener.ListenerData.Filter = eFilter_None; EventListener.ListenerData.Priority = 85; EventListener.ListenerData.EventFn = class'XComGameState_Ability'.static.TypicalAttackListener; Template.AbilityTriggers.AddItem(EventListener); } // Helper function for preventing an ability from applying to the same target too often. This works // by creating a dummy persistent effect that does nothing and expires after some number of turns, // and adding a condition that prevents the ability from affecting units with the dummy persistent // effect. One common use is to prevent overwatch-type abilities from triggering more than once // against the same target in a turn. static function AddPerTargetCooldown(X2AbilityTemplate Template, optional int iTurns = 1, optional name CooldownEffectName = '', optional GameRuleStateChange GameRule = eGameRule_PlayerTurnEnd) { local X2Effect_Persistent PersistentEffect; local X2Condition_UnitEffectsWithAbilitySource EffectsCondition; if (CooldownEffectName == '') { CooldownEffectName = name(Template.DataName $ "_CooldownEffect"); } PersistentEffect = new class'X2Effect_Persistent'; PersistentEffect.EffectName = CooldownEffectName; PersistentEffect.DuplicateResponse = eDupe_Refresh; PersistentEffect.BuildPersistentEffect(iTurns, false, true, false, GameRule); PersistentEffect.bApplyOnHit = true; PersistentEffect.bApplyOnMiss = true; Template.AddTargetEffect(PersistentEffect); Template.AddMultiTargetEffect(PersistentEffect); // Create a condition that checks for the presence of a certain effect. There are three // similar classes that do this: X2Condition_UnitEffects, // X2Condition_UnitEffectsWithAbilitySource, and X2Condition_UnitEffectsWithAbilityTarget. // The first one looks for any effect with the right name, the second only for effects // with that were applied by the unit using this ability, and the third only for effects // that apply to the unit using this ability. Since we want to match the persistent effect // we applied as a mark - but not the same effect applied by any other unit - we use // X2Condition_UnitEffectsWithAbilitySource. EffectsCondition = new class'X2Condition_UnitEffectsWithAbilitySource'; EffectsCondition.AddExcludeEffect(CooldownEffectName, 'AA_UnitIsImmune'); Template.AbilityTargetConditions.AddItem(EffectsCondition); Template.AbilityMultiTargetConditions.AddItem(EffectsCondition); } // For abilities with an XMBAbilityTrigger_EventListener, such as abilities created by // SelfTargetTrigger, this adds an AbilityTargetCondition to the listener. Use this when you want // to add a restriction based on the ability that caused the trigger to fire, for example with an // AbilityActivated trigger. If you want to add a restriction on the unit the triggered ability // will apply to, use X2AbilityTemplate.AbilityTargetConditions instead. static function AddTriggerTargetCondition(X2AbilityTemplate Template, X2Condition Condition) { local X2AbilityTrigger Trigger; foreach Template.AbilityTriggers(Trigger) { if (XMBAbilityTrigger_EventListener(Trigger) != none) XMBAbilityTrigger_EventListener(Trigger).AbilityTargetConditions.AddItem(Condition); } } // For abilities with an XMBAbilityTrigger_EventListener, such as abilities created by // SelfTargetTrigger, this adds an AbilityShooterCondition to the listener. In most cases you // should use X2AbilityTemplate.AbilityShooterConditions instead of this. static function AddTriggerShooterCondition(X2AbilityTemplate Template, X2Condition Condition) { local X2AbilityTrigger Trigger; foreach Template.AbilityTriggers(Trigger) { if (XMBAbilityTrigger_EventListener(Trigger) != none) XMBAbilityTrigger_EventListener(Trigger).AbilityShooterConditions.AddItem(Condition); } } // Prevent an ability from targetting a unit that already has any of the effects the ability would // add. You should also set DuplicateResponse to eDupe_Ignore if you use this. static function PreventStackingEffects(X2AbilityTemplate Template) { local X2Condition_UnitEffectsWithAbilitySource EffectsCondition; local X2Effect Effect; EffectsCondition = new class'X2Condition_UnitEffectsWithAbilitySource'; foreach Template.AbilityTargetEffects(Effect) { if (X2Effect_Persistent(Effect) != none) EffectsCondition.AddExcludeEffect(X2Effect_Persistent(Effect).EffectName, 'AA_UnitIsImmune'); } Template.AbilityTargetConditions.AddItem(EffectsCondition); } // Adds a secondary ability that provides a passive icon for the ability. For use with triggered // abilities and other abilities that should have a passive icon but don't have a passive effect // to use with Passive. static function AddIconPassive(X2AbilityTemplate Template) { local X2AbilityTemplate IconTemplate; IconTemplate = PurePassive(name(Template.DataName $ "_Icon"), Template.IconImage); AddSecondaryAbility(Template, IconTemplate); // Use the long description, rather than the help text X2Effect_Persistent(IconTemplate.AbilityTargetEffects[0]).FriendlyDescription = Template.LocLongDescription; } // Adds an arbitrary secondary ability to an ability template. This handles copying over the // ability's localized name and description to the secondary, so you only have to write one entry // for the ability in XComGame.int. static function AddSecondaryAbility(X2AbilityTemplate Template, X2AbilityTemplate SecondaryTemplate) { local X2Effect Effect; local X2Effect_Persistent PersistentEffect; Template.AdditionalAbilities.AddItem(SecondaryTemplate.DataName); SecondaryTemplate.LocFriendlyName = Template.LocFriendlyName; SecondaryTemplate.LocHelpText = Template.LocHelpText; SecondaryTemplate.LocLongDescription = Template.LocLongDescription; SecondaryTemplate.LocFlyOverText = Template.LocFlyOverText; foreach SecondaryTemplate.AbilityTargetEffects(Effect) { PersistentEffect = X2EFfect_Persistent(Effect); if (PersistentEffect == none) continue; PersistentEffect.FriendlyName = Template.LocFriendlyName; PersistentEffect.FriendlyDescription = Template.LocHelpText; } foreach SecondaryTemplate.AbilityShooterEffects(Effect) { PersistentEffect = X2EFfect_Persistent(Effect); if (PersistentEffect == none) continue; PersistentEffect.FriendlyName = Template.LocFriendlyName; PersistentEffect.FriendlyDescription = Template.LocHelpText; } XMBAbility(class'XComEngine'.static.GetClassDefaultObject(default.class)).ExtraTemplates.AddItem(SecondaryTemplate); } static function XMBEffect_ConditionalBonus AddBonusPassive(X2AbilityTemplate Template, name DataName = name(Template.DataName $ "_Bonuses")) { local X2AbilityTemplate PassiveTemplate; local XMBEffect_ConditionalBonus BonusEffect; local XMBCondition_AbilityName Condition; BonusEffect = new class'XMBEffect_ConditionalBonus'; Condition = new class'XMBCondition_AbilityName'; Condition.IncludeAbilityNames.AddItem(Template.DataName); BonusEffect.AbilityTargetConditions.AddItem(Condition); PassiveTemplate = Passive(DataName, Template.IconImage, false, BonusEffect); AddSecondaryAbility(Template, PassiveTemplate); HidePerkIcon(PassiveTemplate); return BonusEffect; } // Helper function for creating an X2Condition that requires a maximum distance between shooter and target. simulated static function X2Condition_UnitProperty TargetWithinTiles(int Tiles) { local X2Condition_UnitProperty UnitPropertyCondition; UnitPropertyCondition = new class'X2Condition_UnitProperty'; UnitPropertyCondition.RequireWithinRange = true; // WithinRange is measured in Unreal units, so we need to convert tiles to units. UnitPropertyCondition.WithinRange = `TILESTOUNITS(Tiles); // Remove default checks UnitPropertyCondition.ExcludeDead = false; UnitPropertyCondition.ExcludeFriendlyToSource = false; UnitPropertyCondition.ExcludeCosmetic = false; UnitPropertyCondition.ExcludeInStasis = false; return UnitPropertyCondition; } // Set this as the VisualizationFn on an X2Effect_Persistent to have it display a flyover over the target when applied. simulated static function EffectFlyOver_Visualization(XComGameState VisualizeGameState, out VisualizationActionMetadata ActionMetadata, const name EffectApplyResult) { local X2Action_PlaySoundAndFlyOver SoundAndFlyOver; local X2AbilityTemplate AbilityTemplate; local XComGameStateContext_Ability Context; local AbilityInputContext AbilityContext; local EWidgetColor MessageColor; local XComGameState_Unit SourceUnit; local bool bGoodAbility; Context = XComGameStateContext_Ability(VisualizeGameState.GetContext()); AbilityContext = Context.InputContext; AbilityTemplate = class'XComGameState_Ability'.static.GetMyTemplateManager().FindAbilityTemplate(AbilityContext.AbilityTemplateName); SourceUnit = XComGameState_Unit(`XCOMHISTORY.GetGameStateForObjectID(AbilityContext.SourceObject.ObjectID)); bGoodAbility = SourceUnit.IsFriendlyToLocalPlayer(); MessageColor = bGoodAbility ? eColor_Good : eColor_Bad; if (EffectApplyResult == 'AA_Success' && XGUnit(ActionMetadata.VisualizeActor).IsAlive()) { SoundAndFlyOver = X2Action_PlaySoundAndFlyOver(class'X2Action_PlaySoundAndFlyOver'.static.AddToVisualizationTree(ActionMetadata, VisualizeGameState.GetContext(), false, ActionMetadata.LastActionAdded)); SoundAndFlyOver.SetSoundAndFlyOverParameters(None, AbilityTemplate.LocFlyOverText, '', MessageColor, AbilityTemplate.IconImage); } } // This is an implementation detail. We replace X2DataSet.CreateTemplatesEvent() in order to add // extra templates that come from AddSecondaryAbility() calls. static event array<X2DataTemplate> CreateTemplatesEvent() { local array<X2DataTemplate> BaseTemplates, NewTemplates; local X2DataTemplate CurrentBaseTemplate; local int Index; BaseTemplates = CreateTemplates(); for (Index = 0; Index < default.ExtraTemplates.Length; ++Index) BaseTemplates.AddItem(default.ExtraTemplates[Index]); for( Index = 0; Index < BaseTemplates.Length; ++Index ) { CurrentBaseTemplate = BaseTemplates[Index]; CurrentBaseTemplate.ClassThatCreatedUs = default.Class; if( default.bShouldCreateDifficultyVariants ) { CurrentBaseTemplate.bShouldCreateDifficultyVariants = true; } if( CurrentBaseTemplate.bShouldCreateDifficultyVariants ) { CurrentBaseTemplate.CreateDifficultyVariants(NewTemplates); } else { NewTemplates.AddItem(CurrentBaseTemplate); } } return NewTemplates; } defaultproperties { Begin Object Class=XMBCondition_CoverType Name=DefaultFullCoverCondition AllowedCoverTypes[0] = CT_Standing End Object FullCoverCondition = DefaultFullCoverCondition Begin Object Class=XMBCondition_CoverType Name=DefaultHalfCoverCondition AllowedCoverTypes[0] = CT_MidLevel End Object HalfCoverCondition = DefaultHalfCoverCondition Begin Object Class=XMBCondition_CoverType Name=DefaultNoCoverCondition AllowedCoverTypes[0] = CT_None End Object NoCoverCondition = DefaultNoCoverCondition Begin Object Class=XMBCondition_CoverType Name=DefaultFlankedCondition AllowedCoverTypes[0] = CT_None bRequireCanTakeCover = true End Object FlankedCondition = DefaultFlankedCondition Begin Object Class=XMBCondition_HeightAdvantage Name=DefaultHeightAdvantageCondition bRequireHeightAdvantage = true End Object HeightAdvantageCondition = DefaultHeightAdvantageCondition Begin Object Class=XMBCondition_HeightAdvantage Name=DefaultHeightDisadvantageCondition bRequireHeightDisadvantage = true End Object HeightDisadvantageCondition = DefaultHeightDisadvantageCondition Begin Object Class=XMBCondition_ReactionFire Name=DefaultReactionFireCondition End Object ReactionFireCondition = DefaultReactionFireCondition Begin Object Class=XMBCondition_Dead Name=DefaultDeadCondition End Object DeadCondition = DefaultDeadCondition Begin Object Class=XMBCondition_AbilityHitResult Name=DefaultHitCondition bRequireHit = true End Object HitCondition = DefaultHitCondition Begin Object Class=XMBCondition_AbilityHitResult Name=DefaultMissCondition bRequireMiss = true End Object MissCondition = DefaultMissCondition Begin Object Class=XMBCondition_AbilityHitResult Name=DefaultCritCondition IncludeHitResults[0] = eHit_Crit End Object CritCondition = DefaultCritCondition Begin Object Class=XMBCondition_AbilityHitResult Name=DefaultGrazeCondition IncludeHitResults[0] = eHit_Graze End Object GrazeCondition = DefaultGrazeCondition Begin Object Class=XMBCondition_MatchingWeapon Name=DefaultMatchingWeaponCondition End Object MatchingWeaponCondition = DefaultMatchingWeaponCondition Begin Object Class=XMBCondition_AbilityProperty Name=DefaultMeleeCondition bRequireMelee = true End Object MeleeCondition = DefaultMeleeCondition Begin Object Class=XMBCondition_AbilityProperty Name=DefaultRangedCondition bExcludeMelee = true End Object RangedCondition = DefaultRangedCondition Begin Object Class=X2Condition_UnitProperty Name=DefaultLivingFriendlyTargetProperty ExcludeAlive=false ExcludeDead=true ExcludeFriendlyToSource=false ExcludeHostileToSource=true RequireSquadmates=true FailOnNonUnits=true End Object LivingFriendlyTargetProperty = DefaultLivingFriendlyTargetProperty AUTO_PRIORITY = -1 }
1
0.851169
1
0.851169
game-dev
MEDIA
0.717589
game-dev
0.93696
1
0.93696
magefree/mage
3,305
Mage.Sets/src/mage/cards/g/GeneralKudroOfDrannith.java
package mage.cards.g; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldThisOrAnotherTriggeredAbility; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.effects.common.ExileTargetEffect; import mage.abilities.effects.common.continuous.BoostControlledEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.FilterCard; import mage.filter.FilterPermanent; import mage.filter.common.FilterControlledPermanent; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.PowerPredicate; import mage.target.TargetPermanent; import mage.target.common.TargetCardInOpponentsGraveyard; import mage.target.common.TargetControlledPermanent; import java.util.UUID; /** * @author TheElk801 */ public final class GeneralKudroOfDrannith extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent(SubType.HUMAN, "Humans"); private static final FilterPermanent filter2 = new FilterPermanent(SubType.HUMAN, "Human"); private static final FilterCard filter3 = new FilterCard("card from an opponent's graveyard"); private static final FilterControlledPermanent filter4 = new FilterControlledPermanent(SubType.HUMAN, "Humans"); private static final FilterCreaturePermanent filter5 = new FilterCreaturePermanent("creature with power 4 or greater"); static { filter5.add(new PowerPredicate(ComparisonType.MORE_THAN, 3)); } public GeneralKudroOfDrannith(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}{B}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SOLDIER); this.power = new MageInt(3); this.toughness = new MageInt(3); // Other Humans you control get +1/+1. this.addAbility(new SimpleStaticAbility(new BoostControlledEffect( 1, 1, Duration.WhileOnBattlefield, filter, true ))); // Whenever General Kudro of Drannith or another Human you control enters, exile target card from an opponent's graveyard. Ability ability = new EntersBattlefieldThisOrAnotherTriggeredAbility(new ExileTargetEffect(), filter2, false, true); ability.addTarget(new TargetCardInOpponentsGraveyard(filter3)); this.addAbility(ability); // {2}, Sacrifice two Humans: Destroy target creature with power 4 or greater. ability = new SimpleActivatedAbility(new DestroyTargetEffect(), new GenericManaCost(2)); ability.addCost(new SacrificeTargetCost(2, filter4)); ability.addTarget(new TargetPermanent(filter5)); this.addAbility(ability); } private GeneralKudroOfDrannith(final GeneralKudroOfDrannith card) { super(card); } @Override public GeneralKudroOfDrannith copy() { return new GeneralKudroOfDrannith(this); } }
1
0.963971
1
0.963971
game-dev
MEDIA
0.96238
game-dev
0.989131
1
0.989131
Sigma-Skidder-Team/SigmaRemap
6,778
src/main/java/mapped/Class2230.java
package mapped; import com.google.common.collect.Lists; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import it.unimi.dsi.fastutil.objects.ObjectSet; import net.minecraft.block.*; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.state.properties.ChestType; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.util.palette.UpgradeData; import net.minecraft.world.IWorld; import java.util.List; public enum Class2230 implements Class2234 { field14618( Blocks.OBSERVER, Blocks.NETHER_PORTAL, Blocks.WHITE_CONCRETE_POWDER, Blocks.ORANGE_CONCRETE_POWDER, Blocks.MAGENTA_CONCRETE_POWDER, Blocks.LIGHT_BLUE_CONCRETE_POWDER, Blocks.YELLOW_CONCRETE_POWDER, Blocks.LIME_CONCRETE_POWDER, Blocks.PINK_CONCRETE_POWDER, Blocks.GRAY_CONCRETE_POWDER, Blocks.LIGHT_GRAY_CONCRETE_POWDER, Blocks.CYAN_CONCRETE_POWDER, Blocks.PURPLE_CONCRETE_POWDER, Blocks.BLUE_CONCRETE_POWDER, Blocks.BROWN_CONCRETE_POWDER, Blocks.GREEN_CONCRETE_POWDER, Blocks.RED_CONCRETE_POWDER, Blocks.BLACK_CONCRETE_POWDER, Blocks.ANVIL, Blocks.CHIPPED_ANVIL, Blocks.DAMAGED_ANVIL, Blocks.DRAGON_EGG, Blocks.GRAVEL, Blocks.SAND, Blocks.RED_SAND, Blocks.OAK_SIGN, Blocks.SPRUCE_SIGN, Blocks.BIRCH_SIGN, Blocks.ACACIA_SIGN, Blocks.JUNGLE_SIGN, Blocks.DARK_OAK_SIGN, Blocks.OAK_WALL_SIGN, Blocks.SPRUCE_WALL_SIGN, Blocks.BIRCH_WALL_SIGN, Blocks.ACACIA_WALL_SIGN, Blocks.JUNGLE_WALL_SIGN, Blocks.DARK_OAK_WALL_SIGN ) { @Override public BlockState method8970(BlockState var1, Direction var2, BlockState var3, IWorld var4, BlockPos var5, BlockPos var6) { return var1; } }, field14619() { @Override public BlockState method8970(BlockState var1, Direction var2, BlockState var3, IWorld var4, BlockPos var5, BlockPos var6) { return var1.method23439(var2, var4.getBlockState(var6), var4, var5, var6); } }, field14620(Blocks.CHEST, Blocks.TRAPPED_CHEST) { @Override public BlockState method8970(BlockState var1, Direction var2, BlockState var3, IWorld var4, BlockPos var5, BlockPos var6) { if (var3.isIn(var1.getBlock()) && var2.getAxis().isHorizontal() && var1.get(ChestBlock.TYPE) == ChestType.field379 && var3.get(ChestBlock.TYPE) == ChestType.field379) { Direction var9 = var1.get(ChestBlock.field18865); if (var2.getAxis() != var9.getAxis() && var9 == var3.get(ChestBlock.field18865)) { ChestType var10 = var2 != var9.rotateY() ? ChestType.RIGHT : ChestType.LEFT; var4.setBlockState(var6, var3.with(ChestBlock.TYPE, var10.method308()), 18); if (var9 == Direction.NORTH || var9 == Direction.EAST ) { TileEntity var11 = var4.getTileEntity(var5); TileEntity var12 = var4.getTileEntity(var6); if (var11 instanceof ChestTileEntity && var12 instanceof ChestTileEntity) { ChestTileEntity.swapContents((ChestTileEntity)var11, (ChestTileEntity)var12); } } return var1.with(ChestBlock.TYPE, var10); } } return var1; } }, field14621(true, Blocks.ACACIA_LEAVES, Blocks.BIRCH_LEAVES, Blocks.DARK_OAK_LEAVES, Blocks.JUNGLE_LEAVES, Blocks.OAK_LEAVES, Blocks.SPRUCE_LEAVES) { private final ThreadLocal<List<ObjectSet<BlockPos>>> field14625 = ThreadLocal.withInitial(() -> Lists.newArrayListWithCapacity(7)); @Override public BlockState method8970(BlockState var1, Direction var2, BlockState var3, IWorld var4, BlockPos var5, BlockPos var6) { BlockState var9 = var1.method23439(var2, var4.getBlockState(var6), var4, var5, var6); if (var1 != var9) { int var10 = var9.get(BlockStateProperties.DISTANCE); List<ObjectSet<BlockPos>> var11 = this.field14625.get(); if (var11.isEmpty()) { for(int var12 = 0; var12 < 7; ++var12) { var11.add(new ObjectOpenHashSet<>()); } } var11.get(var10).add(var5.toImmutable()); } return var1; } @Override public void method8971(IWorld var1) { BlockPos.Mutable var4 = new BlockPos.Mutable(); List<ObjectSet<BlockPos>> var5 = this.field14625.get(); for(int var6 = 2; var6 < var5.size(); ++var6) { int var7 = var6 - 1; ObjectSet<BlockPos> var8 = var5.get(var7); ObjectSet<BlockPos> var9 = var5.get(var6); for (BlockPos var11 : var8) { BlockState var12 = var1.getBlockState(var11); if (var12.get(BlockStateProperties.DISTANCE) >= var7) { var1.setBlockState(var11, var12.with(BlockStateProperties.DISTANCE, Integer.valueOf(var7)), 18); if (var6 != 7) { for (Direction var16 : field14623) { var4.method8377(var11, var16); BlockState var17 = var1.getBlockState(var4); if (var17.hasProperty(BlockStateProperties.DISTANCE) && var12.get(BlockStateProperties.DISTANCE) > var6) { var9.add(var4.toImmutable()); } } } } } } var5.clear(); } }, field14622(Blocks.MELON_STEM, Blocks.PUMPKIN_STEM) { @Override public BlockState method8970(BlockState var1, Direction var2, BlockState var3, IWorld var4, BlockPos var5, BlockPos var6) { if (var1.get(Class3486.field19347) == 7) { Class3462 var9 = ((Class3486)var1.getBlock()).method12185(); if (var3.isIn(var9)) { return var9.method12147().getDefaultState().with(HorizontalBlock.HORIZONTAL_FACING, var2); } } return var1; } }; public static final Direction[] field14623 = Direction.values(); private static final Class2230[] field14624 = new Class2230[]{field14618, field14619, field14620, field14621, field14622}; private Class2230(Block... var3) { this(false, var3); } private Class2230(boolean var3, Block... var4) { for (Block var10 : var4) { UpgradeData.method32610().put(var10, this); } if (var3) { UpgradeData.method32611().add(this); } } }
1
0.71398
1
0.71398
game-dev
MEDIA
0.947666
game-dev
0.734441
1
0.734441
dboglobal/DBOGLOBAL
1,920
DboServer/Server/GameServer/GameData.cpp
#include "stdafx.h" #include "GameData.h" #include "GameServer.h" CGameData::CGameData() { Init(); } CGameData::~CGameData() { Destroy(); } bool CGameData::Create(DWORD dwCodePage) { CGameServer* app = (CGameServer*)g_pApp; NTL_PRINT(PRINT_APP, "Create Table Container"); if (!m_tableContainer.CreateTableContainer(app->m_config.LoadTableFormat, (char*)app->m_config.TablePath.c_str())) { ERR_LOG(LOG_GENERAL, "CreateTableContainer == false"); Destroy(); return false; } if (app->IsDojoChannel() == false) //check if not dojo channel { NTL_PRINT(PRINT_APP, "Init Play Script Manager"); if (!m_playScriptManager.Create(app->m_config.strPlayScriptPath.c_str(), CControlScriptManager::FILE_SCRIPT, "sps", "spe", "spc")) { ERR_LOG(LOG_GENERAL, "m_playScriptManager.Create == false"); return false; } NTL_PRINT(PRINT_APP, "Init AI Script Manager"); if (!m_AiScriptManager.Create(app->m_config.strAIScriptPath.c_str(), CControlScriptManager::FILE_SCRIPT, "ais", "aie", "aic")) { ERR_LOG(LOG_GENERAL, "m_AiScriptManager.Create == false"); return false; } NTL_PRINT(PRINT_APP, "Init Time Quest Script Manager"); if (!m_timeQuestScriptManager.Create(app->m_config.strTimeQuestScriptPath.c_str(), CControlScriptManager::FILE_SCRIPT, "tqs", "tqe", "tqc")) { ERR_LOG(LOG_GENERAL, "m_timeQuestScriptManager.Create == false"); return false; } NTL_PRINT(PRINT_APP, "Init World Play Script Manager"); if (!m_WorldPlayScriptManager.Create(app->m_config.strWorldPlayScriptPath.c_str(), CControlScriptManager::FILE_SCRIPT, "wps", "wpe", "wpc")) { ERR_LOG(LOG_GENERAL, "m_WorldPlayScriptManager.Create == false"); } } return true; } void CGameData::Destroy() { m_tableContainer.Destroy(); m_playScriptManager.Destroy(); m_AiScriptManager.Destroy(); m_timeQuestScriptManager.Destroy(); m_WorldPlayScriptManager.Destroy(); } void CGameData::Init() { }
1
0.835214
1
0.835214
game-dev
MEDIA
0.622121
game-dev
0.837047
1
0.837047
4drian3d/SignedVelocity
2,572
velocity/src/main/java/io/github/_4drian3d/signedvelocity/velocity/listener/PostPlayerCommandListener.java
package io.github._4drian3d.signedvelocity.velocity.listener; import com.google.inject.Inject; import com.velocitypowered.api.command.CommandResult; import com.velocitypowered.api.event.EventManager; import com.velocitypowered.api.event.EventTask; import com.velocitypowered.api.event.command.PostCommandInvocationEvent; import com.velocitypowered.api.proxy.Player; import io.github._4drian3d.signedvelocity.shared.types.QueueType; import io.github._4drian3d.signedvelocity.velocity.SignedVelocity; import io.github._4drian3d.signedvelocity.velocity.cache.ModificationCache; import org.jetbrains.annotations.NotNull; public final class PostPlayerCommandListener implements Listener<@NotNull PostCommandInvocationEvent> { @Inject private SignedVelocity plugin; @Inject private EventManager eventManager; @Override public void register() { this.eventManager.register(plugin, PostCommandInvocationEvent.class, Short.MIN_VALUE, this); } @Override public EventTask executeAsync(PostCommandInvocationEvent event) { return EventTask.async(() -> { // If the command was executed in the CommandDispatcher // but was configured to be re-executed on the backend server, // the result is sent for processing immediately. if (event.getResult() == CommandResult.FORWARDED && event.getCommandSource() instanceof Player player) { plugin.logDebug("Post Command Execution | Forwarded Command: " + event.getCommand()); final String playerUUID = player.getUniqueId().toString(); final ModificationCache cache = plugin.modificationCache().getIfPresent(playerUUID); plugin.modificationCache().invalidate(playerUUID); player.getCurrentServer() .ifPresent(connection -> { plugin.logDebug("Post Command Execution | Server Available"); if (cache != null && cache.modifiedCommand().equals(event.getCommand())) { plugin.logDebug("Post Command Execution | Modified Command"); this.sendModifiedData(player, connection, QueueType.COMMAND, event.getCommand()); } else { plugin.logDebug("Post Command Execution | Non modified command"); sendAllowedData(player, connection, QueueType.COMMAND); } }); } }); } }
1
0.846944
1
0.846944
game-dev
MEDIA
0.669929
game-dev
0.95215
1
0.95215
LandSandBoat/server
1,213
scripts/items/plate_of_friture_de_la_misareaux.lua
----------------------------------- -- ID: 5159 -- Item: plate_of_friture_de_la_misareaux -- Food Effect: 240Min, All Races ----------------------------------- -- Dexterity 3 -- Vitality 3 -- Mind -3 -- Defense 5 -- Ranged ATT % 7 -- Ranged ATT Cap 15 ----------------------------------- ---@type TItemFood local itemObject = {} itemObject.onItemCheck = function(target, item, param, caster) return xi.itemUtils.foodOnItemCheck(target, xi.foodType.BASIC) end itemObject.onItemUse = function(target, user, item, action) target:addStatusEffect(xi.effect.FOOD, 0, 0, 14400, 0, 0, 0, xi.effectSourceType.FOOD, item:getID(), user:getID()) end itemObject.onEffectGain = function(target, effect) target:addMod(xi.mod.DEX, 3) target:addMod(xi.mod.VIT, 3) target:addMod(xi.mod.MND, -3) target:addMod(xi.mod.DEF, 5) target:addMod(xi.mod.FOOD_RATTP, 7) target:addMod(xi.mod.FOOD_RATT_CAP, 15) end itemObject.onEffectLose = function(target, effect) target:delMod(xi.mod.DEX, 3) target:delMod(xi.mod.VIT, 3) target:delMod(xi.mod.MND, -3) target:delMod(xi.mod.DEF, 5) target:delMod(xi.mod.FOOD_RATTP, 7) target:delMod(xi.mod.FOOD_RATT_CAP, 15) end return itemObject
1
0.528921
1
0.528921
game-dev
MEDIA
0.989618
game-dev
0.591395
1
0.591395
SamboyCoding/Cpp2IL
5,236
Cpp2IL.Core/Cpp2IlApi.cs
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using AssetRipper.Primitives; using Cpp2IL.Core.Exceptions; using Cpp2IL.Core.Logging; using Cpp2IL.Core.Model.Contexts; using Cpp2IL.Core.Utils; using Cpp2IL.Core.Utils.AsmResolver; using LibCpp2IL; using LibCpp2IL.Logging; [assembly: InternalsVisibleTo("Cpp2IL.Core.Tests")] namespace Cpp2IL.Core; public static class Cpp2IlApi { public static ApplicationAnalysisContext? CurrentAppContext; public static Cpp2IlRuntimeArgs? RuntimeOptions; internal static bool LowMemoryMode => RuntimeOptions?.LowMemoryMode ?? false; [RequiresUnreferencedCode("Plugins are loaded dynamically.")] public static void Init(string pluginsDir = "Plugins") { Cpp2IlPluginManager.LoadFromDirectory(Path.Combine(Environment.CurrentDirectory, pluginsDir)); Cpp2IlPluginManager.InitAll(); } public static UnityVersion DetermineUnityVersion(string? unityPlayerPath, string? gameDataPath) => LibCpp2IlMain.DetermineUnityVersion(unityPlayerPath, gameDataPath); public static UnityVersion GetVersionFromGlobalGameManagers(byte[] ggmBytes) => LibCpp2IlMain.GetVersionFromGlobalGameManagers(ggmBytes); public static UnityVersion GetVersionFromDataUnity3D(Stream fileStream) => LibCpp2IlMain.GetVersionFromDataUnity3D(fileStream); public static void ConfigureLib(bool allowUserToInputAddresses) { //Set this flag from the options LibCpp2IlMain.Settings.AllowManualMetadataAndCodeRegInput = allowUserToInputAddresses; //We have to have this on, despite the cost, because we need them for attribute restoration LibCpp2IlMain.Settings.DisableMethodPointerMapping = false; LibLogger.Writer = new LibLogWriter(); } [MemberNotNull(nameof(CurrentAppContext))] public static void InitializeLibCpp2Il(string assemblyPath, string metadataPath, UnityVersion unityVersion, bool allowUserToInputAddresses = false) { if (IsLibInitialized()) ResetInternalState(); ConfigureLib(allowUserToInputAddresses); #if !DEBUG try { #endif if (!LibCpp2IlMain.LoadFromFile(assemblyPath, metadataPath, unityVersion)) throw new Exception("Initialization with LibCpp2Il failed"); #if !DEBUG } catch (Exception e) { throw new LibCpp2ILInitializationException("Fatal Exception initializing LibCpp2IL!", e); } #endif OnLibInitialized(); } [MemberNotNull(nameof(CurrentAppContext))] public static void InitializeLibCpp2Il(byte[] assemblyData, byte[] metadataData, UnityVersion unityVersion, bool allowUserToInputAddresses = false) { if (IsLibInitialized()) ResetInternalState(); ConfigureLib(allowUserToInputAddresses); try { if (!LibCpp2IlMain.Initialize(assemblyData, metadataData, unityVersion)) throw new Exception("Initialization with LibCpp2Il failed"); } catch (Exception e) { throw new LibCpp2ILInitializationException("Fatal Exception initializing LibCpp2IL!", e); } OnLibInitialized(); } [MemberNotNull(nameof(CurrentAppContext))] private static void OnLibInitialized() { MiscUtils.Init(); LibCpp2IlMain.Binary!.AllCustomAttributeGenerators.ToList() .ForEach(ptr => SharedState.AttributeGeneratorStarts.Add(ptr)); var start = DateTime.Now; Logger.InfoNewline("Creating application model..."); CurrentAppContext = new(LibCpp2IlMain.Binary, LibCpp2IlMain.TheMetadata!); Logger.InfoNewline($"Application model created in {(DateTime.Now - start).TotalMilliseconds}ms"); } public static void ResetInternalState() { SharedState.Clear(); MiscUtils.Reset(); AsmResolverUtils.Reset(); LibCpp2IlMain.Reset(); CurrentAppContext = null; } // public static void PopulateConcreteImplementations() // { // CheckLibInitialized(); // // Logger.InfoNewline("Populating Concrete Implementation Table..."); // // foreach (var def in LibCpp2IlMain.TheMetadata!.typeDefs) // { // if (def.IsAbstract) // continue; // // var baseTypeReflectionData = def.BaseType; // while (baseTypeReflectionData != null) // { // if (baseTypeReflectionData.baseType == null) // break; // // if (baseTypeReflectionData.isType && baseTypeReflectionData.baseType.IsAbstract && !SharedState.ConcreteImplementations.ContainsKey(baseTypeReflectionData.baseType)) // SharedState.ConcreteImplementations[baseTypeReflectionData.baseType] = def; // // baseTypeReflectionData = baseTypeReflectionData.baseType.BaseType; // } // } // } private static bool IsLibInitialized() { return LibCpp2IlMain.Binary != null && LibCpp2IlMain.TheMetadata != null; } }
1
0.818117
1
0.818117
game-dev
MEDIA
0.624498
game-dev
0.832843
1
0.832843
hellyguo/rust_java_samples
2,113
sample/src/samples/s011_thread_ctl2.rs
use jni::objects::JClass; use jni::signature::{Primitive, ReturnType}; use jni::sys::jboolean; use jni::JNIEnv; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; use std::thread; use std::time::Duration; static ACTIVE: Mutex<AtomicBool> = Mutex::new(AtomicBool::new(true)); #[no_mangle] pub extern "system" fn Java_sample_s011_RunInRustThread2_callAsync<'local>( env: JNIEnv<'local>, // This is the class that owns our static method. It's not going to be used, // but still must be present to match the expected signature of a static // native method. _class: JClass<'local>, ) { let vm = env.get_java_vm().expect("get jvm"); thread::spawn(move || { let mut env = vm.attach_current_thread().expect("attach"); let class = env.find_class("sample/s011/LogCaller").expect("find class"); let method_id = env .get_static_method_id(&class, "hello", "()V") .expect("get method"); loop { if let Ok(active) = ACTIVE.lock() { if active.load(Ordering::SeqCst) { let _ = unsafe { env.call_static_method_unchecked( &class, &method_id, ReturnType::Primitive(Primitive::Void), &[], ) }; } else { println!("quit"); break; } } thread::sleep(Duration::from_millis(50)); } }); } #[no_mangle] pub extern "system" fn Java_sample_s011_RunInRustThread2_stopExecute<'local>( _env: JNIEnv<'local>, // This is the class that owns our static method. It's not going to be used, // but still must be present to match the expected signature of a static // native method. _class: JClass<'local>, ) -> jboolean { if let Ok(active) = ACTIVE.lock() { active.store(false, Ordering::SeqCst); 1 } else { println!("failed to lock active"); 0 } }
1
0.816405
1
0.816405
game-dev
MEDIA
0.136378
game-dev
0.88181
1
0.88181
hieki-chan/Supermarket-Simulator-Prototype
8,083
Library/PackageCache/com.unity.visualscripting@1.9.4/Runtime/VisualScripting.Flow/Framework/Time/Timer.cs
using System; using UnityEngine; namespace Unity.VisualScripting { /// <summary> /// Runs a timer and outputs elapsed and remaining measurements. /// </summary> [UnitCategory("Time")] [UnitOrder(7)] public sealed class Timer : Unit, IGraphElementWithData, IGraphEventListener { public sealed class Data : IGraphElementData { public float elapsed; public float duration; public bool active; public bool paused; public bool unscaled; public Delegate update; public bool isListening; } /// <summary> /// The moment at which to start the timer. /// If the timer is already started, this will reset it. /// If the timer is paused, this will resume it. /// </summary> [DoNotSerialize] public ControlInput start { get; private set; } /// <summary> /// Trigger to pause the timer. /// </summary> [DoNotSerialize] public ControlInput pause { get; private set; } /// <summary> /// Trigger to resume the timer. /// </summary> [DoNotSerialize] public ControlInput resume { get; private set; } /// <summary> /// Trigger to toggle the timer. /// If it is idle, it will start. /// If it is active, it will pause. /// If it is paused, it will resume. /// </summary> [DoNotSerialize] public ControlInput toggle { get; private set; } /// <summary> /// The total duration of the timer. /// </summary> [DoNotSerialize] public ValueInput duration { get; private set; } /// <summary> /// Whether to ignore the time scale. /// </summary> [DoNotSerialize] [PortLabel("Unscaled")] public ValueInput unscaledTime { get; private set; } /// <summary> /// Called when the timer is started.co /// </summary> [DoNotSerialize] public ControlOutput started { get; private set; } /// <summary> /// Called each frame while the timer is active. /// </summary> [DoNotSerialize] public ControlOutput tick { get; private set; } /// <summary> /// Called when the timer completes. /// </summary> [DoNotSerialize] public ControlOutput completed { get; private set; } /// <summary> /// The number of seconds elapsed since the timer started. /// </summary> [DoNotSerialize] [PortLabel("Elapsed")] public ValueOutput elapsedSeconds { get; private set; } /// <summary> /// The proportion of the duration that has elapsed (0-1). /// </summary> [DoNotSerialize] [PortLabel("Elapsed %")] public ValueOutput elapsedRatio { get; private set; } /// <summary> /// The number of seconds remaining until the timer is elapsed. /// </summary> [DoNotSerialize] [PortLabel("Remaining")] public ValueOutput remainingSeconds { get; private set; } /// <summary> /// The proportion of the duration remaining until the timer is elapsed (0-1). /// </summary> [DoNotSerialize] [PortLabel("Remaining %")] public ValueOutput remainingRatio { get; private set; } protected override void Definition() { isControlRoot = true; start = ControlInput(nameof(start), Start); pause = ControlInput(nameof(pause), Pause); resume = ControlInput(nameof(resume), Resume); toggle = ControlInput(nameof(toggle), Toggle); duration = ValueInput(nameof(duration), 1f); unscaledTime = ValueInput(nameof(unscaledTime), false); started = ControlOutput(nameof(started)); tick = ControlOutput(nameof(tick)); completed = ControlOutput(nameof(completed)); elapsedSeconds = ValueOutput<float>(nameof(elapsedSeconds)); elapsedRatio = ValueOutput<float>(nameof(elapsedRatio)); remainingSeconds = ValueOutput<float>(nameof(remainingSeconds)); remainingRatio = ValueOutput<float>(nameof(remainingRatio)); } public IGraphElementData CreateData() { return new Data(); } public void StartListening(GraphStack stack) { var data = stack.GetElementData<Data>(this); if (data.isListening) { return; } var reference = stack.ToReference(); var hook = new EventHook(EventHooks.Update, stack.machine); Action<EmptyEventArgs> update = args => TriggerUpdate(reference); EventBus.Register(hook, update); data.update = update; data.isListening = true; } public void StopListening(GraphStack stack) { var data = stack.GetElementData<Data>(this); if (!data.isListening) { return; } var hook = new EventHook(EventHooks.Update, stack.machine); EventBus.Unregister(hook, data.update); stack.ClearReference(); data.update = null; data.isListening = false; } public bool IsListening(GraphPointer pointer) { return pointer.GetElementData<Data>(this).isListening; } private void TriggerUpdate(GraphReference reference) { using (var flow = Flow.New(reference)) { Update(flow); } } private ControlOutput Start(Flow flow) { var data = flow.stack.GetElementData<Data>(this); data.elapsed = 0; data.duration = flow.GetValue<float>(duration); data.active = true; data.paused = false; data.unscaled = flow.GetValue<bool>(unscaledTime); AssignMetrics(flow, data); return started; } private ControlOutput Pause(Flow flow) { var data = flow.stack.GetElementData<Data>(this); data.paused = true; return null; } private ControlOutput Resume(Flow flow) { var data = flow.stack.GetElementData<Data>(this); data.paused = false; return null; } private ControlOutput Toggle(Flow flow) { var data = flow.stack.GetElementData<Data>(this); if (!data.active) { return Start(flow); } else { data.paused = !data.paused; return null; } } private void AssignMetrics(Flow flow, Data data) { flow.SetValue(elapsedSeconds, data.elapsed); flow.SetValue(elapsedRatio, Mathf.Clamp01(data.elapsed / data.duration)); flow.SetValue(remainingSeconds, Mathf.Max(0, data.duration - data.elapsed)); flow.SetValue(remainingRatio, Mathf.Clamp01((data.duration - data.elapsed) / data.duration)); } public void Update(Flow flow) { var data = flow.stack.GetElementData<Data>(this); if (!data.active || data.paused) { return; } data.elapsed += data.unscaled ? Time.unscaledDeltaTime : Time.deltaTime; data.elapsed = Mathf.Min(data.elapsed, data.duration); AssignMetrics(flow, data); var stack = flow.PreserveStack(); flow.Invoke(tick); if (data.elapsed >= data.duration) { data.active = false; flow.RestoreStack(stack); flow.Invoke(completed); } flow.DisposePreservedStack(stack); } } }
1
0.900697
1
0.900697
game-dev
MEDIA
0.335092
game-dev
0.956832
1
0.956832
ow-mods/owml
2,208
src/OWML.ModHelper.Menus/ModMainMenu.cs
using System.Linq; using OWML.Common; using OWML.Common.Menus; using OWML.Utils; using UnityEngine; using UnityEngine.UI; namespace OWML.ModHelper.Menus { public class ModMainMenu : ModMenu, IModMainMenu { public IModTabbedMenu OptionsMenu { get; } public IModButton ResumeExpeditionButton { get; private set; } public IModButton NewExpeditionButton { get; private set; } public IModButton OptionsButton { get; private set; } public IModButton ViewCreditsButton { get; private set; } public IModButton SwitchProfileButton { get; private set; } public IModButton QuitButton { get; private set; } private TitleAnimationController _anim; private TitleScreenManager _titleManager; public ModMainMenu(IModTabbedMenu optionsMenu, IModConsole console) : base(console) => OptionsMenu = optionsMenu; public void Initialize(TitleScreenManager titleScreenManager) { _titleManager = titleScreenManager; _anim = titleScreenManager.GetComponent<TitleAnimationController>(); var menu = titleScreenManager.GetValue<Menu>("_mainMenu"); Initialize(menu); ResumeExpeditionButton = GetTitleButton("Button-ResumeGame"); NewExpeditionButton = GetTitleButton("Button-NewGame"); OptionsButton = GetTitleButton("Button-Options"); ViewCreditsButton = GetTitleButton("Button-Credits"); SwitchProfileButton = GetTitleButton("Button-Profile"); QuitButton = GetTitleButton("Button-Exit"); var tabbedMenu = titleScreenManager.GetValue<TabbedMenu>("_optionsMenu"); OptionsMenu.Initialize(tabbedMenu, 0); InvokeOnInit(); } public override IModButtonBase AddButton(IModButtonBase button, int index) { var modButton = base.AddButton(button, index); var fadeControllers = Buttons.OrderBy(x => x.Index).Select(x => new CanvasGroupFadeController { group = x.Button.GetComponent<CanvasGroup>() }); _anim.SetValue("_buttonFadeControllers", fadeControllers.ToArray()); if (button is ModTitleButton titleButton) { var texts = _titleManager.GetValue<Text[]>("_mainMenuTextFields").ToList(); texts.Add(titleButton.Text); _titleManager.SetValue("_mainMenuTextFields", texts.ToArray()); } return modButton; } } }
1
0.713698
1
0.713698
game-dev
MEDIA
0.695932
game-dev
0.658444
1
0.658444