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
mcclure/bitbucket-backup
7,217
repos/whoop/contents/source/cpVect.h
#ifndef CP_VECT_H #define CP_VECT_H /* Copyright (c) 2007 Scott Lembcke * * 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. */ // Special for polycode typedef Number cpFloat; #define CP_USE_DOUBLES 1 #if CP_USE_DOUBLES //typedef double cpFloat; #define cpfsqrt sqrt #define cpfsin sin #define cpfcos cos #define cpfacos acos #define cpfatan2 atan2 #define cpfmod fmod #define cpfexp exp #define cpfpow pow #define cpffloor floor #define cpfceil ceil #else //typedef float cpFloat; #define cpfsqrt sqrtf #define cpfsin sinf #define cpfcos cosf #define cpfacos acosf #define cpfatan2 atan2f #define cpfmod fmodf #define cpfexp expf #define cpfpow powf #define cpffloor floorf #define cpfceil ceilf #endif static inline cpFloat cpfmax(cpFloat a, cpFloat b) { return (a > b) ? a : b; } static inline cpFloat cpfmin(cpFloat a, cpFloat b) { return (a < b) ? a : b; } static inline cpFloat cpfabs(cpFloat n) { return (n < 0) ? -n : n; } static inline cpFloat cpfclamp(cpFloat f, cpFloat min, cpFloat max) { return cpfmin(cpfmax(f, min), max); } static inline cpFloat cpflerp(cpFloat f1, cpFloat f2, cpFloat t) { return f1*(1.0f - t) + f2*t; } static inline cpFloat cpflerpconst(cpFloat f1, cpFloat f2, cpFloat d) { return f1 + cpfclamp(f2 - f1, -d, d); } typedef struct cpVect{cpFloat x,y;} cpVect; #ifdef CP_BOOL_TYPE typedef CP_BOOL_TYPE cpBool; #else typedef int cpBool; #endif /// Constant for the zero vector. static const cpVect cpvzero = {0.0f,0.0f}; /// Convenience constructor for cpVect structs. static inline cpVect cpv(const cpFloat x, const cpFloat y) { cpVect v = {x, y}; return v; } static inline cpVect cpv(Polycode::Vector3 i) { cpVect v = {i.x, i.y}; return v; } // non-inlined functions /// Returns the length of v. cpFloat cpvlength(const cpVect v); /// Spherical linearly interpolate between v1 and v2. cpVect cpvslerp(const cpVect v1, const cpVect v2, const cpFloat t); /// Spherical linearly interpolate between v1 towards v2 by no more than angle a radians cpVect cpvslerpconst(const cpVect v1, const cpVect v2, const cpFloat a); /// Returns the unit length vector for the given angle (in radians). cpVect cpvforangle(const cpFloat a); /// Returns the angular direction v is pointing in (in radians). cpFloat cpvtoangle(const cpVect v); /** Returns a string representation of v. Intended mostly for debugging purposes and not production use. @attention The string points to a static local and is reset every time the function is called. If you want to print more than one vector you will have to split up your printing onto separate lines. */ char *cpvstr(const cpVect v); /// Check if two vectors are equal. (Be careful when comparing floating point numbers!) static inline cpBool cpveql(const cpVect v1, const cpVect v2) { return (v1.x == v2.x && v1.y == v2.y); } /// Add two vectors static inline cpVect cpvadd(const cpVect v1, const cpVect v2) { return cpv(v1.x + v2.x, v1.y + v2.y); } /// Negate a vector. static inline cpVect cpvneg(const cpVect v) { return cpv(-v.x, -v.y); } /// Subtract two vectors. static inline cpVect cpvsub(const cpVect v1, const cpVect v2) { return cpv(v1.x - v2.x, v1.y - v2.y); } /// Scalar multiplication. static inline cpVect cpvmult(const cpVect v, const cpFloat s) { return cpv(v.x*s, v.y*s); } /// Vector dot product. static inline cpFloat cpvdot(const cpVect v1, const cpVect v2) { return v1.x*v2.x + v1.y*v2.y; } /** 2D vector cross product analog. The cross product of 2D vectors results in a 3D vector with only a z component. This function returns the magnitude of the z value. */ static inline cpFloat cpvcross(const cpVect v1, const cpVect v2) { return v1.x*v2.y - v1.y*v2.x; } /// Returns a perpendicular vector. (90 degree rotation) static inline cpVect cpvperp(const cpVect v) { return cpv(-v.y, v.x); } /// Returns a perpendicular vector. (-90 degree rotation) static inline cpVect cpvrperp(const cpVect v) { return cpv(v.y, -v.x); } /// Returns the vector projection of v1 onto v2. static inline cpVect cpvproject(const cpVect v1, const cpVect v2) { return cpvmult(v2, cpvdot(v1, v2)/cpvdot(v2, v2)); } /// Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector. static inline cpVect cpvrotate(const cpVect v1, const cpVect v2) { return cpv(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x); } /// Inverse of cpvrotate(). static inline cpVect cpvunrotate(const cpVect v1, const cpVect v2) { return cpv(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y); } /// Returns the squared length of v. Faster than cpvlength() when you only need to compare lengths. static inline cpFloat cpvlengthsq(const cpVect v) { return cpvdot(v, v); } /// Linearly interpolate between v1 and v2. static inline cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t) { return cpvadd(cpvmult(v1, 1.0f - t), cpvmult(v2, t)); } /// Returns a normalized copy of v. static inline cpVect cpvnormalize(const cpVect v) { return cpvmult(v, 1.0f/cpvlength(v)); } /// Returns a normalized copy of v or cpvzero if v was already cpvzero. Protects against divide by zero errors. static inline cpVect cpvnormalize_safe(const cpVect v) { return (v.x == 0.0f && v.y == 0.0f ? cpvzero : cpvnormalize(v)); } /// Clamp v to length len. static inline cpVect cpvclamp(const cpVect v, const cpFloat len) { return (cpvdot(v,v) > len*len) ? cpvmult(cpvnormalize(v), len) : v; } /// Linearly interpolate between v1 towards v2 by distance d. static inline cpVect cpvlerpconst(cpVect v1, cpVect v2, cpFloat d) { return cpvadd(v1, cpvclamp(cpvsub(v2, v1), d)); } /// Returns the distance between v1 and v2. static inline cpFloat cpvdist(const cpVect v1, const cpVect v2) { return cpvlength(cpvsub(v1, v2)); } /// Returns the squared distance between v1 and v2. Faster than cpvdist() when you only need to compare distances. static inline cpFloat cpvdistsq(const cpVect v1, const cpVect v2) { return cpvlengthsq(cpvsub(v1, v2)); } /// Returns true if the distance between v1 and v2 is less than dist. static inline cpBool cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist) { return cpvdistsq(v1, v2) < dist*dist; } #endif // CP_RECT_H
0
0.668844
1
0.668844
game-dev
MEDIA
0.836531
game-dev
0.75824
1
0.75824
pdpdds/CGSF
5,414
Sample/FPSClient/FPSClient/Bullet.cpp
//----------------------------------------------------------------------------- // Bullet.h implementation. // Refer to the Bullet.h interface for more details. // // Programming a Multiplayer First Person Shooter in DirectX // Copyright (c) 2004 Vaughan Young //----------------------------------------------------------------------------- #include "FPSMain.h" //----------------------------------------------------------------------------- // The bullet class constructor. //----------------------------------------------------------------------------- Bullet::Bullet( SceneObject *owner, D3DXVECTOR3 translation, D3DXVECTOR3 direction, float velocity, float range, float damage ) { // Store the owner of the bullet. m_owner = owner; // Create a ray intersection result for the bullet. m_hitResult = new RayIntersectionResult; // Indicate that the bullet has not moved yet. m_totalDistance = 0.0f; // The bullet has not expired yet. m_expired = false; // Set all the properties of the bullet. m_translation = translation; m_direction = direction; m_velocity = velocity; m_range = range; m_damage = damage; } //----------------------------------------------------------------------------- // The bullet class destructor. //----------------------------------------------------------------------------- Bullet::~Bullet() { SAFE_DELETE( m_hitResult ); } //----------------------------------------------------------------------------- // Updates the bullet. //----------------------------------------------------------------------------- void Bullet::Update( float elapsed ) { // Clear the hit result. m_hitResult->material = NULL; m_hitResult->distance = 0.0f; m_hitResult->hitObject = NULL; // Cast a ray through the scene to see if the bullet might hit something. if( g_engine->GetSceneManager()->RayIntersectScene( m_hitResult, m_translation, m_direction, true, m_owner, true ) == true ) { // Ensure the hit distance is within the velocity of the bullet. if( m_hitResult->distance <= m_velocity * elapsed ) { // Ensure the bullet will not go beyond its range. m_totalDistance += m_hitResult->distance; if( m_totalDistance > m_range ) { // Clear the hit result. m_hitResult->material = NULL; m_hitResult->distance = 0.0f; m_hitResult->hitObject = NULL; // Indicate that the bullet has expired. m_expired = true; // Return now so that the collision isn't processed. return; } // The bullet has legally hit something, so expire it. m_expired = true; // Only the host is allowed to process bullet collision results. //if( g_engine->GetNetwork()->IsHost() == false ) //return; // Ensure the bullet hit an object, and not just part of the scene. if( m_hitResult->hitObject == NULL ) return; // Check if the bullet hit another player. if( m_hitResult->hitObject->GetType() == TYPE_PLAYER_OBJECT ) ( (PlayerObject*)m_hitResult->hitObject )->Hurt( m_damage, (PlayerObject*)m_owner ); return; } else { // Clear the hit result. m_hitResult->material = NULL; m_hitResult->distance = 0.0f; m_hitResult->hitObject = NULL; } } // Expire the bullet if it will move beyond its range. m_totalDistance += m_velocity * elapsed; if( m_totalDistance > m_range ) { m_expired = true; return; } // Move the bullet. m_translation += m_direction * ( m_velocity * elapsed ); } //----------------------------------------------------------------------------- // Returns true if the bullet is expired. //----------------------------------------------------------------------------- bool Bullet::IsExpired() { return m_expired; } //----------------------------------------------------------------------------- // The bullet manager class constructor. //----------------------------------------------------------------------------- BulletManager::BulletManager() { // Create the linked list of bullets. m_bullets = new LinkedList< Bullet >; } //----------------------------------------------------------------------------- // The bullet manager class destructor. //----------------------------------------------------------------------------- BulletManager::~BulletManager() { SAFE_DELETE( m_bullets ); } //----------------------------------------------------------------------------- // Allows the bullet manager to update its bullets. //----------------------------------------------------------------------------- void BulletManager::Update( float elapsed ) { // Go through the list of bullets. Bullet *remove = NULL; Bullet *bullet = m_bullets->GetFirst(); while( bullet != NULL ) { // Check if the bullet has expired. If not, allow it to update. if( bullet->IsExpired() == true ) remove = bullet; else bullet->Update( elapsed ); // Go to the next bullet. bullet = m_bullets->GetNext( bullet ); // If the bullet did expire, then remove it now. if( remove != NULL ) m_bullets->Remove( &remove ); } } //----------------------------------------------------------------------------- // Adds a new bullet to the bullet manager. //----------------------------------------------------------------------------- void BulletManager::AddBullet( SceneObject *owner, D3DXVECTOR3 translation, D3DXVECTOR3 direction, float velocity, float range, float damage ) { m_bullets->Add( new Bullet( owner, translation, direction, velocity, range, damage ) ); }
0
0.55112
1
0.55112
game-dev
MEDIA
0.91283
game-dev
0.58949
1
0.58949
PhongFeng/FFramework
7,112
Assets/Main/GameFramework/Editor/Misc/LogScriptingDefineSymbols.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using UnityEditor; namespace UnityGameFramework.Editor { /// <summary> /// 日志脚本宏定义。 /// </summary> public static class LogScriptingDefineSymbols { private const string EnableLogScriptingDefineSymbol = "ENABLE_LOG"; private const string EnableDebugAndAboveLogScriptingDefineSymbol = "ENABLE_DEBUG_AND_ABOVE_LOG"; private const string EnableInfoAndAboveLogScriptingDefineSymbol = "ENABLE_INFO_AND_ABOVE_LOG"; private const string EnableWarningAndAboveLogScriptingDefineSymbol = "ENABLE_WARNING_AND_ABOVE_LOG"; private const string EnableErrorAndAboveLogScriptingDefineSymbol = "ENABLE_ERROR_AND_ABOVE_LOG"; private const string EnableFatalAndAboveLogScriptingDefineSymbol = "ENABLE_FATAL_AND_ABOVE_LOG"; private const string EnableDebugLogScriptingDefineSymbol = "ENABLE_DEBUG_LOG"; private const string EnableInfoLogScriptingDefineSymbol = "ENABLE_INFO_LOG"; private const string EnableWarningLogScriptingDefineSymbol = "ENABLE_WARNING_LOG"; private const string EnableErrorLogScriptingDefineSymbol = "ENABLE_ERROR_LOG"; private const string EnableFatalLogScriptingDefineSymbol = "ENABLE_FATAL_LOG"; private static readonly string[] AboveLogScriptingDefineSymbols = new string[] { EnableDebugAndAboveLogScriptingDefineSymbol, EnableInfoAndAboveLogScriptingDefineSymbol, EnableWarningAndAboveLogScriptingDefineSymbol, EnableErrorAndAboveLogScriptingDefineSymbol, EnableFatalAndAboveLogScriptingDefineSymbol }; private static readonly string[] SpecifyLogScriptingDefineSymbols = new string[] { EnableDebugLogScriptingDefineSymbol, EnableInfoLogScriptingDefineSymbol, EnableWarningLogScriptingDefineSymbol, EnableErrorLogScriptingDefineSymbol, EnableFatalLogScriptingDefineSymbol }; /// <summary> /// 禁用所有日志脚本宏定义。 /// </summary> [MenuItem("Game Framework/Log Scripting Define Symbols/Disable All Logs", false, 30)] public static void DisableAllLogs() { ScriptingDefineSymbols.RemoveScriptingDefineSymbol(EnableLogScriptingDefineSymbol); foreach (string specifyLogScriptingDefineSymbol in SpecifyLogScriptingDefineSymbols) { ScriptingDefineSymbols.RemoveScriptingDefineSymbol(specifyLogScriptingDefineSymbol); } foreach (string aboveLogScriptingDefineSymbol in AboveLogScriptingDefineSymbols) { ScriptingDefineSymbols.RemoveScriptingDefineSymbol(aboveLogScriptingDefineSymbol); } } /// <summary> /// 开启所有日志脚本宏定义。 /// </summary> [MenuItem("Game Framework/Log Scripting Define Symbols/Enable All Logs", false, 31)] public static void EnableAllLogs() { DisableAllLogs(); ScriptingDefineSymbols.AddScriptingDefineSymbol(EnableLogScriptingDefineSymbol); } /// <summary> /// 开启调试及以上级别的日志脚本宏定义。 /// </summary> [MenuItem("Game Framework/Log Scripting Define Symbols/Enable Debug And Above Logs", false, 32)] public static void EnableDebugAndAboveLogs() { SetAboveLogScriptingDefineSymbol(EnableDebugAndAboveLogScriptingDefineSymbol); } /// <summary> /// 开启信息及以上级别的日志脚本宏定义。 /// </summary> [MenuItem("Game Framework/Log Scripting Define Symbols/Enable Info And Above Logs", false, 33)] public static void EnableInfoAndAboveLogs() { SetAboveLogScriptingDefineSymbol(EnableInfoAndAboveLogScriptingDefineSymbol); } /// <summary> /// 开启警告及以上级别的日志脚本宏定义。 /// </summary> [MenuItem("Game Framework/Log Scripting Define Symbols/Enable Warning And Above Logs", false, 34)] public static void EnableWarningAndAboveLogs() { SetAboveLogScriptingDefineSymbol(EnableWarningAndAboveLogScriptingDefineSymbol); } /// <summary> /// 开启错误及以上级别的日志脚本宏定义。 /// </summary> [MenuItem("Game Framework/Log Scripting Define Symbols/Enable Error And Above Logs", false, 35)] public static void EnableErrorAndAboveLogs() { SetAboveLogScriptingDefineSymbol(EnableErrorAndAboveLogScriptingDefineSymbol); } /// <summary> /// 开启严重错误及以上级别的日志脚本宏定义。 /// </summary> [MenuItem("Game Framework/Log Scripting Define Symbols/Enable Fatal And Above Logs", false, 36)] public static void EnableFatalAndAboveLogs() { SetAboveLogScriptingDefineSymbol(EnableFatalAndAboveLogScriptingDefineSymbol); } /// <summary> /// 设置日志脚本宏定义。 /// </summary> /// <param name="aboveLogScriptingDefineSymbol">要设置的日志脚本宏定义。</param> public static void SetAboveLogScriptingDefineSymbol(string aboveLogScriptingDefineSymbol) { if (string.IsNullOrEmpty(aboveLogScriptingDefineSymbol)) { return; } foreach (string i in AboveLogScriptingDefineSymbols) { if (i == aboveLogScriptingDefineSymbol) { DisableAllLogs(); ScriptingDefineSymbols.AddScriptingDefineSymbol(aboveLogScriptingDefineSymbol); return; } } } /// <summary> /// 设置日志脚本宏定义。 /// </summary> /// <param name="specifyLogScriptingDefineSymbols">要设置的日志脚本宏定义。</param> public static void SetSpecifyLogScriptingDefineSymbols(string[] specifyLogScriptingDefineSymbols) { if (specifyLogScriptingDefineSymbols == null || specifyLogScriptingDefineSymbols.Length <= 0) { return; } bool removed = false; foreach (string specifyLogScriptingDefineSymbol in specifyLogScriptingDefineSymbols) { if (string.IsNullOrEmpty(specifyLogScriptingDefineSymbol)) { continue; } foreach (string i in SpecifyLogScriptingDefineSymbols) { if (i == specifyLogScriptingDefineSymbol) { if (!removed) { removed = true; DisableAllLogs(); } ScriptingDefineSymbols.AddScriptingDefineSymbol(specifyLogScriptingDefineSymbol); break; } } } } } }
0
0.735741
1
0.735741
game-dev
MEDIA
0.383942
game-dev
0.607851
1
0.607851
Barbelot/Chimera
3,701
3D/WithCustomRenderTextures/Scripts/Fluid3DTextureController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Chimera { public class Fluid3DTextureController : MonoBehaviour { [Header("Fluid Controller ID")] public string ID; [Header("Custom Render Textures")] public CustomRenderTexture fluidTexture; [Header("Fluid Parameters")] [Range(0, 10)] public int updatesPerFrame = 4; [Header("Debug")] public bool reinitialize = false; public struct Emitter { public Vector2 position; public Vector2 direction; public float force; public float radiusPower; public float shape; } private const int _fluidEmitterSize = 7 * sizeof(float); private ComputeBuffer _emittersBuffer; private List<Fluid3DEmitter> _emittersList; private Emitter[] _emittersArray; private Material fluidMaterial; private bool _initialized = false; #region MonoBehaviour Functions private void OnEnable() { if (!_initialized) Initialize(); } void Update() { if (!_initialized) { Initialize(); return; } //Update shader time fluidMaterial.SetFloat("_AbsoluteTime", Time.time); //Update emitters UpdateEmittersBuffer(); //Update fluid texture fluidTexture.Update(updatesPerFrame); //Debug if (reinitialize) { fluidTexture.Initialize(); reinitialize = false; } } private void OnDisable() { ReleaseEmittersBuffer(); } #endregion void Initialize() { fluidMaterial = fluidTexture.material; //Initialize emitters InitializeEmitters(); //Initialize fluid texture fluidTexture.Initialize(); _initialized = true; } #region Emitters void InitializeEmitters() { CreateEmittersList(); CreateEmittersArray(); CreateEmittersBuffer(); } void CreateEmittersList() { _emittersList = new List<Fluid3DEmitter>(); } void CreateEmittersArray() { _emittersArray = _emittersList.Count > 0 ? new Emitter[_emittersList.Count] : new Emitter[1]; } void CreateEmittersBuffer() { if (_emittersBuffer != null) _emittersBuffer.Release(); _emittersBuffer = _emittersList.Count > 0 ? new ComputeBuffer(_emittersList.Count, _fluidEmitterSize) : new ComputeBuffer(1, _fluidEmitterSize); UpdateEmittersBuffer(); } void UpdateEmittersArray() { if (_emittersArray.Length != _emittersList.Count) CreateEmittersArray(); for (int i = 0; i < _emittersList.Count; i++) { _emittersArray[i].position = _emittersList[i].position; _emittersArray[i].direction = _emittersList[i].direction; _emittersArray[i].force = _emittersList[i].force; _emittersArray[i].radiusPower = _emittersList[i].forceRadiusPower; _emittersArray[i].shape = _emittersList[i].shape == Fluid3DEmitter.EmitterShape.Directional ? 0 : 1; } } void UpdateEmittersBuffer() { UpdateEmittersArray(); _emittersBuffer.SetData(_emittersArray); fluidMaterial.SetBuffer("_EmittersBuffer", _emittersBuffer); fluidMaterial.SetInt("_EmittersCount", _emittersList.Count); } void ReleaseEmittersBuffer() { _emittersBuffer.Release(); } public void AddEmitter(Fluid3DEmitter emitter) { if (!_initialized) Initialize(); _emittersList.Add(emitter); CreateEmittersBuffer(); } public void RemoveEmitter(Fluid3DEmitter emitter) { _emittersList.Remove(emitter); CreateEmittersBuffer(); } void DebugEmittersList() { Debug.Log("EmittersListCount = " + _emittersList.Count); for (int i = 0; i < _emittersList.Count; i++) { Debug.Log("Emitter " + i + " : position = " + _emittersList[i].position + "; direction = " + _emittersList[i].direction + "; force = " + _emittersList[i].force); } } #endregion } }
0
0.800568
1
0.800568
game-dev
MEDIA
0.768511
game-dev,graphics-rendering
0.901316
1
0.901316
sheenli/U3dFrameworkTolua
1,717
Assets/YKFramwork/Script/Libs/FairyGUI/Scripts/UI/Gears/GearAnimation.cs
using System.Collections.Generic; using FairyGUI.Utils; namespace FairyGUI { class GearAnimationValue { public bool playing; public int frame; public GearAnimationValue(bool playing, int frame) { this.playing = playing; this.frame = frame; } } /// <summary> /// Gear is a connection between object and controller. /// </summary> public class GearAnimation : GearBase { Dictionary<string, GearAnimationValue> _storage; GearAnimationValue _default; public GearAnimation(GObject owner) : base(owner) { } protected override void Init() { _default = new GearAnimationValue(((IAnimationGear)_owner).playing, ((IAnimationGear)_owner).frame); _storage = new Dictionary<string, GearAnimationValue>(); } override protected void AddStatus(string pageId, ByteBuffer buffer) { GearAnimationValue gv; if (pageId == null) gv = _default; else { gv = new GearAnimationValue(false, 0); _storage[pageId] = gv; } gv.playing = buffer.ReadBool(); gv.frame = buffer.ReadInt(); } override public void Apply() { _owner._gearLocked = true; GearAnimationValue gv; if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) gv = _default; IAnimationGear mc = (IAnimationGear)_owner; mc.frame = gv.frame; mc.playing = gv.playing; _owner._gearLocked = false; } override public void UpdateState() { IAnimationGear mc = (IAnimationGear)_owner; GearAnimationValue gv; if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) _storage[_controller.selectedPageId] = new GearAnimationValue(mc.playing, mc.frame); else { gv.playing = mc.playing; gv.frame = mc.frame; } } } }
0
0.726087
1
0.726087
game-dev
MEDIA
0.944096
game-dev
0.881969
1
0.881969
OpenLoco/OpenLoco
4,760
src/OpenLoco/src/GameCommands/Vehicles/VehiclePlaceWater.cpp
#include "VehiclePlaceWater.h" #include "Economy/Expenditures.h" #include "Entities/EntityManager.h" #include "Localisation/StringIds.h" #include "Map/StationElement.h" #include "Map/TileManager.h" #include "Objects/DockObject.h" #include "Objects/ObjectManager.h" #include "Random.h" #include "Vehicles/Vehicle.h" #include "ViewportManager.h" #include "World/StationManager.h" using namespace OpenLoco::Literals; namespace OpenLoco::GameCommands { // 0x0048B199 static void playWaterPlacedownSound(const World::Pos3 pos) { const auto frequency = gPrng2().randNext(20003, 24095); Audio::playSound(Audio::SoundId::constructShip, pos, -600, frequency); } // 0x004267BE static uint32_t vehiclePlaceWater(const VehicleWaterPlacementArgs& args, uint8_t flags) { setExpenditureType(ExpenditureType::ShipRunningCosts); setPosition(args.pos + World::Pos3{ 32, 32, 0 }); // Odd why 32,32 auto* head = EntityManager::get<Vehicles::VehicleHead>(args.head); if (head == nullptr) { return FAILURE; } if (!sub_431E6A(head->owner)) { return FAILURE; } Vehicles::Vehicle train(head->id); if (!args.convertGhost) { if (head->tileX != -1) { setErrorText(StringIds::empty); return FAILURE; } if (train.cars.empty()) { setErrorText(StringIds::empty); return FAILURE; } } if (args.convertGhost) { train.applyToComponents([](auto& component) { component.var_38 &= ~Vehicles::Flags38::isGhost; Ui::ViewportManager::invalidate(&component, ZoomLevel::eighth); }); } else { auto* elStation = [pos = args.pos]() -> World::StationElement* { const auto tile = World::TileManager::get(pos); for (auto& el : tile) { auto* elStation = el.as<World::StationElement>(); if (elStation == nullptr) { continue; } if (elStation->baseHeight() != pos.z) { continue; } return elStation; } return nullptr; }(); if (elStation == nullptr) { return FAILURE; } if (elStation->isGhost() || elStation->isAiAllocated()) { return FAILURE; } auto* station = StationManager::get(elStation->stationId()); if (!sub_431E6A(station->owner)) { return FAILURE; } if (elStation->isFlag6()) { setErrorText(StringIds::vehicle_approaching_or_in_the_way); return FAILURE; } auto* dockObj = ObjectManager::get<DockObject>(elStation->objectId()); const auto boatPos = World::Pos3(Math::Vector::rotate(dockObj->boatPosition, elStation->rotation()), 0) + args.pos + World::Pos3(32, 32, 0); const auto waterHeight = World::TileManager::getHeight(boatPos).waterHeight; if (waterHeight == 0) { setErrorText(StringIds::noWater); return FAILURE; } if (!(flags & Flags::apply)) { return 0; } auto yaw = ((elStation->rotation() + 1) & 0x3) * 16; head->moveBoatTo(boatPos, yaw, Pitch::flat); head->moveTo(boatPos + World::Pos3(0, 0, 32)); head->status = Vehicles::Status::stopped; head->vehicleFlags |= VehicleFlags::commandStop; head->stationId = elStation->stationId(); head->tileX = args.pos.x; head->tileY = args.pos.y; head->tileBaseZ = args.pos.z / World::kSmallZStep; elStation->setFlag6(true); train.veh1->var_48 |= Vehicles::Flags48::flag2; if (flags & Flags::ghost) { train.applyToComponents([](auto& component) { component.var_38 |= Vehicles::Flags38::isGhost; }); } } if ((flags & Flags::apply) && !(flags & Flags::ghost)) { playWaterPlacedownSound(getPosition()); } return 0; } void vehiclePlaceWater(registers& regs) { regs.ebx = vehiclePlaceWater(VehicleWaterPlacementArgs(regs), regs.bl); } }
0
0.963194
1
0.963194
game-dev
MEDIA
0.763312
game-dev
0.92454
1
0.92454
Flectone/FlectonePulse
1,757
core/src/main/java/net/flectone/pulse/module/message/join/listener/JoinPulseListener.java
package net.flectone.pulse.module.message.join.listener; import com.github.retrooper.packetevents.manager.server.ServerVersion; import com.google.inject.Inject; import com.google.inject.Singleton; import lombok.RequiredArgsConstructor; import net.flectone.pulse.annotation.Pulse; import net.flectone.pulse.listener.PulseListener; import net.flectone.pulse.model.entity.FPlayer; import net.flectone.pulse.model.event.message.MessageReceiveEvent; import net.flectone.pulse.model.event.player.PlayerJoinEvent; import net.flectone.pulse.module.message.join.JoinModule; import net.flectone.pulse.platform.provider.PacketProvider; import net.kyori.adventure.text.TranslatableComponent; @Singleton @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class JoinPulseListener implements PulseListener { private final PacketProvider packetProvider; private final JoinModule joinModule; @Pulse public void onPlayerJoinEvent(PlayerJoinEvent event) { FPlayer fPlayer = event.getPlayer(); if (packetProvider.getServerVersion().isNewerThanOrEquals(ServerVersion.V_1_20_2)) { // delay for vanish plugins and newer versions joinModule.sendLater(fPlayer); } else { joinModule.send(fPlayer, false); } } @Pulse public void onTranslatableMessageReceiveEvent(MessageReceiveEvent event) { TranslatableComponent translatableComponent = event.getTranslatableComponent(); if (translatableComponent == null) return; String translationKey = translatableComponent.key(); if (!translationKey.equals("multiplayer.player.joined") && !translationKey.equals("multiplayer.player.joined.renamed")) return; event.setCancelled(true); } }
0
0.835308
1
0.835308
game-dev
MEDIA
0.742088
game-dev,networking
0.803847
1
0.803847
SkelletonX/DDTank4.1
2,203
Source Server/Game.Logic/PetEffects/CASE1201.cs
using Game.Logic.Phy.Object; using System; namespace Game.Logic.PetEffects { public class CASE1201 : BasePetEffect { private int int_0; private int int_1; private int int_2; private int int_3; private int int_4; private int int_5; private int int_6; public CASE1201(int count, int probability, int type, int skillId, int delay, string elementID) : base(ePetEffectType.CASE1201, elementID) { this.int_1 = count; this.int_4 = count; this.int_2 = ((probability == -1) ? 10000 : probability); this.int_0 = type; this.int_3 = delay; this.int_5 = skillId; } public override bool Start(Living living) { CASE1201 aE = living.PetEffectList.GetOfType(ePetEffectType.CASE1201) as CASE1201; if (aE != null) { aE.int_2 = ((this.int_2 > aE.int_2) ? this.int_2 : aE.int_2); return true; } return base.Start(living); } protected override void OnAttachedToPlayer(Player player) { player.AfterKillingLiving += new KillLivingEventHanlde(this.method_1); player.PlayerBuffSkillPet += new PlayerEventHandle(this.method_0); } private void method_0(Player player_0) { if (player_0.PetEffects.CurrentUseSkill == this.int_5) { this.IsTrigger = true; } } private void method_1(Living living_0, Living living_1, int int_7, int int_8) { if (this.IsTrigger) { this.IsTrigger = false; living_1.AddPetEffect(new CASE1201A(3, this.int_2, this.int_0, this.int_5, this.int_3, base.Info.ID.ToString()), 0); Console.WriteLine("-100 sat thuong cua dich khi trung phai"); } } protected override void OnRemovedFromPlayer(Player player) { player.AfterKillingLiving -= new KillLivingEventHanlde(this.method_1); player.PlayerBuffSkillPet -= new PlayerEventHandle(this.method_0); } } }
0
0.812943
1
0.812943
game-dev
MEDIA
0.801423
game-dev
0.700976
1
0.700976
NBlood/NBlood
86,873
source/rr/src/premap.cpp
//------------------------------------------------------------------------- /* Copyright (C) 2016 EDuke32 developers and contributors This file is part of EDuke32. EDuke32 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- #include "duke3d.h" #include "anim.h" #include "menus.h" #include "demo.h" #include "savegame.h" #include "cmdline.h" static int32_t g_whichPalForPlayer = 9; static uint8_t precachehightile[2][MAXTILES>>3]; static int32_t g_precacheCount; static void flag_precache(int32_t tile, int32_t type) { if (!(gotpic[tile>>3] & pow2char[tile&7])) g_precacheCount++; gotpic[tile>>3] |= pow2char[tile&7]; precachehightile[type][tile>>3] |= pow2char[tile&7]; } static void tloadtile(int32_t tilenume, int32_t type) { int32_t i,j; if ((picanm[tilenume].sf&PICANM_ANIMTYPE_MASK)==PICANM_ANIMTYPE_BACK) { i = tilenume - picanm[tilenume].num; j = tilenume; } else { i = tilenume; j = tilenume + picanm[tilenume].num; } for (; i<=j; i++) flag_precache(i, type); } static void G_CacheSpriteNum(int32_t i) { char maxc; int32_t j; if (ud.monsters_off && A_CheckEnemySprite(&sprite[i])) return; maxc = 1; for (j = PN(i); j <= g_tile[PN(i)].cacherange; j++) tloadtile(j,1); switch (DYNAMICTILEMAP(PN(i))) { case HYDRENT__STATIC: tloadtile(BROKEFIREHYDRENT,1); for (j = TOILETWATER; j < (TOILETWATER+4); j++) tloadtile(j,1); break; case RRTILE2121__STATICRR: case RRTILE2122__STATICRR: tloadtile(BROKEFIREHYDRENT, 1); break; case TOILET__STATIC: tloadtile(TOILETBROKE,1); for (j = TOILETWATER; j < (TOILETWATER+4); j++) tloadtile(j,1); break; case STALL__STATIC: tloadtile(STALLBROKE,1); for (j = TOILETWATER; j < (TOILETWATER+4); j++) tloadtile(j,1); break; case FORCERIPPLE__STATIC: if (!RR) break; maxc = 9; break; case RUBBERCAN__STATIC: maxc = 2; break; case TOILETWATER__STATIC: maxc = 4; break; case BUBBASTAND__STATICRR: for (j = BUBBASCRATCH; j < (BUBBASCRATCH+47); j++) tloadtile(j,1); maxc = 0; break; case SBSWIPE__STATICRR: if (!RRRA) break; for (j = BUBBASCRATCH; j <= (SBSWIPE+47); j++) tloadtile(j,1); maxc = 0; break; case COOT__STATICRR: for(j = COOT; j <= (COOT+217); j++) tloadtile(j,1); for(j = COOTJIBA; j < COOTJIBC+4; j++) tloadtile(j,1); maxc = 0; break; case LTH__STATICRR: maxc = 105; for (j = LTH; j < (LTH + maxc); j++) tloadtile(j,1); maxc = 0; break; case BILLYRAY__STATICRR: maxc = 144; for (j = BILLYWALK; j < (BILLYWALK + maxc); j++) tloadtile(j,1); for (j = BILLYJIBA; j <= BILLYJIBB + 4; j++) tloadtile(j,1); maxc = 0; break; case COW__STATICRR: maxc = 56; for (j = PN(i); j < (PN(i) + maxc); j++) tloadtile(j,1); maxc = 0; break; case DOGRUN__STATICRR: for (j = DOGATTACK; j <= DOGATTACK + 35; j++) tloadtile(j,1); for (j = DOGRUN; j <= DOGRUN + 121; j++) tloadtile(j,1); maxc = 0; break; case RABBIT__STATICRR: if (!RRRA) break; for (j = RABBIT; j <= RABBIT + 54; j++) tloadtile(j,1); for (j = RABBIT + 56; j <= RABBIT + 56 + 49; j++) tloadtile(j,1); for (j = RABBIT + 56; j <= RABBIT + 56 + 49; j++) tloadtile(j,1); maxc = 0; break; case BIKERB__STATICRR: case BIKERBV2__STATICRR: if (!RRRA) break; for (j = BIKERB; j <= BIKERB + 104; j++) tloadtile(j,1); maxc = 0; break; case BIKER__STATICRR: if (!RRRA) break; for (j = BIKER; j <= BIKER + 116; j++) tloadtile(j,1); for (j = BIKER + 150; j <= BIKER + 150 + 104; j++) tloadtile(j,1); maxc = 0; break; case CHEER__STATICRR: if (!RRRA) break; for (j = CHEER; j <= CHEER + 44; j++) tloadtile(j,1); for (j = CHEER + 47; j <= CHEER + 47 + 211; j++) tloadtile(j,1); for (j = CHEER + 262; j <= CHEER + 262 + 72; j++) tloadtile(j,1); maxc = 0; break; case CHEERB__STATICRR: if (!RRRA) break; for (j = CHEERB; j <= CHEERB + 157 + 83; j++) tloadtile(j,1); maxc = 0; break; case MAMA__STATICRR: if (!RRRA) break; for (j = MAMA; j <= MAMA + 78; j++) tloadtile(j,1); for (j = MAMA + 80; j <= MAMA + 80 + 7; j++) tloadtile(j,1); for (j = MAMA + 90; j <= MAMA + 90 + 94; j++) tloadtile(j,1); maxc = 0; break; case CHEERBOAT__STATICRR: if (!RRRA) break; if (waloff[CHEERBOAT] == 0) tloadtile(CHEERBOAT,1); maxc = 0; break; case HULKBOAT__STATICRR: if (!RRRA) break; if (waloff[HULKBOAT] == 0) tloadtile(HULKBOAT,1); maxc = 0; break; case MINIONBOAT__STATICRR: if (!RRRA) break; if (waloff[MINIONBOAT] == 0) tloadtile(MINIONBOAT,1); maxc = 0; break; case BILLYPLAY__STATICRR: if (!RRRA) break; for (j = BILLYPLAY; j <= BILLYPLAY + 2; j++) tloadtile(j,1); maxc = 0; break; case COOTPLAY__STATICRR: if (!RRRA) break; for (j = COOTPLAY; j <= COOTPLAY + 4; j++) tloadtile(j,1); maxc = 0; break; case PIG__STATICRR: case PIGSTAYPUT__STATICRR: maxc = 69; break; case TORNADO__STATICRR: maxc = 7; break; case HEN__STATICRR: case HENSTAND__STATICRR: maxc = 34; break; case FEMPIC1__STATIC: if (RR) break; maxc = 44; break; case LIZTROOP__STATIC: case LIZTROOPRUNNING__STATIC: case LIZTROOPSHOOT__STATIC: case LIZTROOPJETPACK__STATIC: case LIZTROOPONTOILET__STATIC: case LIZTROOPDUCKING__STATIC: if (RR) break; for (j = LIZTROOP; j < (LIZTROOP+72); j++) tloadtile(j,1); for (j=HEADJIB1; j<LEGJIB1+3; j++) tloadtile(j,1); maxc = 0; break; case WOODENHORSE__STATIC: if (RR) break; maxc = 5; for (j = HORSEONSIDE; j < (HORSEONSIDE+4); j++) tloadtile(j,1); break; case NEWBEAST__STATIC: case NEWBEASTSTAYPUT__STATIC: if (RR) break; maxc = 90; break; case BOSS1__STATIC: case BOSS2__STATIC: case BOSS3__STATIC: if (RR) break; maxc = 30; break; case OCTABRAIN__STATIC: case OCTABRAINSTAYPUT__STATIC: case COMMANDER__STATIC: case COMMANDERSTAYPUT__STATIC: if (RR) break; maxc = 38; break; case RECON__STATIC: if (RR) break; maxc = 13; break; case PIGCOP__STATIC: case PIGCOPDIVE__STATIC: if (RR) break; maxc = 61; break; case SHARK__STATIC: if (RR) break; maxc = 30; break; case LIZMAN__STATIC: case LIZMANSPITTING__STATIC: case LIZMANFEEDING__STATIC: case LIZMANJUMP__STATIC: if (RR) break; for (j=LIZMANHEAD1; j<LIZMANLEG1+3; j++) tloadtile(j,1); maxc = 80; break; case APLAYER__STATIC: maxc = 0; if ((g_netServer || ud.multimode > 1)) { maxc = 5; if (RR) { for (j = APLAYER; j < APLAYER+220; j++) tloadtile(j,1); for (j = DUKEGUN; j < DUKELEG+4; j++) tloadtile(j,1); } else for (j = 1420; j < 1420+106; j++) tloadtile(j,1); } break; case ATOMICHEALTH__STATIC: maxc = 14; break; case DRONE__STATIC: maxc = RR ? 6 : 10; break; case EXPLODINGBARREL__STATIC: case SEENINE__STATIC: case OOZFILTER__STATIC: maxc = 3; break; case NUKEBARREL__STATIC: case CAMERA1__STATIC: maxc = 5; break; // caching of HUD sprites for weapons that may be in the level case CHAINGUNSPRITE__STATIC: if (RR) break; for (j=CHAINGUN; j<=CHAINGUN+7; j++) tloadtile(j,1); break; case RPGSPRITE__STATIC: if (RR) break; for (j=RPGGUN; j<=RPGGUN+2; j++) tloadtile(j,1); break; case FREEZESPRITE__STATIC: if (RR) break; for (j=FREEZE; j<=FREEZE+5; j++) tloadtile(j,1); break; case GROWSPRITEICON__STATIC: case SHRINKERSPRITE__STATIC: if (RR) break; for (j=SHRINKER-2; j<=SHRINKER+5; j++) tloadtile(j,1); break; case HBOMBAMMO__STATIC: case HEAVYHBOMB__STATIC: if (RR) break; for (j=HANDREMOTE; j<=HANDREMOTE+5; j++) tloadtile(j,1); break; case TRIPBOMBSPRITE__STATIC: if (RR) break; for (j=HANDHOLDINGLASER; j<=HANDHOLDINGLASER+4; j++) tloadtile(j,1); break; case SHOTGUNSPRITE__STATIC: if (RR) break; tloadtile(SHOTGUNSHELL,1); for (j=SHOTGUN; j<=SHOTGUN+6; j++) tloadtile(j,1); break; case DEVISTATORSPRITE__STATIC: if (RR) break; for (j=DEVISTATOR; j<=DEVISTATOR+1; j++) tloadtile(j,1); break; case VIXEN__STATICRR: maxc = 214; for (j = PN(i); j < PN(i) + maxc; j++) tloadtile(j,1); maxc = 0; break; case SBMOVE__STATICRR: if (RRRA) break; maxc = 54; for (j = PN(i); j < PN(i) + maxc; j++) tloadtile(j,1); maxc = 100; for (j = SBMOVE; j < SBMOVE + maxc; j++) tloadtile(j,1); maxc = 0; break; case HULK__STATICRR: maxc = 40; for (j = PN(i) - 41; j < PN(i) + maxc - 41; j++) tloadtile(j,1); for (j = HULKJIBA; j <= HULKJIBC + 4; j++) tloadtile(j,1); maxc = 0; break; case MINION__STATICRR: maxc = 141; for (j = PN(i); j < PN(i) + maxc; j++) tloadtile(j,1); for (j = MINJIBA; j <= MINJIBC + 4; j++) tloadtile(j,1); maxc = 0; break; } for (j = PN(i); j < (PN(i)+maxc); j++) tloadtile(j,1); } static void G_PrecacheSprites(void) { int32_t i; //for (i=0; i<MAXTILES; i++) //{ // if (g_tile[i].flags & SFLAG_PROJECTILE) // tloadtile(i,1); // // if (A_CheckSpriteTileFlags(i, SFLAG_CACHE)) // for (j = i; j <= g_tile[i].cacherange; j++) // tloadtile(j,1); //} tloadtile(BOTTOMSTATUSBAR,1); if ((g_netServer || ud.multimode > 1)) tloadtile(FRAGBAR,1); tloadtile(VIEWSCREEN,1); for (i=STARTALPHANUM; i<ENDALPHANUM+1; i++) tloadtile(i,1); for (i=BIGALPHANUM-11; i<BIGALPHANUM+82; i++) tloadtile(i,1); for (i=MINIFONT; i<MINIFONT+93; i++) tloadtile(i,1); for (i=FOOTPRINTS; i<FOOTPRINTS+3; i++) tloadtile(i,1); for (i = BURNING; i < BURNING+14; i++) tloadtile(i,1); for (i = FIRSTGUN; i < FIRSTGUN+(RR ? 10 : 3) ; i++) tloadtile(i,1); for (i = EXPLOSION2; i < EXPLOSION2+21 ; i++) tloadtile(i,1); for (i = COOLEXPLOSION1; i < COOLEXPLOSION1+21 ; i++) tloadtile(i,1); tloadtile(BULLETHOLE,1); tloadtile(BLOODPOOL,1); for (i = SMALLSMOKE; i < (SMALLSMOKE+4); i++) tloadtile(i,1); for (i = SHOTSPARK1; i < (SHOTSPARK1+4); i++) tloadtile(i,1); for (i = BLOOD; i < (BLOOD+4); i++) tloadtile(i,1); for (i = JIBS1; i < (JIBS5+5); i++) tloadtile(i,1); for (i = JIBS6; i < (JIBS6+8); i++) tloadtile(i,1); for (i = SCRAP1; i < (SCRAP1+(RR? 19 : 29)); i++) tloadtile(i,1); if (!RR) { for (i = BURNING2; i < BURNING2+14; i++) tloadtile(i,1); for (i = CRACKKNUCKLES; i < CRACKKNUCKLES+4; i++) tloadtile(i,1); for (i = FIRSTGUNRELOAD; i < FIRSTGUNRELOAD+8 ; i++) tloadtile(i,1); for (i = TRANSPORTERBEAM; i < (TRANSPORTERBEAM+6); i++) tloadtile(i,1); tloadtile(FIRELASER,1); for (i=TRANSPORTERSTAR; i<TRANSPORTERSTAR+6; i++) tloadtile(i,1); for (i=FORCERIPPLE; i<(FORCERIPPLE+9); i++) tloadtile(i,1); for (i=MENUSCREEN; i<DUKECAR; i++) tloadtile(i,1); for (i=RPG; i<RPG+7; i++) tloadtile(i,1); for (i=FREEZEBLAST; i<FREEZEBLAST+3; i++) tloadtile(i,1); for (i=SHRINKSPARK; i<SHRINKSPARK+4; i++) tloadtile(i,1); for (i=GROWSPARK; i<GROWSPARK+4; i++) tloadtile(i,1); for (i=SHRINKEREXPLOSION; i<SHRINKEREXPLOSION+4; i++) tloadtile(i,1); for (i=MORTER; i<MORTER+4; i++) tloadtile(i,1); for (i=0; i<=60; i++) tloadtile(i,1); } else { if (RRRA) { if (ud.volume_number == 0 && ud.level_number == 4) tloadtile(RRTILE2577, 1); } else { if (ud.volume_number == 1 && ud.level_number == 2) { tloadtile(RRTILE3190, 1); tloadtile(RRTILE3191, 1); tloadtile(RRTILE3192, 1); tloadtile(RRTILE3144, 1); tloadtile(RRTILE3139, 1); tloadtile(RRTILE3132, 1); tloadtile(RRTILE3120, 1); tloadtile(RRTILE3121, 1); tloadtile(RRTILE3122, 1); tloadtile(RRTILE3123, 1); tloadtile(RRTILE3124, 1); } } if (g_lastLevel) { tloadtile(UFO1, 1); tloadtile(UFO2, 1); tloadtile(UFO3, 1); tloadtile(UFO4, 1); tloadtile(UFO5, 1); } } } static void G_DoLoadScreen(const char *statustext, int32_t percent) { if (ud.recstat != 2) { int32_t i = 0; //g_player[myconnectindex].ps->palette = palette; P_SetGamePalette(g_player[myconnectindex].ps, BASEPAL, 1); // JBF 20040308 if (!statustext) { i = ud.screen_size; ud.screen_size = 0; G_UpdateScreenArea(); videoClearScreen(0L); } videoClearScreen(0); if (REALITY) { RT_DisablePolymost(0); RT_RotateSpriteSetColor(255, 255, 255, 255); RT_RotateSprite(160, 120, 100, 100, 3670, RTRS_SCALED); RT_EnablePolymost(); } else { int const loadScreenTile = VM_OnEventWithReturn(EVENT_GETLOADTILE, g_player[screenpeek].ps->i, screenpeek, DEER ? 7040 : LOADSCREEN); rotatesprite_fs(320<<15,200<<15,65536L,0,loadScreenTile,0,0,2+8+64+BGSTRETCH); } int const textY = RRRA ? 140 : 90; if (boardfilename[0] != 0 && ud.level_number == 7 && ud.volume_number == 0) { menutext_center(textY, RR ? "ENTERIN' USER MAP" : "Loading User Map"); if (RR) menutext_center(textY+20, boardfilename); else gametext_center_shade_pal(textY+10, boardfilename, 14, 2); } else if (RR && g_lastLevel) { menutext_center(textY,"ENTERIN'"); menutext_center(textY+16+8,"CLOSE ENCOUNTERS"); } else { menutext_center(textY, RR ? "ENTERIN'" : "Loading"); if (g_mapInfo[(ud.volume_number*MAXLEVELS) + ud.level_number].name != NULL) menutext_center(textY+16+8,g_mapInfo[(ud.volume_number*MAXLEVELS) + ud.level_number].name); } #ifndef EDUKE32_TOUCH_DEVICES if (statustext) gametext_center_number(180, statustext); #endif if (percent != -1) { int32_t ii = scale(scale(xdim-1,288,320),percent,100); rotatesprite(31<<16,145<<16,65536,0,929,15,0,2+8+16,0,0,ii,ydim-1); rotatesprite(159<<16,145<<16,65536,0,929,15,0,2+8+16,0,0,ii,ydim-1); rotatesprite(30<<16,144<<16,65536,0,929,0,0,2+8+16,0,0,ii,ydim-1); rotatesprite(158<<16,144<<16,65536,0,929,0,0,2+8+16,0,0,ii,ydim-1); } videoNextPage(); if (!statustext) { KB_FlushKeyboardQueue(); ud.screen_size = i; } } else { if (!statustext) { videoClearScreen(0L); //g_player[myconnectindex].ps->palette = palette; //G_FadePalette(0,0,0,0); P_SetGamePalette(g_player[myconnectindex].ps, BASEPAL, 0); // JBF 20040308 } /*Gv_SetVar(g_iReturnVarID,LOADSCREEN, -1, -1);*/ rotatesprite_fs(320<<15,200<<15,65536L, 0,LOADSCREEN,0,0,2+8+64+BGSTRETCH); menutext_center(RRRA?155:105,RR?"LOADIN'":"Loading..."); if (statustext) gametext_center_number(180, statustext); videoNextPage(); } } void G_CacheMapData(void) { int32_t i,j,pc=0; int32_t tc; uint32_t starttime, endtime; if (ud.recstat == 2) return; S_TryPlaySpecialMusic(MUS_LOADING); #if defined EDUKE32_TOUCH_DEVICES && defined USE_OPENGL polymost_glreset(); #endif starttime = timerGetTicks(); S_PrecacheSounds(); G_PrecacheSprites(); for (i=0; i<numwalls; i++) { tloadtile(wall[i].picnum, 0); if (wall[i].overpicnum >= 0) { tloadtile(wall[i].overpicnum, 0); } } for (i=0; i<numsectors; i++) { tloadtile(sector[i].floorpicnum, 0); tloadtile(sector[i].ceilingpicnum, 0); if (sector[i].ceilingpicnum == LA) // JBF 20040509: if( waloff[sector[i].ceilingpicnum] == LA) WTF?!?!?!? { tloadtile(LA+1, 0); tloadtile(LA+2, 0); } for (SPRITES_OF_SECT(i, j)) if (sprite[j].xrepeat != 0 && sprite[j].yrepeat != 0 && (sprite[j].cstat&32768) == 0) G_CacheSpriteNum(j); } tc = (int32_t) totalclock; j = 0; int lpc = -1; for (i=0; i<MAXTILES; i++) { if (!(i&7) && !gotpic[i>>3]) { i+=7; continue; } if (gotpic[i>>3] & pow2char[i&7]) { if (waloff[i] == 0) tileLoad((int16_t)i); #ifdef USE_OPENGL // PRECACHE if (ud.config.useprecache && bpp > 8) { int32_t k,type; for (type=0; type<=1; type++) if (precachehightile[type][i>>3] & pow2char[i&7]) { k = 0; for (k=0; k<MAXPALOOKUPS-RESERVEDPALS && !KB_KeyPressed(sc_Space); k++) { // this is the CROSSHAIR_PAL, see comment in game.c if (k == MAXPALOOKUPS-RESERVEDPALS-1) break; #ifdef POLYMER if (videoGetRenderMode() != REND_POLYMER || !polymer_havehighpalookup(0, k)) #endif polymost_precache(i,k,type); } #ifdef USE_GLEXT if (r_detailmapping && !KB_KeyPressed(sc_Space)) polymost_precache(i,DETAILPAL,type); if (r_glowmapping && !KB_KeyPressed(sc_Space)) polymost_precache(i,GLOWPAL,type); #endif #ifdef POLYMER if (videoGetRenderMode() == REND_POLYMER) { if (pr_specularmapping && !KB_KeyPressed(sc_Space)) polymost_precache(i,SPECULARPAL,type); if (pr_normalmapping && !KB_KeyPressed(sc_Space)) polymost_precache(i,NORMALPAL,type); } #endif } } #endif j++; pc++; } else continue; MUSIC_Update(); if ((j&7) == 0) G_HandleAsync(); if (bpp > 8 && totalclock - tc > TICRATE/4) { /*Bsprintf(tempbuf,"%d resources remaining\n",g_precacheCount-pc+1);*/ int percentage = min(100, tabledivide32_noinline(100 * pc, g_precacheCount)); while (percentage > lpc) { G_HandleAsync(); Bsprintf(tempbuf, "Loaded %d%% (%d/%d textures)\n", lpc, pc, g_precacheCount); G_DoLoadScreen(tempbuf, lpc); if (totalclock - tc >= 1) { tc = (int32_t) totalclock; lpc++; } // OSD_Printf("percentage %d lpc %d\n", percentage, lpc); } tc = (int32_t) totalclock; } } Bmemset(gotpic, 0, sizeof(gotpic)); endtime = timerGetTicks(); OSD_Printf("Cache time: %dms\n", endtime-starttime); } extern int32_t fragbarheight(void) { if (ud.screen_size > 0 && !(ud.statusbarflags & STATUSBAR_NOFRAGBAR) #ifdef SPLITSCREEN_MOD_HACKS && !g_fakeMultiMode #endif && (g_netServer || ud.multimode > 1) && GTFLAGS(GAMETYPE_FRAGBAR)) { int32_t i, j = 0; for (TRAVERSE_CONNECT(i)) if (i > j) j = i; return ((j + 3) >> 2) << 3; } return 0; } void G_UpdateScreenArea(void) { if (!in3dmode()) return; ud.screen_size = clamp(ud.screen_size, 0, 64); if (ud.screen_size == 0) renderFlushPerms(); { const int32_t ss = max(ud.screen_size-8,0); int32_t x1 = scale(ss,xdim,160); int32_t x2 = xdim-x1; int32_t y1 = scale(ss,(200 * 100) - ((tilesiz[BOTTOMSTATUSBAR].y >> (RR ? 1 : 0)) * ud.statusbarscale),200 - tilesiz[BOTTOMSTATUSBAR].y); int32_t y2 = 200*100-y1; if (RR && ud.screen_size <= 12) { x1 = 0; x2 = xdim; y1 = 0; if (ud.statusbarmode) y2 = 200*100; } y1 += fragbarheight()*100; if (ud.screen_size >= 8 && ud.statusbarmode==0) y2 -= (tilesiz[BOTTOMSTATUSBAR].y >> (RR ? 1 : 0))*ud.statusbarscale; y1 = scale(y1,ydim,200*100); y2 = scale(y2,ydim,200*100); videoSetViewableArea(x1,y1,x2-1,y2-1); } G_GetCrosshairColor(); G_SetCrosshairColor(CrosshairColors.r, CrosshairColors.g, CrosshairColors.b); pub = NUMPAGES; pus = NUMPAGES; } void P_RandomSpawnPoint(int playerNum) { DukePlayer_t *const pPlayer = g_player[playerNum].ps; int32_t i = playerNum; if ((g_netServer || ud.multimode > 1) && !(g_gametypeFlags[ud.coop] & GAMETYPE_FIXEDRESPAWN)) { i = krand2() % g_playerSpawnCnt; if (g_gametypeFlags[ud.coop] & GAMETYPE_TDMSPAWN) { uint32_t pdist = -1; for (bssize_t j=0; j<ud.multimode; j++) { if (j != playerNum && g_player[j].ps->team == pPlayer->team && sprite[g_player[j].ps->i].extra > 0) { for (bssize_t k=0; k<g_playerSpawnCnt; k++) { uint32_t dist = FindDistance2D(g_player[j].ps->pos.x - g_playerSpawnPoints[k].pos.x, g_player[j].ps->pos.y - g_playerSpawnPoints[k].pos.y); if (dist < pdist) i = k, pdist = dist; } break; } } } } pPlayer->pos = g_playerSpawnPoints[i].pos; pPlayer->opos = pPlayer->pos; pPlayer->bobpos = *(vec2_t *)&pPlayer->pos; pPlayer->q16ang = fix16_from_int(g_playerSpawnPoints[i].ang); pPlayer->cursectnum = g_playerSpawnPoints[i].sect; sprite[pPlayer->i].cstat = 1 + 256; } static inline void P_ResetTintFade(DukePlayer_t *const pPlayer) { pPlayer->pals.f = 0; } void P_ResetPlayer(int playerNum) { DukePlayer_t *const pPlayer = g_player[playerNum].ps; spritetype *const pSprite = &sprite[pPlayer->i]; vec3_t tmpvect = pPlayer->pos; tmpvect.z += PHEIGHT; P_RandomSpawnPoint(playerNum); pPlayer->opos = pPlayer->pos; pPlayer->bobpos = *(vec2_t *)&pPlayer->pos; actor[pPlayer->i].bpos = pPlayer->pos; *(vec3_t *)pSprite = pPlayer->pos; updatesector(pPlayer->pos.x, pPlayer->pos.y, &pPlayer->cursectnum); setsprite(pPlayer->i, &tmpvect); pSprite->cstat = 257; pSprite->shade = -12; pSprite->clipdist = RR ? 32 : 64; pSprite->xrepeat = RR ? 24 : 42; pSprite->yrepeat = RR ? 17 : 36; pSprite->owner = pPlayer->i; pSprite->xoffset = 0; pSprite->pal = pPlayer->palookup; pPlayer->last_extra = pSprite->extra = pPlayer->max_player_health; pPlayer->wantweaponfire = -1; pPlayer->q16horiz = F16(100); pPlayer->on_crane = -1; pPlayer->frag_ps = playerNum; pPlayer->q16horizoff = 0; pPlayer->opyoff = 0; pPlayer->wackedbyactor = -1; pPlayer->inv_amount[GET_SHIELD] = g_startArmorAmount; pPlayer->dead_flag = 0; pPlayer->footprintcount = 0; pPlayer->weapreccnt = 0; pPlayer->fta = 0; pPlayer->ftq = 0; pPlayer->vel.x = pPlayer->vel.y = 0; if (!RR) pPlayer->rotscrnang = 0; pPlayer->runspeed = g_playerFriction; pPlayer->falling_counter = 0; P_ResetTintFade(pPlayer); actor[pPlayer->i].extra = -1; actor[pPlayer->i].owner = pPlayer->i; actor[pPlayer->i].cgg = 0; actor[pPlayer->i].movflag = 0; actor[pPlayer->i].tempang = 0; actor[pPlayer->i].actorstayput = -1; actor[pPlayer->i].dispicnum = 0; actor[pPlayer->i].owner = pPlayer->i; actor[pPlayer->i].t_data[4] = 0; P_ResetInventory(playerNum); P_ResetWeapons(playerNum); //pPlayer->reloading = 0; pPlayer->movement_lock = 0; } void P_ResetStatus(int playerNum) { DukePlayer_t *const pPlayer = g_player[playerNum].ps; ud.show_help = 0; ud.showallmap = 0; pPlayer->dead_flag = 0; pPlayer->wackedbyactor = -1; pPlayer->falling_counter = 0; pPlayer->quick_kick = 0; pPlayer->subweapon = 0; pPlayer->last_full_weapon = 0; pPlayer->ftq = 0; pPlayer->fta = 0; pPlayer->tipincs = 0; pPlayer->buttonpalette = 0; pPlayer->actorsqu = -1; pPlayer->invdisptime = 0; pPlayer->refresh_inventory = 0; pPlayer->last_pissed_time = 0; pPlayer->holster_weapon = 0; pPlayer->pycount = 0; pPlayer->pyoff = 0; pPlayer->opyoff = 0; pPlayer->loogcnt = 0; pPlayer->q16angvel = 0; pPlayer->weapon_sway = 0; pPlayer->extra_extra8 = 0; pPlayer->show_empty_weapon = 0; pPlayer->dummyplayersprite = -1; pPlayer->crack_time = 0; pPlayer->hbomb_hold_delay = 0; pPlayer->transporter_hold = 0; //pPlayer->clipdist = 164; pPlayer->wantweaponfire = -1; pPlayer->hurt_delay = 0; if (RRRA) pPlayer->hurt_delay2 = 0; pPlayer->footprintcount = 0; pPlayer->footprintpal = 0; pPlayer->footprintshade = 0; pPlayer->jumping_toggle = 0; pPlayer->oq16horiz = F16(140); pPlayer->q16horiz = F16(140); pPlayer->q16horizoff = 0; pPlayer->bobcounter = 0; pPlayer->on_ground = 0; pPlayer->player_par = 0; pPlayer->return_to_center = 9; pPlayer->airleft = 15 * GAMETICSPERSEC; pPlayer->rapid_fire_hold = 0; pPlayer->toggle_key_flag = 0; pPlayer->access_spritenum = -1; pPlayer->got_access = ((g_netServer || ud.multimode > 1) && (g_gametypeFlags[ud.coop] & GAMETYPE_ACCESSATSTART)) ? 7 : 0; pPlayer->random_club_frame = 0; pus = 1; pPlayer->on_warping_sector = 0; pPlayer->spritebridge = 0; //pPlayer->sbs = 0; pPlayer->palette = BASEPAL; if (pPlayer->inv_amount[GET_STEROIDS] < 400) { pPlayer->inv_amount[GET_STEROIDS] = 0; pPlayer->inven_icon = ICON_NONE; } pPlayer->heat_on = 0; pPlayer->jetpack_on = 0; pPlayer->holoduke_on = -1; pPlayer->look_ang = 512 - ((ud.level_number & 1) << 10); pPlayer->rotscrnang = 0; pPlayer->orotscrnang = 1; // JBF 20031220 pPlayer->newowner = -1; pPlayer->jumping_counter = 0; pPlayer->hard_landing = 0; pPlayer->vel.x = 0; pPlayer->vel.y = 0; pPlayer->vel.z = 0; pPlayer->fric.x = 0; pPlayer->fric.y = 0; pPlayer->somethingonplayer = -1; pPlayer->one_eighty_count = 0; pPlayer->cheat_phase = 0; pPlayer->on_crane = -1; pPlayer->kickback_pic = (pPlayer->curr_weapon == PISTOL_WEAPON) ? (RR ? 22 : 5) : 0; pPlayer->weapon_pos = WEAPON_POS_START; pPlayer->walking_snd_toggle = 0; pPlayer->weapon_ang = 0; pPlayer->knuckle_incs = 1; pPlayer->fist_incs = 0; pPlayer->knee_incs = 0; //pPlayer->reloading = 0; pPlayer->movement_lock = 0; pPlayer->frag_ps = playerNum; if (REALITY) { pPlayer->dn64_370 = 0; pPlayer->dn64_374 = 0; pPlayer->dn64_376 = 0; pPlayer->dn64_378 = 0; pPlayer->dn64_372 = pPlayer->curr_weapon; } if (!REALITY) P_UpdateScreenPal(pPlayer); if (RR) { pPlayer->stairs = 0; pPlayer->noise_x = 0; pPlayer->noise_y = 0; pPlayer->make_noise = 0; pPlayer->noise_radius = 0; if ((g_netServer || ud.multimode > 1) && (g_gametypeFlags[ud.coop] & GAMETYPE_ACCESSATSTART)) { pPlayer->keys[0] = 1; pPlayer->keys[1] = 1; pPlayer->keys[2] = 1; pPlayer->keys[3] = 1; pPlayer->keys[4] = 1; } else { pPlayer->keys[0] = 0; pPlayer->keys[1] = 0; pPlayer->keys[2] = 0; pPlayer->keys[3] = 0; pPlayer->keys[4] = 0; } g_wupass = 0; pPlayer->drink_ang = pPlayer->eat_ang = 1647; pPlayer->drink_amt = pPlayer->eat_amt = 0; pPlayer->drink_timer = pPlayer->eat_timer = 4096; pPlayer->shotgun_state[0] = pPlayer->shotgun_state[1] = 0; pPlayer->hbomb_time = 0; pPlayer->hbomb_offset = 0; pPlayer->recoil = 0; pPlayer->yehaa_timer = 0; if (RRRA) { g_chickenWeaponTimer = 0; if (pPlayer->on_motorcycle) { pPlayer->on_motorcycle = 0; pPlayer->gotweapon &= ~(1 << MOTORCYCLE_WEAPON); pPlayer->curr_weapon = SLINGBLADE_WEAPON; } pPlayer->lotag800kill = 0; pPlayer->moto_do_bump = 0; pPlayer->moto_on_ground = 1; pPlayer->moto_underwater = 0; pPlayer->moto_speed = 0; pPlayer->tilt_status = 0; pPlayer->moto_drink = 0; pPlayer->moto_bump_target = 0; pPlayer->moto_bump = 0; pPlayer->moto_bump_fast = 0; pPlayer->moto_turb = 0; pPlayer->moto_on_mud = 0; pPlayer->moto_on_oil = 0; if (pPlayer->on_boat) { pPlayer->on_boat = 0; pPlayer->gotweapon &= ~(1 << BOAT_WEAPON); pPlayer->curr_weapon = SLINGBLADE_WEAPON; } pPlayer->not_on_water = 0; pPlayer->sea_sick = 0; pPlayer->nocheat = 0; pPlayer->drug_mode = 0; pPlayer->drug_stat[0] = 0; pPlayer->drug_stat[1] = 0; pPlayer->drug_stat[2] = 0; pPlayer->drug_aspect = 0; } A_ResetLanePics(); if (!g_netServer && numplayers < 2) { g_ufoSpawn = min(RRRA ? 3 : (ud.m_player_skill*4+1), 32); g_ufoCnt = 0; g_hulkSpawn = ud.m_player_skill + 1; } else { g_ufoSpawn = 32; g_ufoCnt = 0; g_hulkSpawn = 2; } } } void P_ResetWeapons(int playerNum) { DukePlayer_t *const pPlayer = g_player[playerNum].ps; for (bssize_t weaponNum = PISTOL_WEAPON; weaponNum < MAX_WEAPONS; weaponNum++) pPlayer->ammo_amount[weaponNum] = 0; pPlayer->weapon_pos = WEAPON_POS_START; pPlayer->curr_weapon = PISTOL_WEAPON; if (REALITY) pPlayer->dn64_372 = PISTOL_WEAPON; pPlayer->kickback_pic = 5; pPlayer->gotweapon = ((1 << PISTOL_WEAPON) | (1 << KNEE_WEAPON) | (1 << HANDREMOTE_WEAPON)); if (REALITY) pPlayer->gotweapon |= (1 << BOWLINGBALL_WEAPON); pPlayer->ammo_amount[PISTOL_WEAPON] = min<int16_t>(pPlayer->max_ammo_amount[PISTOL_WEAPON], 48); if (RRRA) { g_chickenWeaponTimer = 0; pPlayer->gotweapon |= (1 << SLINGBLADE_WEAPON); pPlayer->ammo_amount[KNEE_WEAPON] = 1; pPlayer->ammo_amount[SLINGBLADE_WEAPON] = 1; pPlayer->on_motorcycle = 0; pPlayer->moto_underwater = 0; pPlayer->on_boat = 0; pPlayer->lotag800kill = 0; } pPlayer->last_weapon = -1; pPlayer->show_empty_weapon = 0; pPlayer->last_pissed_time = 0; pPlayer->holster_weapon = 0; pPlayer->last_used_weapon = -1; VM_OnEvent(EVENT_RESETWEAPONS, pPlayer->i, playerNum); } void P_ResetInventory(int playerNum) { DukePlayer_t *const pPlayer = g_player[playerNum].ps; Bmemset(pPlayer->inv_amount, 0, sizeof(pPlayer->inv_amount)); pPlayer->scuba_on = 0; pPlayer->heat_on = 0; pPlayer->jetpack_on = 0; pPlayer->holoduke_on = -1; pPlayer->inven_icon = ICON_NONE; pPlayer->inv_amount[GET_SHIELD] = g_startArmorAmount; if (RR) { if ((g_netServer || ud.multimode > 1) && (g_gametypeFlags[ud.coop] & GAMETYPE_ACCESSATSTART)) { pPlayer->keys[0] = 1; pPlayer->keys[1] = 1; pPlayer->keys[2] = 1; pPlayer->keys[3] = 1; pPlayer->keys[4] = 1; } else { pPlayer->keys[0] = 0; pPlayer->keys[1] = 0; pPlayer->keys[2] = 0; pPlayer->keys[3] = 0; pPlayer->keys[4] = 0; } pPlayer->drink_ang = pPlayer->eat_ang = 1647; pPlayer->drink_amt = pPlayer->eat_amt = 0; pPlayer->drink_timer = pPlayer->eat_timer = 4096; pPlayer->shotgun_state[0] = pPlayer->shotgun_state[1] = 0; pPlayer->hbomb_time = 0; pPlayer->hbomb_offset = 0; pPlayer->recoil = 0; pPlayer->yehaa_timer = 0; A_ResetLanePics(); if (!g_netServer && numplayers < 2) { g_ufoSpawn = min(ud.m_player_skill*4+1, 32); g_ufoCnt = 0; g_hulkSpawn = ud.m_player_skill + 1; } else { g_ufoSpawn = 32; g_ufoCnt = 0; g_hulkSpawn = 2; } } VM_OnEvent(EVENT_RESETINVENTORY, pPlayer->i, playerNum); } static void resetprestat(int playerNum, int gameMode) { DukePlayer_t *const pPlayer = g_player[playerNum].ps; g_spriteDeleteQueuePos = 0; for (bssize_t i = 0; i < g_deleteQueueSize; i++) SpriteDeletionQueue[i] = -1; pPlayer->hbomb_on = 0; pPlayer->cheat_phase = 0; pPlayer->toggle_key_flag = 0; pPlayer->secret_rooms = 0; pPlayer->max_secret_rooms = 0; pPlayer->actors_killed = 0; pPlayer->max_actors_killed = 0; if (REALITY) { pPlayer->dn64_36e = 0; pPlayer->dn64_36d = 0; } pPlayer->lastrandomspot = 0; pPlayer->weapon_pos = WEAPON_POS_START; P_ResetTintFade(pPlayer); pPlayer->kickback_pic = 5; pPlayer->last_weapon = -1; pPlayer->weapreccnt = 0; pPlayer->interface_toggle_flag = 0; pPlayer->show_empty_weapon = 0; pPlayer->holster_weapon = 0; pPlayer->last_pissed_time = 0; pPlayer->one_parallax_sectnum = -1; pPlayer->visibility = ud.const_visibility; screenpeek = myconnectindex; g_animWallCnt = 0; g_cyclerCnt = 0; g_animateCnt = 0; parallaxtype = 0; randomseed = 17; ud.pause_on = 0; ud.camerasprite = -1; ud.eog = 0; tempwallptr = 0; g_curViewscreen = -1; g_earthquakeTime = 0; g_interpolationCnt = 0; if (RRRA) { g_windTime = 0; g_windDir = 0; g_fakeBubbaCnt = 0; g_RAendLevel = 0; g_bellTime = 0; g_bellSprite = 0; } if (((gameMode & MODE_EOL) != MODE_EOL && numplayers < 2 && !g_netServer) || (!(g_gametypeFlags[ud.coop] & GAMETYPE_PRESERVEINVENTORYDEATH) && numplayers > 1)) { P_ResetWeapons(playerNum); P_ResetInventory(playerNum); } else if (pPlayer->curr_weapon == HANDREMOTE_WEAPON) { pPlayer->ammo_amount[HANDBOMB_WEAPON]++; pPlayer->curr_weapon = HANDBOMB_WEAPON; } pPlayer->timebeforeexit = 0; pPlayer->customexitsound = REALITY ? -1 : 0; if (REALITY) { pPlayer->dn64_374 = 0; pPlayer->dn64_378 = 0; } if (RR) { pPlayer->stairs = 0; pPlayer->noise_x = 131072; pPlayer->noise_y = 131072; pPlayer->make_noise = 0; pPlayer->noise_radius = 0; if ((g_netServer || ud.multimode > 1) && (g_gametypeFlags[ud.coop] & GAMETYPE_ACCESSATSTART)) { pPlayer->keys[0] = 1; pPlayer->keys[1] = 1; pPlayer->keys[2] = 1; pPlayer->keys[3] = 1; pPlayer->keys[4] = 1; } else { pPlayer->keys[0] = 0; pPlayer->keys[1] = 0; pPlayer->keys[2] = 0; pPlayer->keys[3] = 0; pPlayer->keys[4] = 0; } pPlayer->drink_ang = pPlayer->eat_ang = 1647; pPlayer->drink_amt = pPlayer->eat_amt = 0; pPlayer->drink_timer = pPlayer->eat_timer = 4096; pPlayer->shotgun_state[0] = pPlayer->shotgun_state[1] = 0; pPlayer->hbomb_time = 0; pPlayer->hbomb_offset = 0; pPlayer->recoil = 0; pPlayer->yehaa_timer = 0; A_ResetLanePics(); if (!g_netServer && numplayers < 2) { g_ufoSpawn = min(ud.m_player_skill*4+1, 32); g_ufoCnt = 0; g_hulkSpawn = ud.m_player_skill + 1; } else { g_ufoSpawn = 32; g_ufoCnt = 0; g_hulkSpawn = 2; } } } static inline int G_CheckExitSprite(int spriteNum) { return ((uint16_t)sprite[spriteNum].lotag == UINT16_MAX && (sprite[spriteNum].cstat & 16)); } void G_InitRRRASkies(void) { if (!RRRA) return; for (bssize_t i = 0; i < MAXSECTORS; i++) { if (sector[i].ceilingpicnum != LA && sector[i].ceilingpicnum != MOONSKY1 && sector[i].ceilingpicnum != BIGORBIT1) { int const picnum = sector[i].ceilingpicnum; if (tilesiz[picnum].x == 512) { psky_t *sky = tileSetupSky(picnum); sky->horizfrac = 32768; sky->lognumtiles = 1; sky->tileofs[0] = 0; sky->tileofs[1] = 0; } else if (tilesiz[picnum].x == 1024) { psky_t *sky = tileSetupSky(picnum); sky->horizfrac = 32768; sky->lognumtiles = 0; sky->tileofs[0] = 0; } } } } static void prelevel(char g) { uint8_t *tagbitmap = (uint8_t *)Xcalloc(65536>>3, 1); int32_t p1 = 0, p2 = 0, p3 = 0; //DukePlayer_t *ps = g_player[screenpeek].ps; if (RRRA) { G_SetFog(0); g_fogType = 0; g_ufoSpawnMinion = 0; g_pistonSound = 0; g_slotWin = 0; g_changeEnemySize = 0; g_player[myconnectindex].ps->level_end_timer = 0; g_mamaSpawnCnt = 15; g_banjoSong = 0; g_RAendLevel = 0; if (!DEER) { for (bssize_t TRAVERSE_CONNECT(playerNum)) { DukePlayer_t *ps = g_player[playerNum].ps; ps->sea_sick_stat = 0; if (ud.level_number == 4 && ud.volume_number == 1) ps->inv_amount[GET_STEROIDS] = 0; } if (ud.level_number == 3 && ud.volume_number == 0) g_mamaSpawnCnt = 5; else if (ud.level_number == 2 && ud.volume_number == 1) g_mamaSpawnCnt = 10; else if (ud.level_number == 6 && ud.volume_number == 1) g_mamaSpawnCnt = 15; } } Bmemset(g_spriteExtra, 0, sizeof(g_spriteExtra)); Bmemset(g_sectorExtra, 0, sizeof(g_sectorExtra)); Bmemset(g_shadedSector, 0, sizeof(g_shadedSector)); Bmemset(g_geoSectorWarp, -1, sizeof(g_geoSectorWarp)); Bmemset(g_geoSectorWarp2, -1, sizeof(g_geoSectorWarp2)); Bmemset(g_ambientHitag, -1, sizeof(g_ambientHitag)); Bmemset(g_ambientLotag, -1, sizeof(g_ambientLotag)); Bmemset(show2dsector, 0, sizeof(show2dsector)); #ifdef LEGACY_ROR Bmemset(ror_protectedsectors, 0, MAXSECTORS); #endif resetprestat(0,g); if (RR) { g_lightninCnt = 0; g_torchCnt = 0; g_geoSectorCnt = 0; g_jailDoorCnt = 0; g_mineCartCnt = 0; g_ambientCnt = 0; g_thunderOn = 0; g_chickenPlant = 0; if (RRRA) { g_windTime = 0; g_windDir = 0; g_fakeBubbaCnt = 0; g_RAendLevel = 0; g_mamaSpawnCnt = 15; // ??? g_bellTime = 0; g_bellSprite = 0; for (bssize_t spriteNum = 0; spriteNum < MAXSPRITES; spriteNum++) { if (sprite[spriteNum].pal == 100) { if (g_netServer || numplayers > 1) A_DeleteSprite(spriteNum); else sprite[spriteNum].pal = 0; } else if (sprite[spriteNum].pal == 101) { sprite[spriteNum].extra = 0; sprite[spriteNum].hitag = 1; sprite[spriteNum].pal = 0; changespritestat(spriteNum, 118); } } } } g_cloudCnt = 0; int missedCloudSectors = 0; if (!DEER) for (bssize_t i=0; i<numsectors; i++) { if (RR && sector[i].ceilingpicnum == RRTILE2577) g_thunderOn = 1; sector[i].extra = 256; switch (sector[i].lotag) { case 41: { if (!RR) break; int k = headspritesect[i]; while (k != -1) { int const nexti = nextspritesect[k]; if (sprite[k].picnum == RRTILE11) { p1 = sprite[k].lotag << 4; p2 = sprite[k].hitag; A_DeleteSprite(k); } if (sprite[k].picnum == RRTILE38) { p3 = sprite[k].lotag; A_DeleteSprite(k); } k = nexti; } for (bssize_t j = 0; j<numsectors; j++) { if (sector[i].hitag == sector[j].hitag && i != j) { if (g_jailDoorCnt >= 32) G_GameExit("\nToo many jaildoor sectors"); g_jailDoorDist[g_jailDoorCnt] = p1; g_jailDoorSpeed[g_jailDoorCnt] = p2; g_jailDoorSecHitag[g_jailDoorCnt] = sector[i].hitag; g_jailDoorSect[g_jailDoorCnt] = j; g_jailDoorDrag[g_jailDoorCnt] = 0; g_jailDoorOpen[g_jailDoorCnt] = 0; g_jailDoorDir[g_jailDoorCnt] = sector[j].lotag; g_jailDoorSound[g_jailDoorCnt] = p3; g_jailDoorCnt++; } } break; } case 42: { if (!RR) break; int k = headspritesect[i]; while (k != -1) { int const nexti = nextspritesect[k]; if (sprite[k].picnum == RRTILE64) { p1 = sprite[k].lotag << 4; p2 = sprite[k].hitag; for (bssize_t kk = 0; kk < MAXSPRITES; kk++) { if (sprite[kk].picnum == RRTILE66) if (sprite[kk].lotag == sprite[k].sectnum) { g_mineCartChildSect[g_mineCartCnt] = sprite[kk].sectnum; A_DeleteSprite(kk); } } A_DeleteSprite(k); } if (sprite[k].picnum == RRTILE65) { p3 = sprite[k].lotag; A_DeleteSprite(k); } k = nexti; } if (g_mineCartCnt >= 16) G_GameExit("\nToo many minecart sectors"); g_mineCartDist[g_mineCartCnt] = p1; g_mineCartSpeed[g_mineCartCnt] = p2; g_mineCartSect[g_mineCartCnt] = i; g_mineCartDir[g_mineCartCnt] = sector[i].hitag; g_mineCartDrag[g_mineCartCnt] = p1; g_mineCartOpen[g_mineCartCnt] = 1; g_mineCartSound[g_mineCartCnt] = p3; g_mineCartCnt++; break; } case ST_20_CEILING_DOOR: case ST_22_SPLITTING_DOOR: if (sector[i].floorz > sector[i].ceilingz) sector[i].lotag |= 32768u; continue; } if (sector[i].ceilingstat&1) { if (waloff[sector[i].ceilingpicnum] == 0) { if (sector[i].ceilingpicnum == LA) for (bsize_t j = 0; j < 5; j++) tloadtile(sector[i].ceilingpicnum + j, 0); } if (!RR && sector[i].ceilingpicnum == CLOUDYSKIES) { if (g_cloudCnt < ARRAY_SSIZE(g_cloudSect)) g_cloudSect[g_cloudCnt++] = i; else missedCloudSectors++; } if (g_player[0].ps->one_parallax_sectnum == -1) g_player[0].ps->one_parallax_sectnum = i; } if (sector[i].lotag == 32767) //Found a secret room { g_player[0].ps->max_secret_rooms++; continue; } if ((uint16_t)sector[i].lotag == UINT16_MAX) { g_player[0].ps->exitx = wall[sector[i].wallptr].x; g_player[0].ps->exity = wall[sector[i].wallptr].y; continue; } } if (missedCloudSectors > 0) OSD_Printf(OSDTEXT_RED "Map warning: have %d unhandled CLOUDYSKIES ceilings.\n", missedCloudSectors); // NOTE: must be safe loop because callbacks could delete sprites. if (!DEER) for (bssize_t nextSprite, SPRITES_OF_STAT_SAFE(STAT_DEFAULT, i, nextSprite)) { //A_LoadActor(i); if (G_CheckExitSprite(i)) { g_player[0].ps->exitx = SX(i); g_player[0].ps->exity = SY(i); } else switch (DYNAMICTILEMAP(PN(i))) { case NUKEBUTTON__STATIC: if (RR) g_chickenPlant = 1; break; case GPSPEED__STATIC: // DELETE_AFTER_LOADACTOR. Must not change statnum. sector[SECT(i)].extra = SLT(i); A_DeleteSprite(i); break; case CYCLER__STATIC: // DELETE_AFTER_LOADACTOR. Must not change statnum. if (g_cyclerCnt >= MAXCYCLERS) { Bsprintf(tempbuf,"\nToo many cycling sectors (%d max).",MAXCYCLERS); G_GameExit(tempbuf); } g_cyclers[g_cyclerCnt][0] = SECT(i); g_cyclers[g_cyclerCnt][1] = SLT(i); g_cyclers[g_cyclerCnt][2] = SS(i); g_cyclers[g_cyclerCnt][3] = sector[SECT(i)].floorshade; g_cyclers[g_cyclerCnt][4] = SHT(i); g_cyclers[g_cyclerCnt][5] = (SA(i) == 1536); g_cyclerCnt++; A_DeleteSprite(i); break; case RRTILE18__STATICRR: if (!RR) break; if (g_torchCnt >= 64) G_GameExit("\nToo many torch effects"); g_torchSector[g_torchCnt] = SECT(i); g_torchSectorShade[g_torchCnt] = sector[SECT(i)].floorshade; g_torchType[g_torchCnt] = SLT(i); g_torchCnt++; A_DeleteSprite(i); break; case RRTILE35__STATICRR: if (g_lightninCnt >= 64) G_GameExit("\nToo many lightnin effects"); g_lightninSector[g_lightninCnt] = SECT(i); g_lightninSectorShade[g_lightninCnt] = sector[SECT(i)].floorshade; g_lightninCnt++; A_DeleteSprite(i); break; case RRTILE68__STATICRR: g_shadedSector[SECT(i)] = 1; A_DeleteSprite(i); break; case RRTILE67__STATICRR: sprite[i].cstat |= 32768; break; case SOUNDFX__STATICRR: if (g_ambientCnt >= 64) G_GameExit("\nToo many ambient effects"); else { g_ambientHitag[g_ambientCnt] = SHT(i); g_ambientLotag[g_ambientCnt] = SLT(i); sprite[i].ang = g_ambientCnt++; sprite[i].lotag = 0; sprite[i].hitag = 0; } break; //case SECTOREFFECTOR__STATIC: //case ACTIVATOR__STATIC: //case TOUCHPLATE__STATIC: //case ACTIVATORLOCKED__STATIC: //case MUSICANDSFX__STATIC: //case LOCATORS__STATIC: //case MASTERSWITCH__STATIC: //case RESPAWN__STATIC: // sprite[i].cstat &= ~(1|16|32|256); // break; } } if (RR && !DEER) { for (bssize_t i = 0; i < MAXSPRITES; i++) { if (sprite[i].picnum == RRTILE19) { if (sprite[i].hitag == 0) { if (g_geoSectorCnt >= MAXGEOSECTORS) G_GameExit("\nToo many geometry effects"); g_geoSector[g_geoSectorCnt] = sprite[i].sectnum; for (bssize_t j = 0; j < MAXSPRITES; j++) { if (sprite[i].lotag == sprite[j].lotag && i != j && sprite[j].picnum == RRTILE19) { if (sprite[j].hitag == 1) { g_geoSectorWarp[g_geoSectorCnt] = sprite[j].sectnum; g_geoSectorX[g_geoSectorCnt] = sprite[i].x - sprite[j].x; g_geoSectorY[g_geoSectorCnt] = sprite[i].y - sprite[j].y; } if (sprite[j].hitag == 2) { g_geoSectorWarp2[g_geoSectorCnt] = sprite[j].sectnum; g_geoSectorX2[g_geoSectorCnt] = sprite[i].x - sprite[j].x; g_geoSectorY2[g_geoSectorCnt] = sprite[i].y - sprite[j].y; } } } g_geoSectorCnt++; } } } } for (size_t i = 0; i < MAXSPRITES; i++) { if (sprite[i].statnum < MAXSTATUS && (DEER || PN(i) != SECTOREFFECTOR || SLT(i) != SE_14_SUBWAY_CAR)) A_Spawn(-1, i); } if (!DEER) for (size_t i = 0; i < MAXSPRITES; i++) { if (sprite[i].statnum < MAXSTATUS && PN(i) == SECTOREFFECTOR && SLT(i) == SE_14_SUBWAY_CAR) A_Spawn(-1, i); if (RR && sprite[i].picnum == RRTILE19) A_DeleteSprite(i); if (RR && sprite[i].picnum == RRTILE34) { g_sectorExtra[sprite[i].sectnum] = sprite[i].lotag; A_DeleteSprite(i); } } //G_SetupRotfixedSprites(); if (!DEER) for (bssize_t i=headspritestat[STAT_DEFAULT]; i>=0; i=nextspritestat[i]) { if (PN(i) <= 0) // oob safety for switch below continue; for (bsize_t ii=0; ii<2; ii++) { switch (DYNAMICTILEMAP(PN(i)-1+ii)) { case DIPSWITCH__STATIC: case DIPSWITCH2__STATIC: case PULLSWITCH__STATIC: case HANDSWITCH__STATIC: case SLOTDOOR__STATIC: case LIGHTSWITCH__STATIC: case SPACELIGHTSWITCH__STATIC: case SPACEDOORSWITCH__STATIC: case FRANKENSTINESWITCH__STATIC: case LIGHTSWITCH2__STATIC: case POWERSWITCH1__STATIC: case LOCKSWITCH1__STATIC: case POWERSWITCH2__STATIC: case RRTILE8464__STATICRR: if (RR && !RRRA && PN(i)-1+ii == (uint32_t)RRTILE8464) break; // the lower code only for the 'on' state (*) if (ii==0) { uint16_t const tag = sprite[i].lotag; tagbitmap[tag>>3] |= 1<<(tag&7); } break; } } } // initially 'on' SE 12 light (*) if (!DEER) for (bssize_t j=headspritestat[STAT_EFFECTOR]; j>=0; j=nextspritestat[j]) { uint16_t const tag = sprite[j].hitag; if (sprite[j].lotag == SE_12_LIGHT_SWITCH && tagbitmap[tag>>3]&(1<<(tag&7))) actor[j].t_data[0] = 1; } Xfree(tagbitmap); g_mirrorCount = 0; for (bssize_t i = 0; i < numwalls; i++) { walltype * const pWall = &wall[i]; if (!DEER && pWall->overpicnum == MIRROR && (pWall->cstat&32) != 0) { int const nextSectnum = pWall->nextsector; if ((nextSectnum >= 0) && sector[nextSectnum].ceilingpicnum != MIRROR) { if (g_mirrorCount > 63) { G_GameExit("\nToo many mirrors (64 max.)"); } sector[nextSectnum].ceilingpicnum = MIRROR; sector[nextSectnum].floorpicnum = MIRROR; g_mirrorWall[g_mirrorCount] = i; g_mirrorSector[g_mirrorCount] = nextSectnum; g_mirrorCount++; continue; } } if (g_animWallCnt >= MAXANIMWALLS) { Bsprintf(tempbuf,"\nToo many 'anim' walls (%d max).",MAXANIMWALLS); G_GameExit(tempbuf); } animwall[g_animWallCnt].tag = 0; animwall[g_animWallCnt].wallnum = 0; if (DEER) { pWall->extra = -1; continue; } int const switchPic = G_GetForcefieldPicnum(i); if (switchPic >= 0) { switch (DYNAMICTILEMAP(switchPic)) { case FANSHADOW__STATIC: if (RR) break; fallthrough__; case FANSPRITE__STATIC: wall->cstat |= 65; animwall[g_animWallCnt].wallnum = i; g_animWallCnt++; break; case W_FORCEFIELD__STATIC: if (RR) break; if (pWall->overpicnum == W_FORCEFIELD__STATIC) for (bsize_t j = 0; j < 3; j++) tloadtile(W_FORCEFIELD + j, 0); if (pWall->shade > 31) pWall->cstat = 0; else pWall->cstat |= FORCEFIELD_CSTAT | 256; if (pWall->lotag && pWall->nextwall >= 0) wall[pWall->nextwall].lotag = pWall->lotag; fallthrough__; case BIGFORCE__STATIC: animwall[g_animWallCnt].wallnum = i; g_animWallCnt++; continue; } } pWall->extra = -1; switch (DYNAMICTILEMAP(pWall->picnum)) { case WATERTILE2__STATIC: for (bsize_t j = 0; j < 3; j++) tloadtile(pWall->picnum + j, 0); break; case RRTILE1814__STATICRR: case RRTILE1817__STATICRR: tloadtile(pWall->picnum, 0); break; case RRTILE1939__STATICRR: case RRTILE1986__STATICRR: case RRTILE1987__STATICRR: case RRTILE1988__STATICRR: case RRTILE2004__STATICRR: case RRTILE2005__STATICRR: case RRTILE2123__STATICRR: case RRTILE2124__STATICRR: case RRTILE2125__STATICRR: case RRTILE2126__STATICRR: case RRTILE2636__STATICRR: case RRTILE2637__STATICRR: case RRTILE2878__STATICRR: case RRTILE2879__STATICRR: case RRTILE2898__STATICRR: case RRTILE2899__STATICRR: tloadtile(pWall->picnum, 0); break; case TECHLIGHT2__STATIC: case TECHLIGHT4__STATIC: tloadtile(pWall->picnum, 0); break; case W_TECHWALL1__STATIC: case W_TECHWALL2__STATIC: case W_TECHWALL3__STATIC: case W_TECHWALL4__STATIC: if (RR) break; animwall[g_animWallCnt].wallnum = i; // animwall[g_numAnimWalls].tag = -1; g_animWallCnt++; break; case SCREENBREAK6__STATIC: case SCREENBREAK7__STATIC: case SCREENBREAK8__STATIC: for (bssize_t j = SCREENBREAK6; j < SCREENBREAK9; j++) tloadtile(j, 0); animwall[g_animWallCnt].wallnum = i; animwall[g_animWallCnt].tag = -1; g_animWallCnt++; break; case FEMPIC1__STATIC: case FEMPIC2__STATIC: case FEMPIC3__STATIC: if (RR) break; pWall->extra = pWall->picnum; animwall[g_animWallCnt].tag = -1; if (ud.lockout) pWall->picnum = (pWall->picnum == FEMPIC1) ? BLANKSCREEN : SCREENBREAK6; animwall[g_animWallCnt].wallnum = i; animwall[g_animWallCnt].tag = pWall->picnum; g_animWallCnt++; break; case SCREENBREAK1__STATIC: case SCREENBREAK2__STATIC: case SCREENBREAK3__STATIC: case SCREENBREAK4__STATIC: case SCREENBREAK5__STATIC: // case SCREENBREAK9__STATIC: case SCREENBREAK10__STATIC: case SCREENBREAK11__STATIC: case SCREENBREAK12__STATIC: case SCREENBREAK13__STATIC: case SCREENBREAK14__STATIC: case SCREENBREAK15__STATIC: case SCREENBREAK16__STATIC: case SCREENBREAK17__STATIC: case SCREENBREAK18__STATIC: case SCREENBREAK19__STATIC: if (RR) break; animwall[g_animWallCnt].wallnum = i; animwall[g_animWallCnt].tag = pWall->picnum; g_animWallCnt++; break; } } //Invalidate textures in sector behind mirror for (bssize_t i=0; i<g_mirrorCount; i++) { int const startWall = sector[g_mirrorSector[i]].wallptr; int const endWall = startWall + sector[g_mirrorSector[i]].wallnum; for (bssize_t j = startWall; j < endWall; j++) { wall[j].picnum = MIRROR; wall[j].overpicnum = MIRROR; } } if (RR && !g_thunderOn) { videoSetPalette(ud.brightness >> 2,BASEPAL,0); g_visibility = g_player[screenpeek].ps->visibility; } if (RR) { tilesiz[0].x = 0; tilesiz[0].y = 0; } G_SetupGlobalPsky(); if (DEER) sub_52BA8(); } void G_NewGame(int volumeNum, int levelNum, int skillNum) { DukePlayer_t *const pPlayer = g_player[0].ps; G_HandleAsync(); if (g_skillSoundVoice >= 0 && ud.config.SoundToggle) { while (FX_SoundActive(g_skillSoundVoice)) G_HandleAsync(); } g_skillSoundVoice = -1; ready2send = 0; if (ud.m_recstat != 2 && ud.last_level >= 0 && (g_netServer || ud.multimode > 1) && (ud.coop&GAMETYPE_SCORESHEET)) { if (!RRRA || g_mostConcurrentPlayers > 1 || g_netServer || numplayers > 1) G_BonusScreen(1); else G_BonusScreenRRRA(1); } if (RR && !RRRA && g_turdLevel && !g_lastLevel) G_BonusScreen(0); g_showShareware = GAMETICSPERSEC*34; if (REALITY) rt_levelnum = levelNum; ud.level_number = levelNum; ud.volume_number = volumeNum; ud.player_skill = skillNum; ud.secretlevel = 0; ud.from_bonus = 0; ud.last_level = -1; g_lastAutoSaveArbitraryID = -1; g_lastautosave.reset(); g_lastusersave.reset(); g_quickload = nullptr; int const UserMap = Menu_HaveUserMap(); if (REALITY && (!g_netServer && ud.multimode < 2) && UserMap == 0 && levelNum == 0) RT_Intro(); // we don't want the intro to play after the multiplayer setup screen if (!RR && (!g_netServer && ud.multimode < 2) && UserMap == 0 && levelNum == 0 && volumeNum == 3 && ud.lockout == 0) { S_PlaySpecialMusicOrNothing(MUS_BRIEFING); renderFlushPerms(); videoSetViewableArea(0,0,xdim-1,ydim-1); videoClearViewableArea(0L); videoNextPage(); int animReturn = Anim_Play("vol41a.anm"); videoClearViewableArea(0L); videoNextPage(); if (animReturn) goto end_vol4a; animReturn = Anim_Play("vol42a.anm"); videoClearViewableArea(0L); videoNextPage(); if (animReturn) goto end_vol4a; Anim_Play("vol43a.anm"); videoClearViewableArea(0L); videoNextPage(); end_vol4a: FX_StopAllSounds(); } #ifdef EDUKE32_TOUCH_DEVICES pPlayer->zoom = 360; #else pPlayer->zoom = 768; #endif pPlayer->gm = 0; Menu_Close(0); Gv_ResetVars(); Gv_InitWeaponPointers(); Gv_RefreshPointers(); Gv_ResetSystemDefaults(); //AddLog("Newgame"); for (bssize_t i=0; i<(MAXVOLUMES*MAXLEVELS); i++) G_FreeMapState(i); if (ud.m_coop != 1) { for (bssize_t weaponNum = 0; weaponNum < MAX_WEAPONS; weaponNum++) { auto const worksLike = WW2GI ? PWEAPON(0, weaponNum, WorksLike) : weaponNum; if (worksLike == PISTOL_WEAPON) { pPlayer->curr_weapon = weaponNum; pPlayer->gotweapon |= (1 << weaponNum); pPlayer->ammo_amount[weaponNum] = min<int16_t>(pPlayer->max_ammo_amount[weaponNum], 48); } else if (worksLike == KNEE_WEAPON || (!RR && worksLike == HANDREMOTE_WEAPON) || (RRRA && worksLike == SLINGBLADE_WEAPON)) { pPlayer->gotweapon |= (1 << weaponNum); if (RRRA) pPlayer->ammo_amount[KNEE_WEAPON] = 1; } } pPlayer->last_weapon = -1; } display_mirror = 0; if (ud.multimode > 1) { if (numplayers < 2) { connecthead = 0; for (int i = 0; i < MAXPLAYERS; i++) connectpoint2[i] = i + 1; connectpoint2[ud.multimode - 1] = -1; } } else { connecthead = 0; connectpoint2[0] = -1; } } static void resetpspritevars(char gameMode) { int16_t i, j; //circ; uint8_t aimmode[MAXPLAYERS],autoaim[MAXPLAYERS],weaponswitch[MAXPLAYERS]; DukeStatus_t tsbar[MAXPLAYERS]; if (g_player[0].ps->cursectnum >= 0) // < 0 may happen if we start a map in void space (e.g. testing it) { A_InsertSprite(g_player[0].ps->cursectnum,g_player[0].ps->pos.x,g_player[0].ps->pos.y,g_player[0].ps->pos.z, APLAYER,0,0,0,fix16_to_int(g_player[0].ps->q16ang),0,0,0,10); } if (ud.recstat != 2) for (TRAVERSE_CONNECT(i)) { aimmode[i] = g_player[i].ps->aim_mode; autoaim[i] = g_player[i].ps->auto_aim; weaponswitch[i] = g_player[i].ps->weaponswitch; if ((g_netServer || ud.multimode > 1) && (g_gametypeFlags[ud.coop]&GAMETYPE_PRESERVEINVENTORYDEATH) && ud.last_level >= 0) { for (j=0; j<MAX_WEAPONS; j++) tsbar[i].ammo_amount[j] = g_player[i].ps->ammo_amount[j]; tsbar[i].gotweapon = g_player[i].ps->gotweapon; Bmemcpy(tsbar[i].inv_amount, g_player[i].ps->inv_amount, sizeof(tsbar[i].inv_amount)); tsbar[i].curr_weapon = g_player[i].ps->curr_weapon; tsbar[i].inven_icon = g_player[i].ps->inven_icon; } } P_ResetStatus(0); for (TRAVERSE_CONNECT(i)) { if (i) Bmemcpy(g_player[i].ps,g_player[0].ps,sizeof(DukePlayer_t)); if (REALITY) P_PalFrom(g_player[i].ps, 64, 0, 0, 0); } if (ud.recstat != 2) for (TRAVERSE_CONNECT(i)) { g_player[i].ps->aim_mode = aimmode[i]; g_player[i].ps->auto_aim = autoaim[i]; g_player[i].ps->weaponswitch = weaponswitch[i]; if ((g_netServer || ud.multimode > 1) && (g_gametypeFlags[ud.coop]&GAMETYPE_PRESERVEINVENTORYDEATH) && ud.last_level >= 0) { for (j=0; j<MAX_WEAPONS; j++) g_player[i].ps->ammo_amount[j] = tsbar[i].ammo_amount[j]; g_player[i].ps->gotweapon = tsbar[i].gotweapon; g_player[i].ps->curr_weapon = tsbar[i].curr_weapon; g_player[i].ps->inven_icon = tsbar[i].inven_icon; Bmemcpy(g_player[i].ps->inv_amount, tsbar[i].inv_amount, sizeof(tsbar[i].inv_amount)); } } g_playerSpawnCnt = 0; // circ = 2048/ud.multimode; g_whichPalForPlayer = 9; j = 0; i = headspritestat[STAT_PLAYER]; while (i >= 0) { const int32_t nexti = nextspritestat[i]; spritetype *const s = &sprite[i]; if (g_playerSpawnCnt == MAXPLAYERS) G_GameExit("\nToo many player sprites (max 16.)"); g_playerSpawnPoints[g_playerSpawnCnt].pos.x = s->x; g_playerSpawnPoints[g_playerSpawnCnt].pos.y = s->y; g_playerSpawnPoints[g_playerSpawnCnt].pos.z = s->z; g_playerSpawnPoints[g_playerSpawnCnt].ang = s->ang; g_playerSpawnPoints[g_playerSpawnCnt].sect = s->sectnum; g_playerSpawnCnt++; if (j < MAXPLAYERS) { s->owner = i; s->shade = 0; s->xrepeat = RR ? 24 : 42; s->yrepeat = RR ? 17 : 36; //s->xrepeat = 42; //s->yrepeat = 36; s->cstat = j < ud.multimode ? 1+256 : 32768; s->xoffset = 0; s->clipdist = 64; if (j < g_mostConcurrentPlayers) { if ((gameMode&MODE_EOL) != MODE_EOL || g_player[j].ps->last_extra == 0) { g_player[j].ps->last_extra = g_player[j].ps->max_player_health; s->extra = g_player[j].ps->max_player_health; g_player[j].ps->runspeed = g_playerFriction; } else s->extra = g_player[j].ps->last_extra; s->yvel = j; if (!g_player[j].pcolor && (g_netServer || ud.multimode > 1) && !(g_gametypeFlags[ud.coop] & GAMETYPE_TDM)) { if (s->pal == 0) { int32_t k = 0; for (; k<ud.multimode; k++) { if (g_whichPalForPlayer == g_player[k].ps->palookup) { g_whichPalForPlayer++; if (g_whichPalForPlayer >= 17) g_whichPalForPlayer = 9; k=0; } } g_player[j].pcolor = s->pal = g_player[j].ps->palookup = g_whichPalForPlayer++; if (g_whichPalForPlayer >= 17) g_whichPalForPlayer = 9; } else g_player[j].pcolor = g_player[j].ps->palookup = s->pal; } else { int32_t k = g_player[j].pcolor; if (g_gametypeFlags[ud.coop] & GAMETYPE_TDM) { k = G_GetTeamPalette(g_player[j].pteam); g_player[j].ps->team = g_player[j].pteam; } s->pal = g_player[j].ps->palookup = k; } g_player[j].ps->i = i; g_player[j].ps->frag_ps = j; actor[i].owner = i; g_player[j].ps->autostep = (20L<<8); g_player[j].ps->autostep_sbw = (4L<<8); actor[i].bpos.x = g_player[j].ps->bobpos.x = g_player[j].ps->opos.x = g_player[j].ps->pos.x = s->x; actor[i].bpos.y = g_player[j].ps->bobpos.y = g_player[j].ps->opos.y = g_player[j].ps->pos.y = s->y; actor[i].bpos.z = g_player[j].ps->opos.z = g_player[j].ps->pos.z = s->z; g_player[j].ps->oq16ang = g_player[j].ps->q16ang = fix16_from_int(s->ang); updatesector(s->x,s->y,&g_player[j].ps->cursectnum); } j++; } else A_DeleteSprite(i); i = nexti; } } static inline void clearfrags(void) { for (bssize_t i = 0; i < ud.multimode; i++) { playerdata_t *const pPlayerData = &g_player[i]; pPlayerData->ps->frag = pPlayerData->ps->fraggedself = 0; Bmemset(pPlayerData->frags, 0, sizeof(pPlayerData->frags)); } } void G_ResetTimers(uint8_t keepgtics) { totalclock = g_cloudClock = ototalclock = lockclock = 0; ready2send = 1; g_levelTextTime = 85; if (!keepgtics) g_moveThingsCount = 0; if (g_curViewscreen >= 0) actor[g_curViewscreen].t_data[0] = 0; } void G_ClearFIFO(void) { Net_ClearFIFO(); clearbufbyte(&localInput, sizeof(input_t), 0L); clearbufbyte(&inputfifo, sizeof(input_t) * MOVEFIFOSIZ * MAXPLAYERS, 0L); for (bsize_t p = 0; p <= MAXPLAYERS - 1; ++p) { if (g_player[p].inputBits != NULL) Bmemset(g_player[p].inputBits, 0, sizeof(input_t)); g_player[p].vote = g_player[p].gotvote = 0; } } int G_FindLevelByFile(const char *fileName) { for (bssize_t volumeNum = 0; volumeNum < MAXVOLUMES; volumeNum++) { int const volOffset = volumeNum * MAXLEVELS; for (bssize_t levelNum = 0; levelNum < MAXLEVELS; levelNum++) { if (g_mapInfo[volOffset + levelNum].filename == NULL) continue; if (!Bstrcasecmp(fileName, g_mapInfo[volOffset + levelNum].filename)) return volOffset + levelNum; } } return MAXLEVELS * MAXVOLUMES; } #if 0 static void G_FadeLoad(int32_t r, int32_t g, int32_t b, int32_t start, int32_t end, int32_t step, int32_t ticwait, int32_t tc) { int32_t m = (step < 0) ? -1 : 1; int32_t nexttic = totalclock; for (; m*start <= m*end; start += step) { while (totalclock < nexttic) sampletimer(); nexttic += ticwait; if (KB_KeyPressed(sc_Space)) { KB_ClearKeyDown(sc_Space); return; } setpalettefade(r,g,b,start); flushperms(); G_DoLoadScreen(" ", tc); } } #endif static int G_TryMapHack(const char *mhkfile) { int32_t failure = engineLoadMHK(mhkfile); if (!failure) initprintf("Loaded map hack file \"%s\"\n", mhkfile); return failure; } static void G_LoadMapHack(char *outbuf, const char *filename) { if (filename != NULL) Bstrcpy(outbuf, filename); append_ext_UNSAFE(outbuf, ".mhk"); if (G_TryMapHack(outbuf) && usermaphacks != NULL) { usermaphack_t *pMapInfo = (usermaphack_t*)bsearch( &g_loadedMapHack, usermaphacks, num_usermaphacks, sizeof(usermaphack_t), compare_usermaphacks); if (pMapInfo) G_TryMapHack(pMapInfo->mhkfile); } } // levnamebuf should have at least size BMAX_PATH void G_SetupFilenameBasedMusic(char *nameBuf, const char *fileName, int levelNum) { char *p; char const *exts[] = { #ifdef HAVE_FLAC "flac", #endif #ifdef HAVE_VORBIS "ogg", #endif "mid" }; Bstrncpy(nameBuf, fileName, BMAX_PATH); Bcorrectfilename(nameBuf, 0); if (NULL == (p = Bstrrchr(nameBuf, '.'))) { p = nameBuf + Bstrlen(nameBuf); p[0] = '.'; } for (auto & ext : exts) { int32_t kFile; Bmemcpy(p+1, ext, Bstrlen(ext) + 1); if ((kFile = kopen4loadfrommod(nameBuf, 0)) != -1) { kclose(kFile); realloc_copy(&g_mapInfo[levelNum].musicfn, nameBuf); return; } } realloc_copy(&g_mapInfo[levelNum].musicfn, "dethtoll.mid"); } int G_EnterLevel(int gameMode) { int32_t i, mii; char levelName[BMAX_PATH]; // flushpackets(); // waitforeverybody(); vote_map = vote_episode = voting = -1; ud.respawn_monsters = ud.m_respawn_monsters; ud.respawn_items = ud.m_respawn_items; ud.respawn_inventory = ud.m_respawn_inventory; ud.monsters_off = ud.m_monsters_off; ud.coop = ud.m_coop; ud.marker = ud.m_marker; ud.ffire = ud.m_ffire; ud.noexits = ud.m_noexits; if (REALITY) { ud.volume_number = 0; ud.level_number = rt_levelnum; } if ((gameMode & MODE_DEMO) != MODE_DEMO) ud.recstat = ud.m_recstat; if ((gameMode & MODE_DEMO) == 0 && ud.recstat == 2) ud.recstat = 0; VM_OnEvent(EVENT_ENTERLEVEL); //if (g_networkMode != NET_DEDICATED_SERVER) { S_PauseSounds(false); FX_StopAllSounds(); S_ClearSoundLocks(); FX_SetReverb(0); videoSetGameMode(ud.setup.fullscreen, ud.setup.xdim, ud.setup.ydim, ud.setup.bpp, upscalefactor); } if (Menu_HaveUserMap()) { Bcorrectfilename(boardfilename,0); int levelNum = G_FindLevelByFile(boardfilename); if (levelNum != MAXLEVELS*MAXVOLUMES) { int volumeNum = levelNum; levelNum &= MAXLEVELS-1; volumeNum = (volumeNum - levelNum) / MAXLEVELS; ud.level_number = ud.m_level_number = levelNum; ud.volume_number = ud.m_volume_number = volumeNum; boardfilename[0] = 0; } } mii = (ud.volume_number*MAXLEVELS)+ud.level_number; if (!REALITY && (g_mapInfo[mii].name == NULL || g_mapInfo[mii].filename == NULL)) { if (RR && g_lastLevel) { if (g_mapInfo[mii].filename == NULL) g_mapInfo[mii].filename = (char *)Xcalloc(BMAX_PATH, sizeof(uint8_t)); if (g_mapInfo[mii].name == NULL) g_mapInfo[mii].name = Xstrdup("CLOSE ENCOUNTERS"); } else if (Menu_HaveUserMap()) { if (g_mapInfo[mii].filename == NULL) g_mapInfo[mii].filename = (char *)Xcalloc(BMAX_PATH, sizeof(uint8_t)); if (g_mapInfo[mii].name == NULL) g_mapInfo[mii].name = Xstrdup("User Map"); } else { OSD_Printf(OSDTEXT_RED "Map E%dL%d not defined!\n", ud.volume_number+1, ud.level_number+1); return 1; } } i = ud.screen_size; ud.screen_size = 0; G_DoLoadScreen("Loading map . . .", -1); G_UpdateScreenArea(); ud.screen_size = i; if (Menu_HaveUserMap()) { if (g_gameNamePtr) Bsnprintf(apptitle, sizeof(apptitle), "%s - %s - " APPNAME, boardfilename, g_gameNamePtr); else Bsnprintf(apptitle, sizeof(apptitle), "%s - " APPNAME, boardfilename); } else { if (g_gameNamePtr) Bsprintf(apptitle, "%s - %s - " APPNAME, g_mapInfo[mii].name, g_gameNamePtr); else Bsprintf(apptitle,"%s - " APPNAME,g_mapInfo[mii].name); } Bstrcpy(tempbuf,apptitle); wm_setapptitle(tempbuf); DukePlayer_t *const pPlayer = g_player[0].ps; int16_t lbang; if (RR && g_lastLevel) { if (engineLoadBoard("endgame.map", 0, &pPlayer->pos, &lbang, &pPlayer->cursectnum) < 0) { OSD_Printf(OSD_ERROR "Map \"endgame.map\" not found or invalid map version!\n"); return 1; } G_LoadMapHack(levelName, "endgame.map"); G_SetupFilenameBasedMusic(levelName, "endgame.map", ud.m_level_number); } else if (!VOLUMEONE && Menu_HaveUserMap()) { if (engineLoadBoard(boardfilename, 0, &pPlayer->pos, &lbang, &pPlayer->cursectnum) < 0) { OSD_Printf(OSD_ERROR "Map \"%s\" not found or invalid map version!\n", boardfilename); return 1; } G_LoadMapHack(levelName, boardfilename); G_SetupFilenameBasedMusic(levelName, boardfilename, ud.m_level_number); } else if (REALITY) { RT_LoadBoard(rt_levelnum); } else if (engineLoadBoard(g_mapInfo[mii].filename, VOLUMEONE, &pPlayer->pos, &lbang, &pPlayer->cursectnum) < 0) { OSD_Printf(OSD_ERROR "Map \"%s\" not found or invalid map version!\n", g_mapInfo[mii].filename); return 1; } else { G_LoadMapHack(levelName, g_mapInfo[mii].filename); } if (RR && !RRRA && ud.volume_number == 1 && ud.level_number == 1) { for (bssize_t i = PISTOL_WEAPON; i < MAX_WEAPONS; i++) g_player[0].ps->ammo_amount[i] = 0; g_player[0].ps->gotweapon &= (1<<KNEE_WEAPON); } if (!REALITY) pPlayer->q16ang = fix16_from_int(lbang); g_precacheCount = 0; Bmemset(gotpic, 0, sizeof(gotpic)); Bmemset(precachehightile, 0, sizeof(precachehightile)); //clearbufbyte(Actor,sizeof(Actor),0l); // JBF 20040531: yes? no? prelevel(gameMode); G_InitRRRASkies(); if (RRRA && ud.level_number == 2 && ud.volume_number == 0) { for (bssize_t i = PISTOL_WEAPON; i < MAX_WEAPONS; i++) g_player[0].ps->ammo_amount[i] = 0; g_player[0].ps->gotweapon &= (1<<KNEE_WEAPON); g_player[0].ps->gotweapon |= (1<<SLINGBLADE_WEAPON); g_player[0].ps->ammo_amount[SLINGBLADE_WEAPON] = 1; g_player[0].ps->curr_weapon = SLINGBLADE_WEAPON; } G_AlignWarpElevators(); resetpspritevars(gameMode); ud.playerbest = CONFIG_GetMapBestTime(Menu_HaveUserMap() ? boardfilename : g_mapInfo[mii].filename, g_loadedMapHack.md4); // G_FadeLoad(0,0,0, 252,0, -28, 4, -1); G_CacheMapData(); // G_FadeLoad(0,0,0, 0,252, 28, 4, -2); if (ud.recstat != 2) { if (g_mapInfo[g_musicIndex].musicfn == NULL || g_mapInfo[mii].musicfn == NULL || // intentional, to pass control further while avoiding the strcmp on null strcmp(g_mapInfo[g_musicIndex].musicfn, g_mapInfo[mii].musicfn) || g_musicSize == 0 || ud.last_level == -1) { S_PlayLevelMusicOrNothing(mii); } } if (RR && !(gameMode & MODE_DEMO)) S_PlayRRMusic(); if (gameMode & (MODE_GAME|MODE_EOL)) { for (TRAVERSE_CONNECT(i)) { g_player[i].ps->gm = MODE_GAME; Menu_Close(i); } } else if (gameMode & MODE_RESTART) { if (ud.recstat == 2) g_player[myconnectindex].ps->gm = MODE_DEMO; else g_player[myconnectindex].ps->gm = MODE_GAME; } if ((ud.recstat == 1) && (gameMode&MODE_RESTART) != MODE_RESTART) G_OpenDemoWrite(); #ifndef EDUKE32_TOUCH_DEVICES if (VOLUMEONE && ud.level_number == 0 && ud.recstat != 2) P_DoQuote(QUOTE_F1HELP,g_player[myconnectindex].ps); #endif for (TRAVERSE_CONNECT(i)) { switch (DYNAMICTILEMAP(sector[sprite[g_player[i].ps->i].sectnum].floorpicnum)) { case HURTRAIL__STATIC: case FLOORSLIME__STATIC: case FLOORPLASMA__STATIC: P_ResetWeapons(i); P_ResetInventory(i); g_player[i].ps->gotweapon &= ~(1 << PISTOL_WEAPON); g_player[i].ps->ammo_amount[PISTOL_WEAPON] = 0; g_player[i].ps->curr_weapon = KNEE_WEAPON; g_player[i].ps->kickback_pic = 0; break; } } //PREMAP.C - replace near the my's at the end of the file Net_NotifyNewGame(); Net_ResetPrediction(); //g_player[myconnectindex].ps->palette = palette; //G_FadePalette(0,0,0,0); P_SetGamePalette(g_player[myconnectindex].ps, BASEPAL, 0); // JBF 20040308 P_UpdateScreenPal(g_player[myconnectindex].ps); renderFlushPerms(); everyothertime = 0; g_globalRandom = 0; ud.last_level = ud.level_number+1; G_ClearFIFO(); for (i=g_interpolationCnt-1; i>=0; i--) bakipos[i] = *curipos[i]; for (i=0; i<ud.multimode; i++) g_player[i].playerquitflag = 1; g_player[myconnectindex].ps->over_shoulder_on = 0; clearfrags(); G_ResetTimers(0); // Here we go //Bsprintf(g_szBuf,"G_EnterLevel L=%d V=%d",ud.level_number, ud.volume_number); //AddLog(g_szBuf); // variables are set by pointer... Bmemcpy(currentboardfilename, boardfilename, BMAX_PATH); if (G_HaveUserMap()) { OSD_Printf(OSDTEXT_YELLOW "User Map: %s\n", boardfilename); } else { OSD_Printf(OSDTEXT_YELLOW "E%dL%d: %s\n", ud.volume_number+1, ud.level_number+1, g_mapInfo[mii].name); } g_restorePalette = -1; G_UpdateScreenArea(); videoClearViewableArea(0L); G_DrawBackground(); G_DrawRooms(myconnectindex,65536); if (REALITY) RT_ResetBarScroll(); Net_WaitForEverybody(); return 0; } void G_FreeMapState(int levelNum) { map_t *const pMapInfo = &g_mapInfo[levelNum]; if (pMapInfo->savedstate == NULL) return; ALIGNED_FREE_AND_NULL(pMapInfo->savedstate); } void G_SetFog(int fogtype) { static int oldFogType = 0; static int makeTables = 0; static char *lut0,*lut30,*lut33,*lut23,*lut8; #ifdef USE_OPENGL static palette_t flut0,flut30,flut33,flut23,flut8; extern coltypef fogtable[MAXPALOOKUPS]; #endif if (!makeTables) { makeTables = 1; lut0 = palookup[0]; lut30 = palookup[30]; lut33 = palookup[33]; lut23 = palookup[23]; lut8 = palookup[8]; #ifdef USE_OPENGL flut0 = palookupfog[0]; flut30 = palookupfog[30]; flut33 = palookupfog[33]; flut23 = palookupfog[23]; flut8 = palookupfog[8]; #endif paletteMakeLookupTable(50, NULL, 12*4, 12*4, 12*4, 0); paletteMakeLookupTable(51, NULL, 12*4, 12*4, 12*4, 0); } if (fogtype == 0) { palookup[0] = lut0; palookup[30] = lut30; palookup[33] = lut33; palookup[23] = lut23; palookup[8] = lut8; #ifdef USE_OPENGL palookupfog[0] = flut0; palookupfog[30] = flut30; palookupfog[33] = flut33; palookupfog[23] = flut23; palookupfog[8] = flut8; #endif } else if (fogtype == 2) { palookup[0] = palookup[50]; palookup[30] = palookup[51]; palookup[33] = palookup[51]; palookup[23] = palookup[51]; palookup[8] = palookup[54]; #ifdef USE_OPENGL palookupfog[0] = palookupfog[50]; palookupfog[30] = palookupfog[51]; palookupfog[33] = palookupfog[51]; palookupfog[23] = palookupfog[51]; palookupfog[8] = palookupfog[54]; #endif } if (oldFogType != fogtype) { oldFogType = fogtype; #ifdef USE_OPENGL if (videoGetRenderMode() >= REND_POLYMOST) { for (bssize_t i=0; i<=MAXPALOOKUPS-1; i++) { fogtable[i].r = palookupfog[i].r * (1.f/255.f); fogtable[i].g = palookupfog[i].g * (1.f/255.f); fogtable[i].b = palookupfog[i].b * (1.f/255.f); fogtable[i].a = 0; } gltexinvalidatetype(INVALIDATE_ALL_NON_INDEXED); uploadpalswap(0); uploadpalswap(30); uploadpalswap(33); uploadpalswap(23); uploadpalswap(8); } #endif } }
0
0.926863
1
0.926863
game-dev
MEDIA
0.781411
game-dev
0.998206
1
0.998206
Direwolf20-MC/BuildingGadgets
1,593
src/main/java/com/direwolf20/buildinggadgets/common/network/packets/PacketToggleFuzzy.java
package com.direwolf20.buildinggadgets.common.network.packets; import com.direwolf20.buildinggadgets.common.config.Config; import com.direwolf20.buildinggadgets.common.items.AbstractGadget; import com.direwolf20.buildinggadgets.common.items.GadgetBuilding; import com.direwolf20.buildinggadgets.common.items.GadgetDestruction; import com.direwolf20.buildinggadgets.common.items.GadgetExchanger; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class PacketToggleFuzzy { public static void encode(PacketToggleFuzzy msg, FriendlyByteBuf buffer) {} public static PacketToggleFuzzy decode(FriendlyByteBuf buffer) { return new PacketToggleFuzzy(); } public static class Handler { public static void handle(final PacketToggleFuzzy msg, Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayer player = ctx.get().getSender(); if (player == null) return; ItemStack stack = AbstractGadget.getGadget(player); if (stack.getItem() instanceof GadgetExchanger || stack.getItem() instanceof GadgetBuilding || (stack.getItem() instanceof GadgetDestruction && Config.GADGETS.GADGET_DESTRUCTION.nonFuzzyEnabled.get())) AbstractGadget.toggleFuzzy(player, stack); }); ctx.get().setPacketHandled(true); } } }
0
0.527979
1
0.527979
game-dev
MEDIA
0.995914
game-dev
0.677289
1
0.677289
CyberdyneCC/Thermos
1,542
patches/net/minecraft/inventory/SlotFurnace.java.patch
--- ../src-base/minecraft/net/minecraft/inventory/SlotFurnace.java +++ ../src-work/minecraft/net/minecraft/inventory/SlotFurnace.java @@ -9,6 +9,12 @@ import net.minecraft.stats.AchievementList; import net.minecraft.util.MathHelper; +// CraftBukkit start +import net.minecraft.tileentity.TileEntityFurnace; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.FurnaceExtractEvent; +// CraftBukkit end + public class SlotFurnace extends Slot { private EntityPlayer thePlayer; @@ -74,6 +80,20 @@ i = j; } + // Cauldron start - validate inventory before attempting to cast it + if (this.inventory instanceof TileEntityFurnace) + { + // CraftBukkit start + Player player = (Player) thePlayer.getBukkitEntity(); + TileEntityFurnace furnace = ((TileEntityFurnace) this.inventory); + org.bukkit.block.Block block = thePlayer.worldObj.getWorld().getBlockAt(furnace.xCoord, furnace.yCoord, furnace.zCoord); + FurnaceExtractEvent event = new FurnaceExtractEvent(player, block, org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(p_75208_1_.getItem()), p_75208_1_.stackSize, i); + thePlayer.worldObj.getServer().getPluginManager().callEvent(event); + i = event.getExpToDrop(); + // CraftBukkit end + } + // Cauldron end + while (i > 0) { j = EntityXPOrb.getXPSplit(i);
0
0.799073
1
0.799073
game-dev
MEDIA
0.999377
game-dev
0.839455
1
0.839455
PotRooms/StarResonanceData
5,476
lua/ui/view_model/weekly_hunt_vm.lua
local WeeklyHuntVm = {} local enterdungeonsceneVm = Z.VMMgr.GetVM("ui_enterdungeonscene") local wordProxy = require("zproxy.world_proxy") function WeeklyHuntVm.OpenRankView() Z.UIMgr:OpenView("weekly_hunt_rankings_window") end function WeeklyHuntVm.CloseRankView() Z.UIMgr:CloseView("weekly_hunt_rankings_window") end function WeeklyHuntVm.OpenWeekHuntView() Z.UIMgr:OpenView("weekly_hunt_main") end function WeeklyHuntVm.CloseWeekHuntView() Z.UIMgr:CloseView("weekly_hunt_main") end function WeeklyHuntVm.OpenTargetView() Z.UIMgr:OpenView("weekly_hunt_target_reward_popup") end function WeeklyHuntVm.CloseTargetView() Z.UIMgr:CloseView("weekly_hunt_target_reward_popup") end function WeeklyHuntVm.AsyncGetWeeklyTowerProcessAward(climbUpId, isoneKey, token) local request = {climbUpId = climbUpId} if isoneKey then request.oneKey = isoneKey end local ret = wordProxy.GetWeeklyTowerProcessAward(request, token) Z.TipsVM.ShowTips(ret) end function WeeklyHuntVm.AsyncGetTeamTowerLayerInfo(token) local ret = wordProxy.GetTeamTowerLayerInfo(token) if ret.errCode ~= 0 then Z.TipsVM.ShowTips(ret.errCode) else return ret end end function WeeklyHuntVm.InitClimbUpLayerTable() local data = Z.DataMgr.Get("weekly_hunt_data") local climbUpLayerData = Z.TableMgr.GetTable("ClimbUpLayerTableMgr").GetDatas() local tabs = {} local dungeons = {} local maxLayer = 0 local climbUpRuleTable = Z.TableMgr.GetTable("ClimbUpRuleTableMgr").GetDatas() local ruleTab = {} for index, value in pairs(climbUpRuleTable) do ruleTab[value.Season] = value end for index, value in pairs(climbUpLayerData) do if maxLayer < value.LayerNumber then maxLayer = value.LayerNumber end if tabs[value.Season] == nil then tabs[value.Season] = {} end dungeons[value.DungeonId] = value.LayerNumber local tab = tabs[value.Season][value.StageId] if tab == nil then tabs[value.Season][value.StageId] = {} tab = tabs[value.Season][value.StageId] tab.awards = {} tab.stageId = value.StageId tab.climbUpLayerRows = {} tab.affixIds = {} tab.layer = value.LayerNumber tab.isBossLayer = value.LayarType == E.WeeklyHuntMonsterType.Boss tab.jumpStage = 1 local releRow = ruleTab[value.Season] if releRow then for index, stage in pairs(releRow.JumpStage) do if stage >= value.StageId then tab.jumpStage = index break end end end end if value.RewardId ~= 0 then tab.awards[value.LayarType] = value.RewardId end for index, value in ipairs(value.AffixId) do if not tab.affixIds[value] then tab.affixIds[value] = value end end tab.climbUpLayerRows[#tab.climbUpLayerRows + 1] = value end for seasonId, climbUpLayerDatas in pairs(tabs) do for _, v in pairs(climbUpLayerDatas) do table.sort(v.climbUpLayerRows, function(left, right) return left.LayerNumber < right.LayerNumber end) end end data:SetMaxLayer(maxLayer) data:SetClimbUpLayerDatas(table.zvalues(tabs)) data:SetDungeons(dungeons) data:SetClimbRuleDatas(ruleTab) end function WeeklyHuntVm.GetAffixByDungeonId(dungeonId) local data = Z.DataMgr.Get("weekly_hunt_data") local layer = data.DungeonLayers[dungeonId] if layer then local climbUpLayerTableRow = Z.TableMgr.GetRow("ClimbUpLayerTableMgr", layer) return climbUpLayerTableRow.AffixId end return nil end function WeeklyHuntVm.Enterdungeon(dungeonId, token) return enterdungeonsceneVm.AsyncCreateLevel(E.FunctionID.WeeklyHunt, dungeonId, token) end function WeeklyHuntVm.enterTeamTowerLayer() local teamVm = Z.VMMgr.GetVM("team") if teamVm.CheckIsInTeam() and not teamVm.GetYouIsLeader() then return end Z.CoroUtil.create_coro_xpcall(function() local dungeonData = Z.DataMgr.Get("dungeon_data") dungeonData:CreatCancelSource() local ret = WeeklyHuntVm.AsyncGetTeamTowerLayerInfo(dungeonData.CancelSource:CreateToken()) if ret then local climbUpLayerTableRow = Z.TableMgr.GetRow("ClimbUpLayerTableMgr", ret.enterClimbUpId) if climbUpLayerTableRow then WeeklyHuntVm.Enterdungeon(climbUpLayerTableRow.DungeonId, dungeonData.CancelSource:CreateToken()) end end dungeonData:RecycleCancelSource() end)() end function WeeklyHuntVm.Countdown(isShow) if isShow then local time = 5 Z.GlobalTimerMgr:StartTimer(E.GlobalTimerTag.WeeklyHuntNext, function() Z.TipsVM.ShowTips(1006001, {val = time}) time = time - 1 if time == 0 then WeeklyHuntVm.enterTeamTowerLayer() end end, 1, 5) else Z.GlobalTimerMgr:StopTimer(E.GlobalTimerTag.WeeklyHuntNext) end end function WeeklyHuntVm.ResultFailed() local dungeonId = Z.StageMgr.GetCurrentDungeonId() if not dungeonId and dungeonId == 0 then return end local teamVm = Z.VMMgr.GetVM("team") local player = {name = ""} local isReturn = false local teamMembers = teamVm.GetTeamMemData() for key, value in pairs(teamMembers) do if value.socialData.basicData.sceneId ~= dungeonId or value.socialData.basicData.offlineTime ~= 0 then player.name = player.name .. value.socialData.basicData.name isReturn = true end end if isReturn then return end end function WeeklyHuntVm.GetTargetAwardRedName(layer) return "weekly_hunt_award_red" .. layer end return WeeklyHuntVm
0
0.870867
1
0.870867
game-dev
MEDIA
0.968379
game-dev
0.965269
1
0.965269
autoas/as
10,458
infras/libraries/dds/vdds/src/vring/spmc/writer.cpp
/** * SSAS - Simple Smart Automotive Software * Copyright (C) 2024 Parai Wang <parai@foxmail.com> */ /* ================================ [ INCLUDES ] ============================================== */ #include "vring/spmc/writer.hpp" #include "Std_Debug.h" #include <assert.h> #include <cinttypes> #include <fcntl.h> #include <unistd.h> namespace as { namespace vdds { namespace vring { namespace spmc { /* ================================ [ MACROS ] ============================================== */ #define AS_LOG_VRING 0 #define AS_LOG_VRINGI 1 #define AS_LOG_VRINGW 2 #define AS_LOG_VRINGE 3 #ifndef VRING_DESC_TIMEOUT #define VRING_DESC_TIMEOUT (2000000) #endif #ifndef VRING_SPIN_MAX_COUNTER #define VRING_SPIN_MAX_COUNTER (1000000) #endif /* ================================ [ TYPES ] ============================================== */ /* ================================ [ DECLARES ] ============================================== */ /* ================================ [ DATAS ] ============================================== */ /* ================================ [ LOCALS ] ============================================== */ /* ================================ [ FUNCTIONS ] ============================================== */ Writer::Writer(std::string name, uint32_t msgSize, uint32_t numDesc) : Base(name, numDesc), m_MsgSize(msgSize) { m_SemUseds.reserve(numDesc); } int Writer::init() { int ret = 0; auto sharedMemory = std::make_shared<SharedMemory>(m_Name, size()); if (nullptr == sharedMemory) { ret = ENOMEM; } else { ret = sharedMemory->create(); } if (0 == ret) { m_SharedMemory = sharedMemory; m_Meta = (VRing_MetaType *)m_SharedMemory->getVA(); m_Desc = (VRing_DescType *)(((uintptr_t)m_Meta) + VRING_SIZE_OF_META()); m_Avail = (VRing_AvailType *)(((uintptr_t)m_Desc) + VRING_SIZE_OF_DESC(m_NumDesc)); m_Used = (VRing_UsedType *)(((uintptr_t)m_Avail) + VRING_SIZE_OF_AVAIL(m_NumDesc)); ret = setup(); } else { ASLOG(VRINGE, ("vring writer can't open shm %s\n", m_Name.c_str())); } if (0 == ret) { m_SemAvail = std::make_shared<NamedSemaphore>(m_Name, m_NumDesc); if (nullptr == m_SemAvail) { ret = ENOMEM; } else { ret = m_SemAvail->create(); } } if (0 == ret) { for (uint32_t i = 0; i < VRING_MAX_READERS; i++) { std::string semName = m_Name + "_used" + std::to_string(i); auto sem = std::make_shared<NamedSemaphore>(semName, 0); if (nullptr == sem) { ret = ENOMEM; } else { ret = sem->create(); if (0 == ret) { m_SemUseds.push_back(sem); } } } } if (0 == ret) { ASLOG(VRING, ("vring writer %s online: msgSize = %u, numDesc = %u\n", m_Name.c_str(), m_MsgSize, m_NumDesc)); m_Thread = std::thread(&Writer::threadMain, this); } return ret; } Writer::~Writer() { m_Stop = true; if (m_Thread.joinable()) { m_Thread.join(); } m_SemAvail = nullptr; m_SemUseds.clear(); m_SharedMemory = nullptr; m_DmaMems.clear(); } int Writer::setup() { uint32_t i; int ret = 0; memset(m_SharedMemory->getVA(), 0, size()); m_Meta->msgSize = m_MsgSize; m_Meta->numDesc = m_NumDesc; for (i = 0; (i < m_NumDesc) && (0 == ret); i++) { std::string shmFile = m_Name + "_" + std::to_string(i) + "_" + std::to_string(m_MsgSize); auto dmaMemory = std::make_shared<DmaMemory>(shmFile, m_MsgSize); if (nullptr != dmaMemory) { ret = dmaMemory->create(); if (0 == ret) { #ifdef USE_DMA_BUF m_Desc[i].handle = dmaMemory->getHandle(); #else m_Desc[i].handle = i; #endif m_Desc[i].len = m_MsgSize; m_Avail->ring[i] = i; m_Avail->idx++; m_DmaMems.push_back(dmaMemory); } } else { ret = ENOMEM; } } return ret; } int Writer::get(void *&buf, uint32_t &idx, uint32_t &len, uint32_t timeoutMs) { int ret = 0; int32_t ref; (void)m_SemAvail->wait(timeoutMs); ret = spinLock(&m_Avail->spin); if (0 == ret) { if (m_Avail->lastIdx == m_Avail->idx) { /* no buffers */ ret = ENODATA; } else { idx = m_Avail->ring[m_Avail->lastIdx % m_NumDesc]; ref = __atomic_load_n(&m_Desc[idx].ref, __ATOMIC_RELAXED); if (0 == ref) { buf = m_DmaMems[idx]->getVA(); len = m_Desc[idx].len; m_Avail->lastIdx++; ASLOG(VRING, ("vring writer %s: get DESC[%u], len = %u; AVAIL: lastIdx = %u, idx = %u\n", m_Name.c_str(), idx, len, m_Avail->lastIdx, m_Avail->idx)); } else { ASLOG(VRINGE, ("vring writer %s: get DESC[%u] with ref = %d\n", m_Name.c_str(), idx, ref)); ret = EBADF; } } spinUnlock(&m_Avail->spin); } else { ASLOG(VRINGE, ("vring writer %s: get lock AVAIL spin timeout\n", m_Name.c_str())); } return ret; } int Writer::put(uint32_t idx, uint32_t len) { VRing_UsedType *used; VRing_UsedElemType *usedElem; uint32_t i; bool isUsed = false; int ret = 0; std::vector<uint32_t> readerIdxs; readerIdxs.reserve(VRING_MAX_READERS); if (idx > m_NumDesc) { ret = EINVAL; } else { ret = spinLock(&m_Desc[idx].spin); if (0 == ret) { m_Desc[idx].timestamp = timestamp(); for (i = 0; i < VRING_MAX_READERS; i++) { used = (VRing_UsedType *)(((uintptr_t)m_Used) + VRING_SIZE_OF_USED(m_NumDesc) * i); /* state == 1, the used ring is in good status */ if (VRING_USED_STATE_READY == __atomic_load_n(&used->state, __ATOMIC_RELAXED)) { usedElem = &used->ring[used->idx % m_NumDesc]; usedElem->id = idx; usedElem->len = len; __atomic_fetch_add(&m_Desc[idx].ref, 1, __ATOMIC_RELAXED); isUsed = true; ASLOG(VRING, ("vring writer %s@%u: put DESC[%u], len = %u ref = %d; used: lastIdx = " "%u, idx = %u\n", m_Name.c_str(), i, idx, len, __atomic_load_n(&m_Desc[idx].ref, __ATOMIC_RELAXED), used->lastIdx, used->idx)); used->idx++; readerIdxs.push_back(i); } } spinUnlock(&m_Desc[idx].spin); } else { ASLOG(VRINGE, ("vring writer %s: put lock DESC[%u] spin timeout\n", m_Name.c_str(), idx)); } if (false == isUsed) { /* OK, put it back */ (void)drop(idx); ret = ENOLINK; } else { for (auto i : readerIdxs) { ret |= m_SemUseds[i]->post(); } } } return ret; } int Writer::drop(uint32_t idx) { int ret = 0; if (idx > m_NumDesc) { ret = EINVAL; } else { ret = spinLock(&m_Avail->spin); if (0 == ret) { m_Avail->ring[m_Avail->idx % m_NumDesc] = idx; m_Avail->idx++; spinUnlock(&m_Avail->spin); ASLOG(VRING, ("vring writer %s: drop DESC[%u]; AVAIL: lastIdx = %u, idx = %u\n", m_Name.c_str(), idx, m_Avail->lastIdx, m_Avail->idx)); ret = m_SemAvail->post(); } else { ASLOG(VRINGE, ("vring writer %s: drop lock AVAIL spin timeout\n", m_Name.c_str())); } } return ret; } void Writer::releaseDesc(uint32_t idx) { int32_t ref; int ret = 0; ref = __atomic_sub_fetch(&m_Desc[idx].ref, 1, __ATOMIC_RELAXED); if (0 < ref) { /* still used by others */ } else if (0 == ref) { ret = spinLock(&m_Avail->spin); if (0 == ret) { m_Avail->ring[m_Avail->idx % m_NumDesc] = idx; m_Avail->idx++; spinUnlock(&m_Avail->spin); ASLOG(VRINGE, ("vring writer %s: release DESC[%u]\n", m_Name.c_str(), idx)); (void)m_SemAvail->post(); } else { ASLOG(VRINGE, ("vring writer %s: release lock AVAIL spin timeout\n", m_Name.c_str())); } } else { ASLOG(VRING, ("vring writer %s: release DESC[%u] ref = %d failed\n", m_Name.c_str(), idx, ref)); assert(0); } } void Writer::removeAbnormalReader(VRing_UsedType *used, uint32_t readerIdx) { VRing_UsedElemType *usedElem; uint32_t ref; uint32_t idx; int ret = 0; ASLOG(VRINGE, ("vring reader %s@%u is dead\n", m_Name.c_str(), readerIdx)); /* set ref > 1, mark as dead to stop the writer to put data on this used ring */ /* step 1: release the DESC in the reader used ring */ ref = __atomic_add_fetch(&used->state, 1, __ATOMIC_RELAXED); assert(VRING_USED_STATE_KILLED == ref); while (used->lastIdx != used->idx) { usedElem = &used->ring[used->lastIdx % m_NumDesc]; idx = usedElem->id; ret = spinLock(&m_Desc[idx].spin); if (0 == ret) { releaseDesc(idx); spinUnlock(&m_Desc[idx].spin); } else { ASLOG(VRINGE, ("vring writer %s: rm reader lock DESC[%u] spin timeout\n", m_Name.c_str(), idx)); } used->lastIdx++; } ref = __atomic_sub_fetch(&used->state, VRING_USED_STATE_KILLED, __ATOMIC_RELAXED); assert(VRING_USED_STATE_FREE == ref); } void Writer::readerHeartCheck() { VRing_UsedType *used; uint32_t i; uint32_t curHeart; for (i = 0; i < VRING_MAX_READERS; i++) { used = (VRing_UsedType *)(((uintptr_t)m_Used) + VRING_SIZE_OF_USED(m_NumDesc) * i); if (VRING_USED_STATE_READY == __atomic_load_n(&used->state, __ATOMIC_RELAXED)) { curHeart = __atomic_load_n(&used->heart, __ATOMIC_RELAXED); if (curHeart == used->lastHeart) { /* the reader is dead or stuck */ removeAbnormalReader(used, i); } else { used->lastHeart = curHeart; } } } } void Writer::checkDescLife() { uint64_t elapsed; uint32_t idx; int32_t ref; int ret = 0; for (idx = 0; idx < m_NumDesc; idx++) { ret = spinLock(&m_Desc[idx].spin); if (0 == ret) { ref = __atomic_load_n(&m_Desc[idx].ref, __ATOMIC_RELAXED); if (ref > 0) { elapsed = timestamp() - m_Desc[idx].timestamp; if (elapsed > VRING_DESC_TIMEOUT) { ASLOG(VRINGE, ("vring writer %s: DESC %u ref = %d timeout\n", m_Name.c_str(), idx, ref)); /* TODO: this is not right to do the release, it's FATAL APP's bug */ releaseDesc(idx); } } spinUnlock(&m_Desc[idx].spin); } else { ASLOG(VRINGE, ("vring writer %s: check DESC life lock DESC[%u] spin timeout\n", m_Name.c_str(), idx)); } } } void Writer::threadMain() { while (false == m_Stop) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); readerHeartCheck(); checkDescLife(); } } } // namespace spmc } // namespace vring } // namespace vdds } // namespace as
0
0.964681
1
0.964681
game-dev
MEDIA
0.204128
game-dev
0.990567
1
0.990567
ChaoticOnyx/OnyxBay
13,207
code/game/machinery/camera/camera.dm
/obj/machinery/camera name = "security camera" desc = "It's used to monitor rooms." icon = 'icons/obj/monitors.dmi' icon_state = "camera" use_power = POWER_USE_ACTIVE idle_power_usage = 5 WATTS active_power_usage = 10 WATTS layer = CAMERA_LAYER var/list/network = list(NETWORK_EXODUS) var/c_tag = null var/c_tag_order = 999 var/number = 0 //camera number in area var/status = 1 anchored = 1.0 var/invuln = null var/bugged = 0 var/weakref/assembly_ref = null var/toughness = 5 //sorta fragile // WIRES var/datum/wires/camera/wires = null // Wires datum //OTHER var/view_range = 7 var/short_range = 2 var/light_disabled = 0 var/alarm_on = 0 var/busy = 0 var/on_open_network = 0 var/affected_by_emp_until = 0 /obj/machinery/camera/examine(mob/user, infix) . = ..() if(stat & BROKEN) . += "<span class='warning'>It is completely demolished.</span>" /obj/machinery/camera/malf_upgrade(mob/living/silicon/ai/user) ..() malf_upgraded = 1 upgradeEmpProof() upgradeXRay() to_chat(user, "\The [src] has been upgraded. It now has X-Ray capability and EMP resistance.") return 1 /obj/machinery/camera/apply_visual(mob/living/carbon/human/M) if(!M.client) return if (!istype(M)) return 1 M.hud_used.show_hud(HUD_STYLE_NONE) M.overlay_fullscreen("scanlines", /atom/movable/screen/fullscreen/scanline) M.overlay_fullscreen("cam_corners", /atom/movable/screen/fullscreen/cam_corners) M.overlay_fullscreen("fishbed", /atom/movable/screen/fullscreen/fishbed) M.overlay_fullscreen("recording", /atom/movable/screen/fullscreen/rec) M.client.view_size.supress() M.machine_visual = src return 1 /obj/machinery/camera/remove_visual(mob/living/carbon/human/M) if(!M.client) return if (!istype(M)) return 1 M.hud_used.show_hud(HUD_STYLE_STANDART) M.clear_fullscreen("scanlines") M.clear_fullscreen("cam_corners", 0) M.clear_fullscreen("fishbed", 0) M.clear_fullscreen("recording", 0) M.client.view_size.unsupress() M.machine_visual = null return 1 /obj/machinery/camera/New() wires = new(src) var/obj/item/camera_assembly/assembly = new(src) assembly.state = 4 assembly_ref = weakref(assembly) /* // Use this to look for cameras that have the same c_tag. for(var/obj/machinery/camera/C in cameranet.cameras) var/list/tempnetwork = C.network&src.network if(C != src && C.c_tag == src.c_tag && tempnetwork.len) to_world_log("[src.c_tag] [src.x] [src.y] [src.z] conflicts with [C.c_tag] [C.x] [C.y] [C.z]") */ if(!src.network || src.network.len < 1) if(loc) error("[src.name] in [get_area(src)] (x:[src.x] y:[src.y] z:[src.z] has errored. [src.network?"Empty network list":"Null network list"]") else error("[src.name] in [get_area(src)]has errored. [src.network?"Empty network list":"Null network list"]") ASSERT(src.network) ASSERT(src.network.len > 0) ..() /obj/machinery/camera/Initialize() . = ..() if(!c_tag) number = 1 var/area/A = get_area(src) if(A) for(var/obj/machinery/camera/C in A) if(C == src) continue if(C.number) number = max(number, C.number+1) c_tag = "[A.name][number == 1 ? "" : " #[number]"]" invalidateCameraCache() /obj/machinery/camera/Destroy() deactivate(null, 0) //kick anyone viewing out QDEL_NULL(assembly_ref) QDEL_NULL(wires) return ..() /obj/machinery/camera/Process() if((stat & EMPED) && world.time >= affected_by_emp_until) stat &= ~EMPED cancelCameraAlarm() update_icon() update_coverage() return internal_process() /obj/machinery/camera/proc/internal_process() return /obj/machinery/camera/emp_act(severity) if(!isEmpProof() && prob(100/severity)) if(!affected_by_emp_until || (world.time < affected_by_emp_until)) affected_by_emp_until = max(affected_by_emp_until, world.time + (90 SECONDS / severity)) else stat |= EMPED set_light(0) triggerCameraAlarm() update_icon() update_coverage() START_PROCESSING(SSmachines, src) /obj/machinery/camera/bullet_act(obj/item/projectile/P) take_damage(P.get_structure_damage()) /obj/machinery/camera/ex_act(severity) if(src.invuln) return //camera dies if an explosion touches it! if(severity <= 2 || prob(50)) destroy() ..() //and give it the regular chance of being deleted outright /obj/machinery/camera/hitby(atom/movable/AM, speed, nomsg) ..() if(istype(AM, /obj)) var/obj/O = AM take_damage(O.throwforce) /obj/machinery/camera/proc/setViewRange(num = 7) src.view_range = num cameranet.update_visibility(src, 0) /obj/machinery/camera/attack_hand(mob/living/carbon/human/user) if(!istype(user)) return if(user.species.can_shred(user)) set_status(0) user.do_attack_animation(src) user.setClickCooldown(DEFAULT_QUICK_COOLDOWN) visible_message("<span class='warning'>\The [user] slashes at [src]!</span>") playsound(src.loc, 'sound/weapons/slash.ogg', 100, 1) add_hiddenprint(user) destroy() /obj/machinery/camera/attackby(obj/item/W as obj, mob/living/user as mob) update_coverage() // DECONSTRUCTION if(isScrewdriver(W)) // to_chat(user, "<span class='notice'>You start to [panel_open ? "close" : "open"] the camera's panel.</span>") //if(toggle_panel(user)) // No delay because no one likes screwdrivers trying to be hip and have a duration cooldown panel_open = !panel_open user.visible_message("<span class='warning'>[user] screws the camera's panel [panel_open ? "open" : "closed"]!</span>", "<span class='notice'>You screw the camera's panel [panel_open ? "open" : "closed"].</span>") playsound(src.loc, 'sound/items/Screwdriver.ogg', 50, 1) else if((isWirecutter(W) || isMultitool(W)) && panel_open) interact(user) else if(isWelder(W) && (wires.CanDeconstruct() || (stat & BROKEN))) if(weld(W, user)) var/obj/item/camera_assembly/assembly = assembly_ref?.resolve() if(assembly) assembly.dropInto(loc) assembly.anchored = 1 assembly.camera_name = c_tag assembly.camera_network = english_list(network, "Exodus", ",", ",") assembly.update_icon() assembly.dir = src.dir if(stat & BROKEN) assembly.state = 2 to_chat(user, "<span class='notice'>You repaired \the [src] frame.</span>") cancelCameraAlarm() else assembly.state = 1 to_chat(user, "<span class='notice'>You cut \the [src] free from the wall.</span>") new /obj/item/stack/cable_coil(src.loc, length=2) assembly_ref = null //so qdel doesn't eat it. qdel(src) return // OTHER else if (can_use() && (istype(W, /obj/item/paper) || istype(W, /obj/item/device/pda)) && isliving(user)) var/mob/living/U = user var/obj/item/paper/X = null var/obj/item/device/pda/P = null var/itemname = "" var/info = "" if(istype(W, /obj/item/paper)) X = W itemname = X.name info = X.info else P = W itemname = P.name info = P.notehtml to_chat(U, "You hold \a [itemname] up to the camera ...") for(var/mob/living/silicon/ai/O in GLOB.living_mob_list_) if(!O.client) continue if(U.name == "Unknown") to_chat(O, "<b>[U]</b> holds \a [itemname] up to one of your cameras ...") else to_chat(O, "<b><a href='byond://?src=\ref[O];track2=\ref[O];track=\ref[U];trackname=[U.name]'>[U]</a></b> holds \a [itemname] up to one of your cameras ...") show_browser(O, text("<HTML><meta charset=\"utf-8\"><HEAD><TITLE>[]</TITLE></HEAD><BODY><TT>[]</TT></BODY></HTML>", itemname, info), text("window=[]", itemname)) else if(W.damtype == BRUTE || W.damtype == BURN) //bashing cameras user.setClickCooldown(DEFAULT_ATTACK_COOLDOWN) if (W.force >= src.toughness) user.do_attack_animation(src) visible_message("<span class='warning'><b>[src] has been [pick(W.attack_verb)] with [W] by [user]!</b></span>") shake_animation(stime = 3) obj_attack_sound(W) take_damage(W.force) else ..() /obj/machinery/camera/proc/deactivate(mob/user, choice = 1) // The only way for AI to reactivate cameras are malf abilities, this gives them different messages. if(istype(user, /mob/living/silicon/ai)) user = null if(choice != 1) return set_status(!src.status) if (!(src.status)) if(user) visible_message("<span class='notice'> [user] has deactivated [src]!</span>") else visible_message("<span class='notice'> [src] clicks and shuts down. </span>") playsound(src.loc, 'sound/items/Wirecutter.ogg', 100, 1) icon_state = "[initial(icon_state)]1" add_hiddenprint(user) else if(user) visible_message("<span class='notice'> [user] has reactivated [src]!</span>") else visible_message("<span class='notice'> [src] clicks and reactivates itself. </span>") playsound(src.loc, 'sound/items/Wirecutter.ogg', 100, 1) icon_state = initial(icon_state) add_hiddenprint(user) /obj/machinery/camera/proc/take_damage(force, message) //prob(25) gives an average of 3-4 hits if (force >= toughness && (force > toughness*4 || prob(25))) destroy() //Used when someone breaks a camera /obj/machinery/camera/proc/destroy() set_broken(TRUE) wires.RandomCutAll() triggerCameraAlarm() update_coverage() //sparks var/datum/effect/effect/system/spark_spread/spark_system = new /datum/effect/effect/system/spark_spread() spark_system.set_up(5, 0, loc) spark_system.start() playsound(loc, SFX_SPARK, 50, 1) /obj/machinery/camera/proc/set_status(newstatus) if (status != newstatus) status = newstatus update_coverage() /obj/machinery/camera/check_eye(mob/user) if(!can_use()) return -1 if(isXRay()) return SEE_TURFS|SEE_MOBS|SEE_OBJS return 0 /obj/machinery/camera/on_update_icon() if (!status || (stat & BROKEN)) icon_state = "[initial(icon_state)]1" else if (stat & EMPED) icon_state = "[initial(icon_state)]emp" else icon_state = initial(icon_state) /obj/machinery/camera/proc/triggerCameraAlarm(duration = 0) alarm_on = 1 camera_alarm.triggerAlarm(loc, src, duration) /obj/machinery/camera/proc/cancelCameraAlarm() if(wires.IsIndexCut(CAMERA_WIRE_ALARM)) return alarm_on = 0 camera_alarm.clearAlarm(loc, src) //if false, then the camera is listed as DEACTIVATED and cannot be used /obj/machinery/camera/can_use() if(!status) return 0 if(stat & (EMPED|BROKEN)) return 0 return 1 /obj/machinery/camera/proc/can_see() var/list/see = null var/turf/pos = get_turf(src) if(!pos) return list() if(isXRay()) see = range(view_range, pos) else see = hear(view_range, pos) return see /atom/proc/auto_turn() //Automatically turns based on nearby walls. var/turf/simulated/wall/T = null for(var/i = 1, i <= 8; i += i) T = get_ranged_target_turf(src, i, 1) if(istype(T)) //If someone knows a better way to do this, let me know. -Giacom switch(i) if(NORTH) src.set_dir(SOUTH) if(SOUTH) src.set_dir(NORTH) if(WEST) src.set_dir(EAST) if(EAST) src.set_dir(WEST) break //Return a working camera that can see a given mob //or null if none /proc/seen_by_camera(mob/M) for(var/obj/machinery/camera/C in oview(4, M)) if(C.can_use()) // check if camera disabled return C return null /proc/near_range_camera(mob/M) for(var/obj/machinery/camera/C in range(4, M)) if(C.can_use()) // check if camera disabled return C return null /obj/machinery/camera/proc/weld(obj/item/weldingtool/WT, mob/user) to_chat(user, "<span class='notice'>You start to weld the [src]..</span>") if(!WT.use_tool(src, user, delay = 5 SECONDS, amount = 50)) return FALSE if(QDELETED(src)) return FALSE return TRUE /obj/machinery/camera/interact(mob/living/user as mob) if(!panel_open || istype(user, /mob/living/silicon/ai)) return if(stat & BROKEN) to_chat(user, "<span class='warning'>\The [src] is broken.</span>") return user.set_machine(src) wires.Interact(user) /obj/machinery/camera/proc/add_network(network_name) add_networks(list(network_name)) /obj/machinery/camera/proc/remove_network(network_name) remove_networks(list(network_name)) /obj/machinery/camera/proc/add_networks(list/networks) var/network_added network_added = 0 for(var/network_name in networks) if(!(network_name in src.network)) network += network_name network_added = 1 if(network_added) update_coverage(1) /obj/machinery/camera/proc/remove_networks(list/networks) var/network_removed network_removed = 0 for(var/network_name in networks) if(network_name in src.network) network -= network_name network_removed = 1 if(network_removed) update_coverage(1) /obj/machinery/camera/proc/replace_networks(list/networks) if(networks.len != network.len) network = networks update_coverage(1) return for(var/new_network in networks) if(!(new_network in network)) network = networks update_coverage(1) return /obj/machinery/camera/proc/clear_all_networks() if(network.len) network.Cut() update_coverage(1) /obj/machinery/camera/proc/nano_structure() var/cam[0] cam["name"] = sanitize(c_tag) cam["deact"] = !can_use() cam["camera"] = "\ref[src]" cam["x"] = x cam["y"] = y cam["z"] = z return cam // Resets the camera's wires to fully operational state. Used by one of Malfunction abilities. /obj/machinery/camera/proc/reset_wires() if(!wires) return set_broken(FALSE) // Fixes the camera and updates the icon. wires.CutAll() wires.MendAll() update_coverage()
0
0.971152
1
0.971152
game-dev
MEDIA
0.805512
game-dev
0.954688
1
0.954688
garbagemule/MobArena
2,306
src/main/java/com/garbagemule/MobArena/commands/admin/DisableCommand.java
package com.garbagemule.MobArena.commands.admin; import com.garbagemule.MobArena.Msg; import com.garbagemule.MobArena.commands.Command; import com.garbagemule.MobArena.commands.CommandInfo; import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.ArenaMaster; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @CommandInfo( name = "disable", pattern = "disable|off", usage = "/ma disable (<arena>|all)", desc = "disable MobArena or individual arenas", permission = "mobarena.admin.enable" ) public class DisableCommand implements Command { @Override public boolean execute(ArenaMaster am, CommandSender sender, String... args) { // Grab the argument, if any. String arg1 = (args.length > 0 ? args[0] : ""); if (arg1.equals("all")) { for (Arena arena : am.getArenas()) { disable(arena, sender); } return true; } if (!arg1.equals("")) { Arena arena = am.getArenaWithName(arg1); if (arena == null) { am.getGlobalMessenger().tell(sender, Msg.ARENA_DOES_NOT_EXIST); return true; } disable(arena, sender); return true; } am.setEnabled(false); am.saveConfig(); am.getGlobalMessenger().tell(sender, "MobArena " + ChatColor.RED + "disabled"); return true; } private void disable(Arena arena, CommandSender sender) { arena.setEnabled(false); arena.getPlugin().saveConfig(); arena.getGlobalMessenger().tell(sender, "Arena '" + arena.configName() + "' " + ChatColor.RED + "disabled"); } @Override public List<String> tab(ArenaMaster am, Player player, String... args) { if (args.length > 1) { return Collections.emptyList(); } String prefix = args[0].toLowerCase(); List<Arena> arenas = am.getArenas(); return arenas.stream() .filter(arena -> arena.getSlug().startsWith(prefix)) .map(Arena::getSlug) .collect(Collectors.toList()); } }
0
0.528021
1
0.528021
game-dev
MEDIA
0.874581
game-dev
0.630094
1
0.630094
FxMorin/carpet-fixes
1,057
src/main/java/carpetfixes/mixins/blockFixes/PistonBlock_pushOrderMixin.java
package carpetfixes.mixins.blockFixes; import carpetfixes.CFSettings; import com.google.common.collect.Maps; import net.minecraft.block.BlockState; import net.minecraft.block.PistonBlock; import net.minecraft.util.math.BlockPos; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.HashMap; /** * Fixes the piston update order being locational */ @Mixin(PistonBlock.class) public class PistonBlock_pushOrderMixin { @Redirect( method = "move(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;" + "Lnet/minecraft/util/math/Direction;Z)Z", at = @At( value = "INVOKE", target = "Lcom/google/common/collect/Maps;newHashMap()Ljava/util/HashMap;" ) ) private HashMap<BlockPos, BlockState> cf$hashmapBadYeeeet() { return CFSettings.pistonUpdateOrderIsLocationalFix ? Maps.newLinkedHashMap() : Maps.newHashMap(); } }
0
0.89029
1
0.89029
game-dev
MEDIA
0.985033
game-dev
0.792301
1
0.792301
Eis4TY/XR-Stereoscopic-Viewer
6,864
XR-Stereoscopic-Viewer/Assets/Oculus/Interaction/Runtime/Scripts/Grab/FingerPalmGrabAPI.cs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * Licensed under the Oculus SDK License Agreement (the "License"); * you may not use the Oculus SDK except in compliance with the License, * which is provided at the time of installation or download, or which * otherwise accompanies this software in either electronic or hard copy form. * * You may obtain a copy of the License at * * https://developer.oculus.com/licenses/oculussdk/ * * Unless required by applicable law or agreed to in writing, the Oculus SDK * 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. */ using Oculus.Interaction.Input; using Oculus.Interaction.PoseDetection; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Assertions; namespace Oculus.Interaction.GrabAPI { /// <summary> /// This Finger API uses the curl value of the fingers to detect if they are grabbing /// </summary> public class FingerPalmGrabAPI : IFingerAPI { // Temporary structure used to pass data to and from native components [StructLayout(LayoutKind.Sequential)] public class HandData { private const int NumHandJoints = 24; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NumHandJoints * 7, ArraySubType = UnmanagedType.R4)] private float[] jointValues; private float _rootRotX; private float _rootRotY; private float _rootRotZ; private float _rootRotW; private float _rootPosX; private float _rootPosY; private float _rootPosZ; private int _handedness; public HandData() { jointValues = new float[NumHandJoints * 7]; } public void SetData(IReadOnlyList<Pose> joints, Pose root, Handedness handedness) { Assert.AreEqual(NumHandJoints, joints.Count); int jointValueIndex = 0; for (int jointIndex = 0; jointIndex < NumHandJoints; jointIndex++) { Pose joint = joints[jointIndex]; jointValues[jointValueIndex++] = joint.rotation.x; jointValues[jointValueIndex++] = joint.rotation.y; jointValues[jointValueIndex++] = joint.rotation.z; jointValues[jointValueIndex++] = joint.rotation.w; jointValues[jointValueIndex++] = joint.position.x; jointValues[jointValueIndex++] = joint.position.y; jointValues[jointValueIndex++] = joint.position.z; } this._rootRotX = root.rotation.x; this._rootRotY = root.rotation.y; this._rootRotZ = root.rotation.z; this._rootRotW = root.rotation.w; this._rootPosX = root.position.x; this._rootPosY = root.position.y; this._rootPosZ = root.position.z; this._handedness = (int)handedness; } } #region DLLImports enum ReturnValue { Success = 0, Failure = -1 }; [DllImport("InteractionSdk")] private static extern int isdk_FingerPalmGrabAPI_Create(); [DllImport("InteractionSdk")] private static extern ReturnValue isdk_FingerPalmGrabAPI_UpdateHandData(int handle, [In] HandData data); [DllImport("InteractionSdk")] private static extern ReturnValue isdk_FingerPalmGrabAPI_GetFingerIsGrabbing(int handle, HandFinger finger, out bool grabbing); [DllImport("InteractionSdk")] private static extern ReturnValue isdk_FingerPalmGrabAPI_GetFingerIsGrabbingChanged(int handle, HandFinger finger, bool targetGrabState, out bool changed); [DllImport("InteractionSdk")] private static extern ReturnValue isdk_FingerPalmGrabAPI_GetFingerGrabScore(int handle, HandFinger finger, out float score); [DllImport("InteractionSdk")] private static extern ReturnValue isdk_FingerPalmGrabAPI_GetCenterOffset(int handle, out Vector3 score); #endregion private int apiHandle_ = -1; private HandData handData_; public FingerPalmGrabAPI() { handData_ = new HandData(); } private int GetHandle() { if (apiHandle_ == -1) { apiHandle_ = isdk_FingerPalmGrabAPI_Create(); Debug.Assert(apiHandle_ != -1, "FingerPalmGrabAPI: isdk_FingerPalmGrabAPI_Create failed"); } return apiHandle_; } public bool GetFingerIsGrabbing(HandFinger finger) { ReturnValue rv = isdk_FingerPalmGrabAPI_GetFingerIsGrabbing(GetHandle(), finger, out bool grabbing); Debug.Assert(rv != ReturnValue.Failure, "FingerPalmGrabAPI: isdk_FingerPalmGrabAPI_GetFingerIsGrabbing failed"); return grabbing; } public bool GetFingerIsGrabbingChanged(HandFinger finger, bool targetGrabState) { ReturnValue rv = isdk_FingerPalmGrabAPI_GetFingerIsGrabbingChanged(GetHandle(), finger, targetGrabState, out bool grabbing); Debug.Assert(rv != ReturnValue.Failure, "FingerPalmGrabAPI: isdk_FingerPalmGrabAPI_GetFingerIsGrabbingChanged failed"); return grabbing; } public float GetFingerGrabScore(HandFinger finger) { ReturnValue rv = isdk_FingerPalmGrabAPI_GetFingerGrabScore(GetHandle(), finger, out float score); Debug.Assert(rv != ReturnValue.Failure, "FingerPalmGrabAPI: isdk_FingerPalmGrabAPI_GetFingerGrabScore failed"); return score; } public void Update(IHand hand) { if (!hand.GetRootPose(out Pose rootPose)) { return; } if (!hand.GetJointPosesFromWrist(out ReadOnlyHandJointPoses poses)) { return; } handData_.SetData(poses, rootPose, hand.Handedness); ReturnValue rv = isdk_FingerPalmGrabAPI_UpdateHandData(GetHandle(), handData_); Debug.Assert(rv != ReturnValue.Failure, "FingerPalmGrabAPI: isdk_FingerPalmGrabAPI_UpdateHandData failed"); } public Vector3 GetWristOffsetLocal() { ReturnValue rv = isdk_FingerPalmGrabAPI_GetCenterOffset(GetHandle(), out Vector3 center); Debug.Assert(rv != ReturnValue.Failure, "FingerPalmGrabAPI: isdk_FingerPalmGrabAPI_GetCenterOffset failed"); return center; } } }
0
0.831419
1
0.831419
game-dev
MEDIA
0.803929
game-dev
0.789186
1
0.789186
ION28/BLUESPAWN
24,085
BLUESPAWN-win-client/src/user/BLUESPAWN.cpp
#include "user/bluespawn.h" #include <iostream> #include <memory> #include "util/DynamicLinker.h" #include "util/StringUtils.h" #include "util/ThreadPool.h" #include "util/eventlogs/EventLogs.h" #include "util/log/CLISink.h" #include "util/log/DebugSink.h" #include "util/log/JSONSink.h" #include "util/log/XMLSink.h" #include "hunt/hunts/HuntT1036.h" #include "hunt/hunts/HuntT1037.h" #include "hunt/hunts/HuntT1053.h" #include "hunt/hunts/HuntT1055.h" #include "hunt/hunts/HuntT1068.h" #include "hunt/hunts/HuntT1070.h" #include "hunt/hunts/HuntT1136.h" #include "hunt/hunts/HuntT1484.h" #include "hunt/hunts/HuntT1505.h" #include "hunt/hunts/HuntT1543.h" #include "hunt/hunts/HuntT1546.h" #include "hunt/hunts/HuntT1547.h" #include "hunt/hunts/HuntT1548.h" #include "hunt/hunts/HuntT1553.h" #include "hunt/hunts/HuntT1562.h" #include "hunt/hunts/HuntT1569.h" #include "reaction/CarveMemory.h" #include "reaction/DeleteFile.h" #include "reaction/QuarantineFile.h" #include "reaction/RemoveValue.h" #include "reaction/SuspendProcess.h" #include "scan/FileScanner.h" #include "scan/ProcessScanner.h" #include "user/CLI.h" #pragma warning(push) #pragma warning(disable : 26451) #pragma warning(disable : 26444) #include "cxxopts.hpp" #pragma warning(pop) #include <VersionHelpers.h> #include <iostream> DEFINE_FUNCTION(BOOL, IsWow64Process2, NTAPI, HANDLE hProcess, USHORT* pProcessMachine, USHORT* pNativeMachine); LINK_FUNCTION(IsWow64Process2, KERNEL32.DLL); const IOBase& Bluespawn::io = CLI::GetInstance(); HuntRegister Bluespawn::huntRecord{}; MitigationRegister Bluespawn::mitigationRecord{}; Aggressiveness Bluespawn::aggressiveness{ Aggressiveness::Normal }; DetectionRegister Bluespawn::detections{ Certainty::Moderate }; ReactionManager Bluespawn::reaction{}; std::vector<std::shared_ptr<DetectionSink>> Bluespawn::detectionSinks{}; bool Bluespawn::EnablePreScanDetections{ false }; std::map<std::string, std::unique_ptr<Reaction>> reactions{}; Bluespawn::Bluespawn() { huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1036>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1037>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1053>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1055>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1068>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1070>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1136>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1484>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1505>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1543>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1546>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1547>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1548>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1553>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1562>()); huntRecord.RegisterHunt(std::make_unique<Hunts::HuntT1569>()); mitigationRecord.Initialize(); reactions.emplace("carve-memory", std::make_unique<Reactions::CarveMemoryReaction>()); reactions.emplace("delete-file", std::make_unique<Reactions::DeleteFileReaction>()); reactions.emplace("quarantine-file", std::make_unique<Reactions::QuarantineFileReaction>()); reactions.emplace("remove-value", std::make_unique<Reactions::RemoveValueReaction>()); reactions.emplace("suspend", std::make_unique<Reactions::SuspendProcessReaction>()); } void Bluespawn::RunHunts() { Bluespawn::io.InformUser(L"Starting a Hunt"); DWORD tactics = UINT_MAX; DWORD dataSources = UINT_MAX; DWORD affectedThings = UINT_MAX; Scope scope{}; huntRecord.RunHunts(vIncludedHunts, vExcludedHunts, scope); } void Bluespawn::RunMitigations(bool enforce) { if(enforce) { Bluespawn::io.InformUser(L"Enforcing Mitigations"); mitigationRecord.PrintMitigationReports(mitigationRecord.EnforceMitigations(*mitigationConfig)); } else { Bluespawn::io.InformUser(L"Auditing Mitigations"); mitigationRecord.PrintMitigationReports(mitigationRecord.AuditMitigations(*mitigationConfig)); } } void Bluespawn::RunMonitor() { DWORD tactics = UINT_MAX; DWORD dataSources = UINT_MAX; DWORD affectedThings = UINT_MAX; Scope scope{}; Bluespawn::io.InformUser(L"Monitoring the system"); huntRecord.SetupMonitoring(vIncludedHunts, vExcludedHunts); HandleWrapper hRecordEvent{ CreateEventW(nullptr, false, false, L"Local\\FlushLogs") }; while(true) { SetEvent(hRecordEvent); Sleep(5000); } } void Bluespawn::AddReaction(std::unique_ptr<Reaction>&& reaction) { Bluespawn::reaction.AddHandler(std::move(reaction)); } void Bluespawn::EnableMode(BluespawnMode mode, int option) { modes.emplace(mode, option); } void Bluespawn::SetIncludedHunts(std::vector<std::string> includedHunts) { for(auto& id : includedHunts) { Bluespawn::vIncludedHunts.emplace_back(StringToWidestring(id)); } } void Bluespawn::SetExcludedHunts(std::vector<std::string> excludedHunts) { for(auto& id : excludedHunts) { Bluespawn::vExcludedHunts.emplace_back(StringToWidestring(id)); } } void Bluespawn::RunScan(){ std::vector<std::shared_ptr<Detection>> detections; for(auto& file : scanFiles){ if(FileScanner::PerformQuickScan(file.GetFilePath())){ detections.emplace_back(Bluespawn::detections.AddDetection(Detection(FileDetectionData{ file }))); } } for(auto pid : scanProcesses){ Hunts::HuntT1055::HandleReport(detections, Hunts::HuntT1055::QueueProcessScan(pid)); } } void Bluespawn::Run() { if(modes.find(BluespawnMode::MITIGATE) != modes.end()) { RunMitigations(modes[BluespawnMode::MITIGATE]); } if(modes.find(BluespawnMode::HUNT) != modes.end()) { RunHunts(); } if(modes.find(BluespawnMode::MONITOR) != modes.end()){ RunMonitor(); } if(modes.find(BluespawnMode::SCAN) != modes.end()){ RunScan(); } ThreadPool::GetInstance().Wait(); Bluespawn::detections.Wait(); } void print_help(cxxopts::ParseResult result, cxxopts::Options options) { std::string help_category = result["help"].as<std::string>(); std::string output = ""; if(CompareIgnoreCase(help_category, std::string{ "hunt" })) { output = options.help({ "hunt" }); } else if(CompareIgnoreCase(help_category, std::string{ "monitor" })) { output = std::regex_replace(options.help({ "hunt" }), std::regex("hunt options"), "monitor options"); } else if(CompareIgnoreCase(help_category, std::string{ "mitigate" })) { output = options.help({ "mitigate" }); } else { output = std::regex_replace(options.help(), std::regex("hunt options"), "hunt/monitor options"); } Bluespawn::io.InformUser(StringToWidestring(output)); } void Bluespawn::SetMitigationConfig(const MitigationsConfiguration& config){ mitigationConfig = config; } void Bluespawn::check_correct_arch() { BOOL bIsWow64 = FALSE; if(IsWindows10OrGreater() && Linker::IsWow64Process2) { USHORT ProcessMachine; USHORT NativeMachine; Linker::IsWow64Process2(GetCurrentProcess(), &ProcessMachine, &NativeMachine); if(ProcessMachine != IMAGE_FILE_MACHINE_UNKNOWN) { bIsWow64 = TRUE; } } else { IsWow64Process(GetCurrentProcess(), &bIsWow64); } if(bIsWow64) { Bluespawn::io.AlertUser(L"Running the x86 version of BLUESPAWN on an x64 system! This configuration is not " L"fully supported, so we recommend downloading the x64 version.", 5000, ImportanceLevel::MEDIUM); LOG_WARNING("Running the x86 version of BLUESPAWN on an x64 system! This configuration is not fully supported, " "so we recommend downloading the x64 version."); } } void ParseLogSinks(const std::string& sinks, const std::string& logdir) { std::set<std::string> sink_set; for(unsigned startIdx = 0; startIdx < sinks.size();) { auto endIdx{ sinks.find(',', startIdx) }; auto sink{ sinks.substr(startIdx, endIdx - startIdx) }; sink_set.emplace(sink); startIdx = endIdx + 1; if(endIdx == std::string::npos) { break; } } std::wstring outputFolderPath = L"."; auto outputDir = FileSystem::Folder(StringToWidestring(logdir)); if(outputDir.GetFolderExists() && !outputDir.GetCurIsFile() && outputDir.GetFolderWrite()) { outputFolderPath = outputDir.GetFolderPath(); } else { LOG_ERROR(L"Unable to access " << StringToWidestring(logdir) << L" to write logs. Defaulting to current directory."); Bluespawn::io.AlertUser(L"Unable to access " + StringToWidestring(logdir) + L" to write logs. Defaulting to current directory.", 5000, ImportanceLevel::MEDIUM); } std::vector<std::reference_wrapper<Log::LogLevel>> levels{ Log::LogLevel::LogError, Log::LogLevel::LogWarn, Log::LogLevel::LogInfo1, Log::LogLevel::LogInfo2, Log::LogLevel::LogInfo3, Log::LogLevel::LogVerbose1, Log::LogLevel::LogVerbose2, Log::LogLevel::LogVerbose3, }; for(auto sink : sink_set) { if(sink == "console") { auto console = std::make_shared<Log::CLISink>(); Log::AddSink(console, levels); Bluespawn::detectionSinks.emplace_back(console); } else if(sink == "xml") { auto XML = std::make_shared<Log::XMLSink>(outputFolderPath); Log::AddSink(XML, levels); Bluespawn::detectionSinks.emplace_back(XML); } else if(sink == "json") { auto JSON = std::make_shared<Log::JSONSink>(outputFolderPath); Log::AddSink(JSON, levels); Bluespawn::detectionSinks.emplace_back(JSON); } else if(sink == "debug") { auto debug = std::make_shared<Log::DebugSink>(); Log::AddSink(debug, levels); Bluespawn::detectionSinks.emplace_back(debug); } else { Bluespawn::io.AlertUser(L"Unknown log sink \"" + StringToWidestring(sink) + L"\"", INFINITY, ImportanceLevel::MEDIUM); } } } Aggressiveness GetAggressiveness(const cxxopts::OptionValue& value) { Aggressiveness aHuntLevel{}; auto level{ value.as<std::string>() }; if(CompareIgnoreCase<std::string>(level, "Cursory")) { aHuntLevel = Aggressiveness::Cursory; } else if(CompareIgnoreCase<std::string>(level, "Normal")) { aHuntLevel = Aggressiveness::Normal; } else if(CompareIgnoreCase<std::string>(level, "Intensive")) { aHuntLevel = Aggressiveness::Intensive; } else { LOG_ERROR("Error " << StringToWidestring(level) << " - Unknown level. Please specify either Cursory, Normal, or Intensive"); LOG_ERROR("Will default to Normal for this run."); Bluespawn::io.InformUser(L"Error " + StringToWidestring(level) + L" - Unknown level. Please specify either Cursory, Normal, or Intensive"); Bluespawn::io.InformUser(L"Will default to Normal."); aHuntLevel = Aggressiveness::Normal; } return aHuntLevel; } int main(int argc, char* argv[]) { Log::LogLevel::LogError.Enable(); Log::LogLevel::LogWarn.Enable(); ThreadPool::GetInstance().AddExceptionHandler([](const auto& e) { LOG_ERROR(e.what()); }); Bluespawn bluespawn{}; print_banner(); bluespawn.check_correct_arch(); if(argc == 1) { Bluespawn::io.AlertUser(L"Please launch BLUESPAWN from a CLI and specify what you want it to do. You can use " L"the --help flag to see what options are available.", INFINITE, ImportanceLevel::MEDIUM); } cxxopts::Options options("BLUESPAWN.exe", "BLUESPAWN: An Active Defense and EDR software to empower Blue Teams"); // clang-format off options.add_options() ("h,hunt", "Hunt for malicious activity on the system", cxxopts::value<bool>()) ("n,monitor", "Monitor the system for malicious activity, dispatching hunts as changes are detected.", cxxopts::value<bool>()) ("m,mitigate", "Mitigate vulnerabilities by applying security settings.", cxxopts::value<bool>()) ("s,scan", "Scan a particular process, file, or folder", cxxopts::value<bool>()) ("log", "Specify how BLUESPAWN should log events. Options are console, xml, json, and debug.", cxxopts::value<std::string>()->default_value("console")->implicit_value("console")) ("help", "Help Information. You can also specify a category for help on a specific module such as hunt.", cxxopts::value<std::string>()->implicit_value("general")) ("v,verbose", "Verbosity", cxxopts::value<int>()->default_value("1")) ("debug", "Enable Debug Output", cxxopts::value<int>()->default_value("0")) ("a,aggressiveness", "Sets the aggressiveness of BLUESPAWN. Options are cursory, normal, and intensive", cxxopts::value<std::string>()->default_value("Normal")) ("r,react", "Specifies how BLUESPAWN should react to potential threats dicovered during hunts. Available reactions are remove-value, carve-memory, suspend, delete-file, and quarantine-file", cxxopts::value<std::string>()->default_value("")) ; options.add_options("scan") ("scan-folder", "Specify a folder to scan", cxxopts::value<std::vector<std::string>>()->implicit_value({})) ("scan-file", "Specify a file to scan", cxxopts::value<std::vector<std::string>>()->implicit_value({})) ("scan-process", "Specify a process to scan by PID", cxxopts::value<std::vector<int>>()->implicit_value({})) ; options.add_options("hunt") ("hunts", "Only run the hunts specified. Provide as a comma separated list of Mitre ATT&CK Technique IDs.", cxxopts::value<std::vector<std::string>>()) ("exclude-hunts", "Run all hunts except those specified. Provide as a comma separated list of Mitre ATT&CK Technique IDs.", cxxopts::value<std::vector<std::string>>()) ; options.add_options("log") ("o,output", "Specify the output folder for any logs written to a file", cxxopts::value<std::string>()->default_value(".")) ; options.add_options("mitigate") ("mode", "Selects whether to audit or enforce each mitigations. Options are audit and enforce. Ignored if " "--gen-config is specified", cxxopts::value<std::string>()->default_value("audit")->implicit_value("audit")) ("config-json", "Specify a file containing a JSON configuration for which mitigations and policies should run", cxxopts::value<std::string>()) ("enforcement-level", "Specify the enforcement level for mitigations. This is used to select which policies " "should be run. Available levels are none, low, moderate, high, and all", cxxopts::value<std::string>()->default_value("moderate")->implicit_value("moderate")) ("add-mitigations", "Specify additional JSON files containing mitigations.", cxxopts::value<std::vector<std::string>>()) ("gen-config", "Generate a default JSON configuration file (./bluespawn-mitigation-config.json) with the " "specified level of detail. Options are global, mitigations, and mitigation-policies. Will not " "run any mitigations if this is specified", cxxopts::value<std::string>()->default_value("mitigations")) ; // clang-format on try { auto result = options.parse(argc, argv); if(result.count("help")) { print_help(result, options); return 0; } if(result["verbose"].as<int>() >= 1) { Log::LogLevel::LogInfo1.Enable(); } if(result["verbose"].as<int>() >= 2) { Log::LogLevel::LogInfo2.Enable(); } if(result["verbose"].as<int>() >= 3) { Log::LogLevel::LogInfo3.Enable(); } if(result.count("debug")) { if(result["debug"].as<int>() >= 1) { Log::LogLevel::LogVerbose1.Enable(); } if(result["debug"].as<int>() >= 2) { Log::LogLevel::LogVerbose2.Enable(); } if(result["debug"].as<int>() >= 3) { Log::LogLevel::LogVerbose3.Enable(); } } ParseLogSinks(result["log"].as<std::string>(), result["output"].as<std::string>()); if(result.count("aggressiveness")){ bluespawn.aggressiveness = GetAggressiveness(result["aggressiveness"]); } if(result.count("hunt") || result.count("monitor") || result.count("scan")) { if(result.count("hunt")) { bluespawn.EnableMode(BluespawnMode::HUNT); } if(result.count("monitor")) { bluespawn.EnableMode(BluespawnMode::MONITOR); } if(result.count("scan")){ if(result.count("scan-file")){ for(auto& filePath : result["scan-file"].as<std::vector<std::string>>()){ FileSystem::File file{ StringToWidestring(filePath) }; if(!file.GetFileExists()){ Bluespawn::io.AlertUser(L"File " + file.GetFilePath() + L" not found"); continue; } bluespawn.scanFiles.emplace_back(file); } } if(result.count("scan-folder")){ for(auto& folderPath : result["scan-folder"].as<std::vector<std::string>>()){ FileSystem::Folder folder{ StringToWidestring(folderPath) }; if(!folder.GetFolderExists()){ Bluespawn::io.AlertUser(L"Folder " + folder.GetFolderPath() + L" not found"); continue; } auto folderContents{ folder.GetFiles() }; for(auto& file : folderContents){ bluespawn.scanFiles.emplace_back(file); } } } if(result.count("scan-process")){ for(auto& process : result["scan-process"].as<std::vector<int>>()){ bluespawn.scanProcesses.emplace_back(process); } } bluespawn.EnableMode(BluespawnMode::SCAN); } if(result.count("hunts")) { bluespawn.SetIncludedHunts(result["hunts"].as<std::vector<std::string>>()); } else if(result.count("exclude-hunts")) { bluespawn.SetExcludedHunts(result["exclude-hunts"].as<std::vector<std::string>>()); } auto UserReactions = result["react"].as<std::string>(); std::set<std::string> reaction_set; for(unsigned startIdx = 0; startIdx < UserReactions.size();) { auto endIdx{ UserReactions.find(',', startIdx) }; auto sink{ UserReactions.substr(startIdx, endIdx - startIdx) }; reaction_set.emplace(sink); startIdx = endIdx + 1; if(endIdx == std::string::npos) { break; } } for(auto reaction : reaction_set) { if(reactions.find(reaction) != reactions.end()) { bluespawn.AddReaction(std::move(reactions[reaction])); } else { bluespawn.io.AlertUser(L"Unknown reaction \"" + StringToWidestring(reaction) + L"\"", INFINITY, ImportanceLevel::MEDIUM); } } } if(result.count("mitigate")) { if(result.count("add-mitigations")){ for(auto& path : result["add-mitigations"].as<std::vector<std::string>>()){ Bluespawn::mitigationRecord.ParseMitigationsJSON({ StringToWidestring(path) }); } } if(result.count("gen-config")){ auto opt{ ToLowerCaseA(result["gen-config"].as<std::string>()) }; std::map<std::string, int> genConfigOptions{ {"global", 0}, {"mitigations", 1}, {"mitigation-policies", 2} }; if(genConfigOptions.count(opt)){ if(Bluespawn::mitigationRecord.CreateConfig( FileSystem::File{ L".\\bluespawn-mitigation-config.json" }, genConfigOptions[opt])){ Bluespawn::io.InformUser(L"Saved configuration to .\\bluespawn-mitigation-config.json"); } } else{ Bluespawn::io.AlertUser(StringToWidestring("Unknown gen-config mode \"" + opt + "\". Options are " "global, mitigations, and mitigation-policies")); } } else{ auto mode{ result["mode"].as<std::string>() }; bool enforce{ mode == "e" || mode == "enforce" }; std::map<std::string, EnforcementLevel> enforcementLevelOptions{ {"none", EnforcementLevel::None}, {"low", EnforcementLevel::Low}, {"moderate", EnforcementLevel::Moderate}, {"high", EnforcementLevel::High}, {"all", EnforcementLevel::All}, }; auto fileSpecified{ result.count("config-json") }; if(!fileSpecified){ auto level{ EnforcementLevel::None }; auto levelSpecified{ result["enforcement-level"].as<std::string>() }; if(enforcementLevelOptions.count(levelSpecified)){ level = enforcementLevelOptions[levelSpecified]; } else{ Bluespawn::io.AlertUser( StringToWidestring("Unknown enforcement level \"" + levelSpecified + "\". Options are none," "low, moderate, high, and all. Defaulting to none")); } bluespawn.SetMitigationConfig(level); } else{ auto file{ FileSystem::File(StringToWidestring(result["config-json"].as<std::string>())) }; if(file.GetFileExists()){ try{ auto contents{ file.Read() }; bluespawn.SetMitigationConfig(json::parse(nlohmann::detail::span_input_adapter( contents.GetAsPointer<char>(), contents.GetSize()))); } catch(std::exception& e){ Bluespawn::io.AlertUser(L"Error parsing JSON: " + StringToWidestring(e.what())); } } else{ Bluespawn::io.AlertUser(L"JSON configuration file " + file.GetFilePath() + L" not found!"); bluespawn.SetMitigationConfig(EnforcementLevel::None); } } bluespawn.EnableMode(BluespawnMode::MITIGATE, enforce); } } bluespawn.Run(); } catch(cxxopts::OptionParseException e1) { Bluespawn::io.InformUser(StringToWidestring(options.help())); LOG_ERROR(e1.what()); } return 0; }
0
0.982462
1
0.982462
game-dev
MEDIA
0.758882
game-dev
0.950022
1
0.950022
DK22Pac/plugin-sdk
8,366
plugin_sa/game_sa/meta/meta.CStreamedScripts.h
/* Plugin-SDK (Grand Theft Auto San Andreas) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "PluginBase.h" namespace plugin { META_BEGIN(CStreamedScripts::Initialise) static int address; static int global_address; static const int id = 0x470660; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470660, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x5B8E16, GAME_10US_COMPACT, H_CALL, 0x5B8AD0, 1>; using def_t = void(CStreamedScripts *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *>, 0>; META_END META_BEGIN(CStreamedScripts::ReInitialise) static int address; static int global_address; static const int id = 0x4706A0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4706A0, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x40E568, GAME_10US_COMPACT, H_CALL, 0x40E560, 1>; using def_t = void(CStreamedScripts *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *>, 0>; META_END META_BEGIN(CStreamedScripts::RegisterScript) static int address; static int global_address; static const int id = 0x4706C0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4706C0, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x5B6419, GAME_10US_COMPACT, H_CALL, 0x5B6170, 1>; using def_t = int(CStreamedScripts *, char const *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,char const *>, 0,1>; META_END META_BEGIN(CStreamedScripts::FindStreamedScriptQuiet) static int address; static int global_address; static const int id = 0x4706F0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4706F0, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x470740, GAME_10US_COMPACT, H_JUMP, 0x470740, 1>; using def_t = signed int(CStreamedScripts *, char const *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,char const *>, 0,1>; META_END META_BEGIN(CStreamedScripts::FindStreamedScript) static int address; static int global_address; static const int id = 0x470740; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470740, 0, 0, 0, 0, 0>; using refs_t = RefList<>; using def_t = signed int(CStreamedScripts *, char const *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,char const *>, 0,1>; META_END META_BEGIN(CStreamedScripts::ReadStreamedScriptData) static int address; static int global_address; static const int id = 0x470750; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470750, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x468F97, GAME_10US_COMPACT, H_CALL, 0x468D50, 1>; using def_t = void(CStreamedScripts *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *>, 0>; META_END META_BEGIN(CStreamedScripts::GetProperIndexFromIndexUsedByScript) static int address; static int global_address; static const int id = 0x470810; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470810, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x471CA7, GAME_10US_COMPACT, H_CALL, 0x470A90, 1, 0x472382, GAME_10US_COMPACT, H_CALL, 0x472310, 1, 0x475025, GAME_10US_COMPACT, H_CALL, 0x474900, 1, 0x475061, GAME_10US_COMPACT, H_CALL, 0x474900, 2, 0x4766A1, GAME_10US_COMPACT, H_CALL, 0x4762D0, 1, 0x4766DD, GAME_10US_COMPACT, H_CALL, 0x4762D0, 2, 0x47675A, GAME_10US_COMPACT, H_CALL, 0x4762D0, 3, 0x476D28, GAME_10US_COMPACT, H_CALL, 0x4762D0, 4, 0x476D56, GAME_10US_COMPACT, H_CALL, 0x4762D0, 5, 0x476DB0, GAME_10US_COMPACT, H_CALL, 0x4762D0, 6>; using def_t = signed short(CStreamedScripts *, short); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,short>, 0,1>; META_END META_BEGIN(CStreamedScripts::LoadStreamedScript) static int address; static int global_address; static const int id = 0x470840; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470840, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x40CAB3, GAME_10US_COMPACT, H_CALL, 0x40C6B0, 1>; using def_t = void(CStreamedScripts *, RwStream *, int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,RwStream *,int>, 0,1,2>; META_END META_BEGIN(CStreamedScripts::StartNewStreamedScript) static int address; static int global_address; static const int id = 0x470890; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470890, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x46B286, GAME_10US_COMPACT, H_CALL, 0x46B270, 1, 0x47676D, GAME_10US_COMPACT, H_CALL, 0x4762D0, 1>; using def_t = CRunningScript *(CStreamedScripts *, int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,int>, 0,1>; META_END META_BEGIN(CStreamedScripts::RemoveStreamedScriptFromMemory) static int address; static int global_address; static const int id = 0x4708E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4708E0, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x408ABE, GAME_10US_COMPACT, H_CALL, 0x4089A0, 1, 0x408C55, GAME_10US_COMPACT, H_CALL, 0x4089A0, 2>; using def_t = void(CStreamedScripts *, int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,int>, 0,1>; META_END META_BEGIN(CStreamedScripts::GetStreamedScriptFilename) static int address; static int global_address; static const int id = 0x470900; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470900, 0, 0, 0, 0, 0>; using refs_t = RefList<>; using def_t = char const *(CStreamedScripts *, unsigned short); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,unsigned short>, 0,1>; META_END META_BEGIN(CStreamedScripts::GetStreamedScriptWithThisStartAddress) static int address; static int global_address; static const int id = 0x470910; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x470910, 0, 0, 0, 0, 0>; using refs_t = RefList< 0x465AD4, GAME_10US_COMPACT, H_CALL, 0x465AA0, 1>; using def_t = unsigned short(CStreamedScripts *, unsigned char *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CStreamedScripts *,unsigned char *>, 0,1>; META_END }
0
0.768466
1
0.768466
game-dev
MEDIA
0.485772
game-dev
0.663842
1
0.663842
amethyst/rustrogueliketutorial
1,805
chapter-67-dragon/src/map_builders/voronoi_spawning.rs
use super::{MetaMapBuilder, BuilderMap, TileType, spawner}; use rltk::RandomNumberGenerator; use std::collections::HashMap; pub struct VoronoiSpawning {} impl MetaMapBuilder for VoronoiSpawning { fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) { self.build(rng, build_data); } } impl VoronoiSpawning { #[allow(dead_code)] pub fn new() -> Box<VoronoiSpawning> { Box::new(VoronoiSpawning{}) } #[allow(clippy::map_entry)] fn build(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) { let mut noise_areas : HashMap<i32, Vec<usize>> = HashMap::new(); let mut noise = rltk::FastNoise::seeded(rng.roll_dice(1, 65536) as u64); noise.set_noise_type(rltk::NoiseType::Cellular); noise.set_frequency(0.08); noise.set_cellular_distance_function(rltk::CellularDistanceFunction::Manhattan); for y in 1 .. build_data.map.height-1 { for x in 1 .. build_data.map.width-1 { let idx = build_data.map.xy_idx(x, y); if build_data.map.tiles[idx] == TileType::Floor { let cell_value_f = noise.get_noise(x as f32, y as f32) * 10240.0; let cell_value = cell_value_f as i32; if noise_areas.contains_key(&cell_value) { noise_areas.get_mut(&cell_value).unwrap().push(idx); } else { noise_areas.insert(cell_value, vec![idx]); } } } } // Spawn the entities for area in noise_areas.iter() { spawner::spawn_region(&build_data.map, rng, area.1, build_data.map.depth, &mut build_data.spawn_list); } } }
0
0.891964
1
0.891964
game-dev
MEDIA
0.944564
game-dev
0.934422
1
0.934422
cpw/ironchest
16,815
src/main/java/cpw/mods/ironchest/TileEntityIronChest.java
/******************************************************************************* * Copyright (c) 2012 cpw. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * cpw - initial API and implementation ******************************************************************************/ package cpw.mods.ironchest; import java.util.Arrays; import java.util.Comparator; import java.util.List; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntityLockable; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraftforge.common.util.Constants; public class TileEntityIronChest extends TileEntityLockable implements ITickable, IInventory { private int ticksSinceSync = -1; public float prevLidAngle; public float lidAngle; private int numUsingPlayers; private IronChestType type; public ItemStack[] chestContents; private ItemStack[] topStacks; private byte facing; private boolean inventoryTouched; private boolean hadStuff; private String customName; public TileEntityIronChest() { this(IronChestType.IRON); } protected TileEntityIronChest(IronChestType type) { super(); this.type = type; this.chestContents = new ItemStack[getSizeInventory()]; this.topStacks = new ItemStack[8]; } public ItemStack[] getContents() { return chestContents; } public void setContents(ItemStack[] contents) { chestContents = new ItemStack[getSizeInventory()]; for (int i = 0; i < contents.length; i++) { if (i < chestContents.length) { chestContents[i] = contents[i]; } } inventoryTouched = true; } @Override public int getSizeInventory() { return type.size; } public int getFacing() { return this.facing; } public IronChestType getType() { return type; } @Override public ItemStack getStackInSlot(int i) { inventoryTouched = true; return chestContents[i]; } @Override public void markDirty() { super.markDirty(); sortTopStacks(); } protected void sortTopStacks() { if (!type.isTransparent() || (worldObj != null && worldObj.isRemote)) { return; } ItemStack[] tempCopy = new ItemStack[getSizeInventory()]; boolean hasStuff = false; int compressedIdx = 0; mainLoop: for (int i = 0; i < getSizeInventory(); i++) { if (chestContents[i] != null) { for (int j = 0; j < compressedIdx; j++) { if (tempCopy[j].isItemEqual(chestContents[i])) { tempCopy[j].stackSize += chestContents[i].stackSize; continue mainLoop; } } tempCopy[compressedIdx++] = chestContents[i].copy(); hasStuff = true; } } if (!hasStuff && hadStuff) { hadStuff = false; for (int i = 0; i < topStacks.length; i++) { topStacks[i] = null; } if (worldObj != null) { worldObj.markBlockForUpdate(pos); } return; } hadStuff = true; Arrays.sort(tempCopy, new Comparator<ItemStack>() { @Override public int compare(ItemStack o1, ItemStack o2) { if (o1 == null) { return 1; } else if (o2 == null) { return -1; } else { return o2.stackSize - o1.stackSize; } } }); int p = 0; for (int i = 0; i < tempCopy.length; i++) { if (tempCopy[i] != null && tempCopy[i].stackSize > 0) { topStacks[p++] = tempCopy[i]; if (p == topStacks.length) { break; } } } for (int i = p; i < topStacks.length; i++) { topStacks[i] = null; } if (worldObj != null) { worldObj.markBlockForUpdate(pos); } } @Override public ItemStack decrStackSize(int i, int j) { if (chestContents[i] != null) { if (chestContents[i].stackSize <= j) { ItemStack itemstack = chestContents[i]; chestContents[i] = null; markDirty(); return itemstack; } ItemStack itemstack1 = chestContents[i].splitStack(j); if (chestContents[i].stackSize == 0) { chestContents[i] = null; } markDirty(); return itemstack1; } else { return null; } } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { chestContents[i] = itemstack; if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { itemstack.stackSize = getInventoryStackLimit(); } markDirty(); } @Override public String getName() { return this.hasCustomName() ? this.customName : type.name(); } @Override public boolean hasCustomName() { return this.customName != null && this.customName.length() > 0; } public void setCustomName(String name) { this.customName = name; } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); NBTTagList nbttaglist = nbttagcompound.getTagList("Items", Constants.NBT.TAG_COMPOUND); this.chestContents = new ItemStack[getSizeInventory()]; if (nbttagcompound.hasKey("CustomName", Constants.NBT.TAG_STRING)) { this.customName = nbttagcompound.getString("CustomName"); } for (int i = 0; i < nbttaglist.tagCount(); i++) { NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound1.getByte("Slot") & 0xff; if (j >= 0 && j < chestContents.length) { chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1); } } facing = nbttagcompound.getByte("facing"); sortTopStacks(); } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < chestContents.length; i++) { if (chestContents[i] != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte) i); chestContents[i].writeToNBT(nbttagcompound1); nbttaglist.appendTag(nbttagcompound1); } } nbttagcompound.setTag("Items", nbttaglist); nbttagcompound.setByte("facing", facing); if (this.hasCustomName()) { nbttagcompound.setString("CustomName", this.customName); } } @Override public int getInventoryStackLimit() { return 64; } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { if (worldObj == null) { return true; } if (worldObj.getTileEntity(pos) != this) { return false; } return entityplayer.getDistanceSq(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D) <= 64D; } @Override public void update() { // Resynchronize clients with the server state if (worldObj != null && !this.worldObj.isRemote && this.numUsingPlayers != 0 && (this.ticksSinceSync + pos.getX() + pos.getY() + pos.getZ()) % 200 == 0) { this.numUsingPlayers = 0; float var1 = 5.0F; List<EntityPlayer> var2 = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, new AxisAlignedBB(pos.getX() - var1, pos.getY() - var1, pos.getZ() - var1, pos.getX() + 1 + var1, pos.getY() + 1 + var1, pos.getZ() + 1 + var1)); for (EntityPlayer var4 : var2) { if (var4.openContainer instanceof ContainerIronChest) { ++this.numUsingPlayers; } } } if (worldObj != null && !worldObj.isRemote && ticksSinceSync < 0) { worldObj.addBlockEvent(pos, IronChest.ironChestBlock, 3, ((numUsingPlayers << 3) & 0xF8) | (facing & 0x7)); } if (!worldObj.isRemote && inventoryTouched) { inventoryTouched = false; sortTopStacks(); } this.ticksSinceSync++; prevLidAngle = lidAngle; float f = 0.1F; if (numUsingPlayers > 0 && lidAngle == 0.0F) { double d = pos.getX() + 0.5D; double d1 = pos.getZ() + 0.5D; worldObj.playSoundEffect(d, pos.getY() + 0.5D, d1, "random.chestopen", 0.5F, worldObj.rand.nextFloat() * 0.1F + 0.9F); } if (numUsingPlayers == 0 && lidAngle > 0.0F || numUsingPlayers > 0 && lidAngle < 1.0F) { float f1 = lidAngle; if (numUsingPlayers > 0) { lidAngle += f; } else { lidAngle -= f; } if (lidAngle > 1.0F) { lidAngle = 1.0F; } float f2 = 0.5F; if (lidAngle < f2 && f1 >= f2) { double d2 = pos.getX() + 0.5D; double d3 = pos.getZ() + 0.5D; worldObj.playSoundEffect(d2, pos.getY() + 0.5D, d3, "random.chestclosed", 0.5F, worldObj.rand.nextFloat() * 0.1F + 0.9F); } if (lidAngle < 0.0F) { lidAngle = 0.0F; } } } @Override public boolean receiveClientEvent(int i, int j) { if (i == 1) { numUsingPlayers = j; } else if (i == 2) { facing = (byte) j; } else if (i == 3) { facing = (byte) (j & 0x7); numUsingPlayers = (j & 0xF8) >> 3; } return true; } @Override public void openInventory(EntityPlayer player) { if (worldObj == null) { return; } numUsingPlayers++; worldObj.addBlockEvent(pos, IronChest.ironChestBlock, 1, numUsingPlayers); } @Override public void closeInventory(EntityPlayer player) { if (worldObj == null) { return; } numUsingPlayers--; worldObj.addBlockEvent(pos, IronChest.ironChestBlock, 1, numUsingPlayers); } public void setFacing(byte facing2) { this.facing = facing2; } public ItemStack[] getTopItemStacks() { return topStacks; } public TileEntityIronChest updateFromMetadata(int l) { if (worldObj != null && worldObj.isRemote) { if (l != type.ordinal()) { worldObj.setTileEntity(pos, IronChestType.makeEntity(l)); return (TileEntityIronChest) worldObj.getTileEntity(pos); } } return this; } @Override public Packet<?> getDescriptionPacket() { NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("type", getType().ordinal()); nbt.setByte("facing", facing); ItemStack[] stacks = buildItemStackDataList(); if (stacks != null) { NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < stacks.length; i++) { if (stacks[i] != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte) i); stacks[i].writeToNBT(nbttagcompound1); nbttaglist.appendTag(nbttagcompound1); } } nbt.setTag("stacks", nbttaglist); } return new S35PacketUpdateTileEntity(pos, 0, nbt); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { if (pkt.getTileEntityType() == 0) { NBTTagCompound nbt = pkt.getNbtCompound(); type = IronChestType.values()[nbt.getInteger("type")]; facing = nbt.getByte("facing"); NBTTagList tagList = nbt.getTagList("stacks", Constants.NBT.TAG_COMPOUND); ItemStack[] stacks = new ItemStack[topStacks.length]; for (int i = 0; i < stacks.length; i++) { NBTTagCompound nbt1 = tagList.getCompoundTagAt(i); int j = nbt1.getByte("Slot") & 0xff; if (j >= 0 && j < stacks.length) { stacks[j] = ItemStack.loadItemStackFromNBT(nbt1); } } if (type.isTransparent() && stacks != null) { int pos = 0; for (int i = 0; i < topStacks.length; i++) { if (stacks[pos] != null) { topStacks[i] = stacks[pos]; } else { topStacks[i] = null; } pos++; } } } } public ItemStack[] buildItemStackDataList() { if (type.isTransparent()) { ItemStack[] sortList = new ItemStack[topStacks.length]; int pos = 0; for (ItemStack is : topStacks) { if (is != null) { sortList[pos++] = is; } else { sortList[pos++] = null; } } return sortList; } return null; } @Override public ItemStack removeStackFromSlot(int par1) { if (this.chestContents[par1] != null) { ItemStack var2 = this.chestContents[par1]; this.chestContents[par1] = null; return var2; } else { return null; } } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return type.acceptsStack(itemstack); } public void rotateAround() { facing++; if (facing > EnumFacing.EAST.ordinal()) { facing = (byte) EnumFacing.NORTH.ordinal(); } setFacing(facing); worldObj.addBlockEvent(pos, IronChest.ironChestBlock, 2, facing); } public void wasPlaced(EntityLivingBase entityliving, ItemStack itemStack) { } public void removeAdornments() { } @Override public int getField(int id) { return 0; } @Override public void setField(int id, int value) { } @Override public int getFieldCount() { return 0; } @Override public void clear() { for (int i = 0; i < this.chestContents.length; ++i) { this.chestContents[i] = null; } } @Override public Container createContainer(InventoryPlayer playerInventory, EntityPlayer player) { return null; } @Override public String getGuiID() { return "IronChest:" + type.name(); } @Override public boolean canRenderBreaking() { return true; } }
0
0.927202
1
0.927202
game-dev
MEDIA
0.99009
game-dev
0.977647
1
0.977647
Bunny67/Details-WotLK
3,698
Details/Libs/AceGUI-3.0/widgets/AceGUIWidget-Icon.lua
--[[----------------------------------------------------------------------------- Icon Widget -------------------------------------------------------------------------------]] local Type, Version = "Icon", 21 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local select, pairs, print = select, pairs, print -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Button_OnClick(frame, button) frame.obj:Fire("OnClick", button) AceGUI:ClearFocus() end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetHeight(110) self:SetWidth(110) self:SetLabel() self:SetImage(nil) self:SetImageSize(64, 64) self:SetDisabled(false) end, -- ["OnRelease"] = nil, ["SetLabel"] = function(self, text) if text and text ~= "" then self.label:Show() self.label:SetText(text) self:SetHeight(self.image:GetHeight() + 25) else self.label:Hide() self:SetHeight(self.image:GetHeight() + 10) end end, ["SetImage"] = function(self, path, ...) local image = self.image image:SetTexture(path) if image:GetTexture() then local n = select("#", ...) if n == 4 or n == 8 then image:SetTexCoord(...) else image:SetTexCoord(0, 1, 0, 1) end end end, ["SetImageSize"] = function(self, width, height) self.image:SetWidth(width) self.image:SetHeight(height) --self.frame:SetWidth(width + 30) if self.label:IsShown() then self:SetHeight(height + 25) else self:SetHeight(height + 10) end end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.frame:Disable() self.label:SetTextColor(0.5, 0.5, 0.5) self.image:SetVertexColor(0.5, 0.5, 0.5, 0.5) else self.frame:Enable() self.label:SetTextColor(1, 1, 1) self.image:SetVertexColor(1, 1, 1, 1) end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Button", nil, UIParent) frame:Hide() frame:EnableMouse(true) frame:SetScript("OnEnter", Control_OnEnter) frame:SetScript("OnLeave", Control_OnLeave) frame:SetScript("OnClick", Button_OnClick) local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlight") label:SetPoint("BOTTOMLEFT") label:SetPoint("BOTTOMRIGHT") label:SetJustifyH("CENTER") label:SetJustifyV("TOP") label:SetHeight(18) local image = frame:CreateTexture(nil, "BACKGROUND") image:SetWidth(64) image:SetHeight(64) image:SetPoint("TOP", 0, -5) local highlight = frame:CreateTexture(nil, "HIGHLIGHT") highlight:SetAllPoints(image) highlight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight") highlight:SetTexCoord(0, 1, 0.23, 0.77) highlight:SetBlendMode("ADD") local widget = { label = label, image = image, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end widget.SetText = widget.SetLabel return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
0
0.863686
1
0.863686
game-dev
MEDIA
0.640311
game-dev
0.521792
1
0.521792
schoudry/eaem-extensions
1,559
eaem-65-extensions/eaem-dms7-audio-video-component/jcr_root/apps/eaem-dms7-audio-video-component/eaem-dms7-audio-video-component/audio-video.js
use( function(){ var METADATA_NODE = com.day.cq.dam.api.s7dam.constants.S7damConstants.S7_ASSET_METADATA_NODE, SCENE7_FODLER = METADATA_NODE + "/metadata/dam:scene7Folder", SCENE7_DOMAIN = METADATA_NODE + "/metadata/dam:scene7Domain", fileReference = properties['./fileReference'], rootNode = currentSession.rootNode, mediaInfo = {}; if(!fileReference) { mediaInfo.isAudio = false; return; } var assetNode = rootNode.getNode(fileReference.substring(1)), publishUrl = getPublishServerURL(assetNode); //log.info("publishUrl----------" + publishUrl); return{ isAudio: isAudioFile(assetNode), assetName: assetNode.getName(), s7PublishPath: publishUrl, bgImage: assetNode.getPath() + "/jcr:content/renditions/poster.png" }; function isAudioFile(assetNode){ var META_DC_FORMAT = "jcr:content/metadata/dc:format", isAudioFile = false; if(assetNode == undefined){ return isAudioFile; } if( assetNode.hasProperty(META_DC_FORMAT)) { var dcFormat = assetNode.getProperty(META_DC_FORMAT).getString(); isAudioFile = dcFormat.startsWith("audio"); } return isAudioFile; } function getPublishServerURL(assetNode) { var s7Path = assetNode.getProperty(SCENE7_DOMAIN).getString() + "is/content/" + assetNode.getProperty(SCENE7_FODLER).getString() + assetNode.getName(); return s7Path; } });
0
0.634342
1
0.634342
game-dev
MEDIA
0.496512
game-dev,audio-video-media
0.661359
1
0.661359
andreasdr/tdme2
17,577
src/tdme/engine/tools/ThumbnailTool.cpp
#include <array> #include <memory> #include <string> #include <tdme/tdme.h> #include <tdme/engine/tools/ThumbnailTool.h> #include <tdme/application/Application.h> #include <tdme/engine/model/Face.h> #include <tdme/engine/model/FacesEntity.h> #include <tdme/engine/model/Material.h> #include <tdme/engine/model/Model.h> #include <tdme/engine/model/Node.h> #include <tdme/engine/model/RotationOrder.h> #include <tdme/engine/model/ShaderModel.h> #include <tdme/engine/model/SpecularMaterialProperties.h> #include <tdme/engine/model/UpVector.h> #include <tdme/engine/primitives/BoundingBox.h> #include <tdme/engine/primitives/OrientedBoundingBox.h> #include <tdme/engine/prototype/Prototype.h> #include <tdme/engine/prototype/Prototype_Type.h> #include <tdme/engine/prototype/PrototypeBoundingVolume.h> #include <tdme/engine/prototype/PrototypeImposterLOD.h> #include <tdme/engine/prototype/PrototypeLODLevel.h> #include <tdme/engine/tools/CameraRotationInputHandler.h> #include <tdme/engine/Camera.h> #include <tdme/engine/Color4.h> #include <tdme/engine/Engine.h> #include <tdme/engine/Entity.h> #include <tdme/engine/EntityHierarchy.h> #include <tdme/engine/ImposterObject.h> #include <tdme/engine/Light.h> #include <tdme/engine/Object.h> #include <tdme/engine/SceneConnector.h> #include <tdme/engine/SimplePartition.h> #include <tdme/engine/Texture.h> #include <tdme/engine/Transform.h> #include <tdme/math/Math.h> #include <tdme/math/Quaternion.h> #include <tdme/math/Vector2.h> #include <tdme/math/Vector3.h> #include <tdme/math/Vector4.h> #include <tdme/os/filesystem/FileSystem.h> #include <tdme/os/filesystem/FileSystemInterface.h> #include <tdme/utilities/ModelTools.h> using std::array; using std::make_unique; using std::string; using std::to_string; using std::unique_ptr; using tdme::engine::tools::ThumbnailTool; using tdme::application::Application; using tdme::engine::model::Face; using tdme::engine::model::FacesEntity; using tdme::engine::model::Material; using tdme::engine::model::Model; using tdme::engine::model::Node; using tdme::engine::model::RotationOrder; using tdme::engine::model::ShaderModel; using tdme::engine::model::SpecularMaterialProperties; using tdme::engine::model::UpVector; using tdme::engine::primitives::BoundingBox; using tdme::engine::primitives::OrientedBoundingBox; using tdme::engine::prototype::Prototype; using tdme::engine::prototype::Prototype_Type; using tdme::engine::prototype::PrototypeBoundingVolume; using tdme::engine::prototype::PrototypeImposterLOD; using tdme::engine::prototype::PrototypeLODLevel; using tdme::engine::tools::CameraRotationInputHandler; using tdme::engine::Camera; using tdme::engine::Color4; using tdme::engine::Engine; using tdme::engine::Entity; using tdme::engine::EntityHierarchy; using tdme::engine::ImposterObject; using tdme::engine::Light; using tdme::engine::Object; using tdme::engine::SceneConnector; using tdme::engine::SimplePartition; using tdme::engine::Texture; using tdme::engine::Transform; using tdme::math::Math; using tdme::math::Quaternion; using tdme::math::Vector2; using tdme::math::Vector3; using tdme::math::Vector4; using tdme::os::filesystem::FileSystem; using tdme::os::filesystem::FileSystemInterface; using tdme::utilities::ModelTools; Engine* ThumbnailTool::osEngine = nullptr; ThumbnailTool::ToolsShutdown ThumbnailTool::toolsShutdown; void ThumbnailTool::oseInit() { if (osEngine != nullptr) return; osEngine = Engine::createOffScreenInstance(128, 128, false, true, false); osEngine->setPartition(new SimplePartition()); setDefaultLight(osEngine->getLightAt(0)); } void ThumbnailTool::oseDispose() { if (osEngine == nullptr) return; osEngine->dispose(); delete osEngine; } void ThumbnailTool::oseThumbnail(Prototype* prototype, vector<uint8_t>& pngData) { oseInit(); Vector3 objectScale; Transform oseLookFromRotations; oseLookFromRotations.addRotation(Vector3(0.0f, 1.0f, 0.0f), -45.0f); oseLookFromRotations.addRotation(Vector3(1.0f, 0.0f, 0.0f), -45.0f); oseLookFromRotations.addRotation(Vector3(0.0f, 0.0f, 1.0f), 0.0f); oseLookFromRotations.update(); ThumbnailTool::setupPrototype(prototype, osEngine, oseLookFromRotations, 1, objectScale, nullptr, 1.0f); osEngine->setSceneColor(Color4(0.5f, 0.5f, 0.5f, 1.0f)); osEngine->display(); osEngine->makeScreenshot(pngData); /* osEngine->setSceneColor(Color4(0.8f, 0.0f, 0.0f, 1.0f)); osEngine->display(); osEngine->makeScreenshot(pngData); */ osEngine->reset(); } void ThumbnailTool::setDefaultLight(Light* light) { light->setAmbient(Color4(1.0f, 1.0f, 1.0f, 1.0f)); light->setDiffuse(Color4(0.5f, 0.5f, 0.5f, 1.0f)); light->setSpecular(Color4(1.0f, 1.0f, 1.0f, 1.0f)); light->setPosition(Vector4(0.0f, 20000.0f, 0.0f, 0.0f)); light->setSpotDirection(Vector3(0.0f, 0.0f, 0.0f).sub(Vector3(light->getPosition().getX(), light->getPosition().getY(), light->getPosition().getZ()))); light->setConstantAttenuation(0.5f); light->setLinearAttenuation(0.0f); light->setQuadraticAttenuation(0.0f); light->setSpotExponent(0.0f); light->setSpotCutOff(180.0f); light->setEnabled(true); } float ThumbnailTool::computeMaxAxisDimension(BoundingBox* boundingBox) { auto maxAxisDimension = 0.0f; Vector3 dimension = boundingBox->getMax().clone().sub(boundingBox->getMin()); if (dimension.getX() > maxAxisDimension) maxAxisDimension = dimension.getX(); if (dimension.getY() > maxAxisDimension) maxAxisDimension = dimension.getY(); if (dimension.getZ() > maxAxisDimension) maxAxisDimension = dimension.getZ(); return maxAxisDimension; } Model* ThumbnailTool::createGroundModel(float width, float depth, float y) { auto modelId = "tdme.ground" + to_string(static_cast<int>(width * 100)) + "x" + to_string(static_cast<int>(depth * 100)) + "@" + to_string(static_cast<int>(y * 100)); auto ground = make_unique<Model>(modelId, modelId, UpVector::Y_UP, RotationOrder::ZYX, nullptr); // auto groundMaterial = make_unique<Material>("ground"); groundMaterial->setSpecularMaterialProperties(make_unique<SpecularMaterialProperties>().release()); groundMaterial->getSpecularMaterialProperties()->setSpecularColor(Color4(0.0f, 0.0f, 0.0f, 1.0f)); groundMaterial->getSpecularMaterialProperties()->setDiffuseTexture("resources/engine/textures", "groundplate.png"); // auto groundNode = make_unique<Node>(ground.get(), nullptr, "ground", "ground"); vector<Vector3> groundVertices; groundVertices.emplace_back(-width/2, y, -depth/2); groundVertices.emplace_back(-width/2, y, +depth/2); groundVertices.emplace_back(+width/2, y, +depth/2); groundVertices.emplace_back(+width/2, y, -depth/2); vector<Vector3> groundNormals; groundNormals.emplace_back(0.0f, 1.0f, 0.0f); vector<Vector2> groundTextureCoordinates; groundTextureCoordinates.emplace_back(0.0f, 0.0f); groundTextureCoordinates.emplace_back(0.0f, depth); groundTextureCoordinates.emplace_back(width, depth); groundTextureCoordinates.emplace_back(width, 0.0f); vector<Face> groundFacesGround; groundFacesGround.emplace_back(groundNode.get(), 0, 1, 2, 0, 0, 0, 0, 1, 2); groundFacesGround.emplace_back(groundNode.get(), 2, 3, 0, 0, 0, 0, 2, 3, 0); FacesEntity nodeFacesEntityGround(groundNode.get(), "ground.facesentity"); nodeFacesEntityGround.setMaterial(groundMaterial.get()); vector<FacesEntity> nodeFacesEntities; nodeFacesEntityGround.setFaces(groundFacesGround); nodeFacesEntities.push_back(nodeFacesEntityGround); groundNode->setVertices(groundVertices); groundNode->setNormals(groundNormals); groundNode->setTextureCoordinates(groundTextureCoordinates); groundNode->setFacesEntities(nodeFacesEntities); ground->getNodes()["ground"] = groundNode.get(); ground->getSubNodes()["ground"] = groundNode.get(); groundNode.release(); // ground->getMaterials()["ground"] = groundMaterial.get(); groundMaterial.release(); // ModelTools::prepareForIndexedRendering(ground.get()); // return ground.release(); } Model* ThumbnailTool::createGridModel() { // auto groundPlate = make_unique<Model>("tdme.grid", "tdme.grid", UpVector::Y_UP, RotationOrder::XYZ, make_unique<BoundingBox>(Vector3(0.0f, -0.01f, 0.0f), Vector3(10000.0f, +0.01f, 10000.0f)).release()); // auto groundPlateMaterial = make_unique<Material>("ground"); groundPlateMaterial->setSpecularMaterialProperties(make_unique<SpecularMaterialProperties>().release()); groundPlateMaterial->getSpecularMaterialProperties()->setDiffuseColor( Color4( groundPlateMaterial->getSpecularMaterialProperties()->getDiffuseColor().getRed(), groundPlateMaterial->getSpecularMaterialProperties()->getDiffuseColor().getGreen(), groundPlateMaterial->getSpecularMaterialProperties()->getDiffuseColor().getBlue(), 0.75f ) ); groundPlateMaterial->getSpecularMaterialProperties()->setDiffuseTexture("resources/engine/textures", "groundplate.png"); groundPlateMaterial->getSpecularMaterialProperties()->setSpecularColor(Color4(0.0f, 0.0f, 0.0f, 1.0f)); // auto groundNode = make_unique<Node>(groundPlate.get(), nullptr, "grid", "grid"); vector<Vector3> groundVertices; groundVertices.emplace_back(0.0f, 0.0f, 0.0f); groundVertices.emplace_back(0.0f, 0.0f, 10000.0f); groundVertices.emplace_back(10000.0f, 0.0f, 10000.0f); groundVertices.emplace_back(10000.0f, 0.0f, 0.0f); vector<Vector3> groundNormals; groundNormals.emplace_back(0.0f, 1.0f, 0.0f); vector<Vector2> groundTextureCoordinates; groundTextureCoordinates.emplace_back(0.0f, 0.0f); groundTextureCoordinates.emplace_back(0.0f, 10000.0f); groundTextureCoordinates.emplace_back(10000.0f, 10000.0f); groundTextureCoordinates.emplace_back(10000.0f, 0.0f); vector<Face> groundFacesGround; groundFacesGround.emplace_back(groundNode.get(), 0, 1, 2, 0, 0, 0, 0, 1, 2); groundFacesGround.emplace_back(groundNode.get(), 2, 3, 0, 0, 0, 0, 2, 3, 0); FacesEntity nodeFacesEntityGround(groundNode.get(), "tdme.sceneeditor.grid.facesentity"); nodeFacesEntityGround.setMaterial(groundPlateMaterial.get()); nodeFacesEntityGround.setFaces(groundFacesGround); vector<FacesEntity> nodeFacesEntities; nodeFacesEntities.push_back(nodeFacesEntityGround); groundNode->setVertices(groundVertices); groundNode->setNormals(groundNormals); groundNode->setTextureCoordinates(groundTextureCoordinates); groundNode->setFacesEntities(nodeFacesEntities); groundPlate->getNodes()[groundNode->getId()] = groundNode.get(); groundPlate->getSubNodes()[groundNode->getId()] = groundNode.get(); groundNode.release(); // groundPlate->getMaterials()["grid"] = groundPlateMaterial.get(); groundPlateMaterial.release(); // ModelTools::prepareForIndexedRendering(groundPlate.get()); // return groundPlate.release(); } void ThumbnailTool::setupPrototype(Prototype* prototype, Engine* engine, const Transform& lookFromRotations, int lodLevel, Vector3& objectScale, CameraRotationInputHandler* cameraRotationInputHandler, float scale, bool resetup) { if (prototype == nullptr) return; // create engine entity auto entityBoundingBoxFallback = make_unique<BoundingBox>(Vector3(-2.5f, 0.0f, -2.5f), Vector3(2.5f, 2.0f, 2.5f)); BoundingBox* entityBoundingBox = nullptr; Entity* modelEntity = nullptr; objectScale.set(1.0f, 1.0f, 1.0f); Color4 colorMul(1.0f, 1.0f, 1.0f, 1.0f); Color4 colorAdd(0.0f, 0.0f, 0.0f, 0.0f); // bounding volumes auto entityBoundingVolumesHierarchy = new EntityHierarchy("tdme.prototype.bvs"); { auto i = 0; for (auto prototypeBoundingVolume: prototype->getBoundingVolumes()) { if (prototypeBoundingVolume->getModel() != nullptr) { auto bvObject = new Object("tdme.prototype.bv." + to_string(i), prototypeBoundingVolume->getModel()); bvObject->setEnabled(false); entityBoundingVolumesHierarchy->addEntity(bvObject); } i++; } } entityBoundingVolumesHierarchy->update(); engine->addEntity(entityBoundingVolumesHierarchy); // if (prototype->getType() == Prototype_Type::TRIGGER || prototype->getType() == Prototype_Type::ENVIRONMENTMAPPING || prototype->getType() == Prototype_Type::DECAL) { entityBoundingBox = entityBoundingVolumesHierarchy->getBoundingBox(); } else if (prototype->getType() == Prototype_Type::PARTICLESYSTEM) { modelEntity = SceneConnector::createEntity(prototype, "model", Transform()); if (modelEntity != nullptr) engine->addEntity(modelEntity); } else if (prototype->getModel() != nullptr) { // model Model* model = nullptr; switch (lodLevel) { case 1: model = prototype->getModel(); break; case 2: { auto lodLevelEntity = prototype->getLODLevel2(); if (lodLevelEntity != nullptr) { model = lodLevelEntity->getModel(); colorMul.set(lodLevelEntity->getColorMul()); colorAdd.set(lodLevelEntity->getColorAdd()); } break; } case 3: { auto lodLevelEntity = prototype->getLODLevel3(); if (lodLevelEntity != nullptr) { model = lodLevelEntity->getModel(); colorMul.set(lodLevelEntity->getColorMul()); colorAdd.set(lodLevelEntity->getColorAdd()); } break; } case 4: { auto imposterLOD = prototype->getImposterLOD(); if (imposterLOD != nullptr) { modelEntity = new ImposterObject( "model", imposterLOD->getModels() ); // TODO: remove this duplicated code, see :368 modelEntity->setContributesShadows(true); modelEntity->setReceivesShadows(true); modelEntity->setEffectColorMul(colorMul); modelEntity->setEffectColorAdd(colorAdd); auto object = dynamic_cast<ImposterObject*>(modelEntity); object->setShader(prototype->getShader()); for (const auto& parameterName: Engine::getShaderParameterNames(prototype->getShader())) { auto parameterValue = prototype->getShaderParameters().getShaderParameter(parameterName); object->setShaderParameter(parameterName, parameterValue); } engine->addEntity(modelEntity); } } } entityBoundingBox = prototype->getModel()->getBoundingBox(); if (model != nullptr) { modelEntity = new Object("model", model); modelEntity->setContributesShadows(true); modelEntity->setReceivesShadows(true); modelEntity->setEffectColorMul(colorMul); modelEntity->setEffectColorAdd(colorAdd); auto object = dynamic_cast<Object*>(modelEntity); object->setShader(prototype->getShader()); for (const auto& parameterName: Engine::getShaderParameterNames(prototype->getShader())) { auto parameterValue = prototype->getShaderParameters().getShaderParameter(parameterName); object->setShaderParameter(parameterName, parameterValue); } engine->addEntity(modelEntity); } } // auto entityBoundingBoxToUse = entityBoundingBox != nullptr?entityBoundingBox:entityBoundingBoxFallback.get(); // do a feasible scale float maxAxisDimension = ThumbnailTool::computeMaxAxisDimension(entityBoundingBoxToUse); if (maxAxisDimension < Math::EPSILON) maxAxisDimension = 1.0f; if (modelEntity != nullptr) { modelEntity->setPickable(true); modelEntity->setScale(objectScale); modelEntity->update(); } // generate ground auto ground = createGroundModel( 50.0f, 50.0f, 0.0f ); auto groundObject = new Object("ground", ground); groundObject->setEnabled(false); groundObject->setScale(objectScale); groundObject->setShader("solid"); groundObject->update(); engine->addEntity(groundObject); // dynamic_cast<EntityHierarchy*>(engine->getEntity("tdme.prototype.bvs"))->setScale(objectScale); dynamic_cast<EntityHierarchy*>(engine->getEntity("tdme.prototype.bvs"))->update(); // if re setting up we do leave camera and lighting as it is if (resetup == false) { // lights for (auto i = 1; i < engine->getLightCount(); i++) engine->getLightAt(i)->setEnabled(false); auto light0 = engine->getLightAt(0); light0->setAmbient(Color4(0.7f, 0.7f, 0.7f, 1.0f)); light0->setDiffuse(Color4(0.3f, 0.3f, 0.3f, 1.0f)); light0->setSpecular(Color4(1.0f, 1.0f, 1.0f, 1.0f)); light0->setPosition( Vector4( 0.0f, 20.0f * maxAxisDimension, 20.0f * maxAxisDimension, 1.0f ) ); light0->setSpotDirection(Vector3(0.0f, 0.0f, 0.0f).sub(Vector3(light0->getPosition().getX(), light0->getPosition().getY(), light0->getPosition().getZ())).normalize()); light0->setConstantAttenuation(0.5f); light0->setLinearAttenuation(0.0f); light0->setQuadraticAttenuation(0.0f); light0->setSpotExponent(0.0f); light0->setSpotCutOff(180.0f); light0->setEnabled(true); // cam auto cam = engine->getCamera(); auto lookAt = cam->getLookAt(); lookAt.set(entityBoundingBoxToUse->getCenter().clone().scale(objectScale)); Vector3 forwardVector(0.0f, 0.0f, 1.0f); // TODO: a.drewke Transform _lookFromRotations; _lookFromRotations.setTransform(lookFromRotations); if (cameraRotationInputHandler != nullptr) { cameraRotationInputHandler->setDefaultScale(maxAxisDimension * scale); cameraRotationInputHandler->setScale(maxAxisDimension * scale); } auto forwardVectorTransformed = _lookFromRotations.getTransformMatrix().multiply(forwardVector).scale(cameraRotationInputHandler != nullptr?cameraRotationInputHandler->getScale():maxAxisDimension * scale); auto upVector = _lookFromRotations.getRotation(2).getQuaternion().multiply(Vector3(0.0f, 1.0f, 0.0f)).normalize(); auto lookFrom = lookAt.clone().add(forwardVectorTransformed); cam->setLookFrom(lookFrom); cam->setLookAt(lookAt); cam->setUpVector(upVector); } else { if (cameraRotationInputHandler != nullptr) { cameraRotationInputHandler->setDefaultScale(maxAxisDimension * scale); } } } ThumbnailTool::ToolsShutdown::~ToolsShutdown() { if (Application::hasApplication() == true) ThumbnailTool::oseDispose(); };
0
0.9106
1
0.9106
game-dev
MEDIA
0.756512
game-dev,graphics-rendering
0.896368
1
0.896368
lordofduct/spacepuppy-unity-framework-3.0
3,818
SPUtils/Render/Events/i_TweenMaterial.cs
#pragma warning disable 0649 // variable declared but not used. using UnityEngine; using com.spacepuppy.Events; using com.spacepuppy.Tween; namespace com.spacepuppy.Render.Events { public class i_TweenMaterial : AutoTriggerable { #region Fields [SerializeField()] private VariantReference _autoKillId; [SerializeField()] private bool _killOnDisable; [SerializeField()] private SPTimePeriod _duration; [SerializeField()] private EaseStyle _ease; [SerializeField()] [DisableOnPlay()] [EnumPopupExcluding((int)TweenHash.AnimMode.AnimCurve, (int)TweenHash.AnimMode.Curve, (int)TweenHash.AnimMode.By, (int)TweenHash.AnimMode.RedirectTo)] private TweenHash.AnimMode _mode; [SerializeField()] private MaterialTransition _transition; [SerializeField()] private SPEvent _onComplete; [SerializeField()] private SPEvent _onTick; #endregion #region CONSTRUCTOR protected override void Awake() { base.Awake(); switch (_mode) { case TweenHash.AnimMode.To: _transition.Values.Insert(0, new VariantReference()); break; case TweenHash.AnimMode.From: _transition.Values.Add(new VariantReference()); break; } } protected override void OnDisable() { base.OnDisable(); if (_killOnDisable) { SPTween.Find((t) => { if (t is ObjectTweener && (t as ObjectTweener).Target == _transition) { t.Kill(); return true; } return false; }); } } #endregion #region Properties public object AutoKillId { get { var id = _autoKillId.Value; if (id == null) id = this; return id; } set { if (Object.Equals(value, this)) _autoKillId.Value = null; else _autoKillId.Value = value; } } #endregion #region ITriggerable Interface public override bool CanTrigger { get { return base.CanTrigger && _transition.Material != null && _transition.Values.Count != 0; } } public override bool Trigger(object sender, object arg) { if (!this.CanTrigger) return false; switch (_mode) { case TweenHash.AnimMode.To: _transition.Values[0].Value = _transition.GetValue(); break; case TweenHash.AnimMode.From: _transition.Values[_transition.Values.Count - 1].Value = _transition.GetValue(); break; } var twn = SPTween.Tween(_transition) .FromTo("Position", EaseMethods.GetEase(_ease), _duration.Seconds, 0f, 1f) .SetId(this.AutoKillId) .Use(_duration.TimeSupplier); if (_onComplete?.HasReceivers ?? false) twn.OnFinish((t) => _onComplete.ActivateTrigger(this, null)); if (_onTick?.HasReceivers ?? false) twn.OnStep((t) => _onTick.ActivateTrigger(this, null)); twn.Play(true); return true; } #endregion } }
0
0.948728
1
0.948728
game-dev
MEDIA
0.987826
game-dev
0.9729
1
0.9729
Unity-Technologies/360-Video-Heatmaps
3,908
Assets/AssetStorePackage/Plugins/Heatmaps/Data Collection/HeatmapSender.cs
/// <summary> /// Send Heatmap event based on VideoPlayer. /// </summary> using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; using UnityAnalytics360VideoHeatmap; namespace UnityAnalytics360VideoHeatmap { public class HeatmapSender : MonoBehaviour { public VideoPlayer videoPlayer; private int k_currentSendEventRatio; private bool k_eventSender; private int k_eventLimit = 5000; private float k_eventInterval = 1.0f; private WaitForSeconds k_waitForSecond; private Dictionary<string, object> k_clipDict; void Start() { if (videoPlayer == null) { videoPlayer = FindObjectOfType<VideoPlayer>(); } EnsureRatio(); k_eventInterval = DetermineEventInterval(k_eventLimit); k_waitForSecond = new WaitForSeconds(k_eventInterval); #if UNITY_EDITOR StartCoroutine(SendHeatmapEvent()); #else if (k_eventSender) StartCoroutine(SendHeatmapEvent()); #endif } /// <summary> /// Make sure the ratio is most updated. /// </summary> private void EnsureRatio() { k_eventSender = PlayerPrefs.GetInt("_360VideoHeatMap_EventSender", 0) == 0 ? true : false; k_currentSendEventRatio = PlayerPrefs.GetInt("_360VideoHeatMap_EventRatio", 10); int m_newSendEventRatio = RemoteSettings.GetInt("heatmaps_sample_rate", 10); // If the ratio has changed or the role has not been assigned before, reassign the user. if (!PlayerPrefs.HasKey("_360VideoHeatMap_EventSender") || k_currentSendEventRatio != m_newSendEventRatio) { k_currentSendEventRatio = m_newSendEventRatio; EnsureUserRole(); PlayerPrefs.SetInt("_360VideoHeatMap_EventSender", k_eventSender == true ? 0 : 1); PlayerPrefs.SetInt("_360VideoHeatMap_EventRatio", k_currentSendEventRatio); } } /// <summary> /// Check if the user is allowed to send event based on the RemoteSetting key. /// </summary> private void EnsureUserRole() { if (k_currentSendEventRatio >= 100) { k_eventSender = true; return; } if (k_currentSendEventRatio <= 0) { k_eventSender = false; return; } int m_random = Random.Range(0, 100); if (m_random <= k_currentSendEventRatio) { k_eventSender = true; return; } k_eventSender = false; } /// <summary> /// Send the event only when VideoPlayer, clip exist and the video is playing. /// </summary> IEnumerator SendHeatmapEvent() { if (k_clipDict == null) k_clipDict = new Dictionary<string, object>(); while (true) { if (videoPlayer != null && videoPlayer.clip != null && videoPlayer.isPlaying) { float m_standardTime = videoPlayer.frame / (float)videoPlayer.frameCount; k_clipDict["clipName"] = videoPlayer.clip.name; HeatmapEvent.Send("PlayerLook", this.transform, m_standardTime, k_clipDict); } yield return k_waitForSecond; } } /// <summary> /// Determine what's the time interval for event sending to not exceed the event limit. /// </summary> float DetermineEventInterval(int eventLimit) { float m_minimumInterval = 3600 / (float)eventLimit; return Mathf.Ceil(m_minimumInterval); } } }
0
0.961383
1
0.961383
game-dev
MEDIA
0.460005
game-dev,audio-video-media
0.990563
1
0.990563
dotnet/dotnet-api-docs
1,565
snippets/csharp/System.Runtime.InteropServices/Marshal/Overview/Marshal.cs
//Types:System.Runtime.InteropServices.Marshal //<snippet1> using System; using System.Text; using System.Runtime.InteropServices; public struct Point { public Int32 x, y; } public sealed class App { static void Main() { //<snippet2> // Demonstrate the use of public static fields of the Marshal class. Console.WriteLine("SystemDefaultCharSize={0}, SystemMaxDBCSCharSize={1}", Marshal.SystemDefaultCharSize, Marshal.SystemMaxDBCSCharSize); //</snippet2> //<snippet4> // Demonstrate how to call GlobalAlloc and // GlobalFree using the Marshal class. IntPtr hglobal = Marshal.AllocHGlobal(100); Marshal.FreeHGlobal(hglobal); //</snippet4> //<snippet5> // Demonstrate how to use the Marshal class to get the Win32 error // code when a Win32 method fails. Boolean f = CloseHandle(new IntPtr(-1)); if (!f) { Console.WriteLine("CloseHandle call failed with an error code of: {0}", Marshal.GetLastWin32Error()); } } // This is a platform invoke prototype. SetLastError is true, which allows // the GetLastWin32Error method of the Marshal class to work correctly. [DllImport("Kernel32", ExactSpelling = true, SetLastError = true)] static extern Boolean CloseHandle(IntPtr h); //</snippet5> } // This code produces the following output. // // SystemDefaultCharSize=2, SystemMaxDBCSCharSize=1 // CloseHandle call failed with an error code of: 6 //</snippet1>
0
0.715558
1
0.715558
game-dev
MEDIA
0.582692
game-dev
0.525186
1
0.525186
markol/machines
2,619
src/libdev/machphys/door.cpp
/* * D O O R . C P P * (c) Charybdis Limited, 1997. All Rights Reserved */ // Definitions of non-inline non-template methods and global functions #include "phys/rampacce.hpp" #include "ctl/vector.hpp" #include "ctl/countptr.hpp" #include "mathex/transf3d.hpp" #include "phys/linetrav.hpp" #include "world4d/entity.hpp" #include "world4d/entyplan.hpp" #include "sim/manager.hpp" #include "machphys/door.hpp" ////////////////////////////////////////////////////////////////////////////////////////// MachPhysDoor::MachPhysDoor( W4dEntity* pDoor, const MexVec3& displacement, MATHEX_SCALAR speed, MATHEX_SCALAR acceleration ) : pDoor_( pDoor ), speed_( speed ), acceleration_( acceleration ), closedLocation_( pDoor->localTransform().position() ) { PRE( pDoor != NULL ); PRE( speed > 0 ); PRE( acceleration > 0 ); //Compute open location openLocation_ = closedLocation_; openLocation_ += displacement; TEST_INVARIANT; } ////////////////////////////////////////////////////////////////////////////////////////// MachPhysDoor::~MachPhysDoor() { TEST_INVARIANT; } ////////////////////////////////////////////////////////////////////////////////////////// void MachPhysDoor::CLASS_INVARIANT { INVARIANT( this != NULL ); } ////////////////////////////////////////////////////////////////////////////////////////// PhysRelativeTime MachPhysDoor::changeState( bool doOpen ) { //Create a motion plan for the move. First create a collection of the 2 transforms. PhysMotionPlan::Transforms* pTransforms = _NEW( PhysMotionPlan::Transforms ); pTransforms->reserve( 2 ); MexTransform3d doorTransform( pDoor_->localTransform() ); //doorTransform.position( doOpen ? closedLocation_ : openLocation_ ); pTransforms->push_back( doorTransform ); doorTransform.position( doOpen ? openLocation_ : closedLocation_ ); pTransforms->push_back( doorTransform ); //Now create the plan PhysLinearTravelPlan* pPlan = _NEW( PhysLinearTravelPlan( PhysMotionPlan::TransformsPtr( pTransforms ), 0, speed_, acceleration_, acceleration_, 0, 1, 1, 1, true ) ); //Apply it to the entity pDoor_->entityPlanForEdit().absoluteMotion( PhysMotionPlanPtr( pPlan ), SimManager::instance().currentTime() ); return pPlan->duration(); } ////////////////////////////////////////////////////////////////////////////////////////// /* End DOOR.CPP *****************************************************/
0
0.780453
1
0.780453
game-dev
MEDIA
0.424903
game-dev
0.794339
1
0.794339
blupi-games/planetblupi
85,862
src/decor.cxx
/* * This file is part of the planetblupi source code * Copyright (C) 1997, Daniel Roux & EPSITEC SA * Copyright (C) 2017-2018, Mathieu Schroeter * https://epsitec.ch; https://www.blupi.org; https://github.com/blupi-games * * 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://gnu.org/licenses */ #include <stdio.h> #include <stdlib.h> #include <unordered_map> #include "action.h" #include "decmove.h" #include "decor.h" #include "def.h" #include "fifo.h" #include "gettext.h" #include "misc.h" #include "pixmap.h" #include "sound.h" #include "text.h" #define TEXTDELAY 10 // délai avant apparition tooltips Point GetCel (Sint32 x, Sint32 y) { Point cel; cel.x = x; cel.y = y; return cel; } Point GetCel (Point cel, Sint32 x, Sint32 y) { cel.x += x; cel.y += y; return cel; } // Indique si une coordonnée de cellule est valide. // On ne peut pas aller dans la dernière cellule tout au // bord (-2) pour permettre de gérer le brouillard proprement // jusque dans les bords ! bool IsValid (Point cel) { if (cel.x < 2 || cel.x >= MAXCELX - 2 || cel.y < 2 || cel.y >= MAXCELX - 2) return false; return true; } // Retourne un vecteur orienté dans une direction donnée. Point GetVector (Sint32 direct) { Point vector; vector.x = 0; vector.y = 0; switch (direct) { case DIRECT_E: vector.x = +1; break; case DIRECT_SE: vector.x = +1; vector.y = +1; break; case DIRECT_S: vector.y = +1; break; case DIRECT_SW: vector.x = -1; vector.y = +1; break; case DIRECT_W: vector.x = -1; break; case DIRECT_NW: vector.x = -1; vector.y = -1; break; case DIRECT_N: vector.y = -1; break; case DIRECT_NE: vector.x = +1; vector.y = -1; break; } return vector; } // Constructeur. CDecor::CDecor () { m_pSound = nullptr; m_pUndoDecor = nullptr; m_celCorner.x = 90; m_celCorner.y = 98; m_celHili.x = -1; m_celOutline1.x = -1; m_celOutline2.x = -1; m_bHiliRect = false; // pas de rectangle de sélection m_shiftHili = 0; m_shiftOffset.x = 0; m_shiftOffset.y = 0; m_nbBlupiHili = 0; m_rankBlupiHili = -1; m_rankHili = -1; m_bFog = false; m_bBuild = false; m_bInvincible = false; m_bSuper = false; m_bHideTooltips = false; m_bInfo = false; m_infoHeight = 100; m_phase = 0; m_totalTime = 0; m_region = 0; m_lastRegion = 999; m_skill = 0; m_SurfaceMap = nullptr; Init (CHFLOOR, 0); BlupiFlush (); MoveFlush (); InitDrapeau (); } // Destructeur. CDecor::~CDecor () { if (m_SurfaceMap) SDL_FreeSurface (m_SurfaceMap); UndoClose (); // libère le buffer du undo } // Initialisation générale. void CDecor::Create (CSound * pSound, CPixmap * pPixmap) { m_pSound = pSound; m_pPixmap = pPixmap; m_bOutline = false; } // Initialise le décor avec un sol plat partout. void CDecor::Init (Sint32 channel, Sint32 icon) { Sint32 x, y; for (x = 0; x < MAXCELX / 2; x++) { for (y = 0; y < MAXCELY / 2; y++) { m_decor[x][y].floorChannel = channel; m_decor[x][y].floorIcon = icon; m_decor[x][y].objectChannel = -1; m_decor[x][y].objectIcon = -1; m_decor[x][y].fog = FOGHIDE; // caché m_decor[x][y].rankMove = -1; m_decor[x][y].workBlupi = -1; m_decor[x][y].fire = 0; m_decorMem[x][y].flagged = false; } } for (x = 0; x < MAXCELX; x++) { for (y = 0; y < MAXCELY; y++) m_rankBlupi[x][y] = -1; } m_bOutline = false; m_bGroundRedraw = true; } // Initialise le décor après une modification. void CDecor::InitAfterBuild () { ClearFog (); // met tout sous le brouillard ClearFire (); MoveFixInit (); InitDrapeau (); BlupiDeselect (); } // Initialise les mises en évidence, avant de jouer. void CDecor::ResetHili () { m_bHiliRect = false; // plus de rectangle InitOutlineRect (); } // Charge les images nécessaires au décor. bool CDecor::LoadImages () { Point totalDim, iconDim; char filename[50]; if (m_region == m_lastRegion) return true; m_lastRegion = m_region; totalDim.x = DIMCELX * 2 * 16; totalDim.y = DIMCELY * 2 * 6; iconDim.x = DIMCELX * 2; iconDim.y = DIMCELY * 2; snprintf (filename, sizeof (filename), "floor%.3d.png", m_region); if (!m_pPixmap->Cache (CHFLOOR, filename, totalDim, iconDim)) return false; totalDim.x = DIMOBJX * 16; totalDim.y = DIMOBJY * 8; iconDim.x = DIMOBJX; iconDim.y = DIMOBJY; snprintf (filename, sizeof (filename), "obj%.3d.png", m_region); if (!m_pPixmap->Cache (CHOBJECT, filename, totalDim, iconDim)) return false; snprintf (filename, sizeof (filename), "obj-o%.3d.png", m_region); if (!m_pPixmap->Cache (CHOBJECTo, filename, totalDim, iconDim)) return false; MapInitColors (); // init les couleurs pour la carte m_bGroundRedraw = true; return true; } // Met partout du brouillard, sauf aux endroits des blupi. void CDecor::ClearFog () { Sint32 x, y, rank; for (x = 0; x < MAXCELX / 2; x++) { for (y = 0; y < MAXCELY / 2; y++) { m_decor[x][y].fog = FOGHIDE; // caché } } for (rank = 0; rank < MAXBLUPI; rank++) { if (m_blupi[rank].bExist) BlupiPushFog (rank); } m_bOutline = false; } // Permet de nouveau aux cellules brulées de bruler. void CDecor::ClearFire () { Sint32 x, y; for (x = 0; x < MAXCELX / 2; x++) { for (y = 0; y < MAXCELY / 2; y++) { if (m_decor[x][y].fire >= MoveMaxFire ()) // déjà brulé ? { m_decor[x][y].fire = 0; // pourra de nouveau bruler } if (m_decor[x][y].fire > 1) // en train de bruler ? { m_decor[x][y].fire = 1; // début du feu } } } } // Indique le mode jeu/construction. void CDecor::SetBuild (bool bBuild) { m_bBuild = bBuild; } // Indique s'il faut tenir compte du brouillard. void CDecor::EnableFog (bool bEnable) { m_bFog = bEnable; m_bOutline = false; } // Gestion du mode invincible. bool CDecor::GetInvincible () { return m_bInvincible; } void CDecor::SetInvincible (bool bInvincible) { m_bInvincible = bInvincible; } // Gestion du mode costaud (superblupi). bool CDecor::GetSuper () { return m_bSuper; } void CDecor::SetSuper (bool bSuper) { m_bSuper = bSuper; } // Bascule le mode outline. void CDecor::FlipOutline () { m_bOutline = !m_bOutline; m_timeFlipOutline = m_timeConst + 50; } // Initialise un sol dans une cellule. bool CDecor::PutFloor (Point cel, Sint32 channel, Sint32 icon) { if (cel.x < 0 || cel.x >= MAXCELX || cel.y < 0 || cel.y >= MAXCELY) return false; m_decor[cel.x / 2][cel.y / 2].floorChannel = channel; m_decor[cel.x / 2][cel.y / 2].floorIcon = icon; m_bGroundRedraw = true; //? SubDrapeau(cel); // on pourra de nouveau planter un drapeau return true; } // Initialise un objet dans une cellule. bool CDecor::PutObject (Point cel, Sint32 channel, Sint32 icon) { if (cel.x < 0 || cel.x >= MAXCELX || cel.y < 0 || cel.y >= MAXCELY) return false; if (icon == -1) channel = -1; m_decor[cel.x / 2][cel.y / 2].objectChannel = channel; m_decor[cel.x / 2][cel.y / 2].objectIcon = icon; /* When flagged, it's possible to build a mine for iron */ if (icon == 124) m_decorMem[cel.x / 2][cel.y / 2].flagged = true; SubDrapeau (cel); // on pourra de nouveau planter un drapeau return true; } // Retourne un sol dans une cellule. bool CDecor::GetFloor (Point cel, Sint32 & channel, Sint32 & icon) { if (cel.x < 0 || cel.x >= MAXCELX || cel.y < 0 || cel.y >= MAXCELY) return false; channel = m_decor[cel.x / 2][cel.y / 2].floorChannel; icon = m_decor[cel.x / 2][cel.y / 2].floorIcon; return true; } // Retourne une objet dans une cellule. bool CDecor::GetObject (Point cel, Sint32 & channel, Sint32 & icon) { if (cel.x < 0 || cel.x >= MAXCELX || cel.y < 0 || cel.y >= MAXCELY) return false; channel = m_decor[cel.x / 2][cel.y / 2].objectChannel; icon = m_decor[cel.x / 2][cel.y / 2].objectIcon; return true; } // Modifie le feu pour une cellule. bool CDecor::SetFire (Point cel, bool bFire) { if (cel.x < 0 || cel.x >= MAXCELX || cel.y < 0 || cel.y >= MAXCELY) return false; m_decor[cel.x / 2][cel.y / 2].fire = bFire ? 1 : 0; return true; } void CDecor::FixShifting (Sint32 & nbx, Sint32 & nby, Point & iCel, Point & iPos) { if (m_shiftOffset.x < 0) // décalage à droite ? nbx += 2; if (m_shiftOffset.y < 0) // décalage en bas ? nby += 3; if (m_shiftOffset.x > 0) // décalage à gauche ? { nbx += 2; iCel.x--; iCel.y++; iPos = ConvCelToPos (iCel); } if (m_shiftOffset.y > 0) // décalage en haut ? { nby += 2; iCel.x--; iCel.y--; iPos = ConvCelToPos (iCel); } } // Modifie l'offset pour le shift. void CDecor::SetShiftOffset (Point offset) { m_shiftOffset = offset; m_bGroundRedraw = true; } // Convertit la position d'une cellule en coordonnée graphique. Point CDecor::ConvCelToPos (Point cel) { Point pos; pos.x = ((cel.x - m_celCorner.x) - (cel.y - m_celCorner.y)) * (DIMCELX / 2); pos.y = ((cel.x - m_celCorner.x) + (cel.y - m_celCorner.y)) * (DIMCELY / 2); pos.x += POSDRAWX + m_shiftOffset.x; pos.y += POSDRAWY + m_shiftOffset.y; return pos; } // Convertit une coordonnée graphique en cellule. Point CDecor::ConvPosToCel (Point pos, bool bMap) { Point cel; if ( bMap && pos.x >= POSMAPX && pos.x < POSMAPX + DIMMAPX && pos.y >= POSMAPY && pos.y < POSMAPY + DIMMAPY) { pos.x -= POSMAPX; pos.y -= POSMAPY; return ConvMapToCel (pos); } pos.x -= POSDRAWX + DIMCELX / 2; pos.y -= POSDRAWY; cel.x = (pos.y * DIMCELX + pos.x * DIMCELY) / (DIMCELX * DIMCELY); // cel.y = (pos.y*DIMCELX - pos.x*DIMCELY) / (DIMCELX*DIMCELY); cel.y = (pos.y * DIMCELX - pos.x * DIMCELY); if (cel.y < 0) cel.y -= (DIMCELX * DIMCELY); cel.y /= (DIMCELX * DIMCELY); cel.x += m_celCorner.x; cel.y += m_celCorner.y; return cel; } // Convertit une coordonnée graphique en grande cellule (2x2). Point CDecor::ConvPosToCel2 (Point pos) { Point cel; pos.x -= POSDRAWX + DIMCELX / 2; pos.y -= POSDRAWY; if (m_celCorner.x % 2 != 0 && m_celCorner.y % 2 == 0) { pos.x += DIMCELX / 2; pos.y += DIMCELY / 2; } if (m_celCorner.x % 2 == 0 && m_celCorner.y % 2 != 0) { pos.x -= DIMCELX / 2; pos.y += DIMCELY / 2; } if (m_celCorner.x % 2 != 0 && m_celCorner.y % 2 != 0) pos.y += DIMCELY; cel.x = (pos.y * DIMCELX * 2 + pos.x * DIMCELY * 2) / (DIMCELX * 2 * DIMCELY * 2); // cel.y = (pos.y*DIMCELX*2 - pos.x*DIMCELY*2) / (DIMCELX*2*DIMCELY*2); cel.y = (pos.y * DIMCELX * 2 - pos.x * DIMCELY * 2); if (cel.y < 0) cel.y -= (DIMCELX * 2 * DIMCELY * 2); cel.y /= (DIMCELX * 2 * DIMCELY * 2); cel.x = (cel.x * 2 + m_celCorner.x) / 2 * 2; cel.y = (cel.y * 2 + m_celCorner.y) / 2 * 2; return cel; } // Attribution des blupi aux différentes cellules. // Lorsque un blupi a deux positions (courante et destination), // il faut toujours mettre blupi le plus au fond possible // (minimiser x et y). void CDecor::BuildPutBlupi () { Sint32 x, y, dx, dy, xMin, yMin, rank, clipLeft; Point pos; for (rank = 0; rank < MAXBLUPI; rank++) { if ( m_blupi[rank].bExist && m_blupi[rank].channel != -1 && m_blupi[rank].icon != -1) { xMin = m_blupi[rank].destCel.x; if (xMin > m_blupi[rank].cel.x) xMin = m_blupi[rank].cel.x; yMin = m_blupi[rank].destCel.y; if (yMin > m_blupi[rank].cel.y) yMin = m_blupi[rank].cel.y; // Si blupi entre dans une maison, il faut initialiser // le clipping à gauche. m_blupi[rank].clipLeft = 0; // pas de clipping if ( !m_bOutline && xMin > 0 && xMin % 2 == 1 && yMin % 2 == 1 && m_decor[xMin / 2][yMin / 2].objectChannel == CHOBJECT && (m_decor[xMin / 2][yMin / 2].objectIcon == 28 || // maison ? m_decor[xMin / 2][yMin / 2].objectIcon == 101 || // usine ? m_decor[xMin / 2][yMin / 2].objectIcon == 103 || // usine ? m_decor[xMin / 2][yMin / 2].objectIcon == 105 || // usine ? m_decor[xMin / 2][yMin / 2].objectIcon == 116 || // usine ? m_decor[xMin / 2][yMin / 2].objectIcon == 120 || // usine ? m_decor[xMin / 2][yMin / 2].objectIcon == 18 || // usine ? m_decor[xMin / 2][yMin / 2].objectIcon == 122 || // mine ? m_decor[xMin / 2][yMin / 2].objectIcon == 113) && // maison ? m_blupi[rank].posZ > -DIMBLUPIY) { pos = ConvCelToPos (GetCel (xMin, yMin)); clipLeft = pos.x + 34; if (clipLeft < POSDRAWX) clipLeft = POSDRAWX; m_blupi[rank].clipLeft = clipLeft; } x = m_blupi[rank].cel.x; y = m_blupi[rank].cel.y; dx = m_blupi[rank].destCel.x - x; dy = m_blupi[rank].destCel.y - y; if (dx != -dy) // déplacement non horizontal (ne/so) ? { if (dx < 0) x = m_blupi[rank].destCel.x; if (dy < 0) y = m_blupi[rank].destCel.y; } if (dx == -1 && dy == 1) // déplacement "so" ? { x = m_blupi[rank].destCel.x; y = m_blupi[rank].destCel.y; } if (x % 2 != 0) { if ( IsFreeCelObstacle (GetCel (x, y + 0)) && !IsFreeCelObstacle (GetCel (x, y + 1))) x--; } if (x % 2 == 0 && y % 2 != 0) { if (!IsFreeCelObstacle (GetCel (x + 1, y))) y--; } if (x % 2 != 0 && y % 2 != 0 && dx != 0 && dy == 0) { if (!IsFreeCelObstacle (GetCel (x + 1, y - 1))) x++; } if (m_rankBlupi[x][y] != -1) // déjà occupé ? { if (x == m_blupi[rank].cel.x) x--; else x = m_blupi[rank].cel.x; if (m_rankBlupi[x][y] != -1) // déjà occupé ? { if (y == m_blupi[rank].cel.y) y--; else y = m_blupi[rank].cel.y; if (m_rankBlupi[x][y] != -1) // déjà occupé ? { /* HACK: It's not right but at least less Blupi are * lost (invisible). The logic is not very clear, then * consider the following code as a workaround. */ if (x == m_blupi[rank].cel.x) x -= 2; else x = m_blupi[rank].cel.x; if (m_rankBlupi[x][y] != -1) continue; // que faire d'autre ? } } } m_rankBlupi[x][y] = rank; } } } // Dessine une cellule du décor contenant un sol animé. void CDecor::BuildMoveFloor (Sint32 x, Sint32 y, Point pos, Sint32 rank) { Sint32 icon, nb; Sint16 * pTable; if (m_move[rank].rankIcons == 0) { icon = m_move[rank].maskIcon + m_move[rank].cTotal; m_pPixmap->BuildIconMask ( m_move[rank].maskChannel, icon, m_move[rank].channel, m_move[rank].icon, 0); m_pPixmap->DrawIcon (-1, m_move[rank].channel, 0, pos); } else { pTable = GetListIcons (m_move[rank].rankIcons); nb = pTable[0]; icon = pTable[1 + m_move[rank].cTotal % nb]; if (m_move[rank].cel.x % 2 == 1) { pos.x += DIMCELX / 2; pos.y += DIMCELY / 2; } if (m_move[rank].cel.y % 2 == 1) { pos.x -= DIMCELX / 2; pos.y += DIMCELY / 2; } m_pPixmap->DrawIcon (-1, m_move[rank].channel, icon, pos); } } // Dessine une cellule du décor contenant un objet animé. void CDecor::BuildMoveObject (Sint32 x, Sint32 y, Point pos, Sint32 rank) { Sint32 hBuild, offset, startY, endY; Sint32 channel, icon, nb; Sint16 * pTable; if (m_move[rank].rankMoves != 0) { pTable = GetListMoves (m_move[rank].rankMoves); offset = m_move[rank].phase; if (offset < pTable[0]) { pos.x += pTable[1 + 2 * offset + 0]; pos.y += pTable[1 + 2 * offset + 1]; } else m_move[rank].rankMoves = 0; } // Dessine un chiffre par-dessus if (m_move[rank].icon >= MOVEICONNB && m_move[rank].icon <= MOVEICONNB + 100) { Point textPos; char string[20]; m_pPixmap->DrawIcon ( -1, m_decor[x / 2][y / 2].objectChannel, m_decor[x / 2][y / 2].objectIcon, pos); snprintf (string, sizeof (string), "%d", m_move[rank].icon - MOVEICONNB); textPos.x = pos.x + DIMCELX / 2 + 32; textPos.y = pos.y + (DIMOBJY - DIMCELY * 2) + 36; DrawTextCenter (m_pPixmap, textPos, string, FONTLITTLE); } else { hBuild = (m_move[rank].cTotal * m_move[rank].stepY) / 100; if (m_move[rank].stepY >= 0) { if (hBuild <= 0) hBuild = 0; if (hBuild > DIMOBJY) hBuild = DIMOBJY; } else { if (hBuild >= 0) hBuild = 0; if (hBuild < -DIMOBJY) hBuild = -DIMOBJY; } // Dessine l'objet actuellement dans le décor. if (m_decor[x / 2][y / 2].objectChannel >= 0) { if (hBuild >= 0) { startY = 0; endY = DIMOBJY - hBuild; } else { startY = -hBuild; endY = DIMOBJY; } channel = m_decor[x / 2][y / 2].objectChannel; if (m_bOutline && channel == CHOBJECT) channel = CHOBJECTo; m_pPixmap->DrawIconPart ( -1, channel, m_decor[x / 2][y / 2].objectIcon, pos, startY, endY); } // Dessine le nouvel objet par-dessus. if (m_move[rank].icon >= 0) { if (hBuild >= 0) { startY = DIMOBJY - hBuild; endY = DIMOBJY; } else { startY = 0; endY = -hBuild; } channel = m_move[rank].channel; if (m_bOutline && channel == CHOBJECT) channel = CHOBJECTo; m_pPixmap->DrawIconPart ( -1, channel, m_move[rank].icon, pos, startY, endY); } } // Dessine le feu ou les rayons. if (m_move[rank].rankIcons != 0) { pTable = GetListIcons (m_move[rank].rankIcons); nb = pTable[0]; icon = pTable[1 + m_move[rank].cTotal % nb]; m_pPixmap->DrawIcon (-1, m_move[rank].channel, icon, pos); } } // Déplace l'objet transporté par blupi. void BuildMoveTransport (Sint32 icon, Point & pos) { pos.x -= DIMCELX / 2; pos.y -= 96; // clang-format off static Sint32 offset_bateau[16 * 2] = { -4, -3, // e -2, -3, -1, -3, // se +1, -3, +2, -3, // s +5, -2, +6, -2, // so +5, -1, +1, 0, // o -1, 0, -2, 0, // no -2, 0, -3, 0, // n -4, -1, -5, -1, // ne -4, -2, }; static Sint32 offset_jeep[16 * 2] = { -2, -6, // e -1, -6, -1, -6, // se -1, -6, +3, -6, // s +1, -6, +4, -6, // so +4, -5, +4, -5, // o +2, -5, +1, -4, // no +1, -4, -3, -3, // n -4, -4, -3, -4, // ne -4, -4, }; // clang-format on if (icon >= 0 && icon <= 47) pos.y -= (icon % 3) * 2; if (icon == 114) // mange ? { pos.x += 1; pos.y += 1; } if (icon == 106) // se penche (mèche dynamite) ? { pos.x += 8; pos.y += 10; } if (icon == 194) // se penche (mèche dynamite) ? { pos.x += 9; pos.y += 9; } if (icon == 347) // se penche (armure) ? { pos.x += 2; pos.y += 2; } if (icon >= 234 && icon <= 249) // blupi en bateau ? { pos.x += offset_bateau[(icon - 234) * 2 + 0]; pos.y += offset_bateau[(icon - 234) * 2 + 1]; } if (icon >= 250 && icon <= 265) // blupi en jeep ? { pos.x += offset_jeep[(icon - 250) * 2 + 0]; pos.y += offset_jeep[(icon - 250) * 2 + 1]; } if (icon == 270) pos.y += 3; // blupi électrocuté if (icon == 271) pos.y -= 2; if (icon == 272) pos.y -= 7; } // Construit tous les sols fixes dans CHGROUND. void CDecor::BuildGround (Rect clip) { //? OutputDebug("BuildGround\n"); Sint32 x, y, i, j, nbx, nby, width, height, channel, icon; Point iCel, mCel, iPos, mPos, cPos, pos; width = clip.right - clip.left; height = clip.bottom - clip.top; pos.x = clip.left; pos.y = clip.top; iCel = ConvPosToCel (pos); mCel = iCel; if (mCel.x % 2 == 0 && mCel.y % 2 == 0) { iCel.x -= 2; width += DIMCELX; height += DIMCELY; } if (mCel.x % 2 != 0 && mCel.y % 2 != 0) { iCel.x -= 3; iCel.y -= 1; width += DIMCELX; height += DIMCELY * 2; } if (mCel.x % 2 == 0 && mCel.y % 2 != 0) { iCel.x -= 2; iCel.y -= 1; width += DIMCELX / 2; height += (DIMCELY / 2) * 3; } if (mCel.x % 2 != 0 && mCel.y % 2 == 0) { iCel.x -= 3; width += (DIMCELX / 2) * 3; height += (DIMCELY / 2) * 3; } iPos = ConvCelToPos (iCel); nbx = (width / DIMCELX) + 2; nby = (height / (DIMCELY / 2)) + 0; if (GetInfoHeight () != 0) { nbx += 2; nby += 2; } this->FixShifting (nbx, nby, iCel, iPos); // Construit les sols. mCel = iCel; mPos = iPos; for (j = 0; j < nby; j++) { x = mCel.x; y = mCel.y; cPos = mPos; for (i = 0; i < nbx; i++) { if (x % 2 == 0 && y % 2 == 0) { pos.x = cPos.x - DIMCELX / 2; pos.y = cPos.y; if ( x >= 2 && x < MAXCELX - 2 && y >= 2 && y < MAXCELY - 2 && m_decor[x / 2][y / 2].floorChannel >= 0 && m_decor[x / 2][y / 2].floorIcon >= 0) { channel = m_decor[x / 2][y / 2].floorChannel; icon = m_decor[x / 2][y / 2].floorIcon; } else { channel = CHFLOOR; icon = 78; // losange noir } if (!m_bBuild && icon == 71) // terre à fer ? { icon = 33; // terre normale ! } // Dessine l'eau sous les rives et les ponts. if ( (icon >= 2 && icon <= 13) || // rive ? (icon >= 59 && icon <= 64)) // pont ? { m_pPixmap->DrawIcon (CHGROUND, CHFLOOR, 14, pos); // eau } m_pPixmap->DrawIcon (CHGROUND, channel, icon, pos); } x++; y--; cPos.x += DIMCELX; } if (j % 2 == 0) { mCel.y++; mPos.x -= DIMCELX / 2; mPos.y += DIMCELY / 2; } else { mCel.x++; mPos.x += DIMCELX / 2; mPos.y += DIMCELY / 2; } } m_bGroundRedraw = false; } // Construit le décor dans un pixmap. void CDecor::Build (Rect clip, Point posMouse) { Sint32 x, y, i, j, nbx, nby, width, height, rank, icon, channel, n; Point iCel, mCel, cel, iPos, mPos, cPos, pos, tPos; Rect oldClip, clipRect; static Sint32 table_eau[6] = {70, 68, 14, 69, 14, 68}; static Sint32 table_random_x[10] = {2, 5, 1, 9, 4, 0, 6, 3, 8, 7}; static Sint32 table_random_y[10] = {4, 8, 3, 5, 9, 1, 7, 2, 0, 6}; oldClip = m_pPixmap->GetClipping (); m_pPixmap->SetClipping (clip); if (m_bGroundRedraw) { BuildGround (clip); // refait les sols fixes } // Dessine tous les sols fixes. m_pPixmap->DrawImage (-1, CHGROUND, clip); width = clip.right - clip.left; height = clip.bottom - clip.top; pos.x = clip.left; pos.y = clip.top; iCel = ConvPosToCel (pos); mCel = iCel; if (mCel.x % 2 == 0 && mCel.y % 2 == 0) { iCel.x -= 2; width += DIMCELX; height += DIMCELY; } if (mCel.x % 2 != 0 && mCel.y % 2 != 0) { iCel.x -= 3; iCel.y -= 1; width += DIMCELX; height += DIMCELY * 2; } if (mCel.x % 2 == 0 && mCel.y % 2 != 0) { iCel.x -= 2; iCel.y -= 1; width += DIMCELX / 2; height += (DIMCELY / 2) * 3; } if (mCel.x % 2 != 0 && mCel.y % 2 == 0) { iCel.x -= 3; width += (DIMCELX / 2) * 3; height += (DIMCELY / 2) * 3; } iPos = ConvCelToPos (iCel); nbx = (width / DIMCELX) + 2; nby = (height / (DIMCELY / 2)) + 0; if (GetInfoHeight () != 0) { nbx += 2; nby += 2; } this->FixShifting (nbx, nby, iCel, iPos); // Construit les sols. mCel = iCel; mPos = iPos; for (j = 0; j < nby; j++) { x = mCel.x; y = mCel.y; cPos = mPos; for (i = 0; i < nbx; i++) { if (x >= 2 && x < MAXCELX - 2 && y >= 2 && y < MAXCELY - 2) { m_rankBlupi[x][y] = -1; // (1), voir BuildPutBlupi if (x % 2 == 0 && y % 2 == 0) { icon = m_decor[x / 2][y / 2].floorIcon; if (!m_bBuild && icon == 71) // terre à fer ? { icon = 33; // terre normale ! } // Dessine l'eau sous les rives et les ponts. if ( (icon >= 2 && icon <= 14) || // rive ? (icon >= 59 && icon <= 64)) // pont ? { // Dessine l'eau en mouvement. pos.x = cPos.x - DIMCELX / 2; pos.y = cPos.y; n = table_eau [(m_timeConst / 2 + // lent ! table_random_x[x % 10] + table_random_y[y % 10]) % 6]; m_pPixmap->DrawIcon (CHGROUND, CHFLOOR, n, pos); // eau if (icon != 14) m_pPixmap->DrawIcon (CHGROUND, CHFLOOR, icon, pos); } rank = m_decor[x / 2][y / 2].rankMove; if ( rank != -1 && // décor animé ? m_move[rank].bFloor) { pos.x = cPos.x - DIMCELX / 2; pos.y = cPos.y; BuildMoveFloor (x, y, pos, rank); } } } if ( m_celHili.x != -1 && x >= m_celHili.x - 1 && x <= m_celHili.x + 2 && y >= m_celHili.y - 1 && y <= m_celHili.y + 2) { icon = m_iconHili[x - (m_celHili.x - 1)][y - (m_celHili.y - 1)]; if (icon != -1) { // hilight cellule m_pPixmap->DrawIconDemi (-1, CHBLUPI, icon, cPos); } } if (m_bHiliRect) // rectangle de sélection existe ? { if ( (m_p1Hili.x == x && m_p1Hili.y == y) || (m_p2Hili.x == x && m_p2Hili.y == y)) m_pPixmap->DrawIconDemi (-1, CHBLUPI, ICON_HILI_SEL, cPos); } x++; y--; cPos.x += DIMCELX; } if (j % 2 == 0) { mCel.y++; mPos.x -= DIMCELX / 2; mPos.y += DIMCELY / 2; } else { mCel.x++; mPos.x += DIMCELX / 2; mPos.y += DIMCELY / 2; } } for (j = nby; j < nby + 3; j++) { x = mCel.x; y = mCel.y; for (i = 0; i < nbx; i++) { if (x >= 2 && x < MAXCELX - 2 && y >= 2 && y < MAXCELY - 2) { m_rankBlupi[x][y] = -1; // (1), voir BuildPutBlupi } x++; y--; } if (j % 2 == 0) mCel.y++; else mCel.x++; } BlupiDrawHili (); // dessine le rectangle de sélection // Construit les objets et les blupi. BuildPutBlupi (); // m_rankBlupi[x][y] <- rangs des blupi this->FixShifting (nbx, nby, iCel, iPos); mCel = iCel; mPos = iPos; for (j = 0; j < nby + 3; j++) { x = mCel.x; y = mCel.y; cPos = mPos; for (i = 0; i < nbx; i++) { if (x >= 2 && x < MAXCELX - 2 && y >= 2 && y < MAXCELY - 2) { rank = m_rankBlupi[x][y]; if ( rank != -1 && // un blupi sur cette cellule ? !m_blupi[rank].bCache && m_blupi[rank].bExist) { cel.x = m_blupi[rank].cel.x; cel.y = m_blupi[rank].cel.y; pos = ConvCelToPos (cel); pos.x += m_blupi[rank].pos.x; pos.y += m_blupi[rank].pos.y - (DIMBLUPIY - DIMCELY) - SHIFTBLUPIY; if (m_blupi[rank].bHili) { icon = 120 + (m_blupi[rank].energy * 18) / MAXENERGY; if (icon < 120) icon = 120; if (icon > 137) icon = 137; tPos = pos; tPos.y += DIMCELY; if (m_blupi[rank].vehicule == 1) // en bateau ? tPos.y -= 6; // Dessine la sélection/énergie if (m_blupi[rank].clipLeft == 0) m_pPixmap->DrawIconDemi (-1, CHBLUPI, icon, tPos); else { clipRect = clip; clipRect.left = m_blupi[rank].clipLeft; m_pPixmap->SetClipping (clipRect); m_pPixmap->DrawIconDemi (-1, CHBLUPI, icon, tPos); m_pPixmap->SetClipping (clip); } } // Dessine la flèche ronde "répète" sous blupi. if (m_blupi[rank].repeatLevel != -1) { tPos = pos; tPos.y += DIMCELY; if (m_blupi[rank].vehicule == 1) // en bateau ? tPos.y -= 6; // Dessine la sélection/énergie if (m_blupi[rank].clipLeft == 0) m_pPixmap->DrawIconDemi (-1, CHBLUPI, 116, tPos); else { clipRect = clip; clipRect.left = m_blupi[rank].clipLeft; m_pPixmap->SetClipping (clipRect); m_pPixmap->DrawIconDemi (-1, CHBLUPI, 116, tPos); m_pPixmap->SetClipping (clip); } } // Dessine la flèche jaune sur blupi. if (m_blupi[rank].bArrow) { tPos = pos; if (m_phase % (6 * 2) < 6) tPos.y -= DIMBLUPIY + (m_phase % 6) * 4; else tPos.y -= DIMBLUPIY + (6 - (m_phase % 6) - 1) * 4; m_pPixmap->DrawIcon (-1, CHBLUPI, 132, tPos); } // Dessine le stop sur blupi. if (m_blupi[rank].stop == 1) { tPos = pos; tPos.x += 9; tPos.y -= 24; m_pPixmap->DrawIcon ( -1, CHBUTTON, IsRightReading () ? 115 : 46, tPos); } // Dessine blupi pos.y += m_blupi[rank].posZ; if (m_blupi[rank].clipLeft == 0) { m_pPixmap->DrawIcon ( -1, m_blupi[rank].channel, m_blupi[rank].icon, pos); // Dessine l'objet transporté. if (m_blupi[rank].takeChannel != -1) { BuildMoveTransport (m_blupi[rank].icon, pos); m_pPixmap->DrawIcon ( -1, m_blupi[rank].takeChannel, m_blupi[rank].takeIcon, pos); } } else { clipRect = clip; clipRect.left = m_blupi[rank].clipLeft; m_pPixmap->SetClipping (clipRect); m_pPixmap->DrawIcon ( -1, m_blupi[rank].channel, m_blupi[rank].icon, pos); // Dessine l'objet transporté. if (m_blupi[rank].takeChannel != -1) { BuildMoveTransport (m_blupi[rank].icon, pos); m_pPixmap->DrawIcon ( -1, m_blupi[rank].takeChannel, m_blupi[rank].takeIcon, pos); } m_pPixmap->SetClipping (clip); } } if (x % 2 == 0 && y % 2 == 0) { rank = m_decor[x / 2][y / 2].rankMove; if (m_decor[x / 2][y / 2].objectChannel >= 0) { pos.x = cPos.x - DIMCELX / 2; pos.y = cPos.y - (DIMOBJY - DIMCELY * 2); // Dessine l'objet if ( rank == -1 || // décor fixe ? m_move[rank].bFloor || m_bBuild) { channel = m_decor[x / 2][y / 2].objectChannel; if (m_bOutline && channel == CHOBJECT) channel = CHOBJECTo; if ( m_celOutline1.x != -1 && x >= m_celOutline1.x && y >= m_celOutline1.y && x <= m_celOutline2.x && y <= m_celOutline2.y) { if (channel == CHOBJECT) channel = CHOBJECTo; else channel = CHOBJECT; } m_pPixmap->DrawIcon ( -1, channel, m_decor[x / 2][y / 2].objectIcon, pos); if (m_decor[x / 2][y / 2].objectIcon == 12) // fusée ? { pos.y -= DIMOBJY; m_pPixmap->DrawIcon (-1, channel, 13, pos); } } else // décor animé ? BuildMoveObject (x, y, pos, rank); } else { if ( rank != -1 && // décor animé ? !m_move[rank].bFloor && !m_bBuild) { pos.x = cPos.x - DIMCELX / 2; pos.y = cPos.y - (DIMOBJY - DIMCELY * 2); BuildMoveObject (x, y, pos, rank); } } // Dessine le feu en mode construction. if ( m_bBuild && m_decor[x / 2][y / 2].fire > 0 && m_decor[x / 2][y / 2].fire < MoveMaxFire ()) { pos.x = cPos.x - DIMCELX / 2; pos.y = cPos.y - (DIMOBJY - DIMCELY * 2); m_pPixmap->DrawIcon (-1, CHOBJECT, 49, pos); // petite flamme } } } x++; y--; cPos.x += DIMCELX; } if (j % 2 == 0) { mCel.y++; mPos.x -= DIMCELX / 2; mPos.y += DIMCELY / 2; } else { mCel.x++; mPos.x += DIMCELX / 2; mPos.y += DIMCELY / 2; } } // Construit le brouillard. if (!m_bFog) goto term; this->FixShifting (nbx, nby, iCel, iPos); mCel = iCel; mPos = iPos; for (j = 0; j < nby; j++) { x = mCel.x; y = mCel.y; cPos = mPos; for (i = 0; i < nbx; i++) { if ( x >= 0 && x < MAXCELX && y >= 0 && y < MAXCELY && x % 2 == 0 && y % 2 == 0) icon = m_decor[x / 2][y / 2].fog; else { icon = FOGHIDE; // caché } if ( abs (x) % 4 == abs (y) % 4 && (abs (x) % 4 == 0 || abs (x) % 4 == 2) && icon != -1) { pos.x = cPos.x - DIMCELX / 2; pos.y = cPos.y; m_pPixmap->DrawIcon (-1, CHFOG, icon, pos); } x++; y--; cPos.x += DIMCELX; } if (j % 2 == 0) { mCel.y++; mPos.x -= DIMCELX / 2; mPos.y += DIMCELY / 2; } else { mCel.x++; mPos.x += DIMCELX / 2; mPos.y += DIMCELY / 2; } } term: // Dessine la flèche jaune sur un objet. if (m_celArrow.x != -1) { tPos = ConvCelToPos (m_celArrow); if (m_phase % (6 * 2) < 6) tPos.y -= DIMBLUPIY + (m_phase % 6) * 4; else tPos.y -= DIMBLUPIY + (6 - (m_phase % 6) - 1) * 4; m_pPixmap->DrawIcon (-1, CHBLUPI, 132, tPos); } // Dessine le nom de l'objet pointé par la souris. if (posMouse.x == m_textLastPos.x && posMouse.y == m_textLastPos.y) { if (m_textCount == 0) { const auto text = GetResHili (posMouse); if (text) { posMouse.x += IsRightReading () ? 0 : 10; posMouse.y += 20; DrawText (m_pPixmap, posMouse, text); } } else m_textCount--; } else { m_textLastPos = posMouse; m_textCount = TEXTDELAY; } m_pPixmap->SetClipping (oldClip); GenerateMap (); // dessine la carte miniature GenerateStatictic (); // dessine les statistiques } // Augmente la phase. // -1 mise à jour continue // 0 début de mise à jour périodique // 1 mise à jour périodique suivante void CDecor::NextPhase (Sint32 mode) { if (mode == -1) m_phase = -1; if (mode == 0) m_phase = 0; if (mode == 1) m_phase++; m_totalTime++; } // Modifie le temps total passé dans cette partie. void CDecor::SetTotalTime (Sint32 total) { m_totalTime = total; } // Retourne le temps total passé dans cette partie. Sint32 CDecor::GetTotalTime () { return m_totalTime; } // Compte le nombre total de sols contenus dans les décors. Sint32 CDecor::CountFloor (Sint32 channel, Sint32 icon) { Sint32 x, y; Sint32 nb = 0; for (x = 0; x < MAXCELX / 2; x++) { for (y = 0; y < MAXCELY / 2; y++) { if ( channel == m_decor[x][y].floorChannel && icon == m_decor[x][y].floorIcon) nb++; } } return nb; } // Indique si une cellule est ok pour une action. // Le rang du blupi qui effectuera le travail est donnée dans rank. // action = 0 sélection jeu // 1 construction d'une cellule 1x1 // 2 construction d'une cellule 2x2 // EV_ACTION* action Errors CDecor::CelOkForAction ( Point cel, Sint32 action, Sint32 rank, Sint32 icons[4][4], Point & celOutline1, Point & celOutline2) { Sint32 x, y, i, j, channel, icon, nb, start, direct; Errors error = Errors::NONE; bool bStrong = false; bool bTransport = false; bool bVehicule = false; bool bVehiculeA = false; Point vector; for (x = 0; x < 4; x++) { for (y = 0; y < 4; y++) icons[x][y] = -1; } celOutline1.x = -1; celOutline2.x = -1; if ( action == 2 || action == EV_ACTION_ABAT1 || action == EV_ACTION_ROC1 || action == EV_ACTION_DROP || action == EV_ACTION_LABO || action == EV_ACTION_FABJEEP || action == EV_ACTION_FABARMURE || action == EV_ACTION_FABMINE || action == EV_ACTION_FLOWER1 || action == EV_ACTION_CULTIVE || action == EV_ACTION_FLAG) { cel.x = (cel.x / 2) * 2; cel.y = (cel.y / 2) * 2; } if (rank >= 0) { if (m_blupi[rank].energy > MAXENERGY / 4) // blupi fort ? bStrong = true; if (m_blupi[rank].takeChannel != -1) // porte qq chose ? bTransport = true; if (m_blupi[rank].vehicule != 0) // pas à pied ? bVehicule = true; if ( m_blupi[rank].vehicule != 0 && // pas à pied ? m_blupi[rank].vehicule != 3) // pas armure ? bVehiculeA = true; } if (action == 0) { if (IsBlupiHere (cel, false)) icons[1][1] = ICON_HILI_SEL; else { if (IsFreeCel (cel, -1) && m_nbBlupiHili > 0) icons[1][1] = ICON_HILI_ANY; else icons[1][1] = ICON_HILI_ERR; } } if (action == 1) { icons[1][1] = ICON_HILI_BUILD; // action } if (action == 2) { icons[1][1] = ICON_HILI_BUILD; // action icons[2][1] = ICON_HILI_BUILD; icons[1][2] = ICON_HILI_BUILD; icons[2][2] = ICON_HILI_BUILD; } if (action == EV_ACTION_STOP) { error = Errors::MISC; if ( m_blupi[rank].stop == 0 && (m_blupi[rank].goalAction == EV_ACTION_GO || (m_blupi[rank].goalAction >= EV_ACTION_ABAT1 && m_blupi[rank].goalAction <= EV_ACTION_ABAT6) || (m_blupi[rank].goalAction >= EV_ACTION_ROC1 && m_blupi[rank].goalAction <= EV_ACTION_ROC7) || m_blupi[rank].goalAction == EV_ACTION_CULTIVE || m_blupi[rank].goalAction == EV_ACTION_CULTIVE2 || m_blupi[rank].goalAction == EV_ACTION_FLAG || m_blupi[rank].goalAction == EV_ACTION_FLAG2 || m_blupi[rank].goalAction == EV_ACTION_FLAG3 || m_blupi[rank].goalAction == EV_ACTION_FLOWER1 || m_blupi[rank].goalAction == EV_ACTION_FLOWER2 || m_blupi[rank].goalAction == EV_ACTION_FLOWER3)) error = Errors::NONE; if ( m_blupi[rank].stop == 0 && m_blupi[rank].goalAction != 0 && m_blupi[rank].interrupt == 1) error = Errors::NONE; if (m_blupi[rank].repeatLevel != -1) error = Errors::NONE; } if (action == EV_ACTION_GO) { if (m_decor[cel.x / 2][cel.y / 2].objectIcon == 113) // maison ? { cel.x = (cel.x / 2) * 2 + 1; cel.y = (cel.y / 2) * 2 + 1; } error = Errors::MISC; if (m_nbBlupiHili > 0) { nb = m_nbBlupiHili; if (nb > 16) nb = 16; for (i = 0; i < nb; i++) { x = table_multi_goal[i * 2 + 0]; y = table_multi_goal[i * 2 + 1]; rank = GetHiliRankBlupi (i); if ( ((m_blupi[rank].takeChannel == -1) || (m_blupi[rank].energy > MAXENERGY / 4)) && IsFreeCelGo (GetCel (cel.x + x, cel.y + y), rank) && !IsBlupiHere (GetCel (cel.x + x, cel.y + y), true)) { icons[1 + x][1 + y] = ICON_HILI_OP; // action error = Errors::NONE; } else icons[1 + x][1 + y] = ICON_HILI_ERR; } } else icons[1][1] = ICON_HILI_ERR; } if (action == EV_ACTION_ABAT1) { GetObject (cel, channel, icon); if ( bStrong && !bTransport && !bVehicule && channel == CHOBJECT && icon >= 6 && icon <= 11 && // arbre ? !MoveIsUsed (cel) && IsWorkableObject (cel, rank)) { icons[1][1] = ICON_HILI_OP; // action icons[2][1] = ICON_HILI_OP; icons[1][2] = ICON_HILI_OP; icons[2][2] = ICON_HILI_OP; celOutline1 = cel; celOutline2 = cel; } else { icons[1][1] = ICON_HILI_ERR; // croix icons[2][1] = ICON_HILI_ERR; icons[1][2] = ICON_HILI_ERR; icons[2][2] = ICON_HILI_ERR; error = Errors::MISC; } } if (action == EV_ACTION_ROC1) { GetObject (cel, channel, icon); if ( bStrong && !bTransport && !bVehicule && m_blupi[rank].perso != 8 && // pas disciple ? channel == CHOBJECT && icon >= 37 && icon <= 43 && // rochers ? !MoveIsUsed (cel) && IsWorkableObject (cel, rank)) { icons[1][1] = ICON_HILI_OP; // action icons[2][1] = ICON_HILI_OP; icons[1][2] = ICON_HILI_OP; icons[2][2] = ICON_HILI_OP; celOutline1 = cel; celOutline2 = cel; } else { icons[1][1] = ICON_HILI_ERR; // croix icons[2][1] = ICON_HILI_ERR; icons[1][2] = ICON_HILI_ERR; icons[2][2] = ICON_HILI_ERR; error = Errors::MISC; } } if (action >= EV_ACTION_BUILD1 && action <= EV_ACTION_BUILD6) { if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { cel.x--; cel.y--; if (!bStrong || bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } if ( action == EV_ACTION_BUILD1 || // cabane ? action == EV_ACTION_BUILD2 || // couveuse ? action == EV_ACTION_BUILD6) // téléporteur ? { GetFloor (cel, channel, icon); if ( channel != CHFLOOR || (icon != 1 && // herbe claire ? (icon < 19 || icon > 32))) // herbe foncée ? { error = Errors::GROUND; // sol pas adéquat } } GetFloor (cel, channel, icon); if ( // mine ? action == EV_ACTION_BUILD4 && ((!g_restoreBugs && !m_decorMem[cel.x / 2][cel.y / 2].flagged) || // fixed (g_restoreBugs && (channel != CHFLOOR || icon != 71)))) // funny bug { error = Errors::GROUND; // sol pas adéquat } if ( action == EV_ACTION_BUILD6 && // téléporteur ? CountFloor (CHFLOOR, 80) >= 2) // déjà 2 ? { error = Errors::TELE2; // déjà 2 téléporteurs } if (action == EV_ACTION_BUILD3 || action == EV_ACTION_BUILD5) start = 44; // pierres else start = 36; // planches if (start == 44 && m_blupi[rank].perso == 8) start = 999; // disciple ? GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != start) // planches ? { error = Errors::MISC; // pas de planches ! } for (x = -1; x < 3; x++) { for (y = -1; y < 3; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = -1; x < 3; x++) { for (y = -1; y < 3; y++) { if ( (x < 0 || x > 1 || y < 0 || y > 1) && !IsFreeCel (GetCel (cel, x, y), rank)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } } if (action == EV_ACTION_WALL) { if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { cel.x--; cel.y--; if (!bStrong || bTransport || bVehicule || m_blupi[rank].perso == 8) // disciple // ? { error = Errors::MISC; // pas assez fort } if (m_blupi[rank].energy <= MAXENERGY / 2) error = Errors::ENERGY; // not enough energy GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != 44) // pierres ? { error = Errors::MISC; // pas de pierres ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } } if (action == EV_ACTION_TOWER) { bool bTour; if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { cel.x--; cel.y--; if (!bStrong || bTransport || bVehicule || m_blupi[rank].perso == 8) // disciple // ? { error = Errors::MISC; // pas assez fort } if (m_blupi[rank].energy <= MAXENERGY / 2) error = Errors::ENERGY; // not enough energy GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != 44) // pierres ? { error = Errors::MISC; // pas de pierres ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = -1; x < 3; x++) { for (y = -1; y < 3; y++) { if (x < 0 || x > 1 || y < 0 || y > 1) // périphérie ? { GetFloor (GetCel (cel, x, y), channel, icon); if (channel == CHFLOOR && (icon >= 2 && icon <= 13)) // rive ? { error = Errors::TOUREAU; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } if (error == 0) { bTour = false; for (i = 0; i < 4; i++) { vector = GetVector (i * 2 * 16); x = cel.x; y = cel.y; for (j = 0; j < 3; j++) { x += vector.x * 2; y += vector.y * 2; if (m_decor[x / 2][y / 2].objectIcon == 27) // tour ? bTour = true; if ( MoveGetObject (GetCel (x, y), channel, icon) && channel == CHOBJECT && icon == 27) // tour en construction ? bTour = true; } } if (!bTour) error = Errors::TOURISOL; } } } if (action == EV_ACTION_PALIS) { if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { cel.x--; cel.y--; if (!bStrong || bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != 36) // planches ? { error = Errors::MISC; // pas de pierres ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } } if (action == EV_ACTION_BRIDGEE) { Point test; if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { cel.x--; cel.y--; if (!bStrong || bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != 36) // planches ? { error = Errors::MISC; // pas de pierres ! } test = cel; if (error == 0) error = IsBuildPont (test, icon); for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } } if (action == EV_ACTION_CARRY) { if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { GetObject (GetCel (cel, -1, -1), channel, icon); if ( bStrong && !bTransport && !bVehiculeA && channel == CHOBJECT && (icon == 14 || // métal ? icon == 36 || // planches ? icon == 44 || // pierres ? icon == 60 || // tomates ? icon == 63 || // oeufs ? icon == 80 || // bouteille ? icon == 82 || // fleurs ? icon == 84 || // fleurs ? icon == 95 || // fleurs ? icon == 85 || // dynamite ? icon == 92 || // poison ? icon == 93 || // piège ? icon == 123 || // fer ? icon == 125) && // mine ? (!IsBlupiHereEx (GetCel (cel, -1, 0), rank, false) || !IsBlupiHereEx (GetCel (cel, 0, -1), rank, false))) { icons[1][1] = ICON_HILI_OP; // action } else { icons[1][1] = ICON_HILI_ERR; // croix error = Errors::MISC; } } } if (action == EV_ACTION_DROP) { if (!bTransport || bVehiculeA) { error = Errors::MISC; // ne transporte rien } GetObject (GetCel ((cel.x / 2) * 2, (cel.y / 2) * 2), channel, icon); if (icon != -1 && icon != 124) // pas drapeau ? error = Errors::MISC; start = 0; if (error == 0) { GetFloor (cel, channel, icon); if ( channel == CHFLOOR && icon == 52 && // nurserie ? m_blupi[rank].takeChannel == CHOBJECT && m_blupi[rank].takeIcon == 63) // oeufs ? { for (x = -1; x < 2; x++) { for (y = 0; y < 2; y++) { if ( !IsFreeCelDepose (GetCel (cel, x, y), rank) || IsBlupiHereEx (GetCel (cel, x, y), rank, false)) error = Errors::MISC; } } start = -1; } else { if ( !IsFreeCelDepose (GetCel (cel, 1, 1), rank) || IsBlupiHereEx (GetCel (cel, 1, 1), rank, false)) error = Errors::MISC; else { if ( !IsFreeCelDepose (GetCel (cel, 0, 1), rank) || IsBlupiHereEx (GetCel (cel, 0, 1), rank, false)) { if ( !IsFreeCelDepose (GetCel (cel, 1, 0), rank) || IsBlupiHereEx (GetCel (cel, 1, 0), rank, false)) error = Errors::MISC; } } } } for (x = start; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } } if (action == EV_ACTION_CULTIVE) { if (!bStrong || bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != 61) // maison ? { error = Errors::MISC; // pas de maison ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::MISC; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } if (action == EV_ACTION_LABO) { if (!bStrong || !bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if ( channel != CHOBJECT || icon != 28 || // laboratoire ? m_blupi[rank].takeChannel != CHOBJECT || (m_blupi[rank].takeIcon != 82 && // fleurs ? m_blupi[rank].takeIcon != 84 && // fleurs ? m_blupi[rank].takeIcon != 95 && // fleurs ? m_blupi[rank].takeIcon != 60)) // tomates ? { error = Errors::MISC; // pas de laboratoire ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::MISC; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } if (action == EV_ACTION_FLOWER1) { GetObject (cel, channel, icon); if ( bStrong && !bTransport && !bVehicule && channel == CHOBJECT && (icon == 81 || icon == 83 || icon == 94) && // fleurs ? !MoveIsUsed (cel) && IsWorkableObject (cel, rank)) { icons[1][1] = ICON_HILI_OP; // action icons[2][1] = ICON_HILI_OP; icons[1][2] = ICON_HILI_OP; icons[2][2] = ICON_HILI_OP; celOutline1 = cel; celOutline2 = cel; } else { icons[1][1] = ICON_HILI_ERR; // croix icons[2][1] = ICON_HILI_ERR; icons[1][2] = ICON_HILI_ERR; icons[2][2] = ICON_HILI_ERR; error = Errors::MISC; } } if (action == EV_ACTION_DYNAMITE) { if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { cel.x--; cel.y--; //? if ( !bStrong || bVehicule ) if (bVehiculeA) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if (icon != 85 && icon != 125) // dynamite/mine ? { error = Errors::MISC; // pas de dynamite ! } for (x = 0; x < 2; x++) { for (y = 1; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 1; y < 2; y++) { if ( (x < 0 || x > 1 || y < 0 || y > 1) && !IsFreeCel (GetCel (cel, x, y), rank)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } } if (action == EV_ACTION_EAT) { if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { GetObject (GetCel (cel, -1, -1), channel, icon); if ( !m_blupi[rank].bMalade && !bVehicule && m_blupi[rank].perso != 8 && // pas disciple ? channel == CHOBJECT && icon == 60 && // tomates ? (!IsBlupiHereEx (GetCel (cel, -1, 0), rank, false) || !IsBlupiHereEx (GetCel (cel, 0, -1), rank, false))) { icons[1][1] = ICON_HILI_OP; // action } else { icons[1][1] = ICON_HILI_ERR; // croix error = Errors::MISC; } } } if (action == EV_ACTION_DRINK) { if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { GetObject (GetCel (cel, -1, -1), channel, icon); if ( m_blupi[rank].bMalade && !bVehicule && m_blupi[rank].perso != 8 && // pas disciple ? channel == CHOBJECT && icon == 80 && // bouteille ? (!IsBlupiHereEx (GetCel (cel, -1, 0), rank, false) || !IsBlupiHereEx (GetCel (cel, 0, -1), rank, false))) { icons[1][1] = ICON_HILI_OP; // action } else { icons[1][1] = ICON_HILI_ERR; // croix error = Errors::MISC; } } } if (action == EV_ACTION_BOATE) { Point test; if (cel.x % 2 != 1 || cel.y % 2 != 1) { icons[1][1] = ICON_HILI_ERR; error = Errors::MISC; } else { cel.x--; cel.y--; if (!bStrong || bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != 36) // planches ? { error = Errors::MISC; // pas de pierres ! } test = cel; if (error == 0 && !IsBuildBateau (test, direct)) { error = Errors::MISC; // impossible ici ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::FREE; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } } if (action == EV_ACTION_DJEEP) { cel.x = (cel.x / 2) * 2; cel.y = (cel.y / 2) * 2; error = Errors::MISC; if ( m_blupi[rank].vehicule == 2 && // en jeep ? m_decor[cel.x / 2][cel.y / 2].objectIcon == -1 && m_decor[cel.x / 2][cel.y / 2].floorIcon != 80) // pas téléporteur ? { if ( IsFreeCelGo (GetCel (cel, +1, 0), rank) && IsFreeCelGo (GetCel (cel, +1, +1), rank) && !IsBlupiHereEx (GetCel (cel, +1, 0), rank, false) && !IsBlupiHereEx (GetCel (cel, +1, +1), rank, false)) { icons[1][1] = ICON_HILI_OP; // action icons[2][1] = ICON_HILI_OP; icons[1][2] = ICON_HILI_OP; icons[2][2] = ICON_HILI_OP; error = Errors::NONE; } } else { icons[1][1] = ICON_HILI_ERR; // croix icons[2][1] = ICON_HILI_ERR; icons[1][2] = ICON_HILI_ERR; icons[2][2] = ICON_HILI_ERR; } } if (action == EV_ACTION_DARMURE) { cel.x = (cel.x / 2) * 2; cel.y = (cel.y / 2) * 2; error = Errors::MISC; if ( m_blupi[rank].vehicule == 3 && // armure ? !bTransport && m_decor[cel.x / 2][cel.y / 2].objectIcon == -1 && m_decor[cel.x / 2][cel.y / 2].floorIcon != 80) // pas téléporteur ? { if ( IsFreeCelGo (GetCel (cel, +1, 0), rank) && IsFreeCelGo (GetCel (cel, +1, +1), rank) && !IsBlupiHereEx (GetCel (cel, +1, 0), rank, false) && !IsBlupiHereEx (GetCel (cel, +1, +1), rank, false)) { icons[1][1] = ICON_HILI_OP; // action icons[2][1] = ICON_HILI_OP; icons[1][2] = ICON_HILI_OP; icons[2][2] = ICON_HILI_OP; error = Errors::NONE; } } else { icons[1][1] = ICON_HILI_ERR; // croix icons[2][1] = ICON_HILI_ERR; icons[1][2] = ICON_HILI_ERR; icons[2][2] = ICON_HILI_ERR; } } if (action == EV_ACTION_FLAG) { if (!bStrong || bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetFloor (cel, channel, icon); if ((icon < 33 || icon > 48) && icon != 71) // pas terre ? { error = Errors::MISC; // terrain pas adapté } GetObject (cel, channel, icon); if (channel == CHOBJECT) // y a-t-il un objet ? { error = Errors::MISC; // terrain pas adapté } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::MISC; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } if (action == EV_ACTION_EXTRAIT) { if (!bStrong || bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if (channel != CHOBJECT || icon != 122) // mine de fer ? { error = Errors::MISC; // pas de mine } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::MISC; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } if ( action == EV_ACTION_FABJEEP || action == EV_ACTION_FABMINE || action == EV_ACTION_FABARMURE) { if (!bStrong || !bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } if (action == EV_ACTION_FABJEEP && m_blupi[rank].perso == 8) // disciple ? { error = Errors::MISC; // impossible } if (action == EV_ACTION_FABARMURE && m_blupi[rank].perso == 8) // disciple ? { error = Errors::MISC; // impossible } GetObject (cel, channel, icon); if ( channel != CHOBJECT || icon != 120 || // usine ? m_blupi[rank].takeChannel != CHOBJECT || m_blupi[rank].takeIcon != 123) // fer ? { error = Errors::MISC; // pas d'usine ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::MISC; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } if (action == EV_ACTION_FABDISC) { if (!bStrong || !bTransport || bVehicule) { error = Errors::MISC; // pas assez fort } GetObject (cel, channel, icon); if ( channel != CHOBJECT || icon != 120 || // usine ? m_blupi[rank].takeChannel != CHOBJECT || m_blupi[rank].takeIcon != 14) // métal ? { error = Errors::MISC; // pas d'usine ! } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (error) icons[x + 1][y + 1] = ICON_HILI_ERR; else icons[x + 1][y + 1] = ICON_HILI_OP; } } for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { if (IsBlupiHereEx (GetCel (cel, x, y), rank, false)) { error = Errors::MISC; icons[x + 1][y + 1] = ICON_HILI_ERR; // croix } } } } return error; } // Indique si une cellule est ok pour une action. // Le rang du blupi qui effectuera le travail est donnée dans rank. Errors CDecor::CelOkForAction (Point cel, Sint32 action, Sint32 rank) { Sint32 icons[4][4]; Point celOutline1, celOutline2; return CelOkForAction (cel, action, rank, icons, celOutline1, celOutline2); } // Retourne le rang du nième blupi sélectionné. Sint32 CDecor::GetHiliRankBlupi (Sint32 nb) { Sint32 rank; if (m_nbBlupiHili == 0) return -1; if (m_nbBlupiHili == 1) { if (nb == 0) return m_rankBlupiHili; return -1; } for (rank = 0; rank < MAXBLUPI; rank++) { if (m_blupi[rank].bExist && m_blupi[rank].bHili) { if (nb == 0) return rank; nb--; } } return -1; } // Marque la cellule visée par la souris. // action = 0 sélection jeu // 1 construction d'une cellule 1x1 // 2 construction d'une cellule 2x2 void CDecor::CelHili (Point pos, Sint32 action) { Sint32 x, y, i, channel, icon, rank, nb; Point cel; for (x = 0; x < 4; x++) { for (y = 0; y < 4; y++) m_iconHili[x][y] = -1; } m_celOutline1.x = -1; m_celOutline2.x = -1; m_rankHili = -1; if (action == 0) // sélection pendant jeu ? { rank = GetTargetBlupi (pos); if (rank >= 0) { m_celHili = m_blupi[rank].cel; m_rankHili = rank; m_iconHili[1][1] = ICON_HILI_SEL; } else { m_celHili = ConvPosToCel (pos); if (IsBlupiHere (m_celHili, false)) { m_rankHili = m_blupiHere; m_iconHili[1][1] = ICON_HILI_SEL; } else { if (m_nbBlupiHili > 0) { nb = m_nbBlupiHili; if (nb > 16) nb = 16; for (i = 0; i < nb; i++) { x = table_multi_goal[i * 2 + 0]; y = table_multi_goal[i * 2 + 1]; cel.x = m_celHili.x + x; cel.y = m_celHili.y + y; rank = GetHiliRankBlupi (i); if (IsFreeCelHili (cel, rank)) m_iconHili[1 + x][1 + y] = ICON_HILI_ANY; else m_iconHili[1 + x][1 + y] = ICON_HILI_ERR; } } else m_iconHili[1][1] = ICON_HILI_ERR; m_celOutline1.x = (m_celHili.x / 2) * 2; m_celOutline1.y = (m_celHili.y / 2) * 2; if ( GetObject (m_celOutline1, channel, icon) && channel == CHOBJECT && (icon == 14 // métal ? || icon == 36 // planches ? || icon == 44 // pierres ? || icon == 60 // tomates ? || icon == 64 // oeufs ? || icon == 80 // bouteille ? || icon == 82 // fleurs ? || icon == 84 // fleurs ? || icon == 95 // fleurs ? || icon == 85 // dynamite ? || icon == 92 // poison ? || icon == 93 // piège ? || icon == 123 // fer ? || icon == 125)) // mine ? { if (m_celHili.x % 2 == 0 || m_celHili.y % 2 == 0) m_celOutline1.x = -1; } m_celOutline2 = m_celOutline1; } } } if (action == 1) // construction d'une cellule 1x1 ? { m_celHili = ConvPosToCel (pos); m_iconHili[1][1] = ICON_HILI_BUILD; // action } if (action == 2) // construction d'une cellule 2x2 ? { m_celHili = ConvPosToCel2 (pos); m_iconHili[1][1] = ICON_HILI_BUILD; // action m_iconHili[2][1] = ICON_HILI_BUILD; m_iconHili[1][2] = ICON_HILI_BUILD; m_iconHili[2][2] = ICON_HILI_BUILD; } } // Marque la cellule visée par la souris pour un bouton donné. void CDecor::CelHiliButton (Point cel, Sint32 button) { Point celOutline1, celOutline2; CelOkForAction ( cel, table_actions[button], m_rankBlupiHili, m_iconHili, celOutline1, celOutline2); if ( button == BUTTON_ABAT || button == BUTTON_ABATn || button == BUTTON_ROC || button == BUTTON_ROCn || button == BUTTON_WALL || button == BUTTON_TOWER || button == BUTTON_PALIS || button == BUTTON_BRIDGE || button == BUTTON_CULTIVE || button == BUTTON_DEPOSE || button == BUTTON_LABO || button == BUTTON_FLOWER || button == BUTTON_FLOWERn || button == BUTTON_DYNAMITE || button == BUTTON_BOAT || button == BUTTON_DJEEP || button == BUTTON_DARMOR || button == BUTTON_FLAG || button == BUTTON_EXTRAIT || button == BUTTON_FABJEEP || button == BUTTON_MAKEARMOR || button == BUTTON_FABMINE || button == BUTTON_FABDISC || (button >= BUTTON_BUILD1 && button <= BUTTON_BUILD6)) { m_celHili.x = (cel.x / 2) * 2; m_celHili.y = (cel.y / 2) * 2; } else m_celHili = cel; } // Marque la cellule visée par la souris pour une répétition donnée. void CDecor::CelHiliRepeat (Sint32 list) { Sint32 rank, button, x, y, i; Point cel; for (x = 0; x < 4; x++) { for (y = 0; y < 4; y++) m_iconHili[x][y] = -1; } if (m_nbBlupiHili != 1) return; rank = m_rankBlupiHili; i = m_blupi[rank].repeatLevelHope - list; if (i < 0 || i > m_blupi[rank].repeatLevelHope) return; button = m_blupi[rank].listButton[i]; if ( button == BUTTON_ABAT || button == BUTTON_ABATn || button == BUTTON_ROC || button == BUTTON_ROCn || button == BUTTON_WALL || button == BUTTON_TOWER || button == BUTTON_PALIS || button == BUTTON_BRIDGE || button == BUTTON_CULTIVE || button == BUTTON_DEPOSE || button == BUTTON_LABO || button == BUTTON_FLOWER || button == BUTTON_FLOWERn || button == BUTTON_DYNAMITE || button == BUTTON_BOAT || button == BUTTON_DJEEP || button == BUTTON_DARMOR || button == BUTTON_FLAG || button == BUTTON_EXTRAIT || button == BUTTON_FABJEEP || button == BUTTON_MAKEARMOR || button == BUTTON_FABMINE || button == BUTTON_FABDISC || (button >= BUTTON_BUILD1 && button <= BUTTON_BUILD6)) { m_iconHili[1][1] = ICON_HILI_OP; // action m_iconHili[2][1] = ICON_HILI_OP; // action m_iconHili[1][2] = ICON_HILI_OP; // action m_iconHili[2][2] = ICON_HILI_OP; // action cel = m_blupi[rank].listCel[i]; cel.x = (cel.x / 2) * 2; cel.y = (cel.y / 2) * 2; } else { m_iconHili[1][1] = ICON_HILI_OP; // action cel = m_blupi[rank].listCel[i]; } m_celHili = cel; } // Retourne l'identificateur du texte correspondant à // l'objet ou au blupi visé par la souris. const char * CDecor::GetResHili (Point posMouse) { Sint32 icon; // The `corner == true` values are corresponding to the objects // positionned at the bottom/right corner of the cell. struct object_t { bool corner; const char * text; }; static const std::unordered_map<size_t, object_t> tableObject = { {6, {false, translate ("Tree")}}, {7, {false, translate ("Tree")}}, {8, {false, translate ("Tree")}}, {9, {false, translate ("Tree")}}, {10, {false, translate ("Tree")}}, {11, {false, translate ("Tree")}}, {12, {false, translate ("Enemy rocket")}}, {14, {false, translate ("Platinium")}}, {16, {true, translate ("Armour")}}, {17, {false, translate ("Enemy construction")}}, {18, {false, translate ("Enemy construction")}}, {20, {false, translate ("Wall")}}, {21, {false, translate ("Wall")}}, {22, {false, translate ("Wall")}}, {23, {false, translate ("Wall")}}, {24, {false, translate ("Wall")}}, {25, {false, translate ("Wall")}}, {26, {false, translate ("Wall")}}, {27, {false, translate ("Protection tower")}}, {28, {false, translate ("Laboratory")}}, {29, {false, translate ("Laboratory")}}, {30, {false, translate ("Tree trunks")}}, {31, {false, translate ("Tree trunks")}}, {32, {false, translate ("Tree trunks")}}, {33, {false, translate ("Tree trunks")}}, {34, {false, translate ("Tree trunks")}}, {35, {false, translate ("Tree trunks")}}, {36, {true, translate ("Planks")}}, {37, {false, translate ("Rocks")}}, {38, {false, translate ("Rocks")}}, {39, {false, translate ("Rocks")}}, {40, {false, translate ("Rocks")}}, {41, {false, translate ("Rocks")}}, {42, {false, translate ("Rocks")}}, {43, {false, translate ("Rocks")}}, {44, {true, translate ("Stones")}}, {45, {false, translate ("Fire")}}, {46, {false, translate ("Fire")}}, {47, {false, translate ("Fire")}}, {48, {false, translate ("Fire")}}, {49, {false, translate ("Fire")}}, {50, {false, translate ("Fire")}}, {51, {false, translate ("Fire")}}, {52, {false, translate ("Fire")}}, {57, {true, translate ("Tomatoes")}}, {58, {true, translate ("Tomatoes")}}, {59, {true, translate ("Tomatoes")}}, {60, {true, translate ("Tomatoes")}}, {61, {false, translate ("Garden shed")}}, {62, {false, translate ("Garden shed")}}, {63, {true, translate ("Eggs")}}, {64, {false, translate ("Eggs")}}, {65, {false, translate ("Palisade")}}, {66, {false, translate ("Palisade")}}, {67, {false, translate ("Palisade")}}, {68, {false, translate ("Palisade")}}, {69, {false, translate ("Palisade")}}, {70, {false, translate ("Palisade")}}, {71, {false, translate ("Palisade")}}, {72, {false, translate ("Bridge")}}, {73, {false, translate ("Bridge")}}, {80, {true, translate ("Medical potion")}}, {81, {false, translate ("Flowers")}}, {82, {true, translate ("Bunch of flowers")}}, {83, {false, translate ("Flowers")}}, {84, {true, translate ("Bunch of flowers")}}, {85, {true, translate ("Dynamite")}}, {86, {true, translate ("Dynamite")}}, {87, {true, translate ("Dynamite")}}, {92, {true, translate ("Poison")}}, {93, {true, translate ("Sticky trap")}}, {94, {false, translate ("Flowers")}}, {95, {true, translate ("Bunch of flowers")}}, {96, {true, translate ("Trapped enemy")}}, {97, {true, translate ("Trapped enemy")}}, {98, {true, translate ("Trapped enemy")}}, {99, {false, translate ("Enemy construction")}}, {100, {false, translate ("Enemy construction")}}, {101, {false, translate ("Enemy construction")}}, {102, {false, translate ("Enemy construction")}}, {103, {false, translate ("Enemy construction")}}, {104, {false, translate ("Enemy construction")}}, {105, {false, translate ("Enemy construction")}}, {106, {false, translate ("Enemy construction")}}, {107, {false, translate ("Enemy construction")}}, {108, {false, translate ("Enemy construction")}}, {109, {false, translate ("Enemy construction")}}, {110, {false, translate ("Enemy construction")}}, {111, {false, translate ("Enemy construction")}}, {112, {false, translate ("Enemy construction")}}, {113, {false, translate ("Blupi's house")}}, {114, {true, translate ("Trapped enemy")}}, {115, {false, translate ("Enemy construction")}}, {116, {false, translate ("Enemy construction")}}, {117, {true, translate ("Boat")}}, {118, {true, translate ("Jeep")}}, {119, {false, translate ("Workshop")}}, {120, {false, translate ("Workshop")}}, {121, {false, translate ("Mine")}}, {122, {false, translate ("Mine")}}, {123, {true, translate ("Iron")}}, {124, {false, translate ("Flag")}}, {125, {true, translate ("Time bomb")}}, {126, {false, translate ("Mine")}}, {127, {true, translate ("Time bomb")}}, {128, {false, translate ("Enemy construction")}}, {129, {false, translate ("Enemy construction")}}, {130, {true, translate ("Trapped enemy")}}, }; static const std::unordered_map<size_t, object_t> tableFloor = { {1, {false, translate ("Normal ground")}}, {2, {false, translate ("Bank")}}, {3, {false, translate ("Bank")}}, {4, {false, translate ("Bank")}}, {5, {false, translate ("Bank")}}, {6, {false, translate ("Bank")}}, {7, {false, translate ("Bank")}}, {8, {false, translate ("Bank")}}, {9, {false, translate ("Bank")}}, {10, {false, translate ("Bank")}}, {11, {false, translate ("Bank")}}, {12, {false, translate ("Bank")}}, {13, {false, translate ("Bank")}}, {14, {false, translate ("Water")}}, {15, {false, translate ("Paving stones")}}, {16, {false, translate ("Paving stones")}}, {17, {false, translate ("Striped paving stones")}}, {18, {false, translate ("Ice")}}, {19, {false, translate ("Burnt ground")}}, {20, {false, translate ("Inflammable ground")}}, {21, {false, translate ("Miscellaneous ground")}}, {22, {false, translate ("Miscellaneous ground")}}, {23, {false, translate ("Miscellaneous ground")}}, {24, {false, translate ("Miscellaneous ground")}}, {25, {false, translate ("Miscellaneous ground")}}, {26, {false, translate ("Miscellaneous ground")}}, {27, {false, translate ("Miscellaneous ground")}}, {28, {false, translate ("Miscellaneous ground")}}, {29, {false, translate ("Miscellaneous ground")}}, {30, {false, translate ("Miscellaneous ground")}}, {31, {false, translate ("Miscellaneous ground")}}, {32, {false, translate ("Miscellaneous ground")}}, {33, {false, translate ("Sterile ground")}}, {34, {false, translate ("Miscellaneous ground")}}, {35, {false, translate ("Miscellaneous ground")}}, {36, {false, translate ("Miscellaneous ground")}}, {37, {false, translate ("Miscellaneous ground")}}, {38, {false, translate ("Miscellaneous ground")}}, {39, {false, translate ("Miscellaneous ground")}}, {40, {false, translate ("Miscellaneous ground")}}, {41, {false, translate ("Miscellaneous ground")}}, {42, {false, translate ("Miscellaneous ground")}}, {43, {false, translate ("Miscellaneous ground")}}, {44, {false, translate ("Miscellaneous ground")}}, {45, {false, translate ("Miscellaneous ground")}}, {46, {false, translate ("Sterile ground")}}, {47, {false, translate ("Sterile ground")}}, {48, {false, translate ("Sterile ground")}}, {49, {false, translate ("Normal ground")}}, {50, {false, translate ("Normal ground")}}, {51, {false, translate ("Normal ground")}}, {52, {false, translate ("Incubator")}}, {53, {false, translate ("Incubator")}}, {54, {false, translate ("Incubator")}}, {55, {false, translate ("Incubator")}}, {56, {false, translate ("Incubator")}}, {57, {false, translate ("Normal ground")}}, {58, {false, translate ("Inflammable ground")}}, {59, {false, translate ("Bridge")}}, {60, {false, translate ("Bridge")}}, {61, {false, translate ("Bridge")}}, {62, {false, translate ("Bridge")}}, {63, {false, translate ("Bridge")}}, {64, {false, translate ("Bridge")}}, {65, {false, translate ("Enemy ground")}}, {66, {false, translate ("Miscellaneous ground")}}, {67, {false, translate ("Enemy ground")}}, {68, {false, translate ("Water")}}, {69, {false, translate ("Water")}}, {70, {false, translate ("Water")}}, {71, {false, translate ("Sterile ground")}}, {78, {false, translate ("Miscellaneous ground")}}, {79, {false, translate ("Miscellaneous ground")}}, {80, {false, translate ("Teleporter")}}, {81, {false, translate ("Teleporter")}}, {82, {false, translate ("Teleporter")}}, {83, {false, translate ("Teleporter")}}, {84, {false, translate ("Teleporter")}}, }; if (m_bHideTooltips) return nullptr; // rien si menu présent if ( posMouse.x < POSDRAWX || posMouse.x > POSDRAWX + DIMDRAWX || posMouse.y < POSDRAWY || posMouse.y > POSDRAWY + DIMDRAWY) return nullptr; if (m_celHili.x != -1) { if (m_rankHili != -1) // blupi visé ? { switch (m_blupi[m_rankHili].perso) { case 0: // blupi ? if (m_blupi[m_rankHili].energy <= MAXENERGY / 4) return gettext ("Tired Blupi"); if (m_blupi[m_rankHili].bMalade) return gettext ("Sick Blupi"); return gettext ("Blupi"); case 1: // spider ? return gettext ("Spider"); case 2: // virus ? return gettext ("Virus"); case 3: // tracks ? return gettext ("Bulldozer"); case 4: // robot ? return gettext ("Master robot"); case 5: // bombe ? return gettext ("Bouncing bomb"); case 7: // electro ? return gettext ("Electrocutor"); case 8: // disciple ? return gettext ("Helper robot"); } return nullptr; } icon = m_decor[m_celHili.x / 2][m_celHili.y / 2].objectIcon; if (icon != -1) { const auto obj = tableObject.find (icon); if (obj != tableObject.end ()) { if (!obj->second.corner) return gettext (obj->second.text); if (m_celHili.x % 2 && m_celHili.y % 2) return gettext (obj->second.text); } } icon = m_decor[m_celHili.x / 2][m_celHili.y / 2].floorIcon; if (icon != -1) { const auto obj = tableFloor.find (icon); if (obj != tableFloor.end ()) return gettext (obj->second.text); } } return nullptr; } // Indique si le menu est présent et qu'il faut cacher // les tooltips du décor. void CDecor::HideTooltips (bool bHide) { m_bHideTooltips = bHide; } // Modifie l'origine supérieure/gauche du décor. void CDecor::SetCorner (Point corner, bool bCenter) { if (bCenter) { corner.x -= 10; corner.y -= 2; } if (corner.x < -8) corner.x = -8; if (corner.x > MAXCELX - 12) corner.x = MAXCELX - 12; if (corner.y < -2) corner.y = -2; if (corner.y > MAXCELY - 4) corner.y = MAXCELY - 4; m_celCorner = corner; m_bGroundRedraw = true; // faudra redessiner les sols m_celHili.x = -1; m_textLastPos.x = -1; // tooltips plus lavable ! } Point CDecor::GetCorner () { return m_celCorner; } Point CDecor::GetHome () { return m_celHome; } // Mémoirise une position pendant le jeu. void CDecor::MemoPos (Sint32 rank, bool bRecord) { Point pos; pos.x = LXIMAGE () / 2; pos.y = LYIMAGE () / 2; if (rank < 0 || rank >= 4) return; if (bRecord) { m_pSound->PlayImage (SOUND_CLOSE, pos); m_memoPos[rank] = m_celCorner; } else { if (m_memoPos[rank].x == 0 && m_memoPos[rank].y == 0) m_pSound->PlayImage (SOUND_BOING, pos); else { m_pSound->PlayImage (SOUND_GOAL, pos); SetCorner (m_memoPos[rank], false); } } } // Gestion du temps absolu global. void CDecor::SetTime (Sint32 time) { m_time = time; m_timeConst = time; // vraiment ? m_timeFlipOutline = time; } Sint32 CDecor::GetTime () { return m_time; } // Gestion de la musique midi. void CDecor::SetMusic (Sint32 music) { m_music = music; } Sint32 CDecor::GetMusic () { return m_music; } // Gestion de la difficulté. void CDecor::SetSkill (Sint32 skill) { m_skill = skill; } Sint32 CDecor::GetSkill () { return m_skill; } // Gestion de la région. // 0 = normal // 1 = palmier // 2 = hiver // 3 = sapin void CDecor::SetRegion (Sint32 region) { m_region = region; } Sint32 CDecor::GetRegion () { return m_region; } // Gestion des infos. void CDecor::SetInfoMode (bool bInfo) { m_bInfo = bInfo; m_bGroundRedraw = true; // faudra redessiner les sols } bool CDecor::GetInfoMode () { return m_bInfo; } void CDecor::SetInfoHeight (Sint32 height) { m_infoHeight = height; m_bGroundRedraw = true; // faudra redessiner les sols } Sint32 CDecor::GetInfoHeight () { if (m_bInfo) return m_infoHeight; else return 0; } // Retourne le pointeur à la liste des boutons existants. char * CDecor::GetButtonExist () { return m_buttonExist; } // Ouvre le buffer pour le undo pendant la construction. void CDecor::UndoOpen () { if (m_pUndoDecor == nullptr) m_pUndoDecor = (Cellule *) malloc (sizeof (Cellule) * (MAXCELX / 2) * (MAXCELY / 2)); } // Ferme le buffer pour le undo pendant la construction. void CDecor::UndoClose () { if (m_pUndoDecor != nullptr) { free (m_pUndoDecor); m_pUndoDecor = nullptr; } } // Copie le décor dans le buffer pour le undo. void CDecor::UndoCopy () { UndoOpen (); // ouvre le buffer du undo si nécessaire if (m_pUndoDecor != nullptr) memcpy ( m_pUndoDecor, &m_decor, sizeof (Cellule) * (MAXCELX / 2) * (MAXCELY / 2)); } // Revient en arrière pour tout le décor. void CDecor::UndoBack () { if (m_pUndoDecor != nullptr) { memcpy ( &m_decor, m_pUndoDecor, sizeof (Cellule) * (MAXCELX / 2) * (MAXCELY / 2)); UndoClose (); m_bGroundRedraw = true; } } // Indique s'il est possible d'effectuer un undo. bool CDecor::IsUndo () { return (m_pUndoDecor != nullptr); } void CDecor::InvalidateGrounds () { m_bGroundRedraw = true; }
0
0.871234
1
0.871234
game-dev
MEDIA
0.790142
game-dev
0.948666
1
0.948666
ProjectIgnis/CardScripts
1,977
rush/c160008041.lua
--シャワーリング・インフェルギョ --Showering Seaferno local s,id=GetID() function s.initial_effect(c) -- fusion c:EnableReviveLimit() Fusion.AddProcMix(c,true,true,160008025,CARD_JELLYPLUG) --All pyro monsters you control gain ATK local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DAMAGE) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) end s.listed_names={160008025} --Check for card in deck to send to GY function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDiscardDeckAsCost(tp,1) end end function s.thfilter(c) return c:IsCode(160008025) and c:IsAbleToHand() end --Activation legality function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE) end function s.operation(e,tp,eg,ep,ev,re,r,rp) --Effect local c=e:GetHandler() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_GRAVE,0,1,1,nil) if #g>0 then if Duel.SendtoHand(g,nil,REASON_EFFECT)>0 then Duel.ConfirmCards(1-tp,g) Duel.Damage(1-tp,800,REASON_EFFECT) if Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsLevel,8),tp,0,LOCATION_MZONE,1,nil) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(800) e1:SetReset(RESETS_STANDARD_PHASE_END) c:RegisterEffect(e1) local ag=Duel.GetMatchingGroup(aux.FaceupFilter(Card.IsLevel,8),tp,0,LOCATION_MZONE,nil) for tc in ag:Iter() do local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(-800) e1:SetReset(RESETS_STANDARD_PHASE_END) tc:RegisterEffect(e1) end end end end end
0
0.936384
1
0.936384
game-dev
MEDIA
0.987481
game-dev
0.959374
1
0.959374
FirelandsProject/firelands-cata
7,740
src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp
/* * This file is part of the FirelandsCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero 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 Affero General Public License for * more details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BattlegroundRV.h" #include "GameObject.h" #include "Log.h" #include "ObjectAccessor.h" #include "Player.h" #include "WorldPacket.h" #include "WorldStatePackets.h" BattlegroundRV::BattlegroundRV() { BgObjects.resize(BG_RV_OBJECT_MAX); _timer = 0; _state = 0; _pillarCollision = false; } void BattlegroundRV::PostUpdateImpl(uint32 diff) { if (GetStatus() != STATUS_IN_PROGRESS) return; if (_timer < diff) { switch (_state) { case BG_RV_STATE_OPEN_FENCES: // Open fire (only at game start) for (uint8 i = BG_RV_OBJECT_FIRE_1; i <= BG_RV_OBJECT_FIREDOOR_2; ++i) DoorOpen(i); _timer = BG_RV_CLOSE_FIRE_TIMER; _state = BG_RV_STATE_CLOSE_FIRE; break; case BG_RV_STATE_CLOSE_FIRE: for (uint8 i = BG_RV_OBJECT_FIRE_1; i <= BG_RV_OBJECT_FIREDOOR_2; ++i) DoorClose(i); // Fire got closed after five seconds, leaves twenty seconds before toggling pillars _timer = BG_RV_FIRE_TO_PILLAR_TIMER; _state = BG_RV_STATE_SWITCH_PILLARS; break; case BG_RV_STATE_SWITCH_PILLARS: TogglePillarCollision(); _timer = BG_RV_PILLAR_SWITCH_TIMER; break; } } else _timer -= diff; } void BattlegroundRV::StartingEventOpenDoors() { // Buff respawn SpawnBGObject(BG_RV_OBJECT_BUFF_1, 90); SpawnBGObject(BG_RV_OBJECT_BUFF_2, 90); // Elevators DoorOpen(BG_RV_OBJECT_ELEVATOR_1); DoorOpen(BG_RV_OBJECT_ELEVATOR_2); _state = BG_RV_STATE_OPEN_FENCES; _timer = BG_RV_FIRST_TIMER; // Should be false at first, TogglePillarCollision will do it. _pillarCollision = true; TogglePillarCollision(); } void BattlegroundRV::HandleAreaTrigger(Player* player, uint32 trigger) { if (GetStatus() != STATUS_IN_PROGRESS) return; switch (trigger) { case 5224: case 5226: // fire was removed in 3.2.0 case 5473: case 5474: break; default: Battleground::HandleAreaTrigger(player, trigger); break; } } void BattlegroundRV::FillInitialWorldStates(WorldPackets::WorldState::InitWorldStates& data) { data.Worldstates.emplace_back(uint32(BG_RV_WORLD_STATE), uint32(1)); Arena::FillInitialWorldStates(data); } bool BattlegroundRV::SetupBattleground() { // elevators if (!AddObject(BG_RV_OBJECT_ELEVATOR_1, BG_RV_OBJECT_TYPE_ELEVATOR_1, 763.536377f, -294.535767f, 0.505383f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_ELEVATOR_2, BG_RV_OBJECT_TYPE_ELEVATOR_2, 763.506348f, -273.873352f, 0.505383f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) // buffs || !AddObject(BG_RV_OBJECT_BUFF_1, BG_RV_OBJECT_TYPE_BUFF_1, 735.551819f, -284.794678f, 28.276682f, 0.034906f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_BUFF_2, BG_RV_OBJECT_TYPE_BUFF_2, 791.224487f, -284.794464f, 28.276682f, 2.600535f, 0, 0, 0, RESPAWN_IMMEDIATELY) // fire || !AddObject(BG_RV_OBJECT_FIRE_1, BG_RV_OBJECT_TYPE_FIRE_1, 743.543457f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_FIRE_2, BG_RV_OBJECT_TYPE_FIRE_2, 782.971802f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_FIREDOOR_1, BG_RV_OBJECT_TYPE_FIREDOOR_1, 743.711060f, -284.099609f, 27.542587f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_FIREDOOR_2, BG_RV_OBJECT_TYPE_FIREDOOR_2, 783.221252f, -284.133362f, 27.535686f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) // Gear || !AddObject(BG_RV_OBJECT_GEAR_1, BG_RV_OBJECT_TYPE_GEAR_1, 763.664551f, -261.872986f, 26.686588f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_GEAR_2, BG_RV_OBJECT_TYPE_GEAR_2, 763.578979f, -306.146149f, 26.665222f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) // Pulley || !AddObject(BG_RV_OBJECT_PULLEY_1, BG_RV_OBJECT_TYPE_PULLEY_1, 700.722290f, -283.990662f, 39.517582f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_PULLEY_2, BG_RV_OBJECT_TYPE_PULLEY_2, 826.303833f, -283.996429f, 39.517582f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) // Pilars || !AddObject(BG_RV_OBJECT_PILAR_1, BG_RV_OBJECT_TYPE_PILAR_1, 763.632385f, -306.162384f, 25.909504f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_PILAR_2, BG_RV_OBJECT_TYPE_PILAR_2, 723.644287f, -284.493256f, 24.648525f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_PILAR_3, BG_RV_OBJECT_TYPE_PILAR_3, 763.611145f, -261.856750f, 25.909504f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_PILAR_4, BG_RV_OBJECT_TYPE_PILAR_4, 802.211609f, -284.493256f, 24.648525f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) // Pilars Collision || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_1, BG_RV_OBJECT_TYPE_PILAR_COLLISION_1, 763.632385f, -306.162384f, 30.639660f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_2, BG_RV_OBJECT_TYPE_PILAR_COLLISION_2, 723.644287f, -284.493256f, 32.382710f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_3, BG_RV_OBJECT_TYPE_PILAR_COLLISION_3, 763.611145f, -261.856750f, 30.639660f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_4, BG_RV_OBJECT_TYPE_PILAR_COLLISION_4, 802.211609f, -284.493256f, 32.382710f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)) { LOG_ERROR("sql.sql", "BatteGroundRV: Failed to spawn some object!"); return false; } return true; } void BattlegroundRV::TogglePillarCollision() { // Toggle visual pillars, pulley, gear, and collision based on previous state for (uint8 i = BG_RV_OBJECT_PILAR_1; i <= BG_RV_OBJECT_GEAR_2; ++i) _pillarCollision ? DoorOpen(i) : DoorClose(i); for (uint8 i = BG_RV_OBJECT_PILAR_2; i <= BG_RV_OBJECT_PULLEY_2; ++i) _pillarCollision ? DoorClose(i) : DoorOpen(i); for (uint8 i = BG_RV_OBJECT_PILAR_1; i <= BG_RV_OBJECT_PILAR_COLLISION_4; ++i) { if (GameObject* go = GetBGObject(i)) { if (i >= BG_RV_OBJECT_PILAR_COLLISION_1) { GOState state = ((go->GetGOInfo()->door.startOpen != 0) == _pillarCollision) ? GO_STATE_ACTIVE : GO_STATE_READY; go->SetGoState(state); } for (BattlegroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr) if (Player* player = ObjectAccessor::FindPlayer(itr->first)) go->SendUpdateToPlayer(player); } } _pillarCollision = !_pillarCollision; }
0
0.665013
1
0.665013
game-dev
MEDIA
0.994336
game-dev
0.835968
1
0.835968
rexrainbow/phaser3-rex-notes
3,655
examples/ui-scrollablepanel/resize.js
import phaser from 'phaser/src/phaser.js'; import UIPlugin from '../../templates/ui/ui-plugin.js'; const COLOR_MAIN = 0x4e342e; const COLOR_LIGHT = 0x7b5e57; const COLOR_DARK = 0x260e04; class Demo extends Phaser.Scene { constructor() { super({ key: 'examples' }) } preload() { } create() { var scrollablePanel = this.rexUI.add.scrollablePanel({ x: 400, y: 300, width: 400, height: 400, scrollMode: 0, background: this.rexUI.add.roundRectangle(0, 0, 2, 2, 10, COLOR_MAIN), panel: { child: this.rexUI.add.fixWidthSizer({ space: { left: 3, right: 3, top: 3, bottom: 3, item: 8, line: 8, } }), mask: { padding: 1 }, }, slider: { track: this.rexUI.add.roundRectangle(0, 0, 20, 10, 10, COLOR_DARK), thumb: this.rexUI.add.roundRectangle(0, 0, 0, 0, 13, COLOR_LIGHT), }, space: { left: 10, right: 10, top: 10, bottom: 10, panel: 10, } }) .layout() //.drawBounds(this.add.graphics(), 0xff0000); updatePanel(scrollablePanel, content); // Shrink top-most sizer this.input.once('pointerup', function () { scrollablePanel .setMinSize(250, 220) .layout(); }) } update() { } } var updatePanel = function (panel, content) { var sizer = panel.getElement('panel'); var scene = panel.scene; sizer.clear(true); var lines = content.split('\n'); for (var li = 0, lcnt = lines.length; li < lcnt; li++) { var words = lines[li].split(' '); for (var wi = 0, wcnt = words.length; wi < wcnt; wi++) { sizer.add( scene.add.text(0, 0, words[wi], { fontSize: 18 }) .setInteractive() .on('pointerdown', function () { this.setTint(Phaser.Math.Between(0, 0xffffff)) }) ); } if (li < (lcnt - 1)) { sizer.addNewLine(); } } panel.layout(); return panel; } var content = `Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop and mobile web browsers. Games can be compiled to iOS, Android and native apps by using 3rd party tools. You can use JavaScript or TypeScript for development. Along with the fantastic open source community, Phaser is actively developed and maintained by Photon Storm. As a result of rapid support, and a developer friendly API, Phaser is currently one of the most starred game frameworks on GitHub. Thousands of developers from indie and multi-national digital agencies, and universities worldwide use Phaser. You can take a look at their incredible games.`; var config = { type: Phaser.AUTO, parent: 'phaser-example', width: 800, height: 600, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, }, scene: Demo, plugins: { scene: [{ key: 'rexUI', plugin: UIPlugin, mapping: 'rexUI' }] } }; var game = new Phaser.Game(config);
0
0.778115
1
0.778115
game-dev
MEDIA
0.751482
game-dev,web-frontend
0.915239
1
0.915239
GTNewHorizons/NewHorizonsCoreMod
13,394
src/main/java/com/dreammaster/config/CoreModConfig.java
package com.dreammaster.config; import java.io.File; import com.dreammaster.lib.Refstrings; import com.dreammaster.modfixes.oilgen.OilGeneratorFix; import eu.usrv.yamcore.config.ConfigManager; public class CoreModConfig extends ConfigManager { public CoreModConfig(File pConfigBaseDirectory, String pModCollectionDirectory, String pModID) { super(pConfigBaseDirectory, pModCollectionDirectory, pModID); } public boolean OreDictItems_Enabled; public static boolean ModLoginMessage_Enabled; public boolean gtnhPauseMenuButtons; public static String ModPackVersion = Refstrings.MODPACKPACK_VERSION; public boolean ModHazardousItems_Enabled; public boolean ModDebugVersionDisplay_Enabled; public boolean ModCustomToolTips_Enabled; public boolean ModCustomFuels_Enabled; public boolean ModCustomDrops_Enabled; public boolean ModAdminErrorLogs_Enabled; public boolean ModBabyChest_Enabled; public boolean ForestryStampsAndChunkLoaderCoinsEnabled; public boolean ForestryStampsAndChunkLoaderCoinsServerEnabled; public boolean AvaritiaFixEnabled; public boolean MinetweakerFurnaceFixEnabled; public String[] SkullFireSwordEntityTargets; public String[] BlacklistedTileEntiyClassNames; // Deep Dark void miner configs. public boolean DebugPrintAllOres; public boolean DebugPrintAllWerkstoff; public boolean DebugPrintAddedOres; public boolean DebugPrintWerkstoff; public String[] MaterialWeights; public String[] WerkstoffWeights; public String[] GTPPMaterialWeights; public OilGeneratorFix.OilConfig OilFixConfig; // pollution stuff public int pollutionThresholdAirFilter = 10000; public float globalMultiplicator = 30f; public float scalingFactor = 2.5f; public float bonusByTierT1 = 1f; public float bonusByTierT2 = 1.05f; public float bonusByTierT3 = 1.1f; public int usagesPerAbsorptionFilter = 30; public float boostPerAbsorptionFilter = 2f; @Override protected void PreInit() { ModLoginMessage_Enabled = true; gtnhPauseMenuButtons = true; ModDebugVersionDisplay_Enabled = true; ModHazardousItems_Enabled = false; ModCustomToolTips_Enabled = false; ModCustomFuels_Enabled = false; ModCustomDrops_Enabled = false; ModAdminErrorLogs_Enabled = true; ModBabyChest_Enabled = true; OreDictItems_Enabled = true; ForestryStampsAndChunkLoaderCoinsEnabled = true; ForestryStampsAndChunkLoaderCoinsServerEnabled = false; AvaritiaFixEnabled = false; MinetweakerFurnaceFixEnabled = true; BlacklistedTileEntiyClassNames = new String[] { "com.rwtema.extrautils.tileentity.enderquarry.TileEntityEnderQuarry" }; SkullFireSwordEntityTargets = new String[] { "net.minecraft.entity.monster.EntitySkeleton", "galaxyspace.SolarSystem.planets.venus.entities.EntityEvolvedFireSkeleton", "micdoodle8.mods.galacticraft.core.entities.EntityEvolvedSkeleton" }; DebugPrintAllOres = false; DebugPrintAddedOres = false; MaterialWeights = new String[] {}; WerkstoffWeights = new String[] {}; GTPPMaterialWeights = new String[] {}; pollutionThresholdAirFilter = 10000; } @Override protected void Init() { OreDictItems_Enabled = _mainConfig.getBoolean( "OreDictItems", "Modules", OreDictItems_Enabled, "Set to false to prevent the OreDict register for SpaceStones and SpaceDusts"); ModLoginMessage_Enabled = _mainConfig.getBoolean( "LoginMessage", "Modules", ModLoginMessage_Enabled, "Set to true to show login message with modpack version"); gtnhPauseMenuButtons = _mainConfig.getBoolean( "GTNH Pause menu buttons", "Modules", gtnhPauseMenuButtons, "Set to true to display GTNH buttons in the pause menu"); ModPackVersion = _mainConfig.getString("ModPackVersion", "Modules", ModPackVersion, "Version of the Modpack"); ModDebugVersionDisplay_Enabled = _mainConfig.getBoolean( "DebugVersionDisplay", "Modules", ModDebugVersionDisplay_Enabled, "Set to true to display modpack version on debug GUI (F3)"); ModHazardousItems_Enabled = _mainConfig.getBoolean( "HazardousItems", "Modules", ModHazardousItems_Enabled, "Set to true to enable HazardousItems module. This needs a separate config file which is created once you start with this setting enabled"); ModCustomToolTips_Enabled = _mainConfig.getBoolean( "CustomToolTips", "Modules", ModCustomToolTips_Enabled, "Set to true to enable CustomToolTips module. This needs a separate config file which is created once you start with this setting enabled"); ModCustomDrops_Enabled = _mainConfig.getBoolean( "CustomDrops", "Modules", ModCustomDrops_Enabled, "Set to true to enable CustomDrops module. This needs a separate config file which is created once you start with this setting enabled"); ModCustomFuels_Enabled = _mainConfig.getBoolean( "CustomFuels", "Modules", ModCustomFuels_Enabled, "Set to true to enable CustomFuels module. Allows you to set burn-time values to almost any item"); ModAdminErrorLogs_Enabled = _mainConfig.getBoolean( "AdminErrorLog", "Modules", ModAdminErrorLogs_Enabled, "If set to true, every op/admin will receive all errors occoured during the startup phase as ingame message on join"); ModBabyChest_Enabled = _mainConfig.getBoolean( "BabyChest", "Modules", ModBabyChest_Enabled, "A complete, full working example for a custom chest, with its own renderer for items and blocks, custom sound and a GUI"); ForestryStampsAndChunkLoaderCoinsEnabled = _mainConfig.getBoolean( "ForestryStampsAndChunkLoaderCoinsEnabled", "Modules", ForestryStampsAndChunkLoaderCoinsEnabled, "Enables crafting recipes for Forestry stamps and Chunk Loader Coins. Only works on single player"); ForestryStampsAndChunkLoaderCoinsServerEnabled = _mainConfig.getBoolean( "ForestryStampsAndChunkLoaderCoinsServerEnabled", "Modules", ForestryStampsAndChunkLoaderCoinsServerEnabled, "Enables crafting recipes for Forestry stamps and Chunk Loader Coins on server"); AvaritiaFixEnabled = _mainConfig.getBoolean( "AvaritiaFixEnabled", "ModFixes", AvaritiaFixEnabled, "Set to true to enable the modfix for Avaritia SkullFireSword"); MinetweakerFurnaceFixEnabled = _mainConfig.getBoolean( "MinetweakerFurnaceFixEnabled", "ModFixes", MinetweakerFurnaceFixEnabled, "Set to true to allow Minetweaker to override the vanilla furnace fuel handler, allowing the burn value of WOOD material items to be changed."); SkullFireSwordEntityTargets = _mainConfig.getStringList( "Avaritia_SkullFireSwordEntityTargets", "ModFixes.Avaritia", SkullFireSwordEntityTargets, "The Canonical Class-Name of the Entity"); BlacklistedTileEntiyClassNames = _mainConfig.getStringList( "BlacklistedTileEntiyClassNames", "Modules.Worldaccelerator", BlacklistedTileEntiyClassNames, "The Canonical Class-Names of TileEntities that should be ignored by the WorldAccelerator"); DebugPrintAllOres = _mainConfig.getBoolean( "DebugPrintAllOres", "DeepDarkVoidMiner", DebugPrintAllOres, "Set to true to enable logging of all valid ores. This is useful for debugging, or finding names to add to the weight config."); DebugPrintAddedOres = _mainConfig.getBoolean( "DebugPrintAddedOres", "DeepDarkVoidMiner", DebugPrintAddedOres, "Set to true to enable logging of ores added to the Deep Dark void miner, with weights and metadata IDs. This is useful for debugging."); MaterialWeights = _mainConfig.getStringList( "MaterialWeights", "DeepDarkVoidMiner", MaterialWeights, "List of GregTech material names to adjust weight. Example line: \"Aluminium : 0.3\". Intervening whitespace will be ignored. Use the debug options to get valid names. Use weight <= 0 to disable an ore entirely. Anything not specified in the list will have weight 1. See: gregtech.api.enums.Materials"); WerkstoffWeights = _mainConfig.getStringList( "WerkstoffWeights", "DeepDarkVoidMiner", WerkstoffWeights, "List of BartWorks material names to adjust weight. Example line: \"Bismutite : 0.3\". Intervening whitespace will be ignored. Use the debug options to get valid names. Use weight <= 0 to disable an ore entirely. Anything not specified in the list will have weight 1. See: bartworks.system.material.Werkstoff"); GTPPMaterialWeights = _mainConfig.getStringList( "GTPPMaterialWeights", "DeepDarkVoidMiner", GTPPMaterialWeights, "List of GT++ material names to adjust weight. Example line: \"Cerite : 0.3\". Intervening whitespace will be ignored. Use the debug options to get valid names. Use weight <= 0 to disable an ore entirely. Anything not specified in the list will have weight 1. See: gtPlusPlus.core.material.ORES"); OilFixConfig = new OilGeneratorFix.OilConfig(_mainConfig); pollutionThresholdAirFilter = _mainConfig.getInt( "PollutionThresholdAirFilter", "Pollution", pollutionThresholdAirFilter, 0, Integer.MAX_VALUE, "the threshold of pollution above which the electric air filters will start to work"); globalMultiplicator = _mainConfig.getFloat( "globalMultiplicator", "Pollution", globalMultiplicator, 0, 100, "global multiplicator in this formula: globalMultiplicator * bonusByTier * mufflerAmount * turbineEfficiency * maintenanceEff * Floor(scalingFactor^effectiveTier). This gives the pollution cleaned by the electric air filter per second"); scalingFactor = _mainConfig.getFloat( "scalingFactor", "Pollution", scalingFactor, 0, 100, "scaling factor in this formula: globalMultiplicator * bonusByTier * mufflerAmount * turbineEfficiency * maintenanceEff * Floor(scalingFactor^effectiveTier). This gives the pollution cleaned by the electric air filter per second"); bonusByTierT1 = _mainConfig.getFloat( "bonusByTierT1", "Pollution", bonusByTierT1, 0, 100, "T1 bonus tier in this formula: globalMultiplicator * bonusByTier * mufflerAmount * turbineEfficiency * maintenanceEff * Floor(scalingFactor^effectiveTier). This gives the pollution cleaned by the electric air filter per second"); bonusByTierT2 = _mainConfig.getFloat( "bonusByTierT2", "Pollution", bonusByTierT2, 0, 100, "T2 bonus tier in this formula: globalMultiplicator * bonusByTier * mufflerAmount * turbineEfficiency * maintenanceEff * Floor(scalingFactor^effectiveTier). This gives the pollution cleaned by the electric air filter per second"); bonusByTierT3 = _mainConfig.getFloat( "bonusByTierT3", "Pollution", bonusByTierT3, 0, 100, "T3 bonus tier in this formula: globalMultiplicator * bonusByTier * mufflerAmount * turbineEfficiency * maintenanceEff * Floor(scalingFactor^effectiveTier). This gives the pollution cleaned by the electric air filter per second"); boostPerAbsorptionFilter = _mainConfig.getFloat( "boostPerAbsorptionFilter", "Pollution", boostPerAbsorptionFilter, 1, 100, "boost applied when a filter has been set in the electric air filter."); usagesPerAbsorptionFilter = _mainConfig.getInt( "usagesPerAbsorptionFilter", "Pollution", usagesPerAbsorptionFilter, 1, 100, "Number of usage per absorption filter."); } @Override protected void PostInit() {} }
0
0.905526
1
0.905526
game-dev
MEDIA
0.970976
game-dev
0.771093
1
0.771093
ProjectIgnis/CardScripts
2,451
unofficial/c511027029.lua
--オシリスの天空竜 (TF3) --Slifer the Sky Dragon (TF3) local s,id=GetID() function s.initial_effect(c) --summon with 3 tribute local e1=aux.AddNormalSummonProcedure(c,true,false,3,3) local e2=aux.AddNormalSetProcedure(c) --cannot be target local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e3:SetRange(LOCATION_MZONE) e3:SetValue(1) c:RegisterEffect(e3) --to grave local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(id,0)) e4:SetCategory(CATEGORY_TOGRAVE) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e4:SetRange(LOCATION_MZONE) e4:SetCountLimit(1) e4:SetCode(EVENT_PHASE+PHASE_END) e4:SetCondition(s.tgcon) e4:SetTarget(s.tgtg) e4:SetOperation(s.tgop) c:RegisterEffect(e4) --atk/def local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_SET_ATTACK) e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e5:SetRange(LOCATION_MZONE) e5:SetValue(s.adval) c:RegisterEffect(e5) local e6=e5:Clone() e6:SetCode(EFFECT_SET_DEFENSE) c:RegisterEffect(e6) --destroy local e7=Effect.CreateEffect(c) e7:SetDescription(aux.Stringid(id,1)) e7:SetCategory(CATEGORY_DESTROY) e7:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e7:SetRange(LOCATION_MZONE) e7:SetCode(EVENT_SUMMON_SUCCESS) e7:SetTarget(s.destg) e7:SetOperation(s.desop) c:RegisterEffect(e7) local e8=e7:Clone() e8:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e8) end function s.tgcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsSpecialSummoned() end function s.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,e:GetHandler(),1,0,0) end function s.tgop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.SendtoGrave(c,REASON_EFFECT) end end function s.adval(e,c) return Duel.GetFieldGroupCount(c:GetControler(),LOCATION_HAND,0)*1000 end function s.destg(e,tp,eg,ep,ev,re,r,rp,chk) local tc=eg:GetFirst() if chk==0 then return e:GetHandler():IsRelateToEffect(e) and not tc:IsSummonPlayer(tp) and tc:IsFaceup() and tc:IsDefenseBelow(2000) end Duel.SetTargetCard(tc) Duel.SetOperationInfo(0,CATEGORY_DESTROY,tc,1,0,0) end function s.desop(e,tp,eg,ep,ev,re,r,rp) local tc=eg:GetFirst() if tc and tc:IsRelateToEffect(e) and tc:IsFaceup() and tc:IsDefenseBelow(2000) then Duel.Destroy(tc,REASON_EFFECT) end end
0
0.850627
1
0.850627
game-dev
MEDIA
0.990258
game-dev
0.942009
1
0.942009
chukong/programmers-guide-samples
3,014
cpp/src/chapter9/Chapter9_5.cpp
#include "Chapter9_5.h" #include "Chapter9.h" USING_NS_CC; Scene* Chapter9_5::createScene() { Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto winSize = Director::getInstance()->getWinSize(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // create a scene // 'scene' is an autorelease object // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ auto scene = Scene::create(); // add title auto label = LabelTTF::create("Camera", "Arial", 24); label->setPosition(Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x, Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height).y - 30); scene->addChild(label, -1); //add the menu item for back to main menu label = LabelTTF::create("MainMenu", "Arial", 24); auto menuItem = MenuItemLabel::create(label); menuItem->setCallback([&](cocos2d::Ref *sender) { Director::getInstance()->replaceScene(Chapter9::createScene()); }); auto menu = Menu::create(menuItem, nullptr); menu->setPosition( Vec2::ZERO ); menuItem->setPosition( Vec2(origin.x+visibleSize.width - 80, origin.y + 25) ); scene->addChild(menu, 1); auto layer3D=Layer::create(); scene->addChild(layer3D,2); std::string fileName = "orc.c3b"; auto sprite = Sprite3D::create(fileName); sprite->setScale(5.f); sprite->setRotation3D(Vec3(0,180,0)); sprite->setPosition( Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x, Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).y ); // play animation auto animation = Animation3D::create(fileName); if (animation) { auto animate = Animate3D::create(animation); animate->setSpeed(1); sprite->runAction(RepeatForever::create(animate)); } //add to scene layer3D->addChild(sprite); // add camera auto camera=Camera::createPerspective(60, (GLfloat)winSize.width/winSize.height, 1, 1000); camera->setCameraFlag(CameraFlag::USER1);// set camera flag camera->setPosition3D(Vec3(0, 0, 230) + sprite->getPosition3D()); camera->lookAt(sprite->getPosition3D(), Vec3(0,1,0)); // create camera action auto action = MoveBy::create(3, Vec2(100, 0)); auto action_back = action->reverse(); auto action1 = MoveBy::create(3, Vec2(0, 100)); auto action_back1 = action1->reverse(); auto seq = Sequence::create( action, action_back, action1, action_back1, nullptr ); // run camera action camera->runAction( RepeatForever::create(seq) ); layer3D->addChild(camera); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // set camera mask // when node's camera-mask & camer-flag result is true, the node is visible for this camera. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ layer3D->setCameraMask(0x2); // return the scene return scene; }
0
0.667422
1
0.667422
game-dev
MEDIA
0.752348
game-dev,graphics-rendering
0.669853
1
0.669853
sandsmark/freeaoe
5,285
src/mechanics/Civilization.h
#pragma once #include <genie/dat/Civ.h> #include <genie/dat/TechageEffect.h> #include <genie/dat/Research.h> #include <genie/dat/Unit.h> #include <stdint.h> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "core/Logger.h" #include "core/ResourceMap.h" class Civilization { public: typedef std::shared_ptr<Civilization> Ptr; const static genie::Unit nullUnit; Civilization(const int civId); int id() const { return m_civId; } const std::vector<const genie::Unit *> &creatableUnits(int16_t creator) const; const std::vector<const genie::Tech *> &researchAvailableAt(int16_t creator) const; const genie::Unit &unitData(uint32_t id) const; const genie::Tech &tech(const uint16_t id) const; const std::unordered_map<uint16_t, genie::Tech> &availableTechs() const { return m_techs; } const std::vector<const genie::Unit *> &swappableUnits(const uint16_t taskSwapGroup) const; const ResourceMap &startingResources() const { return m_startingResources; } const std::string &name() const { return m_data.Name; } float startingResource(const genie::ResourceType type) const; void applyTechEffect(const genie::EffectCommand &effect); void enableUnit(const uint16_t id); void applyUnitAttributeModifier(const genie::EffectCommand &effect); // This seems so wrong, but meh void setGaiaOverrideCiv(const int civId); private: void applyData(const genie::Civ &data); void applyUnitAttributeModifier(const genie::EffectCommand &effect, uint32_t unitId); std::unordered_map<int16_t, std::vector<const genie::Unit*>> m_creatableUnits; std::unordered_map<int16_t, std::vector<const genie::Tech*>> m_researchAvailable; std::vector<std::vector<const genie::Unit*>> m_taskSwapUnits; const int m_civId; const genie::Civ &m_data; std::vector<genie::Unit> m_unitsData; std::unordered_map<uint16_t, genie::Tech> m_techs; ResourceMap m_startingResources; }; inline LogPrinter operator <<(LogPrinter os, const genie::EffectCommand::Attributes &type) { const char *separator = os.separator; os.separator = ""; os << "genie::EffectCommand::Attributes::"; switch(type) { case genie::EffectCommand::Attributes::InvalidAttribute: os << "InvalidAttribute"; break; case genie::EffectCommand::Attributes::HitPoints: os << "HitPoints"; break; case genie::EffectCommand::Attributes::LineOfSight: os << "LineOfSight"; break; case genie::EffectCommand::Attributes::GarrisonCapacity: os << "GarrisonCapacity"; break; case genie::EffectCommand::Attributes::UnitSizeX: os << "UnitSizeX"; break; case genie::EffectCommand::Attributes::UnitSizeY: os << "UnitSizeY"; break; case genie::EffectCommand::Attributes::MovementSpeed: os << "MovementSpeed"; break; case genie::EffectCommand::Attributes::RotationSpeed: os << "RotationSpeed"; break; case genie::EffectCommand::Attributes::Armor: os << "Armor"; break; case genie::EffectCommand::Attributes::Attack: os << "Attack"; break; case genie::EffectCommand::Attributes::AttackReloadTime: os << "AttackReloadTime"; break; case genie::EffectCommand::Attributes::AccuracyPercent: os << "AccuracyPercent"; break; case genie::EffectCommand::Attributes::MaxRange: os << "MaxRange"; break; case genie::EffectCommand::Attributes::WorkRate: os << "WorkRate"; break; case genie::EffectCommand::Attributes::CarryCapacity: os << "CarryCapacity"; break; case genie::EffectCommand::Attributes::BaseArmor: os << "BaseArmor"; break; case genie::EffectCommand::Attributes::ProjectileUnit: os << "ProjectileUnit"; break; case genie::EffectCommand::Attributes::IconGraphicsAngle: os << "IconGraphicsAngle"; break; case genie::EffectCommand::Attributes::TerrainDefenseBonus: os << "TerrainDefenseBonus"; break; case genie::EffectCommand::Attributes::EnableSmartProjectiles: os << "EnableSmartProjectiles"; break; case genie::EffectCommand::Attributes::MinRange: os << "MinRange"; break; case genie::EffectCommand::Attributes::MainResourceStorage: os << "MainResourceStorage"; break; case genie::EffectCommand::Attributes::BlastWidth: os << "BlastWidth"; break; case genie::EffectCommand::Attributes::SearchRadius: os << "SearchRadius"; break; case genie::EffectCommand::Attributes::ResourceCosts: os << "ResourceCosts"; break; case genie::EffectCommand::Attributes::TrainTime: os << "TrainTime"; break; case genie::EffectCommand::Attributes::TotalMissiles: os << "TotalMissiles"; break; case genie::EffectCommand::Attributes::FoodCosts: os << "FoodCosts"; break; case genie::EffectCommand::Attributes::WoodCosts: os << "WoodCosts"; break; case genie::EffectCommand::Attributes::GoldCosts: os << "GoldCosts"; break; case genie::EffectCommand::Attributes::StoneCosts: os << "StoneCosts"; break; case genie::EffectCommand::Attributes::MaxTotalMissiles: os << "MaxTotalMissiles"; break; case genie::EffectCommand::Attributes::GarrisonHealRate: os << "GarrisonHealRate"; break; case genie::EffectCommand::Attributes::RegenerationRate: os << "RegenerationRate"; break; default: os << "Invalid"; break; } os << separator; os.separator = separator; return os; }
0
0.920016
1
0.920016
game-dev
MEDIA
0.758092
game-dev
0.920726
1
0.920726
ellermister/MapleStory
2,522
scripts/npc/9201124.js
var status; function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == 1) { status++; }else{ status--; } if (status == 0) { if (cm.getPlayer().getJob() == 0) { cm.sendNext("Welcome, Beginning Explorer! In Maple Story,you can\r\nchoose a #rjob#k when you reach #rLv 10#k (Lv 8 for Magicians).\r\n\r\nIn other words, you'll be choosing your own future path!\r\nWhen you get a job,you get to use various skills and magic nwhice will make your experience in Maple Story more enjoyable.So,work hard to carve your own destiny"); } else { cm.sendOk("It looks like you've already made a job advancement!\r\nTransportation can only be used by beginners"); cm.dispose(); } } else if (status == 1) { cm.sendNextPrev("My role is to help you become a #rBowman.#k\r\n\r\nBowmen specialize in Long-Ranged Attacks from the back of the battle lines, since they are deft but have limited Strength. Bowmen become stronger as they level up, employing various attack skills that make them particularly effective with long-ranged Attacks. They aare also very capable hunters who can take advantage of the topography."); } else if (status == 2) { cm.sendNextPrev("Weapons used include the #bBow#k and #bCrossbow#k\r\n\r\nRequired Level: #rOver Lv 10#k\r\nLocation: #rBowman Instrustional School#k in #bHenesys#k\r\nJob Instructor: #rAthena Pierce#k"); } else if (status == 3) { cm.sendSimple("Would you like to become a #rBowman?#k\r\n#b#L0#Yes#l\r\n#L1#No#l#k"); } else if (status == 4) { if (selection == 0) { cm.sendSimple("In order to make the job advancement, you must visit #rAthena Pierce#k at the #rBowman Instrustional School#k in #bHenesys#k.Would you like to be trasported there now?-The transportation service cannot be used once you make the job advancement-\r\n\r\n#b#L0#Yes#l\r\n#L1#No#l#k"); } else if (selection == 1) { cm.sendNext("Please talk to me again if you have any questions."); cm.dispose(); } } else if (status == 5) { if (selection == 0) { cm.sendNext("Alright.I will now take you to the #rBowman Instrustional School#k in #bHenesys.#k"); } else if (selection == 1) { cm.sendNext("Please talk to me again if you have any questions."); cm.dispose(); } } else if (status == 6) { cm.warp(100000201, 11); cm.dispose(); } }
0
0.617628
1
0.617628
game-dev
MEDIA
0.821553
game-dev
0.700872
1
0.700872
OpenSilver/OpenSilver
14,855
src/Runtime/Runtime/System.Windows.Data/BindingExpressionBase.cs
 /*=================================================================================== * * Copyright (c) Userware/OpenSilver.net * * This file is part of the OpenSilver Runtime (https://opensilver.net), which is * licensed under the MIT license: https://opensource.org/licenses/MIT * * As stated in the MIT license, "the above copyright notice and this permission * notice shall be included in all copies or substantial portions of the Software." * \*====================================================================================*/ using System.Diagnostics; using System.Windows.Input; using OpenSilver.Internal; using OpenSilver.Internal.Data; namespace System.Windows.Data; public abstract class BindingExpressionBase : Expression { [Flags] internal enum PrivateFlags { iSourceToTarget = 0x00000001, iTargetToSource = 0x00000002, iPropDefault = 0x00000004, iInTransfer = 0x00000008, iInUpdate = 0x00000010, iNeedDataTransfer = 0x00000020, // used by MultiBindingExpression iTransferDeferred = 0x00000040, // used by MultiBindingExpression iUpdateOnLostFocus = 0x00000080, iUpdateExplicitly = 0x00000100, iUpdateOnPropertyChanged = 0x00000200, iUpdateDefault = iUpdateExplicitly | iUpdateOnLostFocus | iUpdateOnPropertyChanged, iNeedsUpdate = 0x00000400, iDetaching = 0x00000800, iInMultiBindingExpression = 0x00001000, iNotifyOnValidationError = 0x00002000, iAttaching = 0x00004000, iValidatesOnExceptions = 0x00008000, iValidatesOnDataErrors = 0x00010000, iValidatesOnNotifyDataErrors = 0x00020000, iPropagationMask = iSourceToTarget | iTargetToSource | iPropDefault, iUpdateMask = iUpdateOnPropertyChanged | iUpdateOnLostFocus | iUpdateExplicitly, } /// <summary> /// NoTarget DependencyProperty, a placeholder used by BindingExpressions with no target property /// </summary> internal static readonly DependencyProperty NoTargetProperty = DependencyProperty.RegisterAttached( "NoTarget", typeof(object), typeof(BindingExpressionBase), null); /// <summary> Sentinel meaning "field has its default value" </summary> internal static readonly object DefaultValueObject = new NamedObject("DefaultValue"); private PrivateFlags _flags; private PrivateFlags _defaultFlags; private PropertyChangeListener _targetPropertyListener; internal BindingExpressionBase(BindingBase binding, BindingExpressionBase parent) { ParentBindingBase = binding; ParentBindingExpressionBase = parent; _flags = (PrivateFlags)binding.Flags; } /// <summary> /// Gets the <see cref="BindingBase"/> object from which this <see cref="BindingExpressionBase"/> object is created. /// </summary> /// <returns> /// The <see cref="BindingBase"/> object from which this <see cref="BindingExpressionBase"/> object is created. /// </returns> internal BindingBase ParentBindingBase { get; } /// <summary> /// Gets the element that is the binding target object of this binding expression. /// </summary> /// <returns> /// The element that is the binding target object of this binding expression. /// </returns> internal DependencyObject Target { get; private set; } /// <summary> /// Gets the binding target property of this binding expression. /// </summary> /// <returns> /// The binding target property of this binding expression. /// </returns> internal DependencyProperty TargetProperty { get; private set; } /// <summary> The parent MultiBindingExpression (if any) </summary> internal BindingExpressionBase ParentBindingExpressionBase { get; } /// <summary> The default value of the target property </summary> internal object DefaultValue => TargetProperty.GetDefaultValue(Target); /// <summary> True if this binding expression is attaching </summary> internal bool IsAttaching { get => TestFlag(PrivateFlags.iAttaching); private set => ChangeFlag(PrivateFlags.iAttaching, value); } /// <summary> True if this binding expression is detaching </summary> internal bool IsDetaching { get => TestFlag(PrivateFlags.iDetaching); private set => ChangeFlag(PrivateFlags.iDetaching, value); } /// <summary> True if this binding expression updates the target </summary> internal bool IsDynamic => TestFlag(PrivateFlags.iSourceToTarget) && (!IsInMultiBindingExpression || ParentBindingExpressionBase.IsDynamic); /// <summary> True if this binding expression updates the source </summary> internal bool IsReflective => TestFlag(PrivateFlags.iTargetToSource) && (!IsInMultiBindingExpression || ParentBindingExpressionBase.IsReflective); /// <summary> True if this binding expression updates on PropertyChanged </summary> internal bool IsUpdateOnPropertyChanged => TestFlag(PrivateFlags.iUpdateOnPropertyChanged); /// <summary> True if this binding expression updates on LostFocus </summary> internal bool IsUpdateOnLostFocus => TestFlag(PrivateFlags.iUpdateOnLostFocus); /// <summary> True if this binding expression is deferring a target update </summary> internal bool TransferIsDeferred { get => TestFlag(PrivateFlags.iTransferDeferred); set => ChangeFlag(PrivateFlags.iTransferDeferred, value); } /// <summary> True if this binding expression is updating the target </summary> internal bool IsInTransfer { get => TestFlag(PrivateFlags.iInTransfer); set => ChangeFlag(PrivateFlags.iInTransfer, value); } /// <summary> True if this binding expression is updating the source </summary> internal bool IsInUpdate { get => TestFlag(PrivateFlags.iInUpdate); set => ChangeFlag(PrivateFlags.iInUpdate, value); } /// <summary> True if this binding expression has a pending target update </summary> internal bool NeedsDataTransfer { get => TestFlag(PrivateFlags.iNeedDataTransfer); set => ChangeFlag(PrivateFlags.iNeedDataTransfer, value); } /// <summary> True if this binding expression has a pending source update </summary> internal bool NeedsUpdate { get => TestFlag(PrivateFlags.iNeedsUpdate); set => ChangeFlag(PrivateFlags.iNeedsUpdate, value); } /// <summary> True if this binding expression belongs to a MultiBinding </summary> internal bool IsInMultiBindingExpression { get => TestFlag(PrivateFlags.iInMultiBindingExpression); set => ChangeFlag(PrivateFlags.iInMultiBindingExpression, value); } /// <summary> True if this binding expression belongs to a PriorityBinding or MultiBinding </summary> internal bool IsInBindingExpressionCollection => TestFlag(PrivateFlags.iInMultiBindingExpression); /// <summary> True if this binding expression validates on exceptions </summary> internal bool ValidatesOnExceptions => TestFlag(PrivateFlags.iValidatesOnExceptions); /// <summary> True if this binding expression validates on data errors </summary> internal bool ValidatesOnDataErrors => TestFlag(PrivateFlags.iValidatesOnDataErrors); /// <summary> True if this binding expression validates on notify data errors </summary> internal bool ValidatesOnNotifyDataErrors => TestFlag(PrivateFlags.iValidatesOnNotifyDataErrors); /// <summary> /// Invalidate the given child expression. /// </summary> internal abstract void InvalidateChild(BindingExpressionBase bindingExpression); // transfer a value from the source to the target internal void Invalidate() { // don't invalidate during Attach. The property engine does it already. if (IsAttaching) return; Target.ApplyExpression(TargetProperty, this); } internal sealed override void OnAttach(DependencyObject d, DependencyProperty dp) => Attach(d, dp); internal void Attach(DependencyObject d, DependencyProperty dp) { IsAttaching = true; AttachOverride(d, dp); IsAttaching = false; } /// <summary> /// Attach the binding expression to the given target object and property. /// Derived classes should call base.AttachOverride before doing their work, /// and should continue only if it returns true. /// </summary> internal virtual void AttachOverride(DependencyObject d, DependencyProperty dp) { Target = d; TargetProperty = dp; DetermineEffectiveValidatesOnNotifyDataErrors(); // Listen to changes on the Target if the Binding is TwoWay: if (IsReflective && IsUpdateOnPropertyChanged) { if (IsUpdateOnLostFocus && Target is UIElement uie) { uie.LostFocus += new RoutedEventHandler(OnTargetLostFocus); } _targetPropertyListener = PropertyChangeListener.CreateListener(Target, TargetProperty, OnTargetPropertyChanged); } } internal sealed override void OnDetach(DependencyObject d, DependencyProperty dp) => Detach(); internal void Detach() { IsDetaching = true; DetachOverride(); IsDetaching = false; } /// <summary> /// Detach the binding expression from its target object and property. /// Derived classes should call base.DetachOverride after doing their work. /// </summary> internal virtual void DetachOverride() { if (_targetPropertyListener != null) { _targetPropertyListener.Dispose(); _targetPropertyListener = null; } if (IsUpdateOnLostFocus && Target is UIElement uie) { uie.LostFocus -= new RoutedEventHandler(OnTargetLostFocus); } Target = null; TargetProperty = null; _flags = _defaultFlags; } private void OnTargetLostFocus(object sender, RoutedEventArgs e) => Update(); private void OnTargetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs args) { if (IsInTransfer || IsInUpdate) { return; } NeedsUpdate = true; if (IsUpdateOnLostFocus && ReferenceEquals(FocusManager.GetFocusedElement(), Target)) { return; } Update(); } internal virtual void Update() { } // Return the object from which the given value was obtained, if possible internal abstract object GetSourceItem(object newValue); /// <summary> /// Create a format that is suitable for String.Format /// </summary> internal string GetEffectiveStringFormat() { if (ParentBindingBase.StringFormat is not string stringFormat) { return null; } if (stringFormat.IndexOf('{') < 0) { stringFormat = @"{0:" + stringFormat + @"}"; } return stringFormat; } internal static void HandleException(Exception ex) { if (Application.Current.Host.Settings.EnableBindingErrorsLogging) { Debug.WriteLine(ex.ToString()); } if (Application.Current.Host.Settings.EnableBindingErrorsThrowing) { throw ex; } } /// <summary> Begin a source update </summary> internal void BeginSourceUpdate() => ChangeFlag(PrivateFlags.iInUpdate, true); /// <summary> End a source update </summary> internal void EndSourceUpdate() => ChangeFlag(PrivateFlags.iInUpdate | PrivateFlags.iNeedsUpdate, false); internal void ResolvePropertyDefaultSettings(BindingMode mode, UpdateSourceTrigger updateTrigger, FrameworkPropertyMetadata fwMetaData) { // resolve "property-default" dataflow if (mode == BindingMode.Default) { PrivateFlags f = PrivateFlags.iSourceToTarget; if (fwMetaData is not null && fwMetaData.BindsTwoWayByDefault) { f = PrivateFlags.iSourceToTarget | PrivateFlags.iTargetToSource; } ChangeFlag(PrivateFlags.iPropagationMask, false); ChangeFlag(f, true); } Debug.Assert((_flags & PrivateFlags.iPropagationMask) != PrivateFlags.iPropDefault, "BindingExpression should not have Default propagation"); // resolve "property-default" update trigger if (updateTrigger == UpdateSourceTrigger.Default) { UpdateSourceTrigger ust = GetDefaultUpdateSourceTrigger(fwMetaData); SetUpdateSourceTrigger(ust); } Debug.Assert((_flags & PrivateFlags.iUpdateMask) != PrivateFlags.iUpdateDefault, "BindingExpression should not have Default update trigger"); } // return the effective update trigger, used when binding doesn't set one explicitly private UpdateSourceTrigger GetDefaultUpdateSourceTrigger(FrameworkPropertyMetadata fwMetaData) { if (IsInMultiBindingExpression) { return UpdateSourceTrigger.Explicit; } return fwMetaData?.DefaultUpdateSourceTrigger ?? UpdateSourceTrigger.PropertyChanged; } private void SetUpdateSourceTrigger(UpdateSourceTrigger ust) { ChangeFlag(PrivateFlags.iUpdateMask, false); ChangeFlag((PrivateFlags)BindingBase.FlagsFrom(ust), true); } internal void SaveDefaultFlags() => _defaultFlags = _flags; internal Type GetEffectiveTargetType() { Type targetType = TargetProperty.PropertyType; BindingExpressionBase be = ParentBindingExpressionBase; while (be is not null) { if (be is MultiBindingExpression) { // for descendants of a MultiBinding, the effective target // type is Object. targetType = typeof(object); break; } be = be.ParentBindingExpressionBase; } return targetType; } private void DetermineEffectiveValidatesOnNotifyDataErrors() { bool result = ParentBindingBase.ValidatesOnNotifyDataErrorsInternal; BindingExpressionBase beb = ParentBindingExpressionBase; while (result && beb is not null) { result = beb.ValidatesOnNotifyDataErrors; beb = beb.ParentBindingExpressionBase; } ChangeFlag(PrivateFlags.iValidatesOnNotifyDataErrors, result); } private bool TestFlag(PrivateFlags flag) => (_flags & flag) != 0; private void ChangeFlag(PrivateFlags flag, bool value) { if (value) { _flags |= flag; } else { _flags &= ~flag; } } }
0
0.864876
1
0.864876
game-dev
MEDIA
0.261375
game-dev
0.904267
1
0.904267
Raven-APlus/RavenAPlus
2,076
src/main/java/keystrokesmod/module/impl/combat/velocity/MatrixVelocity.java
package keystrokesmod.module.impl.combat.velocity; import keystrokesmod.event.PostVelocityEvent; import keystrokesmod.module.impl.combat.Velocity; import keystrokesmod.module.setting.impl.ButtonSetting; import keystrokesmod.module.setting.impl.SubMode; import keystrokesmod.utility.Utils; import net.minecraft.entity.EntityLivingBase; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.jetbrains.annotations.NotNull; public class MatrixVelocity extends SubMode<Velocity> { private final ButtonSetting debug; private boolean reduced = false; public MatrixVelocity(String name, @NotNull Velocity parent) { super(name, parent); this.registerSetting(debug = new ButtonSetting("Debug", false)); } @Override public void onEnable() { reduced = false; } @SubscribeEvent public void onPostVelocity(PostVelocityEvent event) { reduced = false; } @SubscribeEvent public void onAttack(@NotNull AttackEntityEvent event) { if (event.target instanceof EntityLivingBase && mc.thePlayer.hurtTime > 0) { if (reduced) return; if (mc.thePlayer.isSprinting()) { final double motionX = mc.thePlayer.motionX; final double motionZ = mc.thePlayer.motionZ; if (Math.abs(motionX) < 0.625 && Math.abs(motionZ) < 0.625) { mc.thePlayer.motionX = motionX * 0.4; mc.thePlayer.motionZ = motionZ * 0.4; } else if (Math.abs(motionX) < 1.25 && Math.abs(motionZ) < 1.25) { mc.thePlayer.motionX = motionX * 0.67; mc.thePlayer.motionZ = motionZ * 0.67; } mc.thePlayer.setSprinting(false); if (debug.isToggled()) Utils.sendMessage(String.format("reduced %.2f %.2f", motionX - mc.thePlayer.motionX, motionZ - mc.thePlayer.motionZ)); } reduced = true; } } }
0
0.620566
1
0.620566
game-dev
MEDIA
0.765919
game-dev
0.895823
1
0.895823
Lexxie9952/fcw.org-server
5,877
freeciv/freeciv/common/idex.c
/*********************************************************************** Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold 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, 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. ***********************************************************************/ /*********************************************************************** idex = ident index: a lookup table for quick mapping of unit and city id values to unit and city pointers. Method: use separate hash tables for each type. Means code duplication for city/unit cases, but simplicity advantages. Don't have to manage memory at all: store pointers to unit and city structs allocated elsewhere, and keys are pointers to id values inside the structs. Note id values should probably be unsigned int: here leave as plain int so can use pointers to pcity->id etc. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include <fc_config.h> #endif /* utility */ #include "log.h" /* common */ #include "city.h" #include "unit.h" #include "idex.h" /**********************************************************************//** Initialize. Should call this at the start before use. **************************************************************************/ void idex_init(struct world *iworld) { iworld->cities = city_hash_new(); iworld->units = unit_hash_new(); } /**********************************************************************//** Free the hashs. **************************************************************************/ void idex_free(struct world *iworld) { city_hash_destroy(iworld->cities); iworld->cities = NULL; unit_hash_destroy(iworld->units); iworld->units = NULL; } /**********************************************************************//** Register a city into idex, with current pcity->id. Call this when pcity created. **************************************************************************/ void idex_register_city(struct world *iworld, struct city *pcity) { struct city *old; city_hash_replace_full(iworld->cities, pcity->id, pcity, NULL, &old); fc_assert_ret_msg(NULL == old, "IDEX: city collision: new %d %p %s, old %d %p %s", pcity->id, (void *) pcity, city_name_get(pcity), old->id, (void *) old, city_name_get(old)); } /**********************************************************************//** Register a unit into idex, with current punit->id. Call this when punit created. **************************************************************************/ void idex_register_unit(struct world *iworld, struct unit *punit) { struct unit *old; unit_hash_replace_full(iworld->units, punit->id, punit, NULL, &old); fc_assert_ret_msg(NULL == old, "IDEX: unit collision: new %d %p %s, old %d %p %s", punit->id, (void *) punit, unit_rule_name(punit), old->id, (void *) old, unit_rule_name(old)); } /**********************************************************************//** Remove a city from idex, with current pcity->id. Call this when pcity deleted. **************************************************************************/ void idex_unregister_city(struct world *iworld, struct city *pcity) { struct city *old; city_hash_remove_full(iworld->cities, pcity->id, NULL, &old); fc_assert_ret_msg(NULL != old, "IDEX: city unreg missing: %d %p %s", pcity->id, (void *) pcity, city_name_get(pcity)); fc_assert_ret_msg(old == pcity, "IDEX: city unreg mismatch: " "unreg %d %p %s, old %d %p %s", pcity->id, (void *) pcity, city_name_get(pcity), old->id, (void *) old, city_name_get(old)); } /**********************************************************************//** Remove a unit from idex, with current punit->id. Call this when punit deleted. **************************************************************************/ void idex_unregister_unit(struct world *iworld, struct unit *punit) { struct unit *old; unit_hash_remove_full(iworld->units, punit->id, NULL, &old); fc_assert_ret_msg(NULL != old, "IDEX: unit unreg missing: %d %p %s", punit->id, (void *) punit, unit_rule_name(punit)); fc_assert_ret_msg(old == punit, "IDEX: unit unreg mismatch: " "unreg %d %p %s, old %d %p %s", punit->id, (void *) punit, unit_rule_name(punit), old->id, (void*) old, unit_rule_name(old)); } /**********************************************************************//** Lookup city with given id. Returns NULL if the city is not registered (which is not an error). **************************************************************************/ struct city *idex_lookup_city(struct world *iworld, int id) { struct city *pcity; city_hash_lookup(iworld->cities, id, &pcity); return pcity; } /**********************************************************************//** Lookup unit with given id. Returns NULL if the unit is not registered (which is not an error). **************************************************************************/ struct unit *idex_lookup_unit(struct world *iworld, int id) { struct unit *punit; unit_hash_lookup(iworld->units, id, &punit); return punit; }
0
0.730684
1
0.730684
game-dev
MEDIA
0.756767
game-dev
0.744919
1
0.744919
Swarmops/Swarmops
3,424
Boneyard/Site5/Controls/v5/Swarm/TreePositions.ascx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Swarmops.Common.Enums; namespace Swarmops.Frontend.Controls.v5.Swarm { public partial class TreePositions : ControlV5Base { protected void Page_Init (object sender, EventArgs e) { // Request control framework in Init - the Load is too late for child controls ((PageV5Base) this.Page).RegisterControl (EasyUIControl.Tree | EasyUIControl.DataGrid); } protected void Page_Load (object sender, EventArgs e) { Localize(); this.DropPerson.Placeholder = Resources.Global.Swarm_TypeName; } private void Localize() { this.LiteralHeaderAction.Text = Resources.Global.Global_Action; this.LiteralHeaderName.Text = Resources.Global.Swarm_AssignedPerson; this.LiteralHeaderPosition.Text = Resources.Global.Swarm_Position; this.LiteralHeaderExpires.Text = Resources.Controls.Swarm.Positions_AssignmentExpires; this.LiteralHeaderMinMax.Text = Resources.Global.Global_MinMax; this.LabelAssignPersonTo.Text = Resources.Controls.Swarm.Positions_AssignPersonToPosition; this.LabelAssignmentDuration.Text = Resources.Controls.Swarm.Positions_AssignmentDuration; this.LabelModalHeader.Text = String.Format (Resources.Controls.Swarm.Positions_ModalHeader, this.ClientID); this.LiteralButtonAssign.Text = Resources.Controls.Swarm.Positions_ButtonAssign; // Wrongly flagged red-error by Resharper; this assignment is legit this.DropDuration.Items.Add (new ListItem(Resources.Global.Timespan_Selection_OneMonth, "1")); this.DropDuration.Items.Add(new ListItem(Resources.Global.Timespan_Selection_TwoMonths, "2")); this.DropDuration.Items.Add(new ListItem(Resources.Global.Timespan_Selection_ThreeMonths, "3")); this.DropDuration.Items.Add(new ListItem(Resources.Global.Timespan_Selection_SixMonths, "6")); this.DropDuration.Items.Add(new ListItem(Resources.Global.Timespan_Selection_OneYear, "12")); this.DropDuration.Items.Add(new ListItem(Resources.Global.Timespan_Selection_TwoYears, "24")); this.DropDuration.Items.Add(new ListItem(Resources.Global.Timespan_Selection_UntilTermination, "-1")); this.LiteralTerminateNo.Text = JavascriptEscape (Resources.Controls.Swarm.Positions_TerminateNo); this.LiteralTerminateYes.Text = JavascriptEscape (Resources.Controls.Swarm.Positions_TerminateYes); this.LiteralTerminateSelfNo.Text = JavascriptEscape (Resources.Controls.Swarm.Positions_TerminateSelfNo); this.LiteralTerminateSelfYes.Text = JavascriptEscape (Resources.Controls.Swarm.Positions_TerminateSelfYes); this.LiteralConfirmTermination.Text = JavascriptEscape (Resources.Controls.Swarm.Positions_ConfirmTerminate); this.LiteralConfirmSelfTermination.Text = JavascriptEscape (Resources.Controls.Swarm.Positions_ConfirmSelfTerminate); this.DropDuration.SelectedValue = "12"; } public PositionLevel Level { get; set; } public int OrganizationId { get; set; } public int GeographyId { get; set; } public string Cookie { get; set; } } }
0
0.876083
1
0.876083
game-dev
MEDIA
0.319269
game-dev
0.930122
1
0.930122
okaychen/RetroSnake
9,471
js/snake.js
/** * snake.js * @author okaychen * @description * @created Fri Dec 01 2017 11:24:41 GMT+0800 (中国标准时间) * @copyright None * None * @last-modified Fri Dec 01 2017 17:08:44 GMT+0800 (中国标准时间) */ (function () { // Canvas & Context var canvas; var ctx; // Snake var snake; var snake_dir; var snake_next_dir; var snake_speed; // Food var food = { x: 0, y: 0 }; // score var score; // wall var wall; // HTML Elements var screen_snake; var screen_menu; var screen_settings; var screen_gameover; var button_newgame_menu; var button_newgame_settings; var button_newgame_gameover; var button_setting_menu; var button_setting_gameover; var ele_score; var speed_setting; var wall_setting; /*-------------*/ var activeDot = function (x, y) { ctx.fillStyle = "#eee"; ctx.fillRect(x * 10, y * 10, 10, 10); } // changer dir var changeDir = function (key) { if (key == 38 && snake_dir != 2) { snake_next_dir = 0; } else { if (key == 39 && snake_dir != 3) { snake_next_dir = 1; } else { if (key == 40 && snake_dir != 0) { snake_next_dir = 2; } else { if (key == 37 && snake_dir != 1) { snake_next_dir = 3; } } } } } // add food var addFood = function () { food.x = Math.floor(Math.random() * ((canvas.width / 10) - 1)); food.y = Math.floor(Math.random() * ((canvas.height / 10) - 1)); for (var i = 0; i < snake.length; i++) { // 如果食物被吃就增加食物 if (checkBlock(food.x, food.y, snake[i].x, snake[i].y)) { addFood(); } } } var checkBlock = function (x, y, _x, _y) { return (x == _x && y == _y) ? true : false; } //////////////////////////////////////////// var altScore = function (score_val) { ele_score.innerHTML = String(score_val); } //////////////////////////////////////////// var mainLoop = function () { var _x = snake[0].x; var _y = snake[0].y; snake_dir = snake_next_dir; // 0 — up 1 — right 2 — down 3 — left switch (snake_dir) { case 0: _y--; break; case 1: _x++; break; case 2: _y++; break; case 3: _x--; break; } snake.pop(); snake.unshift({ x: _x, y: _y }) // --wall if (wall == 1) { if (snake[0].x < 0 || snake[0].x == canvas.width / 10 || snake[0].y < 0 || snake[0].y == canvas.height / 10) { showScreen(3); return; } } else { // off 无墙 for (var i = 0, x = snake.length; i < x; i++) { if (snake[i].x < 0) { snake[i].x = snake[i].x + (canvas.width / 10); } if (snake[i].x == canvas.width / 10) { snake[i].x = snake[i].x - (canvas.width / 10); } if (snake[i].y < 0) { snake[i].y = snake[i].y + (canvas.height / 10); } if (snake[i].y == canvas.height / 10) { snake[i].y = snake[i].y - (canvas.height / 10); } } } // Autophagy death for (var i = 1; i < snake.length; i++) { if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) { showScreen(3); return; } } // Eat food if (checkBlock(snake[0].x, snake[0].y, food.x, food.y)) { snake[snake.length] = { x: snake[0].x, y: snake[0].y }; score += 1; altScore(score); addFood(); activeDot(food.x, food.y); } // -------------------- ctx.beginPath(); ctx.fillStyle = "#111"; ctx.fillRect(0, 0, canvas.width, canvas.height); // -------------------- for (var i = 0; i < snake.length; i++) { activeDot(snake[i].x, snake[i].y); } // -------------------- activeDot(food.x, food.y); setTimeout(mainLoop, snake_speed); } var newGame = function () { showScreen(0); screen_snake.focus(); snake = []; for (var i = 4; i >= 0; i--) { snake.push({ x: i, y: 15 }); } snake_next_dir = 1; score = 0; altScore(score); addFood(); canvas.onkeydown = function (evt) { evt = evt || window.event; changeDir(evt.keyCode); } mainLoop(); } // Change the snake speed... // 150 = slow // 100 = normal // 50 = fast var setSnakeSpeed = function (speed_value) { snake_speed = speed_value; } //////////////////////////////////////////// var setWall = function (wall_value) { wall = wall_value; if (wall == 0) { screen_snake.style.borderColor = '#606060'; } if (wall == 1) { screen_snake.style.borderColor = '#FFF'; } } // 0 show the game (canvas) // 1 show the main menu // 2 show the settings menu // 3 show the gameover menu var showScreen = function (screen_opt) { switch (screen_opt) { case 0: screen_snake.style.display = "block"; screen_menu.style.display = "none"; screen_settings.style.display = "none"; screen_gameover.style.display = "none"; break; case 1: screen_snake.style.display = "none"; screen_menu.style.display = "block"; screen_settings.style.display = "none"; screen_gameover.style.display = "none"; break; case 2: screen_snake.style.display = "none"; screen_menu.style.display = "none"; screen_settings.style.display = "block"; screen_gameover.style.display = "none"; break; case 3: screen_snake.style.display = "none"; screen_menu.style.display = "none"; screen_settings.style.display = "none"; screen_gameover.style.display = "block"; break; } } window.onload = function () { canvas = document.getElementById('snake'); ctx = canvas.getContext('2d'); // Screen screen_snake = document.getElementById('snake'); screen_menu = document.getElementById('menu'); screen_gameover = document.getElementById('gameOver'); screen_settings = document.getElementById('settings'); // Buttons button_newgame_menu = document.getElementById('newgame_menu'); button_newgame_setting = document.getElementById('newgame_setting'); button_newgame_gameover = document.getElementById('newgame_gameOver'); button_setting_menu = document.getElementById('setting_menu'); button_setting_gameover = document.getElementById('setting_gameOver'); // etc ele_score = document.getElementById('score_value'); speed_setting = document.getElementsByName('speed'); wall_setting = document.getElementsByName('wall'); // ------------- button_newgame_menu.onclick = function () { newGame(); }; button_newgame_gameover.onclick = function () { newGame(); }; button_newgame_setting.onclick = function () { newGame(); }; button_setting_menu.onclick = function () { showScreen(2); }; button_setting_gameover.onclick = function () { showScreen(2) }; setSnakeSpeed(150); setWall(1); showScreen("menu"); // -------------------- // Settings // speed for (var i = 0; i < speed_setting.length; i++) { speed_setting[i].addEventListener("click", function () { for (var i = 0; i < speed_setting.length; i++) { if (speed_setting[i].checked) { setSnakeSpeed(speed_setting[i].value); } } }); } // wall for (var i = 0; i < wall_setting.length; i++) { wall_setting[i].addEventListener("click", function () { for (var i = 0; i < wall_setting.length; i++) { if (wall_setting[i].checked) { setWall(wall_setting[i].value); } } }); } document.onkeydown = function (evt) { if (screen_gameover.style.display == "block") { evt = evt || window.event; if (evt.keyCode == 32) { newGame(); } } } } })()
0
0.578901
1
0.578901
game-dev
MEDIA
0.77302
game-dev
0.81032
1
0.81032
EasyFarm/EasyFarm
3,000
EasyFarm/Infrastructure/ViewModelBase.cs
// /////////////////////////////////////////////////////////////////// // This file is a part of EasyFarm for Final Fantasy XI // Copyright (C) 2013 Mykezero // // EasyFarm 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. // // EasyFarm 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 // If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////// using System; using System.IO; using EasyFarm.Classes; using EasyFarm.Parsing; using EasyFarm.Persistence; using EasyFarm.States; using EasyFarm.UserSettings; using MemoryAPI; namespace EasyFarm.Infrastructure { public class ViewModelBase : GalaSoft.MvvmLight.ViewModelBase, IViewModel { /// <summary> /// Global game engine controlling the player. /// </summary> protected static GameEngine GameEngine { get; set; } /// <summary> /// Solo EliteApi instance for current player. /// </summary> public static IMemoryAPI FFACE { get; set; } /// <summary> /// View Model name for header in tab control item. /// </summary> public string ViewName { get; set; } /// <summary> /// Path record to let users record waypoint paths /// </summary> protected static PathRecorder PathRecorder { get; set; } public static AbilityService AbilityService { get; set; } = new AbilityService(null); /// <summary> /// Set up session from given EliteApi session. /// </summary> /// <param name="fface"></param> public static void SetSession(IMemoryAPI fface) { if (fface == null) return; // Save EliteApi Write FFACE = fface; // Create a new game engine to control our character. GameEngine = new GameEngine(FFACE); // Create path record for navigation PathRecorder = new PathRecorder(FFACE); AbilityService = new AbilityService(FFACE); AutoLoadSettings(); } private static void AutoLoadSettings() { var persister = new Persister(); var characterName = FFACE?.Player?.Name; var fileName = $"{characterName}.eup"; if (String.IsNullOrWhiteSpace(fileName)) return; if (!File.Exists(fileName)) return; var config = persister.Deserialize<Config>(fileName); Config.Instance = config; AppServices.SendConfigLoaded(); } } }
0
0.900698
1
0.900698
game-dev
MEDIA
0.804623
game-dev
0.844045
1
0.844045
3dfxdev/EDGE
15,542
zdbsp/nodebuild_extract.cc
/* Routines for extracting usable data from the new BSP tree. Copyright (C) 2002-2006 Randy Heit 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <string.h> #include <stdio.h> #include <float.h> #include "zdbsp.h" #include "nodebuild.h" #include "templates.h" #if 0 #define D(x) x #define DD 1 #else #define D(x) do{}while(0) #undef DD #endif void FNodeBuilder::GetGLNodes (MapNodeEx *&outNodes, int &nodeCount, MapSegGLEx *&outSegs, int &segCount, MapSubsectorEx *&outSubs, int &subCount) { TArray<MapSegGLEx> segs (Segs.Size()*5/4); int i, j, k; nodeCount = Nodes.Size (); outNodes = new MapNodeEx[nodeCount]; for (i = 0; i < nodeCount; ++i) { const node_t *orgnode = &Nodes[i]; MapNodeEx *newnode = &outNodes[i]; newnode->x = orgnode->x; newnode->y = orgnode->y; newnode->dx = orgnode->dx; newnode->dy = orgnode->dy; for (j = 0; j < 2; ++j) { for (k = 0; k < 4; ++k) { newnode->bbox[j][k] = orgnode->bbox[j][k] >> FRACBITS; } newnode->children[j] = orgnode->intchildren[j]; } } subCount = Subsectors.Size(); outSubs = new MapSubsectorEx[subCount]; for (i = 0; i < subCount; ++i) { int numsegs = CloseSubsector (segs, i); outSubs[i].numlines = numsegs; outSubs[i].firstline = segs.Size() - numsegs; } segCount = segs.Size (); outSegs = new MapSegGLEx[segCount]; memcpy (outSegs, &segs[0], segCount*sizeof(MapSegGLEx)); for (i = 0; i < segCount; ++i) { if (outSegs[i].partner != DWORD_MAX) { outSegs[i].partner = Segs[outSegs[i].partner].storedseg; } } D(DumpNodes(outNodes, nodeCount)); } int FNodeBuilder::CloseSubsector (TArray<MapSegGLEx> &segs, int subsector) { FPrivSeg *seg, *prev; angle_t prevAngle; double accumx, accumy; fixed_t midx, midy; int i, j, first, max, count, firstVert; bool diffplanes; int firstplane; first = Subsectors[subsector].firstline; max = first + Subsectors[subsector].numlines; count = 0; accumx = accumy = 0.0; diffplanes = false; firstplane = Segs[SegList[first].SegNum].planenum; // Calculate the midpoint of the subsector and also check for degenerate subsectors. // A subsector is degenerate if it exists in only one dimension, which can be // detected when all the segs lie in the same plane. This can happen if you have // outward-facing lines in the void that don't point toward any sector. (Some of the // polyobjects in Hexen are constructed like this.) for (i = first; i < max; ++i) { seg = &Segs[SegList[i].SegNum]; accumx += double(Vertices[seg->v1].x) + double(Vertices[seg->v2].x); accumy += double(Vertices[seg->v1].y) + double(Vertices[seg->v2].y); if (firstplane != seg->planenum) { diffplanes = true; } } midx = fixed_t(accumx / (max - first) / 2); midy = fixed_t(accumy / (max - first) / 2); seg = &Segs[SegList[first].SegNum]; prevAngle = PointToAngle (Vertices[seg->v1].x - midx, Vertices[seg->v1].y - midy); seg->storedseg = PushGLSeg (segs, seg); count = 1; prev = seg; firstVert = seg->v1; #ifdef DD printf("--%d--\n", subsector); for (j = first; j < max; ++j) { seg = &Segs[SegList[j].SegNum]; angle_t ang = PointToAngle (Vertices[seg->v1].x - midx, Vertices[seg->v1].y - midy); printf ("%d%c %5d(%5d,%5d)->%5d(%5d,%5d) - %3.5f %d,%d [%08x,%08x]-[%08x,%08x]\n", j, seg->linedef == -1 ? '+' : ':', seg->v1, Vertices[seg->v1].x>>16, Vertices[seg->v1].y>>16, seg->v2, Vertices[seg->v2].x>>16, Vertices[seg->v2].y>>16, double(ang/2)*180/(1<<30), seg->planenum, seg->planefront, Vertices[seg->v1].x, Vertices[seg->v1].y, Vertices[seg->v2].x, Vertices[seg->v2].y); } #endif if (diffplanes) { // A well-behaved subsector. Output the segs sorted by the angle formed by connecting // the subsector's center to their first vertex. D(printf("Well behaved subsector\n")); for (i = first + 1; i < max; ++i) { angle_t bestdiff = ANGLE_MAX; FPrivSeg *bestseg = NULL; int bestj = -1; for (j = first; j < max; ++j) { seg = &Segs[SegList[j].SegNum]; angle_t ang = PointToAngle (Vertices[seg->v1].x - midx, Vertices[seg->v1].y - midy); angle_t diff = prevAngle - ang; if (seg->v1 == prev->v2) { bestdiff = diff; bestseg = seg; bestj = j; break; } if (diff < bestdiff && diff > 0) { bestdiff = diff; bestseg = seg; bestj = j; } } if (bestseg != NULL) { seg = bestseg; } if (prev->v2 != seg->v1) { // Add a new miniseg to connect the two segs PushConnectingGLSeg (subsector, segs, prev->v2, seg->v1); count++; } #ifdef DD printf ("+%d\n", bestj); #endif prevAngle -= bestdiff; seg->storedseg = PushGLSeg (segs, seg); count++; prev = seg; if (seg->v2 == firstVert) { prev = seg; break; } } #ifdef DD printf ("\n"); #endif } else { // A degenerate subsector. These are handled in three stages: // Stage 1. Proceed in the same direction as the start seg until we // hit the seg furthest from it. // Stage 2. Reverse direction and proceed until we hit the seg // furthest from the start seg. // Stage 3. Reverse direction again and insert segs until we get // to the start seg. // A dot product serves to determine distance from the start seg. D(printf("degenerate subsector\n")); // Stage 1. Go forward. count += OutputDegenerateSubsector (segs, subsector, true, 0, prev); // Stage 2. Go backward. count += OutputDegenerateSubsector (segs, subsector, false, DBL_MAX, prev); // Stage 3. Go forward again. count += OutputDegenerateSubsector (segs, subsector, true, -DBL_MAX, prev); } if (prev->v2 != firstVert) { PushConnectingGLSeg (subsector, segs, prev->v2, firstVert); count++; } #ifdef DD printf ("Output GL subsector %d:\n", subsector); for (i = segs.Size() - count; i < (int)segs.Size(); ++i) { printf (" Seg %5d%c(%5d,%5d)-(%5d,%5d) [%08x,%08x]-[%08x,%08x]\n", i, segs[i].linedef == NO_INDEX ? '+' : ' ', Vertices[segs[i].v1].x>>16, Vertices[segs[i].v1].y>>16, Vertices[segs[i].v2].x>>16, Vertices[segs[i].v2].y>>16, Vertices[segs[i].v1].x, Vertices[segs[i].v1].y, Vertices[segs[i].v2].x, Vertices[segs[i].v2].y); } #endif return count; } int FNodeBuilder::OutputDegenerateSubsector (TArray<MapSegGLEx> &segs, int subsector, bool bForward, double lastdot, FPrivSeg *&prev) { static const double bestinit[2] = { -DBL_MAX, DBL_MAX }; FPrivSeg *seg; int i, j, first, max, count; double dot, x1, y1, dx, dy, dx2, dy2; bool wantside; first = Subsectors[subsector].firstline; max = first + Subsectors[subsector].numlines; count = 0; seg = &Segs[SegList[first].SegNum]; x1 = Vertices[seg->v1].x; y1 = Vertices[seg->v1].y; dx = Vertices[seg->v2].x - x1; dy = Vertices[seg->v2].y - y1; wantside = seg->planefront ^ !bForward; for (i = first + 1; i < max; ++i) { double bestdot = bestinit[bForward]; FPrivSeg *bestseg = NULL; for (j = first + 1; j < max; ++j) { seg = &Segs[SegList[j].SegNum]; if (seg->planefront != wantside) { continue; } dx2 = Vertices[seg->v1].x - x1; dy2 = Vertices[seg->v1].y - y1; dot = dx*dx2 + dy*dy2; if (bForward) { if (dot < bestdot && dot > lastdot) { bestdot = dot; bestseg = seg; } } else { if (dot > bestdot && dot < lastdot) { bestdot = dot; bestseg = seg; } } } if (bestseg != NULL) { if (prev->v2 != bestseg->v1) { PushConnectingGLSeg (subsector, segs, prev->v2, bestseg->v1); count++; } seg->storedseg = PushGLSeg (segs, bestseg); count++; prev = bestseg; lastdot = bestdot; } } return count; } DWORD FNodeBuilder::PushGLSeg (TArray<MapSegGLEx> &segs, const FPrivSeg *seg) { MapSegGLEx newseg; newseg.v1 = seg->v1; newseg.v2 = seg->v2; newseg.linedef = seg->linedef; // Just checking the sidedef to determine the side is insufficient. // When a level is sidedef compressed both sides may well have the same sidedef. if (newseg.linedef != NO_INDEX) { IntLineDef *ld = &Level.Lines[newseg.linedef]; if (ld->sidenum[0] == ld->sidenum[1]) { // When both sidedefs are the same a quick check doesn't work so this // has to be done by comparing the distances of the seg's end point to // the line's start. WideVertex *lv1 = &Level.Vertices[ld->v1]; WideVertex *sv1 = &Level.Vertices[seg->v1]; WideVertex *sv2 = &Level.Vertices[seg->v2]; double dist1sq = double(sv1->x-lv1->x)*(sv1->x-lv1->x) + double(sv1->y-lv1->y)*(sv1->y-lv1->y); double dist2sq = double(sv2->x-lv1->x)*(sv2->x-lv1->x) + double(sv2->y-lv1->y)*(sv2->y-lv1->y); newseg.side = dist1sq < dist2sq ? 0 : 1; } else { newseg.side = ld->sidenum[1] == seg->sidedef ? 1 : 0; } } else { newseg.side = 0; } newseg.partner = seg->partner; return segs.Push (newseg); } void FNodeBuilder::PushConnectingGLSeg (int subsector, TArray<MapSegGLEx> &segs, int v1, int v2) { MapSegGLEx newseg; Warn ("Unclosed subsector %d, from (%d,%d) to (%d,%d)\n", subsector, Vertices[v1].x >> FRACBITS, Vertices[v1].y >> FRACBITS, Vertices[v2].x >> FRACBITS, Vertices[v2].y >> FRACBITS); newseg.v1 = v1; newseg.v2 = v2; newseg.linedef = NO_INDEX; newseg.side = 0; newseg.partner = DWORD_MAX; segs.Push (newseg); } void FNodeBuilder::GetVertices (WideVertex *&verts, int &count) { count = Vertices.Size (); verts = new WideVertex[count]; for (int i = 0; i < count; ++i) { verts[i].x = Vertices[i].x; verts[i].y = Vertices[i].y; verts[i].index = Vertices[i].index; } } void FNodeBuilder::GetNodes (MapNodeEx *&outNodes, int &nodeCount, MapSegEx *&outSegs, int &segCount, MapSubsectorEx *&outSubs, int &subCount) { short bbox[4]; TArray<MapSegEx> segs (Segs.Size()); // Walk the BSP and create a new BSP with only the information // suitable for a standard tree. At a minimum, this means removing // all minisegs. As an optional step, I also recompute all the // nodes' bounding boxes so that they only bound the real segs and // not the minisegs. nodeCount = Nodes.Size (); outNodes = new MapNodeEx[nodeCount]; subCount = Subsectors.Size (); outSubs = new MapSubsectorEx[subCount]; RemoveMinisegs (outNodes, segs, outSubs, Nodes.Size() - 1, bbox); segCount = segs.Size (); outSegs = new MapSegEx[segCount]; memcpy (outSegs, &segs[0], segCount*sizeof(MapSegEx)); D(DumpNodes(outNodes, nodeCount)); #ifdef DD for (int i = 0; i < segCount; ++i) { printf("Seg %d: v1(%d) -> v2(%d)\n", i, outSegs[i].v1, outSegs[i].v2); } #endif } int FNodeBuilder::RemoveMinisegs (MapNodeEx *nodes, TArray<MapSegEx> &segs, MapSubsectorEx *subs, int node, short bbox[4]) { if (node & NFX_SUBSECTOR) { int subnum = node == -1 ? 0 : node & ~NFX_SUBSECTOR; int numsegs = StripMinisegs (segs, subnum, bbox); subs[subnum].numlines = numsegs; subs[subnum].firstline = segs.Size() - numsegs; return NFX_SUBSECTOR | subnum; } else { const node_t *orgnode = &Nodes[node]; MapNodeEx *newnode = &nodes[node]; int child0 = RemoveMinisegs (nodes, segs, subs, orgnode->intchildren[0], newnode->bbox[0]); int child1 = RemoveMinisegs (nodes, segs, subs, orgnode->intchildren[1], newnode->bbox[1]); newnode->x = orgnode->x; newnode->y = orgnode->y; newnode->dx = orgnode->dx; newnode->dy = orgnode->dy; newnode->children[0] = child0; newnode->children[1] = child1; bbox[BOXTOP] = MAX(newnode->bbox[0][BOXTOP], newnode->bbox[1][BOXTOP]); bbox[BOXBOTTOM] = MIN(newnode->bbox[0][BOXBOTTOM], newnode->bbox[1][BOXBOTTOM]); bbox[BOXLEFT] = MIN(newnode->bbox[0][BOXLEFT], newnode->bbox[1][BOXLEFT]); bbox[BOXRIGHT] = MAX(newnode->bbox[0][BOXRIGHT], newnode->bbox[1][BOXRIGHT]); return node; } } int FNodeBuilder::StripMinisegs (TArray<MapSegEx> &segs, int subsector, short bbox[4]) { int count, i, max; // The bounding box is recomputed to only cover the real segs and not the // minisegs in the subsector. bbox[BOXTOP] = -32768; bbox[BOXBOTTOM] = 32767; bbox[BOXLEFT] = 32767; bbox[BOXRIGHT] = -32768; i = Subsectors[subsector].firstline; max = Subsectors[subsector].numlines + i; for (count = 0; i < max; ++i) { const FPrivSeg *org = &Segs[SegList[i].SegNum]; // Because of the ordering guaranteed by SortSegs(), all mini segs will // be at the end of the subsector, so once one is encountered, we can // stop right away. if (org->linedef == -1) { break; } else { MapSegEx newseg; AddSegToShortBBox (bbox, org); newseg.v1 = org->v1; newseg.v2 = org->v2; newseg.angle = org->angle >> 16; newseg.offset = org->offset >> FRACBITS; newseg.linedef = org->linedef; // Just checking the sidedef to determine the side is insufficient. // When a level is sidedef compressed both sides may well have the same sidedef. IntLineDef * ld = &Level.Lines[newseg.linedef]; if (ld->sidenum[0]==ld->sidenum[1]) { // When both sidedefs are the same a quick check doesn't work so this // has to be done by comparing the distances of the seg's end point to // the line's start. WideVertex * lv1 = &Level.Vertices[ld->v1]; WideVertex * sv1 = &Level.Vertices[org->v1]; WideVertex * sv2 = &Level.Vertices[org->v2]; double dist1sq = double(sv1->x-lv1->x)*(sv1->x-lv1->x) + double(sv1->y-lv1->y)*(sv1->y-lv1->y); double dist2sq = double(sv2->x-lv1->x)*(sv2->x-lv1->x) + double(sv2->y-lv1->y)*(sv2->y-lv1->y); newseg.side = dist1sq<dist2sq? 0:1; } else { newseg.side = ld->sidenum[1] == org->sidedef ? 1 : 0; } newseg.side = Level.Lines[org->linedef].sidenum[1] == org->sidedef ? 1 : 0; segs.Push (newseg); ++count; } } return count; } void FNodeBuilder::AddSegToShortBBox (short bbox[4], const FPrivSeg *seg) { const FPrivVert *v1 = &Vertices[seg->v1]; const FPrivVert *v2 = &Vertices[seg->v2]; short v1x = v1->x >> FRACBITS; short v1y = v1->y >> FRACBITS; short v2x = v2->x >> FRACBITS; short v2y = v2->y >> FRACBITS; if (v1x < bbox[BOXLEFT]) bbox[BOXLEFT] = v1x; if (v1x > bbox[BOXRIGHT]) bbox[BOXRIGHT] = v1x; if (v1y < bbox[BOXBOTTOM]) bbox[BOXBOTTOM] = v1y; if (v1y > bbox[BOXTOP]) bbox[BOXTOP] = v1y; if (v2x < bbox[BOXLEFT]) bbox[BOXLEFT] = v2x; if (v2x > bbox[BOXRIGHT]) bbox[BOXRIGHT] = v2x; if (v2y < bbox[BOXBOTTOM]) bbox[BOXBOTTOM] = v2y; if (v2y > bbox[BOXTOP]) bbox[BOXTOP] = v2y; } void FNodeBuilder::DumpNodes(MapNodeEx *outNodes, int nodeCount) { for (unsigned int i = 0; i < Nodes.Size(); ++i) { printf("Node %d: Splitter[%08x,%08x] [%08x,%08x]\n", i, outNodes[i].x, outNodes[i].y, outNodes[i].dx, outNodes[i].dy); for (int j = 1; j >= 0; --j) { if (outNodes[i].children[j] & NFX_SUBSECTOR) { printf(" subsector %d\n", outNodes[i].children[j] & ~NFX_SUBSECTOR); } else { printf(" node %d\n", outNodes[i].children[j]); } } } }
0
0.920711
1
0.920711
game-dev
MEDIA
0.377941
game-dev
0.973403
1
0.973403
Perchik71/Creation-Kit-Platform-Extended
3,820
CKPE.SkyrimSE/Src/Patches/CKPE.SkyrimSE.Patch.CrashFootstepSetRemove.cpp
// Copyright © 2023-2025 aka perchik71. All rights reserved. // Contacts: <email:timencevaleksej@gmail.com> // License: https://www.gnu.org/licenses/lgpl-3.0.html #include <windows.h> #include <commctrl.h> #include <CKPE.Utils.h> #include <CKPE.Detours.h> #include <CKPE.SafeWrite.h> #include <CKPE.Asserts.h> #include <CKPE.Application.h> #include <CKPE.Common.Interface.h> #include <CKPE.SkyrimSE.VersionLists.h> #include <EditorAPI/Forms/BGSFootstepSet.h> #include <Patches/CKPE.SkyrimSE.Patch.Console.h> #include <Patches/CKPE.SkyrimSE.Patch.CrashFootstepSetRemove.h> namespace CKPE { namespace SkyrimSE { namespace Patch { uintptr_t pointer_sub19BD6E0 = 0; uintptr_t pointer_sub19BE490 = 0; CrashFootstepSetRemove::CrashFootstepSetRemove() : Common::Patch() { SetName("Crash Footstep Set Remove"); } bool CrashFootstepSetRemove::HasOption() const noexcept(true) { return false; } const char* CrashFootstepSetRemove::GetOptionName() const noexcept(true) { return nullptr; } bool CrashFootstepSetRemove::HasDependencies() const noexcept(true) { return false; } std::vector<std::string> CrashFootstepSetRemove::GetDependencies() const noexcept(true) { return {}; } bool CrashFootstepSetRemove::DoQuery() const noexcept(true) { return VersionLists::GetEditorVersion() <= VersionLists::EDITOR_SKYRIM_SE_LAST; } bool CrashFootstepSetRemove::DoActive(Common::RelocatorDB::PatchDB* db) noexcept(true) { if (db->GetVersion() != 1) return false; auto interface = CKPE::Common::Interface::GetSingleton(); auto base = interface->GetApplication()->GetBase(); // With multiple deletions, CTD occurs. // Reason is the deletion of array elements from beginning, // while element is actually deleted from array. // Deleting goes beyond the boundaries or removes necessary elements. // Detailed: https://github.com/Perchik71/Creation-Kit-Platform-Extended/issues/114 auto off = __CKPE_OFFSET(0); pointer_sub19BD6E0 = __CKPE_OFFSET(1); pointer_sub19BE490 = __CKPE_OFFSET(2); // Remove erroneous code SafeWrite::WriteNop(off, 0x95); // mov rcx, qword ptr ss:[rsp+0xF0] // mov rdx, qword ptr ss:[rsp+0x68] SafeWrite::Write(off, { 0x48, 0x8B, 0x8C, 0x24, 0xF0, 0x00, 0x00, 0x00, 0x48, 0x8B, 0x54, 0x24, 0x68 }); Detours::DetourCall((std::size_t)off + 0xD, (std::uintptr_t)&RemoveSelectedItemsFromArray); return true; } void CrashFootstepSetRemove::RemoveSelectedItemsFromArray(void* Sets, void** hWindowList) noexcept(true) { if (!Sets || !hWindowList || !*hWindowList) return; auto hwnd = (HWND)(*hWindowList); auto sets = ((EditorAPI::Forms::BGSFootstepSet*)Sets); auto Items = sets->CurrentArrayItem; if (!Items) return; std::int32_t index = ListView_GetNextItem(hwnd, -1, LVNI_SELECTED); std::vector<std::int32_t> indexes; // I get a list of indexes for remove items while (index != -1) { indexes.push_back(index); index = ListView_GetNextItem(hwnd, index, LVNI_SELECTED); } // The array is always removed from end. for (auto it = indexes.rbegin(); it != indexes.rend(); it++) { auto reference_form = fast_call<EditorAPI::Forms::BGSFootstep**>(pointer_sub19BD6E0, Items, *it); if (!reference_form) { auto editorID = sets->EditorID; Console::LogWarning(Console::FORMS, "BGSFootstepSet \"%s\" (0x%08X) does not contain BGSFootstep behind the %d index. Aborting operation.", editorID ? editorID : "", sets->FormID, *it); // Stopped break; } fast_call<void>(pointer_sub19BE490, Sets, ((EditorAPI::Forms::BGSFootstepSet*)Sets)->CurrentIndex, *reference_form); } } } } }
0
0.937041
1
0.937041
game-dev
MEDIA
0.594604
game-dev
0.859701
1
0.859701
Floatkyun/2024TI_C
13,256
GUI-Guider工程/lvgl-simulator/SDL2/i686-w64-mingw32/include/SDL2/SDL_thread.h
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_thread_h_ #define SDL_thread_h_ /** * \file SDL_thread.h * * Header for the SDL thread management routines. */ #include "SDL_stdinc.h" #include "SDL_error.h" /* Thread synchronization primitives */ #include "SDL_atomic.h" #include "SDL_mutex.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* The SDL thread structure, defined in SDL_thread.c */ struct SDL_Thread; typedef struct SDL_Thread SDL_Thread; /* The SDL thread ID */ typedef unsigned long SDL_threadID; /* Thread local storage ID, 0 is the invalid ID */ typedef unsigned int SDL_TLSID; /** * The SDL thread priority. * * \note On many systems you require special privileges to set high or time critical priority. */ typedef enum { SDL_THREAD_PRIORITY_LOW, SDL_THREAD_PRIORITY_NORMAL, SDL_THREAD_PRIORITY_HIGH, SDL_THREAD_PRIORITY_TIME_CRITICAL } SDL_ThreadPriority; /** * The function passed to SDL_CreateThread(). * It is passed a void* user context parameter and returns an int. */ typedef int (SDLCALL * SDL_ThreadFunction) (void *data); #if defined(__WIN32__) /** * \file SDL_thread.h * * We compile SDL into a DLL. This means, that it's the DLL which * creates a new thread for the calling process with the SDL_CreateThread() * API. There is a problem with this, that only the RTL of the SDL2.DLL will * be initialized for those threads, and not the RTL of the calling * application! * * To solve this, we make a little hack here. * * We'll always use the caller's _beginthread() and _endthread() APIs to * start a new thread. This way, if it's the SDL2.DLL which uses this API, * then the RTL of SDL2.DLL will be used to create the new thread, and if it's * the application, then the RTL of the application will be used. * * So, in short: * Always use the _beginthread() and _endthread() of the calling runtime * library! */ #define SDL_PASSED_BEGINTHREAD_ENDTHREAD #include <process.h> /* _beginthreadex() and _endthreadex() */ typedef uintptr_t (__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned, unsigned (__stdcall *func)(void *), void * /*arg*/, unsigned, unsigned * /* threadID */); typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); #ifndef SDL_beginthread #define SDL_beginthread _beginthreadex #endif #ifndef SDL_endthread #define SDL_endthread _endthreadex #endif /** * Create a thread. */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThreadWithStackSize(int (SDLCALL * fn) (void *), const char *name, const size_t stacksize, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); /** * Create a thread. */ #if defined(SDL_CreateThread) && SDL_DYNAMIC_API #undef SDL_CreateThread #define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #undef SDL_CreateThreadWithStackSize #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #else #define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)SDL_endthread) #endif #elif defined(__OS2__) /* * just like the windows case above: We compile SDL2 * into a dll with Watcom's runtime statically linked. */ #define SDL_PASSED_BEGINTHREAD_ENDTHREAD #ifndef __EMX__ #include <process.h> #else #include <stdlib.h> #endif typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void * /*arg*/); typedef void (*pfnSDL_CurrentEndThread)(void); #ifndef SDL_beginthread #define SDL_beginthread _beginthread #endif #ifndef SDL_endthread #define SDL_endthread _endthread #endif extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); #if defined(SDL_CreateThread) && SDL_DYNAMIC_API #undef SDL_CreateThread #define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #undef SDL_CreateThreadWithStackSize #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #else #define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #endif #else /** * Create a thread with a default stack size. * * This is equivalent to calling: * SDL_CreateThreadWithStackSize(fn, name, 0, data); */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data); /** * Create a thread. * * Thread naming is a little complicated: Most systems have very small * limits for the string length (Haiku has 32 bytes, Linux currently has 16, * Visual C++ 6.0 has nine!), and possibly other arbitrary rules. You'll * have to see what happens with your system's debugger. The name should be * UTF-8 (but using the naming limits of C identifiers is a better bet). * There are no requirements for thread naming conventions, so long as the * string is null-terminated UTF-8, but these guidelines are helpful in * choosing a name: * * http://stackoverflow.com/questions/149932/naming-conventions-for-threads * * If a system imposes requirements, SDL will try to munge the string for * it (truncate, etc), but the original string contents will be available * from SDL_GetThreadName(). * * The size (in bytes) of the new stack can be specified. Zero means "use * the system default" which might be wildly different between platforms * (x86 Linux generally defaults to eight megabytes, an embedded device * might be a few kilobytes instead). * * In SDL 2.1, stacksize will be folded into the original SDL_CreateThread * function. */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data); #endif /** * Get the thread name, as it was specified in SDL_CreateThread(). * This function returns a pointer to a UTF-8 string that names the * specified thread, or NULL if it doesn't have a name. This is internal * memory, not to be free()'d by the caller, and remains valid until the * specified thread is cleaned up by SDL_WaitThread(). */ extern DECLSPEC const char *SDLCALL SDL_GetThreadName(SDL_Thread *thread); /** * Get the thread identifier for the current thread. */ extern DECLSPEC SDL_threadID SDLCALL SDL_ThreadID(void); /** * Get the thread identifier for the specified thread. * * Equivalent to SDL_ThreadID() if the specified thread is NULL. */ extern DECLSPEC SDL_threadID SDLCALL SDL_GetThreadID(SDL_Thread * thread); /** * Set the priority for the current thread */ extern DECLSPEC int SDLCALL SDL_SetThreadPriority(SDL_ThreadPriority priority); /** * Wait for a thread to finish. Threads that haven't been detached will * remain (as a "zombie") until this function cleans them up. Not doing so * is a resource leak. * * Once a thread has been cleaned up through this function, the SDL_Thread * that references it becomes invalid and should not be referenced again. * As such, only one thread may call SDL_WaitThread() on another. * * The return code for the thread function is placed in the area * pointed to by \c status, if \c status is not NULL. * * You may not wait on a thread that has been used in a call to * SDL_DetachThread(). Use either that function or this one, but not * both, or behavior is undefined. * * It is safe to pass NULL to this function; it is a no-op. */ extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status); /** * A thread may be "detached" to signify that it should not remain until * another thread has called SDL_WaitThread() on it. Detaching a thread * is useful for long-running threads that nothing needs to synchronize * with or further manage. When a detached thread is done, it simply * goes away. * * There is no way to recover the return code of a detached thread. If you * need this, don't detach the thread and instead use SDL_WaitThread(). * * Once a thread is detached, you should usually assume the SDL_Thread isn't * safe to reference again, as it will become invalid immediately upon * the detached thread's exit, instead of remaining until someone has called * SDL_WaitThread() to finally clean it up. As such, don't detach the same * thread more than once. * * If a thread has already exited when passed to SDL_DetachThread(), it will * stop waiting for a call to SDL_WaitThread() and clean up immediately. * It is not safe to detach a thread that might be used with SDL_WaitThread(). * * You may not call SDL_WaitThread() on a thread that has been detached. * Use either that function or this one, but not both, or behavior is * undefined. * * It is safe to pass NULL to this function; it is a no-op. */ extern DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread * thread); /** * \brief Create an identifier that is globally visible to all threads but refers to data that is thread-specific. * * \return The newly created thread local storage identifier, or 0 on error * * \code * static SDL_SpinLock tls_lock; * static SDL_TLSID thread_local_storage; * * void SetMyThreadData(void *value) * { * if (!thread_local_storage) { * SDL_AtomicLock(&tls_lock); * if (!thread_local_storage) { * thread_local_storage = SDL_TLSCreate(); * } * SDL_AtomicUnlock(&tls_lock); * } * SDL_TLSSet(thread_local_storage, value, 0); * } * * void *GetMyThreadData(void) * { * return SDL_TLSGet(thread_local_storage); * } * \endcode * * \sa SDL_TLSGet() * \sa SDL_TLSSet() */ extern DECLSPEC SDL_TLSID SDLCALL SDL_TLSCreate(void); /** * \brief Get the value associated with a thread local storage ID for the current thread. * * \param id The thread local storage ID * * \return The value associated with the ID for the current thread, or NULL if no value has been set. * * \sa SDL_TLSCreate() * \sa SDL_TLSSet() */ extern DECLSPEC void * SDLCALL SDL_TLSGet(SDL_TLSID id); /** * \brief Set the value associated with a thread local storage ID for the current thread. * * \param id The thread local storage ID * \param value The value to associate with the ID for the current thread * \param destructor A function called when the thread exits, to free the value. * * \return 0 on success, -1 on error * * \sa SDL_TLSCreate() * \sa SDL_TLSGet() */ extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (SDLCALL *destructor)(void*)); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_thread_h_ */ /* vi: set ts=4 sw=4 expandtab: */
0
0.920136
1
0.920136
game-dev
MEDIA
0.341856
game-dev
0.581063
1
0.581063
Ubpa/USRefl
8,458
src/AutoRefl/Meta.cpp
#include "Meta.h" #include <cassert> using namespace Ubpa::USRefl; std::string Attr::GenerateName(bool withoutQuatation) const { auto rst = ns.empty() ? name : ns + "::" + name; if (!withoutQuatation) rst = "\"" + rst + "\""; return "TSTR(" + rst + ")"; } std::string Attr::GenerateValue(bool toFunction) const { if(toFunction) return value.empty() ? "[]{}" : "[]{ return " + value + "; }"; return value.empty() ? "0" : value; } std::string Attr::GenerateValue(const std::string& type) const { return "[]()->" + type + "{ return " + (value.empty() ? "{}" : value) + "; }"; } std::string Parameter::GenerateTypeName() const { std::string rst = type; if (isPacked) rst += "..."; return rst; } std::string Parameter::GenerateParameterName() const { std::string rst = GenerateTypeName(); if (isPacked) rst += "..."; rst += " "; rst += name; return rst; } std::string Parameter::GenerateArgumentName() const { std::string rst = name; if (isPacked) rst += "..."; return rst; } std::string TypeMeta::GenerateNsName() const { std::string rst; for (const auto& ns : namespaces) { rst += ns; rst += "::"; } rst += name; return rst; } std::string TypeMeta::GenerateFullName() const { std::string rst = GenerateNsName(); if (!IsTemplateType()) return rst; std::size_t idx = 0; rst += "<"; for (std::size_t i = 0; i < templateParameters.size(); i++) { const auto& ele = templateParameters[i]; if (ele.name.empty()) { rst += "_"; rst += std::to_string(idx); idx++; } else rst += ele.name; if (ele.isPacked) rst += "..."; if (i != templateParameters.size() - 1) rst += ", "; } rst += ">"; return rst; } std::string TypeMeta::GenerateTemplateList() const { std::string rst; std::size_t idx = 0; for (std::size_t i = 0; i < templateParameters.size(); i++) { const auto& ele = templateParameters[i]; rst += ele.type; if (ele.isPacked) rst += "..."; rst += " "; if (ele.name.empty()) { rst += "_"; rst += std::to_string(idx); idx++; } else rst += ele.name; if (i != templateParameters.size() - 1) rst += ", "; } return rst; } std::vector<std::size_t> TypeMeta::GetPublicBaseIndices() const { std::vector<std::size_t> rst; for(std::size_t i=0;i<bases.size();i++) { const auto& base = bases[i]; if ( base.accessSpecifier == AccessSpecifier::DEFAULT && mode == Mode::Struct || base.accessSpecifier == AccessSpecifier::PUBLIC ) rst.push_back(i); } return rst; } std::string Base::GenerateText() const { std::string rst = "Base<"; rst += name; if (isVirtual) rst += ", true"; rst += ">"; if (isPacked) rst += "..."; return rst; } void Field::Clear() { mode = Mode::Variable; attrs.clear(); declSpecifiers.clear(); pointerOperators.clear(); name.clear(); parameters.clear(); qualifiers.clear(); } bool Field::IsStaticConstexprVariable() const { bool containsStatic = false; bool containsConstexpr = false; for(const auto& declSpecifier : declSpecifiers) { if (declSpecifier == "static") containsStatic = true; else if (declSpecifier == "constexpr") containsConstexpr = true; } return mode == Mode::Variable && containsStatic && containsConstexpr; } std::string Field::GenerateFieldType() const { std::string rst; for (std::size_t i = 0; i < declSpecifiers.size(); i++) { rst += declSpecifiers[i]; if (i != declSpecifiers.size() - 1) rst += " "; } if(!pointerOperators.empty()) { if (!rst.empty()) rst += " "; for (std::size_t i = 0; i < pointerOperators.size(); i++) { rst += pointerOperators[i]; if (i != pointerOperators.size() - 1) rst += " "; } } if (rst.empty()) return "int"; // default return rst; } std::string Field::GenerateSimpleFieldType() const { std::string rst; std::vector<std::size_t> filterdIndice; for (std::size_t i = 0; i < declSpecifiers.size(); i++) { const auto& declSpecifier = declSpecifiers[i]; if ( // storage class specifier declSpecifier != "register" && declSpecifier != "static" && declSpecifier != "thread_local" && declSpecifier != "extern" && declSpecifier != "mutable" // function specifier && declSpecifier != "inline" && declSpecifier != "virtual" && declSpecifier != "explicit" // others && declSpecifier != "friend" && declSpecifier != "typedef" && declSpecifier != "constexpr" ) filterdIndice.push_back(i); } for (std::size_t i = 0; i < filterdIndice.size(); i++) { rst += declSpecifiers[filterdIndice[i]]; if (i != filterdIndice.size() - 1) rst += " "; } if (!pointerOperators.empty()) { if (!rst.empty()) rst += " "; for (std::size_t i = 0; i < pointerOperators.size(); i++) { rst += pointerOperators[i]; if (i != pointerOperators.size() - 1) rst += " "; } } if (rst.empty()) return "int"; // default return rst; } bool Field::IsMemberFunction() const { if (mode != Mode::Function) return false; bool containsStatic = false; for(const auto& declSpecifier : declSpecifiers) { if (declSpecifier == "static") containsStatic = true; } bool containsFriend = false; for (const auto& declSpecifier : declSpecifiers) { if (declSpecifier == "friend") containsFriend = true; } return !containsStatic && !containsFriend; } bool Field::IsFriendFunction() const { if (mode != Mode::Function) return false; for (const auto& declSpecifier : declSpecifiers) { if (declSpecifier == "friend") return true; } return false; } bool Field::IsDeletedFunction() const { return mode == Mode::Function && initializer == "delete"; } std::string Field::GenerateParamTypeList() const { return GenerateParamTypeList(parameters.size()); } std::string Field::GenerateParamTypeList(std::size_t num) const { assert(num <= parameters.size()); std::string rst; for (std::size_t i = 0; i < num; i++) { rst += parameters[i].GenerateTypeName(); if (i != num - 1) rst += ", "; } return rst; } std::size_t Field::GetDefaultParameterNum() const { if (mode != Mode::Function) return 0; for(std::size_t i=0;i<parameters.size();i++) { if(!parameters[i].initializer.empty()) return parameters.size() - i; } return 0; } std::string Field::GenerateNamedParameterList(std::size_t num) const { assert(num <= parameters.size()); std::string rst; std::size_t idx = 0; for (std::size_t i = 0; i < num; i++) { rst += parameters[i].GenerateTypeName(); if (parameters[i].isPacked) rst += "..."; rst += " "; if (parameters[i].name.empty()) { rst += "_" + std::to_string(idx); idx++; } else rst += parameters[i].name; if (i != num - 1) rst += ", "; } return rst; } std::string Field::GenerateForwardArgumentList(std::size_t num) const { assert(num <= parameters.size()); std::string rst; std::size_t idx = 0; for (std::size_t i = 0; i < num; i++) { rst += "std::forward<"; rst += parameters[i].GenerateTypeName(); rst += ">("; if(parameters[i].name.empty()) { std::string name = "_" + std::to_string(idx); idx++; rst += name; } else rst += parameters[i].name; rst += ")"; if (parameters[i].isPacked) rst += "..."; if (i != num - 1) rst += ", "; } return rst; } std::string Field::GenerateQualifiers() const { std::string rst; for (std::size_t i = 0; i < qualifiers.size(); i++) { rst += qualifiers[i]; if (i != qualifiers.size() - 1) rst += " "; } return rst; } std::string Field::GenerateFunctionType(std::string_view obj) const { assert(mode == Mode::Function); std::string rst; rst += GenerateSimpleFieldType(); if (IsMemberFunction()) { rst += "("; rst += obj; rst += "::*)"; } rst += "("; rst += GenerateParamTypeList(); rst += ")"; for (std::size_t i = 0; i < qualifiers.size(); i++) { rst += qualifiers[i]; if (i != qualifiers.size() - 1) rst += " "; } return rst; } std::string Field::GenerateInitFunction() const { return "[]{ return " + GenerateSimpleFieldType() + (!initializer.empty() ? initializer : "{}") + "; }"; } bool TypeMeta::IsOverloaded(std::string_view name) const { std::size_t cnt = 0; for(const auto& field : fields) { if (field.name == name && !field.IsFriendFunction()) cnt++; } return cnt > 1; } bool TypeMeta::HaveAnyOutputField() const { for (const auto& field : fields) { if (field.accessSpecifier == AccessSpecifier::PUBLIC && !field.IsFriendFunction() && !field.IsDeletedFunction()) return true; } return false; }
0
0.890252
1
0.890252
game-dev
MEDIA
0.125513
game-dev
0.865374
1
0.865374
mkst/conker
13,768
conker/src/game_16EE20.c
#include <ultra64.h> #include "functions.h" #include "variables.h" void func_15141970(struct37 *arg0) { func_1514EDF0(arg0, arg0->unk2C); } void func_15141990(void *arg0) { func_15141970(arg0); } void func_151419B0(void *arg0) { func_15141970(arg0); } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151419D0.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15141A7C.s") // requires jump table #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15141C0C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15141CC0.s") void func_15141DA4(void *arg0, s32 arg1, s32 arg2) { if ((arg1 < 12) && (arg1 >= 0) && (arg2 < 20) && (arg2 >= 0) && (D_800BE616 == 0) && (D_8008A084[arg1] != 0) && (arg2 != -1)) { if ((D_8008A0B4[arg2].unk0 != 0) && (D_8008A0B4[arg2].unk4 > 0)) { func_15141E38(arg0, arg2); } } } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15141E38.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15141F78.s") // NON-MATCHING: need to determine arguments // void func_1513C650(s32, s32, s32, u16, s32, s32, s32, f32, f32, s32, s32, s32, s32, s32, u8, s32); // s32 func_1513C650(s32 arg0, u8 arg1, u8 arg2, s32 arg3, f32 arg4, f32 arg5, f32 arg6, f32 arg7, f32 arg8, u8 arg9, u8 argA, s32 argB, s32 argC, s32 argD, u8 argE, s32 argF); // void func_15141F78(u8 arg0, struct157 *arg1, f32 arg2, s32 arg3, struct157 *arg4, u8 arg5) { // struct157 tmp; // f32 temp_f2; // s32 phi_v0; // // tmp.unk6 = arg0; // tmp.unk7 = 0; // tmp.unk0 = 0x6F701; // tmp.unk4 = (func_150ADA20() % 61U) + 100; // tmp.unk8 = 0; // tmp.unkC = 0; // tmp.unk10 = (func_150ADA20() & 0x7F) + 128; // tmp.unk11 = 0xFF; // tmp.unk12 = 0xFF; // tmp.unk13 = 0xFF; // tmp.unk14 = 0xFF; // tmp.unk15 = 0xFF; // tmp.unk18 = 0x3B0002; // tmp.unk16 = 0; // tmp.unk17 = 7; // tmp.unk20 = 0xFF; // tmp.unk1C = arg1->unk18; // tmp.unk22 = 0x28; // tmp.unk24 = 6; // temp_f2 = ((func_150ADA68() * 5.0f) + 10.0f) * arg2; // // --- matching to here --- // if (arg5 == 2) { // phi_v0 = 1; // } else { // phi_v0 = 0; // } // func_1513C650(&tmp, 0, 0, arg1->unk4, arg4->unk0, arg1->unk0, arg4->unk8, temp_f2, temp_f2, arg3, phi_v0, 3, 1, 0, 0xFF, 1); // } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151420F8.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142180.s") s32 func_151422C0(s32 arg0, s32 arg1, s32 arg2, s32 arg3) { return (arg3 + arg2) >> 1; } s32 func_151422DC(s32 arg0, s32 arg1, s32 arg2, s32 arg3, s32 arg4, s32 arg5, s32 arg6) { return arg4; } s32 func_151422F8(s32 arg0, s32 arg1, s32 arg2, s32 arg3, s32 arg4) { return arg4; } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142314.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151423D8.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142444.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151424F4.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142600.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142838.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142914.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151429E0.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142A5C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142A80.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142AC0.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142B04.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142B44.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142B7C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142C10.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142CF0.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142E24.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15142FBC.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143044.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514306C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143134.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151432BC.s") // void func_151432BC(struct208 *arg0, f32 *arg1, f32 *arg2, f32 *arg3, f32 *arg4) { // struct209 tmp; // f32 temp_f2; // f32 temp_f6; // f32 temp_ret; // s32 temp_t6; // u8 temp_a0; // // temp_t6 = (arg0->unk15) & 3; // if (temp_t6 == 0) { // tmp.unk1B = func_150ADA20(); // tmp.unk14 = func_151423D8((tmp.unk1B - 64) & 0xFF); // tmp.unk10 = func_151423D8(tmp.unk1B); // temp_ret = func_150ADA68(); // temp_f2 = temp_ret * arg0->unk6; // *arg1 = (arg0->unk0 + (temp_f2 * tmp.unk10)); // *arg2 = (arg0->unk4 - (temp_f2 * tmp.unk14)); // *arg3 = (arg0->unk2 + arg0->unk8); // *arg4 = arg0->unk2; // } else if (temp_t6 != 1) { // if (temp_t6 == 2) { // tmp.unk2F = (u32) (arg0->unk10 * D_800A5644); // 0.7111111283302307 // tmp.unk28 = func_151423D8((tmp.unk2F - 64)); // tmp.unk24 = func_151423D8(tmp.unk2F); // tmp.unk20 = (func_150ADA68() * (2.0f * (f32) arg0->unk6)) + (f32) -(s32) arg0->unk6; // temp_f2 = (func_150ADA68() * (2.0f * (f32) arg0->unkA)) + (f32) -(s32) arg0->unkA; // temp_f6 = temp_f2 * tmp.unk24; // *arg1 = (arg0->unk0 + ((tmp.unk20 * tmp.unk24) + (temp_f2 * tmp.unk28))); // *arg2 = (arg0->unk4 + (temp_f6 - (tmp.unk20 * tmp.unk28))); // *arg3 = (arg0->unk2 + arg0->unk8); // *arg4 = arg0->unk2; // } else { // *arg1 = arg0->unk0; // *arg2 = arg0->unk4; // *arg3 = (arg0->unk2 + arg0->unk8); // *arg4 = (arg0->unk2 - arg0->unk8); // } // } else { // tmp.unkB = func_150ADA20(); // tmp.unk4 = func_151423D8((tmp.unkB - 64)); // tmp.unk0 = func_151423D8(tmp.unkB); // temp_ret = func_150ADA68(); // temp_f2 = temp_ret * (f32) arg0->unk6; // *arg1 = (arg0->unk0 + (temp_f2 * tmp.unk0)); // *arg2 = (arg0->unk4 - (temp_f2 * tmp.unk4)); // *arg3 = (arg0->unk2 + arg0->unk8); // *arg4 = (arg0->unk2 - arg0->unk8); // } // } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151436B4.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514373C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143794.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143834.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143874.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151438D8.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143D18.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143DA8.s") s32 func_15143E08(struct127 *arg0) { return (((s32) arg0->unk7A >> 8) + 64) & 0xFF; } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143E24.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143E64.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15143E94.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514401C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151441A4.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151442FC.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151444DC.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144528.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144598.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514462C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514470C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144A74.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144AA8.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144B34.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144B68.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144BC8.s") s32 func_15144C2C(s16 arg0) { s16 tmp1 = arg0; while (tmp1 >= 256) { tmp1 -= 255; } while (tmp1 < 0) { tmp1 += 255; } return tmp1; } f32 func_15144C8C(f32 arg0, f32 arg1) { f32 tmp; arg0 = func_15144B68(arg0); tmp = fabsf(arg0 - func_15144B68(arg1)); if (D_800A56A8 < tmp) { tmp = D_800A56AC - tmp; } return tmp; } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144CEC.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15144E80.s") void func_151450B4(struct17 *arg0, struct17 *arg1, struct17 *arg2) { arg2->unk0 = arg0->unk4 * arg1->unk8 - arg0->unk8 * arg1->unk4; arg2->unk4 = arg0->unk8 * arg1->unk0 - arg0->unk0 * arg1->unk8; arg2->unk8 = arg0->unk0 * arg1->unk4 - arg0->unk4 * arg1->unk0; } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15145128.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151451F0.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151452C4.s") s32 func_151454BC(u8 arg0, f32 arg1, struct17 *arg2) { f32 tmp1; f32 tmp2; f32 tmp3; struct17 *temp_v0; temp_v0 = func_15144B34(arg0); tmp1 = arg2->unk0 - temp_v0->unk0; tmp2 = arg2->unk4 - temp_v0->unk4; tmp3 = arg2->unk8 - temp_v0->unk8; if ((arg1 * arg1) < ((tmp1 * tmp1) + (tmp2 * tmp2) + (tmp3 * tmp3))) { return 0; } return 1; } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15145548.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514563C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15145740.s") // NON-MATCHING: 90% there // void func_15145740(struct127 *arg0, struct17 *arg1, struct17 *arg2, struct17 *arg3, f32 arg4) { // struct194 tmp; // f32 temp_f6; // s16 phi_v1; // s16 phi_t0; // // if ((arg0->unk4 == 0x96) && ((arg0->unk31C->unk7D != 0))) { // phi_t0 = arg0->unk7A + arg0->unk31C->unk80; // } else { // if (arg0->unk31C != 0) { // phi_t0 = arg0->unk7A - arg0->unk31C->unk12; // } else { // phi_t0 = arg0->unk7A; // } // } // if ((arg0->unk4 == 0x96) && (arg0->unk31C->unk7D != 0)) { // phi_v1 = arg0->unk31C->unk82 + 1024; // } else { // phi_v1 = arg0->unk1D1 * 200; // } // tmp.unk14 = phi_t0; // tmp.unk10 = phi_v1 * 0.005493164f; // tmp.unk0 = tmp.unk10 * D_800A56B4; // func_1505A184(phi_t0, 2000.0f, tmp.unk10, &arg1->unk0, &arg1->unk8, &arg1->unk4); // if (arg2 != 0) { // arg2->unk4 = cosf(tmp.unk0) * 1000.0f; // temp_f6 = sinf(tmp.unk0) * 1000.0f; // tmp.unk8 = temp_f6; // tmp.unk4 = phi_t0 * D_800A56B8; // arg2->unk0 = cosf(tmp.unk4) * tmp.unk8; // arg2->unk8 = sinf(tmp.unk4) * -temp_f6; // if (arg3 != 0) { // tmp.unkC = tmp.unk0 + arg4; // arg3->unk4 = cosf(tmp.unkC) * 1000.0f; // tmp.unk8 = sinf(tmp.unkC) * 1000.0f; // arg3->unk0 = cosf(tmp.unk4) * tmp.unk8; // arg3->unk8 = sinf(tmp.unk4) * -tmp.unk8; // } // } // } void func_15145974(struct17 *arg0, f32 *arg1, f32 *arg2) { *arg1 = func_150484A0(arg0->unk0, arg0->unk8) * D_800A56BC; if (arg2 != NULL) { *arg2 = (func_150484A0(sqrtf(arg0->unk0 * arg0->unk0 + arg0->unk8 * arg0->unk8), arg0->unk4) * D_800A56C0) - 90.0f; } } f32 func_15145A0C(f32 arg0, f32 arg1, f32 arg2) { return D_800A548C[(s32)(arg0 * arg2 * 100.0f)] * arg1; } void func_15145A50(struct127 *arg0) { arg0->unk5 = 3; if (D_800BE9F0 != 51) { if ((D_800BE616 != 0) || (arg0->interaction_state == 5) || (arg0->interaction_state == 1) || (arg0->interaction_state == 21)) { arg0->interaction_state = 5; if (arg0->unk31C != NULL) { arg0->unk31C->unk78 = 0; } } else { func_15053694(arg0); } } } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15145AD8.s") u8 func_15145C90(s32 arg0) { if (arg0 < 0) { return 1; } else { return (D_800DBEF4[arg0].unk6F & 0x80) == 0x80; } } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15145CD0.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15145DB4.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15145EA4.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_15146078.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151462C8.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_151464B8.s") void func_15146508(struct127 *arg0, struct127 *arg1) { struct193 tmp; tmp.unk0 = arg0; tmp.unk4 = arg1; tmp.unk8 = arg0->unique_id; tmp.unk9 = arg1->unique_id; func_15169040(&tmp, 45, arg0, arg1); } #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514654C.s") #pragma GLOBAL_ASM("asm/nonmatchings/game_16EE20/func_1514672C.s") // NON-MATCHING: JUSTREG: first 3 statements are out of order // s32 func_1514672C(struct17 *arg0) { // if ((D_800A56C4 < fabsf(arg0->unk0)) || (D_800A56C4 < fabsf(arg0->unk8)) || (D_800A56C4 < arg0->unk4) || (arg0->unk4 < D_800A56C8)) { // return 0; // } else { // return 1; // } // } void func_151467A4(f32 *arg0, f32 arg1, f32 *arg2, f32 arg3, f32 arg4, f32 arg5, f32 arg6, f32 *arg7) { *arg0 = *arg0 - D_800BE9A4; if (*arg0 < 0.0f) { *arg0 = func_150ADA68() * arg1; if ((func_150ADA20() & 3) != 0) { *arg2 = (func_150ADA68() * (arg4 - arg3)) + arg3; } else { *arg2 = (func_150ADA68() * (arg5 - arg4)) + arg4; } } *arg7 = ((*arg2 - *arg7) * arg6) + *arg7; }
0
0.620566
1
0.620566
game-dev
MEDIA
0.811811
game-dev
0.578595
1
0.578595
ProjectIgnis/CardScripts
2,647
official/c59208943.lua
--クロノダイバー・パーペチュア --Time Thief Perpetua --Scripted by Eerie Code local s,id=GetID() function s.initial_effect(c) c:EnableReviveLimit() Xyz.AddProcedure(c,nil,4,2) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_PHASE|PHASE_STANDBY) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1,id) e1:SetCost(Cost.DetachFromSelf(1)) e1:SetTarget(s.sptg) e1:SetOperation(s.spop) c:RegisterEffect(e1) --attach local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_FREE_CHAIN) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1,{id,1}) e2:SetTarget(s.mattg) e2:SetOperation(s.matop) c:RegisterEffect(e2) end s.listed_names={id} s.listed_series={SET_TIME_THIEF} function s.spfilter(c,e,tp) return c:IsSetCard(SET_TIME_THIEF) and not c:IsCode(id) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and s.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(s.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function s.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end function s.xyzfilter(c) return c:IsFaceup() and c:IsType(TYPE_XYZ) end function s.mattg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local c=e:GetHandler() if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and s.xyzfilter(chkc) and chkc~=c end if chk==0 then return Duel.IsExistingTarget(s.xyzfilter,tp,LOCATION_MZONE,0,1,c) and Duel.IsExistingMatchingCard(Card.IsSetCard,tp,LOCATION_DECK,0,1,nil,SET_TIME_THIEF) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,s.xyzfilter,tp,LOCATION_MZONE,0,1,1,c) end function s.matop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsFaceup() and tc:IsRelateToEffect(e) and not tc:IsImmuneToEffect(e) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_XMATERIAL) local g=Duel.SelectMatchingCard(tp,Card.IsSetCard,tp,LOCATION_DECK,0,1,1,nil,SET_TIME_THIEF) if #g>0 then Duel.Overlay(tc,g) end end end
0
0.957653
1
0.957653
game-dev
MEDIA
0.971488
game-dev
0.938483
1
0.938483
magefree/mage
1,285
Mage/src/main/java/mage/game/permanent/token/MaskToken.java
package mage.game.permanent.token; import mage.abilities.Ability; import mage.abilities.effects.common.AttachEffect; import mage.abilities.keyword.EnchantAbility; import mage.abilities.keyword.UmbraArmorAbility; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.SubType; import mage.target.TargetPermanent; /** * @author TheElk801 */ public final class MaskToken extends TokenImpl { public MaskToken() { super( "Mask", "white Aura enchantment token named Mask " + "attached to another target permanent. " + "The token has enchant permanent and umbra armor." ); cardType.add(CardType.ENCHANTMENT); color.setWhite(true); subtype.add(SubType.AURA); TargetPermanent auraTarget = new TargetPermanent(); Ability ability = new EnchantAbility(auraTarget); ability.addTarget(auraTarget); ability.addEffect(new AttachEffect(Outcome.BoostCreature)); this.addAbility(ability); // Umbra armor this.addAbility(new UmbraArmorAbility()); } private MaskToken(final MaskToken token) { super(token); } public MaskToken copy() { return new MaskToken(this); } }
0
0.818246
1
0.818246
game-dev
MEDIA
0.904231
game-dev
0.813695
1
0.813695
mcMMO-Dev/mcMMO
2,798
src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java
package com.gmail.nossr50.commands.party; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class PartyLockCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { switch (args.length) { case 1: if (args[0].equalsIgnoreCase("lock")) { togglePartyLock(sender, true); } else if (args[0].equalsIgnoreCase("unlock")) { togglePartyLock(sender, false); } return true; case 2: if (!args[0].equalsIgnoreCase("lock")) { sendUsageStrings(sender); return true; } if (CommandUtils.shouldEnableToggle(args[1])) { togglePartyLock(sender, true); } else if (CommandUtils.shouldDisableToggle(args[1])) { togglePartyLock(sender, false); } else { sendUsageStrings(sender); } return true; default: sendUsageStrings(sender); return true; } } private void sendUsageStrings(CommandSender sender) { sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "lock", "[on|off]")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "unlock")); } private void togglePartyLock(CommandSender sender, boolean lock) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } Party party = UserManager.getPlayer((Player) sender).getParty(); if (!Permissions.partySubcommand(sender, lock ? PartySubcommandType.LOCK : PartySubcommandType.UNLOCK)) { sender.sendMessage(LocaleLoader.getString("mcMMO.NoPermission")); return; } if (lock == party.isLocked()) { sender.sendMessage( LocaleLoader.getString("Party." + (lock ? "IsLocked" : "IsntLocked"))); return; } party.setLocked(lock); sender.sendMessage(LocaleLoader.getString("Party." + (lock ? "Locked" : "Unlocked"))); } }
0
0.774781
1
0.774781
game-dev
MEDIA
0.499186
game-dev
0.781313
1
0.781313
devonium/EGSM
1,152
source/vs/ShatteredGlass_EnvMapSphere.inc
class shatteredglass_envmapsphere_Static_Index { public: shatteredglass_envmapsphere_Static_Index() { } int GetIndex() { // Asserts to make sure that we aren't using any skipped combinations. // Asserts to make sure that we are setting all of the combination vars. #ifdef _DEBUG #endif // _DEBUG return 0; } }; class shatteredglass_envmapsphere_Dynamic_Index { private: int m_nDOWATERFOG; #ifdef _DEBUG bool m_bDOWATERFOG; #endif public: void SetDOWATERFOG( int i ) { Assert( i >= 0 && i <= 1 ); m_nDOWATERFOG = i; #ifdef _DEBUG m_bDOWATERFOG = true; #endif } void SetDOWATERFOG( bool i ) { m_nDOWATERFOG = i ? 1 : 0; #ifdef _DEBUG m_bDOWATERFOG = true; #endif } public: shatteredglass_envmapsphere_Dynamic_Index() { #ifdef _DEBUG m_bDOWATERFOG = false; #endif // _DEBUG m_nDOWATERFOG = 0; } int GetIndex() { // Asserts to make sure that we aren't using any skipped combinations. // Asserts to make sure that we are setting all of the combination vars. #ifdef _DEBUG bool bAllDynamicVarsDefined = m_bDOWATERFOG; Assert( bAllDynamicVarsDefined ); #endif // _DEBUG return ( 1 * m_nDOWATERFOG ) + 0; } };
0
0.841686
1
0.841686
game-dev
MEDIA
0.335001
game-dev
0.67537
1
0.67537
RS485/LogisticsPipes
7,041
src/api/kotlin/network/rs485/logisticspipes/property/BitSetProperty.kt
/* * Copyright (c) 2021 RS485 * * "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public * License 1.0.1, or MMPL. Please check the contents of the license located in * https://github.com/RS485/LogisticsPipes/blob/dev/LICENSE.md * * This file can instead be distributed under the license terms of the * MIT license: * * Copyright (c) 2021 RS485 * * This MIT license was reworded to only match this file. If you use the regular * MIT license in your project, replace this copyright notice (this line and any * lines below and NOT the copyright line above) with the lines from the original * MIT license located here: http://opensource.org/licenses/MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this file and associated documentation files (the "Source Code"), to deal in * the Source Code without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Source Code, and to permit persons to whom the Source Code 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 Source Code, which also can be * distributed under the MIT. * * 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 network.rs485.logisticspipes.property import net.minecraft.nbt.NBTTagCompound import java.util.* import java.util.concurrent.CopyOnWriteArraySet interface IBitSet { operator fun get(bit: Int): Boolean operator fun set(bit: Int, value: Boolean) fun flip(bit: Int) fun nextSetBit(idx: Int): Int fun replaceWith(other: BitSet) fun replaceWith(other: IBitSet) fun copyValue(): BitSet fun clear() fun sequence(): Sequence<Int> { var idx = nextSetBit(0) return generateSequence { idx.takeUnless { it == -1 }?.also { idx = nextSetBit(it + 1) } } } } class BitSetProperty(private val bitset: BitSet, override val tagKey: String) : IBitSet, Property<BitSet> { override val propertyObservers: CopyOnWriteArraySet<ObserverCallback<BitSet>> = CopyOnWriteArraySet() override fun copyValue(): BitSet = bitset.clone() as BitSet override fun clear() = bitset.clear().alsoIChanged() fun copyValue(startIdx: Int, endIdx: Int): BitSet = bitset.get(startIdx, endIdx + 1) override fun copyProperty(): BitSetProperty = BitSetProperty(copyValue(), tagKey) override fun replaceWith(other: BitSet) { other.takeUnless { it == bitset } ?.let { bitset.clear(); bitset.or(it) } ?.alsoIChanged() } override fun replaceWith(other: IBitSet) { other.takeUnless { it == bitset } ?.let { bitset.clear(); bitset.or(it.copyValue()) } ?.alsoIChanged() } fun replaceWith(other: BitSetProperty) { other.takeUnless { it === this } ?.let { bitset.clear(); bitset.or(other.bitset) } ?.alsoIChanged() } override fun readFromNBT(tag: NBTTagCompound) { if (tag.hasKey(tagKey)) replaceWith(BitSet.valueOf(tag.getByteArray(tagKey))) } override fun writeToNBT(tag: NBTTagCompound) = tag.setByteArray(tagKey, bitset.toByteArray()) override fun get(bit: Int): Boolean = bitset.get(bit) override fun set(bit: Int, value: Boolean) = bitset.set(bit, value).alsoIChanged() override fun flip(bit: Int) = bitset.flip(bit).alsoIChanged() override fun nextSetBit(idx: Int): Int = bitset.nextSetBit(idx) fun get(startIdx: Int, endIdx: Int): IBitSet { if (startIdx < 0 || startIdx >= bitset.size()) { throw IndexOutOfBoundsException("startIdx[$startIdx] is out of bounds") } if (endIdx < 0 || endIdx >= bitset.size()) { throw IndexOutOfBoundsException("endIdx[$endIdx] is out of bounds") } return PartialBitSet(startIdx..endIdx) } override fun equals(other: Any?): Boolean = (other as? BitSetProperty)?.let { tagKey == other.tagKey && bitset == other.bitset } ?: false override fun hashCode(): Int = Objects.hash(tagKey, bitset) override fun toString(): String = "BitSetProperty(tagKey=$tagKey, bitset=$bitset)" inner class PartialBitSet(private val indices: IntRange) : IBitSet { val size: Int get() = (indices.last - indices.first) + 1 init { if (indices.last < indices.first) { throw IllegalArgumentException("start[${indices.first}] must be <= end[${indices.last}]") } } private fun rangeCheck(idx: Int): Int { if (idx < 0 || idx >= size) { throw IndexOutOfBoundsException("idx[$idx] out of bounds of $this") } return idx } override fun get(bit: Int): Boolean = this@BitSetProperty[indices.first + rangeCheck(bit)] override fun set(bit: Int, value: Boolean) = this@BitSetProperty.set(indices.first + rangeCheck(bit), value) override fun flip(bit: Int) = this@BitSetProperty.flip(indices.first + rangeCheck(bit)) override fun clear() = this@BitSetProperty.bitset.clear(indices.first, indices.last + 1).alsoIChanged() override fun copyValue(): BitSet = this@BitSetProperty.copyValue(indices.first, indices.last) override fun nextSetBit(idx: Int): Int { if (idx >= size) return -1 return this@BitSetProperty.nextSetBit(indices.first + rangeCheck(idx)) .takeUnless { it == -1 || it > indices.last } ?.let { it - indices.first } ?: -1 } override fun replaceWith(other: BitSet) { bitset.clear(indices.first, indices.last + 1) other.stream().forEach { bit -> (indices.first + bit).takeIf { it <= indices.last }?.also { bitset.set(it) } } iChanged() } override fun replaceWith(other: IBitSet) { bitset.clear(indices.first, indices.last + 1) other.sequence().map { bit -> indices.first + bit } .takeWhile { bit -> bit <= indices.last } .forEach { bit -> bitset.set(bit) } iChanged() } override fun equals(other: Any?): Boolean = (other as? IBitSet)?.copyValue()?.equals(copyValue()) ?: false override fun hashCode(): Int = copyValue().hashCode() override fun toString(): String = "PartialBitSet(indices=$indices, bitset=${copyValue()})" } }
0
0.914186
1
0.914186
game-dev
MEDIA
0.267077
game-dev
0.927453
1
0.927453
dbeef/spelunky-psp
10,919
src/game-loop/src/game-loop/GameLoopPlayingState.cpp
#include "prefabs/ui/DeathOverlay.hpp" #include "prefabs/ui/HudOverlay.hpp" #include "prefabs/ui/PauseOverlay.hpp" #include "prefabs/npc/ShopkeeperScript.hpp" #include "prefabs/main-dude/MainDude.hpp" #include "game-loop/GameLoopPlayingState.hpp" #include "game-loop/GameLoop.hpp" #include "EntityRegistry.hpp" #include "components/specialized/HudOverlayComponent.hpp" #include "components/specialized/PauseOverlayComponent.hpp" #include "components/specialized/DeathOverlayComponent.hpp" #include "components/specialized/LevelSummaryTracker.hpp" #include "components/specialized/MainDudeComponent.hpp" #include "components/generic/ItemCarrierComponent.hpp" #include "components/generic/CollectibleComponent.hpp" #include "system/RenderingSystem.hpp" #include "system/DamageSystem.hpp" #include "system/ItemSystem.hpp" #include "system/CollectibleSystem.hpp" #include "system/ScriptingSystem.hpp" #include "system/ShoppingSystem.hpp" #include "system/PhysicsSystem.hpp" #include "system/AnimationSystem.hpp" #include "system/InputSystem.hpp" #include "system/DisposingSystem.hpp" #include "system/ParticleSystem.hpp" #include "logger/log.h" #include "ModelViewCamera.hpp" #include "ScreenSpaceCamera.hpp" #include "CameraType.hpp" #include "Level.hpp" #include "audio/Audio.hpp" #include "populator/Populator.hpp" #include "prefabs/ui/CheatConsole.hpp" GameLoopBaseState *GameLoopPlayingState::update(GameLoop& game_loop, uint32_t delta_time_ms) { auto& registry = EntityRegistry::instance().get_registry(); auto& rendering_system = game_loop._rendering_system; auto& scripting_system = game_loop._scripting_system; auto& physics_system = game_loop._physics_system; auto& animation_system = game_loop._animation_system; auto& collectible_system = game_loop._collectible_system; auto& input_system = game_loop._input_system; auto& item_system = game_loop._item_system; auto& disposing_system = game_loop._disposing_system; auto& particle_system = game_loop._particle_system; auto& damage_system = game_loop._damage_system; auto& shopping_system = game_loop._shopping_system; // Adjust camera to follow main dude: auto& position = registry.get<PositionComponent>(_main_dude); auto& model_view_camera = game_loop._rendering_system->get_model_view_camera(); model_view_camera.adjust_to_bounding_box(position.x_center, position.y_center); model_view_camera.adjust_to_level_boundaries(Consts::LEVEL_WIDTH_TILES, Consts::LEVEL_HEIGHT_TILES); model_view_camera.update_gl_modelview_matrix(); rendering_system->update(delta_time_ms); input_system->update(delta_time_ms); auto& pause = registry.get<PauseOverlayComponent>(_pause_overlay); if (pause.is_paused()) { if (pause.is_death_requested()) { log_info("Death requested."); auto& dude = registry.get<MainDudeComponent>(_main_dude); dude.enter_dead_state(); } if (pause.is_quit_requested()) { log_info("Quit requested."); game_loop._exit = true; } pause.update(registry); } else { scripting_system->update(delta_time_ms); physics_system->update(delta_time_ms); animation_system->update(delta_time_ms); item_system->update(delta_time_ms); disposing_system->update(delta_time_ms); collectible_system->update(delta_time_ms); particle_system->update(delta_time_ms); damage_system->update(delta_time_ms); shopping_system->update(delta_time_ms); } auto& dude = registry.get<MainDudeComponent>(_main_dude); if (dude.entered_door()) { return &game_loop._states.level_summary; } auto& death = registry.get<DeathOverlayComponent>(_death_overlay); if (death.is_scores_requested()) { return &game_loop._states.scores; } game_loop._level_summary_tracker->update(delta_time_ms); auto& cheat_console = registry.get<prefabs::CheatConsoleComponent>(_cheat_console); if (cheat_console.is_state_change_requested()) { return game_loop.get_game_loop_state_ptr(cheat_console.get_requested_state()); } return this; } void GameLoopPlayingState::enter(GameLoop& game_loop) { log_info("Entered GameLoopPlayingState"); std::srand(game_loop._time_elapsed_ms); auto& registry = EntityRegistry::instance().get_registry(); Audio::instance().play(MusicType::CAVE); TileBatch::LevelGeneratorParams generator_params; generator_params.shopkeeper_robbed = game_loop._shopping_system->is_robbed(); Level::instance().get_tile_batch().generate_new_level_layout(generator_params); Level::instance().get_tile_batch().initialise_tiles_from_room_layout(); Level::instance().get_tile_batch().generate_frame(); Level::instance().get_tile_batch().generate_cave_background(); Level::instance().get_tile_batch().batch_vertices(); Level::instance().get_tile_batch().add_render_entity(registry); // Update main dude: MapTile *entrance = nullptr; Level::instance().get_tile_batch().get_first_tile_of_given_type(MapTileType::ENTRANCE, entrance); assert(entrance); float pos_x = entrance->x + (MapTile::PHYSICAL_WIDTH / 2.0f); float pos_y = entrance->y + (MapTile::PHYSICAL_HEIGHT / 2.0f); // Update main dude: _main_dude = prefabs::MainDude::create(pos_x, pos_y); _pause_overlay = prefabs::PauseOverlay::create(game_loop._viewport, PauseOverlayComponent::Type::PLAYING); _death_overlay = prefabs::DeathOverlay::create(game_loop._viewport); _hud = prefabs::HudOverlay::create(game_loop._viewport); _cheat_console = prefabs::CheatConsole::create(game_loop._viewport); game_loop._rendering_system->sort(); auto& dude = registry.get<MainDudeComponent>(_main_dude); dude.add_observer(this); // Subscribe HUD on main-dude's ItemCarrierComponent events: auto& hud_component = registry.get<HudOverlayComponent>(_hud); auto& item_component = registry.get<ItemCarrierComponent>(_main_dude); item_component.add_observer(hud_component.get_item_observer()); auto& death = registry.get<DeathOverlayComponent>(_death_overlay); death.disable_input(); Populator populator; populator.generate_loot(game_loop._shopping_system->is_robbed()); populator.generate_npc(is_damsel_rescued(), game_loop._shopping_system->is_robbed()); populator.generate_inventory_items(_main_dude); // Wire subjects with observers: for (const auto& collectible_entity : populator.get_collectibles()) { auto& collectible = registry.get<CollectibleComponent>(collectible_entity); collectible.add_observer(game_loop._level_summary_tracker.get()); } for (const auto& npc_entity : populator.get_npcs()) { auto& hitpoints = registry.get<HitpointComponent>(npc_entity); hitpoints.add_observer(game_loop._level_summary_tracker.get()); } for (const auto& shopkeeper : populator.get_shopkeepers()) { auto &scripting_component = registry.get<ScriptingComponent>(shopkeeper); auto *shopkeeper_script = scripting_component.get<prefabs::ShopkeeperScript>(); game_loop._shopping_system->add_observer(shopkeeper_script->get_thievery_observer()); shopkeeper_script->add_observer(game_loop._shopping_system.get()); if (game_loop._shopping_system->is_robbed()) { shopkeeper_script-> get_angry(shopkeeper); } } game_loop._level_summary_tracker->entered_new_level(); _special_events.damsel_rescued = false; // Subscribe HUD on main-dude's wallet: auto& item_carrier = registry.get<ItemCarrierComponent>(_main_dude); const auto wallet_entity = item_carrier.get_item(ItemType::WALLET); if (wallet_entity != entt::null) { auto& wallet_scripting_component = registry.get<ScriptingComponent>(wallet_entity); auto* wallet_script = wallet_scripting_component.get<prefabs::WalletScript>(); auto& hud_overlay = registry.get<HudOverlayComponent>(_hud); wallet_script->add_observer(static_cast<Observer<ShoppingTransactionEvent>*>(&hud_overlay)); } } void GameLoopPlayingState::exit(GameLoop& game_loop) { auto& registry = EntityRegistry::instance().get_registry(); Audio::instance().stop(); auto& dude = registry.get<MainDudeComponent>(_main_dude); auto& dude_item_carrier_component = registry.get<ItemCarrierComponent>(_main_dude); // Save collected item types in inventory which is persistent between the levels: auto& inventory = Inventory::instance(); inventory.set_items(dude_item_carrier_component.get_items()); game_loop._shopping_system->remove_all_observers(); dude.remove_observer(this); registry.clear(); } void GameLoopPlayingState::on_notify(const MainDudeEvent* event) { auto& registry = EntityRegistry::instance().get_registry(); switch(*event) { case MainDudeEvent::DIED: { if (_hud == entt::null) { break; } // TODO: Maybe just remove components when they are no longer needed? auto& death = registry.get<DeathOverlayComponent>(_death_overlay); auto& pause = registry.get<PauseOverlayComponent>(_pause_overlay); death.launch(); death.enable_input(); pause.unpause(); pause.hide(registry); pause.disable_input(); registry.view<ItemComponent>().each([&registry](entt::entity item_entity, ItemComponent& item) { if (item.get_type() == ItemType::COMPASS) { auto& compass_scripting_component = registry.get<ScriptingComponent>(item_entity); auto* compass_script = compass_scripting_component.get<prefabs::CompassScript>(); compass_script->remove_all_observers(); } }); auto& item_carrier_component = registry.get<ItemCarrierComponent>(_main_dude); auto& hud_overlay_component = registry.get<HudOverlayComponent>(_hud); item_carrier_component.remove_observer(hud_overlay_component.get_item_observer()); const auto wallet_entity = item_carrier_component.get_item(ItemType::WALLET); if (wallet_entity != entt::null) { auto& wallet_scripting_component = registry.get<ScriptingComponent>(wallet_entity); auto* wallet_script = wallet_scripting_component.get<prefabs::WalletScript>(); wallet_script->remove_observer(static_cast<Observer<ShoppingTransactionEvent>*>(&hud_overlay_component)); } registry.destroy(_hud); _hud = entt::null; break; } default: break; } }
0
0.953833
1
0.953833
game-dev
MEDIA
0.966847
game-dev
0.915284
1
0.915284
qnpiiz/rich-2.0
2,109
src/main/java/net/minecraft/entity/player/PlayerAbilities.java
package net.minecraft.entity.player; import net.minecraft.nbt.CompoundNBT; public class PlayerAbilities { public boolean disableDamage; public boolean isFlying; public boolean allowFlying; public boolean isCreativeMode; public boolean allowEdit = true; private float flySpeed = 0.05F; private float walkSpeed = 0.1F; public void write(CompoundNBT tagCompound) { CompoundNBT compoundnbt = new CompoundNBT(); compoundnbt.putBoolean("invulnerable", this.disableDamage); compoundnbt.putBoolean("flying", this.isFlying); compoundnbt.putBoolean("mayfly", this.allowFlying); compoundnbt.putBoolean("instabuild", this.isCreativeMode); compoundnbt.putBoolean("mayBuild", this.allowEdit); compoundnbt.putFloat("flySpeed", this.flySpeed); compoundnbt.putFloat("walkSpeed", this.walkSpeed); tagCompound.put("abilities", compoundnbt); } public void read(CompoundNBT tagCompound) { if (tagCompound.contains("abilities", 10)) { CompoundNBT compoundnbt = tagCompound.getCompound("abilities"); this.disableDamage = compoundnbt.getBoolean("invulnerable"); this.isFlying = compoundnbt.getBoolean("flying"); this.allowFlying = compoundnbt.getBoolean("mayfly"); this.isCreativeMode = compoundnbt.getBoolean("instabuild"); if (compoundnbt.contains("flySpeed", 99)) { this.flySpeed = compoundnbt.getFloat("flySpeed"); this.walkSpeed = compoundnbt.getFloat("walkSpeed"); } if (compoundnbt.contains("mayBuild", 1)) { this.allowEdit = compoundnbt.getBoolean("mayBuild"); } } } public float getFlySpeed() { return this.flySpeed; } public void setFlySpeed(float speed) { this.flySpeed = speed; } public float getWalkSpeed() { return this.walkSpeed; } public void setWalkSpeed(float speed) { this.walkSpeed = speed; } }
0
0.751396
1
0.751396
game-dev
MEDIA
0.971107
game-dev
0.855505
1
0.855505
hajimehoshi/ebiten
3,348
exp/textinput/textinput_darwin.m
// Copyright 2023 The Ebitengine Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !ios // TODO: Remove Cgo with PureGo (#1162). #import <Cocoa/Cocoa.h> int ebitengine_textinput_hasMarkedText(); void ebitengine_textinput_markedRange(int64_t* start, int64_t* length); void ebitengine_textinput_selectedRange(int64_t* start, int64_t* length); void ebitengine_textinput_unmarkText(); void ebitengine_textinput_setMarkedText(const char* text, int64_t selectionStart, int64_t selectionLen, int64_t replaceStart, int64_t replaceLen); void ebitengine_textinput_insertText(const char* text, int64_t replaceStart, int64_t replaceLen); NSRect ebitengine_textinput_firstRectForCharacterRange(uintptr_t self, NSRange range, NSRangePointer actualRange); void ebitengine_textinput_end(); @interface TextInputClient : NSView<NSTextInputClient> { } @end @implementation TextInputClient - (BOOL)hasMarkedText { return ebitengine_textinput_hasMarkedText() != 0; } - (NSRange)markedRange { int64_t start = 0; int64_t length = 0; ebitengine_textinput_markedRange(&start, &length); return NSMakeRange(start, length); } - (NSRange)selectedRange { int64_t start = 0; int64_t length = 0; ebitengine_textinput_selectedRange(&start, &length); return NSMakeRange(start, length); } - (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange { if ([string isKindOfClass:[NSAttributedString class]]) { string = [string string]; } ebitengine_textinput_setMarkedText([string UTF8String], selectedRange.location, selectedRange.length, replacementRange.location, replacementRange.length); } - (void)unmarkText { ebitengine_textinput_unmarkText(); } - (NSArray<NSAttributedStringKey> *)validAttributesForMarkedText { return @[]; } - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange { return nil; } - (void)insertText:(id)string replacementRange:(NSRange)replacementRange { if ([string isKindOfClass:[NSAttributedString class]]) { string = [string string]; } if ([string length] == 1 && [string characterAtIndex:0] < 0x20) { return; } ebitengine_textinput_insertText([string UTF8String], replacementRange.location, replacementRange.length); } - (NSUInteger)characterIndexForPoint:(NSPoint)point { return 0; } - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange { return ebitengine_textinput_firstRectForCharacterRange((uintptr_t)(self), range, actualRange); } - (void)doCommandBySelector:(SEL)selector { // Do nothing. } - (BOOL)resignFirstResponder { ebitengine_textinput_end(); return [super resignFirstResponder]; } @end
0
0.715947
1
0.715947
game-dev
MEDIA
0.399986
game-dev,desktop-app
0.869303
1
0.869303
Dimbreath/AzurLaneData
10,459
en-US/view/activity/summerfeast/summerfeastscene.lua
slot0 = class("SummerFeastScene", import("view.base.BaseUI")) function slot0.getUIName(slot0) return "SummerFeastUI" end slot0.HUB_ID = 1 slot1 = { [0] = { color = "ffffff", name = "none" }, { color = "ffed95", name = "na" }, { color = "feb8ff", name = "k" }, { color = "ad92ff", name = "rb" }, { color = "affff4", name = "zn" }, { color = "ffa685", name = "ca" }, { color = "c1ffa7", name = "cu" } } function slot0.GetCurrentDay() return pg.TimeMgr.GetInstance():STimeDescS(pg.TimeMgr.GetInstance():GetServerTime(), "*t").yday end function slot0.GetTheDay() return os.date("*t", os.time({ hour = 0, month = 8, year = 2019, min = 0, sec = 0, isdst = false, day = 29 })).yday end function slot0.TransformColor(slot0) return Color.New(tonumber(string.sub(slot0, 1, 2), 16) / 255, tonumber(string.sub(slot0, 3, 4), 16) / 255, tonumber(string.sub(slot0, 5, 6), 16) / 255) end function slot0.GenerateRandomFanPosition(slot0, slot1, slot2, slot3, slot4, slot5, slot6) slot7 = {} for slot11 = 1, slot6 do table.insert(slot7, math.lerp(slot4, slot5, math.random(1, 100) / 100)) end slot8 = slot3 / (slot6 - 1) slot9 = math.sin(slot8) slot10 = math.cos(slot8) slot11 = Vector2.Normalize(slot2 - slot1) slot18 = slot1.x + slot7[1] * slot11.x table.insert({}, Vector2.New(slot18, slot1.y + slot7[1] * slot11.y)) for slot18 = 2, slot6 do table.insert(slot12, Vector2.New(slot1.x + slot7[slot18] * (slot13 * slot10 + slot14 * slot9), slot1.y + slot7[slot18] * (slot14 * slot10 - slot13 * slot9))) end return slot12 end function slot0.init(slot0) slot0.top = slot0:findTF("top") slot0._closeBtn = slot0:findTF("top/back") slot0._homeBtn = slot0:findTF("top/home") slot0._helpBtn = slot0:findTF("top/help") slot0.ticketTimes = slot0.top:Find("ticket/text") slot0.yinhuace = slot0.top:Find("yinhuace") slot0.yinhuaceTimes = slot0.yinhuace:Find("get") slot0.yinhuaceTips = slot0.yinhuace:Find("tip") slot0.shouce = slot0.top:Find("yinhuashouceye") slot0.shouce_bg = slot0.shouce:Find("bg") slot0.layout_shouce = slot0.shouce:Find("yinhuace/go/layout") slot0.group_get = slot0:Clone2Full(slot0.layout_shouce, 14) slot0.btn_receive = slot0.shouce:Find("yinhuace/receive") slot0.btn_shouce_help = slot0.shouce:Find("yinhuace/help") slot0.img_get = slot0.shouce:Find("yinhuace/get") setActive(slot0.shouce, false) slot0.sakura = slot0:findTF("effect") slot0._map = slot0:findTF("scrollRect/map") slot0.wave = slot0._map:Find("effect_wave") slot0.shrine = slot0._map:Find("shrine") slot0.snack_street = slot0._map:Find("snack_street") slot0.entertainment_street = slot0._map:Find("entertainment_street") slot0.firework_factory = slot0._map:Find("firework_factory") slot0.btn_fire = slot0.firework_factory:Find("fire") slot0.bottom = slot0._map:Find("bottom") slot0.middle = slot0._map:Find("middle") slot0.front = slot0._map:Find("front") slot0._shipTpl = slot0._map:Find("ship") slot0.graphPath = GraphPath.New(import("GameCfg.SummerFeastGraph")) pg.PoolMgr.GetInstance():GetPrefab("ui/firework", "", true, function (slot0) pg.PoolMgr.GetInstance():ReturnPrefab("ui/firework", "", slot0) end) slot0.workingEffect = {} end function slot0.didEnter(slot0) slot1 = getProxy(MiniGameProxy) onButton(slot0, slot0._closeBtn, function () uv0:emit(uv1.ON_BACK) end) onButton(slot0, slot0._homeBtn, function () uv0:emit(uv1.ON_HOME) end) onButton(slot0, slot0._helpBtn, function () pg.MsgboxMgr.GetInstance():ShowMsgBox({ type = MSGBOX_TYPE_HELP, helps = pg.gametip.help_summer_feast.tip }) end) onButton(slot0, slot0.yinhuace, function () setActive(uv0.shouce, true) end) onButton(slot0, slot0.shouce_bg, function () setActive(uv0.shouce, false) end) onButton(slot0, slot0.btn_shouce_help, function () pg.MsgboxMgr.GetInstance():ShowMsgBox({ type = MSGBOX_TYPE_HELP, helps = pg.gametip.help_summer_stamp.tip }) end) onButton(slot0, slot0.btn_receive, function () if uv0:GetHubByHubId(uv1.HUB_ID).ultimate ~= 0 or slot0.usedtime < slot0:getConfig("reward_need") then return end uv1:emit(SummerFeastMediator.MINI_GAME_OPERATOR, { hubid = slot0.id, cmd = MiniGameOPCommand.CMD_ULTIMATE, args1 = {} }) end) slot0:InitFacility(slot0.shrine, function () pg.m02:sendNotification(GAME.GO_MINI_GAME, 3) end) slot0:InitFacility(slot0.snack_street, function () pg.m02:sendNotification(GAME.GO_MINI_GAME, 2) end) slot0:InitFacility(slot0.entertainment_street, function () pg.m02:sendNotification(GAME.GO_MINI_GAME, 5) end) slot0:InitFacility(slot0.firework_factory, function () pg.m02:sendNotification(GAME.GO_MINI_GAME, 4) end) onButton(slot0, slot0.btn_fire, function () if not uv0:GetMiniGameData(FireworkFactoryView.MINIGAME_ID):GetRuntimeData("elements") or #slot1 < 4 or slot1[4] ~= uv1.GetCurrentDay() then return end uv1:PlayFirework(slot1) setActive(uv1.btn_fire, false) end) pg.UIMgr.GetInstance():OverlayPanel(slot0.top, false) slot0.academyStudents = {} slot0:InitAreaTransFunc() slot0:updateStudents() slot0:UpdateView() end function slot0.UpdateView(slot0) slot2 = getProxy(MiniGameProxy):GetHubByHubId(slot0.HUB_ID) setText(slot0.ticketTimes, slot2.count) setText(slot0.yinhuaceTimes, slot2.usedtime) for slot7, slot8 in ipairs(slot0.group_get) do setActive(slot8, slot7 <= slot3) end slot4 = slot3 >= #slot0.group_get and slot2.ultimate == 0 setActive(slot0.btn_receive, slot4) setActive(slot0.yinhuaceTips, slot4) setActive(slot0.img_get, slot2.ultimate ~= 0) if slot2.ultimate == 1 then slot0:TryPlayStory() end setActive(slot0.btn_fire, slot1:GetMiniGameData(FireworkFactoryView.MINIGAME_ID):GetRuntimeData("elements") and #slot6 >= 4 and slot6[4] == slot0.GetCurrentDay()) end function slot0.InitFacility(slot0, slot1, slot2) onButton(slot0, slot1, slot2) onButton(slot0, slot1:Find("button"), slot2) end function slot0.PlayFirework(slot0, slot1) if #slot0.workingEffect > 0 then return end slot1 = slot1 or { 0, 0, 0 } slot3 = UnityEngine.ParticleSystem.MinMaxGradient.New for slot7, slot8 in pairs({ Vector2(215, 150) }) do pg.PoolMgr.GetInstance():GetPrefab("ui/firework", "", false, function (slot0) slot2 = tf(slot0):Find("Fire"):GetComponent("ParticleSystem").main.startColor tf(slot0):Find("Fire"):GetComponent("ParticleSystem").main.startColor = uv0(uv1.TransformColor(uv2[uv3[1]].color)) tf(slot0):Find("Fire/par_small"):GetComponent("ParticleSystem").main.startColor = uv0(uv1.TransformColor(uv2[uv3[2]].color)) tf(slot0):Find("Fire/par_small/par_big"):GetComponent("ParticleSystem").main.startColor = uv0(uv1.TransformColor(uv2[uv3[3]].color)) table.insert(uv1.workingEffect, slot0) setParent(slot0, uv1._map) slot0.transform.localPosition = uv4 end) end slot0:PlaySE() end function slot0.ClearEffectFirework(slot0) slot0:StopSE() slot1 = pg.PoolMgr.GetInstance() for slot5, slot6 in pairs(slot0.workingEffect) do slot1:ReturnPrefab("ui/firework", "", slot6) end slot1:DestroyPrefab("ui/firework", "") slot0.workingEffect = {} end function slot0.PlaySE(slot0) if slot0.SETimer then return end slot0.SECount = 10 slot0.SETimer = Timer.New(function () uv0.SECount = uv0.SECount - 1 if uv0.SECount <= 0 then uv0.SECount = math.random(5, 20) pg.CriMgr.GetInstance():PlaySE_V3("battle-firework") end end, 0.1, -1) slot0.SETimer:Start() end function slot0.StopSE(slot0) if slot0.SETimer then pg.CriMgr.GetInstance():StopSEBattle_V3() slot0.SETimer:Stop() slot0.SETimer = nil end end function slot0.getStudents(slot0) if not getProxy(ActivityProxy):getActivityById(ActivityConst.SUMMER_FEAST_ID) then return {} end if slot3:getConfig("config_client") and slot4.ships then slot5 = 0 slot6 = #Clone(slot4) while slot5 < 15 and slot6 > 0 do slot7 = math.random(1, slot6) table.insert(slot1, slot4[slot7]) slot4[slot7] = slot4[slot6] slot6 = slot6 - 1 slot5 = slot5 + math.random(3, 5) end end return slot1 end function slot0.InitAreaTransFunc(slot0) slot0.edge2area = { ["1_4"] = slot0.bottom, ["1_5"] = slot0.bottom, ["4_5"] = slot0.bottom, ["3_5"] = slot0.middle } slot0.graphPath.points[5].isBan = true end function slot0.updateStudents(slot0) for slot5, slot6 in pairs(slot0:getStudents()) do if not slot0.academyStudents[slot5] then slot7 = cloneTplTo(slot0._shipTpl, slot0._map) slot7.gameObject.name = slot5 slot8 = SummerFeastNavigationAgent.New(slot7.gameObject) slot8:attach() slot8:setPathFinder(slot0.graphPath) slot8:SetOnTransEdge(function (slot0, slot1, slot2) slot0._tf:SetParent(uv0.edge2area[math.min(slot1, slot2) .. "_" .. math.max(slot1, slot2)] or uv0.front) end) slot8:updateStudent(slot6) slot0.academyStudents[slot5] = slot8 end end if #slot1 > 0 then slot0.sortTimer = Timer.New(function () uv0:sortStudents() end, 0.2, -1) slot0.sortTimer:Start() slot0.sortTimer.func() end end function slot0.sortStudents(slot0) for slot5, slot6 in pairs({ slot0.front, slot0.middle, slot0.bottom }) do if slot6.childCount > 1 then slot7 = {} for slot11 = 1, slot6.childCount do table.insert(slot7, { tf = slot6:GetChild(slot11 - 1), index = slot11 }) end table.sort(slot7, function (slot0, slot1) if math.abs(slot0.tf.anchoredPosition.y - slot1.tf.anchoredPosition.y) < 1 then return slot0.index < slot1.index else return slot2 > 0 end end) for slot11, slot12 in ipairs(slot7) do slot12.tf:SetSiblingIndex(slot11 - 1) end end end end function slot0.clearStudents(slot0) if slot0.sortTimer then slot0.sortTimer:Stop() slot0.sortTimer = nil end for slot4, slot5 in pairs(slot0.academyStudents) do slot5:detach() Destroy(slot5._go) end slot0.academyStudents = {} end function slot0.Clone2Full(slot0, slot1, slot2) slot4 = slot1:GetChild(0) for slot9 = 0, slot1.childCount - 1 do table.insert({}, slot1:GetChild(slot9)) end for slot9 = slot5, slot2 - 1 do table.insert(slot3, tf(cloneTplTo(slot4, slot1))) end return slot3 end function slot0.TryPlayStory(slot0) if "TIANHOUYUYI2" then pg.NewStoryMgr.GetInstance():Play(slot1) end end function slot0.willExit(slot0) pg.UIMgr.GetInstance():UnOverlayPanel(slot0.top, slot0._tf) slot0:clearStudents() slot0:ClearEffectFirework() end return slot0
0
0.662503
1
0.662503
game-dev
MEDIA
0.957801
game-dev
0.907082
1
0.907082
kgsws/kg3d_x16
17,384
PC/x16_editor/engine/things.c
#include "inc.h" #include "defs.h" #include "engine.h" #include "list.h" #include "tick.h" #include "things.h" #include "x16g.h" #include "x16t.h" typedef struct { kge_xy_vec_t src; kge_xy_vec_t dst; kge_xy_vec_t dir; kge_xy_vec_t norm; kge_sector_t *sec; struct { int32_t hit; float dist; kge_line_t *line; kge_xy_vec_t spot; kge_xy_vec_t vect; kge_xy_vec_t norm; kge_xy_vec_t vtx; } pick; struct { float botz; float topz; float height; float radius; float r2; } th; float dist; kge_vertex_t pointvtx; kge_line_t pointline; } thing_xy_move_t; // kge_thing_t *thing_local_player; kge_thing_t *thing_local_camera; static thing_xy_move_t xymove; uint32_t vc_move; // static uint32_t recursive_xy_move(kge_thing_t *thing, kge_sector_t *sec, uint32_t recursion); // // functions static void sector_transition(kge_thing_t *thing, kge_xy_vec_t *origin) { kge_sector_t *sec = thing->pos.sector; kge_xy_vec_t vec; vec.x = thing->pos.x - origin->x; vec.y = thing->pos.y - origin->y; vc_move++; while(1) { kge_sector_t *pick_s = NULL; kge_line_t *pick_l = NULL; float pick_d = 1.0f; for(uint32_t i = 0; i < sec->line_count; i++) { kge_line_t *line = sec->line + i; uint32_t s0, s1; float d; if(line->vc.move == vc_move) continue; if(!line->backsector) { line->vc.move = vc_move; continue; } // reject lines not crossed if(kge_line_point_side(line, thing->pos.x, thing->pos.y) >= 0.0f) { line->vc.move = vc_move; continue; } if(kge_line_point_side(line, origin->x, origin->y) < 0.0f) { line->vc.move = vc_move; continue; } // actually check line cross d = kge_divline_cross(origin->xy, vec.xy, line->vertex[0]->xy, line->stuff.dist.xy); if(d >= 0.0f && d <= 1.0f) { // get cross distance d = kge_divline_cross(line->vertex[0]->xy, line->stuff.dist.xy, origin->xy, vec.xy); if(d >= 0.0f && d < pick_d) { pick_d = d; pick_l = line; pick_s = line->backsector; } } } if(!pick_s) break; pick_l->vc.move = vc_move; sec = pick_s; } thing->pos.sector = sec; } static uint32_t process_back_sector(kge_thing_t *thing, kge_line_t *line, float *coord, uint32_t recursion) { kge_sector_t *bs = line->backsector; float floorz, ceilingz; // check back sector if(!bs) return 1; floorz = bs->plane[PLANE_BOT].height; ceilingz = bs->plane[PLANE_TOP].height; if(ceilingz - floorz < xymove.th.height) return 1; if(xymove.th.botz < floorz) return 1; if(xymove.th.topz > ceilingz) return 1; if(bs->vc.move != vc_move && recursive_xy_move(thing, bs, recursion + 1)) return 2; return 0; } static uint32_t recursive_xy_move(kge_thing_t *thing, kge_sector_t *sec, uint32_t recursion) { kge_line_t *first; if(recursion > MAX_COLLISION_RECURSION) { xymove.pick.hit = -1; xymove.pick.dist = 0; return 1; } sec->vc.move = vc_move; // store first line first = sec->line; // check all lines for(uint32_t i = 0; i < sec->line_count; i++) { kge_line_t *line = sec->line + i; kge_line_t *ln; kge_vertex_t *vn; kge_xy_vec_t vtx; kge_vertex_t coord; float d0, d1; // check next line if(i < sec->line_count-1) ln = line + 1; else ln = first; // check for split if(ln->vertex[0] != line->vertex[1]) { kge_line_t *tmp = ln; ln = first; first = tmp; } vn = ln->vertex[1]; // check angle if(line->backsector) d0 = -1.0f; else d0 = kge_line_point_side(line, vn->x, vn->y); if(d0 <= 0.0f) { kge_vertex_t *vv = line->vertex[0]; if( d0 < 0.0f || (vv->x == vn->x && vv->y == vn->y) // very rare special case ){ vv = line->vertex[1]; // check direction if(kge_divline_point_side(xymove.src.xy, xymove.norm.xy, vv->x, vv->y) > 0) { float t, d; t = xymove.dir.x * (vv->x - xymove.src.x) + xymove.dir.y * (vv->y - xymove.src.y); // check distance if(t - 0.01f - thing->prop.radius < xymove.dist) { // check circle collision coord.x = xymove.src.x + xymove.dir.x * t; coord.x -= vv->x; coord.y = xymove.src.y + xymove.dir.y * t; coord.y -= vv->y; d = coord.x * coord.x + coord.y * coord.y; if(d <= xymove.th.r2) { kge_vertex_t vect; d = t - sqrtf(xymove.th.r2 - d); d /= xymove.dist; if(d <= xymove.pick.dist) { uint32_t blocked; // get collision spot coord.x = xymove.src.x + thing->mom.x * d; coord.y = xymove.src.y + thing->mom.y * d; // check first line blocked = process_back_sector(thing, line, coord.xy, recursion); if(blocked == 2) return 1; // check next line if(!blocked) { blocked = process_back_sector(thing, ln, coord.xy, recursion); if(blocked == 2) return 1; } if(blocked) { // found closer hit xymove.pick.hit = 2; xymove.pick.line = NULL; // TODO: pick a line? xymove.pick.dist = d; xymove.pick.spot.x = coord.x; xymove.pick.spot.y = coord.y; xymove.pick.norm.x = xymove.pick.spot.x - vv->x; xymove.pick.norm.y = xymove.pick.spot.y - vv->y; d = sqrtf(xymove.pick.norm.x * xymove.pick.norm.x + xymove.pick.norm.y * xymove.pick.norm.y); xymove.pick.norm.x /= d; xymove.pick.norm.y /= d; xymove.pick.vect.x = xymove.pick.norm.y; xymove.pick.vect.y = -xymove.pick.norm.x; xymove.pick.vtx.x = vv->x; xymove.pick.vtx.y = vv->y; } } } } } } } // offset line by thing radius vtx.x = line->vertex[0]->x + line->stuff.normal.x * thing->prop.radius; vtx.y = line->vertex[0]->y + line->stuff.normal.y * thing->prop.radius; // reject lines without possible collision if(kge_divline_point_side(vtx.xy, line->stuff.dist.xy, xymove.dst.x, xymove.dst.y) > 0.0f) continue; // reject lines this thing starts behind if(kge_divline_point_side(vtx.xy, line->stuff.dist.xy, xymove.src.x, xymove.src.y) < 0.0f) { // check if inside line area if( kge_line_point_side(line, xymove.src.x, xymove.src.y) > 0.0f && kge_divline_point_side(line->vertex[0]->xy, line->stuff.normal.xy, xymove.src.x, xymove.src.y) <= 0.0f && kge_divline_point_side(line->vertex[1]->xy, line->stuff.normal.xy, xymove.src.x, xymove.src.y) >= 0.0f ){ // get collision spot d0 = xymove.th.radius - kge_line_point_distance(line, xymove.src.x, xymove.src.y); coord.x = thing->pos.x + line->stuff.normal.x * d0; coord.y = thing->pos.y + line->stuff.normal.y * d0; // fake collision distance d1 = -1.0f; goto do_collide; } continue; } // check for actual collision d0 = kge_divline_cross(xymove.src.xy, thing->mom.xyz, vtx.xy, line->stuff.dist.xy); if(d0 < 0.0f || d0 > 1.0f) continue; // get collision distance d1 = kge_divline_cross(vtx.xy, line->stuff.dist.xy, xymove.src.xy, thing->mom.xyz); do_collide: if(d1 <= xymove.pick.dist) { uint32_t blocked = 1; // get collision spot if(d1 >= 0.0f) { coord.x = thing->pos.x + thing->mom.x * d1; coord.y = thing->pos.y + thing->mom.y * d1; } // check back sectors if(line->backsector) { // check first line blocked = process_back_sector(thing, line, coord.xy, recursion); if(blocked == 2) return 1; } if(blocked) { // found closer hit xymove.pick.hit = 1; xymove.pick.line = line; xymove.pick.dist = d1; xymove.pick.spot = vtx; xymove.pick.vect = line->stuff.dist; xymove.pick.norm = line->stuff.normal; xymove.pick.spot.x = coord.x; xymove.pick.spot.y = coord.y; } } } if(xymove.pick.dist <= 0.0f) return 1; return 0; } static int32_t xy_move(kge_thing_t *thing) { int32_t ret = 0; // prepare vc_move++; xymove.src.x = thing->pos.x; xymove.src.y = thing->pos.y; xymove.dst.x = thing->pos.x + thing->mom.x; xymove.dst.y = thing->pos.y + thing->mom.y; xymove.sec = thing->pos.sector; xymove.pick.hit = 0; xymove.pick.dist = 1.0f; xymove.pick.line = NULL; xymove.dist = sqrtf(thing->mom.x * thing->mom.x + thing->mom.y * thing->mom.y); xymove.dir.x = thing->mom.x / xymove.dist; xymove.dir.y = thing->mom.y / xymove.dist; xymove.norm.x = xymove.dir.y; xymove.norm.y = -xymove.dir.x; xymove.th.botz = thing->pos.z; xymove.th.topz = thing->pos.z + thing->prop.height; xymove.th.height = thing->prop.height; xymove.th.radius = thing->prop.radius; xymove.th.r2 = thing->prop.radius * thing->prop.radius; // check for collisions recursive_xy_move(thing, thing->pos.sector, 0); if(xymove.pick.hit < 0) { // out of recursions // do not move return -1; } else if(xymove.pick.hit) { kge_vertex_t vtx; float step = 0.0001f; float sx, sy; // blocked thing->pos.x = xymove.pick.spot.x; thing->pos.y = xymove.pick.spot.y; // check sector transitions sector_transition(thing, &xymove.src); // backup, again xymove.src.x = thing->pos.x; xymove.src.y = thing->pos.y; // step size sx = xymove.pick.norm.x * step; sy = xymove.pick.norm.y * step; // correct position if(xymove.pick.hit == 1) { // TODO: this might cause anoter collision and transition; check again? do { float nx, ny; while(1) { nx = thing->pos.x + sx; ny = thing->pos.y + sy; if(thing->pos.x != nx || thing->pos.y != ny) break; // step does not seem to change the position (float precision issue) step += 0.0001f; sx = xymove.pick.norm.x * step; sy = xymove.pick.norm.y * step; } thing->pos.x = nx; thing->pos.y = ny; // make sure this point is not behind the line } while(kge_line_point_distance(xymove.pick.line, thing->pos.x, thing->pos.y) <= xymove.th.radius); } else { // TODO: this might cause anoter collision and transition; check again? do { float nx, ny; while(1) { nx = thing->pos.x + sx; ny = thing->pos.y + sy; if(thing->pos.x != nx || thing->pos.y != ny) break; // step does not seem to change the position (float precision issue) step += 0.0001f; sx = xymove.pick.norm.x * step; sy = xymove.pick.norm.y * step; } thing->pos.x = nx; thing->pos.y = ny; // make sure this point is outside of the circle } while(kge_point_point_dist2(thing->pos.xyz, xymove.pick.vtx.xy) <= xymove.th.r2); } // check sector transitions, again if(xymove.src.x != thing->pos.x || xymove.src.y != thing->pos.y) sector_transition(thing, &xymove.src); ret = 1; } else { // not blocked thing->pos.x = xymove.dst.x; thing->pos.y = xymove.dst.y; // check sector transitions sector_transition(thing, &xymove.src); // ret = 0; } // position fallback if something fails // just keep thing inside the sector box if(thing->pos.x < thing->pos.sector->stuff.box[BOX_XMIN]) { thing->pos.x = thing->pos.sector->stuff.box[BOX_XMIN]; ret = -1; } else if(thing->pos.x > thing->pos.sector->stuff.box[BOX_XMAX]) { thing->pos.x = thing->pos.sector->stuff.box[BOX_XMAX]; ret = -1; } if(thing->pos.y < thing->pos.sector->stuff.box[BOX_YMIN]) { thing->pos.y = thing->pos.sector->stuff.box[BOX_YMIN]; ret = -1; } else if(thing->pos.y > thing->pos.sector->stuff.box[BOX_YMAX]) { thing->pos.y = thing->pos.sector->stuff.box[BOX_YMAX]; ret = -1; } return ret; } static void recursive_update_sector(kge_thing_t *thing, kge_sector_t *sec, uint32_t forced, uint32_t recursion) { float floorz; float ceilingz; engine_add_sector_link(thing, sec); sec->vc.move = vc_move; for(uint32_t i = 0; i < sec->line_count; i++) { kge_line_t *line = sec->line + i; float dist; if(!line->backsector) continue; if(kge_point_point_dist2(thing->pos.xyz, line->vertex[0]->xy) < xymove.th.r2) goto do_check; if(kge_point_point_dist2(thing->pos.xyz, line->vertex[1]->xy) < xymove.th.r2) goto do_check; dist = kge_line_point_distance(line, thing->pos.x, thing->pos.y); if(dist < 0) continue; if(dist >= thing->prop.radius) continue; dist = kge_divline_cross(thing->pos.xyz, line->stuff.normal.xy, line->vertex[0]->xy, line->stuff.dist.xy); if(dist < 0.0f || dist >= 1.0f) continue; do_check: if(line->backsector->vc.move != vc_move) { kge_sector_t *bs = line->backsector; float floorz, ceilingz; floorz = bs->plane[PLANE_BOT].height; ceilingz = bs->plane[PLANE_TOP].height; if(!forced) { if(ceilingz - floorz < xymove.th.height) continue; if(xymove.th.botz < floorz) continue; if(xymove.th.topz > ceilingz) continue; } if(floorz > thing->prop.floorz) thing->prop.floorz = floorz; if(ceilingz < thing->prop.ceilingz) thing->prop.ceilingz = ceilingz; recursive_update_sector(thing, bs, forced, recursion + 1); } } } // // thing ticker uint32_t thing_ticker(kge_thing_t *thing) { uint32_t moved = 0; if(!thing->pos.sector) return 0; // handle player input if(thing->ticcmd) { kge_ticcmd_t *tick_move = thing->ticcmd; if( tick_move->fmove != -32768 && tick_move->smove != -32768 && tick_move->pitch != -32768 ){ float speed; // angles thing->pos.angle = tick_move->angle; thing->pos.pitch = tick_move->pitch; // forward speed speed = (float)tick_move->fmove * thing->prop.speed * TICCMD_SPEED_MULT * (1.0f - FRICTION_DEFAULT); if(speed) thing_thrust(thing, speed, thing->pos.angle, thing->prop.gravity > 0.0f ? 0 : thing->pos.pitch); // side speed speed = (float)tick_move->smove * thing->prop.speed * TICCMD_SPEED_MULT * (1.0f - FRICTION_DEFAULT); if(speed) thing_thrust(thing, speed, thing->pos.angle - 0x4000, 0); } } // movement if(thing->mom.x || thing->mom.y) { // X Y int32_t ret; ret = xy_move(thing); moved = ret >= 0; if(ret < 0) { // movement failed; stop thing->mom.x = 0; thing->mom.y = 0; } else if(ret > 0) { // collision detected { // sliding kge_xy_vec_t bkup; kge_xy_vec_t diff; kge_xy_vec_t slide; float dot; diff.x = xymove.dst.x - thing->pos.x; diff.y = xymove.dst.y - thing->pos.y; slide.x = -xymove.pick.norm.y; slide.y = xymove.pick.norm.x; dot = thing->mom.x * slide.x + thing->mom.y * slide.y; slide.x *= dot; slide.y *= dot; thing->mom.x = slide.x; thing->mom.y = slide.y; xy_move(thing); } } } if(thing->mom.z) { // Z thing->pos.z += thing->mom.z; if(thing->pos.z > thing->prop.ceilingz - thing->prop.height) thing->pos.z = thing->prop.ceilingz - thing->prop.height; if(thing->pos.z < thing->prop.floorz) thing->pos.z = thing->prop.floorz; } // update sector links if(moved) thing_update_sector(thing, 0); // if(moved & 2) thing->prop.viewz = thing->pos.z + thing->prop.viewheight; // apply friction and check minimal velocity // if(thing->mom.x) { if(thing->mom.x < MIN_VELOCITY && thing->mom.x > -MIN_VELOCITY) thing->mom.x = 0; else thing->mom.x *= FRICTION_DEFAULT; } if(thing->mom.y) { if(thing->mom.y < MIN_VELOCITY && thing->mom.y > -MIN_VELOCITY) thing->mom.y = 0; else thing->mom.y *= FRICTION_DEFAULT; } if(thing->mom.z) { if(thing->mom.z < MIN_VELOCITY && thing->mom.z > -MIN_VELOCITY) thing->mom.z = 0; else if(thing->prop.gravity <= 0.0f) thing->mom.z *= FRICTION_DEFAULT; } return 0; } // // API kge_thing_t *thing_spawn(float x, float y, float z, kge_sector_t *sec) { kge_ticker_t *ticker; kge_thing_t *th; ticker = tick_create(sizeof(kge_thing_t), &tick_list_normal); ticker->info.tick = (void*)thing_ticker; th = (kge_thing_t*)&ticker->thing; th->pos.x = x; th->pos.y = y; th->pos.z = z; th->pos.sector = sec; th->prop.type = THING_TYPE_UNKNOWN; th->prop.name[0] = '\t'; th->prop.radius = 16; th->prop.height = 32; return th; } void thing_remove(kge_thing_t *th) { kge_ticker_t *ticker = (void*)th - sizeof(kge_tickhead_t); th->pos.sector = NULL; thing_update_sector(th, 0); list_del_entry(&tick_list_normal, LIST_ENTRY(ticker)); } void thing_update_sector(kge_thing_t *thing, uint32_t forced) { sector_link_t *link; // unset old poistion link = thing->thinglist; while(link) { sector_link_t *next; if(link->next_thing) link->next_thing->prev_thing = link->prev_thing; *link->prev_thing = link->next_thing; next = link->next_sector; link->next_sector = NULL; free(link); link = next; } thing->thinglist = NULL; if(!thing->pos.sector) return; thing->prop.floorz = thing->pos.sector->plane[PLANE_BOT].height; thing->prop.ceilingz = thing->pos.sector->plane[PLANE_TOP].height; xymove.th.botz = thing->pos.z; xymove.th.topz = thing->pos.z + thing->prop.height; xymove.th.r2 = thing->prop.radius * thing->prop.radius; engine_link_ptr = &thing->thinglist; vc_move++; recursive_update_sector(thing, thing->pos.sector, forced, 0); engine_link_ptr = NULL; } void thing_thrust(kge_thing_t *th, float speed, uint32_t angle, int32_t pitch) { float aaa = ANGLE_TO_RAD(angle); if(pitch) { float vvv = PITCH_TO_RAD(pitch); th->mom.z += sinf(vvv) * speed; speed *= cosf(vvv); } th->mom.x -= sinf(aaa) * speed; th->mom.y += cosf(aaa) * speed; }
0
0.85663
1
0.85663
game-dev
MEDIA
0.733782
game-dev
0.987835
1
0.987835
unresolved3169/Turanic
2,577
src/pocketmine/level/generator/populator/DeadBush.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\level\generator\populator; use pocketmine\block\Block; use pocketmine\level\ChunkManager; use pocketmine\utils\Random; class DeadBush extends Populator { /** @var ChunkManager */ private $level; private $randomAmount; private $baseAmount; /** * @param $amount */ public function setRandomAmount($amount){ $this->randomAmount = $amount; } /** * @param $amount */ public function setBaseAmount($amount){ $this->baseAmount = $amount; } /** * @param ChunkManager $level * @param $chunkX * @param $chunkZ * @param Random $random * * @return mixed|void */ public function populate(ChunkManager $level, $chunkX, $chunkZ, Random $random){ $this->level = $level; $amount = $random->nextRange(0, $this->randomAmount + 1) + $this->baseAmount; for($i = 0; $i < $amount; ++$i){ $x = $random->nextRange($chunkX * 16, $chunkX * 16 + 15); $z = $random->nextRange($chunkZ * 16, $chunkZ * 16 + 15); $y = $this->getHighestWorkableBlock($x, $z); if($y !== -1 and $this->canDeadBushStay($x, $y, $z)){ $this->level->setBlockIdAt($x, $y, $z, Block::DEAD_BUSH); $this->level->setBlockDataAt($x, $y, $z, 1); } } } /** * @param $x * @param $y * @param $z * * @return bool */ private function canDeadBushStay($x, $y, $z){ $b = $this->level->getBlockIdAt($x, $y, $z); return ($b === Block::AIR or $b === Block::SNOW_LAYER) and $this->level->getBlockIdAt($x, $y - 1, $z) === Block::SAND; } /** * @param $x * @param $z * * @return int */ private function getHighestWorkableBlock($x, $z){ for($y = 127; $y >= 0; --$y){ $b = $this->level->getBlockIdAt($x, $y, $z); if($b !== Block::AIR and $b !== Block::LEAVES and $b !== Block::LEAVES2 and $b !== Block::SNOW_LAYER){ break; } } return $y === 0 ? -1 : ++$y; } }
0
0.799684
1
0.799684
game-dev
MEDIA
0.632665
game-dev,web-backend
0.981505
1
0.981505
TouchController/TouchController
8,779
buildSrc/src/main/kotlin/TouchController.fabric-conventions.gradle.kts
import org.gradle.accessors.dm.LibrariesForLibs import top.fifthlight.touchcontoller.gradle.MinecraftVersion plugins { java id("fabric-loom") id("com.gradleup.gr8") id("r8-parallel") } val libs = the<LibrariesForLibs>() val modId: String by extra.properties val modName: String by extra.properties val modVersion: String by extra.properties val modDescription: String by extra.properties val modLicense: String by extra.properties val modHomepage: String by extra.properties val modAuthors: String by extra.properties val modContributors: String by extra.properties val modSource: String by extra.properties val modIssueTracker: String by extra.properties val javaVersion: String by extra.properties val gameVersion: String by extra.properties val fabricApiVersion: String by extra.properties val modmenuVersion: String by extra.properties val bridgeSlf4j: String by extra.properties val bridgeSlf4jBool = bridgeSlf4j.toBoolean() val excludeR8: String by extra.properties val useMojangMap: String by extra.properties val useMojangMapBool = useMojangMap.toBoolean() val minecraftVersion = MinecraftVersion(gameVersion) val useAccessWidener: String by extra.properties val useAccessWidenerBool = useAccessWidener.toBoolean() val localProperties: Map<String, String> by rootProject.ext val minecraftVmArgs = localProperties["minecraft.vm-args"]?.toString()?.split(":") ?: listOf() version = "$modVersion+fabric-$gameVersion" group = "top.fifthlight.touchcontroller" configurations { create("shadow") create("resource") } tasks.jar { archiveBaseName = "$modName-slim" } fun DependencyHandlerScope.shade(dependency: Any) { add("shadow", dependency) } fun DependencyHandlerScope.shade( dependency: String, dependencyConfiguration: ExternalModuleDependency.() -> Unit, ) { add("shadow", dependency, dependencyConfiguration) } fun <T : ModuleDependency> DependencyHandlerScope.shade( dependency: T, dependencyConfiguration: T.() -> Unit, ) { add("shadow", dependency, dependencyConfiguration) } fun DependencyHandlerScope.shadeAndImplementation(dependency: Any) { shade(dependency) implementation(dependency) } fun DependencyHandlerScope.shadeAndImplementation( dependency: String, dependencyConfiguration: ExternalModuleDependency.() -> Unit ) { shade(dependency, dependencyConfiguration) implementation(dependency, dependencyConfiguration) } fun <T : ModuleDependency> DependencyHandlerScope.shadeAndImplementation( dependency: T, dependencyConfiguration: T.() -> Unit, ) { shade(dependency, dependencyConfiguration) implementation(dependency, dependencyConfiguration) } fun DependencyHandlerScope.resource(dependency: Any) { add("resource", dependency) } dependencies { minecraft("com.mojang:minecraft:$gameVersion") if (useMojangMapBool) { val parchmentVersion = properties["parchmentVersion"]?.toString() if (parchmentVersion != null) { mappings(loom.layered { officialMojangMappings() parchment("org.parchmentmc.data:parchment-$gameVersion:$parchmentVersion@zip") }) } else { mappings(loom.officialMojangMappings()) } } else { val yarnVersion: String by properties mappings("net.fabricmc:yarn:$yarnVersion:v2") } modImplementation(libs.fabric.loader) resource(project(":mod:resources", "texture")) resource(project(":mod:resources", "fabric-icon")) resource(project(":mod:resources", "lang")) modImplementation("net.fabricmc.fabric-api:fabric-api:$fabricApiVersion") modImplementation("com.terraformersmc:modmenu:$modmenuVersion") shadeAndImplementation(project(":mod:common")) { exclude("org.slf4j") } shadeAndImplementation(project(":combine")) shadeAndImplementation(project(":mod:common-fabric")) shadeAndImplementation(project(":mod:common-lwjgl3")) if (bridgeSlf4jBool) { shadeAndImplementation(project(":log4j-slf4j2-impl")) { exclude("org.apache.logging.log4j") } } if (minecraftVersion < MinecraftVersion(1, 19, 3)) { shadeAndImplementation(libs.joml) } } loom { runs.configureEach { vmArgs.addAll(minecraftVmArgs) } mixin { useLegacyMixinAp = false } if (useAccessWidenerBool) { accessWidenerPath.set(file("../common-$gameVersion/src/main/resources/touchcontroller.accesswidener")) } } tasks.processResources { val modAuthorsList = modAuthors.split(",").map(String::trim).filter(String::isNotEmpty) val modContributorsList = modContributors.split(",").map(String::trim).filter(String::isNotEmpty) fun String.quote(quoteStartChar: Char = '"', quoteEndChar: Char = '"') = quoteStartChar + this + quoteEndChar val modAuthorsArray = modAuthorsList.joinToString(", ", transform = String::quote).drop(1).dropLast(1) val modContributorsArray = modContributorsList.joinToString(", ", transform = String::quote).drop(1).dropLast(1) // Fabric API changed its mod ID to "fabric-api" in version 1.19.2 val fabricApiName = if (minecraftVersion >= MinecraftVersion(1, 19, 2)) { "fabric-api" } else { "fabric" } val properties = mutableMapOf( "mod_id" to modId, "mod_version_full" to version, "mod_name" to modName, "mod_description" to modDescription, "mod_license" to modLicense, "mod_homepage" to modHomepage, "mod_authors_string" to modAuthors, "mod_contributors_string" to modContributors, "mod_authors_array" to modAuthorsArray, "mod_contributors_array" to modContributorsArray, "mod_source" to modSource, "mod_issue_tracker" to modIssueTracker, "fabric_loader_version" to libs.versions.fabric.loader.get(), "game_version" to gameVersion, "java_version" to javaVersion, "fabric_api_name" to fabricApiName, "fabric_api_version" to fabricApiVersion, ) properties += if (useAccessWidenerBool) { "access_widener_entry" to """, "accessWidener": "touchcontroller.accesswidener"""" } else { "access_widener_entry" to "" } inputs.properties(properties) from(fileTree(project(":mod:common-fabric").layout.projectDirectory.file("src/main/resources"))) { expand(properties) } from(File(rootDir, "LICENSE")) { rename { "${it}_${modName}" } } from(configurations["resource"].elements.map { fileSet -> fileSet.map { fileLocation -> val fileName = fileLocation.asFile.name if (fileName.endsWith(".jar")) { zipTree(fileLocation) } else { fileLocation } } }) { exclude("META-INF/MANIFEST.MF") } if (useAccessWidenerBool) { from(file("../common-$gameVersion/src/main/resources/touchcontroller.accesswidener")) } } val minecraftShadow = configurations.create("minecraftShadow") { excludeR8.split(",").filter(String::isNotEmpty).forEach { if (it.contains(":")) { val (group, module) = it.split(":") exclude(group, module) } else { exclude(it) } } extendsFrom(configurations.compileClasspath.get()) } gr8 { create("gr8") { addProgramJarsFrom(configurations.getByName("shadow")) addProgramJarsFrom(tasks.jar) addClassPathJarsFrom(minecraftShadow) r8Version("8.9.21") proguardFile(rootProject.file("mod/common-fabric/rules.pro")) } } tasks.remapJar { dependsOn("gr8Gr8ShadowedJar") val jarFile = tasks.getByName("gr8Gr8ShadowedJar").outputs.files .first { it.extension.equals("jar", ignoreCase = true) } inputFile = jarFile archiveBaseName = "$modName-fat" addNestedDependencies = false } val copyJarTask = tasks.register<Jar>("copyJar") { dependsOn(tasks.remapJar) archiveBaseName = modName duplicatesStrategy = DuplicatesStrategy.EXCLUDE isPreserveFileTimestamps = false isReproducibleFileOrder = true val jarFile = tasks.remapJar.get().outputs.files.files.first() manifest { from({ zipTree(jarFile).first { it.name == "MANIFEST.MF" } }) } val excludeWhitelist = listOf("org.slf4j.spi.SLF4JServiceProvider") from(zipTree(jarFile)) { exclude { file -> val path = file.relativePath if (path.segments.first() == "META-INF") { excludeWhitelist.all { !path.endsWith(it) } } else { path.lastName == "module-info.class" } } } } tasks.assemble { dependsOn(copyJarTask) }
0
0.977529
1
0.977529
game-dev
MEDIA
0.924362
game-dev
0.874879
1
0.874879
aybe/DearImGui
2,960
DearGenerator/TypeMaps/TypeMapImVector.cs
using System.Text.RegularExpressions; using CppSharp.AST; using CppSharp.Generators; using CppSharp.Generators.CSharp; using CppSharp.Types; using JetBrains.Annotations; using Type = CppSharp.AST.Type; namespace DearGenerator.TypeMaps; [UsedImplicitly] [TypeMap("ImVector", GeneratorKind.CSharp)] internal sealed class TypeMapImVector : TypeMapBase { public override Type CSharpSignatureType(TypePrinterContext ctx) { if ((ctx.Kind, ctx.MarshalKind) is (TypePrinterContextKind.Native, MarshalKind.NativeField)) { return new CustomType("ImVector.__Internal"); // the stuff is auto-generated by CppSharp } var args = ((TemplateSpecializationType)ctx.Type).Arguments[0].Type.Type; var type = new CustomType($"ImVector<{args}>"); return type; } public override void CSharpMarshalToManaged(CSharpMarshalContext ctx) { if (ctx.Function == null) { if (ctx.ReturnVarName == null) { // NOP } else { var args = ((TemplateSpecializationType)ctx.ReturnType.Type).Arguments[0]; var type = $"ImVector<{args}>"; var data = Regex.Replace(ctx.ReturnVarName, @"^new __IntPtr\(&(.*)\)$", @"$1"); var text = $"new {type}(Unsafe.As<ImVector.__Internal, {type}.__Internal>(ref {data}))"; ctx.Return.Write(text); } } else { if (ctx.ReturnVarName == null) { // NOP } else { if (ctx.ReturnType.Type is PointerType) { ctx.Return.Write($"Unsafe.Read<ImVector>({ctx.ReturnVarName}.ToPointer())"); } else { ctx.Return.Write(ctx.ReturnVarName); } } } base.CSharpMarshalToManaged(ctx); } public override void CSharpMarshalToNative(CSharpMarshalContext ctx) { if (ctx.Function == null) { if (ctx.ReturnVarName == null) { // NOP } else { ctx.Return.Write(ctx.ReturnVarName); // not valid but pruned by SetPropertyAsReadOnly } } else { if (ctx.ReturnVarName == null) { if (ctx.Parameter.IsConst || ctx.Parameter.HasDefaultValue is false) { ctx.Return.Write($"new IntPtr(Unsafe.AsPointer(ref {ctx.Parameter.Name}))"); } else { ctx.Return.Write($"{ctx.Parameter.Name}"); } } else { ctx.Return.Write(ctx.ReturnVarName); } } base.CSharpMarshalToNative(ctx); } }
0
0.955579
1
0.955579
game-dev
MEDIA
0.295292
game-dev
0.881705
1
0.881705
chaldea-center/chaldea
11,024
lib/app/battle/functions/add_state.dart
import 'package:chaldea/app/api/atlas.dart'; import 'package:chaldea/app/battle/models/battle.dart'; import 'package:chaldea/app/battle/utils/buff_utils.dart'; import 'package:chaldea/generated/l10n.dart'; import 'package:chaldea/models/db.dart'; import 'package:chaldea/models/gamedata/gamedata.dart'; import 'package:chaldea/utils/utils.dart'; import '../interactions/td_type_change_selector.dart'; class AddState { AddState._(); static Future<void> addState( final BattleData battleData, final Buff buff, final int funcId, final DataVals dataVals, final BattleServantData? activator, final List<BattleServantData> targets, { final bool isShortBuff = false, final SelectTreasureDeviceInfo? selectTreasureDeviceInfo, final SkillType? skillType, final SkillInfoType? skillInfoType, }) async { final isClassPassive = skillInfoType == SkillInfoType.svtClassPassive; final isCommandCode = skillInfoType == SkillInfoType.commandCode; // skillInfoType != null means it's from a proper skill. Otherwise the concept of passive doesn't apply // e.g. from trigger buffs bool isPassive = skillType == SkillType.passive && skillInfoType != null; if (dataVals.ProcActive == 1) { isPassive = false; } else if (dataVals.ProcPassive == 1) { isPassive = true; } // based on video if (buff.type == BuffType.donotSelectCommandcard) { for (final actor in battleData.nonnullActors) { actor.battleBuff.removeBuffOfType(BuffType.donotSelectCommandcard); } } for (final target in targets) { final buffData = BuffData( buff: buff, vals: dataVals, addOrder: battleData.getNextAddOrder(), activatorUniqueId: activator?.uniqueId, activatorName: activator?.lBattleName, ownerUniqueId: target.uniqueId, passive: isPassive, skillInfoType: skillInfoType, ); // Processing logicTurn related logic if (isShortBuff) { buffData.logicTurn -= 1; } // enemy Bazett may not contains niceSvt if (target.niceSvt?.script?.svtBuffTurnExtend == true || target.svtId == 1001100) { if (ConstData.constantStr.extendTurnBuffType.contains(buff.type.value)) { buffData.logicTurn += 1; } } final isOpponentTurn = target.isPlayer != battleData.isPlayerTurn; if (isOpponentTurn) { if (dataVals.ExtendBuffHalfTurnInOpponentTurn == 1) buffData.logicTurn += 1; if (dataVals.ShortenBuffHalfTurnInOpponentTurn == 1) buffData.logicTurn -= 1; } else { if (dataVals.ExtendBuffHalfTurnInPartyTurn == 1) buffData.logicTurn += 1; if (dataVals.ShortenBuffHalfTurnInPartyTurn == 1) buffData.logicTurn -= 1; } // Processing special logic for certain buff types if (buff.type.isTdTypeChange) { buffData.tdTypeChange = await getTypeChangeTd(battleData, target, buff, selectTreasureDeviceInfo); } else if (buff.type == BuffType.upDamageEventPoint) { final pointBuff = battleData.options.pointBuffs.values.firstWhereOrNull( (pointBuff) => pointBuff.funcIds.isEmpty || pointBuff.funcIds.contains(funcId), ); if (pointBuff == null) { continue; } buffData.param += pointBuff.value; } else if (buff.type == BuffType.overwriteBattleclass) { // it is unclear what this will do for now, the only example is when TargetEnemyClass is set to 1 final targetEnemyClassId = battleData.getTargetedEnemy(target)?.logicalClassId; if (dataVals.TargetEnemyClass == 1) { if (targetEnemyClassId == target.logicalClassId || !ConstData.constantStr.enableOverwriteClassIds.contains(targetEnemyClassId)) { continue; } buffData.param = targetEnemyClassId!; } } buffData.shortenMaxCountEachSkill = dataVals.ShortenMaxCountEachSkill?.toList(); // convert Buff checks for (final convertBuff in collectBuffsPerAction(target.battleBuff.validBuffs, BuffAction.buffConvert)) { if (await convertBuff.shouldActivateBuff( battleData, BattleServantData.fetchSelfTraits(BuffAction.buffConvert, convertBuff, target), opponentTraits: BattleServantData.fetchOpponentTraits(BuffAction.buffConvert, convertBuff, activator), buffToCheck: buff, )) { Buff? convertedBuff; final convert = convertBuff.buff.script.convert; if (convert != null) { switch (convert.convertType) { case BuffConvertType.none: break; case BuffConvertType.buff: for (final (index, targetBuff) in convert.targetBuffs.indexed) { if (targetBuff.id == buff.id) { convertedBuff = convert.convertBuffs[index]; break; } } break; case BuffConvertType.individuality: for (final (index, targetIndiv) in convert.targetIndividualities.indexed) { if (buff.vals.contains(targetIndiv)) { convertedBuff = convert.convertBuffs[index]; break; } } break; } if (convertedBuff != null) { buffData.buff = convertedBuff; convertBuff.setUsed(target, battleData); } } } } final isStackable = target.isBuffStackable(buffData.buff.buffGroup) && checkSameBuffLimitNum(target, dataVals); if (isStackable && await shouldAddState(battleData, dataVals, activator, target, buffData, isCommandCode, isClassPassive)) { target.addBuff(buffData, isPassive: isPassive, isCommandCode: isCommandCode); buffData.updateActState(battleData, target); battleData.setFuncResult(target.uniqueId, true); target.postAddStateProcessing(buffData, dataVals); } } } static bool checkSameBuffLimitNum(final BattleServantData target, final DataVals dataVals) { return dataVals.SameBuffLimitNum == null || dataVals.SameBuffLimitNum! > target.countBuffWithTrait([dataVals.SameBuffLimitTargetIndividuality!]); } static Future<bool> shouldAddState( final BattleData battleData, final DataVals dataVals, final BattleServantData? activator, final BattleServantData target, final BuffData buffData, final bool isCommandCode, final bool isSvtClassPassive, ) async { if (dataVals.ForceAddState == 1 || isCommandCode) { return true; } int functionRate = dataVals.Rate ?? 1000; if (functionRate < 0 && battleData.functionResults.lastOrNull?[target.uniqueId] != true) { return false; } functionRate = functionRate.abs(); // based on https://discord.com/channels/839788731108032532/1098222580755861545/1278033086981865646 // svtClassPassive should ignore all avoidState buffs if (!isSvtClassPassive) { final hasAvoidState = await target.hasBuff( battleData, BuffAction.avoidState, opponent: activator, addTraits: buffData.getTraits(), ); if (hasAvoidState) { battleData.battleLogger.debug( '${S.current.effect_target}: ${target.lBattleName} - ${S.current.battle_invalid}', ); return false; } } final buffReceiveChance = await target.getBuffValue( battleData, BuffAction.resistanceState, opponent: activator, addTraits: buffData.getTraits(), ); final buffChance = await activator?.getBuffValue( battleData, BuffAction.grantState, opponent: target, addTraits: buffData.getTraits(), ) ?? 0; final activationRate = functionRate + buffChance; final resistRate = buffReceiveChance; final success = await battleData.canActivateFunction(activationRate - resistRate); final resultsString = success ? S.current.success : resistRate > 0 ? 'GUARD' : 'MISS'; battleData.battleLogger.debug( '${S.current.effect_target}: ${target.lBattleName} - ' '$resultsString' '${battleData.options.tailoredExecution ? '' : ' [($activationRate - $resistRate) vs ${battleData.options.threshold}]'}', ); return success; } static Future<NiceTd?> getTypeChangeTd( BattleData battleData, BattleServantData svt, Buff buff, SelectTreasureDeviceInfo? selectTreasureDeviceInfo, ) async { final NiceTd? baseTd = svt.getBaseTD(); if (baseTd == null) return null; if (!buff.type.isTdTypeChange) return null; final tdTypeChangeIDs = baseTd.script?.tdTypeChangeIDs; if (tdTypeChangeIDs == null || tdTypeChangeIDs.isEmpty) return null; // hardcoding since there's no NP with extra card type final validCardIndex = <int>[CardType.arts.value, CardType.buster.value, CardType.quick.value]; validCardIndex.retainWhere((e) => e <= tdTypeChangeIDs.length); if (validCardIndex.isEmpty) return null; // in UI, Q/A/B order int? targetTdIndex; if (buff.type == BuffType.tdTypeChangeArts) { targetTdIndex = CardType.arts.value; } else if (buff.type == BuffType.tdTypeChangeBuster) { targetTdIndex = CardType.buster.value; } else if (buff.type == BuffType.tdTypeChangeQuick) { targetTdIndex = CardType.quick.value; } else if (buff.type == BuffType.tdTypeChange) { final excludeTypes = baseTd.script?.excludeTdChangeTypes; if (excludeTypes != null && excludeTypes.isNotEmpty) { validCardIndex.removeWhere((e) => excludeTypes.contains(e)); } if (battleData.delegate?.tdTypeChange != null) { targetTdIndex = await battleData.delegate!.tdTypeChange!(svt, validCardIndex); } else if (battleData.mounted) { selectTreasureDeviceInfo ??= svt.getBaseTD()?.script?.selectTreasureDeviceInfo?.getOrNull(svt.tdLv - 1); targetTdIndex = await TdTypeChangeSelector.show( battleData, tdTypeChangeIDs, validCardIndex, selectTreasureDeviceInfo, ); if (targetTdIndex != null) { battleData.replayDataRecord.tdTypeChanges.add(targetTdIndex); } } } NiceTd? targetTd; if (targetTdIndex != null && validCardIndex.contains(targetTdIndex)) { // start from Q/A/B=1/2/3 -> index 0/1/2 final tdId = tdTypeChangeIDs.getOrNull(targetTdIndex - 1); if (tdId == null) return null; final List<NiceTd?> tds = svt.isPlayer ? (svt.playerSvtData?.svt?.noblePhantasms ?? []) : (svt.niceSvt?.noblePhantasms ?? [svt.niceEnemy?.noblePhantasm.noblePhantasm]); targetTd = tds.lastWhereOrNull((e) => e?.id == tdId); targetTd ??= await showEasyLoading(() => AtlasApi.td(tdId, svtId: svt.svtId), mask: true); } return targetTd; } }
0
0.818228
1
0.818228
game-dev
MEDIA
0.948052
game-dev
0.975541
1
0.975541
Lothrazar/Cyclic
1,523
src/main/java/com/lothrazar/cyclic/block/miner/ContainerMiner.java
package com.lothrazar.cyclic.block.miner; import com.lothrazar.cyclic.gui.ContainerBase; import com.lothrazar.cyclic.registry.BlockRegistry; import com.lothrazar.cyclic.registry.MenuTypeRegistry; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.level.Level; import net.minecraftforge.items.SlotItemHandler; public class ContainerMiner extends ContainerBase { TileMiner tile; public ContainerMiner(int windowId, Level world, BlockPos pos, Inventory playerInventory, Player player) { super(MenuTypeRegistry.MINER.get(), windowId); tile = (TileMiner) world.getBlockEntity(pos); this.playerEntity = player; this.playerInventory = playerInventory; this.endInv = tile.inventory.getSlots(); addSlot(new SlotItemHandler(tile.inventory, 0, 33, 9) { @Override public void setChanged() { tile.setChanged(); } }); addSlot(new SlotItemHandler(tile.inventory, 1, 135, 9) { @Override public void setChanged() { tile.setChanged(); } }); layoutPlayerInventorySlots(8, 84); trackEnergy(tile); this.trackAllIntFields(tile, TileMiner.Fields.values().length); } @Override public boolean stillValid(Player playerIn) { return stillValid(ContainerLevelAccess.create(tile.getLevel(), tile.getBlockPos()), playerEntity, BlockRegistry.MINER.get()); } }
0
0.845304
1
0.845304
game-dev
MEDIA
0.998341
game-dev
0.965776
1
0.965776
goonstation/goonstation
3,612
code/modules/maptext/_maptext_manager.dm
/// The maptext manager of this `atom`, responsible for displaying maptext over this atom to clients. /atom/var/atom/movable/maptext_manager/maptext_manager /atom/disposing() qdel(src.maptext_manager) . = ..() /** * Maptext manager `atom/movable`s govern displaying maptext over single parent atom. To this end, they track the outermost movable * of the parent atom, and relocate to the outermost loc if possible. To display maptext to a client, the list of maptext holders * indexed by their associated clients is queried for the maptext holder associated with that client, and instructed to add a line. */ /atom/movable/maptext_manager appearance_flags = RESET_COLOR | RESET_ALPHA | RESET_TRANSFORM | KEEP_APART | TILE_BOUND | PIXEL_SCALE mouse_opacity = 0 /// The atom that this maptext manager belongs to. var/atom/parent /// Whether this maptext manager is registered to the `XSIG_OUTERMOST_MOVABLE_CHANGED` complex signal. var/registered = FALSE /// A list of maptext holders belonging to this maptext manager, indexed by their associated clients. var/list/atom/movable/maptext_holder/maptext_holders_by_client /atom/movable/maptext_manager/New(atom/parent) . = ..() src.parent = parent src.maptext_holders_by_client = list() src.set_loc(null) /atom/movable/maptext_manager/disposing() for (var/client/client as anything in src.maptext_holders_by_client) qdel(src.maptext_holders_by_client[client]) src.notify_empty() src.parent.maptext_manager = null src.parent = null src.maptext_holders_by_client = null . = ..() /// Adds a line of maptext to the maptext holder associated with the specified client, displaying the maptext over the parent atom. /atom/movable/maptext_manager/proc/add_maptext(client/client, image/maptext/text) if (client.preferences.flying_chat_hidden && text.respect_maptext_preferences) return src.maptext_holders_by_client[client] ||= new /atom/movable/maptext_holder(src, client) src.maptext_holders_by_client[client].add_line(text) /// Notifies this maptext manager that the maptext holder of the specified client is empty. If all maptext holders are empty, the `XSIG_OUTERMOST_MOVABLE_CHANGED` complex signal is unregistered. /atom/movable/maptext_manager/proc/notify_empty(client/client) if (client) qdel(src.maptext_holders_by_client[client]) if (length(src.maptext_holders_by_client) || !src.registered) return src.vis_locs = null UnregisterSignal(src.parent, XSIG_OUTERMOST_MOVABLE_CHANGED) src.registered = FALSE /// Notifies this maptext manager that a maptext holder is nonempty, requiring it to register the `XSIG_OUTERMOST_MOVABLE_CHANGED` complex signal if not already done so. /atom/movable/maptext_manager/proc/notify_nonempty() if (src.registered) return if (!ismovable(src.parent)) src.update_outermost_movable(null, null, src.parent) return src.update_outermost_movable(null, null, global.outermost_movable(src.parent)) RegisterSignal(src.parent, XSIG_OUTERMOST_MOVABLE_CHANGED, PROC_REF(update_outermost_movable)) src.registered = TRUE /// Update the loc of this maptext manager to specified new outermost movable. Used with `XSIG_OUTERMOST_MOVABLE_CHANGED`. /atom/movable/maptext_manager/proc/update_outermost_movable(datum/component/component, atom/movable/old_outermost, atom/movable/new_outermost) src.vis_locs = null // Use a turf for the maptext holder if the outermost in a disposal pipe or other such underfloor things. if ((new_outermost.level == UNDERFLOOR) && (new_outermost.invisibility == INVIS_ALWAYS)) new_outermost = new_outermost.loc new_outermost.vis_contents += src
0
0.818657
1
0.818657
game-dev
MEDIA
0.444281
game-dev
0.653966
1
0.653966
TheKisDevs/LavaHack-Public
1,487
src/main/java/com/kisman/cc/module/movement/NoSlowBypass.java
package com.kisman.cc.module.movement; import com.kisman.cc.module.Category; import com.kisman.cc.module.Module; import net.minecraft.item.Item; import net.minecraft.item.ItemBow; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemPotion; import net.minecraft.network.play.client.CPacketEntityAction; import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class NoSlowBypass extends Module { private boolean sneaking; public NoSlowBypass() { super("NoSlowBypass", "NoSlowBypass", Category.MOVEMENT); } public void update() { if(mc.player != null || mc.world != null) { Item item = mc.player.getActiveItemStack().getItem(); if (sneaking && ((!mc.player.isHandActive() && item instanceof ItemFood || item instanceof ItemBow || item instanceof ItemPotion) || (!(item instanceof ItemFood) || !(item instanceof ItemBow) || !(item instanceof ItemPotion)))) { mc.player.connection.sendPacket(new CPacketEntityAction(mc.player, CPacketEntityAction.Action.STOP_SNEAKING)); sneaking = false; } } } @SubscribeEvent public void onUseItem(LivingEntityUseItemEvent event) { if (!sneaking) { mc.player.connection.sendPacket(new CPacketEntityAction(mc.player, CPacketEntityAction.Action.START_SNEAKING)); sneaking = true; } } }
0
0.615695
1
0.615695
game-dev
MEDIA
0.994525
game-dev
0.588866
1
0.588866
passiony/ETFramework
9,829
Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Core/Misc/MovementUtilities.cs
using System.Collections; using PF; using Mathf = UnityEngine.Mathf; using Vector2 = UnityEngine.Vector2; namespace Pathfinding.Util { public static class MovementUtilities { /** Clamps the velocity to the max speed and optionally the forwards direction. * \param velocity Desired velocity of the character. In world units per second. * \param maxSpeed Max speed of the character. In world units per second. * \param slowdownFactor Value between 0 and 1 which determines how much slower the character should move than normal. * Normally 1 but should go to 0 when the character approaches the end of the path. * \param slowWhenNotFacingTarget Prevent the velocity from being too far away from the forward direction of the character * and slow the character down if the desired velocity is not in the same direction as the forward vector. * \param forward Forward direction of the character. Used together with the \a slowWhenNotFacingTarget parameter. * * Note that all vectors are 2D vectors, not 3D vectors. * * \returns The clamped velocity in world units per second. */ public static Vector2 ClampVelocity (Vector2 velocity, float maxSpeed, float slowdownFactor, bool slowWhenNotFacingTarget, Vector2 forward) { // Max speed to use for this frame var currentMaxSpeed = maxSpeed * slowdownFactor; // Check if the agent should slow down in case it is not facing the direction it wants to move in if (slowWhenNotFacingTarget && (forward.x != 0 || forward.y != 0)) { float currentSpeed; var normalizedVelocity = VectorMath.Normalize(velocity.ToPFV2(), out currentSpeed); float dot = Vector2.Dot(normalizedVelocity.ToUnityV2(), forward); // Lower the speed when the character's forward direction is not pointing towards the desired velocity // 1 when velocity is in the same direction as forward // 0.2 when they point in the opposite directions float directionSpeedFactor = Mathf.Clamp(dot+0.707f, 0.2f, 1.0f); currentMaxSpeed *= directionSpeedFactor; currentSpeed = Mathf.Min(currentSpeed, currentMaxSpeed); // Angle between the forwards direction of the character and our desired velocity float angle = Mathf.Acos(Mathf.Clamp(dot, -1, 1)); // Clamp the angle to 20 degrees // We cannot keep the velocity exactly in the forwards direction of the character // because we use the rotation to determine in which direction to rotate and if // the velocity would always be in the forwards direction of the character then // the character would never rotate. // Allow larger angles when near the end of the path to prevent oscillations. angle = Mathf.Min(angle, (20f + 180f*(1 - slowdownFactor*slowdownFactor))*Mathf.Deg2Rad); float sin = Mathf.Sin(angle); float cos = Mathf.Cos(angle); // Determine if we should rotate clockwise or counter-clockwise to move towards the current velocity sin *= Mathf.Sign(normalizedVelocity.x*forward.y - normalizedVelocity.y*forward.x); // Rotate the #forward vector by #angle radians // The rotation is done using an inlined rotation matrix. // See https://en.wikipedia.org/wiki/Rotation_matrix return new Vector2(forward.x*cos + forward.y*sin, forward.y*cos - forward.x*sin) * currentSpeed; } else { return Vector2.ClampMagnitude(velocity, currentMaxSpeed); } } /** Calculate an acceleration to move deltaPosition units and get there with approximately a velocity of targetVelocity */ public static Vector2 CalculateAccelerationToReachPoint (Vector2 deltaPosition, Vector2 targetVelocity, Vector2 currentVelocity, float forwardsAcceleration, float rotationSpeed, float maxSpeed, Vector2 forwardsVector) { // Guard against div by zero if (forwardsAcceleration <= 0) return Vector2.zero; float currentSpeed = currentVelocity.magnitude; // Convert rotation speed to an acceleration // See https://en.wikipedia.org/wiki/Centripetal_force var sidewaysAcceleration = currentSpeed * rotationSpeed * Mathf.Deg2Rad; // To avoid weird behaviour when the rotation speed is very low we allow the agent to accelerate sideways without rotating much // if the rotation speed is very small. Also guards against division by zero. sidewaysAcceleration = Mathf.Max(sidewaysAcceleration, forwardsAcceleration); sidewaysAcceleration = forwardsAcceleration; // Transform coordinates to local space where +X is the forwards direction // This is essentially equivalent to Transform.InverseTransformDirection. deltaPosition = VectorMath.ComplexMultiplyConjugate(deltaPosition.ToPFV2(), forwardsVector.ToPFV2()).ToUnityV2(); targetVelocity = VectorMath.ComplexMultiplyConjugate(targetVelocity.ToPFV2(), forwardsVector.ToPFV2()).ToUnityV2(); currentVelocity = VectorMath.ComplexMultiplyConjugate(currentVelocity.ToPFV2(), forwardsVector.ToPFV2()).ToUnityV2(); float ellipseSqrFactorX = 1 / (forwardsAcceleration*forwardsAcceleration); float ellipseSqrFactorY = 1 / (sidewaysAcceleration*sidewaysAcceleration); // If the target velocity is zero we can use a more fancy approach // and calculate a nicer path. // In particular, this is the case at the end of the path. if (targetVelocity == Vector2.zero) { // Run a binary search over the time to get to the target point. float mn = 0.01f; float mx = 10; while (mx - mn > 0.01f) { var time = (mx + mn) * 0.5f; // Given that we want to move deltaPosition units from out current position, that our current velocity is given // and that when we reach the target we want our velocity to be zero. Also assume that our acceleration will // vary linearly during the slowdown. Then we can calculate what our acceleration should be during this frame. //{ t = time //{ deltaPosition = vt + at^2/2 + qt^3/6 //{ 0 = v + at + qt^2/2 //{ solve for a // a = acceleration vector // q = derivative of the acceleration vector var a = (6*deltaPosition - 4*time*currentVelocity)/(time*time); var q = 6*(time*currentVelocity - 2*deltaPosition)/(time*time*time); // Make sure the acceleration is not greater than our maximum allowed acceleration. // If it is we increase the time we want to use to get to the target // and if it is not, we decrease the time to get there faster. // Since the acceleration is described by acceleration = a + q*t // we only need to check at t=0 and t=time. // Note that the acceleration limit is described by an ellipse, not a circle. var nextA = a + q*time; if (a.x*a.x*ellipseSqrFactorX + a.y*a.y*ellipseSqrFactorY > 1.0f || nextA.x*nextA.x*ellipseSqrFactorX + nextA.y*nextA.y*ellipseSqrFactorY > 1.0f) { mn = time; } else { mx = time; } } var finalAcceleration = (6*deltaPosition - 4*mx*currentVelocity)/(mx*mx); // Boosting { // The trajectory calculated above has a tendency to use very wide arcs // and that does unfortunately not look particularly good in some cases. // Here we amplify the component of the acceleration that is perpendicular // to our current velocity. This will make the agent turn towards the // target quicker. // How much amplification to use. Value is unitless. const float Boost = 1; finalAcceleration.y *= 1 + Boost; // Clamp the velocity to the maximum acceleration. // Note that the maximum acceleration constraint is shaped like an ellipse, not like a circle. float ellipseMagnitude = finalAcceleration.x*finalAcceleration.x*ellipseSqrFactorX + finalAcceleration.y*finalAcceleration.y*ellipseSqrFactorY; if (ellipseMagnitude > 1.0f) finalAcceleration /= Mathf.Sqrt(ellipseMagnitude); } return VectorMath.ComplexMultiply(finalAcceleration.ToPFV2(), forwardsVector.ToPFV2()).ToUnityV2(); } else { // Here we try to move towards the next waypoint which has been modified slightly using our // desired velocity at that point so that the agent will more smoothly round the corner. // How much to strive for making sure we reach the target point with the target velocity. Unitless. const float TargetVelocityWeight = 0.5f; // Limit to how much to care about the target velocity. Value is in seconds. // This prevents the character from moving away from the path too much when the target point is far away const float TargetVelocityWeightLimit = 1.5f; float targetSpeed; var normalizedTargetVelocity = VectorMath.Normalize(targetVelocity.ToPFV2(), out targetSpeed); var distance = deltaPosition.magnitude; var targetPoint = deltaPosition.ToPFV2() - normalizedTargetVelocity * System.Math.Min(TargetVelocityWeight * distance * targetSpeed / (currentSpeed + targetSpeed), maxSpeed*TargetVelocityWeightLimit); // How quickly the agent will try to reach the velocity that we want it to have. // We need this to prevent oscillations and jitter which is what happens if // we let the constant go towards zero. Value is in seconds. const float TimeToReachDesiredVelocity = 0.1f; // TODO: Clamp to ellipse using more accurate acceleration (use rotation speed as well) var finalAcceleration = (targetPoint.normalized*maxSpeed - currentVelocity.ToPFV2()) * (1f/TimeToReachDesiredVelocity); // Clamp the velocity to the maximum acceleration. // Note that the maximum acceleration constraint is shaped like an ellipse, not like a circle. float ellipseMagnitude = finalAcceleration.x*finalAcceleration.x*ellipseSqrFactorX + finalAcceleration.y*finalAcceleration.y*ellipseSqrFactorY; if (ellipseMagnitude > 1.0f) finalAcceleration /= Mathf.Sqrt(ellipseMagnitude); return VectorMath.ComplexMultiply(finalAcceleration, forwardsVector.ToPFV2()).ToUnityV2(); } } } }
0
0.964182
1
0.964182
game-dev
MEDIA
0.878341
game-dev
0.979234
1
0.979234
wulonghao/UGCFramework
3,309
ExampleProject/UnityProject/Packages/com.code-philosophy.hybridclr/Editor/MethodBridge/PlatformGeneratorArm64.cs
using dnlib.DotNet; using HybridCLR.Editor.ABI; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace HybridCLR.Editor.MethodBridge { public class PlatformGeneratorArm64 : PlatformGeneratorBase { public override PlatformABI PlatformABI { get; } = PlatformABI.Universal64; public override void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines) { string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" })); string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => p.Managed2NativeParamValue(this.PlatformABI)).Concat(new string[] { "method" })); lines.Add($@" static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret) {{ typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr}); {(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr}); }} "); } public override void GenerateNative2ManagedMethod(MethodDesc method, List<string> lines) { int totalQuadWordNum = method.ParamInfos.Count + method.ReturnInfo.GetParamSlotNum(this.PlatformABI); string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" })); lines.Add($@" static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}({paramListStr}) {{ StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => p.Native2ManagedParamValue(this.PlatformABI)))} }}; StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)}; Interpreter::Execute(method, args, ret); {(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")} }} "); } public override void GenerateAdjustThunkMethod(MethodDesc method, List<string> lines) { int totalQuadWordNum = method.ParamInfos.Count + method.ReturnInfo.GetParamSlotNum(this.PlatformABI); string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" })); lines.Add($@" static {method.ReturnInfo.Type.GetTypeName()} __N2M_AdjustorThunk_{method.CreateCallSigName()}({paramListStr}) {{ StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => (p.Index == 0 ? $"(uint64_t)(*(uint8_t**)&__arg{p.Index} + sizeof(Il2CppObject))" : p.Native2ManagedParamValue(this.PlatformABI))))} }}; StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)}; Interpreter::Execute(method, args, ret); {(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")} }} "); } } }
0
0.817994
1
0.817994
game-dev
MEDIA
0.269302
game-dev
0.904473
1
0.904473
Ilyaki/ProtoInput
7,547
lib/imgui/backends/imgui_impl_glut.cpp
// dear imgui: Platform Backend for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! // !!! Nowadays, prefer using GLFW or SDL instead! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I // [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2019-04-03: Misc: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. // 2019-03-25: Misc: Made io.DeltaTime always above zero. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-03-22: Added GLUT Platform binding. #include "imgui.h" #include "imgui_impl_glut.h" #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif #ifdef _MSC_VER #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #endif static int g_Time = 0; // Current time, in milliseconds bool ImGui_ImplGLUT_Init() { ImGuiIO& io = ImGui::GetIO(); #ifdef FREEGLUT io.BackendPlatformName = "imgui_impl_glut (freeglut)"; #else io.BackendPlatformName = "imgui_impl_glut"; #endif g_Time = 0; // Glut has 1 function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above. io.KeyMap[ImGuiKey_Tab] = '\t'; // == 9 == CTRL+I io.KeyMap[ImGuiKey_LeftArrow] = 256 + GLUT_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = 256 + GLUT_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = 256 + GLUT_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = 256 + GLUT_KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = 256 + GLUT_KEY_PAGE_UP; io.KeyMap[ImGuiKey_PageDown] = 256 + GLUT_KEY_PAGE_DOWN; io.KeyMap[ImGuiKey_Home] = 256 + GLUT_KEY_HOME; io.KeyMap[ImGuiKey_End] = 256 + GLUT_KEY_END; io.KeyMap[ImGuiKey_Insert] = 256 + GLUT_KEY_INSERT; io.KeyMap[ImGuiKey_Delete] = 127; io.KeyMap[ImGuiKey_Backspace] = 8; // == CTRL+H io.KeyMap[ImGuiKey_Space] = ' '; io.KeyMap[ImGuiKey_Enter] = 13; // == CTRL+M io.KeyMap[ImGuiKey_Escape] = 27; io.KeyMap[ImGuiKey_KeyPadEnter] = 13; // == CTRL+M io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; return true; } void ImGui_ImplGLUT_InstallFuncs() { glutReshapeFunc(ImGui_ImplGLUT_ReshapeFunc); glutMotionFunc(ImGui_ImplGLUT_MotionFunc); glutPassiveMotionFunc(ImGui_ImplGLUT_MotionFunc); glutMouseFunc(ImGui_ImplGLUT_MouseFunc); #ifdef __FREEGLUT_EXT_H__ glutMouseWheelFunc(ImGui_ImplGLUT_MouseWheelFunc); #endif glutKeyboardFunc(ImGui_ImplGLUT_KeyboardFunc); glutKeyboardUpFunc(ImGui_ImplGLUT_KeyboardUpFunc); glutSpecialFunc(ImGui_ImplGLUT_SpecialFunc); glutSpecialUpFunc(ImGui_ImplGLUT_SpecialUpFunc); } void ImGui_ImplGLUT_Shutdown() { } void ImGui_ImplGLUT_NewFrame() { // Setup time step ImGuiIO& io = ImGui::GetIO(); int current_time = glutGet(GLUT_ELAPSED_TIME); int delta_time_ms = (current_time - g_Time); if (delta_time_ms <= 0) delta_time_ms = 1; io.DeltaTime = delta_time_ms / 1000.0f; g_Time = current_time; // Start the frame ImGui::NewFrame(); } static void ImGui_ImplGLUT_UpdateKeyboardMods() { ImGuiIO& io = ImGui::GetIO(); int mods = glutGetModifiers(); io.KeyCtrl = (mods & GLUT_ACTIVE_CTRL) != 0; io.KeyShift = (mods & GLUT_ACTIVE_SHIFT) != 0; io.KeyAlt = (mods & GLUT_ACTIVE_ALT) != 0; } void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) { // Send character to imgui //printf("char_down_func %d '%c'\n", c, c); ImGuiIO& io = ImGui::GetIO(); if (c >= 32) io.AddInputCharacter((unsigned int)c); // Store letters in KeysDown[] array as both uppercase and lowercase + Handle GLUT translating CTRL+A..CTRL+Z as 1..26. // This is a hacky mess but GLUT is unable to distinguish e.g. a TAB key from CTRL+I so this is probably the best we can do here. if (c >= 1 && c <= 26) io.KeysDown[c] = io.KeysDown[c - 1 + 'a'] = io.KeysDown[c - 1 + 'A'] = true; else if (c >= 'a' && c <= 'z') io.KeysDown[c] = io.KeysDown[c - 'a' + 'A'] = true; else if (c >= 'A' && c <= 'Z') io.KeysDown[c] = io.KeysDown[c - 'A' + 'a'] = true; else io.KeysDown[c] = true; ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y) { //printf("char_up_func %d '%c'\n", c, c); ImGuiIO& io = ImGui::GetIO(); if (c >= 1 && c <= 26) io.KeysDown[c] = io.KeysDown[c - 1 + 'a'] = io.KeysDown[c - 1 + 'A'] = false; else if (c >= 'a' && c <= 'z') io.KeysDown[c] = io.KeysDown[c - 'a' + 'A'] = false; else if (c >= 'A' && c <= 'Z') io.KeysDown[c] = io.KeysDown[c - 'A' + 'a'] = false; else io.KeysDown[c] = false; ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y) { //printf("key_down_func %d\n", key); ImGuiIO& io = ImGui::GetIO(); if (key + 256 < IM_ARRAYSIZE(io.KeysDown)) io.KeysDown[key + 256] = true; ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y) { //printf("key_up_func %d\n", key); ImGuiIO& io = ImGui::GetIO(); if (key + 256 < IM_ARRAYSIZE(io.KeysDown)) io.KeysDown[key + 256] = false; ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_MouseFunc(int glut_button, int state, int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2((float)x, (float)y); int button = -1; if (glut_button == GLUT_LEFT_BUTTON) button = 0; if (glut_button == GLUT_RIGHT_BUTTON) button = 1; if (glut_button == GLUT_MIDDLE_BUTTON) button = 2; if (button != -1 && state == GLUT_DOWN) io.MouseDown[button] = true; if (button != -1 && state == GLUT_UP) io.MouseDown[button] = false; } #ifdef __FREEGLUT_EXT_H__ void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2((float)x, (float)y); if (dir > 0) io.MouseWheel += 1.0; else if (dir < 0) io.MouseWheel -= 1.0; (void)button; // Unused } #endif void ImGui_ImplGLUT_ReshapeFunc(int w, int h) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)w, (float)h); } void ImGui_ImplGLUT_MotionFunc(int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2((float)x, (float)y); }
0
0.71481
1
0.71481
game-dev
MEDIA
0.538155
game-dev,desktop-app
0.664032
1
0.664032
magefree/mage
1,450
Mage.Sets/src/mage/cards/r/RhysticShield.java
package mage.cards.r; import java.util.UUID; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.Effect; import mage.abilities.effects.common.DoUnlessAnyPlayerPaysEffect; import mage.abilities.effects.common.continuous.BoostControlledEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.filter.StaticFilters; /** * * @author L_J */ public final class RhysticShield extends CardImpl { public RhysticShield(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{W}"); // Creatures you control get +0/+1 until end of turn. They get an additional +0/+2 until end of turn unless any player pays {2}. this.getSpellAbility().addEffect(new BoostControlledEffect(0, 1, Duration.EndOfTurn, StaticFilters.FILTER_PERMANENT_CREATURES, false)); Effect effect = new DoUnlessAnyPlayerPaysEffect(new BoostControlledEffect(0, 2, Duration.EndOfTurn, StaticFilters.FILTER_PERMANENT_CREATURES, false), new ManaCostsImpl<>("{2}")); effect.setText("They get an additional +0/+2 until end of turn unless any player pays {2}"); this.getSpellAbility().addEffect(effect); } private RhysticShield(final RhysticShield card) { super(card); } @Override public RhysticShield copy() { return new RhysticShield(this); } }
0
0.966614
1
0.966614
game-dev
MEDIA
0.923236
game-dev
0.991249
1
0.991249
Histidine91/Nexerelin
2,431
jars/sources/ExerelinCore/exerelin/campaign/events/covertops/SecurityAlertEvent.java
package exerelin.campaign.events.covertops; import com.fs.starfarer.api.Global; import com.fs.starfarer.api.campaign.events.CampaignEventTarget; import com.fs.starfarer.api.impl.campaign.events.BaseEventPlugin; import exerelin.utilities.StringHelper; public class SecurityAlertEvent extends BaseEventPlugin { public static final float DAYS_PER_STAGE = 30f; public static final float ALERT_LEVEL_DECREMENT = 0.05f; protected float elapsedDays = 0f; protected float alertLevel = 0; //protected String conditionToken = null; @Override public void init(String type, CampaignEventTarget eventTarget) { super.init(type, eventTarget); } @Override public void startEvent() { super.startEvent(); if (market == null) { endEvent(); return; } //conditionToken = market.addCondition("exerelin_security_alert_condition", true, this); } @Override public void advance(float amount) { if (!isEventStarted()) return; if (isDone()) return; float days = Global.getSector().getClock().convertToDays(amount); elapsedDays += days; if (elapsedDays >= DAYS_PER_STAGE) { elapsedDays -= DAYS_PER_STAGE; alertLevel -= ALERT_LEVEL_DECREMENT; //market.reapplyCondition(conditionToken); } if (alertLevel <= 0) { endEvent(); } } private boolean ended = false; private void endEvent() { /* if (market != null && conditionToken != null) { //market.removeSpecificCondition(conditionToken); } */ ended = true; } @Override public boolean isDone() { return ended; } public float getAlertLevel() { return alertLevel; } public void setAlertLevel(float alertLevel) { this.alertLevel = alertLevel; if (alertLevel <= 0) { endEvent(); } else { //market.reapplyCondition(conditionToken); } } public void increaseAlertLevel(float level) { this.alertLevel += level; if (alertLevel <= 0) { endEvent(); } else { //market.reapplyCondition(conditionToken); } } public void decreaseAlertLevel(float level) { this.alertLevel -= level; if (alertLevel <= 0) { endEvent(); } else { //market.reapplyCondition(conditionToken); } } @Override public String getEventName() { return StringHelper.getStringAndSubstituteToken("exerelin_events", "securityAlert", "$market", market.getName()); } @Override public CampaignEventCategory getEventCategory() { return CampaignEventCategory.DO_NOT_SHOW_IN_MESSAGE_FILTER; } }
0
0.867571
1
0.867571
game-dev
MEDIA
0.684918
game-dev
0.925647
1
0.925647
ggnkua/Atari_ST_Sources
8,499
ASM/Running Design Team/srcfalco/INCLUDE/MENU/MENU.S
;*********************************************************** ;*** ;*** RUNNING-3D-ENGINE ;*** ;*** (C) 1994-1996 BY TARZAN BOY ;*** ;*********************************************************** * Menu by MIG 1996 ;************************************** ;* equ's ;************************************** final equ 0 debug equ 0 debug_color equ 0 record_lauf equ 0 play_lauf equ 0 time_debug equ 0 include "e:\running\include\const_02.s" ;************************************** ;************************************** TEXT pea 0 move.w #$0020,-(SP) trap #1 addq.l #6,SP move.l D0,old_stack bsr MODULEdsp jsr save_video_system jsr init_stuff jsr init_stuff_2 bsr mainmenu jsr restore_system move.w old_res,-(SP) move.w #3,-(SP) move.l old_screen,-(SP) move.l old_screen,-(SP) move.w #$0005,-(SP) trap #$0E lea $000E(SP),SP out: jsr restore_video_system move.l old_stack,-(SP) move.w #$0020,-(SP) trap #1 addq.l #6,SP clr.w -(SP) trap #1 **************************************** gear_phase dc.w 0 episode_menu move.w #0,gear_phase lea FILEgear(pc),a0 lea fade_buffer_2,a1 move.l BYTESgear(pc),d0 bsr load episode_loop rept 4 bsr vsync endr * Symbol Animation move.w gear_phase,d0 addq.w #1,d0 and.w #$f,d0 move.w d0,gear_phase move.l screen_2,a0 adda.l #50*640+50,a0 lea fade_buffer_2+128,a1 lsl.w #5,d0 * 16 * 2 Pixel adda.w d0,a1 * Zeichnen move.w #$ffff,d2 move.w #$0020,d3 * truepaint black is no black ! move.w #16-1,d0 scan_line move.w #16-1,d1 scan_pixel move.w (a1)+,d4 cmp.w d3,d4 bne.s scan_it move.w d2,d4 scan_it move.w d4,(a0)+ dbra d1,scan_pixel lea 640-32(a0),a0 lea 512-32(a1),a1 dbra d0,scan_line bsr swap_me neg.w index tst.b keytable+$1c beq.s episode_loop * menu ist fertig ... bsr MODULEstop move.l old_menu_vbl,$70.w rts ;************************************** ;* init routines ... ;************************************** include "e:\running\include\init.s" include "e:\running\include\key_hit2.s" ;************************************** ;* new_key ;************************************** new_key: movem.l D0/A0,-(SP) lea $FFFFFC00.w,A0 move.b (A0),D0 btst #7,D0 beq.s must_be_midi cmpi.b #$FF,2(A0) bne.s test_2 i1a: move.b (A0),D0 btst #7,D0 beq.s i1a i1: move.b 2(A0),D0 cmpi.b #$FF,D0 beq.s i1 move.b D0,port bra.s new_key_out ;--- test_2: cmpi.b #$FE,2(A0) bne.s only_a_key i1a2: move.b (A0),D0 btst #7,D0 beq.s i1a2 i12: move.b 2(A0),D0 cmp.b #$FE,D0 beq.s i12 move.b D0,port+1 bra.s new_key_out ;--- only_a_key: move.b 2(A0),D0 move.b D0,key bsr.s convert_key_code bra.s new_key_out nop ;--------------- new_key_out: movem.l (SP)+,D0/A0 rte ;--------------- must_be_midi: movea.l midi_rout_ptr,A0 jsr (A0) bra.s new_key_out ;--------------- convert_key_code: ifeq record_lauf lea keytable(PC),A0 andi.w #$00FF,D0 tst.b D0 bmi.s losgelassen move.b #$FF,0(A0,D0.w) rts losgelassen: andi.b #%01111111,D0 clr.b 0(A0,D0.w) rts else lea keytable_help(PC),A0 andi.w #$00FF,D0 tst.b D0 bmi.s losgelassen move.b #$FF,0(A0,D0.w) rts losgelassen: andi.b #%01111111,D0 clr.b 0(A0,D0.w) rts endc ;--------------- keytable: DS.B 256 keytable_help ds.b 256 port: DC.W 0 last_time_joy: DC.W 0 midi_nothing: rts ;************************************** ;* my_vbl ;************************************** my_vbl: addq.l #1,vbl_count addq.w #1,vbl_checker rte ****************************************** include "menuv6.txt" ;*********************************************************** ;*********************************************************** DATA counter: DC.W 0 true_offi: DC.L true karte_flag: DC.W 0 cameraview_flag dc.w 0 terminal_flag dc.w 0 screen_1: dc.l 0 screen_2: dc.l 0 screen_3: dc.l 0 ;--------------- vbl_start: DC.L 0 vbl_time: DC.W 0 ;--------------- dont_change_scr dc.w 0 double_scan dc.w 0 cinemascope dc.w 0 ds_vor_karte dc.w 0 cine_vor_karte dc.w 0 true_vor_karte dc.l 0 ;--------------- step: DC.W 0 direction: DC.W 0 has_moved: DC.W 0 ;--------------- schnitt_flags: DS.W 4 ccw_erg: DC.W 0 test_points: DS.L 4 stand_rot: DS.L 5*2 schnitt_anz: DC.W 0 ccw_temp: DC.W 0 DC.W 0 sx_test: DC.L 0 sy_test: DC.L 0 sh_found: DC.L 0 inside_ok: DC.W 0 durchstoss_anz: DC.W 0 clear_it_flag dc.w 0 inter_ptr: DS.L 5 file_name_ptr: DC.L 0 file_size: DC.L 0 file_buf_ptr: DC.L 0 ;--------------- midi_record: DS.B 16 midi_rec_pos: DC.W 0 midi_rec_len: DC.W 16 old_vbl: DC.L 0 old_stack: DC.L 0 old_res: DC.W 0 old_screen: DC.L 0 vbl_count: DC.L 0 vbl_checker: DC.W 1 ;************************************** ;* level daten (pointer) ;************************************** big_sector_ptr: DC.L 0 boden_col_ptr: DC.L 0 play_dat_ptr: DC.L 0 ;--------------- max_trains: DC.W 0 nb_of_trains: DC.L 0 trains_aktive: DC.W %0000000000000000 trains_visible: DC.W %0000000000000000 ;--------------- video_data: ds.b 34 ********* fire ************ include "fire.dat" include "gouraud.dat" include "texture.dat" ;*********************************************************** ;*********************************************************** BSS bss_start: vsync_flag ds.w 1 ;--------------- ;>PART 'main_midi_buf' main_midi_buf: DS.L 1 ; figur 0 - sx DS.L 1 ; sy DS.W 1 ; sh DS.W 1 ; alpha DS.W 1 ; animstufe DS.L 1 ; figur 1 - sx DS.L 1 ; sy DS.W 1 ; sh DS.W 1 ; alpha DS.W 1 ; animstufe DS.L 1 ; figur 2 - sx DS.L 1 ; sy DS.W 1 ; sh DS.W 1 ; alpha DS.W 1 ; animstufe DS.L 1 ; figur 3 - sx DS.L 1 ; sy DS.W 1 ; sh DS.W 1 ; alpha DS.W 1 ; animstufe main_midi_buf_end: ;ENDPART ;>PART 'test_position_routs' midi_rout_ptr: DS.L 1 mouse_pos: DS.B 8 key: DS.W 1 midi: DS.W 1 save_mfp: DS.L 6 save_system: DS.L 9 black: DS.L 8 menue_anim_ptr ds.l 1 menue_anim_buf ds.w 16*16 ;--------------- pistol_lines: ds.l 128*4 pistol_offsets: ds.w 128*4 pistol_pixel: ds.w 128*4 pistol_data: ds.b 100000 ****** menu ********** include "fire.bss" include "gouraud.bss" include "texture.bss" include "data.bss" **** screen mem ******** ds.b 256 screen_mem: ds.b 153600*2 ds.b 256 bss_end: END
0
0.633348
1
0.633348
game-dev
MEDIA
0.242889
game-dev
0.892492
1
0.892492
oestrich/kalevala
1,284
lib/kalevala/world.ex
defmodule Kalevala.World do @moduledoc """ Manages the virtual world """ require Logger use DynamicSupervisor alias Kalevala.Character.Foreman alias Kalevala.World.Room alias Kalevala.World.Zone alias Kalevala.World.ZoneSupervisor @doc """ Start the zone into the world """ def start_zone(zone, config) do options = %{ zone: zone, config: config, genserver_options: [name: Zone.global_name(zone)] } DynamicSupervisor.start_child(config.supervisor_name, {ZoneSupervisor, options}) end @doc """ Start the room into the world """ def start_room(room, item_instances, config) do options = %{ room: room, item_instances: item_instances, config: config, genserver_options: [name: Room.global_name(room)] } DynamicSupervisor.start_child(config.supervisor_name, {Room, options}) end @doc """ Start a world character into the world """ def start_character(character, config) do options = Keyword.merge(config, character: character) Foreman.start_non_player(options) end @doc false def start_link(opts) do DynamicSupervisor.start_link(__MODULE__, [], opts) end @impl true def init(_) do DynamicSupervisor.init(strategy: :one_for_one) end end
0
0.825952
1
0.825952
game-dev
MEDIA
0.656759
game-dev
0.898092
1
0.898092
gideros/gideros
3,085
external/liquidfun-1.0.0/liquidfun/Box2D/Box2D/Collision/b2BroadPhase.cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Collision/b2BroadPhase.h> b2BroadPhase::b2BroadPhase() { m_proxyCount = 0; m_pairCapacity = 16; m_pairCount = 0; m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); m_moveCapacity = 16; m_moveCount = 0; m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); } b2BroadPhase::~b2BroadPhase() { b2Free(m_moveBuffer); b2Free(m_pairBuffer); } int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) { int32 proxyId = m_tree.CreateProxy(aabb, userData); ++m_proxyCount; BufferMove(proxyId); return proxyId; } void b2BroadPhase::DestroyProxy(int32 proxyId) { UnBufferMove(proxyId); --m_proxyCount; m_tree.DestroyProxy(proxyId); } void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) { bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); if (buffer) { BufferMove(proxyId); } } void b2BroadPhase::TouchProxy(int32 proxyId) { BufferMove(proxyId); } void b2BroadPhase::BufferMove(int32 proxyId) { if (m_moveCount == m_moveCapacity) { int32* oldBuffer = m_moveBuffer; m_moveCapacity *= 2; m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); b2Free(oldBuffer); } m_moveBuffer[m_moveCount] = proxyId; ++m_moveCount; } void b2BroadPhase::UnBufferMove(int32 proxyId) { for (int32 i = 0; i < m_moveCount; ++i) { if (m_moveBuffer[i] == proxyId) { m_moveBuffer[i] = e_nullProxy; } } } // This is called from b2DynamicTree::Query when we are gathering pairs. bool b2BroadPhase::QueryCallback(int32 proxyId) { // A proxy cannot form a pair with itself. if (proxyId == m_queryProxyId) { return true; } // Grow the pair buffer as needed. if (m_pairCount == m_pairCapacity) { b2Pair* oldBuffer = m_pairBuffer; m_pairCapacity *= 2; m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); b2Free(oldBuffer); } m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); ++m_pairCount; return true; }
0
0.796044
1
0.796044
game-dev
MEDIA
0.389881
game-dev
0.968263
1
0.968263
shawwn/noh
51,005
src/sav_shared/c_replaymanager.cpp
// (C)2007 S2 Games // c_replaymanager.cpp // //============================================================================= //============================================================================= // Headers //============================================================================= #include "game_shared_common.h" #include "c_replaymanager.h" #include "i_game.h" #include "c_teaminfo.h" #include "../k2/k2_protocol.h" #include "../k2/c_statestring.h" #include "../k2/c_uicmd.h" #undef pReplayManager #undef ReplayManager //============================================================================= //============================================================================= // Globals //============================================================================= CReplayManager *pReplayManager(CReplayManager::GetInstance()); SINGLETON_INIT(CReplayManager) CVAR_BOOLF (replay_isPlaying, false, CVAR_READONLY); CVAR_BOOL (replay_pause, false); //============================================================================= /*==================== CReplayManager::CReplayManager ====================*/ CReplayManager::CReplayManager() : m_sFilename(_T("")), m_bPlaying(false), m_bRecording(false), m_bFrameOpen(false), m_iCurrentFrame(-1), m_uiBeginTime(INVALID_TIME), m_uiEndTime(INVALID_TIME), m_iSpeed(0) { } /*==================== CReplayManager::StartRecording ====================*/ void CReplayManager::StartRecording(const tstring &sFilename) { if (IsPlaying() && Host.HasServer()) return; m_hReplayData.Open(Filename_StripExtension(sFilename) + _T(".tmp"), FILE_WRITE | FILE_BINARY | FILE_UTF16); if (m_hReplayData.IsOpen()) m_bRecording = true; else return; m_sFilename = sFilename; // File type code m_hReplayData.WriteByte('S'); m_hReplayData.WriteByte('2'); m_hReplayData.WriteByte('R'); m_hReplayData.WriteByte('0'); // Version m_hReplayData.WriteInt32(REPLAY_VERSION); // Write world name as a wide string const wstring &sWorldName(TStringToWString(Host.GetServerWorldName())); m_hReplayData.Write(sWorldName.c_str(), sWorldName.length() * sizeof(wstring::value_type)); m_hReplayData.WriteInt16(short(0)); // Write state strings for (uint uiID(1); uiID != 4; ++uiID) { tstring sBuffer; Game.GetStateString(uiID).AppendToBuffer(sBuffer); const wstring &sStateString(TStringToWString(sBuffer)); m_hReplayData.Write(sStateString.c_str(), sStateString.length() * sizeof(wstring::value_type)); m_hReplayData.WriteInt16(short(0)); } m_mapStateStrings.clear(); m_cLastSnapshot = CSnapshot(); m_cCurrentSnapshot = CSnapshot(); } /*==================== CReplayManager::StopRecording ====================*/ void CReplayManager::StopRecording() { if (!IsRecording()) return; m_hReplayData.Close(); m_bRecording = false; m_hReplayData.Open(Filename_StripExtension(m_sFilename) + _T(".tmp"), FILE_READ | FILE_BINARY | FILE_UTF16); if (m_hReplayData.IsOpen()) { tstring sPath(m_sFilename); CArchive hArchive(sPath, ARCHIVE_WRITE | ARCHIVE_MAX_COMPRESS); if (!hArchive.IsOpen()) return; uint uiSize; const char *pBuffer(m_hReplayData.GetBuffer(uiSize)); hArchive.WriteFile(_T("ReplayData"), pBuffer, uiSize); m_hReplayData.Close(); hArchive.Close(); FileManager.Delete(Filename_StripExtension(m_sFilename) + _T(".tmp")); } } /*==================== CReplayManager::StartPlayback ====================*/ bool CReplayManager::StartPlayback(const tstring &sFilename) { CArchive *pArchive(NULL); try { if (IsRecording()) EX_WARN(_T("No playback allowed while recording")); CArchive *pArchive(K2_NEW(global, CArchive)(_TS("~/") + sFilename)); if (!pArchive->IsOpen()) { K2_DELETE(pArchive); pArchive = K2_NEW(global, CArchive)(sFilename); if (!pArchive->IsOpen()) EX_WARN(_T("Failed to open archive")); } m_hReplayData.Open(_T("ReplayData"), FILE_READ | FILE_BINARY | FILE_UTF16, *pArchive); if (!m_hReplayData.IsOpen()) EX_WARN(_T("Failed to open replay data")); if (m_hReplayData.ReadByte() != 'S' || m_hReplayData.ReadByte() != '2' || m_hReplayData.ReadByte() != 'R' || m_hReplayData.ReadByte() != '0') EX_WARN(_T("Invalid replay header")); if (m_hReplayData.ReadInt32() != REPLAY_VERSION) EX_WARN(_T("Version mismatch")); m_bPlaying = true; replay_isPlaying = true; wchar_t wChar(m_hReplayData.ReadInt16()); while (wChar) { m_sWorldName += TCHAR(wChar); wChar = m_hReplayData.ReadInt16(); } for (uint uiID(1); uiID != 4; ++uiID) { tstring sStr; wchar_t wChar(m_hReplayData.ReadInt16()); while (wChar) { sStr += TCHAR(wChar); wChar = m_hReplayData.ReadInt16(); } m_mapStateStrings[uiID] = sStr; } m_cCurrentSnapshot.SetFrameNumber(-1); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(0); m_cCurrentSnapshot.FreeEntities(); m_zStartPos = m_hReplayData.Tell(); m_uiBeginTime = INVALID_TIME; m_uiEndTime = INVALID_TIME; GenerateKeyFrames(); return true; } catch (CException &ex) { if (m_hReplayData.IsOpen()) m_hReplayData.Close(); SAFE_DELETE(pArchive); ex.Process(_T("CReplayManager::StartPlayback() -"), NO_THROW); return false; } } /*==================== CReplayManager::StopPlayback ====================*/ void CReplayManager::StopPlayback() { if (!IsPlaying()) return; m_hReplayData.Close(); m_bPlaying = false; replay_isPlaying = false; } /*==================== CReplayManager::IsRecording ====================*/ bool CReplayManager::IsRecording() { return m_hReplayData.IsOpen() && m_bRecording; } /*==================== CReplayManager::IsPlaying ====================*/ bool CReplayManager::IsPlaying() { return m_hReplayData.IsOpen() && m_bPlaying; } /*==================== CReplayManager::ReadSnapshot ====================*/ void CReplayManager::ReadSnapshot(int iFrame, IBuffer &cBuffer) { CSnapshot snapshot(cBuffer); m_cCurrentSnapshot.SetValid(true); m_cCurrentSnapshot.SetFrameNumber(iFrame); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(snapshot.GetTimeStamp()); // Clear events m_cCurrentSnapshot.SetNumEvents(0); m_cCurrentSnapshot.GetEventBuffer().Clear(); byte yNumEvents(snapshot.GetNumEvents()); // Translate events CBufferDynamic bufferTranslate(40); for (int i(0); i < yNumEvents; ++i) { CGameEvent::Translate(snapshot.GetReceivedBuffer(), bufferTranslate); m_cCurrentSnapshot.AddEventSnapshot(bufferTranslate); } SnapshotVector &vBaseEntities(m_cCurrentSnapshot.GetEntities()); SnapshotVector_it citBase(vBaseEntities.begin()); static CEntitySnapshot entSnapshot; // Translate entities for (;;) { // Grab a "shell" entity snapshot from the the frame snapshot. // The data will be filled in once we know the type. entSnapshot.Clear(); if (!snapshot.GetNextEntity(entSnapshot, -1)) break; while (citBase != vBaseEntities.end() && citBase->first < entSnapshot.GetIndex()) ++citBase; if (citBase == vBaseEntities.end() || citBase->first > entSnapshot.GetIndex()) { // // New entity, read from baseline // ushort unType(entSnapshot.GetType()); // If the type is NULL, the entity is dead and should be removed if (unType == 0) continue; const vector<SDataField>* pTypeVector(EntityRegistry.GetTypeVector(unType)); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); citBase = vBaseEntities.insert(citBase, SnapshotEntry(entSnapshot.GetIndex(), CEntitySnapshot::Allocate(entSnapshot))); ++citBase; } else if (citBase->first == entSnapshot.GetIndex()) { // // Update existing entity // CEntitySnapshot *pBaseSnapshot(CEntitySnapshot::GetByHandle(citBase->second)); ushort unType(entSnapshot.GetTypeChange() ? entSnapshot.GetType() : pBaseSnapshot->GetType()); // If the type is NULL, the entity is dead and should be removed if (unType == 0) { CEntitySnapshot::DeleteByHandle(citBase->second); citBase = vBaseEntities.erase(citBase); continue; } const vector<SDataField> *pTypeVector(EntityRegistry.GetTypeVector(unType)); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); if (entSnapshot.GetTypeChange()) { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); *pBaseSnapshot = entSnapshot; } else { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector); pBaseSnapshot->ApplyDiff(entSnapshot); } ++citBase; } } } /*==================== CReplayManager::StartFrame ====================*/ void CReplayManager::StartFrame(int iFrame) { if (IsPlaying() && replay_pause) { m_bFrameOpen = true; } else if (IsPlaying()) { if (m_hReplayData.IsEOF() || uint(m_iCurrentFrame) == m_uiNumFrames) return; uint uiLength(m_hReplayData.ReadInt32()); if (uiLength == 0) return; CBufferStatic cBuffer(uiLength); uint uiNumClients; for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); ReadSnapshot(iFrame, cBuffer); // Read reliable game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { uint uiIndex(m_hReplayData.ReadInt32()); uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); m_mapGameDataReliable[uiIndex].Append(cBuffer.Get(), cBuffer.GetLength()); } } // Read game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { uint uiIndex(m_hReplayData.ReadInt32()); uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); m_mapGameData[uiIndex].Append(cBuffer.Get(), cBuffer.GetLength()); } } // Read state strings uint uiNumStateString(m_hReplayData.ReadInt32()); for (uint ui(0); ui < uiNumStateString; ++ui) { uint uiID(m_hReplayData.ReadInt32()); tstring sStr; wchar_t wChar(m_hReplayData.ReadInt16()); while (wChar) { sStr += TCHAR(wChar); wChar = m_hReplayData.ReadInt16(); } m_mapStateStrings[uiID] = sStr; } ++m_iCurrentFrame; m_bFrameOpen = true; } else if (IsRecording()) { m_iCurrentFrame = iFrame; m_bFrameOpen = true; } } /*==================== CReplayManager::EndFrame ====================*/ void CReplayManager::EndFrame() { if (!m_bFrameOpen) return; // Write game snapshot if (IsRecording()) { CBufferDynamic bufFrameData; m_cCurrentSnapshot.WriteDiff(bufFrameData, m_cLastSnapshot, 0, 0, -1); m_hReplayData.WriteInt32(bufFrameData.GetLength()); m_hReplayData.Write(bufFrameData.Get(), bufFrameData.GetLength()); // Write reliable game data uint uiNumClientsReliable(0); for (MapClientGameData::iterator it(m_mapGameDataReliable.begin()); it != m_mapGameDataReliable.end(); ++it) { if (it->second.GetLength() > 0) ++uiNumClientsReliable; } m_hReplayData.WriteInt32(uiNumClientsReliable); for (MapClientGameData::iterator it(m_mapGameDataReliable.begin()); it != m_mapGameDataReliable.end(); ++it) { if (it->second.GetLength() == 0) continue; m_hReplayData.WriteInt32(it->first); m_hReplayData.WriteInt32(it->second.GetLength()); m_hReplayData.Write(it->second.Get(), it->second.GetLength()); it->second.Clear(); } // Write game data uint uiNumClients(0); for (MapClientGameData::iterator it(m_mapGameData.begin()); it != m_mapGameData.end(); ++it) { if (it->second.GetLength() > 0) ++uiNumClients; } m_hReplayData.WriteInt32(uiNumClients + 1); for (MapClientGameData::iterator it(m_mapGameData.begin()); it != m_mapGameData.end(); ++it) { if (it->second.GetLength() == 0) continue; m_hReplayData.WriteInt32(it->first); m_hReplayData.WriteInt32(it->second.GetLength()); m_hReplayData.Write(it->second.Get(), it->second.GetLength()); it->second.Clear(); } // Server profiling data m_hReplayData.WriteInt32(-1); m_hReplayData.WriteInt32(5); m_hReplayData.WriteByte(GAME_CMD_SERVER_STATS); m_hReplayData.WriteInt32(Host.GetFrameLength()); // Write state strings m_hReplayData.WriteInt32(uint(m_mapStateStrings.size())); for (MapStateString::iterator it(m_mapStateStrings.begin()); it != m_mapStateStrings.end(); ++it) { m_hReplayData.WriteInt32(it->first); const wstring &sStateString(TStringToWString(it->second)); m_hReplayData.Write(sStateString.c_str(), sStateString.length() * sizeof(wstring::value_type)); m_hReplayData.WriteInt16(short(0)); } m_mapStateStrings.clear(); m_cLastSnapshot = m_cCurrentSnapshot; } else if (IsPlaying()) { // Clear old data for (MapClientGameData::iterator it(m_mapGameDataReliable.begin()); it != m_mapGameDataReliable.end(); ++it) it->second.Clear(); for (MapClientGameData::iterator it(m_mapGameData.begin()); it != m_mapGameData.end(); ++it) it->second.Clear(); m_mapStateStrings.clear(); } m_bFrameOpen = false; } /*==================== CReplayManager::WriteStateString TODO: Better memory allocations here ====================*/ void CReplayManager::WriteStateString(uint uiID, const CStateString &ss) { if (IsPlaying()) return; tstring sBuffer; ss.AppendToBuffer(sBuffer); m_mapStateStrings[uiID] = sBuffer; } /*==================== CReplayManager::WriteGameData ====================*/ void CReplayManager::WriteGameData(uint iClient, const IBuffer &buffer, bool bReliable) { if (!IsRecording()) return; if (bReliable) { if (m_mapGameDataReliable[iClient].GetLength() > 0) m_mapGameDataReliable[iClient] << NETCMD_SERVER_GAME_DATA; m_mapGameDataReliable[iClient] << buffer; } else { if (m_mapGameData[iClient].GetLength() > 0) m_mapGameData[iClient] << NETCMD_SERVER_GAME_DATA; m_mapGameData[iClient] << buffer; } } /*==================== CReplayManager::WriteSnapshot ====================*/ void CReplayManager::WriteSnapshot(const CSnapshot &snapshot) { if (!m_bFrameOpen) return; m_cCurrentSnapshot = snapshot; } /*==================== CReplayManager::GetWorldName ====================*/ tstring CReplayManager::GetWorldName() { return m_sWorldName; } /*==================== CReplayManager::GetSnapshot ====================*/ void CReplayManager::GetSnapshot(CSnapshot &snapshot) { if (!m_bFrameOpen) return; snapshot = m_cCurrentSnapshot; } /*==================== CReplayManager::GetGameData ====================*/ void CReplayManager::GetGameData(uint uiClient, IBuffer &buffer) { if (!m_bFrameOpen) return; MapClientGameData::iterator itFind(m_mapGameData.find(uiClient)); if (itFind != m_mapGameData.end()) buffer = itFind->second; } /*==================== CReplayManager::GetGameDataReliable ====================*/ void CReplayManager::GetGameDataReliable(uint uiClient, IBuffer &buffer) { if (!m_bFrameOpen) return; MapClientGameData::iterator itFind(m_mapGameDataReliable.find(uiClient)); if (itFind != m_mapGameDataReliable.end()) buffer = itFind->second; } /*==================== CReplayManager::SetPlaybackFrame ====================*/ void CReplayManager::SetPlaybackFrame(int iFrame) { iFrame = CLAMP<int>(iFrame, 0, m_uiNumFrames - 1); if (iFrame == 0) { m_hReplayData.Seek(int(m_zStartPos)); m_cCurrentSnapshot.SetFrameNumber(-1); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(0); m_cCurrentSnapshot.FreeEntities(); m_mapGameData.clear(); m_mapGameDataReliable.clear(); m_mapStateStrings.clear(); m_iCurrentFrame = 0; } // Search for the closest valid keyframe map<uint, SReplayKeyFrame>::iterator it(m_mapKeyFrames.begin()); for (; it != m_mapKeyFrames.end(); ++it) { if (it->first >= uint(iFrame)) break; } if (it != m_mapKeyFrames.end()) { m_hReplayData.Seek(int(it->second.zPos)); m_cCurrentSnapshot.SetFrameNumber(-1); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(0); m_cCurrentSnapshot.FreeEntities(); it->second.bufSnapshot.Rewind(); ReadSnapshot(it->second.uiFrame, it->second.bufSnapshot); m_mapGameData.clear(); m_mapGameDataReliable.clear(); m_mapStateStrings.clear(); m_iCurrentFrame = it->second.uiFrame; } } /*==================== CReplayManager::Profile ====================*/ void CReplayManager::Profile(const tstring &sFilename, int iClient) { if (!StartPlayback(sFilename)) return; int iFrame(0); int iSnapshotHeaderBytes(0); int iNumEvents(0); int iEventBytes(0); int iNumEntitySnapshots(0); int iEntitySnapshotBytes(0); int iEntityHeaderBytes(0); int iEntityTransmitFlagBytes(0); int iEntityFieldBytes(0); map<ushort, SProfileEntitySnapshot> mapProfileEntity; int iReliableGameDataBytes(0); int iGameDataBytes(0); int iStateStringBytes(0); map<uint, uint> mapReliableGameDataBytes; map<uint, uint> mapGameDataBytes; CBufferStatic cBuffer(0x4000); CSnapshot snapshot; while (!m_hReplayData.IsEOF()) { uint uiLength(m_hReplayData.ReadInt32()); if (uiLength == 0) continue; cBuffer.Clear(); cBuffer.Reserve(uiLength); cBuffer.SetLength(uiLength); m_hReplayData.Read((char *)cBuffer.Get(), uiLength); uint uiSnapshotStartPos(cBuffer.GetReadPos()); snapshot.ReadBuffer(cBuffer); iSnapshotHeaderBytes += cBuffer.GetReadPos() - uiSnapshotStartPos; const IBuffer &buffer(snapshot.GetReceivedBuffer()); m_cCurrentSnapshot.SetValid(true); m_cCurrentSnapshot.SetFrameNumber(snapshot.GetFrameNumber()); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(snapshot.GetTimeStamp()); // Clear events m_cCurrentSnapshot.SetNumEvents(0); m_cCurrentSnapshot.GetEventBuffer().Clear(); byte yNumEvents(snapshot.GetNumEvents()); // Translate events for (int i(0); i < yNumEvents; ++i) { uint uiStartPos(buffer.GetReadPos()); CGameEvent::AdvanceBuffer(buffer); ++iNumEvents; iEventBytes += buffer.GetReadPos() - uiStartPos; } SnapshotVector &vBaseEntities(m_cCurrentSnapshot.GetEntities()); SnapshotVector_it citBase(vBaseEntities.begin()); static CEntitySnapshot entSnapshot; // Translate entities for (;;) { uint uiEntitySnapshotStartPos(buffer.GetReadPos()); const vector<SDataField>* pTypeVector(NULL); // Grab a "shell" entity snapshot from the the frame snapshot. // The data will be filled in once we know the type. entSnapshot.Clear(); if (!snapshot.GetNextEntity(entSnapshot, -1)) break; uint uiEntityFieldStartPos(buffer.GetReadPos()); while (citBase != vBaseEntities.end() && citBase->first < entSnapshot.GetIndex()) ++citBase; if (citBase == vBaseEntities.end() || citBase->first > entSnapshot.GetIndex()) { // // New entity, read from baseline // ushort unType(entSnapshot.GetType()); SProfileEntitySnapshot &cEntityProfile(mapProfileEntity[unType]); ++iNumEntitySnapshots; ++cEntityProfile.uiCount; uint uiHeaderBytes(buffer.GetReadPos() - uiEntitySnapshotStartPos); iEntityHeaderBytes += uiHeaderBytes; cEntityProfile.uiHeaderBytes += uiHeaderBytes; // If the type is NULL, the entity is dead and should be removed if (unType == 0) { uint uiSnapshotBytes(buffer.GetReadPos() - uiEntitySnapshotStartPos); iEntitySnapshotBytes += uiSnapshotBytes; cEntityProfile.uiSnapshotBytes += uiSnapshotBytes; continue; } pTypeVector = EntityRegistry.GetTypeVector(unType); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); if (pTypeVector) cEntityProfile.vFieldChanges.resize(pTypeVector->size(), 0); uint uiEntityFieldStartPos(buffer.GetReadPos()); entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); citBase = vBaseEntities.insert(citBase, SnapshotEntry(entSnapshot.GetIndex(), CEntitySnapshot::Allocate(entSnapshot))); ++citBase; uint uiFieldBytes(buffer.GetReadPos() - uiEntityFieldStartPos - entSnapshot.GetTransmitFlagBytes()); iEntityTransmitFlagBytes += entSnapshot.GetTransmitFlagBytes(); cEntityProfile.uiTransmitFlagBytes += entSnapshot.GetTransmitFlagBytes(); iEntityFieldBytes += uiFieldBytes; cEntityProfile.uiFieldBytes += uiFieldBytes; uint uiSnapshotBytes(buffer.GetReadPos() - uiEntitySnapshotStartPos); iEntitySnapshotBytes += uiSnapshotBytes; cEntityProfile.uiSnapshotBytes += uiSnapshotBytes; for (uint ui(0); ui < pTypeVector->size(); ++ui) { if (entSnapshot.IsFieldSet(ui) && ((*pTypeVector)[ui].eAccess != FIELD_PRIVATE || iClient == -1 || entSnapshot.GetPrivateClient() == iClient)) ++cEntityProfile.vFieldChanges[ui]; } } else if (citBase->first == entSnapshot.GetIndex()) { // // Update existing entity // CEntitySnapshot *pBaseSnapshot(CEntitySnapshot::GetByHandle(citBase->second)); ushort unType(entSnapshot.GetTypeChange() ? entSnapshot.GetType() : pBaseSnapshot->GetType()); SProfileEntitySnapshot &cEntityProfile(mapProfileEntity[unType]); ++iNumEntitySnapshots; ++cEntityProfile.uiCount; uint uiHeaderBytes(buffer.GetReadPos() - uiEntitySnapshotStartPos); iEntityHeaderBytes += uiHeaderBytes; cEntityProfile.uiHeaderBytes += uiHeaderBytes; // If the type is NULL, the entity is dead and should be removed if (unType == 0) { uint uiSnapshotBytes(buffer.GetReadPos() - uiEntitySnapshotStartPos); iEntitySnapshotBytes += uiSnapshotBytes; cEntityProfile.uiSnapshotBytes += uiSnapshotBytes; CEntitySnapshot::DeleteByHandle(citBase->second); citBase = vBaseEntities.erase(citBase); continue; } pTypeVector = EntityRegistry.GetTypeVector(unType); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); if (pTypeVector) cEntityProfile.vFieldChanges.resize(pTypeVector->size(), 0); if (entSnapshot.GetTypeChange()) { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); *pBaseSnapshot = entSnapshot; } else { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector); pBaseSnapshot->ApplyDiff(entSnapshot); } ++citBase; uint uiFieldBytes(buffer.GetReadPos() - uiEntityFieldStartPos - entSnapshot.GetTransmitFlagBytes()); iEntityTransmitFlagBytes += entSnapshot.GetTransmitFlagBytes(); cEntityProfile.uiTransmitFlagBytes += entSnapshot.GetTransmitFlagBytes(); iEntityFieldBytes += uiFieldBytes; cEntityProfile.uiFieldBytes += uiFieldBytes; uint uiSnapshotBytes(buffer.GetReadPos() - uiEntitySnapshotStartPos); iEntitySnapshotBytes += uiSnapshotBytes; cEntityProfile.uiSnapshotBytes += uiSnapshotBytes; for (uint ui(0); ui < pTypeVector->size(); ++ui) { if (entSnapshot.IsFieldSet(ui) && ((*pTypeVector)[ui].eAccess != FIELD_PRIVATE || iClient == -1 || entSnapshot.GetPrivateClient() == iClient)) ++cEntityProfile.vFieldChanges[ui]; } } } uint uiNumClients; // Read reliable game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { uint uiIndex(m_hReplayData.ReadInt32()); uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); iReliableGameDataBytes += uiLength + 8; if (mapReliableGameDataBytes.find(uiIndex) == mapReliableGameDataBytes.end()) mapReliableGameDataBytes[uiIndex] = uiLength + 8; else mapReliableGameDataBytes[uiIndex] = mapReliableGameDataBytes[uiIndex] + uiLength + 8; } } // Read game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { uint uiIndex(m_hReplayData.ReadInt32()); uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); iGameDataBytes += uiLength + 8; if (mapGameDataBytes.find(uiIndex) == mapGameDataBytes.end()) mapGameDataBytes[uiIndex] = uiLength + 8; else mapGameDataBytes[uiIndex] = mapGameDataBytes[uiIndex] + uiLength + 8; } } // Read state strings uint uiNumStateString(m_hReplayData.ReadInt32()); for (uint ui(0); ui < uiNumStateString; ++ui) { m_hReplayData.ReadInt32(); // uiID tstring sStr; wchar_t wChar(m_hReplayData.ReadInt16()); while (wChar) { sStr += TCHAR(wChar); wChar = m_hReplayData.ReadInt16(); } } ++iFrame; } tstring sOutputFilename(iClient != -1 ? _T("~/") + Filename_StripExtension(sFilename) + _T("-") + XtoA(iClient) + _T(".txt") : _T("~/") + Filename_StripExtension(sFilename) + _T(".txt")); CFileHandle hOutput(sOutputFilename, FILE_WRITE | FILE_TEXT); hOutput << _T("Frames: ") << iFrame << newl; hOutput << _T("Total Bytes: ") << uint(m_hReplayData.GetLength()) << newl; hOutput << _T("Snapshot Header Bytes: ") << iSnapshotHeaderBytes << newl; hOutput << _T("Events: ") << iNumEvents << newl; hOutput << _T("Event Bytes: ") << iEventBytes << newl; hOutput << _T("Reliable Game Data Bytes: ") << iReliableGameDataBytes << newl; hOutput << _T("Game Data Bytes: ") << iGameDataBytes << newl; hOutput << _T("State String Bytes: ") << iStateStringBytes << newl << newl; hOutput << _T("Name Count Bytes Header Flags Fields") << newl; hOutput << _T("================================================================================") << newl; hOutput << XtoA(_TS("Entity Snapshots"), FMT_ALIGNLEFT, 31) << XtoA(iNumEntitySnapshots, 0, 9) << _T(" ") << XtoA(iEntitySnapshotBytes, 0, 9) << _T(" ") << XtoA(iEntityHeaderBytes, 0, 9) << _T(" ") << XtoA(iEntityTransmitFlagBytes, 0, 9) << _T(" ") << XtoA(iEntityFieldBytes, 0, 9) << newl; SProfileEntitySnapshot &cEntityDeleteProfile(mapProfileEntity[0]); hOutput << XtoA(_TS("Delete"), FMT_ALIGNLEFT, 31) << XtoA(cEntityDeleteProfile.uiCount, 0, 9) << _T(" ") << XtoA(cEntityDeleteProfile.uiSnapshotBytes, 0, 9) << _T(" ") << XtoA(cEntityDeleteProfile.uiHeaderBytes, 0, 9) << _T(" ") << XtoA(cEntityDeleteProfile.uiTransmitFlagBytes, 0, 9) << _T(" ") << XtoA(cEntityDeleteProfile.uiFieldBytes, 0, 9) << newl << newl; const EntAllocatorNameMap &mapAllocatorNames(EntityRegistry.GetAllocatorNames()); for (EntAllocatorNameMap::const_iterator cit(mapAllocatorNames.begin()); cit != mapAllocatorNames.end(); ++cit) { const IEntityAllocator *pAllocator(cit->second); if (!pAllocator) continue; ushort unType(pAllocator->GetID()); if (mapProfileEntity.find(unType) == mapProfileEntity.end()) continue; SProfileEntitySnapshot &cEntityProfile(mapProfileEntity[unType]); hOutput << XtoA(pAllocator->GetName().substr(0, 30), FMT_ALIGNLEFT, 31) << XtoA(cEntityProfile.uiCount, 0, 9) << _T(" ") << XtoA(cEntityProfile.uiSnapshotBytes, 0, 9) << _T(" ") << XtoA(cEntityProfile.uiHeaderBytes, 0, 9) << _T(" ") << XtoA(cEntityProfile.uiTransmitFlagBytes, 0, 9) << _T(" ") << XtoA(cEntityProfile.uiFieldBytes, 0, 9) << newl; } map<tstring, SProfileField> mapFields; for (EntAllocatorNameMap::const_iterator cit(mapAllocatorNames.begin()); cit != mapAllocatorNames.end(); ++cit) { const IEntityAllocator *pAllocator(cit->second); if (!pAllocator) continue; ushort unType(pAllocator->GetID()); if (mapProfileEntity.find(unType) == mapProfileEntity.end()) continue; SProfileEntitySnapshot &cEntityProfile(mapProfileEntity[unType]); const TypeVector *pTypeVector(pAllocator->GetTypeVector()); hOutput << newl << newl; hOutput << XtoA(pAllocator->GetName().substr(0, 30), FMT_ALIGNLEFT, 31) << XtoA(_T("Count"), 0, 9) << XtoA(_T("Bytes"), 0, 9) << newl; hOutput << _T("=================================================") << newl; int iCount(0); int iBytes(0); for (uint ui(0); ui < cEntityProfile.vFieldChanges.size(); ++ui) { int iSize(0); switch ((*pTypeVector)[ui].eDataType) { case TYPE_CHAR: iSize = 1; break; case TYPE_SHORT: iSize = 2; break; case TYPE_INT: iSize = 4; break; case TYPE_FLOAT: iSize = 4; break; case TYPE_V2F: iSize = 8; break; case TYPE_V3F: iSize = 12; break; case TYPE_RESHANDLE: iSize = 2; break; case TYPE_GAMEINDEX: iSize = 2; break; case TYPE_ANGLE16: iSize = 2; break; case TYPE_ROUND16: iSize = 2; break; } hOutput << XtoA((*pTypeVector)[ui].sName.substr(0, 30), FMT_ALIGNLEFT, 31) << XtoA(cEntityProfile.vFieldChanges[ui], 0, 9) << XtoA(cEntityProfile.vFieldChanges[ui] * iSize, 0, 9) << newl; iCount += cEntityProfile.vFieldChanges[ui]; iBytes += cEntityProfile.vFieldChanges[ui] * iSize; SProfileField &cProfileField(mapFields[(*pTypeVector)[ui].sName]); cProfileField.uiCount += cEntityProfile.vFieldChanges[ui]; cProfileField.uiBytes += cEntityProfile.vFieldChanges[ui] * iSize; } hOutput << XtoA(_TS("Total"), FMT_ALIGNLEFT, 31) << XtoA(iCount, 0, 9) << XtoA(iBytes, 0, 9) << newl; } hOutput << newl << newl; for (map<tstring, SProfileField>::iterator it(mapFields.begin()); it != mapFields.end(); ++it) { hOutput << XtoA(_T(it->first), FMT_ALIGNLEFT, 31) << XtoA(it->second.uiCount, 0, 9) << XtoA(it->second.uiBytes, 0, 9) << newl; } StopPlayback(); Console << _T("Done") << newl; } /*==================== CReplayManager::Parse ====================*/ void CReplayManager::Parse(const tstring &sFilename) { if (!StartPlayback(sFilename)) return; int iFrame(0); //CFileHandle hKeyFrames(_T("~/") + Filename_StripExtension(sFilename) + _T(".tmp"), FILE_WRITE | FILE_BINARY | FILE_UTF16); CBufferStatic cBuffer(0x4000); CSnapshot snapshot; while (!m_hReplayData.IsEOF()) { uint uiLength(m_hReplayData.ReadInt32()); cBuffer.Clear(); cBuffer.Reserve(uiLength); cBuffer.SetLength(uiLength); m_hReplayData.Read((char *)cBuffer.Get(), uiLength); snapshot.ReadBuffer(cBuffer); m_cCurrentSnapshot.SetValid(true); m_cCurrentSnapshot.SetFrameNumber(snapshot.GetFrameNumber()); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(snapshot.GetTimeStamp()); // Clear events m_cCurrentSnapshot.SetNumEvents(0); m_cCurrentSnapshot.GetEventBuffer().Clear(); byte yNumEvents(snapshot.GetNumEvents()); // Translate events for (int i(0); i < yNumEvents; ++i) CGameEvent::AdvanceBuffer(snapshot.GetReceivedBuffer()); SnapshotVector &vBaseEntities(m_cCurrentSnapshot.GetEntities()); SnapshotVector_it citBase(vBaseEntities.begin()); static CEntitySnapshot entSnapshot; // Translate entities for (;;) { const vector<SDataField> *pTypeVector(NULL); // Grab a "shell" entity snapshot from the the frame snapshot. // The data will be filled in once we know the type. entSnapshot.Clear(); if (!snapshot.GetNextEntity(entSnapshot, -1)) break; while (citBase != vBaseEntities.end() && citBase->first < entSnapshot.GetIndex()) ++citBase; if (citBase == vBaseEntities.end() || citBase->first > entSnapshot.GetIndex()) { // // New entity, read from baseline // ushort unType(entSnapshot.GetType()); // If the type is NULL, the entity is dead and should be removed if (unType == 0) continue; pTypeVector = EntityRegistry.GetTypeVector(unType); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); citBase = vBaseEntities.insert(citBase, SnapshotEntry(entSnapshot.GetIndex(), CEntitySnapshot::Allocate(entSnapshot))); ++citBase; } else if (citBase->first == entSnapshot.GetIndex()) { // // Update existing entity // CEntitySnapshot *pBaseSnapshot(CEntitySnapshot::GetByHandle(citBase->second)); ushort unType(entSnapshot.GetTypeChange() ? entSnapshot.GetType() : pBaseSnapshot->GetType()); // If the type is NULL, the entity is dead and should be removed if (unType == 0) { CEntitySnapshot::DeleteByHandle(citBase->second); citBase = vBaseEntities.erase(citBase); continue; } pTypeVector = EntityRegistry.GetTypeVector(unType); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); if (entSnapshot.GetTypeChange()) { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); *pBaseSnapshot = entSnapshot; } else { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector); pBaseSnapshot->ApplyDiff(entSnapshot); } ++citBase; } } uint uiNumClients; // Read reliable game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { m_hReplayData.ReadInt32(); // uiIndex uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); } } // Read game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { m_hReplayData.ReadInt32(); // uiIndex uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); } } // Read state strings uint uiNumStateString(m_hReplayData.ReadInt32()); for (uint ui(0); ui < uiNumStateString; ++ui) { m_hReplayData.ReadInt32(); // uiID tstring sStr; wchar_t wChar(m_hReplayData.ReadInt16()); while (wChar) { sStr += TCHAR(wChar); wChar = m_hReplayData.ReadInt16(); } } #if 0 if (iFrame % 100 == 0) { CBufferDynamic bufFrameData; m_cCurrentSnapshot.WriteBuffer(bufFrameData, 0, 0, -1); hKeyFrames.WriteInt32(bufFrameData.GetLength()); hKeyFrames.Write(bufFrameData.Get(), bufFrameData.GetLength()); } #endif ++iFrame; } StopPlayback(); //hKeyFrames.Close(); Console << _T("Done") << newl; } /*==================== CReplayManager::GenerateKeyFrames ====================*/ void CReplayManager::GenerateKeyFrames() { int iFrame(0); CBufferStatic cBuffer(0x4000); CSnapshot snapshot; while (!m_hReplayData.IsEOF()) { uint uiLength(m_hReplayData.ReadInt32()); if (!uiLength) continue; cBuffer.Clear(); cBuffer.Reserve(uiLength); cBuffer.SetLength(uiLength); m_hReplayData.Read((char *)cBuffer.Get(), uiLength); snapshot.ReadBuffer(cBuffer); if (m_uiBeginTime == INVALID_TIME) m_uiBeginTime = snapshot.GetTimeStamp(); m_cCurrentSnapshot.SetValid(true); m_cCurrentSnapshot.SetFrameNumber(snapshot.GetFrameNumber()); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(snapshot.GetTimeStamp()); // Clear events m_cCurrentSnapshot.SetNumEvents(0); m_cCurrentSnapshot.GetEventBuffer().Clear(); byte yNumEvents(snapshot.GetNumEvents()); // Translate events for (int i(0); i < yNumEvents; ++i) CGameEvent::AdvanceBuffer(snapshot.GetReceivedBuffer()); SnapshotVector &vBaseEntities(m_cCurrentSnapshot.GetEntities()); SnapshotVector_it citBase(vBaseEntities.begin()); static CEntitySnapshot entSnapshot; // Translate entities for (;;) { const vector<SDataField>* pTypeVector(NULL); // Grab a "shell" entity snapshot from the the frame snapshot. // The data will be filled in once we know the type. entSnapshot.Clear(); if (!snapshot.GetNextEntity(entSnapshot, -1)) break; while (citBase != vBaseEntities.end() && citBase->first < entSnapshot.GetIndex()) ++citBase; if (citBase == vBaseEntities.end() || citBase->first > entSnapshot.GetIndex()) { // // New entity, read from baseline // ushort unType(entSnapshot.GetType()); // If the type is NULL, the entity is dead and should be removed if (unType == 0) continue; pTypeVector = EntityRegistry.GetTypeVector(unType); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); citBase = vBaseEntities.insert(citBase, SnapshotEntry(entSnapshot.GetIndex(), CEntitySnapshot::Allocate(entSnapshot))); ++citBase; } else if (citBase->first == entSnapshot.GetIndex()) { // // Update existing entity // CEntitySnapshot *pBaseSnapshot(CEntitySnapshot::GetByHandle(citBase->second)); ushort unType(entSnapshot.GetTypeChange() ? entSnapshot.GetType() : pBaseSnapshot->GetType()); // If the type is NULL, the entity is dead and should be removed if (unType == 0) { CEntitySnapshot::DeleteByHandle(citBase->second); citBase = vBaseEntities.erase(citBase); continue; } pTypeVector = EntityRegistry.GetTypeVector(unType); if (pTypeVector == NULL) EX_ERROR(_T("Unknown entity type, bad snapshot")); if (entSnapshot.GetTypeChange()) { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector, EntityRegistry.GetBaseline(unType)); *pBaseSnapshot = entSnapshot; } else { entSnapshot.ReadBody(snapshot.GetReceivedBuffer(), *pTypeVector); pBaseSnapshot->ApplyDiff(entSnapshot); } ++citBase; } } uint uiNumClients; // Read reliable game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { m_hReplayData.ReadInt32(); // uiIndex uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); } } // Read game data uiNumClients = m_hReplayData.ReadInt32(); for (uint ui(0); ui < uiNumClients; ++ui) { m_hReplayData.ReadInt32(); // uiIndex uint uiLength(m_hReplayData.ReadInt32()); if (uiLength > 0) { CBufferStatic cBuffer(uiLength); for (uint uiRead(0); uiRead < uiLength; ++uiRead) cBuffer << m_hReplayData.ReadByte(); } } // Read state strings uint uiNumStateString(m_hReplayData.ReadInt32()); for (uint ui(0); ui < uiNumStateString; ++ui) { m_hReplayData.ReadInt32(); // uiID tstring sStr; wchar_t wChar(m_hReplayData.ReadInt16()); while (wChar) { sStr += TCHAR(wChar); wChar = m_hReplayData.ReadInt16(); } } if (iFrame % 100 == 0) { SReplayKeyFrame &cKeyFrame = m_mapKeyFrames[iFrame] = SReplayKeyFrame(); cKeyFrame.uiFrame = iFrame; cKeyFrame.zPos = m_hReplayData.Tell(); m_cCurrentSnapshot.WriteBuffer(cKeyFrame.bufSnapshot, 0, 0, -1); } ++iFrame; } m_uiNumFrames = iFrame; m_uiEndTime = m_cCurrentSnapshot.GetTimeStamp(); m_hReplayData.Seek(int(m_zStartPos)); m_cCurrentSnapshot.SetFrameNumber(-1); m_cCurrentSnapshot.SetPrevFrameNumber(-1); m_cCurrentSnapshot.SetTimeStamp(0); m_cCurrentSnapshot.FreeEntities(); } /*==================== CReplayManager::SetPlaybackSpeed ====================*/ void CReplayManager::SetPlaybackSpeed(int iSpeed) { m_iSpeed = CLAMP(iSpeed, -3, 3); if (m_iSpeed > 0) host_timeScale = 1 << m_iSpeed; else if (m_iSpeed < 0) host_timeScale = 1.0f / (1 << -m_iSpeed); else host_timeScale = 1.0f; } /*-------------------- cmdReplayRestart --------------------*/ CMD(ReplayRestart) { CReplayManager::GetInstance()->SetPlaybackFrame(0); return true; } /*-------------------- cmdReplaySetFrame --------------------*/ CMD(ReplaySetFrame) { if (vArgList.size() < 1) { Console << "syntax: ReplaySetFrame <frame>" << newl; return false; } CReplayManager::GetInstance()->SetPlaybackFrame(AtoI(vArgList[0])); return true; } /*-------------------- ReplaySetFrame --------------------*/ UI_VOID_CMD(ReplaySetFrame, 1) { cmdReplaySetFrame(vArgList[0]->Evaluate()); } /*-------------------- cmdReplayIncFrame --------------------*/ CMD(ReplayIncFrame) { if (vArgList.size() < 1) { Console << "syntax: ReplayIncFrame <numframes>" << newl; return false; } CReplayManager::GetInstance()->SetPlaybackFrame(CReplayManager::GetInstance()->GetFrame() + AtoI(vArgList[0])); return true; } /*-------------------- ReplayIncFrame --------------------*/ UI_VOID_CMD(ReplayIncFrame, 1) { cmdReplayIncFrame(vArgList[0]->Evaluate()); } /*-------------------- cmdReplaySetPlaybackSpeed --------------------*/ CMD(ReplaySetPlaybackSpeed) { if (vArgList.size() < 1) { Console << "syntax: ReplaySetPlaybackSpeed <speed>" << newl; return false; } CReplayManager::GetInstance()->SetPlaybackSpeed(AtoI(vArgList[0])); return true; } /*-------------------- ReplaySetPlaybackSpeed --------------------*/ UI_VOID_CMD(ReplaySetPlaybackSpeed, 1) { cmdReplaySetPlaybackSpeed(vArgList[0]->Evaluate()); } /*-------------------- cmdReplayIncPlaybackSpeed --------------------*/ CMD(ReplayIncPlaybackSpeed) { if (vArgList.size() < 1) { Console << "syntax: ReplayIncPlaybackSpeed <inc>" << newl; return false; } CReplayManager::GetInstance()->SetPlaybackSpeed(CReplayManager::GetInstance()->GetPlaybackSpeed() + AtoI(vArgList[0])); return true; } /*-------------------- ReplayIncPlaybackSpeed --------------------*/ UI_VOID_CMD(ReplayIncPlaybackSpeed, 1) { cmdReplayIncPlaybackSpeed(vArgList[0]->Evaluate()); } /*-------------------- cmdReplayProfile --------------------*/ CMD(ReplayProfile) { if (vArgList.size() < 1) { Console << "syntax: ReplayProfile <filename>" << newl; return false; } CReplayManager::GetInstance()->Profile(vArgList[0], vArgList.size() > 1 ? AtoI(vArgList[1]) : -1); return true; } /*-------------------- cmdReplayParse --------------------*/ CMD(ReplayParse) { if (vArgList.size() < 1) { Console << "syntax: ReplayParse <filename>" << newl; return false; } uint uiStartTime(K2System.Milliseconds()); CReplayManager::GetInstance()->Parse(vArgList[0]); Console << _T("Replay parse took ") << MsToSec(K2System.Milliseconds() - uiStartTime) << _T(" secs") << newl; return true; }
0
0.938979
1
0.938979
game-dev
MEDIA
0.771795
game-dev
0.994625
1
0.994625
Doddler/RagnarokRebuildTcp
6,286
RebuildClient/Assets/Scripts/Objects/AudioPlayer.cs
using System; using Assets.Scripts.Utility; using UnityEngine; using UnityEngine.ResourceManagement.AsyncOperations; namespace Assets.Scripts.Objects { public class AudioPlayer : MonoBehaviour { public AudioManager AudioManager; public int ChannelId; private AudioSource audioSource; private GameObject followTarget; private bool hasFollowTarget; private bool isLoading; private bool isInUse; private AsyncOperationHandle<AudioClip> loadHandle; private float endTime; private float delayTime; private bool isDelayed; public void Init(AudioManager manager, int id) { AudioManager = manager; ChannelId = id; audioSource = gameObject.AddComponent<AudioSource>(); audioSource.spatialBlend = 0.65f; audioSource.priority = 80; audioSource.maxDistance = 50; audioSource.rolloffMode = AudioRolloffMode.Custom; audioSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, AudioManager.Instance.FalloffCurve); audioSource.volume = 1f; audioSource.dopplerLevel = 0; audioSource.outputAudioMixerGroup = manager.Mixer.FindMatchingGroups("Sounds")[0];; gameObject.transform.SetParent(AudioManager.gameObject.transform); } public bool PlayAudioClip(AudioClip clip, GameObject attachTarget, float volume) { isInUse = true; isLoading = false; gameObject.SetActive(true); hasFollowTarget = true; followTarget = attachTarget; audioSource.volume = volume; audioSource.clip = clip; audioSource.Play(); endTime = Time.fixedTime + clip.length; return audioSource.isPlaying; } public bool PlayAudioClip(AudioClip clip, Vector3 position, float volume) { //AudioManager.Mixer.GetFloat("Sounds", out var db); //var targetVolume = Mathf.Pow(10f, db / 20f) * volume; isInUse = true; isLoading = false; isDelayed = false; gameObject.SetActive(true); gameObject.transform.localPosition = position; audioSource.volume = volume; audioSource.clip = clip; audioSource.Play(); endTime = Time.fixedTime + clip.length; return audioSource.isPlaying; } public bool PlayAudioClip(string filename, GameObject attachTarget, float volume, bool inEffectFolder = true) { isInUse = true; isLoading = true; isDelayed = false; gameObject.SetActive(true); hasFollowTarget = true; followTarget = attachTarget; audioSource.volume = volume; audioSource.clip = null; audioSource.Stop(); var path = "Assets/Sounds/Effects/" + filename; if (!inEffectFolder) path = "Assets/Sounds/" + filename; loadHandle = AddressableUtility.Load<AudioClip>(gameObject, path, OnFinishLoad); return true; } public bool PlayAudioClip(string filename, Vector3 position, float volume, float delay) { //AudioManager.Mixer.GetFloat("Sounds", out var db); //var targetVolume = Mathf.Pow(10f, db / 20f) * volume; isInUse = true; isLoading = true; if (delay > 0) { isDelayed = true; delayTime = delay; } else isDelayed = false; gameObject.SetActive(true); gameObject.transform.localPosition = position; audioSource.volume = volume; audioSource.clip = null; audioSource.Stop(); var path = "Assets/Sounds/Effects/" + filename; // Debug.Log(path); loadHandle = AddressableUtility.Load<AudioClip>(gameObject, path, OnFinishLoad); return true; } private void OnFinishLoad(AudioClip clip) { // Debug.Log("OnFinishLoad " + clip); if (!isInUse) { Debug.LogWarning($"OnFinishLoad called on audioclip {clip} but the source is already in use playing {audioSource.clip}"); return; //why would this happen? } audioSource.clip = clip; if(!isDelayed) audioSource.Play(); endTime = Time.fixedTime + clip.length + delayTime; } public void Update() { if (!isInUse) { gameObject.SetActive(false); return; } if (hasFollowTarget && followTarget != null) transform.localPosition = followTarget.transform.position; if (isLoading) { if (loadHandle.Status == AsyncOperationStatus.Failed) { AudioManager.MarkAudioChannelAsFree(ChannelId); throw new Exception($"Failed to load audio clip!", loadHandle.OperationException); } if(loadHandle.Status == AsyncOperationStatus.Succeeded) isLoading = false; return; } if (isDelayed) { delayTime -= Time.deltaTime; if (delayTime < 0) { isDelayed = false; audioSource.Play(); } } if (!isLoading && Time.fixedTime > endTime) { audioSource.Stop(); audioSource.clip = null; isInUse = false; followTarget = null; hasFollowTarget = false; gameObject.SetActive(false); AudioManager.MarkAudioChannelAsFree(ChannelId); } } } }
0
0.859506
1
0.859506
game-dev
MEDIA
0.802662
game-dev,audio-video-media
0.996208
1
0.996208
RighteousRyan1/TanksRebirth
20,969
GameContent/Systems/AI/AITank.Attacking.cs
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using TanksRebirth.Enums; using TanksRebirth.GameContent.GameMechanics; using TanksRebirth.GameContent.Globals; using TanksRebirth.GameContent.ID; using TanksRebirth.GameContent.Systems.PingSystem; using TanksRebirth.GameContent.Systems.TankSystem; using TanksRebirth.Graphics; using TanksRebirth.Internals.Common.Framework; using TanksRebirth.Internals.Common.Framework.Collisions; using TanksRebirth.Internals.Common.Utilities; using TanksRebirth.Net; namespace TanksRebirth.GameContent.Systems.AI; public partial class AITank { bool _predicts; bool _isSeeking; float _seekRotation; public bool DoAttack = true; public Tank? TargetTank; public float TurretRotationMultiplier = 1f; public bool IsEnemySpotted; public int CurrentRandomMineLay; public int CurrentRandomShoot; public float ObstacleAwarenessMineReal; /// <summary>The location(s) of which this tank's shot path hits an obstacle.</summary> public Vector2[] ShotPathRicochetPoints { get; private set; } = []; /// <summary>The location(s) of which this tank's shot path hits an tank.</summary> public Vector2[] ShotPathTankCollPoints { get; private set; } = []; /// <summary>Updates turret directions/targets and updates tanks in the shoot path.</summary> public void HandleTurret() { TargetTurretRotation %= MathHelper.TwoPi; TurretRotation %= MathHelper.TwoPi; var diff = TargetTurretRotation - TurretRotation; if (diff > MathHelper.Pi) TargetTurretRotation -= MathHelper.TwoPi; else if (diff < -MathHelper.Pi) TargetTurretRotation += MathHelper.TwoPi; TurretRotation = MathUtils.RoughStep(TurretRotation, TargetTurretRotation, Parameters.TurretSpeed * TurretRotationMultiplier * RuntimeData.DeltaTime); // update things prior to timer check if (TargetTank is null) return; if (!_isSeeking && !_predicts) { IsEnemySpotted = false; if (TargetTank!.Properties.Invisible && TargetTank.TimeSinceLastAction < Parameters.Rememberance) { AimTarget = TargetTank.Position; IsEnemySpotted = true; } if (!TargetTank.Properties.Invisible) { AimTarget = TargetTank.Position; IsEnemySpotted = true; } } UpdateAim(); if (!Behaviors[1].IsModOf(Parameters.TurretMovementTimer)) return; var dirVec = Position - AimTarget; TargetTurretRotation = -dirVec.ToRotation() - MathHelper.PiOver2 + Client.ClientRandom.NextFloat(-Parameters.AimOffset, Parameters.AimOffset); } /// <summary>Attempts to lay a mine based on various conditions and environmental factors.</summary> /// <remarks>This method evaluates multiple conditions to determine whether a mine can be laid, including: /// <list type="bullet"> <item>Whether the tank is capable of laying mines.</item> <item>Whether the mine limit has /// been reached.</item> <item>Proximity to friendly tanks to avoid friendly fire.</item> <item>Presence of /// destructible obstacles nearby, which may influence the chance of laying a mine.</item> <item>Availability of /// safe directions to lay a mine, avoiding existing mines and obstacles.</item> </list> If all conditions are met, /// a mine is laid, and the tank selects a direction to flee.</remarks> public void TryMineLay() { // don't even bother if the tank can't lay mines if (!Behaviors[3].IsModOf(CurrentRandomMineLay)) return; // set our new random window, this gets set Behaviors[3].Value = 0; if (Properties.MineLimit <= 0) return; if (IsSurviving) return; CurrentRandomMineLay = Client.ClientRandom.Next(Parameters.RandomTimerMinMine, Parameters.RandomTimerMaxMine); // check for friendly tanks nearby, if there are any, don't even attempt to lay a mine if (TanksNearMineAwareness.Any(x => x.Team == Team && x.Team != TeamID.NoTeam)) return; bool nearDestructible = false; // call me the wizard of oz ObstacleAwarenessMineReal = 3 * Parameters.ObstacleAwarenessMine; var dist = ObstacleAwarenessMineReal / 2; var dirs = RayCastCardinals(dist, (fixture, point, normal, fraction) => { if (fixture.Body.Tag is Block b) { if (!nearDestructible) nearDestructible = b.Properties.IsDestructible; // b.Stack = (byte)Client.ClientRandom.Next(1, 8); } return fraction; // this wizardry goes beyond me }, ChassisRotation - MathHelper.Pi); var goodDirs = dirs.Where(x => x.Direction != CollisionDirection.None).ToArray(); for (int i = 0; i < goodDirs.Length; i++) { var pos = goodDirs[i].Vec * dist; for (int j = 0; j < Mine.AllMines.Length; j++) { var mine = Mine.AllMines[j]; if (mine is null) continue; // check against radius. ensures the tank doesn't move towards an already laid mine // 70 is the magic number for the default mine radius, multiplied by the scalar if (GameUtils.Distance_WiiTanksUnits(pos, mine.Position) <= mine.ExplosionRadius * GameUtils.Value_WiiTanksUnits(70)) { // Console.WriteLine("Direction " + dirs[i].Direction + " is contaminated"); goodDirs[i].Direction = CollisionDirection.None; } } } bool isMineLayOk = goodDirs.Length != 0; /*Console.WriteLine(); Console.WriteLine($"Opportunity: " + $"\nIsOk: {isMineLayOk}" + $"\nDirsNoObstacle: {string.Join(", ", goodDirs.Select(x => x.Direction))}" + $"\nNearDestructible: {nearDestructible}" + $"\nNewOpportunity: {CurrentRandomMineLay}");*/ //Console.WriteLine(isMineLayOk ? $"Mine-lay is ok! ({string.Join(", ", dirs.Where(x => x.Direction != CollisionDirection.None).Select(x => x.Direction))})" : "Mine-lay is not ok."); // don't lay a mine if the checks fail if (!isMineLayOk) return; // SmartMineLaying was removed in favor // attempt via an opportunity to lay a mine var random = Client.ClientRandom.NextFloat(0, 1); // change chance based on whether or not the tank is near a destructible obstacle var randomSuccess = random <= (nearDestructible ? Parameters.ChanceMineLayNearBreakables : Parameters.ChanceMineLay); if (!randomSuccess) return; LayMine(); var randomDir = Client.ClientRandom.Next(goodDirs.Length); // then determine a good fleeing direction // Console.WriteLine("Laid mine. Choosing to go " + goodDirs[randomDir].Direction); var rot = goodDirs[randomDir].Vec.ToRotation(); // Position += goodDirs[randomDir].Vec * 50; DesiredChassisRotation = rot - MathHelper.PiOver2; } // TODO: make view distance, and make tanks in path public /// <summary>Updates meta-data related to aiming and shooting. The tank will not fire if <see cref="DoAttack"/> is false, but meta-data will still update.</summary> public void UpdateAim() { _predicts = false; SeesTarget = false; bool tooCloseToExplosiveShell = false; var friendliesNearby = TanksNearShootAwareness.Any(x => IsOnSameTeamAs(x.Team)); // stop doing expensive checks if the tank can't even shoot anyway if (friendliesNearby) return; List<Tank> tanksDef; if (Properties.ShellType == ShellID.Explosive) { tanksDef = GetTanksInPath(Vector2.UnitY.Rotate(TurretRotation - MathHelper.Pi), out var ricP, out var tnkCol, offset: Vector2.UnitY * 20, pattern: x => !x.Properties.IsDestructible && x.Properties.IsSolid || x.Type == BlockID.Teleporter, missDist: Parameters.DetectionForgivenessHostile, doBounceReset: Parameters.BounceReset); if (GameUtils.Distance_WiiTanksUnits(ricP[^1], Position) < 150f) // TODO: change from hardcode to normalcode :YES: tooCloseToExplosiveShell = true; } else { tanksDef = GetTanksInPath( Vector2.UnitY.Rotate(TurretRotation - MathHelper.Pi), out var ricP, out var tnkCol, offset: Vector2.UnitY * 20, missDist: Parameters.DetectionForgivenessHostile, doBounceReset: Parameters.BounceReset); TanksSpotted = [.. tanksDef]; ShotPathRicochetPoints = ricP; ShotPathTankCollPoints = tnkCol; } if (Parameters.PredictsPositions) { if (TargetTank is not null) { var calculation = Position.Distance(TargetTank.Position) / (float)(Properties.ShellSpeed * 1.2f); float rot = -Position.DirectionTo(GeometryUtils.PredictFuturePosition(TargetTank.Position, TargetTank.Velocity, calculation)) .ToRotation() - MathHelper.PiOver2; tanksDef = GetTanksInPath( Vector2.UnitY.Rotate(-Position.DirectionTo(TargetTank.Position).ToRotation() - MathHelper.PiOver2), out var ricP, out var tnkCol, offset: Parameters.PredictsPositions ? Vector2.Zero : Vector2.UnitY * 20, missDist: Parameters.DetectionForgivenessHostile, doBounceReset: Parameters.BounceReset); var targ = GeometryUtils.PredictFuturePosition(TargetTank.Position, TargetTank.Velocity, calculation); var posPredict = GetTanksInPath(Vector2.UnitY.Rotate(rot), out var ricP1, out var tnkCol2, offset: Vector2.UnitY * 20, missDist: Parameters.DetectionForgivenessHostile, doBounceReset: Parameters.BounceReset); if (tanksDef.Contains(TargetTank)) { _predicts = true; TargetTurretRotation = rot + MathHelper.Pi; } } } // TODO: is findsSelf even necessary? findsEnemy is only true if findsSelf is false. eh, whatever. my brain is fucked. var findsEnemy = tanksDef.Any(tnk => tnk is not null && (tnk.Team != Team || tnk.Team == TeamID.NoTeam) && tnk != this); var findsSelf = tanksDef.Any(tnk => tnk is not null && tnk == this); var findsFriendly = tanksDef.Any(tnk => tnk is not null && tnk.Team == Team && tnk.Team != TeamID.NoTeam); if (findsEnemy && !tooCloseToExplosiveShell) SeesTarget = true; if (Parameters.SmartRicochets) { //if (!seeks) _seekRotation += Parameters.TurretSpeed * 0.25f; var canShoot = !(CurShootCooldown > 0 || OwnedShellCount >= Properties.ShellLimit); if (canShoot) { var tanks = GetTanksInPath(Vector2.UnitY.Rotate(_seekRotation), out var ricP, out var tnkCol, false, default, Parameters.DetectionForgivenessHostile, doBounceReset: Parameters.BounceReset); var findsEnemy2 = tanks.Any(tnk => tnk is not null && !tnk.IsOnSameTeamAs(Team) && tnk != this); // var findsSelf2 = tanks.Any(tnk => tnk is not null && tnk == this); // var findsFriendly2 = tanks.Any(tnk => tnk is not null && (tnk.Team == Team && tnk.Team != TeamID.NoTeam)); // ChatSystem.SendMessage($"{findsEnemy2} {findsFriendly2} | seek: {seeks}", Color.White); if (findsEnemy2/* && !findsFriendly2*/) { _isSeeking = true; TurretRotationMultiplier = 3f; TargetTurretRotation = _seekRotation - MathHelper.Pi; } } if (TurretRotation == TargetTurretRotation || !canShoot) _isSeeking = false; } // tanks wont shoot when fleeing from a mine if (ClosestDanger is Mine) if (Parameters.CantShootWhileFleeing) return; if (!DoAttack) return; if (!Behaviors[2].IsModOf(CurrentRandomShoot)) return; CurrentRandomShoot = Client.ClientRandom.Next(Parameters.RandomTimerMinShoot, Parameters.RandomTimerMaxShoot); Behaviors[2].Value = 0; // Console.WriteLine(TanksSpotted.Length); // no need to check friendliesNearby because we return earlier in this method if there are any if (Parameters.PredictsPositions) { if (SeesTarget) if (CurShootCooldown <= 0) Shoot(false); } else { if (SeesTarget && !findsSelf && !findsFriendly) if (CurShootCooldown <= 0) Shoot(false); } } /// <summary>Gets the cloesest <see cref="Tank"/> that is hostile and is targetable.</summary> public Tank? GetClosestTarget() { Tank? target = null; var targetPosition = new Vector2(float.MaxValue); foreach (var tank in GameHandler.AllTanks) { if (tank is null || tank.IsDestroyed) continue; if (tank == this) continue; // don't target self if (tank.IsOnSameTeamAs(Team)) continue; // no friendly fire // no need for WiiTanksUnits here since we are simply looking for the closest tank if (Vector2.Distance(tank.Position, Position) < Vector2.Distance(targetPosition, Position)) { // if the tank is invisible, we only target it if it has acted in the last 60 ticks if (tank.Properties.Invisible && tank.TimeSinceLastAction < Parameters.Rememberance || !tank.Properties.Invisible) { target = tank; targetPosition = tank.Position; } } } return target; } /// <summary>A method that simply changes an AI </summary> public Tank? TryOverrideTarget() { Tank? target = TargetTank; if (GameHandler.AllPlayerTanks.Any(x => x is not null && x.IsOnSameTeamAs(Team))) { foreach (var ping in IngamePing.AllIngamePings) { if (ping is null) break; if (ping.TrackedTank is null) break; if (ping.TrackedTank == this) continue; // no self-targeting if (ping.TrackedTank.IsDestroyed) continue; // no dead tanks if (ping.TrackedTank.Team == Team) break; // no friendly fire target = ping.TrackedTank; } } return target; } /// <summary>Makes this <see cref="AITank"/> attempt to shoot to destroy the given <see cref="Shell"/>.</summary> public void DoDeflection(Shell shell) { var calculation = (Position.Distance(shell.Position) - 20f) / (float)(Properties.ShellSpeed * 1.2f); float rot = -Position.DirectionTo(GeometryUtils.PredictFuturePosition(shell.Position, shell.Velocity, calculation)) .ToRotation() + MathHelper.PiOver2; TargetTurretRotation = rot; TurretRotationMultiplier = 4f; // used to be rot %=... was it necessary? //TargetTurretRotation %= MathHelper.Tau; //if ((-TurretRotation + MathHelper.PiOver2).IsInRangeOf(TargetTurretRotation, 0.15f)) Shoot(false); } // TODO: literally fix everything about these turret rotation values. private List<Tank> GetTanksInPath(Vector2 pathDir, out Vector2[] ricochetPoints, out Vector2[] tankCollPoints, bool draw = false, Vector2 offset = default, float missDist = 0f, Func<Block, bool>? pattern = null, bool doBounceReset = true) { const int MAX_PATH_UNITS = 1000; const int PATH_UNIT_LENGTH = 8; List<Tank> tanks = []; List<Vector2> ricoPoints = []; List<Vector2> tnkPoints = []; pattern ??= c => c.Properties.IsSolid || c.Type == BlockID.Teleporter; var whitePixel = TextureGlobals.Pixels[Color.White]; Vector2 pathPos = Position + offset.Rotate(-TurretRotation); pathDir.Y *= -1; pathDir *= PATH_UNIT_LENGTH; int ricochetCount = 0; int uninterruptedIterations = 0; bool teleported = false; int tpTriggerIndex = -1; Vector2 teleportedTo = Vector2.Zero; var pathHitbox = new Rectangle(); for (int i = 0; i < MAX_PATH_UNITS; i++) { uninterruptedIterations++; // World bounds check if (pathPos.X < GameScene.MIN_X || pathPos.X > GameScene.MAX_X) { ricoPoints.Add(pathPos); pathDir.X *= -1; ricochetCount++; if (doBounceReset) uninterruptedIterations = 0; } else if (pathPos.Y < GameScene.MIN_Z || pathPos.Y > GameScene.MAX_Z) { ricoPoints.Add(pathPos); pathDir.Y *= -1; ricochetCount++; if (doBounceReset) uninterruptedIterations = 0; } // Setup hitbox once pathHitbox.X = (int)pathPos.X - 5; pathHitbox.Y = (int)pathPos.Y - 5; pathHitbox.Width = 8; pathHitbox.Height = 8; Vector2 dummy = Vector2.Zero; Collision.HandleCollisionSimple_ForBlocks(pathHitbox, pathDir, ref dummy, out var dir, out var block, out bool corner, false, pattern); if (corner) break; if (block is not null) { if (block.Type == BlockID.Teleporter && !teleported) { var dest = Block.AllBlocks.FirstOrDefault(bl => bl != null && bl != block && bl.TpLink == block.TpLink); if (dest is not null) { teleported = true; teleportedTo = dest.Position; tpTriggerIndex = i + 1; } } else if (block.Properties.AllowShotPathBounce) { ricoPoints.Add(pathPos); ricochetCount += block.Properties.PathBounceCount; switch (dir) { case CollisionDirection.Up: case CollisionDirection.Down: pathDir.Y *= -1; break; case CollisionDirection.Left: case CollisionDirection.Right: pathDir.X *= -1; break; } if (doBounceReset) uninterruptedIterations = 0; } } // Delay teleport until next frame if (teleported && i == tpTriggerIndex) { pathPos = teleportedTo; } // Check destroy conditions bool hitsInstant = i == 0 && Block.AllBlocks.Any(x => x != null && x.Hitbox.Intersects(pathHitbox) && pattern(x)); bool hitsTooEarly = i < (int)Properties.ShellSpeed / 2 && ricochetCount > 0; bool ricochetLimitReached = ricochetCount > Properties.RicochetCount; if (hitsInstant || hitsTooEarly || ricochetLimitReached) break; // Check tanks BEFORE moving float realMiss = 1f + missDist * 2 * uninterruptedIterations; foreach (var enemy in GameHandler.AllTanks) { if (enemy is null || enemy.IsDestroyed || tanks.Contains(enemy)) continue; if (i > 15 && GameUtils.Distance_WiiTanksUnits(enemy.Position, pathPos) <= realMiss) { var pathAngle = pathDir.ToRotation(); var toEnemy = pathPos.DirectionTo(enemy.Position).ToRotation(); if (MathUtils.AbsoluteAngleBetween(pathAngle, toEnemy) >= MathHelper.PiOver2) tanks.Add(enemy); } var pathCircle = new Circle { Center = pathPos, Radius = 4 }; if (enemy.CollisionCircle.Intersects(pathCircle)) { tnkPoints.Add(pathPos); tanks.Add(enemy); } } if (draw) { var screenPos = MatrixUtils.ConvertWorldToScreen( Vector3.Zero, Matrix.CreateTranslation(pathPos.X, 11, pathPos.Y), CameraGlobals.GameView, CameraGlobals.GameProjection ); TankGame.SpriteRenderer.Draw( whitePixel, screenPos, null, Color.White * 0.5f, 0, whitePixel.Size() / 2, realMiss, default, default ); } pathPos += pathDir; } tankCollPoints = [.. tnkPoints]; ricochetPoints = [.. ricoPoints]; return tanks; } }
0
0.958067
1
0.958067
game-dev
MEDIA
0.972976
game-dev
0.93331
1
0.93331
HunterPie/HunterPie
1,531
HunterPie.UI/Overlay/Widgets/Classes/ViewModels/InsectGlaiveViewModel.cs
using HunterPie.Core.Game.Enums; using HunterPie.UI.Architecture; namespace HunterPie.UI.Overlay.Widgets.Classes.ViewModels; public class InsectGlaiveViewModel : ViewModel, IClassViewModel { public Weapon WeaponId => Weapon.InsectGlaive; private KinsectBuff _primaryQueuedBuff; public KinsectBuff PrimaryQueuedBuff { get => _primaryQueuedBuff; set => SetValue(ref _primaryQueuedBuff, value); } private KinsectBuff _secondaryQueuedBuff; public KinsectBuff SecondaryQueuedBuff { get => _secondaryQueuedBuff; set => SetValue(ref _secondaryQueuedBuff, value); } private double _stamina; public double Stamina { get => _stamina; set => SetValue(ref _stamina, value); } private double _maxStamina; public double MaxStamina { get => _maxStamina; set => SetValue(ref _maxStamina, value); } private double _attackTimer; public double AttackTimer { get => _attackTimer; set => SetValue(ref _attackTimer, value); } private double _movementSpeedTimer; public double MovementSpeedTimer { get => _movementSpeedTimer; set => SetValue(ref _movementSpeedTimer, value); } private double _defenseTimer; public double DefenseTimer { get => _defenseTimer; set => SetValue(ref _defenseTimer, value); } private KinsectChargeType _chargeType; public KinsectChargeType ChargeType { get => _chargeType; set => SetValue(ref _chargeType, value); } private double _chargeTimer; public double ChargeTimer { get => _chargeTimer; set => SetValue(ref _chargeTimer, value); } }
0
0.914958
1
0.914958
game-dev
MEDIA
0.953169
game-dev
0.783535
1
0.783535
Wanderers-Of-The-Rift/wotr-mod
1,577
src/main/java/com/wanderersoftherift/wotr/core/rift/parameter/definitions/RiftParameter.java
package com.wanderersoftherift.wotr.core.rift.parameter.definitions; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; import com.wanderersoftherift.wotr.init.WotrRegistries; import com.wanderersoftherift.wotr.serialization.LaxRegistryCodec; import net.minecraft.core.Holder; import net.minecraft.resources.ResourceKey; import net.minecraft.util.RandomSource; import java.util.function.Function; public interface RiftParameter { Codec<Holder<RiftParameter>> HOLDER_CODEC = LaxRegistryCodec.ref(WotrRegistries.Keys.RIFT_PARAMETER_CONFIGS); Codec<RiftParameter> CODEC = Codec .either(Codec.either(ConstantRiftParameter.CODEC, ReferenceRiftParameter.CODEC), RegisteredRiftParameter.CODEC) .xmap(it -> it.map(it2 -> it2.map(it3 -> it3, it3 -> it3), it2 -> it2), it -> switch (it) { case ConstantRiftParameter constantRiftParameterType -> Either.left(Either.left(constantRiftParameterType)); case RegisteredRiftParameter registeredRiftParameterType -> Either.right(registeredRiftParameterType); case ReferenceRiftParameter referenceRiftParameterType -> Either.left(Either.right(referenceRiftParameterType)); default -> throw new IllegalStateException("Unexpected value: " + it); }); Codec<RiftParameter> DEFINITION_CODEC = CODEC.fieldOf("initializer").codec(); double getValue(int tier, RandomSource rng, Function<ResourceKey<RiftParameter>, Double> parameterGetter); }
0
0.896944
1
0.896944
game-dev
MEDIA
0.572377
game-dev
0.770735
1
0.770735
DeltaV-Station/Delta-v
1,993
Content.IntegrationTests/Pair/TestPair.Prototypes.cs
#nullable enable using System.Collections.Generic; using Robust.Shared.Prototypes; using Robust.Shared.Utility; using Robust.UnitTesting; namespace Content.IntegrationTests.Pair; // This partial class contains helper methods to deal with yaml prototypes. public sealed partial class TestPair { private Dictionary<Type, HashSet<string>> _loadedPrototypes = new(); private HashSet<string> _loadedEntityPrototypes = new(); public async Task LoadPrototypes(List<string> prototypes) { await LoadPrototypes(Server, prototypes); await LoadPrototypes(Client, prototypes); } private async Task LoadPrototypes(RobustIntegrationTest.IntegrationInstance instance, List<string> prototypes) { var changed = new Dictionary<Type, HashSet<string>>(); foreach (var file in prototypes) { instance.ProtoMan.LoadString(file, changed: changed); } await instance.WaitPost(() => instance.ProtoMan.ReloadPrototypes(changed)); foreach (var (kind, ids) in changed) { _loadedPrototypes.GetOrNew(kind).UnionWith(ids); } if (_loadedPrototypes.TryGetValue(typeof(EntityPrototype), out var entIds)) _loadedEntityPrototypes.UnionWith(entIds); } public bool IsTestPrototype(EntityPrototype proto) { return _loadedEntityPrototypes.Contains(proto.ID); } public bool IsTestEntityPrototype(string id) { return _loadedEntityPrototypes.Contains(id); } public bool IsTestPrototype<TPrototype>(string id) where TPrototype : IPrototype { return IsTestPrototype(typeof(TPrototype), id); } public bool IsTestPrototype<TPrototype>(TPrototype proto) where TPrototype : IPrototype { return IsTestPrototype(typeof(TPrototype), proto.ID); } public bool IsTestPrototype(Type kind, string id) { return _loadedPrototypes.TryGetValue(kind, out var ids) && ids.Contains(id); } }
0
0.729738
1
0.729738
game-dev
MEDIA
0.314792
game-dev
0.638744
1
0.638744
manaporkun/Automatic-LOD-Generator
1,494
Project Files/Assets/Plugins/Auto-LOD-Generator/Editor/MeshSimplify.cs
using System; using JetBrains.Annotations; using UnityEngine; namespace Plugins.Auto_LOD_Generator.Editor { public class MeshSimplify : MonoBehaviour { public static void Simplify([NotNull] GameObject originalObject, float qualityFactor, string name) { if (originalObject == null) throw new ArgumentNullException(nameof(originalObject)); var originalMesh = originalObject.GetComponent<MeshFilter>().sharedMesh; var originalMaterial = originalObject.GetComponent<MeshRenderer>().sharedMaterial; var originalTransform = originalObject.transform; var meshSimplifier = new UnityMeshSimplifier.MeshSimplifier(); meshSimplifier.Initialize(originalMesh); meshSimplifier.SimplifyMesh(qualityFactor); var destMesh = meshSimplifier.ToMesh(); var newGameObj = new GameObject(originalObject.name + name); newGameObj.AddComponent<MeshFilter>(); newGameObj.AddComponent<MeshRenderer>(); newGameObj.GetComponent<MeshFilter>().sharedMesh = destMesh; newGameObj.GetComponent<MeshRenderer>().sharedMaterial = originalMaterial; newGameObj.transform.position = originalTransform.position; newGameObj.transform.rotation = originalTransform.rotation; newGameObj.transform.localScale = originalTransform.localScale; } } }
0
0.819869
1
0.819869
game-dev
MEDIA
0.661713
game-dev,graphics-rendering
0.74421
1
0.74421
lua9520/source-engine-2018-cstrike15_src
7,425
game/shared/entityutil.h
/** * EntityUtil.h * Various utility functions */ #ifndef _ENTITY_UTIL_H_ #define _ENTITY_UTIL_H_ //------------------------------------------------------------------------------------------ enum WhoType { ANYONE, ONLY_FRIENDS, ONLY_ENEMIES }; //-------------------------------------------------------------------------------------------------------------- /** * Iterate over all entities in the game, invoking functor on each. * If functor returns false, stop iteration and return false. */ template < typename Functor > bool ForEachEntity( Functor &func ) { CBaseEntity *entity = gEntList.FirstEnt(); while ( entity ) { if ( func( entity ) == false ) return false; entity = gEntList.NextEnt( entity ); } return true; } //-------------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------------- #ifdef GAME_DLL class FindInViewConeFunctor { public: FindInViewConeFunctor( CBasePlayer *me, WhoType who, float tolerance, CBaseEntity *ignore = NULL ) { m_me = me; m_who = who; m_tolerance = tolerance; m_target = NULL; m_range = 9999999.9f; m_ignore = ignore; me->EyeVectors(&m_dir, NULL, NULL); m_origin = me->GetAbsOrigin() + me->GetViewOffset(); } bool operator() ( CBasePlayer *player ) { if (player != m_me && player != m_ignore && player->IsAlive()) { if (m_who == ONLY_FRIENDS && m_me->GetTeamNumber() != player->GetTeamNumber() ) return true; if (m_who == ONLY_ENEMIES && m_me->GetTeamNumber() == player->GetTeamNumber() ) return true; Vector to = player->WorldSpaceCenter() - m_origin; float range = to.NormalizeInPlace(); if (DotProduct( to, m_dir ) > m_tolerance && range < m_range) { if ( m_me->IsLineOfSightClear( player ) ) { m_target = player; m_range = range; } } } return true; } CBasePlayer *m_me; WhoType m_who; float m_tolerance; CBaseEntity *m_ignore; Vector m_origin; Vector m_dir; CBasePlayer *m_target; float m_range; }; /** * Find the closest player within the given view cone */ inline CBasePlayer *GetClosestPlayerInViewCone( CBasePlayer *me, WhoType who, float tolerance = 0.95f, float *range = NULL, CBaseEntity *ignore = NULL ) { // choke the victim we are pointing at FindInViewConeFunctor checkCone( me, who, tolerance, ignore ); ForEachPlayer( checkCone ); if (range) *range = checkCone.m_range; return checkCone.m_target; } #endif //-------------------------------------------------------------------------------------------------------------- /** * Find player closest to ray. * Return perpendicular distance to ray in 'offset' if it is non-NULL. */ extern CBasePlayer *GetPlayerClosestToRay( CBasePlayer *me, WhoType who, const Vector &start, const Vector &end, float *offset = NULL ); //-------------------------------------------------------------------------------------------------------------- /** * Compute the closest point on the ray to 'pos' and return it in 'pointOnRay'. * If point projects beyond the ends of the ray, return false - but clamp 'pointOnRay' to the correct endpoint. */ inline bool ClosestPointOnRay( const Vector &pos, const Vector &rayStart, const Vector &rayEnd, Vector *pointOnRay ) { Vector to = pos - rayStart; Vector dir = rayEnd - rayStart; float length = dir.NormalizeInPlace(); float rangeAlong = DotProduct( dir, to ); if (rangeAlong < 0.0f) { // off start point *pointOnRay = rayStart; return false; } else if (rangeAlong > length) { // off end point *pointOnRay = rayEnd; return false; } else // within ray bounds { Vector onRay = rayStart + rangeAlong * dir; *pointOnRay = onRay; return true; } } //------------------------------------------------------------------------------------------ /** * Functor to find the player closest to a ray. * For use with ForEachPlayerNearRay(). */ class ClosestToRayFunctor { public: ClosestToRayFunctor( CBasePlayer *ignore, WhoType who = ANYONE ) { m_ignore = ignore; m_who = who; m_closestPlayer = NULL; m_closestPlayerRange = 999999999.9f; } bool operator() ( CBasePlayer *player, float rangeToRay ) { if (player == m_ignore) return true; if (!player->IsAlive()) return true; if (m_who == ONLY_FRIENDS && m_ignore->GetTeamNumber() != player->GetTeamNumber() ) return true; if (m_who == ONLY_ENEMIES && m_ignore->GetTeamNumber() == player->GetTeamNumber() ) return true; // keep the player closest to the ray if (rangeToRay < m_closestPlayerRange) { m_closestPlayerRange = rangeToRay; m_closestPlayer = player; } return true; } CBasePlayer *m_ignore; WhoType m_who; CBasePlayer *m_closestPlayer; float m_closestPlayerRange; }; //-------------------------------------------------------------------------------------------------------------- /** * Iterate over all players that are within range of the ray and invoke functor. * If functor returns false, stop iteration and return false. * @todo Check LOS to ray. */ template < typename Functor > bool ForEachPlayerNearRay( Functor &func, const Vector &start, const Vector &end, float maxRadius ) { for( int i=1; i<=gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (player == NULL) continue; if (FNullEnt( player->edict() )) continue; if (!player->IsPlayer()) continue; if (!player->IsAlive()) continue; float range = DistanceToRay( player->WorldSpaceCenter(), start, end ); if (range < 0.0f || range > maxRadius) continue; if (func( player, range ) == false) return false; } return true; } //-------------------------------------------------------------------------------------------------------------- /** * Iterate over all players that are within range of the sphere and invoke functor. * If functor returns false, stop iteration and return false. * @todo Check LOS to ray. */ template < typename Functor > bool ForEachPlayerNearSphere( Functor &func, const Vector &origin, float radius ) { for( int i=1; i<=gpGlobals->maxClients; ++i ) { CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) ); if (player == NULL) continue; if (FNullEnt( player->edict() )) continue; if (!player->IsPlayer()) continue; if (!player->IsAlive()) continue; Vector to = player->WorldSpaceCenter() - origin; float range = to.Length(); if (range > radius) continue; if (func( player, range ) == false) return false; } return true; } //-------------------------------------------------------------------------------------------------------------- /** * Reflect a vector. * Assumes 'unitNormal' is normalized. */ inline Vector VectorReflect( const Vector &in, const Vector &unitNormal ) { // compute the unit vector out of the plane of 'in' and 'unitNormal' Vector lat = CrossProduct( in, unitNormal ); Vector forward = CrossProduct( unitNormal, lat ); forward.NormalizeInPlace(); Vector forwardComponent = forward * DotProduct( in, forward ); Vector normalComponent = unitNormal * DotProduct( in, unitNormal ); return forwardComponent - normalComponent; } #endif // _ENTITY_UTIL_H_
0
0.820331
1
0.820331
game-dev
MEDIA
0.893598
game-dev
0.982685
1
0.982685
GeyserMC/Geyser
3,512
core/src/main/java/org/geysermc/geyser/level/chunk/bitarray/PaddedBitArray.java
/* * Copyright (c) 2019-2022 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.level.chunk.bitarray; import org.cloudburstmc.protocol.common.util.Preconditions; import org.geysermc.geyser.util.MathUtils; import java.util.Arrays; public class PaddedBitArray implements BitArray { /** * Array used to store data */ private final int[] words; /** * Palette version information */ private final BitArrayVersion version; /** * Number of entries in this palette (<b>not</b> the length of the words array that internally backs this palette) */ private final int size; PaddedBitArray(BitArrayVersion version, int size, int[] words) { this.size = size; this.version = version; this.words = words; int expectedWordsLength = MathUtils.ceil((float) size / version.entriesPerWord); if (words.length != expectedWordsLength) { throw new IllegalArgumentException("Invalid length given for storage, got: " + words.length + " but expected: " + expectedWordsLength); } } @Override public void set(int index, int value) { Preconditions.checkElementIndex(index, this.size); Preconditions.checkArgument(value >= 0 && value <= this.version.maxEntryValue, "Invalid value"); int arrayIndex = index / this.version.entriesPerWord; int offset = (index % this.version.entriesPerWord) * this.version.bits; this.words[arrayIndex] = this.words[arrayIndex] & ~(this.version.maxEntryValue << offset) | (value & this.version.maxEntryValue) << offset; } @Override public int get(int index) { Preconditions.checkElementIndex(index, this.size); int arrayIndex = index / this.version.entriesPerWord; int offset = (index % this.version.entriesPerWord) * this.version.bits; return (this.words[arrayIndex] >>> offset) & this.version.maxEntryValue; } @Override public int size() { return this.size; } @Override public int[] getWords() { return this.words; } @Override public BitArrayVersion getVersion() { return this.version; } @Override public BitArray copy() { return new PaddedBitArray(this.version, this.size, Arrays.copyOf(this.words, this.words.length)); } }
0
0.815384
1
0.815384
game-dev
MEDIA
0.366393
game-dev
0.769789
1
0.769789
cao-awa/Conium
1,411
common/src/main/kotlin/com/github/cao/awa/conium/block/entity/event/chest/close/ConiumChestClosingEventMetadata.kt
package com.github.cao.awa.conium.block.entity.event.chest.close import com.github.cao.awa.conium.event.context.ConiumEventContext import com.github.cao.awa.conium.event.metadata.ConiumEventMetadata import com.github.cao.awa.conium.event.type.ConiumEventArgTypes.BLOCK_ENTITY import com.github.cao.awa.conium.event.type.ConiumEventArgTypes.BLOCK_POS import com.github.cao.awa.conium.event.type.ConiumEventArgTypes.PLAYER import com.github.cao.awa.conium.event.type.ConiumEventArgTypes.VIEWER_COUNT_MANAGER import com.github.cao.awa.conium.event.type.ConiumEventArgTypes.WORLD import com.github.cao.awa.conium.event.type.ConiumEventArgTypes.BLOCK_STATE import net.minecraft.block.Block import net.minecraft.block.BlockState import net.minecraft.block.entity.BlockEntity import net.minecraft.block.entity.ViewerCountManager import net.minecraft.entity.player.PlayerEntity import net.minecraft.util.math.BlockPos import net.minecraft.world.World class ConiumChestClosingEventMetadata(val context: ConiumEventContext<Block>) : ConiumEventMetadata<Block>() { val world: World = this.context[WORLD] val player: PlayerEntity = this.context[PLAYER] val blockEntity: BlockEntity = this.context[BLOCK_ENTITY] val blockState: BlockState = this.context[BLOCK_STATE] val blockPos: BlockPos = this.context[BLOCK_POS] val viewerCountManager: ViewerCountManager = this.context[VIEWER_COUNT_MANAGER] }
0
0.693929
1
0.693929
game-dev
MEDIA
0.966116
game-dev
0.519432
1
0.519432
SkelletonX/DDTank4.1
12,256
Source Flash/scripts/game/TryAgain.as
package game { import com.pickgliss.toplevel.StageReferance; import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.controls.BaseButton; import com.pickgliss.ui.core.Disposeable; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.utils.ObjectUtils; import ddt.events.GameEvent; import ddt.manager.GameInSocketOut; import ddt.manager.LanguageMgr; import ddt.manager.LeavePageManager; import ddt.manager.PlayerManager; import ddt.manager.SoundManager; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.Shape; import flash.display.Sprite; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.geom.Matrix; import flash.utils.Dictionary; import flash.utils.Timer; import game.model.MissionAgainInfo; import room.RoomManager; import room.model.RoomInfo; [Event(name="giveup",type="ddt.events.GameEvent")] [Event(name="tryagain",type="ddt.events.GameEvent")] [Event(name="timeOut",type="ddt.events.GameEvent")] public class TryAgain extends Sprite implements Disposeable { private var _back:DisplayObject; private var _tryagain:BaseButton; private var _giveup:BaseButton; private var _titleField:FilterFrameText; private var _valueField:FilterFrameText; private var _valueBack:DisplayObject; private var _timer:Timer; private var _numDic:Dictionary; private var _markshape:Shape; private var _container:Sprite; protected var _info:MissionAgainInfo; private var _buffNote:DisplayObject; protected var _isShowNum:Boolean; public function TryAgain(param1:MissionAgainInfo, param2:Boolean = true) { this._numDic = new Dictionary(); this._info = param1; this._isShowNum = param2; super(); this._timer = new Timer(1000,10); if(this._isShowNum) { this.creatNums(); } this.configUI(); this.addEvent(); } protected function tryagain(param1:Boolean = true) : void { dispatchEvent(new GameEvent(GameEvent.TRYAGAIN,param1)); } public function show() : void { if(!RoomManager.Instance.current) { return; } if(RoomManager.Instance.current.selfRoomPlayer.isViewer) { switch(GameManager.Instance.TryAgain) { case GameManager.MissionAgain: this.tryagain(false); break; case GameManager.MissionGiveup: this.__giveup(null); break; case GameManager.MissionTimeout: this.timeOut(); } } else { this._timer.start(); } } private function configUI() : void { this.drawBlack(); this._container = new Sprite(); addChild(this._container); this._back = ComponentFactory.Instance.creatBitmap("asset.game.tryagain.back"); this._container.addChild(this._back); this._tryagain = ComponentFactory.Instance.creatComponentByStylename("GameTryAgain"); if(RoomManager.Instance.current) { this._tryagain.enable = RoomManager.Instance.current.selfRoomPlayer.isHost; } this._container.addChild(this._tryagain); this._giveup = ComponentFactory.Instance.creatComponentByStylename("GameGiveUp"); if(RoomManager.Instance.current) { this._giveup.enable = RoomManager.Instance.current.selfRoomPlayer.isHost; } this._container.addChild(this._giveup); this._titleField = ComponentFactory.Instance.creatComponentByStylename("GameTryAgainTitle"); this._container.addChild(this._titleField); this._titleField.htmlText = LanguageMgr.GetTranslation("tnak.game.tryagain.title",this._info.host); if(RoomManager.Instance.current && RoomManager.Instance.current.type == RoomInfo.LANBYRINTH_ROOM) { this._titleField.htmlText = LanguageMgr.GetTranslation("tnak.game.tryagain.titleII",this._info.host); } this._valueBack = ComponentFactory.Instance.creatBitmap("asset.game.tryagain.text"); this._container.addChild(this._valueBack); this._valueField = ComponentFactory.Instance.creatComponentByStylename("GameTryAgainValue"); this._container.addChild(this._valueField); this._markshape = new Shape(); this._markshape.y = 80; if(this._isShowNum && RoomManager.Instance.current && !RoomManager.Instance.current.selfRoomPlayer.isViewer) { this.drawMark(this._timer.repeatCount); } this._container.addChild(this._markshape); this._container.x = StageReferance.stageWidth - this._container.width >> 1; this._container.y = StageReferance.stageHeight - this._container.height >> 1; if(RoomManager.Instance.current && RoomManager.Instance.current.selfRoomPlayer.isHost && this._info.hasLevelAgain) { this.drawLevelAgainBuff(); this._valueField.htmlText = LanguageMgr.GetTranslation("tnak.game.tryagain.value",0); } else { this._valueField.htmlText = LanguageMgr.GetTranslation("tnak.game.tryagain.value",this._info.value); } } private function drawLevelAgainBuff() : void { this._buffNote = addChild(ComponentFactory.Instance.creat("asset.core.payBuffAsset72.note")); } private function drawBlack() : void { var _loc1_:Graphics = graphics; _loc1_.clear(); _loc1_.beginFill(0,0.4); _loc1_.drawRect(0,0,2000,1000); _loc1_.endFill(); } private function creatNums() : void { var _loc1_:BitmapData = null; var _loc2_:int = 0; while(_loc2_ < 10) { _loc1_ = ComponentFactory.Instance.creatBitmapData("asset.game.mark.Blue" + _loc2_); this._numDic["Blue" + _loc2_] = _loc1_; _loc2_++; } } private function addEvent() : void { this._tryagain.addEventListener(MouseEvent.CLICK,this.__tryagainClick); this._giveup.addEventListener(MouseEvent.CLICK,this.__giveup); this._timer.addEventListener(TimerEvent.TIMER,this.__mark); this._timer.addEventListener(TimerEvent.TIMER_COMPLETE,this.__timeComplete); GameManager.Instance.addEventListener(GameEvent.MISSIONAGAIN,this.__missionAgain); } private function __missionAgain(param1:GameEvent) : void { var _loc2_:int = param1.data; switch(_loc2_) { case GameManager.MissionAgain: this.tryagain(false); break; case GameManager.MissionGiveup: this.__giveup(null); break; case GameManager.MissionTimeout: this.timeOut(); } } private function timeOut() : void { dispatchEvent(new GameEvent(GameEvent.TIMEOUT,null)); } private function __timeComplete(param1:TimerEvent) : void { switch(GameManager.Instance.TryAgain) { case GameManager.MissionAgain: this.tryagain(false); break; case GameManager.MissionGiveup: this.__giveup(null); break; case GameManager.MissionTimeout: this.timeOut(); } } private function drawMark(param1:int) : void { var _loc3_:BitmapData = null; var _loc5_:String = null; var _loc6_:int = 0; var _loc2_:Graphics = this._markshape.graphics; _loc2_.clear(); var _loc4_:String = param1.toString(); if(param1 == 10) { _loc6_ = 0; while(_loc6_ < _loc4_.length) { _loc5_ = "Blue" + _loc4_.substr(_loc6_,1); _loc3_ = this._numDic[_loc5_]; _loc2_.beginBitmapFill(_loc3_,new Matrix(1,0,0,1,this._markshape.width)); _loc2_.drawRect(this._markshape.width,0,_loc3_.width,_loc3_.height); _loc2_.endFill(); _loc6_++; } this._markshape.x = (this._back.width - _loc3_.width >> 1) - 20; } else { _loc3_ = this._numDic["Blue" + _loc4_]; _loc2_.beginBitmapFill(_loc3_); _loc2_.drawRect(0,0,_loc3_.width,_loc3_.height); _loc2_.endFill(); this._markshape.x = this._back.width - _loc3_.width >> 1; } } private function __mark(param1:TimerEvent) : void { SoundManager.instance.play("014"); if(this._isShowNum) { this.drawMark(this._timer.repeatCount - this._timer.currentCount); } } protected function __tryagainClick(param1:MouseEvent) : void { if(param1) { SoundManager.instance.play("008"); } if(GameManager.Instance.Current.selfGamePlayer.hasLevelAgain > 0) { GameInSocketOut.sendMissionTryAgain(GameManager.MissionAgain,true,false); return; } if(RoomManager.Instance.current && RoomManager.Instance.current.selfRoomPlayer.isHost) { if(this.checkMoney(this._info.value)) { return; } GameInSocketOut.sendMissionTryAgain(GameManager.MissionAgain,true); } else { this.tryagain(false); } } public function checkMoney(param1:int) : Boolean { if(PlayerManager.Instance.Self.Money < param1) { LeavePageManager.showFillFrame(); return true; } return false; } private function __giveup(param1:MouseEvent) : void { if(param1) { SoundManager.instance.play("008"); } dispatchEvent(new GameEvent(GameEvent.GIVEUP,null)); } private function removeEvent() : void { this._tryagain.removeEventListener(MouseEvent.CLICK,this.__tryagainClick); this._giveup.removeEventListener(MouseEvent.CLICK,this.__giveup); this._timer.removeEventListener(TimerEvent.TIMER,this.__mark); this._timer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.__timeComplete); GameManager.Instance.removeEventListener(GameEvent.MISSIONAGAIN,this.__missionAgain); } public function setLabyrinthTryAgain() : void { this._titleField.htmlText = LanguageMgr.GetTranslation("tnak.game.tryagain.titleII",this._info.host); } public function dispose() : void { var _loc1_:* = null; this.removeEvent(); for(_loc1_ in this._numDic) { ObjectUtils.disposeObject(this._numDic[_loc1_]); delete this._numDic[_loc1_]; } ObjectUtils.disposeObject(this._buffNote); this._buffNote = null; ObjectUtils.disposeObject(this._markshape); this._markshape = null; ObjectUtils.disposeObject(this._valueField); this._valueField = null; ObjectUtils.disposeObject(this._valueBack); this._valueBack = null; ObjectUtils.disposeObject(this._titleField); this._titleField = null; ObjectUtils.disposeObject(this._giveup); this._giveup = null; ObjectUtils.disposeObject(this._tryagain); this._tryagain = null; ObjectUtils.disposeObject(this._back); this._back = null; if(parent) { parent.removeChild(this); } } } }
0
0.952446
1
0.952446
game-dev
MEDIA
0.968634
game-dev
0.987512
1
0.987512
Tslat/Advent-Of-Ascension
1,076
source/content/item/tool/artifice/ArtificeItem.java
package net.tslat.aoa3.content.item.tool.artifice; import net.minecraft.core.Holder; import net.minecraft.network.chat.Component; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.enchantment.Enchantment; import net.tslat.aoa3.common.registration.AoATags; import net.tslat.aoa3.util.LocaleUtil; import java.util.List; public class ArtificeItem extends Item { public ArtificeItem(Properties properties) { super(properties); } @Override public boolean supportsEnchantment(ItemStack stack, Holder<Enchantment> enchantment) { return !enchantment.is(AoATags.Enchantments.ARTIFICE_TOOL_INCOMPATIBLE) && super.supportsEnchantment(stack, enchantment); } @Override public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltipComponents, TooltipFlag tooltipFlag) { tooltipComponents.add(LocaleUtil.getFormattedItemDescriptionText(this, LocaleUtil.ItemDescriptionType.NEUTRAL, 1)); } }
0
0.591507
1
0.591507
game-dev
MEDIA
0.997353
game-dev
0.698505
1
0.698505
EverestAPI/Everest
26,728
Celeste.Mod.mm/Patches/OuiFileSelectSlot.cs
#pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value #pragma warning disable CS0414 // The field is assigned but its value is never used using Celeste.Mod; using Celeste.Mod.Core; using Celeste.Mod.UI; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Mono.Cecil; using Mono.Cecil.Cil; using Monocle; using MonoMod; using MonoMod.Cil; using MonoMod.InlineRT; using MonoMod.Utils; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Celeste { public class patch_OuiFileSelectSlot : OuiFileSelectSlot { /// <summary> /// Interface used to tag OuiFileSelectSlot submenus. /// </summary> public interface ISubmenu { } // We're effectively in OuiFileSelectSlot, but still need to "expose" private fields to our mod. public new patch_SaveData SaveData; private OuiFileSelect fileSelect; private List<Button> buttons; private Tween tween; private float inputDelay; private bool deleting; private int buttonIndex; private float selectedEase; private float newgameFade; private Wiggler wiggler; [MonoModIgnore] private bool selected { get; set; } private OuiFileSelectSlotLevelSetPicker newGameLevelSetPicker; public bool MissingVanillaData; // computed maximums for stamp rendering private int maxStrawberryCount; private int maxGoldenStrawberryCount; private int maxStrawberryCountIncludingUntracked; private int maxCassettes; private int maxCrystalHeartsExcludingCSides; private int maxCrystalHearts; private bool summitStamp; private bool farewellStamp; private int totalGoldenStrawberries; private int totalHeartGems; private int totalCassettes; private bool renamed; private bool Golden => !Corrupted && Exists && SaveData.TotalStrawberries >= maxStrawberryCountIncludingUntracked; // vanilla: new Vector2(960f, 540 + 310 * (FileSlot - 1)); => slot 1 is centered at all times // if there are 6 slots (0-based): slot 1 should be centered if slot 0 is selected; slot 4 should be centered if slot 5 is selected; the selected slot should be centered otherwise. // this formula doesn't change the behavior with 3 slots, since the slot index will be clamped between 1 and 1. public new Vector2 IdlePosition { [MonoModReplace] get => new Vector2(960f, 540 + 310 * (FileSlot - Calc.Clamp(fileSelect.SlotIndex, 1, fileSelect.Slots.Length - 2))); } public patch_OuiFileSelectSlot(int index, OuiFileSelect fileSelect, SaveData data) : base(index, fileSelect, data) { // no-op. MonoMod ignores this - we only need this to make the compiler shut up. } [MonoModConstructor] [MonoModIgnore] // don't change anything in the method... [PatchTotalHeartGemChecks] // except for replacing TotalHeartGems with TotalHeartGemsInVanilla through MonoModRules public extern void ctor(int index, OuiFileSelect fileSelect, SaveData data); public extern void orig_Show(); public new void Show() { // Temporarily set the current save data to the file slot's save data. // This enables filtering the areas by the save data's current levelset. patch_SaveData prev = patch_SaveData.Instance; patch_SaveData.Instance = SaveData; LevelSetStats stats = SaveData?.LevelSetStats; if (stats != null) { StrawberriesCounter strawbs = Strawberries; strawbs.Amount = stats.TotalStrawberries; strawbs.OutOf = stats.MaxStrawberries; strawbs.ShowOutOf = stats.Name != "Celeste" || strawbs.OutOf <= 0; strawbs.CanWiggle = false; if (stats.Name == "Celeste") { // never mess with vanilla. maxStrawberryCount = 175; maxGoldenStrawberryCount = 25; // vanilla is wrong (there are 26 including dashless), but don't mess with vanilla. maxStrawberryCountIncludingUntracked = 202; maxCassettes = 8; maxCrystalHeartsExcludingCSides = 16; maxCrystalHearts = 24; summitStamp = SaveData.Areas[7].Modes[0].Completed; farewellStamp = SaveData.Areas[10].Modes[0].Completed; } else { // compute the counts for the current level set. maxStrawberryCount = stats.MaxStrawberries; maxGoldenStrawberryCount = stats.MaxGoldenStrawberries; maxStrawberryCountIncludingUntracked = stats.MaxStrawberriesIncludingUntracked; maxCassettes = stats.MaxCassettes; maxCrystalHearts = stats.MaxHeartGems; maxCrystalHeartsExcludingCSides = stats.MaxHeartGemsExcludingCSides; // summit stamp is displayed if we finished all areas that are not interludes. (TotalCompletions filters interludes out.) summitStamp = stats.TotalCompletions >= stats.MaxCompletions; farewellStamp = false; // what is supposed to be Farewell in mod campaigns anyway?? } // save the values from the current level set. They will be patched in instead of SaveData.TotalXX. totalGoldenStrawberries = stats.TotalGoldenStrawberries; // The value saved on the file is global for all level sets. totalHeartGems = stats.TotalHeartGems; // this counts from all level sets. totalCassettes = stats.TotalCassettes; // this relies on SaveData.Instance. // redo what is done on the constructor. This keeps the area name and stats up-to-date with the latest area. FurthestArea = SaveData.UnlockedAreas; Cassettes.Clear(); HeartGems.Clear(); foreach (AreaStats areaStats in SaveData.Areas) { if (areaStats.ID > SaveData.UnlockedAreas) break; if (!AreaData.Areas[areaStats.ID].Interlude && AreaData.Areas[areaStats.ID].CanFullClear) { bool[] hearts = new bool[3]; for (int i = 0; i < hearts.Length; i++) { hearts[i] = areaStats.Modes[i].HeartGem; } Cassettes.Add(areaStats.Cassette); HeartGems.Add(hearts); } } } patch_SaveData.Instance = prev; orig_Show(); } [MonoModReplace] public new Color SelectionColor(bool selected) { if (selected) { if (CoreModule.Settings.AllowTextHighlight && !base.Scene.BetweenInterval(0.1f)) { return TextMenu.HighlightColorB; } return TextMenu.HighlightColorA; } return Color.White; } public extern void orig_CreateButtons(); public new void CreateButtons() { orig_CreateButtons(); if (!Exists) { if (patch_AreaData.Areas.Select(area => area.LevelSet).Distinct().Count() > 1) { if (newGameLevelSetPicker == null) { newGameLevelSetPicker = new OuiFileSelectSlotLevelSetPicker(this); } buttons.Add(newGameLevelSetPicker); } } else if (!Corrupted) { buttons.Insert(buttons.FindIndex(button => button.Label == Dialog.Clean("file_delete")), // Insert immediately before "Delete" new Button { Label = Dialog.Clean("file_rename"), Action = OnExistingFileRenameSelected, Scale = 0.7f } ); } patch_SaveData.LoadModSaveData(FileSlot); Everest.Events.FileSelectSlot.HandleCreateButtons(buttons, this, Exists); } private void OnExistingFileRenameSelected() { renamed = true; Renaming = true; OuiFileNaming ouiFileNaming = fileSelect.Overworld.Goto<OuiFileNaming>(); ouiFileNaming.FileSlot = this; ouiFileNaming.StartingName = Name; Audio.Play("event:/ui/main/savefile_rename_start"); } [MonoModIgnore] [PatchOuiFileSelectSlotOnContinueSelected] private extern void OnContinueSelected(); public extern void orig_OnNewGameSelected(); public void OnNewGameSelected() { orig_OnNewGameSelected(); string newGameLevelSet = newGameLevelSetPicker?.NewGameLevelSet; if (newGameLevelSet != null && newGameLevelSet != "Celeste") { patch_SaveData.Instance.LastArea = patch_AreaData.Areas.FirstOrDefault(area => area.LevelSet == newGameLevelSet)?.ToKey() ?? AreaKey.Default; } } [PatchOuiFileSelectSlotUpdate] public extern void orig_Update(); public override void Update() { orig_Update(); if (newGameLevelSetPicker != null && selected && fileSelect.Selected && fileSelect.Focused && !StartingGame && tween == null && inputDelay <= 0f && !StartingGame && !deleting) { // currently highlighted option is the level set picker, call its Update() method to handle Left and Right presses. newGameLevelSetPicker.Update(buttons[buttonIndex] == newGameLevelSetPicker); if (MInput.Keyboard.Check(Keys.LeftControl) && MInput.Keyboard.Pressed(Keys.S)) { // Ctrl+S: change the default starting level set to the currently selected one. CoreModule.Settings.DefaultStartingLevelSet = newGameLevelSetPicker.NewGameLevelSet; if (CoreModule.Settings.SaveDataFlush ?? false) CoreModule.Instance.ForceSaveDataFlush++; CoreModule.Instance.SaveSettings(); Audio.Play("event:/new_content/ui/rename_entry_accept_locked"); } } } public void WiggleMenu() { wiggler.Start(); } [MonoModReplace] private IEnumerator EnterFirstAreaRoutine() { ((patch_OuiFileSelect) fileSelect).startingNewFile = true; // Set this flag for autosplitters // Replace ID 0 with SaveData.Instance.LastArea.ID Overworld overworld = fileSelect.Overworld; patch_AreaData area = patch_AreaData.Areas[patch_SaveData.Instance.LastArea.ID]; if (area.LevelSet != "Celeste") { // Pretend that we've beaten Prologue. LevelSetStats stats = patch_SaveData.Instance.GetLevelSetStatsFor("Celeste"); stats.UnlockedAreas = 1; stats.AreasIncludingCeleste[0].Modes[0].Completed = true; } yield return fileSelect.Leave(null); overworld.Mountain.Model.EaseState(area.MountainState); yield return overworld.Mountain.EaseCamera(0, area.MountainIdle); yield return 0.3f; overworld.Mountain.EaseCamera(0, area.MountainZoom, 1f); yield return 0.4f; area.Wipe(overworld, false, null); ((patch_RendererList) (object) overworld.RendererList).UpdateLists(); overworld.RendererList.MoveToFront(overworld.Snow); yield return 0.5f; LevelEnter.Go(new Session(patch_SaveData.Instance.LastArea), false); } public extern void orig_Unselect(); public new void Unselect() { orig_Unselect(); // reset the level set picker when we exit out of the file select slot. newGameLevelSetPicker = null; } // Required because Button is private. Also make it public. [MonoModPublic] public class Button { public string Label; public Action Action; public float Scale = 1f; } [PatchFileSelectSlotRenderMissingVanillaDataDialog] [PatchFileSelectSlotRender] // manually manipulate the method via MonoModRules public extern void orig_Render(); public override void Render() { orig_Render(); if (selectedEase > 0f) { Vector2 position = Position + new Vector2(0f, -150f + 350f * selectedEase); float lineHeight = ActiveFont.LineHeight; // go through all buttons, looking for the level set picker. for (int i = 0; i < buttons.Count; i++) { Button button = buttons[i]; if (button == newGameLevelSetPicker) { // we found it: call its Render method. newGameLevelSetPicker.Render(position, buttonIndex == i && !deleting, wiggler.Value * 8f); } position.Y += lineHeight * button.Scale + 15f; } } } // very similar to MoveTo, except the easing is different if the slot was already moving. // used for scrolling, since using MoveTo can look weird if holding up or down in file select. internal void ScrollTo(float x, float y) { Vector2 from = Position; Vector2 to = new Vector2(x, y); bool tweenWasPresent = false; if (tween != null && tween.Entity == this) { tweenWasPresent = true; tween.RemoveSelf(); // snap the "unselect" animation. newgameFade = selectedEase = 0f; } Add(tween = Tween.Create(Tween.TweenMode.Oneshot, tweenWasPresent ? Ease.CubeOut : Ease.CubeInOut, 0.25f)); tween.OnUpdate = t => Position = Vector2.Lerp(from, to, t.Eased); tween.OnComplete = t => tween = null; tween.Start(); } } } namespace MonoMod { /// <summary> /// Patches the method to make its manually-implemented screen flashing respect advanced photosensitivity settings. /// </summary> [MonoModCustomMethodAttribute(nameof(MonoModRules.PatchOuiFileSelectSlotUpdate))] class PatchOuiFileSelectSlotUpdateAttribute : Attribute { } /// <summary> /// IL-patch the Render method for file select slots instead of reimplementing it, /// to un-hardcode stamps. /// </summary> [MonoModCustomMethodAttribute(nameof(MonoModRules.PatchFileSelectSlotRender))] class PatchFileSelectSlotRenderAttribute : Attribute { } /// <summary> /// Patches the method to update the Name and the TheoSisterName, if the file has been renamed in-game, in the file's SaveData. /// </summary> [MonoModCustomMethodAttribute(nameof(MonoModRules.PatchOuiFileSelectSlotOnContinueSelected))] class PatchOuiFileSelectSlotOnContinueSelectedAttribute : Attribute { } /// <summary> /// Patches the method to differentiate between Corrupted and MissingVanillaData. /// </summary> [MonoModCustomMethodAttribute(nameof(MonoModRules.PatchFileSelectSlotRenderMissingVanillaDataDialog))] class PatchFileSelectSlotRenderMissingVanillaDataDialog : Attribute { } static partial class MonoModRules { public static void PatchOuiFileSelectSlotUpdate(ILContext context, CustomAttribute attrib) { TypeDefinition t_CoreModule = MonoModRule.Modder.Module.GetType("Celeste.Mod.Core.CoreModule"); TypeDefinition t_CoreModuleSettings = MonoModRule.Modder.Module.GetType("Celeste.Mod.Core.CoreModuleSettings"); MethodDefinition m_CoreModule_get_Settings = t_CoreModule.FindMethod("get_Settings"); MethodDefinition m_get_AllowScreenFlash = t_CoreModuleSettings.FindMethod("get_AllowScreenFlash"); ILCursor cursor = new ILCursor(context); cursor.GotoNext(MoveType.Before, instr => instr.MatchLdsfld("Celeste.Settings", "Instance")); cursor.RemoveRange(2); cursor.EmitCall(m_CoreModule_get_Settings); cursor.EmitCallvirt(m_get_AllowScreenFlash); cursor.Next.OpCode = OpCodes.Brfalse; } public static void PatchFileSelectSlotRenderMissingVanillaDataDialog(ILContext context, CustomAttribute attrib) { TypeDefinition declaringType = context.Method.DeclaringType; FieldDefinition f_MissingVanillaData = declaringType.FindField("MissingVanillaData"); ILCursor cursor = new ILCursor(context); // C# change: // [...] // else if (Corrupted) // { // - ActiveFont.Draw(Dialog.Clean("file_corrupted"), slide2, new Vector2(0.5f, 0.5f), Vector2.One, Color.Black * 0.8f); // + ActiveFont.Draw(Dialog.Clean((!MissingVanillaData) ? "file_corrupted" : "MISSING_VANILLA_DATA"), vector3, new Vector2(0.5f, 0.5f), Vector2.One, Color.Black * 0.8f); // } // [...] // IL change: // [...] // ldfld System.Boolean Celeste.OuiFileSelectSlot::Corrupted // brfalse.s (...) // + ldarg.0 // + ldfld bool Celeste.OuiFileSelectSlot::MissingVanillaData // + brfalse.s ldstr // + ldstr "MISSING_VANILLA_DATA" // + br.s ldnull // ldstr : ldstr "file_corrupted" // ldnull : ldnull // call string Celeste.Dialog::Clean(string, class Celeste.Language) // [...] cursor.GotoNext(MoveType.Before, instr => instr.MatchLdstr("file_corrupted")); ILLabel ldstr = cursor.MarkLabel(); cursor.GotoNext(); ILLabel ldnull = cursor.MarkLabel(); cursor.GotoLabel(ldstr, MoveType.Before); cursor.EmitLdarg0(); cursor.EmitLdfld(f_MissingVanillaData); cursor.EmitBrfalse(ldstr); cursor.EmitLdstr("MISSING_VANILLA_DATA"); cursor.EmitBr(ldnull); } public static void PatchFileSelectSlotRender(ILContext context, CustomAttribute attrib) { TypeDefinition declaringType = context.Method.DeclaringType; FieldDefinition f_maxStrawberryCount = declaringType.FindField("maxStrawberryCount"); FieldDefinition f_maxGoldenStrawberryCount = declaringType.FindField("maxGoldenStrawberryCount"); FieldDefinition f_maxCassettes = declaringType.FindField("maxCassettes"); FieldDefinition f_maxCrystalHeartsExcludingCSides = declaringType.FindField("maxCrystalHeartsExcludingCSides"); FieldDefinition f_maxCrystalHearts = declaringType.FindField("maxCrystalHearts"); FieldDefinition f_summitStamp = declaringType.FindField("summitStamp"); FieldDefinition f_farewellStamp = declaringType.FindField("farewellStamp"); FieldDefinition f_totalGoldenStrawberries = declaringType.FindField("totalGoldenStrawberries"); FieldDefinition f_totalHeartGems = declaringType.FindField("totalHeartGems"); FieldDefinition f_totalCassettes = declaringType.FindField("totalCassettes"); ILCursor cursor = new ILCursor(context); // SaveData.TotalStrawberries replaced by SaveData.TotalStrawberries_Safe with MonoModLinkFrom // Replace hardcoded ARB value with a field reference cursor.GotoNext(MoveType.After, instr => instr.MatchLdcI4(175)); cursor.Prev.OpCode = OpCodes.Ldarg_0; cursor.Emit(OpCodes.Ldfld, f_maxStrawberryCount); // SaveData.Areas replaced by SaveData.Areas_Safe with MonoModLinkFrom // We want to replace `this.SaveData.Areas_Safe[7].Modes[0].Completed` cursor.GotoNext(instr => instr.MatchLdfld(declaringType.FullName, "SaveData"), instr => instr.MatchCallvirt("Celeste.SaveData", "get_Areas_Safe"), instr => instr.OpCode == OpCodes.Ldc_I4_7); // Remove everything but the preceeding `this` cursor.RemoveRange(8); // Replace with `this.summitStamp` cursor.Emit(OpCodes.Ldfld, f_summitStamp); cursor.GotoNext(instr => instr.MatchLdfld(declaringType.FullName, "SaveData"), instr => instr.MatchCallvirt("Celeste.SaveData", "get_TotalCassettes")); cursor.RemoveRange(3); cursor.Emit(OpCodes.Ldfld, f_totalCassettes); // Replace hardcoded Cassettes value with a field reference cursor.Emit(OpCodes.Ldarg_0); cursor.Emit(OpCodes.Ldfld, f_maxCassettes); cursor.GotoNext(instr => instr.MatchLdfld(declaringType.FullName, "SaveData"), instr => instr.MatchCallvirt("Celeste.SaveData", "get_TotalHeartGems")); cursor.RemoveRange(3); cursor.Emit(OpCodes.Ldfld, f_totalHeartGems); // Replace hardcoded HeartGems value with a field reference cursor.Emit(OpCodes.Ldarg_0); cursor.Emit(OpCodes.Ldfld, f_maxCrystalHeartsExcludingCSides); cursor.GotoNext(instr => instr.MatchLdfld(declaringType.FullName, "SaveData"), instr => instr.MatchLdfld("Celeste.SaveData", "TotalGoldenStrawberries")); cursor.RemoveRange(3); cursor.Emit(OpCodes.Ldfld, f_totalGoldenStrawberries); // Replace hardcoded GoldenStrawberries value with a field reference cursor.Emit(OpCodes.Ldarg_0); cursor.Emit(OpCodes.Ldfld, f_maxGoldenStrawberryCount); cursor.GotoNext(instr => instr.MatchLdfld(declaringType.FullName, "SaveData"), instr => instr.MatchCallvirt("Celeste.SaveData", "get_TotalHeartGems")); cursor.RemoveRange(3); cursor.Emit(OpCodes.Ldfld, f_totalHeartGems); // Replace hardcoded HeartGems value with a field reference cursor.Emit(OpCodes.Ldarg_0); cursor.Emit(OpCodes.Ldfld, f_maxCrystalHearts); // SaveData.Areas replaced by SaveData.Areas_Safe with MonoModLinkFrom // We want to replace `this.SaveData.Areas_Safe[10].Modes[0].Completed` cursor.GotoNext(instr => instr.MatchLdfld(declaringType.FullName, "SaveData"), instr => instr.MatchCallvirt("Celeste.SaveData", "get_Areas_Safe"), instr => instr.MatchLdcI4(10)); // Remove everything but the preceeding `this` cursor.RemoveRange(8); // Replace with `this.farewellStamp` cursor.Emit(OpCodes.Ldfld, f_farewellStamp); } public static void PatchOuiFileSelectSlotOnContinueSelected(ILContext context, CustomAttribute attrib) { FieldDefinition f_OuiFileSelectSlot_Name = context.Method.DeclaringType.FindField("Name"); FieldDefinition f_OuiFileSelectSlot_renamed = context.Method.DeclaringType.FindField("renamed"); FieldDefinition f_SaveData_Name = context.Module.GetType("Celeste.SaveData").Resolve().FindField("Name"); FieldDefinition f_SaveData_TheoSisterName = context.Module.GetType("Celeste.SaveData").Resolve().FindField("TheoSisterName"); MethodDefinition m_Dialog_Clean = context.Module.GetType("Celeste.Dialog").Resolve().FindMethod("System.String Clean(System.String,Celeste.Language)"); TypeDefinition t_String = MonoModRule.Modder.FindType("System.String").Resolve(); MethodReference m_String_IndexOf = MonoModRule.Modder.Module.ImportReference(t_String.FindMethod("System.Int32 IndexOf(System.String,System.StringComparison)")); // Insert after SaveData.Start(SaveData, FileSlot) ILCursor cursor = new ILCursor(context); cursor.GotoNext(MoveType.After, instr => instr.MatchCall("Celeste.SaveData", "System.Void Start(Celeste.SaveData,System.Int32)")); // if (renamed) // { // SaveData.Instance.Name = Name; // SaveData.Instance.TheoSisterName = Dialog.Clean((Name.IndexOf(Dialog.Clean("THEO_SISTER_NAME"), StringComparison.InvariantCultureIgnoreCase) >= 0) ? "THEO_SISTER_ALT_NAME" : "THEO_SISTER_NAME"); // } ILLabel renamedTarget = cursor.DefineLabel(); ILLabel altNameTarget = cursor.DefineLabel(); ILLabel defaultNameTarget = cursor.DefineLabel(); // if (renamed) cursor.Emit(OpCodes.Ldarg_0); cursor.Emit(OpCodes.Ldfld, f_OuiFileSelectSlot_renamed); cursor.Emit(OpCodes.Brfalse_S, renamedTarget); // Assign Name cursor.Emit(cursor.Next.OpCode, cursor.Next.Operand); // ldsfld class Celeste.SaveData Celeste.SaveData::Instance cursor.Emit(OpCodes.Ldarg_0); cursor.Emit(OpCodes.Ldfld, f_OuiFileSelectSlot_Name); cursor.Emit(OpCodes.Stfld, f_SaveData_Name); // Assign TheoSisterName cursor.Emit(cursor.Next.OpCode, cursor.Next.Operand); // ldsfld class Celeste.SaveData Celeste.SaveData::Instance cursor.Emit(OpCodes.Ldarg_0); cursor.Emit(OpCodes.Ldfld, f_OuiFileSelectSlot_Name); cursor.Emit(OpCodes.Ldstr, "THEO_SISTER_NAME"); cursor.Emit(OpCodes.Ldnull); cursor.Emit(OpCodes.Call, m_Dialog_Clean); cursor.Emit(OpCodes.Ldc_I4_3); cursor.Emit(OpCodes.Callvirt, m_String_IndexOf); cursor.Emit(OpCodes.Ldc_I4_0); cursor.Emit(OpCodes.Bge_S, altNameTarget); cursor.Emit(OpCodes.Ldstr, "THEO_SISTER_NAME"); cursor.Emit(OpCodes.Br_S, defaultNameTarget); cursor.MarkLabel(altNameTarget); cursor.Emit(OpCodes.Ldstr, "THEO_SISTER_ALT_NAME"); cursor.MarkLabel(defaultNameTarget); cursor.Emit(OpCodes.Ldnull); cursor.Emit(OpCodes.Call, m_Dialog_Clean); cursor.Emit(OpCodes.Stfld, f_SaveData_TheoSisterName); // Target for if renamed is false cursor.MarkLabel(renamedTarget); } } }
0
0.906368
1
0.906368
game-dev
MEDIA
0.802891
game-dev
0.980939
1
0.980939
locklin/lush-code
2,118
lush1/tags/debian_version_1_0+cvs_2003_05_20/demos/lushlife.lsh
;; A basic implementation of Conway's Game of Life using SDL ;; Keir Mierle, Jan 2003. ;; http://keir.mierle.com (de makewrappable (m) ((-idx2- (-ubyte-)) m) (let* ((real-height (idx-dim m 0)) (real-width (idx-dim m 1))) ((-int-) real-height real-width) ;; Basically I'm faking wraping the rows / cols by having a matrix with ;; 2 extra rows, and 2 extra columns, one on each side. This allows me to ;; simply offset the idx, add, then re-shift the idx. (idx-copy (select m 0 1) (select m 0 (- real-height 1))) (idx-copy (select m 0 (- real-height 2)) (select m 0 0)) (idx-copy (select m 1 1) (select m 1 (- real-width 1))) (idx-copy (select m 1 (- real-width 2)) (select m 1 0)))) (de lifesim (m r) ((-idx2- (-ubyte-)) m r) (let* ((real-height (idx-dim m 0)) (real-width (idx-dim m 1)) (h (- real-height 2)) (w (- real-width 2))) ((-int-) real-height real-width h w) ;; Clear the accumulation matrix and copy around the columns to make it 'wrappable' (idx-clear r) (makewrappable m) ;; Shift the matrix around and add them all up to count the number of neighbors. (idx-add (narrow (narrow m 0 h 0) 1 w 0) (narrow (narrow m 0 h 0) 1 w 1) r) (idx-add (narrow (narrow m 0 h 0) 1 w 2) r r) (idx-add (narrow (narrow m 0 h 1) 1 w 2) r r) (idx-add (narrow (narrow m 0 h 2) 1 w 2) r r) (idx-add (narrow (narrow m 0 h 2) 1 w 1) r r) (idx-add (narrow (narrow m 0 h 2) 1 w 0) r r) (idx-add (narrow (narrow m 0 h 1) 1 w 0) r r) ;; life or death (idx-bloop ((rrow r) (mrow (narrow (narrow m 0 (- real-height 2) 1) 1 (- real-width 2) 1))) (idx-bloop ((neighbors rrow) (cellstatus mrow)) (if (or (and (= (cellstatus) 0) (= (neighbors) 3)) (and (= (cellstatus) 1) (or (= (neighbors) 2) (= (neighbors) 3)))) (cellstatus 1) (cellstatus 0)))))) ;; random initialization of the board (de randomize (m p) ((-idx2- (-ubyte-)) m) ((-double-) p) (idx-bloop ((row m)) (idx-bloop ((col row)) (if (<= (rand) p) (col 1) (col 0))))) (dhc-make () makewrappable lifesim randomize)
0
0.825409
1
0.825409
game-dev
MEDIA
0.560647
game-dev,graphics-rendering
0.981319
1
0.981319
EpochModTeam/DayZ-Epoch
2,520
SQF/dayz_server/compile/server_updateObject.sqf
// [_object,_type] spawn server_updateObject; #include "\z\addons\dayz_server\compile\server_toggle_debug.hpp" //if (isNil "sm_done") exitWith {diag_log "sm_done is nil";}; local _object = _this select 0; if ((isNil "_object") || isNull _object) exitWith {diag_log "server_updateObject.sqf _object null or nil, could not update object"}; local _type = _this select 1; local _forced = if (count _this > 2) then {_this select 2} else {false}; local _totalDmg = if (count _this > 3) then {_this select 3} else {false}; local _isNotOk = false; local _objectID = "0"; local _objectUID = "0"; _objectID = _object getVariable ["ObjectID","0"]; _objectUID = _object getVariable ["ObjectUID","0"]; local _class = typeOf _object; if (typeName _objectID != "STRING" || {typeName _objectUID != "STRING"}) then { #ifdef OBJECT_DEBUG diag_log (format["Non-string Object: ID %1 UID %2", _objectID, _objectUID]); #endif //force fail _objectID = nil; _objectUID = nil; }; if (!(_class in DZE_safeVehicle) && {!locked _object}) then { //diag_log format["Object: %1, ObjectID: %2, ObjectUID: %3",_object,_objectID,_objectUID]; if (!(_objectID in dayz_serverIDMonitor) && {isNil "_objectUID"}) then { //force fail _objectID = nil; _objectUID = nil; }; if (isNil "_objectID" && {isNil "_objectUID"}) then { #ifdef OBJECT_DEBUG diag_log format["Object %1 with invalid ID at pos %2",_class,getPosATL _object]; #endif _isNotOk = true; }; }; if (_isNotOk) exitWith { //deleteVehicle _object; }; call { if (_type == "all") exitwith { [_object,_objectID,_class] call server_obj_pos; [_object,_objectID,_objectUID,_class] call server_obj_inv; [_object,_objectID,_objectUID,_forced,_totalDmg] call server_obj_dam; }; if (_type == "position") exitwith { [_object,_objectID,_class] call server_obj_pos; }; if (_type == "gear") exitwith { [_object,_objectID,_objectUID,_class] call server_obj_inv; }; if (_type == "damage" || _type == "repair") exitwith { [_object,_objectID,_objectUID,_forced,_totalDmg] call server_obj_dam; }; if (_type == "killed") exitwith { if (count _this != 6) exitWith { diag_log "Server_UpdateObject error: wrong parameter format"; }; local _playerUID = _this select 4; local _clientKey = _this select 5; [_object,_objectID,_objectUID,_playerUID,_clientKey,_class] call server_obj_killed; }; if (_type == "coins") exitwith { _object setVariable ["lastInventory",["forceUpdate"]]; [_object,_objectID,_objectUID,_class] call server_obj_inv; }; ""; };
0
0.853164
1
0.853164
game-dev
MEDIA
0.810391
game-dev
0.894463
1
0.894463
Gaby-Station/Gaby-Station
3,025
Content.Shared/StationRecords/StationRecordKeyStorageSystem.cs
// SPDX-FileCopyrightText: 2022 Flipp Syder <76629141+vulppine@users.noreply.github.com> // SPDX-FileCopyrightText: 2022 metalgearsloth <comedian_vs_clown@hotmail.com> // SPDX-FileCopyrightText: 2023 Nemanja <98561806+EmoGarbage404@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Tayrtahn <tayrtahn@gmail.com> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // // SPDX-License-Identifier: MIT using Robust.Shared.GameStates; namespace Content.Shared.StationRecords; public sealed class StationRecordKeyStorageSystem : EntitySystem { [Dependency] private readonly SharedStationRecordsSystem _records = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<StationRecordKeyStorageComponent, ComponentGetState>(OnGetState); SubscribeLocalEvent<StationRecordKeyStorageComponent, ComponentHandleState>(OnHandleState); } private void OnGetState(EntityUid uid, StationRecordKeyStorageComponent component, ref ComponentGetState args) { args.State = new StationRecordKeyStorageComponentState(_records.Convert(component.Key)); } private void OnHandleState(EntityUid uid, StationRecordKeyStorageComponent component, ref ComponentHandleState args) { if (args.Current is not StationRecordKeyStorageComponentState state) return; component.Key = _records.Convert(state.Key); } /// <summary> /// Assigns a station record key to an entity. /// </summary> /// <param name="uid"></param> /// <param name="key"></param> /// <param name="keyStorage"></param> public void AssignKey(EntityUid uid, StationRecordKey key, StationRecordKeyStorageComponent? keyStorage = null) { if (!Resolve(uid, ref keyStorage)) { return; } keyStorage.Key = key; Dirty(uid, keyStorage); } /// <summary> /// Removes a station record key from an entity. /// </summary> /// <param name="uid"></param> /// <param name="keyStorage"></param> /// <returns></returns> public StationRecordKey? RemoveKey(EntityUid uid, StationRecordKeyStorageComponent? keyStorage = null) { if (!Resolve(uid, ref keyStorage) || keyStorage.Key == null) { return null; } var key = keyStorage.Key; keyStorage.Key = null; Dirty(uid, keyStorage); return key; } /// <summary> /// Checks if an entity currently contains a station record key. /// </summary> /// <param name="uid"></param> /// <param name="keyStorage"></param> /// <returns></returns> public bool CheckKey(EntityUid uid, StationRecordKeyStorageComponent? keyStorage = null) { if (!Resolve(uid, ref keyStorage)) { return false; } return keyStorage.Key != null; } }
0
0.83944
1
0.83944
game-dev
MEDIA
0.305753
game-dev
0.844338
1
0.844338
baidu/Elasticsearch
6,692
src/main/elasticsearch/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.indices.analysis; import org.apache.lucene.analysis.Analyzer; import org.elasticsearch.Version; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.index.analysis.*; import java.io.Closeable; import java.util.Locale; import java.util.Map; import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; /** * A node level registry of analyzers, to be reused by different indices which use default analyzers. */ public class IndicesAnalysisService extends AbstractComponent implements Closeable { private final Map<String, PreBuiltAnalyzerProviderFactory> analyzerProviderFactories = ConcurrentCollections.newConcurrentMap(); private final Map<String, PreBuiltTokenizerFactoryFactory> tokenizerFactories = ConcurrentCollections.newConcurrentMap(); private final Map<String, PreBuiltTokenFilterFactoryFactory> tokenFilterFactories = ConcurrentCollections.newConcurrentMap(); private final Map<String, PreBuiltCharFilterFactoryFactory> charFilterFactories = ConcurrentCollections.newConcurrentMap(); public IndicesAnalysisService() { super(EMPTY_SETTINGS); } @Inject public IndicesAnalysisService(Settings settings) { super(settings); // Analyzers for (PreBuiltAnalyzers preBuiltAnalyzerEnum : PreBuiltAnalyzers.values()) { String name = preBuiltAnalyzerEnum.name().toLowerCase(Locale.ROOT); analyzerProviderFactories.put(name, new PreBuiltAnalyzerProviderFactory(name, AnalyzerScope.INDICES, preBuiltAnalyzerEnum.getAnalyzer(Version.CURRENT))); } // Tokenizers for (PreBuiltTokenizers preBuiltTokenizer : PreBuiltTokenizers.values()) { String name = preBuiltTokenizer.name().toLowerCase(Locale.ROOT); tokenizerFactories.put(name, new PreBuiltTokenizerFactoryFactory(preBuiltTokenizer.getTokenizerFactory(Version.CURRENT))); } // Tokenizer aliases tokenizerFactories.put("nGram", new PreBuiltTokenizerFactoryFactory(PreBuiltTokenizers.NGRAM.getTokenizerFactory(Version.CURRENT))); tokenizerFactories.put("edgeNGram", new PreBuiltTokenizerFactoryFactory(PreBuiltTokenizers.EDGE_NGRAM.getTokenizerFactory(Version.CURRENT))); tokenizerFactories.put("PathHierarchy", new PreBuiltTokenizerFactoryFactory(PreBuiltTokenizers.PATH_HIERARCHY.getTokenizerFactory(Version.CURRENT))); // Token filters for (PreBuiltTokenFilters preBuiltTokenFilter : PreBuiltTokenFilters.values()) { String name = preBuiltTokenFilter.name().toLowerCase(Locale.ROOT); tokenFilterFactories.put(name, new PreBuiltTokenFilterFactoryFactory(preBuiltTokenFilter.getTokenFilterFactory(Version.CURRENT))); } // Token filter aliases tokenFilterFactories.put("nGram", new PreBuiltTokenFilterFactoryFactory(PreBuiltTokenFilters.NGRAM.getTokenFilterFactory(Version.CURRENT))); tokenFilterFactories.put("edgeNGram", new PreBuiltTokenFilterFactoryFactory(PreBuiltTokenFilters.EDGE_NGRAM.getTokenFilterFactory(Version.CURRENT))); // Char Filters for (PreBuiltCharFilters preBuiltCharFilter : PreBuiltCharFilters.values()) { String name = preBuiltCharFilter.name().toLowerCase(Locale.ROOT); charFilterFactories.put(name, new PreBuiltCharFilterFactoryFactory(preBuiltCharFilter.getCharFilterFactory(Version.CURRENT))); } // Char filter aliases charFilterFactories.put("htmlStrip", new PreBuiltCharFilterFactoryFactory(PreBuiltCharFilters.HTML_STRIP.getCharFilterFactory(Version.CURRENT))); } public boolean hasCharFilter(String name) { return charFilterFactoryFactory(name) != null; } public Map<String, PreBuiltCharFilterFactoryFactory> charFilterFactories() { return charFilterFactories; } public CharFilterFactoryFactory charFilterFactoryFactory(String name) { return charFilterFactories.get(name); } public boolean hasTokenFilter(String name) { return tokenFilterFactoryFactory(name) != null; } public Map<String, PreBuiltTokenFilterFactoryFactory> tokenFilterFactories() { return tokenFilterFactories; } public TokenFilterFactoryFactory tokenFilterFactoryFactory(String name) { return tokenFilterFactories.get(name); } public boolean hasTokenizer(String name) { return tokenizerFactoryFactory(name) != null; } public Map<String, PreBuiltTokenizerFactoryFactory> tokenizerFactories() { return tokenizerFactories; } public TokenizerFactoryFactory tokenizerFactoryFactory(String name) { return tokenizerFactories.get(name); } public Map<String, PreBuiltAnalyzerProviderFactory> analyzerProviderFactories() { return analyzerProviderFactories; } public PreBuiltAnalyzerProviderFactory analyzerProviderFactory(String name) { return analyzerProviderFactories.get(name); } public boolean hasAnalyzer(String name) { return analyzerProviderFactories.containsKey(name); } public Analyzer analyzer(String name) { PreBuiltAnalyzerProviderFactory analyzerProviderFactory = analyzerProviderFactory(name); if (analyzerProviderFactory == null) { return null; } return analyzerProviderFactory.analyzer(); } @Override public void close() { for (PreBuiltAnalyzerProviderFactory analyzerProviderFactory : analyzerProviderFactories.values()) { try { analyzerProviderFactory.analyzer().close(); } catch (Exception e) { // ignore } } } }
0
0.826726
1
0.826726
game-dev
MEDIA
0.332474
game-dev
0.838364
1
0.838364
senseiwells/EssentialClient
2,534
src/main/java/me/senseiwells/essential_client/mixins/ignore_invalid_chat_messages/ClientPacketListenerMixin.java
package me.senseiwells.essential_client.mixins.ignore_invalid_chat_messages; import me.senseiwells.essential_client.EssentialClientConfig; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.multiplayer.CommonListenerCookie; import net.minecraft.network.Connection; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ClientPacketListener.class) public abstract class ClientPacketListenerMixin extends ClientCommonPacketListenerImpl { protected ClientPacketListenerMixin(Minecraft minecraft, Connection connection, CommonListenerCookie commonListenerCookie) { super(minecraft, connection, commonListenerCookie); } @Inject( method = "handlePlayerChat", at = @At( value = "INVOKE", target = "Lorg/slf4j/Logger;error(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", remap = false ), cancellable = true ) private void onHandleInvalidOrderedChat(ClientboundPlayerChatPacket packet, CallbackInfo ci) { if (EssentialClientConfig.getInstance().getIgnoreInvalidChatMessages()) { this.handleInvalidChat(packet); ci.cancel(); } } @Inject( method = "handlePlayerChat", at = @At( value = "INVOKE", target = "Lorg/slf4j/Logger;error(Ljava/lang/String;Ljava/lang/Object;)V", remap = false, ordinal = 0 ), cancellable = true ) private void onHandleInvalidChatSignature(ClientboundPlayerChatPacket packet, CallbackInfo ci) { if (EssentialClientConfig.getInstance().getIgnoreInvalidChatMessages()) { this.handleInvalidChat(packet); ci.cancel(); } } @Unique private void handleInvalidChat(ClientboundPlayerChatPacket packet) { Component message = packet.unsignedContent() == null ? Component.literal(packet.body().content()) : packet.unsignedContent(); this.minecraft.getChatListener().handleDisguisedChatMessage(message, packet.chatType()); } }
0
0.760855
1
0.760855
game-dev
MEDIA
0.834019
game-dev,networking
0.828685
1
0.828685
ServUO/ServUO
16,631
Scripts/Mobiles/Bosses/PrimevalLich.cs
using System; using System.Collections; using Server.Engines.CannedEvil; using Server.Items; using System.Collections.Generic; using Server.Network; using System.Linq; namespace Server.Mobiles { [CorpseName("a Primeval Lich corpse")] public class PrimevalLich : BaseChampion { private DateTime m_NextDiscordTime; private DateTime m_NextAbilityTime; private Timer m_Timer; [Constructable] public PrimevalLich() : base(AIType.AI_NecroMage) { Name = "Primeval Lich"; Body = 830; SetStr(500); SetDex(100); SetInt(1000); SetHits(30000); SetMana(5000); SetDamage(17, 21); SetDamageType(ResistanceType.Physical, 20); SetDamageType(ResistanceType.Fire, 20); SetDamageType(ResistanceType.Cold, 20); SetDamageType(ResistanceType.Energy, 20); SetDamageType(ResistanceType.Poison, 20); SetResistance(ResistanceType.Physical, 30); SetResistance(ResistanceType.Fire, 30); SetResistance(ResistanceType.Cold, 30); SetResistance(ResistanceType.Poison, 30); SetResistance(ResistanceType.Energy, 20); SetSkill(SkillName.EvalInt, 90, 120.0); SetSkill(SkillName.Magery, 90, 120.0); SetSkill(SkillName.Meditation, 100, 120.0); SetSkill(SkillName.Necromancy, 120.0); SetSkill(SkillName.SpiritSpeak, 120.0); SetSkill(SkillName.MagicResist, 120, 140.0); SetSkill(SkillName.Tactics, 90, 120); SetSkill(SkillName.Wrestling, 100, 120); Fame = 28000; Karma = -28000; VirtualArmor = 80; m_Timer = new TeleportTimer(this); m_Timer.Start(); } public PrimevalLich(Serial serial) : base(serial) { } public override int GetAttackSound() { return 0x61E; } public override int GetDeathSound() { return 0x61F; } public override int GetHurtSound() { return 0x620; } public override int GetIdleSound() { return 0x621; } public override bool CanRummageCorpses { get { return true; } } public override bool BleedImmune { get { return true; } } public override Poison PoisonImmune { get { return Poison.Lethal; } } public override bool ShowFameTitle { get { return false; } } public override bool ClickTitle { get { return false; } } public override ChampionSkullType SkullType { get { return ChampionSkullType.None; } } public override Type[] UniqueList { get { return new Type[] { typeof(BansheesCall), typeof(CastOffZombieSkin), typeof(ChannelersDefender), typeof(LightsRampart) }; } } public override Type[] SharedList { get { return new Type[] { typeof(TokenOfHolyFavor), typeof(TheMostKnowledgePerson), typeof(LieutenantOfTheBritannianRoyalGuard), typeof(ProtectoroftheBattleMage) }; } } public override Type[] DecorativeList { get { return new Type[] { typeof(MummifiedCorpse) }; } } public override MonsterStatuetteType[] StatueTypes { get { return new MonsterStatuetteType[] { }; } } public override void GenerateLoot() { AddLoot(LootPack.UltraRich, 3); AddLoot(LootPack.Meager); } public override void OnDeath(Container c) { base.OnDeath(c); c.DropItem(new PrimalLichDust()); c.DropItem(new RisingColossusScroll()); } public void ChangeCombatant() { ForceReacquire(); BeginFlee(TimeSpan.FromSeconds(2.5)); } public override void OnThink() { if (m_NextDiscordTime <= DateTime.UtcNow) { Mobile target = Combatant as Mobile; if (target != null && target.InRange(this, 8) && CanBeHarmful(target)) Discord(target); } } public override void OnGotMeleeAttack(Mobile attacker) { base.OnGotMeleeAttack(attacker); if (0.05 >= Utility.RandomDouble()) SpawnShadowDwellers(attacker); } public override void AlterDamageScalarFrom(Mobile caster, ref double scalar) { if (0.05 >= Utility.RandomDouble()) SpawnShadowDwellers(caster); } public override void OnGaveMeleeAttack(Mobile defender) { base.OnGaveMeleeAttack(defender); if (DateTime.UtcNow > m_NextAbilityTime && 0.2 > Utility.RandomDouble()) { switch (Utility.Random(2)) { case 0: BlastRadius(); break; case 1: Lightning(); break; } m_NextAbilityTime = DateTime.UtcNow + TimeSpan.FromSeconds(Utility.RandomMinMax(25, 35)); } } #region Blast Radius private static readonly int BlastRange = 16; private static readonly double[] BlastChance = new double[] { 0.0, 0.0, 0.05, 0.95, 0.95, 0.95, 0.05, 0.95, 0.95, 0.95, 0.05, 0.95, 0.95, 0.95, 0.05, 0.95, 0.95 }; private void BlastRadius() { // TODO: Based on OSI taken videos, not accurate, but an aproximation Point3D loc = Location; for (int x = -BlastRange; x <= BlastRange; x++) { for (int y = -BlastRange; y <= BlastRange; y++) { Point3D p = new Point3D(loc.X + x, loc.Y + y, loc.Z); int dist = (int)Math.Round(Utility.GetDistanceToSqrt(loc, p)); if (dist <= BlastRange && BlastChance[dist] > Utility.RandomDouble()) { Timer.DelayCall(TimeSpan.FromSeconds(0.1 * dist), new TimerCallback( delegate { int hue = Utility.RandomList(90, 95); Effects.SendPacket(loc, Map, new HuedEffect(EffectType.FixedXYZ, Serial.Zero, Serial.Zero, 0x3709, p, p, 20, 30, true, false, hue, 4)); } )); } } } PlaySound(0x64C); IPooledEnumerable eable = GetMobilesInRange(BlastRange); foreach (Mobile m in eable) { if (this != m && GetDistanceToSqrt(m) <= BlastRange && CanBeHarmful(m)) { if (m is ShadowDweller) continue; DoHarmful(m); double damage = m.Hits * 0.6; if (damage < 100.0) damage = 100.0; else if (damage > 200.0) damage = 200.0; DoHarmful(m); AOS.Damage(m, this, (int)damage, 0, 0, 0, 0, 100); } } eable.Free(); } #endregion #region Lightning private void Lightning() { int count = 0; IPooledEnumerable eable = GetMobilesInRange(BlastRange); foreach (Mobile m in eable) { if (m is ShadowDweller) continue; if (m.IsPlayer() && GetDistanceToSqrt(m) <= BlastRange && CanBeHarmful(m)) { DoHarmful(m); Effects.SendBoltEffect(m, false, 0); Effects.PlaySound(m, m.Map, 0x51D); double damage = m.Hits * 0.6; if (damage < 100.0) damage = 100.0; else if (damage > 200.0) damage = 200.0; AOS.Damage(m, this, (int)damage, 0, 0, 0, 0, 100); count++; if (count >= 6) break; } } eable.Free(); } #endregion #region Teleport private class TeleportTimer : Timer { private Mobile m_Owner; private static int[] m_Offsets = new int[] { -1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1 }; public TeleportTimer(Mobile owner) : base(TimeSpan.FromSeconds(5.0), TimeSpan.FromSeconds(5.0)) { m_Owner = owner; } protected override void OnTick() { if (m_Owner.Deleted) { Stop(); return; } Map map = m_Owner.Map; if (map == null) return; if (0.25 < Utility.RandomDouble()) return; Mobile toTeleport = null; foreach (Mobile m in m_Owner.GetMobilesInRange(BlastRange)) { if (m != m_Owner && m.IsPlayer() && m_Owner.CanBeHarmful(m) && m_Owner.CanSee(m)) { if (m is ShadowDweller) continue; toTeleport = m; break; } } if (toTeleport != null) { int offset = Utility.Random(8) * 2; Point3D to = m_Owner.Location; for (int i = 0; i < m_Offsets.Length; i += 2) { int x = m_Owner.X + m_Offsets[(offset + i) % m_Offsets.Length]; int y = m_Owner.Y + m_Offsets[(offset + i + 1) % m_Offsets.Length]; if (map.CanSpawnMobile(x, y, m_Owner.Z)) { to = new Point3D(x, y, m_Owner.Z); break; } else { int z = map.GetAverageZ(x, y); if (map.CanSpawnMobile(x, y, z)) { to = new Point3D(x, y, z); break; } } } Mobile m = toTeleport; Point3D from = m.Location; m.Location = to; Server.Spells.SpellHelper.Turn(m_Owner, toTeleport); Server.Spells.SpellHelper.Turn(toTeleport, m_Owner); m.ProcessDelta(); Effects.SendLocationParticles(EffectItem.Create(from, m.Map, EffectItem.DefaultDuration), 0x3728, 10, 10, 2023); Effects.SendLocationParticles(EffectItem.Create(to, m.Map, EffectItem.DefaultDuration), 0x3728, 10, 10, 5023); m.PlaySound(0x1FE); m_Owner.Combatant = toTeleport; } } } #endregion #region Unholy Touch private static Dictionary<Mobile, Timer> m_UnholyTouched = new Dictionary<Mobile, Timer>(); public void Discord(Mobile target) { if (Utility.RandomDouble() < 0.9 && !m_UnholyTouched.ContainsKey(target)) { double scalar = -((20 - (target.Skills[SkillName.MagicResist].Value / 10)) / 100); ArrayList mods = new ArrayList(); if (target.PhysicalResistance > 0) { mods.Add(new ResistanceMod(ResistanceType.Physical, (int)((double)target.PhysicalResistance * scalar))); } if (target.FireResistance > 0) { mods.Add(new ResistanceMod(ResistanceType.Fire, (int)((double)target.FireResistance * scalar))); } if (target.ColdResistance > 0) { mods.Add(new ResistanceMod(ResistanceType.Cold, (int)((double)target.ColdResistance * scalar))); } if (target.PoisonResistance > 0) { mods.Add(new ResistanceMod(ResistanceType.Poison, (int)((double)target.PoisonResistance * scalar))); } if (target.EnergyResistance > 0) { mods.Add(new ResistanceMod(ResistanceType.Energy, (int)((double)target.EnergyResistance * scalar))); } for (int i = 0; i < target.Skills.Length; ++i) { if (target.Skills[i].Value > 0) { mods.Add(new DefaultSkillMod((SkillName)i, true, target.Skills[i].Value * scalar)); } } target.PlaySound(0x458); ApplyMods(target, mods); m_UnholyTouched[target] = Timer.DelayCall(TimeSpan.FromSeconds(30), new TimerCallback( delegate { ClearMods(target, mods); m_UnholyTouched.Remove(target); })); } m_NextDiscordTime = DateTime.UtcNow + TimeSpan.FromSeconds(5 + Utility.RandomDouble() * 22); } private static void ApplyMods(Mobile from, ArrayList mods) { for (int i = 0; i < mods.Count; ++i) { object mod = mods[i]; if (mod is ResistanceMod) from.AddResistanceMod((ResistanceMod)mod); else if (mod is StatMod) from.AddStatMod((StatMod)mod); else if (mod is SkillMod) from.AddSkillMod((SkillMod)mod); } } private static void ClearMods(Mobile from, ArrayList mods) { for (int i = 0; i < mods.Count; ++i) { object mod = mods[i]; if (mod is ResistanceMod) from.RemoveResistanceMod((ResistanceMod)mod); else if (mod is StatMod) from.RemoveStatMod(((StatMod)mod).Name); else if (mod is SkillMod) from.RemoveSkillMod((SkillMod)mod); } } #endregion public void SpawnShadowDwellers(Mobile target) { Map map = Map; if (map == null) return; int newShadowDwellers = Utility.RandomMinMax(2, 3); for (int i = 0; i < newShadowDwellers; ++i) { ShadowDweller shadowdweller = new ShadowDweller(); shadowdweller.Team = Team; shadowdweller.FightMode = FightMode.Closest; bool validLocation = false; Point3D loc = Location; for (int j = 0; !validLocation && j < 10; ++j) { int x = X + Utility.Random(3) - 1; int y = Y + Utility.Random(3) - 1; int z = map.GetAverageZ(x, y); if (validLocation = map.CanFit(x, y, Z, 16, false, false)) loc = new Point3D(x, y, Z); else if (validLocation = map.CanFit(x, y, z, 16, false, false)) loc = new Point3D(x, y, z); } shadowdweller.MoveToWorld(loc, map); shadowdweller.Combatant = target; } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); m_Timer = new TeleportTimer(this); m_Timer.Start(); } } }
0
0.989091
1
0.989091
game-dev
MEDIA
0.985366
game-dev
0.989983
1
0.989983
NeotokyoRebuild/neo
10,845
src/game/server/env_debughistory.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #include "cbase.h" #include "isaverestore.h" #include "env_debughistory.h" #include "tier0/vprof.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Number of characters worth of debug to use per history category #define DEBUG_HISTORY_VERSION 6 #define DEBUG_HISTORY_FIRST_VERSIONED 5 #define MAX_DEBUG_HISTORY_LINE_LENGTH 256 #define MAX_DEBUG_HISTORY_LENGTH (1000 * MAX_DEBUG_HISTORY_LINE_LENGTH) //----------------------------------------------------------------------------- // Purpose: Stores debug history in savegame files for debugging reference //----------------------------------------------------------------------------- class CDebugHistory : public CBaseEntity { DECLARE_CLASS( CDebugHistory, CBaseEntity ); public: DECLARE_DATADESC(); void Spawn(); void AddDebugHistoryLine( int iCategory, const char *szLine ); void ClearHistories( void ); void DumpDebugHistory( int iCategory ); int Save( ISave &save ); int Restore( IRestore &restore ); private: char m_DebugLines[MAX_HISTORY_CATEGORIES][MAX_DEBUG_HISTORY_LENGTH]; char *m_DebugLineEnd[MAX_HISTORY_CATEGORIES]; }; BEGIN_DATADESC( CDebugHistory ) //DEFINE_FIELD( m_DebugLines, FIELD_CHARACTER ), // Not saved because we write it out manually //DEFINE_FIELD( m_DebugLineEnd, FIELD_CHARACTER ), END_DATADESC() LINK_ENTITY_TO_CLASS( env_debughistory, CDebugHistory ); // The handle to the debug history singleton. Created on first access via GetDebugHistory. static CHandle< CDebugHistory > s_DebugHistory; //----------------------------------------------------------------------------- // Spawn //----------------------------------------------------------------------------- void CDebugHistory::Spawn() { BaseClass::Spawn(); #ifdef DISABLE_DEBUG_HISTORY UTIL_Remove( this ); #else if ( g_pGameRules && g_pGameRules->IsMultiplayer() ) { UTIL_Remove( this ); } else { Warning( "DEBUG HISTORY IS ENABLED. Disable before release (in env_debughistory.h).\n" ); } #endif ClearHistories(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDebugHistory::AddDebugHistoryLine( int iCategory, const char *szLine ) { if ( iCategory < 0 || iCategory >= MAX_HISTORY_CATEGORIES ) { Warning("Attempted to add a debughistory line to category %d. Valid categories are %d to %d.\n", iCategory, 0, (MAX_HISTORY_CATEGORIES-1) ); return; } // Don't do debug history before the singleton is properly set up. if ( !m_DebugLineEnd[iCategory] ) return; const char *pszRemaining = szLine; int iCharsToWrite = strlen( pszRemaining ) + 1; // Add 1 so that we copy the null terminator // Clip the line if it's too long. Wasteful doing it this way, but keeps code below nice & simple. char szTmpBuffer[MAX_DEBUG_HISTORY_LINE_LENGTH]; if ( iCharsToWrite > MAX_DEBUG_HISTORY_LINE_LENGTH) { memcpy( szTmpBuffer, szLine, sizeof(szTmpBuffer) ); szTmpBuffer[MAX_DEBUG_HISTORY_LINE_LENGTH-1] = '\0'; pszRemaining = szTmpBuffer; iCharsToWrite = MAX_DEBUG_HISTORY_LINE_LENGTH; } while ( iCharsToWrite ) { int iCharsLeftBeforeLoop = sizeof(m_DebugLines[iCategory]) - (m_DebugLineEnd[iCategory] - m_DebugLines[iCategory]); // Write into the buffer int iWrote = MIN( iCharsToWrite, iCharsLeftBeforeLoop ); memcpy( m_DebugLineEnd[iCategory], pszRemaining, iWrote ); m_DebugLineEnd[iCategory] += iWrote; pszRemaining += iWrote; // Did we loop? if ( iWrote == iCharsLeftBeforeLoop ) { m_DebugLineEnd[iCategory] = m_DebugLines[iCategory]; } iCharsToWrite -= iWrote; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDebugHistory::DumpDebugHistory( int iCategory ) { if ( iCategory < 0 || iCategory >= MAX_HISTORY_CATEGORIES ) { Warning("Attempted to dump a history for category %d. Valid categories are %d to %d.\n", iCategory, 0, (MAX_HISTORY_CATEGORIES-1) ); return; } // Find the start of the oldest whole debug line. const char *pszLine = m_DebugLineEnd[iCategory] + 1; if ( (pszLine - m_DebugLines[iCategory]) >= sizeof(m_DebugLines[iCategory]) ) { pszLine = m_DebugLines[iCategory]; } // Are we at the start of a line? If there's a null terminator before us, then we're good to go. while ( (!( pszLine == m_DebugLines[iCategory] && *(m_DebugLines[iCategory]+sizeof(m_DebugLines[iCategory])-1) == '\0' ) && !( pszLine != m_DebugLines[iCategory] && *(pszLine-1) == '\0' )) || *pszLine == '\0' ) { pszLine++; // Have we looped? if ( (pszLine - m_DebugLines[iCategory]) >= sizeof(m_DebugLines[iCategory]) ) { pszLine = m_DebugLines[iCategory]; } if ( pszLine == m_DebugLineEnd[iCategory] ) { // We looped through the entire history, and found nothing. Msg( "Debug History of Category %d is EMPTY\n", iCategory ); return; } } // Now print everything up till the end char szMsgBuffer[MAX_DEBUG_HISTORY_LINE_LENGTH]; char *pszMsg = szMsgBuffer; Msg( "Starting Debug History Dump of Category %d\n", iCategory ); while ( pszLine != m_DebugLineEnd[iCategory] ) { *pszMsg = *pszLine; if ( *pszLine == '\0' ) { if ( szMsgBuffer[0] != '\0' ) { // Found a full line, so print it Msg( "%s", szMsgBuffer ); } // Clear the buffer pszMsg = szMsgBuffer; *pszMsg = '\0'; } else { pszMsg++; } pszLine++; // Have we looped? if ( (pszLine - m_DebugLines[iCategory]) >= sizeof(m_DebugLines[iCategory]) ) { pszLine = m_DebugLines[iCategory]; } } Msg("Ended Debug History Dump of Category %d\n", iCategory ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDebugHistory::ClearHistories( void ) { for ( int i = 0; i < MAX_HISTORY_CATEGORIES; i++ ) { memset( m_DebugLines[i], 0, sizeof(m_DebugLines[i]) ); m_DebugLineEnd[i] = m_DebugLines[i]; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CDebugHistory::Save( ISave &save ) { int iVersion = DEBUG_HISTORY_VERSION; save.WriteInt( &iVersion ); int iMaxCategorys = MAX_HISTORY_CATEGORIES; save.WriteInt( &iMaxCategorys ); for ( int iCategory = 0; iCategory < MAX_HISTORY_CATEGORIES; iCategory++ ) { int iEnd = m_DebugLineEnd[iCategory] - m_DebugLines[iCategory]; save.WriteInt( &iEnd ); save.WriteData( m_DebugLines[iCategory], MAX_DEBUG_HISTORY_LENGTH ); } return BaseClass::Save(save); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CDebugHistory::Restore( IRestore &restore ) { ClearHistories(); int iVersion = restore.ReadInt(); if ( iVersion >= DEBUG_HISTORY_FIRST_VERSIONED ) { int iMaxCategorys = restore.ReadInt(); for ( int iCategory = 0; iCategory < MIN(iMaxCategorys,MAX_HISTORY_CATEGORIES); iCategory++ ) { int iEnd = restore.ReadInt(); m_DebugLineEnd[iCategory] = m_DebugLines[iCategory] + iEnd; restore.ReadData( m_DebugLines[iCategory], sizeof(m_DebugLines[iCategory]), 0 ); } } else { int iMaxCategorys = iVersion; for ( int iCategory = 0; iCategory < MIN(iMaxCategorys,MAX_HISTORY_CATEGORIES); iCategory++ ) { int iEnd = restore.ReadInt(); m_DebugLineEnd[iCategory] = m_DebugLines[iCategory] + iEnd; restore.ReadData( m_DebugLines[iCategory], sizeof(m_DebugLines[iCategory]), 0 ); } } return BaseClass::Restore(restore); } //----------------------------------------------------------------------------- // Purpose: Singleton debug history. Created by first usage. //----------------------------------------------------------------------------- CDebugHistory *GetDebugHistory() { #ifdef DISABLE_DEBUG_HISTORY return NULL; #endif if ( g_pGameRules && g_pGameRules->IsMultiplayer() ) return NULL; if ( s_DebugHistory == NULL ) { CBaseEntity *pEnt = gEntList.FindEntityByClassname( NULL, "env_debughistory" ); if ( pEnt ) { s_DebugHistory = dynamic_cast<CDebugHistory*>(pEnt); } else { s_DebugHistory = ( CDebugHistory * )CreateEntityByName( "env_debughistory" ); if ( s_DebugHistory ) { s_DebugHistory->Spawn(); } } } Assert( s_DebugHistory ); return s_DebugHistory; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void AddDebugHistoryLine( int iCategory, const char *pszLine ) { #ifdef DISABLE_DEBUG_HISTORY return; #else if ( g_pGameRules && g_pGameRules->IsMultiplayer() ) return; if ( !GetDebugHistory() ) { Warning("Failed to find or create an env_debughistory.\n" ); return; } GetDebugHistory()->AddDebugHistoryLine( iCategory, pszLine ); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CC_DebugHistory_AddLine( const CCommand &args ) { if ( !UTIL_IsCommandIssuedByServerAdmin() ) return; if ( args.ArgC() < 3 ) { Warning("Incorrect parameters. Format: <category id> <line>\n"); return; } int iCategory = atoi(args[ 1 ]); const char *pszLine = args[ 2 ]; AddDebugHistoryLine( iCategory, pszLine ); } static ConCommand dbghist_addline( "dbghist_addline", CC_DebugHistory_AddLine, "Add a line to the debug history. Format: <category id> <line>", FCVAR_NONE ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CC_DebugHistory_Dump( const CCommand &args ) { if ( !UTIL_IsCommandIssuedByServerAdmin() ) return; if ( args.ArgC() < 2 ) { Warning("Incorrect parameters. Format: <category id>\n"); return; } if ( GetDebugHistory() ) { int iCategory = atoi(args[ 1 ]); GetDebugHistory()->DumpDebugHistory( iCategory ); } } static ConCommand dbghist_dump("dbghist_dump", CC_DebugHistory_Dump, "Dump the debug history to the console. Format: <category id>\n" " Categories:\n" " 0: Entity I/O\n" " 1: AI Decisions\n" " 2: Scene Print\n" " 3: Alyx Blind\n" " 4: Log of damage done to player", FCVAR_NONE );
0
0.735911
1
0.735911
game-dev
MEDIA
0.563625
game-dev
0.800838
1
0.800838
microsoft/MixedReality-WorldLockingTools-Unity
5,295
Assets/WorldLocking.Tools/Scripts/SpongyAnchorVisual.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using UnityEngine; using Microsoft.MixedReality.WorldLocking.Core; namespace Microsoft.MixedReality.WorldLocking.Tools { /// <summary> /// Component for controlling location, visual appearance and ID text of a spongy anchor visualization. /// </summary> /// <remarks> /// Spongy anchors are visualized by a concentric pair of an outer ring and an inner disc /// The outer ring of fixed size indicates the state of the spatial anchor by its color: /// /// green: support(area of inner circle indicating relevance) /// red: support with zero relevance /// yellow: not a support /// gray: anchor not located(i.e.currently not part of spongy world) /// /// The inner disc indicates the relevance of the spongy anchor (0..100%) by its area. /// </remarks> public class SpongyAnchorVisual : MonoBehaviour { /// <summary> /// The SpongyAnchor on a separate GameObject for syncing this GameObject's localPose")] /// </summary> private SpongyAnchor spongyAnchor = null; [SerializeField] [Tooltip("The child object that will have its color controlled")] private Renderer ringObject = null; [SerializeField] [Tooltip("The child object that will have its scale controlled")] private GameObject discObject = null; [SerializeField] [Tooltip("The child Text object that will have its color and text controlled")] private TextMesh textObject = null; private Color color; /// <summary> /// Set in AnchorGraphVisual. /// </summary> private float verticalDisplacement = 0; /// <summary> /// Create a visualizer for a spongy anchor. /// </summary> /// <param name="parent">Coordinate space to create the visualizer in</param> /// <param name="spongyAnchor">The spongyAnchor component assigned to some other object that this object is supposed to sync with</param> /// <returns></returns> public SpongyAnchorVisual Instantiate(FrameVisual parent, SpongyAnchor spongyAnchor, float verticalDisplacement) { var res = Instantiate(this, parent.transform); res.name = spongyAnchor.name; if (res.textObject != null) { res.textObject.text = res.name; } res.spongyAnchor = spongyAnchor; res.color = Color.gray; res.verticalDisplacement = verticalDisplacement; return res; } private void Update() { var color = this.color; // Unity's implementation of spatial anchor adjusts its global transform to track the // SpatialAnchor coordinate system. Here we want to keep the local transform of the visualization // towards its parent to track the SpatialAnchor, so we copy the global pose of the anchor to the // local pose of the visualization object. // This is because the visualizations tree is rooted at the SpongyFrame, which also contains the camera (and MRTK Playspace). // The SpongyFrame is adjusted by FrozeWorld every frame. This means that giving a transform M relative to the SpongyFrame, // as done here, will put the object _relative to the camera_ in the same place as setting M as the world transform // if SpongyFrame wasn't there, i.e. Unity World Space. Pose localPose = spongyAnchor.SpongyPose; localPose.position = new Vector3(localPose.position.x, localPose.position.y + verticalDisplacement, localPose.position.z); transform.SetLocalPose(localPose); if (!spongyAnchor.IsLocated) color = Color.gray; if (ringObject != null) { ringObject.material.color = color; } if (textObject != null) { textObject.color = color; } } /// <summary> /// Set the relevance, which sets the color. /// </summary> /// <param name="relevance">The new relevance</param> public void SetSupportRelevance(float relevance) { if (relevance > 0.0f) { color = Color.green; var rad = (float)Math.Sqrt(relevance); if (discObject != null) { discObject.SetActive(true); discObject.transform.localScale = new Vector3(rad, 1.0f, rad); } } else { color = Color.red; if (discObject != null) { discObject.SetActive(false); } } } /// <summary> /// Declare as not being a support. /// </summary> public void SetNoSupport() { color = Color.yellow; if (discObject != null) { discObject.SetActive(false); } } } }
0
0.850054
1
0.850054
game-dev
MEDIA
0.504409
game-dev,graphics-rendering
0.871366
1
0.871366
bozimmerman/CoffeeMud
4,699
com/planet_ink/coffee_mud/core/collections/PairSLinkedList.java
package com.planet_ink.coffee_mud.core.collections; import java.util.*; import com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary; public final class PairSLinkedList<T, K> extends SLinkedList<Pair<T, K>> implements PairList<T, K> { private static final long serialVersionUID = -9175373328892311411L; @Override public final Pair.FirstConverter<T, K> getFirstConverter() { return new Pair.FirstConverter<T, K>(); } @Override public final Pair.SecondConverter<T, K> getSecondConverter() { return new Pair.SecondConverter<T, K>(); } @Override public final Iterator<T> firstIterator() { return new ConvertingIterator<Pair<T, K>, T>(iterator(), getFirstConverter()); } @Override public final Iterator<K> secondIterator() { return new ConvertingIterator<Pair<T, K>, K>(iterator(), getSecondConverter()); } @Override public synchronized int indexOfFirst(final T t) { return indexOfFirst(t, 0); } @Override public synchronized int indexOfSecond(final K k) { return indexOfSecond(k, 0); } @Override public T getFirst(final int index) { return get(index).first; } @Override public K getSecond(final int index) { return get(index).second; } @Override public void add(final T t, final K k) { add(new Pair<T, K>(t, k)); } @Override public void add(final int x, final T t, final K k) { add(x, new Pair<T, K>(t, k)); } public void addElement(final T t, final K k) { add(new Pair<T, K>(t, k)); } public void addElement(final int x, final T t, final K k) { add(x, new Pair<T, K>(t, k)); } @Override public boolean containsFirst(final T t) { for (final Iterator<Pair<T, K>> i = iterator(); i.hasNext();) { if ((t == null) ? i.next() == null : t.equals(i.next().first)) return true; } return false; } @Override public boolean containsSecond(final K k) { for (final Iterator<Pair<T, K>> i = iterator(); i.hasNext();) { if ((k == null) ? i.next() == null : k.equals(i.next().second)) return true; } return false; } @Override public T elementAtFirst(final int index) { return get(index).first; } @Override public K elementAtSecond(final int index) { return get(index).second; } @Override public synchronized int indexOfFirst(final T t, final int index) { try { for (int i = index; i < size(); i++) { if ((t == null ? get(i).first == null : t.equals(get(i).first))) return i; } } catch (final Exception e) { } return -1; } @Override public synchronized int indexOfSecond(final K k, final int index) { try { for (int i = index; i < size(); i++) { if ((k == null ? get(i).second == null : k.equals(get(i).second))) return i; } } catch (final Exception e) { } return -1; } @Override public synchronized int lastIndexOfFirst(final T t, final int index) { try { for (int i = index; i >= 0; i--) { if ((t == null ? get(i).first == null : t.equals(get(i).first))) return i; } } catch (final Exception e) { } return -1; } @Override public synchronized int lastIndexOfSecond(final K k, final int index) { try { for (int i = index; i >= 0; i--) { if ((k == null ? get(i).second == null : k.equals(get(i).second))) return i; } } catch (final Exception e) { } return -1; } @Override public synchronized int lastIndexOfFirst(final T t) { return lastIndexOfFirst(t, size() - 1); } @Override public synchronized int lastIndexOfSecond(final K k) { return lastIndexOfSecond(k, size() - 1); } @Override public boolean removeFirst(final T t) { Pair<T, K> pair; for (final Iterator<Pair<T, K>> i = iterator(); i.hasNext();) { pair = i.next(); if ((t == null ? pair.first == null : t.equals(pair.first))) return super.remove(pair); } return false; } @Override public boolean removeSecond(final K k) { Pair<T, K> pair; for (final Iterator<Pair<T, K>> i = iterator(); i.hasNext();) { pair = i.next(); if ((k == null ? pair.second == null : k.equals(pair.second))) return super.remove(pair); } return false; } @Override public boolean removeElementFirst(final T t) { return removeFirst(t); } @Override public boolean removeElementSecond(final K k) { return removeSecond(k); } @Override public T[] toArrayFirst(T[] objs) { if(objs.length < size()) objs = Arrays.copyOf(objs, size()); for (int x = 0; x < size(); x++) objs[x] = getFirst(x); return objs; } @Override public K[] toArraySecond(K[] objs) { if(objs.length < size()) objs = Arrays.copyOf(objs, size()); for (int x = 0; x < size(); x++) objs[x] = getSecond(x); return objs; } }
0
0.922313
1
0.922313
game-dev
MEDIA
0.225606
game-dev
0.955204
1
0.955204
MrShieh-X/console-minecraft-launcher
11,900
src/main/java/com/mrshiehx/cmcl/bean/VersionConfig.java
/* * Console Minecraft Launcher * Copyright (C) 2021-2024 MrShiehX * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ package com.mrshiehx.cmcl.bean; import com.mrshiehx.cmcl.bean.arguments.Argument; import com.mrshiehx.cmcl.bean.arguments.Arguments; import com.mrshiehx.cmcl.bean.arguments.ValueArgument; import com.mrshiehx.cmcl.utils.Utils; import com.mrshiehx.cmcl.utils.cmcl.ArgumentsUtils; import com.mrshiehx.cmcl.utils.console.CommandUtils; import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.json.JSONObject; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class VersionConfig { public static final VersionConfig EMPTY = new VersionConfig(null, null, null, null, null, "", Collections.EMPTY_LIST, Collections.EMPTY_MAP, null, null, "", "", "", "", null, null, null, null); public final String gameDir; public final String javaPath; public final String maxMemory;//同下 public final String windowSizeWidth;//同下 public final String windowSizeHeight;//同下 public final String isFullscreen;//不用boolean是因为要表示一种“未设置”的状态 @NotNull public final List<String> jvmArgs; @NotNull public final Map<String, String> gameArgs; public final String assetsDir; public final String resourcesDir; public final String exitWithMinecraft;//不用boolean是因为要表示一种“未设置”的状态 public final String printStartupInfo;//不用boolean是因为要表示一种“未设置”的状态 public final String checkAccountBeforeStart;//不用boolean是因为要表示一种“未设置”的状态 public final String isolate;//同上 public final String qpLogFile; public final String qpSaveName; public final String qpServerAddress; public final String qpRealmsID; public VersionConfig(String gameDir, String javaPath, String maxMemory, String windowSizeWidth, String windowSizeHeight, String isFullscreen, @NotNull List<String> jvmArgs, @NotNull Map<String, String> gameArgs, String assetsDir, String resourcesDir, String exitWithMinecraft, String printStartupInfo, String checkAccountBeforeStart, String isolate, String qpLogFile, String qpSaveName, String qpServerAddress, String qpRealmsID) { this.gameDir = gameDir; this.javaPath = javaPath; this.maxMemory = maxMemory; this.windowSizeWidth = windowSizeWidth; this.windowSizeHeight = windowSizeHeight; this.isFullscreen = isFullscreen; this.jvmArgs = jvmArgs; this.gameArgs = gameArgs; this.assetsDir = assetsDir; this.resourcesDir = resourcesDir; this.exitWithMinecraft = exitWithMinecraft; this.printStartupInfo = printStartupInfo; this.checkAccountBeforeStart = checkAccountBeforeStart; this.isolate = isolate; this.qpLogFile = qpLogFile; this.qpSaveName = qpSaveName; this.qpServerAddress = qpServerAddress; this.qpRealmsID = qpRealmsID; } public static VersionConfig valueOf(JSONObject origin) { return new VersionConfig(origin.optString("gameDir"), origin.optString("javaPath"), origin.optString("maxMemory"), origin.optString("windowSizeWidth"), origin.optString("windowSizeHeight"), origin.optString("isFullscreen"), ArgumentsUtils.parseJVMArgs(origin.optJSONArray("jvmArgs")), ArgumentsUtils.parseGameArgs(origin.optJSONObject("gameArgs")), origin.optString("assetsDir"), origin.optString("resourcesDir"), origin.optString("exitWithMinecraft"), origin.optString("printStartupInfo"), origin.optString("checkAccountBeforeStart"), origin.optString("isolate"), origin.optString("qpLogFile"), origin.optString("qpSaveName"), origin.optString("qpServerAddress"), origin.optString("qpRealmsID")); } public static VersionConfig valueOfPCL2(String setupIni) { if (Utils.isEmpty(setupIni)) return EMPTY; String[] lines = setupIni.split("\n"); Map<String, String> gameArgs = new LinkedHashMap<>(); List<String> jvmArgs = Collections.emptyList(); String javaPath = null; String isolate = ""; String qpServerAddress = null; for (String line : lines) { int indexOf = line.indexOf(":"); if (indexOf <= 0) continue;//小于0的情况:若不存在:则返回-1 String name = line.substring(0, indexOf); String value; Matcher matcher = Pattern.compile(name + ":\\s*(?<value>[\\s\\S]*)").matcher(line); if (matcher.find()) { value = matcher.group("value"); } else value = ""; if (!Utils.isEmpty(value)) { switch (name) { case "VersionAdvanceGame": Arguments arguments = new Arguments(value, false); for (Argument argument : arguments.getArguments()) { String key = argument.key; if (Objects.equals(key, "version") || Objects.equals(key, "versionType")) continue; if (argument instanceof ValueArgument) { gameArgs.put(key, ((ValueArgument) argument).value); } else { gameArgs.put(key, null); } } break; case "VersionArgumentJavaSelect": try { javaPath = new JSONObject(value).optString("Path"); } catch (JSONException ignored) { } break; case "VersionAdvanceJvm": jvmArgs = ArgumentsUtils.parseJVMArgs(CommandUtils.splitCommand(CommandUtils.clearRedundantSpaces(value)).toArray(new String[0])); break; case "VersionArgumentIndie": if ("1".equals(value)) { isolate = "true"; } else if ("2".equals(value)) { isolate = "false"; } else { isolate = ""; } break; case "VersionServerEnter": qpServerAddress = value; break; } } } return new VersionConfig(null, javaPath, "", "", "", "", jvmArgs, gameArgs, null, null, "", "", "", isolate, null, null, qpServerAddress, null); } public static VersionConfig valueOfHMCL(JSONObject origin) { //workingDirectory String isolate = "false"; String workingDirectory = null; { int gameDirType = origin.optInt("gameDirType"); if (gameDirType == 1) { isolate = "true"; } else if (gameDirType == 2) { workingDirectory = origin.optString("gameDir"); } } Map<String, String> gameArgs = new LinkedHashMap<>(); String gameArgsString = origin.optString("minecraftArgs"); if (!Utils.isEmpty(gameArgsString)) { Arguments arguments = new Arguments(gameArgsString, false); for (Argument argument : arguments.getArguments()) { String key = argument.key; if (Objects.equals(key, "version") || Objects.equals(key, "versionType")) continue; if (argument instanceof ValueArgument) { gameArgs.put(key, ((ValueArgument) argument).value); } else { gameArgs.put(key, null); } } } return new VersionConfig(workingDirectory, origin.optString("defaultJavaPath"), origin.optString("maxMemory"), origin.optString("width"), origin.optString("height"), origin.optString("fullscreen"), ArgumentsUtils.parseJVMArgs(CommandUtils.splitCommand(CommandUtils.clearRedundantSpaces(origin.optString("javaArgs"))).toArray(new String[0])), gameArgs, null, null, "", "", "", isolate, null, null, null,/*I don't know*/ null); } /** * 合并本对象与 <code>versionConfig</code> 并返回新的版本配置对象。 * <p>若 <code>versionConfig</code> 某项为空才会把本对象的对应项作为新版本配置对象的对应项。 **/ public VersionConfig mergeTo(VersionConfig versionConfig) { Map<String, String> newGameArgs = new LinkedHashMap<>(); newGameArgs.putAll(versionConfig.gameArgs); newGameArgs.putAll(gameArgs); List<String> newJvmArgs = new LinkedList<>(); newJvmArgs.addAll(versionConfig.jvmArgs); newJvmArgs.addAll(jvmArgs); return new VersionConfig( !Utils.isEmpty(versionConfig.gameDir) ? versionConfig.gameDir : gameDir, !Utils.isEmpty(versionConfig.javaPath) ? versionConfig.javaPath : javaPath, !Utils.isEmpty(versionConfig.maxMemory) ? versionConfig.maxMemory : maxMemory, !Utils.isEmpty(versionConfig.windowSizeWidth) ? versionConfig.windowSizeWidth : windowSizeWidth, !Utils.isEmpty(versionConfig.windowSizeHeight) ? versionConfig.windowSizeHeight : windowSizeHeight, !Utils.isEmpty(versionConfig.isFullscreen) ? versionConfig.isFullscreen : isFullscreen, newJvmArgs, newGameArgs, !Utils.isEmpty(versionConfig.assetsDir) ? versionConfig.assetsDir : assetsDir, !Utils.isEmpty(versionConfig.resourcesDir) ? versionConfig.resourcesDir : resourcesDir, !Utils.isEmpty(versionConfig.exitWithMinecraft) ? versionConfig.exitWithMinecraft : exitWithMinecraft, !Utils.isEmpty(versionConfig.printStartupInfo) ? versionConfig.printStartupInfo : printStartupInfo, !Utils.isEmpty(versionConfig.checkAccountBeforeStart) ? versionConfig.checkAccountBeforeStart : checkAccountBeforeStart, !Utils.isEmpty(versionConfig.isolate) ? versionConfig.isolate : isolate, !Utils.isEmpty(versionConfig.qpLogFile) ? versionConfig.qpLogFile : qpLogFile, !Utils.isEmpty(versionConfig.qpSaveName) ? versionConfig.qpSaveName : qpSaveName, !Utils.isEmpty(versionConfig.qpServerAddress) ? versionConfig.qpServerAddress : qpServerAddress, !Utils.isEmpty(versionConfig.qpRealmsID) ? versionConfig.qpRealmsID : qpRealmsID); } }
0
0.972124
1
0.972124
game-dev
MEDIA
0.572234
game-dev
0.969862
1
0.969862
catbobyman/Unity-Mediapipe-Avatar-3DMotionCaptureDriven
10,859
AvartarMocap/Assets/Plugins/MagicaCloth/Scripts/Core/Deformer/BaseMeshDeformer.cs
// Magica Cloth. // Copyright (c) MagicaSoft, 2020-2022. // https://magicasoft.jp using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace MagicaCloth { /// <summary> /// ベースメッシュデフォーマー /// </summary> [System.Serializable] public abstract class BaseMeshDeformer : IEditorMesh, IDataVerify, IDataHash { /// <summary> /// 仮想メッシュデータ /// </summary> [SerializeField] private MeshData meshData = null; /// <summary> /// メッシュの計算基準となるオブジェクト(必須) /// </summary> [SerializeField] private GameObject targetObject; /// <summary> /// データ検証ハッシュ /// </summary> [SerializeField] protected int dataHash; [SerializeField] protected int dataVersion; /// <summary> /// 実行状態 /// </summary> protected RuntimeStatus status = new RuntimeStatus(); //========================================================================================= /// <summary> /// 親コンポーネント(Unity2019.3の参照切れ対策) /// </summary> private CoreComponent parent; public CoreComponent Parent { get { return parent; } set { parent = value; } } //========================================================================================= public virtual MeshData MeshData { get { #if UNITY_EDITOR if (Application.isPlaying) return meshData; else { // unity2019.3で参照がnullとなる不具合の対処(臨時) var so = new SerializedObject(parent); return so.FindProperty("deformer.meshData").objectReferenceValue as MeshData; } #else return meshData; #endif } set { meshData = value; } } public GameObject TargetObject { get { return targetObject; } set { targetObject = value; } } public RuntimeStatus Status { get { return status; } } /// <summary> /// 登録メッシュインデックス /// (-1=無効) /// </summary> public int MeshIndex { get; protected set; } = -1; /// <summary> /// 登録頂点数 /// </summary> public int VertexCount { get; protected set; } /// <summary> /// 登録スキニング頂点数 /// </summary> public int SkinningVertexCount { get; protected set; } /// <summary> /// 登録トライアングル数 /// </summary> public int TriangleCount { get; protected set; } //========================================================================================= /// <summary> /// 初期化 /// 通常はStart()で呼ぶ /// </summary> /// <param name="vcnt"></param> public virtual void Init() { status.UpdateStatusAction = OnUpdateStatus; status.OwnerFunc = () => Parent; if (status.IsInitComplete || status.IsInitStart) return; status.SetInitStart(); OnInit(); // データチェック if (VerifyData() != Define.Error.None) { // error status.SetInitError(); return; } status.SetInitComplete(); // 状態更新 status.UpdateStatus(); } protected virtual void OnInit() { // メッシュチャンク無効化 MeshIndex = -1; // マネージャへ登録 MagicaPhysicsManager.Instance.Mesh.AddMesh(this); } /// <summary> /// 破棄 /// 通常はOnDestroy()で呼ぶ /// </summary> public virtual void Dispose() { // マネージャから削除 if (MagicaPhysicsManager.IsInstance()) MagicaPhysicsManager.Instance.Mesh.RemoveMesh(this); status.SetDispose(); } public virtual void OnEnable() { status.SetEnable(true); status.UpdateStatus(); } public virtual void OnDisable() { status.SetEnable(false); status.UpdateStatus(); } public virtual void Update() { // 実行中データ監視 var error = VerifyData() != Define.Error.None; status.SetRuntimeError(error); status.UpdateStatus(); } /// <summary> /// メッシュの描画判定 /// </summary> /// <param name="bufferIndex"></param> internal abstract void MeshCalculation(int bufferIndex); /// <summary> /// 通常のメッシュ書き込み /// </summary> /// <param name="bufferIndex"></param> internal abstract void NormalWriting(int bufferIndex); // 実行状態の更新 protected void OnUpdateStatus() { if (status.IsActive) { // 実行状態に入った OnActive(); } else { // 実行状態から抜けた OnInactive(); } } /// <summary> /// 実行状態に入った場合に呼ばれます /// </summary> protected virtual void OnActive() { } /// <summary> /// 実行状態から抜けた場合に呼ばれます /// </summary> protected virtual void OnInactive() { } //========================================================================================= public virtual bool IsMeshUse() { return false; } public virtual bool IsActiveMesh() { return false; } public bool IsSkinning { get { if (MeshData != null) return MeshData.isSkinning; return false; } } public int BoneCount { get { if (MeshData != null) { if (MeshData.isSkinning) return MeshData.BoneCount; else return 1; } else return 0; } } //========================================================================================= public virtual void AddUseMesh(System.Object parent) { } public virtual void RemoveUseMesh(System.Object parent) { } /// <summary> /// 利用頂点登録 /// </summary> /// <param name="vindex"></param> /// <returns>新規登録ならtrueを返す</returns> public virtual bool AddUseVertex(int vindex, bool fix) { return false; } /// <summary> /// 利用頂点解除 /// </summary> /// <param name="vindex"></param> /// <returns>登録解除ならtrueを返す</returns> public virtual bool RemoveUseVertex(int vindex, bool fix) { return false; } /// <summary> /// 未来予測のリセットを行う /// </summary> public virtual void ResetFuturePrediction() { } /// <summary> /// UnityPhysicsでの利用を設定する /// </summary> /// <param name="sw"></param> public virtual void ChangeUseUnityPhysics(bool sw) { } //========================================================================================= /// <summary> /// データを識別するハッシュコードを作成して返す /// </summary> /// <returns></returns> public virtual int GetDataHash() { int hash = 0; if (MeshData != null) hash += MeshData.GetDataHash(); if (targetObject) hash += targetObject.GetDataHash(); return hash; } public int SaveDataHash { get { return dataHash; } } public int SaveDataVersion { get { return dataVersion; } } //========================================================================================= /// <summary> /// データバージョンを取得する /// </summary> /// <returns></returns> public abstract int GetVersion(); /// <summary> /// 現在のデータが正常(実行できる状態)か返す /// </summary> /// <returns></returns> public virtual Define.Error VerifyData() { if (dataVersion == 0) return Define.Error.EmptyData; if (dataHash == 0) return Define.Error.InvalidDataHash; //if (dataVersion != GetVersion()) // return Define.Error.DataVersionMismatch; if (MeshData == null) return Define.Error.MeshDataNull; if (targetObject == null) return Define.Error.TargetObjectNull; var mdataError = MeshData.VerifyData(); if (mdataError != Define.Error.None) return mdataError; return Define.Error.None; } /// <summary> /// データを検証して結果を格納する /// </summary> /// <returns></returns> public virtual void CreateVerifyData() { dataHash = GetDataHash(); dataVersion = GetVersion(); } /// <summary> /// データ検証の結果テキストを取得する /// </summary> /// <returns></returns> public virtual string GetInformation() { return "No information."; } //========================================================================================= /// <summary> /// メッシュのワールド座標/法線/接線を返す(エディタ設定用) /// </summary> /// <param name="wposList"></param> /// <param name="wnorList"></param> /// <param name="wtanList"></param> /// <returns>頂点数</returns> public abstract int GetEditorPositionNormalTangent(out List<Vector3> wposList, out List<Vector3> wnorList, out List<Vector3> wtanList); /// <summary> /// メッシュのトライアングルリストを返す(エディタ設定用) /// </summary> /// <returns></returns> public abstract List<int> GetEditorTriangleList(); /// <summary> /// メッシュのラインリストを返す(エディタ用) /// </summary> /// <returns></returns> public abstract List<int> GetEditorLineList(); } }
0
0.872781
1
0.872781
game-dev
MEDIA
0.427111
game-dev
0.95875
1
0.95875
Armourers-Workshop/Armourers-Workshop
1,318
versions/library/common/src/main/java/moe/plushie/armourers_workshop/compatibility/core/AbstractBlockEntity.java
package moe.plushie.armourers_workshop.compatibility.core; import moe.plushie.armourers_workshop.api.annotation.Available; import moe.plushie.armourers_workshop.api.common.IBlockEntity; import moe.plushie.armourers_workshop.api.common.IBlockEntityCapability; import moe.plushie.armourers_workshop.api.common.IBlockEntityHandler; import moe.plushie.armourers_workshop.api.core.IDataSerializer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; @Available("[1.16, )") public abstract class AbstractBlockEntity extends AbstractBlockEntityImpl implements IBlockEntity { public AbstractBlockEntity(BlockEntityType<?> blockEntityType, BlockPos blockPos, BlockState blockState) { super(blockEntityType, blockPos, blockState); } @Override public abstract void readAdditionalData(IDataSerializer serializer); @Override public abstract void writeAdditionalData(IDataSerializer serializer); @Override public abstract void sendBlockUpdates(); @Nullable @Override public <T> T getCapability(IBlockEntityCapability<T> capability, @Nullable Direction dir) { return null; } }
0
0.726583
1
0.726583
game-dev
MEDIA
0.965592
game-dev
0.56898
1
0.56898
ehsankamrani/vandaengine
1,699
Vanda Engine Editor/VandaEngineEditor/Requirements/vc-include/physX/SampleRaycastCar.h
#define NOMINMAX #if defined(WIN32) #include <windows.h> #include <GL/gl.h> #include <GL/glut.h> #elif defined(__APPLE__) #include <OpenGL/gl.h> #include <GLUT/glut.h> #endif #include <stdio.h> #include "OrthographicDrawing.h" // Physics code #undef random #include "NxPhysics.h" #include "NxVehicle.h" enum CreationModes { MODE_NONE, MODE_CAR, MODE_TRUCK }; extern NxPhysicsSDK* gPhysicsSDK; extern NxScene* gScene; extern NxSpringDesc wheelSpring; extern bool keyDown[256]; extern NxUserContactReport * carContactReport; //void initCar(); //void createCar(const NxVec3& pos); void createCarWithDesc(const NxVec3& pos, bool frontWheelDrive, bool backWheelDrive, bool corvetteMotor, bool monsterTruck, bool oldStyle, NxPhysicsSDK* physicsSDK); void createCart(const NxVec3& pos, bool frontWheelDrive, bool backWheelDrive, bool oldStyle); NxVehicleDesc* createTruckPullerDesc(const NxVec3& pos, NxU32 nbGears, bool oldStyle); NxVehicleDesc* createTruckTrailer1(const NxVec3& pos, NxReal length, bool oldStyle); NxVehicleDesc* createFullTruckDesc(const NxVec3& pos, NxReal length, NxU32 nbGears, bool has4Axes, bool oldStyle); NxVehicleDesc* createTwoAxisTrailer(const NxVec3& pos, NxReal length, bool oldStyle); NxVehicle* createTruckPuller(const NxVec3& pos, NxU32 nbGears, bool oldStyle); NxVehicle* createFullTruck(const NxVec3& pos, NxU32 nbGears, bool has4Axes, bool oldStyle); NxVehicle* createTruckWithTrailer1(const NxVec3& pos, NxU32 nbGears, bool oldStyle); NxVehicle* createFullTruckWithTrailer2(const NxVec3& pos, NxU32 nbGears, bool oldStyle); //void tickCar(); void InitTerrain(); void RenderTerrain(); void RenderAllActors(); void renderHUD(OrthographicDrawing& orthoDraw);
0
0.719469
1
0.719469
game-dev
MEDIA
0.513206
game-dev,graphics-rendering
0.678671
1
0.678671
basiclab/TTSG
11,946
safebench/gym_carla/envs/route_planner.py
""" Date: 2023-01-31 22:23:17 LastEditTime: 2023-03-05 15:00:17 Description: Copyright (c) 2022-2023 Safebench Team Modified from <https://github.com/cjy1992/gym-carla/blob/master/gym_carla/envs/misc.py> Copyright (c) 2019: Jianyu Chen (jianyuchen@berkeley.edu) This work is licensed under the terms of the MIT license. For a copy, see <https://opensource.org/licenses/MIT> """ from collections import deque from enum import Enum import carla from safebench.gym_carla.envs.misc import ( compute_magnitude_angle, distance_vehicle, is_within_distance_ahead, ) class RoadOption(Enum): """ RoadOption represents the possible topological configurations when moving from a segment of lane to other. """ VOID = -1 LEFT = 1 RIGHT = 2 STRAIGHT = 3 LANEFOLLOW = 4 class RoutePlanner: def __init__(self, vehicle, buffer_size, init_waypoints): self._vehicle = vehicle self._world = self._vehicle.get_world() self._map = self._world.get_map() self._sampling_radius = 5 self._min_distance = 4 self._target_waypoint = None self._buffer_size = buffer_size self._waypoint_buffer = deque(maxlen=self._buffer_size) self._waypoints_queue = deque(maxlen=600) self._current_waypoint = self._map.get_waypoint(self._vehicle.get_location()) if len(init_waypoints) == 0: project_waypoint = self._map.get_waypoint( self._vehicle.get_location(), project_to_road=True, lane_type=carla.LaneType.Driving, ) self._waypoints_queue.append((self._current_waypoint, RoadOption.LANEFOLLOW)) self._waypoints_queue.append((project_waypoint, RoadOption.LANEFOLLOW)) else: for i, waypoint in enumerate(init_waypoints): if i == 0: self._waypoints_queue.append( (waypoint, compute_connection(self._current_waypoint, waypoint)) ) else: self._waypoints_queue.append( (waypoint, compute_connection(init_waypoints[i - 1], waypoint)) ) self._target_road_option = RoadOption.LANEFOLLOW self._last_traffic_light = None self._proximity_threshold = 15.0 self._compute_next_waypoints(k=200) def _compute_next_waypoints(self, k=1): """ Add new waypoints to the trajectory queue. :param k: how many waypoints to compute :return: """ # check we do not overflow the queue available_entries = self._waypoints_queue.maxlen - len(self._waypoints_queue) k = min(available_entries, k) for _ in range(k): last_waypoint = self._waypoints_queue[-1][0] next_waypoints = list(last_waypoint.next(self._sampling_radius)) if len(next_waypoints) == 1: # only one option available ==> lanefollowing next_waypoint = next_waypoints[0] road_option = RoadOption.LANEFOLLOW else: # random choice between the possible options road_options_list = retrieve_options(next_waypoints, last_waypoint) road_option = road_options_list[1] # road_option = random.choice(road_options_list) next_waypoint = next_waypoints[road_options_list.index(road_option)] self._waypoints_queue.append((next_waypoint, road_option)) def run_step(self): waypoints, target_road_option, current_waypoint, target_waypoint = self._get_waypoints() red_light, vehicle_front = self._get_hazard() # red_light = False return ( waypoints, target_road_option, current_waypoint, target_waypoint, red_light, vehicle_front, ) def _get_waypoints(self): """ Execute one step of local planning which involves running the longitudinal and lateral PID controllers to follow the waypoints trajectory. :param debug: boolean flag to activate waypoints debugging :return: """ # not enough waypoints in the horizon? => add more! if len(self._waypoints_queue) < int(self._waypoints_queue.maxlen * 0.5): self._compute_next_waypoints(k=100) # Buffering the waypoints while len(self._waypoint_buffer) < self._buffer_size: if self._waypoints_queue: self._waypoint_buffer.append(self._waypoints_queue.popleft()) else: break waypoints = [] for i, (waypoint, _) in enumerate(self._waypoint_buffer): waypoints.append( [ waypoint.transform.location.x, waypoint.transform.location.y, waypoint.transform.rotation.yaw, ] ) # current vehicle waypoint self._current_waypoint = self._map.get_waypoint(self._vehicle.get_location()) # target waypoint self._target_waypoint, self._target_road_option = self._waypoint_buffer[0] # purge the queue of obsolete waypoints vehicle_transform = self._vehicle.get_transform() max_index = -1 for i, (waypoint, _) in enumerate(self._waypoint_buffer): if distance_vehicle(waypoint, vehicle_transform) < self._min_distance: max_index = i if max_index >= 0: for i in range(max_index - 1): self._waypoint_buffer.popleft() # TODO: waypoint location list? return ( waypoints, self._target_road_option, self._current_waypoint, self._target_waypoint, ) def _get_hazard(self): # retrieve relevant elements for safe navigation, i.e.: traffic lights # and other vehicles actor_list = self._world.get_actors() vehicle_list = actor_list.filter("*vehicle*") lights_list = actor_list.filter("*traffic_light*") # check possible obstacles vehicle_state = self._is_vehicle_hazard(vehicle_list) # check for the state of the traffic lights light_state = self._is_light_red_us_style(lights_list) return light_state, vehicle_state def _is_vehicle_hazard(self, vehicle_list): """ Check if a given vehicle is an obstacle in our way. To this end we take into account the road and lane the target vehicle is on and run a geometry test to check if the target vehicle is under a certain distance in front of our ego vehicle. WARNING: This method is an approximation that could fail for very large vehicles, which center is actually on a different lane but their extension falls within the ego vehicle lane. :param vehicle_list: list of potential obstacle to check :return: a tuple given by (bool_flag, vehicle), where - bool_flag is True if there is a vehicle ahead blocking us and False otherwise - vehicle is the blocker object itself """ ego_vehicle_location = self._vehicle.get_location() ego_vehicle_waypoint = self._map.get_waypoint(ego_vehicle_location) for target_vehicle in vehicle_list: # do not account for the ego vehicle if target_vehicle.id == self._vehicle.id: continue # if the object is not in our lane it's not an obstacle target_vehicle_waypoint = self._map.get_waypoint(target_vehicle.get_location()) if ( target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id ): continue loc = target_vehicle.get_location() if is_within_distance_ahead( loc, ego_vehicle_location, self._vehicle.get_transform().rotation.yaw, self._proximity_threshold, ): return True return False def _is_light_red_us_style(self, lights_list): """ This method is specialized to check US style traffic lights. :param lights_list: list containing TrafficLight objects :return: a tuple given by (bool_flag, traffic_light), where - bool_flag is True if there is a traffic light in RED affecting us and False otherwise - traffic_light is the object itself or None if there is no red traffic light affecting us """ ego_vehicle_location = self._vehicle.get_location() ego_vehicle_waypoint = self._map.get_waypoint(ego_vehicle_location) if ego_vehicle_waypoint.is_intersection: # It is too late. Do not block the intersection! Keep going! return False if self._target_waypoint is not None: if self._target_waypoint.is_intersection: potential_lights = [] min_angle = 180.0 sel_magnitude = 0.0 sel_traffic_light = None for traffic_light in lights_list: loc = traffic_light.get_location() magnitude, angle = compute_magnitude_angle( loc, ego_vehicle_location, self._vehicle.get_transform().rotation.yaw, ) if magnitude < 80.0 and angle < min(25.0, min_angle): sel_magnitude = magnitude sel_traffic_light = traffic_light min_angle = angle if sel_traffic_light is not None: if self._last_traffic_light is None: self._last_traffic_light = sel_traffic_light if self._last_traffic_light.state == carla.libcarla.TrafficLightState.Red: return True else: self._last_traffic_light = None return False def retrieve_options(list_waypoints, current_waypoint): """ Compute the type of connection between the current active waypoint and the multiple waypoints present in list_waypoints. The result is encoded as a list of RoadOption enums. :param list_waypoints: list with the possible target waypoints in case of multiple options :param current_waypoint: current active waypoint :return: list of RoadOption enums representing the type of connection from the active waypoint to each candidate in list_waypoints """ options = [] for next_waypoint in list_waypoints: # this is needed because something we are linking to # the beggining of an intersection, therefore the # variation in angle is small next_next_waypoint = next_waypoint.next(3.0)[0] link = compute_connection(current_waypoint, next_next_waypoint) options.append(link) return options def compute_connection(current_waypoint, next_waypoint): """ Compute the type of topological connection between an active waypoint (current_waypoint) and a target waypoint (next_waypoint). :param current_waypoint: active waypoint :param next_waypoint: target waypoint :return: the type of topological connection encoded as a RoadOption enum: RoadOption.STRAIGHT RoadOption.LEFT RoadOption.RIGHT """ n = next_waypoint.transform.rotation.yaw n = n % 360.0 c = current_waypoint.transform.rotation.yaw c = c % 360.0 diff_angle = (n - c) % 180.0 if diff_angle < 1.0: return RoadOption.STRAIGHT elif diff_angle > 90.0: return RoadOption.LEFT else: return RoadOption.RIGHT
0
0.965653
1
0.965653
game-dev
MEDIA
0.645404
game-dev
0.990752
1
0.990752